@myrialabs/clopen 0.4.23 → 0.4.25

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.
Files changed (53) hide show
  1. package/backend/chat/stream-manager.ts +41 -13
  2. package/backend/engine/README.md +18 -0
  3. package/backend/engine/adapters/claude/message-converter.test.ts +36 -0
  4. package/backend/engine/adapters/claude/message-converter.ts +40 -4
  5. package/backend/engine/adapters/claude/stream.ts +68 -3
  6. package/backend/engine/adapters/claude/workflow-transcript.test.ts +65 -0
  7. package/backend/engine/adapters/claude/workflow-transcript.ts +248 -0
  8. package/backend/engine/adapters/coordination-tool-mapping.test.ts +17 -0
  9. package/backend/engine/adapters/copilot/message-converter.ts +20 -1
  10. package/backend/engine/adapters/opencode/message-converter.test.ts +80 -0
  11. package/backend/engine/adapters/opencode/message-converter.ts +32 -0
  12. package/backend/engine/adapters/opencode/stream.ts +29 -23
  13. package/backend/engine/adapters/qwen/message-converter.ts +5 -8
  14. package/backend/engine/docs/adapter-contract.md +29 -1
  15. package/backend/engine/docs/adding-an-engine.md +8 -1
  16. package/backend/engine/docs/frontend-and-chat.md +32 -1
  17. package/backend/engine/docs/lessons-learned.md +49 -2
  18. package/backend/engine/docs/quick-reference.md +2 -0
  19. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
  20. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +8 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +10 -0
  24. package/backend/mcp/internal/servers/browser-automation/context.ts +6 -0
  25. package/backend/mcp/internal/servers/browser-automation/description.ts +1 -1
  26. package/backend/mcp/internal/servers/browser-automation/runner.ts +21 -1
  27. package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
  28. package/backend/module-shadowing.test.ts +135 -0
  29. package/backend/preview/browser/browser-host-bridge.ts +8 -2
  30. package/backend/preview/browser/browser-interaction-handler.ts +95 -38
  31. package/backend/preview/browser/browser-mcp-control.ts +332 -22
  32. package/backend/preview/browser/browser-preview-service.ts +152 -33
  33. package/backend/preview/browser/browser-tab-manager.ts +25 -1
  34. package/backend/preview/browser/browser-video-capture.ts +551 -247
  35. package/backend/preview/browser/scripts/host-bridge.ts +61 -89
  36. package/backend/preview/browser/scripts/video-stream.ts +32 -0
  37. package/backend/preview/browser/types.ts +22 -0
  38. package/backend/preview/index.ts +6 -1
  39. package/backend/ws/preview/browser/console.ts +12 -10
  40. package/backend/ws/preview/browser/interact.ts +40 -10
  41. package/backend/ws/preview/browser/native-ui.ts +35 -10
  42. package/backend/ws/preview/browser/tab-info.ts +46 -7
  43. package/backend/ws/preview/browser/webcodecs.ts +6 -1
  44. package/backend/ws/preview/index.ts +23 -3
  45. package/dist/assets/{index-DH_GO0Lf.js → index-C4PD7B-x.js} +1 -1
  46. package/dist/assets/{index-igSQ3JaM.js → index-KBGloYDk.js} +1 -1
  47. package/dist/assets/{main-D-d8SFfW.js → main-B0AA-88X.js} +364 -358
  48. package/dist/assets/main-OsjA5Ab5.css +1 -0
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/unified/index.ts +7 -0
  52. package/shared/types/unified/tool.ts +57 -2
  53. package/dist/assets/main-BD3-qPfT.css +0 -1
@@ -7,7 +7,7 @@
7
7
  * is why it can never document an action that no longer exists.
8
8
  */
9
9
 
10
- import { ACTION_GROUPS } from './actions';
10
+ import { ACTION_GROUPS } from './actions/index';
11
11
 
12
12
  const PREAMBLE = `Drive the built-in preview browser: tabs, navigation, input, and reading the page.
13
13
 
@@ -20,9 +20,10 @@
20
20
  import type { BrowserAutonomousAction, BrowserTab } from '$backend/preview/browser/types';
21
21
  import { projectContextService } from '$backend/mcp/internal/project-context';
22
22
  import { debug } from '$shared/utils/logger';
23
- import { ACTIONS_BY_TYPE } from './actions';
23
+ import { ACTIONS_BY_TYPE } from './actions/index';
24
24
  import type { ActionContext, ActionImage, TablessActionContext } from './actions/types';
25
25
  import { getActiveTabSession, getPreviewService, peekSessionTab } from './context';
26
+ import { browserMcpControl } from '$backend/preview';
26
27
 
27
28
  interface ActionArgs {
28
29
  type: string;
@@ -179,11 +180,25 @@ async function runControl(item: { index: number; args: ActionArgs }, deps: RunDe
179
180
  return 1;
180
181
  }
181
182
 
183
+ // Remembered rather than re-read in the `finally`: `close_tab` and
184
+ // `switch_tab` change what the current tab is, and the caption has to be
185
+ // taken off the tab it was put on.
186
+ let labelled: string | null = null;
187
+
182
188
  try {
183
189
  // The tab actions run on an empty browser — they are how it stops being
184
190
  // empty. Everything else gets a tab opened for it first.
185
191
  const tab = def.needsTab === false ? deps.peekTab() : await deps.resolveTab();
186
192
 
193
+ // Say what is about to happen while it happens. Input gestures label
194
+ // themselves from inside the engine (see ActionDef.activity); a control
195
+ // action has no gesture, and is often the longest step in a batch — a
196
+ // 30-second `wait_for` with a silent cursor on it reads as a hang.
197
+ if (tab && def.activity) {
198
+ labelled = tab.id;
199
+ browserMcpControl.emitActivity(tab.id, def.activity);
200
+ }
201
+
187
202
  const output = await def.run(item.args, deps.makeContext(tab));
188
203
  report.steps.push({ index: item.index, type: def.type, ok: true, summary: output.summary, detail: output.detail });
189
204
  if (output.images?.length) report.images.push(...output.images);
@@ -191,6 +206,11 @@ async function runControl(item: { index: number; args: ActionArgs }, deps: RunDe
191
206
  const message = error instanceof Error ? error.message : 'Unknown error';
192
207
  debug.warn('mcp', `browser action ${item.args.type} failed: ${message}`);
193
208
  report.steps.push({ index: item.index, type: item.args.type, ok: false, error: message });
209
+ } finally {
210
+ // Back to a bare "Agent". The pointer stays for as long as the tab is
211
+ // held; only the caption is tied to a single action, and one left over
212
+ // from the last step describes a page that has already moved on.
213
+ if (labelled) browserMcpControl.emitActivity(labelled, null);
194
214
  }
195
215
 
196
216
  return 1;
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { z } from 'zod';
6
- import { ALL_ACTIONS } from './actions';
6
+ import { ALL_ACTIONS } from './actions/index';
7
7
 
8
8
  const members = ALL_ACTIONS.map((action) => action.schema) as unknown as [
9
9
  z.ZodObject<any>,
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Guards against a module being shadowed by a file an *older* release left behind.
3
+ *
4
+ * Package upgrades are not guaranteed to be clean. On Windows, `bun add -g` has
5
+ * been observed to overlay the new version onto the old install instead of
6
+ * replacing it, so a file that a previous release shipped can still be sitting
7
+ * on disk long after we deleted it from the repo.
8
+ *
9
+ * That is harmless until a deleted file's path is reused as a directory. Import
10
+ * resolution tries `./x.ts` before `./x/index.ts`, so `import … from './x'`
11
+ * silently binds to the leftover — and the user gets a SyntaxError naming a file
12
+ * that does not exist in the version they installed. v0.4.23 shipped exactly
13
+ * this: `browser-automation/actions.ts` became `browser-automation/actions/`,
14
+ * and anyone upgrading from ≤0.4.21 on Windows could not start Clopen at all.
15
+ *
16
+ * The fix in that case is to import the index explicitly (`./actions/index`),
17
+ * which no leftover file can shadow. This test finds the next one for us.
18
+ */
19
+
20
+ import { describe, expect, test } from 'bun:test';
21
+ import { existsSync, statSync } from 'node:fs';
22
+ import { dirname, extname, join, normalize, relative, resolve } from 'node:path';
23
+
24
+ const repoRoot = resolve(import.meta.dir, '..');
25
+
26
+ /** Directories we ship and therefore import from. */
27
+ const sourceRoots = ['backend', 'shared', 'frontend', 'bin', 'scripts'];
28
+
29
+ const aliases: Record<string, string> = {
30
+ $backend: 'backend',
31
+ $shared: 'shared',
32
+ $frontend: 'frontend'
33
+ };
34
+
35
+ const git = (...args: string[]) =>
36
+ Bun.spawnSync(['git', ...args], { cwd: repoRoot }).stdout.toString();
37
+
38
+ /**
39
+ * Every path git has ever seen deleted, which is the set of files that can be
40
+ * lingering in somebody's install. Needs full history — a shallow clone only
41
+ * knows about the last commit, so the answer would be a vacuous "none".
42
+ */
43
+ const deletedPaths = (): string[] =>
44
+ git('log', '--all', '--diff-filter=D', '--name-only', '--format=')
45
+ .split('\n')
46
+ .map((line) => line.trim())
47
+ .filter(Boolean);
48
+
49
+ const isDirectory = (path: string) => existsSync(path) && statSync(path).isDirectory();
50
+
51
+ /**
52
+ * A directory is shadowable when some earlier release shipped a file at the
53
+ * same path plus an extension, e.g. `actions/` against a deleted `actions.ts`.
54
+ */
55
+ const shadowableDirectories = (): Map<string, string> => {
56
+ const found = new Map<string, string>();
57
+
58
+ for (const path of deletedPaths()) {
59
+ const extension = extname(path);
60
+ if (!extension) continue;
61
+
62
+ const stem = path.slice(0, -extension.length);
63
+ const absolute = join(repoRoot, stem);
64
+
65
+ // Re-added under the same name? Then it is a file again, not a shadow.
66
+ if (existsSync(join(repoRoot, path))) continue;
67
+ if (!isDirectory(absolute)) continue;
68
+
69
+ found.set(stem, path);
70
+ }
71
+
72
+ return found;
73
+ };
74
+
75
+ const sourceFiles = async (): Promise<string[]> => {
76
+ const glob = new Bun.Glob('**/*.{ts,js,svelte,svelte.ts}');
77
+ const files: string[] = [];
78
+
79
+ for (const root of sourceRoots) {
80
+ if (!isDirectory(join(repoRoot, root))) continue;
81
+ for await (const file of glob.scan({ cwd: join(repoRoot, root), absolute: true })) {
82
+ files.push(file);
83
+ }
84
+ }
85
+
86
+ return files;
87
+ };
88
+
89
+ const SPECIFIER = /(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g;
90
+
91
+ /** Resolves a specifier to a repo-relative path, or null if it points elsewhere. */
92
+ const resolveSpecifier = (specifier: string, fromFile: string): string | null => {
93
+ if (specifier.startsWith('.')) {
94
+ return relative(repoRoot, resolve(dirname(fromFile), specifier));
95
+ }
96
+
97
+ const [head, ...rest] = specifier.split('/');
98
+ const aliased = aliases[head];
99
+ if (!aliased) return null;
100
+
101
+ return normalize(join(aliased, ...rest));
102
+ };
103
+
104
+ describe('module shadowing', () => {
105
+ test('no import can be captured by a file a previous release left behind', async () => {
106
+ if (git('rev-parse', '--is-shallow-repository').trim() === 'true') {
107
+ // CI checks out with fetch-depth: 0 so this only skips on shallow clones.
108
+ return;
109
+ }
110
+
111
+ const shadowable = shadowableDirectories();
112
+ if (shadowable.size === 0) return;
113
+
114
+ const violations: string[] = [];
115
+
116
+ for (const file of await sourceFiles()) {
117
+ const contents = await Bun.file(file).text();
118
+
119
+ for (const [, specifier] of contents.matchAll(SPECIFIER)) {
120
+ const target = resolveSpecifier(specifier, file);
121
+ if (!target) continue;
122
+
123
+ const shadowedBy = shadowable.get(target);
124
+ if (!shadowedBy) continue;
125
+
126
+ violations.push(
127
+ `${relative(repoRoot, file)}: '${specifier}' resolves to ${target}/, ` +
128
+ `which a stale ${shadowedBy} would shadow — import '${specifier}/index' instead`
129
+ );
130
+ }
131
+ }
132
+
133
+ expect(violations).toEqual([]);
134
+ });
135
+ });
@@ -42,7 +42,11 @@ export type HostRequestKind =
42
42
  // Not a capability and never shown to anyone: the page reporting that Chrome
43
43
  // resized the renderer behind the emulation's back, so the host can put the
44
44
  // viewport it captures from back the way it was. Answered by the service.
45
- | 'viewport-restore';
45
+ | 'viewport-restore'
46
+ // Also not a capability: the page telling the host it is (or is no longer)
47
+ // showing something full screen, so the viewer can offer a way out that the
48
+ // page cannot lose. Answered by the service.
49
+ | 'fullscreen-state';
46
50
 
47
51
  export interface HostRequestEvent {
48
52
  tabId: string;
@@ -112,7 +116,9 @@ const REQUEST_TIMEOUT_MS: Record<HostRequestKind, number> = {
112
116
  'file-pick': 300_000,
113
117
  // Nobody is asked anything — this is the host talking to itself, and the page
114
118
  // is blocked on it while a screencast restarts.
115
- 'viewport-restore': 15_000
119
+ 'viewport-restore': 15_000,
120
+ // A one-way notification; the page does not wait on the answer.
121
+ 'fullscreen-state': 5_000
116
122
  };
117
123
 
118
124
  /**
@@ -78,6 +78,56 @@ export class BrowserInteractionHandler extends EventEmitter {
78
78
  browserMcpControl.emitCursorClick(sessionId, x, y, button);
79
79
  }
80
80
 
81
+ /**
82
+ * A few words for the caption beside the agent's pointer.
83
+ *
84
+ * Written from the watcher's side of the screen, not the agent's: it answers
85
+ * "what is happening to my page right now", so it names the gesture rather
86
+ * than the action type, and never carries a selector or the text being typed
87
+ * — a password would end up on screen, and the caption has room for about
88
+ * three words before it stops being a caption.
89
+ */
90
+ private describeActivity(action: BrowserAutonomousAction): string {
91
+ switch (action.type) {
92
+ case 'click':
93
+ return action.button === 'right' ? 'Opening a menu' : 'Clicking';
94
+ case 'long_press':
95
+ return 'Holding';
96
+ case 'move':
97
+ return 'Moving';
98
+ case 'drag':
99
+ return 'Dragging';
100
+ case 'scroll':
101
+ return 'Scrolling';
102
+ case 'type':
103
+ return action.text !== undefined ? 'Typing' : 'Pressing a key';
104
+ case 'press':
105
+ return `Pressing ${action.keys || action.key}`;
106
+ case 'paste':
107
+ return 'Pasting';
108
+ case 'focus':
109
+ return 'Selecting a field';
110
+ case 'clear':
111
+ return 'Clearing a field';
112
+ case 'select_option':
113
+ return 'Choosing an option';
114
+ case 'upload':
115
+ return 'Attaching a file';
116
+ case 'tap':
117
+ return 'Tapping';
118
+ case 'swipe':
119
+ return 'Swiping';
120
+ case 'pinch':
121
+ return 'Zooming';
122
+ case 'extract_data':
123
+ return 'Reading the page';
124
+ case 'wait':
125
+ return 'Waiting';
126
+ default:
127
+ return 'Working';
128
+ }
129
+ }
130
+
81
131
  // MCP-optimized mouse movement with smooth curves and ease-out easing
82
132
  private async mcpMouseMove(
83
133
  page: Page,
@@ -146,6 +196,20 @@ export class BrowserInteractionHandler extends EventEmitter {
146
196
  this.sessionCursorPositions.set(sessionId, position);
147
197
  }
148
198
 
199
+ /**
200
+ * Where the agent's pointer stands on a tab, if it has ever moved there.
201
+ *
202
+ * Read when a viewer builds its state from scratch — a page reload, a
203
+ * project switch, a colleague opening the panel halfway through a run. The
204
+ * pointer only sends updates while it is moving, so without this a viewer
205
+ * that joins between two actions has a lock, a caption, and no idea where
206
+ * on the page any of it is happening.
207
+ */
208
+ public getCursorPosition(sessionId: string): { x: number; y: number } | null {
209
+ const stored = this.sessionCursorPositions.get(sessionId);
210
+ return stored ? { ...stored } : null;
211
+ }
212
+
149
213
  // Clear cursor position for session (when session ends)
150
214
  public clearSessionCursor(sessionId: string) {
151
215
  this.sessionCursorPositions.delete(sessionId);
@@ -238,30 +302,6 @@ export class BrowserInteractionHandler extends EventEmitter {
238
302
  this.publishCursor(sessionId, to.x, to.y);
239
303
  }
240
304
 
241
- /**
242
- * Point the overlay at whatever an action is about to act on.
243
- *
244
- * Resolution failure is swallowed: this is telemetry, and the action itself
245
- * is about to resolve the same target and report the real error.
246
- */
247
- private async showTarget(
248
- sessionId: string,
249
- page: Page,
250
- action: BrowserAutonomousAction,
251
- target: BrowserActionTarget | undefined,
252
- opts: { pulse?: boolean } = {}
253
- ) {
254
- if (!target) return;
255
-
256
- try {
257
- const point = await resolveTarget(page, target, { scrollIntoView: !action.noScroll });
258
- await this.glideOverlay(sessionId, point);
259
- if (opts.pulse) this.publishClick(sessionId, point.x, point.y);
260
- } catch {
261
- // Nothing to point at — the action's own resolve will say why.
262
- }
263
- }
264
-
265
305
  /**
266
306
  * The same, for an element the action has already resolved. Preferred where
267
307
  * a handle is at hand: re-resolving the target would sweep every frame a
@@ -382,6 +422,25 @@ export class BrowserInteractionHandler extends EventEmitter {
382
422
  isValidSession: () => boolean
383
423
  ): Promise<AutonomousRunOutcome> {
384
424
  const results: BrowserActionResult[] = [];
425
+
426
+ try {
427
+ return await this.runBatch(sessionId, session, actions, isValidSession, results);
428
+ } finally {
429
+ // The agent keeps the tab between batches, so the pointer stays — but
430
+ // it is no longer doing the last thing it said it was, and a caption
431
+ // left reading "Typing" over a page nothing is typing into is worse
432
+ // than no caption at all.
433
+ browserMcpControl.emitActivity(sessionId, null);
434
+ }
435
+ }
436
+
437
+ private async runBatch(
438
+ sessionId: string,
439
+ session: BrowserTab,
440
+ actions: BrowserAutonomousAction[],
441
+ isValidSession: () => boolean,
442
+ results: BrowserActionResult[]
443
+ ): Promise<AutonomousRunOutcome> {
385
444
  const page = session.page;
386
445
 
387
446
  // Store session ID on page for cursor tracking
@@ -402,6 +461,7 @@ export class BrowserInteractionHandler extends EventEmitter {
402
461
  }
403
462
 
404
463
  const action = actions[i];
464
+ browserMcpControl.emitActivity(sessionId, this.describeActivity(action));
405
465
 
406
466
  try {
407
467
  const outcome = await this.runAction(sessionId, session, action);
@@ -438,15 +498,12 @@ export class BrowserInteractionHandler extends EventEmitter {
438
498
  }
439
499
  }
440
500
 
441
- // Emit test completed event to hide virtual cursor
442
- this.emit('test-completed', {
443
- sessionId: session.id,
444
- timestamp: Date.now(),
445
- // Part of the wire contract for this event; without it the payload
446
- // fails the shape the client is typed against.
447
- source: 'mcp'
448
- });
449
-
501
+ // Nothing is announced at the end of a batch. The agent still holds the
502
+ // tab between batches, so "this batch finished" says nothing about
503
+ // whether the pointer belongs on screen — that follows from the lock,
504
+ // and only from the lock. The event that used to be emitted here fired
505
+ // per tool call, so anything wired to it took the pointer away in the
506
+ // middle of a run that was still going.
450
507
  return { results, aborted: false };
451
508
  }
452
509
 
@@ -466,11 +523,11 @@ export class BrowserInteractionHandler extends EventEmitter {
466
523
  const identifier = action.selector ?? action.target?.selector;
467
524
  if (!identifier) throw new Error('extract_data needs a selector');
468
525
 
469
- // Overlay only, and no pulse: a read is not a click, and driving the
470
- // real pointer over the element could fire the hover handlers that
471
- // change what is about to be read.
472
- await this.showTarget(sessionId, session.page, action, { selector: identifier });
473
-
526
+ // No pointer movement at all: a person reading something on screen
527
+ // does not walk their mouse over to it first, they just look — the
528
+ // caption already says "Reading the page", which is the only signal
529
+ // this needs. Moving the overlay here would also risk firing hover
530
+ // handlers that change what is about to be read.
474
531
  const extracted = await this.extractData(session.page, identifier, action.attribute, action.all);
475
532
  if (extracted.error) throw new Error(extracted.error);
476
533