GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): preview copy only forwards text from the viewer's copy keys by maria-rcks · Pull Request #19561 · pingdotgg/t3code

fix(server): preview copy only forwards text from the viewer's copy keys #19561

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
maria-rcks merged 3 commits into main from t3/fix-preview-copy-keys
Oct 14, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

fix(server): preview copy only forwards text from the viewer's copy keys #19561

Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
847a93d
fix(server): preview copy only forwards text from the viewer's copy keys
maria-rcks Oct 14, 2026
3661e61
fix(server): preview copy keys forward only the text they copied
maria-rcks Oct 14, 2026
5aa3a9a
fix(server): preview copy keys reach frames in their own process
maria-rcks Oct 14, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

46 changes: 34 additions & 12 deletions 46 apps/server/src/preview/ServerBrowser.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,21 @@ function makeSession() {
return {
on: vi.fn(),
detach: vi.fn(async () => {}),
send: vi.fn(async (method: string, _input?: unknown): Promise<Record<string, unknown>> => {
send: vi.fn(async (method: string, input?: unknown): Promise<Record<string, unknown>> => {
if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] };
if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } };
if (method === "Page.captureScreenshot") return { data: "ZnJhbWU=" };
if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
// A copy or cut key copies keyCopy; one that copies nothing leaves the frames as they were.
if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands)
pageCopy = keyCopy || pageCopy;
// The clipboard world hands over what the page's frames copied, once.
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
const value = pageCopy;
pageCopy = "";
return { result: { value } };
}
return { result: { value: "evaluated" } };
}),
};
Expand Down Expand Up @@ -130,10 +141,6 @@ function makeContext(onClose?: (context: BrowserContext) => void) {
sessions,
newPage: async () => page as unknown as Page,
grantPermissions: vi.fn(async () => {}),
exposeBinding: vi.fn(async (_name: string, binding: ClipboardBinding) => {
clipboardBinding = binding;
}),
addInitScript: vi.fn(async () => {}),
newCDPSession: async () => {
const session = makeSession();
sessions.push(session);
Expand All @@ -153,8 +160,10 @@ const contexts: ReturnType<typeof makeContext>[] = [];
/** The profile and isolation each headless tab asked its context for. */
const contextRequests: Array<{ profileId: string; isolated: boolean }> = [];
let contextGate: PromiseWithResolvers<void> | null = null;
type ClipboardBinding = (source: { page: unknown }, text: unknown) => void;
let clipboardBinding: ClipboardBinding | null = null;
/** The text the page's frames hold from their latest copy. */
let pageCopy = "";
/** The text the next copy or cut key copies. */
let keyCopy = "";
let contextFailure: Error | null = null;
/** Server tabs the fake desktop renders, and the endpoints the server connected to. */
let desktopRendersNext = false;
Expand Down Expand Up @@ -272,6 +281,8 @@ beforeEach(() => {
contextRequests.length = 0;
contextGate = null;
contextFailure = null;
pageCopy = "";
keyCopy = "";
desktopTabs.clear();
desktopRendersNext = false;
releasedDesktopTabs.length = 0;
Expand Down Expand Up @@ -1007,29 +1018,40 @@ it.live("closing a tab while a viewer is still opening it does not leave its pag
).pipe(Effect.provide(layer)),
);

it.live("page copies reach only the controlling viewer right after its input", () =>
it.live("only the controlling viewer's copy and cut keys reach its clipboard", () =>
Effect.scoped(
Effect.gen(function* () {
const { browser, tabId } = yield* ready;
const page = contexts[0]!.page;
const watcher = yield* browser.attachViewer(viewerInput(tabId, false));
const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
yield* viewer.input({ type: "takeControl" });
const clipboard = (queue: typeof viewer.output) =>
Queue.clear(queue).pipe(
Effect.map((items) => items.filter((item) => item._tag === "clipboard")),
);
// A page writing on its own, without a recent gesture, stays on the server.
clipboardBinding!({ page }, "unprompted");
// What the page copied on its own stays on the server through other input.
pageCopy = "unprompted";
yield* viewer.input({ type: "mouse", action: "move", x: 10, y: 10 });
yield* viewer.input({ type: "wheel", x: 10, y: 10, deltaY: 40 });
yield* viewer.input({ type: "key", action: "down", key: "v", code: "KeyV", modifiers: 4 });
yield* viewer.input({ type: "unknown" });
expect(yield* clipboard(viewer.output)).toEqual([]);
keyCopy = "copied";
yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
const cdp = contexts[0]!.sessions.at(-1)!;
expect(cdp.send).toHaveBeenCalledWith(
"Input.dispatchKeyEvent",
expect.objectContaining({ key: "c", commands: ["copy"] }),
);
clipboardBinding!({ page }, "copied");
expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]);
keyCopy = "cut";
yield* viewer.input({ type: "key", action: "down", key: "x", code: "KeyX", modifiers: 2 });
expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "cut" }]);
// A copy key with nothing copied sends nothing, not what a frame kept from before.
pageCopy = "left over";
keyCopy = "";
yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
expect(yield* clipboard(viewer.output)).toEqual([]);
expect(yield* clipboard(watcher.output)).toEqual([]);
}),
).pipe(Effect.provide(layer)),
Expand Down
133 changes: 88 additions & 45 deletions 133 apps/server/src/preview/ServerBrowser.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,6 @@ interface ViewerState {
readonly pause: () => Promise<void>;
readonly resume: () => Promise<void>;
scrolledAt: number;
/** Last input from this viewer; page copies reach its clipboard only right after. */
inputAt: number;
/** Panel bounds, retained in fixed mode; passive viewers never request a size. */
requestedSize: { width: number; height: number; order: number } | null;
}
Expand Down Expand Up @@ -434,43 +432,50 @@ const editingCommand = (key: string, modifiers: number) => {
};

const CLIPBOARD_TEXT_LIMIT = 1024 * 1024;
/** Copies reach the viewer only this soon after it last touched the page. */
const CLIPBOARD_GESTURE_MS = 5_000;
const CLIPBOARD_BINDING = "__t3PreviewClipboard";
// Headless Chromium shares one clipboard between every context, so pages
// report their own copies instead of the clipboard being read back.
const CLIPBOARD_WORLD = "t3-preview-clipboard";
// Headless Chromium shares one clipboard between every context, so the copy
// a viewer's copy or cut key makes is read from this world instead of the
// clipboard. Page scripts cannot see the world, and only a copy made while a
// real key is handled counts.
const CLIPBOARD_SCRIPT = `(() => {
const send = (text) => {
if (typeof text !== "string" || text.length === 0) return;
try { globalThis.${CLIPBOARD_BINDING}?.(text.slice(0, ${CLIPBOARD_TEXT_LIMIT})); } catch {}
};
let keying = false;
let copied = "";
// The same Ctrl or Cmd + C or X that editingCommand sends as copy or cut.
addEventListener("keydown", (event) => {
if (!event.isTrusted || event.altKey || event.ctrlKey === event.metaKey) return;
const key = event.key.toLowerCase();
if (key !== "c" && key !== "x") return;
keying = true;
copied = "";
setTimeout(() => { keying = false; });
}, true);
const selection = () => {
const field = document.activeElement;
let field = document.activeElement;
while (field?.shadowRoot?.activeElement) field = field.shadowRoot.activeElement;
if ((field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) && field.selectionStart !== null)
return field.value.slice(field.selectionStart, field.selectionEnd ?? field.selectionStart);
return String(document.getSelection() ?? "");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

};
// Bubbling to window runs after page handlers, before cut removes the selection.
const copied = (event) =>
send(event.defaultPrevented ? event.clipboardData?.getData("text/plain") : selection());
addEventListener("copy", copied);
addEventListener("cut", copied);
const proto = globalThis.Clipboard?.prototype;
if (!proto) return;
const writeText = proto.writeText;
proto.writeText = function (text) {
const result = writeText.call(this, text);
result.then(() => send(String(text)), () => {});
return result;
const record = (text) => {
copied = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT});
};
// Capturing at window runs before page handlers can stop the event, and
// before cut removes the selection.
const snapshot = (event) => {
if (keying && event.isTrusted) record(selection());
};
const write = proto.write;
proto.write = function (items) {
const result = write.call(this, items);
result.then(async () => {
const item = [...items].find((candidate) => candidate.types.includes("text/plain"));
if (item) send(await (await item.getType("text/plain")).text());
}, () => {});
return result;
// Bubbling back to window picks up text a page handler set instead.
const replace = (event) => {
if (keying && event.isTrusted && event.defaultPrevented) record(event.clipboardData?.getData("text/plain"));
};
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

for (const type of ["copy", "cut"]) {
addEventListener(type, snapshot, true);
addEventListener(type, replace);
}
globalThis.takeCopy = () => {
const text = copied;
copied = "";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

return text;
};
})();`;

Expand Down Expand Up @@ -763,13 +768,14 @@ const make = Effect.gen(function* () {
isolatedContext ? tabKey(snapshot.threadId, snapshot.tabId) : undefined,
));
if (adopted?.page.isClosed()) throw new Error("The popup closed before it opened.");
// The desktop page already has its own clipboard; the bridge script is for headless tabs.
// The desktop page already has its own clipboard.
if (!desktop) await prepareContext(context);
const page = adopted?.page ?? desktop?.page ?? (await context.newPage());
const cdp = await context.newCDPSession(page);
// The desktop's page is already a normal browser. A popup's first request
// went out before it became a tab; everything after presents as Chrome.
if (!desktop) await presentAsChrome(cdp, host);
if (!desktop) await recordCopies(cdp);
page.setDefaultTimeout(NAVIGATION_TIMEOUT_MS);
page.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);
const control = new SessionControl(snapshot.automationOwner ?? null, () =>
Expand Down Expand Up @@ -1129,16 +1135,45 @@ const make = Effect.gen(function* () {
if (preparedContexts.has(context)) return;
preparedContexts.add(context);
await context.grantPermissions(["clipboard-write"]);
await context.exposeBinding(CLIPBOARD_BINDING, ({ page }, text: unknown) => {
if (typeof text !== "string") return;
const tab = [...tabs.values()].find((candidate) => candidate.page === page);
const controller = tab
? [...tab.viewers].find((viewer) => viewer.id === tab.control.controller)
: undefined;
if (!controller || Date.now() - controller.inputAt > CLIPBOARD_GESTURE_MS) return;
controller.push({ _tag: "clipboard", text: text.slice(0, CLIPBOARD_TEXT_LIMIT) });
};

/** Records the copies made in each of a headless page's frames. */
const recordCopies = async (cdp: CDPSession) => {
// Scripts for new documents run only while this session's Page domain is on.
await cdp.send("Page.enable");
await cdp.send("Page.addScriptToEvaluateOnNewDocument", {
source: CLIPBOARD_SCRIPT,
worldName: CLIPBOARD_WORLD,
runImmediately: true,
});
await context.addInitScript(CLIPBOARD_SCRIPT);
};

/** Clears every frame's copy and returns what the key just handled copied or cut. */
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

const takeCopiedText = async (tab: ServerTab) => {
const { frameTree } = await tab.cdp.send("Page.getFrameTree");
const frameIds = (node: typeof frameTree): Array<string> => [
node.frame.id,
...(node.childFrames ?? []).flatMap(frameIds),
];
const copies = await Promise.all(
frameIds(frameTree).map((frameId) =>
tab.cdp
.send("Page.createIsolatedWorld", { frameId, worldName: CLIPBOARD_WORLD })
.then(({ executionContextId }) =>
tab.cdp.send("Runtime.evaluate", {
contextId: executionContextId,
expression: "globalThis.takeCopy?.()",
returnByValue: true,
}),
)
.then(
({ result }) => (typeof result.value === "string" ? result.value : ""),
// A frame that detached meanwhile copied nothing.
() => "",
),
),
);
return copies.find((text) => text.length > 0);
};

const adoptPopup = async (opener: ServerTab, popup: Page) => {
Expand Down Expand Up @@ -2058,7 +2093,6 @@ const make = Effect.gen(function* () {
) => {
const message = asRecord(raw);
if (!message) return;
viewer.inputAt = Date.now();
const modifiers = modifiersOf(message);
switch (message.type) {
case "mouse": {
Expand Down Expand Up @@ -2104,19 +2138,29 @@ const make = Effect.gen(function* () {
viewer.pressedKeys.delete(code || key);
return;
}
const command = editingCommand(key, modifiers);
// Only the controlling viewer's own copy and cut reach its clipboard.
const copying =
!tab.desktop && (command?.commands[0] === "copy" || command?.commands[0] === "cut");
// Clear what any frame kept from an earlier key, so only this key's copy is read.
if (copying) await takeCopiedText(tab);
await session.send("Input.dispatchKeyEvent", {
type: text ? "keyDown" : "rawKeyDown",
key,
code,
modifiers,
...(text ? { text, unmodifiedText: text } : {}),
...editingCommand(key, modifiers),
...command,
windowsVirtualKeyCode: num(
message.keyCode,
key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0,
),
});
viewer.pressedKeys.set(code || key, { key, code });
if (copying) {
const copied = await takeCopiedText(tab);
if (copied) viewer.push({ _tag: "clipboard", text: copied });
}
return;
}
case "text":
Expand Down Expand Up @@ -2251,7 +2295,6 @@ const make = Effect.gen(function* () {
},
resume: () => startScreencast(screencastScale),
scrolledAt: 0,
inputAt: 0,
requestedSize: null,
};
yield* Effect.acquireRelease(
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.