Skip to content

Commit 7d1b899

Browse files
fix(web): open default-browser links as tabs in the visible browser
A link opened from another app now becomes a new tab when the thread on screen shows its browser panel, instead of always starting a thread. A draft that holds an open page counts as in use, so a later new-thread request no longer takes it over and drops the page. This replaces the fresh option on the new-thread handler. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0617ef8 commit 7d1b899

5 files changed

Lines changed: 81 additions & 34 deletions

File tree

‎apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx‎

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,56 @@
11
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
22
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3+
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
4+
import { useRouter } from "@tanstack/react-router";
35
import { useEffect, useEffectEvent, useRef } from "react";
46

57
import { openFileInPreview, openUrlInPreview } from "../../browser/openFileInPreview";
8+
import { isPreviewAvailableFor } from "../../browser/previewRuntime";
9+
import { useComposerDraftStore } from "../../composerDraftStore";
610
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
711
import { useScratchProject } from "../../hooks/useScratchProject";
8-
import { useRightPanelStore } from "../../rightPanelStore";
12+
import { selectActiveRightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
13+
import { resolveThreadRouteTarget } from "../../threadRoutes";
914
import { assetEnvironment } from "../../state/assets";
1015
import { useEnvironmentHttpBaseUrl, usePrimaryEnvironment } from "../../state/environments";
1116
import { previewEnvironment } from "../../state/preview";
1217
import { useAtomCommand } from "../../state/use-atom-command";
1318
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
1419
import { stackedThreadToast, toastManager } from "../ui/toast";
1520

21+
/**
22+
* The thread on screen when its browser panel is showing, so a link opens as
23+
* another tab there, the way a browser window takes new links. HTML files are
24+
* served by this machine's environment, so only its threads can take them.
25+
*/
26+
function threadShowingBrowser(
27+
routeParams: Record<string, string | undefined>,
28+
fileEnvironmentId: EnvironmentId | null,
29+
): ScopedThreadRef | null {
30+
const target = resolveThreadRouteTarget(routeParams);
31+
if (target === null) return null;
32+
let threadRef = target.kind === "server" ? target.threadRef : null;
33+
if (target.kind === "draft") {
34+
const session = useComposerDraftStore.getState().getDraftSession(target.draftId);
35+
if (!session || session.promotedTo) return null;
36+
threadRef = scopeThreadRef(session.environmentId, session.threadId);
37+
}
38+
if (threadRef === null || !isPreviewAvailableFor(threadRef.environmentId)) return null;
39+
if (fileEnvironmentId !== null && threadRef.environmentId !== fileEnvironmentId) return null;
40+
const surface = selectActiveRightPanelSurface(
41+
useRightPanelStore.getState().byThreadKey,
42+
threadRef,
43+
);
44+
return surface?.kind === "preview" ? threadRef : null;
45+
}
46+
1647
/**
1748
* Opens each web link or HTML file the OS hands T3 Code as the default browser
18-
* (macOS) in a new thread without a project, its browser panel maximized on the page.
49+
* (macOS). With a browser panel on screen the page opens as a new tab there;
50+
* otherwise it starts a thread without a project, its browser panel maximized.
1951
*/
2052
export function DesktopWebLinkCoordinator() {
53+
const router = useRouter();
2154
const primaryEnvironment = usePrimaryEnvironment();
2255
const { scratchEnvironmentId, openScratchProject } = useScratchProject();
2356
const openThread = useNewThreadHandler();
@@ -34,20 +67,29 @@ export function DesktopWebLinkCoordinator() {
3467
primaryEnvironment?.connection.phase === "connected" &&
3568
primaryEnvironment.serverConfig !== null;
3669

37-
const openLink = useEffectEvent(async (url: string) => {
70+
const startThread = async (): Promise<ScopedThreadRef | null> => {
3871
const environmentId = scratchEnvironmentId(primaryEnvironment?.environmentId ?? null);
39-
if (environmentId === null) return;
72+
if (environmentId === null) return null;
4073
const project = await openScratchProject(environmentId, "Could not open the link");
41-
if (!project) return;
42-
// Each link is its own thread, even before the user types in the last one.
43-
const opened = await openThread(scopeProjectRef(project.environmentId, project.id), {
44-
fresh: true,
45-
});
46-
if (!opened) return;
74+
if (!project) return null;
75+
const opened = await openThread(scopeProjectRef(project.environmentId, project.id));
76+
if (!opened) return null;
4777
const threadRef = scopeThreadRef(project.environmentId, opened.threadId);
4878
useRightPanelStore.getState().requestMaximize(threadRef);
79+
return threadRef;
80+
};
81+
82+
const openLink = useEffectEvent(async (url: string) => {
83+
const isFile = url.startsWith("file:");
84+
const routeParams = router.state.matches.at(-1)?.params ?? {};
85+
const threadRef =
86+
threadShowingBrowser(
87+
routeParams,
88+
isFile ? (primaryEnvironment?.environmentId ?? null) : null,
89+
) ?? (await startThread());
90+
if (threadRef === null) return;
4991
// An HTML file is served from the environment, which runs on this machine.
50-
const result = url.startsWith("file:")
92+
const result = isFile
5193
? httpBaseUrl === null
5294
? null
5395
: await openFileInPreview({

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1561,8 +1561,10 @@ function getComposerDraftState(
15611561
* A draft holding an open page, such as one started for a link another app
15621562
* opened, is work in progress even with an empty composer.
15631563
*/
1564-
function draftThreadHasOpenPreview(draftThread: DraftThreadState | undefined): boolean {
1565-
if (draftThread === undefined) return false;
1564+
export function draftThreadHasOpenPreview(
1565+
draftThread: DraftThreadState | null | undefined,
1566+
): boolean {
1567+
if (!draftThread) return false;
15661568
const ref = scopeThreadRef(draftThread.environmentId, draftThread.threadId);
15671569
return Object.keys(readThreadPreviewState(ref).sessions).length > 0;
15681570
}

‎apps/web/src/hooks/useHandleNewThread.test.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,20 @@ const testState = vi.hoisted(() => {
2828
const draftStore = {
2929
getComposerDraft: vi.fn(() => ({})),
3030
getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft),
31-
getDraftSession: vi.fn(() => null),
31+
getDraftSession: vi.fn((draftId: string) =>
32+
storedDraft?.draftId === draftId ? storedDraft : null,
33+
),
3234
getDraftThread: vi.fn(() => null),
3335
applyStickyState: vi.fn(),
3436
setDraftThreadContext: vi.fn(),
3537
setLogicalProjectDraftThreadId: vi.fn(),
3638
setModelSelection: vi.fn(),
3739
};
3840

41+
const draftIdsWithOpenPage = new Set<string>();
3942
return {
4043
completeProjectFileRead: (value: null) => completeProjectFileRead(value),
44+
draftIdsWithOpenPage,
4145
draftStore,
4246
get projectFileRead() {
4347
return projectFileRead;
@@ -53,6 +57,7 @@ const testState = vi.hoisted(() => {
5357
},
5458
) {
5559
storedDraft = nextStoredDraft;
60+
draftIdsWithOpenPage.clear();
5661
targetSettings = {
5762
defaultThreadEnvMode: workspaceDefaults.envMode,
5863
newWorktreesStartFromOrigin: workspaceDefaults.startFromOrigin,
@@ -134,6 +139,8 @@ vi.mock("../composerDraftStore", () => {
134139
});
135140
return {
136141
composerDraftHasUserContent: () => false,
142+
draftThreadHasOpenPreview: (session: { readonly draftId?: string } | null) =>
143+
session?.draftId !== undefined && testState.draftIdsWithOpenPage.has(session.draftId),
137144
markPromotedDraftThreadByRef: vi.fn(),
138145
useComposerDraftStore,
139146
};
@@ -288,17 +295,18 @@ describe.each([
288295
);
289296
});
290297

291-
it("starts a new draft for fresh requests even when an empty one could be reused", async () => {
298+
it("starts a new draft instead of taking over one that holds an open page", async () => {
292299
testState.reset({
293300
draftId: "draft-existing",
294301
environmentId: "environment-ssh",
295302
promotedTo: null,
296303
threadId: "thread-existing",
297304
});
305+
// A page opened from another app leaves the composer empty; the draft is still in use.
306+
testState.draftIdsWithOpenPage.add("draft-existing");
298307
const projectRef = { environmentId: "environment-ssh", projectId: "project-remote" } as never;
299-
const pendingOpen = useNewThreadHandler()(projectRef, { fresh: true });
308+
const pendingOpen = useNewThreadHandler()(projectRef);
300309
testState.completeProjectFileRead(null);
301310

302-
// A page another app opened is its own thread, not the one the last page took.
303311
expect(await pendingOpen).toEqual({ draftId: "draft-delayed", threadId: "thread-delayed" });
304312
});

‎apps/web/src/hooks/useHandleNewThread.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { useParams, useRouter } from "@tanstack/react-router";
99
import { useCallback, useMemo } from "react";
1010
import {
1111
composerDraftHasUserContent,
12+
draftThreadHasOpenPreview,
1213
markPromotedDraftThreadByRef,
1314
type DraftId,
1415
type DraftThreadEnvMode,
@@ -72,12 +73,6 @@ export function useNewThreadHandler() {
7273
envMode?: DraftThreadEnvMode;
7374
startFromOrigin?: boolean;
7475
replace?: boolean;
75-
/**
76-
* Always start a new draft, even when the project has an empty one to
77-
* reuse. For work that is not typed into the composer, such as a page
78-
* opened from another app, which would otherwise land in the same draft.
79-
*/
80-
fresh?: boolean;
8176
},
8277
// Which draft the thread ended up in, so a caller that has something to put in it — a
8378
// prepared checkout, a task to write — addresses that one rather than looking the project
@@ -98,6 +93,11 @@ export function useNewThreadHandler() {
9893
} = useComposerDraftStore.getState();
9994
const requestingRouteHref = router.state.location.href;
10095
const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref;
96+
// Typed content, attachments, or an open page make a draft work in
97+
// progress that a new-thread request must not take over.
98+
const draftHasWork = (draftId: DraftId) =>
99+
composerDraftHasUserContent(getComposerDraft(draftId)) ||
100+
draftThreadHasOpenPreview(getDraftSession(draftId));
101101
const currentRouteTarget = getCurrentRouteTarget();
102102
// A new thread carries the user's working mode from the thread being
103103
// viewed. The target project's configured model still wins; interaction
@@ -195,9 +195,7 @@ export function useNewThreadHandler() {
195195
// fresh draft instead — the remap in the store preserves invested
196196
// drafts rather than deleting them.
197197
const emptyStoredDraftThread =
198-
!options?.fresh &&
199-
reusableStoredDraftThread &&
200-
!composerDraftHasUserContent(getComposerDraft(reusableStoredDraftThread.draftId))
198+
reusableStoredDraftThread && !draftHasWork(reusableStoredDraftThread.draftId)
201199
? reusableStoredDraftThread
202200
: null;
203201
const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
@@ -250,9 +248,7 @@ export function useNewThreadHandler() {
250248
const remappedMeanwhile =
251249
getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !==
252250
emptyStoredDraftThread.draftId;
253-
const investedMeanwhile = composerDraftHasUserContent(
254-
getComposerDraft(emptyStoredDraftThread.draftId),
255-
);
251+
const investedMeanwhile = draftHasWork(emptyStoredDraftThread.draftId);
256252
if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) {
257253
return null;
258254
}
@@ -334,14 +330,13 @@ export function useNewThreadHandler() {
334330
}
335331

336332
if (
337-
!options?.fresh &&
338333
latestActiveDraftThread &&
339334
currentRouteTarget?.kind === "draft" &&
340335
latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
341336
latestActiveDraftThread.promotedTo == null &&
342337
// Same content rule as above: a new-thread request while viewing an
343338
// invested draft mints a fresh one instead of repurposing it.
344-
!composerDraftHasUserContent(getComposerDraft(currentRouteTarget.draftId))
339+
!draftHasWork(currentRouteTarget.draftId)
345340
) {
346341
if (
347342
hasBranchOption ||
@@ -378,7 +373,6 @@ export function useNewThreadHandler() {
378373
// reuse the winner instead, like the synchronous path above does.
379374
const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey);
380375
if (
381-
!options?.fresh &&
382376
racedDraft &&
383377
// Only a draft REGISTERED during the await counts as a raced
384378
// winner. An invested draft this invocation deliberately declined

‎docs/user/default-browser.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# Use T3 Code as your default browser
22

33
On macOS, the desktop app can be your default web browser. Links you open from other apps then
4-
open in T3 Code: each one starts a new thread without a project, with the browser panel
5-
maximized on the page, so you can ask an agent about it right away.
4+
open in T3 Code. When the thread on screen shows its browser panel, the link opens there as a new
5+
tab. Otherwise it starts a new thread without a project, with the browser panel maximized on the
6+
page, so you can ask an agent about it right away.
67

78
Choose **T3 Code** under **System Settings → Desktop & Dock → Default web browser**. To go back,
89
choose another browser there.

0 commit comments

Comments
 (0)