The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 18:15 UTC
refactor(source-control): forges parse their own change request URLs (#23992)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 24, 2026 at 04:24 UTC
9a85aac901ff22045d8a70885b91bb4322e35431
95 files changed
+2036
-1481
apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
+1
-1
@@ -1,5 +1,5 @@
1
import { StackActions, useNavigation } from "@react-navigation/native";
2
-import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
2
+import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
3
import {
4
createContext,
5
use,
apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts
+43
-8
@@ -1,26 +1,61 @@
1
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
import { nativePullRequestDestination } from "../../lib/pullRequestNavigation";
4
+
5
const context = { environmentId: "remote", projectId: "project" };
6
+const project = (id: string, canonicalKey: string, provider: string, remoteUrl: string) => ({
7
+ id: ProjectId.make(id),
8
+ environmentId: EnvironmentId.make("remote"),
9
+ repositoryIdentity: {
10
+ canonicalKey,
11
+ locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
12
+ displayName: canonicalKey.split("/").slice(1).join("/"),
13
+ provider,
14
+ },
15
+});
16
+const projects = [
17
+ project("project", "github.com/org/repo", "github", "git@github.com:org/repo.git"),
18
+ project("gitlab", "git.example/group/sub/repo", "gitlab", "git@git.example:group/sub/repo.git"),
19
+ project("forgejo", "forgejo.test/org/repo", "forgejo", "http://forgejo.test:3000/org/repo.git"),
20
+];
21
+
22
describe("native PR entry points", () => {
23
it("keeps a thread link in its own environment and handles renamed host path shapes", () => {
24
expect(
7
- nativePullRequestDestination("https://github.com/org/repo/pull/12/files#diff", context),
25
+ nativePullRequestDestination(
26
+ "https://github.com/org/repo/pull/12/files#diff",
27
+ context,
28
+ projects,
29
+ ),
30
).toEqual({ ...context, host: "github.com", repository: "org/repo", number: 12 });
31
expect(
10
- nativePullRequestDestination("https://git.example/group/sub/repo/-/merge_requests/9", context)
11
- ?.repository,
12
- ).toBe("group/sub/repo");
32
+ nativePullRequestDestination(
33
+ "https://git.example/group/sub/repo/-/merge_requests/9",
34
+ context,
35
+ projects,
36
+ ),
37
+ ).toMatchObject({ projectId: "gitlab", repository: "group/sub/repo" });
38
expect(
14
- nativePullRequestDestination("http://forgejo.test:3000/org/repo/pulls/3", context)?.host,
39
+ nativePullRequestDestination("http://forgejo.test:3000/org/repo/pulls/3", context, projects)
40
+ ?.host,
41
).toBe("forgejo.test:3000");
42
});
43
+
44
+ it("leaves pull requests from repositories without a project to the external opener", () => {
45
+ expect(
46
+ nativePullRequestDestination("https://github.com/someone/else/pull/12", context, projects),
47
+ ).toBeNull();
48
+ });
49
+
50
it("leaves issues, unknown sites, and unscoped links to the external opener", () => {
51
expect(
19
- nativePullRequestDestination("https://github.com/org/repo/issues/12", context),
52
+ nativePullRequestDestination("https://github.com/org/repo/issues/12", context, projects),
53
+ ).toBeNull();
54
+ expect(
55
+ nativePullRequestDestination("https://example.com/org/repo/pull/12", context, projects),
56
).toBeNull();
57
expect(
22
- nativePullRequestDestination("https://example.com/org/repo/pull/12", context),
58
+ nativePullRequestDestination("https://github.com/org/repo/pull/12", null, projects),
59
).toBeNull();
24
- expect(nativePullRequestDestination("https://github.com/org/repo/pull/12", null)).toBeNull();
60
});
61
});
apps/mobile/src/features/pull-requests/usePullRequestStack.ts
+4
-2
@@ -1,6 +1,6 @@
1
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
2
import type { PullRequestDetail } from "@t3tools/contracts";
3
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
3
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4
import { useMemo } from "react";
5
import { useEnvironmentServerConfig, useNavigationThreadShells } from "../../state/entities";
6
import { pullRequestStackAtom } from "../../state/pull-requests";
@@ -18,7 +18,9 @@ export function usePullRequestStack(params: PullRequestParams, pr: PullRequestDe
18
const reference = useMemo(
19
() => ({
20
...pullRequestTarget(params).input,
21
- host: params.host ?? (pr ? parseChangeRequestUrl(pr.url)?.host : undefined),
21
+ host:
22
+ params.host ??
23
+ (pr ? sourceControlClients.parseChangeRequestUrl(pr.url)?.link.host : undefined),
24
}),
25
[params, pr],
26
);
apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
+3
-3
@@ -11,8 +11,8 @@ import {
11
type PullRequestLinkedThreadsResult,
12
} from "@t3tools/contracts";
13
import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
14
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
15
-import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
14
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
15
+import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
16
import { useRef, useState } from "react";
17
import { Platform } from "react-native";
18
import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
@@ -49,7 +49,7 @@ export function usePullRequestThreads(
49
const target = pullRequestTarget(params);
50
const config = useEnvironmentServerConfig(target.environmentId);
51
const supported = threadPullRequestLinkMode(config?.environment.capabilities) === "multiple";
52
- const parsed = pr ? parseChangeRequestUrl(pr.url) : null;
52
+ const parsed = pr ? sourceControlClients.parseChangeRequestUrl(pr.url)?.link : undefined;
53
const reference = {
54
...target,
55
input: { ...target.input, ...(parsed ? normalizeThreadPullRequestKey(parsed) : {}) },
apps/mobile/src/features/threads/LinkedPullRequestList.tsx
+1
-1
@@ -4,7 +4,7 @@ import {
4
resolveThreadPullRequestChains,
5
threadPullRequestKeyOf,
6
type PullRequestListLine,
7
-} from "@t3tools/shared/threadPullRequests";
7
+} from "@t3tools/client-runtime/thread-pull-requests";
8
import { memo, useMemo } from "react";
9
import { Pressable, useWindowDimensions, View } from "react-native";
10
apps/mobile/src/features/threads/new-task-context-presentation.ts
+2
-2
@@ -1,5 +1,5 @@
1
import { sanitizeNewRefName } from "@t3tools/shared/git";
2
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
2
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3
import { resolveSendEnvMode } from "@t3tools/shared/projectSettings";
4
import type { ComposerDraftWorkspaceSelection } from "../../state/use-composer-drafts";
5
@@ -79,7 +79,7 @@ export function resolveNewTaskBranchLabel(input: {
79
readonly pullRequestReference?: string;
80
}): string {
81
if (input.workspaceMode === "worktree" && input.pullRequestReference) {
82
- const pr = parseChangeRequestUrl(input.pullRequestReference);
82
+ const pr = sourceControlClients.parseChangeRequestUrl(input.pullRequestReference)?.link;
83
if (pr) return `From PR #${pr.number}`;
84
}
85
if (!input.branchName) {
apps/mobile/src/lib/pullRequestNavigation.ts
+20
-3
@@ -1,13 +1,30 @@
1
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
1
+import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";
2
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4
5
+/**
6
+ * Opens a change request in the app only under a project of the link's environment whose own
7
+ * repository holds it, preferring the one the link came from; anything else is the browser's.
8
+ */
9
export function nativePullRequestDestination(
10
url: string,
11
context: { environmentId: string; projectId: string } | null,
12
+ projects: ReadonlyArray<Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity">>,
13
) {
7
- const parsed = parseChangeRequestUrl(url);
14
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
15
if (!parsed || !context) return null;
16
+ const candidates = projects.filter((project) => project.environmentId === context.environmentId);
17
+ const project = findProjectForChangeRequest(
18
+ [
19
+ ...candidates.filter((candidate) => candidate.id === context.projectId),
20
+ ...candidates.filter((candidate) => candidate.id !== context.projectId),
21
+ ],
22
+ parsed,
23
+ );
24
+ if (project === undefined) return null;
25
return {
10
- ...context,
26
+ environmentId: context.environmentId,
27
+ projectId: String(project.id),
28
repository: parsed.repository,
29
number: parsed.number,
30
host: parsed.authority ?? parsed.host,
apps/mobile/src/native/useOpenPullRequest.ts
+4
-3
@@ -4,7 +4,7 @@ import { useCallback } from "react";
4
import { Platform } from "react-native";
5
import { resetAndroidWorkspace } from "../lib/android-workspace-navigation";
6
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
7
-import { useThreadShell } from "../state/entities";
7
+import { useProjects, useThreadShell } from "../state/entities";
8
import { tryOpenExternalUrl } from "../lib/openExternalUrl";
9
10
type PullRequestContext = { readonly environmentId: string; readonly projectId: string };
@@ -13,10 +13,11 @@ type PullRequestContext = { readonly environmentId: string; readonly projectId:
13
// route context for useRoute, can open pull requests for any thread.
14
export function useNavigateToPullRequest(options?: { readonly replace?: boolean }) {
15
const navigation = useNavigation();
16
+ const projects = useProjects();
17
const replace = options?.replace;
18
return useCallback(
19
async (url: string, context: PullRequestContext | null) => {
19
- const params = nativePullRequestDestination(url, context);
20
+ const params = nativePullRequestDestination(url, context, projects);
21
if (!params) return tryOpenExternalUrl(url, "pull-request");
22
if (Platform.OS === "android")
23
resetAndroidWorkspace(navigation, { name: "PullRequest", params });
@@ -24,7 +25,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean
25
else navigation.navigate("PullRequest", params);
26
return true;
27
},
27
- [navigation, replace],
28
+ [navigation, projects, replace],
29
);
30
}
31
apps/mobile/src/state/thread-pr-presentation.ts
+1
-1
@@ -9,7 +9,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli
9
import {
10
resolveThreadCurrentPullRequestLink,
11
resolveThreadPullRequestBadge,
12
-} from "@t3tools/shared/threadPullRequests";
12
+} from "@t3tools/client-runtime/thread-pull-requests";
13
14
export type ThreadPr = NonNullable<VcsStatusResult["pr"]>;
15
apps/server/src/git/GitManager.ts
+4
-4
@@ -62,7 +62,6 @@ import {
62
isSshRemoteUrl,
63
type ChangeRequestTerminology,
64
} from "@t3tools/shared/sourceControl";
65
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
65
import * as HostProcess from "@t3tools/shared/HostProcess";
66
import {
67
parseGitHubRepositorySelector,
@@ -71,7 +70,8 @@ import {
70
import {
71
normalizeThreadPullRequestKey,
72
threadPullRequestKeyOf,
74
-} from "@t3tools/shared/threadPullRequests";
73
+} from "../sourceControl/threadPullRequests.ts";
74
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
75
76
import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
77
import {
@@ -1202,8 +1202,8 @@ export const make = Effect.gen(function* () {
1202
>();
1203
const noteLookupState = (pr: PullRequestInfo) =>
1204
Effect.suspend(() => {
1205
- const parsed = parseChangeRequestUrl(pr.url);
1206
- if (parsed === null || parsed.number !== pr.number) return Effect.void;
1205
+ const parsed = sourceControlClients.parseChangeRequestUrl(pr.url)?.link;
1206
+ if (parsed === undefined || parsed.number !== pr.number) return Effect.void;
1207
const key = normalizeThreadPullRequestKey(parsed);
1208
const id = threadPullRequestKeyOf(key);
1209
const previous = lookupStates.get(id);
apps/server/src/git/linkCreatedPullRequest.ts
+5
-3
@@ -7,13 +7,13 @@ import {
7
type SourceControlProviderKind,
8
type ThreadId,
9
} from "@t3tools/contracts";
10
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
10
import * as Cause from "effect/Cause";
11
import * as Effect from "effect/Effect";
12
import * as Option from "effect/Option";
13
14
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
15
import * as ProjectService from "../project/ProjectService.ts";
16
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
17
18
export interface CreatedPullRequestKey {
19
readonly host: string;
@@ -30,8 +30,10 @@ export function createdPullRequestKey(
30
if ((status !== "created" && status !== "opened_existing") || number === undefined || !url) {
31
return null;
32
}
33
- const parsed = parseChangeRequestUrl(url);
34
- if (parsed !== null) return { ...parsed, url };
33
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
34
+ if (parsed !== undefined) {
35
+ return { host: parsed.host, repository: parsed.repository, number: parsed.number, url };
36
+ }
37
const identity = project?.repositoryIdentity;
38
const kind = identity?.provider as SourceControlProviderKind | undefined;
39
const repository = sourceControlRepositorySelector(identity);
apps/server/src/mcp/OrchestratorMcpService.ts
+1
-1
@@ -70,7 +70,7 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
70
import {
71
normalizeThreadPullRequestKey,
72
visibleThreadPullRequests,
73
-} from "@t3tools/shared/threadPullRequests";
73
+} from "../sourceControl/threadPullRequests.ts";
74
import * as Clock from "effect/Clock";
75
import * as Context from "effect/Context";
76
import * as Crypto from "effect/Crypto";
apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
+15
-41
@@ -390,44 +390,22 @@ describe("pull request toolkit handlers", () => {
390
});
391
expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
392
expect(result.host).toBe("gitlab.com");
393
- }),
394
- );
395
-
396
- it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () =>
397
- Effect.gen(function* () {
398
- const harness = yield* makeHarness({
399
- project: makeProject({
400
- canonicalKey: "forge.example/git/owner/repo",
401
- locator: {
402
- source: "git-remote",
403
- remoteName: "origin",
404
- remoteUrl: "http://forge.example:3000/git/owner/repo.git",
405
- },
406
- provider: "forgejo",
407
- displayName: "git/owner/repo",
408
- }),
409
- });
410
- const result = yield* harness.call("link_pull_request", {
411
- repository: "git/owner/repo",
412
- number: 42,
413
- });
414
- expect(result).toEqual({
415
- host: "forge.example:3000",
416
- repository: "git/owner/repo",
417
- number: 42,
418
- url: "http://forge.example:3000/git/owner/repo/pulls/42",
419
- alreadyLinked: false,
420
- });
393
const other = yield* harness.call("link_pull_request", {
422
- host: "other.example",
423
- repository: "owner/repo",
424
- number: 42,
394
+ host: "gitlab.example.test",
395
+ repository: "team/repo",
396
+ number: 7,
397
+ });
398
+ expect(other.url).toBe("https://gitlab.example.test/team/repo/-/merge_requests/7");
399
+ const onGitHub = yield* harness.call("link_pull_request", {
400
+ host: "github.com",
401
+ repository: "acme/web",
402
+ number: 9,
403
});
426
- expect(other.url).toBe("https://other.example/owner/repo/pull/42");
404
+ expect(onGitHub.url).toBe("https://github.com/acme/web/pull/9");
405
}),
406
);
407
430
- it.effect("links Azure DevOps Server URLs and numeric references without a known provider", () =>
408
+ it.effect("links a URL but not a bare number when the project's host is unknown", () =>
409
Effect.gen(function* () {
410
const harness = yield* makeHarness({
411
project: makeProject({
@@ -441,13 +419,10 @@ describe("pull request toolkit handlers", () => {
419
displayName: "tfs/collection/project/_git/repo",
420
}),
421
});
444
- const generated =
445
- "http://scm.example.test:8080/tfs/collection/project/_git/repo/pullrequest/124";
446
- const fromNumber = yield* harness.call("link_pull_request", {
447
- repository: "tfs/Collection/Project/_git/Repo",
448
- number: 124,
449
- });
450
- expect.soft(fromNumber.url).toBe(generated);
422
+ const error = yield* harness
423
+ .call("link_pull_request", { repository: "tfs/Collection/Project/_git/Repo", number: 124 })
424
+ .pipe(Effect.flip);
425
+ expect(error).toMatchObject({ _tag: "PullRequestUrlUnavailableError" });
426
427
const supplied = "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123";
428
const fromUrl = yield* harness.call("link_pull_request", { url: supplied });
@@ -459,7 +434,6 @@ describe("pull request toolkit handlers", () => {
434
alreadyLinked: false,
435
});
436
expect(yield* Ref.get(harness.commands)).toMatchObject([
462
- { type: "thread.pull-request.link", number: 124, url: generated },
437
{ type: "thread.pull-request.link", number: 123, url: supplied },
438
]);
439
}),
apps/server/src/mcp/toolkits/pullRequests/handlers.ts
+35
-29
@@ -1,7 +1,3 @@
1
-import {
2
- threadPullRequestsOf,
3
- threadPullRequestKeysEqual,
4
-} from "@t3tools/shared/threadPullRequests";
1
import {
2
CommandId,
3
pullRequestHostOf,
@@ -11,14 +7,7 @@ import {
7
type ThreadId,
8
type ThreadPullRequestLink,
9
} from "@t3tools/contracts";
14
-import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
10
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
16
-import {
17
- normalizeThreadPullRequestKey,
18
- resolveThreadPullRequestChains,
19
- threadPullRequestKeyOf,
20
- visibleThreadPullRequests,
21
-} from "@t3tools/shared/threadPullRequests";
11
import * as Cause from "effect/Cause";
12
import * as Crypto from "effect/Crypto";
13
import * as Effect from "effect/Effect";
@@ -28,6 +17,15 @@ import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
17
import * as ProjectService from "../../../project/ProjectService.ts";
18
import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
19
import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
20
+import { sourceControlClients } from "../../../sourceControl/sourceControlClients.ts";
21
+import {
22
+ normalizeThreadPullRequestKey,
23
+ resolveThreadPullRequestChains,
24
+ threadPullRequestKeyOf,
25
+ threadPullRequestKeysEqual,
26
+ threadPullRequestsOf,
27
+ visibleThreadPullRequests,
28
+} from "../../../sourceControl/threadPullRequests.ts";
29
import * as McpInvocationContext from "../../McpInvocationContext.ts";
30
import * as McpToolAccess from "../../McpToolAccess.ts";
31
import {
@@ -36,6 +34,7 @@ import {
34
PullRequestUrlInvalidError,
35
PullRequestTargetIncompleteError,
36
PullRequestHostRequiredError,
37
+ PullRequestUrlUnavailableError,
38
PullRequestUnlinkFailedError,
39
PullRequestListFailedError,
40
PullRequestNotOpenError,
@@ -75,8 +74,8 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
74
project: OrchestrationProjectShell | undefined,
75
) {
76
if (input.url !== undefined) {
78
- const parsed = parseChangeRequestUrl(input.url);
79
- if (parsed === null) {
77
+ const parsed = sourceControlClients.parseChangeRequestUrl(input.url)?.link;
78
+ if (parsed === undefined) {
79
return yield* new PullRequestUrlInvalidError({});
80
}
81
return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;
@@ -90,24 +89,21 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
89
return yield* new PullRequestHostRequiredError({});
90
}
91
const repository = input.repository.toLowerCase();
92
+ // Without a URL, a public forge host says what shape its change request URLs take;
93
+ // any other host is taken to run the project's own forge.
94
+ const kind = sourceControlClients.findByPublicHost(host)?.kind ?? projectHost.kind;
95
const url =
94
- changeRequestUrlFor(
95
- host === projectHost.host ? projectHost.kind : null,
96
- host,
97
- repository,
98
- input.number,
99
- project?.repositoryIdentity?.locator.remoteUrl,
100
- ) ??
101
- (/(?:^|\/)_git\/[^/]+$/u.test(repository)
102
- ? changeRequestUrlFor(
103
- "azure-devops",
96
+ kind === null
97
+ ? null
98
+ : sourceControlClients.get(kind).changeRequestUrl({
99
host,
100
repository,
106
- input.number,
107
- project?.repositoryIdentity?.locator.remoteUrl,
108
- )
109
- : null) ??
110
- `https://${host}/${repository}/pull/${input.number}`;
101
+ number: input.number,
102
+ remoteUrl: project?.repositoryIdentity?.locator.remoteUrl,
103
+ });
104
+ if (url === null) {
105
+ return yield* new PullRequestUrlUnavailableError({});
106
+ }
107
return {
108
...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
109
url,
@@ -314,8 +310,18 @@ const make = Effect.gen(function* () {
310
.listShells()
311
.pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
312
const callerProject = known.find((project) => project.id === callerThread?.projectId);
313
+ // A pull request named by host and repository builds its URL through the project that holds
314
+ // it, which need not be the caller's.
315
+ const urlProject = (input: PullRequestTargetInput) =>
316
+ input.url === undefined && input.host !== undefined && input.repository !== undefined
317
+ ? (projectForPullRequest(
318
+ known,
319
+ { host: input.host, repository: input.repository },
320
+ callerProject,
321
+ ) ?? callerProject)
322
+ : callerProject;
323
return yield* Effect.forEach(targets, (input) =>
318
- resolveTarget(input, callerProject).pipe(
324
+ resolveTarget(input, urlProject(input)).pipe(
325
Effect.map((target) => ({
326
input,
327
target,
apps/server/src/mcp/toolkits/pullRequests/tools.ts
+10
@@ -93,6 +93,15 @@ export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequest
93
}
94
}
95
96
+export class PullRequestUrlUnavailableError extends Schema.TaggedError<PullRequestUrlUnavailableError>()(
97
+ "PullRequestUrlUnavailableError",
98
+ {},
99
+) {
100
+ override get message(): string {
101
+ return "This thread's project is on a host with no known pull request URL shape. Pass url.";
102
+ }
103
+}
104
+
105
export class PullRequestThreadRequiredError extends Schema.TaggedError<PullRequestThreadRequiredError>()(
106
"PullRequestThreadRequiredError",
107
{},
@@ -189,6 +198,7 @@ export const PullRequestToolError = Schema.Union([
198
PullRequestUrlInvalidError,
199
PullRequestTargetIncompleteError,
200
PullRequestHostRequiredError,
201
+ PullRequestUrlUnavailableError,
202
PullRequestThreadRequiredError,
203
PullRequestThreadNotFoundError,
204
PullRequestLinkFailedError,
apps/server/src/orchestration-v2/Orchestrator.ts
+2
-2
@@ -9,13 +9,13 @@ import {
9
runRanAfter,
10
usageLimitBlockedRun,
11
} from "@t3tools/shared/orchestrationV2ThreadError";
12
-import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
12
+import { threadPullRequestsOf } from "../sourceControl/threadPullRequests.ts";
13
import {
14
normalizeThreadPullRequestKey,
15
visibleThreadPullRequests,
16
threadPullRequestKeysEqual,
17
legacyThreadPullRequestKey,
18
-} from "@t3tools/shared/threadPullRequests";
18
+} from "../sourceControl/threadPullRequests.ts";
19
import {
20
ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
21
type ChatAttachment,
apps/server/src/orchestration-v2/ProjectionStore.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { applyThreadPullRequestLinkUpdate } from "@t3tools/shared/threadPullRequests";
1
+import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts";
2
import { projectTurnItemForWire } from "./WireProjection.ts";
3
import * as Stream from "effect/Stream";
4
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -14,7 +14,7 @@ import {
14
threadErrorSummary,
15
usageLimitRunPresentedAsLatest,
16
} from "@t3tools/shared/orchestrationV2ThreadError";
17
-import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
17
+import { threadPullRequestsOf } from "../sourceControl/threadPullRequests.ts";
18
import type {
19
OrchestrationV2AppThread,
20
OrchestrationV2Checkpoint,
apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
+17
-3
@@ -1,4 +1,3 @@
1
-import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
1
import {
2
CommandId,
3
type PullRequestSummary,
@@ -14,7 +13,8 @@ import {
13
normalizeThreadPullRequestKey,
14
threadPullRequestKeysEqual,
15
visibleThreadPullRequests,
17
-} from "@t3tools/shared/threadPullRequests";
16
+} from "../sourceControl/threadPullRequests.ts";
17
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
18
import * as Cause from "effect/Cause";
19
import * as Clock from "effect/Clock";
20
import * as Context from "effect/Context";
@@ -53,6 +53,20 @@ interface LinkEntry {
53
readonly link: ThreadPullRequestLink;
54
}
55
56
+/** Another layer of the stack `url` belongs to, in its host's canonical shape. */
57
+function siblingChangeRequestUrl(url: string, number: number): string | null {
58
+ if (!Number.isSafeInteger(number) || number < 1) return null;
59
+ const parsed = sourceControlClients.parseChangeRequestUrl(url);
60
+ if (parsed === null) return null;
61
+ const { definition, link } = parsed;
62
+ return definition.changeRequestUrl({
63
+ host: link.host,
64
+ repository: link.repository,
65
+ number,
66
+ webUrl: link.repositoryUrl,
67
+ });
68
+}
69
+
70
function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
71
return {
72
state: summary.state,
@@ -287,7 +301,7 @@ export const make = Effect.gen(function* () {
301
) {
302
continue;
303
}
290
- const url = siblingPullRequestUrl(link.url, layer.number);
304
+ const url = siblingChangeRequestUrl(link.url, layer.number);
305
if (url === null) continue;
306
const uuid = yield* crypto.randomUUIDv4();
307
yield* engine.dispatch({
apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+1
-1
@@ -13,7 +13,7 @@ import {
13
normalizeThreadPullRequestKey,
14
threadPullRequestKeyOf,
15
visibleThreadPullRequests,
16
-} from "@t3tools/shared/threadPullRequests";
16
+} from "../sourceControl/threadPullRequests.ts";
17
import * as Cause from "effect/Cause";
18
import * as Clock from "effect/Clock";
19
import * as Context from "effect/Context";
apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
+1
-1
@@ -1,7 +1,7 @@
1
import {
2
threadPullRequestKeysEqual,
3
threadPullRequestsOf,
4
-} from "@t3tools/shared/threadPullRequests";
4
+} from "../../sourceControl/threadPullRequests.ts";
5
import {
6
ChatAttachment,
7
OrchestrationMessageContext,
apps/server/src/persistence/Migrations/050_ProjectionThreadPullRequests.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { legacyThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
1
+import { legacyThreadPullRequestKey } from "./legacyThreadPullRequestKey.ts";
2
import * as Effect from "effect/Effect";
3
import * as SqlClient from "effect/sql/SqlClient";
4
apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.ts
+1
-1
@@ -1,5 +1,5 @@
1
import { ThreadLinkedPullRequest, ThreadPullRequestLink } from "@t3tools/contracts";
2
-import { legacyThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
2
+import { legacyThreadPullRequestKey } from "./legacyThreadPullRequestKey.ts";
3
import * as Effect from "effect/Effect";
4
import * as Schema from "effect/Schema";
5
import * as SqlClient from "effect/sql/SqlClient";
apps/server/src/persistence/Migrations/legacyThreadPullRequestKey.ts
new
+109
@@ -0,0 +1,109 @@
1
+import type { ThreadLinkedPullRequest, ThreadPullRequestKey } from "@t3tools/contracts";
2
+
3
+/**
4
+ * Frozen for migrations 050 and 064: the change request URL parsing and key normalization they
5
+ * shipped with. Migrations are history, so they must not follow the live source control hosts.
6
+ */
7
+
8
+interface FrozenLink {
9
+ readonly host: string;
10
+ readonly repository: string;
11
+ readonly number: number;
12
+ readonly authority?: string;
13
+}
14
+
15
+function canonicalRepositoryKey(key: string): string {
16
+ return key
17
+ .replace(
18
+ /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
19
+ "dev.azure.com/$1/$2/_git/$3",
20
+ )
21
+ .replace(
22
+ /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
23
+ "dev.azure.com/$1/$2/_git/$3",
24
+ );
25
+}
26
+
27
+function isHostOf(hostname: string, apex: string, label: string): boolean {
28
+ return hostname === apex || hostname.endsWith(`.${apex}`) || hostname.split(".").includes(label);
29
+}
30
+
31
+function claim(host: string, match: RegExpExecArray | null): FrozenLink | null {
32
+ const repository = match?.[1];
33
+ const number = Number(match?.[2]);
34
+ return repository && Number.isSafeInteger(number) && number > 0
35
+ ? { host, repository: repository.toLowerCase(), number }
36
+ : null;
37
+}
38
+
39
+function parseChangeRequestUrl(targetUrl: string): FrozenLink | null {
40
+ let url: URL;
41
+ try {
42
+ url = new URL(targetUrl);
43
+ } catch {
44
+ return null;
45
+ }
46
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
47
+ const host = url.hostname.toLowerCase();
48
+
49
+ if (host === "git.cafe" || host === "staging.git.cafe") {
50
+ const match = /^\/([^/]+\/[^/]+)\/pulls?\/(\d+)(?:\/|$)/u.exec(url.pathname);
51
+ if (match) return claim(host, match);
52
+ } else {
53
+ if (isHostOf(host, "github.com", "github")) {
54
+ const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
55
+ if (match) return claim(host, match);
56
+ }
57
+ const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);
58
+ if (forgejo) {
59
+ const link = claim(host, forgejo);
60
+ return link === null ? null : { ...link, authority: url.host.toLowerCase() };
61
+ }
62
+ const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
63
+ if (gitlab) return claim(host, gitlab);
64
+ if (isHostOf(host, "bitbucket.org", "bitbucket")) {
65
+ const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
66
+ if (match) return claim(host, match);
67
+ }
68
+ }
69
+ const azure = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
70
+ const link = claim(host, azure);
71
+ return link === null || url.port === "" ? link : { ...link, authority: url.host.toLowerCase() };
72
+}
73
+
74
+function normalizeThreadPullRequestKey(
75
+ key: ThreadPullRequestKey & { readonly authority?: string },
76
+): ThreadPullRequestKey {
77
+ const canonical = canonicalRepositoryKey(
78
+ `${(key.authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
79
+ );
80
+ const separator = canonical.indexOf("/");
81
+ return {
82
+ host: canonical.slice(0, separator),
83
+ repository: canonical.slice(separator + 1),
84
+ number: key.number,
85
+ };
86
+}
87
+
88
+export function legacyThreadPullRequestKey(
89
+ linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
90
+): ThreadPullRequestKey {
91
+ const parsed = parseChangeRequestUrl(linked.url);
92
+ if (parsed !== null && parsed.number === linked.number) {
93
+ const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
94
+ if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
95
+ return normalizeThreadPullRequestKey(parsed);
96
+ }
97
+ }
98
+ let host: string;
99
+ try {
100
+ host = new URL(linked.url).hostname;
101
+ } catch {
102
+ host = "unknown";
103
+ }
104
+ return {
105
+ host: host.trim().toLowerCase() || "unknown",
106
+ repository: linked.repository.trim().toLowerCase(),
107
+ number: linked.number,
108
+ };
109
+}
apps/server/src/pullRequest/linkedThreads.ts
+1
-1
@@ -1,7 +1,7 @@
1
import {
2
normalizeThreadPullRequestKey,
3
threadPullRequestKeysEqual,
4
-} from "@t3tools/shared/threadPullRequests";
4
+} from "../sourceControl/threadPullRequests.ts";
5
import {
6
PullRequestLinkedThreadsResult,
7
PullRequestOperationError,
apps/server/src/pullRequest/pullRequestSyncKey.ts
+1
-1
@@ -6,7 +6,7 @@ import {
6
type ThreadPullRequestKey,
7
} from "@t3tools/contracts";
8
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
9
-import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
9
+import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts";
10
11
export function pullRequestSyncKey(
12
reference: PullRequestRef,
apps/server/src/sourceControl/SourceControlDiscovery.test.ts
+8
-8
@@ -217,27 +217,27 @@ Logged in to gitlab.com as gitlab-user
217
detail: Option.none(),
218
},
219
{
220
- kind: SourceControlProviderKind.make("azure-devops"),
220
+ kind: SourceControlProviderKind.make("gitcafe"),
221
auth: "authenticated",
222
- account: Option.some("azure-user@example.com"),
222
+ account: Option.some("cafe-user"),
223
detail: Option.none(),
224
},
225
{
226
- kind: SourceControlProviderKind.make("bitbucket"),
226
+ kind: SourceControlProviderKind.make("forgejo"),
227
auth: "authenticated",
228
- account: Option.some("bitbucket-user"),
228
+ account: Option.some("forgejo-user"),
229
detail: Option.none(),
230
},
231
{
232
- kind: SourceControlProviderKind.make("forgejo"),
232
+ kind: SourceControlProviderKind.make("bitbucket"),
233
auth: "authenticated",
234
- account: Option.some("forgejo-user"),
234
+ account: Option.some("bitbucket-user"),
235
detail: Option.none(),
236
},
237
{
238
- kind: SourceControlProviderKind.make("gitcafe"),
238
+ kind: SourceControlProviderKind.make("azure-devops"),
239
auth: "authenticated",
240
- account: Option.some("cafe-user"),
240
+ account: Option.some("azure-user@example.com"),
241
detail: Option.none(),
242
},
243
],
apps/server/src/sourceControl/builtInDrivers.ts
+1
-15
@@ -1,34 +1,20 @@
1
import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
2
import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
3
-import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";
3
import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
4
import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
6
-import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";
5
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
8
-import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
6
import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
7
import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
11
-import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver";
8
import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
9
import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
14
-import * as GitHubDriver from "@t3tools/source-control-github/server/driver";
10
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
11
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
17
-import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
12
import type { SourceControlDriver } from "@t3tools/source-control-core/server/driver";
13
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
14
import * as Layer from "effect/Layer";
15
16
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
23
-
24
-const drivers = [
25
- GitHubDriver.driver,
26
- GitLabDriver.driver,
27
- AzureDevOpsDriver.driver,
28
- BitbucketDriver.driver,
29
- ForgejoDriver.driver,
30
- GitCafeDriver.driver,
31
-];
17
+import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST as drivers } from "./sourceControlClients.ts";
18
19
export type BuiltInSourceControlDriversEnv =
20
(typeof drivers)[number] extends SourceControlDriver<infer R> ? R : never;
apps/server/src/sourceControl/sourceControlClients.ts
new
+27
@@ -0,0 +1,27 @@
1
+import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";
2
+import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";
3
+import { makeSourceControlClientRegistry } from "@t3tools/source-control-core/client/definition";
4
+import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
5
+import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver";
6
+import * as GitHubDriver from "@t3tools/source-control-github/server/driver";
7
+import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
8
+
9
+/**
10
+ * The same order as the clients' registry in `@t3tools/client-runtime/source-control-clients`.
11
+ * A change request URL goes to the first host whose shape it has, so GitCafe, which claims
12
+ * `/pull/` and `/pulls/` only on its own hostnames, claims before GitHub and Forgejo, which
13
+ * claim them everywhere.
14
+ */
15
+export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [
16
+ GitHubDriver.driver,
17
+ GitLabDriver.driver,
18
+ GitCafeDriver.driver,
19
+ ForgejoDriver.driver,
20
+ BitbucketDriver.driver,
21
+ AzureDevOpsDriver.driver,
22
+] as const;
23
+
24
+export const sourceControlClients = makeSourceControlClientRegistry(
25
+ BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.map((driver) => driver.definition),
26
+ { claimChangeRequestUrlsFirst: [GitCafeDriver.driver.kind] },
27
+);
apps/server/src/sourceControl/sourceControlHostSecrets.ts
+2
-16
@@ -1,26 +1,12 @@
1
import { secretSettingsFields } from "@t3tools/contracts";
2
-import * as AzureDevOps from "@t3tools/source-control-azure-devops/client/definition";
3
-import * as Bitbucket from "@t3tools/source-control-bitbucket/client/definition";
4
-import type { SourceControlClientDefinition } from "@t3tools/source-control-core/client/definition";
5
-import * as Forgejo from "@t3tools/source-control-forgejo/client/definition";
6
-import * as GitCafe from "@t3tools/source-control-gitcafe/client/definition";
7
-import * as GitHub from "@t3tools/source-control-github/client/definition";
8
-import * as GitLab from "@t3tools/source-control-gitlab/client/definition";
2
10
-const definitions: ReadonlyArray<SourceControlClientDefinition> = [
11
- GitHub.definition,
12
- GitLab.definition,
13
- AzureDevOps.definition,
14
- Bitbucket.definition,
15
- Forgejo.definition,
16
- GitCafe.definition,
17
-];
3
+import { sourceControlClients } from "./sourceControlClients.ts";
4
5
export const SOURCE_CONTROL_HOST_SECRET_FIELDS: ReadonlyMap<
6
string,
7
ReadonlyArray<string>
8
> = new Map(
23
- definitions.flatMap((definition) => {
9
+ sourceControlClients.definitions.flatMap((definition) => {
10
const fields = definition.settings ? secretSettingsFields(definition.settings) : [];
11
return fields.length > 0 ? [[definition.kind, fields] as const] : [];
12
}),
apps/server/src/sourceControl/threadPullRequests.ts
new
+15
@@ -0,0 +1,15 @@
1
+import { makeThreadPullRequests } from "@t3tools/source-control-core/client/threadPullRequests";
2
+
3
+import { sourceControlClients } from "./sourceControlClients.ts";
4
+
5
+export { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
6
+
7
+export const {
8
+ normalizeThreadPullRequestKey,
9
+ legacyThreadPullRequestKey,
10
+ threadPullRequestKeysEqual,
11
+ threadPullRequestKeyOf,
12
+ resolveThreadPullRequestChains,
13
+ threadPullRequestsOf,
14
+ applyThreadPullRequestLinkUpdate,
15
+} = makeThreadPullRequests(sourceControlClients);
apps/web/src/components/BranchToolbarBranchSelector.tsx
+1
-1
@@ -1,7 +1,7 @@
1
import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
2
import { ComposerContextLabel } from "./ComposerContextLabel";
3
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
4
-import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
4
+import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";
5
import { useRightPanelStore } from "../rightPanelStore";
6
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
7
import {
apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx
+1
-11
@@ -95,20 +95,10 @@ vi.mock(import("../localApi"), async (original) => ({
95
shell: { openExternal: state.openExternal },
96
}) as never,
97
}));
98
-vi.mock(import("~/lib/openPullRequestLink"), async (original) => ({
98
+vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({
99
...(await original()),
100
resolvePullRequestPreviewTarget: () => null,
101
findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
102
- matchesLinkedPullRequestUrl: (candidate: ThreadLinkedPullRequest, href: string) =>
103
- candidate.url === href,
104
- parseChangeRequestUrl: ((href: string) =>
105
- href === linkedPullRequest.url
106
- ? {
107
- host: "github.com",
108
- repository: linkedPullRequest.repository,
109
- number: linkedPullRequest.number,
110
- }
111
- : null) as never,
102
}));
103
104
import ChatMarkdown from "./ChatMarkdown";
apps/web/src/components/ChatMarkdown.tsx
+10
-11
@@ -167,12 +167,9 @@ import {
167
stripRepeatedWorkspacePrefix,
168
WORKSPACE_BASENAME_LOOKUP_LIMIT,
169
} from "@t3tools/client-runtime/workspace-basename-lookup";
170
-import {
171
- parseChangeRequestUrl,
172
- pullRequestCandidateUrlFromReferenceAutolink,
173
- resolvePullRequestPreviewTarget,
174
- useOpenChangeRequestLink,
175
-} from "~/lib/openPullRequestLink";
170
+import { resolvePullRequestPreviewTarget } from "@t3tools/client-runtime/change-request-links";
171
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
172
+import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
173
import { useOpenLink } from "../browser/useOpenLink";
174
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
175
import { isPreviewAvailableFor } from "../browser/previewRuntime";
@@ -679,14 +676,14 @@ function useChatMarkdownState({
676
!pullRequestLinking.canLink(href)
677
)
678
return null;
682
- const parsed = parseChangeRequestUrl(href);
683
- return parsed === null ? null : { ...parsed, url: href };
679
+ const parsed = sourceControlClients.parseChangeRequestUrl(href)?.link;
680
+ return parsed === undefined ? null : { ...parsed, url: href };
681
};
682
const linkedThreadPullRequestFor = (href: string) => {
683
if (threadRef === undefined || !pullRequestLinking.isLinked(readThreadShell(threadRef), href))
684
return null;
688
- const parsed = parseChangeRequestUrl(href);
689
- return parsed === null ? null : { ...parsed, url: href };
685
+ const parsed = sourceControlClients.parseChangeRequestUrl(href)?.link;
686
+ return parsed === undefined ? null : { ...parsed, url: href };
687
};
688
const updateThreadPullRequestLink = async (href: string, linked: boolean) => {
689
if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return;
@@ -1109,7 +1106,9 @@ const CHAT_MARKDOWN_COMPONENTS = {
1106
const isPullRequestAutolink = pullRequestCopy !== undefined;
1107
const confirmBeforeOpen = pullRequestAutolink === "reference";
1108
const pullRequestCandidateUrl =
1112
- confirmBeforeOpen && href ? pullRequestCandidateUrlFromReferenceAutolink(href) : href;
1109
+ confirmBeforeOpen && href
1110
+ ? sourceControlClients.changeRequestUrlFromReferenceAutolink(href)
1111
+ : href;
1112
const pullRequestPreviewTarget = pullRequestCandidateUrl
1113
? resolvePullRequestPreviewTarget({
1114
environmentId,
apps/web/src/components/ChatView.tsx
+1
-1
@@ -102,7 +102,7 @@ import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/mod
102
import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
103
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
104
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
105
-import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
105
+import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
106
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
107
import { useAtomValue } from "@effect/atom-react";
108
import { type SetStateAction, useEffect, useLayoutEffect, useRef, useState } from "react";
apps/web/src/components/CommandPalette.tsx
+1
-1
@@ -22,7 +22,7 @@ import {
22
} from "@t3tools/client-runtime/operations/projects";
23
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
24
import { connectionStatusText } from "@t3tools/client-runtime/connection";
25
-import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
25
+import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
26
import {
27
canPreloadBrowsePath,
28
createBrowseNavigationCoordinator,
apps/web/src/components/LegacySidebar.tsx
+1
-1
@@ -1,5 +1,5 @@
1
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
2
-import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
2
+import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";
3
import { Spinner } from "~/components/ui/spinner";
4
import {
5
ArchiveIcon,
apps/web/src/components/RightPanelTabs.tsx
+1
-1
@@ -4,7 +4,7 @@ import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities
4
import {
5
threadPullRequestKeysEqual,
6
visibleThreadPullRequests,
7
-} from "@t3tools/shared/threadPullRequests";
7
+} from "@t3tools/client-runtime/thread-pull-requests";
8
import type {
9
ContextMenuItem,
10
EnvironmentId,
apps/web/src/components/ThreadStatusIndicators.tsx
+3
-4
@@ -27,13 +27,12 @@ import {
27
resolveThreadPullRequestChains,
28
type ThreadPullRequestBadge,
29
visibleThreadPullRequests,
30
-} from "@t3tools/shared/threadPullRequests";
30
+} from "@t3tools/client-runtime/thread-pull-requests";
31
import { useRender } from "@base-ui/react/use-render";
32
import { type ReactNode, type AnimationEvent, type MouseEvent, type ReactElement } from "react";
33
import { cn } from "../lib/utils";
34
import { revealThreadTerminal } from "../lib/revealThreadTerminal";
35
36
-import { parseChangeRequestUrl } from "../lib/openPullRequestLink";
36
import { useEnvironmentQuery } from "../state/query";
37
import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
38
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
@@ -120,7 +119,7 @@ export function useLinkedThreadPullRequest(
119
}
120
121
function linkedPullRequestReference(fallback: ThreadLinkedPullRequest) {
123
- const host = parseChangeRequestUrl(fallback.url)?.host;
122
+ const host = sourceControlClients.parseChangeRequestUrl(fallback.url)?.link.host;
123
return { ...fallback, ...(host === undefined ? {} : { host }) };
124
}
125
@@ -150,7 +149,7 @@ export function linkedPullRequestSnapshotStatus(
149
export {
150
resolveThreadPullRequestBadge,
151
type ThreadPullRequestBadge,
153
-} from "@t3tools/shared/threadPullRequests";
152
+} from "@t3tools/client-runtime/thread-pull-requests";
153
154
export interface ThreadPullRequestBadgePresentation {
155
readonly Icon: PullRequestGlyphIcon;
apps/web/src/components/chat/ThreadDetailsPrRows.tsx
+5
-4
@@ -5,11 +5,12 @@ import {
5
resolveThreadPullRequestChains,
6
threadPullRequestKeyOf,
7
visibleThreadPullRequests,
8
-} from "@t3tools/shared/threadPullRequests";
8
+} from "@t3tools/client-runtime/thread-pull-requests";
9
import { Minus, Plus } from "lucide";
10
import { useState, type ComponentProps, type MouseEvent as ReactMouseEvent } from "react";
11
12
-import { findProjectOnChangeRequestHost, parseChangeRequestUrl } from "~/lib/openPullRequestLink";
12
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
13
+import { findProjectOnChangeRequestHost } from "~/lib/openPullRequestLink";
14
15
import { useProjects } from "~/state/entities";
16
import { threadEnvironment } from "~/state/threads";
@@ -34,9 +35,9 @@ function ThreadDetailsPrLinkRow({
35
onStopWatching?: (() => void) | undefined;
36
}) {
37
const projects = useProjects();
37
- const parsed = parseChangeRequestUrl(link.url);
38
+ const parsed = sourceControlClients.parseChangeRequestUrl(link.url)?.link;
39
const project =
39
- parsed === null
40
+ parsed === undefined
41
? null
42
: (findProjectOnChangeRequestHost(
43
projects.filter((candidate) => candidate.environmentId === environmentId),
apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
+2
-2
@@ -1,7 +1,7 @@
1
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
4
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
4
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
6
import { useRouter } from "@tanstack/react-router";
7
import * as Effect from "effect/Effect";
@@ -155,7 +155,7 @@ export function DesktopWebLinkCoordinator() {
155
// delivered at launch would miss its project and fall through to the browser. Hold PR
156
// links, and only those, until discovery settles; an ordinary link never waits for it.
157
const hold =
158
- openPullRequestsInApp && parseChangeRequestUrl(url) !== null
158
+ openPullRequestsInApp && sourceControlClients.parseChangeRequestUrl(url) !== null
159
? projectsSettled()
160
: Promise.resolve();
161
void hold.then(() => {
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+21
-7
@@ -1,4 +1,4 @@
1
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
1
+import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
2
import { useAtomValue } from "@effect/atom-react";
3
import { usePullRequestStack } from "~/state/usePullRequestStack";
4
import {
@@ -53,7 +53,6 @@ import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings
53
import { primaryServerKeybindingsAtom } from "~/state/server";
54
import { usePullRequestDefaultMergeMethodResolver } from "./usePullRequestActions";
55
import { OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST } from "./pullRequestCheckoutToast";
56
-import { changeRequestRepositoryUrl, gitHubPullRequestBrowserUrl } from "~/lib/openPullRequestLink";
56
import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
57
import { cn } from "~/lib/utils";
58
import { readLocalApi } from "~/localApi";
@@ -252,7 +251,10 @@ function pullRequestStackReference(
251
) {
252
return detail === null || detail.capabilities.stacks !== true || !supportsThreadPullRequests
253
? null
255
- : { ...reference, host: reference.host ?? parseChangeRequestUrl(detail.url)?.host };
254
+ : {
255
+ ...reference,
256
+ host: reference.host ?? sourceControlClients.parseChangeRequestUrl(detail.url)?.link.host,
257
+ };
258
}
259
260
export function PullRequestDetailPanel({
@@ -305,7 +307,7 @@ export function PullRequestDetailPanel({
307
supportsThreadPullRequests,
308
);
309
const loadingCheckoutCommand = loadingPullRequestCheckoutCommand(reference, repositoryIdentity);
308
- const unavailableGitHubUrl = gitHubPullRequestBrowserUrl(
310
+ const unavailableHostUrl = projectChangeRequestUrl(
311
repositoryIdentity,
312
reference.repository,
313
reference.number,
@@ -469,7 +471,10 @@ export function PullRequestDetailPanel({
471
setSeenAutoMergeKey(autoMergeKey);
472
if (detail?.autoMergeMethod !== undefined) setMergeMethod(detail.autoMergeMethod);
473
}
472
- const repositoryUrl = detail === null ? null : changeRequestRepositoryUrl(detail.url);
474
+ const repositoryUrl =
475
+ detail === null
476
+ ? null
477
+ : (sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl ?? null);
478
const hostClient = sourceControlClients.get(detail?.provider);
479
const openOnHostText = openOnHostLabel(hostClient);
480
const markdownContext = pullRequestMarkdownContext(hostClient, repositoryUrl, threadRef);
@@ -483,7 +488,7 @@ export function PullRequestDetailPanel({
488
handoffSummary.number,
489
handoffSummary.headBranch,
490
detail?.headRepositoryNameWithOwner,
486
- changeRequestRepositoryUrl(handoffSummary.url),
491
+ sourceControlClients.parseChangeRequestUrl(handoffSummary.url)?.link.repositoryUrl ?? null,
492
)
493
: loadingCheckoutCommand;
494
const branchRefsQuery = useEnvironmentQuery(
@@ -1695,7 +1700,16 @@ export function PullRequestDetailPanel({
1700
: { error: detailQuery.error })}
1701
refreshing={detailQuery.isPending}
1702
onRetry={refreshDetail}
1698
- {...(unavailableGitHubUrl ? { gitHubUrl: unavailableGitHubUrl } : {})}
1703
+ {...(unavailableHostUrl
1704
+ ? {
1705
+ host: {
1706
+ url: unavailableHostUrl,
1707
+ openLabel: openOnHostLabel(
1708
+ sourceControlClients.get(repositoryIdentity?.provider),
1709
+ ),
1710
+ },
1711
+ }
1712
+ : {})}
1713
/>
1714
) : detail ? (
1715
<PullRequestMarkdownContext value={markdownContext}>
apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx
+3
-3
@@ -7,8 +7,8 @@ import { useState } from "react";
7
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
8
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
9
10
-import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
11
-import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
10
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
11
+import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
12
import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";
13
import { pullRequestEnvironment } from "~/state/pullRequests";
14
import { useEnvironmentQuery } from "~/state/query";
@@ -49,7 +49,7 @@ function EnabledPullRequestThreadLinks({
49
display,
50
onPickerOpenChange,
51
}: PullRequestThreadLinksProps) {
52
- const parsed = parseChangeRequestUrl(url);
52
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link ?? null;
53
const thread = useThreadShell(threadRef?.environmentId === environmentId ? threadRef : null);
54
const currentThreadRef = thread === null ? null : threadRef;
55
const linking = usePullRequestLinking(environmentId);
apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx
+6
-6
@@ -10,13 +10,13 @@ export function PullRequestsUnavailableState({
10
error,
11
onRetry,
12
refreshing = false,
13
- gitHubUrl,
13
+ host,
14
}: {
15
title?: string;
16
error: string;
17
onRetry?: () => void;
18
refreshing?: boolean;
19
- gitHubUrl?: string;
19
+ host?: { readonly url: string; readonly openLabel: string };
20
}) {
21
return (
22
<Empty className="scrollbar-gutter-both min-h-0 justify-center-safe overflow-y-auto [&>*]:shrink-0">
@@ -29,7 +29,7 @@ export function PullRequestsUnavailableState({
29
shows its message rather than trying to infer one from the failure text. */}
30
<EmptyDescription>{error}</EmptyDescription>
31
</EmptyHeader>
32
- {onRetry || gitHubUrl ? (
32
+ {onRetry || host ? (
33
<div className="flex flex-wrap justify-center gap-2">
34
{onRetry ? (
35
<Button
@@ -43,14 +43,14 @@ export function PullRequestsUnavailableState({
43
Retry
44
</Button>
45
) : null}
46
- {gitHubUrl ? (
46
+ {host ? (
47
<Button
48
size="sm"
49
variant="outline"
50
- render={<a href={gitHubUrl} target="_blank" rel="noopener noreferrer" />}
50
+ render={<a href={host.url} target="_blank" rel="noopener noreferrer" />}
51
>
52
<ExternalLinkIcon aria-hidden className="size-3.5" />
53
- Open on GitHub
53
+ {host.openLabel}
54
</Button>
55
) : null}
56
</div>
apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx
+3
-2
@@ -8,7 +8,7 @@ import {
8
pullRequestListLines,
9
resolveThreadPullRequestChains,
10
visibleThreadPullRequests,
11
-} from "@t3tools/shared/threadPullRequests";
11
+} from "@t3tools/client-runtime/thread-pull-requests";
12
import {
13
ArrowUpRightIcon,
14
EyeIcon,
@@ -25,7 +25,8 @@ import {
25
encodePullRequestDragPayload,
26
} from "~/components/chat/composerMentionDrag";
27
import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
28
-import { findProjectForChangeRequest, useOpenPrLink } from "~/lib/openPullRequestLink";
28
+import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";
29
+import { useOpenPrLink } from "~/lib/openPullRequestLink";
30
import { cn } from "~/lib/utils";
31
import { useShortcutModifierState } from "~/shortcutModifierState";
32
import { useProjects, useServerConfigs, useThreadShell } from "~/state/entities";
apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+5
-11
@@ -34,7 +34,7 @@ import {
34
resolveThreadCurrentPullRequestLink,
35
threadPullRequestKeysEqual,
36
visibleThreadPullRequests,
37
-} from "@t3tools/shared/threadPullRequests";
37
+} from "@t3tools/client-runtime/thread-pull-requests";
38
39
import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";
40
import { reviewCommentContextId } from "~/lib/composerContextRecords";
@@ -1409,16 +1409,10 @@ export function resolveDisplayedPullRequestDetail(input: {
1409
return null;
1410
}
1411
if (input.reference.host === undefined) return input.cached;
1412
- try {
1413
- const url = new URL(input.cached.url);
1414
- const host = sourceControlClients.get(input.cached.provider).changeRequestUrlHost(url);
1415
- return (url.protocol === "https:" || url.protocol === "http:") &&
1416
- host.toLowerCase() === input.reference.host.toLowerCase()
1417
- ? input.cached
1418
- : null;
1419
- } catch {
1420
- return null;
1421
- }
1412
+ const link = sourceControlClients.parseChangeRequestUrl(input.cached.url)?.link;
1413
+ return link !== undefined && (link.authority ?? link.host) === input.reference.host.toLowerCase()
1414
+ ? input.cached
1415
+ : null;
1416
}
1417
1418
export function resolvePullRequestDetailChecks(
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+1
-1
@@ -3,7 +3,7 @@ import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators";
3
import { discardComposerDraft } from "../../lib/discardComposerDraft";
4
import { requestCustomSnooze } from "../CustomSnoozeDialog";
5
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
6
-import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
6
+import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";
7
import { useSortable } from "@dnd-kit/sortable";
8
import { CSS } from "@dnd-kit/utilities";
9
import {
apps/web/src/hooks/useOpenPanelPullRequestUrl.ts
+2
-6
@@ -5,7 +5,7 @@ import {
5
readPullRequestDetailSnapshot,
6
resolvePullRequestReferenceHost,
7
} from "../components/pullRequest/pullRequestDetail.logic";
8
-import { gitHubPullRequestBrowserUrl } from "../lib/openPullRequestLink";
8
+import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
9
import { selectActiveRightPanelSurface, useRightPanelStore } from "../rightPanelStore";
10
import { useProject } from "../state/entities";
11
import { pullRequestEnvironment } from "../state/pullRequests";
@@ -71,11 +71,7 @@ export function useOpenPanelPullRequestUrl(threadRef: ScopedThreadRef | null) {
71
: null;
72
const fallbackUrl = reference
73
? (requestedReference?.url ??
74
- gitHubPullRequestBrowserUrl(
75
- project?.repositoryIdentity,
76
- reference.repository,
77
- reference.number,
78
- ))
74
+ projectChangeRequestUrl(project?.repositoryIdentity, reference.repository, reference.number))
75
: undefined;
76
const detail = useEnvironmentQuery(
77
reference && environmentId
apps/web/src/hooks/usePullRequestLinking.test.ts
+4
-2
@@ -1,11 +1,13 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
import { canLinkChangeRequest } from "./usePullRequestLinking";
4
-import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
4
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5
6
describe("canLinkChangeRequest (#9435 / #9440)", () => {
7
const nonGitProject = { id: "scratch-project" } as never;
8
- const link = parseChangeRequestUrl("https://github.com/pingdotgg/t3code/pull/15111")!;
8
+ const link = sourceControlClients.parseChangeRequestUrl(
9
+ "https://github.com/pingdotgg/t3code/pull/15111",
10
+ )!.link;
11
12
it("links a pasted pull request URL when the server tracks links on the thread, even with no matching project", () => {
13
expect(canLinkChangeRequest("multiple", [nonGitProject], link)).toBe(true);
apps/web/src/hooks/usePullRequestLinking.ts
+15
-12
@@ -17,13 +17,12 @@ import {
17
import {
18
threadPullRequestKeysEqual,
19
visibleThreadPullRequests,
20
-} from "@t3tools/shared/threadPullRequests";
20
+} from "@t3tools/client-runtime/thread-pull-requests";
21
+import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";
22
import {
22
- findProjectForChangeRequest,
23
- matchesLinkedPullRequestUrl,
24
- parseChangeRequestUrl,
23
+ sourceControlClients,
24
type ChangeRequestLink,
26
-} from "~/lib/openPullRequestLink";
25
+} from "@t3tools/client-runtime/source-control-clients";
26
import { useAtomValue } from "@effect/atom-react";
27
import { Atom } from "effect/reactivity";
28
import { appAtomRegistry } from "~/rpc/atomRegistry";
@@ -62,8 +61,8 @@ export function usePullRequestLinking(environmentId: EnvironmentId | null | unde
61
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
62
const environmentProjects = projects.filter((project) => project.environmentId === environmentId);
63
const canLink = (url: string) => {
65
- const parsed = parseChangeRequestUrl(url);
66
- return parsed !== null && canLinkChangeRequest(mode, environmentProjects, parsed);
64
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
65
+ return parsed !== undefined && canLinkChangeRequest(mode, environmentProjects, parsed);
66
};
67
const isLinked = (
68
thread: {
@@ -76,19 +75,23 @@ export function usePullRequestLinking(environmentId: EnvironmentId | null | unde
75
if (mode !== "multiple")
76
return (
77
thread.linkedPullRequest != null &&
79
- matchesLinkedPullRequestUrl(thread.linkedPullRequest, url)
78
+ sourceControlClients.isSameChangeRequest(thread.linkedPullRequest.url, url)
79
);
81
- const parsed = parseChangeRequestUrl(url);
80
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
81
return (
83
- parsed !== null &&
82
+ parsed !== undefined &&
83
visibleThreadPullRequests(thread.pullRequests ?? []).some((entry) =>
84
threadPullRequestKeysEqual(entry, parsed),
85
)
86
);
87
};
88
const changeLink = async (threadRef: ScopedThreadRef, url: string, linked: boolean) => {
90
- const parsed = parseChangeRequestUrl(url);
91
- if (parsed === null || threadRef.environmentId !== environmentId || (linked && !canLink(url)))
89
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
90
+ if (
91
+ parsed === undefined ||
92
+ threadRef.environmentId !== environmentId ||
93
+ (linked && !canLink(url))
94
+ )
95
throw new Error("The pull request is not available in this environment.");
96
const legacyProject = findProjectForChangeRequest(environmentProjects, parsed);
97
const mutation = planThreadPullRequestMutation({
apps/web/src/lib/openPullRequestLink.test.ts
+1
-315
@@ -1,190 +1,6 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
-import {
4
- changeRequestRepositoryUrl,
5
- findProjectForChangeRequest,
6
- findProjectOnChangeRequestHost,
7
- gitHubPullRequestBrowserUrl,
8
- matchesLinkedPullRequestUrl,
9
- parseChangeRequestUrl,
10
- pullRequestCandidateUrlFromReferenceAutolink,
11
-} from "./openPullRequestLink";
12
-import { ProjectId, type RepositoryIdentity } from "@t3tools/contracts";
13
-
14
-function repositoryIdentity(
15
- provider: string,
16
- canonicalKey: string,
17
- remoteUrl: string,
18
-): RepositoryIdentity {
19
- return {
20
- canonicalKey,
21
- provider,
22
- locator: { source: "git-remote", remoteName: "origin", remoteUrl },
23
- };
24
-}
25
-
26
-describe("gitHubPullRequestBrowserUrl", () => {
27
- it("uses the requested GitHub repository instead of the project's default repository", () => {
28
- const identity = repositoryIdentity(
29
- "github",
30
- "github.com/acme/default",
31
- "https://github.com/acme/default.git",
32
- );
33
-
34
- expect(gitHubPullRequestBrowserUrl(identity, "acme/other", 42)).toBe(
35
- "https://github.com/acme/other/pull/42",
36
- );
37
- });
38
-
39
- it("preserves a custom GitHub HTTP origin without its credentials", () => {
40
- const identity = repositoryIdentity(
41
- "github",
42
- "github.acme.test/team/default",
43
- "http://token@github.acme.test:8443/team/default.git",
44
- );
45
-
46
- expect(gitHubPullRequestBrowserUrl(identity, "platform/api", 7)).toBe(
47
- "http://github.acme.test:8443/platform/api/pull/7",
48
- );
49
- });
50
-
51
- it.each([
52
- {
53
- name: "SSH",
54
- remoteUrl: "git@github.acme.test:team/default.git",
55
- },
56
- {
57
- name: "git protocol",
58
- remoteUrl: "git://github.acme.test/team/default.git",
59
- },
60
- ])("uses the normalized host for a $name remote", ({ remoteUrl }) => {
61
- const identity = repositoryIdentity("github", "github.acme.test/team/default", remoteUrl);
62
-
63
- expect(gitHubPullRequestBrowserUrl(identity, "platform/api", 9)).toBe(
64
- "https://github.acme.test/platform/api/pull/9",
65
- );
66
- });
67
-
68
- // regression: #8507 the browser fallback must not open a bogus URL
69
- it("returns null for missing or invalid GitHub data", () => {
70
- expect(gitHubPullRequestBrowserUrl(null, "acme/repository", 1)).toBeNull();
71
- expect(
72
- gitHubPullRequestBrowserUrl(
73
- repositoryIdentity("github", "github.com/acme/repository", "https://github.com/a/b"),
74
- "acme",
75
- 1,
76
- ),
77
- ).toBeNull();
78
- expect(
79
- gitHubPullRequestBrowserUrl(
80
- repositoryIdentity("github", "github.com/acme/repository", "https://github.com/a/b"),
81
- "../repository",
82
- 1,
83
- ),
84
- ).toBeNull();
85
- expect(
86
- gitHubPullRequestBrowserUrl(
87
- repositoryIdentity("github", "github.com/acme/repository", "https://github.com/a/b"),
88
- "acme/repository",
89
- 0,
90
- ),
91
- ).toBeNull();
92
- expect(
93
- gitHubPullRequestBrowserUrl(
94
- repositoryIdentity("github", "bad host/acme/repository", "not a remote"),
95
- "acme/repository",
96
- 1,
97
- ),
98
- ).toBeNull();
99
- });
100
-
101
- // regression: #8507 the browser fallback for failed PR loads must only target GitHub
102
- it.each(["gitlab", "bitbucket", "azure-devops", "unknown"])(
103
- "does not build a fallback for %s",
104
- (provider) => {
105
- expect(
106
- gitHubPullRequestBrowserUrl(
107
- repositoryIdentity(provider, "github.com/acme/repository", "https://github.com/a/b"),
108
- "acme/repository",
109
- 1,
110
- ),
111
- ).toBeNull();
112
- },
113
- );
114
-});
115
-
116
-describe("changeRequestRepositoryUrl", () => {
117
- it("keeps pull-like segments inside nested GitLab repository paths", () => {
118
- expect(
119
- changeRequestRepositoryUrl(
120
- "https://gitlab.example.test/group/pull/123/repo/-/merge_requests/42",
121
- ),
122
- ).toBe("https://gitlab.example.test/group/pull/123/repo");
123
- });
124
-});
125
-
126
-describe("pullRequestCandidateUrlFromReferenceAutolink", () => {
127
- it("turns GitHub's shared issue route into a pull request candidate", () => {
128
- expect(
129
- pullRequestCandidateUrlFromReferenceAutolink(
130
- "https://github.com/pingdotgg/t3code/issues/8600#issuecomment-1",
131
- ),
132
- ).toBe("https://github.com/pingdotgg/t3code/pull/8600#issuecomment-1");
133
- });
134
-
135
- it("does not reinterpret other issue hosts or malformed references", () => {
136
- expect(
137
- pullRequestCandidateUrlFromReferenceAutolink(
138
- "https://gitlab.com/pingdotgg/t3code/-/issues/8600",
139
- ),
140
- ).toBeNull();
141
- expect(
142
- pullRequestCandidateUrlFromReferenceAutolink(
143
- "https://github.com/pingdotgg/t3code/issues/not-a-number",
144
- ),
145
- ).toBeNull();
146
- });
147
-});
148
-
149
-describe("matchesLinkedPullRequestUrl", () => {
150
- const linkedPullRequest = {
151
- projectId: ProjectId.make("project-1"),
152
- repository: "pingdotgg/t3code",
153
- number: 42,
154
- url: "https://github.com/pingdotgg/t3code/pull/42",
155
- };
156
-
157
- it("matches the same pull request without looking up its project", () => {
158
- expect(
159
- matchesLinkedPullRequestUrl(
160
- linkedPullRequest,
161
- "https://github.com/PingDotGG/T3Code/pull/42/files",
162
- ),
163
- ).toBe(true);
164
- });
165
-
166
- it.each([
167
- ["http://forge.example:3000/git/team/repo/pulls/42/files", true],
168
- ["http://forge.example:4000/git/team/repo/pulls/42", false],
169
- ["http://forge.example/git/team/repo/pulls/42", false],
170
- ])("matches Forgejo links by web authority: %s", (url, expected) => {
171
- expect(
172
- matchesLinkedPullRequestUrl(
173
- { ...linkedPullRequest, url: "http://forge.example:3000/git/team/repo/pulls/42" },
174
- url,
175
- ),
176
- ).toBe(expected);
177
- });
178
-
179
- it("keeps Forgejo and GitHub path shapes distinct on a GitHub-named host", () => {
180
- expect(
181
- matchesLinkedPullRequestUrl(
182
- { ...linkedPullRequest, url: "https://github.internal/team/repo/pulls/42" },
183
- "https://github.internal/team/repo/pull/42",
184
- ),
185
- ).toBe(false);
186
- });
187
-});
3
+import { findProjectOnChangeRequestHost } from "./openPullRequestLink";
4
5
describe("findProjectOnChangeRequestHost", () => {
6
const project = (id: string, identity: Record<string, unknown>) =>
@@ -202,41 +18,6 @@ describe("findProjectOnChangeRequestHost", () => {
18
name: "backend",
19
});
20
205
- it.each([
206
- ["ssh.dev.azure.com/v3/org-a/project/web", "git@ssh.dev.azure.com:v3/org-a/project/web"],
207
- [
208
- "vs-ssh.visualstudio.com/v3/org-a/project/web",
209
- "git@vs-ssh.visualstudio.com:v3/org-a/project/web",
210
- ],
211
- [
212
- "org-a.visualstudio.com/defaultcollection/project/_git/web",
213
- "https://org-a.visualstudio.com/DefaultCollection/Project/_git/Web",
214
- ],
215
- ["dev.azure.com/org-a/project/_git/web", "https://org-a@dev.azure.com/org-a/Project/_git/Web"],
216
- ])("matches Azure browser references against %s", (canonicalKey, remoteUrl) => {
217
- const checkout = project("azure", {
218
- ...repositoryIdentity("azure-devops", canonicalKey, remoteUrl),
219
- displayName: canonicalKey.split("/").slice(1).join("/"),
220
- });
221
- const reference = parseChangeRequestUrl(
222
- "https://dev.azure.com/org-a/project/_git/web/pullrequest/42",
223
- )!;
224
- expect(findProjectForChangeRequest([checkout], reference)).toBe(checkout);
225
- expect(findProjectOnChangeRequestHost([checkout], reference)).toBe(checkout);
226
- expect(
227
- findProjectOnChangeRequestHost([checkout], {
228
- ...reference,
229
- repository: "org-b/project/_git/web",
230
- }),
231
- ).toBeUndefined();
232
- expect(
233
- findProjectOnChangeRequestHost([checkout], {
234
- ...reference,
235
- repository: "org-a/other-project/_git/web",
236
- }),
237
- ).toBeUndefined();
238
- });
239
-
21
it("prefers the project checked out from the link's own repository", () => {
22
expect(
23
findProjectOnChangeRequestHost([frontend, backend], {
@@ -247,59 +28,6 @@ describe("findProjectOnChangeRequestHost", () => {
28
).toBe(backend);
29
});
30
250
- it("selects the Forgejo HTTP port for repository and host-level matches", () => {
251
- const projects = [3000, 4000].map((port) =>
252
- project(`forgejo-${port}`, {
253
- canonicalKey: "forge.example/git/team/repo",
254
- provider: "forgejo",
255
- displayName: "git/team/repo",
256
- locator: { remoteUrl: `http://forge.example:${port}/git/team/repo.git` },
257
- }),
258
- );
259
- const reference = parseChangeRequestUrl("http://forge.example:4000/git/team/repo/pulls/42")!;
260
- expect(findProjectForChangeRequest(projects, reference)).toBe(projects[1]);
261
- expect(findProjectOnChangeRequestHost(projects, reference)).toBe(projects[1]);
262
- expect(
263
- findProjectOnChangeRequestHost(projects, { ...reference, repository: "git/team/other" }),
264
- ).toBe(projects[1]);
265
- expect(findProjectForChangeRequest([projects[0]!], reference)).toBeUndefined();
266
- expect(findProjectOnChangeRequestHost([projects[0]!], reference)).toBeUndefined();
267
- });
268
-
269
- it("lets tea resolve the web port for Forgejo SSH remotes", () => {
270
- const checkout = project("forgejo-ssh", {
271
- canonicalKey: "forge.example/git/team/repo",
272
- provider: "forgejo",
273
- displayName: "git/team/repo",
274
- locator: { remoteUrl: "git@forge.example:git/team/repo.git" },
275
- });
276
- const reference = parseChangeRequestUrl("http://forge.example:4000/git/team/repo/pulls/42")!;
277
- expect(findProjectForChangeRequest([checkout], reference)).toBe(checkout);
278
- const aliased = project("forgejo-alias", {
279
- canonicalKey: "ssh.forge.example/team/repo",
280
- provider: "forgejo",
281
- displayName: "team/repo",
282
- locator: { remoteUrl: "git@ssh.forge.example:team/repo.git" },
283
- webUrl: "http://forge.example:4000/git/team/repo",
284
- });
285
- expect(findProjectForChangeRequest([aliased], reference)).toBe(aliased);
286
- expect(findProjectOnChangeRequestHost([aliased], reference)).toBe(aliased);
287
- expect(
288
- findProjectOnChangeRequestHost([aliased], { ...reference, repository: "git/team/other" }),
289
- ).toBe(aliased);
290
- for (const url of [
291
- "http://other.example:4000/git/team/repo/pulls/42",
292
- "http://forge.example:3000/git/team/repo/pulls/42",
293
- ]) {
294
- const other = parseChangeRequestUrl(url)!;
295
- expect(findProjectForChangeRequest([aliased], other)).toBeUndefined();
296
- expect(findProjectOnChangeRequestHost([aliased], other)).toBeUndefined();
297
- }
298
- const otherMount = parseChangeRequestUrl("http://forge.example:4000/other/team/repo/pulls/42")!;
299
- expect(findProjectForChangeRequest([aliased], otherMount)).toBeUndefined();
300
- expect(findProjectOnChangeRequestHost([aliased], otherMount)).toBeUndefined();
301
- });
302
-
31
it("lends any project on the host to a repository nobody has checked out", () => {
32
expect(
33
findProjectOnChangeRequestHost([frontend], {
@@ -310,45 +38,3 @@ describe("findProjectOnChangeRequestHost", () => {
38
).toBe(frontend);
39
});
40
});
313
-
314
-describe("findProjectForChangeRequest", () => {
315
- const project = (identity: Record<string, unknown>) =>
316
- ({ id: "p1", repositoryIdentity: identity }) as never;
317
-
318
- it("matches a nested GitLab group by the whole path below the host", () => {
319
- const projects = [
320
- project({
321
- canonicalKey: "gitlab.com/t3tools/platform/t3code",
322
- provider: "gitlab",
323
- displayName: "t3tools/platform/t3code",
324
- owner: "t3tools",
325
- name: "t3code",
326
- }),
327
- ];
328
- expect(
329
- findProjectForChangeRequest(projects, {
330
- host: "gitlab.com",
331
- repository: "t3tools/platform/t3code",
332
- number: 42,
333
- }),
334
- ).toBe(projects[0]);
335
- });
336
-
337
- it("claims nothing for a lookalike host, which is what keeps a link a link", () => {
338
- const projects = [
339
- project({
340
- canonicalKey: "github.com/pingdotgg/t3code",
341
- provider: "github",
342
- owner: "pingdotgg",
343
- name: "t3code",
344
- }),
345
- ];
346
- expect(
347
- findProjectForChangeRequest(projects, {
348
- host: "github.com-evil.test",
349
- repository: "pingdotgg/t3code",
350
- number: 1,
351
- }),
352
- ).toBeUndefined();
353
- });
354
-});
apps/web/src/lib/openPullRequestLink.ts
+12
-58
@@ -1,10 +1,16 @@
1
-import type { EnvironmentId, PullRequestRef, ScopedThreadRef } from "@t3tools/contracts";
1
+import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
2
import { useAtomValue } from "@effect/atom-react";
3
import { useNavigate } from "@tanstack/react-router";
4
import { type MouseEvent } from "react";
5
6
-import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7
-import { parseChangeRequestUrl, type ChangeRequestLink } from "@t3tools/shared/changeRequestUrl";
6
+import {
7
+ findProjectForChangeRequest,
8
+ resolvePullRequestPreviewTarget,
9
+} from "@t3tools/client-runtime/change-request-links";
10
+import {
11
+ sourceControlClients,
12
+ type ChangeRequestLink,
13
+} from "@t3tools/client-runtime/source-control-clients";
14
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
15
16
import { useOpenLink } from "../browser/useOpenLink";
@@ -18,58 +24,6 @@ import { readProjects, useProjects } from "../state/entities";
24
import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
25
import { usePrimaryEnvironmentId } from "../state/environments";
26
21
-export {
22
- parseChangeRequestUrl,
23
- type ChangeRequestLink,
24
- gitHubPullRequestBrowserUrl,
25
- pullRequestCandidateUrlFromReferenceAutolink,
26
- matchesLinkedPullRequestUrl,
27
- changeRequestRepositoryUrl,
28
-} from "@t3tools/shared/changeRequestUrl";
29
-
30
-export function findProjectForChangeRequest(
31
- projects: ReadonlyArray<EnvironmentProject>,
32
- link: ChangeRequestLink,
33
-): EnvironmentProject | undefined {
34
- return projects.find((project) => {
35
- const identity = project.repositoryIdentity;
36
- return (
37
- identity?.provider !== undefined &&
38
- sourceControlClients.get(identity.provider).isChangeRequestInRepository(identity, link)
39
- );
40
- });
41
-}
42
-
43
-export function resolvePullRequestPreviewTarget({
44
- environmentId,
45
- projects,
46
- pullRequestsEnabled,
47
- url,
48
-}: {
49
- environmentId: EnvironmentId | null;
50
- projects: ReadonlyArray<EnvironmentProject>;
51
- pullRequestsEnabled: boolean;
52
- url: string;
53
-}): { environmentId: EnvironmentId; input: PullRequestRef } | null {
54
- if (!pullRequestsEnabled || environmentId === null) return null;
55
- const parsed = parseChangeRequestUrl(url);
56
- if (parsed === null) return null;
57
- const project = findProjectForChangeRequest(
58
- projects.filter((candidate) => candidate.environmentId === environmentId),
59
- parsed,
60
- );
61
- if (project === undefined) return null;
62
- return {
63
- environmentId,
64
- input: {
65
- projectId: project.id,
66
- host: parsed.authority ?? parsed.host,
67
- repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository,
68
- number: parsed.number,
69
- },
70
- };
71
-}
72
-
27
export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) {
28
const projects = useProjects();
29
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
@@ -96,7 +50,7 @@ export function findProjectOnChangeRequestHost(
50
});
51
}
52
99
-export function shouldOpenPullRequestExternally(
53
+function shouldOpenPullRequestExternally(
54
event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey"> &
55
Partial<Pick<MouseEvent<HTMLElement>, "button">>,
56
): boolean {
@@ -127,8 +81,8 @@ export function useOpenChangeRequestLink(
81
const allProjects = readProjects();
82
const resolvedThreadRef = targetThreadRef ?? threadRef;
83
const resolvedPanelRef = panelRef ?? resolvedThreadRef;
130
- const parsed = parseChangeRequestUrl(targetUrl);
131
- if (parsed === null) return false;
84
+ const parsed = sourceControlClients.parseChangeRequestUrl(targetUrl)?.link;
85
+ if (parsed === undefined) return false;
86
const reads = (environmentId: string) =>
87
serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
88
true;
apps/web/src/state/pullRequests.ts
+1
-1
@@ -19,7 +19,7 @@ import type {
19
import {
20
threadPullRequestKeyOf,
21
visibleThreadPullRequests,
22
-} from "@t3tools/shared/threadPullRequests";
22
+} from "@t3tools/client-runtime/thread-pull-requests";
23
import * as Option from "effect/Option";
24
import { AsyncResult, Atom } from "effect/reactivity";
25
import { useLayoutEffect } from "react";
packages/client-runtime/package.json
+12
@@ -367,6 +367,18 @@
367
"types": "./src/pullRequestLinkInput.ts",
368
"default": "./src/pullRequestLinkInput.ts"
369
},
370
+ "./change-request-links": {
371
+ "types": "./src/changeRequestLinks.ts",
372
+ "default": "./src/changeRequestLinks.ts"
373
+ },
374
+ "./thread-pull-requests": {
375
+ "types": "./src/threadPullRequests.ts",
376
+ "default": "./src/threadPullRequests.ts"
377
+ },
378
+ "./thread-reference": {
379
+ "types": "./src/threadReference.ts",
380
+ "default": "./src/threadReference.ts"
381
+ },
382
"./thread-pull-request-compatibility": {
383
"types": "./src/threadPullRequestCompatibility.ts",
384
"default": "./src/threadPullRequestCompatibility.ts"
packages/client-runtime/src/changeRequestLinks.test.ts
new
+104
@@ -0,0 +1,104 @@
1
+import { EnvironmentId, ProjectId, type RepositoryIdentity } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import {
5
+ findProjectForChangeRequest,
6
+ projectChangeRequestUrl,
7
+ resolvePullRequestPreviewTarget,
8
+} from "./changeRequestLinks.ts";
9
+
10
+describe("findProjectForChangeRequest", () => {
11
+ const project = (identity: Record<string, unknown>) =>
12
+ ({ id: "p1", repositoryIdentity: identity }) as never;
13
+
14
+ it("matches a nested GitLab group by the whole path below the host", () => {
15
+ const projects = [
16
+ project({
17
+ canonicalKey: "gitlab.com/t3tools/platform/t3code",
18
+ provider: "gitlab",
19
+ displayName: "t3tools/platform/t3code",
20
+ owner: "t3tools",
21
+ name: "t3code",
22
+ }),
23
+ ];
24
+ expect(
25
+ findProjectForChangeRequest(projects, {
26
+ host: "gitlab.com",
27
+ repository: "t3tools/platform/t3code",
28
+ number: 42,
29
+ }),
30
+ ).toBe(projects[0]);
31
+ });
32
+
33
+ it("claims nothing for a lookalike host, which is what keeps a link a link", () => {
34
+ const projects = [
35
+ project({
36
+ canonicalKey: "github.com/pingdotgg/t3code",
37
+ provider: "github",
38
+ owner: "pingdotgg",
39
+ name: "t3code",
40
+ }),
41
+ ];
42
+ expect(
43
+ findProjectForChangeRequest(projects, {
44
+ host: "github.com-evil.test",
45
+ repository: "pingdotgg/t3code",
46
+ number: 1,
47
+ }),
48
+ ).toBeUndefined();
49
+ });
50
+});
51
+
52
+describe("resolvePullRequestPreviewTarget", () => {
53
+ const environmentId = EnvironmentId.make("env-1");
54
+ const project = {
55
+ id: ProjectId.make("project-1"),
56
+ environmentId,
57
+ repositoryIdentity: {
58
+ canonicalKey: "github.com/acme/web",
59
+ provider: "github",
60
+ displayName: "acme/web",
61
+ locator: { source: "git-remote", remoteName: "origin", remoteUrl: "git@github.com:acme/web" },
62
+ } satisfies RepositoryIdentity,
63
+ };
64
+
65
+ it("previews a pull request only under the project that holds its repository", () => {
66
+ const target = (url: string) =>
67
+ resolvePullRequestPreviewTarget({
68
+ environmentId,
69
+ projects: [project],
70
+ pullRequestsEnabled: true,
71
+ url,
72
+ });
73
+ expect(target("https://github.com/acme/web/pull/7")).toEqual({
74
+ environmentId,
75
+ input: { projectId: project.id, host: "github.com", repository: "acme/web", number: 7 },
76
+ });
77
+ expect(target("https://github.com/acme/other/pull/7")).toBeNull();
78
+ });
79
+});
80
+
81
+describe("projectChangeRequestUrl", () => {
82
+ const identity = (provider: string): RepositoryIdentity => ({
83
+ canonicalKey: "github.com/acme/default",
84
+ provider,
85
+ locator: {
86
+ source: "git-remote",
87
+ remoteName: "origin",
88
+ remoteUrl: "git@github.com:acme/default",
89
+ },
90
+ });
91
+
92
+ it("builds the requested repository's URL on the project's host", () => {
93
+ expect(projectChangeRequestUrl(identity("github"), "acme/other", 42)).toBe(
94
+ "https://github.com/acme/other/pull/42",
95
+ );
96
+ });
97
+
98
+ it("builds nothing without a project host that knows its URL shape", () => {
99
+ expect(projectChangeRequestUrl(null, "acme/repository", 1)).toBeNull();
100
+ expect(projectChangeRequestUrl(identity("unknown"), "acme/repository", 1)).toBeNull();
101
+ const { provider: _provider, ...withoutProvider } = identity("github");
102
+ expect(projectChangeRequestUrl(withoutProvider, "acme/repository", 1)).toBeNull();
103
+ });
104
+});
packages/client-runtime/src/changeRequestLinks.ts
new
+77
@@ -0,0 +1,77 @@
1
+import type {
2
+ EnvironmentId,
3
+ ProjectId,
4
+ PullRequestRef,
5
+ RepositoryIdentity,
6
+} from "@t3tools/contracts";
7
+import type { ChangeRequestLink } from "@t3tools/source-control-core/client/definition";
8
+import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
9
+
10
+import { sourceControlClients } from "./sourceControlClients.ts";
11
+
12
+interface ChangeRequestProject {
13
+ readonly id: ProjectId;
14
+ readonly environmentId: EnvironmentId;
15
+ readonly repositoryIdentity?: RepositoryIdentity | null | undefined;
16
+}
17
+
18
+/** The project whose own repository holds the change request, not just one on its host. */
19
+export function findProjectForChangeRequest<Project extends ChangeRequestProject>(
20
+ projects: ReadonlyArray<Project>,
21
+ link: ChangeRequestLink,
22
+): Project | undefined {
23
+ return projects.find((project) => {
24
+ const identity = project.repositoryIdentity;
25
+ return (
26
+ identity?.provider !== undefined &&
27
+ sourceControlClients.get(identity.provider).isChangeRequestInRepository(identity, link)
28
+ );
29
+ });
30
+}
31
+
32
+export function resolvePullRequestPreviewTarget({
33
+ environmentId,
34
+ projects,
35
+ pullRequestsEnabled,
36
+ url,
37
+}: {
38
+ environmentId: EnvironmentId | null;
39
+ projects: ReadonlyArray<ChangeRequestProject>;
40
+ pullRequestsEnabled: boolean;
41
+ url: string;
42
+}): { environmentId: EnvironmentId; input: PullRequestRef } | null {
43
+ if (!pullRequestsEnabled || environmentId === null) return null;
44
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;
45
+ if (parsed === undefined) return null;
46
+ const project = findProjectForChangeRequest(
47
+ projects.filter((candidate) => candidate.environmentId === environmentId),
48
+ parsed,
49
+ );
50
+ if (project === undefined) return null;
51
+ return {
52
+ environmentId,
53
+ input: {
54
+ projectId: project.id,
55
+ host: parsed.authority ?? parsed.host,
56
+ repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository,
57
+ number: parsed.number,
58
+ },
59
+ };
60
+}
61
+
62
+/** The project host's browser URL for one of its change requests, before its detail loads. */
63
+export function projectChangeRequestUrl(
64
+ identity: RepositoryIdentity | null | undefined,
65
+ repository: string,
66
+ number: number,
67
+): string | null {
68
+ if (identity?.provider === undefined) return null;
69
+ const host = identity.canonicalKey.split("/")[0];
70
+ if (!host) return null;
71
+ return sourceControlClients.get(identity.provider).changeRequestUrl({
72
+ host,
73
+ repository,
74
+ number,
75
+ remoteUrl: identity.locator.remoteUrl.trim(),
76
+ });
77
+}
packages/client-runtime/src/promptLinks.ts
+1
-1
@@ -12,7 +12,7 @@ import {
12
threadPullRequestKeyOf,
13
threadPullRequestsOf,
14
visibleThreadPullRequests,
15
-} from "@t3tools/shared/threadPullRequests";
15
+} from "./threadPullRequests.ts";
16
17
const repositoryKey = (repository: PromptLinkRepository) =>
18
`github.com/${repository.owner}/${repository.name}`.toLowerCase();
packages/client-runtime/src/pullRequestLinkInput.ts
+12
-7
@@ -1,5 +1,4 @@
1
import { pullRequestHostOf, type RepositoryIdentity } from "@t3tools/contracts";
2
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
2
3
import { sourceControlClients } from "./sourceControlClients.ts";
4
@@ -75,12 +74,12 @@ export function resolveLinkPullRequestInput(input: {
74
readonly hasProject: (reference: ResolvedLink) => boolean;
75
}): { link: ResolvedLink } | { error: string } | null {
76
const parsed =
78
- parseChangeRequestUrl(input.reference.trim()) !== null
77
+ sourceControlClients.parseChangeRequestUrl(input.reference.trim()) !== null
78
? input.reference.trim()
79
: parsePullRequestReference(input.reference);
80
if (parsed === null) return null;
82
- const url = parseChangeRequestUrl(parsed);
83
- if (url !== null) {
81
+ const url = sourceControlClients.parseChangeRequestUrl(parsed)?.link;
82
+ if (url !== undefined) {
83
if (!input.hasProject({ ...url, url: parsed })) {
84
return { error: `No project in this environment can read ${url.host}/${url.repository}.` };
85
}
@@ -97,11 +96,17 @@ export function resolveLinkPullRequestInput(input: {
96
};
97
}
98
const webUrl = input.project.webUrl(number);
100
- const webReference = webUrl === null ? null : parseChangeRequestUrl(webUrl);
101
- if (webUrl === null || webReference === null) {
99
+ const webReference =
100
+ webUrl === null ? undefined : sourceControlClients.parseChangeRequestUrl(webUrl)?.link;
101
+ if (webUrl === null || webReference === undefined) {
102
return { error: "Paste a full URL; this project's host has no known pull request URL." };
103
}
104
return {
105
- link: { ...webReference, url: webUrl },
105
+ link: {
106
+ host: webReference.host,
107
+ repository: webReference.repository,
108
+ number: webReference.number,
109
+ url: webUrl,
110
+ },
111
};
112
}
packages/client-runtime/src/sourceControlClients.test.ts
new
+240
@@ -0,0 +1,240 @@
1
+import { ProjectId } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { sourceControlClients } from "./sourceControlClients.ts";
5
+import { normalizeThreadPullRequestKey } from "./threadPullRequests.ts";
6
+
7
+const parse = (url: string) => {
8
+ const parsed = sourceControlClients.parseChangeRequestUrl(url);
9
+ if (parsed === null) return null;
10
+ const { repositoryUrl: _repositoryUrl, ...link } = parsed.link;
11
+ return link;
12
+};
13
+const kindOf = (url: string) => sourceControlClients.parseChangeRequestUrl(url)?.definition.kind;
14
+
15
+describe("sourceControlClients.parseChangeRequestUrl", () => {
16
+ it("reads a GitHub pull request, lower-casing the repository", () => {
17
+ expect(parse("https://github.com/T3Tools/T3Code/pull/123")).toEqual({
18
+ host: "github.com",
19
+ repository: "t3tools/t3code",
20
+ number: 123,
21
+ });
22
+ });
23
+
24
+ it("reads a GitCafe pull request at its canonical /pull/ path and the older /pulls/ path", () => {
25
+ for (const path of ["pull", "pulls"]) {
26
+ const url = `https://git.cafe/PingDotGG/T3Code/${path}/23897`;
27
+ expect(parse(url), path).toEqual({
28
+ host: "git.cafe",
29
+ repository: "pingdotgg/t3code",
30
+ number: 23897,
31
+ });
32
+ expect(kindOf(url), path).toBe("gitcafe");
33
+ }
34
+ expect(parse("https://staging.git.cafe/team/repo/pull/7/files")).toEqual({
35
+ host: "staging.git.cafe",
36
+ repository: "team/repo",
37
+ number: 7,
38
+ });
39
+ });
40
+
41
+ it("reads Forgejo URLs even when the hostname contains github", () => {
42
+ expect(parse("https://github.internal/team/repo/pulls/7")).toEqual({
43
+ host: "github.internal",
44
+ authority: "github.internal",
45
+ repository: "team/repo",
46
+ number: 7,
47
+ });
48
+ });
49
+
50
+ it("reads a GitHub pull request on any host, so GitHub Enterprise works on its own name", () => {
51
+ expect(parse("https://code.github.example.com/acme/web/pull/42")).toEqual({
52
+ host: "code.github.example.com",
53
+ repository: "acme/web",
54
+ number: 42,
55
+ });
56
+ expect(kindOf("https://scm.example.test/acme/web/pull/42")).toBe("github");
57
+ expect(
58
+ sourceControlClients.changeRequestUrlFromReferenceAutolink(
59
+ "https://code.github.example.com/acme/web/issues/42",
60
+ ),
61
+ ).toBe("https://code.github.example.com/acme/web/pull/42");
62
+ });
63
+
64
+ it("reads a GitLab merge request on any host, nested groups and all", () => {
65
+ expect(parse("https://gitlab.com/t3tools/platform/t3code/-/merge_requests/42")).toEqual({
66
+ host: "gitlab.com",
67
+ repository: "t3tools/platform/t3code",
68
+ number: 42,
69
+ });
70
+ expect(parse("https://code.acme.test/team/project/-/merge_requests/9")).toEqual({
71
+ host: "code.acme.test",
72
+ repository: "team/project",
73
+ number: 9,
74
+ });
75
+ });
76
+
77
+ it("reads Bitbucket and both Azure DevOps URL forms", () => {
78
+ expect(parse("https://bitbucket.org/workspace/repo/pull-requests/5")).toEqual({
79
+ host: "bitbucket.org",
80
+ repository: "workspace/repo",
81
+ number: 5,
82
+ });
83
+ expect(parse("https://dev.azure.com/acme/platform/_git/t3code/pullrequest/17")).toEqual({
84
+ host: "dev.azure.com",
85
+ repository: "acme/platform/_git/t3code",
86
+ number: 17,
87
+ });
88
+ expect(parse("https://acme.visualstudio.com/platform/_git/t3code/pullrequest/17")).toEqual({
89
+ host: "acme.visualstudio.com",
90
+ repository: "platform/_git/t3code",
91
+ number: 17,
92
+ });
93
+ });
94
+
95
+ it("reads Azure DevOps Server links and keeps servers on different ports distinct", () => {
96
+ for (const host of ["scm.example.test", "git.cafe", "code.bitbucket.example.test"]) {
97
+ const repository = "tfs/collection/project/_git/repo";
98
+ const linked = {
99
+ projectId: ProjectId.make("project-1"),
100
+ host,
101
+ repository,
102
+ number: 123,
103
+ url: `https://${host.toUpperCase()}:8443/tfs/Collection/Project/_git/Repo/pullrequest/123`,
104
+ };
105
+ const other = { ...linked, url: linked.url.replace(":8443/", ":9443/") };
106
+ expect.soft(parse(linked.url), host).toEqual({
107
+ host,
108
+ authority: `${host}:8443`,
109
+ repository,
110
+ number: 123,
111
+ });
112
+ expect
113
+ .soft(
114
+ sourceControlClients.isSameChangeRequest(linked.url, `${linked.url}?view=files`),
115
+ host,
116
+ )
117
+ .toBe(true);
118
+ expect
119
+ .soft(sourceControlClients.isSameChangeRequest(linked.url, other.url), host)
120
+ .toBe(false);
121
+ expect.soft([linked, other].map(normalizeThreadPullRequestKey), host).toEqual([
122
+ { host: `${host}:8443`, repository, number: 123 },
123
+ { host: `${host}:9443`, repository, number: 123 },
124
+ ]);
125
+ }
126
+ });
127
+
128
+ it("survives trailing segments, a trailing slash and a query string", () => {
129
+ expect(parse("https://github.com/t3tools/t3code/pull/123/files?w=1")).toEqual({
130
+ host: "github.com",
131
+ repository: "t3tools/t3code",
132
+ number: 123,
133
+ });
134
+ expect(parse("https://github.com/t3tools/t3code/pull/123/")).toEqual({
135
+ host: "github.com",
136
+ repository: "t3tools/t3code",
137
+ number: 123,
138
+ });
139
+ });
140
+
141
+ it("claims nothing it cannot be sure of", () => {
142
+ for (const link of [
143
+ "https://github.com/t3tools/t3code/issues/123",
144
+ "https://git.cafe/pingdotgg/t3code/issues/23897",
145
+ "https://git.cafe/pingdotgg/t3code/pull/abc",
146
+ "https://git.cafe/pingdotgg/t3code",
147
+ "https://github.com/t3tools/t3code/commit/0a1b2c3",
148
+ "https://github.com/t3tools/t3code",
149
+ "https://github.com/t3tools/t3code/pull/abc",
150
+ "https://gitlab.com/t3tools/t3code/-/issues/12",
151
+ "https://blog.example.test/2026/updates/archive/pull/3",
152
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo",
153
+ "https://scm.example.test/tfs/Collection/Project/pullrequest/123",
154
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/abc",
155
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/0",
156
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/9007199254740992",
157
+ "ftp://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123",
158
+ "javascript:alert(1)//github.com/t3tools/t3code/pull/1",
159
+ "not a url",
160
+ ]) {
161
+ expect(parse(link), link).toBeNull();
162
+ }
163
+ });
164
+});
165
+
166
+describe("sourceControlClients.isSameChangeRequest", () => {
167
+ const linked = "https://github.com/pingdotgg/t3code/pull/42";
168
+
169
+ it("matches the same pull request whatever its case or trailing path", () => {
170
+ expect(
171
+ sourceControlClients.isSameChangeRequest(
172
+ linked,
173
+ "https://github.com/PingDotGG/T3Code/pull/42/files",
174
+ ),
175
+ ).toBe(true);
176
+ });
177
+
178
+ it.each([
179
+ ["http://forge.example:3000/git/team/repo/pulls/42/files", true],
180
+ ["http://forge.example:4000/git/team/repo/pulls/42", false],
181
+ ["http://forge.example/git/team/repo/pulls/42", false],
182
+ ])("matches Forgejo links by web authority: %s", (url, expected) => {
183
+ expect(
184
+ sourceControlClients.isSameChangeRequest(
185
+ "http://forge.example:3000/git/team/repo/pulls/42",
186
+ url,
187
+ ),
188
+ ).toBe(expected);
189
+ });
190
+
191
+ it("keeps Forgejo and GitHub path shapes distinct on a GitHub-named host", () => {
192
+ expect(
193
+ sourceControlClients.isSameChangeRequest(
194
+ "https://github.internal/team/repo/pulls/42",
195
+ "https://github.internal/team/repo/pull/42",
196
+ ),
197
+ ).toBe(false);
198
+ });
199
+});
200
+
201
+describe("change request URLs built from a parsed link", () => {
202
+ const sibling = (url: string, number: number) => {
203
+ const parsed = sourceControlClients.parseChangeRequestUrl(url)!;
204
+ return parsed.definition.changeRequestUrl({
205
+ host: parsed.link.host,
206
+ repository: parsed.link.repository,
207
+ number,
208
+ webUrl: parsed.link.repositoryUrl,
209
+ });
210
+ };
211
+
212
+ it.each([
213
+ [
214
+ "http://git.example.test:3000/team/repo/pulls/42/files",
215
+ "http://git.example.test:3000/team/repo/pulls/43",
216
+ ],
217
+ ["https://github.com/pull/1/pull/42/files", "https://github.com/pull/1/pull/43"],
218
+ [
219
+ "https://dev.azure.com/acme/project/_git/web/pullrequest/42?view=files",
220
+ "https://dev.azure.com/acme/project/_git/web/pullrequest/43",
221
+ ],
222
+ ])("builds a canonical sibling of %s", (url, expected) => {
223
+ expect(sibling(url, 43)).toBe(expected);
224
+ });
225
+
226
+ it.each([
227
+ ["ssh.dev.azure.com", "v3/org/project/web"],
228
+ ["org.visualstudio.com", "defaultcollection/project/_git/web"],
229
+ ["dev.azure.com", "org/project/_git/web"],
230
+ ])("reads back the Azure browser URL built from the remote %s/%s", (host, repository) => {
231
+ const url = sourceControlClients
232
+ .get("azure-devops")
233
+ .changeRequestUrl({ host, repository, number: 42 });
234
+ expect(parse(url!)).toEqual({
235
+ host: "dev.azure.com",
236
+ repository: "org/project/_git/web",
237
+ number: 42,
238
+ });
239
+ });
240
+});
packages/client-runtime/src/sourceControlClients.ts
+6
-2
@@ -8,7 +8,9 @@ import type { ServerSettings } from "@t3tools/contracts";
8
9
export {
10
UNKNOWN_SOURCE_CONTROL_CLIENT,
11
+ type ChangeRequestLink,
12
type ChangeRequestTerminology,
13
+ type ParsedChangeRequestUrl,
14
type SourceControlClientDefinition,
15
} from "@t3tools/source-control-core/client/definition";
16
import * as Forgejo from "@t3tools/source-control-forgejo/client/definition";
@@ -19,8 +21,9 @@ import * as GitLab from "@t3tools/source-control-gitlab/client/definition";
21
/**
22
* GitHub comes first because a repository that has not reported its host yet reads as GitHub,
23
* which is what clients have always shown there. A change request URL goes to the first host
22
- * whose shape it has, so GitCafe, which claims `/pulls/` only on its own hostnames, comes before
23
- * Forgejo, which claims it everywhere.
24
+ * whose shape it has, so GitCafe, which claims `/pull/` and `/pulls/` only on its own hostnames,
25
+ * claims before GitHub and Forgejo, which claim them everywhere. The server's
26
+ * `sourceControl/sourceControlClients.ts` keeps the same order.
27
*/
28
const BUILT_IN_SOURCE_CONTROL_CLIENTS = [
29
GitHub.definition,
@@ -33,6 +36,7 @@ const BUILT_IN_SOURCE_CONTROL_CLIENTS = [
36
37
export const sourceControlClients = makeSourceControlClientRegistry(
38
BUILT_IN_SOURCE_CONTROL_CLIENTS,
39
+ { claimChangeRequestUrlsFirst: [GitCafe.definition.kind] },
40
);
41
42
export type { GitHubSettings } from "@t3tools/source-control-github/client/definition";
packages/client-runtime/src/state/models.ts
+1
-1
@@ -1,5 +1,5 @@
1
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2
-import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
2
+import { threadPullRequestsOf } from "../threadPullRequests.ts";
3
import type {
4
ThreadLinkedPullRequest,
5
EnvironmentId,
packages/client-runtime/src/state/orchestrationV2Projection.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { applyThreadPullRequestLinkUpdate } from "@t3tools/shared/threadPullRequests";
1
+import { applyThreadPullRequestLinkUpdate } from "../threadPullRequests.ts";
2
import type {
3
OrchestrationV2DomainEvent,
4
OrchestrationV2Run,
packages/client-runtime/src/threadPullRequestCompatibility.ts
+1
-1
@@ -4,7 +4,7 @@ import type {
4
ThreadId,
5
ThreadPullRequestKey,
6
} from "@t3tools/contracts";
7
-import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
7
+import { normalizeThreadPullRequestKey } from "./threadPullRequests.ts";
8
9
type LinkingCapabilities = Pick<
10
ExecutionEnvironmentCapabilities,
packages/client-runtime/src/threadPullRequests.test.ts
renamed
packages/client-runtime/src/threadPullRequests.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { makeThreadPullRequests } from "@t3tools/source-control-core/client/threadPullRequests";
2
+
3
+import { sourceControlClients } from "./sourceControlClients.ts";
4
+
5
+export {
6
+ threadPullRequestSearchTerms,
7
+ visibleThreadPullRequests,
8
+} from "@t3tools/shared/threadPullRequests";
9
+export {
10
+ pullRequestListLines,
11
+ type PullRequestListLine,
12
+ type ThreadCurrentPullRequest,
13
+ type ThreadPullRequestBadge,
14
+ type ThreadPullRequestChain,
15
+} from "@t3tools/source-control-core/client/threadPullRequests";
16
+
17
+export const {
18
+ normalizeThreadPullRequestKey,
19
+ legacyThreadPullRequestKey,
20
+ threadPullRequestKeysEqual,
21
+ threadPullRequestKeyOf,
22
+ resolveThreadCurrentPullRequest,
23
+ resolveThreadCurrentPullRequestLink,
24
+ resolveThreadPullRequestChains,
25
+ resolveThreadPullRequestBadge,
26
+ threadPullRequestsOf,
27
+ applyThreadPullRequestLinkUpdate,
28
+} = makeThreadPullRequests(sourceControlClients);
packages/client-runtime/src/threadReference.test.ts
renamed
packages/client-runtime/src/threadReference.ts
renamed
packages/client-runtime/src/work-log/presentation.ts
+5
-2
@@ -16,7 +16,7 @@ import {
16
} from "@t3tools/shared/t3McpToolPresentation";
17
import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
18
import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
19
-import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
19
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
20
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
21
import { formatTokens } from "@t3tools/shared/usageFormat";
22
import { classifyToolActivity } from "@t3tools/shared/toolActivity";
@@ -184,7 +184,10 @@ function resolveT3McpToolPresentation(
184
const payload = asRecord(data);
185
const input =
186
asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
187
- const urlTarget = typeof input?.url === "string" ? parseChangeRequestUrl(input.url) : null;
187
+ const urlTarget =
188
+ typeof input?.url === "string"
189
+ ? sourceControlClients.parseChangeRequestUrl(input.url)?.link
190
+ : null;
191
const number = urlTarget?.number ?? input?.number;
192
const target =
193
actionKind !== undefined &&
packages/shared/package.json
-8
@@ -239,10 +239,6 @@
239
"types": "./src/threadTranscript.ts",
240
"import": "./src/threadTranscript.ts"
241
},
242
- "./threadReference": {
243
- "types": "./src/threadReference.ts",
244
- "import": "./src/threadReference.ts"
245
- },
242
"./paletteSearch": {
243
"types": "./src/paletteSearch.ts",
244
"import": "./src/paletteSearch.ts"
@@ -251,10 +247,6 @@
247
"types": "./src/threadPullRequests.ts",
248
"import": "./src/threadPullRequests.ts"
249
},
254
- "./changeRequestUrl": {
255
- "types": "./src/changeRequestUrl.ts",
256
- "import": "./src/changeRequestUrl.ts"
257
- },
250
"./composerTrigger": {
251
"types": "./src/composerTrigger.ts",
252
"import": "./src/composerTrigger.ts"
packages/shared/src/changeRequestUrl.test.ts
deleted
-197
@@ -1,197 +0,0 @@
1
-import { ProjectId } from "@t3tools/contracts";
2
-import { describe, expect, it } from "vite-plus/test";
3
-
4
-import {
5
- changeRequestUrlFor,
6
- matchesLinkedPullRequestUrl,
7
- parseChangeRequestUrl,
8
- pullRequestCandidateUrlFromReferenceAutolink,
9
- siblingPullRequestUrl,
10
-} from "./changeRequestUrl.ts";
11
-import { normalizeThreadPullRequestKey } from "./threadPullRequests.ts";
12
-
13
-describe("parseChangeRequestUrl", () => {
14
- it("reads a GitHub pull request, lower-casing the repository", () => {
15
- expect(parseChangeRequestUrl("https://github.com/T3Tools/T3Code/pull/123")).toEqual({
16
- host: "github.com",
17
- repository: "t3tools/t3code",
18
- number: 123,
19
- });
20
- });
21
-
22
- it("reads a GitCafe pull request at its canonical /pull/ path and the older /pulls/ path", () => {
23
- for (const path of ["pull", "pulls"]) {
24
- expect(
25
- parseChangeRequestUrl(`https://git.cafe/PingDotGG/T3Code/${path}/23897`),
26
- path,
27
- ).toEqual({ host: "git.cafe", repository: "pingdotgg/t3code", number: 23897 });
28
- }
29
- expect(parseChangeRequestUrl("https://staging.git.cafe/team/repo/pull/7/files")).toEqual({
30
- host: "staging.git.cafe",
31
- repository: "team/repo",
32
- number: 7,
33
- });
34
- });
35
-
36
- it("reads Forgejo URLs even when the hostname contains github", () => {
37
- expect(parseChangeRequestUrl("https://github.internal/team/repo/pulls/7")).toEqual({
38
- host: "github.internal",
39
- authority: "github.internal",
40
- repository: "team/repo",
41
- number: 7,
42
- });
43
- });
44
-
45
- it("reads a supported GitHub host with a middle DNS label", () => {
46
- expect(parseChangeRequestUrl("https://code.github.example.com/acme/web/pull/42")).toEqual({
47
- host: "code.github.example.com",
48
- repository: "acme/web",
49
- number: 42,
50
- });
51
- expect(
52
- pullRequestCandidateUrlFromReferenceAutolink(
53
- "https://code.github.example.com/acme/web/issues/42",
54
- ),
55
- ).toBe("https://code.github.example.com/acme/web/pull/42");
56
- });
57
-
58
- it("reads a GitLab merge request on any host, nested groups and all", () => {
59
- expect(
60
- parseChangeRequestUrl("https://gitlab.com/t3tools/platform/t3code/-/merge_requests/42"),
61
- ).toEqual({ host: "gitlab.com", repository: "t3tools/platform/t3code", number: 42 });
62
- expect(parseChangeRequestUrl("https://code.acme.test/team/project/-/merge_requests/9")).toEqual(
63
- { host: "code.acme.test", repository: "team/project", number: 9 },
64
- );
65
- });
66
-
67
- it("reads Bitbucket and both Azure DevOps URL forms", () => {
68
- expect(parseChangeRequestUrl("https://bitbucket.org/workspace/repo/pull-requests/5")).toEqual({
69
- host: "bitbucket.org",
70
- repository: "workspace/repo",
71
- number: 5,
72
- });
73
- expect(
74
- parseChangeRequestUrl("https://dev.azure.com/acme/platform/_git/t3code/pullrequest/17"),
75
- ).toEqual({ host: "dev.azure.com", repository: "acme/platform/_git/t3code", number: 17 });
76
- expect(
77
- parseChangeRequestUrl("https://acme.visualstudio.com/platform/_git/t3code/pullrequest/17"),
78
- ).toEqual({ host: "acme.visualstudio.com", repository: "platform/_git/t3code", number: 17 });
79
- });
80
-
81
- it("reads Azure DevOps Server links and keeps servers on different ports distinct", () => {
82
- for (const host of ["scm.example.test", "git.cafe", "code.bitbucket.example.test"]) {
83
- const repository = "tfs/collection/project/_git/repo";
84
- const linked = {
85
- projectId: ProjectId.make("project-1"),
86
- host,
87
- repository,
88
- number: 123,
89
- url: `https://${host.toUpperCase()}:8443/tfs/Collection/Project/_git/Repo/pullrequest/123`,
90
- };
91
- const other = { ...linked, url: linked.url.replace(":8443/", ":9443/") };
92
- expect.soft(parseChangeRequestUrl(linked.url), host).toEqual({
93
- host,
94
- authority: `${host}:8443`,
95
- repository,
96
- number: 123,
97
- });
98
- expect.soft(matchesLinkedPullRequestUrl(linked, `${linked.url}?view=files`), host).toBe(true);
99
- expect.soft(matchesLinkedPullRequestUrl(linked, other.url), host).toBe(false);
100
- expect.soft([linked, other].map(normalizeThreadPullRequestKey), host).toEqual([
101
- { host: `${host}:8443`, repository, number: 123 },
102
- { host: `${host}:9443`, repository, number: 123 },
103
- ]);
104
- }
105
- });
106
-
107
- it("survives trailing segments, a trailing slash and a query string", () => {
108
- expect(parseChangeRequestUrl("https://github.com/t3tools/t3code/pull/123/files?w=1")).toEqual({
109
- host: "github.com",
110
- repository: "t3tools/t3code",
111
- number: 123,
112
- });
113
- expect(parseChangeRequestUrl("https://github.com/t3tools/t3code/pull/123/")).toEqual({
114
- host: "github.com",
115
- repository: "t3tools/t3code",
116
- number: 123,
117
- });
118
- });
119
-
120
- it("claims nothing it cannot be sure of", () => {
121
- for (const link of [
122
- "https://github.com/t3tools/t3code/issues/123",
123
- "https://git.cafe/pingdotgg/t3code/issues/23897",
124
- "https://git.cafe/pingdotgg/t3code/pull/abc",
125
- "https://git.cafe/pingdotgg/t3code",
126
- "https://github.com/t3tools/t3code/commit/0a1b2c3",
127
- "https://github.com/t3tools/t3code",
128
- "https://github.com/t3tools/t3code/pull/abc",
129
- "https://gitlab.com/t3tools/t3code/-/issues/12",
130
- "https://blog.example.test/2026/updates/pull/3",
131
- "https://scm.example.test/tfs/Collection/Project/_git/Repo",
132
- "https://scm.example.test/tfs/Collection/Project/pullrequest/123",
133
- "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/abc",
134
- "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/0",
135
- "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/9007199254740992",
136
- "ftp://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123",
137
- "javascript:alert(1)//github.com/t3tools/t3code/pull/1",
138
- "not a url",
139
- ]) {
140
- expect(parseChangeRequestUrl(link), link).toBeNull();
141
- }
142
- });
143
-});
144
-
145
-describe("siblingPullRequestUrl", () => {
146
- it.each([
147
- [
148
- "http://git.example.test:3000/team/repo/pulls/42/files",
149
- "http://git.example.test:3000/team/repo/pulls/43",
150
- ],
151
- ["https://github.com/pull/1/pull/42/files", "https://github.com/pull/1/pull/43"],
152
- [
153
- "https://dev.azure.com/acme/project/_git/web/pullrequest/42?view=files",
154
- "https://dev.azure.com/acme/project/_git/web/pullrequest/43",
155
- ],
156
- ])("builds a canonical sibling of %s", (url, expected) => {
157
- expect(siblingPullRequestUrl(url, 43)).toBe(expected);
158
- });
159
-});
160
-
161
-describe("changeRequestUrlFor", () => {
162
- it("preserves the origin when the Forgejo host already contains its port", () => {
163
- expect(
164
- changeRequestUrlFor(
165
- "forgejo",
166
- "forge.example:3000",
167
- "team/repo",
168
- 42,
169
- "http://forge.example:3000/team/repo.git",
170
- ),
171
- ).toBe("http://forge.example:3000/team/repo/pulls/42");
172
- });
173
-
174
- it.each([
175
- ["http://forge.example:3000/git/owner/repo.git", "http://forge.example:3000"],
176
- ["git@forge.example:git/owner/repo.git", "https://forge.example"],
177
- ["http://other.example:3000/git/owner/repo.git", "https://forge.example"],
178
- ])("preserves the matching Forgejo web origin from %s", (remoteUrl, origin) => {
179
- expect(changeRequestUrlFor("forgejo", "forge.example", "git/owner/repo", 42, remoteUrl)).toBe(
180
- `${origin}/git/owner/repo/pulls/42`,
181
- );
182
- });
183
-
184
- it.each([
185
- ["ssh.dev.azure.com", "v3/org/project/web"],
186
- ["org.visualstudio.com", "defaultcollection/project/_git/web"],
187
- ["dev.azure.com", "org/project/_git/web"],
188
- ])("builds a browser URL from the Azure remote %s/%s", (host, repository) => {
189
- const url = changeRequestUrlFor("azure-devops", host, repository, 42);
190
- expect(url).toBe("https://dev.azure.com/org/project/_git/web/pullrequest/42");
191
- expect(parseChangeRequestUrl(url!)).toEqual({
192
- host: "dev.azure.com",
193
- repository: "org/project/_git/web",
194
- number: 42,
195
- });
196
- });
197
-});
packages/shared/src/changeRequestUrl.ts
deleted
-216
@@ -1,216 +0,0 @@
1
-import type { RepositoryIdentity, ThreadLinkedPullRequest } from "@t3tools/contracts";
2
-import { canonicalRepositoryKey } from "./sourceControl.ts";
3
-
4
-/**
5
- * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
6
- * from a git remote — lower case, no port, the full path below the host — because links are
7
- * matched against those. Anything else matches nothing.
8
- */
9
-export interface ChangeRequestLink {
10
- readonly host: string;
11
- readonly repository: string;
12
- readonly number: number;
13
- readonly authority?: string;
14
-}
15
-
16
-function isHostOf(hostname: string, apex: string, label?: string): boolean {
17
- if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
18
- return label !== undefined && hostname.split(".").includes(label);
19
-}
20
-
21
-export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
22
- let url: URL;
23
- try {
24
- url = new URL(targetUrl);
25
- } catch {
26
- return null;
27
- }
28
- if (url.protocol !== "https:" && url.protocol !== "http:") return null;
29
- const host = url.hostname.toLowerCase();
30
-
31
- if (host === "git.cafe" || host === "staging.git.cafe") {
32
- // GitCafe serves pull requests at `/pull/<n>` and redirects the older `/pulls/<n>` there.
33
- const match = /^\/([^/]+\/[^/]+)\/pulls?\/(\d+)(?:\/|$)/u.exec(url.pathname);
34
- if (match) return claim(host, match);
35
- } else {
36
- if (isHostOf(host, "github.com", "github")) {
37
- const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
38
- if (match) return claim(host, match);
39
- }
40
- const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);
41
- if (forgejo) {
42
- const link = claim(host, forgejo);
43
- return link === null ? null : { ...link, authority: url.host.toLowerCase() };
44
- }
45
- const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
46
- if (gitlab) return claim(host, gitlab);
47
- if (isHostOf(host, "bitbucket.org", "bitbucket")) {
48
- const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
49
- if (match) return claim(host, match);
50
- }
51
- }
52
- // Azure DevOps Server can use any hostname; its `_git` pull request route identifies it.
53
- const azure = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
54
- const link = claim(host, azure);
55
- return link === null || url.port === "" ? link : { ...link, authority: url.host.toLowerCase() };
56
-}
57
-
58
-function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
59
- const repository = match?.[1];
60
- const number = Number(match?.[2]);
61
- return repository && Number.isSafeInteger(number) && number > 0
62
- ? { host, repository: repository.toLowerCase(), number }
63
- : null;
64
-}
65
-
66
-function remoteWebOrigin(host: string, remoteUrl: string | undefined): string {
67
- try {
68
- const remote = new URL(remoteUrl ?? "");
69
- if (
70
- (remote.protocol === "http:" || remote.protocol === "https:") &&
71
- (remote.hostname.toLowerCase() === host.toLowerCase() ||
72
- remote.host.toLowerCase() === host.toLowerCase())
73
- ) {
74
- return remote.origin;
75
- }
76
- } catch {
77
- // SSH remotes do not specify the server's web origin.
78
- }
79
- return `https://${host}`;
80
-}
81
-
82
-export function changeRequestUrlFor(
83
- kind: string | null | undefined,
84
- host: string,
85
- repository: string,
86
- number: number,
87
- remoteUrl?: string,
88
-): string | null {
89
- switch (kind) {
90
- case "github":
91
- return `https://${host}/${repository}/pull/${number}`;
92
- case "gitcafe":
93
- return `https://${host}/${repository}/pulls/${number}`;
94
- case "forgejo":
95
- return `${remoteWebOrigin(host, remoteUrl)}/${repository}/pulls/${number}`;
96
- case "gitlab":
97
- return `https://${host}/${repository}/-/merge_requests/${number}`;
98
- case "bitbucket":
99
- return `https://${host}/${repository}/pull-requests/${number}`;
100
- case "azure-devops": {
101
- const [canonicalHost = host, ...path] = canonicalRepositoryKey(
102
- `${host}/${repository}`.toLowerCase(),
103
- ).split("/");
104
- return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;
105
- }
106
- default:
107
- return null;
108
- }
109
-}
110
-
111
-export function gitHubPullRequestBrowserUrl(
112
- identity: RepositoryIdentity | null | undefined,
113
- repository: string,
114
- number: number,
115
-): string | null {
116
- if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
117
- const repositoryPath = repository.split("/");
118
- if (
119
- repositoryPath.length !== 2 ||
120
- repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
121
- ) {
122
- return null;
123
- }
124
-
125
- let origin: string | null = null;
126
- try {
127
- const remoteUrl = new URL(identity.locator.remoteUrl.trim());
128
- if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
129
- origin = remoteUrl.origin;
130
- }
131
- } catch {}
132
- const hostname = identity.canonicalKey.split("/")[0];
133
- if (origin === null && !hostname) return null;
134
-
135
- try {
136
- const url = new URL(origin ?? `https://${hostname}`);
137
- url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
138
- return url.toString();
139
- } catch {
140
- return null;
141
- }
142
-}
143
-
144
-/**
145
- * The pull-request URL a GitHub-style `#123` autolink might name. GitHub writes every bare
146
- * reference through `/issues/`, including pull requests, so this only builds a candidate: the
147
- * caller must successfully read it as a pull request before treating it as one.
148
- */
149
-export function pullRequestCandidateUrlFromReferenceAutolink(targetUrl: string): string | null {
150
- let url: URL;
151
- try {
152
- url = new URL(targetUrl);
153
- } catch {
154
- return null;
155
- }
156
- if (
157
- (url.protocol !== "https:" && url.protocol !== "http:") ||
158
- !(
159
- url.hostname.toLowerCase() === "github.com" ||
160
- url.hostname.toLowerCase().endsWith(".github.com") ||
161
- url.hostname.toLowerCase().split(".").includes("github")
162
- )
163
- ) {
164
- return null;
165
- }
166
- const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u.exec(url.pathname);
167
- if (match?.[1] === undefined || match[2] === undefined) return null;
168
- url.pathname = `/${match[1]}/pull/${match[2]}`;
169
- return url.toString();
170
-}
171
-
172
-export function matchesLinkedPullRequestUrl(
173
- linkedPullRequest: ThreadLinkedPullRequest,
174
- targetUrl: string,
175
-): boolean {
176
- const linked = parseChangeRequestUrl(linkedPullRequest.url);
177
- const target = parseChangeRequestUrl(targetUrl);
178
- return (
179
- linked !== null &&
180
- target !== null &&
181
- linked.host === target.host &&
182
- linked.repository === target.repository &&
183
- linked.number === target.number &&
184
- linked.authority === target.authority
185
- );
186
-}
187
-
188
-export function changeRequestRepositoryUrl(targetUrl: string): string | null {
189
- const changeRequest = parseChangeRequestUrl(targetUrl);
190
- if (changeRequest === null) return null;
191
- const url = new URL(targetUrl);
192
- const repositoryPath =
193
- /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
194
- /^(.*?)(?:\/pulls?\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
195
- url.pathname,
196
- )?.[1];
197
- if (!repositoryPath) return null;
198
- url.pathname = repositoryPath;
199
- url.search = "";
200
- url.hash = "";
201
- return url.toString();
202
-}
203
-
204
-export function siblingPullRequestUrl(url: string, number: number): string | null {
205
- const reference = parseChangeRequestUrl(url);
206
- if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;
207
- const sibling = new URL(url);
208
- const route = /^\/(-\/merge_requests|pulls?|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
209
- sibling.pathname.slice(reference.repository.length + 1),
210
- )?.[1];
211
- if (route === undefined) return null;
212
- sibling.pathname = `/${reference.repository}/${route}/${number}`;
213
- sibling.search = "";
214
- sibling.hash = "";
215
- return sibling.toString();
216
-}
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+3
-2
@@ -10,7 +10,6 @@ import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
10
import * as Predicate from "effect/Predicate";
11
12
import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
13
-import { threadPullRequestKeyOf } from "./threadPullRequests.ts";
13
14
const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
15
"command_execution",
@@ -303,7 +302,9 @@ function pullRequestWatchTasks(
302
? []
303
: [
304
{
306
- taskId: `pull-request-watch:${threadPullRequestKeyOf(link)}`,
305
+ // Links store their normalized identity, and this id only has to be unique within the
306
+ // thread, so it reads those fields instead of parsing the URL.
307
+ taskId: `pull-request-watch:${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
308
description: `Watching pull request #${link.number}`,
309
kind: "monitor" as const,
310
},
packages/shared/src/threadPullRequests.ts
+1
-342
@@ -1,88 +1,4 @@
1
-import type {
2
- OrchestrationV2AppThread,
3
- ThreadLinkedPullRequest,
4
- ThreadPullRequestKey,
5
- ThreadPullRequestLink,
6
-} from "@t3tools/contracts";
7
-
8
-import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
9
-import { canonicalRepositoryKey } from "./sourceControl.ts";
10
-
11
-type ThreadPullRequestKeySource = ThreadPullRequestKey & {
12
- readonly authority?: string;
13
- readonly url?: string;
14
-};
15
-
16
-export function normalizeThreadPullRequestKey(
17
- key: ThreadPullRequestKeySource,
18
-): ThreadPullRequestKey {
19
- const parsed = key.url === undefined ? null : parseChangeRequestUrl(key.url);
20
- const authority =
21
- key.authority ??
22
- (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
23
- ? parsed.authority
24
- : undefined);
25
- const canonical = canonicalRepositoryKey(
26
- `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
27
- );
28
- const separator = canonical.indexOf("/");
29
- return {
30
- host: canonical.slice(0, separator),
31
- repository: canonical.slice(separator + 1),
32
- number: key.number,
33
- };
34
-}
35
-
36
-export function legacyThreadPullRequestKey(
37
- linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
38
- fallbackHost?: string,
39
-): ThreadPullRequestKey {
40
- const parsed = parseChangeRequestUrl(linked.url);
41
- if (parsed !== null && parsed.number === linked.number) {
42
- const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
43
- if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
44
- return normalizeThreadPullRequestKey(parsed);
45
- }
46
- }
47
- let host = fallbackHost;
48
- if (host === undefined) {
49
- try {
50
- host = new URL(linked.url).hostname;
51
- } catch {
52
- host = "unknown";
53
- }
54
- }
55
- return {
56
- host: host.trim().toLowerCase() || "unknown",
57
- repository: linked.repository.trim().toLowerCase(),
58
- number: linked.number,
59
- };
60
-}
61
-
62
-export function threadPullRequestKeysEqual(
63
- left: ThreadPullRequestKeySource,
64
- right: ThreadPullRequestKeySource,
65
-): boolean {
66
- return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
67
-}
68
-
69
-// Clients re-derive chains for every link on each render, and normalizing parses the
70
-// link's URL. Links are immutable and keep their identity until they change.
71
-const normalizedKeys = new WeakMap<ThreadPullRequestKeySource, ThreadPullRequestKey>();
72
-
73
-function normalizedKeyOf(key: ThreadPullRequestKeySource): ThreadPullRequestKey {
74
- let normalized = normalizedKeys.get(key);
75
- if (normalized === undefined) {
76
- normalized = normalizeThreadPullRequestKey(key);
77
- normalizedKeys.set(key, normalized);
78
- }
79
- return normalized;
80
-}
81
-
82
-export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
83
- const normalized = normalizedKeyOf(key);
84
- return `${normalized.host}/${normalized.repository}#${normalized.number}`;
85
-}
1
+import type { ThreadLinkedPullRequest, ThreadPullRequestLink } from "@t3tools/contracts";
2
3
/** Tombstoned stack members stay in the array only so the
4
* sync reactor does not re-add them. */
@@ -92,202 +8,12 @@ export function visibleThreadPullRequests(
8
return links.filter((link) => link.source !== "stack-dismissed");
9
}
10
95
-function isOpen(link: ThreadPullRequestLink): boolean {
96
- return link.snapshot === null || link.snapshot.state === "open";
97
-}
98
-
11
function latestUpdatedAt(link: ThreadPullRequestLink): number {
12
const value = link.snapshot?.updatedAt ?? link.linkedAt;
13
const ms = Date.parse(value);
14
return Number.isNaN(ms) ? 0 : ms;
15
}
16
105
-export type ThreadCurrentPullRequest =
106
- | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
107
- | {
108
- readonly kind: "stack";
109
- readonly open: ReadonlyArray<ThreadPullRequestLink>;
110
- readonly top: ThreadPullRequestLink;
111
- };
112
-
113
-function layersFromTop(chain: ThreadPullRequestChain): Array<ThreadPullRequestLink> {
114
- // `.sort()` on a fresh array, not `.toSorted()`: this runs on Hermes, which has no ES2023
115
- // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
116
- return chain.layers
117
- .map((link, index) => ({ link, index, depth: chain.depths[index]! }))
118
- .sort((left, right) => right.depth - left.depth || right.index - left.index)
119
- .map((entry) => entry.link);
120
-}
121
-
122
-export function resolveThreadCurrentPullRequest(
123
- links: ReadonlyArray<ThreadPullRequestLink>,
124
-): ThreadCurrentPullRequest | null {
125
- const visible = visibleThreadPullRequests(links);
126
- if (visible.length === 0) return null;
127
- const open = visible.filter(isOpen);
128
- if (open.length === 1) return { kind: "single", link: open[0]! };
129
- const chains = resolveThreadPullRequestChains(visible);
130
- if (open.length > 1) {
131
- const openChains = chains
132
- .map((chain) => layersFromTop(chain).filter(isOpen))
133
- .filter((layers) => layers.length > 0)
134
- .sort(
135
- (left, right) =>
136
- Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
137
- Math.max(...left.map((link) => Date.parse(link.linkedAt))),
138
- );
139
- const ordered = openChains.flat();
140
- return { kind: "stack", open: ordered, top: ordered[0]! };
141
- }
142
- if (chains.length === 1) {
143
- return { kind: "single", link: layersFromTop(chains[0]!)[0]! };
144
- }
145
- const terminal = [...visible].sort(
146
- (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
147
- );
148
- return { kind: "single", link: terminal[0]! };
149
-}
150
-
151
-export function resolveThreadCurrentPullRequestLink(
152
- links: ReadonlyArray<ThreadPullRequestLink>,
153
-): ThreadPullRequestLink | null {
154
- const current = resolveThreadCurrentPullRequest(links);
155
- if (current === null) return null;
156
- return current.kind === "single" ? current.link : current.top;
157
-}
158
-
159
-export interface ThreadPullRequestChain {
160
- readonly kind: "native" | "derived";
161
- readonly layers: ReadonlyArray<ThreadPullRequestLink>;
162
- /** One per layer: 0 for the base, parent's depth + 1 above it. Siblings share a depth. */
163
- readonly depths: ReadonlyArray<number>;
164
-}
165
-
166
-export function resolveThreadPullRequestChains(
167
- links: ReadonlyArray<ThreadPullRequestLink>,
168
-): ReadonlyArray<ThreadPullRequestChain> {
169
- const visible = visibleThreadPullRequests(links);
170
- const chains: Array<ThreadPullRequestChain> = [];
171
- const placed = new Set<string>();
172
-
173
- const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
174
- for (const link of visible) {
175
- if (link.stack === null) continue;
176
- const key = normalizedKeyOf(link);
177
- const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
178
- const members = nativeStacks.get(stackKey) ?? [];
179
- members.push(link);
180
- nativeStacks.set(stackKey, members);
181
- }
182
- for (const members of nativeStacks.values()) {
183
- // Saved snapshots can lag behind newer members of the same stack.
184
- const memberNumbers = new Set(members.map((member) => member.number));
185
- let layers = members[0]!.stack!.layers;
186
- let coverage = layers.filter((layer) => memberNumbers.has(layer.number)).length;
187
- for (const member of members.slice(1)) {
188
- const candidate = member.stack!.layers;
189
- const candidateCoverage = candidate.filter((layer) => memberNumbers.has(layer.number)).length;
190
- if (
191
- candidateCoverage > coverage ||
192
- (candidateCoverage === coverage && candidate.length > layers.length)
193
- ) {
194
- layers = candidate;
195
- coverage = candidateCoverage;
196
- }
197
- }
198
- const order = new Map(layers.map((layer, index) => [layer.number, index]));
199
- members.sort(
200
- (left, right) =>
201
- (order.get(left.number) ?? layers.length) - (order.get(right.number) ?? layers.length),
202
- );
203
- for (const member of members) placed.add(threadPullRequestKeyOf(member));
204
- chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
205
- }
206
-
207
- const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
208
- const branchKey = (link: ThreadPullRequestLink, branch: string) => {
209
- const key = normalizedKeyOf(link);
210
- return `${key.host}/${key.repository}:${branch}`;
211
- };
212
- const byHead = new Map<string, ThreadPullRequestLink | null>();
213
- for (const link of remaining) {
214
- if (link.snapshot === null) continue;
215
- const key = branchKey(link, link.snapshot.headBranch);
216
- byHead.set(key, byHead.has(key) ? null : link);
217
- }
218
- const parentOf = (link: ThreadPullRequestLink) => {
219
- if (link.snapshot === null) return undefined;
220
- const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
221
- return parent == null || parent === link ? undefined : parent;
222
- };
223
- const children = new Map<string, Array<ThreadPullRequestLink>>();
224
- for (const link of remaining) {
225
- const parent = parentOf(link);
226
- if (parent === undefined) continue;
227
- const key = threadPullRequestKeyOf(parent);
228
- const siblings = children.get(key) ?? [];
229
- siblings.push(link);
230
- children.set(key, siblings);
231
- }
232
- for (const base of remaining) {
233
- if (parentOf(base) !== undefined) continue;
234
- const layers: Array<ThreadPullRequestLink> = [];
235
- const depths: Array<number> = [];
236
- const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
237
- { link: base, depth: 0 },
238
- ];
239
- for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
240
- const key = threadPullRequestKeyOf(next.link);
241
- // Two links with one identity would otherwise share a child list and expand forever.
242
- if (placed.has(key)) continue;
243
- placed.add(key);
244
- layers.push(next.link);
245
- depths.push(next.depth);
246
- const below = children.get(key) ?? [];
247
- for (let index = below.length - 1; index >= 0; index -= 1) {
248
- pending.push({ link: below[index]!, depth: next.depth + 1 });
249
- }
250
- }
251
- if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
252
- }
253
- for (const link of remaining) {
254
- if (!placed.has(threadPullRequestKeyOf(link))) {
255
- chains.push({ kind: "derived", layers: [link], depths: [0] });
256
- }
257
- }
258
- return chains;
259
-}
260
-
261
-export type ThreadPullRequestBadge = {
262
- readonly state: "open" | "closed" | "merged" | "draft";
263
-} & (
264
- | {
265
- readonly kind: "stack";
266
- readonly layers: number;
267
- }
268
- | { readonly kind: "pull-request"; readonly others: number }
269
-);
270
-
271
-export function resolveThreadPullRequestBadge(
272
- pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
273
-): ThreadPullRequestBadge | null {
274
- const visible = visibleThreadPullRequests(pullRequests ?? []);
275
- if (visible.length === 0) return null;
276
- const states = visible.map((link) => link.snapshot?.state ?? "open");
277
- const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
278
- ? "draft"
279
- : states.includes("open")
280
- ? "open"
281
- : states.every((entry) => entry === "merged")
282
- ? "merged"
283
- : "closed";
284
- const chains = resolveThreadPullRequestChains(visible);
285
- if (visible.length > 1 && chains.length === 1) {
286
- return { kind: "stack", layers: visible.length, state };
287
- }
288
- return { kind: "pull-request", others: visible.length - 1, state };
289
-}
290
-
17
export interface ThreadSearchPullRequest {
18
readonly number: number;
19
readonly title: string | null;
@@ -338,70 +64,3 @@ export function threadPullRequestSearchTerms(thread: {
64
...(pullRequest.title ? [pullRequest.title] : []),
65
]);
66
}
341
-
342
-/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
343
-export function threadPullRequestsOf(thread: {
344
- readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
345
- readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
346
-}): ReadonlyArray<ThreadPullRequestLink> {
347
- if (thread.pullRequests !== undefined) return thread.pullRequests;
348
- const linked = thread.linkedPullRequest;
349
- return linked == null
350
- ? []
351
- : [
352
- {
353
- ...legacyThreadPullRequestKey(linked),
354
- url: linked.url,
355
- source: "manual",
356
- linkedAt: "1970-01-01T00:00:00.000Z",
357
- snapshot: null,
358
- stack: null,
359
- },
360
- ];
361
-}
362
-
363
-export function applyThreadPullRequestLinkUpdate(
364
- thread: OrchestrationV2AppThread,
365
- updated: ThreadPullRequestLink,
366
-): OrchestrationV2AppThread {
367
- return {
368
- ...thread,
369
- pullRequests: threadPullRequestsOf(thread).map((link) =>
370
- threadPullRequestKeysEqual(link, updated) ? updated : link,
371
- ),
372
- };
373
-}
374
-
375
-export interface PullRequestListLine {
376
- readonly link: ThreadPullRequestLink;
377
- readonly depth: number;
378
- readonly chainKey: string;
379
- readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
380
-}
381
-
382
-function chainKeyOf(chain: ThreadPullRequestChain): string {
383
- const bottom = chain.layers[0]!;
384
- return `${bottom.host}/${bottom.repository}#${bottom.number}`;
385
-}
386
-
387
-export function pullRequestListLines(
388
- chains: ReadonlyArray<ThreadPullRequestChain>,
389
-): ReadonlyArray<PullRequestListLine> {
390
- const ordered = [...chains].sort(
391
- (left, right) =>
392
- Math.max(...right.layers.map(latestUpdatedAt)) -
393
- Math.max(...left.layers.map(latestUpdatedAt)),
394
- );
395
- return ordered.flatMap((chain) => {
396
- const chainKey = chainKeyOf(chain);
397
- return chain.layers.map((link, index) => ({
398
- link,
399
- depth: chain.depths[index]!,
400
- chainKey,
401
- stack:
402
- index === 0 && chain.layers.length > 1
403
- ? { kind: chain.kind, size: chain.layers.length }
404
- : null,
405
- }));
406
- });
407
-}
packages/source-control-azure-devops/src/client/definition.test.ts
new
+104
@@ -0,0 +1,104 @@
1
+import type { ChangeRequestProjectIdentity } from "@t3tools/source-control-core/client/definition";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { definition } from "./definition.ts";
5
+
6
+const parse = (url: string) => definition.parseChangeRequestUrl(new URL(url));
7
+
8
+describe("Azure DevOps change request URLs", () => {
9
+ it("reads both hosted URL forms", () => {
10
+ expect(parse("https://dev.azure.com/acme/platform/_git/t3code/pullrequest/17")).toEqual({
11
+ host: "dev.azure.com",
12
+ repository: "acme/platform/_git/t3code",
13
+ number: 17,
14
+ repositoryUrl: "https://dev.azure.com/acme/platform/_git/t3code",
15
+ });
16
+ expect(
17
+ parse("https://acme.visualstudio.com/platform/_git/t3code/pullrequest/17"),
18
+ ).toMatchObject({
19
+ host: "acme.visualstudio.com",
20
+ repository: "platform/_git/t3code",
21
+ number: 17,
22
+ });
23
+ });
24
+
25
+ it("keeps Azure DevOps Server ports in the authority, on any hostname", () => {
26
+ expect(
27
+ parse("https://GIT.CAFE:8443/tfs/Collection/Project/_git/Repo/pullrequest/123?view=files"),
28
+ ).toEqual({
29
+ host: "git.cafe",
30
+ authority: "git.cafe:8443",
31
+ repository: "tfs/collection/project/_git/repo",
32
+ number: 123,
33
+ repositoryUrl: "https://git.cafe:8443/tfs/Collection/Project/_git/Repo",
34
+ });
35
+ expect(parse("https://scm.example.test/tfs/c/p/_git/r/pullrequest/1")).not.toHaveProperty(
36
+ "authority",
37
+ );
38
+ });
39
+
40
+ it("claims nothing without the _git route or a valid number", () => {
41
+ for (const url of [
42
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo",
43
+ "https://scm.example.test/tfs/Collection/Project/pullrequest/123",
44
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/abc",
45
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/0",
46
+ "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/9007199254740992",
47
+ ]) {
48
+ expect(parse(url), url).toBeNull();
49
+ }
50
+ });
51
+
52
+ it.each([
53
+ ["ssh.dev.azure.com", "v3/org/project/web"],
54
+ ["org.visualstudio.com", "defaultcollection/project/_git/web"],
55
+ ["dev.azure.com", "org/project/_git/web"],
56
+ ])("builds a canonical browser URL from the remote %s/%s", (host, repository) => {
57
+ expect(definition.changeRequestUrl({ host, repository, number: 42 })).toBe(
58
+ "https://dev.azure.com/org/project/_git/web/pullrequest/42",
59
+ );
60
+ });
61
+
62
+ it("keeps an Azure DevOps Server's HTTP origin and builds below a web URL", () => {
63
+ expect(
64
+ definition.changeRequestUrl({
65
+ host: "scm.example.test",
66
+ repository: "tfs/collection/project/_git/repo",
67
+ number: 124,
68
+ remoteUrl: "http://dummy:secret@scm.example.test:8080/tfs/Collection/Project/_git/Repo",
69
+ }),
70
+ ).toBe("http://scm.example.test:8080/tfs/collection/project/_git/repo/pullrequest/124");
71
+ expect(
72
+ definition.changeRequestUrl({
73
+ host: "dev.azure.com",
74
+ repository: "acme/project/_git/web",
75
+ number: 43,
76
+ webUrl: "https://dev.azure.com/acme/project/_git/web",
77
+ }),
78
+ ).toBe("https://dev.azure.com/acme/project/_git/web/pullrequest/43");
79
+ });
80
+
81
+ it.each([
82
+ ["ssh.dev.azure.com/v3/org-a/project/web", "git@ssh.dev.azure.com:v3/org-a/project/web"],
83
+ [
84
+ "vs-ssh.visualstudio.com/v3/org-a/project/web",
85
+ "git@vs-ssh.visualstudio.com:v3/org-a/project/web",
86
+ ],
87
+ [
88
+ "org-a.visualstudio.com/defaultcollection/project/_git/web",
89
+ "https://org-a.visualstudio.com/DefaultCollection/Project/_git/Web",
90
+ ],
91
+ ["dev.azure.com/org-a/project/_git/web", "https://org-a@dev.azure.com/org-a/Project/_git/Web"],
92
+ ])("matches browser references against the checkout %s", (canonicalKey, remoteUrl) => {
93
+ const identity: ChangeRequestProjectIdentity = {
94
+ canonicalKey,
95
+ displayName: canonicalKey.split("/").slice(1).join("/"),
96
+ locator: { source: "git-remote", remoteName: "origin", remoteUrl },
97
+ };
98
+ const link = parse("https://dev.azure.com/org-a/project/_git/web/pullrequest/42")!;
99
+ expect(definition.isChangeRequestInRepository(identity, link)).toBe(true);
100
+ for (const repository of ["org-b/project/_git/web", "org-a/other-project/_git/web"]) {
101
+ expect(definition.isChangeRequestInRepository(identity, { ...link, repository })).toBe(false);
102
+ }
103
+ });
104
+});
packages/source-control-azure-devops/src/client/definition.ts
+18
-5
@@ -1,11 +1,15 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import { canonicalRepositoryKey } from "@t3tools/shared/sourceControl";
3
import {
4
+ changeRequestUrlBelow,
5
defineSourceControlClient,
6
isChangeRequestAuthorityOfProject,
6
- isChangeRequestPath,
7
+ parseChangeRequestPath,
8
+ remoteWebOrigin,
9
} from "@t3tools/source-control-core/client/definition";
10
11
+// Azure DevOps Server runs on any hostname; its `_git` route identifies it.
12
+const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u;
13
const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
14
const CHANGE_REQUEST_REFERENCE =
15
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
@@ -33,8 +37,19 @@ export const definition = defineSourceControlClient({
37
publishHost: () => "dev.azure.com",
38
newRepositoryOwner: () => null,
39
defaultCloneTransport: "ssh",
36
- changeRequestUrl: ({ host, repository, number }) =>
37
- `https://${canonicalRepositoryKey(`${host}/${repository}`.toLowerCase())}/pullrequest/${number}`,
40
+ changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {
41
+ if (webUrl) return changeRequestUrlBelow(webUrl, `pullrequest/${number}`);
42
+ const [canonicalHost = host, ...path] = canonicalRepositoryKey(
43
+ `${host}/${repository}`.toLowerCase(),
44
+ ).split("/");
45
+ return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;
46
+ },
47
+ // Servers on different ports are different servers, so a port stays in the link.
48
+ parseChangeRequestUrl: (url) => {
49
+ const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
50
+ return link === null || url.port === "" ? link : { ...link, authority: url.host.toLowerCase() };
51
+ },
52
+ changeRequestUrlFromReferenceAutolink: () => null,
53
changeRequestActions: new Set([
54
"merge",
55
"ready",
@@ -53,12 +68,10 @@ export const definition = defineSourceControlClient({
68
return args ? checkoutCommandId(args) : null;
69
},
70
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
56
- changeRequestUrlHost: (url) => url.hostname,
71
checkoutChangeRequestHost: () => null,
72
isChangeRequestInRepository: (identity, link) =>
73
isChangeRequestAuthorityOfProject(identity, link) &&
74
canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===
75
canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase()),
76
canReadChangeRequestOnHost: () => false,
63
- isChangeRequestUrl: (url) => isChangeRequestPath(url, "/pullrequest/"),
77
});
packages/source-control-azure-devops/src/server/driver.ts
+4
-2
@@ -1,12 +1,14 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
1
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
2
import * as Effect from "effect/Effect";
3
4
+import { definition } from "../client/definition.ts";
5
+
6
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
7
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
8
9
export const driver = defineSourceControlDriver({
9
- kind: SourceControlProviderKind.make("azure-devops"),
10
+ kind: definition.kind,
11
+ definition,
12
make: Effect.all({
13
sourceControl: AzureDevOpsSourceControlProvider.make,
14
discovery: Effect.succeed(AzureDevOpsSourceControlProvider.discovery),
packages/source-control-bitbucket/src/client/definition.test.ts
new
+38
@@ -0,0 +1,38 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { definition } from "./definition.ts";
4
+
5
+const parse = (url: string) => definition.parseChangeRequestUrl(new URL(url));
6
+
7
+describe("Bitbucket change request URLs", () => {
8
+ it("reads a pull request on Bitbucket hosts", () => {
9
+ expect(parse("https://bitbucket.org/workspace/repo/pull-requests/5/diff")).toEqual({
10
+ host: "bitbucket.org",
11
+ repository: "workspace/repo",
12
+ number: 5,
13
+ repositoryUrl: "https://bitbucket.org/workspace/repo",
14
+ });
15
+ expect(parse("https://code.bitbucket.example.test/team/repo/pull-requests/6")).toMatchObject({
16
+ host: "code.bitbucket.example.test",
17
+ number: 6,
18
+ });
19
+ });
20
+
21
+ it("leaves other hosts alone", () => {
22
+ expect(parse("https://scm.example.test/workspace/repo/pull-requests/5")).toBeNull();
23
+ });
24
+
25
+ it("builds pull request URLs below the repository", () => {
26
+ expect(
27
+ definition.changeRequestUrl({ host: "bitbucket.org", repository: "w/repo", number: 5 }),
28
+ ).toBe("https://bitbucket.org/w/repo/pull-requests/5");
29
+ expect(
30
+ definition.changeRequestUrl({
31
+ host: "bitbucket.org",
32
+ repository: "w/repo",
33
+ number: 5,
34
+ webUrl: "https://bitbucket.org/w/repo",
35
+ }),
36
+ ).toBe("https://bitbucket.org/w/repo/pull-requests/5");
37
+ });
38
+});
packages/source-control-bitbucket/src/client/definition.ts
+20
-5
@@ -6,17 +6,29 @@ import {
6
import * as Effect from "effect/Effect";
7
import * as Schema from "effect/Schema";
8
import {
9
+ changeRequestUrlBelow,
10
defineSourceControlClient,
11
isChangeRequestInProjectRepository,
12
isChangeRequestOnProjectHost,
12
- isChangeRequestPath,
13
+ parseChangeRequestPath,
14
} from "@t3tools/source-control-core/client/definition";
15
16
const safeShellArgument = /^[A-Za-z0-9._/@+=,-]+$/;
17
const repositoryName = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
18
19
+const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u;
20
+
21
const KIND = SourceControlProviderKind.make("bitbucket");
22
23
+function isBitbucketHost(hostname: string): boolean {
24
+ const host = hostname.toLowerCase();
25
+ return (
26
+ host === "bitbucket.org" ||
27
+ host.endsWith(".bitbucket.org") ||
28
+ host.split(".").includes("bitbucket")
29
+ );
30
+}
31
+
32
const text = (annotations: Schema.Annotations.Key<string>) =>
33
TrimmedString.pipe(
34
Schema.withDecodingDefault(Effect.succeed("")),
@@ -62,8 +74,13 @@ export const definition = defineSourceControlClient({
74
// A new repository belongs to a workspace, which the signed-in account does not name.
75
newRepositoryOwner: () => null,
76
defaultCloneTransport: "ssh",
65
- changeRequestUrl: ({ host, repository, number }) =>
66
- `https://${host}/${repository}/pull-requests/${number}`,
77
+ changeRequestUrl: ({ host, repository, number, webUrl }) =>
78
+ webUrl
79
+ ? changeRequestUrlBelow(webUrl, `pull-requests/${number}`)
80
+ : `https://${host}/${repository}/pull-requests/${number}`,
81
+ parseChangeRequestUrl: (url) =>
82
+ isBitbucketHost(url.hostname) ? parseChangeRequestPath(url, CHANGE_REQUEST_PATH) : null,
83
+ changeRequestUrlFromReferenceAutolink: () => null,
84
// No endpoint reopens a declined pull request, and nothing documented moves one in or out of
85
// draft, so neither is offered rather than failing when pressed.
86
changeRequestActions: new Set(["merge", "close"] as const),
@@ -79,12 +96,10 @@ export const definition = defineSourceControlClient({
96
reviewSummaryRequired: () => false,
97
checkoutCommandArgument: () => null,
98
isChangeRequestReference: () => false,
82
- changeRequestUrlHost: (url) => url.hostname,
99
checkoutChangeRequestHost: () => null,
100
isChangeRequestInRepository: (identity, link) =>
101
isChangeRequestInProjectRepository(KIND, identity, link),
102
canReadChangeRequestOnHost: (identity, link) =>
103
isChangeRequestOnProjectHost(KIND, identity, link),
88
- isChangeRequestUrl: (url) => isChangeRequestPath(url, "/pull-requests/"),
104
settings,
105
});
packages/source-control-bitbucket/src/server/driver.ts
+4
-2
@@ -1,12 +1,14 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
1
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
2
import * as Effect from "effect/Effect";
3
4
+import { definition } from "../client/definition.ts";
5
+
6
import * as BitbucketPullRequestProvider from "./BitbucketPullRequestProvider.ts";
7
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
8
9
export const driver = defineSourceControlDriver({
9
- kind: SourceControlProviderKind.make("bitbucket"),
10
+ kind: definition.kind,
11
+ definition,
12
make: Effect.all({
13
sourceControl: BitbucketSourceControlProvider.make,
14
discovery: BitbucketSourceControlProvider.makeDiscovery,
packages/source-control-core/package.json
+4
@@ -7,6 +7,10 @@
7
"types": "./src/client/definition.ts",
8
"import": "./src/client/definition.ts"
9
},
10
+ "./client/threadPullRequests": {
11
+ "types": "./src/client/threadPullRequests.ts",
12
+ "import": "./src/client/threadPullRequests.ts"
13
+ },
14
"./server/diffFileRevisions": {
15
"types": "./src/server/diffFileRevisions.ts",
16
"import": "./src/server/diffFileRevisions.ts"
packages/source-control-core/src/client/definition.ts
+126
-13
@@ -5,9 +5,25 @@ import {
5
type RepositoryIdentity,
6
SourceControlProviderKind,
7
} from "@t3tools/contracts";
8
-import type { ChangeRequestLink } from "@t3tools/shared/changeRequestUrl";
8
import * as Schema from "effect/Schema";
9
10
+/**
11
+ * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
12
+ * from a git remote — lower case, no port, the full path below the host — because links are
13
+ * matched against those. `authority` keeps the port for hosts whose identity includes it.
14
+ */
15
+export interface ChangeRequestLink {
16
+ readonly host: string;
17
+ readonly repository: string;
18
+ readonly number: number;
19
+ readonly authority?: string;
20
+}
21
+
22
+export interface ParsedChangeRequestUrl extends ChangeRequestLink {
23
+ /** The repository's browser URL, without query or hash. */
24
+ readonly repositoryUrl: string;
25
+}
26
+
27
export interface ChangeRequestTerminology {
28
readonly shortLabel: string;
29
readonly singular: string;
@@ -18,6 +34,7 @@ export interface ChangeRequestUrlInput {
34
readonly repository: string;
35
readonly number: number;
36
readonly remoteUrl?: string | undefined;
37
+ /** The repository's browser URL; when given, the result is this plus the host's route. */
38
readonly webUrl?: string | undefined;
39
}
40
@@ -46,6 +63,14 @@ export interface SourceControlClientDefinition {
63
readonly newRepositoryOwner: (account: string | null) => { readonly owner: string | null } | null;
64
readonly defaultCloneTransport: "https" | "ssh";
65
readonly changeRequestUrl: (input: ChangeRequestUrlInput) => string | null;
66
+ /** Null when the URL is not one of this host's change requests. */
67
+ readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null;
68
+ /**
69
+ * The change request URL a bare `#123` autolink might name, for hosts that write every
70
+ * reference through their issue route. Only a candidate: the caller must read it as a change
71
+ * request before treating it as one.
72
+ */
73
+ readonly changeRequestUrlFromReferenceAutolink: (url: URL) => string | null;
74
/**
75
* The actions this host can take on a change request, the same list its server provider
76
* declares in `capabilities.actions`.
@@ -65,9 +90,7 @@ export interface SourceControlClientDefinition {
90
identity: ChangeRequestProjectIdentity,
91
link: ChangeRequestLink,
92
) => boolean;
68
- readonly changeRequestUrlHost: (url: URL) => string;
93
readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;
70
- readonly isChangeRequestUrl: (url: string) => boolean;
94
readonly settings?: SourceControlHostSettingsSchema;
95
}
96
@@ -75,14 +98,44 @@ export type SourceControlHostSettingsSchema = {
98
readonly fields: Readonly<Record<string, Schema.Top>>;
99
} & Schema.Decoder<object>;
100
78
-export function isChangeRequestPath(url: string, route: string): boolean {
101
+/**
102
+ * Reads a change request from `url` with `route`, whose first group is the repository path and
103
+ * second the number.
104
+ */
105
+export function parseChangeRequestPath(url: URL, route: RegExp): ParsedChangeRequestUrl | null {
106
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
107
+ const match = route.exec(url.pathname);
108
+ const repository = match?.[1];
109
+ const number = Number(match?.[2]);
110
+ return repository && Number.isSafeInteger(number) && number > 0
111
+ ? {
112
+ host: url.hostname.toLowerCase(),
113
+ repository: repository.toLowerCase(),
114
+ number,
115
+ repositoryUrl: `${url.origin}/${repository}`,
116
+ }
117
+ : null;
118
+}
119
+
120
+export function changeRequestUrlBelow(webUrl: string, route: string): string {
121
+ return `${webUrl.replace(/\/+$/u, "")}/${route}`;
122
+}
123
+
124
+/** An HTTP remote on `host` names the server's web origin, port included; SSH remotes do not. */
125
+export function remoteWebOrigin(host: string, remoteUrl: string | undefined): string {
126
try {
80
- const path = new URL(url).pathname;
81
- const at = path.indexOf(route);
82
- return at > 0 && /^\d+(?:\/|$)/u.test(path.slice(at + route.length));
127
+ const remote = new URL(remoteUrl ?? "");
128
+ if (
129
+ (remote.protocol === "http:" || remote.protocol === "https:") &&
130
+ (remote.hostname.toLowerCase() === host.toLowerCase() ||
131
+ remote.host.toLowerCase() === host.toLowerCase())
132
+ ) {
133
+ return remote.origin;
134
+ }
135
} catch {
84
- return false;
136
+ // SSH remotes do not specify the server's web origin.
137
}
138
+ return `https://${host}`;
139
}
140
141
export function defineSourceControlClient<const Definition extends SourceControlClientDefinition>(
@@ -150,6 +203,8 @@ export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {
203
newRepositoryOwner: () => null,
204
defaultCloneTransport: "ssh",
205
changeRequestUrl: () => null,
206
+ parseChangeRequestUrl: () => null,
207
+ changeRequestUrlFromReferenceAutolink: () => null,
208
changeRequestActions: new Set(),
209
checkoutCommand: () => null,
210
authorProfileUrl: () => null,
@@ -157,26 +212,49 @@ export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {
212
reviewSummaryRequired: () => false,
213
checkoutCommandArgument: () => null,
214
isChangeRequestReference: () => false,
160
- changeRequestUrlHost: (url) => url.hostname,
215
checkoutChangeRequestHost: () => null,
216
isChangeRequestInRepository: (identity, link) =>
217
isChangeRequestInProjectRepository(SourceControlProviderKind.make("unknown"), identity, link),
218
canReadChangeRequestOnHost: (identity, link) =>
219
isChangeRequestOnProjectHost(SourceControlProviderKind.make("unknown"), identity, link),
166
- isChangeRequestUrl: () => false,
220
};
221
222
+export interface ParsedChangeRequest {
223
+ readonly definition: SourceControlClientDefinition;
224
+ readonly link: ParsedChangeRequestUrl;
225
+}
226
+
227
export interface SourceControlClientRegistry {
228
readonly definitions: ReadonlyArray<SourceControlClientDefinition>;
229
readonly get: (kind: string | null | undefined) => SourceControlClientDefinition;
230
readonly find: (kind: string) => SourceControlClientDefinition | undefined;
231
readonly findByPublicHost: (hostname: string) => SourceControlClientDefinition | undefined;
232
+ /** The first host, in registry order, that reads `url` as one of its change requests. */
233
+ readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
234
readonly findByChangeRequestUrl: (url: string) => SourceControlClientDefinition | undefined;
235
readonly hostLabelForChangeRequestUrl: (url: string) => string;
236
+ readonly isSameChangeRequest: (left: string, right: string) => boolean;
237
+ readonly changeRequestUrlFromReferenceAutolink: (url: string) => string | null;
238
+}
239
+
240
+function httpUrl(value: string): URL | null {
241
+ try {
242
+ const url = new URL(value);
243
+ return url.protocol === "https:" || url.protocol === "http:" ? url : null;
244
+ } catch {
245
+ return null;
246
+ }
247
}
248
249
+/**
250
+ * `definitions` is display order, and its first entry is what `get` returns for a repository
251
+ * that has not reported its host yet. A change request URL goes to the first definition that
252
+ * reads it, trying `claimChangeRequestUrlsFirst` before the rest, so a host that claims a route
253
+ * only on its own hostnames can precede one that claims the route everywhere.
254
+ */
255
export function makeSourceControlClientRegistry(
256
definitions: ReadonlyArray<SourceControlClientDefinition>,
257
+ options?: { readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind> },
258
): SourceControlClientRegistry {
259
const byKind = new Map<string, SourceControlClientDefinition>();
260
for (const definition of definitions) {
@@ -185,6 +263,20 @@ export function makeSourceControlClientRegistry(
263
}
264
byKind.set(definition.kind, definition);
265
}
266
+ const first = new Set(options?.claimChangeRequestUrlsFirst);
267
+ const claimOrder = [
268
+ ...definitions.filter((definition) => first.has(definition.kind)),
269
+ ...definitions.filter((definition) => !first.has(definition.kind)),
270
+ ];
271
+ const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => {
272
+ const url = httpUrl(value);
273
+ if (url === null) return null;
274
+ for (const definition of claimOrder) {
275
+ const link = definition.parseChangeRequestUrl(url);
276
+ if (link !== null) return { definition, link };
277
+ }
278
+ return null;
279
+ };
280
return {
281
definitions,
282
get: (kind) =>
@@ -194,10 +286,31 @@ export function makeSourceControlClientRegistry(
286
const host = hostname.toLowerCase();
287
return definitions.find((definition) => definition.publicHost === host);
288
},
197
- findByChangeRequestUrl: (url) =>
198
- definitions.find((definition) => definition.isChangeRequestUrl(url)),
289
+ parseChangeRequestUrl,
290
+ findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition,
291
hostLabelForChangeRequestUrl: (url) =>
200
- definitions.find((definition) => definition.isChangeRequestUrl(url))?.label ?? "the host",
292
+ parseChangeRequestUrl(url)?.definition.label ?? "the host",
293
+ isSameChangeRequest: (left, right) => {
294
+ const a = parseChangeRequestUrl(left)?.link;
295
+ const b = parseChangeRequestUrl(right)?.link;
296
+ return (
297
+ a !== undefined &&
298
+ b !== undefined &&
299
+ a.host === b.host &&
300
+ a.repository === b.repository &&
301
+ a.number === b.number &&
302
+ a.authority === b.authority
303
+ );
304
+ },
305
+ changeRequestUrlFromReferenceAutolink: (value) => {
306
+ const url = httpUrl(value);
307
+ if (url === null) return null;
308
+ for (const definition of claimOrder) {
309
+ const candidate = definition.changeRequestUrlFromReferenceAutolink(url);
310
+ if (candidate !== null) return candidate;
311
+ }
312
+ return null;
313
+ },
314
};
315
}
316
packages/source-control-core/src/client/threadPullRequests.ts
new
+372
@@ -0,0 +1,372 @@
1
+import type {
2
+ OrchestrationV2AppThread,
3
+ ThreadLinkedPullRequest,
4
+ ThreadPullRequestKey,
5
+ ThreadPullRequestLink,
6
+} from "@t3tools/contracts";
7
+import { canonicalRepositoryKey } from "@t3tools/shared/sourceControl";
8
+import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
9
+
10
+import type { SourceControlClientRegistry } from "./definition.ts";
11
+
12
+type ThreadPullRequestKeySource = ThreadPullRequestKey & {
13
+ readonly authority?: string;
14
+ readonly url?: string;
15
+};
16
+
17
+function isOpen(link: ThreadPullRequestLink): boolean {
18
+ return link.snapshot === null || link.snapshot.state === "open";
19
+}
20
+
21
+function latestUpdatedAt(link: ThreadPullRequestLink): number {
22
+ const value = link.snapshot?.updatedAt ?? link.linkedAt;
23
+ const ms = Date.parse(value);
24
+ return Number.isNaN(ms) ? 0 : ms;
25
+}
26
+
27
+export type ThreadCurrentPullRequest =
28
+ | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
29
+ | {
30
+ readonly kind: "stack";
31
+ readonly open: ReadonlyArray<ThreadPullRequestLink>;
32
+ readonly top: ThreadPullRequestLink;
33
+ };
34
+
35
+function layersFromTop(chain: ThreadPullRequestChain): Array<ThreadPullRequestLink> {
36
+ // `.sort()` on a fresh array, not `.toSorted()`: this runs on Hermes, which has no ES2023
37
+ // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
38
+ return chain.layers
39
+ .map((link, index) => ({ link, index, depth: chain.depths[index]! }))
40
+ .sort((left, right) => right.depth - left.depth || right.index - left.index)
41
+ .map((entry) => entry.link);
42
+}
43
+
44
+export interface ThreadPullRequestChain {
45
+ readonly kind: "native" | "derived";
46
+ readonly layers: ReadonlyArray<ThreadPullRequestLink>;
47
+ /** One per layer: 0 for the base, parent's depth + 1 above it. Siblings share a depth. */
48
+ readonly depths: ReadonlyArray<number>;
49
+}
50
+
51
+export type ThreadPullRequestBadge = {
52
+ readonly state: "open" | "closed" | "merged" | "draft";
53
+} & (
54
+ | {
55
+ readonly kind: "stack";
56
+ readonly layers: number;
57
+ }
58
+ | { readonly kind: "pull-request"; readonly others: number }
59
+);
60
+
61
+/**
62
+ * Thread pull request identity reads a link's URL through the hosts in `registry`, so each side
63
+ * binds these once to its own registry.
64
+ */
65
+export function makeThreadPullRequests(
66
+ registry: Pick<SourceControlClientRegistry, "parseChangeRequestUrl">,
67
+) {
68
+ const parse = (url: string) => registry.parseChangeRequestUrl(url)?.link ?? null;
69
+
70
+ function normalizeThreadPullRequestKey(key: ThreadPullRequestKeySource): ThreadPullRequestKey {
71
+ const parsed = key.url === undefined ? null : parse(key.url);
72
+ const authority =
73
+ key.authority ??
74
+ (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
75
+ ? parsed.authority
76
+ : undefined);
77
+ const canonical = canonicalRepositoryKey(
78
+ `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
79
+ );
80
+ const separator = canonical.indexOf("/");
81
+ return {
82
+ host: canonical.slice(0, separator),
83
+ repository: canonical.slice(separator + 1),
84
+ number: key.number,
85
+ };
86
+ }
87
+
88
+ function legacyThreadPullRequestKey(
89
+ linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
90
+ fallbackHost?: string,
91
+ ): ThreadPullRequestKey {
92
+ const parsed = parse(linked.url);
93
+ if (parsed !== null && parsed.number === linked.number) {
94
+ const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
95
+ if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
96
+ return normalizeThreadPullRequestKey(parsed);
97
+ }
98
+ }
99
+ let host = fallbackHost;
100
+ if (host === undefined) {
101
+ try {
102
+ host = new URL(linked.url).hostname;
103
+ } catch {
104
+ host = "unknown";
105
+ }
106
+ }
107
+ return {
108
+ host: host.trim().toLowerCase() || "unknown",
109
+ repository: linked.repository.trim().toLowerCase(),
110
+ number: linked.number,
111
+ };
112
+ }
113
+
114
+ function threadPullRequestKeysEqual(
115
+ left: ThreadPullRequestKeySource,
116
+ right: ThreadPullRequestKeySource,
117
+ ): boolean {
118
+ return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
119
+ }
120
+
121
+ // Clients re-derive chains for every link on each render, and normalizing parses the
122
+ // link's URL. Links are immutable and keep their identity until they change.
123
+ const normalizedKeys = new WeakMap<ThreadPullRequestKeySource, ThreadPullRequestKey>();
124
+
125
+ function normalizedKeyOf(key: ThreadPullRequestKeySource): ThreadPullRequestKey {
126
+ let normalized = normalizedKeys.get(key);
127
+ if (normalized === undefined) {
128
+ normalized = normalizeThreadPullRequestKey(key);
129
+ normalizedKeys.set(key, normalized);
130
+ }
131
+ return normalized;
132
+ }
133
+
134
+ function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
135
+ const normalized = normalizedKeyOf(key);
136
+ return `${normalized.host}/${normalized.repository}#${normalized.number}`;
137
+ }
138
+
139
+ function resolveThreadCurrentPullRequest(
140
+ links: ReadonlyArray<ThreadPullRequestLink>,
141
+ ): ThreadCurrentPullRequest | null {
142
+ const visible = visibleThreadPullRequests(links);
143
+ if (visible.length === 0) return null;
144
+ const open = visible.filter(isOpen);
145
+ if (open.length === 1) return { kind: "single", link: open[0]! };
146
+ const chains = resolveThreadPullRequestChains(visible);
147
+ if (open.length > 1) {
148
+ const openChains = chains
149
+ .map((chain) => layersFromTop(chain).filter(isOpen))
150
+ .filter((layers) => layers.length > 0)
151
+ .sort(
152
+ (left, right) =>
153
+ Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
154
+ Math.max(...left.map((link) => Date.parse(link.linkedAt))),
155
+ );
156
+ const ordered = openChains.flat();
157
+ return { kind: "stack", open: ordered, top: ordered[0]! };
158
+ }
159
+ if (chains.length === 1) {
160
+ return { kind: "single", link: layersFromTop(chains[0]!)[0]! };
161
+ }
162
+ const terminal = [...visible].sort(
163
+ (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
164
+ );
165
+ return { kind: "single", link: terminal[0]! };
166
+ }
167
+
168
+ function resolveThreadCurrentPullRequestLink(
169
+ links: ReadonlyArray<ThreadPullRequestLink>,
170
+ ): ThreadPullRequestLink | null {
171
+ const current = resolveThreadCurrentPullRequest(links);
172
+ if (current === null) return null;
173
+ return current.kind === "single" ? current.link : current.top;
174
+ }
175
+
176
+ function resolveThreadPullRequestChains(
177
+ links: ReadonlyArray<ThreadPullRequestLink>,
178
+ ): ReadonlyArray<ThreadPullRequestChain> {
179
+ const visible = visibleThreadPullRequests(links);
180
+ const chains: Array<ThreadPullRequestChain> = [];
181
+ const placed = new Set<string>();
182
+
183
+ const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
184
+ for (const link of visible) {
185
+ if (link.stack === null) continue;
186
+ const key = normalizedKeyOf(link);
187
+ const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
188
+ const members = nativeStacks.get(stackKey) ?? [];
189
+ members.push(link);
190
+ nativeStacks.set(stackKey, members);
191
+ }
192
+ for (const members of nativeStacks.values()) {
193
+ // Saved snapshots can lag behind newer members of the same stack.
194
+ const memberNumbers = new Set(members.map((member) => member.number));
195
+ let layers = members[0]!.stack!.layers;
196
+ let coverage = layers.filter((layer) => memberNumbers.has(layer.number)).length;
197
+ for (const member of members.slice(1)) {
198
+ const candidate = member.stack!.layers;
199
+ const candidateCoverage = candidate.filter((layer) =>
200
+ memberNumbers.has(layer.number),
201
+ ).length;
202
+ if (
203
+ candidateCoverage > coverage ||
204
+ (candidateCoverage === coverage && candidate.length > layers.length)
205
+ ) {
206
+ layers = candidate;
207
+ coverage = candidateCoverage;
208
+ }
209
+ }
210
+ const order = new Map(layers.map((layer, index) => [layer.number, index]));
211
+ members.sort(
212
+ (left, right) =>
213
+ (order.get(left.number) ?? layers.length) - (order.get(right.number) ?? layers.length),
214
+ );
215
+ for (const member of members) placed.add(threadPullRequestKeyOf(member));
216
+ chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
217
+ }
218
+
219
+ const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
220
+ const branchKey = (link: ThreadPullRequestLink, branch: string) => {
221
+ const key = normalizedKeyOf(link);
222
+ return `${key.host}/${key.repository}:${branch}`;
223
+ };
224
+ const byHead = new Map<string, ThreadPullRequestLink | null>();
225
+ for (const link of remaining) {
226
+ if (link.snapshot === null) continue;
227
+ const key = branchKey(link, link.snapshot.headBranch);
228
+ byHead.set(key, byHead.has(key) ? null : link);
229
+ }
230
+ const parentOf = (link: ThreadPullRequestLink) => {
231
+ if (link.snapshot === null) return undefined;
232
+ const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
233
+ return parent == null || parent === link ? undefined : parent;
234
+ };
235
+ const children = new Map<string, Array<ThreadPullRequestLink>>();
236
+ for (const link of remaining) {
237
+ const parent = parentOf(link);
238
+ if (parent === undefined) continue;
239
+ const key = threadPullRequestKeyOf(parent);
240
+ const siblings = children.get(key) ?? [];
241
+ siblings.push(link);
242
+ children.set(key, siblings);
243
+ }
244
+ for (const base of remaining) {
245
+ if (parentOf(base) !== undefined) continue;
246
+ const layers: Array<ThreadPullRequestLink> = [];
247
+ const depths: Array<number> = [];
248
+ const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
249
+ { link: base, depth: 0 },
250
+ ];
251
+ for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
252
+ const key = threadPullRequestKeyOf(next.link);
253
+ // Two links with one identity would otherwise share a child list and expand forever.
254
+ if (placed.has(key)) continue;
255
+ placed.add(key);
256
+ layers.push(next.link);
257
+ depths.push(next.depth);
258
+ const below = children.get(key) ?? [];
259
+ for (let index = below.length - 1; index >= 0; index -= 1) {
260
+ pending.push({ link: below[index]!, depth: next.depth + 1 });
261
+ }
262
+ }
263
+ if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
264
+ }
265
+ for (const link of remaining) {
266
+ if (!placed.has(threadPullRequestKeyOf(link))) {
267
+ chains.push({ kind: "derived", layers: [link], depths: [0] });
268
+ }
269
+ }
270
+ return chains;
271
+ }
272
+
273
+ function resolveThreadPullRequestBadge(
274
+ pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
275
+ ): ThreadPullRequestBadge | null {
276
+ const visible = visibleThreadPullRequests(pullRequests ?? []);
277
+ if (visible.length === 0) return null;
278
+ const states = visible.map((link) => link.snapshot?.state ?? "open");
279
+ const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
280
+ ? "draft"
281
+ : states.includes("open")
282
+ ? "open"
283
+ : states.every((entry) => entry === "merged")
284
+ ? "merged"
285
+ : "closed";
286
+ const chains = resolveThreadPullRequestChains(visible);
287
+ if (visible.length > 1 && chains.length === 1) {
288
+ return { kind: "stack", layers: visible.length, state };
289
+ }
290
+ return { kind: "pull-request", others: visible.length - 1, state };
291
+ }
292
+
293
+ /** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
294
+ function threadPullRequestsOf(thread: {
295
+ readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
296
+ readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
297
+ }): ReadonlyArray<ThreadPullRequestLink> {
298
+ if (thread.pullRequests !== undefined) return thread.pullRequests;
299
+ const linked = thread.linkedPullRequest;
300
+ return linked == null
301
+ ? []
302
+ : [
303
+ {
304
+ ...legacyThreadPullRequestKey(linked),
305
+ url: linked.url,
306
+ source: "manual",
307
+ linkedAt: "1970-01-01T00:00:00.000Z",
308
+ snapshot: null,
309
+ stack: null,
310
+ },
311
+ ];
312
+ }
313
+
314
+ function applyThreadPullRequestLinkUpdate(
315
+ thread: OrchestrationV2AppThread,
316
+ updated: ThreadPullRequestLink,
317
+ ): OrchestrationV2AppThread {
318
+ return {
319
+ ...thread,
320
+ pullRequests: threadPullRequestsOf(thread).map((link) =>
321
+ threadPullRequestKeysEqual(link, updated) ? updated : link,
322
+ ),
323
+ };
324
+ }
325
+
326
+ return {
327
+ normalizeThreadPullRequestKey,
328
+ legacyThreadPullRequestKey,
329
+ threadPullRequestKeysEqual,
330
+ threadPullRequestKeyOf,
331
+ resolveThreadCurrentPullRequest,
332
+ resolveThreadCurrentPullRequestLink,
333
+ resolveThreadPullRequestChains,
334
+ resolveThreadPullRequestBadge,
335
+ threadPullRequestsOf,
336
+ applyThreadPullRequestLinkUpdate,
337
+ };
338
+}
339
+
340
+export interface PullRequestListLine {
341
+ readonly link: ThreadPullRequestLink;
342
+ readonly depth: number;
343
+ readonly chainKey: string;
344
+ readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
345
+}
346
+
347
+function chainKeyOf(chain: ThreadPullRequestChain): string {
348
+ const bottom = chain.layers[0]!;
349
+ return `${bottom.host}/${bottom.repository}#${bottom.number}`;
350
+}
351
+
352
+export function pullRequestListLines(
353
+ chains: ReadonlyArray<ThreadPullRequestChain>,
354
+): ReadonlyArray<PullRequestListLine> {
355
+ const ordered = [...chains].sort(
356
+ (left, right) =>
357
+ Math.max(...right.layers.map(latestUpdatedAt)) -
358
+ Math.max(...left.layers.map(latestUpdatedAt)),
359
+ );
360
+ return ordered.flatMap((chain) => {
361
+ const chainKey = chainKeyOf(chain);
362
+ return chain.layers.map((link, index) => ({
363
+ link,
364
+ depth: chain.depths[index]!,
365
+ chainKey,
366
+ stack:
367
+ index === 0 && chain.layers.length > 1
368
+ ? { kind: chain.kind, size: chain.layers.length }
369
+ : null,
370
+ }));
371
+ });
372
+}
packages/source-control-core/src/server/driver.ts
+3
@@ -1,6 +1,8 @@
1
import type { SourceControlProviderKind } from "@t3tools/contracts";
2
import type * as Effect from "effect/Effect";
3
4
+import type { SourceControlClientDefinition } from "../client/definition.ts";
5
+
6
import type { SourceControlProviderDiscoverySpec } from "./discovery.ts";
7
import type { PullRequestProviderApi } from "./PullRequestProvider.ts";
8
import type * as SourceControlProvider from "./SourceControlProvider.ts";
@@ -14,6 +16,7 @@ export interface SourceControlDriverInstance {
16
17
export interface SourceControlDriver<R = never> {
18
readonly kind: SourceControlProviderKind;
19
+ readonly definition: SourceControlClientDefinition;
20
readonly make: Effect.Effect<SourceControlDriverInstance, never, R>;
21
}
22
packages/source-control-forgejo/src/client/definition.test.ts
new
+104
@@ -0,0 +1,104 @@
1
+import type { ChangeRequestProjectIdentity } from "@t3tools/source-control-core/client/definition";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { definition } from "./definition.ts";
5
+
6
+const parse = (url: string) => definition.parseChangeRequestUrl(new URL(url))!;
7
+
8
+const identity = (
9
+ remoteUrl: string,
10
+ fields: Partial<ChangeRequestProjectIdentity> = {},
11
+): ChangeRequestProjectIdentity => ({
12
+ canonicalKey: "forge.example/git/team/repo",
13
+ displayName: "git/team/repo",
14
+ locator: { source: "git-remote", remoteName: "origin", remoteUrl },
15
+ ...fields,
16
+});
17
+
18
+const onHost = (project: ChangeRequestProjectIdentity, link: ReturnType<typeof parse>) =>
19
+ definition.isChangeRequestInRepository(project, link) ||
20
+ definition.canReadChangeRequestOnHost(project, link);
21
+
22
+describe("Forgejo change request URLs", () => {
23
+ it("reads nested paths and keeps the server's port as the authority", () => {
24
+ expect(parse("http://git.example.test:3000/Team/Repo/pulls/42/files")).toEqual({
25
+ host: "git.example.test",
26
+ authority: "git.example.test:3000",
27
+ repository: "team/repo",
28
+ number: 42,
29
+ repositoryUrl: "http://git.example.test:3000/Team/Repo",
30
+ });
31
+ expect(parse("https://github.internal/team/repo/pulls/7")).toMatchObject({
32
+ host: "github.internal",
33
+ authority: "github.internal",
34
+ });
35
+ });
36
+
37
+ it("claims only its own route", () => {
38
+ for (const url of [
39
+ "https://forge.example/team/repo/pull/7",
40
+ "https://forge.example/repo/pulls/7",
41
+ "https://forge.example/team/repo/pulls/abc",
42
+ ]) {
43
+ expect(definition.parseChangeRequestUrl(new URL(url)), url).toBeNull();
44
+ }
45
+ });
46
+
47
+ it.each([
48
+ ["http://forge.example:3000/git/owner/repo.git", "http://forge.example:3000"],
49
+ ["git@forge.example:git/owner/repo.git", "https://forge.example"],
50
+ ["http://other.example:3000/git/owner/repo.git", "https://forge.example"],
51
+ ])("keeps the matching web origin from %s", (remoteUrl, origin) => {
52
+ expect(
53
+ definition.changeRequestUrl({
54
+ host: "forge.example",
55
+ repository: "git/owner/repo",
56
+ number: 42,
57
+ remoteUrl,
58
+ }),
59
+ ).toBe(`${origin}/git/owner/repo/pulls/42`);
60
+ });
61
+
62
+ it("keeps the origin when the host already carries its port", () => {
63
+ expect(
64
+ definition.changeRequestUrl({
65
+ host: "forge.example:3000",
66
+ repository: "team/repo",
67
+ number: 42,
68
+ remoteUrl: "http://forge.example:3000/team/repo.git",
69
+ }),
70
+ ).toBe("http://forge.example:3000/team/repo/pulls/42");
71
+ });
72
+
73
+ it("matches projects by HTTP port at repository and host level", () => {
74
+ const [atThree, atFour] = [3000, 4000].map((port) =>
75
+ identity(`http://forge.example:${port}/git/team/repo.git`),
76
+ );
77
+ const link = parse("http://forge.example:4000/git/team/repo/pulls/42");
78
+ expect(definition.isChangeRequestInRepository(atFour!, link)).toBe(true);
79
+ expect(onHost(atFour!, { ...link, repository: "git/team/other" })).toBe(true);
80
+ expect(definition.isChangeRequestInRepository(atThree!, link)).toBe(false);
81
+ expect(onHost(atThree!, link)).toBe(false);
82
+ });
83
+
84
+ it("lets tea resolve the web port for SSH remotes, and honours a resolved web URL", () => {
85
+ const link = parse("http://forge.example:4000/git/team/repo/pulls/42");
86
+ expect(
87
+ definition.isChangeRequestInRepository(identity("git@forge.example:git/team/repo.git"), link),
88
+ ).toBe(true);
89
+ const aliased = identity("git@ssh.forge.example:team/repo.git", {
90
+ canonicalKey: "ssh.forge.example/team/repo",
91
+ displayName: "team/repo",
92
+ webUrl: "http://forge.example:4000/git/team/repo",
93
+ });
94
+ expect(definition.isChangeRequestInRepository(aliased, link)).toBe(true);
95
+ expect(onHost(aliased, { ...link, repository: "git/team/other" })).toBe(true);
96
+ for (const url of [
97
+ "http://other.example:4000/git/team/repo/pulls/42",
98
+ "http://forge.example:3000/git/team/repo/pulls/42",
99
+ "http://forge.example:4000/other/team/repo/pulls/42",
100
+ ]) {
101
+ expect(onHost(aliased, parse(url)), url).toBe(false);
102
+ }
103
+ });
104
+});
packages/source-control-forgejo/src/client/definition.ts
+15
-16
@@ -1,17 +1,22 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
+ changeRequestUrlBelow,
4
type ChangeRequestProjectIdentity,
5
defineSourceControlClient,
6
isChangeRequestAuthorityOfProject,
7
isChangeRequestInProjectRepository,
8
isChangeRequestOnProjectHost,
8
- isChangeRequestPath,
9
+ parseChangeRequestPath,
10
+ remoteWebOrigin,
11
} from "@t3tools/source-control-core/client/definition";
12
13
const CHECKOUT_COMMAND = /^tea\s+(?:pr|pulls)\s+checkout\s+(.+)$/i;
14
const CHANGE_REQUEST_REFERENCE =
15
/^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)+[^/\s]+\/pulls\/(\d+)(?:[/?#].*)?$/i;
16
17
+// Forgejo and Gitea run on any hostname, possibly mounted below a path.
18
+const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u;
19
+
20
const KIND = SourceControlProviderKind.make("forgejo");
21
22
/**
@@ -43,20 +48,16 @@ export const definition = defineSourceControlClient({
48
defaultCloneTransport: "https",
49
// The server's resolved web URL wins; otherwise an HTTP remote on the same host names the
50
// origin, which may carry a port. SSH remotes say nothing about the web origin.
46
- changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {
47
- if (webUrl) return `${webUrl.replace(/\/+$/, "")}/pulls/${number}`;
48
- try {
49
- const remote = new URL(remoteUrl ?? "");
50
- if (
51
- (remote.protocol === "http:" || remote.protocol === "https:") &&
52
- (remote.hostname.toLowerCase() === host.toLowerCase() ||
53
- remote.host.toLowerCase() === host.toLowerCase())
54
- ) {
55
- return `${remote.origin}/${repository}/pulls/${number}`;
56
- }
57
- } catch {}
58
- return `https://${host}/${repository}/pulls/${number}`;
51
+ changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) =>
52
+ webUrl
53
+ ? changeRequestUrlBelow(webUrl, `pulls/${number}`)
54
+ : `${remoteWebOrigin(host, remoteUrl)}/${repository}/pulls/${number}`,
55
+ // A server's identity includes its port, so the link carries it.
56
+ parseChangeRequestUrl: (url) => {
57
+ const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
58
+ return link === null ? null : { ...link, authority: url.host.toLowerCase() };
59
},
60
+ changeRequestUrlFromReferenceAutolink: () => null,
61
changeRequestActions: new Set(["merge", "close", "reopen", "update-branch"] as const),
62
// Neither `fj` nor `tea` checks out by number, so fetch the pull ref from the repository itself.
63
checkoutCommand: ({ number, repositoryUrl }) =>
@@ -69,7 +70,6 @@ export const definition = defineSourceControlClient({
70
reviewSummaryRequired: (verdict) => verdict === "request-changes",
71
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
72
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
72
- changeRequestUrlHost: (url) => url.host,
73
checkoutChangeRequestHost: () => null,
74
isChangeRequestInRepository: (identity, link) => {
75
if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
@@ -94,5 +94,4 @@ export const definition = defineSourceControlClient({
94
(!mount || link.repository.toLowerCase().startsWith(`${mount.toLowerCase()}/`))
95
);
96
},
97
- isChangeRequestUrl: (url) => isChangeRequestPath(url, "/pulls/"),
97
});
packages/source-control-forgejo/src/server/driver.ts
+4
-2
@@ -1,12 +1,14 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
1
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
2
import * as Effect from "effect/Effect";
3
4
+import { definition } from "../client/definition.ts";
5
+
6
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
7
import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
8
9
export const driver = defineSourceControlDriver({
9
- kind: SourceControlProviderKind.make("forgejo"),
10
+ kind: definition.kind,
11
+ definition,
12
make: Effect.all({
13
sourceControl: ForgejoSourceControlProvider.make,
14
discovery: ForgejoSourceControlProvider.makeDiscovery,
packages/source-control-gitcafe/src/client/definition.test.ts
new
+49
@@ -0,0 +1,49 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { definition } from "./definition.ts";
4
+
5
+const parse = (url: string) => definition.parseChangeRequestUrl(new URL(url));
6
+
7
+describe("GitCafe change request URLs", () => {
8
+ it("reads its canonical /pull/ path and the older /pulls/ path on its own hosts", () => {
9
+ for (const path of ["pull", "pulls"]) {
10
+ expect(parse(`https://git.cafe/PingDotGG/T3Code/${path}/23897`), path).toEqual({
11
+ host: "git.cafe",
12
+ repository: "pingdotgg/t3code",
13
+ number: 23897,
14
+ repositoryUrl: "https://git.cafe/PingDotGG/T3Code",
15
+ });
16
+ }
17
+ expect(parse("https://staging.git.cafe/team/repo/pull/7/files")).toMatchObject({
18
+ host: "staging.git.cafe",
19
+ repository: "team/repo",
20
+ number: 7,
21
+ });
22
+ });
23
+
24
+ it("leaves other hosts and routes alone", () => {
25
+ for (const url of [
26
+ "https://github.com/team/repo/pull/7",
27
+ "https://forge.example/team/repo/pulls/7",
28
+ "https://git.cafe/pingdotgg/t3code/issues/23897",
29
+ "https://git.cafe/pingdotgg/t3code/pull/abc",
30
+ "https://git.cafe/pingdotgg/t3code",
31
+ ]) {
32
+ expect(parse(url), url).toBeNull();
33
+ }
34
+ });
35
+
36
+ it("builds pull request URLs below the repository", () => {
37
+ expect(
38
+ definition.changeRequestUrl({ host: "git.cafe", repository: "team/repo", number: 8 }),
39
+ ).toBe("https://git.cafe/team/repo/pulls/8");
40
+ expect(
41
+ definition.changeRequestUrl({
42
+ host: "git.cafe",
43
+ repository: "team/repo",
44
+ number: 8,
45
+ webUrl: "https://git.cafe/Team/Repo/",
46
+ }),
47
+ ).toBe("https://git.cafe/Team/Repo/pulls/8");
48
+ });
49
+});
packages/source-control-gitcafe/src/client/definition.ts
+16
-15
@@ -7,15 +7,19 @@ import {
7
import * as Effect from "effect/Effect";
8
import * as Schema from "effect/Schema";
9
import {
10
+ changeRequestUrlBelow,
11
defineSourceControlClient,
12
isChangeRequestInProjectRepository,
13
isChangeRequestOnProjectHost,
13
- isChangeRequestPath,
14
+ parseChangeRequestPath,
15
} from "@t3tools/source-control-core/client/definition";
16
17
/** GitCafe has no self-hosted installs: production and staging are its only hosts. */
18
const GITCAFE_HOSTS = new Set(["git.cafe", "staging.git.cafe"]);
19
20
+/** GitCafe serves pull requests at `/pull/<n>` and redirects the older `/pulls/<n>` there. */
21
+const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pulls?\/(\d+)(?:\/|$)/u;
22
+
23
const KIND = SourceControlProviderKind.make("gitcafe");
24
25
export const settings = makeProviderSettingsSchema({
@@ -44,8 +48,17 @@ export const definition = defineSourceControlClient({
48
publishHost: () => "git.cafe",
49
newRepositoryOwner: (account) => (account ? { owner: account } : null),
50
defaultCloneTransport: "ssh",
47
- changeRequestUrl: ({ host, repository, number }) =>
48
- `https://${host}/${repository}/pulls/${number}`,
51
+ changeRequestUrl: ({ host, repository, number, webUrl }) =>
52
+ webUrl
53
+ ? changeRequestUrlBelow(webUrl, `pulls/${number}`)
54
+ : `https://${host}/${repository}/pulls/${number}`,
55
+ // `/pull/` and `/pulls/` are GitHub's and Forgejo's shapes too, so only GitCafe's own hosts
56
+ // claim them.
57
+ parseChangeRequestUrl: (url) =>
58
+ GITCAFE_HOSTS.has(url.hostname.toLowerCase())
59
+ ? parseChangeRequestPath(url, CHANGE_REQUEST_PATH)
60
+ : null,
61
+ changeRequestUrlFromReferenceAutolink: () => null,
62
changeRequestActions: new Set([
63
"ready",
64
"draft",
@@ -58,24 +71,12 @@ export const definition = defineSourceControlClient({
71
authorProfileUrl: () => null,
72
referenceAutolinkRepositoryUrl: () => null,
73
reviewSummaryRequired: () => false,
61
- // `/pulls/` is Forgejo's shape too, so only GitCafe's own hosts claim it.
74
checkoutCommandArgument: () => null,
75
isChangeRequestReference: () => false,
64
- changeRequestUrlHost: (url) => url.hostname,
76
checkoutChangeRequestHost: () => null,
77
isChangeRequestInRepository: (identity, link) =>
78
isChangeRequestInProjectRepository(KIND, identity, link),
79
canReadChangeRequestOnHost: (identity, link) =>
80
isChangeRequestOnProjectHost(KIND, identity, link),
70
- isChangeRequestUrl: (url) => {
71
- try {
72
- return (
73
- GITCAFE_HOSTS.has(new URL(url).hostname.toLowerCase()) &&
74
- (isChangeRequestPath(url, "/pull/") || isChangeRequestPath(url, "/pulls/"))
75
- );
76
- } catch {
77
- return false;
78
- }
79
- },
81
settings,
82
});
packages/source-control-gitcafe/src/server/driver.ts
+4
-2
@@ -1,12 +1,14 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
1
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
2
import * as Effect from "effect/Effect";
3
4
+import { definition } from "../client/definition.ts";
5
+
6
import * as GitCafePullRequestProvider from "./GitCafePullRequestProvider.ts";
7
import * as GitCafeSourceControlProvider from "./GitCafeSourceControlProvider.ts";
8
9
export const driver = defineSourceControlDriver({
9
- kind: SourceControlProviderKind.make("gitcafe"),
10
+ kind: definition.kind,
11
+ definition,
12
make: Effect.all({
13
sourceControl: GitCafeSourceControlProvider.make,
14
discovery: GitCafeSourceControlProvider.makeDiscovery,
packages/source-control-github/src/client/definition.test.ts
new
+96
@@ -0,0 +1,96 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { definition } from "./definition.ts";
4
+
5
+const parse = (url: string) => definition.parseChangeRequestUrl(new URL(url));
6
+
7
+describe("GitHub change request URLs", () => {
8
+ it("reads a pull request on any host, lower-casing host and repository", () => {
9
+ expect(parse("https://github.com/T3Tools/T3Code/pull/123/files?w=1#diff")).toEqual({
10
+ host: "github.com",
11
+ repository: "t3tools/t3code",
12
+ number: 123,
13
+ repositoryUrl: "https://github.com/T3Tools/T3Code",
14
+ });
15
+ expect(parse("https://GHE.Example.com:8443/acme/web/pull/42/")).toEqual({
16
+ host: "ghe.example.com",
17
+ repository: "acme/web",
18
+ number: 42,
19
+ repositoryUrl: "https://ghe.example.com:8443/acme/web",
20
+ });
21
+ });
22
+
23
+ it("claims only the two-segment pull route", () => {
24
+ for (const url of [
25
+ "https://github.com/t3tools/t3code/issues/123",
26
+ "https://github.com/t3tools/t3code/pulls/123",
27
+ "https://github.com/t3tools/t3code/pull/abc",
28
+ "https://github.com/t3tools/t3code/pull/0",
29
+ "https://github.com/group/sub/repo/pull/1",
30
+ "ftp://github.com/t3tools/t3code/pull/1",
31
+ ]) {
32
+ expect(parse(url), url).toBeNull();
33
+ }
34
+ });
35
+
36
+ it("builds pull request URLs below the repository, keeping an HTTP remote's origin", () => {
37
+ expect(
38
+ definition.changeRequestUrl({
39
+ host: "github.acme.test",
40
+ repository: "platform/api",
41
+ number: 7,
42
+ remoteUrl: "http://token@github.acme.test:8443/team/default.git",
43
+ }),
44
+ ).toBe("http://github.acme.test:8443/platform/api/pull/7");
45
+ for (const remoteUrl of [
46
+ "git@github.acme.test:team/default.git",
47
+ "git://github.acme.test/team/default.git",
48
+ "http://other.test/team/default.git",
49
+ ]) {
50
+ expect(
51
+ definition.changeRequestUrl({
52
+ host: "github.acme.test",
53
+ repository: "platform/api",
54
+ number: 9,
55
+ remoteUrl,
56
+ }),
57
+ remoteUrl,
58
+ ).toBe("https://github.acme.test/platform/api/pull/9");
59
+ }
60
+ expect(
61
+ definition.changeRequestUrl({
62
+ host: "github.com",
63
+ repository: "pull/1",
64
+ number: 43,
65
+ webUrl: "https://github.com/pull/1",
66
+ }),
67
+ ).toBe("https://github.com/pull/1/pull/43");
68
+ });
69
+
70
+ // regression: #8507 the browser fallback must not open a bogus URL
71
+ it("builds nothing from an invalid repository, number, or host", () => {
72
+ for (const [host, repository, number] of [
73
+ ["github.com", "acme", 1],
74
+ ["github.com", "../repository", 1],
75
+ ["github.com", "acme/%2e%2e", 1],
76
+ ["github.com", "acme/repository?tab=1", 1],
77
+ ["github.com", "acme/repository", 0],
78
+ ["bad host", "acme/repository", 1],
79
+ ] as const) {
80
+ expect(definition.changeRequestUrl({ host, repository, number })).toBeNull();
81
+ }
82
+ });
83
+
84
+ it("turns GitHub's shared issue route into a pull request candidate", () => {
85
+ const candidate = (url: string) =>
86
+ definition.changeRequestUrlFromReferenceAutolink(new URL(url));
87
+ expect(candidate("https://github.com/pingdotgg/t3code/issues/8600#issuecomment-1")).toBe(
88
+ "https://github.com/pingdotgg/t3code/pull/8600#issuecomment-1",
89
+ );
90
+ expect(candidate("https://code.github.example.com/acme/web/issues/42")).toBe(
91
+ "https://code.github.example.com/acme/web/pull/42",
92
+ );
93
+ expect(candidate("https://github.com/pingdotgg/t3code/issues/not-a-number")).toBeNull();
94
+ expect(candidate("https://code.example.test/acme/web/issues/42")).toBeNull();
95
+ });
96
+});
packages/source-control-github/src/client/definition.ts
+44
-5
@@ -10,18 +10,42 @@ import {
10
import * as Effect from "effect/Effect";
11
import * as Schema from "effect/Schema";
12
import {
13
+ changeRequestUrlBelow,
14
defineSourceControlClient,
15
isChangeRequestInProjectRepository,
16
isChangeRequestOnProjectHost,
16
- isChangeRequestPath,
17
+ parseChangeRequestPath,
18
+ remoteWebOrigin,
19
} from "@t3tools/source-control-core/client/definition";
20
21
const CHECKOUT_COMMAND = /^gh\s+pr\s+checkout\s+(.+)$/i;
22
const CHANGE_REQUEST_REFERENCE =
23
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
24
25
+// GitHub Enterprise Server runs on any hostname, so the `<owner>/<repo>/pull/<n>` route alone
26
+// identifies a GitHub pull request.
27
+const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u;
28
+const ISSUE_PATH = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u;
29
+
30
const KIND = SourceControlProviderKind.make("github");
31
32
+function isGitHubHost(hostname: string): boolean {
33
+ const host = hostname.toLowerCase();
34
+ return (
35
+ host === "github.com" || host.endsWith(".github.com") || host.split(".").includes("github")
36
+ );
37
+}
38
+
39
+function isRepositoryPath(repository: string): boolean {
40
+ const segments = repository.split("/");
41
+ return (
42
+ segments.length === 2 &&
43
+ // GitHub owner and repository names are only these characters, so nothing here can
44
+ // be an encoded dot segment, query or fragment that `new URL` would reinterpret.
45
+ segments.every((segment) => /^[\w.-]+$/u.test(segment) && segment !== "." && segment !== "..")
46
+ );
47
+}
48
+
49
export const GitHubHostChoice = Schema.Struct({
50
account: Schema.optionalKey(TrimmedNonEmptyString),
51
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
@@ -53,8 +77,25 @@ export const definition = defineSourceControlClient({
77
publishHost: () => "github.com",
78
newRepositoryOwner: (account) => ({ owner: account }),
79
defaultCloneTransport: "https",
56
- changeRequestUrl: ({ host, repository, number }) =>
57
- `https://${host}/${repository}/pull/${number}`,
80
+ changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {
81
+ if (!Number.isSafeInteger(number) || number < 1) return null;
82
+ if (webUrl) return changeRequestUrlBelow(webUrl, `pull/${number}`);
83
+ if (!isRepositoryPath(repository)) return null;
84
+ try {
85
+ return new URL(`/${repository}/pull/${number}`, remoteWebOrigin(host, remoteUrl)).toString();
86
+ } catch {
87
+ return null;
88
+ }
89
+ },
90
+ parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
91
+ // GitHub writes every bare reference through `/issues/`, including pull requests.
92
+ changeRequestUrlFromReferenceAutolink: (url) => {
93
+ const match = isGitHubHost(url.hostname) ? ISSUE_PATH.exec(url.pathname) : null;
94
+ if (match?.[1] === undefined || match[2] === undefined) return null;
95
+ const candidate = new URL(url);
96
+ candidate.pathname = `/${match[1]}/pull/${match[2]}`;
97
+ return candidate.toString();
98
+ },
99
changeRequestActions: new Set([
100
"merge",
101
"ready",
@@ -77,12 +118,10 @@ export const definition = defineSourceControlClient({
118
reviewSummaryRequired: () => false,
119
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
120
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
80
- changeRequestUrlHost: (url) => url.hostname,
121
checkoutChangeRequestHost: (identity) => pullRequestHostOf(identity, KIND),
122
isChangeRequestInRepository: (identity, link) =>
123
isChangeRequestInProjectRepository(KIND, identity, link),
124
canReadChangeRequestOnHost: (identity, link) =>
125
isChangeRequestOnProjectHost(KIND, identity, link),
86
- isChangeRequestUrl: (url) => isChangeRequestPath(url, "/pull/"),
126
settings,
127
});
packages/source-control-github/src/server/driver.ts
+4
-2
@@ -1,12 +1,14 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
1
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
2
import * as Effect from "effect/Effect";
3
4
+import { definition } from "../client/definition.ts";
5
+
6
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
7
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
8
9
export const driver = defineSourceControlDriver({
9
- kind: SourceControlProviderKind.make("github"),
10
+ kind: definition.kind,
11
+ definition,
12
make: Effect.all({
13
sourceControl: GitHubSourceControlProvider.make,
14
discovery: GitHubSourceControlProvider.makeDiscovery,
packages/source-control-gitlab/src/client/definition.test.ts
new
+50
@@ -0,0 +1,50 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { definition } from "./definition.ts";
4
+
5
+const parse = (url: string) => definition.parseChangeRequestUrl(new URL(url));
6
+
7
+describe("GitLab change request URLs", () => {
8
+ it("reads a merge request on any host, nested groups and all", () => {
9
+ expect(parse("https://gitlab.com/t3tools/platform/t3code/-/merge_requests/42")).toEqual({
10
+ host: "gitlab.com",
11
+ repository: "t3tools/platform/t3code",
12
+ number: 42,
13
+ repositoryUrl: "https://gitlab.com/t3tools/platform/t3code",
14
+ });
15
+ expect(parse("https://code.acme.test/team/project/-/merge_requests/9")).toMatchObject({
16
+ host: "code.acme.test",
17
+ repository: "team/project",
18
+ number: 9,
19
+ });
20
+ });
21
+
22
+ it("keeps pull-like segments inside nested repository paths", () => {
23
+ expect(
24
+ parse("https://gitlab.example.test/group/pull/123/repo/-/merge_requests/42")?.repositoryUrl,
25
+ ).toBe("https://gitlab.example.test/group/pull/123/repo");
26
+ });
27
+
28
+ it("leaves issues and single-segment paths alone", () => {
29
+ expect(parse("https://gitlab.com/t3tools/t3code/-/issues/12")).toBeNull();
30
+ expect(parse("https://gitlab.com/t3code/-/merge_requests/12")).toBeNull();
31
+ });
32
+
33
+ it("builds merge request URLs below the repository", () => {
34
+ expect(
35
+ definition.changeRequestUrl({
36
+ host: "gitlab.com",
37
+ repository: "group/sub/project",
38
+ number: 4,
39
+ }),
40
+ ).toBe("https://gitlab.com/group/sub/project/-/merge_requests/4");
41
+ expect(
42
+ definition.changeRequestUrl({
43
+ host: "gitlab.com",
44
+ repository: "group/sub/project",
45
+ number: 4,
46
+ webUrl: "https://gitlab.com/group/sub/project",
47
+ }),
48
+ ).toBe("https://gitlab.com/group/sub/project/-/merge_requests/4");
49
+ });
50
+});
packages/source-control-gitlab/src/client/definition.ts
+11
-5
@@ -1,15 +1,19 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
+ changeRequestUrlBelow,
4
defineSourceControlClient,
5
isChangeRequestInProjectRepository,
6
isChangeRequestOnProjectHost,
6
- isChangeRequestPath,
7
+ parseChangeRequestPath,
8
} from "@t3tools/source-control-core/client/definition";
9
10
const CHECKOUT_COMMAND = /^glab\s+mr\s+checkout\s+(.+)$/i;
11
const CHANGE_REQUEST_REFERENCE =
12
/^https:\/\/[^/\s]*gitlab[^/\s]*\/.+\/-\/merge_requests\/(\d+)(?:[/?#].*)?$/i;
13
14
+// Self-managed GitLab runs on any hostname and nests projects in groups.
15
+const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u;
16
+
17
const KIND = SourceControlProviderKind.make("gitlab");
18
19
export const definition = defineSourceControlClient({
@@ -24,8 +28,12 @@ export const definition = defineSourceControlClient({
28
publishHost: () => "gitlab.com",
29
newRepositoryOwner: (account) => ({ owner: account }),
30
defaultCloneTransport: "ssh",
27
- changeRequestUrl: ({ host, repository, number }) =>
28
- `https://${host}/${repository}/-/merge_requests/${number}`,
31
+ changeRequestUrl: ({ host, repository, number, webUrl }) =>
32
+ webUrl
33
+ ? changeRequestUrlBelow(webUrl, `-/merge_requests/${number}`)
34
+ : `https://${host}/${repository}/-/merge_requests/${number}`,
35
+ parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
36
+ changeRequestUrlFromReferenceAutolink: () => null,
37
changeRequestActions: new Set([
38
"merge",
39
"ready",
@@ -42,11 +50,9 @@ export const definition = defineSourceControlClient({
50
reviewSummaryRequired: () => false,
51
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
52
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
45
- changeRequestUrlHost: (url) => url.hostname,
53
checkoutChangeRequestHost: () => null,
54
isChangeRequestInRepository: (identity, link) =>
55
isChangeRequestInProjectRepository(KIND, identity, link),
56
canReadChangeRequestOnHost: (identity, link) =>
57
isChangeRequestOnProjectHost(KIND, identity, link),
51
- isChangeRequestUrl: (url) => isChangeRequestPath(url, "/-/merge_requests/"),
58
});
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts
+12
-10
@@ -1,5 +1,4 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
-import { changeRequestUrlFor } from "@t3tools/shared/changeRequestUrl";
2
import {
3
detectSourceControlProviderFromGitRemoteUrl,
4
normalizeGitRemoteUrl,
@@ -16,6 +15,7 @@ import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSour
15
import * as GitLabCli from "./GitLabCli.ts";
16
import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
17
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
18
+import { definition } from "../client/definition.ts";
19
20
function makeProvider(gitlab: Partial<GitLabCli.GitLabCli["Service"]>) {
21
return GitLabSourceControlProvider.make.pipe(
@@ -166,15 +166,17 @@ it.effect.each([
166
),
167
}) ?? Effect.succeed(identity)
168
);
169
- const [host, ...repository] = refined.canonicalKey.split("/");
170
- assert.strictEqual(
171
- changeRequestUrlFor(refined.provider, host!, repository.join("/"), 42),
172
- expectedProvider === "gitlab"
173
- ? "https://code.example.test/team/repo/-/merge_requests/42"
174
- : expectedProvider === "github"
175
- ? "https://github.com/team/repo/pull/42"
176
- : null,
177
- );
169
+ if (expectedProvider === "gitlab") {
170
+ const [host, ...repository] = refined.canonicalKey.split("/");
171
+ assert.strictEqual(
172
+ definition.changeRequestUrl({
173
+ host: host!,
174
+ repository: repository.join("/"),
175
+ number: 42,
176
+ }),
177
+ "https://code.example.test/team/repo/-/merge_requests/42",
178
+ );
179
+ }
180
assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });
181
if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
182
}),
packages/source-control-gitlab/src/server/driver.ts
+4
-2
@@ -1,12 +1,14 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
1
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
2
import * as Effect from "effect/Effect";
3
4
+import { definition } from "../client/definition.ts";
5
+
6
import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
7
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
8
9
export const driver = defineSourceControlDriver({
9
- kind: SourceControlProviderKind.make("gitlab"),
10
+ kind: definition.kind,
11
+ definition,
12
make: Effect.all({
13
sourceControl: GitLabSourceControlProvider.make,
14
discovery: Effect.succeed(GitLabSourceControlProvider.discovery),