Skip to content

Commit 18062da

Browse files
feat(web): choose whether links open in the default browser or in T3 Code (pingdotgg#9339)
1 parent d42254d commit 18062da

24 files changed

Lines changed: 509 additions & 168 deletions

‎apps/desktop/src/settings/DesktopClientSettings.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
1818
browserDefaultZoomFactor: 1.25,
1919
browserDefaultAppearance: "dark",
2020
browserRecordingFrameRate: 60,
21+
browserLinkTarget: "app",
2122
browserAutoShowFloatingPreview: false,
2223
browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
2324
browserDefaultProfileId: "work",
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { resolveLinkTarget } from "./browserLinkTarget";
4+
5+
const click = { metaKey: false, ctrlKey: false };
6+
7+
describe("resolveLinkTarget", () => {
8+
it("keeps the system browser unless the user asked for in-app", () => {
9+
expect(
10+
resolveLinkTarget({
11+
url: "https://example.com/",
12+
event: click,
13+
preference: "system",
14+
canOpenInApp: true,
15+
}),
16+
).toBe("system");
17+
});
18+
19+
it("opens in-app when asked and the runtime can", () => {
20+
expect(
21+
resolveLinkTarget({
22+
url: "https://example.com/",
23+
event: click,
24+
preference: "app",
25+
canOpenInApp: true,
26+
}),
27+
).toBe("app");
28+
});
29+
30+
it("falls back to the system browser where there is no in-app browser", () => {
31+
// The hosted web app and mobile have nowhere to open a tab, so the
32+
// preference cannot be honoured there and the link still has to open.
33+
expect(
34+
resolveLinkTarget({
35+
url: "https://example.com/",
36+
event: click,
37+
preference: "app",
38+
canOpenInApp: false,
39+
}),
40+
).toBe("system");
41+
});
42+
43+
it("treats a modifier click as the way out of the in-app default", () => {
44+
expect(
45+
resolveLinkTarget({
46+
url: "https://example.com/",
47+
event: { metaKey: true, ctrlKey: false },
48+
preference: "app",
49+
canOpenInApp: true,
50+
}),
51+
).toBe("system");
52+
expect(
53+
resolveLinkTarget({
54+
url: "https://example.com/",
55+
event: { metaKey: false, ctrlKey: true },
56+
preference: "app",
57+
canOpenInApp: true,
58+
}),
59+
).toBe("system");
60+
});
61+
62+
it("leaves non-web schemes to the shell", () => {
63+
for (const url of ["mailto:[email protected]", "vscode://file/x", "not a url"]) {
64+
expect(resolveLinkTarget({ url, event: click, preference: "app", canOpenInApp: true })).toBe(
65+
"system",
66+
);
67+
}
68+
});
69+
});
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Where a link clicked inside a thread should open.
3+
*
4+
* Settings → Integrations → Browser lets the user choose between the OS
5+
* default browser and a tab in the in-app browser. This module turns that
6+
* preference plus the click itself into one answer, so chat markdown and the
7+
* terminal drawer make the same decision and offer the same escape hatch.
8+
*
9+
* @module browserLinkTarget
10+
*/
11+
import type { BrowserLinkTarget } from "@t3tools/contracts";
12+
13+
import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings";
14+
import { isPreviewSupportedInRuntime } from "~/previewStateStore";
15+
16+
export interface ResolveLinkTargetInput {
17+
readonly url: string;
18+
/** Cmd/Ctrl-click always goes to the system browser, whatever the default. */
19+
readonly event: { readonly metaKey: boolean; readonly ctrlKey: boolean };
20+
readonly preference: BrowserLinkTarget;
21+
/** Whether this client has an in-app browser and a thread to open it beside. */
22+
readonly canOpenInApp: boolean;
23+
}
24+
25+
/**
26+
* The target a click resolves to. "app" only comes back when the preference
27+
* asks for it, the runtime can honour it, the URL is one the in-app browser
28+
* can load, and the click carried no modifier — the modifier is the one-gesture
29+
* way out when the default is in-app, mirroring how change-request links
30+
* already treat it.
31+
*/
32+
export function resolveLinkTarget(input: ResolveLinkTargetInput): BrowserLinkTarget {
33+
if (input.event.metaKey || input.event.ctrlKey) return "system";
34+
if (input.preference !== "app") return "system";
35+
if (!input.canOpenInApp) return "system";
36+
if (!isWebUrl(input.url)) return "system";
37+
return "app";
38+
}
39+
40+
/**
41+
* Only http(s) can load in the in-app browser. Anything else — mailto:,
42+
* vscode://, a bare fragment — belongs to the shell whatever the preference.
43+
*/
44+
export function isWebUrl(url: string): boolean {
45+
try {
46+
const { protocol } = new URL(url);
47+
return protocol === "http:" || protocol === "https:";
48+
} catch {
49+
return false;
50+
}
51+
}
52+
53+
/**
54+
* The configured default, once client settings have actually loaded. Before
55+
* hydration the snapshot is the schema default ("system"), so a link clicked
56+
* in the first moments after launch would ignore a persisted "app" — opening
57+
* is asynchronous anyway, so waiting costs nothing the user can see.
58+
*/
59+
export async function resolveBrowserLinkTargetPreference(): Promise<BrowserLinkTarget> {
60+
await ensureClientSettingsHydrated();
61+
return getClientSettings().browserLinkTarget;
62+
}
63+
64+
/** Whether the in-app target is available at all in this client. */
65+
export function canOpenLinksInApp(hasThread: boolean): boolean {
66+
return hasThread && isPreviewSupportedInRuntime();
67+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import type { ScopedThreadRef } from "@t3tools/contracts";
2+
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
3+
import { useCallback } from "react";
4+
5+
import { recordVisitForThread } from "~/browserHistoryStore";
6+
import { readLocalApi } from "~/localApi";
7+
import { previewEnvironment } from "~/state/preview";
8+
import { useAtomCommand } from "~/state/use-atom-command";
9+
10+
import {
11+
canOpenLinksInApp,
12+
resolveBrowserLinkTargetPreference,
13+
resolveLinkTarget,
14+
} from "./browserLinkTarget";
15+
import { openUrlInPreview } from "./openFileInPreview";
16+
17+
const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
18+
19+
/**
20+
* Opens a URL where the "Open links in" setting says, for buttons that sit
21+
* beside a thread but are not markdown anchors: CI check details, a pull
22+
* request that has no project to open in the panel. Without a thread there is
23+
* nowhere to put an in-app tab, so the link goes to the system browser.
24+
*
25+
* An in-app open that fails falls back to the system browser rather than
26+
* dropping the click: the user asked for the link, and the setting only says
27+
* where it should go first. The returned promise rejects only when that
28+
* fallback fails too, the same way `shell.openExternal` does.
29+
*/
30+
export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
31+
url: string,
32+
options?: {
33+
readonly event?: { readonly metaKey: boolean; readonly ctrlKey: boolean };
34+
/** Thread to open beside when it is not the hook's own, e.g. a sidebar row's. */
35+
readonly threadRef?: ScopedThreadRef | undefined;
36+
},
37+
) => Promise<void> {
38+
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
39+
return useCallback(
40+
async (url, options = {}) => {
41+
const targetThreadRef = options.threadRef ?? threadRef;
42+
const target = resolveLinkTarget({
43+
url,
44+
event: options.event ?? NO_MODIFIER,
45+
preference: await resolveBrowserLinkTargetPreference(),
46+
canOpenInApp: canOpenLinksInApp(Boolean(targetThreadRef)),
47+
});
48+
if (target === "app" && targetThreadRef) {
49+
const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview });
50+
if (isAtomCommandInterrupted(result)) return;
51+
if (result._tag === "Success") {
52+
recordVisitForThread(targetThreadRef, url);
53+
return;
54+
}
55+
console.error(result.cause);
56+
}
57+
const api = readLocalApi();
58+
if (!api) throw new Error("Link opening is unavailable.");
59+
await api.shell.openExternal(url);
60+
},
61+
[openPreview, threadRef],
62+
);
63+
}

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ import { LRUCache } from "../lib/lruCache";
119119
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
120120
import { RenderErrorBoundary } from "./RenderErrorBoundary";
121121
import { useTheme } from "../hooks/useTheme";
122-
import { getClientSettings } from "../hooks/useSettings";
122+
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
123123
import {
124124
chatMarkdownClipboardPayload,
125125
serializeTableElementToCsv,
@@ -173,6 +173,7 @@ import {
173173
openUrlInPreview,
174174
BrowserPreviewUnavailableError,
175175
} from "../browser/openFileInPreview";
176+
import { resolveLinkTarget } from "../browser/browserLinkTarget";
176177

177178
interface ChatMarkdownProps {
178179
text: string;
@@ -2120,6 +2121,10 @@ function ChatMarkdown({
21202121
event.clipboardData.setData("text/html", payload.html);
21212122
}, []);
21222123
const openChangeRequestLink = useOpenChangeRequestLink(threadRef);
2124+
// Subscribed rather than read at click time: the anchor has to decide
2125+
// synchronously whether to intercept its `_blank`, and a subscription is what
2126+
// makes a persisted "app" apply once settings hydrate after launch.
2127+
const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
21232128
const resolveThreadPullRequest = useCallback(
21242129
(href: string): ThreadLinkedPullRequest | null => {
21252130
if (
@@ -2472,9 +2477,35 @@ function ChatMarkdown({
24722477
}
24732478
// A link to a change request in a workspace project opens beside the
24742479
// conversation instead of in a browser: it is the thing being talked about, and
2475-
// the panel it opens offers the browser as one of its actions. Anything else is
2476-
// an ordinary link and keeps the `_blank` the shell already handles.
2477-
if (href) openChangeRequestLink(event, href);
2480+
// the panel it opens offers the browser as one of its actions.
2481+
if (!href || openChangeRequestLink(event, href)) return;
2482+
// Anything else follows the "Open links in" setting. The system browser
2483+
// keeps the `_blank` the shell already handles; the in-app browser needs
2484+
// the click intercepted here. A modifier click is the way out of the
2485+
// in-app default, so it is left to the shell too.
2486+
if (
2487+
event.defaultPrevented ||
2488+
resolveLinkTarget({
2489+
url: href,
2490+
event,
2491+
preference: linkTargetPreference,
2492+
canOpenInApp: canOpenInPreview,
2493+
}) !== "app"
2494+
) {
2495+
return;
2496+
}
2497+
event.preventDefault();
2498+
event.stopPropagation();
2499+
// The click was taken from the shell, so an in-app open that fails
2500+
// hands the link to the system browser instead of dropping it.
2501+
void openExternalLinkInPreview(href).then((result) => {
2502+
if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
2503+
reportMarkdownActionFailure(
2504+
{ operation: "open-link-in-preview", target: href },
2505+
result.cause,
2506+
);
2507+
void readLocalApi()?.shell.openExternal(href);
2508+
});
24782509
}}
24792510
onContextMenu={(event) => {
24802511
if (!href || !faviconHost) return;
@@ -2711,6 +2742,7 @@ function ChatMarkdown({
27112742
inlineCodeFileLinkMetaByText,
27122743
imageBaseDir,
27132744
isStreaming,
2745+
linkTargetPreference,
27142746
markdownFileLinkMetaByHref,
27152747
onTaskListChange,
27162748
onUseArtifactTemplate,

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7323,6 +7323,7 @@ function ChatViewContent(props: ChatViewProps) {
73237323
<PullRequestDetailPanel
73247324
key={`${renderedRightPanelSurface.repository}#${renderedRightPanelSurface.number}`}
73257325
environmentId={activeThread.environmentId}
7326+
threadRef={activeThreadRef}
73267327
reference={{
73277328
projectId: renderedRightPanelSurface.projectId as ProjectId,
73287329
repository: renderedRightPanelSurface.repository,

‎apps/web/src/components/GitActionsControl.tsx‎

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import {
3232
ChevronDownIcon,
3333
CloudDownloadIcon,
3434
CloudUploadIcon,
35-
ExternalLinkIcon,
3635
GitBranchPlusIcon,
3736
GitCommitIcon,
3837
InfoIcon,
@@ -97,9 +96,9 @@ import { vcsEnvironment } from "~/state/vcs";
9796
import { randomUUID } from "~/lib/utils";
9897
import { resolvePathLinkTarget } from "~/terminal-links";
9998
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
100-
import { readLocalApi } from "~/localApi";
10199
import { getSourceControlPresentation } from "~/sourceControlPresentation";
102-
import { openPullRequestLink, useOpenPrLink } from "~/lib/openPullRequestLink";
100+
import { useOpenLink } from "~/browser/useOpenLink";
101+
import { useOpenPrLink } from "~/lib/openPullRequestLink";
103102

104103
interface GitActionsControlProps {
105104
gitCwd: string | null;
@@ -384,10 +383,13 @@ interface PublishRepositoryDialogProps {
384383
readonly open: boolean;
385384
readonly onOpenChange: (open: boolean) => void;
386385
readonly environmentId: ScopedThreadRef["environmentId"] | null;
386+
/** Thread the dialog was opened from, so the new repository can open beside it. */
387+
readonly threadRef: ScopedThreadRef | null;
387388
readonly gitCwd: string;
388389
}
389390

390391
function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
392+
const openLink = useOpenLink(props.threadRef);
391393
const navigate = useNavigate();
392394
const sourceControlDiscovery = useEnvironmentQuery(
393395
props.environmentId === null
@@ -911,12 +913,9 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
911913
size="sm"
912914
className="w-full"
913915
onClick={() => {
914-
const api = readLocalApi();
915-
if (!api) return;
916-
void api.shell.openExternal(publishResult.repository.url);
916+
void openLink(publishResult.repository.url).catch(() => undefined);
917917
}}
918918
>
919-
<ExternalLinkIcon className="size-3.5" aria-hidden />
920919
Open on {publishProviderLabel}
921920
</Button>
922921
</>
@@ -1004,6 +1003,7 @@ export default function GitActionsControl({
10041003
[activeThreadRef],
10051004
);
10061005
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
1006+
const openLink = useOpenLink(activeThreadRef);
10071007
const activeDraftThread = useComposerDraftStore((store) =>
10081008
draftId
10091009
? store.getDraftSession(draftId)
@@ -1238,15 +1238,6 @@ export default function GitActionsControl({
12381238
onOpenPullRequest(openPr.number);
12391239
return;
12401240
}
1241-
const api = readLocalApi();
1242-
if (!api) {
1243-
toastManager.add({
1244-
type: "error",
1245-
title: "Link opening is unavailable.",
1246-
data: threadToastData,
1247-
});
1248-
return;
1249-
}
12501241
const prUrl = openPr?.url ?? null;
12511242
if (!prUrl) {
12521243
toastManager.add({
@@ -1256,7 +1247,7 @@ export default function GitActionsControl({
12561247
});
12571248
return;
12581249
}
1259-
void openPullRequestLink(api.shell, prUrl).catch((err: unknown) => {
1250+
void openLink(prUrl).catch((err: unknown) => {
12601251
console.error(err);
12611252
toastManager.add(
12621253
stackedThreadToast({
@@ -1267,7 +1258,7 @@ export default function GitActionsControl({
12671258
}),
12681259
);
12691260
});
1270-
}, [gitStatusForActions, onOpenPullRequest, threadToastData]);
1261+
}, [gitStatusForActions, onOpenPullRequest, openLink, threadToastData]);
12711262

12721263
runGitActionWithToast = useEffectEvent(
12731264
async ({
@@ -2010,6 +2001,7 @@ export default function GitActionsControl({
20102001
open={isPublishDialogOpen}
20112002
onOpenChange={setIsPublishDialogOpen}
20122003
environmentId={activeEnvironmentId}
2004+
threadRef={activeThreadRef}
20132005
gitCwd={gitCwd}
20142006
/>
20152007

0 commit comments

Comments
 (0)