Skip to content
TypeScript

fix(desktop): route external PR links to the pull request view (#22048)

Timb99955489af3
diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
new file mode 100644
index 00000000000..63c73d52d05
--- /dev/null
+++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
@@ -0,0 +1,147 @@
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import type { Atom } from "effect/reactivity";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vite-plus/test";
+
+const state = vi.hoisted(() => ({
+ projects: [] as never[],
+ navigate: vi.fn(async (): Promise<void> => undefined),
+ openScratchProject: vi.fn(async () => null),
+}));
+
+// One connected primary environment that can read pull requests. Its project list and
+// discovery flag start empty so a test can deliver links before they arrive.
+vi.mock(import("@tanstack/react-router"), async (original) => ({
+ ...(await original()),
+ useNavigate: (() => state.navigate) as never,
+ useRouter: (() => ({ navigate: state.navigate, state: { matches: [] } })) as never,
+}));
+vi.mock(import("../../state/environments"), async (original) => ({
+ ...(await original()),
+ usePrimaryEnvironmentId: () => "local" as EnvironmentId,
+ usePrimaryEnvironment: (() => ({
+ environmentId: "local",
+ connection: { phase: "connected" },
+ serverConfig: {},
+ })) as never,
+}));
+vi.mock(import("../../state/server"), async (original) => {
+ const { Atom } = await import("effect/reactivity");
+ const capabilities = { pullRequests: true, threadPullRequests: true };
+ return {
+ ...(await original()),
+ environmentServerConfigsAtom: Atom.make(
+ new Map([["local", { environment: { capabilities } }]]),
+ ) as never,
+ };
+});
+vi.mock(import("../../state/shell"), async (original) => {
+ const { Atom } = await import("effect/reactivity");
+ return { ...(await original()), allReachableShellsLiveAtom: Atom.make(false) };
+});
+vi.mock(import("../../state/entities"), async (original) => ({
+ ...(await original()),
+ readProjects: () => state.projects,
+}));
+vi.mock(import("../../hooks/useScratchProject"), async (original) => ({
+ ...(await original()),
+ useScratchProject: (() => ({
+ scratchEnvironmentId: () => "local",
+ openScratchProject: state.openScratchProject,
+ })) as never,
+}));
+
+import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
+import { allReachableShellsLiveAtom } from "../../state/shell";
+import { DesktopWebLinkCoordinator } from "./DesktopWebLinkCoordinator";
+
+const discoverySettled = allReachableShellsLiveAtom as Atom.Writable<boolean>;
+const environmentId = EnvironmentId.make("local");
+const projectId = ProjectId.make("effect");
+const project = {
+ id: projectId,
+ environmentId,
+ repositoryIdentity: {
+ provider: "github",
+ displayName: "Effect-TS/effect",
+ canonicalKey: "github.com/effect-ts/effect",
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "https://github.com/Effect-TS/effect.git",
+ },
+ },
+} as never;
+const pullRequestUrl = "https://github.com/Effect-TS/effect/pull/9339";
+const pullRequestView = {
+ to: "/pull-requests",
+ search: {
+ involvement: "all",
+ state: "all",
+ repository: "effect-ts/effect",
+ number: 9339,
+ selectedHost: "github.com",
+ selectedProjectId: projectId,
+ selectedEnvironmentId: environmentId,
+ },
+};
+
+let root: Root;
+
+/** Mounts the coordinator behind a desktop bridge that hands over `urls` once the renderer is ready. */
+async function mount(...urls: string[]) {
+ let deliver: ((url: string) => void) | undefined;
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.stubGlobal("desktopBridge", {
+ getClientSettings: async () => null,
+ webLinks: {
+ onOpen: (listener: (url: string) => void) => {
+ deliver = listener;
+ return () => undefined;
+ },
+ setReady: async (ready: boolean) => {
+ if (ready) for (const url of urls.splice(0)) deliver?.(url);
+ },
+ },
+ });
+ root = createRoot(document.createElement("div"));
+ await act(async () =>
+ root.render(
+ <AppAtomRegistryProvider>
+ <DesktopWebLinkCoordinator />
+ </AppAtomRegistryProvider>,
+ ),
+ );
+}
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ state.projects = [];
+ appAtomRegistry.set(discoverySettled, false);
+});
+
+it("holds a launch PR link until project discovery settles, then opens the PR view", async () => {
+ await mount(pullRequestUrl);
+ expect(state.navigate).not.toHaveBeenCalled();
+ expect(state.openScratchProject).not.toHaveBeenCalled();
+
+ state.projects = [project];
+ const navigated = new Promise<void>((resolve) => {
+ state.navigate.mockImplementationOnce(async () => resolve());
+ });
+ await act(async () => {
+ appAtomRegistry.set(discoverySettled, true);
+ await navigated;
+ });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith(pullRequestView);
+ expect(state.openScratchProject).not.toHaveBeenCalled();
+});
+
+it("opens an ordinary link in the browser while a PR link is still held", async () => {
+ await mount(pullRequestUrl, "https://example.com/docs");
+ expect(state.openScratchProject).toHaveBeenCalledOnce();
+ expect(state.navigate).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
index 5b46b60ba52..6e42b7257c3 100644
--- a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
+++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
@@ -1,8 +1,12 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
+import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
import { useRouter } from "@tanstack/react-router";
+import * as Effect from "effect/Effect";
+import { AtomRegistry } from "effect/reactivity";
+import * as Stream from "effect/Stream";
import { useEffect, useEffectEvent, useRef } from "react";
import { openFileInPreview, openUrlInPreview } from "../../browser/openFileInPreview";
@@ -10,15 +14,37 @@ import { isPreviewAvailableFor } from "../../browser/previewRuntime";
import { useComposerDraftStore } from "../../composerDraftStore";
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
import { useScratchProject } from "../../hooks/useScratchProject";
+import { useClientSettings } from "../../hooks/useSettings";
+import { useOpenChangeRequestLink } from "../../lib/openPullRequestLink";
import { selectActiveRightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
+import { appAtomRegistry } from "../../rpc/atomRegistry";
import { resolveThreadRouteTarget } from "../../threadRoutes";
import { assetEnvironment } from "../../state/assets";
import { useEnvironmentHttpBaseUrl, usePrimaryEnvironment } from "../../state/environments";
import { previewEnvironment } from "../../state/preview";
+import { allReachableShellsLiveAtom } from "../../state/shell";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { stackedThreadToast, toastManager } from "../ui/toast";
+/** A link handed over by the OS is a plain click: nothing about it asks for the browser. */
+const externalClick = {
+ preventDefault() {},
+ stopPropagation() {},
+ metaKey: false,
+ ctrlKey: false,
+};
+
+/** Resolves once every reachable environment has reported its projects or settled offline. */
+const projectsSettled = (): Promise<void> =>
+ Effect.runPromise(
+ AtomRegistry.toStream(appAtomRegistry, allReachableShellsLiveAtom).pipe(
+ Stream.filter((settled) => settled),
+ Stream.runHead,
+ Effect.asVoid,
+ ),
+ );
+
/**
* HTML files are served by this machine's environment, so only its threads can
* take them.
@@ -47,6 +73,8 @@ function threadShowingBrowser(
export function DesktopWebLinkCoordinator() {
const router = useRouter();
const primaryEnvironment = usePrimaryEnvironment();
+ const openPullRequestsInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
+ const openChangeRequest = useOpenChangeRequestLink();
const { scratchEnvironmentId, openScratchProject } = useScratchProject();
const openThread = useNewThreadHandler();
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
@@ -91,6 +119,7 @@ export function DesktopWebLinkCoordinator() {
await router.navigate({ href: appPath });
return;
}
+ if (openChangeRequest(externalClick, url)) return;
const isFile = url.startsWith("file:");
const routeParams = router.state.matches.at(-1)?.params ?? {};
const threadRef =
@@ -121,12 +150,23 @@ export function DesktopWebLinkCoordinator() {
}
});
+ const receiveLink = useEffectEvent((url: string) => {
+ // A connected server publishes its config before its project snapshot, so a PR link
+ // delivered at launch would miss its project and fall through to the browser. Hold PR
+ // links, and only those, until discovery settles; an ordinary link never waits for it.
+ const hold =
+ openPullRequestsInApp && parseChangeRequestUrl(url) !== null
+ ? projectsSettled()
+ : Promise.resolve();
+ void hold.then(() => {
+ queueRef.current = queueRef.current.then(() => openLink(url)).catch(() => undefined);
+ });
+ });
+
useEffect(() => {
if (!ready || webLinks === undefined) return;
let subscribed = true;
- const unsubscribe = webLinks.onOpen((url) => {
- queueRef.current = queueRef.current.then(() => openLink(url)).catch(() => undefined);
- });
+ const unsubscribe = webLinks.onOpen(receiveLink);
queueMicrotask(() => {
if (subscribed) void webLinks.setReady(true).catch(() => undefined);
});
diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.ts
index 323173e4cb6..ce5fb92778b 100644
--- a/apps/web/src/lib/openPullRequestLink.ts
+++ b/apps/web/src/lib/openPullRequestLink.ts
@@ -14,7 +14,7 @@ import { useRightPanelStore } from "../rightPanelStore";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { appAtomRegistry } from "../rpc/atomRegistry";
-import { useProjects } from "../state/entities";
+import { readProjects, useProjects } from "../state/entities";
import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
import { usePrimaryEnvironmentId } from "../state/environments";
@@ -116,14 +116,15 @@ export function useOpenChangeRequestLink(
targetEnvironmentId?: EnvironmentId,
) => boolean {
const navigate = useNavigate();
- const allProjects = useProjects();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
return (event, targetUrl, targetThreadRef, targetEnvironmentId) => {
if (!openInApp || shouldOpenPullRequestExternally(event)) return false;
// Read at click time: every provider status push replaces the config map, and
- // subscribing would hand every rendered link a new handler.
+ // 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 = parseChangeRequestUrl(targetUrl);
diff --git a/docs/user/default-browser.md b/docs/user/default-browser.md
index 7364608d211..1e1ef500345 100644
--- a/docs/user/default-browser.md
+++ b/docs/user/default-browser.md
@@ -8,6 +8,9 @@ page, so you can ask an agent about it right away.
Choose **T3 Code** under **System Settings → Desktop & Dock → Default web browser**. To go back,
choose another browser there.
+Pull request links for a connected project open in the pull request view when opening pull
+request links in the app is enabled. Other links still open in the browser panel.
+
HTML files you open from Finder open the same way. [Prompt links](prompt-links.md) to
app.t3.codes open in the app as a draft.