@myrialabs/clopen 0.4.47 → 0.4.49
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/message-pages.test.ts +163 -0
- package/backend/chat/message-pages.ts +233 -0
- package/backend/chat/stream-manager.ts +91 -67
- 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.ts +418 -0
- package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/blob-line-stats-queries.ts +48 -0
- 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 +15 -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/env/diff.ts +9 -33
- package/backend/db-client/env/env.test.ts +8 -8
- package/backend/db-client/env/service.ts +1 -1
- 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/file-watcher.ts +19 -0
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/contributors.test.ts +35 -0
- package/backend/git/contributors.ts +46 -0
- 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/http/static-assets.test.ts +78 -0
- package/backend/http/static-assets.ts +104 -0
- package/backend/index.ts +32 -16
- 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 +383 -29
- 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/blob-store.ts +9 -1
- package/backend/snapshot/helpers.ts +3 -11
- package/backend/snapshot/line-stats.test.ts +80 -0
- package/backend/snapshot/line-stats.ts +64 -0
- package/backend/snapshot/restore.ts +252 -0
- package/backend/snapshot/snapshot-service.ts +14 -27
- package/backend/snapshot/turn-changes.test.ts +10 -5
- package/backend/snapshot/turn-changes.ts +78 -40
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +10 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws-wire.test.ts +87 -0
- package/backend/utils/ws-wire.ts +189 -0
- package/backend/utils/ws.ts +101 -192
- 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 +105 -57
- 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 +45 -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/log.ts +52 -0
- 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 +78 -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 +29 -0
- package/backend/ws/preview/watchers.ts +84 -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 +42 -57
- 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 +12 -13
- 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/terminal/tunnel.ts +2 -2
- 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 +46 -41
- package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
- package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
- package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
- package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
- package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
- package/dist/assets/index-CrVWZH_D.js.br +0 -0
- package/dist/assets/index-CrVWZH_D.js.gz +0 -0
- package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
- package/dist/assets/index-DD0-3EWg.js.br +0 -0
- package/dist/assets/index-DD0-3EWg.js.gz +0 -0
- package/dist/assets/main-D2_TmcwQ.js +1240 -0
- package/dist/assets/main-D2_TmcwQ.js.br +0 -0
- package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
- package/dist/assets/main-Yucigcmf.css +1 -0
- package/dist/assets/main-Yucigcmf.css.br +0 -0
- package/dist/assets/main-Yucigcmf.css.gz +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
- package/dist/fonts/dm-sans.css.br +0 -0
- package/dist/fonts/dm-sans.css.gz +0 -0
- package/dist/index.html +2 -2
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/dist/sw.js.br +0 -0
- package/dist/sw.js.gz +0 -0
- package/package.json +3 -3
- 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 +13 -5
- 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/diff-calculator.test.ts +178 -41
- package/shared/utils/diff-calculator.ts +383 -100
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/process-supervisor.test.ts +172 -0
- package/shared/utils/process-supervisor.ts +251 -0
- package/shared/utils/ws-chunk.test.ts +33 -0
- package/shared/utils/ws-chunk.ts +73 -0
- package/shared/utils/ws-client-chunks.test.ts +45 -0
- package/shared/utils/ws-client.ts +43 -0
- package/shared/utils/ws-server.ts +49 -21
- 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
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import type { SessionScopedChanges } from '$shared/types/database/schema';
|
|
20
20
|
import { naturalCompare } from '$shared/utils/compare';
|
|
21
|
-
import {
|
|
21
|
+
import { countLineChangesAsync, isBinaryBuffer } from '$shared/utils/diff-calculator';
|
|
22
22
|
|
|
23
23
|
export { isBinaryBuffer };
|
|
24
24
|
|
|
@@ -46,54 +46,92 @@ export function statusOf(oldHash: string, newHash: string): TurnFileStatus {
|
|
|
46
46
|
return 'modified';
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** What one (old, new) pair of blobs amounts to as a +/- badge. */
|
|
50
|
+
export interface PairLineStats {
|
|
51
|
+
insertions: number;
|
|
52
|
+
deletions: number;
|
|
53
|
+
isBinary: boolean;
|
|
54
|
+
/** False when a blob this pair needs is no longer readable. */
|
|
55
|
+
contentAvailable: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Where a pair's numbers come from. Production passes `blobLineStats`
|
|
60
|
+
* (backend/snapshot/line-stats.ts), which counts each pair once and remembers
|
|
61
|
+
* it; tests pass `statsFromBlobs` over an in-memory store.
|
|
62
|
+
*/
|
|
63
|
+
export type LineStatsSource = (oldHash: string, newHash: string) => Promise<PairLineStats>;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Count one pair straight from its blobs. This is the single definition of
|
|
67
|
+
* "how many lines did this change" — the cache only stores what it returns.
|
|
68
|
+
*/
|
|
69
|
+
export async function countPairFromBlobs(
|
|
70
|
+
oldHash: string,
|
|
71
|
+
newHash: string,
|
|
72
|
+
readBlob: (hash: string) => Promise<Buffer>
|
|
73
|
+
): Promise<PairLineStats> {
|
|
74
|
+
let oldBuf: Buffer | null = null;
|
|
75
|
+
let newBuf: Buffer | null = null;
|
|
76
|
+
let contentAvailable = true;
|
|
77
|
+
|
|
78
|
+
if (oldHash) {
|
|
79
|
+
try {
|
|
80
|
+
oldBuf = await readBlob(oldHash);
|
|
81
|
+
} catch {
|
|
82
|
+
contentAvailable = false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (newHash) {
|
|
86
|
+
try {
|
|
87
|
+
newBuf = await readBlob(newHash);
|
|
88
|
+
} catch {
|
|
89
|
+
contentAvailable = false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const isBinary =
|
|
94
|
+
(oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
|
|
95
|
+
|
|
96
|
+
let insertions = 0;
|
|
97
|
+
let deletions = 0;
|
|
98
|
+
if (contentAvailable && !isBinary) {
|
|
99
|
+
// Cooperative: a pathological pair takes long, but never holds the
|
|
100
|
+
// server's thread for more than a few milliseconds at a time.
|
|
101
|
+
const counts = await countLineChangesAsync(
|
|
102
|
+
oldBuf ? oldBuf.toString('utf8') : '',
|
|
103
|
+
newBuf ? newBuf.toString('utf8') : ''
|
|
104
|
+
);
|
|
105
|
+
insertions = counts.additions;
|
|
106
|
+
deletions = counts.deletions;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return { insertions, deletions, isBinary, contentAvailable };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** An uncached source over any blob reader. */
|
|
113
|
+
export function statsFromBlobs(readBlob: (hash: string) => Promise<Buffer>): LineStatsSource {
|
|
114
|
+
return (oldHash, newHash) => countPairFromBlobs(oldHash, newHash, readBlob);
|
|
115
|
+
}
|
|
116
|
+
|
|
49
117
|
/**
|
|
50
118
|
* Turn one checkpoint's `session_changes` into a displayable file list.
|
|
51
119
|
*
|
|
52
|
-
* `
|
|
53
|
-
* only I/O is the
|
|
120
|
+
* `statsFor` is injected so this stays a pure function over its inputs — the
|
|
121
|
+
* only I/O is the source the caller hands in.
|
|
54
122
|
*/
|
|
55
123
|
export async function buildTurnFiles(
|
|
56
124
|
changes: SessionScopedChanges,
|
|
57
|
-
|
|
125
|
+
statsFor: LineStatsSource
|
|
58
126
|
): Promise<TurnFileChange[]> {
|
|
59
127
|
const files: TurnFileChange[] = [];
|
|
60
128
|
|
|
61
129
|
for (const [path, change] of Object.entries(changes)) {
|
|
62
130
|
const status = statusOf(change.oldHash, change.newHash);
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (change.oldHash) {
|
|
69
|
-
try {
|
|
70
|
-
oldBuf = await readBlob(change.oldHash);
|
|
71
|
-
} catch {
|
|
72
|
-
contentAvailable = false;
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
if (change.newHash) {
|
|
76
|
-
try {
|
|
77
|
-
newBuf = await readBlob(change.newHash);
|
|
78
|
-
} catch {
|
|
79
|
-
contentAvailable = false;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
const isBinary =
|
|
84
|
-
(oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
|
|
85
|
-
|
|
86
|
-
let insertions = 0;
|
|
87
|
-
let deletions = 0;
|
|
88
|
-
if (contentAvailable && !isBinary) {
|
|
89
|
-
const counts = countLineChanges(
|
|
90
|
-
oldBuf ? oldBuf.toString('utf8') : '',
|
|
91
|
-
newBuf ? newBuf.toString('utf8') : ''
|
|
92
|
-
);
|
|
93
|
-
insertions = counts.additions;
|
|
94
|
-
deletions = counts.deletions;
|
|
95
|
-
}
|
|
96
|
-
|
|
131
|
+
const { insertions, deletions, isBinary, contentAvailable } = await statsFor(
|
|
132
|
+
change.oldHash,
|
|
133
|
+
change.newHash
|
|
134
|
+
);
|
|
97
135
|
files.push({ path, status, insertions, deletions, isBinary, contentAvailable });
|
|
98
136
|
}
|
|
99
137
|
|
|
@@ -177,7 +215,7 @@ export function netChangeRuns(turns: SessionScopedChanges[]): Map<string, Change
|
|
|
177
215
|
/** The chat-level numbers: net files changed, and net lines in and out. */
|
|
178
216
|
export async function summariseNetChanges(
|
|
179
217
|
turns: SessionScopedChanges[],
|
|
180
|
-
|
|
218
|
+
statsFor: LineStatsSource
|
|
181
219
|
): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
|
|
182
220
|
let insertions = 0;
|
|
183
221
|
let deletions = 0;
|
|
@@ -189,7 +227,7 @@ export async function summariseNetChanges(
|
|
|
189
227
|
list.forEach((run, index) => {
|
|
190
228
|
changes[`${index}\0${path}`] = run;
|
|
191
229
|
});
|
|
192
|
-
const summary = summariseTurnFiles(await buildTurnFiles(changes,
|
|
230
|
+
const summary = summariseTurnFiles(await buildTurnFiles(changes, statsFor));
|
|
193
231
|
insertions += summary.insertions;
|
|
194
232
|
deletions += summary.deletions;
|
|
195
233
|
}
|
package/backend/ssh/ptykit.ts
CHANGED
|
@@ -45,13 +45,12 @@ export const sshPtyKitServer = createPtyKitServer(sshPtyKitManager, {
|
|
|
45
45
|
room: (ctx) => ctx.namespace,
|
|
46
46
|
authorize: (ctx) => {
|
|
47
47
|
const userId = ctx.conn.data.userId;
|
|
48
|
-
const isAdmin = ctx.conn.data.isAdmin === true;
|
|
49
48
|
if (typeof userId !== 'string' || !userId) return false;
|
|
50
49
|
|
|
51
50
|
const connectionId = connectionIdFromNamespace(ctx.namespace);
|
|
52
51
|
if (!connectionId) return false;
|
|
53
52
|
|
|
54
|
-
return sshConnectionQueries.
|
|
53
|
+
return sshConnectionQueries.get(connectionId) !== null;
|
|
55
54
|
}
|
|
56
55
|
});
|
|
57
56
|
|
|
@@ -35,13 +35,18 @@ export const ptyKitManager = new PtyKitManager({
|
|
|
35
35
|
// refresh/reconnect can still replay their final screen (matches old 5-min window).
|
|
36
36
|
idleTtl: null,
|
|
37
37
|
retainExitedMs: 5 * 60_000,
|
|
38
|
+
// A flood (a build, a dev server's log) is held to one frame per window;
|
|
39
|
+
// the first chunk after a pause still goes out at once, so typing is not.
|
|
40
|
+
outputCoalesceMs: 16,
|
|
38
41
|
env: { sanitize: true, inject: TERMINAL_ENV }
|
|
39
42
|
});
|
|
40
43
|
|
|
41
44
|
/**
|
|
42
45
|
* Embedded WebSocket server over the manager. No HTTP/Bun mounting — Clopen's
|
|
43
46
|
* tunnel feeds it frames and supplies per-connection `send`. `authorize` enforces
|
|
44
|
-
* project access
|
|
47
|
+
* project access. The room is the workspace scope, which carries awareness (tabs
|
|
48
|
+
* opened or closed on any device); a session's output goes only to the devices
|
|
49
|
+
* that have that tab mounted (PtyKit 0.1.0).
|
|
45
50
|
*/
|
|
46
51
|
export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
47
52
|
room: (ctx) => ctx.namespace,
|
|
@@ -49,19 +54,18 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
|
49
54
|
const userId = ctx.conn.data.userId;
|
|
50
55
|
if (typeof userId !== 'string' || !userId) return false;
|
|
51
56
|
// The namespace separates worktrees; access is still the project's call.
|
|
52
|
-
const allowed = projectQueries.
|
|
57
|
+
const allowed = projectQueries.isListed(scopeProjectId(ctx.namespace));
|
|
53
58
|
if (allowed) knownNamespaces.add(ctx.namespace);
|
|
54
59
|
return allowed;
|
|
55
60
|
},
|
|
56
61
|
/**
|
|
57
|
-
* The shell inherits the git identity of
|
|
58
|
-
* it belongs to. Without this a `git commit` typed into the terminal would
|
|
62
|
+
* The shell inherits the git identity of the project it belongs to. Without this a `git commit` typed into the terminal would
|
|
59
63
|
* use the machine's identity while the same commit from the Git panel used
|
|
60
64
|
* the chosen one — the same repository, two different authors.
|
|
61
65
|
*
|
|
62
66
|
* Pointed at a FILE rather than given the `GIT_CONFIG_*` block the other
|
|
63
67
|
* surfaces use. A shell lives for hours and its environment is fixed at
|
|
64
|
-
* spawn, so an inlined identity goes stale the moment the
|
|
68
|
+
* spawn, so an inlined identity goes stale the moment the project switches
|
|
65
69
|
* accounts — silently, since the tab keeps working. Git re-reads a config
|
|
66
70
|
* file on every invocation, so the switch reaches tabs that are already open.
|
|
67
71
|
* See `backend/git/identity/scope-config.ts`.
|
|
@@ -71,9 +75,7 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
|
71
75
|
* user's own global config away from every git command in the terminal.
|
|
72
76
|
*/
|
|
73
77
|
env: async (ctx): Promise<Record<string, string>> => {
|
|
74
|
-
const
|
|
75
|
-
if (typeof userId !== 'string' || !userId) return {};
|
|
76
|
-
const path = await writeScopeConfig(userId, scopeProjectId(ctx.namespace));
|
|
78
|
+
const path = await writeScopeConfig(scopeProjectId(ctx.namespace));
|
|
77
79
|
return path ? { GIT_CONFIG_GLOBAL: path } : {};
|
|
78
80
|
}
|
|
79
81
|
});
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* build share links against. Where that origin comes from is adaptive, so the
|
|
6
6
|
* caller never has to think about tunnels vs domains:
|
|
7
7
|
*
|
|
8
|
-
* 1. `configured` —
|
|
8
|
+
* 1. `configured` — a set public URL (system setting `publicBaseUrl`),
|
|
9
9
|
* for VPS/reverse-proxy deployments where the browser can't see the real
|
|
10
10
|
* hostname.
|
|
11
11
|
* 2. `domain` — the browser is already hitting Clopen on a non-local origin
|
|
@@ -28,7 +28,7 @@ export interface PublicOrigin {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/** Hostnames that are not reachable by another device — force a tunnel. */
|
|
31
|
-
function isLocalHostname(hostname: string): boolean {
|
|
31
|
+
export function isLocalHostname(hostname: string): boolean {
|
|
32
32
|
const h = hostname.toLowerCase();
|
|
33
33
|
if (h === 'localhost' || h.endsWith('.localhost')) return true;
|
|
34
34
|
if (h === '127.0.0.1' || h === '::1' || h === '0.0.0.0') return true;
|
|
@@ -43,12 +43,12 @@ function isLocalHostname(hostname: string): boolean {
|
|
|
43
43
|
return false;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
/** Strip a trailing slash so callers can append `/#
|
|
46
|
+
/** Strip a trailing slash so callers can append `/#device/...` cleanly. */
|
|
47
47
|
function normalizeOrigin(url: string): string {
|
|
48
48
|
return url.replace(/\/+$/, '');
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/** Read the
|
|
51
|
+
/** Read the configured public base URL from system settings, if any. */
|
|
52
52
|
function getConfiguredPublicBaseUrl(): string | null {
|
|
53
53
|
return readSystemSetting((settings) => {
|
|
54
54
|
const url = settings.publicBaseUrl;
|
|
@@ -66,19 +66,22 @@ function findQuickTunnelForPort(port: number): string | null {
|
|
|
66
66
|
return null;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/** The port another device must reach: Vite's in dev (it proxies to the backend), the server's in production. */
|
|
70
|
+
export function getClopenPublicPort(): number {
|
|
71
|
+
return SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
|
|
72
|
+
}
|
|
73
|
+
|
|
69
74
|
/**
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* the
|
|
75
|
+
* The public origin that already exists, if any — never starts anything.
|
|
76
|
+
*
|
|
77
|
+
* Same order as {@link resolvePublicOrigin}, minus the side effect. A caller
|
|
78
|
+
* reacting to a tunnel going away needs to know whether something is still
|
|
79
|
+
* reachable without restarting the very tunnel the user may just have stopped.
|
|
73
80
|
*/
|
|
74
|
-
export
|
|
75
|
-
// 1. Explicitly configured public URL wins.
|
|
81
|
+
export function findPublicOrigin(requestOrigin?: string): PublicOrigin | null {
|
|
76
82
|
const configured = getConfiguredPublicBaseUrl();
|
|
77
|
-
if (configured) {
|
|
78
|
-
return { origin: configured, source: 'configured' };
|
|
79
|
-
}
|
|
83
|
+
if (configured) return { origin: configured, source: 'configured' };
|
|
80
84
|
|
|
81
|
-
// 2. Already served on a real (non-local) origin — reuse it.
|
|
82
85
|
if (requestOrigin) {
|
|
83
86
|
try {
|
|
84
87
|
const url = new URL(requestOrigin);
|
|
@@ -90,15 +93,23 @@ export async function resolvePublicOrigin(requestOrigin?: string): Promise<Publi
|
|
|
90
93
|
}
|
|
91
94
|
}
|
|
92
95
|
|
|
93
|
-
|
|
96
|
+
const existing = findQuickTunnelForPort(getClopenPublicPort());
|
|
97
|
+
return existing ? { origin: existing, source: 'tunnel' } : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Resolve a public origin for Remote Access share links. `requestOrigin` is the
|
|
102
|
+
* browser's own `window.location.origin` (passed by the client), used to detect
|
|
103
|
+
* the already-public `domain` case.
|
|
104
|
+
*/
|
|
105
|
+
export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
|
|
106
|
+
const found = findPublicOrigin(requestOrigin);
|
|
107
|
+
if (found) return found;
|
|
108
|
+
|
|
109
|
+
// Local install — tunnel Clopen's own port. In dev the app is served by
|
|
94
110
|
// Vite on PORT_FRONTEND (which proxies to the backend), so tunnel that; in
|
|
95
111
|
// production frontend and backend share PORT.
|
|
96
|
-
const port =
|
|
97
|
-
|
|
98
|
-
const existing = findQuickTunnelForPort(port);
|
|
99
|
-
if (existing) {
|
|
100
|
-
return { origin: existing, source: 'tunnel' };
|
|
101
|
-
}
|
|
112
|
+
const port = getClopenPublicPort();
|
|
102
113
|
|
|
103
114
|
debug.log('tunnel', `[remote-access] Starting quick tunnel for Clopen port ${port}`);
|
|
104
115
|
await tunnelKit.bin.ensure();
|
|
@@ -2,38 +2,6 @@
|
|
|
2
2
|
* User domain helper functions
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
// List of friendly animal names for anonymous users
|
|
6
|
-
export const ANIMAL_NAMES = [
|
|
7
|
-
'Penguin', 'Koala', 'Panda', 'Tiger', 'Lion', 'Eagle', 'Dolphin', 'Elephant',
|
|
8
|
-
'Giraffe', 'Zebra', 'Kangaroo', 'Octopus', 'Butterfly', 'Fox', 'Wolf', 'Bear',
|
|
9
|
-
'Rabbit', 'Deer', 'Owl', 'Hawk', 'Falcon', 'Parrot', 'Peacock', 'Swan',
|
|
10
|
-
'Flamingo', 'Pelican', 'Seal', 'Walrus', 'Otter', 'Beaver', 'Raccoon', 'Squirrel',
|
|
11
|
-
'Hedgehog', 'Hamster', 'Gecko', 'Chameleon', 'Turtle', 'Frog', 'Salamander', 'Newt',
|
|
12
|
-
'Shark', 'Whale', 'Stingray', 'Jellyfish', 'Starfish', 'Crab', 'Lobster', 'Shrimp',
|
|
13
|
-
'Ant', 'Bee', 'Ladybug', 'Dragonfly', 'Cricket', 'Grasshopper', 'Beetle', 'Moth',
|
|
14
|
-
'Cheetah', 'Jaguar', 'Leopard', 'Lynx', 'Cougar', 'Panther', 'Ocelot', 'Serval',
|
|
15
|
-
'Monkey', 'Gorilla', 'Chimpanzee', 'Orangutan', 'Lemur', 'Sloth', 'Armadillo', 'Pangolin',
|
|
16
|
-
'Platypus', 'Echidna', 'Wombat', 'Tasmanian', 'Quokka', 'Wallaby', 'Possum', 'Bandicoot',
|
|
17
|
-
'Meerkat', 'Mongoose', 'Ferret', 'Weasel', 'Badger', 'Skunk', 'Porcupine', 'Chinchilla',
|
|
18
|
-
'Capybara', 'Alpaca', 'Llama', 'Vicuna', 'Camel', 'Yak', 'Bison', 'Buffalo',
|
|
19
|
-
'Moose', 'Elk', 'Reindeer', 'Antelope', 'Gazelle', 'Impala', 'Wildebeest', 'Okapi'
|
|
20
|
-
];
|
|
21
|
-
|
|
22
|
-
// Colors for additional uniqueness
|
|
23
|
-
export const COLORS = [
|
|
24
|
-
'Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange', 'Pink', 'Brown',
|
|
25
|
-
'Gray', 'Black', 'White', 'Silver', 'Gold', 'Cyan', 'Magenta', 'Lime',
|
|
26
|
-
'Indigo', 'Violet', 'Turquoise', 'Coral', 'Salmon', 'Crimson', 'Navy', 'Teal'
|
|
27
|
-
];
|
|
28
|
-
|
|
29
|
-
export interface AnonymousUser {
|
|
30
|
-
id: string;
|
|
31
|
-
name: string;
|
|
32
|
-
color: string;
|
|
33
|
-
avatar: string;
|
|
34
|
-
createdAt: string;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
5
|
/**
|
|
38
6
|
* Generate a consistent color from a string
|
|
39
7
|
*/
|
|
@@ -62,26 +30,3 @@ export function getInitials(name: string): string {
|
|
|
62
30
|
// Fallback to first 2 characters
|
|
63
31
|
return trimmed.substring(0, 2).toUpperCase();
|
|
64
32
|
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Generate a unique anonymous user identity
|
|
68
|
-
*/
|
|
69
|
-
export function generateAnonymousUser(): AnonymousUser {
|
|
70
|
-
const randomAnimal = ANIMAL_NAMES[Math.floor(Math.random() * ANIMAL_NAMES.length)];
|
|
71
|
-
const randomColor = COLORS[Math.floor(Math.random() * COLORS.length)];
|
|
72
|
-
const randomNumber = Math.floor(Math.random() * 1000);
|
|
73
|
-
|
|
74
|
-
const name = `${randomColor} ${randomAnimal} ${randomNumber}`;
|
|
75
|
-
const id = `user-${crypto.randomUUID()}`; // Server-side crypto API
|
|
76
|
-
|
|
77
|
-
// Generate a color for the avatar based on the name
|
|
78
|
-
const avatarColor = generateColorFromString(name);
|
|
79
|
-
|
|
80
|
-
return {
|
|
81
|
-
id,
|
|
82
|
-
name,
|
|
83
|
-
color: avatarColor,
|
|
84
|
-
avatar: getInitials(randomAnimal),
|
|
85
|
-
createdAt: new Date().toISOString()
|
|
86
|
-
};
|
|
87
|
-
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The send path every frame takes: what gets compressed, and how a large
|
|
3
|
+
* reply leaves in chunks without filling the socket's buffer.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { describe, expect, test } from 'bun:test';
|
|
7
|
+
|
|
8
|
+
import { decodeChunk } from '$shared/utils/ws-chunk';
|
|
9
|
+
import { CHUNK_BYTES, COMPRESS_MIN_BYTES, sendBinary, sendReply, sendText } from './ws-wire';
|
|
10
|
+
|
|
11
|
+
class FakeSocket {
|
|
12
|
+
readyState = 1;
|
|
13
|
+
buffered = 0;
|
|
14
|
+
sent: Array<{ data: string | Buffer; compress?: boolean }> = [];
|
|
15
|
+
raw = { getBufferedAmount: () => this.buffered };
|
|
16
|
+
send(data: string | Buffer, compress?: boolean) {
|
|
17
|
+
this.sent.push({ data, compress });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('sendText / sendBinary', () => {
|
|
22
|
+
test('compresses text only when it is large enough to gain from it', () => {
|
|
23
|
+
const socket = new FakeSocket();
|
|
24
|
+
sendText(socket, 'small', 'x'.repeat(COMPRESS_MIN_BYTES - 1));
|
|
25
|
+
sendText(socket, 'large', 'x'.repeat(COMPRESS_MIN_BYTES));
|
|
26
|
+
expect(socket.sent.map((frame) => frame.compress)).toEqual([false, true]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('never compresses binary', () => {
|
|
30
|
+
const socket = new FakeSocket();
|
|
31
|
+
sendBinary(socket, 'file:download', new Uint8Array(100_000));
|
|
32
|
+
expect(socket.sent[0].compress).toBe(false);
|
|
33
|
+
expect(Buffer.isBuffer(socket.sent[0].data)).toBe(true);
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
describe('sendReply', () => {
|
|
38
|
+
test('sends a reply under the threshold as one ordinary frame', async () => {
|
|
39
|
+
const socket = new FakeSocket();
|
|
40
|
+
const text = JSON.stringify({ action: 'x:response', payload: { ok: true } });
|
|
41
|
+
await sendReply(socket, 'x:response', 'req-1', text);
|
|
42
|
+
expect(socket.sent).toEqual([{ data: text, compress: false }]);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('chunks a large reply into pieces that reassemble to the exact text', async () => {
|
|
46
|
+
const socket = new FakeSocket();
|
|
47
|
+
const text = JSON.stringify({ action: 'messages:list:response', payload: { data: 'é😀'.repeat(CHUNK_BYTES) } });
|
|
48
|
+
await sendReply(socket, 'messages:list:response', 'req-2', text);
|
|
49
|
+
|
|
50
|
+
const chunks = socket.sent.map((frame) => decodeChunk(frame.data as string)!);
|
|
51
|
+
expect(chunks.length).toBeGreaterThan(1);
|
|
52
|
+
expect(new Set(chunks.map((chunk) => chunk.streamId)).size).toBe(1);
|
|
53
|
+
expect(chunks.every((chunk) => chunk.requestId === 'req-2' && chunk.count === chunks.length)).toBe(true);
|
|
54
|
+
expect(chunks.map((chunk) => chunk.slice).join('')).toBe(text);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('two replies get distinct streams', async () => {
|
|
58
|
+
const socket = new FakeSocket();
|
|
59
|
+
const text = 'x'.repeat(CHUNK_BYTES * 2);
|
|
60
|
+
await sendReply(socket, 'a', 'req', text);
|
|
61
|
+
await sendReply(socket, 'a', 'req', text);
|
|
62
|
+
const streams = new Set(socket.sent.map((frame) => decodeChunk(frame.data as string)!.streamId));
|
|
63
|
+
expect(streams.size).toBe(2);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test('waits for the socket to drain between chunks', async () => {
|
|
67
|
+
const socket = new FakeSocket();
|
|
68
|
+
socket.buffered = 10 * 1024 * 1024;
|
|
69
|
+
const sending = sendReply(socket, 'a', 'req', 'x'.repeat(CHUNK_BYTES * 3));
|
|
70
|
+
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
71
|
+
expect(socket.sent).toHaveLength(1); // first chunk only, then held
|
|
72
|
+
|
|
73
|
+
socket.buffered = 0;
|
|
74
|
+
await sending;
|
|
75
|
+
expect(socket.sent).toHaveLength(3);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('stops when the socket closes mid-reply', async () => {
|
|
79
|
+
const socket = new FakeSocket();
|
|
80
|
+
socket.buffered = 10 * 1024 * 1024;
|
|
81
|
+
const sending = sendReply(socket, 'a', 'req', 'x'.repeat(CHUNK_BYTES * 3));
|
|
82
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
83
|
+
socket.readyState = 3;
|
|
84
|
+
await sending;
|
|
85
|
+
expect(socket.sent).toHaveLength(1);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The last step before a frame leaves the server — the one place that decides
|
|
3
|
+
* how it travels.
|
|
4
|
+
*
|
|
5
|
+
* Every event (`backend/utils/ws.ts`) and every request-response reply
|
|
6
|
+
* (`shared/utils/ws-server.ts`) is sent through here, so three concerns live
|
|
7
|
+
* once instead of at every call site:
|
|
8
|
+
*
|
|
9
|
+
* 1. Compression. The socket negotiates permessage-deflate (see
|
|
10
|
+
* `WS_PER_MESSAGE_DEFLATE`), but Bun only compresses a frame when asked to.
|
|
11
|
+
* JSON shrinks 4–12× under deflate; a frame under ~1 KB grows instead, and
|
|
12
|
+
* binary frames (uploads, downloads, media) are already dense — so only text
|
|
13
|
+
* of at least `COMPRESS_MIN_BYTES` is compressed.
|
|
14
|
+
*
|
|
15
|
+
* 2. Large replies are chunked. A request-response reply above `CHUNK_BYTES`
|
|
16
|
+
* used to leave as one frame. The browser only reports a frame once all of it
|
|
17
|
+
* has arrived, so on a slow link a multi-megabyte reply looked like silence:
|
|
18
|
+
* the client's 30 s request timer fired mid-download and re-sent the read —
|
|
19
|
+
* queueing a second copy — or tore the socket down and started over. Chunks
|
|
20
|
+
* are proof of progress (each one re-arms the request's timer), they let
|
|
21
|
+
* events slip in between instead of waiting behind the whole reply, and
|
|
22
|
+
* sending waits for the socket to drain so a slow client never makes the
|
|
23
|
+
* server buffer an entire reply in memory. Events are never chunked: they
|
|
24
|
+
* must arrive in the order they were emitted.
|
|
25
|
+
*
|
|
26
|
+
* 3. A traffic meter (development, or `CLOPEN_WS_TRAFFIC=1`) that adds up bytes
|
|
27
|
+
* per action, so a bandwidth claim can be checked against real traffic
|
|
28
|
+
* instead of an estimate.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import type { WebSocketCompressor } from 'bun';
|
|
32
|
+
import { debug } from '$shared/utils/logger';
|
|
33
|
+
import { SERVER_ENV } from './env';
|
|
34
|
+
import { encodeChunk, sliceText } from '$shared/utils/ws-chunk';
|
|
35
|
+
|
|
36
|
+
/** Text frames shorter than this are sent uncompressed — deflate would grow them. */
|
|
37
|
+
export const COMPRESS_MIN_BYTES = 1024;
|
|
38
|
+
|
|
39
|
+
/** Request-response replies longer than this (in characters) are chunked. */
|
|
40
|
+
export const CHUNK_BYTES = 256 * 1024;
|
|
41
|
+
|
|
42
|
+
/** Stop sending chunks while the socket has more than this queued. */
|
|
43
|
+
const DRAIN_HIGH_WATER = 1024 * 1024;
|
|
44
|
+
|
|
45
|
+
/** How often to re-check a full socket. */
|
|
46
|
+
const DRAIN_POLL_MS = 10;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Compression the server offers. A per-socket compressor keeps context across
|
|
50
|
+
* messages, which is what makes the stream of small, similar JSON events
|
|
51
|
+
* (stream deltas, file changes, terminal output) compress well; 32 KB per
|
|
52
|
+
* connection is the price. Client → server frames are small and use the shared
|
|
53
|
+
* decompressor.
|
|
54
|
+
*/
|
|
55
|
+
export const WS_PER_MESSAGE_DEFLATE: { compress: WebSocketCompressor; decompress: WebSocketCompressor } = {
|
|
56
|
+
compress: '32KB',
|
|
57
|
+
decompress: 'shared'
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Server-wide socket options, handed to `new Elysia({ websocket })`.
|
|
62
|
+
*
|
|
63
|
+
* They must be set there. Elysia drops the same keys on a `.ws()` route, which
|
|
64
|
+
* is where they used to live — so for as long as that was the case Bun's
|
|
65
|
+
* defaults applied instead: a 16 MB frame limit that closed the socket on any
|
|
66
|
+
* larger upload (1006), and a 120 s idle timeout.
|
|
67
|
+
*/
|
|
68
|
+
export const WS_SERVER_OPTIONS = {
|
|
69
|
+
// Allow large binary frames (file uploads, zip extracts); the per-file
|
|
70
|
+
// limits are enforced by the handlers, not by the transport.
|
|
71
|
+
maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
|
|
72
|
+
// Don't drop a connection that is busy with one long binary transfer.
|
|
73
|
+
idleTimeout: 960, // seconds (max allowed by uWS)
|
|
74
|
+
perMessageDeflate: WS_PER_MESSAGE_DEFLATE
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** Numbers each chunked reply, so two replies to one re-sent request stay apart. */
|
|
78
|
+
let replyStreams = 0;
|
|
79
|
+
|
|
80
|
+
/** The part of a socket this module needs: Elysia's wrapper or Bun's own. */
|
|
81
|
+
interface WireSocket {
|
|
82
|
+
readyState: number;
|
|
83
|
+
send(data: string | Buffer, compress?: boolean): unknown;
|
|
84
|
+
raw?: { getBufferedAmount?: () => number };
|
|
85
|
+
getBufferedAmount?: () => number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Send one text frame, compressed when it is big enough to gain from it. */
|
|
89
|
+
export function sendText(conn: WireSocket, action: string, text: string): void {
|
|
90
|
+
conn.send(text, text.length >= COMPRESS_MIN_BYTES);
|
|
91
|
+
recordTraffic(action, text.length);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Send one binary frame. Never compressed: it is already dense. */
|
|
95
|
+
export function sendBinary(conn: WireSocket, action: string, data: ArrayBuffer | Uint8Array | Buffer): void {
|
|
96
|
+
const buffer = Buffer.isBuffer(data)
|
|
97
|
+
? data
|
|
98
|
+
: data instanceof ArrayBuffer
|
|
99
|
+
? Buffer.from(data)
|
|
100
|
+
: Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
101
|
+
conn.send(buffer, false);
|
|
102
|
+
recordTraffic(action, buffer.byteLength);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Send a serialized request-response reply, chunked when it is large.
|
|
107
|
+
* Resolves once the last chunk is handed to the socket (or the socket closed).
|
|
108
|
+
*/
|
|
109
|
+
export async function sendReply(conn: WireSocket, action: string, requestId: string, text: string): Promise<void> {
|
|
110
|
+
if (text.length <= CHUNK_BYTES || !requestId) {
|
|
111
|
+
sendText(conn, action, text);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const slices = sliceText(text, CHUNK_BYTES);
|
|
116
|
+
const streamId = String(++replyStreams);
|
|
117
|
+
for (let index = 0; index < slices.length; index++) {
|
|
118
|
+
if (index > 0) {
|
|
119
|
+
await waitForDrain(conn);
|
|
120
|
+
if (conn.readyState !== 1) return; // The client is gone; it will re-request.
|
|
121
|
+
}
|
|
122
|
+
const frame = encodeChunk(streamId, requestId, index, slices.length, slices[index]);
|
|
123
|
+
conn.send(frame, true);
|
|
124
|
+
recordTraffic(action, frame.length);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function bufferedAmount(conn: WireSocket): number {
|
|
129
|
+
try {
|
|
130
|
+
if (typeof conn.raw?.getBufferedAmount === 'function') return conn.raw.getBufferedAmount();
|
|
131
|
+
if (typeof conn.getBufferedAmount === 'function') return conn.getBufferedAmount();
|
|
132
|
+
} catch {
|
|
133
|
+
// A closed socket throws; the caller checks readyState next.
|
|
134
|
+
}
|
|
135
|
+
return 0;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function waitForDrain(conn: WireSocket): Promise<void> {
|
|
139
|
+
while (conn.readyState === 1 && bufferedAmount(conn) > DRAIN_HIGH_WATER) {
|
|
140
|
+
await new Promise((resolve) => setTimeout(resolve, DRAIN_POLL_MS));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ============================================================================
|
|
145
|
+
// Traffic meter
|
|
146
|
+
// ============================================================================
|
|
147
|
+
|
|
148
|
+
const TRAFFIC_ENABLED = SERVER_ENV.isDevelopment || process.env.CLOPEN_WS_TRAFFIC === '1';
|
|
149
|
+
const TRAFFIC_REPORT_MS = 30_000;
|
|
150
|
+
|
|
151
|
+
const traffic = new Map<string, { frames: number; bytes: number }>();
|
|
152
|
+
let reportTimer: ReturnType<typeof setInterval> | null = null;
|
|
153
|
+
|
|
154
|
+
function recordTraffic(action: string, bytes: number): void {
|
|
155
|
+
if (!TRAFFIC_ENABLED) return;
|
|
156
|
+
const entry = traffic.get(action);
|
|
157
|
+
if (entry) {
|
|
158
|
+
entry.frames++;
|
|
159
|
+
entry.bytes += bytes;
|
|
160
|
+
} else {
|
|
161
|
+
traffic.set(action, { frames: 1, bytes });
|
|
162
|
+
}
|
|
163
|
+
if (!reportTimer) {
|
|
164
|
+
reportTimer = setInterval(reportTraffic, TRAFFIC_REPORT_MS);
|
|
165
|
+
reportTimer.unref?.();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Bytes sent per action since the last report (before compression), largest first. */
|
|
170
|
+
export function takeTrafficReport(): Array<{ action: string; frames: number; bytes: number }> {
|
|
171
|
+
const rows = [...traffic.entries()]
|
|
172
|
+
.map(([action, entry]) => ({ action, ...entry }))
|
|
173
|
+
.sort((a, b) => b.bytes - a.bytes);
|
|
174
|
+
traffic.clear();
|
|
175
|
+
return rows;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function reportTraffic(): void {
|
|
179
|
+
const rows = takeTrafficReport();
|
|
180
|
+
if (rows.length === 0) return;
|
|
181
|
+
const total = rows.reduce((sum, row) => sum + row.bytes, 0);
|
|
182
|
+
const lines = rows
|
|
183
|
+
.slice(0, 15)
|
|
184
|
+
.map((row) => ` ${(row.bytes / 1024).toFixed(1).padStart(10)} KB ${String(row.frames).padStart(6)}× ${row.action}`);
|
|
185
|
+
debug.log(
|
|
186
|
+
'websocket',
|
|
187
|
+
`WS traffic, last ${TRAFFIC_REPORT_MS / 1000}s: ${(total / 1024).toFixed(1)} KB before compression\n${lines.join('\n')}`
|
|
188
|
+
);
|
|
189
|
+
}
|