Open History to see the last commit
1import {
2 DEFAULT_CLIENT_SETTINGS,
3 type PreviewSessionSnapshot,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import { AsyncResult } from "effect/reactivity";
8import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10import * as browserDefaults from "~/browser/browserDefaults";
11import {
12 BrowserSettingsReadError,
13 openFileInPreview,
14 openUrlInPreview,
15} from "~/browser/openFileInPreview";
16import * as previewRuntime from "~/browser/previewRuntime";
17import { __setClientSettingsForTests } from "~/hooks/useSettings";
18import {
19 hostRightPanel,
20 selectActiveRightPanelSurface,
21 useRightPanelStore,
22} from "~/rightPanelStore";
23import {
24 applyPreviewServerSnapshot,
25 readThreadPreviewState,
26 resetPreviewStateForTests,
27 setActivePreviewTab,
28} from "~/previewStateStore";
29
30import { addBrowserSurface } from "./addBrowserSurface";
31import { openPreviewSession } from "./openPreviewSession";
32
33const threadRef = {
34 environmentId: "local" as ScopedThreadRef["environmentId"],
35 threadId: "thread-1" as ScopedThreadRef["threadId"],
36};
37
38const snapshot: PreviewSessionSnapshot = {
39 threadId: threadRef.threadId,
40 tabId: "tab-1",
41 navStatus: {
42 _tag: "Loading",
43 url: "https://t3.chat/",
44 title: "",
45 },
46 canGoBack: false,
47 canGoForward: false,
48 updatedAt: "2026-06-11T23:00:00.000Z",
49};
50
51beforeEach(() => {
52 resetPreviewStateForTests();
53 useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
54 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
55});
56
57afterEach(() => {
58 vi.restoreAllMocks();
59});
60
61describe("openPreviewSession", () => {
62 it("duplicates a browser beside its source using its URL, profile, viewport and runtime", async () => {
63 const source: PreviewSessionSnapshot = {
64 ...snapshot,
65 profileId: "work",
66 viewport: { _tag: "freeform", width: 800, height: 600 },
67 runtime: "server",
68 };
69 const panels = useRightPanelStore.getState();
70 panels.openBrowser(threadRef, source.tabId);
71 panels.openBrowser(threadRef, "other-tab");
72 const openPreview = vi.fn(async () =>
73 AsyncResult.success({ ...source, tabId: "duplicate-tab" }),
74 );
75
76 await addBrowserSurface({ threadRef, openPreview, duplicateFrom: source });
77
78 expect(openPreview).toHaveBeenCalledWith({
79 environmentId: threadRef.environmentId,
80 input: {
81 threadId: threadRef.threadId,
82 url: "https://t3.chat/",
83 profileId: "work",
84 viewport: source.viewport,
85 runtime: "server",
86 zoomFactor: 1,
87 colorScheme: "system",
88 },
89 });
90 const state = useRightPanelStore.getState();
91 expect(Object.values(state.byThreadKey)[0]?.surfaces.map((surface) => surface.id)).toEqual([
92 `browser:${source.tabId}`,
93 "browser:duplicate-tab",
94 "browser:other-tab",
95 ]);
96 expect(selectActiveRightPanelSurface(state.byThreadKey, threadRef)?.id).toBe(
97 "browser:duplicate-tab",
98 );
99
100 const failed = await addBrowserSurface({
101 threadRef,
102 duplicateFrom: source,
103 openPreview: async () => AsyncResult.failure(Cause.fail(new Error("offline"))),
104 });
105 expect(failed._tag).toBe("Failure");
106 expect(useRightPanelStore.getState().byThreadKey).toBe(state.byThreadKey);
107
108 vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server");
109 const clientRendered = { ...source, runtime: undefined };
110 await addBrowserSurface({ threadRef, openPreview, duplicateFrom: clientRendered });
111 expect(openPreview).toHaveBeenLastCalledWith({
112 environmentId: threadRef.environmentId,
113 input: expect.not.objectContaining({ runtime: expect.anything() }),
114 });
115 });
116
117 it.each(["session", "link"] as const)(
118 "does not open a %s with unread settings and uses the saved profile on retry",
119 async (entryPoint) => {
120 const failure = new Error("Settings read failed");
121 vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockRejectedValueOnce(failure);
122 const viewport = { _tag: "freeform", width: 1280, height: 720 } as const;
123 __setClientSettingsForTests({
124 ...DEFAULT_CLIENT_SETTINGS,
125 browserDefaultViewport: viewport,
126 browserDefaultProfileId: "work",
127 browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
128 });
129 const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
130 const input = { openPreview, threadRef, url: "https://t3.chat/" };
131 const open = entryPoint === "session" ? openPreviewSession : openUrlInPreview;
132
133 const result = await open(input);
134
135 expect(result._tag).toBe("Failure");
136 if (result._tag === "Failure") {
137 expect(Cause.squash(result.cause)).toBeInstanceOf(BrowserSettingsReadError);
138 expect(Cause.squash(result.cause)).toMatchObject({ cause: failure });
139 }
140 expect(openPreview).not.toHaveBeenCalled();
141 expect(readThreadPreviewState(threadRef).snapshot).toBeNull();
142 expect(readThreadPreviewState(threadRef).recentlySeenUrls).toEqual([]);
143
144 await expect(open(input)).resolves.toMatchObject({ _tag: "Success" });
145 expect(openPreview).toHaveBeenCalledExactlyOnceWith({
146 environmentId: threadRef.environmentId,
147 input: {
148 threadId: threadRef.threadId,
149 url: input.url,
150 viewport,
151 profileId: "work",
152 },
153 });
154 },
155 );
156
157 it.each(["new tab", "link"] as const)(
158 "opens a server tab from a %s with the default zoom and appearance",
159 async (entryPoint) => {
160 __setClientSettingsForTests({
161 ...DEFAULT_CLIENT_SETTINGS,
162 browserDefaultZoomFactor: 0.8,
163 browserDefaultAppearance: "dark",
164 });
165 const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
166
167 if (entryPoint === "link") {
168 vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server");
169 await openUrlInPreview({ openPreview, threadRef, url: "https://t3.chat/" });
170 } else {
171 await openPreviewSession({ openPreview, threadRef, runtime: "server" });
172 }
173
174 expect(openPreview).toHaveBeenCalledExactlyOnceWith({
175 environmentId: threadRef.environmentId,
176 input: expect.objectContaining({ runtime: "server", zoomFactor: 0.8, colorScheme: "dark" }),
177 });
178 },
179 );
180});
181
182describe("openUrlInPreview from a link", () => {
183 it.each(["link", "file"] as const)(
184 "opens a side chat's %s in the parent's browser panel after the pane unmounts",
185 async (entryPoint) => {
186 const sideChatRef = { ...threadRef, threadId: "side-chat" as ScopedThreadRef["threadId"] };
187 const unhost = hostRightPanel(sideChatRef, threadRef);
188 const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
189 vi.spyOn(previewRuntime, "isPreviewAvailableFor").mockReturnValue(true);
190 vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockImplementation(async () => {
191 unhost();
192 return browserDefaults.getBrowserDefaults();
193 });
194
195 if (entryPoint === "link") {
196 await openUrlInPreview({ openPreview, threadRef: sideChatRef, url: "https://t3.chat/" });
197 } else {
198 await openFileInPreview({
199 threadRef: sideChatRef,
200 filePath: "/repo/index.html",
201 workspaceRoot: "/repo",
202 httpBaseUrl: "http://localhost:3000",
203 createAssetUrl: async () => {
204 unhost();
205 return AsyncResult.success({ relativeUrl: "/assets/index.html", expiresAt: 0 });
206 },
207 openPreview,
208 });
209 }
210
211 expect(openPreview).toHaveBeenCalledWith(
212 expect.objectContaining({
213 input: expect.objectContaining({ threadId: threadRef.threadId }),
214 }),
215 );
216 expect(readThreadPreviewState(threadRef).activeTabId).toBe(snapshot.tabId);
217 expect(readThreadPreviewState(sideChatRef).sessions).toEqual({});
218 expect(
219 selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.kind,
220 ).toBe("preview");
221 },
222 );
223
224 // regression: #16961 a background link open switched the active preview tab
225 it("keeps the current tab active for a background open", async () => {
226 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-current" });
227
228 await openUrlInPreview({
229 openPreview: async () => AsyncResult.success(snapshot),
230 threadRef,
231 url: "https://t3.chat/",
232 background: true,
233 });
234
235 const state = readThreadPreviewState(threadRef);
236 expect(state.activeTabId).toBe("tab-current");
237 expect(Object.keys(state.sessions).toSorted()).toEqual(["tab-1", "tab-current"]);
238 });
239
240 it("keeps a tab the user picked while a background open was in flight", async () => {
241 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-current" });
242 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-other" });
243 setActivePreviewTab(threadRef, "tab-current");
244
245 await openUrlInPreview({
246 openPreview: async () => {
247 applyPreviewServerSnapshot(threadRef, snapshot);
248 setActivePreviewTab(threadRef, "tab-other");
249 return AsyncResult.success(snapshot);
250 },
251 threadRef,
252 url: "https://t3.chat/",
253 background: true,
254 });
255
256 expect(readThreadPreviewState(threadRef).activeTabId).toBe("tab-other");
257 });
258});