@myrialabs/clopen 0.4.46 → 0.4.48
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 +11 -11
- package/backend/artifacts/project/sources.ts +1 -1
- package/backend/auth/auth-service.ts +52 -358
- package/backend/auth/onboarding.test.ts +2 -3
- package/backend/auth/permissions.test.ts +10 -20
- package/backend/auth/permissions.ts +4 -290
- package/backend/auth/rate-limiter.test.ts +8 -9
- package/backend/auth/rate-limiter.ts +0 -2
- package/backend/auth/tokens.ts +1 -8
- package/backend/bootstrap.ts +7 -0
- package/backend/chat/attachments.test.ts +88 -0
- package/backend/chat/attachments.ts +159 -0
- package/backend/chat/engine-handoff.test.ts +0 -2
- package/backend/chat/stream-manager.ts +62 -62
- package/backend/chat/turn-answer.test.ts +64 -0
- package/backend/chat/turn-answer.ts +125 -0
- package/backend/chat-apps/awaiting.test.ts +39 -0
- package/backend/chat-apps/awaiting.ts +49 -0
- package/backend/chat-apps/conversation.ts +746 -0
- package/backend/chat-apps/inbound.ts +324 -0
- package/backend/chat-apps/index.ts +309 -0
- package/backend/chat-apps/link-events.ts +20 -0
- package/backend/chat-apps/media.test.ts +62 -0
- package/backend/chat-apps/media.ts +208 -0
- package/backend/chat-apps/messages.test.ts +229 -0
- package/backend/chat-apps/messages.ts +365 -0
- package/backend/chat-apps/outbound.ts +243 -0
- package/backend/chat-apps/pairing.test.ts +45 -0
- package/backend/chat-apps/pairing.ts +74 -0
- package/backend/chat-apps/platforms/index.ts +20 -0
- package/backend/chat-apps/platforms/telegram.test.ts +35 -0
- package/backend/chat-apps/platforms/telegram.ts +191 -0
- package/backend/chat-apps/platforms/types.ts +114 -0
- package/backend/chat-apps/questions.ts +133 -0
- package/backend/chat-apps/runtime.ts +572 -0
- package/backend/chat-apps/storage.test.ts +201 -0
- package/backend/chat-apps/turns.test.ts +45 -0
- package/backend/chat-apps/turns.ts +208 -0
- package/backend/containers/pty.ts +3 -11
- package/backend/control/actions/accounts.ts +89 -0
- package/backend/control/actions/files.ts +116 -0
- package/backend/control/actions/models.ts +188 -0
- package/backend/control/actions/projects.ts +272 -0
- package/backend/control/actions/sessions.ts +280 -0
- package/backend/control/actions/skills.ts +111 -0
- package/backend/control/control.test.ts +169 -0
- package/backend/control/define.ts +20 -0
- package/backend/control/folders.test.ts +67 -0
- package/backend/control/index.ts +213 -0
- package/backend/control/invoke.ts +44 -0
- package/backend/control/links.ts +35 -0
- package/backend/control/paging.ts +26 -0
- package/backend/control/types.ts +117 -0
- package/backend/control/workspace.ts +127 -0
- package/backend/database/migrations/084_create_channel_links.ts +71 -0
- package/backend/database/migrations/085_add_home_projects.ts +36 -0
- package/backend/database/migrations/086_single_owner.test.ts +170 -0
- package/backend/database/migrations/086_single_owner.ts +418 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/channel-queries.ts +270 -0
- package/backend/database/queries/db-client-connection-queries.ts +18 -56
- package/backend/database/queries/file-share-queries.ts +5 -23
- package/backend/database/queries/git-identity-queries.ts +31 -42
- package/backend/database/queries/graph-queries.ts +1 -1
- package/backend/database/queries/index.ts +13 -1
- package/backend/database/queries/message-queries.test.ts +146 -0
- package/backend/database/queries/message-queries.ts +42 -1
- package/backend/database/queries/permission-set-queries.ts +1 -1
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
- package/backend/database/queries/project-queries.ts +50 -63
- package/backend/database/queries/session-queries.ts +28 -56
- package/backend/database/queries/ssh-connection-queries.ts +18 -41
- package/backend/db-client/integrations/projector.ts +0 -5
- package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
- package/backend/engine/adapters/claude/message-converter.ts +25 -2
- package/backend/engine/adapters/cline/message-converter.ts +0 -1
- package/backend/engine/adapters/cline/stream.ts +11 -15
- package/backend/engine/adapters/codex/message-converter.ts +0 -2
- package/backend/engine/adapters/copilot/message-converter.ts +1 -2
- package/backend/engine/adapters/cursor/message-converter.ts +0 -1
- package/backend/engine/adapters/opencode/message-converter.ts +2 -4
- package/backend/engine/adapters/opencode/presets.ts +27 -2
- package/backend/engine/adapters/opencode/server.ts +6 -4
- package/backend/engine/adapters/opencode/stream.ts +11 -0
- package/backend/engine/adapters/parent-scope.test.ts +38 -0
- package/backend/engine/adapters/parent-scope.ts +44 -0
- package/backend/engine/adapters/pi/message-converter.ts +0 -1
- package/backend/engine/adapters/pi/stream.ts +4 -5
- package/backend/engine/adapters/qwen/message-converter.ts +0 -2
- package/backend/engine/bootstrap-default-engine.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +8 -1
- package/backend/engine/install-runner.ts +8 -17
- package/backend/files/file-shares.ts +20 -44
- package/backend/files/file-size-limit.ts +3 -3
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/git-executor.ts +25 -5
- package/backend/git/git-service.ts +420 -19
- package/backend/git/identity/credential-helper.test.ts +2 -7
- package/backend/git/identity/import-local.test.ts +11 -16
- package/backend/git/identity/import-local.ts +12 -12
- package/backend/git/identity/index.ts +10 -24
- package/backend/git/identity/resolve.ts +13 -14
- package/backend/git/identity/scope-config.ts +33 -28
- package/backend/git/identity/service.ts +44 -47
- package/backend/git/op-lock.test.ts +111 -0
- package/backend/git/op-lock.ts +180 -0
- package/backend/git/remote-sync.test.ts +249 -0
- package/backend/host/metrics.ts +1 -1
- package/backend/http/bearer-auth.ts +1 -2
- package/backend/http/files-download.test.ts +8 -9
- package/backend/http/files-download.ts +2 -2
- package/backend/http/files-shared.test.ts +62 -89
- package/backend/http/files-shared.ts +2 -2
- package/backend/http/files-upload.test.ts +3 -7
- package/backend/http/files-upload.ts +3 -3
- package/backend/http/notes-images.test.ts +15 -38
- package/backend/http/notes-images.ts +6 -8
- package/backend/http/ssh-sftp.ts +5 -10
- package/backend/index.ts +21 -7
- package/backend/integrations/accounts.ts +61 -3
- package/backend/integrations/index.ts +2 -2
- package/backend/integrations/registry/define.ts +15 -0
- package/backend/integrations/registry/index.ts +2 -0
- package/backend/integrations/registry/providers/telegram.ts +54 -0
- package/backend/integrations/registry/types.ts +21 -1
- package/backend/integrations/webhooks/gateway.ts +7 -6
- package/backend/integrations/webhooks/verify.test.ts +30 -0
- package/backend/integrations/webhooks/verify.ts +4 -0
- package/backend/mcp/external/project.ts +1 -1
- package/backend/mcp/internal/remote-server.test.ts +1 -3
- package/backend/mcp/internal/remote-server.ts +4 -4
- package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
- package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
- package/backend/memory/redact.ts +1 -1
- package/backend/notes/access.test.ts +28 -29
- package/backend/notes/access.ts +6 -11
- package/backend/permissions/service.ts +1 -1
- package/backend/preview/browser/browser-clipboard.test.ts +46 -0
- package/backend/preview/browser/browser-clipboard.ts +67 -0
- package/backend/preview/browser/browser-dialog-handler.ts +95 -6
- package/backend/preview/browser/browser-host-bridge.ts +9 -0
- package/backend/preview/browser/browser-interaction-handler.ts +316 -86
- package/backend/preview/browser/browser-mcp-control.ts +34 -0
- package/backend/preview/browser/browser-pool.ts +67 -6
- package/backend/preview/browser/browser-preview-service.ts +361 -25
- package/backend/preview/browser/browser-tab-manager.ts +66 -23
- package/backend/preview/browser/browser-video-capture.ts +92 -5
- package/backend/preview/browser/element-locator.ts +190 -17
- package/backend/preview/browser/keyboard-chords.test.ts +68 -0
- package/backend/preview/browser/keyboard-chords.ts +132 -0
- package/backend/preview/browser/paste.ts +81 -0
- package/backend/preview/browser/process-usage.ts +142 -0
- package/backend/preview/browser/profile-lock.ts +209 -0
- package/backend/preview/browser/scripts/host-bridge.ts +59 -0
- package/backend/preview/browser/scripts/video-stream.ts +58 -0
- package/backend/preview/browser/types.ts +40 -2
- package/backend/preview/browser/viewport.test.ts +45 -0
- package/backend/preview/browser/viewport.ts +96 -0
- package/backend/profiles/service.ts +2 -2
- package/backend/project/status-manager.ts +43 -172
- package/backend/projects/home.ts +61 -0
- package/backend/projects/project-cleanup.integration.test.ts +2 -2
- package/backend/projects/project-cleanup.ts +0 -8
- package/backend/skills/service.ts +2 -3
- package/backend/snapshot/helpers.ts +0 -1
- package/backend/snapshot/restore.ts +252 -0
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +5 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws.ts +61 -154
- package/backend/worktrees/branching/engine.ts +3 -16
- package/backend/worktrees/branching/index.ts +1 -1
- package/backend/worktrees/branching/projector.ts +1 -1
- package/backend/worktrees/branching/service.ts +13 -25
- package/backend/ws/access.ts +12 -21
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/auth/device.ts +16 -71
- package/backend/ws/auth/index.ts +4 -22
- package/backend/ws/auth/login.test.ts +14 -60
- package/backend/ws/auth/login.ts +24 -124
- package/backend/ws/auth/status.ts +0 -1
- package/backend/ws/chat/composer.ts +118 -118
- package/backend/ws/chat/stream.ts +64 -47
- package/backend/ws/chat-apps/index.ts +117 -0
- package/backend/ws/containers/actions.ts +11 -25
- package/backend/ws/containers/index.ts +3 -4
- package/backend/ws/containers/list.ts +10 -36
- package/backend/ws/containers/logs.ts +2 -2
- package/backend/ws/containers/tunnel.ts +1 -2
- package/backend/ws/db-client/access.ts +2 -16
- package/backend/ws/db-client/accounts.ts +5 -15
- package/backend/ws/db-client/connections.ts +17 -25
- package/backend/ws/db-client/context.ts +1 -1
- package/backend/ws/db-client/env.ts +7 -10
- package/backend/ws/db-client/index.ts +2 -2
- package/backend/ws/db-client/io.ts +5 -5
- package/backend/ws/db-client/query-history-retention.test.ts +8 -8
- package/backend/ws/db-client/query.ts +18 -17
- package/backend/ws/db-client/schema.ts +13 -13
- package/backend/ws/db-client/structure.ts +35 -35
- package/backend/ws/db-client/supabase.ts +4 -21
- package/backend/ws/deployments/context.ts +1 -1
- package/backend/ws/deployments/crud.ts +0 -5
- package/backend/ws/engine/access.ts +7 -20
- package/backend/ws/engine/claude/accounts.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +5 -5
- package/backend/ws/engine/codex/accounts.ts +3 -3
- package/backend/ws/engine/opencode/providers.ts +2 -1
- package/backend/ws/engine/pi/accounts.ts +5 -5
- package/backend/ws/files/clipboard.ts +8 -27
- package/backend/ws/files/image-edit.ts +6 -6
- package/backend/ws/files/index.ts +1 -1
- package/backend/ws/files/path-access.test.ts +32 -131
- package/backend/ws/files/path-access.ts +8 -87
- package/backend/ws/files/read.ts +15 -19
- package/backend/ws/files/reveal.ts +3 -3
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/share.ts +9 -13
- package/backend/ws/files/state.ts +9 -12
- package/backend/ws/files/watch.ts +3 -3
- package/backend/ws/files/write.ts +30 -31
- package/backend/ws/git/branch.ts +80 -59
- package/backend/ws/git/commit.ts +63 -44
- package/backend/ws/git/conflict.ts +16 -18
- package/backend/ws/git/identity-context.ts +8 -17
- package/backend/ws/git/identity.ts +17 -27
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/op-state.ts +139 -0
- package/backend/ws/git/remote.ts +241 -141
- package/backend/ws/git/repo-context.ts +67 -0
- package/backend/ws/git/staging.ts +18 -28
- package/backend/ws/git/status.ts +5 -2
- package/backend/ws/index.ts +5 -1
- package/backend/ws/instructions/crud.ts +1 -1
- package/backend/ws/integrations/crud.ts +1 -3
- package/backend/ws/mcp/crud.ts +3 -5
- package/backend/ws/mcp/tools.ts +1 -1
- package/backend/ws/memory/crud.ts +14 -46
- package/backend/ws/memory/index.ts +2 -2
- package/backend/ws/messages/crud.ts +29 -8
- package/backend/ws/notes/index.ts +33 -39
- package/backend/ws/permissions/crud.ts +3 -4
- package/backend/ws/ports/index.ts +1 -2
- package/backend/ws/ports/kill.ts +5 -10
- package/backend/ws/ports/list.ts +4 -10
- package/backend/ws/preview/access.ts +1 -1
- package/backend/ws/preview/browser/interact.ts +52 -79
- package/backend/ws/preview/browser/native-ui.ts +24 -0
- package/backend/ws/preview/browser/stats.ts +98 -1
- package/backend/ws/preview/browser/tab-info.ts +15 -0
- package/backend/ws/preview/browser/tab.ts +19 -4
- package/backend/ws/preview/index.ts +27 -0
- package/backend/ws/profiles/crud.ts +6 -8
- package/backend/ws/project-artifacts/index.ts +30 -31
- package/backend/ws/projects/crud.ts +33 -35
- package/backend/ws/projects/index.ts +3 -8
- package/backend/ws/projects/info.ts +3 -3
- package/backend/ws/projects/overview.ts +19 -30
- package/backend/ws/projects/status.ts +17 -57
- package/backend/ws/sessions/crud.ts +34 -45
- package/backend/ws/sessions/index.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/skills/crud.ts +3 -4
- package/backend/ws/skills/index.ts +1 -1
- package/backend/ws/snapshot/changes.ts +7 -7
- package/backend/ws/snapshot/restore.ts +11 -295
- package/backend/ws/snapshot/timeline.ts +2 -4
- package/backend/ws/ssh/access.ts +6 -21
- package/backend/ws/ssh/connections.ts +21 -31
- package/backend/ws/ssh/forwards.ts +12 -12
- package/backend/ws/ssh/sftp.ts +34 -34
- package/backend/ws/ssh/tunnel.ts +1 -2
- package/backend/ws/stack/install.ts +7 -17
- package/backend/ws/subagents/crud.ts +1 -1
- package/backend/ws/tunnel/share.ts +0 -2
- package/backend/ws/user/crud.ts +1 -59
- package/backend/ws/user/index.ts +1 -1
- package/backend/ws/work/context.ts +1 -1
- package/backend/ws/work/crud.ts +0 -5
- package/backend/ws/workspace/state.ts +10 -13
- package/backend/ws/worktrees/branching.ts +7 -36
- package/backend/ws/worktrees/crud.ts +2 -2
- package/bin/clopen.ts +10 -11
- package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
- package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
- package/dist/assets/main-BUiUL3eZ.css +1 -0
- package/dist/assets/main-nBOb9YOA.js +1240 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/constants/attachments.ts +14 -0
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/preview.test.ts +259 -0
- package/shared/constants/preview.ts +1018 -57
- package/shared/constants/tool-icons.ts +5 -0
- package/shared/types/containers/container.ts +1 -1
- package/shared/types/database/schema.ts +9 -6
- package/shared/types/git-identity.ts +1 -1
- package/shared/types/git.ts +116 -0
- package/shared/types/integrations.ts +7 -0
- package/shared/types/stores/settings.ts +1 -1
- package/shared/types/unified/index.ts +1 -1
- package/shared/types/unified/message.ts +0 -7
- package/shared/types/unified/stream.ts +2 -4
- package/shared/types/unified/tool.ts +15 -1
- package/shared/utils/ask-user-question.test.ts +319 -0
- package/shared/utils/ask-user-question.ts +154 -0
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/ws-server.ts +32 -7
- package/backend/auth/session-invalidation.test.ts +0 -112
- package/backend/auth/session-invalidation.ts +0 -77
- package/backend/project/status-manager.test.ts +0 -32
- package/backend/ws/auth/invites.ts +0 -94
- package/backend/ws/auth/users.ts +0 -112
- package/backend/ws/projects/presence.ts +0 -46
- package/backend/ws/stack/access.ts +0 -31
- package/dist/assets/main-BiDNMWb3.css +0 -1
- package/dist/assets/main-BlhKWz2B.js +0 -1241
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Browser, BrowserContext, Page, Target } from 'puppeteer';
|
|
2
2
|
import { EventEmitter } from 'events';
|
|
3
|
-
import {
|
|
4
|
-
import type { BrowserTab, BrowserTabInfo, DeviceSize, Rotation } from './types';
|
|
3
|
+
import { planDevice, type DeviceRequest } from '$shared/constants/preview.js';
|
|
4
|
+
import type { BrowserTab, BrowserTabInfo, DeviceSize, Rotation, ViewportSize } from './types';
|
|
5
|
+
import { applyDevice, mergeEmulation, type EmulatedDevice, type EmulationPatch } from './viewport';
|
|
5
6
|
import { DEFAULT_STREAMING_CONFIG } from './types';
|
|
6
7
|
import { browserPool, type PooledSession } from './browser-pool';
|
|
7
8
|
import { BrowserAudioCapture } from './browser-audio-capture';
|
|
@@ -194,8 +195,24 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
194
195
|
preNavigationSetup?: (page: Page, tabId: string) => Promise<void>;
|
|
195
196
|
/** Client-minted name for this launch, so Stop can reach it. */
|
|
196
197
|
launchId?: string;
|
|
198
|
+
/** An exact size; the model's own size when omitted. */
|
|
199
|
+
viewport?: ViewportSize | null;
|
|
200
|
+
/** The device model; the class default when omitted. */
|
|
201
|
+
deviceModel?: string | null;
|
|
202
|
+
/** Device settings on top of the model. */
|
|
203
|
+
emulation?: EmulationPatch | null;
|
|
197
204
|
}
|
|
198
205
|
): Promise<BrowserTab> {
|
|
206
|
+
const device = planDevice(null, {
|
|
207
|
+
deviceSize,
|
|
208
|
+
rotation,
|
|
209
|
+
size: options?.viewport,
|
|
210
|
+
deviceModel: options?.deviceModel
|
|
211
|
+
});
|
|
212
|
+
const { viewport, deviceModel } = device;
|
|
213
|
+
rotation = device.rotation;
|
|
214
|
+
const emulation = mergeEmulation({}, options?.emulation);
|
|
215
|
+
|
|
199
216
|
// The counter restarts per workspace, so the scope token is what stops a
|
|
200
217
|
// worktree's `tab-1` from being matched as the main tree's on the client.
|
|
201
218
|
const tabId = `tab-${scopeSlug(this.projectId)}-${this.nextTabNumber++}`;
|
|
@@ -244,7 +261,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
244
261
|
|
|
245
262
|
// Setup page (viewport, headers, etc.)
|
|
246
263
|
debug.log('preview', `⚙️ Setting up page...`);
|
|
247
|
-
await this.setupPage(page, deviceSize,
|
|
264
|
+
await this.setupPage(page, { deviceSize, viewport, emulation });
|
|
248
265
|
debug.log('preview', `✅ Page setup complete`);
|
|
249
266
|
|
|
250
267
|
// Run pre-navigation setup if provided (e.g., dialog handling)
|
|
@@ -295,6 +312,9 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
295
312
|
// Device
|
|
296
313
|
deviceSize,
|
|
297
314
|
rotation,
|
|
315
|
+
viewport,
|
|
316
|
+
deviceModel,
|
|
317
|
+
emulation,
|
|
298
318
|
|
|
299
319
|
// Console
|
|
300
320
|
consoleLogs: [],
|
|
@@ -342,6 +362,9 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
342
362
|
isActive: tab.isActive,
|
|
343
363
|
deviceSize: tab.deviceSize,
|
|
344
364
|
rotation: tab.rotation,
|
|
365
|
+
width: tab.viewport.width,
|
|
366
|
+
height: tab.viewport.height,
|
|
367
|
+
deviceModel: tab.deviceModel,
|
|
345
368
|
// Echoed so the client can tie this tab to the launch it started,
|
|
346
369
|
// rather than guessing from "some tab is launching" — which stopped
|
|
347
370
|
// being true the moment the user pressed Stop.
|
|
@@ -632,25 +655,39 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
632
655
|
}
|
|
633
656
|
|
|
634
657
|
/**
|
|
635
|
-
* Change
|
|
658
|
+
* Change the device a tab is shown on: its class, model, orientation, exact
|
|
659
|
+
* size, and the device settings on top. See `planDevice` for how a partial
|
|
660
|
+
* request is completed; `emulation` fields left out keep their value and
|
|
661
|
+
* `null` hands them back to the device.
|
|
636
662
|
*/
|
|
637
|
-
async setViewport(
|
|
663
|
+
async setViewport(
|
|
664
|
+
tabId: string,
|
|
665
|
+
request: DeviceRequest & { emulation?: EmulationPatch | null }
|
|
666
|
+
): Promise<boolean> {
|
|
638
667
|
const tab = this.tabs.get(tabId);
|
|
639
668
|
if (!tab) {
|
|
640
669
|
debug.warn('preview', `❌ Cannot set viewport: Tab ${tabId} not found`);
|
|
641
670
|
return false;
|
|
642
671
|
}
|
|
643
672
|
|
|
644
|
-
|
|
645
|
-
|
|
673
|
+
const next = planDevice(
|
|
674
|
+
{ deviceSize: tab.deviceSize, rotation: tab.rotation, viewport: tab.viewport, deviceModel: tab.deviceModel },
|
|
675
|
+
request
|
|
676
|
+
);
|
|
677
|
+
const emulation = mergeEmulation(tab.emulation, request.emulation);
|
|
678
|
+
const { width: viewportWidth, height: viewportHeight } = next.viewport;
|
|
646
679
|
|
|
647
680
|
try {
|
|
648
|
-
//
|
|
649
|
-
|
|
681
|
+
// Metadata first: a touch or mobile change reloads the page, and
|
|
682
|
+
// anything that asks the tab for its viewport while that runs must
|
|
683
|
+
// get the new one.
|
|
684
|
+
tab.deviceSize = next.deviceSize;
|
|
685
|
+
tab.rotation = next.rotation;
|
|
686
|
+
tab.viewport = next.viewport;
|
|
687
|
+
tab.deviceModel = next.deviceModel;
|
|
688
|
+
tab.emulation = emulation;
|
|
650
689
|
|
|
651
|
-
|
|
652
|
-
tab.deviceSize = deviceSize;
|
|
653
|
-
tab.rotation = rotation;
|
|
690
|
+
await applyDevice(tab.page, tab);
|
|
654
691
|
|
|
655
692
|
// Mark tab activity
|
|
656
693
|
this.markTabActivity(tabId);
|
|
@@ -658,14 +695,15 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
658
695
|
// Emit viewport changed event
|
|
659
696
|
this.emit('preview:browser-viewport-changed', {
|
|
660
697
|
tabId,
|
|
661
|
-
deviceSize,
|
|
662
|
-
rotation,
|
|
698
|
+
deviceSize: next.deviceSize,
|
|
699
|
+
rotation: next.rotation,
|
|
663
700
|
width: viewportWidth,
|
|
664
701
|
height: viewportHeight,
|
|
702
|
+
deviceModel: next.deviceModel,
|
|
665
703
|
timestamp: Date.now()
|
|
666
704
|
});
|
|
667
705
|
|
|
668
|
-
debug.log('preview', `📱 Viewport changed for tab ${tabId}: ${deviceSize} (${rotation}) - ${viewportWidth}x${viewportHeight}`);
|
|
706
|
+
debug.log('preview', `📱 Viewport changed for tab ${tabId}: ${next.deviceModel ?? next.deviceSize} (${next.rotation}) - ${viewportWidth}x${viewportHeight}`);
|
|
669
707
|
|
|
670
708
|
return true;
|
|
671
709
|
} catch (error) {
|
|
@@ -718,6 +756,10 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
718
756
|
isStreaming: tab.isStreaming,
|
|
719
757
|
deviceSize: tab.deviceSize,
|
|
720
758
|
rotation: tab.rotation,
|
|
759
|
+
width: tab.viewport.width,
|
|
760
|
+
height: tab.viewport.height,
|
|
761
|
+
deviceModel: tab.deviceModel,
|
|
762
|
+
emulation: tab.emulation,
|
|
721
763
|
isActive: tab.isActive,
|
|
722
764
|
canGoBack: tab.canGoBack,
|
|
723
765
|
canGoForward: tab.canGoForward
|
|
@@ -737,6 +779,10 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
737
779
|
isStreaming: tab.isStreaming,
|
|
738
780
|
deviceSize: tab.deviceSize,
|
|
739
781
|
rotation: tab.rotation,
|
|
782
|
+
width: tab.viewport.width,
|
|
783
|
+
height: tab.viewport.height,
|
|
784
|
+
deviceModel: tab.deviceModel,
|
|
785
|
+
emulation: tab.emulation,
|
|
740
786
|
isActive: tab.isActive,
|
|
741
787
|
canGoBack: tab.canGoBack,
|
|
742
788
|
canGoForward: tab.canGoForward
|
|
@@ -917,7 +963,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
917
963
|
tab.canGoBack = false;
|
|
918
964
|
tab.canGoForward = false;
|
|
919
965
|
|
|
920
|
-
await this.setupPage(pooled.page, tab
|
|
966
|
+
await this.setupPage(pooled.page, tab);
|
|
921
967
|
|
|
922
968
|
const setupHook = this.tabSetupHooks.get(tabId);
|
|
923
969
|
if (setupHook) {
|
|
@@ -983,11 +1029,8 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
983
1029
|
/**
|
|
984
1030
|
* Setup page (viewport, headers, injections)
|
|
985
1031
|
*/
|
|
986
|
-
private async setupPage(page: Page,
|
|
987
|
-
|
|
988
|
-
const { width: viewportWidth, height: viewportHeight } = getViewportDimensions(deviceSize, rotation);
|
|
989
|
-
|
|
990
|
-
await page.setViewport({ width: viewportWidth, height: viewportHeight });
|
|
1032
|
+
private async setupPage(page: Page, device: EmulatedDevice) {
|
|
1033
|
+
await applyDevice(page, device);
|
|
991
1034
|
|
|
992
1035
|
// Set page timeouts - more generous for stability
|
|
993
1036
|
page.setDefaultTimeout(30000);
|
|
@@ -1630,7 +1673,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1630
1673
|
debug.log('preview', `🧹 Cleaning up ${this.tabs.size} tabs...`);
|
|
1631
1674
|
|
|
1632
1675
|
// Every page below is about to be closed on purpose; none of them is a
|
|
1633
|
-
// crash to rebuild from. Restored at the end:
|
|
1676
|
+
// crash to rebuild from. Restored at the end: a "clean up all"
|
|
1634
1677
|
// leaves the manager in service, and the tabs opened after it must be
|
|
1635
1678
|
// able to recover like any other.
|
|
1636
1679
|
const wasShuttingDown = this.shuttingDown;
|
|
@@ -1678,7 +1721,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1678
1721
|
|
|
1679
1722
|
// Deliberately NOT browserPool.cleanup(): that reaches every workspace's
|
|
1680
1723
|
// Chrome, and calling it from one workspace's teardown — deleting a
|
|
1681
|
-
// worktree,
|
|
1724
|
+
// worktree, a "clean up all" — took every other project's
|
|
1682
1725
|
// preview tabs down with it. Our own sessions are already gone with the
|
|
1683
1726
|
// tabs above; the pool closes this workspace's Chrome once its last
|
|
1684
1727
|
// session goes, and every Chrome on process shutdown.
|
|
@@ -41,6 +41,7 @@ import type {
|
|
|
41
41
|
import { DEFAULT_STREAMING_CONFIG, resolveCodecCandidates } from './types';
|
|
42
42
|
import { videoEncoderScript } from './scripts/video-stream';
|
|
43
43
|
import { audioCaptureScript } from './scripts/audio-stream';
|
|
44
|
+
import { applyViewport } from './viewport';
|
|
44
45
|
|
|
45
46
|
/**
|
|
46
47
|
* Install the audio tap in every frame.
|
|
@@ -237,6 +238,19 @@ const DEFAULT_CODEC_SUPPORT: ClientCodecSupport = {
|
|
|
237
238
|
hardware: []
|
|
238
239
|
};
|
|
239
240
|
|
|
241
|
+
/** Aspect disagreement between the captured surface and the page that counts as drift. */
|
|
242
|
+
const SURFACE_DRIFT_TOLERANCE = 0.03;
|
|
243
|
+
|
|
244
|
+
/** How long a mismatch must last before it counts as drift rather than a resize in flight. */
|
|
245
|
+
const SURFACE_DRIFT_GRACE_MS = 250;
|
|
246
|
+
|
|
247
|
+
/** Minimum gap between two viewport restores asked for by the same tab. */
|
|
248
|
+
const SURFACE_DRIFT_COOLDOWN_MS = 1500;
|
|
249
|
+
|
|
250
|
+
/** Restores a tab may ask for within SURFACE_DRIFT_WINDOW_MS before frames are let through. */
|
|
251
|
+
const SURFACE_DRIFT_MAX_RESTORES = 3;
|
|
252
|
+
const SURFACE_DRIFT_WINDOW_MS = 30_000;
|
|
253
|
+
|
|
240
254
|
/**
|
|
241
255
|
* CDP screencast feeder with ack-gated flow control.
|
|
242
256
|
*
|
|
@@ -264,6 +278,8 @@ class ScreencastFeeder {
|
|
|
264
278
|
private lastDispatchAt = 0;
|
|
265
279
|
private lastAckAt = 0;
|
|
266
280
|
private pendingAckId: number | null = null;
|
|
281
|
+
/** When the surface first stopped matching the page, or 0. */
|
|
282
|
+
private driftSince = 0;
|
|
267
283
|
|
|
268
284
|
constructor(
|
|
269
285
|
private readonly cdp: CDPSession,
|
|
@@ -271,7 +287,9 @@ class ScreencastFeeder {
|
|
|
271
287
|
private readonly getSession: () => VideoStreamSession | undefined,
|
|
272
288
|
private readonly getTab: () => BrowserTab | undefined,
|
|
273
289
|
private readonly onInvalidSession: () => void,
|
|
274
|
-
private readonly isValidSession: () => boolean
|
|
290
|
+
private readonly isValidSession: () => boolean,
|
|
291
|
+
/** Returns whether a restore is under way (and the frame should be held back). */
|
|
292
|
+
private readonly onSurfaceDrift: (width: number, height: number) => boolean
|
|
275
293
|
) {
|
|
276
294
|
this.cdp.on('Page.screencastFrame', (event: any) => this.handleFrame(event));
|
|
277
295
|
}
|
|
@@ -407,6 +425,31 @@ class ScreencastFeeder {
|
|
|
407
425
|
return;
|
|
408
426
|
}
|
|
409
427
|
|
|
428
|
+
// A surface stranded by Chrome's fullscreen produces frames of the wrong
|
|
429
|
+
// shape. They are not forwarded — the viewer keeps the last good one —
|
|
430
|
+
// and the host is told so it can put the viewport back.
|
|
431
|
+
const surfaceWidth = Number(event.metadata?.deviceWidth) || 0;
|
|
432
|
+
const surfaceHeight = Number(event.metadata?.deviceHeight) || 0;
|
|
433
|
+
const viewport = tab?.page.viewport();
|
|
434
|
+
if (viewport && surfaceWidth > 0 && surfaceHeight > 0) {
|
|
435
|
+
const expected = viewport.width / viewport.height;
|
|
436
|
+
const drifted = Math.abs(surfaceWidth / surfaceHeight - expected) / expected > SURFACE_DRIFT_TOLERANCE;
|
|
437
|
+
if (!drifted) {
|
|
438
|
+
this.driftSince = 0;
|
|
439
|
+
} else {
|
|
440
|
+
// A device-size change leaves a frame or two of the old shape in
|
|
441
|
+
// flight; those are held back but are not worth a restore.
|
|
442
|
+
const now = Date.now();
|
|
443
|
+
if (!this.driftSince) this.driftSince = now;
|
|
444
|
+
const restoring =
|
|
445
|
+
now - this.driftSince < SURFACE_DRIFT_GRACE_MS || this.onSurfaceDrift(surfaceWidth, surfaceHeight);
|
|
446
|
+
if (restoring) {
|
|
447
|
+
this.ack(event.sessionId);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
410
453
|
const now = Date.now();
|
|
411
454
|
const interval = this.frameIntervalMs;
|
|
412
455
|
|
|
@@ -621,6 +664,12 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
621
664
|
private epochCounter = 0;
|
|
622
665
|
private watchdogTimer: ReturnType<typeof setInterval> | null = null;
|
|
623
666
|
|
|
667
|
+
/** Per tab: when a surface drift last asked for a restore. */
|
|
668
|
+
private lastDriftReportAt = new Map<string, number>();
|
|
669
|
+
|
|
670
|
+
/** Per tab: restores asked for within the current window. */
|
|
671
|
+
private driftRestores = new Map<string, number[]>();
|
|
672
|
+
|
|
624
673
|
constructor() {
|
|
625
674
|
super();
|
|
626
675
|
}
|
|
@@ -897,6 +946,11 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
897
946
|
this.applyEncoderStats(sessionId, stats);
|
|
898
947
|
});
|
|
899
948
|
|
|
949
|
+
// The captured surface stopped matching the page — see video-stream.ts.
|
|
950
|
+
await expose('__reportSurfaceDrift', (width: number, height: number) => {
|
|
951
|
+
this.reportSurfaceDrift(sessionId, width, height);
|
|
952
|
+
});
|
|
953
|
+
|
|
900
954
|
state.bindingsExposed = true;
|
|
901
955
|
}
|
|
902
956
|
|
|
@@ -1373,7 +1427,8 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
1373
1427
|
() => {
|
|
1374
1428
|
void this.stopStreaming(sessionId);
|
|
1375
1429
|
},
|
|
1376
|
-
isValidSession
|
|
1430
|
+
isValidSession,
|
|
1431
|
+
(width, height) => this.reportSurfaceDrift(sessionId, width, height)
|
|
1377
1432
|
);
|
|
1378
1433
|
|
|
1379
1434
|
this.feeders.set(sessionId, feeder);
|
|
@@ -2042,9 +2097,10 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
2042
2097
|
// ------------------------------------------------------------------
|
|
2043
2098
|
|
|
2044
2099
|
/**
|
|
2045
|
-
*
|
|
2100
|
+
* Re-apply the tab's viewport and recompute the capture around it, without
|
|
2101
|
+
* reconnecting (hot-swap). The size is the tab's own — see `BrowserTab.viewport`.
|
|
2046
2102
|
*/
|
|
2047
|
-
async updateViewport(sessionId: string, session: BrowserTab
|
|
2103
|
+
async updateViewport(sessionId: string, session: BrowserTab): Promise<boolean> {
|
|
2048
2104
|
const videoSession = this.sessions.get(sessionId);
|
|
2049
2105
|
if (!videoSession?.isActive || !session.page || session.page.isClosed()) {
|
|
2050
2106
|
debug.warn('webcodecs', `Cannot update viewport: session not active`);
|
|
@@ -2052,11 +2108,12 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
2052
2108
|
}
|
|
2053
2109
|
|
|
2054
2110
|
try {
|
|
2111
|
+
const { width, height } = session.viewport;
|
|
2055
2112
|
debug.log('webcodecs', `🔄 Hot-swapping viewport to ${width}x${height}`);
|
|
2056
2113
|
|
|
2057
2114
|
// The emulated viewport is what the page lays out against; capture
|
|
2058
2115
|
// resolution is derived from it and the viewer's display metrics.
|
|
2059
|
-
await session.page
|
|
2116
|
+
await applyViewport(session.page, session);
|
|
2060
2117
|
|
|
2061
2118
|
// Force a recompute even if the derived size happens to land close
|
|
2062
2119
|
// to the previous one — the page content changed shape.
|
|
@@ -2069,6 +2126,34 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
2069
2126
|
}
|
|
2070
2127
|
}
|
|
2071
2128
|
|
|
2129
|
+
/**
|
|
2130
|
+
* The captured surface no longer has the page's shape.
|
|
2131
|
+
*
|
|
2132
|
+
* Raised by the in-page encoder and by the screencast feeder; whoever owns
|
|
2133
|
+
* the tab re-asserts the viewport. Rate-limited per tab: the frames keep
|
|
2134
|
+
* arriving drifted until the restore lands, and each would otherwise ask
|
|
2135
|
+
* again.
|
|
2136
|
+
*/
|
|
2137
|
+
private reportSurfaceDrift(sessionId: string, width: number, height: number): boolean {
|
|
2138
|
+
const now = Date.now();
|
|
2139
|
+
const recent = (this.driftRestores.get(sessionId) ?? []).filter(
|
|
2140
|
+
(at) => now - at < SURFACE_DRIFT_WINDOW_MS
|
|
2141
|
+
);
|
|
2142
|
+
this.driftRestores.set(sessionId, recent);
|
|
2143
|
+
|
|
2144
|
+
// A drift that keeps coming back after several restores is not one this
|
|
2145
|
+
// can fix; the caller stops holding frames back rather than freezing.
|
|
2146
|
+
if (recent.length >= SURFACE_DRIFT_MAX_RESTORES) return false;
|
|
2147
|
+
|
|
2148
|
+
if (now - (this.lastDriftReportAt.get(sessionId) ?? 0) < SURFACE_DRIFT_COOLDOWN_MS) return true;
|
|
2149
|
+
this.lastDriftReportAt.set(sessionId, now);
|
|
2150
|
+
recent.push(now);
|
|
2151
|
+
|
|
2152
|
+
debug.warn('webcodecs', `📐 Captured surface drifted to ${width}x${height} on ${sessionId}; restoring the viewport`);
|
|
2153
|
+
this.emit('surface-drift', { sessionId, width, height });
|
|
2154
|
+
return true;
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2072
2157
|
/**
|
|
2073
2158
|
* Restart capture at the current geometry.
|
|
2074
2159
|
* Used as a refresh/recovery path when the frontend detects a stuck stream.
|
|
@@ -2178,6 +2263,8 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
2178
2263
|
* Stop video streaming
|
|
2179
2264
|
*/
|
|
2180
2265
|
async stopStreaming(sessionId: string, session?: BrowserTab): Promise<void> {
|
|
2266
|
+
this.lastDriftReportAt.delete(sessionId);
|
|
2267
|
+
this.driftRestores.delete(sessionId);
|
|
2181
2268
|
const videoSession = this.sessions.get(sessionId);
|
|
2182
2269
|
if (!videoSession) return;
|
|
2183
2270
|
|
|
@@ -68,24 +68,191 @@ interface ElementMeta {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
/**
|
|
71
|
-
*
|
|
71
|
+
* Rank the elements of one frame that a piece of visible text could mean.
|
|
72
72
|
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
73
|
+
* Runs inside the page, in a single round trip. Text alone is ambiguous in
|
|
74
|
+
* exactly the place agents use it most: "Click **Continue** to verify" sits
|
|
75
|
+
* right above a Continue button in the same modal, and taking the first match
|
|
76
|
+
* in document order clicked the bold word in the sentence. So every match is
|
|
77
|
+
* scored, the way a person picks the thing they meant:
|
|
78
|
+
*
|
|
79
|
+
* - **Exact** text beats a match that merely contains the words.
|
|
80
|
+
* - **Clickable** beats inert. A match inside a button, link, labelled
|
|
81
|
+
* control or `cursor: pointer` element is aimed at that element, not at
|
|
82
|
+
* the span holding the text.
|
|
83
|
+
* - **On top** beats covered: the element actually under its own centre is
|
|
84
|
+
* reachable; one behind a modal's backdrop is not.
|
|
85
|
+
* - Inside an open **dialog** beats the page behind it.
|
|
86
|
+
*
|
|
87
|
+
* Also matches what has no text node — `<input type=submit value=…>`,
|
|
88
|
+
* icon buttons named by `aria-label` or `title` — which a text search used to
|
|
89
|
+
* miss entirely.
|
|
90
|
+
*
|
|
91
|
+
* Self-contained on purpose: it is serialised into the page.
|
|
76
92
|
*/
|
|
77
|
-
function
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
93
|
+
function rankTextMatches(query: string, includeHidden: boolean, limit: number) {
|
|
94
|
+
const needle = query.replace(/\s+/g, ' ').trim().toLowerCase();
|
|
95
|
+
if (!needle) return [];
|
|
96
|
+
|
|
97
|
+
const norm = (value: string | null | undefined) => (value ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
|
|
98
|
+
|
|
99
|
+
const CLICKABLE_ROLES = new Set([
|
|
100
|
+
'button', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'option',
|
|
101
|
+
'checkbox', 'radio', 'switch', 'treeitem', 'gridcell'
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
const isClickable = (el: Element): boolean => {
|
|
105
|
+
const tag = el.tagName;
|
|
106
|
+
if (tag === 'BUTTON' || tag === 'SUMMARY' || tag === 'SELECT' || tag === 'LABEL') return true;
|
|
107
|
+
if (tag === 'A' && (el as HTMLAnchorElement).hasAttribute('href')) return true;
|
|
108
|
+
if (tag === 'INPUT') {
|
|
109
|
+
const type = ((el as HTMLInputElement).type || '').toLowerCase();
|
|
110
|
+
return ['button', 'submit', 'reset', 'checkbox', 'radio', 'image'].includes(type);
|
|
111
|
+
}
|
|
112
|
+
const role = el.getAttribute('role');
|
|
113
|
+
if (role && CLICKABLE_ROLES.has(role)) return true;
|
|
114
|
+
if (el.hasAttribute('onclick')) return true;
|
|
115
|
+
return false;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const isVisible = (el: Element): boolean => {
|
|
119
|
+
const rect = el.getBoundingClientRect();
|
|
120
|
+
if (rect.width <= 0 || rect.height <= 0) return false;
|
|
121
|
+
const style = window.getComputedStyle(el);
|
|
122
|
+
return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) !== 0;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** The control a click on this text would actually be aimed at. */
|
|
126
|
+
const actionableFor = (el: Element): { target: Element; clickable: boolean } => {
|
|
127
|
+
let node: Element | null = el;
|
|
128
|
+
for (let depth = 0; node && depth < 6; depth++) {
|
|
129
|
+
if (isClickable(node)) return { target: node, clickable: true };
|
|
130
|
+
node = node.parentElement ?? ((node.getRootNode() as ShadowRoot).host || null);
|
|
131
|
+
}
|
|
132
|
+
// No semantic control — a styled div with a click handler still shows a
|
|
133
|
+
// pointer cursor, which is the only hint the page gives.
|
|
134
|
+
node = el;
|
|
135
|
+
for (let depth = 0; node && depth < 4; depth++) {
|
|
136
|
+
if (window.getComputedStyle(node).cursor === 'pointer') return { target: node, clickable: true };
|
|
137
|
+
node = node.parentElement;
|
|
138
|
+
}
|
|
139
|
+
return { target: el, clickable: false };
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** Deepest element under a point, through open shadow roots. */
|
|
143
|
+
const hitAt = (x: number, y: number): Element | null => {
|
|
144
|
+
let hit = document.elementFromPoint(x, y);
|
|
145
|
+
while (hit && (hit as HTMLElement).shadowRoot) {
|
|
146
|
+
const inner = (hit as HTMLElement).shadowRoot!.elementFromPoint(x, y);
|
|
147
|
+
if (!inner || inner === hit) break;
|
|
148
|
+
hit = inner;
|
|
149
|
+
}
|
|
150
|
+
return hit;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const inDialog = (el: Element): boolean =>
|
|
154
|
+
!!el.closest('dialog[open], [role="dialog"], [role="alertdialog"], [aria-modal="true"]');
|
|
155
|
+
|
|
156
|
+
// Innermost elements whose text contains the query: descend only into
|
|
157
|
+
// branches that contain it, and stop where no child does.
|
|
158
|
+
const textMatches: Element[] = [];
|
|
159
|
+
const visit = (root: Element | ShadowRoot) => {
|
|
160
|
+
for (const child of Array.from(root.children)) {
|
|
161
|
+
const tag = child.tagName;
|
|
162
|
+
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT' || tag === 'TEMPLATE') continue;
|
|
163
|
+
const shadow = (child as HTMLElement).shadowRoot;
|
|
164
|
+
const contains = norm(child.textContent).includes(needle);
|
|
165
|
+
if (shadow) visit(shadow);
|
|
166
|
+
if (!contains) continue;
|
|
167
|
+
const deeper = Array.from(child.children).some((grand) => norm(grand.textContent).includes(needle));
|
|
168
|
+
if (deeper) visit(child);
|
|
169
|
+
else textMatches.push(child);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
if (document.body) visit(document.body);
|
|
173
|
+
|
|
174
|
+
// Elements named by an attribute rather than by text.
|
|
175
|
+
const named: Element[] = [];
|
|
176
|
+
for (const el of Array.from(document.querySelectorAll('input[type=submit], input[type=button], input[type=reset], [aria-label], [title]'))) {
|
|
177
|
+
const label = norm(
|
|
178
|
+
el.tagName === 'INPUT' ? (el as HTMLInputElement).value || el.getAttribute('aria-label') : el.getAttribute('aria-label') || el.getAttribute('title')
|
|
179
|
+
);
|
|
180
|
+
if (label.includes(needle)) named.push(el);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const order = new Map<Element, number>();
|
|
184
|
+
const scored = new Map<Element, { el: Element; score: number }>();
|
|
185
|
+
let position = 0;
|
|
186
|
+
|
|
187
|
+
for (const candidate of [...textMatches, ...named]) {
|
|
188
|
+
const { target, clickable } = actionableFor(candidate);
|
|
189
|
+
if (!order.has(target)) order.set(target, position++);
|
|
190
|
+
if (!includeHidden && !isVisible(target)) continue;
|
|
191
|
+
|
|
192
|
+
const ownText = norm(candidate.textContent) || norm(candidate.getAttribute('aria-label')) || norm((candidate as HTMLInputElement).value) || norm(candidate.getAttribute('title'));
|
|
193
|
+
const targetText = norm((target as HTMLElement).innerText ?? target.textContent);
|
|
194
|
+
|
|
195
|
+
let score = 0;
|
|
196
|
+
if (ownText === needle || targetText === needle) score += 100;
|
|
197
|
+
else if (ownText.startsWith(needle) || targetText.startsWith(needle)) score += 40;
|
|
198
|
+
else score += 10;
|
|
199
|
+
|
|
200
|
+
if (clickable) score += 50;
|
|
201
|
+
if ((target as HTMLButtonElement).disabled) score -= 30;
|
|
202
|
+
if (inDialog(target)) score += 20;
|
|
203
|
+
|
|
204
|
+
const rect = target.getBoundingClientRect();
|
|
205
|
+
const cx = rect.left + rect.width / 2;
|
|
206
|
+
const cy = rect.top + rect.height / 2;
|
|
207
|
+
if (cx >= 0 && cy >= 0 && cx <= window.innerWidth && cy <= window.innerHeight) {
|
|
208
|
+
const hit = hitAt(cx, cy);
|
|
209
|
+
if (hit && (target === hit || target.contains(hit))) score += 60;
|
|
210
|
+
else if (hit && !hit.contains(target)) score -= 80;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const previous = scored.get(target);
|
|
214
|
+
if (!previous || score > previous.score) scored.set(target, { el: target, score });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return Array.from(scored.values())
|
|
218
|
+
.sort((a, b) => b.score - a.score || (order.get(a.el) ?? 0) - (order.get(b.el) ?? 0))
|
|
219
|
+
.slice(0, limit);
|
|
81
220
|
}
|
|
82
221
|
|
|
83
|
-
/**
|
|
84
|
-
function
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
222
|
+
/** Ranked text matches from every frame, best first. Caller disposes the handles. */
|
|
223
|
+
async function rankedTextHandles(
|
|
224
|
+
page: Page,
|
|
225
|
+
text: string,
|
|
226
|
+
opts: { includeHidden?: boolean; limit?: number } = {}
|
|
227
|
+
): Promise<Array<{ handle: ElementHandle<Element>; frame: Frame; score: number }>> {
|
|
228
|
+
const found: Array<{ handle: ElementHandle<Element>; frame: Frame; score: number; frameIndex: number }> = [];
|
|
229
|
+
const frames = page.frames();
|
|
230
|
+
|
|
231
|
+
for (let frameIndex = 0; frameIndex < frames.length; frameIndex++) {
|
|
232
|
+
const frame = frames[frameIndex];
|
|
233
|
+
if (frame.isDetached()) continue;
|
|
234
|
+
|
|
235
|
+
try {
|
|
236
|
+
const list = await frame.evaluateHandle(rankTextMatches, text, !!opts.includeHidden, opts.limit ?? 20);
|
|
237
|
+
try {
|
|
238
|
+
const entries = await list.getProperties();
|
|
239
|
+
for (const entry of entries.values()) {
|
|
240
|
+
const el = (await entry.getProperty('el')) as ElementHandle<Element>;
|
|
241
|
+
const score = Number(await (await entry.getProperty('score')).jsonValue());
|
|
242
|
+
found.push({ handle: el, frame, score, frameIndex });
|
|
243
|
+
await entry.dispose().catch(() => {});
|
|
244
|
+
}
|
|
245
|
+
} finally {
|
|
246
|
+
await list.dispose().catch(() => {});
|
|
247
|
+
}
|
|
248
|
+
} catch {
|
|
249
|
+
// A frame that navigated mid-sweep must not abort the others.
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Best score wins across frames; the main frame breaks ties, then page order.
|
|
254
|
+
found.sort((a, b) => b.score - a.score || a.frameIndex - b.frameIndex);
|
|
255
|
+
return found.map(({ handle, frame, score }) => ({ handle, frame, score }));
|
|
89
256
|
}
|
|
90
257
|
|
|
91
258
|
/** Read everything the caller might want to show, in one round trip per element. */
|
|
@@ -153,6 +320,14 @@ async function readMeta(handle: ElementHandle<Element>): Promise<ElementMeta> {
|
|
|
153
320
|
|
|
154
321
|
/** Collect candidate handles for a query, main frame first. */
|
|
155
322
|
async function collectHandles(page: Page, query: LocateQuery): Promise<Array<{ handle: ElementHandle<Element>; frame: Frame }>> {
|
|
323
|
+
// Text is ranked, not listed in document order — see rankTextMatches.
|
|
324
|
+
if (query.text && !query.selector) {
|
|
325
|
+
return rankedTextHandles(page, query.text, {
|
|
326
|
+
includeHidden: query.visibleOnly === false,
|
|
327
|
+
limit: Math.max(query.limit ?? 20, (query.nth ?? 0) + 1)
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
156
331
|
const found: Array<{ handle: ElementHandle<Element>; frame: Frame }> = [];
|
|
157
332
|
|
|
158
333
|
for (const frame of page.frames()) {
|
|
@@ -163,8 +338,6 @@ async function collectHandles(page: Page, query: LocateQuery): Promise<Array<{ h
|
|
|
163
338
|
|
|
164
339
|
if (query.selector) {
|
|
165
340
|
handles.push(...(await frame.$$(query.selector)));
|
|
166
|
-
} else if (query.text) {
|
|
167
|
-
handles.push(...(await frame.$$(innermostTextXPath(query.text))));
|
|
168
341
|
} else if (query.role) {
|
|
169
342
|
// A role is expressed either explicitly or by the element itself:
|
|
170
343
|
// `<button>` carries the button role without saying so. Both are
|
|
@@ -259,7 +432,7 @@ export async function resolveHandle(
|
|
|
259
432
|
target: BrowserActionTarget,
|
|
260
433
|
opts: { scrollIntoView?: boolean } = {}
|
|
261
434
|
): Promise<ElementHandle<Element> | null> {
|
|
262
|
-
const candidates = await collectHandles(page, { selector: target.selector, text: target.text });
|
|
435
|
+
const candidates = await collectHandles(page, { selector: target.selector, text: target.text, nth: target.nth });
|
|
263
436
|
if (candidates.length === 0) return null;
|
|
264
437
|
|
|
265
438
|
const wanted = target.nth ?? 0;
|