@devries-cameron20 / t3code-1 / commits / a6009faba0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(clients): pull request surfaces ask the forge instead of assuming GitHub (#23997)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 24, 2026 at 04:24 UTC a6009faba02b0c820ddc7fd5c4a22e1804fc3e35
49 files changed +578 -354
apps/mobile/src/features/projects/AddProjectScreen.tsx
+2 -1
@@ -21,6 +21,7 @@ import {
21 getNewProjectPublishTarget,
22 getNewProjectPublishTargets,
23 getNewProjectRepository,
24 + defaultHostCloneUrl,
25 normalizePastedCloneUrl,
26 parseAddProjectRemoteSource,
27 resolveAddProjectPath,
@@ -821,7 +822,7 @@ export function AddProjectRepositoryScreen(props: {
822 autoCorrect={false}
823 placeholder={
824 source === "url"
824 - ? "https://github.com/org/repo.git"
825 + ? (defaultHostCloneUrl("org/repo") ?? "https://example.com/org/repo.git")
826 : addProjectRemoteSourcePathHint(source)
827 }
828 returnKeyType="next"
apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+1 -4
@@ -124,10 +124,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
124 const canReply = permissions.canReply && Boolean(thread);
125 const resolveLabel = thread?.isResolved ? "Unresolve" : "Resolve";
126 return (
127 - <PullRequestMarkdownRepository
128 - params={params}
129 - value={detail.data?.provider === "github" ? detail.data.url : null}
130 - >
127 + <PullRequestMarkdownRepository params={params} changeRequest={detail.data}>
128 <KeyboardAvoidingView automaticOffset behavior="height" className="flex-1 bg-screen">
129 <NativeStackScreenOptions
130 options={{ title: "Discussion", unstable_headerSubtitle: `#${params.number}` }}
apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
+22 -8
@@ -10,7 +10,9 @@ import {
10 } from "./PullRequestMedia";
11 import { videoMimeType } from "@t3tools/shared/video";
12 import { createContext, useContext, useCallback, useMemo, useState } from "react";
13 -import { githubMarkdownLinks } from "@t3tools/shared/githubMarkdownLinks";
13 +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
14 +import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
15 +import { linkReferenceAutolinks } from "./pullRequestAutolinks";
16
17 import { useOpenPullRequest } from "../../native/useOpenPullRequest";
18 import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
@@ -26,13 +28,25 @@ import {
28 import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage";
29 import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";
30
29 -const RepositoryContext = createContext<string | null>(null);
31 +const AutolinksContext = createContext<((text: string) => ReadonlyArray<ReferenceAutolink>) | null>(
32 + null,
33 +);
34
35 export function PullRequestMarkdownRepository(props: {
32 - readonly value: string | null;
36 + /** The change request the markdown belongs to, whose host decides what its text links. */
37 + readonly changeRequest: { readonly provider: string; readonly url: string } | null | undefined;
38 readonly params: PullRequestParams;
39 readonly children: ReactNode;
40 }) {
41 + const provider = props.changeRequest?.provider;
42 + const url = props.changeRequest?.url;
43 + const autolinks = useMemo(
44 + () =>
45 + provider === undefined || url === undefined
46 + ? null
47 + : changeRequestReferenceAutolinker({ provider, url }),
48 + [provider, url],
49 + );
50 const target = pullRequestTarget(props.params);
51 const project = useProject({
52 environmentId: target.environmentId,
@@ -44,9 +58,9 @@ export function PullRequestMarkdownRepository(props: {
58 [target.environmentId, cwd],
59 );
60 return (
47 - <RepositoryContext value={props.value}>
61 + <AutolinksContext value={autolinks}>
62 <PullRequestMediaContext value={media}>{props.children}</PullRequestMediaContext>
49 - </RepositoryContext>
63 + </AutolinksContext>
64 );
65 }
66
@@ -103,11 +117,11 @@ function PullRequestMarkdownContent(props: {
117 readonly markdown: string;
118 readonly imageGroupMarkdown?: string;
119 }) {
106 - const repositoryUrl = useContext(RepositoryContext);
120 + const autolinks = useContext(AutolinksContext);
121 const mediaContext = useContext(PullRequestMediaContext);
122 const markdown = useMemo(
109 - () => githubMarkdownLinks(props.markdown, repositoryUrl),
110 - [props.markdown, repositoryUrl],
123 + () => linkReferenceAutolinks(props.markdown, autolinks),
124 + [props.markdown, autolinks],
125 );
126 const openPullRequest = useOpenPullRequest();
127 const openLink = useCallback(
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+1 -4
@@ -387,10 +387,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
387 }
388 };
389 return (
390 - <PullRequestMarkdownRepository
391 - params={params}
392 - value={pr?.provider === "github" ? pr.url : null}
393 - >
390 + <PullRequestMarkdownRepository params={params} changeRequest={pr}>
391 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
392 <NativeStackScreenOptions
393 options={{
apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
+4 -1
@@ -2,6 +2,7 @@ import { usePullRequestConnected } from "./usePullRequestConnected";
2 import { useAtomValue } from "@effect/atom-react";
3 import { useNavigation } from "@react-navigation/native";
4 import type { PullRequestAction, PullRequestDetail } from "@t3tools/contracts";
5 +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
6 import Animated from "react-native-reanimated";
7 import { PR_ROW_LAYOUT, PR_DISCLOSURE_ENTER, PR_ROW_EXIT } from "./pullRequestAnimations";
8 import { useState } from "react";
@@ -162,7 +163,9 @@ export function PullRequestChecksRow(props: RowProps) {
163 icon="arrow.up.right"
164 onPress={() =>
165 void Linking.openURL(
165 - props.pr.provider === "github" ? `${props.pr.url}/checks` : props.pr.url,
166 + sourceControlClients
167 + .get(props.pr.provider)
168 + .changeRequestChecksUrl?.(props.pr.url) ?? props.pr.url,
169 )
170 }
171 />
apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
+1 -4
@@ -161,10 +161,7 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps<GuideSto
161 </Toolbar.MenuAction>
162 </Toolbar.Menu>
163 </Toolbar>
164 - <PullRequestMarkdownRepository
165 - params={route.params}
166 - value={`https://${route.params.host ?? "github.com"}/${route.params.repository}`}
167 - >
164 + <PullRequestMarkdownRepository params={route.params} changeRequest={detail.data}>
165 <ScreenScrollView
166 contentInsetAdjustmentBehavior="automatic"
167 contentContainerStyle={{ padding: 16, paddingBottom: insets.bottom + 24, gap: 20 }}
apps/mobile/src/features/pull-requests/pullRequestActivityFilter.test.ts
+1 -1
@@ -4,7 +4,7 @@ import { DEFAULT_ACTIVITY_FILTER, filterPullRequestActivity } from "./pullReques
4
5 const date = IsoDateTime.make("2026-10-11T00:00:00.000Z");
6 const human: PullRequestActor = { login: "reader", name: null, avatarUrl: null };
7 -const bot: PullRequestActor = { ...human, login: "reviewer[bot]" };
7 +const bot: PullRequestActor = { ...human, login: "reviewer[bot]", isBot: true };
8 const comment = (id: string, author = human, reviewState: string | null = null) => ({
9 id,
10 author,
apps/mobile/src/features/pull-requests/pullRequestActivityFilter.ts
+1 -1
@@ -15,7 +15,7 @@ export const DEFAULT_ACTIVITY_FILTER: ActivityFilter = {
15 };
16
17 function isBot(actor: PullRequestActor | null) {
18 - return actor?.isBot === true || actor?.login.endsWith("[bot]") === true;
18 + return actor?.isBot === true;
19 }
20
21 function eventCount(activity: PullRequestActivity) {
apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts new
+38
@@ -0,0 +1,38 @@
1 +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { linkReferenceAutolinks } from "./pullRequestAutolinks";
5 +
6 +const github = changeRequestReferenceAutolinker({
7 + provider: "github",
8 + url: "https://github.com/team/repo/pull/8",
9 +});
10 +
11 +describe("linkReferenceAutolinks", () => {
12 + it("links the host's references in prose", () => {
13 + expect(linkReferenceAutolinks("Closes #123, see @julius", github)).toBe(
14 + "Closes [#123](https://github.com/team/repo/issues/123), see [@julius](https://github.com/julius)",
15 + );
16 + });
17 +
18 + it("leaves code, links, images, escapes and definitions alone", () => {
19 + const text =
20 + "`#123 @person abc1234`\n\n```\n#123\n```\n\n[#123](https://example.com) ![#123](image.png) https://example.com/#123 user@example.com \\#123 1234567\n\n[ref]: https://example.com/#123";
21 + expect(linkReferenceAutolinks(text, github)).toBe(text);
22 + });
23 +
24 + it("does not nest links inside HTML anchors or code", () => {
25 + const text = 'See <a href="https://example.com">#12</a> and <code>#13</code>, then #14.';
26 + expect(linkReferenceAutolinks(text, github)).toBe(
27 + 'See <a href="https://example.com">#12</a> and <code>#13</code>, then [#14](https://github.com/team/repo/issues/14).',
28 + );
29 + });
30 +
31 + it("leaves markdown unchanged for a host that links nothing", () => {
32 + const gitlab = changeRequestReferenceAutolinker({
33 + provider: "gitlab",
34 + url: "https://gitlab.com/group/project/-/merge_requests/7",
35 + });
36 + expect(linkReferenceAutolinks("Closes #123", gitlab)).toBe("Closes #123");
37 + });
38 +});
apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts new
+73
@@ -0,0 +1,73 @@
1 +import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
2 +import remarkGfm from "remark-gfm";
3 +import remarkParse from "remark-parse";
4 +import { unified } from "unified";
5 +
6 +type MarkdownNode = {
7 + readonly type: string;
8 + readonly position?:
9 + | {
10 + readonly start: { readonly offset?: number | undefined };
11 + readonly end: { readonly offset?: number | undefined };
12 + }
13 + | undefined;
14 + readonly children?: readonly MarkdownNode[] | undefined;
15 +};
16 +
17 +const parser = unified().use(remarkParse).use(remarkGfm);
18 +const UNLINKED_TYPES = new Set([
19 + "link",
20 + "linkReference",
21 + "image",
22 + "imageReference",
23 + "code",
24 + "inlineCode",
25 + "html",
26 + "definition",
27 +]);
28 +
29 +/**
30 + * Rewrites the references `autolinks` finds in the markdown's prose as markdown links, because the
31 + * native renderer takes markdown text. Text is searched as written, escapes included.
32 + */
33 +export function linkReferenceAutolinks(
34 + markdown: string,
35 + autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null,
36 +): string {
37 + if (autolinks === null) return markdown;
38 + const edits: { start: number; end: number; value: string }[] = [];
39 + const visit = (node: MarkdownNode) => {
40 + if (UNLINKED_TYPES.has(node.type)) return;
41 + if (node.type === "text") {
42 + const start = node.position?.start.offset;
43 + const end = node.position?.end.offset;
44 + if (start === undefined || end === undefined) return;
45 + for (const link of autolinks(markdown.slice(start, end))) {
46 + edits.push({
47 + start: start + link.index,
48 + end: start + link.index + link.text.length,
49 + value: `[${link.label}](${link.url})`,
50 + });
51 + }
52 + } else if (node.children !== undefined) {
53 + let protectedHtmlDepth = 0;
54 + for (const child of node.children) {
55 + if (child.type === "html") {
56 + const start = child.position?.start.offset;
57 + const end = child.position?.end.offset;
58 + const tag = start === undefined || end === undefined ? "" : markdown.slice(start, end);
59 + for (const match of tag.matchAll(/<(\/)?(?:a|code|pre|script|style)(?=[\s>])[^>]*>/giu)) {
60 + protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1));
61 + }
62 + } else if (protectedHtmlDepth === 0) visit(child);
63 + }
64 + }
65 + };
66 + visit(parser.parse(markdown));
67 + let linked = markdown;
68 + for (let index = edits.length - 1; index >= 0; index--) {
69 + const edit = edits[index]!;
70 + linked = linked.slice(0, edit.start) + edit.value + linked.slice(edit.end);
71 + }
72 + return linked;
73 +}
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+1 -6
@@ -202,12 +202,7 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
202 const statsKey = JSON.stringify(
203 targets.flatMap(({ environmentId }) => {
204 const refs = visibleRows
205 - .filter(
206 - (row) =>
207 - row.environmentId === environmentId &&
208 - row.provider === "github" &&
209 - row.additions + row.deletions === 0,
210 - )
205 + .filter((row) => row.environmentId === environmentId && row.additions + row.deletions === 0)
206 .map(({ projectId, host, repository, number }) => ({
207 projectId,
208 host,
apps/mobile/src/features/threads/ThreadFeed.tsx
-2
@@ -188,11 +188,9 @@ import {
188 } from "../../lib/appearancePreferences";
189 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
190 import { PierreEntryIcon } from "../../components/PierreEntryIcon";
191 -import { markdownLinkIconSource } from "../../lib/markdownLinkIcons";
191 import {
192 normalizeNativeMarkdownUrl,
193 resolveMarkdownInlineCodePresentation,
195 - resolveMarkdownLinkIcon,
194 resolveMarkdownLinkPresentation,
195 } from "../../lib/markdownLinks";
196 import {
apps/mobile/src/lib/markdownLinkIcons.ts
+8 -6
@@ -1,11 +1,13 @@
1 +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2 import type { ImageSourcePropType } from "react-native";
3
3 -import type { MarkdownLinkIcon } from "./markdownLinks";
4 -
5 -const MARKDOWN_LINK_ICON_SOURCES = {
4 +// The native renderer draws a link's icon from an image, so a host's mark is a bundled image keyed
5 +// by its definition's `icon`. A host without one keeps a plain link.
6 +const SOURCE_CONTROL_LINK_ICON_SOURCES: Partial<Record<string, ImageSourcePropType>> = {
7 github: require("../../assets/link-icons/github.png"),
7 -} as const satisfies Readonly<Record<MarkdownLinkIcon, ImageSourcePropType>>;
8 +};
9
9 -export function markdownLinkIconSource(icon: MarkdownLinkIcon): ImageSourcePropType {
10 - return MARKDOWN_LINK_ICON_SOURCES[icon];
10 +export function markdownLinkIconSource(host: string): ImageSourcePropType | null {
11 + const icon = sourceControlClients.findByPublicDomain(host)?.icon;
12 + return (icon === undefined ? undefined : SOURCE_CONTROL_LINK_ICON_SOURCES[icon]) ?? null;
13 }
apps/mobile/src/lib/markdownLinks.ts
-8
@@ -34,14 +34,6 @@ export type MarkdownLinkPresentation =
34
35 export type MarkdownFileIcon = keyof typeof MARKDOWN_FILE_ICON_SOURCES;
36
37 -export type MarkdownLinkIcon = "github";
38 -
39 -export function resolveMarkdownLinkIcon(host: string): MarkdownLinkIcon | null {
40 - const hostname = host.toLowerCase();
41 - if (hostname === "github.com" || hostname.endsWith(".github.com")) return "github";
42 - return null;
43 -}
44 -
37 const FILE_ICON_BY_NAME: Readonly<Record<string, MarkdownFileIcon>> = {
38 ".babelrc": "babel",
39 ".babelrc.json": "babel",
apps/mobile/src/native/useEnrichedLinkVariants.ts
+3 -3
@@ -13,7 +13,7 @@ import { contextChipIconSource } from "../lib/contextChipIconSource";
13 import { markdownFileIconSource } from "../lib/markdownFileIcons";
14 import { markdownLinkIconSource } from "../lib/markdownLinkIcons";
15 import { useUniwindTheme } from "../lib/useUniwindTheme";
16 -import { resolveMarkdownLinkIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
16 +import { resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
17 import type {
18 MarkdownLinkCustomization,
19 SelectableMarkdownTextProps,
@@ -83,11 +83,11 @@ function presentation(
83 icon: markdownFileIconSource(link.icon),
84 chip: { accent: contextChipPresentation("mention").accent, tintsIcon: false },
85 };
86 - const icon = link.kind === "external" ? resolveMarkdownLinkIcon(link.host) : null;
86 + const icon = link.kind === "external" ? markdownLinkIconSource(link.host) : null;
87 return icon
88 ? {
89 color: props.textStyle.linkColor,
90 - icon: markdownLinkIconSource(icon),
90 + icon,
91 iconTintColor: props.textStyle.linkColor,
92 }
93 : undefined;
apps/web/src/components/ChatMarkdown.tsx
+2 -2
@@ -1102,8 +1102,8 @@ const CHAT_MARKDOWN_COMPONENTS = {
1102 );
1103 const pullRequestCopy =
1104 pullRequestAutolink === "commit"
1105 - ? /\/commit\/([0-9a-f]{40})$/iu.exec(href ?? "")?.[1]
1106 - : pullRequestAutolink === "reference"
1105 + ? /\/commit\/([0-9a-f]{7,40})$/iu.exec(href ?? "")?.[1]
1106 + : pullRequestAutolink === "reference" || pullRequestAutolink === "mention"
1107 ? plainHastText(node)
1108 : undefined;
1109 const isPullRequestAutolink = pullRequestCopy !== undefined;
apps/web/src/components/CommandPalette.tsx
+16 -1
@@ -1540,7 +1540,22 @@ function OpenCommandPaletteDialog(props: {
1540 actionItems.push({
1541 kind: "action",
1542 value: "action:pull-requests",
1543 - searchTerms: ["pull requests", "prs", "pr", "github", "review", "merge", "branch"],
1543 + searchTerms: [
1544 + ...new Set(
1545 + sourceControlClients.definitions.flatMap((definition) => {
1546 + const shortLabel = definition.changeRequest.shortLabel.toLowerCase();
1547 + return [
1548 + `${definition.changeRequest.singular}s`,
1549 + `${shortLabel}s`,
1550 + shortLabel,
1551 + ...definition.label.toLowerCase().split(/[^a-z0-9]+/u),
1552 + ].filter(Boolean);
1553 + }),
1554 + ),
1555 + "review",
1556 + "merge",
1557 + "branch",
1558 + ],
1559 title: "Open pull requests",
1560 icon: <PullRequestGlyph.pullRequest className={ITEM_ICON_CLASS} />,
1561 run: async () => {
apps/web/src/components/ThreadStatusIndicators.tsx
+5 -1
@@ -114,7 +114,11 @@ export function useLinkedThreadPullRequest(
114 ? null
115 : {
116 pr: pullRequestDetailToVcsStatus(detail),
117 - sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
117 + sourceControlProvider: {
118 + kind: detail.provider,
119 + name: sourceControlClients.get(detail.provider).label,
120 + baseUrl: "",
121 + },
122 };
123 }
124
apps/web/src/components/chat/MarkdownExternalLink.tsx
+10 -6
@@ -2,21 +2,25 @@ import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
2 import { GlobeIcon } from "lucide-react";
3 import { Children, Fragment, memo, useState, type ReactNode } from "react";
4
5 +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
6 +
7 import { cn } from "../../lib/utils";
6 -import { GitHubIcon } from "../Icons";
8 +import { sourceControlIcon } from "../../sourceControlPresentation";
9
10 const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
11
12 const failedFaviconHosts = new Set<string>();
13
12 -function isGitHubHost(host: string): boolean {
13 - const hostname = host.toLowerCase();
14 - return hostname === "github.com" || hostname.endsWith(".github.com");
14 +function sourceControlHostIcon(host: string): ReactNode {
15 + const definition = sourceControlClients.findByPublicDomain(host);
16 + if (definition === undefined) return null;
17 + const Icon = sourceControlIcon(definition);
18 + return <Icon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />;
19 }
20
21 const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
22 const [failedHost, setFailedHost] = useState<string | null>(null);
19 - const brandIcon = isGitHubHost(host);
23 + const brandIcon = sourceControlHostIcon(host);
24 const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);
25 return (
26 <span
@@ -24,7 +28,7 @@ const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host:
28 aria-hidden
29 >
30 {brandIcon ? (
27 - <GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
31 + brandIcon
32 ) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
33 <GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
34 ) : (
apps/web/src/components/pullRequest/PullRequestDetailActions.tsx
+1 -1
@@ -131,7 +131,7 @@ export function PullRequestCheckoutMenu({
131 <span className="flex min-w-0 flex-col">
132 <span>In this repository</span>
133 <span className="text-xs text-muted-foreground">
134 - Switches the branch you are working in, like `gh pr checkout`.
134 + Switches the branch you are working in.
135 </span>
136 </span>
137 </MenuItem>
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+4 -8
@@ -1,4 +1,5 @@
1 import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
2 +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
3 import { useAtomValue } from "@effect/atom-react";
4 import { usePullRequestStack } from "~/state/usePullRequestStack";
5 import {
@@ -233,15 +234,10 @@ function resolvePullRequestReference(
234 }
235
236 function pullRequestMarkdownContext(
236 - hostClient: ReturnType<typeof sourceControlClients.get>,
237 - repositoryUrl: string | null,
237 + detail: Pick<PullRequestDetail, "provider" | "url"> | null,
238 threadRef: ScopedThreadRef | null,
239 ) {
240 - return {
241 - repositoryUrl:
242 - repositoryUrl === null ? null : hostClient.referenceAutolinkRepositoryUrl(repositoryUrl),
243 - threadRef,
244 - };
240 + return { autolinks: changeRequestReferenceAutolinker(detail), threadRef };
241 }
242
243 function pullRequestStackReference(
@@ -477,7 +473,7 @@ export function PullRequestDetailPanel({
473 : (sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl ?? null);
474 const hostClient = sourceControlClients.get(detail?.provider);
475 const openOnHostText = openOnHostLabel(hostClient);
480 - const markdownContext = pullRequestMarkdownContext(hostClient, repositoryUrl, threadRef);
476 + const markdownContext = pullRequestMarkdownContext(detail, threadRef);
477 const authorProfileUrl =
478 detail?.author && repositoryUrl !== null
479 ? hostClient.authorProfileUrl(detail.author.login, repositoryUrl)
apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+8 -5
@@ -1,6 +1,9 @@
1 import { ExternalLinkIcon, PaperclipIcon } from "lucide-react";
2 import { markdownImageSourceFragment } from "@t3tools/client-runtime/markdown-images";
3 -import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 +import {
4 + sourceControlClients,
5 + type ReferenceAutolink,
6 +} from "@t3tools/client-runtime/source-control-clients";
7 import {
8 SOURCE_CONTROL_MEDIA_ASSET,
9 type AssetResource,
@@ -19,7 +22,7 @@ import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
22 import { remarkPullRequestAutolinks, splitPullRequestBody } from "./pullRequestMarkdown.logic";
23
24 export const PullRequestMarkdownContext = createContext<{
22 - repositoryUrl: string | null;
25 + autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null;
26 threadRef: ScopedThreadRef | null;
27 } | null>(null);
28
@@ -66,10 +69,10 @@ export function PullRequestMarkdown({
69 }) {
70 const segments = splitPullRequestBody(text);
71 const context = useContext(PullRequestMarkdownContext);
69 - const repositoryUrl = context?.repositoryUrl;
72 + const autolinks = context?.autolinks;
73 const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
71 - const extraRemarkPlugins: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = repositoryUrl
72 - ? [[remarkPullRequestAutolinks, { repositoryUrl }]]
74 + const extraRemarkPlugins: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = autolinks
75 + ? [[remarkPullRequestAutolinks, { autolinks }]]
76 : [];
77 return (
78 <div
apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+16
@@ -54,6 +54,7 @@ import {
54 resolveBaseFreshness,
55 buildPullRequestTimeline,
56 writePullRequestDetailSnapshot,
57 + readableFailure,
58 } from "./pullRequestDetail.logic";
59 import type { ReviewCommentContext } from "~/reviewCommentContext";
60
@@ -1498,3 +1499,18 @@ describe("single-PR merge compatibility during stack discovery", () => {
1499 },
1500 );
1501 });
1502 +
1503 +describe("readableFailure", () => {
1504 + it("replaces a host tool's bare failure with the hint, for every host", () => {
1505 + for (const message of [
1506 + "GitHub CLI failed.",
1507 + "Azure DevOps API failed",
1508 + "Forgejo command failed",
1509 + ]) {
1510 + expect(readableFailure(new Error(message), "Try again.")).toBe("Try again.");
1511 + }
1512 + expect(readableFailure(new Error("Branch is protected."), "Try again.")).toBe(
1513 + "Branch is protected.",
1514 + );
1515 + });
1516 +});
apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+6 -3
@@ -646,8 +646,7 @@ export function filterPullRequestConversationItems(
646 // Matching any member keeps the finding beside a human reply to a bot.
647 pullRequestConversationItemComments(item).some(
648 (comment) =>
649 - (filter.bots ||
650 - !(comment.author?.isBot === true || comment.author?.login.endsWith("[bot]"))) &&
649 + (filter.bots || comment.author?.isBot !== true) &&
650 (filter.resolved ||
651 !isPullRequestCommentFinished(comment, item.kind === "thread" ? item.thread : undefined)),
652 ),
@@ -1216,8 +1215,12 @@ export function isPullRequestNotFound(failure: unknown): boolean {
1215
1216 const OPERATION_PREFIX = /^Pull request operation \w+ failed:\s*/iu;
1217
1218 +const HOST_LABELS = sourceControlClients.definitions
1219 + .map((definition) => definition.label.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"))
1220 + .join("|");
1221 +
1222 const TOOL_NOISE = [
1220 - /^(github|gitlab|bitbucket|azure devops)?\s*(cli|api)?\s*(command\s*)?failed\.?$/iu,
1223 + new RegExp(`^(${HOST_LABELS})?\\s*(cli|api)?\\s*(command\\s*)?failed\\.?$`, "iu"),
1224 /^exited? with (code|status) \d+\.?$/iu,
1225 /^unknown error\.?$/iu,
1226 ];
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+7 -1
@@ -701,10 +701,11 @@ describe("pull request quick actions", () => {
701 ...(actions === undefined ? {} : { actions }),
702 });
703
704 - it("offers what each host reports, and GitHub's legacy set when a server reports none", () => {
704 + it("offers what each host reports, and the host's own set when a server reports none", () => {
705 const actionsOf = pullRequestHostActions([
706 summary("bitbucket.org", "bitbucket", ["merge", "close"]),
707 summary("github.com", "github"),
708 + summary("gitlab.com", "gitlab"),
709 ]);
710 const bitbucket = actionsOf({
711 host: "bitbucket.org",
@@ -719,6 +720,11 @@ describe("pull request quick actions", () => {
720 "close",
721 "ready",
722 ]);
723 + const gitlab = actionsOf({
724 + host: "gitlab.com",
725 + provider: SourceControlProviderKind.make("gitlab"),
726 + });
727 + expect(pullRequestQuickActions({ state: "open", isDraft: false }, gitlab)).toEqual([]);
728 });
729 });
730
apps/web/src/components/pullRequest/pullRequestList.logic.ts
+6 -3
@@ -1015,10 +1015,11 @@ export function pullRequestHostActions(
1015 : [[provider.host.toLowerCase(), new Set(provider.actions)] as const],
1016 ),
1017 );
1018 - const legacy = new Set<PullRequestAction>(["close", "merge", "ready", "reopen"]);
1018 const none = new Set<PullRequestAction>();
1019 return (entry) =>
1021 - byHost.get(entry.host.toLowerCase()) ?? (entry.provider === "github" ? legacy : none);
1020 + byHost.get(entry.host.toLowerCase()) ??
1021 + sourceControlClients.find(entry.provider)?.changeRequestActionsWhenUnreported ??
1022 + none;
1023 }
1024
1025 export function pullRequestQuickActions(
@@ -1042,7 +1043,9 @@ export function largestPullRequestReadCount(
1043 const counts = new Map<string, number>();
1044 for (const entry of entries) {
1045 const read = `${entry.environmentId} ${entry.host.toLowerCase()} ${
1045 - entry.provider === "github" ? "" : entry.repository.toLowerCase()
1046 + sourceControlClients.find(entry.provider)?.changeRequestListScope === "host"
1047 + ? ""
1048 + : entry.repository.toLowerCase()
1049 }`;
1050 counts.set(read, (counts.get(read) ?? 0) + 1);
1051 }
apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts new
+46
@@ -0,0 +1,46 @@
1 +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
2 +import remarkParse from "remark-parse";
3 +import { unified } from "unified";
4 +import { describe, expect, it } from "vite-plus/test";
5 +
6 +import { remarkPullRequestAutolinks } from "./pullRequestMarkdown.logic";
7 +
8 +type Node = {
9 + type: string;
10 + value?: string;
11 + url?: string;
12 + data?: { hProperties?: Record<string, unknown> };
13 + children?: Node[];
14 +};
15 +
16 +function links(markdown: string) {
17 + const autolinks = changeRequestReferenceAutolinker({
18 + provider: "github",
19 + url: "https://github.com/team/repo/pull/8",
20 + })!;
21 + const tree = unified().use(remarkParse).parse(markdown) as Node;
22 + remarkPullRequestAutolinks({ autolinks })(tree as never);
23 + const found: Array<[string | undefined, string | undefined, unknown]> = [];
24 + const visit = (node: Node) => {
25 + if (node.type === "link") {
26 + found.push([
27 + node.children?.[0]?.value,
28 + node.url,
29 + node.data?.hProperties?.["dataPullRequestAutolink"],
30 + ]);
31 + }
32 + node.children?.forEach(visit);
33 + };
34 + visit(tree);
35 + return found;
36 +}
37 +
38 +describe("remarkPullRequestAutolinks", () => {
39 + it("links the host's references in prose and leaves links and code alone", () => {
40 + expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([
41 + ["#12", "https://github.com/team/repo/issues/12", "reference"],
42 + ["abcdef1", "https://github.com/team/repo/commit/abcdef1", "commit"],
43 + ["#13", "https://example.com", undefined],
44 + ]);
45 + });
46 +});
apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
+42 -40
@@ -1,52 +1,54 @@
1 -import {
2 - findAndReplaceText,
3 - type MarkdownNode,
4 - type TextMatch,
5 -} from "~/vendor/mdast-find-and-replace";
1 +import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
2
3 export {
4 splitPullRequestBody,
5 type PullRequestBodySegment,
6 } from "@t3tools/client-runtime/pull-request-markdown";
7
12 -const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;
13 -const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;
14 -const AUTOLINK_COMMIT_PREFIX_PATTERN = /[\s([{]/u;
8 +type MarkdownNode = {
9 + type: string;
10 + value?: string;
11 + children?: MarkdownNode[];
12 + url?: string;
13 + data?: unknown;
14 +};
15 +
16 const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
17
17 -export function remarkPullRequestAutolinks(options: { readonly repositoryUrl: string }) {
18 - const repositoryUrl = options.repositoryUrl.replace(/\/+$/u, "");
19 - return (tree: MarkdownNode) => {
20 - findAndReplaceText(
21 - tree,
22 - AUTOLINK_CANDIDATE_PATTERN,
23 - (matched: string, match: TextMatch) => {
24 - const reference = matched.startsWith("#");
25 - const before = match.input[match.index - 1];
26 - const after = match.input[match.index + matched.length];
27 - if (
28 - (before !== undefined &&
29 - (reference
30 - ? AUTOLINK_WORD_CHARACTER_PATTERN.test(before)
31 - : !AUTOLINK_COMMIT_PREFIX_PATTERN.test(before))) ||
32 - (after !== undefined && AUTOLINK_WORD_CHARACTER_PATTERN.test(after))
33 - ) {
34 - return false;
18 +export function remarkPullRequestAutolinks(options: {
19 + readonly autolinks: (text: string) => ReadonlyArray<ReferenceAutolink>;
20 +}) {
21 + const visit = (node: MarkdownNode): void => {
22 + const children = node.children;
23 + if (children === undefined) return;
24 + for (let index = 0; index < children.length; index += 1) {
25 + const child = children[index]!;
26 + if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue;
27 + if (child.type !== "text" || child.value === undefined) {
28 + visit(child);
29 + continue;
30 + }
31 + const value = child.value;
32 + const links = options.autolinks(value);
33 + if (links.length === 0) continue;
34 + const replacements: MarkdownNode[] = [];
35 + let start = 0;
36 + for (const link of links) {
37 + if (start < link.index) {
38 + replacements.push({ type: "text", value: value.slice(start, link.index) });
39 }
36 - return {
40 + replacements.push({
41 type: "link",
38 - url: reference
39 - ? `${repositoryUrl}/issues/${matched.slice(1)}`
40 - : `${repositoryUrl}/commit/${matched}`,
41 - data: {
42 - hProperties: {
43 - dataPullRequestAutolink: reference ? "reference" : "commit",
44 - },
45 - },
46 - children: [{ type: "text", value: reference ? matched : matched.slice(0, 7) }],
47 - };
48 - },
49 - AUTOLINK_IGNORED_TYPES,
50 - );
42 + url: link.url,
43 + data: { hProperties: { dataPullRequestAutolink: link.kind } },
44 + children: [{ type: "text", value: link.label }],
45 + });
46 + start = link.index + link.text.length;
47 + }
48 + if (start < value.length) replacements.push({ type: "text", value: value.slice(start) });
49 + children.splice(index, 1, ...replacements);
50 + index += replacements.length - 1;
51 + }
52 };
53 + return (tree: MarkdownNode) => visit(tree);
54 }
apps/web/src/components/settings/ThemeSearchSection.tsx
+8 -9
@@ -1,6 +1,7 @@
1 +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2 import { RefreshIcon } from "~/components/ui/refresh-icon";
3 import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";
3 -import { useEffect, useEffectEvent, useRef, useState } from "react";
4 +import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
5 import {
6 importOpenVsxThemeExtension,
7 searchOpenVsxThemes,
@@ -14,7 +15,7 @@ import {
15 replaceCustomThemeCollection,
16 type ThemeDefinition,
17 } from "../../themePalette";
17 -import { GitHubIcon, GitLabIcon } from "../Icons";
18 +import { sourceControlIcon } from "../../sourceControlPresentation";
19 import {
20 AlertDialog,
21 AlertDialogClose,
@@ -51,13 +52,11 @@ function sourceHost(url: string): string | null {
52 }
53 }
54
54 -function SourceLinkIcon({ url }: { url: string }) {
55 +function sourceLinkIcon(url: string): ReactNode {
56 const host = sourceHost(url);
56 - if (host === "github.com" || host?.endsWith(".github.com"))
57 - return <GitHubIcon className="size-3.5" />;
58 - if (host === "gitlab.com" || host?.endsWith(".gitlab.com"))
59 - return <GitLabIcon className="size-3.5" monochrome />;
60 - return <ExternalLinkIcon className="size-3.5" />;
57 + const definition = host === null ? undefined : sourceControlClients.findByPublicDomain(host);
58 + const Icon = definition ? sourceControlIcon(definition) : ExternalLinkIcon;
59 + return <Icon className="size-3.5" />;
60 }
61
62 function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
@@ -415,7 +414,7 @@ export function ThemeSearchSection({
414 size="icon-micro"
415 variant="ghost-muted"
416 >
418 - <SourceLinkIcon url={extension.sourceUrl} />
417 + {sourceLinkIcon(extension.sourceUrl)}
418 </Button>
419 ) : null}
420 </div>
apps/web/src/vendor/mdast-find-and-replace.ts deleted
-89
@@ -1,89 +0,0 @@
1 -/*
2 - * Adapted from mdast-util-find-and-replace:
3 - * https://github.com/syntax-tree/mdast-util-find-and-replace/blob/main/lib/index.js
4 - *
5 - * The MIT License
6 - *
7 - * Copyright (c) Titus Wormer <tituswormer@gmail.com>
8 - *
9 - * Permission is hereby granted, free of charge, to any person obtaining a copy
10 - * of this software and associated documentation files (the "Software"), to deal
11 - * in the Software without restriction, including without limitation the rights
12 - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 - * copies of the Software, and to permit persons to whom the Software is
14 - * furnished to do so, subject to the following conditions:
15 - *
16 - * The above copyright notice and this permission notice shall be included in
17 - * all copies or substantial portions of the Software.
18 - *
19 - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 - * SOFTWARE.
26 - */
27 -
28 -export type MarkdownNode = {
29 - type: string;
30 - value?: string;
31 - children?: MarkdownNode[];
32 - url?: string;
33 - data?: unknown;
34 -};
35 -
36 -export type TextMatch = {
37 - index: number;
38 - input: string;
39 -};
40 -
41 -export function findAndReplaceText(
42 - tree: MarkdownNode,
43 - find: RegExp,
44 - replace: (matched: string, match: TextMatch) => MarkdownNode | false,
45 - ignoredTypes: ReadonlySet<string>,
46 -): void {
47 - visit(tree);
48 -
49 - function visit(node: MarkdownNode): void {
50 - if (node.children === undefined) return;
51 - for (let childIndex = 0; childIndex < node.children.length; childIndex += 1) {
52 - const child = node.children[childIndex]!;
53 - if (ignoredTypes.has(child.type)) continue;
54 - if (child.type !== "text" || child.value === undefined) {
55 - visit(child);
56 - continue;
57 - }
58 -
59 - const replacements: MarkdownNode[] = [];
60 - let start = 0;
61 - let changed = false;
62 - find.lastIndex = 0;
63 - let match = find.exec(child.value);
64 - while (match !== null) {
65 - const position = match.index;
66 - const replacement = replace(match[0], { index: position, input: match.input });
67 - if (replacement === false) {
68 - find.lastIndex = position + 1;
69 - } else {
70 - if (start < position) {
71 - replacements.push({ type: "text", value: child.value.slice(start, position) });
72 - }
73 - replacements.push(replacement);
74 - start = position + match[0].length;
75 - changed = true;
76 - }
77 - if (!find.global) break;
78 - match = find.exec(child.value);
79 - }
80 -
81 - if (!changed) continue;
82 - if (start < child.value.length) {
83 - replacements.push({ type: "text", value: child.value.slice(start) });
84 - }
85 - node.children.splice(childIndex, 1, ...replacements);
86 - childIndex += replacements.length - 1;
87 - }
88 - }
89 -}
packages/client-runtime/src/operations/projects.ts
+15 -5
@@ -91,14 +91,24 @@ export function parseAddProjectRemoteSource(
91 return (value ? sourceControlClients.find(value)?.kind : undefined) ?? "url";
92 }
93
94 -const GITHUB_REPOSITORY_SHORTHAND =
95 - /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
94 +const REPOSITORY_SHORTHAND = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+(?:\.git)?$/;
95 +
96 +/**
97 + * The clone URL of `owner/name` on the public host of the host a repository reads as before it
98 + * reports one. Null when that host has no public host.
99 + */
100 +export function defaultHostCloneUrl(repository: string): string | null {
101 + const definition = sourceControlClients.get(undefined);
102 + if (definition.publicHost === null) return null;
103 + const path = repository.endsWith(".git") ? repository : `${repository}.git`;
104 + return definition.defaultCloneTransport === "https"
105 + ? `https://${definition.publicHost}/${path}`
106 + : `git@${definition.publicHost}:${path}`;
107 +}
108
109 export function normalizePastedCloneUrl(input: string): string {
110 const trimmed = input.trim();
99 - if (!GITHUB_REPOSITORY_SHORTHAND.test(trimmed)) return trimmed;
100 - const repository = trimmed.endsWith(".git") ? trimmed : `${trimmed}.git`;
101 - return `https://github.com/${repository}`;
111 + return REPOSITORY_SHORTHAND.test(trimmed) ? (defaultHostCloneUrl(trimmed) ?? trimmed) : trimmed;
112 }
113
114 export function getDefaultCloneUrl(
packages/client-runtime/src/pullRequestMarkdown.test.ts
+18 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { splitPullRequestBody } from "./pullRequestMarkdown.ts";
3 +import { changeRequestReferenceAutolinker, splitPullRequestBody } from "./pullRequestMarkdown.ts";
4
5 describe("pull request body segmentation", () => {
6 // GitHub writes a dropped image into the body as an `<img>` tag, so a bare attachment link on
@@ -123,3 +123,20 @@ describe("media on custom hosts", () => {
123 ]);
124 });
125 });
126 +
127 +describe("change request reference autolinks", () => {
128 + const urls = (provider: string, url: string, text: string) =>
129 + changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
130 +
131 + it("links references against the change request's own repository", () => {
132 + expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
133 + "https://ghe.example.com/acme/web/issues/5",
134 + ]);
135 + });
136 +
137 + // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
138 + it("links nothing on a host whose grammar is not applied", () => {
139 + expect(urls("gitlab", "https://gitlab.com/group/project/-/merge_requests/7", "#5")).toBeNull();
140 + expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
141 + });
142 +});
packages/client-runtime/src/pullRequestMarkdown.ts
+17 -1
@@ -1,4 +1,4 @@
1 -import { sourceControlClients } from "./sourceControlClients.ts";
1 +import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
2
3 /** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
4 export type PullRequestBodySegment =
@@ -131,3 +131,19 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
131 flushMarkdown();
132 return segments;
133 }
134 +
135 +/**
136 + * Finds the references the change request's host links in plain text, resolved against the change
137 + * request's repository. Null when the host links none.
138 + */
139 +export function changeRequestReferenceAutolinker(
140 + changeRequest: { readonly provider: string; readonly url: string } | null | undefined,
141 +): ((text: string) => ReadonlyArray<ReferenceAutolink>) | null {
142 + if (!changeRequest) return null;
143 + const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
144 + const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
145 + .repositoryUrl;
146 + return find === undefined || repositoryUrl === undefined
147 + ? null
148 + : (text) => find(text, repositoryUrl);
149 +}
packages/client-runtime/src/sourceControlClients.test.ts
+15
@@ -350,3 +350,18 @@ describe("sourceControlClients project hosts", () => {
350 expect(sourceControlClients.repositorySelector({ owner: "o", name: "r" })).toBe("o/r");
351 });
352 });
353 +
354 +describe("sourceControlClients.findByPublicDomain", () => {
355 + it("names the host a link is on, subdomains included", () => {
356 + const kindOf = (hostname: string) => sourceControlClients.findByPublicDomain(hostname)?.kind;
357 + expect(kindOf("gist.github.com")).toBe("github");
358 + expect(kindOf("GitLab.com")).toBe("gitlab");
359 + expect(kindOf("codeberg.org")).toBe("forgejo");
360 + expect(kindOf("notgithub.com")).toBeUndefined();
361 + expect(kindOf("github.com.example")).toBeUndefined();
362 + });
363 +
364 + it("leaves findByPublicHost to the public host alone", () => {
365 + expect(sourceControlClients.findByPublicHost("gist.github.com")).toBeUndefined();
366 + });
367 +});
packages/client-runtime/src/sourceControlClients.ts
+1
@@ -11,6 +11,7 @@ export {
11 type ChangeRequestLink,
12 type ChangeRequestTerminology,
13 type ParsedChangeRequestUrl,
14 + type ReferenceAutolink,
15 type SourceControlClientDefinition,
16 } from "@t3tools/source-control-core/client/definition";
17 import * as Forgejo from "@t3tools/source-control-forgejo/client/definition";
packages/shared/package.json
-4
@@ -7,10 +7,6 @@
7 "types": "./src/changedFileKind.ts",
8 "import": "./src/changedFileKind.ts"
9 },
10 - "./githubMarkdownLinks": {
11 - "types": "./src/githubMarkdownLinks.ts",
12 - "import": "./src/githubMarkdownLinks.ts"
13 - },
10 "./authScopeOptions": {
11 "types": "./src/authScopeOptions.ts",
12 "import": "./src/authScopeOptions.ts"
packages/shared/src/githubMarkdownLinks.test.ts deleted
-27
@@ -1,27 +0,0 @@
1 -import { describe, expect, it } from "vite-plus/test";
2 -import { githubMarkdownLinks } from "./githubMarkdownLinks.ts";
3 -
4 -const url = "https://github.com/team/repo/pull/8";
5 -describe("githubMarkdownLinks", () => {
6 - it("links closing references, cross-repository references, commits and mentions", () => {
7 - expect(
8 - githubMarkdownLinks(
9 - "Closes #123, fixes other/project#9; other#4 @julius @team/mobile abc1234 other/project@abcdef1",
10 - url,
11 - ),
12 - ).toBe(
13 - "Closes [#123](https://github.com/team/repo/issues/123), fixes [other/project#9](https://github.com/other/project/issues/9); [other#4](https://github.com/other/repo/issues/4) [@julius](https://github.com/julius) [@team/mobile](https://github.com/orgs/team/teams/mobile) [abc1234](https://github.com/team/repo/commit/abc1234) [other/project@abcdef1](https://github.com/other/project/commit/abcdef1)",
14 - );
15 - });
16 - it("leaves code, links, images, URLs, escapes, emails, and plain numbers alone", () => {
17 - const text =
18 - "`#123 @person abc1234`\n\n```\n#123\n```\n\n[#123](https://example.com) ![#123](image.png) https://example.com/#123 user@example.com \\#123 1234567\n\n[ref]: https://example.com/#123";
19 - expect(githubMarkdownLinks(text, url)).toBe(text);
20 - });
21 - it("does not nest links inside HTML anchors or code", () => {
22 - const text = 'See <a href="https://example.com">#12</a> and <code>#13</code>, then #14.';
23 - expect(githubMarkdownLinks(text, url)).toBe(
24 - 'See <a href="https://example.com">#12</a> and <code>#13</code>, then [#14](https://github.com/team/repo/issues/14).',
25 - );
26 - });
27 -});
packages/shared/src/githubMarkdownLinks.ts deleted
-89
@@ -1,89 +0,0 @@
1 -import { unified } from "unified";
2 -import remarkParse from "remark-parse";
3 -import remarkGfm from "remark-gfm";
4 -
5 -type MarkdownNode = {
6 - readonly type: string;
7 - readonly position?:
8 - | {
9 - readonly start: { readonly offset?: number | undefined };
10 - readonly end: { readonly offset?: number | undefined };
11 - }
12 - | undefined;
13 - readonly children?: readonly MarkdownNode[] | undefined;
14 -};
15 -
16 -const parser = unified().use(remarkParse).use(remarkGfm);
17 -const reference =
18 - /(?<![\w/\\])(?:([\w.-]+\/[\w.-]+|[\w-]+)?#([1-9]\d*)|(?:([\w.-]+\/[\w.-]+|[\w-]+)@)?([a-f\d]{7,40})(?![\w])|@([a-z\d](?:[a-z\d-]*[a-z\d])?(?:\/[a-z\d][a-z\d-]*)?))(?![\w])/gi;
19 -
20 -export function githubMarkdownLinks(markdown: string, pullRequestUrl: string | null): string {
21 - if (!pullRequestUrl || !/[#@]|\b[a-f\d]{7,40}\b/i.test(markdown)) return markdown;
22 - let url: URL;
23 - try {
24 - url = new URL(pullRequestUrl);
25 - } catch {
26 - return markdown;
27 - }
28 - const [owner, repo] = url.pathname.split("/").filter(Boolean);
29 - if (!owner || !repo || !/^https?:$/.test(url.protocol)) return markdown;
30 - const edits: { start: number; end: number; value: string }[] = [];
31 - const repository = (qualifier: string | undefined) =>
32 - qualifier?.includes("/") ? qualifier : qualifier ? `${qualifier}/${repo}` : `${owner}/${repo}`;
33 - const visit = (node: MarkdownNode) => {
34 - if (
35 - [
36 - "link",
37 - "linkReference",
38 - "image",
39 - "imageReference",
40 - "code",
41 - "inlineCode",
42 - "html",
43 - "definition",
44 - ].includes(node.type)
45 - )
46 - return;
47 - if (node.type === "text") {
48 - const start = node.position?.start.offset;
49 - const end = node.position?.end.offset;
50 - if (start === undefined || end === undefined) return;
51 - const source = markdown.slice(start, end);
52 - for (const match of source.matchAll(reference)) {
53 - const [label, issueRepo, number, commitRepo, sha, mention] = match;
54 - if (sha && !/[a-f]/i.test(sha)) continue;
55 - const path = number
56 - ? `${repository(issueRepo)}/issues/${number}`
57 - : sha
58 - ? `${repository(commitRepo)}/commit/${sha}`
59 - : mention?.includes("/")
60 - ? `orgs/${mention.split("/")[0]}/teams/${mention.split("/")[1]}`
61 - : mention;
62 - if (!path) continue;
63 - edits.push({
64 - start: start + match.index,
65 - end: start + match.index + label.length,
66 - value: `[${label}](${url.origin}/${path})`,
67 - });
68 - }
69 - } else if ("children" in node) {
70 - let protectedHtmlDepth = 0;
71 - for (const child of node.children ?? []) {
72 - if (child.type === "html") {
73 - const start = child.position?.start.offset;
74 - const end = child.position?.end.offset;
75 - const tag = start === undefined || end === undefined ? "" : markdown.slice(start, end);
76 - for (const match of tag.matchAll(/<(\/)?(?:a|code|pre|script|style)(?=[\s>])[^>]*>/gi)) {
77 - protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1));
78 - }
79 - } else if (protectedHtmlDepth === 0) visit(child);
80 - }
81 - }
82 - };
83 - visit(parser.parse(markdown));
84 - for (let index = edits.length - 1; index >= 0; index--) {
85 - const edit = edits[index]!;
86 - markdown = markdown.slice(0, edit.start) + edit.value + markdown.slice(edit.end);
87 - }
88 - return markdown;
89 -}
packages/source-control-azure-devops/src/client/definition.ts
-1
@@ -102,7 +102,6 @@ export const definition = defineSourceControlClient({
102 changeRequestCloseCommand:
103 /\baz\s+repos\s+pr\s+update\b[^;&|]*--status[\s=]+["']?(?:completed|abandoned)\b/u,
104 authorProfileUrl: () => null,
105 - referenceAutolinkRepositoryUrl: () => null,
105 reviewSummaryRequired: () => false,
106 checkoutCommandArgument: (input) => {
107 const args = CHECKOUT_COMMAND.exec(input)?.[1];
packages/source-control-bitbucket/src/client/definition.ts
-1
@@ -93,7 +93,6 @@ export const definition = defineSourceControlClient({
93 ? `git clone --single-branch --branch ${headBranch} https://bitbucket.org/${headRepositoryNameWithOwner}.git t3code-pr-${number}`
94 : null,
95 authorProfileUrl: () => null,
96 - referenceAutolinkRepositoryUrl: () => null,
96 reviewSummaryRequired: () => false,
97 checkoutCommandArgument: () => null,
98 isChangeRequestReference: () => false,
packages/source-control-core/src/client/definition.ts
+45 -2
@@ -84,6 +84,16 @@ export interface SourceControlMediaUrl {
84 readonly kind?: "image" | "video";
85 }
86
87 +export interface ReferenceAutolink {
88 + /** Where `text` starts in the string that was searched. */
89 + readonly index: number;
90 + readonly text: string;
91 + /** What to show for the link, which can be shorter than `text`, as for a commit SHA. */
92 + readonly label: string;
93 + readonly url: string;
94 + readonly kind: "reference" | "commit" | "mention";
95 +}
96 +
97 export interface SourceControlClientDefinition {
98 readonly kind: SourceControlProviderKind;
99 readonly label: string;
@@ -117,7 +127,28 @@ export interface SourceControlClientDefinition {
127 */
128 readonly changeRequestCloseCommand?: RegExp;
129 readonly authorProfileUrl: (login: string, repositoryUrl: string) => string | null;
120 - readonly referenceAutolinkRepositoryUrl: (repositoryUrl: string) => string | null;
130 + /**
131 + * The references this host's own renderer links in plain text, such as `#12` or a commit SHA,
132 + * resolved against `repositoryUrl`, in the order they appear. Absent for a host whose grammar
133 + * T3 does not apply.
134 + */
135 + readonly referenceAutolinks?: (
136 + text: string,
137 + repositoryUrl: string,
138 + ) => ReadonlyArray<ReferenceAutolink>;
139 + /** Where the host lists a change request's checks. Absent means the change request's own page. */
140 + readonly changeRequestChecksUrl?: (changeRequestUrl: string) => string;
141 + /**
142 + * The actions a server too old to report `capabilities.actions` could still take on this host's
143 + * change requests. Absent means none.
144 + */
145 + readonly changeRequestActionsWhenUnreported?: ReadonlySet<PullRequestAction>;
146 + /**
147 + * `host` when the server lists change requests in many repositories on this host with one read,
148 + * so a page's size bounds the rows of every repository together. Absent means one read per
149 + * repository.
150 + */
151 + readonly changeRequestListScope?: "host" | "repository";
152 readonly reviewSummaryRequired: (verdict: PullRequestReviewVerdict) => boolean;
153 readonly checkoutCommandArgument: (input: string) => string | null;
154 readonly isChangeRequestReference: (url: string) => boolean;
@@ -346,7 +377,6 @@ export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {
377 changeRequestActions: new Set(),
378 checkoutCommand: () => null,
379 authorProfileUrl: () => null,
349 - referenceAutolinkRepositoryUrl: () => null,
380 reviewSummaryRequired: () => false,
381 checkoutCommandArgument: () => null,
382 isChangeRequestReference: () => false,
@@ -376,6 +406,11 @@ export interface SourceControlClientRegistry {
406 readonly get: (kind: string | null | undefined) => SourceControlClientDefinition;
407 readonly find: (kind: string) => SourceControlClientDefinition | undefined;
408 readonly findByPublicHost: (hostname: string) => SourceControlClientDefinition | undefined;
409 + /**
410 + * The host whose `publicHost` is `hostname` or a parent domain of it, such as GitHub for
411 + * `gist.github.com`: which host a link is on, not one T3 can read from.
412 + */
413 + readonly findByPublicDomain: (hostname: string) => SourceControlClientDefinition | undefined;
414 /** The first host, in registry order, that reads `url` as one of its change requests. */
415 readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
416 readonly findByChangeRequestUrl: (url: string) => SourceControlClientDefinition | undefined;
@@ -471,6 +506,14 @@ export function makeSourceControlClientRegistry(
506 const host = hostname.toLowerCase();
507 return definitions.find((definition) => definition.publicHost === host);
508 },
509 + findByPublicDomain: (hostname) => {
510 + const host = hostname.toLowerCase();
511 + return definitions.find(
512 + (definition) =>
513 + definition.publicHost !== null &&
514 + (host === definition.publicHost || host.endsWith(`.${definition.publicHost}`)),
515 + );
516 + },
517 parseChangeRequestUrl,
518 findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition,
519 hostLabelForChangeRequestUrl: (url) =>
packages/source-control-forgejo/src/client/definition.ts
-1
@@ -84,7 +84,6 @@ export const definition = defineSourceControlClient({
84 changeRequestCloseCommand: /\b(?:tea\s+(?:pr|pulls)|fj\s+pr)\s+(?:merge|close)\b/u,
85 authorProfileUrl: () => null,
86 // Forgejo refuses a change request review without a summary, even with inline comments.
87 - referenceAutolinkRepositoryUrl: () => null,
87 reviewSummaryRequired: (verdict) => verdict === "request-changes",
88 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
89 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
packages/source-control-gitcafe/src/client/definition.ts
-1
@@ -71,7 +71,6 @@ export const definition = defineSourceControlClient({
71 checkoutCommand: ({ number }) => `cafe pr checkout ${number}`,
72 changeRequestCloseCommand: /\bcafe\s+(?:pr|stack)\s+(?:merge|close)\b/u,
73 authorProfileUrl: () => null,
74 - referenceAutolinkRepositoryUrl: () => null,
74 reviewSummaryRequired: () => false,
75 checkoutCommandArgument: () => null,
76 isChangeRequestReference: () => false,
packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts
+19
@@ -118,6 +118,25 @@ describe("toChangeRequest", () => {
118 assert.strictEqual(row.author?.login, "remote-user");
119 assert.deepStrictEqual(row.reviewRequestLogins, ["alice", "upstream", "linked-local"]);
120 });
121 +
122 + it("marks a mirrored GitHub bot account as a bot", () => {
123 + const row = (accountType: string) =>
124 + GitCafePullRequestJson.toChangeRequest(
125 + decodePull({
126 + ...pull,
127 + author: {
128 + kind: "github",
129 + actorId: "act_bot",
130 + login: "coderabbitai[bot]",
131 + accountType,
132 + avatarUrl: null,
133 + },
134 + }),
135 + { repository: "owner/repo", host: "git.cafe" },
136 + );
137 + assert.isTrue(row("bot").author?.isBot);
138 + assert.isUndefined(row("user").author?.isBot);
139 + });
140 });
141
142 describe("toViewerPermissions", () => {
packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts
+6 -1
@@ -37,6 +37,7 @@ const Actor = Schema.Union([
37 actorId: Schema.String,
38 login: TrimmedNonEmptyString,
39 avatarUrl: Schema.NullOr(Schema.String),
40 + accountType: Schema.optional(Schema.NullOr(Schema.String)),
41 linkedProfile: Schema.optional(
42 Schema.NullOr(
43 Schema.Struct({ handle: TrimmedNonEmptyString, actorId: Schema.optional(Schema.String) }),
@@ -300,7 +301,11 @@ function toActor(actor: Actor, host: string): PullRequestActor | null {
301 return {
302 login: actor.kind === "local" ? actor.handle : actor.login,
303 name: actor.kind === "local" ? actor.displayName : null,
303 - ...(actor.kind === "local" && actor.bot === true ? { isBot: true } : {}),
304 + // A mirrored GitHub account says it is a bot by its account type, not its login.
305 + ...((actor.kind === "local" && actor.bot === true) ||
306 + (actor.kind === "github" && actor.accountType === "bot")
307 + ? { isBot: true }
308 + : {}),
309 // GitCafe serves its own avatars by path, so a relative one is read against the host.
310 avatarUrl: actor.avatarUrl === null ? null : new URL(actor.avatarUrl, `https://${host}`).href,
311 };
packages/source-control-github/src/client/definition.ts
+7 -1
@@ -19,6 +19,7 @@ import {
19 } from "@t3tools/source-control-core/client/definition";
20
21 import { gitHubMediaUrl } from "./gitHubMedia.ts";
22 +import { gitHubReferenceAutolinks } from "./referenceAutolinks.ts";
23
24 const CHECKOUT_COMMAND = /^gh\s+pr\s+checkout\s+(.+)$/i;
25 const CHANGE_REQUEST_REFERENCE =
@@ -117,7 +118,12 @@ export const definition = defineSourceControlClient({
118 login.endsWith("[bot]")
119 ? null
120 : new URL(`/${encodeURIComponent(login)}`, repositoryUrl).toString(),
120 - referenceAutolinkRepositoryUrl: (repositoryUrl) => repositoryUrl,
121 + referenceAutolinks: gitHubReferenceAutolinks,
122 + changeRequestChecksUrl: (changeRequestUrl) => `${changeRequestUrl.replace(/\/+$/u, "")}/checks`,
123 + // Before servers reported their actions, GitHub was the only host they acted on from a list.
124 + changeRequestActionsWhenUnreported: new Set(["close", "merge", "ready", "reopen"] as const),
125 + // One search reads every repository on the host.
126 + changeRequestListScope: "host",
127 reviewSummaryRequired: () => false,
128 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
129 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
packages/source-control-github/src/client/referenceAutolinks.test.ts new
+44
@@ -0,0 +1,44 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { gitHubReferenceAutolinks } from "./referenceAutolinks.ts";
4 +
5 +const repositoryUrl = "https://github.com/team/repo";
6 +const linked = (text: string) =>
7 + gitHubReferenceAutolinks(text, repositoryUrl).map(({ label, url, kind }) => [label, url, kind]);
8 +
9 +describe("gitHubReferenceAutolinks", () => {
10 + it("links references, cross-repository references, commits and mentions", () => {
11 + expect(
12 + linked(
13 + "Closes #123, fixes other/project#9; other#4 @julius @team/mobile abc1234 other/project@abcdef1",
14 + ),
15 + ).toEqual([
16 + ["#123", "https://github.com/team/repo/issues/123", "reference"],
17 + ["other/project#9", "https://github.com/other/project/issues/9", "reference"],
18 + ["other#4", "https://github.com/other/repo/issues/4", "reference"],
19 + ["@julius", "https://github.com/julius", "mention"],
20 + ["@team/mobile", "https://github.com/orgs/team/teams/mobile", "mention"],
21 + ["abc1234", "https://github.com/team/repo/commit/abc1234", "commit"],
22 + ["other/project@abcdef1", "https://github.com/other/project/commit/abcdef1", "commit"],
23 + ]);
24 + });
25 +
26 + it("shows a full SHA by its first seven characters", () => {
27 + const sha = "0123456789abcdef0123456789abcdef01234567";
28 + expect(linked(`Reverts ${sha}.`)).toEqual([
29 + ["0123456", `https://github.com/team/repo/commit/${sha}`, "commit"],
30 + ]);
31 + });
32 +
33 + it("leaves URLs, escapes, emails, words and plain numbers alone", () => {
34 + expect(linked("https://example.com/#123 user@example.com \\#123 1234567 issue#x a#1b")).toEqual(
35 + [],
36 + );
37 + });
38 +
39 + it("links against the repository's own host", () => {
40 + expect(
41 + gitHubReferenceAutolinks("See #5", "https://ghe.example.com/acme/web").map(({ url }) => url),
42 + ).toEqual(["https://ghe.example.com/acme/web/issues/5"]);
43 + });
44 +});
packages/source-control-github/src/client/referenceAutolinks.ts new
+58
@@ -0,0 +1,58 @@
1 +import type { ReferenceAutolink } from "@t3tools/source-control-core/client/definition";
2 +
3 +// GitHub's autolinked references: `#12`, `repo#12` and `owner/repo#12`; a SHA of 7 to 40
4 +// characters, optionally `repo@` or `owner/repo@` qualified; `@user` and `@org/team`.
5 +const REFERENCE =
6 + /(?<![\w/\\])(?:([\w.-]+\/[\w.-]+|[\w-]+)?#([1-9]\d*)|(?:([\w.-]+\/[\w.-]+|[\w-]+)@)?([a-f\d]{7,40})(?![\w])|@([a-z\d](?:[a-z\d-]*[a-z\d])?(?:\/[a-z\d][a-z\d-]*)?))(?![\w])/giu;
7 +const CANDIDATE = /[#@]|\b[a-f\d]{7,40}\b/iu;
8 +const SHORT_SHA_LENGTH = 7;
9 +
10 +export function gitHubReferenceAutolinks(
11 + text: string,
12 + repositoryUrl: string,
13 +): ReadonlyArray<ReferenceAutolink> {
14 + if (!CANDIDATE.test(text)) return [];
15 + let url: URL;
16 + try {
17 + url = new URL(repositoryUrl);
18 + } catch {
19 + return [];
20 + }
21 + const [owner, repo] = url.pathname.split("/").filter(Boolean);
22 + if (!owner || !repo || !/^https?:$/u.test(url.protocol)) return [];
23 + const repository = (qualifier: string | undefined) =>
24 + qualifier?.includes("/") ? qualifier : qualifier ? `${qualifier}/${repo}` : `${owner}/${repo}`;
25 + const links: ReferenceAutolink[] = [];
26 + for (const match of text.matchAll(REFERENCE)) {
27 + const [matched, issueRepo, number, commitRepo, sha, mention] = match;
28 + if (number) {
29 + links.push({
30 + index: match.index,
31 + text: matched,
32 + label: matched,
33 + url: `${url.origin}/${repository(issueRepo)}/issues/${number}`,
34 + kind: "reference",
35 + });
36 + } else if (sha) {
37 + // A run of digits is a number far more often than a SHA.
38 + if (!/[a-f]/iu.test(sha)) continue;
39 + links.push({
40 + index: match.index,
41 + text: matched,
42 + label: `${commitRepo ? `${commitRepo}@` : ""}${sha.slice(0, SHORT_SHA_LENGTH)}`,
43 + url: `${url.origin}/${repository(commitRepo)}/commit/${sha}`,
44 + kind: "commit",
45 + });
46 + } else if (mention) {
47 + const [organization, team] = mention.split("/");
48 + links.push({
49 + index: match.index,
50 + text: matched,
51 + label: matched,
52 + url: `${url.origin}/${team ? `orgs/${organization}/teams/${team}` : mention}`,
53 + kind: "mention",
54 + });
55 + }
56 + }
57 + return links;
58 +}
packages/source-control-gitlab/src/client/definition.ts
-1
@@ -48,7 +48,6 @@ export const definition = defineSourceControlClient({
48 checkoutCommand: ({ number }) => `glab mr checkout ${number}`,
49 changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,
50 authorProfileUrl: () => null,
51 - referenceAutolinkRepositoryUrl: () => null,
51 reviewSummaryRequired: () => false,
52 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
53 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),