Open History to see the last commit
1import type { 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 useOpenChangeRequestLink(
177 threadRef?: ScopedThreadRef,
178): (
179 event: Pick<MouseEvent<HTMLElement>, "preventDefault" | "stopPropagation">,
180 targetUrl: string,
181 targetThreadRef?: ScopedThreadRef,
182) => boolean {
183 const navigate = useNavigate();
184 const allProjects = useProjects();
185 const serverConfigs = useServerConfigs();
186 const primaryEnvironmentId = usePrimaryEnvironmentId();
187 return useCallback(
188 (event, targetUrl, targetThreadRef) => {
189 const resolvedThreadRef = targetThreadRef ?? threadRef;
190 const environmentId = resolvedThreadRef?.environmentId ?? primaryEnvironmentId;
191 if (
192 environmentId === null ||
193 serverConfigs.get(environmentId)?.environment.capabilities.pullRequests !== true
194 ) {
195 return false;
196 }
197 // Beside a thread the panel reads on that thread's environment, so a project from another
198 // one could not be read there whatever its remote says: two environments can hold the same
199 // repository, and handing the panel the wrong one's id opens a surface that never loads.
200 const projects = allProjects.filter((project) => project.environmentId === environmentId);
201 const parsed = parseChangeRequestUrl(targetUrl);
202 const project = parsed === null ? undefined : findProjectForChangeRequest(projects, parsed);
203 if (parsed === null || project === undefined) return false;
204 event.preventDefault();
205 event.stopPropagation();
206 if (resolvedThreadRef) {
207 useRightPanelStore.getState().openPullRequest(resolvedThreadRef, {
208 projectId: project.id,
209 // The identity's own spelling, not the one read out of the URL: the panel asks the
210 // provider for this repository, while matching a link only ever compares lower case.
211 repository: project.repositoryIdentity?.displayName ?? parsed.repository,
212 number: parsed.number,
213 });
214 return true;
215 }
216 void navigate({
217 to: "/pull-requests",
218 search: {
219 involvement: "all",
220 // Every state, so the pull request being opened is also in the list behind it whether
221 // it is open, merged or closed.
222 state: "all",
223 repository: parsed.repository,
224 number: parsed.number,
225 selectedProjectId: project.id,
226 },
227 });
228 return true;
229 },
230 [allProjects, navigate, primaryEnvironmentId, serverConfigs, threadRef],
231 );
232}
233
234export function useOpenPrLink(threadRef?: ScopedThreadRef) {
235 const openChangeRequest = useOpenChangeRequestLink(threadRef);
236 return useCallback(
237 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
238 event.preventDefault();
239 event.stopPropagation();
240 if (openChangeRequest(event, prUrl, targetThreadRef)) return true;
241
242 const api = readLocalApi();
243 if (!api) {
244 toastManager.add({
245 type: "error",
246 title: "Link opening is unavailable.",
247 });
248 return false;
249 }
250
251 void openPullRequestLink(api.shell, prUrl).catch((error) => {
252 console.error(error);
253 toastManager.add(
254 stackedThreadToast({
255 type: "error",
256 title: "Unable to open pull request link",
257 description: error instanceof Error ? error.message : "An error occurred.",
258 }),
259 );
260 });
261 return false;
262 },
263 [openChangeRequest],
264 );
265}