@athenaintel/react 0.22.3 → 0.23.0
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 +394 -4
- package/dist/chat/AthenaChat.cjs +389 -240
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.d.ts +26 -8
- package/dist/chat/AthenaChat.js +394 -245
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/StatewireApprovalCard.cjs +2 -1
- package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
- package/dist/chat/StatewireApprovalCard.js +2 -1
- package/dist/chat/StatewireApprovalCard.js.map +1 -1
- package/dist/chat/StatewireClientToolBridge.cjs +1 -0
- package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
- package/dist/chat/StatewireClientToolBridge.js +1 -0
- package/dist/chat/StatewireClientToolBridge.js.map +1 -1
- package/dist/chat/StatewireQueuedMessages.cjs +1 -0
- package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
- package/dist/chat/StatewireQueuedMessages.js +1 -0
- package/dist/chat/StatewireQueuedMessages.js.map +1 -1
- package/dist/chat/WaitingOnYouBanner.cjs +100 -0
- package/dist/chat/WaitingOnYouBanner.cjs.map +1 -0
- package/dist/chat/WaitingOnYouBanner.d.ts +29 -0
- package/dist/chat/WaitingOnYouBanner.js +100 -0
- package/dist/chat/WaitingOnYouBanner.js.map +1 -0
- package/dist/chat/athena-chat-welcome.cjs +148 -0
- package/dist/chat/athena-chat-welcome.cjs.map +1 -0
- package/dist/chat/athena-chat-welcome.d.ts +54 -0
- package/dist/chat/athena-chat-welcome.js +148 -0
- package/dist/chat/athena-chat-welcome.js.map +1 -0
- package/dist/chat/athena-composer-controls.cjs +76 -0
- package/dist/chat/athena-composer-controls.cjs.map +1 -0
- package/dist/chat/athena-composer-controls.d.ts +21 -0
- package/dist/chat/athena-composer-controls.js +76 -0
- package/dist/chat/athena-composer-controls.js.map +1 -0
- package/dist/chat/composer-keyboard-hint.cjs +61 -0
- package/dist/chat/composer-keyboard-hint.cjs.map +1 -0
- package/dist/chat/composer-keyboard-hint.d.ts +33 -0
- package/dist/chat/composer-keyboard-hint.js +61 -0
- package/dist/chat/composer-keyboard-hint.js.map +1 -0
- package/dist/chat/message-time.cjs +64 -0
- package/dist/chat/message-time.cjs.map +1 -0
- package/dist/chat/message-time.d.ts +45 -0
- package/dist/chat/message-time.js +64 -0
- package/dist/chat/message-time.js.map +1 -0
- package/dist/chat/run-activity.cjs +38 -7
- package/dist/chat/run-activity.cjs.map +1 -1
- package/dist/chat/run-activity.d.ts +14 -3
- package/dist/chat/run-activity.js +39 -8
- package/dist/chat/run-activity.js.map +1 -1
- package/dist/chat/statewire-client-tools.cjs +2 -1
- package/dist/chat/statewire-client-tools.cjs.map +1 -1
- package/dist/chat/statewire-client-tools.js +2 -1
- package/dist/chat/statewire-client-tools.js.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.cjs +2 -1
- package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.js +2 -1
- package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
- package/dist/chat/thread-scroll-to-bottom.cjs +24 -0
- package/dist/chat/thread-scroll-to-bottom.cjs.map +1 -0
- package/dist/chat/thread-scroll-to-bottom.d.ts +11 -0
- package/dist/chat/thread-scroll-to-bottom.js +24 -0
- package/dist/chat/thread-scroll-to-bottom.js.map +1 -0
- package/dist/chat/tiptap-text.cjs +26 -99
- package/dist/chat/tiptap-text.cjs.map +1 -1
- package/dist/chat/tiptap-text.d.ts +13 -0
- package/dist/chat/tiptap-text.js +26 -99
- package/dist/chat/tiptap-text.js.map +1 -1
- package/dist/chat/use-athena-run-live.cjs +2 -1
- package/dist/chat/use-athena-run-live.cjs.map +1 -1
- package/dist/chat/use-athena-run-live.js +2 -1
- package/dist/chat/use-athena-run-live.js.map +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +1 -0
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.js +1 -0
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.cjs +39 -4
- package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.d.ts +21 -0
- package/dist/chat-ui/composer/tiptap-composer.js +39 -4
- package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
- package/dist/chat-ui/index.cjs +15 -1
- package/dist/chat-ui/index.cjs.map +1 -1
- package/dist/chat-ui/index.d.ts +6 -3
- package/dist/chat-ui/index.js +16 -2
- package/dist/chat-ui/index.js.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.cjs +31 -4
- package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.js +31 -4
- package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
- package/dist/chat-ui/messages/message-components.cjs +19 -1
- package/dist/chat-ui/messages/message-components.cjs.map +1 -1
- package/dist/chat-ui/messages/message-components.d.ts +13 -0
- package/dist/chat-ui/messages/message-components.js +19 -1
- package/dist/chat-ui/messages/message-components.js.map +1 -1
- package/dist/chat-ui/messages/runtime-message.cjs +2 -1
- package/dist/chat-ui/messages/runtime-message.cjs.map +1 -1
- package/dist/chat-ui/messages/runtime-message.js +2 -1
- package/dist/chat-ui/messages/runtime-message.js.map +1 -1
- package/dist/chat-ui/messages/statewire-continue-run.cjs +1 -0
- package/dist/chat-ui/messages/statewire-continue-run.cjs.map +1 -1
- package/dist/chat-ui/messages/statewire-continue-run.js +1 -0
- package/dist/chat-ui/messages/statewire-continue-run.js.map +1 -1
- package/dist/chat-ui/messages/user-edit-composer.cjs +3 -1
- package/dist/chat-ui/messages/user-edit-composer.cjs.map +1 -1
- package/dist/chat-ui/messages/user-edit-composer.js +3 -1
- package/dist/chat-ui/messages/user-edit-composer.js.map +1 -1
- package/dist/chat-ui/messages/wake-marker.cjs +84 -0
- package/dist/chat-ui/messages/wake-marker.cjs.map +1 -0
- package/dist/chat-ui/messages/wake-marker.d.ts +16 -0
- package/dist/chat-ui/messages/wake-marker.js +84 -0
- package/dist/chat-ui/messages/wake-marker.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-blocks.cjs +177 -0
- package/dist/chat-ui/rich-text/chat-blocks.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-blocks.d.ts +58 -0
- package/dist/chat-ui/rich-text/chat-blocks.js +177 -0
- package/dist/chat-ui/rich-text/chat-blocks.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-link.cjs +69 -0
- package/dist/chat-ui/rich-text/chat-link.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-link.d.ts +24 -0
- package/dist/chat-ui/rich-text/chat-link.js +69 -0
- package/dist/chat-ui/rich-text/chat-link.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-message-body.cjs +144 -18
- package/dist/chat-ui/rich-text/chat-message-body.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-message-body.d.ts +10 -1
- package/dist/chat-ui/rich-text/chat-message-body.js +149 -23
- package/dist/chat-ui/rich-text/chat-message-body.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-node-views.cjs +84 -4
- package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-node-views.d.ts +12 -1
- package/dist/chat-ui/rich-text/chat-node-views.js +85 -5
- package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.cjs +21 -3
- package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.d.ts +17 -2
- package/dist/chat-ui/rich-text/chat-text-schema.js +21 -3
- package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -1
- package/dist/chat-ui/rich-text/citation-anchors.cjs +139 -0
- package/dist/chat-ui/rich-text/citation-anchors.cjs.map +1 -0
- package/dist/chat-ui/rich-text/citation-anchors.d.ts +74 -0
- package/dist/chat-ui/rich-text/citation-anchors.js +139 -0
- package/dist/chat-ui/rich-text/citation-anchors.js.map +1 -0
- package/dist/chat-ui/statewire.cjs +8 -1
- package/dist/chat-ui/statewire.cjs.map +1 -1
- package/dist/chat-ui/statewire.d.ts +2 -0
- package/dist/chat-ui/statewire.js +8 -1
- package/dist/chat-ui/statewire.js.map +1 -1
- package/dist/chat-ui/thread/chat-composer-dock.cjs +27 -6
- package/dist/chat-ui/thread/chat-composer-dock.cjs.map +1 -1
- package/dist/chat-ui/thread/chat-composer-dock.d.ts +21 -1
- package/dist/chat-ui/thread/chat-composer-dock.js +28 -7
- package/dist/chat-ui/thread/chat-composer-dock.js.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.cjs +12 -13
- package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.d.ts +11 -10
- package/dist/chat-ui/thread/statewire-history-edge.js +13 -14
- package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
- package/dist/chat-ui/thread/thread-loading-overlay.cjs +31 -0
- package/dist/chat-ui/thread/thread-loading-overlay.cjs.map +1 -0
- package/dist/chat-ui/thread/thread-loading-overlay.d.ts +14 -0
- package/dist/chat-ui/thread/thread-loading-overlay.js +31 -0
- package/dist/chat-ui/thread/thread-loading-overlay.js.map +1 -0
- package/dist/composer/ComposerDropZone.cjs +8 -1
- package/dist/composer/ComposerDropZone.cjs.map +1 -1
- package/dist/composer/ComposerDropZone.d.ts +6 -0
- package/dist/composer/ComposerDropZone.js +9 -2
- package/dist/composer/ComposerDropZone.js.map +1 -1
- package/dist/diagnostics/errors.cjs +20 -0
- package/dist/diagnostics/errors.cjs.map +1 -1
- package/dist/diagnostics/errors.d.ts +20 -0
- package/dist/diagnostics/errors.js +20 -0
- package/dist/diagnostics/errors.js.map +1 -1
- package/dist/index.cjs +47 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +26 -7
- package/dist/index.js +51 -5
- package/dist/index.js.map +1 -1
- package/dist/lib/use-prefers-reduced-motion.cjs +29 -0
- package/dist/lib/use-prefers-reduced-motion.cjs.map +1 -0
- package/dist/lib/use-prefers-reduced-motion.d.ts +6 -0
- package/dist/lib/use-prefers-reduced-motion.js +29 -0
- package/dist/lib/use-prefers-reduced-motion.js.map +1 -0
- package/dist/packages/agent-runtime/src/conversation-index.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-index.js.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.cjs +59 -0
- package/dist/packages/agent-runtime/src/conversation-list.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.js +60 -1
- package/dist/packages/agent-runtime/src/conversation-list.js.map +1 -1
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.cjs +5 -3
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.js +5 -3
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
- package/dist/packages/agent-runtime/src/edit-command.cjs +21 -17
- package/dist/packages/agent-runtime/src/edit-command.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/edit-command.js +22 -18
- package/dist/packages/agent-runtime/src/edit-command.js.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +9 -11
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +9 -11
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/packages/agent-runtime/src/github-wake-event.cjs +86 -0
- package/dist/packages/agent-runtime/src/github-wake-event.cjs.map +1 -0
- package/dist/packages/agent-runtime/src/github-wake-event.js +86 -0
- package/dist/packages/agent-runtime/src/github-wake-event.js.map +1 -0
- package/dist/packages/agent-runtime/src/message-window.cjs +150 -42
- package/dist/packages/agent-runtime/src/message-window.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/message-window.js +151 -43
- package/dist/packages/agent-runtime/src/message-window.js.map +1 -1
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs +13 -9
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js +13 -9
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
- package/dist/packages/agent-runtime/src/statewire-suspended.cjs +1 -3
- package/dist/packages/agent-runtime/src/statewire-suspended.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/statewire-suspended.js +1 -3
- package/dist/packages/agent-runtime/src/statewire-suspended.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs +61 -30
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.js +59 -28
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.cjs +56 -36
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.js +59 -39
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
- package/dist/packages/react/package.json.cjs +1 -1
- package/dist/packages/react/package.json.js +1 -1
- package/dist/provider/AthenaContext.cjs.map +1 -1
- package/dist/provider/AthenaContext.d.ts +3 -0
- package/dist/provider/AthenaContext.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +93 -45
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +6 -1
- package/dist/provider/AthenaProvider.js +97 -49
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/runtime/statewire-lifecycle.cjs +2 -1
- package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
- package/dist/runtime/statewire-lifecycle.js +2 -1
- package/dist/runtime/statewire-lifecycle.js.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.cjs +3 -2
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.d.ts +8 -12
- package/dist/runtime/useAthenaStatewireRuntime.js +3 -2
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/search/useAthenaRepoSearch.cjs +94 -0
- package/dist/search/useAthenaRepoSearch.cjs.map +1 -0
- package/dist/search/useAthenaRepoSearch.d.ts +95 -0
- package/dist/search/useAthenaRepoSearch.js +94 -0
- package/dist/search/useAthenaRepoSearch.js.map +1 -0
- package/dist/styles.css +1 -1
- package/dist/threads/SessionList.cjs +486 -0
- package/dist/threads/SessionList.cjs.map +1 -0
- package/dist/threads/SessionList.d.ts +60 -0
- package/dist/threads/SessionList.js +486 -0
- package/dist/threads/SessionList.js.map +1 -0
- package/dist/threads/api.cjs +112 -4
- package/dist/threads/api.cjs.map +1 -1
- package/dist/threads/api.d.ts +128 -1
- package/dist/threads/api.js +113 -5
- package/dist/threads/api.js.map +1 -1
- package/dist/threads/conversation-list-fetcher.cjs +27 -3
- package/dist/threads/conversation-list-fetcher.cjs.map +1 -1
- package/dist/threads/conversation-list-fetcher.d.ts +16 -3
- package/dist/threads/conversation-list-fetcher.js +27 -3
- package/dist/threads/conversation-list-fetcher.js.map +1 -1
- package/dist/threads/index.d.ts +5 -1
- package/dist/threads/session-list-model.cjs +130 -0
- package/dist/threads/session-list-model.cjs.map +1 -0
- package/dist/threads/session-list-model.d.ts +62 -0
- package/dist/threads/session-list-model.js +130 -0
- package/dist/threads/session-list-model.js.map +1 -0
- package/dist/threads/statewire-thread-list.cjs +220 -38
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.d.ts +152 -2
- package/dist/threads/statewire-thread-list.js +222 -40
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/threads/thread-prefetcher.cjs +63 -0
- package/dist/threads/thread-prefetcher.cjs.map +1 -0
- package/dist/threads/thread-prefetcher.d.ts +54 -0
- package/dist/threads/thread-prefetcher.js +63 -0
- package/dist/threads/thread-prefetcher.js.map +1 -0
- package/dist/threads/use-athena-session-attention.cjs +22 -0
- package/dist/threads/use-athena-session-attention.cjs.map +1 -0
- package/dist/threads/use-athena-session-attention.d.ts +24 -0
- package/dist/threads/use-athena-session-attention.js +22 -0
- package/dist/threads/use-athena-session-attention.js.map +1 -0
- package/dist/threads/use-rest-conversation-history.cjs +25 -2
- package/dist/threads/use-rest-conversation-history.cjs.map +1 -1
- package/dist/threads/use-rest-conversation-history.d.ts +8 -1
- package/dist/threads/use-rest-conversation-history.js +25 -2
- package/dist/threads/use-rest-conversation-history.js.map +1 -1
- package/dist/threads/use-statewire-conversation-history.cjs +40 -16
- package/dist/threads/use-statewire-conversation-history.cjs.map +1 -1
- package/dist/threads/use-statewire-conversation-history.d.ts +13 -0
- package/dist/threads/use-statewire-conversation-history.js +40 -16
- package/dist/threads/use-statewire-conversation-history.js.map +1 -1
- package/dist/threads/use-thread-archive.cjs +128 -0
- package/dist/threads/use-thread-archive.cjs.map +1 -0
- package/dist/threads/use-thread-archive.d.ts +26 -0
- package/dist/threads/use-thread-archive.js +128 -0
- package/dist/threads/use-thread-archive.js.map +1 -0
- package/dist/threads/use-thread-favorite.cjs +53 -0
- package/dist/threads/use-thread-favorite.cjs.map +1 -0
- package/dist/threads/use-thread-favorite.d.ts +49 -0
- package/dist/threads/use-thread-favorite.js +53 -0
- package/dist/threads/use-thread-favorite.js.map +1 -0
- package/dist/threads/use-thread-field-override.cjs +184 -0
- package/dist/threads/use-thread-field-override.cjs.map +1 -0
- package/dist/threads/use-thread-field-override.d.ts +55 -0
- package/dist/threads/use-thread-field-override.js +184 -0
- package/dist/threads/use-thread-field-override.js.map +1 -0
- package/dist/threads/use-thread-rename.cjs +53 -0
- package/dist/threads/use-thread-rename.cjs.map +1 -0
- package/dist/threads/use-thread-rename.d.ts +48 -0
- package/dist/threads/use-thread-rename.js +53 -0
- package/dist/threads/use-thread-rename.js.map +1 -0
- package/dist/tools/index.cjs +5 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +7 -3
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/misc-tool-uis.cjs +2 -1
- package/dist/tools/misc-tool-uis.cjs.map +1 -1
- package/dist/tools/misc-tool-uis.js +2 -1
- package/dist/tools/misc-tool-uis.js.map +1 -1
- package/dist/tools/primitives.cjs +25 -2
- package/dist/tools/primitives.cjs.map +1 -1
- package/dist/tools/primitives.d.ts +9 -2
- package/dist/tools/primitives.js +26 -3
- package/dist/tools/primitives.js.map +1 -1
- package/dist/tools/tool-appearance.cjs +11 -0
- package/dist/tools/tool-appearance.cjs.map +1 -0
- package/dist/tools/tool-appearance.d.ts +29 -0
- package/dist/tools/tool-appearance.js +11 -0
- package/dist/tools/tool-appearance.js.map +1 -0
- package/dist/tools/tool-fallback.cjs +211 -13
- package/dist/tools/tool-fallback.cjs.map +1 -1
- package/dist/tools/tool-fallback.d.ts +31 -4
- package/dist/tools/tool-fallback.js +214 -16
- package/dist/tools/tool-fallback.js.map +1 -1
- package/dist/tools/use-elapsed-seconds.cjs +24 -0
- package/dist/tools/use-elapsed-seconds.cjs.map +1 -0
- package/dist/tools/use-elapsed-seconds.d.ts +10 -0
- package/dist/tools/use-elapsed-seconds.js +24 -0
- package/dist/tools/use-elapsed-seconds.js.map +1 -0
- package/dist/tools/voice-update-tool-ui.cjs +2 -1
- package/dist/tools/voice-update-tool-ui.cjs.map +1 -1
- package/dist/tools/voice-update-tool-ui.js +2 -1
- package/dist/tools/voice-update-tool-ui.js.map +1 -1
- package/package.json +1 -1
- package/src/chat-ui/tailwind-preset.js +14 -1
|
@@ -1,29 +1,35 @@
|
|
|
1
1
|
import { jsx } from "react/jsx-runtime";
|
|
2
2
|
import "../packages/agent-runtime/src/generated/runconfig-contract.js";
|
|
3
|
-
import { useContext, createContext, useState, useRef,
|
|
3
|
+
import { useContext, createContext, useState, useRef, useCallback, useMemo, useEffect } from "react";
|
|
4
4
|
import { useConversationIndex, conversationIndexUrlFromStatewireUrl } from "../packages/agent-runtime/src/conversation-index.js";
|
|
5
|
+
import { deriveConversationAttention, summaryFromConversationIndexEntry } from "../packages/agent-runtime/src/conversation-list.js";
|
|
5
6
|
import { useConversationList } from "../packages/agent-runtime/src/use-conversation-list.js";
|
|
6
7
|
import "../packages/agent-runtime/src/statewire-state.js";
|
|
7
8
|
import "../packages/agent-runtime/src/messages.js";
|
|
8
|
-
import "
|
|
9
|
+
import "statewire";
|
|
9
10
|
import "@assistant-ui/store";
|
|
10
11
|
import "../packages/agent-runtime/src/quota-safe-local-storage-session.js";
|
|
11
12
|
import "../packages/agent-runtime/src/statewire-suspended.js";
|
|
12
13
|
import "@assistant-ui/tap";
|
|
13
14
|
import "../packages/agent-runtime/src/statewire-attach-observer.js";
|
|
14
|
-
import "statewire";
|
|
15
15
|
import "../packages/agent-runtime/src/thread-status.js";
|
|
16
|
+
import "@assistant-ui/react-statewire";
|
|
16
17
|
import "@assistant-ui/core";
|
|
17
18
|
import "../packages/agent-runtime/src/thread-handoff.js";
|
|
18
19
|
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
|
|
19
20
|
import { useAuiState } from "@assistant-ui/react";
|
|
20
21
|
import { AthenaAuthContext } from "../auth/AthenaAuthContext.js";
|
|
21
22
|
import { resolveStatewireAuthToken, resolveStatewireAuthHeaders } from "../runtime/statewire-auth-headers.js";
|
|
22
|
-
import { fetchAccountIdentity } from "./api.js";
|
|
23
|
+
import { fetchAccountIdentity, getThreadState } from "./api.js";
|
|
23
24
|
import { createRestConversationListFetcher } from "./conversation-list-fetcher.js";
|
|
24
25
|
import { credentialShape, sameCredentialShape } from "./credential-shape.js";
|
|
25
26
|
import { mintThreadId } from "./mint-thread-id.js";
|
|
27
|
+
import { useAthenaStatewireThreadId } from "./thread-id-context.js";
|
|
28
|
+
import { createThreadPrefetcher } from "./thread-prefetcher.js";
|
|
26
29
|
import { normalizeThreadTitle, isSerializedContentPartsTitle } from "./title.js";
|
|
30
|
+
import { useThreadArchive } from "./use-thread-archive.js";
|
|
31
|
+
import { useThreadFavorite, withFavoriteOverrides, withFavoriteOverride } from "./use-thread-favorite.js";
|
|
32
|
+
import { useThreadRename, withTitleOverrides, withTitleOverride } from "./use-thread-rename.js";
|
|
27
33
|
const AthenaStatewireThreadListContext = createContext(null);
|
|
28
34
|
function useAthenaStatewireThreadList() {
|
|
29
35
|
return useContext(AthenaStatewireThreadListContext);
|
|
@@ -32,6 +38,25 @@ function useRefreshThreadList() {
|
|
|
32
38
|
var _a;
|
|
33
39
|
return ((_a = useAthenaStatewireThreadList()) == null ? void 0 : _a.refresh) ?? null;
|
|
34
40
|
}
|
|
41
|
+
function threadSummaryFromConversation(conversation) {
|
|
42
|
+
return {
|
|
43
|
+
id: conversation.threadId,
|
|
44
|
+
title: normalizeThreadTitle(conversation.title) ?? null,
|
|
45
|
+
attention: deriveConversationAttention(conversation),
|
|
46
|
+
nextAction: conversation.nextAction ?? null,
|
|
47
|
+
attentionSource: conversation.attentionSource ?? null,
|
|
48
|
+
isFavorited: conversation.isFavorited ?? false,
|
|
49
|
+
isUnread: conversation.isUnread,
|
|
50
|
+
sessionStatus: conversation.sessionStatus,
|
|
51
|
+
runStatus: conversation.runStatus,
|
|
52
|
+
startChannel: conversation.sourceChannel,
|
|
53
|
+
appId: conversation.appId,
|
|
54
|
+
triggerType: conversation.triggerType,
|
|
55
|
+
pullRequests: conversation.pullRequests ?? null,
|
|
56
|
+
lastWake: conversation.lastWake ?? null,
|
|
57
|
+
updatedAt: conversation.updatedAt
|
|
58
|
+
};
|
|
59
|
+
}
|
|
35
60
|
const THREAD_LIST_PAGE_SIZE = 50;
|
|
36
61
|
function StatewireThreadListState({
|
|
37
62
|
backendUrl,
|
|
@@ -41,12 +66,15 @@ function StatewireThreadListState({
|
|
|
41
66
|
getToken,
|
|
42
67
|
appId,
|
|
43
68
|
initialThreadId,
|
|
69
|
+
includePullRequests,
|
|
70
|
+
snapshotCache,
|
|
44
71
|
children
|
|
45
72
|
}) {
|
|
46
73
|
var _a, _b, _c;
|
|
47
74
|
const [active, setActive] = useState(
|
|
48
75
|
() => initialThreadId ? { id: initialThreadId, isNew: false } : { id: mintThreadId(), isNew: true }
|
|
49
76
|
);
|
|
77
|
+
const [search, setSearch] = useState("");
|
|
50
78
|
const tokenRef = useRef(token);
|
|
51
79
|
tokenRef.current = token;
|
|
52
80
|
const apiKeyRef = useRef(apiKey);
|
|
@@ -56,30 +84,35 @@ function StatewireThreadListState({
|
|
|
56
84
|
const authContext = useContext(AthenaAuthContext);
|
|
57
85
|
const principal = ((_a = authContext == null ? void 0 : authContext.user) == null ? void 0 : _a.userId) ?? "";
|
|
58
86
|
const hasAuth = !!(apiKey || token || getToken);
|
|
59
|
-
const
|
|
60
|
-
() =>
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
token: await resolveStatewireAuthToken(
|
|
67
|
-
{ apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },
|
|
68
|
-
{ staleAuth: false }
|
|
69
|
-
)
|
|
70
|
-
})
|
|
87
|
+
const getAuth = useCallback(
|
|
88
|
+
async () => ({
|
|
89
|
+
apiKey: apiKeyRef.current,
|
|
90
|
+
token: await resolveStatewireAuthToken(
|
|
91
|
+
{ apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },
|
|
92
|
+
{ staleAuth: false }
|
|
93
|
+
)
|
|
71
94
|
}),
|
|
72
|
-
[
|
|
95
|
+
[]
|
|
73
96
|
);
|
|
97
|
+
const fetchPage = useMemo(
|
|
98
|
+
() => createRestConversationListFetcher({ backendUrl, includePullRequests, getAuth }),
|
|
99
|
+
[backendUrl, includePullRequests, getAuth]
|
|
100
|
+
);
|
|
101
|
+
const trimmedSearch = search.trim();
|
|
74
102
|
const filter = useMemo(
|
|
75
|
-
() =>
|
|
76
|
-
|
|
103
|
+
() => ({
|
|
104
|
+
...appId ? { appId } : {},
|
|
105
|
+
...trimmedSearch ? { search: trimmedSearch } : {}
|
|
106
|
+
}),
|
|
107
|
+
[appId, trimmedSearch]
|
|
77
108
|
);
|
|
78
109
|
const list = useConversationList({
|
|
79
110
|
fetchPage,
|
|
80
111
|
filter,
|
|
81
112
|
pageSize: THREAD_LIST_PAGE_SIZE,
|
|
82
|
-
|
|
113
|
+
// Pull-request opt-in changes what a cached row holds, so it is part of
|
|
114
|
+
// the cache identity.
|
|
115
|
+
scopeKey: `${backendUrl}::${principal}::${hasAuth ? "auth" : "anon"}::${includePullRequests ? "prs" : "no-prs"}`,
|
|
83
116
|
enabled: hasAuth
|
|
84
117
|
});
|
|
85
118
|
const indexHeaders = useCallback(
|
|
@@ -126,25 +159,94 @@ function StatewireThreadListState({
|
|
|
126
159
|
headers: indexHeaders,
|
|
127
160
|
enabled: indexEnabled
|
|
128
161
|
});
|
|
129
|
-
const
|
|
130
|
-
const
|
|
131
|
-
for (const entry of index.entries ?? [])
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
return titles;
|
|
162
|
+
const indexByThread = useMemo(() => {
|
|
163
|
+
const entries = /* @__PURE__ */ new Map();
|
|
164
|
+
for (const entry of index.entries ?? []) entries.set(entry.thread_id, entry);
|
|
165
|
+
return entries;
|
|
135
166
|
}, [index.entries]);
|
|
167
|
+
const mergedConversations = useMemo(
|
|
168
|
+
() => list.conversations.map((conversation) => {
|
|
169
|
+
const entry = indexByThread.get(conversation.threadId);
|
|
170
|
+
if (!entry) return conversation;
|
|
171
|
+
const merged = summaryFromConversationIndexEntry(entry, conversation);
|
|
172
|
+
return normalizeThreadTitle(merged.title) === void 0 ? { ...merged, title: conversation.title } : merged;
|
|
173
|
+
}),
|
|
174
|
+
[list.conversations, indexByThread]
|
|
175
|
+
);
|
|
176
|
+
const listPatchConversation = list.patchConversation;
|
|
177
|
+
const favorite = useThreadFavorite({
|
|
178
|
+
backendUrl,
|
|
179
|
+
principalId: principal,
|
|
180
|
+
getAuth,
|
|
181
|
+
rows: mergedConversations,
|
|
182
|
+
onServerTruth: ({ threadId, isFavorited }) => listPatchConversation(threadId, { isFavorited })
|
|
183
|
+
});
|
|
184
|
+
const favoriteOverrides = favorite.overrides;
|
|
185
|
+
const rename = useThreadRename({
|
|
186
|
+
backendUrl,
|
|
187
|
+
principalId: principal,
|
|
188
|
+
getAuth,
|
|
189
|
+
rows: mergedConversations,
|
|
190
|
+
onServerTruth: ({ threadId, title }) => listPatchConversation(threadId, { title })
|
|
191
|
+
});
|
|
192
|
+
const titleOverrides = rename.overrides;
|
|
193
|
+
const listRemoveConversation = list.removeConversation;
|
|
194
|
+
const archive = useThreadArchive({
|
|
195
|
+
backendUrl,
|
|
196
|
+
principalId: principal,
|
|
197
|
+
getAuth,
|
|
198
|
+
onArchived: (threadId) => {
|
|
199
|
+
listRemoveConversation(threadId);
|
|
200
|
+
setActive(
|
|
201
|
+
(current) => current.id === threadId ? { id: mintThreadId(), isNew: true } : current
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
const hiddenThreadIds = archive.hiddenThreadIds;
|
|
206
|
+
const archiveRelease = archive.release;
|
|
207
|
+
useEffect(() => {
|
|
208
|
+
if (hiddenThreadIds.size === 0) return;
|
|
209
|
+
const forgotten = [...hiddenThreadIds].filter(
|
|
210
|
+
(threadId) => !mergedConversations.some((conversation) => conversation.threadId === threadId) && !indexByThread.has(threadId)
|
|
211
|
+
);
|
|
212
|
+
if (forgotten.length > 0) archiveRelease(forgotten);
|
|
213
|
+
}, [hiddenThreadIds, mergedConversations, indexByThread, archiveRelease]);
|
|
136
214
|
const data = useMemo(
|
|
137
|
-
() =>
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
[
|
|
215
|
+
() => withTitleOverrides(
|
|
216
|
+
withFavoriteOverrides(mergedConversations, favoriteOverrides),
|
|
217
|
+
titleOverrides
|
|
218
|
+
).filter((conversation) => !hiddenThreadIds.has(conversation.threadId)).map(threadSummaryFromConversation),
|
|
219
|
+
[mergedConversations, favoriteOverrides, titleOverrides, hiddenThreadIds]
|
|
142
220
|
);
|
|
143
221
|
const isLoading = list.isLoading;
|
|
222
|
+
const lastActiveConversationRef = useRef(null);
|
|
223
|
+
const activeConversation = useMemo(() => {
|
|
224
|
+
var _a2;
|
|
225
|
+
const listed = mergedConversations.find((conversation) => conversation.threadId === active.id);
|
|
226
|
+
if (listed) return listed;
|
|
227
|
+
const remembered = ((_a2 = lastActiveConversationRef.current) == null ? void 0 : _a2.threadId) === active.id ? lastActiveConversationRef.current : void 0;
|
|
228
|
+
const entry = indexByThread.get(active.id);
|
|
229
|
+
if (entry) return summaryFromConversationIndexEntry(entry, remembered);
|
|
230
|
+
return remembered ?? null;
|
|
231
|
+
}, [mergedConversations, indexByThread, active.id]);
|
|
232
|
+
if (activeConversation !== null) lastActiveConversationRef.current = activeConversation;
|
|
233
|
+
const activeThread = useMemo(
|
|
234
|
+
() => activeConversation ? threadSummaryFromConversation(
|
|
235
|
+
withTitleOverride(
|
|
236
|
+
withFavoriteOverride(activeConversation, favoriteOverrides),
|
|
237
|
+
titleOverrides
|
|
238
|
+
)
|
|
239
|
+
) : null,
|
|
240
|
+
[activeConversation, favoriteOverrides, titleOverrides]
|
|
241
|
+
);
|
|
144
242
|
const listRefresh = list.refresh;
|
|
145
243
|
const refresh = useCallback(() => {
|
|
146
244
|
void listRefresh();
|
|
147
245
|
}, [listRefresh]);
|
|
246
|
+
const listFetchNextPage = list.fetchNextPage;
|
|
247
|
+
const fetchNextPage = useCallback(() => {
|
|
248
|
+
void listFetchNextPage();
|
|
249
|
+
}, [listFetchNextPage]);
|
|
148
250
|
const refreshedForRef = useRef(/* @__PURE__ */ new Set());
|
|
149
251
|
useEffect(() => {
|
|
150
252
|
if (index.entries === null) return;
|
|
@@ -164,10 +266,31 @@ function StatewireThreadListState({
|
|
|
164
266
|
(current) => current.id === threadId ? current : { id: threadId, isNew: false }
|
|
165
267
|
);
|
|
166
268
|
}, []);
|
|
269
|
+
const prefetchScope = `${backendUrl}::${principal}::${credentialGeneration}`;
|
|
270
|
+
const prefetchScopeRef = useRef(prefetchScope);
|
|
271
|
+
prefetchScopeRef.current = prefetchScope;
|
|
272
|
+
const prefetcher = useMemo(() => {
|
|
273
|
+
if (!snapshotCache) return null;
|
|
274
|
+
const scope = prefetchScope;
|
|
275
|
+
return createThreadPrefetcher({
|
|
276
|
+
cache: snapshotCache,
|
|
277
|
+
fetchState: async (threadId) => getThreadState(backendUrl, await getAuth(), threadId, { skipCache: false }),
|
|
278
|
+
isCurrent: () => prefetchScopeRef.current === scope
|
|
279
|
+
});
|
|
280
|
+
}, [snapshotCache, prefetchScope, backendUrl, getAuth]);
|
|
281
|
+
const activeIdRef = useRef(active.id);
|
|
282
|
+
activeIdRef.current = active.id;
|
|
283
|
+
const prefetchThread = useCallback(
|
|
284
|
+
(threadId) => {
|
|
285
|
+
if (!prefetcher || !threadId || threadId === activeIdRef.current) return;
|
|
286
|
+
prefetcher.prefetch(threadId);
|
|
287
|
+
},
|
|
288
|
+
[prefetcher]
|
|
289
|
+
);
|
|
167
290
|
const newThread = useCallback(() => {
|
|
168
291
|
setActive({ id: mintThreadId(), isNew: true });
|
|
169
292
|
}, []);
|
|
170
|
-
const isPersisted = data.some((thread) => thread.id === active.id);
|
|
293
|
+
const isPersisted = data.some((thread) => thread.id === active.id) || indexByThread.has(active.id);
|
|
171
294
|
useEffect(() => {
|
|
172
295
|
if (isPersisted) {
|
|
173
296
|
setActive((current) => current.isNew ? { ...current, isNew: false } : current);
|
|
@@ -178,14 +301,62 @@ function StatewireThreadListState({
|
|
|
178
301
|
() => ({
|
|
179
302
|
threads: data,
|
|
180
303
|
isLoading,
|
|
304
|
+
isFetching: list.isFetching,
|
|
305
|
+
hasResolvedFirstPage: list.hasResolvedFirstPage,
|
|
181
306
|
activeThreadId: active.id,
|
|
307
|
+
activeThread,
|
|
182
308
|
isNewChat: active.isNew,
|
|
183
309
|
selectThread,
|
|
310
|
+
prefetchThread,
|
|
184
311
|
newThread,
|
|
185
312
|
refresh,
|
|
313
|
+
search,
|
|
314
|
+
setSearch,
|
|
315
|
+
hasNextPage: list.hasNextPage,
|
|
316
|
+
isFetchingNextPage: list.isFetchingNextPage,
|
|
317
|
+
fetchNextPage,
|
|
318
|
+
setFavorited: favorite.setFavorited,
|
|
319
|
+
favoritePending: favorite.isPending,
|
|
320
|
+
favoritePendingThreadIds: favorite.pendingThreadIds,
|
|
321
|
+
favoriteToggleAvailable: favorite.isAvailable,
|
|
322
|
+
renameThread: rename.rename,
|
|
323
|
+
renamePendingThreadIds: rename.pendingThreadIds,
|
|
324
|
+
renameAvailable: rename.isAvailable,
|
|
325
|
+
archiveThread: archive.archive,
|
|
326
|
+
archivePendingThreadIds: archive.pendingThreadIds,
|
|
327
|
+
archivePending: archive.isPending,
|
|
328
|
+
archiveAvailable: archive.isAvailable,
|
|
186
329
|
titleSource
|
|
187
330
|
}),
|
|
188
|
-
[
|
|
331
|
+
[
|
|
332
|
+
data,
|
|
333
|
+
isLoading,
|
|
334
|
+
list.isFetching,
|
|
335
|
+
list.hasResolvedFirstPage,
|
|
336
|
+
active.id,
|
|
337
|
+
activeThread,
|
|
338
|
+
active.isNew,
|
|
339
|
+
selectThread,
|
|
340
|
+
prefetchThread,
|
|
341
|
+
newThread,
|
|
342
|
+
refresh,
|
|
343
|
+
search,
|
|
344
|
+
list.hasNextPage,
|
|
345
|
+
list.isFetchingNextPage,
|
|
346
|
+
fetchNextPage,
|
|
347
|
+
favorite.setFavorited,
|
|
348
|
+
favorite.isPending,
|
|
349
|
+
favorite.pendingThreadIds,
|
|
350
|
+
favorite.isAvailable,
|
|
351
|
+
rename.rename,
|
|
352
|
+
rename.pendingThreadIds,
|
|
353
|
+
rename.isAvailable,
|
|
354
|
+
archive.archive,
|
|
355
|
+
archive.pendingThreadIds,
|
|
356
|
+
archive.isPending,
|
|
357
|
+
archive.isAvailable,
|
|
358
|
+
titleSource
|
|
359
|
+
]
|
|
189
360
|
);
|
|
190
361
|
return /* @__PURE__ */ jsx(AthenaStatewireThreadListContext.Provider, { value, children });
|
|
191
362
|
}
|
|
@@ -197,6 +368,8 @@ function AthenaStatewireThreadListProvider({
|
|
|
197
368
|
getToken,
|
|
198
369
|
appId,
|
|
199
370
|
initialThreadId,
|
|
371
|
+
includePullRequests = true,
|
|
372
|
+
snapshotCache,
|
|
200
373
|
children
|
|
201
374
|
}) {
|
|
202
375
|
const [queryClient] = useState(() => new QueryClient());
|
|
@@ -210,6 +383,8 @@ function AthenaStatewireThreadListProvider({
|
|
|
210
383
|
getToken,
|
|
211
384
|
appId,
|
|
212
385
|
initialThreadId,
|
|
386
|
+
includePullRequests,
|
|
387
|
+
snapshotCache,
|
|
213
388
|
children
|
|
214
389
|
}
|
|
215
390
|
) });
|
|
@@ -220,27 +395,32 @@ const TITLE_POLL_MAX_DURATION_MS = 6e4;
|
|
|
220
395
|
function StatewireThreadTitlePoller() {
|
|
221
396
|
var _a;
|
|
222
397
|
const list = useAthenaStatewireThreadList();
|
|
398
|
+
const activeThreadId = useAthenaStatewireThreadId();
|
|
223
399
|
const hasMessages = useAuiState((s) => {
|
|
224
400
|
var _a2;
|
|
225
401
|
return (((_a2 = s.optional.thread) == null ? void 0 : _a2.messages.length) ?? 0) > 0;
|
|
226
402
|
});
|
|
227
|
-
const activeThreadId = (list == null ? void 0 : list.activeThreadId) ?? null;
|
|
228
403
|
const titleSource = (list == null ? void 0 : list.titleSource) ?? "poll";
|
|
229
404
|
const entry = list == null ? void 0 : list.threads.find((thread) => thread.id === activeThreadId);
|
|
230
405
|
const title = ((_a = entry == null ? void 0 : entry.title) == null ? void 0 : _a.trim()) ?? "";
|
|
231
406
|
const hasTitle = title.length > 0 && !isSerializedContentPartsTitle(title);
|
|
232
|
-
const
|
|
407
|
+
const visitRef = useRef(null);
|
|
233
408
|
const refreshRef = useRef(list == null ? void 0 : list.refresh);
|
|
234
409
|
refreshRef.current = list == null ? void 0 : list.refresh;
|
|
235
410
|
useEffect(() => {
|
|
236
|
-
|
|
237
|
-
if (
|
|
238
|
-
|
|
411
|
+
var _a2;
|
|
412
|
+
if (((_a2 = visitRef.current) == null ? void 0 : _a2.threadId) !== activeThreadId) {
|
|
413
|
+
visitRef.current = { threadId: activeThreadId, polled: false };
|
|
414
|
+
}
|
|
415
|
+
const visit = visitRef.current;
|
|
416
|
+
if (!hasMessages || hasTitle || titleSource === "index") return;
|
|
417
|
+
if (visit.polled) return;
|
|
418
|
+
visit.polled = true;
|
|
239
419
|
let intervalId = null;
|
|
240
420
|
const startId = setTimeout(() => {
|
|
241
421
|
intervalId = setInterval(() => {
|
|
242
|
-
var
|
|
243
|
-
return (
|
|
422
|
+
var _a3;
|
|
423
|
+
return (_a3 = refreshRef.current) == null ? void 0 : _a3.call(refreshRef);
|
|
244
424
|
}, TITLE_POLL_INTERVAL_MS);
|
|
245
425
|
}, TITLE_POLL_DELAY_MS);
|
|
246
426
|
const stopId = setTimeout(() => {
|
|
@@ -258,6 +438,8 @@ export {
|
|
|
258
438
|
AthenaStatewireThreadListContext,
|
|
259
439
|
AthenaStatewireThreadListProvider,
|
|
260
440
|
StatewireThreadTitlePoller,
|
|
441
|
+
TITLE_POLL_DELAY_MS,
|
|
442
|
+
threadSummaryFromConversation,
|
|
261
443
|
useAthenaStatewireThreadList,
|
|
262
444
|
useRefreshThreadList
|
|
263
445
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"statewire-thread-list.js","sources":["../../src/threads/statewire-thread-list.tsx"],"sourcesContent":["import {\n type ConversationListFilter,\n conversationIndexUrlFromStatewireUrl,\n type DeepAgentHeadersResolver,\n useConversationIndex,\n useConversationList,\n} from '@athenaintel/agent-runtime';\nimport { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';\nimport { useAuiState } from '@assistant-ui/react';\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n resolveStatewireAuthToken,\n} from '../runtime/statewire-auth-headers';\nimport { fetchAccountIdentity } from './api';\nimport { createRestConversationListFetcher } from './conversation-list-fetcher';\nimport { credentialShape, sameCredentialShape } from './credential-shape';\nimport { mintThreadId } from './mint-thread-id';\nimport { isSerializedContentPartsTitle, normalizeThreadTitle } from './title';\n\nexport interface AthenaStatewireThreadSummary {\n id: string;\n title: string | null;\n}\n\n/**\n * Thread-list state. The list is the persisted Agora session list; the ACTIVE\n * thread is a plain id the statewire runtime attaches to — switching threads\n * remounts the statewire session against the new `…/v2/threads/{id}` URL\n * (the same model the mobile app uses).\n */\nexport interface AthenaStatewireThreadListState {\n threads: AthenaStatewireThreadSummary[];\n isLoading: boolean;\n activeThreadId: string;\n /** True while the active thread is a locally-minted chat with no server history. */\n isNewChat: boolean;\n selectThread: (threadId: string) => void;\n newThread: () => void;\n refresh: () => void;\n /**\n * Where titles come from. `'index'` once the signed-in user's live\n * conversation index has replicated — titles and newly created threads then\n * arrive as pushed updates; `'poll'` while it has not (no signed-in\n * principal, e.g. API-key mode, or before its snapshot), when a\n * freshly-started thread's title is picked up by the bounded REST poll.\n */\n titleSource: 'index' | 'poll';\n}\n\nexport const AthenaStatewireThreadListContext =\n createContext<AthenaStatewireThreadListState | null>(null);\n\n/** Read the statewire thread-list state, or null outside that mode. */\nexport function useAthenaStatewireThreadList(): AthenaStatewireThreadListState | null {\n return useContext(AthenaStatewireThreadListContext);\n}\n\n/** Trigger a re-fetch of the thread list. `null` outside `enableThreadList` mode. */\nexport function useRefreshThreadList(): (() => void) | null {\n return useAthenaStatewireThreadList()?.refresh ?? null;\n}\n\n/**\n * The statewire thread list reads one live page through the shared\n * conversation-list contract; the REST default page size predates the shared\n * pager and is preserved here.\n */\nconst THREAD_LIST_PAGE_SIZE = 50;\n\nfunction StatewireThreadListState({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n initialThreadId,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n initialThreadId?: string;\n children: ReactNode;\n}) {\n const [active, setActive] = useState<{ id: string; isNew: boolean }>(() =>\n initialThreadId\n ? { id: initialThreadId, isNew: false }\n : { id: mintThreadId(), isNew: true },\n );\n\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const apiKeyRef = useRef(apiKey);\n apiKeyRef.current = apiKey;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n // The cache must be keyed by WHO is asking. Keying on `backendUrl`/`appId`\n // alone let a token swap to a different user read the previous user's thread\n // titles out of the cache. The principal is a non-secret user id, so no\n // credential enters the key (or React Query's devtools). The shared pager\n // never serves placeholder rows across keys, so another principal's list is\n // never shown while the new one loads.\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n // A live token getter is a credential too: a `getToken`-only host\n // authenticates its chat, so its list must not stay empty.\n const hasAuth = !!(apiKey || token || getToken);\n\n const fetchPage = useMemo(\n () =>\n createRestConversationListFetcher({\n backendUrl,\n // Resolved per request with the attach's token semantics (getter first,\n // host-held token as the fallback) so a rotated token is never stale.\n getAuth: async () => ({\n apiKey: apiKeyRef.current,\n token: await resolveStatewireAuthToken(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n { staleAuth: false },\n ),\n }),\n }),\n [backendUrl],\n );\n const filter = useMemo<ConversationListFilter>(\n () => (appId ? { appId } : {}),\n [appId],\n );\n const list = useConversationList({\n fetchPage,\n filter,\n pageSize: THREAD_LIST_PAGE_SIZE,\n scopeKey: `${backendUrl}::${principal}::${hasAuth ? 'auth' : 'anon'}`,\n enabled: hasAuth,\n });\n\n // Live titles ride the signed-in user's conversation index — the same push\n // channel the conversation-history panel renders from: the host replicates\n // title, lifecycle, and creation changes as ops, so a freshly-started\n // thread's server-generated title lands without polling. The index is one\n // instance per `(workspace, user)` in agora's ids, so the pair is resolved\n // from the backend once a principal is known and the index only attaches\n // once both halves are; API-key-only hosts keep the bounded REST poll\n // (`titleSource: 'poll'`).\n const indexHeaders = useCallback<DeepAgentHeadersResolver>(\n (ctx) =>\n resolveStatewireAuthHeaders(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n ctx,\n ),\n [],\n );\n // The workspace half is the CREDENTIAL's: a scoped credential (sandbox,\n // preview, Office session) pins its own workspace, so swapping one for\n // another under the same principal must re-resolve the pair. The query is\n // therefore keyed by a credential generation — a counter that advances\n // whenever the host's credentials change — so no secret enters the key.\n const credentialsRef = useRef(credentialShape({ apiKey, token, getToken }));\n const credentialGenerationRef = useRef(0);\n const currentCredentials = credentialShape({ apiKey, token, getToken });\n if (!sameCredentialShape(credentialsRef.current, currentCredentials)) {\n credentialsRef.current = currentCredentials;\n credentialGenerationRef.current += 1;\n }\n const credentialGeneration = credentialGenerationRef.current;\n const identityEnabled = syncUrl !== undefined && principal.length > 0 && hasAuth;\n const identity = useQuery({\n // Keyed by the non-secret principal and credential generation, never the\n // credential itself.\n queryKey: ['athena-sdk', 'account-identity', backendUrl, principal, credentialGeneration],\n queryFn: async ({ signal }) =>\n fetchAccountIdentity(\n backendUrl,\n {\n apiKey: apiKeyRef.current,\n token: await resolveStatewireAuthToken(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n { staleAuth: false },\n ),\n },\n { signal },\n ),\n enabled: identityEnabled,\n staleTime: Number.POSITIVE_INFINITY,\n });\n const indexWorkspaceId = identity.data?.workspaceId ?? '';\n const indexUserId = identity.data?.userId ?? '';\n const indexEnabled = identityEnabled && indexWorkspaceId.length > 0 && indexUserId.length > 0;\n const index = useConversationIndex({\n baseUrl: syncUrl === undefined ? '' : conversationIndexUrlFromStatewireUrl(syncUrl),\n workspaceId: indexWorkspaceId || 'pending-workspace',\n userId: indexUserId || 'pending-user',\n headers: indexHeaders,\n enabled: indexEnabled,\n });\n const indexTitles = useMemo(() => {\n const titles = new Map<string, string | null>();\n for (const entry of index.entries ?? []) {\n titles.set(entry.thread_id, normalizeThreadTitle(entry.title) ?? null);\n }\n return titles;\n }, [index.entries]);\n\n const data = useMemo(\n () =>\n list.conversations.map((conversation) => ({\n id: conversation.threadId,\n title:\n indexTitles.get(conversation.threadId) ??\n normalizeThreadTitle(conversation.title) ??\n null,\n })),\n [list.conversations, indexTitles],\n );\n const isLoading = list.isLoading;\n\n const listRefresh = list.refresh;\n const refresh = useCallback(() => {\n void listRefresh();\n }, [listRefresh]);\n\n // A thread the index knows — created here on first send, or elsewhere —\n // that the REST page does not list yet: refresh once per such id so the row\n // appears without the user pressing refresh. Rows for other app ids belong\n // to other lists and never trigger one.\n const refreshedForRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n if (index.entries === null) return;\n const listed = new Set(list.conversations.map((conversation) => conversation.threadId));\n let pending = false;\n for (const entry of index.entries) {\n if (appId && entry.app_id !== appId) continue;\n if (listed.has(entry.thread_id) || refreshedForRef.current.has(entry.thread_id)) continue;\n refreshedForRef.current.add(entry.thread_id);\n pending = true;\n }\n if (pending) void listRefresh();\n }, [index.entries, list.conversations, appId, listRefresh]);\n\n const selectThread = useCallback((threadId: string) => {\n if (!threadId) return;\n setActive((current) =>\n current.id === threadId ? current : { id: threadId, isNew: false },\n );\n }, []);\n\n const newThread = useCallback(() => {\n setActive({ id: mintThreadId(), isNew: true });\n }, []);\n\n // A minted thread stops being \"new\" once the backend lists it: until then\n // `useAthenaThreadManager` reports a null id, so URL sync cannot name it.\n const isPersisted = data.some((thread) => thread.id === active.id);\n useEffect(() => {\n if (isPersisted) {\n setActive((current) => (current.isNew ? { ...current, isNew: false } : current));\n }\n }, [isPersisted]);\n\n const titleSource: AthenaStatewireThreadListState['titleSource'] =\n index.entries !== null ? 'index' : 'poll';\n\n const value = useMemo<AthenaStatewireThreadListState>(\n () => ({\n threads: data,\n isLoading,\n activeThreadId: active.id,\n isNewChat: active.isNew,\n selectThread,\n newThread,\n refresh,\n titleSource,\n }),\n [data, isLoading, active.id, active.isNew, selectThread, newThread, refresh, titleSource],\n );\n\n return (\n <AthenaStatewireThreadListContext.Provider value={value}>\n {children}\n </AthenaStatewireThreadListContext.Provider>\n );\n}\n\n/**\n * Provides the statewire thread-list state, with an SDK-scoped QueryClient so\n * consumers do not need their own QueryClientProvider. `syncUrl` (the\n * `…/v2/threads` mount) locates the conversation index beside it; without it\n * titles fall back to the REST poll.\n */\nexport function AthenaStatewireThreadListProvider({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n initialThreadId,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n initialThreadId?: string;\n children: ReactNode;\n}) {\n const [queryClient] = useState(() => new QueryClient());\n return (\n <QueryClientProvider client={queryClient}>\n <StatewireThreadListState\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n initialThreadId={initialThreadId}\n >\n {children}\n </StatewireThreadListState>\n </QueryClientProvider>\n );\n}\n\nconst TITLE_POLL_DELAY_MS = 5000;\nconst TITLE_POLL_INTERVAL_MS = 2000;\nconst TITLE_POLL_MAX_DURATION_MS = 60_000;\n\n/**\n * Fallback for hosts without a live conversation index (`titleSource: 'poll'`,\n * i.e. no signed-in principal): refreshes the thread list until a\n * freshly-started thread's server-generated title appears. Idle while the\n * index carries titles. Mount inside the statewire runtime scope (needs aui\n * state).\n */\nexport function StatewireThreadTitlePoller(): null {\n const list = useAthenaStatewireThreadList();\n const hasMessages = useAuiState((s) => (s.optional.thread?.messages.length ?? 0) > 0);\n\n const activeThreadId = list?.activeThreadId ?? null;\n const titleSource = list?.titleSource ?? 'poll';\n const entry = list?.threads.find((thread) => thread.id === activeThreadId);\n const title = entry?.title?.trim() ?? '';\n const hasTitle = title.length > 0 && !isSerializedContentPartsTitle(title);\n\n const polledThreadsRef = useRef<Set<string>>(new Set());\n const refreshRef = useRef(list?.refresh);\n refreshRef.current = list?.refresh;\n\n useEffect(() => {\n if (!activeThreadId || !hasMessages || hasTitle || titleSource === 'index') return;\n if (polledThreadsRef.current.has(activeThreadId)) return;\n polledThreadsRef.current.add(activeThreadId);\n\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const startId = setTimeout(() => {\n intervalId = setInterval(() => refreshRef.current?.(), TITLE_POLL_INTERVAL_MS);\n }, TITLE_POLL_DELAY_MS);\n const stopId = setTimeout(() => {\n if (intervalId !== null) clearInterval(intervalId);\n }, TITLE_POLL_MAX_DURATION_MS);\n\n return () => {\n clearTimeout(startId);\n clearTimeout(stopId);\n if (intervalId !== null) clearInterval(intervalId);\n };\n }, [activeThreadId, hasMessages, hasTitle, titleSource]);\n\n return null;\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6DO,MAAM,mCACX,cAAqD,IAAI;AAGpD,SAAS,+BAAsE;AACpF,SAAO,WAAW,gCAAgC;AACpD;AAGO,SAAS,uBAA4C;;AAC1D,WAAO,kCAAA,MAAA,mBAAgC,YAAW;AACpD;AAOA,MAAM,wBAAwB;AAE9B,SAAS,yBAAyB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GASG;;AACD,QAAM,CAAC,QAAQ,SAAS,IAAI;AAAA,IAAyC,MACnE,kBACI,EAAE,IAAI,iBAAiB,OAAO,MAAA,IAC9B,EAAE,IAAI,aAAA,GAAgB,OAAO,KAAA;AAAA,EAAK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AS,KAAK,CAAC,8BAA8B,KAAK;AAEzE,QAAM,mBAAmB,OAAoB,oBAAI,KAAK;AACtD,QAAM,aAAa,OAAO,6BAAM,OAAO;AACvC,aAAW,UAAU,6BAAM;AAE3B,YAAU,MAAM;AACd,QAAI,CAAC,kBAAkB,CAAC,eAAe,YAAY,gBAAgB,QAAS;AAC5E,QAAI,iBAAiB,QAAQ,IAAI,cAAc,EAAG;AAClD,qBAAiB,QAAQ,IAAI,cAAc;AAE3C,QAAI,aAAoD;AACxD,UAAM,UAAU,WAAW,MAAM;AAC/B,mBAAa,YAAY,MAAA;;AAAM,gBAAAA,MAAA,WAAW,YAAX,gBAAAA,IAAA;AAAA,SAAwB,sBAAsB;AAAA,IAC/E,GAAG,mBAAmB;AACtB,UAAM,SAAS,WAAW,MAAM;AAC9B,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD,GAAG,0BAA0B;AAE7B,WAAO,MAAM;AACX,mBAAa,OAAO;AACpB,mBAAa,MAAM;AACnB,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,UAAU,WAAW,CAAC;AAEvD,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"statewire-thread-list.js","sources":["../../src/threads/statewire-thread-list.tsx"],"sourcesContent":["import {\n type ConversationAttention,\n type ConversationAttentionSource,\n type ConversationIndexEntry,\n type ConversationListFilter,\n type ConversationPullRequest,\n type ConversationSummary,\n type ConversationWake,\n conversationIndexUrlFromStatewireUrl,\n type DeepAgentHeadersResolver,\n type DeepAgentThreadSnapshotCache,\n deriveConversationAttention,\n summaryFromConversationIndexEntry,\n useConversationIndex,\n useConversationList,\n} from '@athenaintel/agent-runtime';\nimport { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';\nimport { useAuiState } from '@assistant-ui/react';\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n resolveStatewireAuthToken,\n} from '../runtime/statewire-auth-headers';\nimport { fetchAccountIdentity, getThreadState } from './api';\nimport { createRestConversationListFetcher } from './conversation-list-fetcher';\nimport { credentialShape, sameCredentialShape } from './credential-shape';\nimport { mintThreadId } from './mint-thread-id';\nimport { useAthenaStatewireThreadId } from './thread-id-context';\nimport { createThreadPrefetcher } from './thread-prefetcher';\nimport { isSerializedContentPartsTitle, normalizeThreadTitle } from './title';\nimport { useThreadArchive } from './use-thread-archive';\nimport {\n type ThreadFavoriteTarget,\n useThreadFavorite,\n withFavoriteOverride,\n withFavoriteOverrides,\n} from './use-thread-favorite';\nimport {\n type ThreadRenameTarget,\n useThreadRename,\n withTitleOverride,\n withTitleOverrides,\n} from './use-thread-rename';\n\n/**\n * One row of the thread list — the fields a Devin-style session list renders\n * (`SessionList`), all read from the shared conversation-list contract. The\n * attention fields are `null` on a server that does not derive them; the\n * pull-request state is `null` until the list has fetched it (or when the\n * provider opted out of it).\n */\nexport interface AthenaStatewireThreadSummary {\n id: string;\n title: string | null;\n /**\n * What the session asks of the viewer: the server-derived state when\n * reported, else the client fallback from the status planes\n * (`deriveConversationAttention`).\n */\n attention: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction: string | null;\n attentionSource: ConversationAttentionSource | null;\n /**\n * Whether the viewer pinned the session. Toggled through\n * `AthenaStatewireThreadListState.setFavorited`; a toggle in flight is\n * reflected here at once and held until the list sources report it.\n */\n isFavorited: boolean;\n isUnread: boolean;\n /** Canonical status_v2 planes, or `null` on an older server. */\n sessionStatus: string | null;\n runStatus: string | null;\n /** Channel the session was started from (e.g. `web`, `github`, `api`). */\n startChannel: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Pull requests the session opened with their live GitHub state. */\n pullRequests: ConversationPullRequest[] | null;\n /** The last wake of a resting session. */\n lastWake: ConversationWake | null;\n /** ISO 8601 timestamp of the last update (the list's sort key). */\n updatedAt: string;\n}\n\n/**\n * Thread-list state. The list is the persisted Agora session list; the ACTIVE\n * thread is a plain id the statewire runtime attaches to — switching threads\n * remounts the statewire session against the new `…/v2/threads/{id}` URL\n * (the same model the mobile app uses).\n */\nexport interface AthenaStatewireThreadListState {\n /** The rows the current `search` lists, newest first. */\n threads: AthenaStatewireThreadSummary[];\n isLoading: boolean;\n /** True while the live first page (or a history page) is being fetched. */\n isFetching: boolean;\n /**\n * True once the live first page has answered at least once for the current\n * search and identity. Until then an empty `threads` means \"not known\n * yet\" (no credential resolved, first page in flight), not \"no sessions\":\n * `SessionList` shows skeleton rows, never the empty state.\n */\n hasResolvedFirstPage: boolean;\n activeThreadId: string;\n /**\n * The active thread's row, independent of what `threads` currently lists:\n * a search that hides the row, or a page that has not fetched it, must not\n * make the active chat's attention disappear. Resolved from the listed row,\n * else the pushed index entry folded over the last row seen, else that\n * last row; `null` for a never-started chat the backend does not know yet.\n */\n activeThread: AthenaStatewireThreadSummary | null;\n /** True while the active thread is a locally-minted chat with no server history. */\n isNewChat: boolean;\n selectThread: (threadId: string) => void;\n /**\n * Warm the provider's snapshot cache with a thread's REST state ahead of a\n * `selectThread`, so the switch paints the transcript on its first frame\n * instead of the loading scrim while the statewire attach lands.\n * `SessionList` calls it after a 120 ms hover dwell and on row focus.\n * Fetches once per thread per identity, deduplicates requests in flight,\n * runs at most two at a time and ignores failures; a no-op for the active\n * thread, a thread the cache already holds, or a provider without a cache.\n */\n prefetchThread: (threadId: string) => void;\n newThread: () => void;\n refresh: () => void;\n /**\n * Server-side title search (`search` on the REST thread list). An empty\n * string lists everything; the search covers the viewer's whole authorized\n * history, not just the live page.\n */\n search: string;\n setSearch: (search: string) => void;\n /** Whether another page of older sessions can be fetched. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n /** Fetch the next page of older sessions (frozen history pages, never replayed). */\n fetchNextPage: () => void;\n /**\n * Pin or unpin a session (`POST /api/conversations/threads/favorite`). The\n * row flips at once and moves between the `Pinned` and `Recent` groups; the\n * server's answer is written back, and a failure restores the previous\n * state. Writes for one thread are serialized: a toggle while that\n * thread's write is in flight records the value and sends at most one\n * follow-up write once the first has answered.\n */\n setFavorited: (target: ThreadFavoriteTarget) => void;\n /** True while any pin toggle is in flight. */\n favoritePending: boolean;\n /** The sessions whose pin toggle is in flight; `SessionList` disables their pin control. */\n favoritePendingThreadIds: ReadonlySet<string>;\n /**\n * Whether the backend offers the favorite route. `false` once it answered\n * 404 / 405 (an agora that predates the route): `SessionList` then shows\n * the read-only pin and no toggle, and `setFavorited` keeps failing.\n */\n favoriteToggleAvailable: boolean;\n /**\n * Rename a session for every viewer (`POST /api/conversations/threads/rename`).\n * The row shows the new title at once; the server's stored title is\n * written back, and a failure restores the previous one. Same-thread\n * writes are serialized like the pin's.\n */\n renameThread: (target: ThreadRenameTarget) => void;\n /** The sessions whose rename is in flight; `SessionList` keeps their editor closed. */\n renamePendingThreadIds: ReadonlySet<string>;\n /**\n * Whether the backend offers the rename route. `false` once it answered\n * 404 / 405 (an agora that predates the route): `SessionList` then offers\n * no Rename action, and `renameThread` keeps failing.\n */\n renameAvailable: boolean;\n /**\n * Archive a session (`POST /api/conversations/threads/archive`). The row\n * leaves the list at once and stays hidden until both list sources stop\n * reporting it; a failure brings it back. Archiving the active session\n * moves the chat to a new one once the server has confirmed.\n */\n archiveThread: (threadId: string) => void;\n /** The sessions whose archive is in flight. */\n archivePendingThreadIds: ReadonlySet<string>;\n /** True while any archive is in flight. */\n archivePending: boolean;\n /**\n * Whether the backend offers the archive route. `false` once it answered\n * 404 / 405: `SessionList` then offers no Archive action.\n */\n archiveAvailable: boolean;\n /**\n * Where titles come from. `'index'` once the signed-in user's live\n * conversation index has replicated — titles and newly created threads then\n * arrive as pushed updates; `'poll'` while it has not (no signed-in\n * principal, e.g. API-key mode, or before its snapshot), when a\n * freshly-started thread's title is picked up by the bounded REST poll.\n */\n titleSource: 'index' | 'poll';\n}\n\nexport const AthenaStatewireThreadListContext =\n createContext<AthenaStatewireThreadListState | null>(null);\n\n/** Read the statewire thread-list state, or null outside that mode. */\nexport function useAthenaStatewireThreadList(): AthenaStatewireThreadListState | null {\n return useContext(AthenaStatewireThreadListContext);\n}\n\n/** Trigger a re-fetch of the thread list. `null` outside `enableThreadList` mode. */\nexport function useRefreshThreadList(): (() => void) | null {\n return useAthenaStatewireThreadList()?.refresh ?? null;\n}\n\n/**\n * Project one contract row onto the thread-list row. Exported for hosts (and\n * tests) that build rows from a `ConversationSummary` of their own.\n */\nexport function threadSummaryFromConversation(\n conversation: ConversationSummary,\n): AthenaStatewireThreadSummary {\n return {\n id: conversation.threadId,\n title: normalizeThreadTitle(conversation.title) ?? null,\n attention: deriveConversationAttention(conversation),\n nextAction: conversation.nextAction ?? null,\n attentionSource: conversation.attentionSource ?? null,\n isFavorited: conversation.isFavorited ?? false,\n isUnread: conversation.isUnread,\n sessionStatus: conversation.sessionStatus,\n runStatus: conversation.runStatus,\n startChannel: conversation.sourceChannel,\n appId: conversation.appId,\n triggerType: conversation.triggerType,\n pullRequests: conversation.pullRequests ?? null,\n lastWake: conversation.lastWake ?? null,\n updatedAt: conversation.updatedAt,\n };\n}\n\n/**\n * The statewire thread list reads one live page through the shared\n * conversation-list contract; the REST default page size predates the shared\n * pager and is preserved here.\n */\nconst THREAD_LIST_PAGE_SIZE = 50;\n\nfunction StatewireThreadListState({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n initialThreadId,\n includePullRequests,\n snapshotCache,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n initialThreadId?: string;\n includePullRequests: boolean;\n snapshotCache?: DeepAgentThreadSnapshotCache;\n children: ReactNode;\n}) {\n const [active, setActive] = useState<{ id: string; isNew: boolean }>(() =>\n initialThreadId\n ? { id: initialThreadId, isNew: false }\n : { id: mintThreadId(), isNew: true },\n );\n const [search, setSearch] = useState('');\n\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const apiKeyRef = useRef(apiKey);\n apiKeyRef.current = apiKey;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n // The cache must be keyed by WHO is asking. Keying on `backendUrl`/`appId`\n // alone let a token swap to a different user read the previous user's thread\n // titles out of the cache. The principal is a non-secret user id, so no\n // credential enters the key (or React Query's devtools). The shared pager\n // never serves placeholder rows across keys, so another principal's list is\n // never shown while the new one loads.\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n // A live token getter is a credential too: a `getToken`-only host\n // authenticates its chat, so its list must not stay empty.\n const hasAuth = !!(apiKey || token || getToken);\n\n // Resolved per request with the attach's token semantics (getter first,\n // host-held token as the fallback) so a rotated token is never stale.\n const getAuth = useCallback(\n async () => ({\n apiKey: apiKeyRef.current,\n token: await resolveStatewireAuthToken(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n { staleAuth: false },\n ),\n }),\n [],\n );\n const fetchPage = useMemo(\n () => createRestConversationListFetcher({ backendUrl, includePullRequests, getAuth }),\n [backendUrl, includePullRequests, getAuth],\n );\n const trimmedSearch = search.trim();\n const filter = useMemo<ConversationListFilter>(\n () => ({\n ...(appId ? { appId } : {}),\n ...(trimmedSearch ? { search: trimmedSearch } : {}),\n }),\n [appId, trimmedSearch],\n );\n const list = useConversationList({\n fetchPage,\n filter,\n pageSize: THREAD_LIST_PAGE_SIZE,\n // Pull-request opt-in changes what a cached row holds, so it is part of\n // the cache identity.\n scopeKey: `${backendUrl}::${principal}::${hasAuth ? 'auth' : 'anon'}::${\n includePullRequests ? 'prs' : 'no-prs'\n }`,\n enabled: hasAuth,\n });\n\n // Live rows ride the signed-in user's conversation index — the same push\n // channel the conversation-history panel renders from: the host replicates\n // title, lifecycle, attention and creation changes as ops, so a\n // freshly-started thread's server-generated title (or a session flipping to\n // \"needs you\") lands without polling. The index is one instance per\n // `(workspace, user)` in agora's ids, so the pair is resolved from the\n // backend once a principal is known and the index only attaches once both\n // halves are; API-key-only hosts keep the bounded REST poll\n // (`titleSource: 'poll'`).\n const indexHeaders = useCallback<DeepAgentHeadersResolver>(\n (ctx) =>\n resolveStatewireAuthHeaders(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n ctx,\n ),\n [],\n );\n // The workspace half is the CREDENTIAL's: a scoped credential (sandbox,\n // preview, Office session) pins its own workspace, so swapping one for\n // another under the same principal must re-resolve the pair. The query is\n // therefore keyed by a credential generation — a counter that advances\n // whenever the host's credentials change — so no secret enters the key.\n const credentialsRef = useRef(credentialShape({ apiKey, token, getToken }));\n const credentialGenerationRef = useRef(0);\n const currentCredentials = credentialShape({ apiKey, token, getToken });\n if (!sameCredentialShape(credentialsRef.current, currentCredentials)) {\n credentialsRef.current = currentCredentials;\n credentialGenerationRef.current += 1;\n }\n const credentialGeneration = credentialGenerationRef.current;\n const identityEnabled = syncUrl !== undefined && principal.length > 0 && hasAuth;\n const identity = useQuery({\n // Keyed by the non-secret principal and credential generation, never the\n // credential itself.\n queryKey: ['athena-sdk', 'account-identity', backendUrl, principal, credentialGeneration],\n queryFn: async ({ signal }) =>\n fetchAccountIdentity(\n backendUrl,\n {\n apiKey: apiKeyRef.current,\n token: await resolveStatewireAuthToken(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n { staleAuth: false },\n ),\n },\n { signal },\n ),\n enabled: identityEnabled,\n staleTime: Number.POSITIVE_INFINITY,\n });\n const indexWorkspaceId = identity.data?.workspaceId ?? '';\n const indexUserId = identity.data?.userId ?? '';\n const indexEnabled = identityEnabled && indexWorkspaceId.length > 0 && indexUserId.length > 0;\n const index = useConversationIndex({\n baseUrl: syncUrl === undefined ? '' : conversationIndexUrlFromStatewireUrl(syncUrl),\n workspaceId: indexWorkspaceId || 'pending-workspace',\n userId: indexUserId || 'pending-user',\n headers: indexHeaders,\n enabled: indexEnabled,\n });\n const indexByThread = useMemo(() => {\n const entries = new Map<string, ConversationIndexEntry>();\n for (const entry of index.entries ?? []) entries.set(entry.thread_id, entry);\n return entries;\n }, [index.entries]);\n\n // Each fetched row folds its pushed index entry through the shared\n // `summaryFromConversationIndexEntry`, so titles, lifecycle and attention\n // update live while the fields the index never carries (pull requests,\n // the last wake) keep their fetched values. A pushed title that normalizes\n // to nothing falls back to the fetched one.\n const mergedConversations = useMemo(\n () =>\n list.conversations.map((conversation) => {\n const entry = indexByThread.get(conversation.threadId);\n if (!entry) return conversation;\n const merged = summaryFromConversationIndexEntry(entry, conversation);\n return normalizeThreadTitle(merged.title) === undefined\n ? { ...merged, title: conversation.title }\n : merged;\n }),\n [list.conversations, indexByThread],\n );\n // A pin toggle sits over the fold: the row flips at once, and a pushed\n // index entry that predates the write cannot clobber it. The override drops\n // once both sources report the toggled value.\n const listPatchConversation = list.patchConversation;\n const favorite = useThreadFavorite({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, isFavorited }) =>\n listPatchConversation(threadId, { isFavorited }),\n });\n const favoriteOverrides = favorite.overrides;\n // A rename sits over the fold the same way: the row shows the new title\n // at once, and a pushed index entry that predates the write cannot restore\n // the old one. The override drops once both sources report the new title.\n const rename = useThreadRename({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, title }) => listPatchConversation(threadId, { title }),\n });\n const titleOverrides = rename.overrides;\n\n // An archive hides the row at once and keeps it hidden until neither list\n // source reports it any more — the cached page is patched on the server's\n // answer, but the pushed index may still carry the row until the publish\n // that follows the commit lands. A failure drops the id and the row comes\n // back from the still-cached page: no refetch needed. Scoping, the\n // one-write-per-thread guard and the route-missing fallback live in the hook.\n const listRemoveConversation = list.removeConversation;\n const archive = useThreadArchive({\n backendUrl,\n principalId: principal,\n getAuth,\n onArchived: (threadId) => {\n listRemoveConversation(threadId);\n // The archived session cannot stay the active chat: the server no\n // longer lists it, so the chat moves to a fresh one.\n setActive((current) =>\n current.id === threadId ? { id: mintThreadId(), isNew: true } : current,\n );\n },\n });\n const hiddenThreadIds = archive.hiddenThreadIds;\n const archiveRelease = archive.release;\n // A hidden row is released once both sources have forgotten it, so a\n // session archived elsewhere and then restored is never masked here.\n useEffect(() => {\n if (hiddenThreadIds.size === 0) return;\n const forgotten = [...hiddenThreadIds].filter(\n (threadId) =>\n !mergedConversations.some((conversation) => conversation.threadId === threadId) &&\n !indexByThread.has(threadId),\n );\n if (forgotten.length > 0) archiveRelease(forgotten);\n }, [hiddenThreadIds, mergedConversations, indexByThread, archiveRelease]);\n\n const data = useMemo(\n () =>\n withTitleOverrides(\n withFavoriteOverrides(mergedConversations, favoriteOverrides),\n titleOverrides,\n )\n .filter((conversation) => !hiddenThreadIds.has(conversation.threadId))\n .map(threadSummaryFromConversation),\n [mergedConversations, favoriteOverrides, titleOverrides, hiddenThreadIds],\n );\n const isLoading = list.isLoading;\n\n // The active thread's row must survive a search that filters it out of\n // the page (the banner above the chat reads it): the listed row when there\n // is one, else the pushed index entry folded over the last row seen for\n // this thread (so pull requests survive the fold), else that last row.\n const lastActiveConversationRef = useRef<ConversationSummary | null>(null);\n const activeConversation = useMemo<ConversationSummary | null>(() => {\n const listed = mergedConversations.find((conversation) => conversation.threadId === active.id);\n if (listed) return listed;\n const remembered =\n lastActiveConversationRef.current?.threadId === active.id\n ? lastActiveConversationRef.current\n : undefined;\n const entry = indexByThread.get(active.id);\n if (entry) return summaryFromConversationIndexEntry(entry, remembered);\n return remembered ?? null;\n }, [mergedConversations, indexByThread, active.id]);\n if (activeConversation !== null) lastActiveConversationRef.current = activeConversation;\n const activeThread = useMemo(\n () =>\n activeConversation\n ? threadSummaryFromConversation(\n withTitleOverride(\n withFavoriteOverride(activeConversation, favoriteOverrides),\n titleOverrides,\n ),\n )\n : null,\n [activeConversation, favoriteOverrides, titleOverrides],\n );\n\n const listRefresh = list.refresh;\n const refresh = useCallback(() => {\n void listRefresh();\n }, [listRefresh]);\n const listFetchNextPage = list.fetchNextPage;\n const fetchNextPage = useCallback(() => {\n void listFetchNextPage();\n }, [listFetchNextPage]);\n\n // A thread the index knows — created here on first send, or elsewhere —\n // that the REST page does not list yet: refresh once per such id so the row\n // appears without the user pressing refresh. Rows for other app ids belong\n // to other lists and never trigger one.\n const refreshedForRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n if (index.entries === null) return;\n const listed = new Set(list.conversations.map((conversation) => conversation.threadId));\n let pending = false;\n for (const entry of index.entries) {\n if (appId && entry.app_id !== appId) continue;\n if (listed.has(entry.thread_id) || refreshedForRef.current.has(entry.thread_id)) continue;\n refreshedForRef.current.add(entry.thread_id);\n pending = true;\n }\n if (pending) void listRefresh();\n }, [index.entries, list.conversations, appId, listRefresh]);\n\n const selectThread = useCallback((threadId: string) => {\n if (!threadId) return;\n setActive((current) =>\n current.id === threadId ? current : { id: threadId, isNew: false },\n );\n }, []);\n\n // The hover prefetcher is one per (backend, principal, credential\n // generation): a credential swap clears the provider's snapshot cache, so\n // the attempt ledger resets with it and a late answer from the previous\n // identity is never remembered under the new one.\n const prefetchScope = `${backendUrl}::${principal}::${credentialGeneration}`;\n const prefetchScopeRef = useRef(prefetchScope);\n prefetchScopeRef.current = prefetchScope;\n const prefetcher = useMemo(() => {\n if (!snapshotCache) return null;\n const scope = prefetchScope;\n return createThreadPrefetcher({\n cache: snapshotCache,\n fetchState: async (threadId) =>\n getThreadState(backendUrl, await getAuth(), threadId, { skipCache: false }),\n isCurrent: () => prefetchScopeRef.current === scope,\n });\n }, [snapshotCache, prefetchScope, backendUrl, getAuth]);\n const activeIdRef = useRef(active.id);\n activeIdRef.current = active.id;\n const prefetchThread = useCallback(\n (threadId: string) => {\n if (!prefetcher || !threadId || threadId === activeIdRef.current) return;\n prefetcher.prefetch(threadId);\n },\n [prefetcher],\n );\n\n const newThread = useCallback(() => {\n setActive({ id: mintThreadId(), isNew: true });\n }, []);\n\n // A minted thread stops being \"new\" once the backend lists it — on the\n // fetched page or in the pushed index (a search may keep it off the page):\n // until then `useAthenaThreadManager` reports a null id, so URL sync cannot\n // name it.\n const isPersisted =\n data.some((thread) => thread.id === active.id) || indexByThread.has(active.id);\n useEffect(() => {\n if (isPersisted) {\n setActive((current) => (current.isNew ? { ...current, isNew: false } : current));\n }\n }, [isPersisted]);\n\n const titleSource: AthenaStatewireThreadListState['titleSource'] =\n index.entries !== null ? 'index' : 'poll';\n\n const value = useMemo<AthenaStatewireThreadListState>(\n () => ({\n threads: data,\n isLoading,\n isFetching: list.isFetching,\n hasResolvedFirstPage: list.hasResolvedFirstPage,\n activeThreadId: active.id,\n activeThread,\n isNewChat: active.isNew,\n selectThread,\n prefetchThread,\n newThread,\n refresh,\n search,\n setSearch,\n hasNextPage: list.hasNextPage,\n isFetchingNextPage: list.isFetchingNextPage,\n fetchNextPage,\n setFavorited: favorite.setFavorited,\n favoritePending: favorite.isPending,\n favoritePendingThreadIds: favorite.pendingThreadIds,\n favoriteToggleAvailable: favorite.isAvailable,\n renameThread: rename.rename,\n renamePendingThreadIds: rename.pendingThreadIds,\n renameAvailable: rename.isAvailable,\n archiveThread: archive.archive,\n archivePendingThreadIds: archive.pendingThreadIds,\n archivePending: archive.isPending,\n archiveAvailable: archive.isAvailable,\n titleSource,\n }),\n [\n data,\n isLoading,\n list.isFetching,\n list.hasResolvedFirstPage,\n active.id,\n activeThread,\n active.isNew,\n selectThread,\n prefetchThread,\n newThread,\n refresh,\n search,\n list.hasNextPage,\n list.isFetchingNextPage,\n fetchNextPage,\n favorite.setFavorited,\n favorite.isPending,\n favorite.pendingThreadIds,\n favorite.isAvailable,\n rename.rename,\n rename.pendingThreadIds,\n rename.isAvailable,\n archive.archive,\n archive.pendingThreadIds,\n archive.isPending,\n archive.isAvailable,\n titleSource,\n ],\n );\n\n return (\n <AthenaStatewireThreadListContext.Provider value={value}>\n {children}\n </AthenaStatewireThreadListContext.Provider>\n );\n}\n\n/**\n * Provides the statewire thread-list state, with an SDK-scoped QueryClient so\n * consumers do not need their own QueryClientProvider. `syncUrl` (the\n * `…/v2/threads` mount) locates the conversation index beside it; without it\n * titles fall back to the REST poll. `includePullRequests` (default `true`)\n * asks the list for live pull-request state so `SessionList` can render its\n * chips; a host that never shows them turns it off to spare the server the\n * lookup. `snapshotCache` is the provider's thread snapshot cache — the one\n * the runtime seeds a switched-to thread from — which `prefetchThread` warms;\n * without it prefetching is a no-op.\n */\nexport function AthenaStatewireThreadListProvider({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n initialThreadId,\n includePullRequests = true,\n snapshotCache,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n initialThreadId?: string;\n includePullRequests?: boolean;\n snapshotCache?: DeepAgentThreadSnapshotCache;\n children: ReactNode;\n}) {\n const [queryClient] = useState(() => new QueryClient());\n return (\n <QueryClientProvider client={queryClient}>\n <StatewireThreadListState\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n initialThreadId={initialThreadId}\n includePullRequests={includePullRequests}\n snapshotCache={snapshotCache}\n >\n {children}\n </StatewireThreadListState>\n </QueryClientProvider>\n );\n}\n\n/** How long after a thread's first message the title poll starts (exported for tests). */\nexport const TITLE_POLL_DELAY_MS = 5000;\nconst TITLE_POLL_INTERVAL_MS = 2000;\nconst TITLE_POLL_MAX_DURATION_MS = 60_000;\n\n/**\n * Fallback for hosts without a live conversation index (`titleSource: 'poll'`,\n * i.e. no signed-in principal): refreshes the thread list until a\n * freshly-started thread's server-generated title appears. Idle while the\n * index carries titles. Mount inside the statewire runtime scope (needs aui\n * state).\n *\n * The thread is read from the statewire scope, not the list: the scope\n * publishes the id together with the client it belongs to, so the messages\n * observed here are always the named thread's (the list's selection moves\n * one commit ahead of the client during a switch).\n */\nexport function StatewireThreadTitlePoller(): null {\n const list = useAthenaStatewireThreadList();\n const activeThreadId = useAthenaStatewireThreadId();\n const hasMessages = useAuiState((s) => (s.optional.thread?.messages.length ?? 0) > 0);\n\n const titleSource = list?.titleSource ?? 'poll';\n const entry = list?.threads.find((thread) => thread.id === activeThreadId);\n const title = entry?.title?.trim() ?? '';\n const hasTitle = title.length > 0 && !isSerializedContentPartsTitle(title);\n\n // The poller stays mounted across thread switches, so the visit is tracked\n // by hand: one poll per visit — no restart when the visited thread's\n // messages or title flip underneath it — and a re-selected thread polls\n // again, as it did when every switch remounted the poller. The record is\n // replaced whenever the attached thread changes, whether or not a poll\n // started for it, so a visit to a thread that needs no poll can never make\n // the next visit to a previous thread look already polled.\n const visitRef = useRef<{ threadId: string; polled: boolean } | null>(null);\n const refreshRef = useRef(list?.refresh);\n refreshRef.current = list?.refresh;\n\n useEffect(() => {\n if (visitRef.current?.threadId !== activeThreadId) {\n visitRef.current = { threadId: activeThreadId, polled: false };\n }\n const visit = visitRef.current;\n if (!hasMessages || hasTitle || titleSource === 'index') return;\n if (visit.polled) return;\n visit.polled = true;\n\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const startId = setTimeout(() => {\n intervalId = setInterval(() => refreshRef.current?.(), TITLE_POLL_INTERVAL_MS);\n }, TITLE_POLL_DELAY_MS);\n const stopId = setTimeout(() => {\n if (intervalId !== null) clearInterval(intervalId);\n }, TITLE_POLL_MAX_DURATION_MS);\n\n return () => {\n clearTimeout(startId);\n clearTimeout(stopId);\n if (intervalId !== null) clearInterval(intervalId);\n };\n }, [activeThreadId, hasMessages, hasTitle, titleSource]);\n\n return null;\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNO,MAAM,mCACX,cAAqD,IAAI;AAGpD,SAAS,+BAAsE;AACpF,SAAO,WAAW,gCAAgC;AACpD;AAGO,SAAS,uBAA4C;;AAC1D,WAAO,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;AACd,UAAIA,MAAA,SAAS,YAAT,gBAAAA,IAAkB,cAAa,gBAAgB;AACjD,eAAS,UAAU,EAAE,UAAU,gBAAgB,QAAQ,MAAA;AAAA,IACzD;AACA,UAAM,QAAQ,SAAS;AACvB,QAAI,CAAC,eAAe,YAAY,gBAAgB,QAAS;AACzD,QAAI,MAAM,OAAQ;AAClB,UAAM,SAAS;AAEf,QAAI,aAAoD;AACxD,UAAM,UAAU,WAAW,MAAM;AAC/B,mBAAa,YAAY,MAAA;;AAAM,gBAAAA,MAAA,WAAW,YAAX,gBAAAA,IAAA;AAAA,SAAwB,sBAAsB;AAAA,IAC/E,GAAG,mBAAmB;AACtB,UAAM,SAAS,WAAW,MAAM;AAC9B,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD,GAAG,0BAA0B;AAE7B,WAAO,MAAM;AACX,mBAAa,OAAO;AACpB,mBAAa,MAAM;AACnB,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,UAAU,WAAW,CAAC;AAEvD,SAAO;AACT;"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const THREAD_PREFETCH_MAX_CONCURRENT = 2;
|
|
4
|
+
const THREAD_PREFETCH_HOVER_DELAY_MS = 120;
|
|
5
|
+
function threadStateToSnapshot(state) {
|
|
6
|
+
const { thread_id: _threadId, status: _status, messages, ...channelValues } = state;
|
|
7
|
+
if (!Array.isArray(messages) || messages.length === 0) return null;
|
|
8
|
+
return { ...channelValues, messages };
|
|
9
|
+
}
|
|
10
|
+
function createThreadPrefetcher({
|
|
11
|
+
fetchState,
|
|
12
|
+
cache,
|
|
13
|
+
maxConcurrent = THREAD_PREFETCH_MAX_CONCURRENT,
|
|
14
|
+
isCurrent = () => true
|
|
15
|
+
}) {
|
|
16
|
+
const attempted = /* @__PURE__ */ new Set();
|
|
17
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
18
|
+
const queue = [];
|
|
19
|
+
let generation = 0;
|
|
20
|
+
const pump = () => {
|
|
21
|
+
while (inFlight.size < maxConcurrent && queue.length > 0) {
|
|
22
|
+
const threadId = queue.shift();
|
|
23
|
+
if (threadId === void 0) break;
|
|
24
|
+
start(threadId);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const start = (threadId) => {
|
|
28
|
+
const startedIn = generation;
|
|
29
|
+
attempted.add(threadId);
|
|
30
|
+
inFlight.add(threadId);
|
|
31
|
+
fetchState(threadId).then((state) => {
|
|
32
|
+
if (startedIn !== generation || !isCurrent()) return;
|
|
33
|
+
const snapshot = threadStateToSnapshot(state);
|
|
34
|
+
if (snapshot) cache.remember(threadId, snapshot);
|
|
35
|
+
}).catch(() => {
|
|
36
|
+
}).finally(() => {
|
|
37
|
+
inFlight.delete(threadId);
|
|
38
|
+
if (startedIn === generation) pump();
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
prefetch(threadId) {
|
|
43
|
+
var _a;
|
|
44
|
+
if (!threadId) return;
|
|
45
|
+
if (attempted.has(threadId) || inFlight.has(threadId) || queue.includes(threadId)) return;
|
|
46
|
+
if ((_a = cache.peek) == null ? void 0 : _a.call(cache, threadId)) return;
|
|
47
|
+
queue.push(threadId);
|
|
48
|
+
pump();
|
|
49
|
+
},
|
|
50
|
+
inFlight: () => inFlight,
|
|
51
|
+
queued: () => queue,
|
|
52
|
+
reset() {
|
|
53
|
+
generation += 1;
|
|
54
|
+
attempted.clear();
|
|
55
|
+
queue.length = 0;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
exports.THREAD_PREFETCH_HOVER_DELAY_MS = THREAD_PREFETCH_HOVER_DELAY_MS;
|
|
60
|
+
exports.THREAD_PREFETCH_MAX_CONCURRENT = THREAD_PREFETCH_MAX_CONCURRENT;
|
|
61
|
+
exports.createThreadPrefetcher = createThreadPrefetcher;
|
|
62
|
+
exports.threadStateToSnapshot = threadStateToSnapshot;
|
|
63
|
+
//# sourceMappingURL=thread-prefetcher.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"thread-prefetcher.cjs","sources":["../../src/threads/thread-prefetcher.ts"],"sourcesContent":["/**\n * Hover prefetch for the session list: warm the provider's thread snapshot\n * cache with a thread's REST state before the user selects it, so the switch\n * paints the transcript on its first frame instead of a spinner while the\n * statewire attach lands (see `DeepAgentThreadSnapshotCache` and\n * `toThreadSnapshotSeed`: the attach snapshot replaces the seed).\n *\n * React-free so the scheduling rules — once per thread, in-flight requests\n * deduplicated, at most `maxConcurrent` requests at a time with the rest\n * queued in arrival order, failures swallowed — are testable on their own.\n */\nimport type {\n DeepAgentThreadSnapshotCache,\n DeepAgentStreamValues,\n} from '@athenaintel/agent-runtime';\nimport type { ThreadStateResponse } from './api';\n\n/** How many hover prefetches may be in flight at once. */\nexport const THREAD_PREFETCH_MAX_CONCURRENT = 2;\n\n/** How long a pointer must rest on a row before its prefetch starts. */\nexport const THREAD_PREFETCH_HOVER_DELAY_MS = 120;\n\n/**\n * Shape a REST thread state as a snapshot the runtime can seed a mount from.\n * `null` when there is nothing to paint (an empty or not-yet-persisted\n * thread): an empty seed would render the same empty thread the attach\n * covers, so it buys no paint. The REST-only keys (`thread_id`, the legacy\n * `status`) are not wire state and are dropped; every channel value the\n * server returned rides along, as it does on the wire.\n */\nexport function threadStateToSnapshot(state: ThreadStateResponse): DeepAgentStreamValues | null {\n const { thread_id: _threadId, status: _status, messages, ...channelValues } = state;\n if (!Array.isArray(messages) || messages.length === 0) return null;\n // The REST messages are LangChain messages deserialized to their plain\n // shape — the same records the wire's `messages` lane carries — so the\n // cast mirrors `readDeepAgentStreamValues`, which types a wire state the\n // same way.\n return { ...channelValues, messages } as DeepAgentStreamValues;\n}\n\nexport interface ThreadPrefetcherOptions {\n /** Fetch the thread's REST state (`getThreadState` bound to the current credential). */\n fetchState: (threadId: string) => Promise<ThreadStateResponse>;\n /** The cache the runtime seeds a mount from. */\n cache: Pick<DeepAgentThreadSnapshotCache, 'remember' | 'peek'>;\n maxConcurrent?: number;\n /**\n * Whether a resolved fetch may still be remembered: the identity that\n * started it must still be the acting one (a credential swap clears the\n * cache, and a late answer must not re-seed it under another account).\n */\n isCurrent?: () => boolean;\n}\n\nexport interface ThreadPrefetcher {\n /**\n * Ask for a thread's snapshot. A no-op for a thread already warm in the\n * cache, already fetched (or attempted) here, or already in flight or\n * queued; otherwise the fetch starts now, or once a slot frees.\n */\n prefetch: (threadId: string) => void;\n /** The threads whose fetch is in flight (tests, diagnostics). */\n inFlight: () => ReadonlySet<string>;\n /** The threads waiting for a slot, in arrival order (tests, diagnostics). */\n queued: () => readonly string[];\n /** Drop the queue and forget every attempt; in-flight answers are still ignored by `isCurrent`. */\n reset: () => void;\n}\n\nexport function createThreadPrefetcher({\n fetchState,\n cache,\n maxConcurrent = THREAD_PREFETCH_MAX_CONCURRENT,\n isCurrent = () => true,\n}: ThreadPrefetcherOptions): ThreadPrefetcher {\n // Every thread ever started here: a prefetch is one attempt per thread per\n // identity, whether it succeeded or failed — a hover must not turn into a\n // retry storm against a thread the server keeps refusing.\n const attempted = new Set<string>();\n const inFlight = new Set<string>();\n const queue: string[] = [];\n // A reset abandons the generation: answers from before it are dropped.\n let generation = 0;\n\n const pump = (): void => {\n while (inFlight.size < maxConcurrent && queue.length > 0) {\n const threadId = queue.shift();\n if (threadId === undefined) break;\n start(threadId);\n }\n };\n\n const start = (threadId: string): void => {\n const startedIn = generation;\n attempted.add(threadId);\n inFlight.add(threadId);\n fetchState(threadId)\n .then((state) => {\n if (startedIn !== generation || !isCurrent()) return;\n const snapshot = threadStateToSnapshot(state);\n if (snapshot) cache.remember(threadId, snapshot);\n })\n .catch(() => {\n // Best effort: a refused or failed warm-up changes nothing the user\n // sees — the selection still attaches and loads on its own.\n })\n .finally(() => {\n inFlight.delete(threadId);\n if (startedIn === generation) pump();\n });\n };\n\n return {\n prefetch(threadId) {\n if (!threadId) return;\n if (attempted.has(threadId) || inFlight.has(threadId) || queue.includes(threadId)) return;\n if (cache.peek?.(threadId)) return;\n queue.push(threadId);\n pump();\n },\n inFlight: () => inFlight,\n queued: () => queue,\n reset() {\n generation += 1;\n attempted.clear();\n queue.length = 0;\n },\n };\n}\n"],"names":[],"mappings":";;AAkBO,MAAM,iCAAiC;AAGvC,MAAM,iCAAiC;AAUvC,SAAS,sBAAsB,OAA0D;AAC9F,QAAM,EAAE,WAAW,WAAW,QAAQ,SAAS,UAAU,GAAG,kBAAkB;AAC9E,MAAI,CAAC,MAAM,QAAQ,QAAQ,KAAK,SAAS,WAAW,EAAG,QAAO;AAK9D,SAAO,EAAE,GAAG,eAAe,SAAA;AAC7B;AA+BO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA,EAChB,YAAY,MAAM;AACpB,GAA8C;AAI5C,QAAM,gCAAgB,IAAA;AACtB,QAAM,+BAAe,IAAA;AACrB,QAAM,QAAkB,CAAA;AAExB,MAAI,aAAa;AAEjB,QAAM,OAAO,MAAY;AACvB,WAAO,SAAS,OAAO,iBAAiB,MAAM,SAAS,GAAG;AACxD,YAAM,WAAW,MAAM,MAAA;AACvB,UAAI,aAAa,OAAW;AAC5B,YAAM,QAAQ;AAAA,IAChB;AAAA,EACF;AAEA,QAAM,QAAQ,CAAC,aAA2B;AACxC,UAAM,YAAY;AAClB,cAAU,IAAI,QAAQ;AACtB,aAAS,IAAI,QAAQ;AACrB,eAAW,QAAQ,EAChB,KAAK,CAAC,UAAU;AACf,UAAI,cAAc,cAAc,CAAC,YAAa;AAC9C,YAAM,WAAW,sBAAsB,KAAK;AAC5C,UAAI,SAAU,OAAM,SAAS,UAAU,QAAQ;AAAA,IACjD,CAAC,EACA,MAAM,MAAM;AAAA,IAGb,CAAC,EACA,QAAQ,MAAM;AACb,eAAS,OAAO,QAAQ;AACxB,UA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