Skip to content

Commit 10f3657

Browse files
fix(server): preview click timeouts identify the target (pingdotgg#23489)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent fd63914 commit 10f3657

5 files changed

Lines changed: 128 additions & 3 deletions

File tree

‎apps/server/src/mcp/PreviewAutomationBroker.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,43 @@ it.effect.each([
335335
),
336336
);
337337

338+
it.effect("names the click target that matched nothing when the server browser times out", () =>
339+
Effect.scoped(
340+
Effect.gen(function* () {
341+
const broker = yield* makeBroker;
342+
const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
343+
const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
344+
yield* Stream.runForEach(requests, (request) =>
345+
broker.respond({
346+
clientId,
347+
connectionId: request.connectionId,
348+
requestId: request.requestId,
349+
ok: false,
350+
error: {
351+
_tag: "PreviewAutomationTimeoutError",
352+
message: "No element matches the target.",
353+
detail: { reason: 'No element matches ".definitely-no-such-t3-target".' },
354+
},
355+
}),
356+
).pipe(Effect.forkScoped);
357+
yield* Effect.yieldNow;
358+
359+
const error = yield* broker
360+
.invoke<void>({
361+
scope,
362+
operation: "click",
363+
input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 },
364+
})
365+
.pipe(Effect.flip);
366+
367+
expect(error._tag).toBe("PreviewAutomationTimeoutError");
368+
expect(error.message).toBe(
369+
'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".',
370+
);
371+
}),
372+
),
373+
);
374+
338375
it.effect("distinguishes malformed remote failures", () =>
339376
Effect.scoped(
340377
Effect.gen(function* () {

‎apps/server/src/mcp/PreviewAutomationBroker.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,14 @@ const readRemoteTimeoutMs = (detail: unknown): number | undefined => {
205205
: undefined;
206206
};
207207

208+
const readRemoteReason = (detail: unknown): string | undefined =>
209+
typeof detail === "object" &&
210+
detail !== null &&
211+
"reason" in detail &&
212+
typeof detail.reason === "string"
213+
? detail.reason
214+
: undefined;
215+
208216
const MAX_REASON_CHARS = 500;
209217

210218
const classifyResponseError = (
@@ -255,9 +263,13 @@ const classifyResponseError = (
255263
});
256264
case "PreviewAutomationTimeoutError": {
257265
const remoteTimeoutMs = readRemoteTimeoutMs(error.detail);
266+
const remoteReason = readRemoteReason(error.detail);
258267
return new PreviewAutomationTimeoutError({
259268
...context,
260269
...remoteDiagnostics,
270+
...(context.clientId === SERVER_BROWSER_AUTOMATION_CLIENT_ID && remoteReason !== undefined
271+
? { reason: remoteReason.slice(0, MAX_REASON_CHARS) }
272+
: {}),
261273
...(remoteTimeoutMs === undefined
262274
? {}
263275
: { timeoutMs: Math.min(context.timeoutMs, remoteTimeoutMs) }),

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,27 @@ describe("server browser element refs", () => {
9898
expect(await page.locator("li").count()).toBe(5);
9999
});
100100

101+
it("tells a click target that matches nothing from one that never becomes clickable", async () => {
102+
await page.setContent(`<button hidden>hidden</button>`);
103+
const failure = (selector: string) =>
104+
ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
105+
() => expect.unreachable(),
106+
ServerBrowserPage.toOperationError,
107+
);
108+
109+
const absent = await failure(".definitely-no-such-t3-target");
110+
expect(absent.tag).toBe("PreviewAutomationTimeoutError");
111+
expect(absent.message).toBe(
112+
'The click may have happened and removed its target or navigated; check the page before retrying. No element matches ".definitely-no-such-t3-target" after the timeout; take a fresh snapshot and use its locator.',
113+
);
114+
expect(absent.cause).toMatchObject({ name: "TimeoutError" });
115+
const hidden = await failure("button");
116+
expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
117+
expect(hidden.message).toBe(
118+
'The click may have happened; check the page before retrying. "button" still matches an element after the timeout.',
119+
);
120+
});
121+
101122
it("does not retarget a removed ref to a replacement node", async () => {
102123
await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
103124
const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");

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

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ export class ServerBrowserOperationError extends Error {
3333
readonly tag: string;
3434
readonly detail: unknown;
3535

36-
constructor(tag: string, message: string, detail?: unknown) {
37-
super(message);
36+
constructor(tag: string, message: string, detail?: unknown, options?: ErrorOptions) {
37+
super(message, options);
3838
this.tag = tag;
3939
this.detail = detail;
4040
}
@@ -72,6 +72,8 @@ export const toOperationError = (
7272
};
7373

7474
const DEFAULT_TIMEOUT_MS = 15_000;
75+
const TARGET_COUNT_MS = 250;
76+
const MAX_TARGET_CHARS = 200;
7577

7678
const pageRefs = new WeakMap<Page, { generation: string; refs: Map<string, string> }>();
7779
// A compact runtime namespace prevents old refs from aliasing after a server restart.
@@ -634,6 +636,58 @@ export const click = async (
634636
): Promise<{ readonly x: number; readonly y: number }> => {
635637
const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
636638
const locator = targetLocator(page, input);
639+
try {
640+
return await clickTarget(page, locator, input, timeout, pointer);
641+
} catch (cause) {
642+
throw locator === null ? cause : await namedTargetTimeout(locator, input, cause);
643+
}
644+
};
645+
646+
/**
647+
* Playwright's timeout names neither the target nor why it waited. Counting only after the
648+
* wait failed keeps auto-wait intact, but the count describes the page after the timeout, not
649+
* what the click did: Playwright can dispatch the click and then time out waiting for the
650+
* navigation it started.
651+
*/
652+
const namedTargetTimeout = async (
653+
locator: Locator,
654+
input: { readonly locator?: string | undefined; readonly selector?: string | undefined },
655+
cause: unknown,
656+
) => {
657+
if (!(cause instanceof Error && cause.name === "TimeoutError")) return cause;
658+
const selector = JSON.stringify(input.locator ?? input.selector);
659+
// The warning leads and the target is capped, so a reply cut short still carries the warning.
660+
const target =
661+
selector.length > MAX_TARGET_CHARS ? `${selector.slice(0, MAX_TARGET_CHARS)}...` : selector;
662+
// The host's reply must still beat the broker's short grace after the operation timeout.
663+
let timer: ReturnType<typeof setTimeout> | undefined;
664+
const matches = await Promise.race([
665+
locator.count().catch(() => undefined),
666+
new Promise<undefined>((resolve) => {
667+
timer = setTimeout(() => resolve(undefined), TARGET_COUNT_MS);
668+
}),
669+
]).finally(() => clearTimeout(timer));
670+
const reason =
671+
matches === undefined
672+
? `The click may have happened; check the page before retrying. Whether ${target} still matches an element is unknown.`
673+
: matches === 0
674+
? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.`
675+
: `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`;
676+
return new ServerBrowserOperationError(
677+
"PreviewAutomationTimeoutError",
678+
reason,
679+
{ reason },
680+
{ cause },
681+
);
682+
};
683+
684+
const clickTarget = async (
685+
page: Page,
686+
locator: Locator | null,
687+
input: PreviewAutomationClickInput,
688+
timeout: number,
689+
pointer: PointerReporter,
690+
) => {
637691
const point = await targetPoint(page, locator, input, timeout);
638692
await pointer(point, "click");
639693
const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const;

‎packages/contracts/src/previewAutomation.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -766,11 +766,12 @@ export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAut
766766
{
767767
...PreviewAutomationRequestErrorFields,
768768
...PreviewAutomationOptionalRemoteDiagnosticFields,
769+
reason: Schema.optional(Schema.String),
769770
},
770771
) {
771772
override get message(): string {
772773
const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
773-
return summary;
774+
return this.reason === undefined ? summary : `${summary} ${this.reason}`;
774775
}
775776
}
776777

0 commit comments

Comments
 (0)