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("duplicates a server browser with its zoom and appearance, as reopening a closed tab does", async () => {
118 const source: PreviewSessionSnapshot = {
119 ...snapshot,
120 runtime: "server",
121 zoomFactor: 1.5,
122 colorScheme: "dark",
123 };
124 useRightPanelStore.getState().openBrowser(threadRef, source.tabId);
125 const openPreview = vi.fn(async () =>
126 AsyncResult.success({ ...source, tabId: "duplicate-tab" }),
127 );
128
129 await addBrowserSurface({ threadRef, openPreview, duplicateFrom: source });
130
131 expect(openPreview).toHaveBeenCalledWith({
132 environmentId: threadRef.environmentId,
133 input: expect.objectContaining({ runtime: "server", zoomFactor: 1.5, colorScheme: "dark" }),
134 });
135 });
136
137 it.each(["session", "link"] as const)(
138 "does not open a %s with unread settings and uses the saved profile on retry",
139 async (entryPoint) => {
140 const failure = new Error("Settings read failed");
141 vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockRejectedValueOnce(failure);
142 const viewport = { _tag: "freeform", width: 1280, height: 720 } as const;
143 __setClientSettingsForTests({
144 ...DEFAULT_CLIENT_SETTINGS,
145 browserDefaultViewport: viewport,
146 browserDefaultProfileId: "work",
147 browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
148 });
149 const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
150 const input = { openPreview, threadRef, url: "https://t3.chat/" };
151 const open = entryPoint === "session" ? openPreviewSession : openUrlInPreview;
152
153 const result = await open(input);
154
155 expect(result._tag).toBe("Failure");
156 if (result._tag === "Failure") {
157 expect(Cause.squash(result.cause)).toBeInstanceOf(BrowserSettingsReadError);
158 expect(Cause.squash(result.cause)).toMatchObject({ cause: failure });
159 }
160 expect(openPreview).not.toHaveBeenCalled();
161 expect(readThreadPreviewState(threadRef).snapshot).toBeNull();
162 expect(readThreadPreviewState(threadRef).recentlySeenUrls).toEqual([]);
163
164 await expect(open(input)).resolves.toMatchObject({ _tag: "Success" });
165 expect(openPreview).toHaveBeenCalledExactlyOnceWith({
166 environmentId: threadRef.environmentId,
167 input: {
168 threadId: threadRef.threadId,
169 url: input.url,
170 viewport,
171 profileId: "work",
172 },
173 });
174 },
175 );
176
177 it.each(["new tab", "link"] as const)(
178 "opens a server tab from a %s with the default zoom and appearance",
179 async (entryPoint) => {
180 __setClientSettingsForTests({
181 ...DEFAULT_CLIENT_SETTINGS,
182 browserDefaultZoomFactor: 0.8,
183 browserDefaultAppearance: "dark",
184 });
185 const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
186
187 if (entryPoint === "link") {
188 vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server");
189 await openUrlInPreview({ openPreview, threadRef, url: "https://t3.chat/" });
190 } else {
191 await openPreviewSession({ openPreview, threadRef, runtime: "server" });
192 }
193
194 expect(openPreview).toHaveBeenCalledExactlyOnceWith({
195 environmentId: threadRef.environmentId,
196 input: expect.objectContaining({ runtime: "server", zoomFactor: 0.8, colorScheme: "dark" }),
197 });
198 },
199 );
200});
201
202describe("openUrlInPreview from a link", () => {
203 it.each(["link", "file"] as const)(
204 "opens a side chat's %s in the parent's browser panel after the pane unmounts",
205 async (entryPoint) => {
206 const sideChatRef = { ...threadRef, threadId: "side-chat" as ScopedThreadRef["threadId"] };
207 const unhost = hostRightPanel(sideChatRef, threadRef);
208 const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
209 vi.spyOn(previewRuntime, "isPreviewAvailableFor").mockReturnValue(true);
210 vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockImplementation(async () => {
211 unhost();
212 return browserDefaults.getBrowserDefaults();
213 });
214
215 if (entryPoint === "link") {
216 await openUrlInPreview({ openPreview, threadRef: sideChatRef, url: "https://t3.chat/" });
217 } else {
218 await openFileInPreview({
219 threadRef: sideChatRef,
220 filePath: "/repo/index.html",
221 workspaceRoot: "/repo",
222 httpBaseUrl: "http://localhost:3000",
223 createAssetUrl: async () => {
224 unhost();
225 return AsyncResult.success({ relativeUrl: "/assets/index.html", expiresAt: 0 });
226 },
227 openPreview,
228 });
229 }
230
231 expect(openPreview).toHaveBeenCalledWith(
232 expect.objectContaining({
233 input: expect.objectContaining({ threadId: threadRef.threadId }),
234 }),
235 );
236 expect(readThreadPreviewState(threadRef).activeTabId).toBe(snapshot.tabId);
237 expect(readThreadPreviewState(sideChatRef).sessions).toEqual({});
238 expect(
239 selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.kind,
240 ).toBe("preview");
241 },
242 );
243
244 // regression: #16961 a background link open switched the active preview tab
245 it("keeps the current tab active for a background open", async () => {
246 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-current" });
247
248 await openUrlInPreview({
249 openPreview: async () => AsyncResult.success(snapshot),
250 threadRef,
251 url: "https://t3.chat/",
252 background: true,
253 });
254
255 const state = readThreadPreviewState(threadRef);
256 expect(state.activeTabId).toBe("tab-current");
257 expect(Object.keys(state.sessions).toSorted()).toEqual(["tab-1", "tab-current"]);
258 });
259
260 it("keeps a tab the user picked while a background open was in flight", async () => {
261 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-current" });
262 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-other" });
263 setActivePreviewTab(threadRef, "tab-current");
264
265 await openUrlInPreview({
266 openPreview: async () => {
267 applyPreviewServerSnapshot(threadRef, snapshot);
268 setActivePreviewTab(threadRef, "tab-other");
269 return AsyncResult.success(snapshot);
270 },
271 threadRef,
272 url: "https://t3.chat/",
273 background: true,
274 });
275
276 expect(readThreadPreviewState(threadRef).activeTabId).toBe("tab-other");
277 });
278});