TypeScript
fix(mobile): PR links open in the app the same way they do on web (#24738)
Julius Marmingec2845de6c451
diff --git a/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts b/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.tsindex faed80ecc13..ab07c99b6f0 100644--- a/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts@@ -1,6 +1,6 @@import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";-import { nativePullRequestDestination } from "../../lib/pullRequestNavigation";+import { nativePullRequestDestination as destination } from "../../lib/pullRequestNavigation";const context = { environmentId: "remote", projectId: "project" };const project = (id: string, canonicalKey: string, provider: string, remoteUrl: string) => ({@@ -19,6 +19,14 @@ const projects = [project("forgejo", "forgejo.test/org/repo", "forgejo", "http://forgejo.test:3000/org/repo.git"),];+const hostReads = () => ({ pullRequests: true, threadPullRequests: true });+const nativePullRequestDestination = (+ url: string,+ linkContext: typeof context | null,+ linkProjects: typeof projects,+ capabilities: Parameters<typeof destination>[3] = hostReads,+) => destination(url, linkContext, linkProjects, capabilities);+describe("native PR entry points", () => {it("keeps a thread link in its own environment and handles renamed host path shapes", () => {expect(@@ -41,9 +49,25 @@ describe("native PR entry points", () => {).toBe("forgejo.test:3000");});- it("leaves pull requests from repositories without a project to the external opener", () => {+ it("opens a repository nobody has checked out under a project on its host, as web does", () => {expect(nativePullRequestDestination("https://github.com/someone/else/pull/12", context, projects),+ ).toEqual({ ...context, host: "github.com", repository: "someone/else", number: 12 });+ });++ it("leaves links to the external opener when the environment cannot show them", () => {+ const url = "https://github.com/org/repo/pull/12";+ expect(nativePullRequestDestination(url, context, projects, () => undefined)).toBeNull();+ expect(+ nativePullRequestDestination(+ "https://github.com/someone/else/pull/12",+ context,+ projects,+ () => ({+ pullRequests: true,+ threadPullRequests: false,+ }),+ ),).toBeNull();});diff --git a/apps/mobile/src/lib/pullRequestNavigation.ts b/apps/mobile/src/lib/pullRequestNavigation.tsindex 1c84cfb6876..9ce9408cf9c 100644--- a/apps/mobile/src/lib/pullRequestNavigation.ts+++ b/apps/mobile/src/lib/pullRequestNavigation.ts@@ -1,32 +1,32 @@-import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";+import {+ resolveChangeRequestLinkTarget,+ type ChangeRequestLinkCapabilities,+} from "@t3tools/client-runtime/change-request-links";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";-import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";+import { EnvironmentId, ProjectId } from "@t3tools/contracts";-/**- * Opens a change request in the app only under a project of the link's environment whose own- * repository holds it, preferring the one the link came from; anything else is the browser's.- */+/** The PullRequest route for a change request link from a project, or null for the browser. */export function nativePullRequestDestination(url: string,context: { environmentId: string; projectId: string } | null,projects: ReadonlyArray<Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity">>,+ capabilities: (environmentId: EnvironmentId) => ChangeRequestLinkCapabilities | undefined,) {- const parsed = sourceControlClients.parseChangeRequestUrl(url)?.link;- if (!parsed || !context) return null;- const candidates = projects.filter((project) => project.environmentId === context.environmentId);- const project = findProjectForChangeRequest(- [- ...candidates.filter((candidate) => candidate.id === context.projectId),- ...candidates.filter((candidate) => candidate.id !== context.projectId),- ],- parsed,- );- if (project === undefined) return null;+ if (!context) return null;+ const target = resolveChangeRequestLinkTarget({+ url,+ projects,+ capabilities,+ environmentId: EnvironmentId.make(context.environmentId),+ projectId: ProjectId.make(context.projectId),+ lendHostProject: true,+ });+ if (target === null) return null;return {environmentId: context.environmentId,- projectId: String(project.id),- repository: parsed.repository,- number: parsed.number,- host: parsed.authority ?? parsed.host,+ projectId: String(target.project.id),+ repository: target.repository,+ number: target.number,+ ...(target.host === undefined ? {} : { host: target.host }),};}diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.tsindex ffd5248123c..4e71aa5fde1 100644--- a/apps/mobile/src/native/useOpenPullRequest.ts+++ b/apps/mobile/src/native/useOpenPullRequest.ts@@ -6,6 +6,8 @@ import { resetAndroidWorkspace } from "../lib/android-workspace-navigation";import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { useProjects, useThreadShell } from "../state/entities";import { tryOpenExternalUrl } from "../lib/openExternalUrl";+import { appAtomRegistry } from "../state/atom-registry";+import { environmentServerConfigsAtom } from "../state/server";type PullRequestContext = { readonly environmentId: string; readonly projectId: string };@@ -16,7 +18,14 @@ export function useNavigateToPullRequest(options?: { readonly replace?: booleanconst replace = options?.replace;return useCallback(async (url: string, context: PullRequestContext | null) => {- const params = nativePullRequestDestination(url, context, projects);+ // Read at press time so a capability push does not hand every link a new handler.+ const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);+ const params = nativePullRequestDestination(+ url,+ context,+ projects,+ (environmentId) => serverConfigs.get(environmentId)?.environment.capabilities,+ );if (!params) return tryOpenExternalUrl(url, "pull-request");if (Platform.OS === "android")resetAndroidWorkspace(navigation, { name: "PullRequest", params });diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsxindex f08251b1842..c7b30050892 100644--- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx+++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx@@ -10,7 +10,7 @@ import { Minus, Plus } from "lucide";import { useState, type ComponentProps, type MouseEvent as ReactMouseEvent } from "react";import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";-import { findProjectOnChangeRequestHost } from "~/lib/openPullRequestLink";+import { findProjectOnChangeRequestHost } from "@t3tools/client-runtime/change-request-links";import { useProjects } from "~/state/entities";import { threadEnvironment } from "~/state/threads";diff --git a/apps/web/src/lib/openPullRequestLink.test.ts b/apps/web/src/lib/openPullRequestLink.test.tsdeleted file mode 100644index 4b0de9244c5..00000000000--- a/apps/web/src/lib/openPullRequestLink.test.ts+++ /dev/null@@ -1,40 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import { findProjectOnChangeRequestHost } from "./openPullRequestLink";--describe("findProjectOnChangeRequestHost", () => {- const project = (id: string, identity: Record<string, unknown>) =>- ({ id, repositoryIdentity: identity }) as never;- const frontend = project("frontend", {- canonicalKey: "github.com/acme/frontend",- provider: "github",- owner: "acme",- name: "frontend",- });- const backend = project("backend", {- canonicalKey: "github.com/acme/backend",- provider: "github",- owner: "acme",- name: "backend",- });-- it("prefers the project checked out from the link's own repository", () => {- expect(- findProjectOnChangeRequestHost([frontend, backend], {- host: "github.com",- repository: "acme/backend",- number: 7,- }),- ).toBe(backend);- });-- it("lends any project on the host to a repository nobody has checked out", () => {- expect(- findProjectOnChangeRequestHost([frontend], {- host: "github.com",- repository: "acme/backend",- number: 7,- }),- ).toBe(frontend);- });-});diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.tsindex 670484f0bdf..b6928a805d3 100644--- a/apps/web/src/lib/openPullRequestLink.ts+++ b/apps/web/src/lib/openPullRequestLink.ts@@ -4,19 +4,14 @@ import { useNavigate } from "@tanstack/react-router";import { type MouseEvent } from "react";import {- findProjectForChangeRequest,+ resolveChangeRequestLinkTarget,resolvePullRequestPreviewTarget,} from "@t3tools/client-runtime/change-request-links";-import {- sourceControlClients,- type ChangeRequestLink,-} from "@t3tools/client-runtime/source-control-clients";import { useOpenLink } from "../browser/useOpenLink";import { useClientSettings } from "../hooks/useSettings";import { stackedThreadToast, toastManager } from "../components/ui/toast";import { useRightPanelStore } from "../rightPanelStore";-import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import { appAtomRegistry } from "../rpc/atomRegistry";import { readProjects, useProjects } from "../state/entities";@@ -34,21 +29,6 @@ export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null,});}-export function findProjectOnChangeRequestHost(- projects: ReadonlyArray<EnvironmentProject>,- link: ChangeRequestLink,-): EnvironmentProject | undefined {- const own = findProjectForChangeRequest(projects, link);- if (own !== undefined) return own;- return projects.find((project) => {- const identity = project.repositoryIdentity;- return (- identity?.provider !== undefined &&- sourceControlClients.get(identity.provider).canReadChangeRequestOnHost(identity, link)- );- });-}-function shouldOpenPullRequestExternally(event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey"> &Partial<Pick<MouseEvent<HTMLElement>, "button">>,@@ -77,47 +57,27 @@ export function useOpenChangeRequestLink(// subscribing would hand every rendered link a new handler. Projects likewise, so a// link can resolve against a snapshot that arrived after this handler was built.const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);- const allProjects = readProjects();const resolvedThreadRef = targetThreadRef ?? threadRef;const resolvedPanelRef = panelRef ?? resolvedThreadRef;- const parsed = sourceControlClients.parseChangeRequestUrl(targetUrl)?.link;- if (parsed === undefined) return false;- const reads = (environmentId: string) =>- serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===- true;- // Matching remotes do not make project ids usable outside the panel thread's environment.- const projects = resolvedThreadRef- ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)- : targetEnvironmentId- ? allProjects.filter((project) => project.environmentId === targetEnvironmentId)- : allProjects- .filter((project) => reads(project.environmentId))- .toSorted(- (left, right) =>- Number(right.environmentId === primaryEnvironmentId) -- Number(left.environmentId === primaryEnvironmentId),- );- const exactProject = findProjectForChangeRequest(projects, parsed);- const project =- exactProject ??- (resolvedPanelRef- ? findProjectOnChangeRequestHost(- projects.filter(- (candidate) =>- serverConfigs.get(candidate.environmentId)?.environment.capabilities- .threadPullRequests === true,- ),- parsed,- )- : undefined);- if (project === undefined || !reads(project.environmentId)) return false;- const repository =- serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests === true- ? parsed.repository- : (sourceControlClients.repositorySelector(project.repositoryIdentity) ??- parsed.repository);+ const target = resolveChangeRequestLinkTarget({+ url: targetUrl,+ projects: readProjects(),+ capabilities: (environmentId) => serverConfigs.get(environmentId)?.environment.capabilities,+ environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId,+ primaryEnvironmentId,+ lendHostProject: resolvedPanelRef !== undefined,+ });+ if (target === null) return false;+ const { project, repository, number, host } = target;event.preventDefault();event.stopPropagation();+ const pullRequestsSearch = {+ repository,+ number,+ ...(host === undefined ? {} : { selectedHost: host }),+ selectedProjectId: project.id,+ selectedEnvironmentId: project.environmentId,+ };if (resolvedPanelRef) {useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {// The standalone PR panel has a synthetic ref; each tab keeps its real environment.@@ -125,13 +85,10 @@ export function useOpenChangeRequestLink(? {}: { environmentId: project.environmentId }),projectId: project.id,- ...(serverConfigs.get(project.environmentId)?.environment.capabilities- .threadPullRequests === true- ? { host: parsed.authority ?? parsed.host }- : {}),+ ...(host === undefined ? {} : { host }),repository,url: targetUrl,- number: parsed.number,+ number,});if (!resolvedThreadRef) {void navigate({@@ -140,11 +97,7 @@ export function useOpenChangeRequestLink(...previous,involvement: previous.involvement ?? "all",state: previous.state ?? "all",- repository,- number: parsed.number,- selectedHost: parsed.authority ?? parsed.host,- selectedProjectId: project.id,- selectedEnvironmentId: project.environmentId,+ ...pullRequestsSearch,}),replace: true,});@@ -153,15 +106,7 @@ export function useOpenChangeRequestLink(}void navigate({to: "/pull-requests",- search: {- involvement: "all",- state: "all",- repository,- number: parsed.number,- selectedHost: parsed.authority ?? parsed.host,- selectedProjectId: project.id,- selectedEnvironmentId: project.environmentId,- },+ search: { involvement: "all", state: "all", ...pullRequestsSearch },});return true;};diff --git a/packages/client-runtime/src/changeRequestLinks.test.ts b/packages/client-runtime/src/changeRequestLinks.test.tsindex be25a3e5b10..243c71913b1 100644--- a/packages/client-runtime/src/changeRequestLinks.test.ts+++ b/packages/client-runtime/src/changeRequestLinks.test.ts@@ -8,7 +8,9 @@ import { describe, expect, it } from "vite-plus/test";import {findProjectForChangeRequest,+ findProjectOnChangeRequestHost,projectChangeRequestUrl,+ resolveChangeRequestLinkTarget,resolvePullRequestPreviewTarget,} from "./changeRequestLinks.ts";@@ -54,6 +56,112 @@ describe("findProjectForChangeRequest", () => {});});+describe("findProjectOnChangeRequestHost", () => {+ const project = (id: string, identity: Record<string, unknown>) =>+ ({ id, repositoryIdentity: identity }) as never;+ const frontend = project("frontend", {+ canonicalKey: "github.com/acme/frontend",+ provider: "github",+ owner: "acme",+ name: "frontend",+ });+ const backend = project("backend", {+ canonicalKey: "github.com/acme/backend",+ provider: "github",+ owner: "acme",+ name: "backend",+ });++ it("prefers the project checked out from the link's own repository", () => {+ expect(+ findProjectOnChangeRequestHost([frontend, backend], {+ host: "github.com",+ repository: "acme/backend",+ number: 7,+ }),+ ).toBe(backend);+ });++ it("lends any project on the host to a repository nobody has checked out", () => {+ expect(+ findProjectOnChangeRequestHost([frontend], {+ host: "github.com",+ repository: "acme/backend",+ number: 7,+ }),+ ).toBe(frontend);+ });+});++describe("resolveChangeRequestLinkTarget", () => {+ const local = EnvironmentId.make("local");+ const remote = EnvironmentId.make("remote");+ const project = (id: string, environmentId: EnvironmentId, canonicalKey: string) => ({+ id: ProjectId.make(id),+ environmentId,+ repositoryIdentity: {+ canonicalKey,+ provider: SourceControlProviderKind.make(+ canonicalKey.startsWith("git.cafe") ? "gitcafe" : "github",+ ),+ displayName: canonicalKey.split("/").slice(1).join("/"),+ locator: { source: "git-remote", remoteName: "origin", remoteUrl: `https://${canonicalKey}` },+ } satisfies RepositoryIdentity,+ });+ const mirrored = project("mirrored", local, "git.cafe/acme/app");+ const sibling = project("sibling", local, "github.com/acme/tools");+ const elsewhere = project("elsewhere", remote, "github.com/acme/app");+ const projects = [mirrored, sibling, elsewhere];+ const hostReads = () => ({ pullRequests: true, threadPullRequests: true });+ const url = "https://github.com/acme/app/pull/7";++ it("opens a mirror's link in its own environment under a project on the link's host", () => {+ expect(+ resolveChangeRequestLinkTarget({+ url,+ projects,+ capabilities: hostReads,+ environmentId: local,+ projectId: mirrored.id,+ lendHostProject: true,+ }),+ ).toEqual({ project: sibling, host: "github.com", repository: "acme/app", number: 7 });+ });++ it("only borrows a host project for views that can show any repository on the host", () => {+ const resolve = (capabilities: typeof hostReads, lendHostProject: boolean) =>+ resolveChangeRequestLinkTarget({+ url,+ projects,+ capabilities,+ environmentId: local,+ lendHostProject,+ });+ expect(resolve(hostReads, false)).toBeNull();+ expect(resolve(() => ({ pullRequests: true, threadPullRequests: false }), true)).toBeNull();+ });++ it("finds the checked-out repository in any environment that reads change requests", () => {+ expect(+ resolveChangeRequestLinkTarget({+ url,+ projects,+ capabilities: hostReads,+ primaryEnvironmentId: local,+ lendHostProject: false,+ })?.project,+ ).toBe(elsewhere);+ expect(+ resolveChangeRequestLinkTarget({+ url,+ projects,+ capabilities: (environmentId) => (environmentId === remote ? undefined : hostReads()),+ lendHostProject: false,+ }),+ ).toBeNull();+ });+});+describe("resolvePullRequestPreviewTarget", () => {const environmentId = EnvironmentId.make("env-1");const project = {diff --git a/packages/client-runtime/src/changeRequestLinks.ts b/packages/client-runtime/src/changeRequestLinks.tsindex 2629a934c58..cdf0bf7732f 100644--- a/packages/client-runtime/src/changeRequestLinks.ts+++ b/packages/client-runtime/src/changeRequestLinks.ts@@ -28,6 +28,98 @@ export function findProjectForChangeRequest<Project extends ChangeRequestProject});}+/** Prefers the project checked out from the link's repository, else lends any project on its host. */+export function findProjectOnChangeRequestHost<Project extends ChangeRequestProject>(+ projects: ReadonlyArray<Project>,+ link: ChangeRequestLink,+): Project | undefined {+ return (+ findProjectForChangeRequest(projects, link) ??+ projects.find((project) => {+ const identity = project.repositoryIdentity;+ return (+ identity?.provider !== undefined &&+ sourceControlClients.get(identity.provider).canReadChangeRequestOnHost(identity, link)+ );+ })+ );+}++export interface ChangeRequestLinkCapabilities {+ readonly pullRequests?: boolean | undefined;+ readonly threadPullRequests?: boolean | undefined;+}++/**+ * Where every client opens a change request link in the app, or null for the browser. A link+ * opened into a pull request view may borrow any project on its host when the server reads+ * change requests by host, so a mirror's or a sibling repository's link still opens in the app.+ */+export function resolveChangeRequestLinkTarget<Project extends ChangeRequestProject>({+ url,+ projects,+ capabilities,+ environmentId,+ projectId,+ primaryEnvironmentId,+ lendHostProject,+}: {+ url: string;+ projects: ReadonlyArray<Project>;+ capabilities: (environmentId: EnvironmentId) => ChangeRequestLinkCapabilities | undefined;+ /** The link's own environment; without one, any environment that reads change requests. */+ environmentId?: EnvironmentId | undefined;+ /** The project the link came from, tried first. */+ projectId?: ProjectId | undefined;+ primaryEnvironmentId?: EnvironmentId | null | undefined;+ lendHostProject: boolean;+}): {+ readonly project: Project;+ readonly repository: string;+ readonly number: number;+ readonly host?: string;+} | null {+ const link = sourceControlClients.parseChangeRequestUrl(url)?.link;+ if (link === undefined) return null;+ // Matching remotes do not make project ids usable outside the link's environment.+ const candidates = (+ environmentId === undefined+ ? projects.filter((project) => capabilities(project.environmentId)?.pullRequests === true)+ : projects.filter((project) => project.environmentId === environmentId)+ ).sort(+ (left, right) =>+ Number(right.id === projectId) - Number(left.id === projectId) ||+ Number(right.environmentId === primaryEnvironmentId) -+ Number(left.environmentId === primaryEnvironmentId),+ );+ const project =+ findProjectForChangeRequest(candidates, link) ??+ (lendHostProject+ ? findProjectOnChangeRequestHost(+ candidates.filter(+ (candidate) => capabilities(candidate.environmentId)?.threadPullRequests === true,+ ),+ link,+ )+ : undefined);+ if (project === undefined) return null;+ const projectCapabilities = capabilities(project.environmentId);+ if (projectCapabilities?.pullRequests !== true) return null;+ return projectCapabilities.threadPullRequests === true+ ? {+ project,+ repository: link.repository,+ number: link.number,+ host: link.authority ?? link.host,+ }+ : {+ project,+ repository:+ sourceControlClients.repositorySelector(project.repositoryIdentity) ?? link.repository,+ number: link.number,+ };+}+export function resolvePullRequestPreviewTarget({environmentId,projects,