Skip to content

Commit 46a2c26

Browse files
fix(web): desktop opens remote environments' browser tabs locally
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5809487 commit 46a2c26

7 files changed

Lines changed: 173 additions & 7 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import type { EnvironmentId } from "@t3tools/contracts";
2+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3+
4+
const state = vi.hoisted(() => ({
5+
desktop: false,
6+
primary: null as string | null,
7+
serverBrowser: new Set<string>(),
8+
}));
9+
10+
vi.mock("~/env", () => ({ isElectron: false }));
11+
vi.mock("~/previewStateStore", () => ({ isPreviewSupportedInRuntime: () => state.desktop }));
12+
vi.mock("~/rpc/atomRegistry", () => ({ appAtomRegistry: { get: () => state.primary } }));
13+
vi.mock("~/state/primaryEnvironment", () => ({ primaryEnvironmentIdAtom: {} }));
14+
vi.mock("~/state/entities", () => ({
15+
readEnvironmentSupportsServerBrowser: (id: string) => state.serverBrowser.has(id),
16+
useEnvironmentSupportsServerBrowser: () => false,
17+
}));
18+
19+
import { alternatePreviewRuntime, previewRuntimeFor } from "./previewRuntime";
20+
21+
const local = "local" as EnvironmentId;
22+
const remote = "remote" as EnvironmentId;
23+
24+
afterEach(() => {
25+
state.desktop = false;
26+
state.primary = null;
27+
state.serverBrowser = new Set();
28+
});
29+
30+
describe("previewRuntimeFor", () => {
31+
it("opens a remote environment's tabs on this computer in the desktop app", () => {
32+
state.desktop = true;
33+
state.primary = local;
34+
state.serverBrowser = new Set([local, remote]);
35+
36+
expect(previewRuntimeFor(remote)).toBeUndefined();
37+
expect(previewRuntimeFor(local)).toBe("server");
38+
});
39+
40+
it("uses the environment's browser where the client has none of its own", () => {
41+
state.serverBrowser = new Set([remote]);
42+
43+
expect(previewRuntimeFor(remote)).toBe("server");
44+
});
45+
});
46+
47+
describe("alternatePreviewRuntime", () => {
48+
it("moves a remote environment's tab between this computer and the environment", () => {
49+
state.desktop = true;
50+
51+
expect(alternatePreviewRuntime(remote, local, true, {})).toBe("server");
52+
expect(alternatePreviewRuntime(remote, local, true, { runtime: "server" })).toBe("desktop");
53+
expect(alternatePreviewRuntime(local, local, true, {})).toBeNull();
54+
expect(alternatePreviewRuntime(remote, local, false, {})).toBeNull();
55+
});
56+
57+
it("offers no move outside the desktop app", () => {
58+
expect(alternatePreviewRuntime(remote, null, true, { runtime: "server" })).toBeNull();
59+
});
60+
});

‎apps/web/src/browser/previewRuntime.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,44 @@ import type { EnvironmentId, PreviewRuntime, PreviewSessionSnapshot } from "@t3t
33

44
import { isElectron } from "~/env";
55
import { isPreviewSupportedInRuntime } from "~/previewStateStore";
6+
import { appAtomRegistry } from "~/rpc/atomRegistry";
67
import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
78
import {
89
readEnvironmentSupportsServerBrowser,
910
useEnvironmentSupportsServerBrowser,
1011
} from "~/state/entities";
1112

13+
/**
14+
* Where a tab the user opens should run. The desktop app draws its own
15+
* server's tabs natively, so those stay agent-drivable at no cost. A remote
16+
* environment's tabs would stream, so the desktop opens them in its own
17+
* browser instead: no latency, and it reaches what this computer reaches. The
18+
* user can move a tab to the environment when only it can reach the page.
19+
*/
1220
export function previewRuntimeFor(environmentId: EnvironmentId): PreviewRuntime | undefined {
13-
return readEnvironmentSupportsServerBrowser(environmentId) ? "server" : undefined;
21+
if (!readEnvironmentSupportsServerBrowser(environmentId)) return undefined;
22+
if (
23+
isPreviewSupportedInRuntime() &&
24+
environmentId !== appAtomRegistry.get(primaryEnvironmentIdAtom)
25+
) {
26+
return undefined;
27+
}
28+
return "server";
29+
}
30+
31+
/**
32+
* The other browser a tab can move to, or null when it has none: a desktop
33+
* tab of a remote environment can move to that environment's browser, and back.
34+
*/
35+
export function alternatePreviewRuntime(
36+
environmentId: EnvironmentId,
37+
primaryEnvironmentId: EnvironmentId | null,
38+
serverBrowser: boolean,
39+
snapshot: Pick<PreviewSessionSnapshot, "runtime"> | null | undefined,
40+
): PreviewRuntime | null {
41+
if (!snapshot || !serverBrowser || !isPreviewSupportedInRuntime()) return null;
42+
if (environmentId === primaryEnvironmentId) return null;
43+
return snapshot.runtime === "server" ? "desktop" : "server";
1444
}
1545

1646
/** Electron hosts its own browser tabs; other clients need the environment to host them. */

‎apps/web/src/components/preview/PreviewMoreMenu.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ interface Props {
6464
nativePictureInPicture: boolean;
6565
/** Profile display name, shown so the menu says which data is being cleared. */
6666
profileName: string | undefined;
67+
/** Reopens the tab in the other browser it can run in. */
68+
move?: { readonly label: string; readonly onMove: () => void };
6769
}
6870

6971
const MenuTriggerButton = () => (
@@ -91,6 +93,7 @@ export function PreviewMoreMenu({
9193
onToggleDeviceToolbar,
9294
nativePictureInPicture,
9395
profileName,
96+
move,
9497
}: Props) {
9598
const zoomLabel = `${Math.round(zoomFactor * 100)}%`;
9699
const disabled = !enabled;
@@ -113,6 +116,7 @@ export function PreviewMoreMenu({
113116
: "Open separate preview window"}
114117
</MenuItem>
115118
) : null}
119+
{move ? <MenuItem onClick={move.onMove}>{move.label}</MenuItem> : null}
116120
<MenuItem onClick={onToggleDeviceToolbar} disabled={disabled}>
117121
{deviceToolbarVisible ? "Hide device toolbar" : "Show device toolbar"}
118122
</MenuItem>

‎apps/web/src/components/preview/PreviewUnreachable.tsx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ interface Props {
1111
/** Stringified Chromium error, e.g. "ERR_NAME_NOT_RESOLVED". */
1212
description: string;
1313
onReload: () => void;
14+
/** Reopens the page in a browser that may reach it, such as the environment's. */
15+
move?: { readonly label: string; readonly onMove: () => void };
1416
}
1517

1618
/** Theme-aware tailwind port of Chromium's "This site can't be reached" page. */
17-
export function PreviewUnreachable({ url, code, description, onReload }: Props) {
19+
export function PreviewUnreachable({ url, code, description, onReload, move }: Props) {
1820
const [showDetails, setShowDetails] = useState(false);
1921
const host = safeHost(url) ?? url;
2022
const friendly = describePreviewError(description);
@@ -37,6 +39,9 @@ export function PreviewUnreachable({ url, code, description, onReload }: Props)
3739
<ul className="list-disc space-y-1 pl-5 text-muted-foreground">
3840
<li>Checking your connection</li>
3941
<li>Confirming the dev server is running</li>
42+
{move ? (
43+
<li>Opening it in the environment&rsquo;s browser, which reaches its network</li>
44+
) : null}
4045
<li>Checking the proxy and the firewall</li>
4146
</ul>
4247
</div>
@@ -56,6 +61,11 @@ export function PreviewUnreachable({ url, code, description, onReload }: Props)
5661
{showDetails ? "Hide details" : "Details"}
5762
</Button>
5863
<div className="flex-1" />
64+
{move ? (
65+
<Button type="button" variant="outline" size="sm" onClick={move.onMove}>
66+
{move.label}
67+
</Button>
68+
) : null}
5969
<Button type="button" size="sm" onClick={onReload}>
6070
Reload
6171
</Button>

‎apps/web/src/components/preview/PreviewView.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,11 @@ vi.mock("~/previewStateStore", () => ({
151151
vi.mock("~/state/environments", () => ({
152152
useEnvironment: () => ({ label: "WSL" }),
153153
useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
154+
usePrimaryEnvironmentId: () => null,
154155
}));
155156

156157
vi.mock("~/state/preview", () => ({
157-
previewEnvironment: { open: {}, resize: {} },
158+
previewEnvironment: { open: {}, close: {}, resize: {} },
158159
}));
159160

160161
vi.mock("~/state/use-atom-command", () => ({

‎apps/web/src/components/preview/PreviewView.tsx‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,12 @@ import {
3535
useThreadPreviewState,
3636
} from "~/previewStateStore";
3737
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
38-
import { useEnvironmentHttpBaseUrl } from "~/state/environments";
38+
import { useEnvironmentSupportsServerBrowser } from "~/state/entities";
39+
import {
40+
useEnvironment,
41+
useEnvironmentHttpBaseUrl,
42+
usePrimaryEnvironmentId,
43+
} from "~/state/environments";
3944
import { previewEnvironment } from "~/state/preview";
4045
import { useAtomCommand } from "~/state/use-atom-command";
4146
import {
@@ -48,6 +53,7 @@ import { useRightPanelStore } from "~/rightPanelStore";
4853

4954
import { previewBridge } from "./previewBridge";
5055
import { subscribePreviewAction } from "./previewActionBus";
56+
import { closePreviewSession } from "./closePreviewSession";
5157
import { openPreviewSession } from "./openPreviewSession";
5258
import { PreviewChromeRow } from "./PreviewChromeRow";
5359
import { PreviewEmptyState } from "./PreviewEmptyState";
@@ -66,7 +72,7 @@ import { revealInFileExplorerLabel } from "./fileExplorerLabel";
6672
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
6773
import { Badge } from "~/components/ui/badge";
6874
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
69-
import { useRendersServerTabNatively } from "~/browser/previewRuntime";
75+
import { alternatePreviewRuntime, useRendersServerTabNatively } from "~/browser/previewRuntime";
7076
import { ServerBrowserSurface, type ServerBrowserHandle } from "~/browser/ServerBrowserSurface";
7177
import { cn } from "~/lib/utils";
7278
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
@@ -141,6 +147,10 @@ export function PreviewView({
141147
? new URL(environmentHttpBaseUrl).hostname
142148
: null;
143149
const open = useAtomCommand(previewEnvironment.open);
150+
const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
151+
const environmentLabel = useEnvironment(threadRef.environmentId)?.label ?? "the environment";
152+
const primaryEnvironmentId = usePrimaryEnvironmentId();
153+
const serverBrowser = useEnvironmentSupportsServerBrowser(threadRef.environmentId);
144154
const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
145155
const adjust = useAtomCommand(previewEnvironment.adjust, "preview appearance or zoom");
146156

@@ -410,6 +420,48 @@ export function PreviewView({
410420
void localApi.shell.openExternal(url).catch(() => undefined);
411421
}, [url]);
412422

423+
// A desktop tab of a remote environment can only reach what this computer
424+
// reaches; the environment's browser reaches its own network, and its agents.
425+
const moveTarget = alternatePreviewRuntime(
426+
threadRef.environmentId,
427+
primaryEnvironmentId,
428+
serverBrowser,
429+
snapshot,
430+
);
431+
const moveLabel =
432+
moveTarget === "server" ? `Open in ${environmentLabel}'s browser` : "Open on this computer";
433+
const handleMoveTab = useCallback(async () => {
434+
if (!moveTarget || !tabId || !snapshot) return;
435+
const result = await openPreviewSession({
436+
openPreview: open,
437+
threadRef,
438+
// Loopback means the environment's machine, which this computer reaches by its address.
439+
...(url
440+
? {
441+
url:
442+
moveTarget === "desktop"
443+
? resolveDiscoveredServerUrl(threadRef.environmentId, url)
444+
: url,
445+
}
446+
: {}),
447+
viewport,
448+
...(snapshot.profileId === undefined ? {} : { profileId: snapshot.profileId }),
449+
runtime: moveTarget,
450+
});
451+
if (result._tag === "Failure") {
452+
if (isAtomCommandInterrupted(result)) return;
453+
const error = squashAtomCommandFailure(result);
454+
toastManager.add({
455+
type: "error",
456+
title: "Unable to move the browser tab",
457+
description: error instanceof Error ? error.message : "An error occurred.",
458+
});
459+
return;
460+
}
461+
useRightPanelStore.getState().openBrowser(threadRef, result.value.tabId);
462+
await closePreviewSession({ closePreview, snapshot, tabId, threadRef });
463+
}, [closePreview, moveTarget, open, snapshot, tabId, threadRef, url, viewport]);
464+
413465
const handlePictureInPicture = useCallback(() => {
414466
if (!tabId) return;
415467
if (miniPlayerTabId === tabId) {
@@ -949,6 +1001,9 @@ export function PreviewView({
9491001
(serverOwnsRendering || (desktopOverlay?.hasWebContents ?? false))
9501002
}
9511003
actions={moreMenuActions}
1004+
{...(moveTarget
1005+
? { move: { label: moveLabel, onMove: () => void handleMoveTab() } }
1006+
: {})}
9521007
profileName={activeProfileName}
9531008
zoomFactor={
9541009
serverOwnsRendering ? serverZoomFactor : (desktopOverlay?.zoomFactor ?? 1)
@@ -1050,6 +1105,9 @@ export function PreviewView({
10501105
code={navStatus.code}
10511106
description={navStatus.description}
10521107
onReload={handleRefresh}
1108+
{...(moveTarget === "server"
1109+
? { move: { label: moveLabel, onMove: () => void handleMoveTab() } }
1110+
: {})}
10531111
/>
10541112
</div>
10551113
) : null}

‎apps/web/src/components/preview/openPreviewSession.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type {
22
EnvironmentId,
33
PreviewOpenInput,
4+
PreviewRuntime,
45
PreviewSessionSnapshot,
56
PreviewViewportSetting,
67
ScopedThreadRef,
@@ -29,6 +30,8 @@ interface OpenPreviewSessionInput<E> {
2930
viewport?: PreviewViewportSetting;
3031
/** Overrides the configured default profile. */
3132
profileId?: string;
33+
/** Overrides where the tab runs, such as when moving a tab between browsers. */
34+
runtime?: PreviewRuntime;
3235
}
3336

3437
export async function openPreviewSession<E>(
@@ -42,15 +45,15 @@ export async function openPreviewSession<E>(
4245
if (defaults instanceof BrowserSettingsReadError) {
4346
return AsyncResult.failure(Cause.fail(defaults));
4447
}
45-
const runtime = previewRuntimeFor(input.threadRef.environmentId);
48+
const runtime = input.runtime ?? previewRuntimeFor(input.threadRef.environmentId);
4649
const result = await input.openPreview({
4750
environmentId: input.threadRef.environmentId,
4851
input: {
4952
threadId: input.threadRef.threadId,
5053
...(input.url === undefined ? {} : { url: input.url }),
5154
viewport: input.viewport ?? browserDefaultOpenViewport(defaults),
5255
profileId: input.profileId ?? browserDefaultOpenProfileId(defaults),
53-
...(runtime === undefined ? {} : { runtime }),
56+
...(runtime === undefined || runtime === "desktop" ? {} : { runtime }),
5457
},
5558
});
5659
if (result._tag === "Failure") {

0 commit comments

Comments
 (0)