@myrialabs/clopen 0.4.22 → 0.4.23

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.
@@ -5,12 +5,16 @@
5
5
  * calls `ctx.invalidateTab()` — without it a batch like
6
6
  * `[open_tab, navigate, screenshot]` would open a tab and then keep driving the
7
7
  * old one.
8
+ *
9
+ * Everything here except `set_viewport` is `needsTab: false`: these are the
10
+ * actions an empty browser has to be able to run, so they must not be gated on
11
+ * a tab already existing.
8
12
  */
9
13
 
10
14
  import { z } from 'zod';
11
15
  import { browserMcpControl } from '$backend/preview';
12
16
  import { debug } from '$shared/utils/logger';
13
- import type { ActionDef } from './types';
17
+ import type { ActionDef, TablessActionContext } from './types';
14
18
  import { commonFields } from './shared';
15
19
 
16
20
  const DEVICE_SIZES = ['desktop', 'laptop', 'tablet', 'mobile'] as const;
@@ -27,7 +31,8 @@ export const listTabs: ActionDef = {
27
31
  doc: `list_tabs {} — every open tab with its id, URL, viewport and who controls it.
28
32
  Use the id, not the position, with switch_tab/close_tab.`,
29
33
  schema: z.object({ type: z.literal('list_tabs'), ...commonFields }),
30
- run: async (_args, ctx) => {
34
+ needsTab: false,
35
+ run: async (_args, ctx: TablessActionContext) => {
31
36
  const tabs = ctx.service.getAllTabs();
32
37
  if (tabs.length === 0) return { summary: 'no tabs open' };
33
38
 
@@ -58,7 +63,8 @@ export const openTab: ActionDef = {
58
63
  rotation: z.enum(ROTATIONS).optional().describe('Orientation. Omit for the device default.'),
59
64
  ...commonFields
60
65
  }),
61
- run: async (args, ctx) => {
66
+ needsTab: false,
67
+ run: async (args, ctx: TablessActionContext) => {
62
68
  const deviceSize = args.deviceSize || 'laptop';
63
69
  const rotation = args.rotation || defaultRotation(deviceSize);
64
70
 
@@ -80,7 +86,8 @@ export const switchTab: ActionDef = {
80
86
  tabId: z.string().min(1).describe('Tab id from list_tabs.'),
81
87
  ...commonFields
82
88
  }),
83
- run: async (args, ctx) => {
89
+ needsTab: false,
90
+ run: async (args, ctx: TablessActionContext) => {
84
91
  if (!ctx.service.switchTab(args.tabId)) throw new Error(`Tab '${args.tabId}' not found`);
85
92
 
86
93
  const tab = ctx.service.getTab(args.tabId);
@@ -108,8 +115,12 @@ export const closeTab: ActionDef = {
108
115
  tabId: z.string().optional().describe('Tab id from list_tabs. Omit to close the current tab.'),
109
116
  ...commonFields
110
117
  }),
111
- run: async (args, ctx) => {
112
- const tabId = args.tabId || ctx.tab.id;
118
+ // Closing is the one thing an empty browser cannot do — and opening a tab
119
+ // just to close it would be a strange way to find that out.
120
+ needsTab: false,
121
+ run: async (args, ctx: TablessActionContext) => {
122
+ const tabId = args.tabId || ctx.tab?.id;
123
+ if (!tabId) throw new Error('No open tab to close');
113
124
  const result = await ctx.service.closeTab(tabId);
114
125
  if (!result.success) throw new Error(`Tab '${tabId}' not found`);
115
126
 
@@ -26,6 +26,13 @@ export interface ActionContext {
26
26
  invalidateTab(): void;
27
27
  }
28
28
 
29
+ /**
30
+ * What a `needsTab: false` action gets: the same context, minus the guarantee
31
+ * that a tab exists. `tab` is whatever the batch was last pointed at, or null
32
+ * when the project has nothing open.
33
+ */
34
+ export type TablessActionContext = Omit<ActionContext, 'tab'> & { tab: BrowserTab | null };
35
+
29
36
  export interface ActionImage {
30
37
  data: string;
31
38
  mimeType: string;
@@ -56,6 +63,15 @@ export interface ActionDef {
56
63
  doc: string;
57
64
  /** Zod object whose `type` field is the discriminator. */
58
65
  schema: z.ZodObject<any>;
66
+ /**
67
+ * `false` for the actions that have to work on an empty browser — the ones
68
+ * that open or enumerate tabs. Everything else gets a tab opened for it
69
+ * before it runs, so a batch never has to start with `open_tab`.
70
+ *
71
+ * Such an action must declare its context as `TablessActionContext`: that is
72
+ * what stops it from reading a `tab` that may be null.
73
+ */
74
+ needsTab?: boolean;
59
75
  /** `input` actions: translate to the native gesture primitive. */
60
76
  toInput?: (args: any, ctx: ActionContext) => BrowserAutonomousAction | Promise<BrowserAutonomousAction>;
61
77
  /** `control` actions: run directly. */
@@ -46,37 +46,55 @@ export function getChatSessionId(): string {
46
46
  }
47
47
 
48
48
  /**
49
- * The tab this call should act on, with MCP control acquired for it.
49
+ * Which tab the batch is pointed at right now, or null when nothing is open.
50
50
  *
51
51
  * A chat session accumulates tabs (open/switch add to its set), and the most
52
52
  * recently used one is the target — not the frontend's active tab, which the
53
53
  * user may have changed while the agent was working.
54
+ *
55
+ * Takes no control and opens nothing, so it is safe for actions that only want
56
+ * to know where things stand.
54
57
  */
55
- export async function getActiveTabSession(projectId?: string): Promise<{ tab: BrowserTab; service: BrowserPreviewService }> {
56
- const service = getPreviewService(projectId);
57
- const resolvedProjectId = service.getProjectId();
58
- const chatSessionId = getChatSessionId();
59
-
58
+ export function peekSessionTab(service: BrowserPreviewService, chatSessionId: string): BrowserTab | null {
60
59
  const sessionTabs = browserMcpControl.getSessionTabs(chatSessionId);
61
60
  if (sessionTabs.length > 0) {
62
61
  const lastTabId = sessionTabs[sessionTabs.length - 1];
63
62
  const controlledTab = service.getTab(lastTabId);
64
- if (controlledTab) {
65
- debug.log('mcp', `🎮 Using session-controlled tab: ${controlledTab.id}`);
66
- return { tab: controlledTab, service };
67
- }
63
+ if (controlledTab) return controlledTab;
68
64
  }
69
65
 
70
- const tab = service.getActiveTab();
71
- if (!tab) {
72
- throw new Error("No open tab. Start with an `open_tab` action.");
73
- }
66
+ return service.getActiveTab();
67
+ }
68
+
69
+ /**
70
+ * The tab this call should act on, with MCP control acquired for it.
71
+ *
72
+ * Opens one when the project has none. Failing instead was a dead end: a fresh
73
+ * browser has no tab, so the first call failed no matter what it asked for, and
74
+ * the only way out was for someone to open a tab by hand in the UI.
75
+ */
76
+ export async function getActiveTabSession(
77
+ projectId?: string
78
+ ): Promise<{ tab: BrowserTab; service: BrowserPreviewService; opened: boolean }> {
79
+ const service = getPreviewService(projectId);
80
+ const resolvedProjectId = service.getProjectId();
81
+ const chatSessionId = getChatSessionId();
74
82
 
75
- const acquired = browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
76
- if (!acquired) {
77
- const owner = browserMcpControl.getTabOwner(tab.id);
78
- throw new Error(`Tab '${tab.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
83
+ const existing = peekSessionTab(service, chatSessionId);
84
+ if (existing) {
85
+ const acquired = browserMcpControl.acquireControl(existing.id, chatSessionId, resolvedProjectId);
86
+ if (!acquired) {
87
+ const owner = browserMcpControl.getTabOwner(existing.id);
88
+ throw new Error(`Tab '${existing.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
89
+ }
90
+
91
+ debug.log('mcp', `🎮 Using tab: ${existing.id}`);
92
+ return { tab: existing, service, opened: false };
79
93
  }
80
94
 
81
- return { tab, service };
95
+ debug.log('mcp', `📑 No tab open for project ${resolvedProjectId} — opening a blank one`);
96
+ const tab = await service.createTab(undefined, 'laptop', 'landscape');
97
+ browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
98
+
99
+ return { tab, service, opened: true };
82
100
  }
@@ -45,6 +45,7 @@ const OUTRO = `NOTES
45
45
  - Coordinates are in the page's own viewport (CSS pixels), the same space a screenshot is captured in.
46
46
  - Selectors are searched in every frame, so an element inside an iframe is addressed the same way as one in the main document.
47
47
  - A tab opened, switched to or closed mid-batch becomes the target for the actions that follow it.
48
+ - You never have to open a tab first. On an empty browser the first action that needs a tab gets a blank one opened for it, and the report says so — \`navigate\` alone is a fine way to start.
48
49
  - The user can interrupt at any time; the batch stops and the report says how far it got.`;
49
50
 
50
51
  function renderReference(): string {
@@ -23,6 +23,12 @@ export function formatReport(report: RunReport): {
23
23
 
24
24
  const lines: string[] = [header.join(' · ')];
25
25
 
26
+ // Say it plainly: the agent asked for one thing and got a tab it never
27
+ // requested, and the blank page is why a screenshot may look empty.
28
+ if (report.openedTabId) {
29
+ lines.push(`No tab was open, so ${report.openedTabId} was opened (about:blank) for this batch.`);
30
+ }
31
+
26
32
  for (const step of report.steps) {
27
33
  const label = `[${step.index + 1}] ${step.type}`;
28
34
  lines.push(step.ok ? `${label} ok${step.summary ? ` → ${step.summary}` : ''}` : `${label} FAILED → ${step.error}`);
@@ -17,12 +17,12 @@
17
17
  * the agent then plans on top of a state that does not exist.
18
18
  */
19
19
 
20
- import type { BrowserAutonomousAction } from '$backend/preview/browser/types';
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
23
  import { ACTIONS_BY_TYPE } from './actions';
24
- import type { ActionContext, ActionImage } from './actions/types';
25
- import { getActiveTabSession, getPreviewService } from './context';
24
+ import type { ActionContext, ActionImage, TablessActionContext } from './actions/types';
25
+ import { getActiveTabSession, getPreviewService, peekSessionTab } from './context';
26
26
 
27
27
  interface ActionArgs {
28
28
  type: string;
@@ -54,6 +54,8 @@ export interface RunReport {
54
54
  failed: boolean;
55
55
  tabId?: string;
56
56
  url?: string;
57
+ /** Set when the batch had to open a tab because the browser had none. */
58
+ openedTabId?: string;
57
59
  }
58
60
 
59
61
  /** Consecutive input gestures form one native run; control actions stand alone. */
@@ -79,20 +81,38 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
79
81
  const signal = projectContextService.getCurrentSignal();
80
82
  const service = getPreviewService(args.projectId);
81
83
  const projectId = service.getProjectId();
84
+ const chatSessionId = projectContextService.getCurrentChatSessionId() ?? '';
82
85
 
83
86
  const report: RunReport = { steps: [], images: [], skipped: 0, aborted: false, failed: false };
84
87
 
85
88
  let tabStale = true;
86
- let tab: Awaited<ReturnType<typeof getActiveTabSession>>['tab'] | null = null;
89
+ let tab: BrowserTab | null = null;
87
90
 
91
+ /** The tab to act on — opened on the spot if the browser has none. */
88
92
  const resolveTab = async () => {
89
93
  if (!tabStale && tab) return tab;
90
94
  const resolved = await getActiveTabSession(args.projectId);
95
+ if (resolved.opened) report.openedTabId = resolved.tab.id;
91
96
  tab = resolved.tab;
92
97
  tabStale = false;
93
98
  return tab;
94
99
  };
95
100
 
101
+ /** Where the batch stands, without opening anything or taking control. */
102
+ const peekTab = () => (!tabStale && tab ? tab : peekSessionTab(service, chatSessionId));
103
+
104
+ // `needsTab: false` actions declare their context as TablessActionContext,
105
+ // so the null this can carry never reaches one that dereferences it.
106
+ const makeContext = (target: BrowserTab | null): ActionContext =>
107
+ ({
108
+ service,
109
+ tab: target,
110
+ projectId,
111
+ chatSessionId,
112
+ signal,
113
+ invalidateTab: () => (tabStale = true)
114
+ } satisfies TablessActionContext as ActionContext);
115
+
96
116
  const groups = groupActions(args.actions);
97
117
  let stopped = false;
98
118
  let consumed = 0;
@@ -104,7 +124,7 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
104
124
  for (const group of groups) {
105
125
  if (stopped || signal?.aborted) break;
106
126
 
107
- const deps: RunDeps = { args, service, projectId, signal, resolveTab, markTabStale: () => (tabStale = true) };
127
+ const deps: RunDeps = { args, service, signal, resolveTab, peekTab, makeContext };
108
128
  const before = report.steps.length;
109
129
 
110
130
  consumed += group.kind === 'input'
@@ -127,12 +147,14 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
127
147
 
128
148
  // Report where the batch left the browser: the next call's plan depends on
129
149
  // it, and it is the cheapest way to notice a navigation nobody asked for.
150
+ // Peeked, not resolved: a batch that closed its last tab should say so, not
151
+ // get a fresh one opened just to have something to report.
130
152
  try {
131
- // Through the resolver, not the cached handle: a tab opened or closed
132
- // mid-batch means the cached one is no longer where the agent is.
133
- const current = await resolveTab();
134
- report.tabId = current.id;
135
- report.url = current.page.url();
153
+ const current = peekTab();
154
+ if (current) {
155
+ report.tabId = current.id;
156
+ report.url = current.page.url();
157
+ }
136
158
  } catch {
137
159
  // No tab left (closed by the batch, or none was ever open).
138
160
  }
@@ -143,10 +165,10 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
143
165
  interface RunDeps {
144
166
  args: RunArgs;
145
167
  service: ReturnType<typeof getPreviewService>;
146
- projectId: string;
147
168
  signal?: AbortSignal;
148
- resolveTab: () => Promise<NonNullable<Awaited<ReturnType<typeof getActiveTabSession>>['tab']>>;
149
- markTabStale: () => void;
169
+ resolveTab: () => Promise<BrowserTab>;
170
+ peekTab: () => BrowserTab | null;
171
+ makeContext: (target: BrowserTab | null) => ActionContext;
150
172
  }
151
173
 
152
174
  /** Run one control action. Returns how many actions were consumed. */
@@ -158,17 +180,11 @@ async function runControl(item: { index: number; args: ActionArgs }, deps: RunDe
158
180
  }
159
181
 
160
182
  try {
161
- const tab = await deps.resolveTab();
162
- const ctx: ActionContext = {
163
- service: deps.service,
164
- tab,
165
- projectId: deps.projectId,
166
- chatSessionId: projectContextService.getCurrentChatSessionId() ?? '',
167
- signal: deps.signal,
168
- invalidateTab: deps.markTabStale
169
- };
170
-
171
- const output = await def.run(item.args, ctx);
183
+ // The tab actions run on an empty browser — they are how it stops being
184
+ // empty. Everything else gets a tab opened for it first.
185
+ const tab = def.needsTab === false ? deps.peekTab() : await deps.resolveTab();
186
+
187
+ const output = await def.run(item.args, deps.makeContext(tab));
172
188
  report.steps.push({ index: item.index, type: def.type, ok: true, summary: output.summary, detail: output.detail });
173
189
  if (output.images?.length) report.images.push(...output.images);
174
190
  } catch (error) {
@@ -196,14 +212,7 @@ async function runInputGroup(items: Array<{ index: number; args: ActionArgs }>,
196
212
  return 1;
197
213
  }
198
214
 
199
- const ctx: ActionContext = {
200
- service: deps.service,
201
- tab,
202
- projectId: deps.projectId,
203
- chatSessionId: projectContextService.getCurrentChatSessionId() ?? '',
204
- signal: deps.signal,
205
- invalidateTab: deps.markTabStale
206
- };
215
+ const ctx = deps.makeContext(tab);
207
216
 
208
217
  // Translation can fail on its own (a path outside the project, a missing
209
218
  // field). Those actions never reach the engine, so they are reported here
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.4.22",
3
+ "version": "0.4.23",
4
4
  "description": "All-in-one web workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, and Cursor — with chat, terminal, git, browser preview, database client, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",