@omercnet/paseo-shared-browser 4.1.12-next.504.1 → 4.1.12-next.513.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -157,6 +157,26 @@ The provider launches the stdio adapter on the Paseo daemon host, beside the dae
157
157
  runtime. Web, desktop, and mobile clients never own or host the adapter or Chromium, and a client
158
158
  disconnect does not close or reset either process.
159
159
 
160
+ ### Choosing which agents get the tool
161
+
162
+ By default every new agent gets the adapter. Settings, under Shared Browser, can restrict that:
163
+
164
+ - **Every new agent** (the default) injects the adapter into every new agent, as above.
165
+ - **Only the agents listed** injects it only into a new agent whose provider id is listed, or whose
166
+ workspace id or project id is listed. Separate entries with commas or new lines. An empty
167
+ configuration means no agent.
168
+
169
+ `agent.create` carries the provider and the working directory but no labels and no workspace id, so a
170
+ workspace or project is matched by directory: the workspace whose directory is the agent's directory or
171
+ the deepest one containing it. Both directories are normalized first (separators, `.` and `..` segments),
172
+ so a path that climbs out of a workspace does not match it. The lookup includes background workspaces. If
173
+ the list is longer than 20 pages of 200, or the lookup fails, those lists match nothing. Workspaces that
174
+ share a directory cannot be told apart, so listing any of them matches them all. Matching is lexical: nothing on disk is consulted, so symlinks are not resolved and letter case is not folded. The settings read has a 2 second deadline, and a read that is too slow is treated like an unreadable setting, so every new agent gets the tool. The workspace lookup has its own 2 second deadline, and a timeout there counts as no match. Either timeout logs one line, and a slow lookup never holds up agent creation. The check runs before the adapter, its credential or the supervisor are set up, so
175
+ an agent that is not allowed costs nothing. It applies to agents created after the setting is saved. A
176
+ setting that cannot be read or is invalid falls back to every new agent, and the plugin log gets one line
177
+ saying so. The settings screen reports an entry over 256 characters or a list over 200 entries instead of
178
+ cutting it off.
179
+
160
180
  ## Runtime environment overrides
161
181
 
162
182
  The plugin recognizes only these deployment overrides:
@@ -0,0 +1,143 @@
1
+ import { type PluginSurfaceProps, useSettings } from "@getpaseo/plugin/client";
2
+ import {
3
+ SettingsAction,
4
+ SettingsCard,
5
+ SettingsInput,
6
+ type SettingsInputHandle,
7
+ SettingsSection,
8
+ SettingsSelect,
9
+ } from "@getpaseo/plugin/client/ui";
10
+ import { useRef, useState } from "react";
11
+ import { Text } from "react-native";
12
+ import { type AgentAccessMode, agentAccessSettings, parseEntries } from "../shared/agent-access";
13
+
14
+ const MODE_OPTIONS: readonly { label: string; value: AgentAccessMode }[] = [
15
+ { label: "Every new agent", value: "all" },
16
+ { label: "Only the agents listed below", value: "listed" },
17
+ ];
18
+
19
+ type ListName = "providers" | "workspaces" | "projects";
20
+ const NO_ERRORS: Record<ListName, string | null> = {
21
+ providers: null,
22
+ workspaces: null,
23
+ projects: null,
24
+ };
25
+
26
+ /** Settings screen: which new agents get the browser tool. */
27
+ export function AgentAccessSettings({ theme }: PluginSurfaceProps) {
28
+ const settings = useSettings(agentAccessSettings);
29
+ const providers = useRef<SettingsInputHandle>(null);
30
+ const workspaces = useRef<SettingsInputHandle>(null);
31
+ const projects = useRef<SettingsInputHandle>(null);
32
+ // Errors belong to the revision they were found on; a newer revision (another client saved) clears them.
33
+ const [found, setFound] = useState<{
34
+ revision: string | null;
35
+ errors: Record<ListName, string | null>;
36
+ }>({ revision: null, errors: NO_ERRORS });
37
+ const muted = { color: theme.colors.foregroundMuted, fontSize: 13, lineHeight: 19 };
38
+
39
+ if (settings.status === "loading") {
40
+ return (
41
+ <SettingsSection title="Shared Browser: agent access">
42
+ <Text style={muted}>Loading</Text>
43
+ </SettingsSection>
44
+ );
45
+ }
46
+ if (settings.status !== "ready") {
47
+ return (
48
+ <SettingsSection title="Shared Browser: agent access">
49
+ <Text style={muted}>{settings.error}</Text>
50
+ <SettingsCard>
51
+ <SettingsAction label="Try again" actionLabel="Reload" onPress={settings.reload} />
52
+ {settings.status === "invalid" ? (
53
+ <SettingsAction
54
+ label="Back to the default"
55
+ actionLabel="Reset"
56
+ onPress={settings.reset}
57
+ />
58
+ ) : null}
59
+ </SettingsCard>
60
+ </SettingsSection>
61
+ );
62
+ }
63
+
64
+ const { values } = settings;
65
+ const listErrors = found.revision === settings.revision ? found.errors : NO_ERRORS;
66
+ const save = (next: typeof values) => void settings.save(next, settings.revision);
67
+ // The lists as typed, parsed the same way for Save and for a mode change, so unsaved text is never
68
+ // lost to the revision remount. A list that does not parse shows its error and nothing is saved.
69
+ const typedLists = () => {
70
+ const parsed = {
71
+ providers: parseEntries(providers.current?.getText() ?? ""),
72
+ workspaces: parseEntries(workspaces.current?.getText() ?? ""),
73
+ projects: parseEntries(projects.current?.getText() ?? ""),
74
+ };
75
+ const errors = {
76
+ providers: parsed.providers.error,
77
+ workspaces: parsed.workspaces.error,
78
+ projects: parsed.projects.error,
79
+ };
80
+ setFound({ revision: settings.revision, errors });
81
+ if (errors.providers || errors.workspaces || errors.projects) return null;
82
+ return {
83
+ providers: parsed.providers.entries,
84
+ workspaces: parsed.workspaces.entries,
85
+ projects: parsed.projects.entries,
86
+ };
87
+ };
88
+ return (
89
+ <SettingsSection title="Shared Browser: agent access">
90
+ {/* Keyed on the revision, so the text inputs start over from the saved lists when another client changes them. */}
91
+ <SettingsCard key={settings.revision}>
92
+ <SettingsSelect
93
+ label="Browser tool for"
94
+ hint="Applies to agents created from now on. With the lists empty, no agent gets the tool."
95
+ error={settings.saveError}
96
+ value={values.mode}
97
+ options={MODE_OPTIONS}
98
+ disabled={settings.saving}
99
+ onValueChange={(mode) => {
100
+ const lists = typedLists();
101
+ if (lists) save({ ...values, ...lists, mode });
102
+ }}
103
+ />
104
+ <SettingsInput
105
+ ref={providers}
106
+ label="Provider ids"
107
+ hint="Separated by commas or new lines. An agent whose provider is listed gets the tool."
108
+ initialValue={values.providers.join(", ")}
109
+ error={listErrors.providers}
110
+ onChangeText={() => {}}
111
+ disabled={settings.saving}
112
+ />
113
+ <SettingsInput
114
+ ref={workspaces}
115
+ label="Workspace ids"
116
+ hint="Every new agent in a listed workspace gets the tool."
117
+ initialValue={values.workspaces.join(", ")}
118
+ error={listErrors.workspaces}
119
+ onChangeText={() => {}}
120
+ disabled={settings.saving}
121
+ />
122
+ <SettingsInput
123
+ ref={projects}
124
+ label="Project ids"
125
+ hint="Every new agent in a workspace of a listed project gets the tool."
126
+ initialValue={values.projects.join(", ")}
127
+ error={listErrors.projects}
128
+ onChangeText={() => {}}
129
+ disabled={settings.saving}
130
+ />
131
+ <SettingsAction
132
+ label="Save the lists"
133
+ actionLabel="Save"
134
+ disabled={settings.saving}
135
+ onPress={() => {
136
+ const lists = typedLists();
137
+ if (lists) save({ ...values, ...lists });
138
+ }}
139
+ />
140
+ </SettingsCard>
141
+ </SettingsSection>
142
+ );
143
+ }
@@ -48,15 +48,20 @@ function fakeDom() {
48
48
  removeEventListener: nodeTarget.remove,
49
49
  } as unknown as KeyboardCanvasNode;
50
50
  sink.focus();
51
+ /** Dispatches to the adapter's listeners; returns whether one cancelled the default. */
51
52
  const fire = (name: string, type: string, event: object = {}) => {
53
+ let cancelled = false;
52
54
  for (const listener of registry.get(`${name}:${type}`) ?? [])
53
55
  (listener as (event: object) => void)({
54
- preventDefault() {},
56
+ preventDefault() {
57
+ cancelled = true;
58
+ },
55
59
  stopPropagation() {},
56
60
  ...event,
57
61
  });
62
+ return cancelled;
58
63
  };
59
- return { node, document, fire };
64
+ return { node, document, sink, fire };
60
65
  }
61
66
 
62
67
  const key = {
@@ -225,3 +230,181 @@ describe("web canvas keyboard adapter Android IME sequences", () => {
225
230
  expect(texts(dom)).toEqual(["x"]);
226
231
  });
227
232
  });
233
+
234
+ type Bound = ReturnType<typeof bind>;
235
+ /** Remote key edges, such as "down:Backspace". */
236
+ const presses = (dom: Bound) =>
237
+ dom.events.flatMap((event) => (event.kind === "key" ? [`${event.type}:${event.key}`] : []));
238
+ const BACKSPACE = ["down:Backspace", "up:Backspace"];
239
+
240
+ /** keydown 229, one beforeinput edit, keyup 229, regardless of what the sink holds. */
241
+ function imeEdit(dom: Bound, inputType: string) {
242
+ dom.fire("sink", "keydown", ime);
243
+ dom.fire("sink", "beforeinput", { inputType, data: null });
244
+ dom.fire("doc", "keyup", ime);
245
+ }
246
+
247
+ /**
248
+ * Chrome Android applying a soft-keyboard Backspace (ImeAdapterImpl
249
+ * deleteSurroundingText): keydown 229; only when the sink has text before the
250
+ * caret, beforeinput deleteContentBackward, the deletion and input; keyup 229.
251
+ * Blink applies this deletion even when beforeinput is cancelled
252
+ * (InputMethodController::DeleteSelectionWithoutAdjustment ignores the result);
253
+ * cancelHonored covers an engine that does honor it.
254
+ */
255
+ function softBackspace(dom: Bound, cancelHonored = false) {
256
+ dom.fire("sink", "keydown", ime);
257
+ if (dom.sink.value.length > 0) {
258
+ const cancelled = dom.fire("sink", "beforeinput", {
259
+ inputType: "deleteContentBackward",
260
+ data: null,
261
+ });
262
+ if (!cancelled || !cancelHonored) {
263
+ dom.sink.value = dom.sink.value.slice(0, -1);
264
+ dom.fire("sink", "input", { inputType: "deleteContentBackward", data: null });
265
+ }
266
+ }
267
+ dom.fire("doc", "keyup", ime);
268
+ }
269
+
270
+ /** Hangul composition steps; Backspace inside it rewrites the composition. */
271
+ function compose(dom: Bound, steps: Array<{ inputType: string; data: string | null }>) {
272
+ dom.fire("sink", "keydown", ime);
273
+ dom.fire("sink", "compositionstart", { data: "" });
274
+ for (const [index, step] of steps.entries()) {
275
+ if (index > 0) dom.fire("sink", "keydown", { ...ime, isComposing: true });
276
+ dom.fire("sink", "beforeinput", step);
277
+ }
278
+ }
279
+
280
+ describe("web canvas keyboard adapter Android soft-keyboard deletion", () => {
281
+ it.each<[string, (dom: Bound) => void, { texts: string[]; presses: string[] }]>([
282
+ [
283
+ "keydown 229 + beforeinput deleteContentBackward presses Backspace",
284
+ (dom) => imeEdit(dom, "deleteContentBackward"),
285
+ { texts: [], presses: BACKSPACE },
286
+ ],
287
+ [
288
+ "keydown 229 + beforeinput deleteContentForward presses Delete",
289
+ (dom) => imeEdit(dom, "deleteContentForward"),
290
+ { texts: [], presses: ["down:Delete", "up:Delete"] },
291
+ ],
292
+ // Word deletion has no host-independent shortcut (Ctrl or Option+Backspace).
293
+ [
294
+ "keydown 229 + beforeinput deleteWordBackward stays unmapped",
295
+ (dom) => imeEdit(dom, "deleteWordBackward"),
296
+ { texts: [], presses: [] },
297
+ ],
298
+ [
299
+ "keydown 229 + beforeinput deleteWordForward stays unmapped",
300
+ (dom) => imeEdit(dom, "deleteWordForward"),
301
+ { texts: [], presses: [] },
302
+ ],
303
+ [
304
+ "Backspace before any typing (empty field, keydown carries no key)",
305
+ (dom) => softBackspace(dom),
306
+ { texts: [], presses: BACKSPACE },
307
+ ],
308
+ [
309
+ "three Backspaces after a committed word",
310
+ (dom) => {
311
+ composeWord(dom, "hi");
312
+ for (let count = 0; count < 3; count += 1) softBackspace(dom);
313
+ },
314
+ { texts: ["hi"], presses: [...BACKSPACE, ...BACKSPACE, ...BACKSPACE] },
315
+ ],
316
+ [
317
+ "three Backspaces when the engine honors the cancelled beforeinput",
318
+ (dom) => {
319
+ composeWord(dom, "hi");
320
+ for (let count = 0; count < 3; count += 1) softBackspace(dom, true);
321
+ },
322
+ { texts: ["hi"], presses: [...BACKSPACE, ...BACKSPACE, ...BACKSPACE] },
323
+ ],
324
+ [
325
+ "Backspace after a non-composing insertText",
326
+ (dom) => {
327
+ dom.fire("sink", "keydown", ime);
328
+ dom.fire("sink", "beforeinput", { inputType: "insertText", data: "a" });
329
+ softBackspace(dom);
330
+ },
331
+ { texts: ["a"], presses: BACKSPACE },
332
+ ],
333
+ [
334
+ "Backspace after a paste",
335
+ (dom) => {
336
+ dom.fire("sink", "paste", { clipboardData: { getData: () => "pasted" } });
337
+ softBackspace(dom);
338
+ },
339
+ { texts: ["pasted"], presses: BACKSPACE },
340
+ ],
341
+ [
342
+ "Backspace after a control reset",
343
+ (dom) => {
344
+ dom.binding.reset();
345
+ softBackspace(dom);
346
+ },
347
+ { texts: [], presses: BACKSPACE },
348
+ ],
349
+ [
350
+ "Backspace inside a composing word edits it locally (Gboard predictive)",
351
+ (dom) => {
352
+ compose(dom, [
353
+ { inputType: "insertCompositionText", data: "hel" },
354
+ { inputType: "insertCompositionText", data: "he" },
355
+ ]);
356
+ dom.fire("sink", "compositionend", { data: "he" });
357
+ },
358
+ { texts: ["he"], presses: [] },
359
+ ],
360
+ [
361
+ "Hangul: Backspace removes a jamo inside the composition",
362
+ (dom) => {
363
+ compose(dom, [
364
+ { inputType: "insertCompositionText", data: "ㅎ" },
365
+ { inputType: "insertCompositionText", data: "하" },
366
+ { inputType: "insertCompositionText", data: "한" },
367
+ { inputType: "insertCompositionText", data: "하" },
368
+ ]);
369
+ dom.fire("sink", "compositionend", { data: "하" });
370
+ },
371
+ { texts: ["하"], presses: [] },
372
+ ],
373
+ [
374
+ "Hangul: Backspace empties the composition, then deletes the committed syllable",
375
+ (dom) => {
376
+ composeWord(dom, "한");
377
+ compose(dom, [
378
+ { inputType: "insertCompositionText", data: "ㄱ" },
379
+ { inputType: "deleteCompositionText", data: null },
380
+ ]);
381
+ dom.fire("sink", "compositionend", { data: "" });
382
+ softBackspace(dom);
383
+ },
384
+ { texts: ["한"], presses: BACKSPACE },
385
+ ],
386
+ [
387
+ "a real Backspace keydown (keyCode 8) presses once even if beforeinput follows",
388
+ (dom) => {
389
+ const backspace = { ...key, key: "Backspace", code: "Backspace", keyCode: 8 };
390
+ dom.fire("sink", "keydown", backspace);
391
+ dom.fire("sink", "beforeinput", { inputType: "deleteContentBackward", data: null });
392
+ dom.fire("doc", "keyup", backspace);
393
+ },
394
+ { texts: [], presses: BACKSPACE },
395
+ ],
396
+ [
397
+ "an IME deletion after a control reset is dropped",
398
+ (dom) => {
399
+ dom.fire("sink", "keydown", ime);
400
+ dom.binding.reset();
401
+ dom.fire("sink", "beforeinput", { inputType: "deleteContentBackward", data: null });
402
+ },
403
+ { texts: [], presses: [] },
404
+ ],
405
+ ])("%s", (_name, replay, expected) => {
406
+ const dom = bind();
407
+ replay(dom);
408
+ expect({ texts: texts(dom), presses: presses(dom) }).toEqual(expected);
409
+ });
410
+ });
@@ -57,6 +57,18 @@ interface BindingOptions {
57
57
  onError(error: Error): void;
58
58
  }
59
59
 
60
+ // Android soft keyboards delete through InputConnection.deleteSurroundingText.
61
+ // Chrome reports keydown 229/"Unidentified", then beforeinput delete* only when
62
+ // the sink has text next to the caret. With an empty sink the keydown and keyup
63
+ // are all that arrive, so the sink always keeps one invisible character to delete.
64
+ const SINK_TEXT = "\u200B";
65
+ // Character deletions map to the key a hardware keyboard sends. Word deletions
66
+ // stay unmapped: the remote shortcut depends on the host OS (Ctrl or Option).
67
+ const IME_EDIT_KEYS: Record<string, string> = {
68
+ deleteContentBackward: "Backspace",
69
+ deleteContentForward: "Delete",
70
+ };
71
+
60
72
  /** DOM-only binding; callers must dispose it and reset on route/control changes. */
61
73
  export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: BindingOptions) {
62
74
  const document = node.ownerDocument;
@@ -80,13 +92,14 @@ export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: Bin
80
92
  });
81
93
  node.tabIndex = 0;
82
94
  node.appendChild(sink);
95
+ sink.value = SINK_TEXT;
83
96
  let composing = false;
84
97
  let compositionAdmitted = false;
85
98
  let altTextPending: string | null = null;
86
- // Soft keyboards (Android Chrome) report committed text outside a composition,
87
- // such as a space after a word or every key on non-predictive keyboards, as
88
- // keydown 229/"Unidentified" followed by beforeinput insertText. That keydown
89
- // carries no key to forward, so the insertion itself is the only text source.
99
+ // Soft keyboards (Android Chrome) report edits outside a composition, such as
100
+ // a space after a word, every key on non-predictive keyboards, or Backspace,
101
+ // as keydown 229/"Unidentified" followed by beforeinput insertText or delete*.
102
+ // That keydown carries no key to forward, so the edit itself is the only source.
90
103
  let imeTextPending = false;
91
104
  const focused = () => document.activeElement === sink || document.activeElement === node;
92
105
  const keyboard = createBrowserCanvasKeyboard({
@@ -103,7 +116,7 @@ export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: Bin
103
116
  composing = false;
104
117
  altTextPending = null;
105
118
  imeTextPending = false;
106
- sink.value = "";
119
+ sink.value = SINK_TEXT;
107
120
  };
108
121
  const cancel = () => {
109
122
  reset();
@@ -177,12 +190,31 @@ export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: Bin
177
190
  if (accepted) {
178
191
  commitText(event.data ?? "");
179
192
  }
180
- sink.value = "";
193
+ sink.value = SINK_TEXT;
194
+ };
195
+ // One full press, as the matching hardware key would send it.
196
+ const pressKey = (key: string) => {
197
+ const press = {
198
+ key,
199
+ code: key,
200
+ altKey: false,
201
+ ctrlKey: false,
202
+ metaKey: false,
203
+ shiftKey: false,
204
+ repeat: false,
205
+ };
206
+ if (keyboard.key("down", press)) {
207
+ keyboard.key("up", press);
208
+ }
181
209
  };
182
210
  const beforeInput = (event: KeyboardDomEvent) => {
183
211
  if (!composing && options.enabled() && focused()) {
184
212
  consume(event);
185
- if (
213
+ const editKey =
214
+ imeTextPending && event.inputType ? IME_EDIT_KEYS[event.inputType] : undefined;
215
+ if (editKey) {
216
+ pressKey(editKey);
217
+ } else if (
186
218
  event.inputType === "insertText" &&
187
219
  event.data &&
188
220
  (imeTextPending || event.data === altTextPending)
@@ -192,6 +224,13 @@ export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: Bin
192
224
  altTextPending = null;
193
225
  }
194
226
  };
227
+ // Blink applies a deleteSurroundingText deletion even when its beforeinput was
228
+ // cancelled. Put the sink text back so the next Backspace still has a target.
229
+ const input = () => {
230
+ if (!composing && sink.value !== SINK_TEXT) {
231
+ sink.value = SINK_TEXT;
232
+ }
233
+ };
195
234
  const paste = (event: KeyboardDomEvent) => {
196
235
  if (!options.enabled() || !focused()) {
197
236
  return;
@@ -199,7 +238,7 @@ export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: Bin
199
238
  consume(event);
200
239
  altTextPending = null;
201
240
  commitText(event.clipboardData?.getData("text/plain") ?? "");
202
- sink.value = "";
241
+ sink.value = SINK_TEXT;
203
242
  };
204
243
  const visibility = () => {
205
244
  if (document.hidden) {
@@ -216,6 +255,7 @@ export function bindBrowserCanvasKeyboard(node: KeyboardCanvasNode, options: Bin
216
255
  [sink, "compositionstart", compositionStart],
217
256
  [sink, "compositionend", compositionEnd],
218
257
  [sink, "beforeinput", beforeInput],
258
+ [sink, "input", input],
219
259
  [sink, "paste", paste],
220
260
  [sink, "blur", cancel],
221
261
  ];
@@ -396,6 +396,38 @@ describe("bounded browser input queue", () => {
396
396
  expect(f.errors).toEqual([]);
397
397
  });
398
398
 
399
+ it("sends soft-keyboard text queued behind an in-flight call as one insertion, never across keys", async () => {
400
+ const f = fixture();
401
+ const backspace = (type: "down" | "up"): BrowserGestureEvent => ({
402
+ kind: "key",
403
+ type,
404
+ key: "Backspace",
405
+ code: "Backspace",
406
+ modifiers: 0,
407
+ repeat: false,
408
+ });
409
+ for (const text of ["h", "e", "l", "l", "o"]) f.queue.enqueue({ kind: "text", text });
410
+ f.queue.enqueue(backspace("down"));
411
+ f.queue.enqueue(backspace("up"));
412
+ for (const text of [" ", "w"]) f.queue.enqueue({ kind: "text", text });
413
+ // Merging stops at the per-event text limit the server enforces.
414
+ f.queue.enqueue({ kind: "text", text: "x".repeat(15_999) });
415
+ f.queue.finish();
416
+ f.beginGate.resolve({ state, gestureId: "owned", nextSequence: 1 });
417
+ await flush();
418
+ expect(f.sent.map(({ event }) => (event.kind === "text" ? event.text : event.kind))).toEqual([
419
+ "h",
420
+ "ello",
421
+ "key",
422
+ "key",
423
+ " w",
424
+ "x".repeat(15_999),
425
+ ]);
426
+ expect(f.sent.map((input) => input.sequence)).toEqual([1, 2, 3, 4, 5, 6]);
427
+ expect(f.ended[0]).toMatchObject({ sequence: 7, cancel: false });
428
+ expect(f.errors).toEqual([]);
429
+ });
430
+
399
431
  it("keeps touch-ID edges through 60Hz motion and partial release", async () => {
400
432
  const f = fixture();
401
433
  const touch = (
@@ -84,6 +84,8 @@ export const BROWSER_INPUT_IDLE_MS = 4_000;
84
84
  export const BROWSER_INPUT_KEEPALIVE_MS = 2_000;
85
85
  const MAX_QUEUED_COMMANDS = 64;
86
86
  const MAX_WHEEL_DELTA = 4_000;
87
+ /** Per-event text limit the gesture schema and runtime owner enforce. */
88
+ const MAX_TEXT_LENGTH = 16_000;
87
89
  const MAX_FRAME_ADMISSION_ATTEMPTS = 3;
88
90
  const FRAME_ADMISSION_WAIT_MS = 4_000;
89
91
 
@@ -551,6 +553,16 @@ export function createBrowserInputQueue(options: QueueOptions) {
551
553
  return true;
552
554
  }
553
555
  }
556
+ // Soft keyboards commit text in small pieces, one update each. Text still
557
+ // queued behind the in-flight call is one insertion; never merge across keys.
558
+ if (
559
+ event.kind === "text" &&
560
+ previous.event.kind === "text" &&
561
+ previous.event.text.length + event.text.length <= MAX_TEXT_LENGTH
562
+ ) {
563
+ previous.event = { kind: "text", text: previous.event.text + event.text };
564
+ return true;
565
+ }
554
566
  }
555
567
  if (commands.length >= MAX_QUEUED_COMMANDS) {
556
568
  cancel();
package/index.client.tsx CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { AgentAccessSettings } from "./client/agent-access-settings";
2
3
  import { contributeSharedBrowserClient, SharedBrowserPanel } from "./client/browser";
3
4
  import { contributeSharedBrowserSidebar } from "./client/sidebar";
4
5
 
@@ -21,9 +22,16 @@ export default function contribute(client: PluginClientContext) {
21
22
  },
22
23
  });
23
24
 
25
+ const removeSettings = client.addSettingsScreen({
26
+ id: "agent-access",
27
+ title: "Shared Browser",
28
+ icon: "PanelsTopLeft",
29
+ Component: AgentAccessSettings,
30
+ });
24
31
  const removeSidebar = contributeSharedBrowserSidebar(client);
25
32
  const cleanup = contributeSharedBrowserClient(client);
26
33
  return () => {
34
+ removeSettings();
27
35
  removeSidebar();
28
36
  return cleanup();
29
37
  };
package/index.server.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
- import type { PluginServerContext } from "@getpaseo/plugin/server";
4
+ import type { PluginHookContext, PluginServerContext } from "@getpaseo/plugin/server";
5
5
  import {
6
6
  bindAgentTicket,
7
7
  cleanupBrowserServer,
@@ -33,6 +33,13 @@ import {
33
33
  revokeAgentBrowserAccess,
34
34
  } from "./server/browser";
35
35
  import { resolveBrowserRuntimeRoot } from "./server/runtime-path";
36
+ import { listAllWorkspaces } from "./server/workspace-list";
37
+ import {
38
+ accessFromState,
39
+ agentAccessSettings,
40
+ agentGetsBrowser,
41
+ DEFAULT_AGENT_ACCESS,
42
+ } from "./shared/agent-access";
36
43
  import {
37
44
  acquireControlRpc,
38
45
  applyDevicePresetRpc,
@@ -63,25 +70,34 @@ import { readBrowserVideoRpc } from "./shared/browser-video";
63
70
  const TICKET_ENV = "PASEO_SHARED_BROWSER_TICKET";
64
71
  const MCP_SERVER_ID = "shared-browser";
65
72
  const TICKET_ISSUE_TIMEOUT_MS = 2_000;
73
+ const ACCESS_DECISION_TIMEOUT_MS = 2_000;
66
74
 
67
- async function issueTicketWithinDeadline(ticket: string): Promise<boolean> {
75
+ /** The result of `work`, or a rejection when it has not settled within `ms`. */
76
+ async function withinDeadline<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
68
77
  let timer: NodeJS.Timeout | undefined;
69
78
  try {
70
- await Promise.race([
71
- issueAgentTicket(ticket),
79
+ return await Promise.race([
80
+ work,
72
81
  new Promise<never>((_, reject) => {
73
- timer = setTimeout(
74
- () => reject(new Error("Shared Browser ticket issuance timed out")),
75
- TICKET_ISSUE_TIMEOUT_MS,
76
- );
82
+ timer = setTimeout(() => reject(new Error(message)), ms);
77
83
  timer.unref();
78
84
  }),
79
85
  ]);
86
+ } finally {
87
+ clearTimeout(timer);
88
+ }
89
+ }
90
+
91
+ async function issueTicketWithinDeadline(ticket: string): Promise<boolean> {
92
+ try {
93
+ await withinDeadline(
94
+ issueAgentTicket(ticket),
95
+ TICKET_ISSUE_TIMEOUT_MS,
96
+ "Shared Browser ticket issuance timed out",
97
+ );
80
98
  return true;
81
99
  } catch {
82
100
  return false;
83
- } finally {
84
- clearTimeout(timer);
85
101
  }
86
102
  }
87
103
 
@@ -95,6 +111,45 @@ function mcpBundlePath(): string {
95
111
 
96
112
  export default function contribute(server: PluginServerContext) {
97
113
  server.registerSettings(browserDisplayPreferences);
114
+ const agentAccess = server.registerSettings(agentAccessSettings);
115
+ // The deadline covers the settings read alone: a setting that cannot be read in time is an unreadable
116
+ // setting, and that falls back to the default (every new agent).
117
+ const readAccess = async () => {
118
+ try {
119
+ const state = await withinDeadline(
120
+ Promise.resolve(agentAccess.read()),
121
+ ACCESS_DECISION_TIMEOUT_MS,
122
+ "the read timed out",
123
+ );
124
+ const access = accessFromState(state);
125
+ if (access === DEFAULT_AGENT_ACCESS) {
126
+ console.warn(
127
+ `shared-browser: the agent-access setting is ${state?.status ?? "missing"}; every new agent gets the browser tool`,
128
+ );
129
+ }
130
+ return access;
131
+ } catch (error) {
132
+ console.warn(
133
+ `shared-browser: the agent-access setting could not be read (${error instanceof Error ? error.message : "error"}); every new agent gets the browser tool`,
134
+ );
135
+ return DEFAULT_AGENT_ACCESS;
136
+ }
137
+ };
138
+ // The workspace lookup has its own deadline; a timeout or any other failure there is no match.
139
+ const lookupWorkspaces = async (paseo: PluginHookContext["paseo"]) => {
140
+ try {
141
+ return await withinDeadline(
142
+ listAllWorkspaces(paseo),
143
+ ACCESS_DECISION_TIMEOUT_MS,
144
+ "the workspace lookup timed out",
145
+ );
146
+ } catch (error) {
147
+ console.warn(
148
+ `shared-browser: the workspace lookup failed (${error instanceof Error ? error.message : "error"}); the agent is not matched to a workspace or project`,
149
+ );
150
+ throw error;
151
+ }
152
+ };
98
153
  server.handle(attachBrowserRpc, handleAttachBrowser);
99
154
  server.handle(detachBrowserRpc, handleDetachBrowser);
100
155
  server.handle(closeBrowserRpc, handleCloseBrowser);
@@ -118,8 +173,13 @@ export default function contribute(server: PluginServerContext) {
118
173
  server.handle(resizeBrowserRpc, handleResizeBrowser);
119
174
  server.handle(applyDevicePresetRpc, handleApplyDevicePreset);
120
175
  server.handle(sendBrowserInputRpc, handleSendBrowserInput);
121
- server.before("agent.create", async ({ request }) => {
176
+ server.before("agent.create", async ({ request }, context) => {
122
177
  if (request.config.internal) return request;
178
+ // Decide before any ticket or supervisor work, so an agent that is not allowed costs nothing.
179
+ const allowed = await agentGetsBrowser(await readAccess(), request.config, () =>
180
+ lookupWorkspaces(context.paseo),
181
+ );
182
+ if (!allowed) return request;
123
183
  const ticket = randomBytes(32).toString("base64url");
124
184
  if (!(await issueTicketWithinDeadline(ticket))) return request;
125
185
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-shared-browser",
3
- "version": "4.1.12-next.504.1",
3
+ "version": "4.1.12-next.513.1",
4
4
  "description": "One real Chromium session per Paseo workspace, shared live across every connected client.",
5
5
  "keywords": [
6
6
  "browser",
@@ -50,8 +50,8 @@
50
50
  "check:write": "biome check --write .",
51
51
  "typecheck": "tsc --noEmit",
52
52
  "prepare:runtime": "node scripts/prepare-runtime.mjs",
53
- "test": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
54
- "test:unit": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
53
+ "test": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-filter.test.ts tests/workspace-list.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
54
+ "test:unit": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-filter.test.ts tests/workspace-list.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
55
55
  "test:smoke": "vitest run tests/browser.smoke.test.ts tests/browser.drag-cancel.smoke.test.ts tests/xvfb.smoke.test.ts tests/browser.failed-open.smoke.test.ts tests/browser.background-tab.smoke.test.ts --testTimeout=30000",
56
56
  "test:tabs": "vitest run tests/browser-tabs.smoke.test.ts --testTimeout=30000",
57
57
  "test:video": "vitest run tests/video.smoke.test.ts --testTimeout=30000"
@@ -0,0 +1,42 @@
1
+ import type { WorkspaceRef } from "../shared/agent-access";
2
+
3
+ export const WORKSPACE_PAGE_SIZE = 200;
4
+ export const WORKSPACE_PAGE_LIMIT = 20;
5
+
6
+ interface WorkspacePage {
7
+ entries: readonly WorkspaceRef[];
8
+ pageInfo: { nextCursor?: string | null; hasMore: boolean };
9
+ }
10
+
11
+ export interface WorkspaceLister {
12
+ workspaces: {
13
+ list(options: {
14
+ filter: { includeBackground: true };
15
+ page: { limit: number; cursor?: string };
16
+ }): Promise<WorkspacePage>;
17
+ };
18
+ }
19
+
20
+ /**
21
+ * Every workspace the daemon knows, background ones included. An access decision made from a partial
22
+ * list could match a shallower workspace than the agent is really in, so a list that is still
23
+ * incomplete after the page limit is an error, and the caller counts it as a failed lookup.
24
+ */
25
+ export async function listAllWorkspaces(
26
+ paseo: WorkspaceLister,
27
+ pageLimit: number = WORKSPACE_PAGE_LIMIT,
28
+ ): Promise<WorkspaceRef[]> {
29
+ const workspaces: WorkspaceRef[] = [];
30
+ let cursor: string | undefined;
31
+ for (let page = 0; page < pageLimit; page += 1) {
32
+ const result = await paseo.workspaces.list({
33
+ filter: { includeBackground: true },
34
+ page: { limit: WORKSPACE_PAGE_SIZE, ...(cursor ? { cursor } : {}) },
35
+ });
36
+ workspaces.push(...result.entries);
37
+ if (!result.pageInfo.hasMore) return workspaces;
38
+ cursor = result.pageInfo.nextCursor ?? undefined;
39
+ if (!cursor) throw new Error("Workspace list reports more pages but gave no cursor");
40
+ }
41
+ throw new Error(`Workspace list is longer than ${pageLimit} pages`);
42
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Which new agents get the Shared Browser tool.
3
+ *
4
+ * "all" injects the adapter into every new agent (the behaviour before this setting existed, and the
5
+ * default). "listed" injects it only when the new agent matches an entry of one of three lists: its
6
+ * provider id, the id of its workspace, or the id of its workspace's project. An empty configuration
7
+ * means no agent. Agents that already exist are never changed.
8
+ *
9
+ * `agent.create` carries the provider and the working directory but no labels and no workspace id, so
10
+ * the workspace is found by matching the directory against the daemon's workspaces.
11
+ */
12
+ import { defineSettings } from "@getpaseo/plugin";
13
+ import { z } from "zod";
14
+
15
+ export const AGENT_ACCESS_MODES = ["all", "listed"] as const;
16
+ export type AgentAccessMode = (typeof AGENT_ACCESS_MODES)[number];
17
+
18
+ const MAX_ENTRIES = 200;
19
+ const MAX_ENTRY_LENGTH = 256;
20
+ const entries = z.array(z.string().min(1).max(MAX_ENTRY_LENGTH)).max(MAX_ENTRIES).default([]);
21
+
22
+ export const agentAccessSchema = z.object({
23
+ mode: z.enum(AGENT_ACCESS_MODES).default("all"),
24
+ providers: entries,
25
+ workspaces: entries,
26
+ projects: entries,
27
+ });
28
+
29
+ export type AgentAccess = z.output<typeof agentAccessSchema>;
30
+
31
+ export const agentAccessSettings = defineSettings({
32
+ id: "agent-access",
33
+ scope: "host",
34
+ version: 1,
35
+ schema: agentAccessSchema,
36
+ });
37
+
38
+ /** Used when the setting cannot be read or fails validation. */
39
+ export const DEFAULT_AGENT_ACCESS: AgentAccess = {
40
+ mode: "all",
41
+ providers: [],
42
+ workspaces: [],
43
+ projects: [],
44
+ };
45
+
46
+ export function accessFromState(
47
+ state: { status: "ready"; values: AgentAccess } | { status: string } | undefined,
48
+ ): AgentAccess {
49
+ return state?.status === "ready" && "values" in state ? state.values : DEFAULT_AGENT_ACCESS;
50
+ }
51
+
52
+ export interface NewAgent {
53
+ provider: string;
54
+ cwd: string;
55
+ }
56
+
57
+ export interface WorkspaceRef {
58
+ id: string;
59
+ projectId: string;
60
+ workspaceDirectory?: string | undefined;
61
+ }
62
+
63
+ /**
64
+ * A directory in one lexical canonical form: backslashes become slashes, repeated slashes collapse, and
65
+ * `.` and `..` segments resolve. An absolute path (a leading slash, or a drive such as `C:`) cannot
66
+ * climb above its root, which is `/` or `C:/`. It is the same idea as posix normalize, written out because
67
+ * shared code does not import Node modules. Nothing on disk is consulted: symlinks are not resolved and
68
+ * letter case is not folded.
69
+ */
70
+ export function normalizeDirectory(path: string): string {
71
+ const slashed = path.replace(/\\/g, "/");
72
+ const drive = /^[A-Za-z]:(?=\/|$)/.exec(slashed)?.[0] ?? "";
73
+ const rest = slashed.slice(drive.length);
74
+ const absolute = drive !== "" || rest.startsWith("/");
75
+ const kept: string[] = [];
76
+ for (const segment of rest.split("/")) {
77
+ if (segment === "" || segment === ".") continue;
78
+ if (segment !== "..") {
79
+ kept.push(segment);
80
+ } else if (kept.length > 0 && kept[kept.length - 1] !== "..") {
81
+ kept.pop();
82
+ } else if (!absolute) {
83
+ kept.push("..");
84
+ }
85
+ }
86
+ const joined = kept.join("/");
87
+ return absolute ? `${drive}/${joined}` : joined;
88
+ }
89
+
90
+ /**
91
+ * The workspaces whose directory is the agent's directory, or the deepest directory that contains it.
92
+ * Several workspaces can share one directory, so this returns all of them.
93
+ */
94
+ export function workspacesForDirectory(
95
+ cwd: string,
96
+ workspaces: readonly WorkspaceRef[],
97
+ ): WorkspaceRef[] {
98
+ const target = normalizeDirectory(cwd);
99
+ let depth = -1;
100
+ let found: WorkspaceRef[] = [];
101
+ for (const workspace of workspaces) {
102
+ if (!workspace.workspaceDirectory) continue;
103
+ const directory = normalizeDirectory(workspace.workspaceDirectory);
104
+ const prefix = directory.endsWith("/") ? directory : `${directory}/`;
105
+ if (target !== directory && !target.startsWith(prefix)) continue;
106
+ if (directory.length > depth) {
107
+ depth = directory.length;
108
+ found = [workspace];
109
+ } else if (directory.length === depth) {
110
+ found.push(workspace);
111
+ }
112
+ }
113
+ return found;
114
+ }
115
+
116
+ /**
117
+ * True when a new agent gets the browser tool. `listWorkspaces` is called only when a workspace or
118
+ * project is listed and the provider did not already match; if it throws, those lists do not match.
119
+ */
120
+ export async function agentGetsBrowser(
121
+ access: AgentAccess,
122
+ agent: NewAgent,
123
+ listWorkspaces: () => Promise<readonly WorkspaceRef[]>,
124
+ ): Promise<boolean> {
125
+ if (access.mode === "all") return true;
126
+ if (access.providers.includes(agent.provider)) return true;
127
+ if (access.workspaces.length === 0 && access.projects.length === 0) return false;
128
+ try {
129
+ return workspacesForDirectory(agent.cwd, await listWorkspaces()).some(
130
+ (workspace) =>
131
+ access.workspaces.includes(workspace.id) || access.projects.includes(workspace.projectId),
132
+ );
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ export const MAX_LIST_ENTRIES = MAX_ENTRIES;
139
+ export const MAX_LIST_ENTRY_LENGTH = MAX_ENTRY_LENGTH;
140
+
141
+ /**
142
+ * The comma or line separated names typed in the settings screen. Repeats are dropped. A name over the
143
+ * length limit or a list over the entry limit is reported in `error` instead of being cut off.
144
+ */
145
+ export function parseEntries(text: string): { entries: string[]; error: string | null } {
146
+ const entries: string[] = [];
147
+ for (const piece of text.split(/[,\n]/)) {
148
+ const name = piece.trim();
149
+ if (name === "") continue;
150
+ if (name.length > MAX_ENTRY_LENGTH) {
151
+ return {
152
+ entries: [],
153
+ error: `An entry is longer than ${MAX_ENTRY_LENGTH} characters: ${name.slice(0, 24)}...`,
154
+ };
155
+ }
156
+ if (!entries.includes(name)) entries.push(name);
157
+ }
158
+ if (entries.length > MAX_ENTRIES) {
159
+ return {
160
+ entries: [],
161
+ error: `A list can hold ${MAX_ENTRIES} entries; this one has ${entries.length}.`,
162
+ };
163
+ }
164
+ return { entries, error: null };
165
+ }