Skip to content
TypeScript

feat(desktop): T3 Code can be your default web browser on macOS (#17587)

Julius Marminge38571328a4bc
diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts
index 76306bfbf22..b4aef409337 100644
--- a/apps/desktop/src/app/DesktopClerk.test.ts
+++ b/apps/desktop/src/app/DesktopClerk.test.ts
@@ -35,9 +35,16 @@ import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
+import * as DesktopWebLinks from "./DesktopWebLinks.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopPreReadyFileSystem from "./DesktopPreReadyFileSystem.ts";
+/** Clerk forwards web links; tests that are not about links ignore them. */
+const ignoreWebLinks = DesktopWebLinks.DesktopWebLinks.of({
+ receive: () => Effect.void,
+ setRendererReady: () => Effect.void,
+});
+
const layerDesktopClerk = (
isDevelopment = true,
events: string[] = [],
@@ -220,11 +227,12 @@ describe("DesktopClerk", () => {
assert.isTrue(Exit.isSuccess(exit));
assert.equal(quit.mock.calls.length, 0);
- assert.deepEqual(registeredEvents, ["open-url", "second-instance"]);
+ assert.deepEqual(registeredEvents, ["open-url", "open-file", "second-instance"]);
}).pipe(
Effect.provide(layerDesktopClerk()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
+ Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
);
});
@@ -253,6 +261,7 @@ describe("DesktopClerk", () => {
Effect.provide(layerDesktopClerk()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
+ Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
);
});
});
@@ -299,6 +308,7 @@ it.effect(
Effect.provide(layerDesktopClerk()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
+ Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
);
},
);
@@ -381,6 +391,54 @@ it.effect.each(["startup", "open-url"] as const)(
ElectronWindow.ElectronWindow,
{} as ElectronWindow.ElectronWindow["Service"],
),
+ Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
);
}).pipe(Effect.scoped),
);
+
+it.effect("hands a web link to the renderer and leaves other links alone", () =>
+ Effect.gen(function* () {
+ storageMock.mockReturnValue(storageAdapter);
+ createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
+ const listeners = new Map<string, (...args: unknown[]) => void>();
+ const electronApp = {
+ whenReady: Effect.void,
+ on: (name: string, listener: (...args: unknown[]) => void) =>
+ Effect.sync(() => {
+ listeners.set(name, listener);
+ }),
+ } as unknown as ElectronApp.ElectronApp["Service"];
+ const received: Array<string> = [];
+ yield* Effect.gen(function* () {
+ const clerk = yield* DesktopClerk.DesktopClerk;
+ yield* clerk.configure;
+ const open = (url: string) => {
+ const event = { preventDefault: vi.fn() };
+ listeners.get("open-url")!(event, url);
+ return event.preventDefault.mock.calls.length;
+ };
+ // macOS hands the default browser every web link.
+ assert.strictEqual(open("https://example.com/page"), 1);
+ assert.strictEqual(open("http://localhost:3000/"), 1);
+ // Anything else is not a web page; Electron keeps its own handling.
+ assert.strictEqual(open("mailto:[email protected]"), 0);
+ yield* Effect.yieldNow;
+ assert.deepStrictEqual(received, ["https://example.com/page", "http://localhost:3000/"]);
+ }).pipe(
+ Effect.provide(layerDesktopClerk(true, [], "darwin")),
+ Effect.provideService(HostProcess.Arguments, ["t3"]),
+ Effect.provideService(ElectronApp.ElectronApp, electronApp),
+ Effect.provideService(
+ ElectronWindow.ElectronWindow,
+ {} as ElectronWindow.ElectronWindow["Service"],
+ ),
+ Effect.provideService(
+ DesktopWebLinks.DesktopWebLinks,
+ DesktopWebLinks.DesktopWebLinks.of({
+ receive: (url) => Effect.sync(() => void received.push(url)),
+ setRendererReady: () => Effect.void,
+ }),
+ ),
+ );
+ }).pipe(Effect.scoped),
+);
diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts
index f1a7f31174a..08d3def1a68 100644
--- a/apps/desktop/src/app/DesktopClerk.ts
+++ b/apps/desktop/src/app/DesktopClerk.ts
@@ -1,4 +1,5 @@
import { createClerkBridge } from "@clerk/electron";
+import * as NodeURL from "node:url";
import { storage } from "@clerk/electron/storage";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -18,6 +19,7 @@ import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopUserData from "./DesktopUserData.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+import * as DesktopWebLinks from "./DesktopWebLinks.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
@@ -53,7 +55,10 @@ export class DesktopClerk extends Context.Service<
readonly configure: Effect.Effect<
void,
never,
- ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
+ | ElectronApp.ElectronApp
+ | ElectronWindow.ElectronWindow
+ | DesktopWebLinks.DesktopWebLinks
+ | Scope.Scope
>;
}
>()("@t3tools/desktop/app/DesktopClerk") {}
@@ -125,6 +130,7 @@ export const make = Effect.gen(function* () {
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
+ const webLinks = yield* DesktopWebLinks.DesktopWebLinks;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
@@ -184,8 +190,21 @@ export const make = Effect.gen(function* () {
};
const args = yield* HostProcess.Arguments;
args.some((value) => startProviderAuthHandoff(value));
+ // As the default browser, macOS hands T3 Code every web link through the same event.
+ const openWebLink = (url: string) => {
+ if (!DesktopWebLinks.isWebLink(url)) return false;
+ void runPromise(webLinks.receive(url));
+ return true;
+ };
yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
- if (startProviderAuthHandoff(url) || resumeProviderAuth(url)) event.preventDefault();
+ if (startProviderAuthHandoff(url) || resumeProviderAuth(url) || openWebLink(url))
+ event.preventDefault();
+ });
+ // A browser opens HTML files too, which macOS hands over by path.
+ yield* electronApp.on("open-file", (event: { preventDefault: () => void }, path: string) => {
+ if (!DesktopWebLinks.isWebPageFile(path)) return;
+ event.preventDefault();
+ void runPromise(webLinks.receive(NodeURL.pathToFileURL(path).href));
});
yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
if (argv?.some((value) => startProviderAuthHandoff(value) || resumeProviderAuth(value)))
diff --git a/apps/desktop/src/app/DesktopWebLinks.test.ts b/apps/desktop/src/app/DesktopWebLinks.test.ts
new file mode 100644
index 00000000000..302fe5f1b4c
--- /dev/null
+++ b/apps/desktop/src/app/DesktopWebLinks.test.ts
@@ -0,0 +1,93 @@
+// @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron webContents.
+import { assert, describe, it } from "@effect/vitest";
+import * as NodeEvents from "node:events";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+
+import * as ElectronWindow from "../electron/ElectronWindow.ts";
+import { WEB_LINK_OPEN_CHANNEL } from "../ipc/channels.ts";
+import * as DesktopWebLinks from "./DesktopWebLinks.ts";
+
+const makeWindow = () => {
+ const sent: Array<string> = [];
+ const revealed: Array<unknown> = [];
+ const webContents = Object.assign(new NodeEvents.EventEmitter(), {
+ isDestroyed: () => false,
+ send: (channel: string, url: string) => {
+ if (channel === WEB_LINK_OPEN_CHANNEL) sent.push(url);
+ },
+ });
+ const window = { webContents } as unknown as Electron.BrowserWindow;
+ /** The web app starts loading a new page, as a reload does. */
+ const reload = () =>
+ webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false });
+ const layer = DesktopWebLinks.layer.pipe(
+ Layer.provide(
+ Layer.succeed(
+ ElectronWindow.ElectronWindow,
+ ElectronWindow.ElectronWindow.of({
+ currentMainOrFirst: Effect.succeed(Option.some(window)),
+ reveal: (target: Electron.BrowserWindow) => Effect.sync(() => void revealed.push(target)),
+ } as unknown as ElectronWindow.ElectronWindow["Service"]),
+ ),
+ ),
+ );
+ return { sent, revealed, layer, reload };
+};
+
+describe("DesktopWebLinks", () => {
+ it("treats only http and https as web links", () => {
+ assert.isTrue(DesktopWebLinks.isWebLink("https://example.com/"));
+ assert.isTrue(DesktopWebLinks.isWebLink("http://localhost:3000/a?b=1"));
+ assert.isFalse(DesktopWebLinks.isWebLink("t3code://app/welcome"));
+ assert.isFalse(DesktopWebLinks.isWebLink("mailto:[email protected]"));
+ assert.isFalse(DesktopWebLinks.isWebLink("not a url"));
+ });
+
+ it("opens HTML files the way a browser does, and nothing else by path", () => {
+ assert.isTrue(DesktopWebLinks.isWebPageFile("/Users/me/report.html"));
+ assert.isTrue(DesktopWebLinks.isWebPageFile("/tmp/page.HTM"));
+ assert.isTrue(DesktopWebLinks.isWebPageFile("/tmp/page.xhtml"));
+ assert.isFalse(DesktopWebLinks.isWebPageFile("/tmp/notes.md"));
+ assert.isFalse(DesktopWebLinks.isWebPageFile("/tmp/html"));
+ });
+
+ it.effect("holds links until the renderer listens, then delivers them in order", () => {
+ const { sent, revealed, layer } = makeWindow();
+ return Effect.gen(function* () {
+ const webLinks = yield* DesktopWebLinks.DesktopWebLinks;
+ // The link that launched the app arrives before the web app has loaded.
+ yield* webLinks.receive("https://example.com/first");
+ yield* webLinks.receive("https://example.com/second");
+ assert.deepStrictEqual(sent, []);
+
+ yield* webLinks.setRendererReady(true);
+ assert.deepStrictEqual(sent, ["https://example.com/first", "https://example.com/second"]);
+ assert.strictEqual(revealed.length, 1);
+
+ yield* webLinks.receive("https://example.com/third");
+ assert.deepStrictEqual(sent.at(-1), "https://example.com/third");
+
+ // A reloading web app stops listening; links wait for it again.
+ yield* webLinks.setRendererReady(false);
+ yield* webLinks.receive("https://example.com/fourth");
+ assert.strictEqual(sent.length, 3);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("holds links that arrive while the web app reloads until it listens again", () => {
+ const { sent, layer, reload } = makeWindow();
+ return Effect.gen(function* () {
+ const webLinks = yield* DesktopWebLinks.DesktopWebLinks;
+ yield* webLinks.setRendererReady(true);
+ // The old page never says it stopped; the reload itself ends its listening.
+ reload();
+ yield* webLinks.receive("https://example.com/during-reload");
+ assert.deepStrictEqual(sent, []);
+
+ yield* webLinks.setRendererReady(true);
+ assert.deepStrictEqual(sent, ["https://example.com/during-reload"]);
+ }).pipe(Effect.provide(layer));
+ });
+});
diff --git a/apps/desktop/src/app/DesktopWebLinks.ts b/apps/desktop/src/app/DesktopWebLinks.ts
new file mode 100644
index 00000000000..44d90534d00
--- /dev/null
+++ b/apps/desktop/src/app/DesktopWebLinks.ts
@@ -0,0 +1,97 @@
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+
+import * as ElectronWindow from "../electron/ElectronWindow.ts";
+import { WEB_LINK_OPEN_CHANNEL } from "../ipc/channels.ts";
+
+/** An http(s) link the operating system handed to T3 Code as the default browser. */
+export const isWebLink = (value: string) => {
+ if (!URL.canParse(value)) return false;
+ const { protocol } = new URL(value);
+ return protocol === "http:" || protocol === "https:";
+};
+
+/** An HTML file the operating system asked T3 Code to open, as browsers are asked to. */
+export const isWebPageFile = (path: string) => /\.x?html?$/i.test(path);
+
+/**
+ * Web links and HTML files macOS opens with T3 Code once it is the default
+ * browser. Files arrive as file:// URLs. They can
+ * arrive before the app is ready (the link that launched it) or while the web
+ * app reloads, so they wait until the renderer says it is listening.
+ */
+export class DesktopWebLinks extends Context.Service<
+ DesktopWebLinks,
+ {
+ /** Queues a link and delivers it as soon as the renderer is listening. */
+ readonly receive: (url: string) => Effect.Effect<void>;
+ /** The renderer started or stopped listening; listening flushes queued links. */
+ readonly setRendererReady: (ready: boolean) => Effect.Effect<void>;
+ }
+>()("@t3tools/desktop/app/DesktopWebLinks") {}
+
+const make = Effect.gen(function* () {
+ const electronWindow = yield* ElectronWindow.ElectronWindow;
+ const pending: Array<string> = [];
+ /** The page that said it is listening; a reload or crash replaces it, and it must say so again. */
+ let listening: Electron.WebContents | null = null;
+ let detachListening: (() => void) | null = null;
+
+ const stopListening = () => {
+ detachListening?.();
+ detachListening = null;
+ listening = null;
+ };
+
+ const flush = Effect.gen(function* () {
+ if (listening === null || pending.length === 0) return;
+ const window = yield* electronWindow.currentMainOrFirst;
+ if (Option.isNone(window) || window.value.webContents !== listening) return;
+ if (listening.isDestroyed()) {
+ stopListening();
+ return;
+ }
+ for (const url of pending.splice(0)) listening.send(WEB_LINK_OPEN_CHANNEL, url);
+ yield* electronWindow.reveal(window.value);
+ });
+
+ const startListening = Effect.gen(function* () {
+ const window = yield* electronWindow.currentMainOrFirst;
+ if (Option.isNone(window) || window.value.webContents.isDestroyed()) return;
+ const webContents = window.value.webContents;
+ if (listening === webContents) return;
+ stopListening();
+ listening = webContents;
+ // Links that arrive while a new page loads wait for it to listen again.
+ const onNavigation = (
+ event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
+ ) => {
+ if (event.isMainFrame && !event.isSameDocument) stopListening();
+ };
+ webContents.on("did-start-navigation", onNavigation);
+ webContents.on("render-process-gone", stopListening);
+ webContents.once("destroyed", stopListening);
+ detachListening = () => {
+ webContents.removeListener("did-start-navigation", onNavigation);
+ webContents.removeListener("render-process-gone", stopListening);
+ webContents.removeListener("destroyed", stopListening);
+ };
+ });
+
+ return DesktopWebLinks.of({
+ receive: (url) =>
+ Effect.suspend(() => {
+ pending.push(url);
+ return flush;
+ }).pipe(Effect.withSpan("DesktopWebLinks.receive")),
+ setRendererReady: (ready) =>
+ (ready ? startListening : Effect.sync(stopListening)).pipe(
+ Effect.andThen(flush),
+ Effect.withSpan("DesktopWebLinks.setRendererReady"),
+ ),
+ });
+});
+
+export const layer = Layer.effect(DesktopWebLinks, make);
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index a67424a795a..caed223e90e 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -70,6 +70,7 @@ import {
} from "./methods/snapShot.ts";
import * as PreviewIpc from "./methods/preview.ts";
import * as AppActivationIpc from "./methods/appActivation.ts";
+import * as WebLinksIpc from "./methods/webLinks.ts";
import {
completeLegacyLocalStorage,
takeLegacyLocalStorage,
@@ -88,6 +89,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(AppActivationIpc.setReady);
yield* ipc.handle(AppActivationIpc.complete);
+ yield* ipc.handle(WebLinksIpc.setReady);
yield* ipc.handleSync(takeLegacyLocalStorage);
yield* ipc.handle(completeLegacyLocalStorage);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index e6b936c100b..a6b617385b5 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -10,6 +10,8 @@ export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const PASTE_AS_TEXT_CHANNEL = "desktop:paste-as-text";
export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event";
+export const WEB_LINK_OPEN_CHANNEL = "desktop:web-link-open";
+export const WEB_LINK_READY_CHANNEL = "desktop:web-link-ready";
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
export const TRACKPAD_SCROLL_END_CHANNEL = "desktop:trackpad-scroll-end";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
diff --git a/apps/desktop/src/ipc/methods/webLinks.ts b/apps/desktop/src/ipc/methods/webLinks.ts
new file mode 100644
index 00000000000..bda6affc074
--- /dev/null
+++ b/apps/desktop/src/ipc/methods/webLinks.ts
@@ -0,0 +1,16 @@
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import * as DesktopWebLinks from "../../app/DesktopWebLinks.ts";
+import * as IpcChannels from "../channels.ts";
+import * as DesktopIpc from "../DesktopIpc.ts";
+
+export const setReady = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.WEB_LINK_READY_CHANNEL,
+ payload: Schema.Boolean,
+ result: Schema.Void,
+ handler: Effect.fn("desktop.ipc.webLinks.setReady")(function* (ready) {
+ const webLinks = yield* DesktopWebLinks.DesktopWebLinks;
+ yield* webLinks.setRendererReady(ready);
+ }),
+});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 806b038d769..ef00c4d66ed 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -35,6 +35,7 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
import * as ElectronWindow from "./electron/ElectronWindow.ts";
import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppActivation from "./app/DesktopAppActivation.ts";
+import * as DesktopWebLinks from "./app/DesktopWebLinks.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts";
@@ -214,6 +215,7 @@ const layerDesktopLocalEnvironmentAuth = DesktopLocalEnvironmentAuth.layer.pipe(
const layerDesktopApplication = Layer.mergeAll(
DesktopLifecycle.layer,
layerDesktopAppActivation,
+ DesktopWebLinks.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopCliCommand.layer,
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 12b68f18608..efd49ffa386 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -285,6 +285,18 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
};
},
+ webLinks: {
+ setReady: (ready) => ipcRenderer.invoke(IpcChannels.WEB_LINK_READY_CHANNEL, ready),
+ onOpen: (listener) => {
+ const wrappedListener = (_event: Electron.IpcRendererEvent, url: unknown) => {
+ if (typeof url === "string") listener(url);
+ };
+ ipcRenderer.on(IpcChannels.WEB_LINK_OPEN_CHANNEL, wrappedListener);
+ return () => {
+ ipcRenderer.removeListener(IpcChannels.WEB_LINK_OPEN_CHANNEL, wrappedListener);
+ };
+ },
+ },
appActivation: {
setReady: (ready) =>
ipcRenderer.invoke(IpcChannels.DESKTOP_APP_ACTIVATION_READY_CHANNEL, ready),
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index c8c202f5cad..a4f56c75e5e 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -6056,6 +6056,13 @@ export default function ChatView(props: ChatViewProps) {
if (!activeThreadRef) return;
useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation);
}, [activeThreadRef, threadPanelPresentation]);
+ // A thread started for a link the OS opened shows its browser maximized, like a browser window.
+ useEffect(() => {
+ if (!canMaximizeRightPanel) return;
+ if (useRightPanelStore.getState().consumeMaximizeRequest(routeThreadRef)) {
+ setMaximizedRightPanelThreadKey(routeThreadKey);
+ }
+ }, [canMaximizeRightPanel, routeThreadKey, routeThreadRef]);
const toggleRightPanelMaximized = useCallback(() => {
if (!canMaximizeRightPanel) return;
setMaximizedRightPanelThreadKey((threadKey) =>
diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx
index 3a34d326e51..20e66263892 100644
--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx
+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx
@@ -1,5 +1,5 @@
import type { DraftId } from "~/composerDraftStore";
-import { useComposerDraftStore } from "~/composerDraftStore";
+import { composerDraftHasUserContent, useComposerDraftStore } from "~/composerDraftStore";
import { resolveEnvironmentMachineKind, type ScopedProjectRef } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
@@ -11,6 +11,7 @@ import { openCommandPalette } from "~/commandPaletteBus";
import { shortcutLabelForCommand } from "~/keybindings";
import { projectIconColorClassName } from "~/projectIconColors";
import { primaryServerKeybindingsAtom } from "~/state/server";
+import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useScratchProject } from "~/hooks/useScratchProject";
import { useClientSettings } from "~/hooks/useSettings";
import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";
@@ -69,6 +70,7 @@ export function DraftHeroHeadline({
const setModelSelection = useComposerDraftStore((store) => store.setModelSelection);
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
const { scratchEnvironmentId, scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
+ const openProjectDraft = useNewThreadHandler();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const environmentLabelById = useMemo(
@@ -172,9 +174,11 @@ export function DraftHeroHeadline({
useEffect(() => {
latestTargetRef.current = { draftId, activeProjectKey, scratchTargetEnvironmentId };
}, [activeProjectKey, scratchTargetEnvironmentId, draftId]);
- // Project selection changes the target of the open draft in place. The
- // prompt stays in the same composer session, so the sidebar only gets a
- // draft row if the user later navigates away.
+ // With a prompt typed, project selection changes the target of the open
+ // draft in place, so the prompt stays in the same composer session. An empty
+ // draft instead opens the chosen project's own draft, like starting a new
+ // thread there: moving it would replace that draft and strand whatever it
+ // holds, such as the browser tabs of the no-project draft.
const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => {
if (!draftId) {
return;
@@ -185,6 +189,10 @@ export function DraftHeroHeadline({
scratchTargetEnvironmentId: project.environmentId,
};
const currentDraft = getComposerDraft(draftId);
+ if (!composerDraftHasUserContent(currentDraft)) {
+ void openProjectDraft(scopeProjectRef(project.environmentId, project.id));
+ return;
+ }
setLogicalProjectDraftThreadId(
logicalProjectKey,
scopeProjectRef(project.environmentId, project.id),
diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
new file mode 100644
index 00000000000..9ee7f216d97
--- /dev/null
+++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
@@ -0,0 +1,146 @@
+import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
+import { useRouter } from "@tanstack/react-router";
+import { useEffect, useEffectEvent, useRef } from "react";
+
+import { openFileInPreview, openUrlInPreview } from "../../browser/openFileInPreview";
+import { isPreviewAvailableFor } from "../../browser/previewRuntime";
+import { useComposerDraftStore } from "../../composerDraftStore";
+import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
+import { useScratchProject } from "../../hooks/useScratchProject";
+import { selectActiveRightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
+import { resolveThreadRouteTarget } from "../../threadRoutes";
+import { assetEnvironment } from "../../state/assets";
+import { useEnvironmentHttpBaseUrl, usePrimaryEnvironment } from "../../state/environments";
+import { previewEnvironment } from "../../state/preview";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
+import { stackedThreadToast, toastManager } from "../ui/toast";
+
+/**
+ * The thread on screen when its browser panel is showing, so a link opens as
+ * another tab there, the way a browser window takes new links. HTML files are
+ * served by this machine's environment, so only its threads can take them.
+ */
+function threadShowingBrowser(
+ routeParams: Record<string, string | undefined>,
+ fileEnvironmentId: EnvironmentId | null,
+): ScopedThreadRef | null {
+ const target = resolveThreadRouteTarget(routeParams);
+ if (target === null) return null;
+ let threadRef = target.kind === "server" ? target.threadRef : null;
+ if (target.kind === "draft") {
+ const session = useComposerDraftStore.getState().getDraftSession(target.draftId);
+ if (!session || session.promotedTo) return null;
+ threadRef = scopeThreadRef(session.environmentId, session.threadId);
+ }
+ if (threadRef === null || !isPreviewAvailableFor(threadRef.environmentId)) return null;
+ if (fileEnvironmentId !== null && threadRef.environmentId !== fileEnvironmentId) return null;
+ const surface = selectActiveRightPanelSurface(
+ useRightPanelStore.getState().byThreadKey,
+ threadRef,
+ );
+ return surface?.kind === "preview" ? threadRef : null;
+}
+
+/**
+ * Opens each web link or HTML file the OS hands T3 Code as the default browser
+ * (macOS). With a browser panel on screen the page opens as a new tab there;
+ * otherwise it starts a thread without a project, its browser panel maximized.
+ */
+export function DesktopWebLinkCoordinator() {
+ const router = useRouter();
+ const primaryEnvironment = usePrimaryEnvironment();
+ const { scratchEnvironmentId, openScratchProject } = useScratchProject();
+ const openThread = useNewThreadHandler();
+ const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
+ const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
+ reportFailure: false,
+ refresh: true,
+ });
+ const httpBaseUrl = useEnvironmentHttpBaseUrl(primaryEnvironment?.environmentId ?? null);
+ const queueRef = useRef(Promise.resolve());
+ const webLinks = window.desktopBridge?.webLinks;
+ const ready =
+ webLinks !== undefined &&
+ primaryEnvironment?.connection.phase === "connected" &&
+ primaryEnvironment.serverConfig !== null;
+
+ const reportFailure = (url: string, description = url) =>
+ toastManager.add(
+ stackedThreadToast({ type: "error", title: "Could not open the link", description }),
+ );
+
+ // The OS hands each link over once, so a thread that could not start says so.
+ const startThread = async (url: string): Promise<ScopedThreadRef | null> => {
+ const environmentId = scratchEnvironmentId(primaryEnvironment?.environmentId ?? null);
+ if (environmentId === null) {
+ reportFailure(url);
+ return null;
+ }
+ // Reports its own failure.
+ const project = await openScratchProject(environmentId, "Could not open the link");
+ if (!project) return null;
+ const opened = await openThread(scopeProjectRef(project.environmentId, project.id));
+ if (!opened) {
+ reportFailure(url);
+ return null;
+ }
+ const threadRef = scopeThreadRef(project.environmentId, opened.threadId);
+ useRightPanelStore.getState().requestMaximize(threadRef);
+ return threadRef;
+ };
+
+ const openLink = useEffectEvent(async (url: string) => {
+ const isFile = url.startsWith("file:");
+ const routeParams = router.state.matches.at(-1)?.params ?? {};
+ const threadRef =
+ threadShowingBrowser(
+ routeParams,
+ isFile ? (primaryEnvironment?.environmentId ?? null) : null,
+ ) ?? (await startThread(url));
+ if (threadRef === null) return;
+ // An HTML file is served from the environment, which runs on this machine.
+ const result = isFile
+ ? httpBaseUrl === null
+ ? null
+ : await openFileInPreview({
+ threadRef,
+ filePath: decodeURIComponent(new URL(url).pathname),
+ workspaceRoot: undefined,
+ httpBaseUrl,
+ createAssetUrl,
+ openPreview,
+ })
+ : await openUrlInPreview({ threadRef, url, openPreview });
+ if (result === null) {
+ reportFailure(url);
+ return;
+ }
+ if (result._tag === "Failure") {
+ const error = squashAtomCommandFailure(result);
+ reportFailure(url, error instanceof Error ? error.message : url);
+ }
+ });
+
+ useEffect(() => {
+ if (!ready || webLinks === undefined) return;
+ let subscribed = true;
+ // Links open one at a time, in the order they came.
+ const unsubscribe = webLinks.onOpen((url) => {
+ queueRef.current = queueRef.current.then(() => openLink(url)).catch(() => undefined);
+ });
+ // Skip readiness if React runs cleanup before this subscription can receive links.
+ queueMicrotask(() => {
+ if (subscribed) void webLinks.setReady(true).catch(() => undefined);
+ });
+ return () => {
+ subscribed = false;
+ void webLinks.setReady(false).catch(() => undefined);
+ unsubscribe();
+ };
+ }, [ready, webLinks]);
+
+ return null;
+}
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index df7969a8618..8a234372b3d 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -89,6 +89,7 @@ import {
type TerminalContextDraft,
} from "./lib/terminalContext";
import { createDeferredStorage } from "./lib/storage";
+import { applyPreviewServerSnapshot, resetPreviewStateForTests } from "./previewStateStore";
function makeImage(input: {
id: string;
@@ -1467,6 +1468,30 @@ describe("composerDraftStore project draft thread mapping", () => {
expect(draftByKey(draftId)).toBeUndefined();
});
+ it("keeps a draft with an open page when remapping a project to a new draft thread", () => {
+ const store = useComposerDraftStore.getState();
+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });
+ // A link another app opened: the composer is empty, but the page is not.
+ applyPreviewServerSnapshot(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId), {
+ threadId,
+ tabId: "tab-link",
+ navStatus: { _tag: "Success", url: "https://example.com/", title: "Example" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-10-09T00:00:00.000Z",
+ });
+ try {
+ store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId });
+
+ expect(useComposerDraftStore.getState().getDraftThread(draftId)?.threadId).toBe(threadId);
+ // It survives a reload too, so the page is still there when the app comes back.
+ const persisted = partializeComposerDraftStoreState(useComposerDraftStore.getState());
+ expect(persisted.draftThreadsByThreadKey[draftId]?.threadId).toBe(threadId);
+ } finally {
+ resetPreviewStateForTests();
+ }
+ });
+
it("keeps invested composer drafts alive unmapped when remapping a project to a new draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts
index 5e0e76730b9..f5663094da6 100644
--- a/apps/web/src/composerDraftStore.ts
+++ b/apps/web/src/composerDraftStore.ts
@@ -40,6 +40,7 @@ import { DeepMutable } from "effect/Types";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import { useMemo } from "react";
import { getLocalStorageItem } from "./hooks/useLocalStorage";
+import { readThreadPreviewState } from "./previewStateStore";
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
import {
DEFAULT_INTERACTION_MODE,
@@ -1556,6 +1557,16 @@ function getComposerDraftState(
return state.draftsByThreadKey[threadKey] ?? null;
}
+/**
+ * A draft holding an open page, such as one started for a link another app
+ * opened, is work in progress even with an empty composer.
+ */
+function draftThreadHasOpenPreview(draftThread: DraftThreadState | undefined): boolean {
+ if (draftThread === undefined) return false;
+ const ref = scopeThreadRef(draftThread.environmentId, draftThread.threadId);
+ return Object.keys(readThreadPreviewState(ref).sessions).length > 0;
+}
+
function isComposerThreadKeyInUse(mappings: Record<string, string>, threadKey: string): boolean {
return Object.values(mappings).includes(threadKey);
}
@@ -2174,10 +2185,10 @@ export function partializeComposerDraftStoreState(
state: ComposerDraftStoreState,
): PersistedComposerDraftStoreState {
// Draft sessions worth persisting: mapped (a new-thread flow targets
- // them), promoting (mid-send), or holding real user content (they back a
- // sidebar row). Everything else is a zombie — and its composer blob must
- // be dropped WITH it, or model/mode-only entries would persist forever
- // keyed to a session that no longer exists.
+ // them), promoting (mid-send), holding real user content (they back a
+ // sidebar row), or holding an open page. Everything else is a zombie — and
+ // its composer blob must be dropped WITH it, or model/mode-only entries
+ // would persist forever keyed to a session that no longer exists.
const mappedDraftKeys = new Set(
Object.values(state.logicalProjectDraftThreadKeyByLogicalProjectKey),
);
@@ -2187,7 +2198,8 @@ export function partializeComposerDraftStoreState(
([threadKey, draftThread]) =>
mappedDraftKeys.has(threadKey) ||
isDraftThreadPromoting(draftThread) ||
- composerDraftHasUserContent(state.draftsByThreadKey[threadKey]),
+ composerDraftHasUserContent(state.draftsByThreadKey[threadKey]) ||
+ draftThreadHasOpenPreview(draftThread),
)
.map(([threadKey]) => threadKey),
);
@@ -2792,7 +2804,8 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
!isDraftThreadPromoting(previousDraftThread) &&
!composerDraftHasUserContent(
state.draftsByThreadKey[previousThreadKeyForLogicalProject],
- )
+ ) &&
+ !draftThreadHasOpenPreview(previousDraftThread)
) {
delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
if (state.draftsByThreadKey[previousThreadKeyForLogicalProject] !== undefined) {
diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts
index 6124297ebef..812de880404 100644
--- a/apps/web/src/rightPanelStore.ts
+++ b/apps/web/src/rightPanelStore.ts
@@ -121,6 +121,13 @@ export interface ThreadPanelVisibility {
interface RightPanelStoreState {
byThreadKey: Record<string, ThreadRightPanelState>;
+ /**
+ * A thread whose right panel should open maximized the next time it shows,
+ * such as one started for a link the OS opened. Its view consumes it once.
+ */
+ pendingMaximizeThreadKey: string | null;
+ requestMaximize: (ref: ScopedThreadRef) => void;
+ consumeMaximizeRequest: (ref: ScopedThreadRef) => boolean;
threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
/** Session-only count of user panel choices per thread. Automatic updates do not advance it. */
userActionRevisionByThreadKey: Record<string, number>;
@@ -590,6 +597,13 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
persist(
(set, get) => ({
byThreadKey: {},
+ pendingMaximizeThreadKey: null,
+ requestMaximize: (ref) => set({ pendingMaximizeThreadKey: scopedThreadKey(ref) }),
+ consumeMaximizeRequest: (ref) => {
+ if (get().pendingMaximizeThreadKey !== scopedThreadKey(ref)) return false;
+ set({ pendingMaximizeThreadKey: null });
+ return true;
+ },
threadPanelVisibilityByThreadKey: {},
userActionRevisionByThreadKey: {},
closeRevisionByThreadKey: {},
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index d1c4ef730c8..69112d6de4e 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -27,6 +27,7 @@ import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstall
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
+import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator";
import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
import { NightlyMobileBetaNotice } from "../components/NightlyMobileBeta";
@@ -228,6 +229,7 @@ function RootRouteView() {
>
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
+ {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
{isElectron ? <RunningThreadKeepAlive /> : null}
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
diff --git a/docs/README.md b/docs/README.md
index a313434ba23..d7628960cb8 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -14,6 +14,7 @@
- [SnapShots](./user/snap-shot.md)
- [Visual replies](./user/html-renders.md)
- [Import browser sessions](./user/browser-import.md)
+- [Use T3 Code as your default browser](./user/default-browser.md)
- [Devices](./user/devices.md)
- [Usage and limits](./user/usage.md)
- [Product usage data](./user/telemetry.md)
diff --git a/docs/user/default-browser.md b/docs/user/default-browser.md
new file mode 100644
index 00000000000..23057d0661d
--- /dev/null
+++ b/docs/user/default-browser.md
@@ -0,0 +1,13 @@
+# Use T3 Code as your default browser
+
+On macOS, the desktop app can be your default web browser. Links you open from other apps then
+open in T3 Code. When the thread on screen shows its browser panel, the link opens there as a new
+tab. Otherwise it starts a new thread without a project, with the browser panel maximized on the
+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.
+
+HTML files you open from Finder open the same way.
+
+A link that launches T3 Code waits until the app has connected to its environment, then opens.
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 19e40442355..e521c4c3727 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -1246,6 +1246,14 @@ export interface DesktopBridge {
uninstall: () => Promise<DesktopCliCommandState>;
};
/** Present when the desktop shell accepts `t3 app` activation requests. */
+ /**
+ * Web links the OS opens with T3 Code as the default browser (macOS). The
+ * renderer reports when it listens; links queue in the main process until then.
+ */
+ webLinks?: {
+ setReady: (ready: boolean) => Promise<void>;
+ onOpen: (listener: (url: string) => void) => () => void;
+ };
appActivation?: {
setReady: (ready: boolean) => Promise<void>;
complete: (response: DesktopAppActivationResponse) => Promise<void>;
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts
index 8d27a55266f..e7c07225ab6 100644
--- a/scripts/build-desktop-artifact.test.ts
+++ b/scripts/build-desktop-artifact.test.ts
@@ -698,6 +698,21 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.deepStrictEqual((linux.linux as Record<string, unknown>).protocols, [
{ name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
]);
+ // macOS also offers itself as a web browser, so it can be chosen as the default.
+ assert.deepStrictEqual((mac.mac as Record<string, unknown>).protocols, [
+ { name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
+ { name: "Web site URL", schemes: ["http", "https"], role: "Viewer" },
+ ]);
+ // macOS lists a default browser only when it also opens web pages as documents.
+ const macInfo = (mac.mac as { extendInfo: Record<string, unknown> }).extendInfo;
+ assert.deepStrictEqual(macInfo.CFBundleDocumentTypes, [
+ {
+ CFBundleTypeName: "Web page",
+ CFBundleTypeRole: "Viewer",
+ LSHandlerRank: "Alternate",
+ LSItemContentTypes: ["public.html", "public.xhtml"],
+ },
+ ]);
assert.deepStrictEqual(linux.toolsets, { appimage: "1.0.3" });
assert.notProperty(mac, "toolsets");
assert.notProperty(win, "toolsets");
@@ -2082,6 +2097,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.match(String(mac.sign), /[\\/]scripts[\\/]sign-macos\.ts$/);
assert.deepStrictEqual(mac.protocols, [
{ name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
+ { name: "Web site URL", schemes: ["http", "https"], role: "Viewer" },
]);
}).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
);
diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts
index 374e3783066..8270b413856 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -2813,12 +2813,29 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* (
extendInfo: {
NSScreenCaptureUsageDescription:
"T3 Code captures the active window when you use the window capture shortcut.",
+ // macOS lists an app under Default web browser only when it opens web
+ // pages as documents as well as http and https links (see protocols).
+ CFBundleDocumentTypes: [
+ {
+ CFBundleTypeName: "Web page",
+ CFBundleTypeRole: "Viewer",
+ LSHandlerRank: "Alternate",
+ LSItemContentTypes: ["public.html", "public.xhtml"],
+ },
+ ],
},
protocols: [
{
name: "T3 Code",
schemes: ["t3code", "t3code-dev"],
},
+ // Lets people choose T3 Code as their default web browser, which opens
+ // each link in a new thread's browser panel.
+ {
+ name: "Web site URL",
+ schemes: ["http", "https"],
+ role: "Viewer",
+ },
],
...(signed ? { sign: path.join(repoRoot, "scripts/sign-macos.ts") } : {}),
...(macPasskeySigning