@myrialabs/clopen 0.4.20 → 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/bootstrap.ts +39 -0
- package/backend/chat/stream-manager.ts +15 -0
- package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/session-queries.ts +10 -0
- package/backend/engine/README.md +11 -8
- package/backend/engine/adapters/claude/models.ts +46 -23
- package/backend/engine/adapters/claude/stream.ts +18 -4
- package/backend/engine/adapters/codex/error-handler.ts +1 -1
- package/backend/engine/adapters/codex/models.ts +19 -2
- package/backend/engine/adapters/codex/stream.ts +10 -3
- package/backend/engine/adapters/copilot/models.ts +20 -1
- package/backend/engine/adapters/copilot/stream.ts +11 -1
- package/backend/engine/adapters/cursor/models.ts +27 -3
- package/backend/engine/adapters/cursor/stream.ts +23 -3
- package/backend/engine/adapters/pi/models.ts +20 -2
- package/backend/engine/adapters/pi/stream.ts +6 -3
- package/backend/engine/adapters/qwen/error-handler.ts +1 -1
- package/backend/engine/bootstrap-default-engine.ts +18 -5
- 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/engine/types.ts +6 -0
- package/backend/index.ts +6 -9
- 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/chat/stream.ts +38 -2
- 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/backend/ws/system/device-info.ts +290 -0
- package/backend/ws/system/index.ts +2 -0
- package/backend/ws/system/operations.ts +7 -0
- package/backend/ws/user/crud.ts +6 -3
- package/dist/assets/{index-BqBxKeAv.js → index-DH_GO0Lf.js} +1 -1
- package/dist/assets/{index-DdrcY5TE.js → index-igSQ3JaM.js} +1 -1
- package/dist/assets/main-BD3-qPfT.css +1 -0
- package/dist/assets/main-D-d8SFfW.js +616 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/constants/engines.ts +23 -0
- package/shared/types/database/schema.ts +1 -0
- package/shared/types/stores/settings.ts +12 -0
- package/shared/types/unified/engine.ts +33 -0
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +6 -0
- package/shared/types/unified/stream.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-BBxAj17T.js +0 -582
- package/dist/assets/main-Cry3pLcl.css +0 -1
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser Host Bridge
|
|
3
|
+
*
|
|
4
|
+
* Owns everything the headless browser cannot answer for itself and the
|
|
5
|
+
* *viewer's* browser can: geolocation, camera/microphone, clipboard,
|
|
6
|
+
* notifications, file pickers and downloads.
|
|
7
|
+
*
|
|
8
|
+
* Two directions meet here:
|
|
9
|
+
* - **Page → viewer.** An injected shim (see `scripts/host-bridge.ts`) turns a
|
|
10
|
+
* `navigator.*` call into a request; this class parks it, emits it, and
|
|
11
|
+
* resolves the page's promise once the frontend answers.
|
|
12
|
+
* - **Chrome → viewer.** File choosers and downloads are intercepted over CDP,
|
|
13
|
+
* which needs no injection because Chrome surfaces them as protocol events.
|
|
14
|
+
*
|
|
15
|
+
* Requests are keyed by an id rather than by tab so a slow decision on one tab
|
|
16
|
+
* never blocks another, and every one carries a deadline — a page that asks for
|
|
17
|
+
* a camera while nobody is watching the panel must eventually fail rather than
|
|
18
|
+
* hang the renderer forever.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { EventEmitter } from 'events';
|
|
22
|
+
import { randomUUID } from 'crypto';
|
|
23
|
+
import { mkdir, readFile, rm, writeFile } from 'fs/promises';
|
|
24
|
+
import { join } from 'path';
|
|
25
|
+
import type { CDPSession, Page } from 'puppeteer';
|
|
26
|
+
import { debug } from '$shared/utils/logger';
|
|
27
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
28
|
+
|
|
29
|
+
/** Capability requests the injected shim can raise. */
|
|
30
|
+
export type HostRequestKind =
|
|
31
|
+
| 'geolocation'
|
|
32
|
+
| 'media-request'
|
|
33
|
+
| 'media-stop'
|
|
34
|
+
| 'media-devices'
|
|
35
|
+
| 'clipboard-read'
|
|
36
|
+
| 'clipboard-write'
|
|
37
|
+
| 'notification-permission'
|
|
38
|
+
| 'notification-show'
|
|
39
|
+
| 'speech-start'
|
|
40
|
+
| 'speech-stop'
|
|
41
|
+
| 'file-pick'
|
|
42
|
+
// Not a capability and never shown to anyone: the page reporting that Chrome
|
|
43
|
+
// resized the renderer behind the emulation's back, so the host can put the
|
|
44
|
+
// viewport it captures from back the way it was. Answered by the service.
|
|
45
|
+
| 'viewport-restore';
|
|
46
|
+
|
|
47
|
+
export interface HostRequestEvent {
|
|
48
|
+
tabId: string;
|
|
49
|
+
requestId: string;
|
|
50
|
+
kind: HostRequestKind;
|
|
51
|
+
payload: unknown;
|
|
52
|
+
timestamp: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface HostDownloadEvent {
|
|
56
|
+
tabId: string;
|
|
57
|
+
downloadId: string;
|
|
58
|
+
filename: string;
|
|
59
|
+
url: string;
|
|
60
|
+
/** base64 payload, present only once the download completed. */
|
|
61
|
+
data?: string;
|
|
62
|
+
state: 'started' | 'completed' | 'failed';
|
|
63
|
+
totalBytes?: number;
|
|
64
|
+
error?: string;
|
|
65
|
+
timestamp: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface HostResponse {
|
|
69
|
+
ok: boolean;
|
|
70
|
+
result?: unknown;
|
|
71
|
+
error?: { name?: string; message?: string; code?: number };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A file handed back by the viewer for an intercepted file chooser. */
|
|
75
|
+
export interface HostPickedFile {
|
|
76
|
+
name: string;
|
|
77
|
+
/** base64, without the data-URL prefix. */
|
|
78
|
+
data: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface PendingRequest {
|
|
82
|
+
tabId: string;
|
|
83
|
+
kind: HostRequestKind;
|
|
84
|
+
resolve: (response: HostResponse) => void;
|
|
85
|
+
timeout: NodeJS.Timeout;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface TabBridge {
|
|
89
|
+
bindingName: string;
|
|
90
|
+
cdp?: CDPSession;
|
|
91
|
+
transferDir: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* How long the page waits before a capability request gives up.
|
|
96
|
+
*
|
|
97
|
+
* Media gets longer than the rest: the viewer has to answer their own browser's
|
|
98
|
+
* camera prompt, and a hurried timeout there reads as a broken feature.
|
|
99
|
+
*/
|
|
100
|
+
const REQUEST_TIMEOUT_MS: Record<HostRequestKind, number> = {
|
|
101
|
+
'geolocation': 60_000,
|
|
102
|
+
'media-request': 120_000,
|
|
103
|
+
'media-stop': 5_000,
|
|
104
|
+
'media-devices': 15_000,
|
|
105
|
+
'clipboard-read': 30_000,
|
|
106
|
+
'clipboard-write': 15_000,
|
|
107
|
+
'notification-permission': 60_000,
|
|
108
|
+
'notification-show': 15_000,
|
|
109
|
+
// Only the handshake is timed; results stream back as events afterwards.
|
|
110
|
+
'speech-start': 120_000,
|
|
111
|
+
'speech-stop': 5_000,
|
|
112
|
+
'file-pick': 300_000,
|
|
113
|
+
// Nobody is asked anything — this is the host talking to itself, and the page
|
|
114
|
+
// is blocked on it while a screencast restarts.
|
|
115
|
+
'viewport-restore': 15_000
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Ceiling for a completed download relayed to the viewer over the WebSocket.
|
|
120
|
+
* Above this the base64 round-trip costs more than the download is worth, so
|
|
121
|
+
* the viewer is told to fetch it directly instead.
|
|
122
|
+
*/
|
|
123
|
+
const MAX_RELAYED_DOWNLOAD_BYTES = 32 * 1024 * 1024;
|
|
124
|
+
|
|
125
|
+
export class BrowserHostBridge extends EventEmitter {
|
|
126
|
+
private tabs = new Map<string, TabBridge>();
|
|
127
|
+
private pending = new Map<string, PendingRequest>();
|
|
128
|
+
|
|
129
|
+
/** Downloads seen per tab, so progress events can find their metadata. */
|
|
130
|
+
private downloads = new Map<string, { tabId: string; filename: string; url: string }>();
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Install the bridge for a tab. Must run before the first navigation so the
|
|
134
|
+
* shim is in place by the time page scripts execute.
|
|
135
|
+
*/
|
|
136
|
+
async setup(tabId: string, page: Page): Promise<void> {
|
|
137
|
+
if (this.tabs.has(tabId)) return;
|
|
138
|
+
|
|
139
|
+
// Randomised per tab: a fixed global name is a one-line detection rule
|
|
140
|
+
// for the same bot-detection scripts these APIs tend to sit behind.
|
|
141
|
+
const bindingName = `__h${randomUUID().replace(/-/g, '').slice(0, 16)}`;
|
|
142
|
+
const transferDir = join(getClopenDir(), 'preview', 'transfer', tabId.replace(/[^\w.-]/g, '_'));
|
|
143
|
+
|
|
144
|
+
this.tabs.set(tabId, { bindingName, transferDir });
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
await page.exposeFunction(bindingName, (raw: string) => this.handlePageRequest(tabId, raw));
|
|
148
|
+
|
|
149
|
+
const { hostBridgeScript } = await import('./scripts/host-bridge');
|
|
150
|
+
await page.evaluateOnNewDocument(hostBridgeScript, bindingName);
|
|
151
|
+
|
|
152
|
+
debug.log('preview', `🌉 Host bridge installed for tab ${tabId}`);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
debug.warn('preview', `⚠️ Host bridge injection failed for tab ${tabId}:`, error);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
await this.setupCdpInterception(tabId, page, transferDir);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* File choosers and downloads come straight off the protocol, so they work
|
|
162
|
+
* even when script injection was rejected above.
|
|
163
|
+
*/
|
|
164
|
+
private async setupCdpInterception(tabId: string, page: Page, transferDir: string): Promise<void> {
|
|
165
|
+
try {
|
|
166
|
+
const cdp = await page.createCDPSession();
|
|
167
|
+
const entry = this.tabs.get(tabId);
|
|
168
|
+
if (entry) entry.cdp = cdp;
|
|
169
|
+
|
|
170
|
+
// `Page.enable` is not optional here: without it the Page domain emits
|
|
171
|
+
// nothing, so `Page.fileChooserOpened` never arrived and file inputs
|
|
172
|
+
// appeared to be ignored entirely.
|
|
173
|
+
await cdp.send('Page.enable');
|
|
174
|
+
await cdp.send('DOM.enable').catch(() => {});
|
|
175
|
+
await cdp.send('Page.setInterceptFileChooserDialog', { enabled: true });
|
|
176
|
+
|
|
177
|
+
// Covers the main frame and every same-process iframe. A chooser raised
|
|
178
|
+
// inside a cross-origin (out-of-process) iframe is dispatched on that
|
|
179
|
+
// frame's own target, which Puppeteer does not surface as a Target —
|
|
180
|
+
// those stay un-intercepted.
|
|
181
|
+
cdp.on('Page.fileChooserOpened', (params: { mode: string; backendNodeId?: number }) => {
|
|
182
|
+
void this.handleFileChooser(tabId, cdp, params);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
await mkdir(transferDir, { recursive: true });
|
|
186
|
+
await cdp.send('Browser.setDownloadBehavior', {
|
|
187
|
+
behavior: 'allowAndName',
|
|
188
|
+
downloadPath: transferDir,
|
|
189
|
+
eventsEnabled: true
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
cdp.on('Browser.downloadWillBegin', (params: { guid: string; url: string; suggestedFilename: string }) => {
|
|
193
|
+
this.downloads.set(params.guid, {
|
|
194
|
+
tabId,
|
|
195
|
+
filename: params.suggestedFilename || 'download',
|
|
196
|
+
url: params.url
|
|
197
|
+
});
|
|
198
|
+
this.emit('download', {
|
|
199
|
+
tabId,
|
|
200
|
+
downloadId: params.guid,
|
|
201
|
+
filename: params.suggestedFilename || 'download',
|
|
202
|
+
url: params.url,
|
|
203
|
+
state: 'started',
|
|
204
|
+
timestamp: Date.now()
|
|
205
|
+
} satisfies HostDownloadEvent);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
cdp.on(
|
|
209
|
+
'Browser.downloadProgress',
|
|
210
|
+
(params: { guid: string; state: string; totalBytes?: number; receivedBytes?: number }) => {
|
|
211
|
+
if (params.state === 'inProgress') return;
|
|
212
|
+
void this.finalizeDownload(params.guid, params.state, transferDir, params.totalBytes);
|
|
213
|
+
}
|
|
214
|
+
);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
debug.warn('preview', `⚠️ Host bridge CDP interception failed for tab ${tabId}:`, error);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Park a request from the page and hand it to whoever is watching the panel.
|
|
222
|
+
* The returned promise is what the page's `await` is blocked on, so it always
|
|
223
|
+
* settles — a rejection here would surface as an unhandled error in the page.
|
|
224
|
+
*/
|
|
225
|
+
private handlePageRequest(tabId: string, raw: string): Promise<string> {
|
|
226
|
+
let parsed: { kind: HostRequestKind; payload?: unknown };
|
|
227
|
+
try {
|
|
228
|
+
parsed = JSON.parse(raw);
|
|
229
|
+
} catch {
|
|
230
|
+
return Promise.resolve(
|
|
231
|
+
JSON.stringify({ ok: false, error: { name: 'DataError', message: 'Malformed bridge request' } })
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return this.request(tabId, parsed.kind, parsed.payload).then((response) => JSON.stringify(response));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Emit a request and wait for the frontend's answer.
|
|
240
|
+
*/
|
|
241
|
+
request(tabId: string, kind: HostRequestKind, payload: unknown): Promise<HostResponse> {
|
|
242
|
+
const requestId = randomUUID();
|
|
243
|
+
|
|
244
|
+
return new Promise<HostResponse>((resolve) => {
|
|
245
|
+
const timeout = setTimeout(() => {
|
|
246
|
+
this.pending.delete(requestId);
|
|
247
|
+
this.emit('request-settled', { tabId, requestId });
|
|
248
|
+
resolve({
|
|
249
|
+
ok: false,
|
|
250
|
+
error: { name: 'NotAllowedError', message: 'No response from the preview host', code: 1 }
|
|
251
|
+
});
|
|
252
|
+
}, REQUEST_TIMEOUT_MS[kind] ?? 60_000);
|
|
253
|
+
|
|
254
|
+
this.pending.set(requestId, { tabId, kind, resolve, timeout });
|
|
255
|
+
|
|
256
|
+
this.emit('request', {
|
|
257
|
+
tabId,
|
|
258
|
+
requestId,
|
|
259
|
+
kind,
|
|
260
|
+
payload,
|
|
261
|
+
timestamp: Date.now()
|
|
262
|
+
} satisfies HostRequestEvent);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Push an event down to the page.
|
|
268
|
+
*
|
|
269
|
+
* The request/response channel cannot carry a stream, and speech recognition
|
|
270
|
+
* is one — results keep arriving until the page stops listening. The top
|
|
271
|
+
* frame receives this and rebroadcasts to its children.
|
|
272
|
+
*/
|
|
273
|
+
async dispatchEvent(page: Page, tabId: string, kind: string, payload: unknown): Promise<void> {
|
|
274
|
+
const entry = this.tabs.get(tabId);
|
|
275
|
+
if (!entry) return;
|
|
276
|
+
|
|
277
|
+
try {
|
|
278
|
+
await page.evaluate(
|
|
279
|
+
(hook: string, raw: string) => {
|
|
280
|
+
const deliver = (window as unknown as Record<string, ((value: string) => void) | undefined>)[hook];
|
|
281
|
+
if (typeof deliver === 'function') deliver(raw);
|
|
282
|
+
},
|
|
283
|
+
`${entry.bindingName}E`,
|
|
284
|
+
JSON.stringify({ kind, payload })
|
|
285
|
+
);
|
|
286
|
+
} catch {
|
|
287
|
+
// Page navigated away mid-stream; the session ends with it.
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Deliver the viewer's answer. Unknown ids are ignored — they belong to
|
|
293
|
+
* requests that already timed out or to a tab that has since closed.
|
|
294
|
+
*/
|
|
295
|
+
respond(requestId: string, response: HostResponse): boolean {
|
|
296
|
+
const pending = this.pending.get(requestId);
|
|
297
|
+
if (!pending) return false;
|
|
298
|
+
|
|
299
|
+
clearTimeout(pending.timeout);
|
|
300
|
+
this.pending.delete(requestId);
|
|
301
|
+
// The page asked once, but the prompt was raised on every device watching
|
|
302
|
+
// this tab. Whoever answered first answered for all of them, so the rest
|
|
303
|
+
// are told to take their copy down.
|
|
304
|
+
this.emit('request-settled', { tabId: pending.tabId, requestId });
|
|
305
|
+
pending.resolve(response);
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ── File chooser ────────────────────────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Chrome cannot open a file picker in headless mode, so the viewer's browser
|
|
313
|
+
* opens a real one and the bytes are written to a scratch dir the renderer
|
|
314
|
+
* can read. Cancelling still has to answer the protocol, otherwise the input
|
|
315
|
+
* stays wedged open for the life of the page.
|
|
316
|
+
*/
|
|
317
|
+
private async handleFileChooser(
|
|
318
|
+
tabId: string,
|
|
319
|
+
cdp: CDPSession,
|
|
320
|
+
params: { mode: string; backendNodeId?: number }
|
|
321
|
+
): Promise<void> {
|
|
322
|
+
const backendNodeId = params.backendNodeId;
|
|
323
|
+
if (!backendNodeId) return;
|
|
324
|
+
|
|
325
|
+
const entry = this.tabs.get(tabId);
|
|
326
|
+
const transferDir = entry?.transferDir;
|
|
327
|
+
let paths: string[] = [];
|
|
328
|
+
|
|
329
|
+
try {
|
|
330
|
+
const response = await this.request(tabId, 'file-pick', {
|
|
331
|
+
multiple: params.mode === 'selectMultiple'
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
if (response.ok && transferDir) {
|
|
335
|
+
const files = (response.result as { files?: HostPickedFile[] })?.files ?? [];
|
|
336
|
+
paths = await this.writePickedFiles(transferDir, files);
|
|
337
|
+
}
|
|
338
|
+
} catch (error) {
|
|
339
|
+
debug.warn('preview', `⚠️ File chooser relay failed for tab ${tabId}:`, error);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
try {
|
|
343
|
+
await cdp.send('DOM.setFileInputFiles', { files: paths, backendNodeId });
|
|
344
|
+
} catch (error) {
|
|
345
|
+
debug.warn('preview', `⚠️ Failed to hand files to the page for tab ${tabId}:`, error);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private async writePickedFiles(transferDir: string, files: HostPickedFile[]): Promise<string[]> {
|
|
350
|
+
if (files.length === 0) return [];
|
|
351
|
+
|
|
352
|
+
const uploadDir = join(transferDir, 'upload', randomUUID());
|
|
353
|
+
await mkdir(uploadDir, { recursive: true });
|
|
354
|
+
|
|
355
|
+
const paths: string[] = [];
|
|
356
|
+
for (const file of files) {
|
|
357
|
+
// Names come from the viewer's filesystem — keep the basename only so
|
|
358
|
+
// a crafted "../" cannot escape the scratch directory.
|
|
359
|
+
const safeName = (file.name || 'file').split(/[\\/]/).pop() || 'file';
|
|
360
|
+
const target = join(uploadDir, safeName);
|
|
361
|
+
await writeFile(target, Buffer.from(file.data, 'base64'));
|
|
362
|
+
paths.push(target);
|
|
363
|
+
}
|
|
364
|
+
return paths;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ── Downloads ───────────────────────────────────────────────────────────
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Relay a finished download to the viewer, then drop the server-side copy —
|
|
371
|
+
* the file belongs on the machine the person is sitting at, not on the host.
|
|
372
|
+
*/
|
|
373
|
+
private async finalizeDownload(
|
|
374
|
+
guid: string,
|
|
375
|
+
state: string,
|
|
376
|
+
transferDir: string,
|
|
377
|
+
totalBytes?: number
|
|
378
|
+
): Promise<void> {
|
|
379
|
+
const meta = this.downloads.get(guid);
|
|
380
|
+
this.downloads.delete(guid);
|
|
381
|
+
if (!meta) return;
|
|
382
|
+
|
|
383
|
+
const filePath = join(transferDir, guid);
|
|
384
|
+
|
|
385
|
+
if (state !== 'completed') {
|
|
386
|
+
await rm(filePath, { force: true }).catch(() => {});
|
|
387
|
+
this.emit('download', {
|
|
388
|
+
tabId: meta.tabId,
|
|
389
|
+
downloadId: guid,
|
|
390
|
+
filename: meta.filename,
|
|
391
|
+
url: meta.url,
|
|
392
|
+
state: 'failed',
|
|
393
|
+
error: 'Download was cancelled',
|
|
394
|
+
timestamp: Date.now()
|
|
395
|
+
} satisfies HostDownloadEvent);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
try {
|
|
400
|
+
const bytes = await readFile(filePath);
|
|
401
|
+
|
|
402
|
+
if (bytes.byteLength > MAX_RELAYED_DOWNLOAD_BYTES) {
|
|
403
|
+
this.emit('download', {
|
|
404
|
+
tabId: meta.tabId,
|
|
405
|
+
downloadId: guid,
|
|
406
|
+
filename: meta.filename,
|
|
407
|
+
url: meta.url,
|
|
408
|
+
state: 'failed',
|
|
409
|
+
totalBytes: bytes.byteLength,
|
|
410
|
+
error: `File is too large to transfer (${Math.round(bytes.byteLength / 1024 / 1024)}MB). Open the link in your own browser instead.`,
|
|
411
|
+
timestamp: Date.now()
|
|
412
|
+
} satisfies HostDownloadEvent);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
this.emit('download', {
|
|
417
|
+
tabId: meta.tabId,
|
|
418
|
+
downloadId: guid,
|
|
419
|
+
filename: meta.filename,
|
|
420
|
+
url: meta.url,
|
|
421
|
+
state: 'completed',
|
|
422
|
+
totalBytes: totalBytes ?? bytes.byteLength,
|
|
423
|
+
data: bytes.toString('base64'),
|
|
424
|
+
timestamp: Date.now()
|
|
425
|
+
} satisfies HostDownloadEvent);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
this.emit('download', {
|
|
428
|
+
tabId: meta.tabId,
|
|
429
|
+
downloadId: guid,
|
|
430
|
+
filename: meta.filename,
|
|
431
|
+
url: meta.url,
|
|
432
|
+
state: 'failed',
|
|
433
|
+
error: error instanceof Error ? error.message : 'Failed to read the downloaded file',
|
|
434
|
+
timestamp: Date.now()
|
|
435
|
+
} satisfies HostDownloadEvent);
|
|
436
|
+
} finally {
|
|
437
|
+
await rm(filePath, { force: true }).catch(() => {});
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// ── Lifecycle ───────────────────────────────────────────────────────────
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Release a tab: settle anything it left pending so the renderer's promises
|
|
445
|
+
* do not dangle, then drop the scratch directory.
|
|
446
|
+
*/
|
|
447
|
+
async teardown(tabId: string): Promise<void> {
|
|
448
|
+
for (const [requestId, pending] of this.pending) {
|
|
449
|
+
if (pending.tabId !== tabId) continue;
|
|
450
|
+
clearTimeout(pending.timeout);
|
|
451
|
+
this.pending.delete(requestId);
|
|
452
|
+
this.emit('request-settled', { tabId, requestId });
|
|
453
|
+
pending.resolve({ ok: false, error: { name: 'AbortError', message: 'Tab closed' } });
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const entry = this.tabs.get(tabId);
|
|
457
|
+
this.tabs.delete(tabId);
|
|
458
|
+
if (!entry) return;
|
|
459
|
+
|
|
460
|
+
if (entry.cdp) {
|
|
461
|
+
await entry.cdp.detach().catch(() => {});
|
|
462
|
+
}
|
|
463
|
+
await rm(entry.transferDir, { recursive: true, force: true }).catch(() => {});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async cleanup(): Promise<void> {
|
|
467
|
+
const tabIds = Array.from(this.tabs.keys());
|
|
468
|
+
await Promise.all(tabIds.map((tabId) => this.teardown(tabId)));
|
|
469
|
+
this.downloads.clear();
|
|
470
|
+
}
|
|
471
|
+
}
|