@myrialabs/clopen 0.4.47 → 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/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/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
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which chords need their editing command attached.
|
|
3
|
+
*
|
|
4
|
+
* The failure this guards is silent: on a macOS host a bare Ctrl/⌘+A selects
|
|
5
|
+
* nothing, so "clear then type" appended to the old text, and nothing errored.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, expect, test } from 'bun:test';
|
|
9
|
+
import { editCommandFor, isPasteChord, parseChord } from './keyboard-chords';
|
|
10
|
+
|
|
11
|
+
describe('parseChord', () => {
|
|
12
|
+
test('splits modifiers from the key and accepts aliases', () => {
|
|
13
|
+
expect(parseChord('Cmd+Shift+z')).toEqual({ modifiers: ['Meta', 'Shift'], key: 'z' });
|
|
14
|
+
expect(parseChord('ctrl + KeyA')).toEqual({ modifiers: ['Control'], key: 'KeyA' });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('a modifier named twice is held once', () => {
|
|
18
|
+
expect(parseChord('Control+Ctrl+C').modifiers).toEqual(['Control']);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe('editCommandFor on macOS', () => {
|
|
23
|
+
test('select all needs the command with either primary modifier', () => {
|
|
24
|
+
expect(editCommandFor(['Meta'], 'a', 'darwin')).toBe('SelectAll');
|
|
25
|
+
expect(editCommandFor(['Control'], 'KeyA', 'darwin')).toBe('SelectAll');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('copy, cut, undo and redo map to their commands', () => {
|
|
29
|
+
expect(editCommandFor(['Meta'], 'c', 'darwin')).toBe('Copy');
|
|
30
|
+
expect(editCommandFor(['Meta'], 'x', 'darwin')).toBe('Cut');
|
|
31
|
+
expect(editCommandFor(['Meta'], 'z', 'darwin')).toBe('Undo');
|
|
32
|
+
expect(editCommandFor(['Meta', 'Shift'], 'z', 'darwin')).toBe('Redo');
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe('editCommandFor elsewhere', () => {
|
|
37
|
+
test('Control is left to the native binding, so nothing runs twice', () => {
|
|
38
|
+
expect(editCommandFor(['Control'], 'a', 'linux')).toBeNull();
|
|
39
|
+
expect(editCommandFor(['Control'], 'z', 'win32')).toBeNull();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('Meta has no native binding, so it carries the command', () => {
|
|
43
|
+
expect(editCommandFor(['Meta'], 'a', 'linux')).toBe('SelectAll');
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe('chords that are not editing shortcuts', () => {
|
|
48
|
+
test('get no command', () => {
|
|
49
|
+
expect(editCommandFor(['Meta', 'Control'], 'a', 'darwin')).toBeNull();
|
|
50
|
+
expect(editCommandFor(['Alt', 'Meta'], 'a', 'darwin')).toBeNull();
|
|
51
|
+
expect(editCommandFor(['Meta', 'Shift'], 'p', 'darwin')).toBeNull();
|
|
52
|
+
expect(editCommandFor(['Meta'], 'Enter', 'darwin')).toBeNull();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('isPasteChord', () => {
|
|
57
|
+
test('recognises Ctrl/⌘+V in any spelling', () => {
|
|
58
|
+
expect(isPasteChord(['Meta'], 'v')).toBe(true);
|
|
59
|
+
expect(isPasteChord(['Control'], 'KeyV')).toBe(true);
|
|
60
|
+
expect(isPasteChord(['Control'], 'V')).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('leaves other chords alone', () => {
|
|
64
|
+
expect(isPasteChord(['Meta', 'Shift'], 'v')).toBe(false);
|
|
65
|
+
expect(isPasteChord(['Alt', 'Meta'], 'v')).toBe(false);
|
|
66
|
+
expect(isPasteChord([], 'v')).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keyboard chords that actually do something.
|
|
3
|
+
*
|
|
4
|
+
* Editing shortcuts are not handled by the page or by Blink's key handling on
|
|
5
|
+
* every platform. On macOS, ⌘A / ⌘C / ⌘Z are resolved by the Cocoa responder
|
|
6
|
+
* chain *before* Blink sees the key, and a key event dispatched over CDP never
|
|
7
|
+
* passes through it — so on a Mac host neither Ctrl+A nor Meta+A selected
|
|
8
|
+
* anything, and `clearFirst` typed the new text after the old one ("ABC" +
|
|
9
|
+
* "DEF" = "ABCDEF"). The protocol's answer is to send the editing command with
|
|
10
|
+
* the key event, which is what this module does wherever the native binding
|
|
11
|
+
* would not fire.
|
|
12
|
+
*
|
|
13
|
+
* Paste is deliberately not one of them: the headless browser's clipboard is
|
|
14
|
+
* not the one anybody copied into. Callers detect it with `isPasteChord` and
|
|
15
|
+
* paste from the workspace clipboard instead.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { KeyInput, Page } from 'puppeteer';
|
|
19
|
+
|
|
20
|
+
export type Modifier = 'Control' | 'Shift' | 'Alt' | 'Meta';
|
|
21
|
+
|
|
22
|
+
/** Modifier aliases an agent (or a model trained on other tools) might use. */
|
|
23
|
+
export const MODIFIER_ALIASES: Record<string, Modifier> = {
|
|
24
|
+
ctrl: 'Control',
|
|
25
|
+
control: 'Control',
|
|
26
|
+
shift: 'Shift',
|
|
27
|
+
alt: 'Alt',
|
|
28
|
+
option: 'Alt',
|
|
29
|
+
meta: 'Meta',
|
|
30
|
+
cmd: 'Meta',
|
|
31
|
+
command: 'Meta',
|
|
32
|
+
super: 'Meta',
|
|
33
|
+
win: 'Meta'
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Blink editor command names, keyed by the letter of the shortcut. */
|
|
37
|
+
const EDIT_COMMANDS: Record<string, string> = {
|
|
38
|
+
a: 'SelectAll',
|
|
39
|
+
c: 'Copy',
|
|
40
|
+
x: 'Cut',
|
|
41
|
+
z: 'Undo',
|
|
42
|
+
y: 'Redo'
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** "Control+Shift+K" → modifiers to hold plus the key to press. */
|
|
46
|
+
export function parseChord(chord: string): { modifiers: Modifier[]; key: string } {
|
|
47
|
+
const parts = chord.split('+').map((p) => p.trim()).filter(Boolean);
|
|
48
|
+
const modifiers: Modifier[] = [];
|
|
49
|
+
let key = '';
|
|
50
|
+
|
|
51
|
+
for (const part of parts) {
|
|
52
|
+
const modifier = MODIFIER_ALIASES[part.toLowerCase()];
|
|
53
|
+
if (modifier) {
|
|
54
|
+
if (!modifiers.includes(modifier)) modifiers.push(modifier);
|
|
55
|
+
} else {
|
|
56
|
+
key = part;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return { modifiers, key };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** "a", "A" and "KeyA" all name the same letter. */
|
|
64
|
+
function letterOf(key: string): string | null {
|
|
65
|
+
const code = /^Key([A-Za-z])$/.exec(key);
|
|
66
|
+
if (code) return code[1].toLowerCase();
|
|
67
|
+
return key.length === 1 ? key.toLowerCase() : null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Exactly one of Control/Meta, no Alt — the shape of an editing shortcut. */
|
|
71
|
+
function primaryModifier(modifiers: Modifier[]): 'Control' | 'Meta' | null {
|
|
72
|
+
if (modifiers.includes('Alt')) return null;
|
|
73
|
+
const hasControl = modifiers.includes('Control');
|
|
74
|
+
const hasMeta = modifiers.includes('Meta');
|
|
75
|
+
if (hasControl === hasMeta) return null;
|
|
76
|
+
return hasControl ? 'Control' : 'Meta';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Ctrl/⌘+V, in either spelling, on any host. */
|
|
80
|
+
export function isPasteChord(modifiers: Modifier[], key: string): boolean {
|
|
81
|
+
return !!primaryModifier(modifiers) && !modifiers.includes('Shift') && letterOf(key) === 'v';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The editing command a chord has to carry, or null when the key event alone
|
|
86
|
+
* is enough.
|
|
87
|
+
*
|
|
88
|
+
* Both Control and Meta are accepted as the primary modifier on every host —
|
|
89
|
+
* an agent cannot know which OS the server runs on, and "Control+A" meaning
|
|
90
|
+
* select-all everywhere is what it expects. The command is only attached where
|
|
91
|
+
* the native binding would not run, because sending it alongside a binding
|
|
92
|
+
* that does would run it twice: harmless for select-all, a double undo for Z.
|
|
93
|
+
*/
|
|
94
|
+
export function editCommandFor(
|
|
95
|
+
modifiers: Modifier[],
|
|
96
|
+
key: string,
|
|
97
|
+
platform: NodeJS.Platform = process.platform
|
|
98
|
+
): string | null {
|
|
99
|
+
const primary = primaryModifier(modifiers);
|
|
100
|
+
const letter = letterOf(key);
|
|
101
|
+
if (!primary || !letter) return null;
|
|
102
|
+
|
|
103
|
+
const shift = modifiers.includes('Shift');
|
|
104
|
+
const command = shift ? (letter === 'z' ? 'Redo' : null) : EDIT_COMMANDS[letter] ?? null;
|
|
105
|
+
if (!command) return null;
|
|
106
|
+
|
|
107
|
+
// Off macOS, Blink maps Ctrl+<key> itself. Meta has no binding there.
|
|
108
|
+
const nativeHandles = platform !== 'darwin' && primary === 'Control';
|
|
109
|
+
return nativeHandles ? null : command;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Press a chord: modifiers down, key, modifiers up in reverse — with the
|
|
114
|
+
* editing command attached when the platform would otherwise ignore it.
|
|
115
|
+
*/
|
|
116
|
+
export async function pressChord(page: Page, modifiers: Modifier[], key: string): Promise<void> {
|
|
117
|
+
const command = editCommandFor(modifiers, key);
|
|
118
|
+
|
|
119
|
+
for (const modifier of modifiers) await page.keyboard.down(modifier);
|
|
120
|
+
try {
|
|
121
|
+
await page.keyboard.press(key as KeyInput, command ? { commands: [command] } : undefined);
|
|
122
|
+
} finally {
|
|
123
|
+
for (const modifier of [...modifiers].reverse()) {
|
|
124
|
+
await page.keyboard.up(modifier).catch(() => {});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Select everything in the focused field, on any host. */
|
|
130
|
+
export async function selectAll(page: Page): Promise<void> {
|
|
131
|
+
await pressChord(page, ['Control'], 'KeyA');
|
|
132
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paste, the way a browser does it.
|
|
3
|
+
*
|
|
4
|
+
* A real paste is two steps: a `paste` event the page may handle itself (rich
|
|
5
|
+
* editors and spreadsheets always do — they read `clipboardData` and insert on
|
|
6
|
+
* their own), and, only if nobody cancelled it, the text inserted at the caret.
|
|
7
|
+
* Inserting alone skipped the first step, so a spreadsheet grid that only
|
|
8
|
+
* listens for `paste` ignored it entirely.
|
|
9
|
+
*
|
|
10
|
+
* The text comes from the caller (the workspace clipboard), never from the
|
|
11
|
+
* headless browser's own clipboard, which is not the one anybody copied into.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Page } from 'puppeteer';
|
|
15
|
+
|
|
16
|
+
export type PasteOutcome = 'handled-by-page' | 'inserted';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Raise `paste` on the focused element, in whichever frame holds focus, then
|
|
20
|
+
* insert the text unless the page took care of it.
|
|
21
|
+
*/
|
|
22
|
+
export async function pasteText(page: Page, text: string): Promise<PasteOutcome> {
|
|
23
|
+
let handled = false;
|
|
24
|
+
let dispatched = false;
|
|
25
|
+
|
|
26
|
+
// The focused frame first; the main frame if none admits to focus (a
|
|
27
|
+
// headless window is not always "focused" in the document's own opinion).
|
|
28
|
+
const frames = page.frames().filter((frame) => !frame.isDetached());
|
|
29
|
+
const ordered = [...frames.slice(1), frames[0]].filter(Boolean);
|
|
30
|
+
|
|
31
|
+
for (const frame of ordered) {
|
|
32
|
+
try {
|
|
33
|
+
const result = await frame.evaluate(
|
|
34
|
+
(value: string, isMain: boolean) => {
|
|
35
|
+
let active: Element | null = document.activeElement;
|
|
36
|
+
while (active && (active as HTMLElement).shadowRoot?.activeElement) {
|
|
37
|
+
active = (active as HTMLElement).shadowRoot!.activeElement;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Focus lives in a child frame; that frame dispatches instead.
|
|
41
|
+
if (active && active.tagName === 'IFRAME') return null;
|
|
42
|
+
const focusedHere = document.hasFocus() && active && active !== document.body;
|
|
43
|
+
if (!focusedHere && !isMain) return null;
|
|
44
|
+
|
|
45
|
+
const target = active ?? document.body;
|
|
46
|
+
const data = new DataTransfer();
|
|
47
|
+
data.setData('text/plain', value);
|
|
48
|
+
const event = new ClipboardEvent('paste', {
|
|
49
|
+
clipboardData: data,
|
|
50
|
+
bubbles: true,
|
|
51
|
+
cancelable: true,
|
|
52
|
+
composed: true
|
|
53
|
+
});
|
|
54
|
+
target.dispatchEvent(event);
|
|
55
|
+
return event.defaultPrevented;
|
|
56
|
+
},
|
|
57
|
+
text,
|
|
58
|
+
frame === page.mainFrame()
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
if (result === null) continue;
|
|
62
|
+
handled = result;
|
|
63
|
+
dispatched = true;
|
|
64
|
+
break;
|
|
65
|
+
} catch {
|
|
66
|
+
// Frame navigated or detached mid-paste; try the next one.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (dispatched && handled) return 'handled-by-page';
|
|
71
|
+
|
|
72
|
+
// `Input.insertText` lands wherever focus is, in any frame, and raises the
|
|
73
|
+
// same beforeinput/input events typing would.
|
|
74
|
+
const client = await page.createCDPSession();
|
|
75
|
+
try {
|
|
76
|
+
await client.send('Input.insertText', { text });
|
|
77
|
+
} finally {
|
|
78
|
+
await client.detach().catch(() => {});
|
|
79
|
+
}
|
|
80
|
+
return 'inserted';
|
|
81
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the preview's Chromes cost the machine.
|
|
3
|
+
*
|
|
4
|
+
* A preview Chrome is not one process but a tree — the browser, a GPU process,
|
|
5
|
+
* a network service, one renderer per site — and the whole tree is what a slow
|
|
6
|
+
* machine is paying for. Measured from the OS rather than from Chrome, because
|
|
7
|
+
* CDP reports CPU time but no memory, and memory is the cost that grows with
|
|
8
|
+
* every tab left open.
|
|
9
|
+
*
|
|
10
|
+
* Read only while someone is looking at the diagnostics panel, so `ps` running
|
|
11
|
+
* once every couple of seconds is fine.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { debug } from '$shared/utils/logger';
|
|
15
|
+
|
|
16
|
+
export interface ProcessTreeUsage {
|
|
17
|
+
pid: number;
|
|
18
|
+
/** Processes in the tree, the browser itself included. */
|
|
19
|
+
processes: number;
|
|
20
|
+
/** Resident memory of the whole tree. */
|
|
21
|
+
rssBytes: number;
|
|
22
|
+
/** CPU of the whole tree, % of one core. Null where the OS does not report it cheaply. */
|
|
23
|
+
cpuPercent: number | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface Row {
|
|
27
|
+
pid: number;
|
|
28
|
+
ppid: number;
|
|
29
|
+
rssBytes: number;
|
|
30
|
+
cpu: number | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readProcessTable(): Row[] {
|
|
34
|
+
try {
|
|
35
|
+
if (process.platform === 'win32') {
|
|
36
|
+
const result = Bun.spawnSync(
|
|
37
|
+
[
|
|
38
|
+
'powershell',
|
|
39
|
+
'-NoProfile',
|
|
40
|
+
'-NonInteractive',
|
|
41
|
+
'-Command',
|
|
42
|
+
'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.WorkingSetSize)" }'
|
|
43
|
+
],
|
|
44
|
+
{ stdout: 'pipe', stderr: 'ignore' }
|
|
45
|
+
);
|
|
46
|
+
return result.stdout
|
|
47
|
+
.toString()
|
|
48
|
+
.split('\n')
|
|
49
|
+
.map((line) => line.trim().split('\t'))
|
|
50
|
+
.filter((parts) => parts.length === 3)
|
|
51
|
+
.map(([pid, ppid, ws]) => ({ pid: Number(pid), ppid: Number(ppid), rssBytes: Number(ws) || 0, cpu: null }));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const result = Bun.spawnSync(['ps', '-axo', 'pid=,ppid=,rss=,%cpu='], { stdout: 'pipe', stderr: 'ignore' });
|
|
55
|
+
return result.stdout
|
|
56
|
+
.toString()
|
|
57
|
+
.split('\n')
|
|
58
|
+
.map((line) => line.trim().split(/\s+/))
|
|
59
|
+
.filter((parts) => parts.length >= 4)
|
|
60
|
+
.map(([pid, ppid, rss, cpu]) => ({
|
|
61
|
+
pid: Number(pid),
|
|
62
|
+
ppid: Number(ppid),
|
|
63
|
+
// ps reports kilobytes.
|
|
64
|
+
rssBytes: (Number(rss) || 0) * 1024,
|
|
65
|
+
cpu: Number(cpu.replace(',', '.')) || 0
|
|
66
|
+
}));
|
|
67
|
+
} catch (error) {
|
|
68
|
+
debug.warn('preview', `⚠️ Could not read the process table: ${error}`);
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Usage of each process tree rooted at the given pids, in one `ps` call. */
|
|
74
|
+
export function measureProcessTrees(rootPids: number[]): Map<number, ProcessTreeUsage> {
|
|
75
|
+
const usage = new Map<number, ProcessTreeUsage>();
|
|
76
|
+
if (rootPids.length === 0) return usage;
|
|
77
|
+
|
|
78
|
+
const rows = readProcessTable();
|
|
79
|
+
const children = new Map<number, Row[]>();
|
|
80
|
+
for (const row of rows) {
|
|
81
|
+
const siblings = children.get(row.ppid) ?? [];
|
|
82
|
+
siblings.push(row);
|
|
83
|
+
children.set(row.ppid, siblings);
|
|
84
|
+
}
|
|
85
|
+
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
86
|
+
|
|
87
|
+
for (const rootPid of rootPids) {
|
|
88
|
+
const root = byPid.get(rootPid);
|
|
89
|
+
if (!root) continue;
|
|
90
|
+
|
|
91
|
+
let processes = 0;
|
|
92
|
+
let rssBytes = 0;
|
|
93
|
+
let cpu: number | null = 0;
|
|
94
|
+
const stack = [root];
|
|
95
|
+
const seen = new Set<number>();
|
|
96
|
+
|
|
97
|
+
while (stack.length > 0) {
|
|
98
|
+
const row = stack.pop()!;
|
|
99
|
+
if (seen.has(row.pid)) continue;
|
|
100
|
+
seen.add(row.pid);
|
|
101
|
+
|
|
102
|
+
processes += 1;
|
|
103
|
+
rssBytes += row.rssBytes;
|
|
104
|
+
cpu = row.cpu === null || cpu === null ? null : cpu + row.cpu;
|
|
105
|
+
for (const child of children.get(row.pid) ?? []) stack.push(child);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
usage.set(rootPid, {
|
|
109
|
+
pid: rootPid,
|
|
110
|
+
processes,
|
|
111
|
+
rssBytes,
|
|
112
|
+
cpuPercent: cpu === null ? null : Math.round(cpu * 10) / 10
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return usage;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Memory the OS could hand out right now.
|
|
121
|
+
*
|
|
122
|
+
* `os.freemem()` on macOS counts only pages nobody has touched, which on a
|
|
123
|
+
* machine that has been up for an hour is a few hundred MB no matter how much
|
|
124
|
+
* is reclaimable — read as-is it would say every Mac is out of memory. The
|
|
125
|
+
* kernel's own notion of "available" adds the inactive, purgeable and
|
|
126
|
+
* speculative pages it can reclaim without swapping. Elsewhere `freemem()`
|
|
127
|
+
* already means available (libuv reads MemAvailable on Linux).
|
|
128
|
+
*/
|
|
129
|
+
export function availableMemoryBytes(fallback: number): number {
|
|
130
|
+
if (process.platform !== 'darwin') return fallback;
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
const output = Bun.spawnSync(['vm_stat'], { stdout: 'pipe', stderr: 'ignore' }).stdout.toString();
|
|
134
|
+
const pageSize = Number(/page size of (\d+) bytes/.exec(output)?.[1]) || 4096;
|
|
135
|
+
const pages = (label: string) => Number(new RegExp(`${label}:\\s+(\\d+)`).exec(output)?.[1]) || 0;
|
|
136
|
+
const available =
|
|
137
|
+
pages('Pages free') + pages('Pages inactive') + pages('Pages purgeable') + pages('Pages speculative');
|
|
138
|
+
return available > 0 ? available * pageSize : fallback;
|
|
139
|
+
} catch {
|
|
140
|
+
return fallback;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Profile lock recovery.
|
|
3
|
+
*
|
|
4
|
+
* Chrome refuses to start on a profile another Chrome still holds, and
|
|
5
|
+
* Puppeteer reports it as "The browser is already running for <dir>". On a
|
|
6
|
+
* profile only Clopen ever uses, that other Chrome can only be one of ours that
|
|
7
|
+
* outlived the server that launched it:
|
|
8
|
+
*
|
|
9
|
+
* - the server died without closing it (a crash, a kill, `bun --watch`
|
|
10
|
+
* restarting) — a Chrome reached over a WebSocket keeps running after its
|
|
11
|
+
* parent is gone, re-parented to init, invisible because it is headless;
|
|
12
|
+
* - or the connection to it dropped (a laptop waking from sleep) and the pool
|
|
13
|
+
* forgot the browser without ending the process.
|
|
14
|
+
*
|
|
15
|
+
* Either way nothing would ever close it, so the preview stayed broken until
|
|
16
|
+
* the machine was restarted. This module finds such a process by its
|
|
17
|
+
* `--user-data-dir` and ends it, and clears the lock files a killed Chrome
|
|
18
|
+
* leaves behind. A Chrome whose parent is another live Clopen server is left
|
|
19
|
+
* alone: that profile is genuinely in use, and the error says so.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { existsSync, readdirSync, readlinkSync, rmSync } from 'fs';
|
|
23
|
+
import { join } from 'path';
|
|
24
|
+
import { debug } from '$shared/utils/logger';
|
|
25
|
+
import { sleep } from '$shared/utils/async';
|
|
26
|
+
|
|
27
|
+
interface ProcessEntry {
|
|
28
|
+
pid: number;
|
|
29
|
+
ppid: number;
|
|
30
|
+
command: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const LOCK_FILES = ['SingletonLock', 'SingletonSocket', 'SingletonCookie'];
|
|
34
|
+
|
|
35
|
+
/** How long a killed Chrome gets to actually go away before we stop waiting. */
|
|
36
|
+
const EXIT_WAIT_MS = 3_000;
|
|
37
|
+
|
|
38
|
+
/** Every process on the machine with its parent and full command line. */
|
|
39
|
+
function listProcesses(): ProcessEntry[] {
|
|
40
|
+
try {
|
|
41
|
+
if (process.platform === 'win32') {
|
|
42
|
+
const result = Bun.spawnSync(
|
|
43
|
+
[
|
|
44
|
+
'powershell',
|
|
45
|
+
'-NoProfile',
|
|
46
|
+
'-NonInteractive',
|
|
47
|
+
'-Command',
|
|
48
|
+
'Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like "*--user-data-dir=*" } | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.CommandLine)" }'
|
|
49
|
+
],
|
|
50
|
+
{ stdout: 'pipe', stderr: 'ignore' }
|
|
51
|
+
);
|
|
52
|
+
return parseLines(result.stdout.toString(), '\t');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// `ww` lifts the column limit: a truncated command line would hide the
|
|
56
|
+
// very `--user-data-dir` flag this is looking for.
|
|
57
|
+
const result = Bun.spawnSync(['ps', '-axww', '-o', 'pid=,ppid=,command='], {
|
|
58
|
+
stdout: 'pipe',
|
|
59
|
+
stderr: 'ignore'
|
|
60
|
+
});
|
|
61
|
+
return parseLines(result.stdout.toString(), null);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
debug.warn('preview', `⚠️ Could not list processes for profile recovery: ${error}`);
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function parseLines(output: string, separator: string | null): ProcessEntry[] {
|
|
69
|
+
const entries: ProcessEntry[] = [];
|
|
70
|
+
for (const raw of output.split('\n')) {
|
|
71
|
+
const line = raw.trim();
|
|
72
|
+
if (!line) continue;
|
|
73
|
+
|
|
74
|
+
if (separator) {
|
|
75
|
+
const [pid, ppid, ...rest] = line.split(separator);
|
|
76
|
+
entries.push({ pid: Number(pid), ppid: Number(ppid), command: rest.join(separator) });
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const match = /^(\d+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
81
|
+
if (match) entries.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] });
|
|
82
|
+
}
|
|
83
|
+
return entries.filter((entry) => Number.isFinite(entry.pid) && entry.pid > 0);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isAlive(pid: number): boolean {
|
|
87
|
+
try {
|
|
88
|
+
process.kill(pid, 0);
|
|
89
|
+
return true;
|
|
90
|
+
} catch (error) {
|
|
91
|
+
// EPERM means it exists but belongs to someone else.
|
|
92
|
+
return (error as NodeJS.ErrnoException).code === 'EPERM';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The browser process for a profile — its helpers carry a `--type=` flag. */
|
|
97
|
+
function isBrowserProcessFor(entry: ProcessEntry, profileDir: string): boolean {
|
|
98
|
+
if (entry.command.includes('--type=')) return false;
|
|
99
|
+
return (
|
|
100
|
+
entry.command.includes(`--user-data-dir=${profileDir}`) ||
|
|
101
|
+
entry.command.includes(`--user-data-dir="${profileDir}"`)
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A Clopen server is a Bun process; anything else owning a Chrome is not one. */
|
|
106
|
+
function isLiveClopenServer(pid: number, processes: ProcessEntry[]): boolean {
|
|
107
|
+
if (pid <= 1 || pid === process.pid || !isAlive(pid)) return false;
|
|
108
|
+
const parent = processes.find((entry) => entry.pid === pid);
|
|
109
|
+
return !!parent && /\bbun(\.exe)?\b/i.test(parent.command);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function killAndWait(pid: number): Promise<void> {
|
|
113
|
+
try {
|
|
114
|
+
process.kill(pid, 'SIGKILL');
|
|
115
|
+
} catch {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const deadline = Date.now() + EXIT_WAIT_MS;
|
|
120
|
+
while (Date.now() < deadline && isAlive(pid)) {
|
|
121
|
+
await sleep(50);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Lock files whose recorded owner is gone. A live owner's lock is left be. */
|
|
126
|
+
function clearStaleLockFiles(profileDir: string): void {
|
|
127
|
+
if (process.platform === 'win32') return;
|
|
128
|
+
|
|
129
|
+
const lockPath = join(profileDir, 'SingletonLock');
|
|
130
|
+
let owner: string;
|
|
131
|
+
try {
|
|
132
|
+
owner = readlinkSync(lockPath);
|
|
133
|
+
} catch {
|
|
134
|
+
return; // No lock — nothing to clear.
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// "<hostname>-<pid>". The hostname is not compared: on a laptop it follows
|
|
138
|
+
// the network (a DHCP-assigned name one day, `.local` the next), so a lock
|
|
139
|
+
// left on another network would otherwise never count as stale.
|
|
140
|
+
const pid = Number(owner.slice(owner.lastIndexOf('-') + 1));
|
|
141
|
+
if (Number.isFinite(pid) && pid > 0 && isAlive(pid)) {
|
|
142
|
+
const processes = listProcesses();
|
|
143
|
+
const holder = processes.find((entry) => entry.pid === pid);
|
|
144
|
+
// A live pid that is not a Chrome on this profile is a recycled pid.
|
|
145
|
+
if (holder && isBrowserProcessFor(holder, profileDir)) return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
for (const name of LOCK_FILES) {
|
|
149
|
+
rmSync(join(profileDir, name), { force: true });
|
|
150
|
+
}
|
|
151
|
+
debug.log('preview', `🔓 Cleared a stale profile lock (${owner}) in ${profileDir}`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Make a profile launchable: end orphaned Chromes holding it, clear stale locks.
|
|
156
|
+
*
|
|
157
|
+
* Throws when the profile is held by a Chrome that another live Clopen server
|
|
158
|
+
* owns — killing that one would take someone else's preview down.
|
|
159
|
+
*/
|
|
160
|
+
export async function releaseProfile(profileDir: string): Promise<void> {
|
|
161
|
+
if (!existsSync(profileDir)) return;
|
|
162
|
+
|
|
163
|
+
const processes = listProcesses();
|
|
164
|
+
const holders = processes.filter((entry) => isBrowserProcessFor(entry, profileDir));
|
|
165
|
+
|
|
166
|
+
for (const holder of holders) {
|
|
167
|
+
if (isLiveClopenServer(holder.ppid, processes)) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`This preview profile is in use by another running Clopen server (pid ${holder.ppid}). Stop that server, or open the project from it.`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
debug.warn('preview', `🧹 Ending orphaned Chrome ${holder.pid} that still held ${profileDir}`);
|
|
174
|
+
await killAndWait(holder.pid);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
clearStaleLockFiles(profileDir);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* End every orphaned preview Chrome under the profiles root.
|
|
182
|
+
*
|
|
183
|
+
* Run once per server, before the first launch. Orphans of profiles nobody
|
|
184
|
+
* opens again would otherwise keep their renderers' memory until reboot.
|
|
185
|
+
*/
|
|
186
|
+
export async function sweepOrphanedProfiles(profilesRoot: string): Promise<void> {
|
|
187
|
+
if (!existsSync(profilesRoot)) return;
|
|
188
|
+
|
|
189
|
+
let dirs: string[];
|
|
190
|
+
try {
|
|
191
|
+
dirs = readdirSync(profilesRoot, { withFileTypes: true })
|
|
192
|
+
.filter((entry) => entry.isDirectory())
|
|
193
|
+
.map((entry) => join(profilesRoot, entry.name));
|
|
194
|
+
} catch {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
for (const dir of dirs) {
|
|
199
|
+
await releaseProfile(dir).catch((error) => {
|
|
200
|
+
debug.warn('preview', `⚠️ ${error instanceof Error ? error.message : error}`);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Whether a launch failure is Chrome refusing a profile that is held. */
|
|
206
|
+
export function isProfileInUseError(error: unknown): boolean {
|
|
207
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
208
|
+
return message.includes('already running for') || message.includes('ProcessSingleton');
|
|
209
|
+
}
|