Skip to content

Commit fddb368

Browse files
committed
Merge remote-tracking branch 'origin/main' into feat/steer-off-npx
2 parents a876198 + cde3620 commit fddb368

3 files changed

Lines changed: 170 additions & 47 deletions

File tree

‎apps/server/src/project/AgentSessionScanner.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,6 +1204,7 @@ export const make = Effect.gen(function* () {
12041204
filePath,
12051205
mtimeMs: stats.value.mtime.value.getTime(),
12061206
providerInstanceId,
1207+
homePath: sessionsDir,
12071208
size: Number(stats.value.size),
12081209
});
12091210
}

‎apps/web/src/browser/ServerBrowserSurface.browser.test.tsx‎

Lines changed: 140 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,102 +1,201 @@
1-
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
1+
import { EnvironmentId } from "@t3tools/contracts";
22
import type {
3+
PreviewStreamControl,
34
PreviewStreamEvents,
45
PreviewStreamInput,
56
} from "@t3tools/client-runtime/preview/server-browser-stream";
6-
7-
import "~/index.css";
87
import { describe, expect, it, vi } from "vite-plus/test";
8+
import { userEvent } from "vite-plus/test/browser";
99

10-
import { render } from "../../test/render";
10+
import { act, render } from "../../test/render";
1111

1212
const mocks = vi.hoisted(() => ({
13-
send: vi.fn<(input: PreviewStreamInput) => void>(),
14-
connect: vi.fn(),
15-
events: null as PreviewStreamEvents | null,
13+
createClient: vi.fn<(target: unknown, handlers: PreviewStreamEvents) => unknown>(),
14+
sent: [] as PreviewStreamInput[],
15+
access: { url: "ws://preview.test", token: "test" },
1616
painted: null as (() => void) | null,
1717
}));
1818

1919
vi.mock(import("@t3tools/client-runtime/preview/server-browser-stream"), async (original) => ({
2020
...(await original()),
21+
createPreviewStreamClient: mocks.createClient as never,
2122
createPreviewFramePainter: (_canvas, onPainted) => {
2223
mocks.painted = onPainted ?? null;
2324
return { paint: () => undefined, stop: () => undefined };
2425
},
25-
createPreviewStreamClient: (_options, events) => {
26-
mocks.events = events;
27-
mocks.connect();
28-
return { send: mocks.send, stop: () => undefined } as never;
29-
},
3026
}));
3127

3228
vi.mock(import("~/state/previewStream"), async (original) => ({
3329
...(await original()),
34-
usePreviewStreamAccess: () => ({}) as never,
30+
usePreviewStreamAccess: () => mocks.access as never,
3531
}));
3632

3733
import { ServerBrowserSurface } from "./ServerBrowserSurface";
3834

39-
async function renderSurface() {
40-
mocks.send.mockReset();
41-
mocks.connect.mockReset();
35+
function setup() {
36+
mocks.sent.length = 0;
37+
mocks.painted = null;
38+
mocks.createClient.mockReset().mockImplementation(() => ({
39+
send: (input: PreviewStreamInput) => mocks.sent.push(input),
40+
stop: () => undefined,
41+
}));
42+
}
43+
44+
async function renderSurface(controller: PreviewStreamControl["controller"]) {
4245
const container = document.createElement("div");
43-
container.style.cssText = "width: 400px; height: 300px;";
46+
container.style.cssText = "width: 400px; height: 300px; display: flex;";
4447
await using stack = new AsyncDisposableStack();
45-
stack.use(
48+
const screen = stack.use(
4649
await render(
4750
<ServerBrowserSurface
48-
environmentId={EnvironmentId.make("environment-1")}
49-
threadId={ThreadId.make("thread-1")}
50-
tabId="tab-1"
51+
environmentId={EnvironmentId.make("environment-copy")}
52+
threadId="thread-copy"
53+
tabId="tab-copy"
5154
visible
55+
followSize={false}
56+
className="flex-1"
5257
/>,
5358
{ container },
5459
),
5560
);
56-
const canvas = container.querySelector("canvas");
57-
if (!canvas) throw new Error("The surface did not render its canvas.");
58-
// The stream connects once the surface has measured its size.
59-
await vi.waitFor(() => expect(mocks.connect).toHaveBeenCalled());
60-
return Object.assign(stack.move(), { canvas });
61+
await vi.waitFor(() => expect(mocks.createClient).toHaveBeenCalled());
62+
const handlers = mocks.createClient.mock.calls.at(-1)![1];
63+
await act(() =>
64+
handlers.onControl?.({ canOperate: true, controller, generation: 1, dialog: null }),
65+
);
66+
mocks.sent.length = 0;
67+
const input = container.querySelector("textarea")!;
68+
const canvas = container.querySelector("canvas")!;
69+
stack.move();
70+
return { screen, input, canvas };
6171
}
6272

73+
const keys = () => mocks.sent.filter((input) => input.type === "key");
74+
75+
describe("ServerBrowserSurface clipboard commands", () => {
76+
it("sends a native Copy or Cut menu command to the page once", async () => {
77+
setup();
78+
const { screen, input, canvas } = await renderSurface("you");
79+
await using _screen = screen;
80+
// Chromium runs a script Copy or Cut only during a user gesture, as a menu click is.
81+
await userEvent.click(canvas);
82+
input.focus();
83+
mocks.sent.length = 0;
84+
85+
// Like Electron's webContents.copy(): the browser's Copy command, with no key.
86+
expect(document.execCommand("copy")).toBe(true);
87+
expect(keys()).toEqual([
88+
{ type: "key", action: "down", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
89+
{ type: "key", action: "up", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
90+
]);
91+
92+
mocks.sent.length = 0;
93+
expect(document.execCommand("cut")).toBe(true);
94+
expect(input.value).toBe("\u200b");
95+
expect(keys()).toEqual([
96+
{ type: "key", action: "down", key: "x", code: "KeyX", keyCode: 88, modifiers: 2 },
97+
{ type: "key", action: "up", key: "x", code: "KeyX", keyCode: 88, modifiers: 2 },
98+
]);
99+
});
100+
101+
it("sends a keyboard Copy or Cut once and leaves menu Copy working after any shortcut", async () => {
102+
setup();
103+
const { screen, input, canvas } = await renderSurface("you");
104+
await using _screen = screen;
105+
await userEvent.click(canvas);
106+
input.focus();
107+
const prevented: boolean[] = [];
108+
const onKeyDown = (event: KeyboardEvent) => {
109+
if (/^[cx]$/i.test(event.key)) prevented.push(event.defaultPrevented);
110+
};
111+
window.addEventListener("keydown", onKeyDown);
112+
using _listener = { [Symbol.dispose]: () => window.removeEventListener("keydown", onKeyDown) };
113+
114+
// An unprevented copy or cut key also makes the browser fire copy or cut: here Chromium's
115+
// Ctrl key binding, on macOS Electron's menu after the Meta keyup.
116+
for (const [shortcut, cancels] of [
117+
["{Control>}x{/Control}", true],
118+
["{Control>}c{/Control}", true],
119+
["{Meta>}{x>}{/Meta}{/x}", true],
120+
["{Control>}{Shift>}c{/Shift}{/Control}", false],
121+
["{Control>}{Alt>}x{/Alt}{/Control}", false],
122+
] as const) {
123+
mocks.sent.length = 0;
124+
prevented.length = 0;
125+
await userEvent.keyboard(shortcut);
126+
expect(prevented, shortcut).toEqual([cancels]);
127+
expect(keys().filter((key) => /^[cx]$/i.test(key.key)).length, shortcut).toBe(2);
128+
expect(input.value).toBe("\u200b");
129+
130+
mocks.sent.length = 0;
131+
expect(document.execCommand("copy")).toBe(true);
132+
expect(keys(), shortcut).toEqual([
133+
{ type: "key", action: "down", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
134+
{ type: "key", action: "up", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
135+
]);
136+
}
137+
});
138+
139+
it("sends nothing when another viewer controls the page", async () => {
140+
setup();
141+
const { screen, input } = await renderSurface("another-viewer");
142+
await using _screen = screen;
143+
144+
expect(
145+
input.dispatchEvent(new ClipboardEvent("copy", { bubbles: true, cancelable: true })),
146+
).toBe(false);
147+
expect(
148+
input.dispatchEvent(new ClipboardEvent("cut", { bubbles: true, cancelable: true })),
149+
).toBe(false);
150+
expect(mocks.sent).toEqual([]);
151+
});
152+
});
153+
63154
const mouseUp = (canvas: HTMLCanvasElement, button: number) => {
64155
const event = new MouseEvent("mouseup", { button, bubbles: true, cancelable: true });
65156
canvas.dispatchEvent(event);
66157
return event;
67158
};
68159

69-
describe("ServerBrowserSurface", () => {
160+
describe("ServerBrowserSurface history", () => {
70161
it("routes mouse thumb buttons to the preview's history instead of the app", async () => {
71-
await using surface = await renderSurface();
72-
const { canvas } = surface;
162+
setup();
163+
const { screen, input } = await renderSurface("you");
164+
await using _screen = screen;
165+
const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
73166

74167
expect(mouseUp(canvas, 3).defaultPrevented).toBe(true);
75168
expect(mouseUp(canvas, 4).defaultPrevented).toBe(true);
76-
expect(mocks.send.mock.calls).toEqual([
77-
[{ type: "history", delta: -1 }],
78-
[{ type: "history", delta: 1 }],
169+
expect(mocks.sent).toEqual([
170+
{ type: "history", delta: -1 },
171+
{ type: "history", delta: 1 },
79172
]);
80173
});
81174

82175
it("leaves other mouse buttons alone", async () => {
83-
await using surface = await renderSurface();
84-
const { canvas } = surface;
176+
setup();
177+
const { screen, input } = await renderSurface("you");
178+
await using _screen = screen;
179+
const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
85180

86181
expect(mouseUp(canvas, 0).defaultPrevented).toBe(false);
87-
expect(mocks.send).not.toHaveBeenCalled();
182+
expect(mocks.sent).toEqual([]);
88183
});
89184

90185
it("does not forward thumb-button presses to the page", async () => {
91-
await using surface = await renderSurface();
92-
const { canvas } = surface;
186+
setup();
187+
const { screen, input } = await renderSurface("you");
188+
await using _screen = screen;
189+
const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
93190
canvas.width = 400;
94191
canvas.height = 300;
95192
// Synthetic pointers have no active pointer id to capture.
96193
canvas.setPointerCapture = () => undefined;
97-
mocks.painted?.();
98-
mocks.events?.onViewport({ width: 400, height: 300 });
99-
mocks.events?.onControl?.({ canOperate: true, controller: "you", generation: 1, dialog: null });
194+
const handlers = mocks.createClient.mock.calls.at(-1)![1];
195+
await act(() => {
196+
mocks.painted?.();
197+
handlers.onViewport({ width: 400, height: 300 });
198+
});
100199
const { left, top } = canvas.getBoundingClientRect();
101200
const press = (type: "pointerdown" | "pointerup", button: number) =>
102201
canvas.dispatchEvent(
@@ -109,7 +208,7 @@ describe("ServerBrowserSurface", () => {
109208
bubbles: true,
110209
}),
111210
);
112-
const mouseInputs = () => mocks.send.mock.calls.filter(([input]) => input.type === "mouse");
211+
const mouseInputs = () => mocks.sent.filter((input) => input.type === "mouse");
113212

114213
for (const button of [3, 4]) {
115214
press("pointerdown", button);

‎apps/web/src/browser/ServerBrowserSurface.tsx‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import type {
2020
PreviewViewportSetting,
2121
} from "@t3tools/contracts";
2222
import {
23+
type ClipboardEvent,
2324
type FormEvent,
2425
type KeyboardEvent,
2526
type MouseEvent,
@@ -57,6 +58,9 @@ const PROBE_REUSE_MS = 10_000;
5758
const INPUT_SENTINEL = "\u200b";
5859
const BACKSPACE = { key: "Backspace", code: "Backspace", keyCode: 8 } as const;
5960
const DELETE = { key: "Delete", code: "Delete", keyCode: 46 } as const;
61+
const COPY = { key: "c", code: "KeyC", keyCode: 67 } as const;
62+
const CUT = { key: "x", code: "KeyX", keyCode: 88 } as const;
63+
const CTRL = 2;
6064
const MAX_UNAUTHORIZED_REFUSALS = 3;
6165
const TAP_SLOP_PX = 8;
6266
const MULTI_CLICK_MS = 500;
@@ -649,9 +653,20 @@ export function ServerBrowserSurface(props: {
649653
textarea.setSelectionRange(INPUT_SENTINEL.length, INPUT_SENTINEL.length);
650654
};
651655

652-
const sendKeyPress = (key: typeof BACKSPACE | typeof DELETE) => {
653-
send({ type: "key", action: "down", ...key, modifiers: 0 });
654-
send({ type: "key", action: "up", ...key, modifiers: 0 });
656+
const sendKeyPress = (
657+
key: typeof BACKSPACE | typeof DELETE | typeof COPY | typeof CUT,
658+
modifiers = 0,
659+
) => {
660+
send({ type: "key", action: "down", ...key, modifiers });
661+
send({ type: "key", action: "up", ...key, modifiers });
662+
};
663+
664+
// Edit menu Copy and Cut fire no key, so send the shortcut the server copies on.
665+
const handleClipboard = (key: typeof COPY | typeof CUT, event: ClipboardEvent) => {
666+
// Keep the sentinel off the clipboard.
667+
event.preventDefault();
668+
if (controlRef.current?.controller !== "you") return;
669+
sendKeyPress(key, CTRL);
655670
};
656671

657672
const handleKey = (action: "down" | "up", event: KeyboardEvent<HTMLTextAreaElement>) => {
@@ -696,6 +711,15 @@ export function ServerBrowserSurface(props: {
696711
action === "down" &&
697712
!shortcut &&
698713
(text !== undefined || event.key === "Backspace" || event.key === "Delete");
714+
// The key copies or cuts in the page, so stop the browser's own copy or cut repeating it.
715+
if (
716+
event.ctrlKey !== event.metaKey &&
717+
!event.altKey &&
718+
!event.shiftKey &&
719+
["c", "x"].includes(event.key.toLowerCase())
720+
) {
721+
event.preventDefault();
722+
}
699723
if (shortcut) return;
700724
event.preventDefault();
701725
event.stopPropagation();
@@ -790,9 +814,8 @@ export function ServerBrowserSurface(props: {
790814
if (text) send({ type: "text", text });
791815
resetInput(event.currentTarget);
792816
}}
793-
// Keep the sentinel off the clipboard.
794-
onCopy={(event) => event.preventDefault()}
795-
onCut={(event) => event.preventDefault()}
817+
onCopy={(event) => handleClipboard(COPY, event)}
818+
onCut={(event) => handleClipboard(CUT, event)}
796819
onPaste={(event) => {
797820
event.preventDefault();
798821
const text = event.clipboardData.getData("text/plain");

0 commit comments

Comments
 (0)