@myrialabs/clopen 0.4.23 → 0.4.24
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/backend/chat/stream-manager.ts +41 -13
- package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
- package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
- package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +8 -0
- package/backend/mcp/internal/servers/browser-automation/actions/types.ts +10 -0
- package/backend/mcp/internal/servers/browser-automation/context.ts +6 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +1 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +21 -1
- package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
- package/backend/module-shadowing.test.ts +135 -0
- package/backend/preview/browser/browser-host-bridge.ts +8 -2
- package/backend/preview/browser/browser-interaction-handler.ts +70 -0
- package/backend/preview/browser/browser-mcp-control.ts +247 -13
- package/backend/preview/browser/browser-preview-service.ts +146 -8
- package/backend/preview/browser/browser-video-capture.ts +551 -247
- package/backend/preview/browser/scripts/host-bridge.ts +61 -89
- package/backend/preview/browser/scripts/video-stream.ts +32 -0
- package/backend/preview/browser/types.ts +22 -0
- package/backend/preview/index.ts +6 -1
- package/backend/ws/preview/browser/interact.ts +16 -2
- package/backend/ws/preview/browser/native-ui.ts +22 -1
- package/backend/ws/preview/browser/tab-info.ts +20 -2
- package/backend/ws/preview/browser/webcodecs.ts +6 -1
- package/backend/ws/preview/index.ts +22 -0
- package/dist/assets/{index-DH_GO0Lf.js → index-CNDHpafl.js} +1 -1
- package/dist/assets/{index-igSQ3JaM.js → index-NF77n8kP.js} +1 -1
- package/dist/assets/{main-D-d8SFfW.js → main-BJ0PUVTW.js} +381 -376
- package/dist/assets/main-DSirC670.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/main-BD3-qPfT.css +0 -1
|
@@ -243,6 +243,22 @@ class StreamManager extends EventEmitter {
|
|
|
243
243
|
super();
|
|
244
244
|
// Increase max listeners for high concurrency
|
|
245
245
|
this.setMaxListeners(1000);
|
|
246
|
+
|
|
247
|
+
// MCP browser locks are scoped to a chat session, and every release path
|
|
248
|
+
// runs from this class. Teaching the lock manager how to check liveness
|
|
249
|
+
// closes the gap those paths can't: a tool call that lands after its
|
|
250
|
+
// stream ended used to be able to take a lock nothing would release.
|
|
251
|
+
browserMcpControl.setSessionLivenessProbe((chatSessionId) =>
|
|
252
|
+
this.isChatSessionStreaming(chatSessionId)
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Whether any stream for this chat session is still running. */
|
|
257
|
+
private isChatSessionStreaming(chatSessionId: string): boolean {
|
|
258
|
+
for (const stream of this.activeStreams.values()) {
|
|
259
|
+
if (stream.chatSessionId === chatSessionId && stream.status === 'active') return true;
|
|
260
|
+
}
|
|
261
|
+
return false;
|
|
246
262
|
}
|
|
247
263
|
|
|
248
264
|
/**
|
|
@@ -1302,6 +1318,27 @@ class StreamManager extends EventEmitter {
|
|
|
1302
1318
|
}
|
|
1303
1319
|
}
|
|
1304
1320
|
|
|
1321
|
+
// Abort first, then release the browser locks, and only then ask the
|
|
1322
|
+
// engine to stop.
|
|
1323
|
+
//
|
|
1324
|
+
// The order matters and used to be the other way round. `engine.cancel()`
|
|
1325
|
+
// is awaited for up to five seconds, and a browser-automation batch that
|
|
1326
|
+
// was mid-flight kept resolving its target tab throughout — re-acquiring
|
|
1327
|
+
// control of a tab moments after (or before) it was handed back, under a
|
|
1328
|
+
// chat session whose release had already run. That is the interrupt that
|
|
1329
|
+
// left the tab locked with nobody to unlock it. Aborting up front makes
|
|
1330
|
+
// the batch stop between actions, and releasing before the wait means
|
|
1331
|
+
// anything that slips through is refused rather than orphaned.
|
|
1332
|
+
if (!streamState.abortController?.signal.aborted) {
|
|
1333
|
+
streamState.abortController?.abort();
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// Auto-release all MCP-controlled tabs for this chat session
|
|
1337
|
+
if (streamState.chatSessionId) {
|
|
1338
|
+
browserMcpControl.releaseSession(streamState.chatSessionId);
|
|
1339
|
+
debug.log('mcp', `✅ Auto-released MCP tabs for session ${streamState.chatSessionId.slice(0, 8)} on stream cancellation`);
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1305
1342
|
// Cancel the per-project engine with a bounded timeout.
|
|
1306
1343
|
// engine.cancel() stops the SDK process (Claude Code: close() kills subprocess,
|
|
1307
1344
|
// OpenCode: aborts controller + HTTP abort to server). If cancel() hangs
|
|
@@ -1320,14 +1357,6 @@ class StreamManager extends EventEmitter {
|
|
|
1320
1357
|
debug.error('chat', 'Error cancelling engine (non-fatal):', error);
|
|
1321
1358
|
}
|
|
1322
1359
|
|
|
1323
|
-
// Abort the stream-manager's controller as a fallback.
|
|
1324
|
-
// engine.cancel() already aborts the same controller, so this is
|
|
1325
|
-
// typically a no-op but ensures cleanup if the engine timed out
|
|
1326
|
-
// or wasn't active.
|
|
1327
|
-
if (!streamState.abortController?.signal.aborted) {
|
|
1328
|
-
streamState.abortController?.abort();
|
|
1329
|
-
}
|
|
1330
|
-
|
|
1331
1360
|
this.emitStreamEvent(streamState, 'cancelled', {
|
|
1332
1361
|
processId: streamState.processId,
|
|
1333
1362
|
timestamp: streamState.completedAt.toISOString()
|
|
@@ -1335,11 +1364,10 @@ class StreamManager extends EventEmitter {
|
|
|
1335
1364
|
|
|
1336
1365
|
this.emitStreamLifecycle(streamState, 'cancelled', reason);
|
|
1337
1366
|
|
|
1338
|
-
//
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
}
|
|
1367
|
+
// Sweep again after the engine has actually stopped: a tool call still
|
|
1368
|
+
// in flight during the wait above may have taken a lock that its own
|
|
1369
|
+
// release path will never reach.
|
|
1370
|
+
browserMcpControl.releaseOrphans();
|
|
1343
1371
|
|
|
1344
1372
|
return true;
|
|
1345
1373
|
}
|
|
@@ -9,6 +9,7 @@ import { commonFields } from './shared';
|
|
|
9
9
|
export const consoleLogs: ActionDef = {
|
|
10
10
|
type: 'console_logs',
|
|
11
11
|
kind: 'control',
|
|
12
|
+
activity: 'Reading the console',
|
|
12
13
|
doc: `console_logs {limit?, level?} — the page's console output, oldest first.
|
|
13
14
|
Where to look when an action "worked" but the page did not react: the error is usually here and invisible on screen.`,
|
|
14
15
|
schema: z.object({
|
|
@@ -37,6 +38,7 @@ export const consoleLogs: ActionDef = {
|
|
|
37
38
|
export const clearConsole: ActionDef = {
|
|
38
39
|
type: 'clear_console',
|
|
39
40
|
kind: 'control',
|
|
41
|
+
activity: 'Clearing the console',
|
|
40
42
|
doc: `clear_console {} — drop stored console output.
|
|
41
43
|
Put this before the step you are debugging so what follows is only that step's output.`,
|
|
42
44
|
schema: z.object({ type: z.literal('clear_console'), ...commonFields }),
|
|
@@ -49,6 +51,7 @@ export const clearConsole: ActionDef = {
|
|
|
49
51
|
export const evaluate: ActionDef = {
|
|
50
52
|
type: 'eval',
|
|
51
53
|
kind: 'control',
|
|
54
|
+
activity: 'Running a script',
|
|
52
55
|
doc: `eval {expression} — run JavaScript in the page and return the result.
|
|
53
56
|
For state that is not in the DOM: computed styles, localStorage, framework internals, window globals. The result must be JSON-serialisable.`,
|
|
54
57
|
schema: z.object({
|
|
@@ -15,6 +15,7 @@ import { resolveWritePath } from '../paths';
|
|
|
15
15
|
export const find: ActionDef = {
|
|
16
16
|
type: 'find',
|
|
17
17
|
kind: 'control',
|
|
18
|
+
activity: 'Looking for an element',
|
|
18
19
|
doc: `find {selector?, text?, role?, limit?} — locate elements and get their positions.
|
|
19
20
|
Returns tag, text, a reusable selector and a centre point for each match, iframes included.
|
|
20
21
|
This is the cheap alternative to a screenshot: to click something you can name, find it and click by selector — no image, no vision, no coordinate guessing.`,
|
|
@@ -60,6 +61,7 @@ export const find: ActionDef = {
|
|
|
60
61
|
export const analyzeDom: ActionDef = {
|
|
61
62
|
type: 'analyze_dom',
|
|
62
63
|
kind: 'control',
|
|
64
|
+
activity: 'Reading the page',
|
|
63
65
|
doc: `analyze_dom {include?} — the page as text: links, headings, content, forms, metadata.
|
|
64
66
|
The primary tool for reading and exploring. Far cheaper than a screenshot and it sees the whole document, not just the part currently on screen — scrolling to "see more" is never necessary.
|
|
65
67
|
include: navigation | structure | content | forms | summary. Omit for all.
|
|
@@ -91,6 +93,7 @@ export const analyzeDom: ActionDef = {
|
|
|
91
93
|
export const screenshot: ActionDef = {
|
|
92
94
|
type: 'screenshot',
|
|
93
95
|
kind: 'control',
|
|
96
|
+
activity: 'Taking a screenshot',
|
|
94
97
|
doc: `screenshot {fullPage?, selector?, format?, quality?, saveTo?, return?} — capture the page.
|
|
95
98
|
Needed for what the DOM cannot express: canvases, charts, iframes, captchas, and any visual check of layout or styling.
|
|
96
99
|
saveTo writes a file under the project directory; with return:"file" the image is not sent back at all, which is what makes "capture twenty pages" affordable.
|
|
@@ -13,6 +13,7 @@ import { commonFields } from './shared';
|
|
|
13
13
|
export const navigate: ActionDef = {
|
|
14
14
|
type: 'navigate',
|
|
15
15
|
kind: 'control',
|
|
16
|
+
activity: 'Navigating',
|
|
16
17
|
doc: `navigate {url} — load a URL in the current tab.
|
|
17
18
|
Following a link you already have the href for is cheaper and far more reliable than clicking it. Session state (cookies, storage) is kept.`,
|
|
18
19
|
schema: z.object({
|
|
@@ -33,6 +34,7 @@ export const navigate: ActionDef = {
|
|
|
33
34
|
export const goBack: ActionDef = {
|
|
34
35
|
type: 'go_back',
|
|
35
36
|
kind: 'control',
|
|
37
|
+
activity: 'Going back',
|
|
36
38
|
doc: `go_back {steps?} — walk back through the tab's history.`,
|
|
37
39
|
schema: z.object({
|
|
38
40
|
type: z.literal('go_back'),
|
|
@@ -50,6 +52,7 @@ export const goBack: ActionDef = {
|
|
|
50
52
|
export const goForward: ActionDef = {
|
|
51
53
|
type: 'go_forward',
|
|
52
54
|
kind: 'control',
|
|
55
|
+
activity: 'Going forward',
|
|
53
56
|
doc: `go_forward {steps?} — walk forward through the tab's history.`,
|
|
54
57
|
schema: z.object({
|
|
55
58
|
type: z.literal('go_forward'),
|
|
@@ -67,6 +70,7 @@ export const goForward: ActionDef = {
|
|
|
67
70
|
export const reload: ActionDef = {
|
|
68
71
|
type: 'reload',
|
|
69
72
|
kind: 'control',
|
|
73
|
+
activity: 'Reloading',
|
|
70
74
|
doc: `reload {hard?} — reload the page. hard bypasses the cache.`,
|
|
71
75
|
schema: z.object({
|
|
72
76
|
type: z.literal('reload'),
|
|
@@ -87,6 +91,7 @@ export const reload: ActionDef = {
|
|
|
87
91
|
export const waitFor: ActionDef = {
|
|
88
92
|
type: 'wait_for',
|
|
89
93
|
kind: 'control',
|
|
94
|
+
activity: 'Waiting for the page',
|
|
90
95
|
doc: `wait_for {selector|text|urlContains|state, timeout?} — wait for the page to catch up.
|
|
91
96
|
Returns the moment the condition holds, so it costs only what it has to.
|
|
92
97
|
state: visible (default, with selector/text) · hidden · navigation · networkIdle.
|
|
@@ -28,6 +28,7 @@ function defaultRotation(deviceSize: string): 'portrait' | 'landscape' {
|
|
|
28
28
|
export const listTabs: ActionDef = {
|
|
29
29
|
type: 'list_tabs',
|
|
30
30
|
kind: 'control',
|
|
31
|
+
activity: 'Checking tabs',
|
|
31
32
|
doc: `list_tabs {} — every open tab with its id, URL, viewport and who controls it.
|
|
32
33
|
Use the id, not the position, with switch_tab/close_tab.`,
|
|
33
34
|
schema: z.object({ type: z.literal('list_tabs'), ...commonFields }),
|
|
@@ -53,6 +54,7 @@ export const listTabs: ActionDef = {
|
|
|
53
54
|
export const openTab: ActionDef = {
|
|
54
55
|
type: 'open_tab',
|
|
55
56
|
kind: 'control',
|
|
57
|
+
activity: 'Opening a tab',
|
|
56
58
|
doc: `open_tab {url?, deviceSize?, rotation?} — open a tab and make it the target.
|
|
57
59
|
deviceSize: desktop 1920×1080 · laptop 1440×900 (default) · tablet 834×1194 · mobile 402×874.
|
|
58
60
|
rotation defaults to landscape for desktop/laptop, portrait for tablet/mobile.`,
|
|
@@ -80,6 +82,7 @@ export const openTab: ActionDef = {
|
|
|
80
82
|
export const switchTab: ActionDef = {
|
|
81
83
|
type: 'switch_tab',
|
|
82
84
|
kind: 'control',
|
|
85
|
+
activity: 'Switching tab',
|
|
83
86
|
doc: `switch_tab {tabId} — make another tab the target of following actions.`,
|
|
84
87
|
schema: z.object({
|
|
85
88
|
type: z.literal('switch_tab'),
|
|
@@ -94,6 +97,9 @@ export const switchTab: ActionDef = {
|
|
|
94
97
|
if (tab) {
|
|
95
98
|
const acquired = browserMcpControl.acquireControl(tab.id, ctx.chatSessionId, ctx.projectId);
|
|
96
99
|
if (!acquired) {
|
|
100
|
+
if (!browserMcpControl.isSessionLive(ctx.chatSessionId)) {
|
|
101
|
+
throw new Error('This chat session is no longer running — the browser was released when it stopped.');
|
|
102
|
+
}
|
|
97
103
|
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
98
104
|
throw new Error(`Tab '${args.tabId}' is controlled by another chat session (${owner?.slice(0, 8)}...)`);
|
|
99
105
|
}
|
|
@@ -109,6 +115,7 @@ export const switchTab: ActionDef = {
|
|
|
109
115
|
export const closeTab: ActionDef = {
|
|
110
116
|
type: 'close_tab',
|
|
111
117
|
kind: 'control',
|
|
118
|
+
activity: 'Closing a tab',
|
|
112
119
|
doc: `close_tab {tabId?} — close a tab (default: the current one).`,
|
|
113
120
|
schema: z.object({
|
|
114
121
|
type: z.literal('close_tab'),
|
|
@@ -135,6 +142,7 @@ export const closeTab: ActionDef = {
|
|
|
135
142
|
export const setViewport: ActionDef = {
|
|
136
143
|
type: 'set_viewport',
|
|
137
144
|
kind: 'control',
|
|
145
|
+
activity: 'Changing the viewport',
|
|
138
146
|
doc: `set_viewport {deviceSize?, rotation?} — resize the current tab.
|
|
139
147
|
Changing this re-runs the page's media queries, so it is how responsive layouts get tested.`,
|
|
140
148
|
schema: z.object({
|
|
@@ -72,6 +72,16 @@ export interface ActionDef {
|
|
|
72
72
|
* what stops it from reading a `tab` that may be null.
|
|
73
73
|
*/
|
|
74
74
|
needsTab?: boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Two or three words for the caption beside the agent's cursor while this
|
|
77
|
+
* runs — "Navigating", "Taking a screenshot".
|
|
78
|
+
*
|
|
79
|
+
* Only `control` actions carry one. An `input` action's caption is written by
|
|
80
|
+
* the interaction handler from the gesture itself, which is the only place
|
|
81
|
+
* that knows whether a `type` is text or a keystroke, or a `click` is a right
|
|
82
|
+
* click — and the runner has already coalesced the group by then anyway.
|
|
83
|
+
*/
|
|
84
|
+
activity?: string;
|
|
75
85
|
/** `input` actions: translate to the native gesture primitive. */
|
|
76
86
|
toInput?: (args: any, ctx: ActionContext) => BrowserAutonomousAction | Promise<BrowserAutonomousAction>;
|
|
77
87
|
/** `control` actions: run directly. */
|
|
@@ -84,6 +84,12 @@ export async function getActiveTabSession(
|
|
|
84
84
|
if (existing) {
|
|
85
85
|
const acquired = browserMcpControl.acquireControl(existing.id, chatSessionId, resolvedProjectId);
|
|
86
86
|
if (!acquired) {
|
|
87
|
+
// Two very different refusals. Saying "another session" for both sent
|
|
88
|
+
// an agent looking for a tab conflict that does not exist, when what
|
|
89
|
+
// actually happened is that its own run was interrupted.
|
|
90
|
+
if (!browserMcpControl.isSessionLive(chatSessionId)) {
|
|
91
|
+
throw new Error('This chat session is no longer running — the browser was released when it stopped.');
|
|
92
|
+
}
|
|
87
93
|
const owner = browserMcpControl.getTabOwner(existing.id);
|
|
88
94
|
throw new Error(`Tab '${existing.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
|
|
89
95
|
}
|
|
@@ -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;
|
|
@@ -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,
|
|
@@ -382,6 +432,25 @@ export class BrowserInteractionHandler extends EventEmitter {
|
|
|
382
432
|
isValidSession: () => boolean
|
|
383
433
|
): Promise<AutonomousRunOutcome> {
|
|
384
434
|
const results: BrowserActionResult[] = [];
|
|
435
|
+
|
|
436
|
+
try {
|
|
437
|
+
return await this.runBatch(sessionId, session, actions, isValidSession, results);
|
|
438
|
+
} finally {
|
|
439
|
+
// The agent keeps the tab between batches, so the pointer stays — but
|
|
440
|
+
// it is no longer doing the last thing it said it was, and a caption
|
|
441
|
+
// left reading "Typing" over a page nothing is typing into is worse
|
|
442
|
+
// than no caption at all.
|
|
443
|
+
browserMcpControl.emitActivity(sessionId, null);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private async runBatch(
|
|
448
|
+
sessionId: string,
|
|
449
|
+
session: BrowserTab,
|
|
450
|
+
actions: BrowserAutonomousAction[],
|
|
451
|
+
isValidSession: () => boolean,
|
|
452
|
+
results: BrowserActionResult[]
|
|
453
|
+
): Promise<AutonomousRunOutcome> {
|
|
385
454
|
const page = session.page;
|
|
386
455
|
|
|
387
456
|
// Store session ID on page for cursor tracking
|
|
@@ -402,6 +471,7 @@ export class BrowserInteractionHandler extends EventEmitter {
|
|
|
402
471
|
}
|
|
403
472
|
|
|
404
473
|
const action = actions[i];
|
|
474
|
+
browserMcpControl.emitActivity(sessionId, this.describeActivity(action));
|
|
405
475
|
|
|
406
476
|
try {
|
|
407
477
|
const outcome = await this.runAction(sessionId, session, action);
|