@myrialabs/clopen 0.4.21 → 0.4.22
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 +2 -1
- package/backend/artifacts/generate.ts +11 -5
- package/backend/auth/permissions.ts +8 -8
- package/backend/engine/README.md +11 -8
- package/backend/engine/adapters/codex/error-handler.ts +1 -1
- package/backend/engine/adapters/qwen/error-handler.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +66 -2
- package/backend/engine/docs/adding-an-engine.md +46 -7
- package/backend/engine/docs/frontend-and-chat.md +80 -17
- package/backend/engine/docs/lessons-learned.md +126 -7
- package/backend/engine/docs/quick-reference.md +12 -3
- package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
- package/backend/engine/docs/websocket-routes.md +54 -15
- package/backend/engine/install-runner.ts +4 -4
- package/backend/engine/resolve-model.ts +87 -0
- package/backend/engine/structured-helpers.test.ts +64 -0
- package/backend/engine/structured-helpers.ts +105 -13
- package/backend/mcp/README.md +32 -11
- package/backend/mcp/internal/config.ts +3 -20
- package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
- package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
- package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
- package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
- package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
- package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
- package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
- package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
- package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
- package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
- package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
- package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
- package/backend/preview/browser/browser-console-manager.ts +310 -156
- package/backend/preview/browser/browser-dialog-handler.ts +45 -16
- package/backend/preview/browser/browser-host-bridge.ts +471 -0
- package/backend/preview/browser/browser-interaction-handler.ts +868 -297
- package/backend/preview/browser/browser-mcp-control.ts +7 -2
- package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
- package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
- package/backend/preview/browser/browser-pool.ts +83 -9
- package/backend/preview/browser/browser-preview-service.ts +432 -53
- package/backend/preview/browser/browser-tab-manager.ts +16 -16
- package/backend/preview/browser/browser-video-capture.ts +1334 -386
- package/backend/preview/browser/capture-profile.ts +213 -0
- package/backend/preview/browser/element-locator.ts +357 -0
- package/backend/preview/browser/frame-targeting.ts +92 -0
- package/backend/preview/browser/scripts/audio-stream.ts +258 -78
- package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
- package/backend/preview/browser/scripts/video-stream.ts +803 -177
- package/backend/preview/browser/types.ts +397 -37
- package/backend/utils/cli.ts +1 -1
- package/backend/utils/path-enrich.ts +2 -2
- package/backend/ws/README.md +1 -1
- package/backend/ws/artifacts/generate.ts +2 -1
- package/backend/ws/engine/codex/accounts.ts +1 -1
- package/backend/ws/engine/codex/status.ts +1 -1
- package/backend/ws/git/branch-name.ts +11 -5
- package/backend/ws/git/commit-message.ts +11 -5
- package/backend/ws/index.ts +3 -3
- package/backend/ws/preview/browser/host.ts +95 -0
- package/backend/ws/preview/browser/interact.ts +204 -10
- package/backend/ws/preview/browser/native-ui.ts +31 -1
- package/backend/ws/preview/browser/tab-info.ts +10 -1
- package/backend/ws/preview/browser/tab.ts +43 -0
- package/backend/ws/preview/browser/webcodecs.ts +180 -53
- package/backend/ws/preview/index.ts +58 -1
- package/backend/ws/{system-tools → stack}/access.ts +1 -1
- package/backend/ws/stack/index.ts +16 -0
- package/backend/ws/{system-tools → stack}/install.ts +7 -7
- package/backend/ws/{system-tools → stack}/status.ts +7 -7
- package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
- package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
- package/dist/assets/main-BD3-qPfT.css +1 -0
- package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
- package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +6 -0
- package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
- package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
- package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
- package/backend/ws/system-tools/index.ts +0 -16
- package/dist/assets/main-D8I0MfRQ.css +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";const C={0:"vp8",1:"vp09.00.10.08",2:"avc1.42E033"},r={decoder:null,codecId:-1,preferHardware:!0};let o=null,p=0,h=0,k=!0,u=0,g=0,m=0,l=0;const s=new Map;function a(t,e){e&&e.length>0?self.postMessage(t,e):self.postMessage(t)}function d(){if(r.decoder)try{r.decoder.reset(),r.decoder.close()}catch{}r.decoder=null,r.codecId=-1,s.clear()}async function H(t){const e=s.get(t.timestamp);e!==void 0&&(s.delete(t.timestamp),m+=performance.now()-e,l++),g++;const n={t:"frame",timestamp:t.timestamp,width:t.displayWidth,height:t.displayHeight};if(k)try{a({...n,frame:t,kind:"videoframe"},[t]);return}catch{k=!1}try{const c=await createImageBitmap(t);a({...n,frame:c,kind:"imagebitmap"},[c])}catch{}finally{try{t.close()}catch{}}}async function I(t){if(r.decoder&&r.codecId===t)return!0;d();const e=C[t];if(!e)return!1;const n={codec:e,optimizeForLatency:!0,hardwareAcceleration:r.preferHardware?"prefer-hardware":"no-preference"};try{let c=await VideoDecoder.isConfigSupported(n);return!c.supported&&r.preferHardware&&(n.hardwareAcceleration="no-preference",c=await VideoDecoder.isConfigSupported(n)),c.supported?(r.decoder=new VideoDecoder({output:f=>{H(f)},error:()=>{d(),a({t:"keyframe-request"})}}),r.decoder.configure(n),r.codecId=t,a({t:"codec",codecId:t,codec:e}),!0):!1}catch{return d(),!1}}async function U(t,e,n,c){if(r.decoder&&n&&c!==r.codecId&&d(),!r.decoder&&n&&await I(c),!r.decoder){a({t:"keyframe-request"});return}try{s.set(e,performance.now()),r.decoder.decode(new EncodedVideoChunk({type:n?"key":"delta",timestamp:e,data:t}))}catch{s.delete(e),d(),a({t:"keyframe-request"})}}function L(t){const e=new DataView(t),n=e.getUint8(0);if(n===0){const c=Number(e.getBigUint64(1,!0)),f=e.getUint8(9)===1,y=e.getUint8(10),w=e.getUint32(11,!0);u++,U(new Uint8Array(t,15,w),c,f,y);return}if(n===2){const c=Number(e.getBigUint64(1,!0)),f=e.getUint8(9)===1,y=e.getUint8(10),w=e.getUint16(11,!0),z=e.getUint16(13,!0),A=e.getUint32(15,!0),T=new Uint8Array(t,19,A);(!o||p!==c)&&(o=[],p=c,h=z),o[w]=T;let v=0;for(const i of o)i&&v++;if(v!==h)return;let b=0;for(const i of o)b+=i.byteLength;const D=new Uint8Array(b);let S=0;for(const i of o)D.set(i,S),S+=i.byteLength;o=null,u++,U(D,c,f,y)}}function V(){const t={t:"stats",decodeQueueSize:r.decoder?.decodeQueueSize??0,decodeLatencyMs:l>0?m/l:0,framesReceived:u,framesDecoded:g};u=0,g=0,m=0,l=0,a(t)}self.onmessage=t=>{const e=t.data;switch(e?.t){case"packet":try{L(e.buffer)}catch{}break;case"stats":V();break;case"reset":d(),o=null,p=0;break;case"init":r.preferHardware=e.preferHardware!==!1,a({t:"ready",ok:typeof VideoDecoder<"u"});break;case"close":d(),self.close();break}}})();
|
package/dist/index.html
CHANGED
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
}
|
|
59
59
|
})();
|
|
60
60
|
</script>
|
|
61
|
-
<script type="module" crossorigin src="/assets/main-D-
|
|
62
|
-
<link rel="stylesheet" crossorigin href="/assets/main-
|
|
61
|
+
<script type="module" crossorigin src="/assets/main-D-d8SFfW.js"></script>
|
|
62
|
+
<link rel="stylesheet" crossorigin href="/assets/main-BD3-qPfT.css">
|
|
63
63
|
</head>
|
|
64
64
|
<body
|
|
65
65
|
class="min-h-dvh bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100 transition-colors duration-200"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@myrialabs/clopen",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.22",
|
|
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",
|
|
@@ -19,6 +19,11 @@ export interface CommitGeneratorSettings {
|
|
|
19
19
|
/** When false, uses the chat model (selectedEngine/selectedModel). When true, uses custom engine/model below. */
|
|
20
20
|
useCustomModel: boolean;
|
|
21
21
|
engine: EngineType;
|
|
22
|
+
/**
|
|
23
|
+
* Provider of `modelId`. Write it with `modelFieldsOf()` so it can never lag
|
|
24
|
+
* behind a model change — the backend re-derives it anyway
|
|
25
|
+
* (`backend/engine/resolve-model.ts`), but a stale value here is misleading.
|
|
26
|
+
*/
|
|
22
27
|
provider: string;
|
|
23
28
|
modelId: string;
|
|
24
29
|
modelName: string;
|
|
@@ -37,6 +42,7 @@ export interface CommitGeneratorSettings {
|
|
|
37
42
|
export interface ArtifactGeneratorSettings {
|
|
38
43
|
useCustomModel: boolean;
|
|
39
44
|
engine: EngineType;
|
|
45
|
+
/** See `CommitGeneratorSettings.provider` — write via `modelFieldsOf()`. */
|
|
40
46
|
provider: string;
|
|
41
47
|
modelId: string;
|
|
42
48
|
modelName: string;
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Browser Action Handlers
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { browserPreviewServiceManager, type BrowserPreviewService } from "$backend/preview";
|
|
6
|
-
import type { BrowserAutonomousAction } from "$backend/preview/browser/types";
|
|
7
|
-
import { projectContextService } from "$backend/mcp/internal/project-context";
|
|
8
|
-
import { getActiveTabSession } from "./browser";
|
|
9
|
-
import { debug } from "$shared/utils/logger";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Get BrowserPreviewService for current MCP execution context
|
|
13
|
-
*/
|
|
14
|
-
function getPreviewService(projectId?: string): BrowserPreviewService {
|
|
15
|
-
// 1. Use explicit projectId if provided
|
|
16
|
-
if (projectId) {
|
|
17
|
-
debug.log('mcp', `Using explicit projectId: ${projectId}`);
|
|
18
|
-
return browserPreviewServiceManager.getService(projectId);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// 2. Try to get projectId from current execution context
|
|
22
|
-
const contextProjectId = projectContextService.getCurrentProjectId();
|
|
23
|
-
if (contextProjectId) {
|
|
24
|
-
debug.log('mcp', `Using projectId from context: ${contextProjectId}`);
|
|
25
|
-
return browserPreviewServiceManager.getService(contextProjectId);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// 3. Fallback: Get first available project's service
|
|
29
|
-
const activeProjects = browserPreviewServiceManager.getActiveProjects();
|
|
30
|
-
if (activeProjects.length > 0) {
|
|
31
|
-
const fallbackProjectId = activeProjects[0];
|
|
32
|
-
debug.warn('mcp', `⚠️ No project context found, falling back to first active project: ${fallbackProjectId}`);
|
|
33
|
-
return browserPreviewServiceManager.getService(fallbackProjectId);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
throw new Error('No active browser preview service found. Project isolation requires projectId.');
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Define action types using discriminated union
|
|
40
|
-
type ClickAction = {
|
|
41
|
-
type: 'click';
|
|
42
|
-
x: number;
|
|
43
|
-
y: number;
|
|
44
|
-
click?: 'left' | 'right' | 'middle';
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
type TypeAction = {
|
|
48
|
-
type: 'type';
|
|
49
|
-
text?: string; // text OR key (mutually exclusive)
|
|
50
|
-
key?: string; // text OR key (mutually exclusive)
|
|
51
|
-
clearFirst?: boolean;
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
type MoveAction = {
|
|
55
|
-
type: 'move';
|
|
56
|
-
x: number;
|
|
57
|
-
y: number;
|
|
58
|
-
steps?: number;
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
type ScrollAction = {
|
|
62
|
-
type: 'scroll';
|
|
63
|
-
deltaX?: number; // deltaX or deltaY or both
|
|
64
|
-
deltaY?: number; // deltaX or deltaY or both
|
|
65
|
-
smooth?: boolean;
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
type WaitAction = {
|
|
69
|
-
type: 'wait';
|
|
70
|
-
delay: number;
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
type ExtractDataAction = {
|
|
74
|
-
type: 'extract_data';
|
|
75
|
-
selector: string;
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
type BrowserAction =
|
|
79
|
-
| ClickAction
|
|
80
|
-
| TypeAction
|
|
81
|
-
| MoveAction
|
|
82
|
-
| ScrollAction
|
|
83
|
-
| WaitAction
|
|
84
|
-
| ExtractDataAction;
|
|
85
|
-
|
|
86
|
-
export async function actionsHandler(args: {
|
|
87
|
-
actions: BrowserAction[];
|
|
88
|
-
projectId?: string;
|
|
89
|
-
}) {
|
|
90
|
-
try {
|
|
91
|
-
// Get active tab and session
|
|
92
|
-
const { tab } = await getActiveTabSession(args.projectId);
|
|
93
|
-
const sessionId = tab.id;
|
|
94
|
-
|
|
95
|
-
// Get preview service
|
|
96
|
-
const previewService = getPreviewService(args.projectId);
|
|
97
|
-
|
|
98
|
-
// Process actions and apply MCP-optimized defaults
|
|
99
|
-
const processedActions: BrowserAutonomousAction[] = args.actions.map(action => {
|
|
100
|
-
const processed: BrowserAutonomousAction = { ...action } as any;
|
|
101
|
-
|
|
102
|
-
// Apply MCP-optimized default delay for type actions with text (30ms)
|
|
103
|
-
if (action.type === 'type' && 'text' in action && action.text && !('delay' in action)) {
|
|
104
|
-
(processed as any).delay = 30;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// Apply clearFirst = true by default for MCP autonomous type actions
|
|
108
|
-
if (action.type === 'type' && 'text' in action && action.text && action.clearFirst === undefined) {
|
|
109
|
-
processed.clearFirst = true;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return processed;
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
// Note: Cursor events are emitted by performAutonomousActions internally
|
|
116
|
-
// with proper delays between each action. No need to emit here.
|
|
117
|
-
// Pass the chat stream's AbortSignal so the action loop breaks the
|
|
118
|
-
// moment the user clicks interrupt — without this, multi-step click
|
|
119
|
-
// sequences keep firing for a few seconds after the engine subprocess
|
|
120
|
-
// dies (the "preview keeps moving by itself" symptom).
|
|
121
|
-
const abortSignal = projectContextService.getCurrentSignal();
|
|
122
|
-
const results = await previewService.performAutonomousActions(sessionId, processedActions, abortSignal);
|
|
123
|
-
|
|
124
|
-
// Format response with extracted data if any
|
|
125
|
-
const extractedData = results?.filter((r: any) => r.action === 'extract_data') || [];
|
|
126
|
-
|
|
127
|
-
let responseText = `Successfully performed ${args.actions.length} action(s) in sequence.`;
|
|
128
|
-
|
|
129
|
-
if (extractedData.length > 0) {
|
|
130
|
-
responseText += '\n\nExtracted Data:';
|
|
131
|
-
extractedData.forEach((item: any, idx: number) => {
|
|
132
|
-
if (item.error) {
|
|
133
|
-
responseText += `\n [${idx + 1}] Error from '${item.selector}': ${item.error}`;
|
|
134
|
-
} else if (item.data !== null && item.data !== undefined) {
|
|
135
|
-
const attrInfo = item.attribute ? ` (via ${item.attribute})` : '';
|
|
136
|
-
responseText += `\n [${idx + 1}] From '${item.selector}'${attrInfo}: ${item.data}`;
|
|
137
|
-
} else {
|
|
138
|
-
responseText += `\n [${idx + 1}] From '${item.selector}': (element not found or empty)`;
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
return {
|
|
144
|
-
content: [{
|
|
145
|
-
type: "text" as const,
|
|
146
|
-
text: responseText
|
|
147
|
-
}]
|
|
148
|
-
};
|
|
149
|
-
} catch (error) {
|
|
150
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
151
|
-
return {
|
|
152
|
-
content: [{
|
|
153
|
-
type: "text" as const,
|
|
154
|
-
text: `Actions execution failed: ${errorMessage}`
|
|
155
|
-
}],
|
|
156
|
-
isError: true
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
}
|
|
@@ -1,375 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Browser Management Handlers for MCP Browser Automation
|
|
3
|
-
*
|
|
4
|
-
* Provides tools for MCP to manage browser:
|
|
5
|
-
* - List and switch tabs
|
|
6
|
-
* - Open and close tabs (auto session management)
|
|
7
|
-
* - Navigate active tab
|
|
8
|
-
*
|
|
9
|
-
* Control model:
|
|
10
|
-
* - Each chat session can control multiple tabs (accumulated via switch/open)
|
|
11
|
-
* - A tab can only be controlled by one chat session at a time
|
|
12
|
-
* - All controlled tabs are released when the chat stream ends
|
|
13
|
-
* - list_tabs shows MCP control status so AI avoids conflicts
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { debug } from "$shared/utils/logger";
|
|
17
|
-
import { browserMcpControl, browserPreviewServiceManager, type BrowserPreviewService } from "$backend/preview";
|
|
18
|
-
import { projectContextService } from "$backend/mcp/internal/project-context";
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Get BrowserPreviewService for current MCP execution context
|
|
22
|
-
*/
|
|
23
|
-
function getPreviewService(projectId?: string): BrowserPreviewService {
|
|
24
|
-
if (projectId) {
|
|
25
|
-
return browserPreviewServiceManager.getService(projectId);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const contextProjectId = projectContextService.getCurrentProjectId();
|
|
29
|
-
if (contextProjectId) {
|
|
30
|
-
return browserPreviewServiceManager.getService(contextProjectId);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const activeProjects = browserPreviewServiceManager.getActiveProjects();
|
|
34
|
-
if (activeProjects.length > 0) {
|
|
35
|
-
debug.warn('mcp', `⚠️ No project context found, falling back to first active project: ${activeProjects[0]}`);
|
|
36
|
-
return browserPreviewServiceManager.getService(activeProjects[0]);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
throw new Error('No active browser preview service found. Project isolation requires projectId.');
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Get chatSessionId from current execution context.
|
|
44
|
-
* Required for session-scoped MCP control.
|
|
45
|
-
*/
|
|
46
|
-
function getChatSessionId(): string {
|
|
47
|
-
const chatSessionId = projectContextService.getCurrentChatSessionId();
|
|
48
|
-
if (!chatSessionId) {
|
|
49
|
-
throw new Error('No chat session context available. Cannot acquire MCP control.');
|
|
50
|
-
}
|
|
51
|
-
return chatSessionId;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Internal helper: Get active tab for MCP operations.
|
|
56
|
-
* Automatically acquires MCP control for the chat session.
|
|
57
|
-
*
|
|
58
|
-
* If this chat session already controls tabs, uses the most recently
|
|
59
|
-
* controlled tab (not necessarily the frontend's active tab).
|
|
60
|
-
*/
|
|
61
|
-
export async function getActiveTabSession(projectId?: string) {
|
|
62
|
-
const previewService = getPreviewService(projectId);
|
|
63
|
-
const resolvedProjectId = previewService.getProjectId();
|
|
64
|
-
const chatSessionId = getChatSessionId();
|
|
65
|
-
|
|
66
|
-
// Check if this session already controls any tabs — use the last one
|
|
67
|
-
const sessionTabs = browserMcpControl.getSessionTabs(chatSessionId);
|
|
68
|
-
if (sessionTabs.length > 0) {
|
|
69
|
-
// Use the last tab this session was working with
|
|
70
|
-
const lastTabId = sessionTabs[sessionTabs.length - 1];
|
|
71
|
-
const controlledTab = previewService.getTab(lastTabId);
|
|
72
|
-
if (controlledTab) {
|
|
73
|
-
debug.log('mcp', `🎮 Using session-controlled tab: ${controlledTab.id}`);
|
|
74
|
-
return { tab: controlledTab, session: controlledTab };
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// No controlled tab — use the frontend's active tab and acquire control
|
|
79
|
-
const tab = previewService.getActiveTab();
|
|
80
|
-
if (!tab) {
|
|
81
|
-
throw new Error("No active tab found. Open a tab first using 'open_new_tab'.");
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Acquire control (will fail if another session owns this tab)
|
|
85
|
-
const acquired = browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
|
|
86
|
-
if (!acquired) {
|
|
87
|
-
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
88
|
-
throw new Error(`Tab '${tab.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
return { tab, session: tab };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* List all open tabs in the browser preview.
|
|
96
|
-
* Shows MCP control status so AI can avoid conflicts.
|
|
97
|
-
*/
|
|
98
|
-
export async function listTabsHandler(projectId?: string) {
|
|
99
|
-
try {
|
|
100
|
-
const previewService = getPreviewService(projectId);
|
|
101
|
-
const tabs = previewService.getAllTabs();
|
|
102
|
-
const chatSessionId = projectContextService.getCurrentChatSessionId();
|
|
103
|
-
|
|
104
|
-
if (tabs.length === 0) {
|
|
105
|
-
return {
|
|
106
|
-
content: [{
|
|
107
|
-
type: "text" as const,
|
|
108
|
-
text: `No browser tabs are currently open.`
|
|
109
|
-
}]
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const tabList = tabs.map((tab: any, index: number) => {
|
|
114
|
-
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
115
|
-
let status = '';
|
|
116
|
-
if (owner) {
|
|
117
|
-
status = owner === chatSessionId
|
|
118
|
-
? ' (MCP: this session)'
|
|
119
|
-
: ' (MCP: another session)';
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
return `${index + 1}. ${tab.isActive ? '* ' : ' '}[${tab.id}] ${tab.title || 'Untitled'}${status}\n URL: ${tab.url || '(empty)'}`;
|
|
123
|
-
}).join('\n\n');
|
|
124
|
-
|
|
125
|
-
return {
|
|
126
|
-
content: [{
|
|
127
|
-
type: "text" as const,
|
|
128
|
-
text: `Browser Tabs (${tabs.length}):\n\n${tabList}`
|
|
129
|
-
}]
|
|
130
|
-
};
|
|
131
|
-
} catch (error) {
|
|
132
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
133
|
-
return {
|
|
134
|
-
content: [{
|
|
135
|
-
type: "text" as const,
|
|
136
|
-
text: `Failed to list tabs: ${errorMessage}`
|
|
137
|
-
}],
|
|
138
|
-
isError: true
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Switch to a specific tab by ID.
|
|
145
|
-
* Adds the tab to this session's controlled set (does NOT release other tabs).
|
|
146
|
-
*/
|
|
147
|
-
export async function switchTabHandler(args: { tabId: string; projectId?: string }) {
|
|
148
|
-
try {
|
|
149
|
-
debug.log('mcp', `🔄 MCP switching to tab: ${args.tabId}`);
|
|
150
|
-
|
|
151
|
-
const previewService = getPreviewService(args.projectId);
|
|
152
|
-
const chatSessionId = getChatSessionId();
|
|
153
|
-
const resolvedProjectId = previewService.getProjectId();
|
|
154
|
-
|
|
155
|
-
const success = previewService.switchTab(args.tabId);
|
|
156
|
-
if (!success) {
|
|
157
|
-
return {
|
|
158
|
-
content: [{
|
|
159
|
-
type: "text" as const,
|
|
160
|
-
text: `Failed to switch tab: Tab '${args.tabId}' not found`
|
|
161
|
-
}],
|
|
162
|
-
isError: true
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// Acquire control of the new tab (adds to session's set, doesn't release others)
|
|
167
|
-
const tab = previewService.getTab(args.tabId);
|
|
168
|
-
if (tab) {
|
|
169
|
-
const acquired = browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
|
|
170
|
-
if (!acquired) {
|
|
171
|
-
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
172
|
-
return {
|
|
173
|
-
content: [{
|
|
174
|
-
type: "text" as const,
|
|
175
|
-
text: `Tab '${args.tabId}' is controlled by another chat session (${owner?.slice(0, 8)}...). Cannot switch to it.`
|
|
176
|
-
}],
|
|
177
|
-
isError: true
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
// Promote tab to end of session's set so getActiveTabSession() targets it next
|
|
181
|
-
browserMcpControl.promoteSessionTab(tab.id, chatSessionId);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
return {
|
|
185
|
-
content: [{
|
|
186
|
-
type: "text" as const,
|
|
187
|
-
text: `Switched to tab '${args.tabId}'.\n\nTitle: ${tab?.title || 'Untitled'}\nURL: ${tab?.url || '(empty)'}`
|
|
188
|
-
}]
|
|
189
|
-
};
|
|
190
|
-
} catch (error) {
|
|
191
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
192
|
-
return {
|
|
193
|
-
content: [{
|
|
194
|
-
type: "text" as const,
|
|
195
|
-
text: `Failed to switch tab: ${errorMessage}`
|
|
196
|
-
}],
|
|
197
|
-
isError: true
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Open a new tab with optional URL and viewport configuration.
|
|
204
|
-
* Auto-acquires MCP control for the new tab.
|
|
205
|
-
*/
|
|
206
|
-
export async function openNewTabHandler(args: { url?: string; deviceSize?: 'desktop' | 'laptop' | 'tablet' | 'mobile'; rotation?: 'portrait' | 'landscape'; projectId?: string }) {
|
|
207
|
-
try {
|
|
208
|
-
const deviceSize = args.deviceSize || 'laptop';
|
|
209
|
-
|
|
210
|
-
let rotation: 'portrait' | 'landscape';
|
|
211
|
-
if (args.rotation) {
|
|
212
|
-
rotation = args.rotation;
|
|
213
|
-
} else {
|
|
214
|
-
rotation = (deviceSize === 'desktop' || deviceSize === 'laptop') ? 'landscape' : 'portrait';
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
debug.log('mcp', `📑 MCP opening new tab with URL: ${args.url || '(empty)'}`);
|
|
218
|
-
|
|
219
|
-
const previewService = getPreviewService(args.projectId);
|
|
220
|
-
const chatSessionId = getChatSessionId();
|
|
221
|
-
const resolvedProjectId = previewService.getProjectId();
|
|
222
|
-
|
|
223
|
-
const tab = await previewService.createTab(args.url || undefined, deviceSize, rotation);
|
|
224
|
-
debug.log('mcp', `✅ Tab created: ${tab.id}`);
|
|
225
|
-
|
|
226
|
-
// Acquire control of the new tab (adds to session's set)
|
|
227
|
-
browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
|
|
228
|
-
|
|
229
|
-
return {
|
|
230
|
-
content: [{
|
|
231
|
-
type: "text" as const,
|
|
232
|
-
text: `New tab opened successfully.\n\nTab ID: ${tab.id}\nTitle: ${tab.title}\nURL: ${tab.url || '(empty)'}\nViewport: ${deviceSize} (${rotation})`
|
|
233
|
-
}]
|
|
234
|
-
};
|
|
235
|
-
} catch (error) {
|
|
236
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
237
|
-
return {
|
|
238
|
-
content: [{
|
|
239
|
-
type: "text" as const,
|
|
240
|
-
text: `Failed to open new tab: ${errorMessage}`
|
|
241
|
-
}],
|
|
242
|
-
isError: true
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Close a specific tab by ID.
|
|
249
|
-
* Releases MCP control for the closed tab only.
|
|
250
|
-
*/
|
|
251
|
-
export async function closeTabHandler(args: { tabId: string; projectId?: string }) {
|
|
252
|
-
try {
|
|
253
|
-
debug.log('mcp', `❌ MCP closing tab: ${args.tabId}`);
|
|
254
|
-
|
|
255
|
-
const previewService = getPreviewService(args.projectId);
|
|
256
|
-
const result = await previewService.closeTab(args.tabId);
|
|
257
|
-
|
|
258
|
-
if (!result.success) {
|
|
259
|
-
return {
|
|
260
|
-
content: [{
|
|
261
|
-
type: "text" as const,
|
|
262
|
-
text: `Failed to close tab: Tab '${args.tabId}' not found`
|
|
263
|
-
}],
|
|
264
|
-
isError: true
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// releaseTab is already called by autoReleaseForTab inside closeTab()
|
|
269
|
-
// No need to manually release here
|
|
270
|
-
|
|
271
|
-
let responseText = `Tab '${args.tabId}' closed successfully.`;
|
|
272
|
-
if (result.newActiveTabId) {
|
|
273
|
-
const newActiveTab = previewService.getTab(result.newActiveTabId);
|
|
274
|
-
if (newActiveTab) {
|
|
275
|
-
responseText += `\n\nNew active tab: ${newActiveTab.id}\nURL: ${newActiveTab.url || '(empty)'}`;
|
|
276
|
-
}
|
|
277
|
-
} else {
|
|
278
|
-
responseText += `\n\nNo remaining tabs.`;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
return {
|
|
282
|
-
content: [{
|
|
283
|
-
type: "text" as const,
|
|
284
|
-
text: responseText
|
|
285
|
-
}]
|
|
286
|
-
};
|
|
287
|
-
} catch (error) {
|
|
288
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
289
|
-
return {
|
|
290
|
-
content: [{
|
|
291
|
-
type: "text" as const,
|
|
292
|
-
text: `Failed to close tab: ${errorMessage}`
|
|
293
|
-
}],
|
|
294
|
-
isError: true
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/**
|
|
300
|
-
* Navigate active tab to a different URL.
|
|
301
|
-
* Waits for page load. Session state preserved.
|
|
302
|
-
*/
|
|
303
|
-
export async function navigateHandler(args: { url: string; projectId?: string }) {
|
|
304
|
-
try {
|
|
305
|
-
const { session } = await getActiveTabSession(args.projectId);
|
|
306
|
-
|
|
307
|
-
await session.page.goto(args.url, {
|
|
308
|
-
waitUntil: 'domcontentloaded',
|
|
309
|
-
timeout: 30000
|
|
310
|
-
});
|
|
311
|
-
|
|
312
|
-
await new Promise(resolve => setTimeout(resolve, 500));
|
|
313
|
-
|
|
314
|
-
const finalUrl = session.page.url();
|
|
315
|
-
|
|
316
|
-
return {
|
|
317
|
-
content: [{
|
|
318
|
-
type: "text" as const,
|
|
319
|
-
text: `Navigation successful.\n\nFinal URL: ${finalUrl}`
|
|
320
|
-
}]
|
|
321
|
-
};
|
|
322
|
-
} catch (error) {
|
|
323
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
324
|
-
return {
|
|
325
|
-
content: [{
|
|
326
|
-
type: "text" as const,
|
|
327
|
-
text: `Navigation failed: ${errorMessage}`
|
|
328
|
-
}],
|
|
329
|
-
isError: true
|
|
330
|
-
};
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
/**
|
|
335
|
-
* Change viewport settings (device size and rotation) for active tab.
|
|
336
|
-
*/
|
|
337
|
-
export async function setViewportHandler(args: { deviceSize?: 'desktop' | 'laptop' | 'tablet' | 'mobile'; rotation?: 'portrait' | 'landscape'; projectId?: string }) {
|
|
338
|
-
try {
|
|
339
|
-
const { tab } = await getActiveTabSession(args.projectId);
|
|
340
|
-
|
|
341
|
-
const deviceSize = args.deviceSize || tab.deviceSize;
|
|
342
|
-
const rotation = args.rotation || tab.rotation;
|
|
343
|
-
|
|
344
|
-
debug.log('mcp', `📱 MCP changing viewport for tab ${tab.id}: ${deviceSize} (${rotation})`);
|
|
345
|
-
|
|
346
|
-
const previewService = getPreviewService(args.projectId);
|
|
347
|
-
const success = await previewService.setViewport(tab.id, deviceSize, rotation);
|
|
348
|
-
|
|
349
|
-
if (!success) {
|
|
350
|
-
return {
|
|
351
|
-
content: [{
|
|
352
|
-
type: "text" as const,
|
|
353
|
-
text: `Failed to change viewport for tab '${tab.id}'`
|
|
354
|
-
}],
|
|
355
|
-
isError: true
|
|
356
|
-
};
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
return {
|
|
360
|
-
content: [{
|
|
361
|
-
type: "text" as const,
|
|
362
|
-
text: `Viewport changed successfully.\n\nTab ID: ${tab.id}\nDevice: ${deviceSize}\nRotation: ${rotation}`
|
|
363
|
-
}]
|
|
364
|
-
};
|
|
365
|
-
} catch (error) {
|
|
366
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
367
|
-
return {
|
|
368
|
-
content: [{
|
|
369
|
-
type: "text" as const,
|
|
370
|
-
text: `Failed to change viewport: ${errorMessage}`
|
|
371
|
-
}],
|
|
372
|
-
isError: true
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
}
|