Skip to content

Commit 859cc41

Browse files
fix(preview): keep desktop status available during dialogs
1 parent 41c4beb commit 859cc41

3 files changed

Lines changed: 150 additions & 92 deletions

File tree

‎apps/server/src/mcp/toolkits/preview/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ const PreviewNavigateTool = safeBrowserTool(
109109
const PreviewResizeTool = safeBrowserTool(
110110
Tool.make("preview_resize", {
111111
description:
112-
"Resize a collaborative browser tab, optionally selected by tabId. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
112+
"Resize a collaborative browser tab, optionally selected by tabId. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent. The returned viewport is measured at response time. Desktop sizing applies asynchronously; confirmed:false means the requested fixed size was not observed yet, which can reflect pending application or a size that could not be applied. Call preview_status to recheck the measured viewport rather than repeating resize.",
113113
parameters: PreviewAutomationResizeInput,
114114
success: Schema.Struct({ ...PreviewAutomationResizeResult.fields, ...presentationFields }),
115115
failure: PreviewToolFailure,

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 144 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import * as Path from "effect/Path";
2323
import * as PubSub from "effect/PubSub";
2424
import * as Queue from "effect/Queue";
2525
import * as Stream from "effect/Stream";
26+
import * as TestClock from "effect/testing/TestClock";
2627
import type { BrowserContext, Page } from "playwright-core";
2728
import { beforeEach, expect, vi } from "vite-plus/test";
2829

@@ -448,42 +449,77 @@ it.effect("desktop resize reports unconfirmed until the UI applies the requested
448449
input: resizeCases[1]!.input,
449450
});
450451
expect(resized).toMatchObject({ viewport: { width: 1280, height: 800 }, confirmed: false });
451-
const applied = yield* broker.invoke<PreviewAutomationResizeResult>({
452+
const applied = yield* broker.invoke<PreviewAutomationStatus>({
452453
scope,
453454
tabId,
454-
operation: "resize",
455-
input: resizeCases[1]!.input,
455+
operation: "status",
456+
input: {},
456457
});
457-
expect(applied).toMatchObject({ viewport: { width: 560, height: 760 }, confirmed: true });
458+
expect(applied).toMatchObject({ viewport: { width: 560, height: 760 } });
458459
}),
459460
).pipe(Effect.provide(layer)),
460461
);
461462

462-
it.effect("desktop resize fails when the CDP measurement receipt is missing", () =>
463+
it.effect("desktop status omits the viewport when live measurement is unavailable", () =>
463464
Effect.scoped(
464465
Effect.gen(function* () {
465466
desktopRendersNext = true;
466467
const { broker, tabId } = yield* ready;
467468
desktopConnections[0]!.context.readMetrics.mockRejectedValue(
468-
new Error("CDP measurement unavailable"),
469+
new Error("Execution context was destroyed"),
470+
);
471+
const status = yield* broker.invoke<PreviewAutomationStatus>({
472+
scope,
473+
tabId,
474+
operation: "status",
475+
input: {},
476+
});
477+
expect(status).toMatchObject({
478+
available: true,
479+
tabId,
480+
viewportSetting: { _tag: "fill" },
481+
dialog: null,
482+
});
483+
expect(status).not.toHaveProperty("viewport");
484+
}),
485+
).pipe(Effect.provide(layer)),
486+
);
487+
488+
it.effect("desktop resize times out when the CDP measurement never responds", () =>
489+
Effect.scoped(
490+
Effect.gen(function* () {
491+
desktopRendersNext = true;
492+
const { broker, tabId } = yield* ready;
493+
const started = Promise.withResolvers<void>();
494+
const measurement = Promise.withResolvers<{ ratio: number; width: number; height: number }>();
495+
yield* Effect.addFinalizer(() =>
496+
Effect.sync(() => measurement.reject(new Error("Test measurement cancelled"))),
469497
);
470-
const result = yield* broker
471-
.invoke({
498+
desktopConnections[0]!.context.readMetrics.mockImplementation(async () => {
499+
started.resolve();
500+
return measurement.promise;
501+
});
502+
const resizing = yield* broker
503+
.invoke<PreviewAutomationResizeResult>({
472504
scope,
473505
tabId,
474506
operation: "resize",
475507
input: resizeCases[0]!.input,
508+
timeoutMs: 100,
476509
})
477-
.pipe(Effect.result);
478-
expect(result).toMatchObject({
510+
.pipe(Effect.result, Effect.forkScoped);
511+
yield* Effect.promise(() => started.promise);
512+
expect(resizing.pollUnsafe()).toBeUndefined();
513+
yield* TestClock.adjust(1_100);
514+
expect(yield* Fiber.join(resizing)).toMatchObject({
479515
_tag: "Failure",
480-
failure: { _tag: "PreviewAutomationExecutionError" },
516+
failure: { _tag: "PreviewAutomationTimeoutError", operation: "resize" },
481517
});
482518
}),
483519
).pipe(Effect.provide(layer)),
484520
);
485521

486-
it.effect.each(["delayed", "missing"] as const)(
522+
it.effect.each(["delayed", "rejected"] as const)(
487523
"desktop resize waits for a $0 CDP measurement receipt",
488524
(receipt) =>
489525
Effect.scoped(
@@ -517,10 +553,10 @@ it.effect.each(["delayed", "missing"] as const)(
517553
);
518554
expect(first).toBe("measurement");
519555
expect(resizing.pollUnsafe()).toBeUndefined();
520-
if (receipt === "missing") measurement.reject(new Error("CDP measurement unavailable"));
556+
if (receipt === "rejected") measurement.reject(new Error("CDP measurement unavailable"));
521557
else measurement.resolve(measured);
522558
const result = yield* Fiber.join(resizing);
523-
if (receipt === "missing") {
559+
if (receipt === "rejected") {
524560
expect(result).toMatchObject({
525561
_tag: "Failure",
526562
failure: { _tag: "PreviewAutomationExecutionError" },
@@ -861,83 +897,104 @@ it.live(
861897
).pipe(Effect.provide(layer)),
862898
);
863899

864-
it.live("reports a pending dialog without evaluating the page and resolves it explicitly", () =>
865-
Effect.scoped(
866-
Effect.gen(function* () {
867-
const { broker, tabId } = yield* ready;
868-
const page = contexts[0]!.page;
869-
yield* broker.invoke({
870-
scope,
871-
tabId,
872-
operation: "navigate",
873-
input: { url: "http://localhost:5173" },
874-
});
875-
const started = Promise.withResolvers<void>();
876-
const resolvedEvaluation = Promise.withResolvers<Record<string, unknown>>();
877-
const session = contexts[0]!.sessions[0]!;
878-
const send = session.send.getMockImplementation()!;
879-
session.send.mockImplementation(async (method, input) => {
880-
if (method !== "Runtime.evaluate") return send(method, input);
881-
started.resolve();
882-
return resolvedEvaluation.promise;
883-
});
884-
const blockedAction = yield* broker
885-
.invoke({
900+
it.live.each(["headless", "desktop"])(
901+
"$0 reports a pending dialog without evaluating the page and resolves it explicitly",
902+
(runtime) =>
903+
Effect.scoped(
904+
Effect.gen(function* () {
905+
desktopRendersNext = runtime === "desktop";
906+
const { broker, tabId } = yield* ready;
907+
const context = runtime === "desktop" ? desktopConnections[0]!.context : contexts[0]!;
908+
const page = context.page;
909+
yield* broker.invoke({
886910
scope,
887911
tabId,
888-
operation: "evaluate",
889-
input: { expression: 'confirm("Delete row?")' },
890-
})
891-
.pipe(Effect.forkScoped);
892-
yield* Effect.addFinalizer(() =>
893-
Effect.sync(() => resolvedEvaluation.resolve({ result: { value: true } })),
894-
);
895-
yield* Effect.promise(() => started.promise);
896-
const dialog = {
897-
type: () => "confirm",
898-
message: () => "Delete row?",
899-
defaultValue: () => "",
900-
accept: vi.fn(async () => {
901-
resolvedEvaluation.resolve({ result: { value: true } });
902-
}),
903-
dismiss: vi.fn(async () => {}),
904-
};
905-
page.emit("dialog", dialog);
906-
page.title.mockClear();
907-
const status = yield* broker.invoke<PreviewAutomationStatus>({
908-
scope,
909-
tabId,
910-
operation: "status",
911-
input: {},
912-
});
913-
expect(status.dialog).toMatchObject({ type: "confirm", message: "Delete row?" });
914-
expect(page.title).not.toHaveBeenCalled();
915-
expect(dialog.dismiss).not.toHaveBeenCalled();
916-
const reuse = yield* broker
917-
.invoke<void>({
912+
operation: "navigate",
913+
input: { url: "http://localhost:5173" },
914+
});
915+
const started = Promise.withResolvers<void>();
916+
const resolvedEvaluation = Promise.withResolvers<Record<string, unknown>>();
917+
const session = context.sessions[0]!;
918+
let dialogPending = false;
919+
const send = session.send.getMockImplementation()!;
920+
session.send.mockImplementation(async (method, input) => {
921+
if (method !== "Runtime.evaluate") return send(method, input);
922+
if ((input as { contextId?: number }).contextId === 8) {
923+
if (dialogPending) throw new Error("Metrics evaluation blocks behind the dialog");
924+
return send(method, input);
925+
}
926+
started.resolve();
927+
return resolvedEvaluation.promise;
928+
});
929+
const blockedAction = yield* broker
930+
.invoke({
931+
scope,
932+
tabId,
933+
operation: "evaluate",
934+
input: { expression: 'confirm("Delete row?")' },
935+
})
936+
.pipe(Effect.forkScoped);
937+
yield* Effect.addFinalizer(() =>
938+
Effect.sync(() => resolvedEvaluation.resolve({ result: { value: true } })),
939+
);
940+
yield* Effect.promise(() => started.promise);
941+
const dialog = {
942+
type: () => "confirm",
943+
message: () => "Delete row?",
944+
defaultValue: () => "",
945+
accept: vi.fn(async () => {
946+
dialogPending = false;
947+
resolvedEvaluation.resolve({ result: { value: true } });
948+
}),
949+
dismiss: vi.fn(async () => {}),
950+
};
951+
dialogPending = true;
952+
page.emit("dialog", dialog);
953+
page.title.mockClear();
954+
context.readMetrics.mockClear();
955+
session.send.mockClear();
956+
const status = yield* broker.invoke<PreviewAutomationStatus>({
918957
scope,
919958
tabId,
920-
operation: "open",
921-
input: { url: "http://localhost:5173/other" },
922-
})
923-
.pipe(Effect.flip);
924-
expect(reuse).toMatchObject({
925-
_tag: "PreviewAutomationControlInterruptedError",
926-
reason: "dialogPending",
927-
});
928-
expect(page.goto).toHaveBeenCalledTimes(1);
929-
yield* broker.invoke({ scope, tabId, operation: "dialog", input: { accept: true } });
930-
expect(yield* Fiber.join(blockedAction)).toBe(true);
931-
expect(dialog.accept).toHaveBeenCalledTimes(1);
932-
const resolved = yield* broker.invoke<PreviewAutomationStatus>({
933-
scope,
934-
tabId,
935-
operation: "status",
936-
input: {},
937-
});
938-
expect(resolved.dialog).toBeNull();
939-
}),
940-
).pipe(Effect.provide(layer)),
959+
operation: "status",
960+
input: {},
961+
});
962+
expect(status.dialog).toMatchObject({ type: "confirm", message: "Delete row?" });
963+
expect(page.title).not.toHaveBeenCalled();
964+
expect(context.readMetrics).not.toHaveBeenCalled();
965+
expect(session.send).not.toHaveBeenCalledWith(
966+
"Runtime.evaluate",
967+
expect.objectContaining({ contextId: 8 }),
968+
);
969+
if (runtime === "desktop") expect(status).not.toHaveProperty("viewport");
970+
else expect(status.viewport).toEqual({ width: 1280, height: 800 });
971+
expect(dialog.dismiss).not.toHaveBeenCalled();
972+
const reuse = yield* broker
973+
.invoke<void>({
974+
scope,
975+
tabId,
976+
operation: "open",
977+
input: { url: "http://localhost:5173/other" },
978+
})
979+
.pipe(Effect.flip);
980+
expect(reuse).toMatchObject({
981+
_tag: "PreviewAutomationControlInterruptedError",
982+
reason: "dialogPending",
983+
});
984+
expect(page.goto).toHaveBeenCalledTimes(1);
985+
yield* broker.invoke({ scope, tabId, operation: "dialog", input: { accept: true } });
986+
expect(yield* Fiber.join(blockedAction)).toBe(true);
987+
expect(dialog.accept).toHaveBeenCalledTimes(1);
988+
const resolved = yield* broker.invoke<PreviewAutomationStatus>({
989+
scope,
990+
tabId,
991+
operation: "status",
992+
input: {},
993+
});
994+
expect(resolved.dialog).toBeNull();
995+
expect(resolved.viewport).toEqual({ width: 1280, height: 800 });
996+
}),
997+
).pipe(Effect.provide(layer)),
941998
);
942999

9431000
it.live("a tab opened to a file the browser cannot show reports the file to download", () =>

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1369,10 +1369,11 @@ const make = Effect.gen(function* () {
13691369
}
13701370
const url = tab.page.url();
13711371
const viewport = tab.desktop
1372-
? await ServerBrowserPage.readPageMetrics(tab.cdp).then(({ width, height }) => ({
1373-
width,
1374-
height,
1375-
}))
1372+
? tab.dialog
1373+
? null
1374+
: await ServerBrowserPage.readPageMetrics(tab.cdp)
1375+
.then(({ width, height }) => ({ width, height }))
1376+
.catch(() => null)
13761377
: tab.page.viewportSize();
13771378
const status = {
13781379
available: true,

0 commit comments

Comments
 (0)