fix(preview): initialize and open browser reliably

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and Theo Browne committed 2026-06-13 22:18:37 -07:00
1 parent 9b43123ba2
commit 63d42a5e58
8 files changed
+116 -6

No files matched your search

@@ -0,0 +1,28 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const fromPartition = vi.fn(() => {
throw new Error("Session can only be received when app is ready");
});
vi.mock("electron", () => ({
BrowserWindow: {
getAllWindows: vi.fn(() => []),
},
session: {
fromPartition,
},
webContents: {
fromId: vi.fn(() => null),
},
}));
describe("preview IPC methods", () => {
beforeEach(() => {
fromPartition.mockClear();
});
it("does not access the Electron session while the module loads", async () => {
await expect(import("./preview.ts")).resolves.toBeDefined();
expect(fromPartition).not.toHaveBeenCalled();
});
});
-1
View File
@@ -9,7 +9,6 @@ import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview-webview-preferences.t
import * as IpcChannels from "../channels.ts";
import type { DesktopIpcMethod } from "../DesktopIpc.ts";
previewViewManager.getBrowserSession();
previewViewManager.onStateChange((tabId, state) => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
@@ -8,6 +8,17 @@ import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
vi.mock("electron", async (importOriginal) => ({
...(await importOriginal<typeof import("electron")>()),
session: {
fromPartition: vi.fn(() => ({
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/1.2.3"),
setPermissionRequestHandler: vi.fn(),
setUserAgent: vi.fn(),
})),
},
}));
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
+1
View File
@@ -171,6 +171,7 @@ const make = Effect.gen(function* () {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
previewViewManager.getBrowserSession();
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
@@ -12,6 +12,7 @@ import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateSt
import { previewBridge } from "./previewBridge";
import { subscribePreviewAction } from "./previewActionBus";
import { openPreviewSession } from "./openPreviewSession";
import { PreviewChromeRow } from "./PreviewChromeRow";
import { PreviewEmptyState } from "./PreviewEmptyState";
import { PreviewMoreMenu } from "./PreviewMoreMenu";
@@ -41,6 +42,7 @@ export function PreviewView({ threadRef, configuredUrls, visible }: Props) {
const previewState = usePreviewStateStore((state) =>
selectThreadPreviewState(state.byThreadKey, threadRef),
);
const applyServerSnapshot = usePreviewStateStore((state) => state.applyServerSnapshot);
const rememberUrl = usePreviewStateStore((state) => state.rememberUrl);
const addElementContext = useComposerDraftStore((store) => store.addElementContext);
@@ -74,15 +76,19 @@ export function PreviewView({ threadRef, configuredUrls, visible }: Props) {
await previewBridge.navigate(tabId, next);
rememberUrl(threadRef, next);
} else {
const resolved = await api.preview.open({ threadId: threadRef.threadId, url: next });
const resolvedUrl = resolved.navStatus._tag === "Idle" ? next : resolved.navStatus.url;
rememberUrl(threadRef, resolvedUrl);
await openPreviewSession({
previewApi: api.preview,
threadRef,
url: next,
applyServerSnapshot,
rememberUrl,
});
}
} catch {
// Server-side `failed` event renders the unreachable view.
}
},
[rememberUrl, tabId, threadRef],
[applyServerSnapshot, rememberUrl, tabId, threadRef],
);
const handleRefresh = useCallback(() => {
@@ -0,0 +1,42 @@
import type { EnvironmentApi, PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { openPreviewSession } from "./openPreviewSession";
const threadRef = {
environmentId: "local" as ScopedThreadRef["environmentId"],
threadId: "thread-1" as ScopedThreadRef["threadId"],
};
const snapshot: PreviewSessionSnapshot = {
threadId: threadRef.threadId,
tabId: "tab-1",
navStatus: {
_tag: "Loading",
url: "https://t3.chat/",
title: "",
},
canGoBack: false,
canGoForward: false,
updatedAt: "2026-06-11T23:00:00.000Z",
};
describe("openPreviewSession", () => {
it("applies the RPC response without waiting for a preview event", async () => {
const open = vi.fn(async () => snapshot);
const applyServerSnapshot = vi.fn();
const rememberUrl = vi.fn();
await openPreviewSession({
previewApi: { open } as Pick<EnvironmentApi["preview"], "open">,
threadRef,
url: "t3.chat",
applyServerSnapshot,
rememberUrl,
});
expect(open).toHaveBeenCalledWith({ threadId: "thread-1", url: "t3.chat" });
expect(applyServerSnapshot).toHaveBeenCalledWith(threadRef, snapshot);
expect(rememberUrl).toHaveBeenCalledWith(threadRef, "https://t3.chat/");
});
});
@@ -0,0 +1,23 @@
import type { EnvironmentApi, ScopedThreadRef } from "@t3tools/contracts";
import type { PreviewStateStoreState } from "~/previewStateStore";
interface OpenPreviewSessionInput {
previewApi: Pick<EnvironmentApi["preview"], "open">;
threadRef: ScopedThreadRef;
url: string;
applyServerSnapshot: PreviewStateStoreState["applyServerSnapshot"];
rememberUrl: PreviewStateStoreState["rememberUrl"];
}
export async function openPreviewSession(input: OpenPreviewSessionInput): Promise<void> {
const snapshot = await input.previewApi.open({
threadId: input.threadRef.threadId,
url: input.url,
});
input.applyServerSnapshot(input.threadRef, snapshot);
input.rememberUrl(
input.threadRef,
snapshot.navStatus._tag === "Idle" ? input.url : snapshot.navStatus.url,
);
}
+1 -1
View File
@@ -42,7 +42,7 @@ const EMPTY_THREAD_PREVIEW_STATE: ThreadPreviewState = Object.freeze({
recentlySeenUrls: [] as string[],
});
interface PreviewStateStoreState {
export interface PreviewStateStoreState {
byThreadKey: Record<string, ThreadPreviewState>;
applyServerEvent: (ref: ScopedThreadRef, event: PreviewEvent) => void;
applyServerSnapshot: (ref: ScopedThreadRef, snapshot: PreviewSessionSnapshot | null) => void;