The best way to control Claude Code, Codex and more from any computer or phone
fix(server): Browser tab titles follow page title changes (#36764)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 14, 2026 at 15:19 UTC
313f601fb2366fad7dd26b7b55844c7c5d750cf0
3 files changed
+318
-61
apps/server/src/preview/ServerBrowser.test.ts
+169
-47
@@ -32,7 +32,7 @@ import * as PubSub from "effect/PubSub";
32
import * as Queue from "effect/Queue";
33
import * as Stream from "effect/Stream";
34
import * as TestClock from "effect/testing/TestClock";
35
-import type { BrowserContext, Page } from "playwright-core";
35
+import { chromium, type BrowserContext, type Page } from "playwright-core";
36
import { beforeEach, expect, vi } from "vite-plus/test";
37
38
import * as ServerConfig from "../config.ts";
@@ -52,6 +52,7 @@ vi.mock("./ServerBrowserContexts.ts", () => ({
52
this.onClose = options.onContextClose;
53
}
54
async contextFor(profileId: string, isolationKey?: string) {
55
+ if (realContextOverride) return realContextOverride;
56
contextRequests.push({ profileId, isolated: isolationKey !== undefined });
57
if (contextFailure) throw contextFailure;
58
await contextGate?.promise;
@@ -122,15 +123,18 @@ function makeSession(
123
if (method === "Runtime.callFunctionOn") return { result: { value: PNG_HEADER } };
124
if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
125
if (method === "Page.createIsolatedWorld") {
126
+ const worldContexts: Record<string, number> = {
127
+ "t3-preview-viewport": 9,
128
+ "t3-preview-title": 11,
129
+ "t3-preview": 1,
130
+ };
131
return {
126
- executionContextId:
127
- (input as { worldName?: string }).worldName === "t3-preview-viewport"
128
- ? 9
129
- : (input as { worldName?: string }).worldName === "t3-preview"
130
- ? 1
131
- : 7,
132
+ executionContextId: worldContexts[(input as { worldName: string }).worldName] ?? 7,
133
};
134
}
135
+ // A title watch settles only when the document's title changes.
136
+ if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 11)
137
+ return new Promise(() => {});
138
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 1) {
139
return { result: { value: [] } };
140
}
@@ -383,6 +387,7 @@ function makeEncoderPage() {
387
388
const contexts: ReturnType<typeof makeContext>[] = [];
389
let encoderPageOverride: Page | undefined;
390
+let realContextOverride: BrowserContext | undefined;
391
const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = [];
392
let decodeGate: PromiseWithResolvers<void> | null = null;
393
const contextRequests: Array<{ profileId: string; isolated: boolean }> = [];
@@ -569,6 +574,7 @@ const openDesktopViewer = Effect.gen(function* () {
574
beforeEach(() => {
575
contexts.length = 0;
576
encoderPageOverride = undefined;
577
+ realContextOverride = undefined;
578
encoderStreams.length = 0;
579
decodeGate = null;
580
contextRequests.length = 0;
@@ -2018,47 +2024,50 @@ it.effect(
2024
).pipe(Effect.provide(layer)),
2025
);
2026
2021
-it.effect("a navigation that fails while a load reads its title keeps its failure", () =>
2022
- Effect.scoped(
2023
- Effect.gen(function* () {
2024
- const { tabId } = yield* ready;
2025
- const manager = yield* Manager.PreviewManager;
2026
- const events = yield* manager.subscribeEvents;
2027
- const page = contexts[0]!.page;
2028
- const heldTitle = Promise.withResolvers<string>();
2029
- page.title.mockImplementationOnce(() => heldTitle.promise);
2030
- yield* Effect.promise(() => page.goto("https://example.com/first"));
2031
- const failing = {
2032
- url: () => "https://example.com/missing",
2033
- method: () => "GET",
2034
- isNavigationRequest: () => true,
2035
- frame: () => page,
2036
- failure: () => ({ errorText: "net::ERR_NAME_NOT_RESOLVED" }),
2037
- };
2038
- page.emit("request", failing);
2039
- page.emit("requestfailed", failing);
2040
- heldTitle.resolve("Held");
2041
- // A load at the same await depth reports after the held one, so its Success marks the end.
2042
- page.emit("load");
2043
-
2044
- const statuses: Array<string> = [];
2045
- while (!statuses.at(-1)?.startsWith("Success")) {
2046
- const event = yield* PubSub.take(events);
2047
- if (event.type === "failed" && event.tabId === tabId) {
2048
- statuses.push(`LoadFailed ${event.url}`);
2049
- } else if (event.type === "navigated" && event.tabId === tabId) {
2050
- const status = event.snapshot.navStatus;
2051
- if (status._tag === "Success") statuses.push(`Success ${status.title}`);
2052
- else if (status._tag === "Loading") statuses.push(`Loading ${status.url}`);
2027
+it.effect.each(["before", "during"] as const)(
2028
+ "a navigation that fails while a load reads its title keeps its failure (request %s read)",
2029
+ (requestTiming) =>
2030
+ Effect.scoped(
2031
+ Effect.gen(function* () {
2032
+ const { tabId } = yield* ready;
2033
+ const manager = yield* Manager.PreviewManager;
2034
+ const events = yield* manager.subscribeEvents;
2035
+ const page = contexts[0]!.page;
2036
+ const heldTitle = Promise.withResolvers<string>();
2037
+ page.title.mockImplementationOnce(() => heldTitle.promise);
2038
+ const failing = {
2039
+ url: () => "https://example.com/missing",
2040
+ method: () => "GET",
2041
+ isNavigationRequest: () => true,
2042
+ frame: () => page,
2043
+ failure: () => ({ errorText: "net::ERR_NAME_NOT_RESOLVED" }),
2044
+ };
2045
+ if (requestTiming === "before") page.emit("request", failing);
2046
+ yield* Effect.promise(() => page.goto("https://example.com/first"));
2047
+ if (requestTiming === "during") page.emit("request", failing);
2048
+ page.emit("requestfailed", failing);
2049
+ heldTitle.resolve("Held");
2050
+ // A load at the same await depth reports after the held one, so its Success marks the end.
2051
+ page.emit("load");
2052
+
2053
+ const statuses: Array<string> = [];
2054
+ while (!statuses.at(-1)?.startsWith("Success")) {
2055
+ const event = yield* PubSub.take(events);
2056
+ if (event.type === "failed" && event.tabId === tabId) {
2057
+ statuses.push(`LoadFailed ${event.url}`);
2058
+ } else if (event.type === "navigated" && event.tabId === tabId) {
2059
+ const status = event.snapshot.navStatus;
2060
+ if (status._tag === "Success") statuses.push(`Success ${status.title}`);
2061
+ else if (status._tag === "Loading") statuses.push(`Loading ${status.url}`);
2062
+ }
2063
}
2054
- }
2055
- expect(statuses).toEqual([
2056
- "Loading https://example.com/missing",
2057
- "LoadFailed https://example.com/missing",
2058
- "Success test page",
2059
- ]);
2060
- }),
2061
- ).pipe(Effect.provide(layer)),
2064
+ expect(statuses).toEqual([
2065
+ "Loading https://example.com/missing",
2066
+ "LoadFailed https://example.com/missing",
2067
+ "Success test page",
2068
+ ]);
2069
+ }),
2070
+ ).pipe(Effect.provide(layer)),
2071
);
2072
2073
it.effect.each([
@@ -3965,3 +3974,116 @@ it.effect("a popup opens in its opener's appearance", () =>
3974
}),
3975
).pipe(Effect.provide(layer)),
3976
);
3977
+
3978
+it.live("a page's title change without navigation reaches its session", () =>
3979
+ Effect.gen(function* () {
3980
+ const native = yield* Effect.acquireRelease(
3981
+ Effect.promise(() => chromium.launch({ headless: true })),
3982
+ (browser) => Effect.promise(() => browser.close()),
3983
+ );
3984
+ const context = yield* Effect.promise(() => native.newContext());
3985
+ yield* Effect.promise(() =>
3986
+ context.route("**/*", (route) =>
3987
+ route.fulfill({ contentType: "text/html", body: "<title>Original</title>" }),
3988
+ ),
3989
+ );
3990
+ let watched = Promise.withResolvers<void>();
3991
+ const newSession = context.newCDPSession.bind(context);
3992
+ vi.spyOn(context, "newCDPSession").mockImplementation(async (page) => {
3993
+ const cdp = await newSession(page);
3994
+ const send = cdp.send.bind(cdp);
3995
+ vi.spyOn(cdp, "send").mockImplementation((...args) => {
3996
+ const result = send(...args);
3997
+ if (
3998
+ args[0] === "Runtime.evaluate" &&
3999
+ args[1] &&
4000
+ "awaitPromise" in args[1] &&
4001
+ args[1].awaitPromise
4002
+ ) {
4003
+ void send("Runtime.evaluate", { expression: "0" }).then(() => {
4004
+ watched.resolve();
4005
+ });
4006
+ }
4007
+ return result;
4008
+ });
4009
+ return cdp;
4010
+ });
4011
+ realContextOverride = context;
4012
+ yield* Effect.gen(function* () {
4013
+ yield* ServerBrowser.ServerBrowser;
4014
+ const manager = yield* Manager.PreviewManager;
4015
+ const events = yield* manager.subscribeEvents;
4016
+ yield* manager.open({
4017
+ threadId: testThread.threadId,
4018
+ runtime: "server",
4019
+ url: "https://fixture.test/",
4020
+ });
4021
+ const successes: Array<{ title: string; url: string; back: boolean; forward: boolean }> = [];
4022
+ const navigatedTo = Effect.fn(function* (title: string) {
4023
+ for (;;) {
4024
+ const event = yield* PubSub.take(events);
4025
+ if (event.type !== "navigated") continue;
4026
+ const { navStatus } = event.snapshot;
4027
+ if (navStatus._tag === "Success") {
4028
+ successes.push({
4029
+ title: navStatus.title,
4030
+ url: navStatus.url,
4031
+ back: event.snapshot.canGoBack,
4032
+ forward: event.snapshot.canGoForward,
4033
+ });
4034
+ if (navStatus.title === title) return navStatus;
4035
+ }
4036
+ }
4037
+ });
4038
+ expect((yield* navigatedTo("Original"))._tag).toBe("Success");
4039
+ const page = context.pages()[0]!;
4040
+ yield* Effect.promise(() => watched.promise);
4041
+ watched = Promise.withResolvers<void>();
4042
+ yield* Effect.promise(() =>
4043
+ page.evaluate("document.head.replaceWith(document.head.cloneNode(true))"),
4044
+ );
4045
+ for (const title of ["Replaced", "Updated", "Final"]) {
4046
+ if (title === "Final")
4047
+ yield* Effect.promise(() =>
4048
+ page.evaluate(
4049
+ "document.documentElement.replaceWith(document.documentElement.cloneNode(true))",
4050
+ ),
4051
+ );
4052
+ yield* Effect.promise(() =>
4053
+ page.evaluate(
4054
+ `document.title = ${JSON.stringify(title)}; ${title === "Updated" ? "history.pushState({}, '', '/next')" : ""}`,
4055
+ ),
4056
+ );
4057
+ expect(yield* navigatedTo(title)).toEqual({
4058
+ _tag: "Success",
4059
+ url: title === "Replaced" ? "https://fixture.test/" : "https://fixture.test/next",
4060
+ title,
4061
+ });
4062
+ yield* Effect.promise(() => watched.promise);
4063
+ watched = Promise.withResolvers<void>();
4064
+ }
4065
+ expect(successes.filter(({ title }) => title === "Updated")).toEqual([
4066
+ { title: "Updated", url: "https://fixture.test/next", back: true, forward: false },
4067
+ ]);
4068
+ yield* Effect.promise(() =>
4069
+ context.route("**/drawing.svg", (route) =>
4070
+ route.fulfill({
4071
+ contentType: "image/svg+xml",
4072
+ body: '<svg xmlns="http://www.w3.org/2000/svg"><title>Drawing</title></svg>',
4073
+ }),
4074
+ ),
4075
+ );
4076
+ yield* Effect.promise(() => page.goto("https://fixture.test/drawing.svg"));
4077
+ yield* navigatedTo("Drawing");
4078
+ yield* Effect.promise(() => watched.promise);
4079
+ yield* Effect.promise(() =>
4080
+ page.evaluate("document.querySelector('title').textContent = 'Renamed drawing'"),
4081
+ );
4082
+ expect(yield* navigatedTo("Renamed drawing")).toEqual({
4083
+ _tag: "Success",
4084
+ url: "https://fixture.test/drawing.svg",
4085
+ title: "Renamed drawing",
4086
+ });
4087
+ }).pipe(Effect.provide(layer));
4088
+ }).pipe(Effect.scoped),
4089
+);
apps/server/src/preview/ServerBrowser.ts
+102
-14
@@ -13,6 +13,7 @@ import {
13
isBuiltInBrowserProfileId,
14
resolveBrowserProfiles,
15
type PreviewReportProfilesInput,
16
+ type PreviewReportStatusInput,
17
PREVIEW_AUTOMATION_SERVER_OPERATIONS,
18
PreviewViewportSetting as PreviewViewportSettingSchema,
19
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
@@ -55,6 +56,7 @@ import { resolvePreviewViewport } from "@t3tools/shared/previewViewport";
56
import * as NodeCrypto from "node:crypto";
57
import * as NodeFSP from "node:fs/promises";
58
import * as NodePath from "node:path";
59
+import * as NodeUtil from "node:util";
60
import * as Context from "effect/Context";
61
import * as Effect from "effect/Effect";
62
import * as FileSystem from "effect/FileSystem";
@@ -387,6 +389,9 @@ interface ServerTab {
389
pendingInitialRequestUrl: string | null;
390
navigationGeneration: number;
391
stoppedGeneration: number | null;
392
+ /** The reported title a watch in the main document's isolated world waits to change from. */
393
+ titleWatch: { readonly contextId: number; readonly title: string } | null;
394
+ lastReport: PreviewReportStatusInput | null;
395
396
abortedNavigation: {
397
readonly url: string;
@@ -477,6 +482,41 @@ const editingCommand = (key: string, modifiers: number) => {
482
return command ? { commands: [command] } : null;
483
};
484
485
+const TITLE_LIMIT = 512;
486
+const TITLE_WORLD = "t3-preview-title";
487
+// Observe root replacement without subscribing to body subtree mutations.
488
+const titleChange = (reported: string) => `new Promise((resolve) => {
489
+ const changed = () => document.title.slice(0, ${TITLE_LIMIT}) !== ${JSON.stringify(reported)};
490
+ if (changed()) return resolve();
491
+ let head;
492
+ let root;
493
+ let title;
494
+ const observer = new MutationObserver(() => {
495
+ if (changed()) {
496
+ observer.disconnect();
497
+ resolve();
498
+ } else if (head !== document.head || root !== document.documentElement || title !== document.querySelector('title')) {
499
+ observe();
500
+ }
501
+ });
502
+ const observe = () => {
503
+ observer.disconnect();
504
+ observer.observe(document, { childList: true });
505
+ root = document.documentElement;
506
+ head = document.head;
507
+ title = document.querySelector('title');
508
+ if (root) observer.observe(root, { childList: true });
509
+ if (head) observer.observe(head, { subtree: true, childList: true, characterData: true });
510
+ if (title && !head?.contains(title)) {
511
+ observer.observe(title, { subtree: true, childList: true, characterData: true });
512
+ for (let ancestor = title.parentElement; ancestor; ancestor = ancestor.parentElement) {
513
+ observer.observe(ancestor, { childList: true });
514
+ }
515
+ }
516
+ };
517
+ observe();
518
+})`;
519
+
520
const CLIPBOARD_TEXT_LIMIT = 1024 * 1024;
521
const CLIPBOARD_WORLD = "t3-preview-clipboard";
522
// Chromium shares its clipboard across contexts; capture real copy/cut keys in a page-inaccessible world instead.
@@ -683,26 +723,32 @@ const make = Effect.gen(function* () {
723
};
724
725
const report = (tab: ServerTab, navStatus: PreviewNavStatus) => {
726
+ const generation = tab.navigationGeneration;
727
+ const loadError = tab.loadError;
728
void tab.cdp
729
.send("Page.getNavigationHistory")
730
.catch(() => null)
731
.then((history) => {
732
// A status the dead page still had in flight must not replace the crash.
733
if (tab.crash) return;
734
+ if (
735
+ navStatus._tag === "Success" &&
736
+ (tab.navigationGeneration !== generation || tab.loadError !== loadError)
737
+ )
738
+ return;
739
const index = history?.currentIndex ?? 0;
740
const count = history?.entries.length ?? 0;
694
- runFork(
695
- manager
696
- .reportStatus({
697
- threadId: tab.threadId,
698
- tabId: tab.tabId,
699
- serverControlled: true,
700
- navStatus,
701
- canGoBack: index > 0,
702
- canGoForward: index < count - 1,
703
- })
704
- .pipe(Effect.ignore),
705
- );
741
+ const input = {
742
+ threadId: tab.threadId,
743
+ tabId: tab.tabId,
744
+ serverControlled: true,
745
+ navStatus,
746
+ canGoBack: index > 0,
747
+ canGoForward: index < count - 1,
748
+ };
749
+ if (NodeUtil.isDeepStrictEqual(tab.lastReport, input)) return;
750
+ tab.lastReport = input;
751
+ runFork(manager.reportStatus(input).pipe(Effect.ignore));
752
});
753
};
754
@@ -712,13 +758,53 @@ const make = Effect.gen(function* () {
758
if (url === "about:blank" || url.startsWith("chrome-error://")) return;
759
// A navigation that starts and fails during the title read leaves the URL unchanged.
760
const generation = tab.navigationGeneration;
715
- const title = (await tab.page.title().catch(() => "")).slice(0, 512);
716
- if (tab.navigationGeneration !== generation || tab.loading || tab.page.url() !== url) return;
761
+ const loadError = tab.loadError;
762
+ const title = (await tab.page.title().catch(() => "")).slice(0, TITLE_LIMIT);
763
+ if (
764
+ tab.navigationGeneration !== generation ||
765
+ tab.loadError !== loadError ||
766
+ tab.loading ||
767
+ tab.page.url() !== url
768
+ )
769
+ return;
770
report(tab, {
771
_tag: "Success",
772
url: ServerBrowserPage.withoutDataPayload(url).slice(0, 2048),
773
title,
774
});
775
+ void watchTitle(tab, title);
776
+ };
777
+
778
+ // A title change fires no page event, so one watch per document reports the next one.
779
+ const watchTitle = async (tab: ServerTab, title: string) => {
780
+ // Chromium keeps one world per name and document, so a new document gets a new context.
781
+ const world = await tab.cdp
782
+ .send("Page.getFrameTree")
783
+ .then(({ frameTree }) =>
784
+ tab.cdp.send("Page.createIsolatedWorld", {
785
+ frameId: frameTree.frame.id,
786
+ worldName: TITLE_WORLD,
787
+ }),
788
+ )
789
+ .catch(() => null);
790
+ if (!world) return;
791
+ const watch = { contextId: world.executionContextId, title };
792
+ if (tab.titleWatch?.contextId === watch.contextId && tab.titleWatch.title === title) return;
793
+ tab.titleWatch = watch;
794
+ const changed = await tab.cdp
795
+ .send("Runtime.evaluate", {
796
+ contextId: watch.contextId,
797
+ expression: titleChange(title),
798
+ awaitPromise: true,
799
+ })
800
+ .then(
801
+ ({ exceptionDetails }) => exceptionDetails === undefined,
802
+ () => false,
803
+ );
804
+ if (tab.titleWatch !== watch) return;
805
+ tab.titleWatch = null;
806
+ // A dropped tab's page can still change its title while it unloads.
807
+ if (changed && !tab.closing && !tab.loadError) await reportLoaded(tab);
808
};
809
810
const reportLiveTabs = () => {
@@ -1083,6 +1169,8 @@ const make = Effect.gen(function* () {
1169
pendingInitialRequestUrl: null,
1170
navigationGeneration: 0,
1171
stoppedGeneration: null,
1172
+ titleWatch: null,
1173
+ lastReport: null,
1174
abortedNavigation: null,
1175
captureLock: Promise.resolve(),
1176
capturing: 0,
scripts/scenarios/browser-tab-follows-page-title.e2e.ts
new
+47
@@ -0,0 +1,47 @@
1
+// @effect-diagnostics-next-line nodeBuiltinImport:off - one fixture page for the server's browser to load
2
+import * as NodeHttp from "node:http";
3
+
4
+import { expect } from "e2e";
5
+
6
+import { test, WEB } from "./t3.ts";
7
+
8
+// A page that renames itself on a click, with no navigation.
9
+const PAGE = `<!doctype html>
10
+<title>Original title</title>
11
+<body style="margin:0;height:100vh" onpointerdown="document.title = 'Updated title'">
12
+ Click to rename
13
+</body>`;
14
+
15
+test(
16
+ "A Browser tab's label follows a title change that makes no navigation",
17
+ WEB,
18
+ async ({ t3, app, browser, screen }) => {
19
+ const server = NodeHttp.createServer((_request, response) => {
20
+ response.writeHead(200, { "content-type": "text/html" });
21
+ response.end(PAGE);
22
+ });
23
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
24
+ try {
25
+ const address = server.address();
26
+ if (address === null || typeof address === "string") throw new Error("No page port.");
27
+ const project = await t3.project("demo");
28
+ const thread = await t3.thread({ project, title: "Rename check", messages: ["first"] });
29
+ await t3.open(thread);
30
+
31
+ await screen.getByRole("button", "Toggle right panel").tap();
32
+ await screen.getByRole("button", "Browser B").tap();
33
+ await screen
34
+ .getByRole("textbox", "Search or enter URL")
35
+ .fill(`http://127.0.0.1:${address.port}/`);
36
+ await browser.keyboard.press("Enter");
37
+ await expect(screen.getByText("Original title")).toBeVisible();
38
+
39
+ // The page draws on the canvas beside its input proxy.
40
+ await browser.locator('canvas:has(~ textarea[aria-label="Browser page"])').tap();
41
+ await expect(screen.getByText("Updated title")).toBeVisible();
42
+ await app.screenshot("after-title-change");
43
+ } finally {
44
+ await new Promise((resolve) => server.close(resolve));
45
+ }
46
+ },
47
+);