The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 23:30 UTC
fix(server): a busy embedded frame no longer holds copy keys back (#34204)
Julius Marminge committed
Nov 11, 2026 at 11:52 UTC
3c7424ee39659205912b5c6b6499242bb19702c4
2 files changed
+94
-22
apps/server/src/preview/ServerBrowser.test.ts
+55
-3
@@ -129,9 +129,13 @@ function makeSession(
129
return { result: { value: [] } };
130
}
131
if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve();
132
- if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands) {
133
- if (focusedFrame) focusedFrame.copy = keyCopy || focusedFrame.copy;
134
- else pageCopy = keyCopy || pageCopy;
132
+ // The recorder drops its last copy on every copy or cut key it sees.
133
+ if (
134
+ method === "Input.dispatchKeyEvent" &&
135
+ ["copy", "cut"].includes((input as { commands?: Array<string> }).commands?.[0] ?? "")
136
+ ) {
137
+ if (focusedFrame) focusedFrame.copy = keyCopy;
138
+ else pageCopy = keyCopy;
139
}
140
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
141
const value = frame ? frame.copy : pageCopy;
@@ -1443,6 +1447,54 @@ it.live("only the controlling viewer's copy and cut keys reach its clipboard", (
1447
).pipe(Effect.provide(layer)),
1448
);
1449
1450
+it.live("a busy embedded frame does not hold a copy key back from the page", () =>
1451
+ Effect.scoped(
1452
+ Effect.gen(function* () {
1453
+ const { browser, tabId } = yield* ready;
1454
+ const context = contexts[0]!;
1455
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
1456
+ yield* viewer.input({ type: "takeControl" });
1457
+ const pageSession = context.sessions.at(-1)!;
1458
+ const frame = makeFrame();
1459
+ context.page.emit("framenavigated", frame);
1460
+ yield* Effect.promise(() => frame.recording.promise);
1461
+
1462
+ // The frame answers its copy read only once the page has the key and the
1463
+ // input after it, like a frame busy for longer than the user waits.
1464
+ const keyReached = Promise.withResolvers<void>();
1465
+ const pageSend = pageSession.send.getMockImplementation()!;
1466
+ pageSession.send.mockImplementation(async (method, input) => {
1467
+ if (method === "Input.dispatchKeyEvent" && (input as { type?: string }).type === "keyUp")
1468
+ keyReached.resolve();
1469
+ return pageSend(method, input);
1470
+ });
1471
+ const frameSession = context.sessions.at(-1)!;
1472
+ const frameSend = frameSession.send.getMockImplementation()!;
1473
+ frameSession.send.mockImplementation(async (method, input) => {
1474
+ if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
1475
+ await keyReached.promise;
1476
+ }
1477
+ return frameSend(method, input);
1478
+ });
1479
+
1480
+ keyCopy = "copied";
1481
+ const copying = yield* viewer
1482
+ .input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 })
1483
+ .pipe(Effect.forkScoped({ startImmediately: true }));
1484
+ yield* viewer.input({ type: "key", action: "up", key: "c", code: "KeyC", modifiers: 4 });
1485
+ yield* Fiber.join(copying);
1486
+ expect(pageSession.send).toHaveBeenCalledWith(
1487
+ "Input.dispatchKeyEvent",
1488
+ expect.objectContaining({ key: "c", commands: ["copy"] }),
1489
+ );
1490
+ const clipboard = yield* Queue.clear(viewer.output);
1491
+ expect(clipboard.filter((item) => item._tag === "clipboard")).toEqual([
1492
+ { _tag: "clipboard", text: "copied" },
1493
+ ]);
1494
+ }),
1495
+ ).pipe(Effect.provide(layer)),
1496
+);
1497
+
1498
it.live.each([false, true])(
1499
"a page download is saved, offered to the controller, and listed for the agent (delete fails: %s)",
1500
(deleteFails) =>
apps/server/src/preview/ServerBrowser.ts
+39
-19
@@ -295,6 +295,10 @@ interface ServerTab {
295
readonly page: Page;
296
readonly cdp: CDPSession;
297
readonly frameSessions: Map<Frame, CDPSession>;
298
+ /** Copy reads run in key order, outside the input queue. */
299
+ copyReads: Promise<void>;
300
+ /** When the last copy or cut key was acknowledged; the next one starts after it. */
301
+ copyKeyedUntil: number;
302
readonly createdAt: number;
303
usedAt: number;
304
readonly viewers: Set<ViewerState>;
@@ -427,14 +431,15 @@ const CLIPBOARD_WORLD = "t3-preview-clipboard";
431
// Chromium shares its clipboard across contexts; capture real copy/cut keys in a page-inaccessible world instead.
432
const CLIPBOARD_SCRIPT = `(() => {
433
let keying = false;
430
- let copied = "";
434
+ // One entry per copy or cut key, oldest first, so a later key cannot overwrite an unread copy.
435
+ const copies = [];
436
// The same Ctrl or Cmd + C or X that editingCommand sends as copy or cut.
437
addEventListener("keydown", (event) => {
438
if (!event.isTrusted || event.altKey || event.ctrlKey === event.metaKey) return;
439
const key = event.key.toLowerCase();
440
if (key !== "c" && key !== "x") return;
441
keying = true;
437
- copied = "";
442
+ copies.push({ at: Date.now(), text: "" });
443
setTimeout(() => { keying = false; });
444
}, true);
445
const selection = () => {
@@ -445,7 +450,8 @@ const CLIPBOARD_SCRIPT = `(() => {
450
return String(document.getSelection() ?? "");
451
};
452
const record = (text) => {
448
- copied = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT});
453
+ const copy = copies.at(-1);
454
+ if (copy) copy.text = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT});
455
};
456
// Capturing at window runs before page handlers can stop the event, and
457
// before cut removes the selection.
@@ -460,10 +466,10 @@ const CLIPBOARD_SCRIPT = `(() => {
466
addEventListener(type, snapshot, true);
467
addEventListener(type, replace);
468
}
463
- globalThis.takeCopy = () => {
464
- const text = copied;
465
- copied = "";
466
- return text;
469
+ // A key's copy was keyed between its dispatch and acknowledgement; older copies are stale.
470
+ globalThis.takeCopy = (since, until) => {
471
+ while (copies.length > 0 && copies[0].at < since) copies.shift();
472
+ return copies[0] && copies[0].at <= until ? copies.shift().text : "";
473
};
474
})();`;
475
@@ -867,6 +873,8 @@ const make = Effect.gen(function* () {
873
page,
874
cdp,
875
frameSessions: new Map(),
876
+ copyReads: Promise.resolve(),
877
+ copyKeyedUntil: 0,
878
createdAt: Date.now(),
879
usedAt: Date.now(),
880
viewers: new Set(),
@@ -1310,7 +1318,7 @@ const make = Effect.gen(function* () {
1318
await recordCopies(cdp).catch(constVoid);
1319
};
1320
1313
- const takeSessionCopies = async (cdp: CDPSession) => {
1321
+ const takeSessionCopies = async (cdp: CDPSession, since: number, until: number) => {
1322
const tree = await cdp.send("Page.getFrameTree").catch(() => null);
1323
if (!tree) return [];
1324
const frameIds = (node: typeof tree.frameTree): Array<string> => [
@@ -1324,7 +1332,7 @@ const make = Effect.gen(function* () {
1332
.then(({ executionContextId }) =>
1333
cdp.send("Runtime.evaluate", {
1334
contextId: executionContextId,
1327
- expression: "globalThis.takeCopy?.()",
1335
+ expression: `globalThis.takeCopy?.(${since}, ${until})`,
1336
returnByValue: true,
1337
}),
1338
)
@@ -1336,9 +1344,9 @@ const make = Effect.gen(function* () {
1344
);
1345
};
1346
1339
- const takeCopiedText = async (tab: ServerTab) => {
1347
+ const takeCopiedText = async (tab: ServerTab, since: number, until: number) => {
1348
const copies = await Promise.all(
1341
- [tab.cdp, ...tab.frameSessions.values()].map(takeSessionCopies),
1349
+ [tab.cdp, ...tab.frameSessions.values()].map((cdp) => takeSessionCopies(cdp, since, until)),
1350
);
1351
return copies.flat().find((text) => text.length > 0);
1352
};
@@ -2447,7 +2455,10 @@ const make = Effect.gen(function* () {
2455
const copying =
2456
!tab.desktop && (command?.commands[0] === "copy" || command?.commands[0] === "cut");
2457
2450
- if (copying) await takeCopiedText(tab);
2458
+ // Copy keys get disjoint millisecond windows so each frame's copy belongs to one key.
2459
+ if (copying)
2460
+ while (Date.now() <= tab.copyKeyedUntil) await sleepUntil(tab.copyKeyedUntil + 1);
2461
+ const since = Date.now();
2462
await session.send("Input.dispatchKeyEvent", {
2463
type: text ? "keyDown" : "rawKeyDown",
2464
key,
@@ -2461,11 +2472,16 @@ const make = Effect.gen(function* () {
2472
),
2473
});
2474
viewer.pressedKeys.set(code || key, { key, code });
2464
- if (copying) {
2465
- const copied = await takeCopiedText(tab);
2475
+ if (!copying) return;
2476
+ const until = Date.now();
2477
+ tab.copyKeyedUntil = until;
2478
+ // A busy frame answers late; its read must not hold later input.
2479
+ const read = tab.copyReads.then(async () => {
2480
+ const copied = await takeCopiedText(tab, since, until);
2481
if (copied) viewer.push({ _tag: "clipboard", text: copied });
2467
- }
2468
- return;
2482
+ });
2483
+ tab.copyReads = read;
2484
+ return () => read;
2485
}
2486
case "text":
2487
if (typeof message.text === "string" && message.text.length > 0) {
@@ -2721,8 +2737,9 @@ const make = Effect.gen(function* () {
2737
: {}),
2738
});
2739
} else {
2724
- const dispatch = (input: Record<string, unknown>) =>
2725
- dispatchViewerInput(tab, session, viewer, input);
2740
+ const dispatch = async (input: Record<string, unknown>) => {
2741
+ await dispatchViewerInput(tab, session, viewer, input);
2742
+ };
2743
if (
2744
message.type === "mouse" &&
2745
message.action === "move" &&
@@ -2749,7 +2766,10 @@ const make = Effect.gen(function* () {
2766
}),
2767
);
2768
} else {
2752
- await tab.control.human(viewer.id, () => dispatch(message));
2769
+ const copyRead = await tab.control.human(viewer.id, () =>
2770
+ dispatchViewerInput(tab, session, viewer, message),
2771
+ );
2772
+ await copyRead?.();
2773
}
2774
}
2775
} catch {