feat(web): choose whether links open in the default browser or in T3 Code (#9339)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-02 21:56:48 -07:00
1 parent d42254dfb4
commit 18062da942
24 files changed
+509 -168

No files matched your search

@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
browserDefaultZoomFactor: 1.25,
browserDefaultAppearance: "dark",
browserRecordingFrameRate: 60,
browserLinkTarget: "app",
browserAutoShowFloatingPreview: false,
browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
browserDefaultProfileId: "work",
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveLinkTarget } from "./browserLinkTarget";
const click = { metaKey: false, ctrlKey: false };
describe("resolveLinkTarget", () => {
it("keeps the system browser unless the user asked for in-app", () => {
expect(
resolveLinkTarget({
url: "https://example.com/",
event: click,
preference: "system",
canOpenInApp: true,
}),
).toBe("system");
});
it("opens in-app when asked and the runtime can", () => {
expect(
resolveLinkTarget({
url: "https://example.com/",
event: click,
preference: "app",
canOpenInApp: true,
}),
).toBe("app");
});
it("falls back to the system browser where there is no in-app browser", () => {
// The hosted web app and mobile have nowhere to open a tab, so the
// preference cannot be honoured there and the link still has to open.
expect(
resolveLinkTarget({
url: "https://example.com/",
event: click,
preference: "app",
canOpenInApp: false,
}),
).toBe("system");
});
it("treats a modifier click as the way out of the in-app default", () => {
expect(
resolveLinkTarget({
url: "https://example.com/",
event: { metaKey: true, ctrlKey: false },
preference: "app",
canOpenInApp: true,
}),
).toBe("system");
expect(
resolveLinkTarget({
url: "https://example.com/",
event: { metaKey: false, ctrlKey: true },
preference: "app",
canOpenInApp: true,
}),
).toBe("system");
});
it("leaves non-web schemes to the shell", () => {
for (const url of ["mailto:[email protected]", "vscode://file/x", "not a url"]) {
expect(resolveLinkTarget({ url, event: click, preference: "app", canOpenInApp: true })).toBe(
"system",
);
}
});
});
+67
View File
@@ -0,0 +1,67 @@
/**
* Where a link clicked inside a thread should open.
*
* Settings → Integrations → Browser lets the user choose between the OS
* default browser and a tab in the in-app browser. This module turns that
* preference plus the click itself into one answer, so chat markdown and the
* terminal drawer make the same decision and offer the same escape hatch.
*
* @module browserLinkTarget
*/
import type { BrowserLinkTarget } from "@t3tools/contracts";
import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings";
import { isPreviewSupportedInRuntime } from "~/previewStateStore";
export interface ResolveLinkTargetInput {
readonly url: string;
/** Cmd/Ctrl-click always goes to the system browser, whatever the default. */
readonly event: { readonly metaKey: boolean; readonly ctrlKey: boolean };
readonly preference: BrowserLinkTarget;
/** Whether this client has an in-app browser and a thread to open it beside. */
readonly canOpenInApp: boolean;
}
/**
* The target a click resolves to. "app" only comes back when the preference
* asks for it, the runtime can honour it, the URL is one the in-app browser
* can load, and the click carried no modifier — the modifier is the one-gesture
* way out when the default is in-app, mirroring how change-request links
* already treat it.
*/
export function resolveLinkTarget(input: ResolveLinkTargetInput): BrowserLinkTarget {
if (input.event.metaKey || input.event.ctrlKey) return "system";
if (input.preference !== "app") return "system";
if (!input.canOpenInApp) return "system";
if (!isWebUrl(input.url)) return "system";
return "app";
}
/**
* Only http(s) can load in the in-app browser. Anything else — mailto:,
* vscode://, a bare fragment — belongs to the shell whatever the preference.
*/
export function isWebUrl(url: string): boolean {
try {
const { protocol } = new URL(url);
return protocol === "http:" || protocol === "https:";
} catch {
return false;
}
}
/**
* The configured default, once client settings have actually loaded. Before
* hydration the snapshot is the schema default ("system"), so a link clicked
* in the first moments after launch would ignore a persisted "app" — opening
* is asynchronous anyway, so waiting costs nothing the user can see.
*/
export async function resolveBrowserLinkTargetPreference(): Promise<BrowserLinkTarget> {
await ensureClientSettingsHydrated();
return getClientSettings().browserLinkTarget;
}
/** Whether the in-app target is available at all in this client. */
export function canOpenLinksInApp(hasThread: boolean): boolean {
return hasThread && isPreviewSupportedInRuntime();
}
+63
View File
@@ -0,0 +1,63 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import { useCallback } from "react";
import { recordVisitForThread } from "~/browserHistoryStore";
import { readLocalApi } from "~/localApi";
import { previewEnvironment } from "~/state/preview";
import { useAtomCommand } from "~/state/use-atom-command";
import {
canOpenLinksInApp,
resolveBrowserLinkTargetPreference,
resolveLinkTarget,
} from "./browserLinkTarget";
import { openUrlInPreview } from "./openFileInPreview";
const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
/**
* Opens a URL where the "Open links in" setting says, for buttons that sit
* beside a thread but are not markdown anchors: CI check details, a pull
* request that has no project to open in the panel. Without a thread there is
* nowhere to put an in-app tab, so the link goes to the system browser.
*
* An in-app open that fails falls back to the system browser rather than
* dropping the click: the user asked for the link, and the setting only says
* where it should go first. The returned promise rejects only when that
* fallback fails too, the same way `shell.openExternal` does.
*/
export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
url: string,
options?: {
readonly event?: { readonly metaKey: boolean; readonly ctrlKey: boolean };
/** Thread to open beside when it is not the hook's own, e.g. a sidebar row's. */
readonly threadRef?: ScopedThreadRef | undefined;
},
) => Promise<void> {
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
return useCallback(
async (url, options = {}) => {
const targetThreadRef = options.threadRef ?? threadRef;
const target = resolveLinkTarget({
url,
event: options.event ?? NO_MODIFIER,
preference: await resolveBrowserLinkTargetPreference(),
canOpenInApp: canOpenLinksInApp(Boolean(targetThreadRef)),
});
if (target === "app" && targetThreadRef) {
const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview });
if (isAtomCommandInterrupted(result)) return;
if (result._tag === "Success") {
recordVisitForThread(targetThreadRef, url);
return;
}
console.error(result.cause);
}
const api = readLocalApi();
if (!api) throw new Error("Link opening is unavailable.");
await api.shell.openExternal(url);
},
[openPreview, threadRef],
);
}
+36 -4
View File
@@ -119,7 +119,7 @@ import { LRUCache } from "../lib/lruCache";
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
import { RenderErrorBoundary } from "./RenderErrorBoundary";
import { useTheme } from "../hooks/useTheme";
import { getClientSettings } from "../hooks/useSettings";
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
import {
chatMarkdownClipboardPayload,
serializeTableElementToCsv,
@@ -173,6 +173,7 @@ import {
openUrlInPreview,
BrowserPreviewUnavailableError,
} from "../browser/openFileInPreview";
import { resolveLinkTarget } from "../browser/browserLinkTarget";
interface ChatMarkdownProps {
text: string;
@@ -2120,6 +2121,10 @@ function ChatMarkdown({
event.clipboardData.setData("text/html", payload.html);
}, []);
const openChangeRequestLink = useOpenChangeRequestLink(threadRef);
// Subscribed rather than read at click time: the anchor has to decide
// synchronously whether to intercept its `_blank`, and a subscription is what
// makes a persisted "app" apply once settings hydrate after launch.
const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
const resolveThreadPullRequest = useCallback(
(href: string): ThreadLinkedPullRequest | null => {
if (
@@ -2472,9 +2477,35 @@ function ChatMarkdown({
}
// A link to a change request in a workspace project opens beside the
// conversation instead of in a browser: it is the thing being talked about, and
// the panel it opens offers the browser as one of its actions. Anything else is
// an ordinary link and keeps the `_blank` the shell already handles.
if (href) openChangeRequestLink(event, href);
// the panel it opens offers the browser as one of its actions.
if (!href || openChangeRequestLink(event, href)) return;
// Anything else follows the "Open links in" setting. The system browser
// keeps the `_blank` the shell already handles; the in-app browser needs
// the click intercepted here. A modifier click is the way out of the
// in-app default, so it is left to the shell too.
if (
event.defaultPrevented ||
resolveLinkTarget({
url: href,
event,
preference: linkTargetPreference,
canOpenInApp: canOpenInPreview,
}) !== "app"
) {
return;
}
event.preventDefault();
event.stopPropagation();
// The click was taken from the shell, so an in-app open that fails
// hands the link to the system browser instead of dropping it.
void openExternalLinkInPreview(href).then((result) => {
if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
reportMarkdownActionFailure(
{ operation: "open-link-in-preview", target: href },
result.cause,
);
void readLocalApi()?.shell.openExternal(href);
});
}}
onContextMenu={(event) => {
if (!href || !faviconHost) return;
@@ -2711,6 +2742,7 @@ function ChatMarkdown({
inlineCodeFileLinkMetaByText,
imageBaseDir,
isStreaming,
linkTargetPreference,
markdownFileLinkMetaByHref,
onTaskListChange,
onUseArtifactTemplate,
+1
View File
@@ -7323,6 +7323,7 @@ function ChatViewContent(props: ChatViewProps) {
<PullRequestDetailPanel
key={`${renderedRightPanelSurface.repository}#${renderedRightPanelSurface.number}`}
environmentId={activeThread.environmentId}
threadRef={activeThreadRef}
reference={{
projectId: renderedRightPanelSurface.projectId as ProjectId,
repository: renderedRightPanelSurface.repository,
+10 -18
View File
@@ -32,7 +32,6 @@ import {
ChevronDownIcon,
CloudDownloadIcon,
CloudUploadIcon,
ExternalLinkIcon,
GitBranchPlusIcon,
GitCommitIcon,
InfoIcon,
@@ -97,9 +96,9 @@ import { vcsEnvironment } from "~/state/vcs";
import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { readLocalApi } from "~/localApi";
import { getSourceControlPresentation } from "~/sourceControlPresentation";
import { openPullRequestLink, useOpenPrLink } from "~/lib/openPullRequestLink";
import { useOpenLink } from "~/browser/useOpenLink";
import { useOpenPrLink } from "~/lib/openPullRequestLink";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -384,10 +383,13 @@ interface PublishRepositoryDialogProps {
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
readonly environmentId: ScopedThreadRef["environmentId"] | null;
/** Thread the dialog was opened from, so the new repository can open beside it. */
readonly threadRef: ScopedThreadRef | null;
readonly gitCwd: string;
}
function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const openLink = useOpenLink(props.threadRef);
const navigate = useNavigate();
const sourceControlDiscovery = useEnvironmentQuery(
props.environmentId === null
@@ -911,12 +913,9 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
size="sm"
className="w-full"
onClick={() => {
const api = readLocalApi();
if (!api) return;
void api.shell.openExternal(publishResult.repository.url);
void openLink(publishResult.repository.url).catch(() => undefined);
}}
>
<ExternalLinkIcon className="size-3.5" aria-hidden />
Open on {publishProviderLabel}
</Button>
</>
@@ -1004,6 +1003,7 @@ export default function GitActionsControl({
[activeThreadRef],
);
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
const openLink = useOpenLink(activeThreadRef);
const activeDraftThread = useComposerDraftStore((store) =>
draftId
? store.getDraftSession(draftId)
@@ -1238,15 +1238,6 @@ export default function GitActionsControl({
onOpenPullRequest(openPr.number);
return;
}
const api = readLocalApi();
if (!api) {
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
data: threadToastData,
});
return;
}
const prUrl = openPr?.url ?? null;
if (!prUrl) {
toastManager.add({
@@ -1256,7 +1247,7 @@ export default function GitActionsControl({
});
return;
}
void openPullRequestLink(api.shell, prUrl).catch((err: unknown) => {
void openLink(prUrl).catch((err: unknown) => {
console.error(err);
toastManager.add(
stackedThreadToast({
@@ -1267,7 +1258,7 @@ export default function GitActionsControl({
}),
);
});
}, [gitStatusForActions, onOpenPullRequest, threadToastData]);
}, [gitStatusForActions, onOpenPullRequest, openLink, threadToastData]);
runGitActionWithToast = useEffectEvent(
async ({
@@ -2010,6 +2001,7 @@ export default function GitActionsControl({
open={isPublishDialogOpen}
onOpenChange={setIsPublishDialogOpen}
environmentId={activeEnvironmentId}
threadRef={activeThreadRef}
gitCwd={gitCwd}
/>
@@ -728,10 +728,8 @@ export function TerminalViewport({
};
void openTerminalLinkInPreview({
url: text,
position: { x: event.clientX, y: event.clientY },
threadRef,
openPreview,
localApi,
fallbackToBrowser,
});
return;
@@ -1,11 +1,10 @@
import type { LocalApi, PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import type { PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
openTerminalLinkInPreview,
TerminalLinkContextMenuShowError,
TerminalLinkPreviewOpenError,
} from "./openTerminalLinkInPreview";
@@ -30,6 +29,15 @@ vi.mock("~/browser/browserDefaults", () => ({
browserDefaultOpenProfileId: (defaults: { profileId: string }) => defaults.profileId,
}));
const linkTargetMocks = vi.hoisted(() => ({
preference: vi.fn<() => "system" | "app">(),
}));
vi.mock("~/browser/browserLinkTarget", () => ({
resolveBrowserLinkTargetPreference: async () => linkTargetMocks.preference(),
isWebUrl: (url: string) => /^https?:/u.test(url),
}));
const hydratedDefaults = {
viewport: { _tag: "fixed", width: 1280, height: 720 } as const,
profileId: "work",
@@ -50,7 +58,9 @@ const snapshot: PreviewSessionSnapshot = {
};
beforeEach(() => {
browserDefaultsMocks.resolve.mockReset();
browserDefaultsMocks.resolve.mockResolvedValue(hydratedDefaults);
linkTargetMocks.preference.mockReturnValue("app");
});
afterEach(() => {
@@ -58,6 +68,37 @@ afterEach(() => {
});
describe("openTerminalLinkInPreview", () => {
it("opens in the system browser while that is the configured target", async () => {
linkTargetMocks.preference.mockReturnValue("system");
const fallbackToBrowser = vi.fn();
const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
await openTerminalLinkInPreview({
url: "http://localhost:3000/",
threadRef,
openPreview,
fallbackToBrowser,
});
expect(fallbackToBrowser).toHaveBeenCalledOnce();
expect(openPreview).not.toHaveBeenCalled();
});
it("opens public URLs in-app too, not only local servers", async () => {
const fallbackToBrowser = vi.fn();
const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
await openTerminalLinkInPreview({
url: "https://example.com/docs",
threadRef,
openPreview,
fallbackToBrowser,
});
expect(openPreview).toHaveBeenCalledOnce();
expect(fallbackToBrowser).not.toHaveBeenCalled();
});
it("waits for hydrated viewport and profile defaults before opening", async () => {
let hydrate: ((defaults: typeof hydratedDefaults) => void) | undefined;
browserDefaultsMocks.resolve.mockImplementationOnce(
@@ -70,14 +111,8 @@ describe("openTerminalLinkInPreview", () => {
const opening = openTerminalLinkInPreview({
url: "http://localhost:3000/",
position: { x: 12, y: 34 },
threadRef,
openPreview,
localApi: {
contextMenu: {
show: vi.fn(async () => "open-in-preview"),
},
} as unknown as LocalApi,
fallbackToBrowser: vi.fn(),
});
@@ -97,42 +132,6 @@ describe("openTerminalLinkInPreview", () => {
});
});
it("preserves context-menu failures with terminal link context before falling back", async () => {
const cause = new Error("menu unavailable");
const fallbackToBrowser = vi.fn();
const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
const reportError = vi.spyOn(console, "error").mockImplementation(() => undefined);
await openTerminalLinkInPreview({
url: "http://localhost:3000/path?token=secret",
position: { x: 12, y: 34 },
threadRef,
openPreview,
localApi: {
contextMenu: {
show: vi.fn(async () => {
throw cause;
}),
},
} as unknown as LocalApi,
fallbackToBrowser,
});
expect(fallbackToBrowser).toHaveBeenCalledOnce();
expect(openPreview).not.toHaveBeenCalled();
expect(reportError).toHaveBeenCalledOnce();
const error = reportError.mock.calls[0]?.[0];
expect(error).toBeInstanceOf(TerminalLinkContextMenuShowError);
expect(error).toMatchObject({
environmentId: "local",
threadId: "thread-1",
targetOrigin: "http://localhost:3000",
cause,
});
expect(error.message).not.toContain("menu unavailable");
expect(error.targetOrigin).not.toContain("secret");
});
it("preserves the complete preview failure cause before falling back", async () => {
const rpcError = new Error("preview unavailable");
const cause = Cause.combine(Cause.fail(rpcError), Cause.die("preview defect"));
@@ -141,14 +140,8 @@ describe("openTerminalLinkInPreview", () => {
await openTerminalLinkInPreview({
url: "http://127.0.0.1:5173/",
position: { x: 12, y: 34 },
threadRef,
openPreview: async () => AsyncResult.failure(cause),
localApi: {
contextMenu: {
show: vi.fn(async () => "open-in-preview"),
},
} as unknown as LocalApi,
fallbackToBrowser,
});
@@ -171,14 +164,8 @@ describe("openTerminalLinkInPreview", () => {
await openTerminalLinkInPreview({
url: "http://localhost:5173/",
position: { x: 12, y: 34 },
threadRef,
openPreview: async () => AsyncResult.failure(Cause.interrupt()),
localApi: {
contextMenu: {
show: vi.fn(async () => "open-in-preview"),
},
} as unknown as LocalApi,
fallbackToBrowser,
});
@@ -1,6 +1,5 @@
import type { LocalApi, ScopedThreadRef } from "@t3tools/contracts";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import { isPreviewableUrl } from "@t3tools/shared/preview";
import * as Schema from "effect/Schema";
import {
@@ -8,6 +7,7 @@ import {
browserDefaultOpenViewport,
resolveBrowserDefaults,
} from "~/browser/browserDefaults";
import { isWebUrl, resolveBrowserLinkTargetPreference } from "~/browser/browserLinkTarget";
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
import { recordVisitForThread } from "~/browserHistoryStore";
import { applyPreviewServerSnapshot, isPreviewSupportedInRuntime } from "~/previewStateStore";
@@ -20,15 +20,6 @@ const terminalLinkErrorContext = {
cause: Schema.Defect(),
};
export class TerminalLinkContextMenuShowError extends Schema.TaggedErrorClass<TerminalLinkContextMenuShowError>()(
"TerminalLinkContextMenuShowError",
terminalLinkErrorContext,
) {
override get message(): string {
return `Failed to show the context menu for terminal link ${this.targetOrigin}.`;
}
}
export class TerminalLinkPreviewOpenError extends Schema.TaggedErrorClass<TerminalLinkPreviewOpenError>()(
"TerminalLinkPreviewOpenError",
terminalLinkErrorContext,
@@ -40,20 +31,26 @@ export class TerminalLinkPreviewOpenError extends Schema.TaggedErrorClass<Termin
interface OpenTerminalLinkInPreviewInput<E> {
readonly url: string;
readonly position: { x: number; y: number };
readonly threadRef: ScopedThreadRef;
readonly openPreview: OpenPreviewMutation<E>;
readonly localApi: LocalApi;
readonly fallbackToBrowser: () => void;
}
/**
* Opens a terminal hyperlink where the "Open links in" setting says. Terminal
* links are activated with the platform modifier already held, so unlike chat
* links the modifier cannot double as the system-browser override; the setting
* alone decides, and the system browser is the fallback whenever the in-app
* one cannot take the URL.
*/
export async function openTerminalLinkInPreview<E>(
input: OpenTerminalLinkInPreviewInput<E>,
): Promise<void> {
const supportsPreview =
isPreviewableUrl(input.url) &&
isWebUrl(input.url) &&
isPreviewSupportedInRuntime() &&
input.threadRef.threadId.length > 0;
input.threadRef.threadId.length > 0 &&
(await resolveBrowserLinkTargetPreference()) === "app";
if (!supportsPreview) {
input.fallbackToBrowser();
@@ -66,59 +63,32 @@ export async function openTerminalLinkInPreview<E>(
targetOrigin: new URL(input.url).origin,
};
let choice: "open-in-preview" | "open-in-browser" | null;
try {
choice = await input.localApi.contextMenu.show(
[
{ id: "open-in-preview", label: "Open in preview" },
{ id: "open-in-browser", label: "Open in browser" },
],
input.position,
);
} catch (cause) {
const defaults = await resolveBrowserDefaults();
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: {
threadId: input.threadRef.threadId,
url: input.url,
// Same reason as `openUrlInPreview`: this path handles its own result
// mapping, so the configured defaults are applied explicitly.
viewport: browserDefaultOpenViewport(defaults),
profileId: browserDefaultOpenProfileId(defaults),
},
});
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
return;
}
console.error(
new TerminalLinkContextMenuShowError({
new TerminalLinkPreviewOpenError({
...errorContext,
cause,
cause: result.cause,
}),
);
input.fallbackToBrowser();
return;
}
if (choice === "open-in-preview") {
const defaults = await resolveBrowserDefaults();
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: {
threadId: input.threadRef.threadId,
url: input.url,
// Same reason as `openUrlInPreview`: this path handles its own result
// mapping, so the configured defaults are applied explicitly.
viewport: browserDefaultOpenViewport(defaults),
profileId: browserDefaultOpenProfileId(defaults),
},
});
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
return;
}
console.error(
new TerminalLinkPreviewOpenError({
...errorContext,
cause: result.cause,
}),
);
input.fallbackToBrowser();
return;
}
recordVisitForThread(input.threadRef, input.url);
applyPreviewServerSnapshot(input.threadRef, result.value);
useRightPanelStore.getState().openBrowser(input.threadRef, result.value.tabId);
return;
}
if (choice === "open-in-browser") {
input.fallbackToBrowser();
}
recordVisitForThread(input.threadRef, input.url);
applyPreviewServerSnapshot(input.threadRef, result.value);
useRightPanelStore.getState().openBrowser(input.threadRef, result.value.tabId);
}
@@ -3,15 +3,17 @@ import type {
PullRequestCheck,
PullRequestChecksState,
PullRequestRef,
ScopedThreadRef,
} from "@t3tools/contracts";
import { readLocalApi } from "~/localApi";
import { useOpenLink } from "~/browser/useOpenLink";
import { cn } from "~/lib/utils";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import {
PullRequestCheckStatusIcon,
pullRequestCheckStatusLabel,
@@ -27,9 +29,11 @@ import {
function LazyChecksBody({
environmentId,
reference,
threadRef,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
threadRef: ScopedThreadRef | null;
}) {
const detailQuery = useEnvironmentQuery(
pullRequestEnvironment.detail({ environmentId, input: reference }),
@@ -44,10 +48,17 @@ function LazyChecksBody({
</p>
);
}
return <ChecksBody checks={detailQuery.data.checks} />;
return <ChecksBody checks={detailQuery.data.checks} threadRef={threadRef} />;
}
function ChecksBody({ checks }: { checks: ReadonlyArray<PullRequestCheck> }) {
function ChecksBody({
checks,
threadRef,
}: {
checks: ReadonlyArray<PullRequestCheck>;
threadRef: ScopedThreadRef | null;
}) {
const openLink = useOpenLink(threadRef);
if (checks.length === 0) {
return <p className="text-muted-foreground text-xs">No checks reported</p>;
}
@@ -71,7 +82,13 @@ function ChecksBody({ checks }: { checks: ReadonlyArray<PullRequestCheck> }) {
<button
type="button"
className="shrink-0 text-primary hover:underline"
onClick={() => void readLocalApi()?.shell.openExternal(check.url ?? "")}
onClick={() => {
if (!check.url) return;
void openLink(check.url).catch((error: unknown) => {
console.error(error);
toastManager.add({ type: "error", title: "Unable to open check details" });
});
}}
>
Details
</button>
@@ -94,6 +111,7 @@ export function PullRequestChecksPopover({
checks,
environmentId,
reference,
threadRef = null,
className,
}: {
checksState: PullRequestChecksState;
@@ -101,6 +119,8 @@ export function PullRequestChecksPopover({
checks?: ReadonlyArray<PullRequestCheck>;
environmentId?: EnvironmentId;
reference?: PullRequestRef;
/** Thread the popover sits beside; a listing row has none. */
threadRef?: ScopedThreadRef | null;
className?: string;
}) {
const presentation = pullRequestChecksStatePresentation(checksState);
@@ -129,9 +149,13 @@ export function PullRequestChecksPopover({
<p className="mb-2 font-medium text-sm">{presentation.label}</p>
{summary === null ? null : <p className="mb-2 text-muted-foreground text-xs">{summary}</p>}
{checks !== undefined ? (
<ChecksBody checks={checks} />
<ChecksBody checks={checks} threadRef={threadRef} />
) : environmentId !== undefined && reference !== undefined ? (
<LazyChecksBody environmentId={environmentId} reference={reference} />
<LazyChecksBody
environmentId={environmentId}
reference={reference}
threadRef={threadRef}
/>
) : null}
</PopoverPopup>
</Popover>
@@ -445,6 +445,7 @@ function PullRequestBaseFreshnessWarning({
export function PullRequestDetailPanel({
environmentId,
threadRef = null,
reference,
refreshToken: forcedRefreshToken = 0,
onActed,
@@ -454,6 +455,13 @@ export function PullRequestDetailPanel({
composerDraftTarget,
}: {
environmentId: EnvironmentId;
/**
* The thread this panel sits beside, if any. Links that are not the pull
* request itself (check details, host permalinks) can open in that thread's
* in-app browser when the user has asked for it; the page has no thread, so
* there they always go to the system browser.
*/
threadRef?: ScopedThreadRef | null;
reference: PullRequestRef;
/**
* Bumped by whatever holds the panel when a reader asks for everything on screen to be read
@@ -2152,7 +2160,11 @@ export function PullRequestDetailPanel({
aria-label={checksSummary ? `Checks: ${checksSummary}` : "Checks"}
>
{checksState !== null ? (
<PullRequestChecksPopover checks={detail.checks} checksState={checksState} />
<PullRequestChecksPopover
checks={detail.checks}
checksState={checksState}
threadRef={threadRef}
/>
) : (
<CircleDotIcon aria-hidden className="size-3.5" />
)}
@@ -2276,6 +2288,7 @@ export function PullRequestDetailPanel({
<div className={cn("absolute inset-0", tab !== "summary" && "invisible")}>
<PullRequestSummaryTab
environmentId={environmentId}
threadRef={threadRef}
reference={reference}
detail={detail}
activityPending={activityPending}
@@ -2303,6 +2316,7 @@ export function PullRequestDetailPanel({
<PullRequestTimelineTab
detail={detail}
environmentId={environmentId}
threadRef={threadRef}
reference={reference}
order={timelineOrder}
onOpenCommit={openCommit}
@@ -1,5 +1,5 @@
import { ExternalLinkIcon, PaperclipIcon, PlayIcon } from "lucide-react";
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { createContext, useContext, useMemo } from "react";
import type { Options as ReactMarkdownOptions } from "react-markdown";
@@ -21,11 +21,14 @@ export function PullRequestMarkdown({
text,
cwd,
environmentId,
threadRef,
className,
}: {
text: string;
cwd: string;
environmentId: EnvironmentId;
/** Thread the body is shown beside, so its links can open in that thread's in-app browser. */
threadRef?: ScopedThreadRef | null;
className?: string;
}) {
const segments = splitPullRequestBody(text);
@@ -43,6 +46,7 @@ export function PullRequestMarkdown({
key={segment.id}
text={segment.text}
cwd={cwd}
threadRef={threadRef ?? undefined}
environmentId={environmentId}
extraRemarkPlugins={extraRemarkPlugins}
/>
@@ -1,5 +1,5 @@
import { useState } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { cn } from "~/lib/utils";
@@ -19,6 +19,7 @@ export function PullRequestMarkdownEditor({
value,
cwd,
environmentId,
threadRef = null,
placeholder,
label,
saving,
@@ -30,6 +31,8 @@ export function PullRequestMarkdownEditor({
readonly value: string;
readonly cwd: string;
readonly environmentId: EnvironmentId;
/** Thread the editor sits beside, so links in its preview follow the link target setting. */
readonly threadRef?: ScopedThreadRef | null;
readonly placeholder?: string | undefined;
readonly label: string;
readonly saving: boolean;
@@ -84,7 +87,12 @@ export function PullRequestMarkdownEditor({
{empty ? (
<p className="text-xs text-muted-foreground">Nothing to preview.</p>
) : (
<PullRequestMarkdown text={draft} cwd={cwd} environmentId={environmentId} />
<PullRequestMarkdown
text={draft}
cwd={cwd}
environmentId={environmentId}
threadRef={threadRef}
/>
)}
</div>
) : (
@@ -4,6 +4,7 @@ import type {
PullRequestComment,
PullRequestDetailView,
PullRequestRef,
ScopedThreadRef,
} from "@t3tools/contracts";
import {
ArrowDownUpIcon,
@@ -23,7 +24,7 @@ import { useRef, useState, type ReactNode } from "react";
import { useAtomCommand } from "~/state/use-atom-command";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { useOpenLink } from "~/browser/useOpenLink";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Button } from "../ui/button";
@@ -93,6 +94,7 @@ function reviewStateLabel(state: string): string {
interface CommentEditing {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef | null;
readonly canEdit: (comment: PullRequestComment) => boolean;
readonly editingId: string | null;
readonly saving: boolean;
@@ -120,6 +122,7 @@ function CommentBody({
value={comment.body}
cwd={editing.cwd}
environmentId={editing.environmentId}
threadRef={editing.threadRef}
label="Edit comment"
saving={editing.saving}
onSave={(body) => editing.onSave(comment, body)}
@@ -134,6 +137,7 @@ function CommentBody({
text={comment.body}
cwd={editing.cwd}
environmentId={editing.environmentId}
threadRef={editing.threadRef}
/>
{editing.canEdit(comment) ? (
<Button
@@ -423,6 +427,7 @@ const COMMENT_PAGE = 30;
export function PullRequestSummaryTab({
environmentId,
threadRef,
reference,
detail,
activityPending,
@@ -436,6 +441,7 @@ export function PullRequestSummaryTab({
onRefresh,
}: {
environmentId: EnvironmentId;
threadRef: ScopedThreadRef | null;
reference: PullRequestRef;
detail: PullRequestDetailView;
activityPending: boolean;
@@ -508,8 +514,12 @@ export function PullRequestSummaryTab({
),
);
const openLink = useOpenLink(threadRef);
const openCheck = (url: string) => {
void readLocalApi()?.shell.openExternal(url);
void openLink(url).catch((error: unknown) => {
console.error(error);
toastManager.add({ type: "error", title: "Unable to open check details" });
});
};
const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
@@ -547,6 +557,7 @@ export function PullRequestSummaryTab({
const commentEditing: CommentEditing = {
cwd: detail.workspaceRoot,
environmentId,
threadRef,
canEdit: (comment) => canEditPullRequestComment(detail, comment),
editingId: editingCommentId,
saving: commentSaving,
@@ -722,6 +733,7 @@ export function PullRequestSummaryTab({
value={detail.body}
cwd={detail.workspaceRoot}
environmentId={environmentId}
threadRef={threadRef}
label="Pull request description"
placeholder="Describe this pull request"
saving={bodySaving}
@@ -735,6 +747,7 @@ export function PullRequestSummaryTab({
text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
cwd={detail.workspaceRoot}
environmentId={environmentId}
threadRef={threadRef}
/>
{canEditPullRequestChangeRequest(detail) ? (
<Button
@@ -4,6 +4,7 @@ import type {
PullRequestComment,
PullRequestDetailView,
PullRequestRef,
ScopedThreadRef,
} from "@t3tools/contracts";
import {
ChevronDownIcon,
@@ -55,6 +56,8 @@ import {
interface ReactionSurface {
readonly canReact: boolean;
readonly environmentId: EnvironmentId;
/** Thread the timeline is shown beside, so body links can open in its in-app browser. */
readonly threadRef: ScopedThreadRef | null;
readonly reference: PullRequestRef;
readonly onRefresh: () => void;
}
@@ -64,16 +67,23 @@ function TimelineBody({
markdown,
cwd,
environmentId,
threadRef,
}: {
body: string;
markdown: boolean;
cwd: string;
environmentId: EnvironmentId;
threadRef: ScopedThreadRef | null;
}) {
return (
<div className="mt-3">
{markdown ? (
<PullRequestMarkdown text={body} cwd={cwd} environmentId={environmentId} />
<PullRequestMarkdown
text={body}
cwd={cwd}
environmentId={environmentId}
threadRef={threadRef}
/>
) : (
<p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
)}
@@ -246,6 +256,7 @@ function ConversationCard({
value={editable.body}
cwd={cwd}
environmentId={reactions.environmentId}
threadRef={reactions.threadRef}
label="Edit comment"
saving={saving}
onSave={(body) => void save(body)}
@@ -259,6 +270,7 @@ function ConversationCard({
markdown={event.markdown}
cwd={cwd}
environmentId={reactions.environmentId}
threadRef={reactions.threadRef}
/>
</div>
) : null}
@@ -526,6 +538,7 @@ function ReviewVerdictEvent({
markdown={event.markdown}
cwd={cwd}
environmentId={reactions.environmentId}
threadRef={reactions.threadRef}
/>
) : null}
</div>
@@ -538,6 +551,7 @@ function ReviewVerdictEvent({
export function PullRequestTimelineTab({
detail,
environmentId,
threadRef = null,
reference,
order,
onOpenCommit,
@@ -545,6 +559,7 @@ export function PullRequestTimelineTab({
}: {
detail: PullRequestDetailView;
environmentId: EnvironmentId;
threadRef?: ScopedThreadRef | null;
reference: PullRequestRef;
order: "newest" | "oldest";
onOpenCommit: (oid: string) => void;
@@ -555,6 +570,7 @@ export function PullRequestTimelineTab({
const reactions: ReactionSurface = {
canReact: detail.capabilities.reactions === true,
environmentId,
threadRef,
reference,
onRefresh,
};
@@ -8,12 +8,14 @@
*/
import {
BROWSER_PROFILE_MAX_COUNT,
type BrowserLinkTarget,
type BrowserProfile,
type EnvironmentId,
BROWSER_PROFILE_NAME_MAX_LENGTH,
BROWSER_RECORDING_FRAME_RATES,
DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
DEFAULT_BROWSER_PROFILE_ID,
DEFAULT_BROWSER_LINK_TARGET,
DEFAULT_BROWSER_RECORDING_FRAME_RATE,
DEFAULT_BROWSER_VIEWPORT,
DEFAULT_PREVIEW_APPEARANCE,
@@ -465,6 +467,53 @@ function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boo
);
}
const LINK_TARGET_LABELS: Readonly<Record<BrowserLinkTarget, string>> = {
system: "Your default browser",
app: "T3 Code",
};
function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean }) {
const linkTarget = useClientSettings((settings) => settings.browserLinkTarget);
const updateSettings = useUpdatePrimarySettings();
return (
<SettingsRow
{...searchableSetting("browser-link-target")}
description="Where links in the chat and terminal open. Hold ⌘ or Ctrl while clicking a chat link to open it in your default browser either way."
resetAction={
!disabled && linkTarget !== DEFAULT_BROWSER_LINK_TARGET ? (
<SettingResetButton
label="link target"
onClick={() => updateSettings({ browserLinkTarget: DEFAULT_BROWSER_LINK_TARGET })}
/>
) : null
}
control={
<Select
disabled={disabled}
value={linkTarget}
onValueChange={(value) => {
if (value === "system" || value === "app") {
updateSettings({ browserLinkTarget: value });
}
}}
>
<SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Open links in">
<SelectValue>{LINK_TARGET_LABELS[linkTarget]}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{(Object.keys(LINK_TARGET_LABELS) as ReadonlyArray<BrowserLinkTarget>).map((target) => (
<SelectItem hideIndicator key={target} value={target}>
{LINK_TARGET_LABELS[target]}
</SelectItem>
))}
</SelectPopup>
</Select>
}
/>
);
}
function AgentBrowserAccessSetting() {
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
@@ -868,6 +917,7 @@ export function IntegrationsSettingsPanel() {
<BrowserZoomSetting disabled={previewDefaultsDisabled} />
<BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
<BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} />
<BrowserLinkTargetSetting disabled={previewDefaultsDisabled} />
<BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} />
</>
);
@@ -269,6 +269,7 @@ describe("getChangedBrowserSettingLabels", () => {
browserDefaultZoomFactor: 1.5,
browserDefaultAppearance: "dark",
browserRecordingFrameRate: 60,
browserLinkTarget: "app",
browserAutoShowFloatingPreview: !DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview,
}),
).toEqual([
@@ -276,6 +277,7 @@ describe("getChangedBrowserSettingLabels", () => {
"Browser zoom",
"Browser appearance",
"Recording frame rate",
"Open links in",
"Floating preview",
]);
});
@@ -115,6 +115,7 @@ export type BrowserDefaultSettings = Pick<
| "browserDefaultZoomFactor"
| "browserDefaultAppearance"
| "browserRecordingFrameRate"
| "browserLinkTarget"
| "browserAutoShowFloatingPreview"
>;
@@ -155,6 +156,9 @@ export function getChangedBrowserSettingLabels(settings: BrowserDefaultSettings)
...(settings.browserRecordingFrameRate !== DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate
? ["Recording frame rate"]
: []),
...(settings.browserLinkTarget !== DEFAULT_UNIFIED_SETTINGS.browserLinkTarget
? ["Open links in"]
: []),
...(settings.browserAutoShowFloatingPreview !==
DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview
? ["Floating preview"]
@@ -589,6 +589,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.browserDefaultZoomFactor,
settings.browserDefaultAppearance,
settings.browserRecordingFrameRate,
settings.browserLinkTarget,
settings.browserAutoShowFloatingPreview,
settings.appearanceContrast,
settings.enableAgentBrowserAccess,
@@ -735,6 +736,7 @@ export function useSettingsRestore(onRestored?: () => void) {
browserDefaultZoomFactor: DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor,
browserDefaultAppearance: DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance,
browserRecordingFrameRate: DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate,
browserLinkTarget: DEFAULT_UNIFIED_SETTINGS.browserLinkTarget,
browserAutoShowFloatingPreview: DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview,
// Re-granted like any other default. The confirmation dialog lists it by
// name, so a user restoring defaults is told the agent regains access
@@ -207,4 +207,12 @@ describe("searchSettings", () => {
});
expect(result).not.toHaveProperty("targetId");
});
it("routes where links open to integrations", () => {
expect(searchSettings("open links in")[0]).toMatchObject({
id: "browser-link-target",
to: "/settings/integrations",
});
expect(searchSettings("external links")[0]).toMatchObject({ id: "browser-link-target" });
});
});
@@ -364,6 +364,12 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Browser recording frame rate",
to: "/settings/integrations",
},
{
id: "browser-link-target",
title: "Open links in",
to: "/settings/integrations",
searchTerms: ["links default browser in-app browser external open"],
},
{
id: "browser-auto-show-floating-preview",
title: "Auto-show floating preview",
+6 -12
View File
@@ -11,8 +11,8 @@ import { type MouseEvent, useCallback } from "react";
import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
import { useOpenLink } from "../browser/useOpenLink";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { readLocalApi } from "../localApi";
import { useRightPanelStore } from "../rightPanelStore";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
@@ -328,6 +328,7 @@ export function useOpenChangeRequestLink(
export function useOpenPrLink(threadRef?: ScopedThreadRef) {
const openChangeRequest = useOpenChangeRequestLink(threadRef);
const openLink = useOpenLink(threadRef);
return useCallback(
(event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
event.stopPropagation();
@@ -342,16 +343,9 @@ export function useOpenPrLink(threadRef?: ScopedThreadRef) {
event.preventDefault();
if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
const api = readLocalApi();
if (!api) {
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
});
return false;
}
void openPullRequestLink(api.shell, prUrl).catch((error) => {
// No project to show it in, so it is an ordinary link and follows the
// "Open links in" setting; the modifier still forces the system browser.
void openLink(prUrl, { event, threadRef: targetThreadRef }).catch((error: unknown) => {
console.error(error);
toastManager.add(
stackedThreadToast({
@@ -363,6 +357,6 @@ export function useOpenPrLink(threadRef?: ScopedThreadRef) {
});
return false;
},
[openChangeRequest],
[openChangeRequest, openLink],
);
}
+16
View File
@@ -188,6 +188,14 @@ export const BROWSER_RECORDING_FRAME_RATES = [30, 60] as const;
export const BrowserRecordingFrameRate = Schema.Literals(BROWSER_RECORDING_FRAME_RATES);
export type BrowserRecordingFrameRate = typeof BrowserRecordingFrameRate.Type;
export const DEFAULT_BROWSER_RECORDING_FRAME_RATE: BrowserRecordingFrameRate = 30;
/**
* Where a clicked link goes: the OS default browser, or a tab in the in-app
* browser beside the thread. "system" is the default because that is what
* every link did before the setting existed.
*/
export const BrowserLinkTarget = Schema.Literals(["system", "app"]);
export type BrowserLinkTarget = typeof BrowserLinkTarget.Type;
export const DEFAULT_BROWSER_LINK_TARGET: BrowserLinkTarget = "system";
export const ClientSettingsSchema = Schema.Struct({
appearanceContrast: AppearanceContrast.pipe(
@@ -210,6 +218,13 @@ export const ClientSettingsSchema = Schema.Struct({
browserRecordingFrameRate: BrowserRecordingFrameRate.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_RECORDING_FRAME_RATE)),
),
/**
* Where links clicked in a thread (chat markdown, terminal output) open.
* Only the desktop app has an in-app browser, so other clients ignore "app".
*/
browserLinkTarget: BrowserLinkTarget.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_LINK_TARGET)),
),
/**
* Whether an agent opening a preview pops the floating mini player into
* view. Only applies when the agent didn't ask either way — an explicit
@@ -1003,6 +1018,7 @@ export const ClientSettingsPatch = Schema.Struct({
browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),
browserLinkTarget: Schema.optionalKey(BrowserLinkTarget),
browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
browserProfiles: Schema.optionalKey(Schema.Array(BrowserProfile)),
browserDefaultProfileId: Schema.optionalKey(BrowserProfileId),