Open History to see the last commit
1import type { EnvironmentId, LocalApi, ScopedThreadRef } from "@t3tools/contracts";
2import { useNavigate } from "@tanstack/react-router";
3import * as Schema from "effect/Schema";
4import { type MouseEvent, useCallback } from "react";
5
6import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
7
8import { stackedThreadToast, toastManager } from "../components/ui/toast";
9import { readLocalApi } from "../localApi";
10import { useRightPanelStore } from "../rightPanelStore";
11import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
12
13import { useProjects, useServerConfigs } from "../state/entities";
14import { usePrimaryEnvironmentId } from "../state/environments";
15
16export class PullRequestLinkOpenError extends Schema.TaggedErrorClass<PullRequestLinkOpenError>()(
17 "PullRequestLinkOpenError",
18 {
19 targetOrigin: Schema.NullOr(Schema.String),
20 cause: Schema.Defect(),
21 },
22) {
23 static fromCause(targetUrl: string, cause: unknown): PullRequestLinkOpenError {
24 let targetOrigin: string | null = null;
25 try {
26 targetOrigin = new URL(targetUrl).origin;
27 } catch {
28 // Keep malformed URLs out of diagnostics while preserving the open failure below.
29 }
30 return new PullRequestLinkOpenError({ targetOrigin, cause });
31 }
32
33 override get message(): string {
34 return this.targetOrigin === null
35 ? "Unable to open pull request link."
36 : `Unable to open pull request link at ${this.targetOrigin}.`;
37 }
38}
39
40export async function openPullRequestLink(
41 shell: Pick<LocalApi["shell"], "openExternal">,
42 targetUrl: string,
43): Promise<void> {
44 try {
45 await shell.openExternal(targetUrl);
46 } catch (cause) {
47 throw PullRequestLinkOpenError.fromCause(targetUrl, cause);
48 }
49}
50
51/**
52 * A change request the page can open, named the way the page names one: the host below which the
53 * repository is addressed, the repository path as that host writes it, and the number.
54 *
55 * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
56 * from a git remote — lower case, no port, the full path below the host — because the page matches
57 * a link against those. Anything else opens nothing.
58 */
59export interface ChangeRequestLink {
60 readonly host: string;
61 readonly repository: string;
62 readonly number: number;
63}
64
65/** The host itself, one of its subdomains, or an install named after the provider. */
66function isHostOf(hostname: string, apex: string, label?: string): boolean {
67 if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
68 return label !== undefined && hostname.startsWith(`${label}.`);
69}
70
71/**
72 * The repository and number behind a change request URL on a host the page can read, or null for
73 * anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
74 * ordinary link. Null means the system browser, so a doubtful match is worse than no match: it
75 * takes the reader out of their browser and into a page that cannot find the change request.
76 *
77 * Each host is recognised by the path shape it alone uses, guarded by a hostname it could
78 * plausibly be served from, since self-hosted installs are named whatever their admin chose:
79 * GitLab's `/-/` marker is unique enough to trust on any hostname, while `/pull/` is generic
80 * enough that it is only believed from a GitHub-ish host.
81 */
82export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
83 let url: URL;
84 try {
85 url = new URL(targetUrl);
86 } catch {
87 return null;
88 }
89 // `javascript:`, `mailto:` and friends have no host to speak of and nothing to open.
90 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
91 // Nothing here tries to tell a lookalike hostname from a real one — `github.com.evil.test`,
92 // `github.com-evil.test` and the rest are an open set, and blocking spellings of it costs real
93 // hosts (`gitlab.com.br` is a registrable domain, not a disguise). What a claim is worth is
94 // decided where it is used: only a link matching a repository this workspace has checked out
95 // opens the page, and everything else stays the ordinary link it was.
96 const host = url.hostname.toLowerCase();
97
98 // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
99 if (isHostOf(host, "github.com", "github")) {
100 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
101 return claim(host, match);
102 }
103 // GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
104 // separator is GitLab's own, so the hostname is not asked about.
105 const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
106 if (gitlab) return claim(host, gitlab);
107 // Bitbucket Cloud: /{workspace}/{repo}/pull-requests/{n}
108 if (isHostOf(host, "bitbucket.org", "bitbucket")) {
109 const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
110 return claim(host, match);
111 }
112 // Azure DevOps, both the current host and the per-organisation one it replaced. `_git` is part
113 // of the repository path there, as it is in the remote URL the identity is read from.
114 if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
115 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
116 return claim(host, match);
117 }
118 return null;
119}
120
121function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
122 const repository = match?.[1];
123 const number = Number(match?.[2]);
124 return repository && Number.isSafeInteger(number) && number > 0
125 ? { host, repository: repository.toLowerCase(), number }
126 : null;
127}
128
129/**
130 * Returns a click handler that opens a pull request URL in the system browser.
131 *
132 * Stops event propagation/default so activating the link does not also trigger
133 * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a
134 * toast when the local API is unavailable or the open fails.
135 */
136/**
137 * The project a link belongs to, or nothing. Matched the way the server matches: the repository
138 * identity is the full path below the host where one was recorded — which is what nested GitLab
139 * groups and Azure project paths need — and the host is the first segment of the canonical
140 * remote, so github.com and an Enterprise install stay apart.
141 */
142export function findProjectForChangeRequest(
143 projects: ReadonlyArray<EnvironmentProject>,
144 link: ChangeRequestLink,
145): EnvironmentProject | undefined {
146 return projects.find((project) => {
147 const identity = project.repositoryIdentity;
148 if (!identity) return false;
149 const kind = identity.provider as SourceControlProviderKind | undefined;
150 if (kind === undefined) return false;
151 const repository =
152 identity.displayName ??
153 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
154 return (
155 repository !== null &&
156 repository.toLowerCase() === link.repository.toLowerCase() &&
157 pullRequestHostOf(identity, kind) === link.host.toLowerCase()
158 );
159 });
160}
161
162/**
163 * Opens a change request link on the page, and says whether it did. Anything else — another
164 * organisation's repository, a host nothing here is checked out from, a link that merely looks
165 * like one — is left alone for the caller to handle as the ordinary link it is.
166 *
167 * Resolving the project here rather than on the page is what makes recognising a URL safe: a
168 * lookalike hostname matches no project and stays a link, and the page is handed the project
169 * rather than a host to narrow its whole list by.
170 *
171 * Given a thread, the link opens beside it in the right panel instead of taking the whole app to
172 * the pull requests page: a reader following a link the agent wrote is reading the thread, and
173 * should still be reading it afterwards. Any change request opens there, not only the thread's
174 * own, since the panel is told which one to show.
175 */
176export function shouldOpenPullRequestExternally(
177 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey">,
178): boolean {
179 return event.metaKey || event.ctrlKey;
180}
181
182export function useOpenChangeRequestLink(
183 threadRef?: ScopedThreadRef,
184): (
185 event: Pick<
186 MouseEvent<HTMLElement>,
187 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
188 >,
189 targetUrl: string,
190 targetThreadRef?: ScopedThreadRef,
191) => boolean {
192 const navigate = useNavigate();
193 const allProjects = useProjects();
194 const serverConfigs = useServerConfigs();
195 const primaryEnvironmentId = usePrimaryEnvironmentId();
196 return useCallback(
197 (event, targetUrl, targetThreadRef) => {
198 if (shouldOpenPullRequestExternally(event)) return false;
199 const resolvedThreadRef = targetThreadRef ?? threadRef;
200 const parsed = parseChangeRequestUrl(targetUrl);
201 if (parsed === null) return false;
202 const reads = (environmentId: string) =>
203 serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
204 true;
205 // Beside a thread the panel reads on that thread's environment, so a project from another
206 // one could not be read there whatever its remote says: two environments can hold the same
207 // repository, and handing the panel the wrong one's id opens a surface that never loads.
208 //
209 // The page has no such tie — it lists every server at once — so the link is resolved
210 // against all of them, the primary first where two hold the same repository.
211 const projects = resolvedThreadRef
212 ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
213 : allProjects
214 .filter((project) => reads(project.environmentId))
215 .toSorted(
216 (left, right) =>
217 Number(right.environmentId === primaryEnvironmentId) -
218 Number(left.environmentId === primaryEnvironmentId),
219 );
220 const project = findProjectForChangeRequest(projects, parsed);
221 if (project === undefined || !reads(project.environmentId)) return false;
222 event.preventDefault();
223 event.stopPropagation();
224 if (resolvedThreadRef) {
225 useRightPanelStore.getState().openPullRequest(resolvedThreadRef, {
226 projectId: project.id,
227 // The identity's own spelling, not the one read out of the URL: the panel asks the
228 // provider for this repository, while matching a link only ever compares lower case.
229 repository: project.repositoryIdentity?.displayName ?? parsed.repository,
230 number: parsed.number,
231 });
232 return true;
233 }
234 void navigate({
235 to: "/pull-requests",
236 search: {
237 involvement: "all",
238 // Every state, so the pull request being opened is also in the list behind it whether
239 // it is open, merged or closed.
240 state: "all",
241 repository: parsed.repository,
242 number: parsed.number,
243 selectedProjectId: project.id,
244 // Named so the page opens the right one of two servers holding this project.
245 selectedEnvironmentId: project.environmentId,
246 },
247 });
248 return true;
249 },
250 [allProjects, navigate, primaryEnvironmentId, serverConfigs, threadRef],
251 );
252}
253
254export function useOpenPrLink(threadRef?: ScopedThreadRef) {
255 const openChangeRequest = useOpenChangeRequestLink(threadRef);
256 return useCallback(
257 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
258 event.stopPropagation();
259 const openInBrowser = shouldOpenPullRequestExternally(event);
260 const isAnchor =
261 event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
262 // A real link already knows how to cmd/ctrl+click. Leave its default
263 // action alone so the browser (or Electron's window-open handler) opens
264 // the host. Buttons have no href, so they still go through openExternal.
265 if (openInBrowser && isAnchor) return false;
266
267 event.preventDefault();
268 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
269
270 const api = readLocalApi();
271 if (!api) {
272 toastManager.add({
273 type: "error",
274 title: "Link opening is unavailable.",
275 });
276 return false;
277 }
278
279 void openPullRequestLink(api.shell, prUrl).catch((error) => {
280 console.error(error);
281 toastManager.add(
282 stackedThreadToast({
283 type: "error",
284 title: "Unable to open pull request link",
285 description: error instanceof Error ? error.message : "An error occurred.",
286 }),
287 );
288 });
289 return false;
290 },
291 [openChangeRequest],
292 );
293}