@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
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Attachments — one rule for every way a file reaches a prompt.
|
|
3
|
+
*
|
|
4
|
+
* The web composer and the chat apps both hand the stream image and document
|
|
5
|
+
* blocks. What an engine can READ natively depends on the model: images and
|
|
6
|
+
* PDFs when its input modalities say so, nothing else. Everything else is
|
|
7
|
+
* still worth sending — a CSV, a log, a zip, a screenshot for a text-only
|
|
8
|
+
* model — so instead of refusing it, the file is written into the session's
|
|
9
|
+
* working tree and the prompt names it, which every engine can act on with its
|
|
10
|
+
* own file tools.
|
|
11
|
+
*
|
|
12
|
+
* Files land in `.clopen/attachments/` under the session's working root. The
|
|
13
|
+
* folder ignores itself (`.clopen/.gitignore` is `*`), so an attachment never
|
|
14
|
+
* shows up in git or in a turn's snapshot as a change the agent made.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { mkdirSync, writeFileSync, existsSync } from 'fs';
|
|
18
|
+
import { join, extname, basename } from 'path';
|
|
19
|
+
import type { EngineModel, EngineType, StreamRequest } from '$shared/types/unified';
|
|
20
|
+
import { getModelsByEngine, registerModels } from '$shared/constants/engines';
|
|
21
|
+
import { debug } from '$shared/utils/logger';
|
|
22
|
+
import { MAX_ATTACHMENT_BYTES, MAX_INLINE_ATTACHMENT_BYTES } from '$shared/constants/attachments';
|
|
23
|
+
|
|
24
|
+
/** Image types every vision model takes inline. */
|
|
25
|
+
export const NATIVE_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] as const;
|
|
26
|
+
export const PDF_TYPE = 'application/pdf';
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
export const ATTACHMENTS_DIR = join('.clopen', 'attachments');
|
|
30
|
+
|
|
31
|
+
type Modalities = EngineModel['modalities']['input'];
|
|
32
|
+
|
|
33
|
+
/** When the model is unknown, assume what the web composer assumes. */
|
|
34
|
+
const FALLBACK_MODALITIES: Modalities = { text: true, image: true, pdf: true, audio: false, video: false };
|
|
35
|
+
|
|
36
|
+
/** A model's input modalities — from the registry, filling it on first use. */
|
|
37
|
+
export async function inputModalities(engine: EngineType, modelId: string): Promise<Modalities> {
|
|
38
|
+
let models = getModelsByEngine(engine);
|
|
39
|
+
if (models.length === 0) {
|
|
40
|
+
try {
|
|
41
|
+
const { initializeEngine } = await import('$backend/engine');
|
|
42
|
+
models = await (await initializeEngine(engine)).getAvailableModels();
|
|
43
|
+
registerModels(engine, models);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
debug.warn('chat', 'Could not load models to check attachment support:', error);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return models.find((model) => model.engine.model.id === modelId)?.modalities.input ?? FALLBACK_MODALITIES;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Can this model read a file of `mediaType` inline? */
|
|
52
|
+
export function isNative(mediaType: string, modalities: Modalities): boolean {
|
|
53
|
+
if ((NATIVE_IMAGE_TYPES as readonly string[]).includes(mediaType)) return modalities.image;
|
|
54
|
+
if (mediaType === PDF_TYPE) return modalities.pdf;
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function base64Size(data: string): number {
|
|
59
|
+
const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
|
|
60
|
+
return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function formatBytes(bytes: number): string {
|
|
64
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
65
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
66
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const EXTENSION_BY_TYPE: Record<string, string> = {
|
|
70
|
+
'image/jpeg': '.jpg',
|
|
71
|
+
'image/png': '.png',
|
|
72
|
+
'image/gif': '.gif',
|
|
73
|
+
'image/webp': '.webp',
|
|
74
|
+
'application/pdf': '.pdf',
|
|
75
|
+
'text/plain': '.txt',
|
|
76
|
+
'audio/ogg': '.ogg',
|
|
77
|
+
'audio/mpeg': '.mp3',
|
|
78
|
+
'video/mp4': '.mp4'
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** A file name that is safe on every OS and keeps its extension. */
|
|
82
|
+
function safeName(name: string | null | undefined, mediaType: string): string {
|
|
83
|
+
const base = basename(name?.trim() || 'attachment').replace(/[^\w.\- ]+/g, '_').replace(/\s+/g, '-').slice(0, 120) || 'attachment';
|
|
84
|
+
return extname(base) ? base : `${base}${EXTENSION_BY_TYPE[mediaType] ?? ''}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function stamp(date = new Date()): string {
|
|
88
|
+
const pad = (value: number) => String(value).padStart(2, '0');
|
|
89
|
+
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Write one attachment under `root` and return its path relative to `root`. */
|
|
93
|
+
export function saveAttachment(root: string, input: { data: Uint8Array; mediaType: string; name?: string | null }): string {
|
|
94
|
+
const dir = join(root, ATTACHMENTS_DIR);
|
|
95
|
+
mkdirSync(dir, { recursive: true });
|
|
96
|
+
const ignore = join(root, '.clopen', '.gitignore');
|
|
97
|
+
if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
|
|
98
|
+
|
|
99
|
+
const name = safeName(input.name, input.mediaType);
|
|
100
|
+
let file = `${stamp()}-${name}`;
|
|
101
|
+
for (let n = 2; existsSync(join(dir, file)); n++) file = `${stamp()}-${n}-${name}`;
|
|
102
|
+
writeFileSync(join(dir, file), input.data);
|
|
103
|
+
return join(ATTACHMENTS_DIR, file);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The line a prompt carries for a file it does not hold inline. */
|
|
107
|
+
export function attachmentMention(relativePath: string, input: { mediaType: string; size: number; name?: string | null }): string {
|
|
108
|
+
const label = input.name?.trim() ? `"${input.name.trim()}"` : 'a file';
|
|
109
|
+
return `[Attached ${label} (${input.mediaType || 'unknown type'}, ${formatBytes(input.size)}), saved at ./${relativePath.split('\\').join('/')}]`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Keep what the model reads inline; save the rest under `root` and name it in
|
|
114
|
+
* the prompt instead. Returns the request unchanged when nothing had to move.
|
|
115
|
+
*/
|
|
116
|
+
export async function normalizeAttachments(request: StreamRequest, root: string): Promise<StreamRequest> {
|
|
117
|
+
const content = (request.prompt as { content?: unknown })?.content;
|
|
118
|
+
if (!Array.isArray(content)) return request;
|
|
119
|
+
const files = content.filter((block) => block?.type === 'image' || block?.type === 'document');
|
|
120
|
+
if (files.length === 0) return request;
|
|
121
|
+
|
|
122
|
+
const modalities = await inputModalities(request.engine.type, request.engine.model.id);
|
|
123
|
+
const mentions: string[] = [];
|
|
124
|
+
const kept: unknown[] = [];
|
|
125
|
+
for (const block of content) {
|
|
126
|
+
if ((block?.type !== 'image' && block?.type !== 'document') || typeof block.data !== 'string') {
|
|
127
|
+
kept.push(block);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const mediaType = typeof block.mediaType === 'string' ? block.mediaType : 'application/octet-stream';
|
|
131
|
+
const size = base64Size(block.data);
|
|
132
|
+
if (isNative(mediaType, modalities) && size <= MAX_INLINE_ATTACHMENT_BYTES) {
|
|
133
|
+
kept.push(block);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (size > MAX_ATTACHMENT_BYTES) {
|
|
137
|
+
mentions.push(`[An attached file "${block.title ?? 'attachment'}" (${formatBytes(size)}) was too large to keep. The limit is ${formatBytes(MAX_ATTACHMENT_BYTES)}.]`);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
const path = saveAttachment(root, { data: Buffer.from(block.data, 'base64'), mediaType, name: block.title });
|
|
142
|
+
mentions.push(attachmentMention(path, { mediaType, size, name: block.title }));
|
|
143
|
+
} catch (error) {
|
|
144
|
+
debug.warn('chat', 'Saving an attachment failed:', error);
|
|
145
|
+
mentions.push(`[An attached file "${block.title ?? 'attachment'}" could not be saved.]`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (mentions.length === 0) return request;
|
|
149
|
+
|
|
150
|
+
// The mention leads the text, so "summarise this" still reads as being about the file.
|
|
151
|
+
const textIndex = kept.findIndex((block) => (block as { type?: string })?.type === 'text');
|
|
152
|
+
const note = mentions.join('\n');
|
|
153
|
+
if (textIndex === -1) kept.push({ type: 'text', text: note });
|
|
154
|
+
else {
|
|
155
|
+
const text = kept[textIndex] as { type: 'text'; text: string };
|
|
156
|
+
kept[textIndex] = { type: 'text', text: text.text.trim() ? `${note}\n\n${text.text}` : note };
|
|
157
|
+
}
|
|
158
|
+
return { ...request, prompt: { ...request.prompt, content: kept } as StreamRequest['prompt'] };
|
|
159
|
+
}
|
|
@@ -36,7 +36,6 @@ function user(id: string, text: string, extra: Partial<UserMessage> = {}): UserM
|
|
|
36
36
|
return {
|
|
37
37
|
...base(id),
|
|
38
38
|
type: 'user',
|
|
39
|
-
sender: { id: 'u', name: 'U' },
|
|
40
39
|
content: [{ type: 'text', text }],
|
|
41
40
|
synthetic: false,
|
|
42
41
|
...extra,
|
|
@@ -77,7 +76,6 @@ function toolResult(id: string, toolUseId: string, content: string): UserMessage
|
|
|
77
76
|
return {
|
|
78
77
|
...base(id),
|
|
79
78
|
type: 'user',
|
|
80
|
-
sender: { id: '', name: '' },
|
|
81
79
|
content: [{ type: 'tool_result', toolUseId, content, isError: false }],
|
|
82
80
|
synthetic: true,
|
|
83
81
|
};
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paging a chat's active branch: pages start at a turn so no turn is split,
|
|
3
|
+
* consecutive pages cover the branch exactly once, and the prompt index and
|
|
4
|
+
* task history cover what is not loaded.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
|
|
8
|
+
import { initializeDatabase, closeDatabase } from '$backend/database';
|
|
9
|
+
import { messageQueries, projectQueries, sessionQueries } from '$backend/database/queries';
|
|
10
|
+
import type { UnifiedMessage } from '$shared/types/unified';
|
|
11
|
+
|
|
12
|
+
import { getMessagePage, getPromptIndex, getTaskHistory } from './message-pages';
|
|
13
|
+
|
|
14
|
+
let projectId: string;
|
|
15
|
+
const engine = { type: 'claude-code', provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
|
|
16
|
+
const base = { createdAt: '2026-11-17T00:00:00.000Z', sessionId: null, engine };
|
|
17
|
+
|
|
18
|
+
const prompt = (text: string) =>
|
|
19
|
+
({ ...base, type: 'user', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'text', text }] }) as unknown as UnifiedMessage;
|
|
20
|
+
const toolCall = (id: string, name = 'Read', input: unknown = {}) =>
|
|
21
|
+
({ ...base, type: 'assistant', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'tool_use', id, name, input }] }) as unknown as UnifiedMessage;
|
|
22
|
+
const toolResult = (toolUseId: string, content = 'ok') =>
|
|
23
|
+
({ ...base, type: 'user', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'tool_result', toolUseId, content }] }) as unknown as UnifiedMessage;
|
|
24
|
+
const answer = (text: string) =>
|
|
25
|
+
({ ...base, type: 'assistant', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'text', text }] }) as unknown as UnifiedMessage;
|
|
26
|
+
|
|
27
|
+
function newSession(): string {
|
|
28
|
+
return sessionQueries.create({ project_id: projectId, engine: 'claude-code', started_at: new Date().toISOString() } as never).id;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Build a branch of turns: each turn = prompt, N tool call/result pairs, answer. */
|
|
32
|
+
function buildBranch(sessionId: string, turns: number, toolsPerTurn: number): string[] {
|
|
33
|
+
const ids: string[] = [];
|
|
34
|
+
let parent: string | undefined;
|
|
35
|
+
const push = (message: UnifiedMessage) => {
|
|
36
|
+
const row = messageQueries.create({ session_id: sessionId, message, parent_message_id: parent });
|
|
37
|
+
parent = row.id;
|
|
38
|
+
ids.push(row.id);
|
|
39
|
+
sessionQueries.updateHead(sessionId, row.id);
|
|
40
|
+
};
|
|
41
|
+
for (let t = 0; t < turns; t++) {
|
|
42
|
+
push(prompt(`turn ${t}`));
|
|
43
|
+
for (let k = 0; k < toolsPerTurn; k++) {
|
|
44
|
+
push(toolCall(`call-${t}-${k}`));
|
|
45
|
+
push(toolResult(`call-${t}-${k}`));
|
|
46
|
+
}
|
|
47
|
+
push(answer(`done ${t}`));
|
|
48
|
+
}
|
|
49
|
+
return ids;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const textOf = (message: UnifiedMessage) =>
|
|
53
|
+
message.type === 'user' || message.type === 'assistant'
|
|
54
|
+
? (message.content.find((block) => block.type === 'text') as { text?: string } | undefined)?.text
|
|
55
|
+
: undefined;
|
|
56
|
+
|
|
57
|
+
beforeAll(async () => {
|
|
58
|
+
await initializeDatabase();
|
|
59
|
+
projectId = projectQueries.create({ name: 'message-pages', path: `/tmp/message-pages-${crypto.randomUUID()}`, created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
afterAll(() => {
|
|
63
|
+
sessionQueries.deleteAllByProjectId(projectId);
|
|
64
|
+
projectQueries.deleteProject(projectId);
|
|
65
|
+
closeDatabase();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('getMessagePage', () => {
|
|
69
|
+
it('never splits a tool call from its result, even inside a long turn', () => {
|
|
70
|
+
const session = newSession();
|
|
71
|
+
buildBranch(session, 2, 60); // two turns of 122 messages each
|
|
72
|
+
|
|
73
|
+
const page = getMessagePage(session, { minCount: 10 });
|
|
74
|
+
expect(page.messages.length).toBeLessThan(20); // cut inside the turn, not at its start
|
|
75
|
+
expect(page.hasMore).toBe(true);
|
|
76
|
+
const calls = new Set<string>();
|
|
77
|
+
for (const message of page.messages) {
|
|
78
|
+
if (message.type !== 'user' && message.type !== 'assistant') continue;
|
|
79
|
+
for (const block of message.content) {
|
|
80
|
+
if (block.type === 'tool_use') calls.add(block.id);
|
|
81
|
+
if (block.type === 'tool_result') expect(calls.has((block as { toolUseId: string }).toolUseId)).toBe(true);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('does not begin a page with a synthetic message, nor split a sub-agent from its call', () => {
|
|
87
|
+
const session = newSession();
|
|
88
|
+
let parent: string | undefined;
|
|
89
|
+
const push = (message: UnifiedMessage) => {
|
|
90
|
+
const row = messageQueries.create({ session_id: session, message, parent_message_id: parent });
|
|
91
|
+
parent = row.id;
|
|
92
|
+
sessionQueries.updateHead(session, row.id);
|
|
93
|
+
};
|
|
94
|
+
push(prompt('start'));
|
|
95
|
+
push(toolCall('agent-1', 'Agent'));
|
|
96
|
+
push({ ...(prompt('sub-agent work') as object), parent: { messageId: null, sessionId: null, toolUseId: 'agent-1' } } as unknown as UnifiedMessage);
|
|
97
|
+
push({ ...(answer('sub-agent answer') as object), parent: { messageId: null, sessionId: null, toolUseId: 'agent-1' } } as unknown as UnifiedMessage);
|
|
98
|
+
push(toolResult('agent-1'));
|
|
99
|
+
push(toolCall('skill-1', 'Skill'));
|
|
100
|
+
push({ ...(prompt('expanded skill prompt') as object), synthetic: true } as unknown as UnifiedMessage);
|
|
101
|
+
|
|
102
|
+
const page = getMessagePage(session, { minCount: 1 });
|
|
103
|
+
expect((page.messages[0] as { synthetic?: boolean }).synthetic).not.toBe(true);
|
|
104
|
+
const texts = page.messages.map(textOf);
|
|
105
|
+
if (texts.includes('sub-agent work')) expect(page.messages.some((m) => JSON.stringify(m).includes('"id":"agent-1"'))).toBe(true);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('pages back through the whole branch exactly once, in order', () => {
|
|
109
|
+
const session = newSession();
|
|
110
|
+
const ids = buildBranch(session, 12, 2);
|
|
111
|
+
|
|
112
|
+
const collected: string[] = [];
|
|
113
|
+
let before: string | undefined;
|
|
114
|
+
for (let guard = 0; guard < 50; guard++) {
|
|
115
|
+
const page = getMessagePage(session, { beforeId: before, minCount: 7 });
|
|
116
|
+
collected.unshift(...page.messages.map((message) => (message as { messageId: string }).messageId));
|
|
117
|
+
if (!page.hasMore) break;
|
|
118
|
+
before = (page.messages[0] as { messageId: string }).messageId;
|
|
119
|
+
}
|
|
120
|
+
expect(collected).toEqual(ids);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('answers an empty page for a session with no messages, or an unknown cursor', () => {
|
|
124
|
+
const session = newSession();
|
|
125
|
+
expect(getMessagePage(session)).toEqual({ messages: [], hasMore: false });
|
|
126
|
+
buildBranch(session, 1, 0);
|
|
127
|
+
expect(getMessagePage(session, { beforeId: 'not-a-message' })).toEqual({ messages: [], hasMore: false });
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
describe('getPromptIndex', () => {
|
|
132
|
+
it('lists every real prompt on the branch, oldest first, with no tool results', () => {
|
|
133
|
+
const session = newSession();
|
|
134
|
+
buildBranch(session, 4, 2);
|
|
135
|
+
expect(getPromptIndex(session).map((entry) => entry.text)).toEqual(['turn 0', 'turn 1', 'turn 2', 'turn 3']);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe('getTaskHistory', () => {
|
|
140
|
+
it('returns the task calls and their results older than a message, and nothing else', () => {
|
|
141
|
+
const session = newSession();
|
|
142
|
+
let parent: string | undefined;
|
|
143
|
+
const push = (message: UnifiedMessage) => {
|
|
144
|
+
const row = messageQueries.create({ session_id: session, message, parent_message_id: parent });
|
|
145
|
+
parent = row.id;
|
|
146
|
+
sessionQueries.updateHead(session, row.id);
|
|
147
|
+
return row.id;
|
|
148
|
+
};
|
|
149
|
+
push(prompt('plan'));
|
|
150
|
+
push(toolCall('task-1', 'TaskCreate', { subject: 'Write tests' }));
|
|
151
|
+
push(toolResult('task-1', 'Task #1 created'));
|
|
152
|
+
push(toolCall('read-1', 'Read'));
|
|
153
|
+
push(toolResult('read-1', 'file body'));
|
|
154
|
+
const later = push(prompt('next'));
|
|
155
|
+
push(toolCall('task-2', 'TaskUpdate', { taskId: '1', status: 'completed' }));
|
|
156
|
+
|
|
157
|
+
const history = getTaskHistory(session, later);
|
|
158
|
+
expect(history.map((message) => message.type)).toEqual(['assistant', 'user']);
|
|
159
|
+
expect(JSON.stringify(history)).toContain('task-1');
|
|
160
|
+
expect(JSON.stringify(history)).not.toContain('read-1');
|
|
161
|
+
expect(JSON.stringify(history)).not.toContain('task-2'); // newer than the cursor
|
|
162
|
+
});
|
|
163
|
+
});
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a chat's active branch a page at a time.
|
|
3
|
+
*
|
|
4
|
+
* Opening a chat used to send its whole branch — every message since the first,
|
|
5
|
+
* images included — which on a long chat was tens of megabytes on every open.
|
|
6
|
+
* The chat now loads its most recent turns and fetches older ones as the user
|
|
7
|
+
* scrolls up (or jumps to a message that is not loaded yet).
|
|
8
|
+
*
|
|
9
|
+
* A page never starts where it would split something the chat renders as one:
|
|
10
|
+
* every tool result and every sub-agent message in it has its tool call in the
|
|
11
|
+
* same page, and it does not begin with a synthetic user message (a compaction
|
|
12
|
+
* summary or an expanded skill prompt, which belong to the message before
|
|
13
|
+
* them). That is checked on the page itself, so a boundary can fall inside a
|
|
14
|
+
* long agent turn — turns of several hundred messages are common, and cutting
|
|
15
|
+
* only at user prompts made the first page nearly the whole chat. A user
|
|
16
|
+
* prompt always qualifies.
|
|
17
|
+
*
|
|
18
|
+
* Two things the chat needs from the WHOLE branch are served separately and
|
|
19
|
+
* cheaply, without message bodies the user is not looking at:
|
|
20
|
+
* - the prompt index (the navigation rail's dots, one per user prompt);
|
|
21
|
+
* - the task tools older than the loaded page (the task progress widget
|
|
22
|
+
* replays TaskCreate / TaskUpdate / TodoWrite from the start).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { getDatabase } from '../database';
|
|
26
|
+
import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
27
|
+
import type { UnifiedMessage } from '$shared/types/unified';
|
|
28
|
+
import { trimSubAgentForWire } from '$shared/utils/subagent-wire-trim';
|
|
29
|
+
import { isCheckpointMessage, extractMessageText } from '../snapshot/helpers';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Walks a branch from newest to oldest and says where a page may begin: at a
|
|
33
|
+
* message no later message depends on from across the boundary.
|
|
34
|
+
*/
|
|
35
|
+
class BoundaryTracker {
|
|
36
|
+
private readonly defined = new Set<string>();
|
|
37
|
+
private readonly needed = new Set<string>();
|
|
38
|
+
|
|
39
|
+
/** Record `message` (older than everything seen so far); true if a page may start at it. */
|
|
40
|
+
add(message: UnifiedMessage): boolean {
|
|
41
|
+
if (message.type === 'user' || message.type === 'assistant') {
|
|
42
|
+
const parentToolUseId = message.parent?.toolUseId;
|
|
43
|
+
if (parentToolUseId && !this.defined.has(parentToolUseId)) this.needed.add(parentToolUseId);
|
|
44
|
+
for (const block of message.content) {
|
|
45
|
+
if (block.type === 'tool_result') {
|
|
46
|
+
const id = (block as { toolUseId?: string }).toolUseId;
|
|
47
|
+
if (id && !this.defined.has(id)) this.needed.add(id);
|
|
48
|
+
} else if (block.type === 'tool_use') {
|
|
49
|
+
this.defined.add(block.id);
|
|
50
|
+
this.needed.delete(block.id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const synthetic = message.type === 'user' && (message as { synthetic?: boolean }).synthetic === true;
|
|
55
|
+
return this.needed.size === 0 && !synthetic;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Messages a page holds at least — then it is extended back to the start of a turn. */
|
|
60
|
+
export const DEFAULT_PAGE_SIZE = 80;
|
|
61
|
+
|
|
62
|
+
/** Longest prompt preview the navigation rail shows. */
|
|
63
|
+
const PROMPT_PREVIEW_LENGTH = 200;
|
|
64
|
+
|
|
65
|
+
/** Tools the task progress widget replays. */
|
|
66
|
+
const TASK_TOOLS = ['TaskCreate', 'TaskUpdate', 'TodoWrite'] as const;
|
|
67
|
+
|
|
68
|
+
export interface MessagePage {
|
|
69
|
+
/** Oldest first, as the chat renders them. */
|
|
70
|
+
messages: UnifiedMessage[];
|
|
71
|
+
/** Whether older messages exist on the branch before this page. */
|
|
72
|
+
hasMore: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface PromptIndexEntry {
|
|
76
|
+
messageId: string;
|
|
77
|
+
text: string;
|
|
78
|
+
createdAt: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function headOf(sessionId: string): string | null {
|
|
82
|
+
const row = getDatabase()
|
|
83
|
+
.prepare('SELECT head_message_id FROM chat_sessions WHERE id = ?')
|
|
84
|
+
.get(sessionId) as { head_message_id: string | null } | null;
|
|
85
|
+
return row?.head_message_id ?? null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* One page of the active branch, ending just before `beforeId` (or at the head
|
|
90
|
+
* when absent). Holds at least `minCount` messages and always begins at a turn.
|
|
91
|
+
*/
|
|
92
|
+
export function getMessagePage(
|
|
93
|
+
sessionId: string,
|
|
94
|
+
options: { beforeId?: string; minCount?: number } = {}
|
|
95
|
+
): MessagePage {
|
|
96
|
+
const minCount = Math.max(1, options.minCount ?? DEFAULT_PAGE_SIZE);
|
|
97
|
+
const byId = getDatabase().prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?');
|
|
98
|
+
|
|
99
|
+
let cursor: string | null;
|
|
100
|
+
if (options.beforeId) {
|
|
101
|
+
const anchor = byId.get(options.beforeId, sessionId) as DatabaseMessage | null;
|
|
102
|
+
if (!anchor) return { messages: [], hasMore: false };
|
|
103
|
+
cursor = anchor.parent_message_id ?? null;
|
|
104
|
+
} else {
|
|
105
|
+
cursor = headOf(sessionId);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const messages: UnifiedMessage[] = [];
|
|
109
|
+
const boundary = new BoundaryTracker();
|
|
110
|
+
while (cursor) {
|
|
111
|
+
const row = byId.get(cursor, sessionId) as DatabaseMessage | null;
|
|
112
|
+
if (!row) {
|
|
113
|
+
cursor = null;
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
117
|
+
messages.push(message);
|
|
118
|
+
cursor = row.parent_message_id ?? null;
|
|
119
|
+
const mayStartHere = boundary.add(message);
|
|
120
|
+
if (messages.length >= minCount && mayStartHere) break;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
messages: messages.reverse().map(trimSubAgentForWire),
|
|
125
|
+
hasMore: cursor !== null && byId.get(cursor, sessionId) != null
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The branch, newest first, as light rows: id and parent for every message,
|
|
131
|
+
* plus the body only where `wantBody` says so (decided in SQL, so the bodies
|
|
132
|
+
* of everything else — tool output, images — are never read into JS).
|
|
133
|
+
*/
|
|
134
|
+
function branchRows(
|
|
135
|
+
sessionId: string,
|
|
136
|
+
wantBody: string,
|
|
137
|
+
fromId: string | null
|
|
138
|
+
): Array<{ id: string; parent_message_id: string | null; data: string | null }> {
|
|
139
|
+
if (!fromId) return [];
|
|
140
|
+
const rows = getDatabase()
|
|
141
|
+
.prepare(`SELECT id, parent_message_id, CASE WHEN ${wantBody} THEN data END AS data FROM messages WHERE session_id = ?`)
|
|
142
|
+
.all(sessionId) as Array<{ id: string; parent_message_id: string | null; data: string | null }>;
|
|
143
|
+
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
144
|
+
|
|
145
|
+
const branch: typeof rows = [];
|
|
146
|
+
const seen = new Set<string>();
|
|
147
|
+
let cursor: string | null = fromId;
|
|
148
|
+
while (cursor && !seen.has(cursor)) {
|
|
149
|
+
seen.add(cursor);
|
|
150
|
+
const row = byId.get(cursor);
|
|
151
|
+
if (!row) break;
|
|
152
|
+
branch.push(row);
|
|
153
|
+
cursor = row.parent_message_id;
|
|
154
|
+
}
|
|
155
|
+
return branch;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Every user prompt on the active branch, oldest first — the navigation rail. */
|
|
159
|
+
export function getPromptIndex(sessionId: string): PromptIndexEntry[] {
|
|
160
|
+
const rows = branchRows(sessionId, `json_extract(data, '$.type') = 'user'`, headOf(sessionId));
|
|
161
|
+
const prompts: PromptIndexEntry[] = [];
|
|
162
|
+
for (let i = rows.length - 1; i >= 0; i--) {
|
|
163
|
+
const row = rows[i];
|
|
164
|
+
if (!row.data) continue;
|
|
165
|
+
const asRow = row as unknown as DatabaseMessage;
|
|
166
|
+
if (!isCheckpointMessage(asRow)) continue;
|
|
167
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
168
|
+
prompts.push({
|
|
169
|
+
messageId: row.id,
|
|
170
|
+
text: extractMessageText(message).slice(0, PROMPT_PREVIEW_LENGTH),
|
|
171
|
+
createdAt: (message as { createdAt?: string }).createdAt ?? ''
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
return prompts;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The task-tool calls (and their results) on the branch older than `beforeId`,
|
|
179
|
+
* oldest first. Together with the loaded messages this is exactly what the task
|
|
180
|
+
* widget used to replay from the full branch.
|
|
181
|
+
*/
|
|
182
|
+
export function getTaskHistory(sessionId: string, beforeId: string): UnifiedMessage[] {
|
|
183
|
+
const parent = getDatabase()
|
|
184
|
+
.prepare('SELECT parent_message_id FROM messages WHERE id = ? AND session_id = ?')
|
|
185
|
+
.get(beforeId, sessionId) as { parent_message_id: string | null } | null;
|
|
186
|
+
if (!parent?.parent_message_id) return [];
|
|
187
|
+
|
|
188
|
+
// Pass 1: the branch, with bodies only for messages that call a task tool.
|
|
189
|
+
const mentionsTaskTool = TASK_TOOLS.map((name) => `instr(data, '"name":"${name}"') > 0`).join(' OR ');
|
|
190
|
+
const branch = branchRows(sessionId, mentionsTaskTool, parent.parent_message_id).reverse();
|
|
191
|
+
|
|
192
|
+
const taskCallIds = new Set<string>();
|
|
193
|
+
const calls = new Map<string, UnifiedMessage>();
|
|
194
|
+
for (const row of branch) {
|
|
195
|
+
if (!row.data) continue;
|
|
196
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
197
|
+
if (message.type !== 'assistant') continue;
|
|
198
|
+
let hasTaskCall = false;
|
|
199
|
+
for (const block of message.content) {
|
|
200
|
+
if (block.type === 'tool_use' && (TASK_TOOLS as readonly string[]).includes(block.name)) {
|
|
201
|
+
taskCallIds.add(block.id);
|
|
202
|
+
hasTaskCall = true;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (hasTaskCall) calls.set(row.id, message);
|
|
206
|
+
}
|
|
207
|
+
if (taskCallIds.size === 0) return [];
|
|
208
|
+
|
|
209
|
+
// Pass 2: only the messages that answer one of those calls — never the
|
|
210
|
+
// thousands of other tool results (file reads, screenshots) on the branch.
|
|
211
|
+
const ids = [...taskCallIds];
|
|
212
|
+
const answerRows = getDatabase()
|
|
213
|
+
.prepare(
|
|
214
|
+
`SELECT id, data FROM messages WHERE session_id = ? AND (${ids.map(() => 'instr(data, ?) > 0').join(' OR ')})`
|
|
215
|
+
)
|
|
216
|
+
.all(sessionId, ...ids.map((id) => `"toolUseId":"${id}"`)) as Array<{ id: string; data: string }>;
|
|
217
|
+
const answers = new Map<string, UnifiedMessage>();
|
|
218
|
+
for (const row of answerRows) {
|
|
219
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
220
|
+
if (message.type !== 'user') continue;
|
|
221
|
+
const answersTask = message.content.some(
|
|
222
|
+
(block) => block.type === 'tool_result' && taskCallIds.has((block as { toolUseId: string }).toolUseId)
|
|
223
|
+
);
|
|
224
|
+
if (answersTask) answers.set(row.id, message);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const history: UnifiedMessage[] = [];
|
|
228
|
+
for (const row of branch) {
|
|
229
|
+
const message = calls.get(row.id) ?? answers.get(row.id);
|
|
230
|
+
if (message) history.push(message);
|
|
231
|
+
}
|
|
232
|
+
return history;
|
|
233
|
+
}
|