@8wave/ai-elements 0.125.0-beta.40 → 0.125.0-beta.42

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.
Files changed (161) hide show
  1. package/dist/_chunks/{Agent-CeZ3bgZ3.js → Agent-DMvYDpLa.js} +123 -122
  2. package/dist/_chunks/Agent-DMvYDpLa.js.map +1 -0
  3. package/dist/_chunks/{PkFilePreview-D_1ZgiiA.js → PkFilePreview-DC4iX7Yc.js} +234 -209
  4. package/dist/_chunks/PkFilePreview-DC4iX7Yc.js.map +1 -0
  5. package/dist/_chunks/{PkFilePreviewDialog-CI22huzK.js → PkFilePreviewDialog-bcTkTcYk.js} +12 -7
  6. package/dist/_chunks/PkFilePreviewDialog-bcTkTcYk.js.map +1 -0
  7. package/dist/_chunks/{PkImageEditorDialog-CAEninFi.js → PkImageEditorDialog-FpbyhV3t.js} +2 -2
  8. package/dist/_chunks/{PkImageEditorDialog-CAEninFi.js.map → PkImageEditorDialog-FpbyhV3t.js.map} +1 -1
  9. package/dist/_chunks/{PkSelectionActions-BriGyWCi.js → PkSelectionActions-BbfVZY0R.js} +140 -13
  10. package/dist/_chunks/PkSelectionActions-BbfVZY0R.js.map +1 -0
  11. package/dist/_chunks/{PkStreamingMarkdown--9i0feuM.js → PkStreamingMarkdown-COSOOhCg.js} +3 -3
  12. package/dist/_chunks/{PkStreamingMarkdown--9i0feuM.js.map → PkStreamingMarkdown-COSOOhCg.js.map} +1 -1
  13. package/dist/_chunks/{PkToolChatFile-BKGUnWrj.js → PkToolChatFile-C_gS0X1j.js} +3 -3
  14. package/dist/_chunks/{PkToolChatFile-BKGUnWrj.js.map → PkToolChatFile-C_gS0X1j.js.map} +1 -1
  15. package/dist/_chunks/{PkToolRequestGeolocation-DktrQJvA.js → PkToolRequestGeolocation-CwDQnr7u.js} +2 -2
  16. package/dist/_chunks/{PkToolRequestGeolocation-DktrQJvA.js.map → PkToolRequestGeolocation-CwDQnr7u.js.map} +1 -1
  17. package/dist/_chunks/{PkToolRequestOAuthConnection-DkcLwFWl.js → PkToolRequestOAuthConnection-DkrnVowp.js} +2 -2
  18. package/dist/_chunks/{PkToolRequestOAuthConnection-DkcLwFWl.js.map → PkToolRequestOAuthConnection-DkrnVowp.js.map} +1 -1
  19. package/dist/_chunks/{PkToolShowArtifact-BfLpz2-W.js → PkToolShowArtifact-fpFtKrZo.js} +2 -2
  20. package/dist/_chunks/{PkToolShowArtifact-BfLpz2-W.js.map → PkToolShowArtifact-fpFtKrZo.js.map} +1 -1
  21. package/dist/_chunks/{PkToolShowContactForm-BsF6DFzV.js → PkToolShowContactForm-BAM772bm.js} +2 -2
  22. package/dist/_chunks/{PkToolShowContactForm-BsF6DFzV.js.map → PkToolShowContactForm-BAM772bm.js.map} +1 -1
  23. package/dist/_chunks/{PkToolShowForm-w6RvbKEB.js → PkToolShowForm-DJcL0bgw.js} +4 -4
  24. package/dist/_chunks/{PkToolShowForm-w6RvbKEB.js.map → PkToolShowForm-DJcL0bgw.js.map} +1 -1
  25. package/dist/_chunks/{PkToolShowImageGallery-BEddh4He.js → PkToolShowImageGallery-DhB_ucYe.js} +2 -2
  26. package/dist/_chunks/{PkToolShowImageGallery-BEddh4He.js.map → PkToolShowImageGallery-DhB_ucYe.js.map} +1 -1
  27. package/dist/_chunks/{PkToolShowProductList-k-VB4pUB.js → PkToolShowProductList-DfcJJrOC.js} +2 -2
  28. package/dist/_chunks/{PkToolShowProductList-k-VB4pUB.js.map → PkToolShowProductList-DfcJJrOC.js.map} +1 -1
  29. package/dist/_chunks/{PkToolShowSources-CGESvGrm.js → PkToolShowSources-GeWAMHYC.js} +3 -3
  30. package/dist/_chunks/{PkToolShowSources-CGESvGrm.js.map → PkToolShowSources-GeWAMHYC.js.map} +1 -1
  31. package/dist/_chunks/{PkToolShowSuggestedReply-DTAq41wP.js → PkToolShowSuggestedReply-gpuWzpoh.js} +2 -2
  32. package/dist/_chunks/{PkToolShowSuggestedReply-DTAq41wP.js.map → PkToolShowSuggestedReply-gpuWzpoh.js.map} +1 -1
  33. package/dist/_chunks/{PkToolShowVideo-DeexblEL.js → PkToolShowVideo-CikqhGpT.js} +2 -2
  34. package/dist/_chunks/{PkToolShowVideo-DeexblEL.js.map → PkToolShowVideo-CikqhGpT.js.map} +1 -1
  35. package/dist/_chunks/{PkToolShowWebPages-C42FNo8K.js → PkToolShowWebPages-B-LuiAtg.js} +2 -2
  36. package/dist/_chunks/{PkToolShowWebPages-C42FNo8K.js.map → PkToolShowWebPages-B-LuiAtg.js.map} +1 -1
  37. package/dist/_chunks/{chatImagePolicy-DlZPHhW-.js → chatImagePolicy-Dv_WHhDs.js} +2 -2
  38. package/dist/_chunks/{chatImagePolicy-DlZPHhW-.js.map → chatImagePolicy-Dv_WHhDs.js.map} +1 -1
  39. package/dist/_chunks/{markdown-DNPhTO5l.js → markdown-BYpvcbWH.js} +2 -2
  40. package/dist/_chunks/{markdown-DNPhTO5l.js.map → markdown-BYpvcbWH.js.map} +1 -1
  41. package/dist/_chunks/{utils-zkq8kMz-.js → utils-DMvy5QRR.js} +2 -2
  42. package/dist/_chunks/{utils-zkq8kMz-.js.map → utils-DMvy5QRR.js.map} +1 -1
  43. package/dist/ai-elements.es.js +405 -135
  44. package/dist/ai-elements.es.js.map +1 -1
  45. package/dist-vue/PkChatbot.js +1 -1
  46. package/dist-vue/PkChatbotEmptyState.js +1 -1
  47. package/dist-vue/PkChatbotInput.js +1 -1
  48. package/dist-vue/PkChatbotMessages.js +1 -1
  49. package/dist-vue/PkChatbotStepPayload.js +1 -1
  50. package/dist-vue/PkChatbotStepToolDetail.js +1 -1
  51. package/dist-vue/PkChatbotSteps.js +1 -1
  52. package/dist-vue/PkChatbotViewChat.js +1 -1
  53. package/dist-vue/PkChatbotViewConversations.js +1 -1
  54. package/dist-vue/PkChatbotViewFiles.js +1 -1
  55. package/dist-vue/PkChatbotViewProfile.js +1 -1
  56. package/dist-vue/_chunks/{Agent-ldDZiq6E.js → Agent-B9iJ1WvR.js} +131 -130
  57. package/dist-vue/_chunks/Agent-B9iJ1WvR.js.map +1 -0
  58. package/dist-vue/_chunks/{Document-BfjAfogy.js → Document-DnsOE7s6.js} +2 -2
  59. package/dist-vue/_chunks/{Document-BfjAfogy.js.map → Document-DnsOE7s6.js.map} +1 -1
  60. package/dist-vue/_chunks/{PkChart-DyyBXkd3.js → PkChart-D-K7nc0g.js} +2 -2
  61. package/dist-vue/_chunks/{PkChart-DyyBXkd3.js.map → PkChart-D-K7nc0g.js.map} +1 -1
  62. package/dist-vue/_chunks/{PkChatbot-wsqj3EpU.js → PkChatbot-DVQ-Bb7n.js} +8 -8
  63. package/dist-vue/_chunks/{PkChatbot-wsqj3EpU.js.map → PkChatbot-DVQ-Bb7n.js.map} +1 -1
  64. package/dist-vue/_chunks/{PkChatbotEmptyState-DcgIfNkX.js → PkChatbotEmptyState-OlgewA4_.js} +2 -2
  65. package/dist-vue/_chunks/{PkChatbotEmptyState-DcgIfNkX.js.map → PkChatbotEmptyState-OlgewA4_.js.map} +1 -1
  66. package/dist-vue/_chunks/{PkChatbotInput-CN4rmNgu.js → PkChatbotInput-D_I0Gf_u.js} +4 -4
  67. package/dist-vue/_chunks/{PkChatbotInput-CN4rmNgu.js.map → PkChatbotInput-D_I0Gf_u.js.map} +1 -1
  68. package/dist-vue/_chunks/{PkChatbotMessages-BlF4Xp0_.js → PkChatbotMessages-CAXnEfXK.js} +18 -18
  69. package/dist-vue/_chunks/{PkChatbotMessages-BlF4Xp0_.js.map → PkChatbotMessages-CAXnEfXK.js.map} +1 -1
  70. package/dist-vue/_chunks/{PkChatbotStepPayload-q9uXE5mr.js → PkChatbotStepPayload-EBri1L10.js} +2 -2
  71. package/dist-vue/_chunks/{PkChatbotStepPayload-q9uXE5mr.js.map → PkChatbotStepPayload-EBri1L10.js.map} +1 -1
  72. package/dist-vue/_chunks/{PkChatbotStepToolDetail-BJz6Qwh3.js → PkChatbotStepToolDetail-DiQEa0UV.js} +3 -3
  73. package/dist-vue/_chunks/{PkChatbotStepToolDetail-BJz6Qwh3.js.map → PkChatbotStepToolDetail-DiQEa0UV.js.map} +1 -1
  74. package/dist-vue/_chunks/{PkChatbotSteps-DvJYNl_k.js → PkChatbotSteps-BgLnv2J1.js} +5 -5
  75. package/dist-vue/_chunks/{PkChatbotSteps-DvJYNl_k.js.map → PkChatbotSteps-BgLnv2J1.js.map} +1 -1
  76. package/dist-vue/_chunks/{PkChatbotViewChat-tmHyxxT3.js → PkChatbotViewChat-CmjD1IXf.js} +360 -355
  77. package/dist-vue/_chunks/PkChatbotViewChat-CmjD1IXf.js.map +1 -0
  78. package/dist-vue/_chunks/{PkChatbotViewConversations-DOzUh_A7.js → PkChatbotViewConversations-CVZH5dXx.js} +3 -3
  79. package/dist-vue/_chunks/{PkChatbotViewConversations-DOzUh_A7.js.map → PkChatbotViewConversations-CVZH5dXx.js.map} +1 -1
  80. package/dist-vue/_chunks/{PkChatbotViewFiles-CsL8OhcA.js → PkChatbotViewFiles-CO4gv9nd.js} +3 -3
  81. package/dist-vue/_chunks/{PkChatbotViewFiles-CsL8OhcA.js.map → PkChatbotViewFiles-CO4gv9nd.js.map} +1 -1
  82. package/dist-vue/_chunks/{PkChatbotViewProfile-CFqxCK2f.js → PkChatbotViewProfile-CriJtak0.js} +2 -2
  83. package/dist-vue/_chunks/{PkChatbotViewProfile-CFqxCK2f.js.map → PkChatbotViewProfile-CriJtak0.js.map} +1 -1
  84. package/dist-vue/_chunks/{PkFilePreview-Bp5-Pl54.js → PkFilePreview-k5gEl3n8.js} +586 -434
  85. package/dist-vue/_chunks/PkFilePreview-k5gEl3n8.js.map +1 -0
  86. package/dist-vue/_chunks/{PkFilePreviewDialog-CS885vBR.js → PkFilePreviewDialog-DUwZPErE.js} +12 -7
  87. package/dist-vue/_chunks/PkFilePreviewDialog-DUwZPErE.js.map +1 -0
  88. package/dist-vue/_chunks/{PkImageEditorDialog-BhfdnsmX.js → PkImageEditorDialog-DQPXePae.js} +2 -2
  89. package/dist-vue/_chunks/{PkImageEditorDialog-BhfdnsmX.js.map → PkImageEditorDialog-DQPXePae.js.map} +1 -1
  90. package/dist-vue/_chunks/{PkStreamingMarkdown-NgrJUZPI.js → PkStreamingMarkdown-ZasabxE0.js} +3 -3
  91. package/dist-vue/_chunks/{PkStreamingMarkdown-NgrJUZPI.js.map → PkStreamingMarkdown-ZasabxE0.js.map} +1 -1
  92. package/dist-vue/_chunks/{PkToolChatFile-DnmiNGF4.js → PkToolChatFile-CD26Q2xp.js} +3 -3
  93. package/dist-vue/_chunks/{PkToolChatFile-DnmiNGF4.js.map → PkToolChatFile-CD26Q2xp.js.map} +1 -1
  94. package/dist-vue/_chunks/{PkToolRequestGeolocation-D1XNCvdr.js → PkToolRequestGeolocation-Bhh7UomV.js} +2 -2
  95. package/dist-vue/_chunks/{PkToolRequestGeolocation-D1XNCvdr.js.map → PkToolRequestGeolocation-Bhh7UomV.js.map} +1 -1
  96. package/dist-vue/_chunks/{PkToolRequestOAuthConnection-OTvMRYaL.js → PkToolRequestOAuthConnection-8GJlt5G1.js} +2 -2
  97. package/dist-vue/_chunks/{PkToolRequestOAuthConnection-OTvMRYaL.js.map → PkToolRequestOAuthConnection-8GJlt5G1.js.map} +1 -1
  98. package/dist-vue/_chunks/{PkToolShowArtifact-C8ueuIGQ.js → PkToolShowArtifact-BhVd_ZQ8.js} +2 -2
  99. package/dist-vue/_chunks/{PkToolShowArtifact-C8ueuIGQ.js.map → PkToolShowArtifact-BhVd_ZQ8.js.map} +1 -1
  100. package/dist-vue/_chunks/{PkToolShowChart-BWO6Hzlq.js → PkToolShowChart-BQXxaPIO.js} +3 -3
  101. package/dist-vue/_chunks/{PkToolShowChart-BWO6Hzlq.js.map → PkToolShowChart-BQXxaPIO.js.map} +1 -1
  102. package/dist-vue/_chunks/{PkToolShowContactForm-BBcDsLEO.js → PkToolShowContactForm-CackCDGD.js} +2 -2
  103. package/dist-vue/_chunks/{PkToolShowContactForm-BBcDsLEO.js.map → PkToolShowContactForm-CackCDGD.js.map} +1 -1
  104. package/dist-vue/_chunks/{PkToolShowDiagram-BzUcxOKy.js → PkToolShowDiagram-CABPsFi8.js} +2 -2
  105. package/dist-vue/_chunks/{PkToolShowDiagram-BzUcxOKy.js.map → PkToolShowDiagram-CABPsFi8.js.map} +1 -1
  106. package/dist-vue/_chunks/{PkToolShowForm-B6uhHzJ8.js → PkToolShowForm-BStbk4Iu.js} +4 -4
  107. package/dist-vue/_chunks/{PkToolShowForm-B6uhHzJ8.js.map → PkToolShowForm-BStbk4Iu.js.map} +1 -1
  108. package/dist-vue/_chunks/{PkToolShowImageGallery-C39nlJrJ.js → PkToolShowImageGallery-BeeHsdTp.js} +2 -2
  109. package/dist-vue/_chunks/{PkToolShowImageGallery-C39nlJrJ.js.map → PkToolShowImageGallery-BeeHsdTp.js.map} +1 -1
  110. package/dist-vue/_chunks/{PkToolShowProductList-FLLkRCnm.js → PkToolShowProductList-BfUiap9U.js} +2 -2
  111. package/dist-vue/_chunks/{PkToolShowProductList-FLLkRCnm.js.map → PkToolShowProductList-BfUiap9U.js.map} +1 -1
  112. package/dist-vue/_chunks/{PkToolShowSources-Cb7r5jrX.js → PkToolShowSources-CgEkcyRg.js} +3 -3
  113. package/dist-vue/_chunks/{PkToolShowSources-Cb7r5jrX.js.map → PkToolShowSources-CgEkcyRg.js.map} +1 -1
  114. package/dist-vue/_chunks/{PkToolShowSuggestedReply-BVLCX5Sm.js → PkToolShowSuggestedReply-DxlGhMvE.js} +2 -2
  115. package/dist-vue/_chunks/{PkToolShowSuggestedReply-BVLCX5Sm.js.map → PkToolShowSuggestedReply-DxlGhMvE.js.map} +1 -1
  116. package/dist-vue/_chunks/{PkToolShowVideo-QDLhVlau.js → PkToolShowVideo-CqSRnDNC.js} +2 -2
  117. package/dist-vue/_chunks/{PkToolShowVideo-QDLhVlau.js.map → PkToolShowVideo-CqSRnDNC.js.map} +1 -1
  118. package/dist-vue/_chunks/{PkToolShowWebPages-P6PdJTEE.js → PkToolShowWebPages-B-qIS8qY.js} +2 -2
  119. package/dist-vue/_chunks/{PkToolShowWebPages-P6PdJTEE.js.map → PkToolShowWebPages-B-qIS8qY.js.map} +1 -1
  120. package/dist-vue/_chunks/{createChatbotApiClient-CGeNprai.js → createChatbotApiClient-DmPcjwB3.js} +7 -7
  121. package/dist-vue/_chunks/{createChatbotApiClient-CGeNprai.js.map → createChatbotApiClient-DmPcjwB3.js.map} +1 -1
  122. package/dist-vue/_chunks/{useChatbotStore-KXAltGz3.js → useChatbotStore-B6ILfm5Z.js} +17 -17
  123. package/dist-vue/_chunks/{useChatbotStore-KXAltGz3.js.map → useChatbotStore-B6ILfm5Z.js.map} +1 -1
  124. package/dist-vue/_chunks/{utils-D4B1FVGF.js → utils-KBB6SDPn.js} +2 -2
  125. package/dist-vue/_chunks/{utils-D4B1FVGF.js.map → utils-KBB6SDPn.js.map} +1 -1
  126. package/dist-vue/api.js +1 -1
  127. package/dist-vue/apps/web-component/src/composables/useChatbotAgent.d.ts +6 -0
  128. package/dist-vue/composables.js +270 -6
  129. package/dist-vue/composables.js.map +1 -1
  130. package/dist-vue/index.js +5325 -5232
  131. package/dist-vue/index.js.map +1 -1
  132. package/dist-vue/locales.js +12 -0
  133. package/dist-vue/packages/components/src/chat/PkAgentSettingsPanel.d.ts +6 -0
  134. package/dist-vue/packages/components/src/chat/PkFilePreview.d.ts +8 -0
  135. package/dist-vue/packages/components/src/chat/PkFilePreviewDialog.d.ts +4 -0
  136. package/dist-vue/packages/components/src/chat/PkSelectionActionIconPicker.d.ts +19 -0
  137. package/dist-vue/packages/components/src/chat/PkSelectionActions.d.ts +3 -0
  138. package/dist-vue/packages/components/src/chat/selectionActionEdits.d.ts +1 -0
  139. package/dist-vue/packages/components/src/chat/selectionActionIcons.d.ts +9 -0
  140. package/dist-vue/packages/components/src/chat/useChatFilePreview.d.ts +12 -12
  141. package/dist-vue/packages/composable/src/chatbot/useChatbotStore.d.ts +18 -0
  142. package/dist-vue/packages/models/src/schema/Agent.d.ts +2688 -0
  143. package/dist-vue/packages/models/src/schema/Chart.d.ts +4 -4
  144. package/dist-vue/packages/models/src/schema/Lead.d.ts +6 -6
  145. package/dist-vue/packages/models/src/schema/ReasoningChat.d.ts +768 -0
  146. package/dist-vue/packages/models/src/schema/SelectionAction.d.ts +1415 -0
  147. package/dist-vue/packages/models/src/schema/SelectionActionPreview.d.ts +38 -0
  148. package/dist-vue/packages/models/src/schema/SpreadsheetPreview.d.ts +6 -6
  149. package/dist-vue/packages/models/src/schema/SubAgent.d.ts +768 -0
  150. package/dist-vue/packages/models/src/schema/WordPreview.d.ts +13 -13
  151. package/dist-vue/packages/models/src/schema/index.d.ts +1 -0
  152. package/dist-vue/style.css +1 -1
  153. package/package.json +1 -1
  154. package/dist/_chunks/Agent-CeZ3bgZ3.js.map +0 -1
  155. package/dist/_chunks/PkFilePreview-D_1ZgiiA.js.map +0 -1
  156. package/dist/_chunks/PkFilePreviewDialog-CI22huzK.js.map +0 -1
  157. package/dist/_chunks/PkSelectionActions-BriGyWCi.js.map +0 -1
  158. package/dist-vue/_chunks/Agent-ldDZiq6E.js.map +0 -1
  159. package/dist-vue/_chunks/PkChatbotViewChat-tmHyxxT3.js.map +0 -1
  160. package/dist-vue/_chunks/PkFilePreview-Bp5-Pl54.js.map +0 -1
  161. package/dist-vue/_chunks/PkFilePreviewDialog-CS885vBR.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"PkChatbotViewChat-tmHyxxT3.js","names":["_hoisted_1","_openBlock","_createElementBlock","_normalizeStyle","_sfc_main","_openBlock","_createElementBlock","_normalizeClass","_createElementVNode","_Fragment","_renderList","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","__unplugin_components_0","_openBlock","_createElementBlock","_normalizeClass","_createVNode","_createBlock","PkVoiceOrb","_createElementVNode","_createCommentVNode","_createTextVNode","_toDisplayString","_unref","_Fragment","PkChatButton","_sfc_main","__unplugin_components_0","_openBlock","_createElementBlock","_normalizeClass","_unref","_createVNode","_Transition","_withCtx","_createBlock","PkChatbotEmptyState","PkChatbotMessages","PkChatbotQueuedMessages","_createCommentVNode","_createElementVNode","PkAuroraCanvas","PkChatbotWakeupBar","_toDisplayString","PkVoiceSession","PkChatbotInput","_isRef","_createSlots","PkAvatar","_Teleport","_sfc_main","PkChatbotMessages_default","chatDropAccepts","provideImageAnnotation","generateId","useChatbotStore","VOICE_LINE_ID_PREFIX","logger","getFilePartMedia","formAnswerAsSpoken","chatFileName","HOST_STEP_CHANGES","HOST_STEP_TITLES","getPartState","resolveGlowTints","useLocalizedString","PkAvatar_default","PkChatButton_default","PkChatbotInput_default","PkChatbotQueuedMessages_default","PkChatbotEmptyState_default","PkChatbotWakeupBar_default","useGreeting","useI18n","computed","resolveNamePlaceholder","toValue","agentInterface","locale","userName","te","t","name","template","_hoisted_1$2","VERTEX_SHADER","FRAGMENT_SHADER","PkAuroraCanvas_default","defineComponent","props","__props","rootEl","useTemplateRef","canvasEl","failed","ref","tints","tintStyle","gl","rafId","resizeObserver","timeLocation","resolutionLocation","centerLocation","halfLocation","spreadLocation","colorLocation","color2Location","duoLocation","startTime","compile","shader","type","source","toUnit","channels","value","applyTints","drawFrame","prefersReducedMotion","resize","dpr","clientWidth","clientHeight","host","canvasRect","sourceRect","scaleX","scaleY","centerX","centerY","halfWidth","halfHeight","spread","timeSeconds","loop","onMounted","canvas","vertex","fragment","program","buffer","positionLocation","nextTick","onBeforeUnmount","onUnmounted","context","openBlock","createElementBlock","normalizeStyle","REST","SMOOTHING","PkVoiceOrb_default","barsEl","heights","frame","readTargets","level","bins","count","now","wave","index","usable","bandSize","total","bin","render","nodes","height","paint","targets","current","stopPainting","watch","state","normalizeClass","createElementVNode","Fragment","renderList","_hoisted_1$1","_hoisted_2$1","_hoisted_3$1","_hoisted_4$1","_hoisted_5$1","_hoisted_6","PkVoiceSession_default","__emit","emit","$t","stateLabel","remainingLabel","minutes","seconds","isRunningOut","isLive","stateTone","_component_VvIcon","VvIcon","createVNode","createBlock","createCommentVNode","createTextVNode","toDisplayString","unref","_cache","useVoiceSession","conversation","shallowRef","status","mode","error","transcript","remainingSeconds","chatId","sessionId","capTimer","generation","disposed","clearCap","startCap","endsAt","maxSessionSeconds","tick","left","stop","releaseGrant","id","options","mine","active","start","isCurrent","ownSessionId","providerModule","grant","conversationStarted","VoiceConversation","next","wasSpeaking","entry","message","details","caught","dismissError","setMuted","muted","sendUserMessage","text","readLevel","channel","readSpectrum","releaseOnPageHide","onScopeDispose","ChatFilePreviewDockKey","provideChatFilePreviewDock","dock","useChatFilePreviewDock","inject","FIRST_LOOK_MS","BACKOFF_MS","WATCH_MAX_MS","PRESENCE_INTERVAL_MS","useWakeupWatch","pendingWakeup","isStopping","timer","isUnmounted","clear","later","run","delayMs","hasTurnOf","wakeId","check","pending","wait","watchTurn","since","step","reset","spokenTurnUnwrittenIn","spokenTurnStarted","spokenTurnsWritten","forgetSpokenTurns","hasQuestions","questions","answering","previous","presenceTimer","sendPresence","onVisibilityChange","MAX_ALIGNED_PAIRS","unmatchedItems","before","after","end","n","m","out","gap","j","j0","j1","i","i0","i1","lengths","withoutIds","key","contentOf","changedCellIds","idsOf","cells","c","was","old","cell","wordChanges","paragraphs","blocks","b","block","cellContents","sheet","preview","spreadsheetChanges","s","changed","at","content","chatFilePreviewChanges","revealFirstChange","el","scroller","selector","box","CHAT_FILE_CHANGES_MS","useChatFilePreview","target","loading","changes","cache","changesTimer","lastOpen","chatGeneration","dropChanges","show","data","open","call","cached","read","close","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","PREVIEW_PANEL_MIN_WIDTH","POLL_LIVE_MS","POLL_ENDED_MIN_MS","POLL_FAILED_MIN_MS","POLL_ENDED_MAX_MS","PkChatbotViewChat_default","PkToolShowForm","defineAsyncComponent","PkToolShowContactForm","PkToolShowSuggestedReply","PkToolShowSources","PkToolRequestGeolocation","PkToolRequestOAuthConnection","PkToolShowLocation","PkToolShowChart","PkToolShowDiagram","PkToolChatFile","PkToolShareDocument","PkFilePreview","PkFilePreviewDialog","store","storedFileUpload","storeToRefs","provide","hostStepTitles","hostStepChanges","inputEl","inputFocusRequest","pagePointer","pointer","pointerChip","agentFileUpload","agentType","takesImages","allowed","isAttachmentLimitReached","file","chatFileDownloadUrl","apiClient","storedFileName","storeHandleSubmit","hostWorking","hostToolsPending","inputStatus","chat","customPageNotice","agentPageAccess","pageNotice","pageNoticeLevel","attachmentNotice","err","fileLimitError","answerNotices","backgroundAnswers","title","dismissableNotice","hasUserMessages","messages","showEmptyState","greeting","chatViewEl","previewDock","previewDocked","previewDockTarget","chatViewWidth","dockWidth","entries","width","previewInPanel","previewFullscreen","previewTarget","previewData","previewLoading","previewError","previewChanges","openFilePreview","closeFilePreview","resetPreview","previewView","openPreview","fileOf","previewExpanded","previewBeside","closePreview","CHAT_FILE_TOOL_PARTS","chatFileVersions","byFile","part","output","versions","fileId","previewVersions","a","showPreviewVersion","version","previewRestorable","chatFileRestore","restoreFromPreview","previewSelectionActions","agentSelectionActions","sendFromPreview","action","handleExpandSourceContext","payload","handleDownloadSource","result","documentId","useDropZone","types","files","isMuted","isAwaitingSpokenAnswer","POLL_ENDED_BACKOFF_MS","pollTimer","callEndedAt","callEndedBadly","endedBackoffStep","isPolling","stopPolling","schedulePoll","runPoll","outcome","refreshMessages","voice","elapsed","delay","pokePoll","callPageTools","appendMessage","failure","isVoiceEnabled","agentVoice","voiceState","voiceErrorText","raw","voiceChannel","sampleVoiceLevel","sampleVoiceSpectrum","startVoice","stopVoice","dismissVoiceError","retryVoice","readToolCallId","answeredOnCall","isAnsweredOnCall","confirmVerdictsOnCall","answerOnCall","spoken","onFormAnswer","answer","addToolOutput","onConfirmRespond","latestFileVersions","latest","chatFileIdsByName","byName","add","filename","isFilePart","isConversationBlocked","twins","onSuggestedReply","reply","onGeolocation","onOAuthConnected","toggleVoiceMute","isStoppingWakeup","stopWakeup","isOverDropZone","Transition","withCtx","revisedAnswers","actions","messageFeedbacks","feedbackDialogMessage","isFeedbackSubmitting","isFeedbackSubmitted","feedbackSubmitError","hostConfirmation","isDark","onFeedbackSubmit","$event","regenerate","startNewChat","onUpvote","onDownvote","onFeedback","addToolApprovalResponse","respondHostConfirmation","baseUrl","isLeadSubmitted","isLoadingSubmitLead","submitLeadError","onLeadSubmit","serverName","lat","lon","query","lang","queuedMessages","editQueuedMessage","removeQueuedMessage","input","isRef","pendingAttachments","inputMessagePlaceholder","canQueue","pagePointerAvailable","pagePointing","confirmationMode","stopGeneration","handleFileSelect","discardPendingAttachment","replacePendingAttachment","retryPendingAttachment","clearFileLimitError","closePageNotice","openBackgroundAnswer","dismissBackgroundAnswer","createSlots","Teleport"],"sources":["../../../../packages/composable/src/chatbot/useGreeting.ts","../../../../packages/components/src/chat/PkAuroraCanvas.vue","../../../../packages/components/src/chat/PkAuroraCanvas.vue","../../../../packages/components/src/chat/PkVoiceOrb.vue","../../../../packages/components/src/chat/PkVoiceOrb.vue","../../../../packages/components/src/chat/PkVoiceSession.vue","../../../../packages/components/src/chat/PkVoiceSession.vue","../../../../packages/components/src/chat/useVoiceSession.ts","../../../../packages/components/src/chat/chatFilePreviewDock.ts","../../../../packages/components/src/chat/useWakeupWatch.ts","../../../../packages/components/src/chat/previewChanges.ts","../../../../packages/components/src/chat/useChatFilePreview.ts","../../../../packages/components/src/chat/PkChatbotViewChat.vue","../../../../packages/components/src/chat/PkChatbotViewChat.vue"],"sourcesContent":["import { computed, toValue } from 'vue'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\nimport { useI18n } from 'vue-i18n'\nimport type { AgentInterface } from 'models'\n\n/**\n * Resolves the greeting shown in the fullscreen empty state.\n *\n * v1 behavior (docs/specs/released/public-chat-page.md): uses the first entry\n * of the `agentInterface.greeting` pool and supports only the `{name}`\n * placeholder. Without one, the default welcome message. The agent's\n * `initialMessage` is not a fallback: it is written as a first reply, and at\n * the size of a heading a long one filled a phone screen.\n * Pool rotation and `{timeGreeting}` are planned follow-ups.\n */\nexport function useGreeting(\n agentInterface: MaybeRefOrGetter<AgentInterface | undefined>,\n userName: MaybeRefOrGetter<string | undefined>,\n): ComputedRef<string> {\n const { locale, t, te } = useI18n({ useScope: 'global' })\n\n return computed(() => {\n const ui = toValue(agentInterface)\n const greeting = resolveNamePlaceholder(\n ui?.greeting?.[0]?.[locale.value] ?? '',\n toValue(userName),\n )\n // A greeting of blanks, or of a {name} with no name to put there,\n // leaves nothing to say: the default says it\n return (\n greeting ||\n (te('message.defaultAgentWelcome')\n ? t('message.defaultAgentWelcome')\n : '')\n )\n })\n}\n\nfunction resolveNamePlaceholder(template: string, name?: string): string {\n const result = name\n ? template.replace(/\\{name\\}/g, name)\n : // No name available: drop the placeholder along with any\n // adjacent punctuation (\", {name}!\" → \"\")\n template.replace(/[,\\s]*\\{name\\}[!?]?/g, '')\n return result.trim()\n}\n","<script setup lang=\"ts\">\n import {\n computed,\n nextTick,\n onBeforeUnmount,\n onMounted,\n onUnmounted,\n ref,\n useTemplateRef,\n watch,\n } from 'vue'\n import { type GlowTints, type RgbChannels, resolveGlowTints } from './utils'\n\n /**\n * Ambient animated \"aurora\" rendered with a raw WebGL fragment shader\n * (simplex noise drifting between the two tints of `resolveGlowTints`).\n * No dependencies; falls back to CSS blobs when WebGL is unavailable.\n * Without `mainColor` the color comes from the CSS cascade: set `color`\n * on the host.\n */\n\n const props = defineProps<{\n /** CSS selector (within the positioned parent) of the element the glow radiates from; defaults to the positioned parent box itself */\n sourceSelector?: string\n /** The agent's main color; without it, the inherited `color` */\n mainColor?: string\n /** One tone or two, as the agent sets them */\n tones?: 'auto' | 'one' | 'two'\n /** The second tone the agent chose; worked out from the first otherwise */\n secondColor?: string\n }>()\n\n const rootEl = useTemplateRef<HTMLElement>('rootEl')\n const canvasEl = useTemplateRef<HTMLCanvasElement>('canvasEl')\n const failed = ref(false)\n const tints = ref<GlowTints | null>(null)\n\n // The CSS fallback draws the same tints, when they could be read\n const tintStyle = computed(() =>\n tints.value\n ? {\n '--pk-aurora-tint': `rgb(${tints.value.first.join(' ')})`,\n '--pk-aurora-tint-2': `rgb(${(tints.value.duo ? tints.value.second : tints.value.first).join(' ')})`,\n }\n : undefined,\n )\n\n const VERTEX_SHADER = `\nattribute vec2 a_position;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n}`\n\n // snoise: 2D simplex noise by Ian McEwan / Stefan Gustavson (MIT)\n const FRAGMENT_SHADER = `\nprecision mediump float;\nuniform vec2 u_resolution;\nuniform float u_time;\nuniform vec3 u_color;\nuniform vec3 u_color2;\nuniform float u_duo;\nuniform vec2 u_center;\nuniform vec2 u_half;\nuniform float u_spread;\n\nvec3 permute(vec3 x) { return mod(((x * 34.0) + 1.0) * x, 289.0); }\n\nfloat snoise(vec2 v) {\n const vec4 C = vec4(0.211324865405187, 0.366025403784439,\n -0.577350269189626, 0.024390243902439);\n vec2 i = floor(v + dot(v, C.yy));\n vec2 x0 = v - i + dot(i, C.xx);\n vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);\n vec4 x12 = x0.xyxy + C.xxzz;\n x12.xy -= i1;\n i = mod(i, 289.0);\n vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0))\n + i.x + vec3(0.0, i1.x, 1.0));\n vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy),\n dot(x12.zw, x12.zw)), 0.0);\n m = m * m;\n m = m * m;\n vec3 x = 2.0 * fract(p * C.www) - 1.0;\n vec3 h = abs(x) - 0.5;\n vec3 ox = floor(x + 0.5);\n vec3 a0 = x - ox;\n m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\n vec3 g;\n g.x = a0.x * x0.x + h.x * x0.y;\n g.yz = a0.yz * x12.xz + h.yz * x12.yw;\n return 130.0 * dot(m, g);\n}\n\nvoid main() {\n vec2 px = gl_FragCoord.xy;\n vec2 rel = px - u_center;\n\n // Ignition: the ellipse lights up expanding from the center on mount\n float intro = smoothstep(0.0, 1.4, u_time);\n\n // Breathing: size and brightness oscillate gently but visibly\n float breath = 1.0\n + 0.12 * sin(u_time * 0.55)\n + 0.06 * snoise(vec2(u_time * 0.1, 3.7));\n float pulse = 1.0 + 0.2 * sin(u_time * 0.55 + 1.3);\n\n // Keep it simple (Gemini-style): one huge soft elliptical glow\n // centered on the pill. Its height follows the pill's, but each half\n // ends inside the canvas: at most the room to that edge over 1.75, so\n // at the widest breath (1.24) the glow there is about 1% of its peak,\n // under one 8-bit step, and the edge fade below finds nothing to cut.\n // Uncapped, a taller pill (a second line, an attachment) or a short\n // canvas left a quarter of the glow or more at the edge, cut straight.\n vec2 radii = vec2(u_half.x * 0.95, u_half.y * 6.5) * u_spread;\n float room = rel.y > 0.0 ? u_resolution.y - u_center.y : u_center.y;\n radii.y = min(radii.y, room / 1.75);\n radii *= breath * mix(0.15, 1.0, intro);\n float r = length(rel / max(radii, vec2(1.0)));\n float glow = exp(-r * r * 2.2);\n\n // Never cut hard against the canvas bounds\n vec2 m = min(px, u_resolution - px);\n glow *= smoothstep(0.0, 32.0, min(m.x, m.y));\n\n // Dither: breaks the 8-bit banding rings of the very soft gradient\n // (no CSS blur on the canvas, the noise must fully mask the bands)\n glow = max(glow + (snoise(px * 0.9) - 0.5) * 0.03, 0.0);\n\n float alpha = glow * 0.2 * pulse * intro;\n\n // Two tones: left to right the glow passes from the first to the\n // second, along a border a slow noise field keeps bending\n vec2 q = rel / max(radii, vec2(1.0));\n float bands = q.x * 0.9\n + 0.7 * snoise(q * 0.8 + vec2(u_time * 0.07, -u_time * 0.05));\n vec3 color = mix(u_color, u_color2, u_duo * smoothstep(-0.6, 0.6, bands));\n\n // Premultiplied alpha (default canvas compositing)\n gl_FragColor = vec4(color * alpha, alpha);\n}`\n\n let gl: WebGLRenderingContext | null = null\n let rafId = 0\n let resizeObserver: ResizeObserver | null = null\n let timeLocation: WebGLUniformLocation | null = null\n let resolutionLocation: WebGLUniformLocation | null = null\n let centerLocation: WebGLUniformLocation | null = null\n let halfLocation: WebGLUniformLocation | null = null\n let spreadLocation: WebGLUniformLocation | null = null\n let colorLocation: WebGLUniformLocation | null = null\n let color2Location: WebGLUniformLocation | null = null\n let duoLocation: WebGLUniformLocation | null = null\n const startTime = performance.now()\n\n const compile = (type: number, source: string): WebGLShader | null => {\n if (!gl) {\n return null\n }\n const shader = gl.createShader(type)\n if (!shader) {\n return null\n }\n gl.shaderSource(shader, source)\n gl.compileShader(shader)\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n return null\n }\n return shader\n }\n\n const toUnit = (channels: RgbChannels) =>\n channels.map((value) => value / 255) as [number, number, number]\n\n // Reads the tints where the glow sits and hands them to the shader (the\n // CSS fallback reads them from `tintStyle`)\n const applyTints = () => {\n if (!rootEl.value) {\n return\n }\n tints.value = resolveGlowTints(rootEl.value, {\n mainColor: props.mainColor,\n tones: props.tones,\n secondColor: props.secondColor,\n })\n if (!gl || failed.value || !tints.value) {\n return\n }\n gl.uniform3f(colorLocation, ...toUnit(tints.value.first))\n gl.uniform3f(color2Location, ...toUnit(tints.value.second))\n gl.uniform1f(duoLocation, tints.value.duo ? 1 : 0)\n drawFrame(prefersReducedMotion() ? 10 : undefined)\n }\n\n // The settings panel changes them while the preview shows the glow\n watch(\n [() => props.mainColor, () => props.tones, () => props.secondColor],\n applyTints,\n )\n\n const resize = () => {\n if (!gl || !canvasEl.value) {\n return\n }\n // The glow is blurred anyway: cap the DPR to keep the GPU cost low\n const dpr = Math.min(window.devicePixelRatio || 1, 1.5)\n const { clientWidth, clientHeight } = canvasEl.value\n canvasEl.value.width = Math.max(1, Math.round(clientWidth * dpr))\n canvasEl.value.height = Math.max(1, Math.round(clientHeight * dpr))\n gl.viewport(0, 0, canvasEl.value.width, canvasEl.value.height)\n\n // The glow radiates from the source element (by selector within the\n // positioned parent, or the parent box itself): measure it into\n // shader pixel coordinates (gl origin is bottom-left)\n const host = canvasEl.value.parentElement?.offsetParent\n const source =\n (props.sourceSelector\n ? host?.querySelector(props.sourceSelector)\n : host) ?? host\n const canvasRect = canvasEl.value.getBoundingClientRect()\n const sourceRect = source?.getBoundingClientRect()\n if (sourceRect && canvasRect.width > 0) {\n const scaleX = canvasEl.value.width / canvasRect.width\n const scaleY = canvasEl.value.height / canvasRect.height\n const centerX =\n (sourceRect.left + sourceRect.width / 2 - canvasRect.left) *\n scaleX\n const centerY =\n (canvasRect.bottom - (sourceRect.top + sourceRect.height / 2)) *\n scaleY\n const halfWidth = (sourceRect.width / 2) * scaleX\n const halfHeight = (sourceRect.height / 2) * scaleY\n gl.uniform2f(centerLocation, centerX, centerY)\n gl.uniform2f(halfLocation, halfWidth, halfHeight)\n // Optional responsive boost of the glow size (e.g. mobile)\n const spread = Number.parseFloat(\n getComputedStyle(canvasEl.value).getPropertyValue(\n '--aurora-spread',\n ),\n )\n gl.uniform1f(spreadLocation, Number.isNaN(spread) ? 1 : spread)\n }\n\n // Redraw before the next paint: setting the canvas size reallocates\n // the drawing buffer, and presenting it undrawn can flash as an\n // uninitialized (white) frame. With reduced motion (no loop) this\n // also keeps the settled static frame across resizes.\n drawFrame(prefersReducedMotion() ? 10 : undefined)\n }\n\n const prefersReducedMotion = () =>\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\n const drawFrame = (timeSeconds?: number) => {\n if (!gl || !canvasEl.value) {\n return\n }\n gl.uniform1f(\n timeLocation,\n timeSeconds ?? (performance.now() - startTime) / 1000,\n )\n gl.uniform2f(\n resolutionLocation,\n canvasEl.value.width,\n canvasEl.value.height,\n )\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)\n }\n\n const loop = () => {\n drawFrame()\n rafId = requestAnimationFrame(loop)\n }\n\n onMounted(() => {\n const canvas = canvasEl.value\n // No context yet: this only reads the tints, the shader gets them\n // once the program is linked\n applyTints()\n gl = canvas?.getContext('webgl', { alpha: true }) ?? null\n if (!canvas || !gl || !tints.value) {\n failed.value = true\n return\n }\n\n const vertex = compile(gl.VERTEX_SHADER, VERTEX_SHADER)\n const fragment = compile(gl.FRAGMENT_SHADER, FRAGMENT_SHADER)\n const program = gl.createProgram()\n if (!vertex || !fragment || !program) {\n failed.value = true\n return\n }\n gl.attachShader(program, vertex)\n gl.attachShader(program, fragment)\n gl.linkProgram(program)\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n failed.value = true\n return\n }\n gl.useProgram(program)\n\n // Fullscreen quad\n const buffer = gl.createBuffer()\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),\n gl.STATIC_DRAW,\n )\n const positionLocation = gl.getAttribLocation(program, 'a_position')\n gl.enableVertexAttribArray(positionLocation)\n gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)\n\n timeLocation = gl.getUniformLocation(program, 'u_time')\n resolutionLocation = gl.getUniformLocation(program, 'u_resolution')\n centerLocation = gl.getUniformLocation(program, 'u_center')\n halfLocation = gl.getUniformLocation(program, 'u_half')\n spreadLocation = gl.getUniformLocation(program, 'u_spread')\n colorLocation = gl.getUniformLocation(program, 'u_color')\n color2Location = gl.getUniformLocation(program, 'u_color2')\n duoLocation = gl.getUniformLocation(program, 'u_duo')\n applyTints()\n\n resizeObserver = new ResizeObserver(resize)\n resizeObserver.observe(canvas)\n resize()\n // And again once the rest of the tree exists: the source is usually a\n // sibling rendered after this canvas, so the measure above ran while\n // the selector still matched nothing and silently fell back to the\n // parent box.\n void nextTick(resize)\n\n if (prefersReducedMotion()) {\n // Static frame: the color stays, the motion goes\n drawFrame(10)\n return\n }\n loop()\n })\n\n onBeforeUnmount(() => {\n cancelAnimationFrame(rafId)\n resizeObserver?.disconnect()\n })\n\n // Release the context (Chrome caps live WebGL contexts per page) only\n // after the compositor committed the removal: dropping the backing\n // buffer while the last frame is still on screen paints an undefined\n // (white) frame — a visible flash on the dark theme\n onUnmounted(() => {\n const context = gl\n gl = null\n setTimeout(() => {\n context?.getExtension('WEBGL_lose_context')?.loseContext()\n }, 150)\n })\n</script>\n\n<template>\n <div ref=\"rootEl\" class=\"pk-aurora\" aria-hidden=\"true\" :style=\"tintStyle\">\n <canvas v-if=\"!failed\" ref=\"canvasEl\" class=\"pk-aurora__canvas\" />\n <div v-else class=\"pk-aurora__fallback\" />\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-aurora {\n position: absolute;\n inset: 0;\n\n // Where the tints start from when no `mainColor` is given, and what\n // the fallback draws when they could not be read\n color: var(--chat-page-accent, var(--color-brand));\n pointer-events: none;\n\n &__canvas {\n width: 100%;\n height: 100%;\n\n // No CSS filter on purpose: a filtered accelerated canvas gets\n // its own compositor surface, which Chrome can present\n // uninitialized (a white flash) when the layer is created or\n // torn down. The glow is smoothed in the shader instead.\n }\n\n // CSS blobs when WebGL is unavailable\n &__fallback {\n position: absolute;\n inset: 0;\n background:\n radial-gradient(\n 45% 65% at 32% 38%,\n color-mix(\n in srgb,\n var(--pk-aurora-tint, currentcolor) 26%,\n transparent\n ),\n transparent 70%\n ),\n radial-gradient(\n 40% 55% at 68% 62%,\n color-mix(\n in srgb,\n var(--pk-aurora-tint-2, currentcolor) 16%,\n transparent\n ),\n transparent 70%\n );\n filter: blur(48px);\n animation: pk-aurora-drift 14s var(--ease-in-out) infinite alternate;\n\n @media (prefers-reduced-motion: reduce) {\n animation: none;\n }\n }\n }\n\n @keyframes pk-aurora-drift {\n from {\n transform: rotate(-10deg) scale(1);\n }\n\n to {\n transform: rotate(10deg) scale(1.2);\n }\n }\n</style>\n","<script setup lang=\"ts\">\n import {\n computed,\n nextTick,\n onBeforeUnmount,\n onMounted,\n onUnmounted,\n ref,\n useTemplateRef,\n watch,\n } from 'vue'\n import { type GlowTints, type RgbChannels, resolveGlowTints } from './utils'\n\n /**\n * Ambient animated \"aurora\" rendered with a raw WebGL fragment shader\n * (simplex noise drifting between the two tints of `resolveGlowTints`).\n * No dependencies; falls back to CSS blobs when WebGL is unavailable.\n * Without `mainColor` the color comes from the CSS cascade: set `color`\n * on the host.\n */\n\n const props = defineProps<{\n /** CSS selector (within the positioned parent) of the element the glow radiates from; defaults to the positioned parent box itself */\n sourceSelector?: string\n /** The agent's main color; without it, the inherited `color` */\n mainColor?: string\n /** One tone or two, as the agent sets them */\n tones?: 'auto' | 'one' | 'two'\n /** The second tone the agent chose; worked out from the first otherwise */\n secondColor?: string\n }>()\n\n const rootEl = useTemplateRef<HTMLElement>('rootEl')\n const canvasEl = useTemplateRef<HTMLCanvasElement>('canvasEl')\n const failed = ref(false)\n const tints = ref<GlowTints | null>(null)\n\n // The CSS fallback draws the same tints, when they could be read\n const tintStyle = computed(() =>\n tints.value\n ? {\n '--pk-aurora-tint': `rgb(${tints.value.first.join(' ')})`,\n '--pk-aurora-tint-2': `rgb(${(tints.value.duo ? tints.value.second : tints.value.first).join(' ')})`,\n }\n : undefined,\n )\n\n const VERTEX_SHADER = `\nattribute vec2 a_position;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n}`\n\n // snoise: 2D simplex noise by Ian McEwan / Stefan Gustavson (MIT)\n const FRAGMENT_SHADER = `\nprecision mediump float;\nuniform vec2 u_resolution;\nuniform float u_time;\nuniform vec3 u_color;\nuniform vec3 u_color2;\nuniform float u_duo;\nuniform vec2 u_center;\nuniform vec2 u_half;\nuniform float u_spread;\n\nvec3 permute(vec3 x) { return mod(((x * 34.0) + 1.0) * x, 289.0); }\n\nfloat snoise(vec2 v) {\n const vec4 C = vec4(0.211324865405187, 0.366025403784439,\n -0.577350269189626, 0.024390243902439);\n vec2 i = floor(v + dot(v, C.yy));\n vec2 x0 = v - i + dot(i, C.xx);\n vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);\n vec4 x12 = x0.xyxy + C.xxzz;\n x12.xy -= i1;\n i = mod(i, 289.0);\n vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0))\n + i.x + vec3(0.0, i1.x, 1.0));\n vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy),\n dot(x12.zw, x12.zw)), 0.0);\n m = m * m;\n m = m * m;\n vec3 x = 2.0 * fract(p * C.www) - 1.0;\n vec3 h = abs(x) - 0.5;\n vec3 ox = floor(x + 0.5);\n vec3 a0 = x - ox;\n m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\n vec3 g;\n g.x = a0.x * x0.x + h.x * x0.y;\n g.yz = a0.yz * x12.xz + h.yz * x12.yw;\n return 130.0 * dot(m, g);\n}\n\nvoid main() {\n vec2 px = gl_FragCoord.xy;\n vec2 rel = px - u_center;\n\n // Ignition: the ellipse lights up expanding from the center on mount\n float intro = smoothstep(0.0, 1.4, u_time);\n\n // Breathing: size and brightness oscillate gently but visibly\n float breath = 1.0\n + 0.12 * sin(u_time * 0.55)\n + 0.06 * snoise(vec2(u_time * 0.1, 3.7));\n float pulse = 1.0 + 0.2 * sin(u_time * 0.55 + 1.3);\n\n // Keep it simple (Gemini-style): one huge soft elliptical glow\n // centered on the pill. Its height follows the pill's, but each half\n // ends inside the canvas: at most the room to that edge over 1.75, so\n // at the widest breath (1.24) the glow there is about 1% of its peak,\n // under one 8-bit step, and the edge fade below finds nothing to cut.\n // Uncapped, a taller pill (a second line, an attachment) or a short\n // canvas left a quarter of the glow or more at the edge, cut straight.\n vec2 radii = vec2(u_half.x * 0.95, u_half.y * 6.5) * u_spread;\n float room = rel.y > 0.0 ? u_resolution.y - u_center.y : u_center.y;\n radii.y = min(radii.y, room / 1.75);\n radii *= breath * mix(0.15, 1.0, intro);\n float r = length(rel / max(radii, vec2(1.0)));\n float glow = exp(-r * r * 2.2);\n\n // Never cut hard against the canvas bounds\n vec2 m = min(px, u_resolution - px);\n glow *= smoothstep(0.0, 32.0, min(m.x, m.y));\n\n // Dither: breaks the 8-bit banding rings of the very soft gradient\n // (no CSS blur on the canvas, the noise must fully mask the bands)\n glow = max(glow + (snoise(px * 0.9) - 0.5) * 0.03, 0.0);\n\n float alpha = glow * 0.2 * pulse * intro;\n\n // Two tones: left to right the glow passes from the first to the\n // second, along a border a slow noise field keeps bending\n vec2 q = rel / max(radii, vec2(1.0));\n float bands = q.x * 0.9\n + 0.7 * snoise(q * 0.8 + vec2(u_time * 0.07, -u_time * 0.05));\n vec3 color = mix(u_color, u_color2, u_duo * smoothstep(-0.6, 0.6, bands));\n\n // Premultiplied alpha (default canvas compositing)\n gl_FragColor = vec4(color * alpha, alpha);\n}`\n\n let gl: WebGLRenderingContext | null = null\n let rafId = 0\n let resizeObserver: ResizeObserver | null = null\n let timeLocation: WebGLUniformLocation | null = null\n let resolutionLocation: WebGLUniformLocation | null = null\n let centerLocation: WebGLUniformLocation | null = null\n let halfLocation: WebGLUniformLocation | null = null\n let spreadLocation: WebGLUniformLocation | null = null\n let colorLocation: WebGLUniformLocation | null = null\n let color2Location: WebGLUniformLocation | null = null\n let duoLocation: WebGLUniformLocation | null = null\n const startTime = performance.now()\n\n const compile = (type: number, source: string): WebGLShader | null => {\n if (!gl) {\n return null\n }\n const shader = gl.createShader(type)\n if (!shader) {\n return null\n }\n gl.shaderSource(shader, source)\n gl.compileShader(shader)\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n return null\n }\n return shader\n }\n\n const toUnit = (channels: RgbChannels) =>\n channels.map((value) => value / 255) as [number, number, number]\n\n // Reads the tints where the glow sits and hands them to the shader (the\n // CSS fallback reads them from `tintStyle`)\n const applyTints = () => {\n if (!rootEl.value) {\n return\n }\n tints.value = resolveGlowTints(rootEl.value, {\n mainColor: props.mainColor,\n tones: props.tones,\n secondColor: props.secondColor,\n })\n if (!gl || failed.value || !tints.value) {\n return\n }\n gl.uniform3f(colorLocation, ...toUnit(tints.value.first))\n gl.uniform3f(color2Location, ...toUnit(tints.value.second))\n gl.uniform1f(duoLocation, tints.value.duo ? 1 : 0)\n drawFrame(prefersReducedMotion() ? 10 : undefined)\n }\n\n // The settings panel changes them while the preview shows the glow\n watch(\n [() => props.mainColor, () => props.tones, () => props.secondColor],\n applyTints,\n )\n\n const resize = () => {\n if (!gl || !canvasEl.value) {\n return\n }\n // The glow is blurred anyway: cap the DPR to keep the GPU cost low\n const dpr = Math.min(window.devicePixelRatio || 1, 1.5)\n const { clientWidth, clientHeight } = canvasEl.value\n canvasEl.value.width = Math.max(1, Math.round(clientWidth * dpr))\n canvasEl.value.height = Math.max(1, Math.round(clientHeight * dpr))\n gl.viewport(0, 0, canvasEl.value.width, canvasEl.value.height)\n\n // The glow radiates from the source element (by selector within the\n // positioned parent, or the parent box itself): measure it into\n // shader pixel coordinates (gl origin is bottom-left)\n const host = canvasEl.value.parentElement?.offsetParent\n const source =\n (props.sourceSelector\n ? host?.querySelector(props.sourceSelector)\n : host) ?? host\n const canvasRect = canvasEl.value.getBoundingClientRect()\n const sourceRect = source?.getBoundingClientRect()\n if (sourceRect && canvasRect.width > 0) {\n const scaleX = canvasEl.value.width / canvasRect.width\n const scaleY = canvasEl.value.height / canvasRect.height\n const centerX =\n (sourceRect.left + sourceRect.width / 2 - canvasRect.left) *\n scaleX\n const centerY =\n (canvasRect.bottom - (sourceRect.top + sourceRect.height / 2)) *\n scaleY\n const halfWidth = (sourceRect.width / 2) * scaleX\n const halfHeight = (sourceRect.height / 2) * scaleY\n gl.uniform2f(centerLocation, centerX, centerY)\n gl.uniform2f(halfLocation, halfWidth, halfHeight)\n // Optional responsive boost of the glow size (e.g. mobile)\n const spread = Number.parseFloat(\n getComputedStyle(canvasEl.value).getPropertyValue(\n '--aurora-spread',\n ),\n )\n gl.uniform1f(spreadLocation, Number.isNaN(spread) ? 1 : spread)\n }\n\n // Redraw before the next paint: setting the canvas size reallocates\n // the drawing buffer, and presenting it undrawn can flash as an\n // uninitialized (white) frame. With reduced motion (no loop) this\n // also keeps the settled static frame across resizes.\n drawFrame(prefersReducedMotion() ? 10 : undefined)\n }\n\n const prefersReducedMotion = () =>\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\n const drawFrame = (timeSeconds?: number) => {\n if (!gl || !canvasEl.value) {\n return\n }\n gl.uniform1f(\n timeLocation,\n timeSeconds ?? (performance.now() - startTime) / 1000,\n )\n gl.uniform2f(\n resolutionLocation,\n canvasEl.value.width,\n canvasEl.value.height,\n )\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)\n }\n\n const loop = () => {\n drawFrame()\n rafId = requestAnimationFrame(loop)\n }\n\n onMounted(() => {\n const canvas = canvasEl.value\n // No context yet: this only reads the tints, the shader gets them\n // once the program is linked\n applyTints()\n gl = canvas?.getContext('webgl', { alpha: true }) ?? null\n if (!canvas || !gl || !tints.value) {\n failed.value = true\n return\n }\n\n const vertex = compile(gl.VERTEX_SHADER, VERTEX_SHADER)\n const fragment = compile(gl.FRAGMENT_SHADER, FRAGMENT_SHADER)\n const program = gl.createProgram()\n if (!vertex || !fragment || !program) {\n failed.value = true\n return\n }\n gl.attachShader(program, vertex)\n gl.attachShader(program, fragment)\n gl.linkProgram(program)\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n failed.value = true\n return\n }\n gl.useProgram(program)\n\n // Fullscreen quad\n const buffer = gl.createBuffer()\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),\n gl.STATIC_DRAW,\n )\n const positionLocation = gl.getAttribLocation(program, 'a_position')\n gl.enableVertexAttribArray(positionLocation)\n gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)\n\n timeLocation = gl.getUniformLocation(program, 'u_time')\n resolutionLocation = gl.getUniformLocation(program, 'u_resolution')\n centerLocation = gl.getUniformLocation(program, 'u_center')\n halfLocation = gl.getUniformLocation(program, 'u_half')\n spreadLocation = gl.getUniformLocation(program, 'u_spread')\n colorLocation = gl.getUniformLocation(program, 'u_color')\n color2Location = gl.getUniformLocation(program, 'u_color2')\n duoLocation = gl.getUniformLocation(program, 'u_duo')\n applyTints()\n\n resizeObserver = new ResizeObserver(resize)\n resizeObserver.observe(canvas)\n resize()\n // And again once the rest of the tree exists: the source is usually a\n // sibling rendered after this canvas, so the measure above ran while\n // the selector still matched nothing and silently fell back to the\n // parent box.\n void nextTick(resize)\n\n if (prefersReducedMotion()) {\n // Static frame: the color stays, the motion goes\n drawFrame(10)\n return\n }\n loop()\n })\n\n onBeforeUnmount(() => {\n cancelAnimationFrame(rafId)\n resizeObserver?.disconnect()\n })\n\n // Release the context (Chrome caps live WebGL contexts per page) only\n // after the compositor committed the removal: dropping the backing\n // buffer while the last frame is still on screen paints an undefined\n // (white) frame — a visible flash on the dark theme\n onUnmounted(() => {\n const context = gl\n gl = null\n setTimeout(() => {\n context?.getExtension('WEBGL_lose_context')?.loseContext()\n }, 150)\n })\n</script>\n\n<template>\n <div ref=\"rootEl\" class=\"pk-aurora\" aria-hidden=\"true\" :style=\"tintStyle\">\n <canvas v-if=\"!failed\" ref=\"canvasEl\" class=\"pk-aurora__canvas\" />\n <div v-else class=\"pk-aurora__fallback\" />\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-aurora {\n position: absolute;\n inset: 0;\n\n // Where the tints start from when no `mainColor` is given, and what\n // the fallback draws when they could not be read\n color: var(--chat-page-accent, var(--color-brand));\n pointer-events: none;\n\n &__canvas {\n width: 100%;\n height: 100%;\n\n // No CSS filter on purpose: a filtered accelerated canvas gets\n // its own compositor surface, which Chrome can present\n // uninitialized (a white flash) when the layer is created or\n // torn down. The glow is smoothed in the shader instead.\n }\n\n // CSS blobs when WebGL is unavailable\n &__fallback {\n position: absolute;\n inset: 0;\n background:\n radial-gradient(\n 45% 65% at 32% 38%,\n color-mix(\n in srgb,\n var(--pk-aurora-tint, currentcolor) 26%,\n transparent\n ),\n transparent 70%\n ),\n radial-gradient(\n 40% 55% at 68% 62%,\n color-mix(\n in srgb,\n var(--pk-aurora-tint-2, currentcolor) 16%,\n transparent\n ),\n transparent 70%\n );\n filter: blur(48px);\n animation: pk-aurora-drift 14s var(--ease-in-out) infinite alternate;\n\n @media (prefers-reduced-motion: reduce) {\n animation: none;\n }\n }\n }\n\n @keyframes pk-aurora-drift {\n from {\n transform: rotate(-10deg) scale(1);\n }\n\n to {\n transform: rotate(10deg) scale(1.2);\n }\n }\n</style>\n","<script lang=\"ts\" setup>\n import { nextTick, onBeforeUnmount, useTemplateRef, watch } from 'vue'\n\n /**\n * Audio-reactive bars for a live voice session: the visible proof that the\n * microphone is open and that the agent is actually speaking.\n *\n * Fed by pull, not by push: the parent hands over samplers and this component\n * calls them once per animation frame. Sixty reactive writes a second through\n * a component tree would cost more than the animation itself, and the levels\n * are only ever needed here.\n */\n const props = withDefaults(\n defineProps<{\n /** Loudness of the channel currently on air, 0 to 1. */\n sample: () => number\n /** Frequency bins of the same channel, when the transport exposes them. */\n spectrum?: () => Uint8Array | undefined\n state: 'idle' | 'connecting' | 'listening' | 'speaking' | 'error'\n bars?: number\n }>(),\n { bars: 5, spectrum: undefined },\n )\n\n const barsEl = useTemplateRef<HTMLElement>('barsEl')\n\n const REST = 0.18\n const SMOOTHING = 0.35\n\n /**\n * Current heights, deliberately NOT reactive: they change every frame and are\n * written straight to a CSS custom property. A ref here would re-render the\n * bars sixty times a second to produce the same DOM.\n */\n let heights = Array.from({ length: props.bars }, () => REST)\n\n let frame: number | undefined\n\n const prefersReducedMotion = () =>\n typeof window !== 'undefined' &&\n window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true\n\n /**\n * One target height per bar. With a spectrum, each bar owns a band, so the\n * shape follows the voice; without it, the single loudness value is spread\n * with a phase offset per bar so it still reads as speech and not as a\n * progress bar.\n */\n const readTargets = (): number[] => {\n const level = Math.min(1, Math.max(0, props.sample()))\n const bins = props.spectrum?.()\n const count = heights.length\n\n if (!bins?.length) {\n const now = Date.now() / 260\n return Array.from({ length: count }, (_unused, index) => {\n const wave = 0.65 + 0.35 * Math.sin(now + index * 0.9)\n return REST + level * 2.4 * wave\n })\n }\n\n // Speech lives in the lower half of the spectrum: using the whole range\n // would leave most bars flat.\n const usable = Math.max(1, Math.floor(bins.length / 2))\n const bandSize = Math.max(1, Math.floor(usable / count))\n return Array.from({ length: count }, (_unused, index) => {\n let total = 0\n for (let bin = 0; bin < bandSize; bin += 1) {\n total += bins[index * bandSize + bin] ?? 0\n }\n return REST + (total / bandSize / 255) * 2.2\n })\n }\n\n const render = () => {\n const nodes = barsEl.value?.children\n if (!nodes) {\n return\n }\n heights.forEach((height, index) => {\n ;(nodes[index] as HTMLElement | undefined)?.style.setProperty(\n '--pk-voice-orb-scale',\n String(height),\n )\n })\n }\n\n const paint = () => {\n const targets = readTargets()\n heights = heights.map((current, index) => {\n const target = Math.min(1, Math.max(REST, targets[index] ?? REST))\n return current + (target - current) * SMOOTHING\n })\n render()\n frame = requestAnimationFrame(paint)\n }\n\n const stopPainting = () => {\n if (frame !== undefined) {\n cancelAnimationFrame(frame)\n frame = undefined\n }\n }\n\n watch(\n () => props.state,\n async (state) => {\n const live = state === 'listening' || state === 'speaking'\n if (!live || prefersReducedMotion()) {\n stopPainting()\n heights = heights.map(() => REST * 1.6)\n // The bars may not be in the DOM yet on the first call.\n await nextTick()\n render()\n return\n }\n if (frame === undefined) {\n frame = requestAnimationFrame(paint)\n }\n },\n { immediate: true },\n )\n\n onBeforeUnmount(stopPainting)\n</script>\n\n<template>\n <div\n class=\"pk-voice-orb\"\n :class=\"`pk-voice-orb--${state}`\"\n aria-hidden=\"true\">\n <div ref=\"barsEl\" class=\"pk-voice-orb__bars\">\n <span\n v-for=\"index in bars\"\n :key=\"index\"\n class=\"pk-voice-orb__bar\" />\n </div>\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-voice-orb {\n --pk-voice-orb-color: var(--color-word-3);\n\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n\n // The size is a custom property so a host can scale the orb without\n // reaching into its internals, and its default lives here in the\n // fallback rather than as a declaration on this block: declared, it\n // would sit on the element itself and shadow whatever the host sets\n // on an ancestor.\n width: var(--pk-voice-orb-size, var(--spacing-40));\n height: var(--pk-voice-orb-size, var(--spacing-40));\n border-radius: var(--rounded-full);\n background-color: color-mix(\n in srgb,\n var(--pk-voice-orb-color) 12%,\n transparent\n );\n transition: background-color var(--duration-200, 200ms) ease;\n\n &__bars {\n display: flex;\n align-items: center;\n gap: 2px;\n height: var(--pk-voice-orb-bars-height, var(--spacing-20));\n }\n\n &__bar {\n width: 3px;\n height: 100%;\n border-radius: var(--rounded-full);\n background-color: var(--pk-voice-orb-color);\n transform: scaleY(var(--pk-voice-orb-scale, 0.2));\n transform-origin: center;\n }\n\n // The user is on air: the agent's colour (the brand of the chat, see\n // agentThemeStyle) in its role for marks, which holds 3:1 on the\n // surface in both themes, so the default black turns grey on the\n // dark theme instead of vanishing.\n &--listening {\n --pk-voice-orb-color: var(--color-brand-graphic);\n }\n\n // The agent has the floor: the orb fills with its colour and the bars\n // take the contrast, as the send button and the launcher do. The fill\n // tells the two turns apart in any colour: a second hue would have to\n // be made up, and a neutral one is the default black itself.\n &--speaking {\n --pk-voice-orb-color: var(--color-brand);\n\n background-color: var(--color-brand);\n }\n\n &--speaking &__bar {\n background-color: var(--color-brand-contrast);\n }\n\n // A live call breathes even in silence: the bars rest flat when nobody\n // talks, so without this ring an open line is indistinguishable from a\n // dead one.\n &--listening,\n &--speaking {\n animation: pk-voice-orb-live 2s ease-out infinite;\n }\n\n &--error {\n --pk-voice-orb-color: var(--color-danger);\n }\n\n &--connecting &__bar {\n animation: pk-voice-orb-wait 1.2s ease-in-out infinite;\n }\n\n &--connecting &__bar:nth-child(2) {\n animation-delay: 0.15s;\n }\n\n &--connecting &__bar:nth-child(3) {\n animation-delay: 0.3s;\n }\n\n &--connecting &__bar:nth-child(4) {\n animation-delay: 0.45s;\n }\n\n &--connecting &__bar:nth-child(5) {\n animation-delay: 0.6s;\n }\n }\n\n @keyframes pk-voice-orb-wait {\n 0%,\n 100% {\n transform: scaleY(0.25);\n }\n\n 50% {\n transform: scaleY(0.8);\n }\n }\n\n // A sonar ping: the ring expands and fades, then the snap back to zero is\n // the start of the next ping rather than a visible jump.\n @keyframes pk-voice-orb-live {\n from {\n box-shadow: 0 0 0 0\n color-mix(in srgb, var(--pk-voice-orb-color) 35%, transparent);\n }\n\n to {\n box-shadow: 0 0 0 var(--spacing-8) transparent;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .pk-voice-orb__bar {\n animation: none;\n transform: scaleY(0.45);\n }\n\n // Still say \"live\", just without moving: a steady ring instead of the ping.\n .pk-voice-orb--listening,\n .pk-voice-orb--speaking {\n animation: none;\n box-shadow: 0 0 0 3px\n color-mix(in srgb, var(--pk-voice-orb-color) 20%, transparent);\n }\n }\n</style>\n","<script lang=\"ts\" setup>\n import { nextTick, onBeforeUnmount, useTemplateRef, watch } from 'vue'\n\n /**\n * Audio-reactive bars for a live voice session: the visible proof that the\n * microphone is open and that the agent is actually speaking.\n *\n * Fed by pull, not by push: the parent hands over samplers and this component\n * calls them once per animation frame. Sixty reactive writes a second through\n * a component tree would cost more than the animation itself, and the levels\n * are only ever needed here.\n */\n const props = withDefaults(\n defineProps<{\n /** Loudness of the channel currently on air, 0 to 1. */\n sample: () => number\n /** Frequency bins of the same channel, when the transport exposes them. */\n spectrum?: () => Uint8Array | undefined\n state: 'idle' | 'connecting' | 'listening' | 'speaking' | 'error'\n bars?: number\n }>(),\n { bars: 5, spectrum: undefined },\n )\n\n const barsEl = useTemplateRef<HTMLElement>('barsEl')\n\n const REST = 0.18\n const SMOOTHING = 0.35\n\n /**\n * Current heights, deliberately NOT reactive: they change every frame and are\n * written straight to a CSS custom property. A ref here would re-render the\n * bars sixty times a second to produce the same DOM.\n */\n let heights = Array.from({ length: props.bars }, () => REST)\n\n let frame: number | undefined\n\n const prefersReducedMotion = () =>\n typeof window !== 'undefined' &&\n window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true\n\n /**\n * One target height per bar. With a spectrum, each bar owns a band, so the\n * shape follows the voice; without it, the single loudness value is spread\n * with a phase offset per bar so it still reads as speech and not as a\n * progress bar.\n */\n const readTargets = (): number[] => {\n const level = Math.min(1, Math.max(0, props.sample()))\n const bins = props.spectrum?.()\n const count = heights.length\n\n if (!bins?.length) {\n const now = Date.now() / 260\n return Array.from({ length: count }, (_unused, index) => {\n const wave = 0.65 + 0.35 * Math.sin(now + index * 0.9)\n return REST + level * 2.4 * wave\n })\n }\n\n // Speech lives in the lower half of the spectrum: using the whole range\n // would leave most bars flat.\n const usable = Math.max(1, Math.floor(bins.length / 2))\n const bandSize = Math.max(1, Math.floor(usable / count))\n return Array.from({ length: count }, (_unused, index) => {\n let total = 0\n for (let bin = 0; bin < bandSize; bin += 1) {\n total += bins[index * bandSize + bin] ?? 0\n }\n return REST + (total / bandSize / 255) * 2.2\n })\n }\n\n const render = () => {\n const nodes = barsEl.value?.children\n if (!nodes) {\n return\n }\n heights.forEach((height, index) => {\n ;(nodes[index] as HTMLElement | undefined)?.style.setProperty(\n '--pk-voice-orb-scale',\n String(height),\n )\n })\n }\n\n const paint = () => {\n const targets = readTargets()\n heights = heights.map((current, index) => {\n const target = Math.min(1, Math.max(REST, targets[index] ?? REST))\n return current + (target - current) * SMOOTHING\n })\n render()\n frame = requestAnimationFrame(paint)\n }\n\n const stopPainting = () => {\n if (frame !== undefined) {\n cancelAnimationFrame(frame)\n frame = undefined\n }\n }\n\n watch(\n () => props.state,\n async (state) => {\n const live = state === 'listening' || state === 'speaking'\n if (!live || prefersReducedMotion()) {\n stopPainting()\n heights = heights.map(() => REST * 1.6)\n // The bars may not be in the DOM yet on the first call.\n await nextTick()\n render()\n return\n }\n if (frame === undefined) {\n frame = requestAnimationFrame(paint)\n }\n },\n { immediate: true },\n )\n\n onBeforeUnmount(stopPainting)\n</script>\n\n<template>\n <div\n class=\"pk-voice-orb\"\n :class=\"`pk-voice-orb--${state}`\"\n aria-hidden=\"true\">\n <div ref=\"barsEl\" class=\"pk-voice-orb__bars\">\n <span\n v-for=\"index in bars\"\n :key=\"index\"\n class=\"pk-voice-orb__bar\" />\n </div>\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-voice-orb {\n --pk-voice-orb-color: var(--color-word-3);\n\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n\n // The size is a custom property so a host can scale the orb without\n // reaching into its internals, and its default lives here in the\n // fallback rather than as a declaration on this block: declared, it\n // would sit on the element itself and shadow whatever the host sets\n // on an ancestor.\n width: var(--pk-voice-orb-size, var(--spacing-40));\n height: var(--pk-voice-orb-size, var(--spacing-40));\n border-radius: var(--rounded-full);\n background-color: color-mix(\n in srgb,\n var(--pk-voice-orb-color) 12%,\n transparent\n );\n transition: background-color var(--duration-200, 200ms) ease;\n\n &__bars {\n display: flex;\n align-items: center;\n gap: 2px;\n height: var(--pk-voice-orb-bars-height, var(--spacing-20));\n }\n\n &__bar {\n width: 3px;\n height: 100%;\n border-radius: var(--rounded-full);\n background-color: var(--pk-voice-orb-color);\n transform: scaleY(var(--pk-voice-orb-scale, 0.2));\n transform-origin: center;\n }\n\n // The user is on air: the agent's colour (the brand of the chat, see\n // agentThemeStyle) in its role for marks, which holds 3:1 on the\n // surface in both themes, so the default black turns grey on the\n // dark theme instead of vanishing.\n &--listening {\n --pk-voice-orb-color: var(--color-brand-graphic);\n }\n\n // The agent has the floor: the orb fills with its colour and the bars\n // take the contrast, as the send button and the launcher do. The fill\n // tells the two turns apart in any colour: a second hue would have to\n // be made up, and a neutral one is the default black itself.\n &--speaking {\n --pk-voice-orb-color: var(--color-brand);\n\n background-color: var(--color-brand);\n }\n\n &--speaking &__bar {\n background-color: var(--color-brand-contrast);\n }\n\n // A live call breathes even in silence: the bars rest flat when nobody\n // talks, so without this ring an open line is indistinguishable from a\n // dead one.\n &--listening,\n &--speaking {\n animation: pk-voice-orb-live 2s ease-out infinite;\n }\n\n &--error {\n --pk-voice-orb-color: var(--color-danger);\n }\n\n &--connecting &__bar {\n animation: pk-voice-orb-wait 1.2s ease-in-out infinite;\n }\n\n &--connecting &__bar:nth-child(2) {\n animation-delay: 0.15s;\n }\n\n &--connecting &__bar:nth-child(3) {\n animation-delay: 0.3s;\n }\n\n &--connecting &__bar:nth-child(4) {\n animation-delay: 0.45s;\n }\n\n &--connecting &__bar:nth-child(5) {\n animation-delay: 0.6s;\n }\n }\n\n @keyframes pk-voice-orb-wait {\n 0%,\n 100% {\n transform: scaleY(0.25);\n }\n\n 50% {\n transform: scaleY(0.8);\n }\n }\n\n // A sonar ping: the ring expands and fades, then the snap back to zero is\n // the start of the next ping rather than a visible jump.\n @keyframes pk-voice-orb-live {\n from {\n box-shadow: 0 0 0 0\n color-mix(in srgb, var(--pk-voice-orb-color) 35%, transparent);\n }\n\n to {\n box-shadow: 0 0 0 var(--spacing-8) transparent;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .pk-voice-orb__bar {\n animation: none;\n transform: scaleY(0.45);\n }\n\n // Still say \"live\", just without moving: a steady ring instead of the ping.\n .pk-voice-orb--listening,\n .pk-voice-orb--speaking {\n animation: none;\n box-shadow: 0 0 0 3px\n color-mix(in srgb, var(--pk-voice-orb-color) 20%, transparent);\n }\n }\n</style>\n","<script lang=\"ts\" setup>\n import { computed } from 'vue'\n import { useI18n } from 'vue-i18n'\n import PkVoiceOrb from './PkVoiceOrb.vue'\n import PkChatButton from './PkChatButton.vue'\n\n /**\n * The live voice session, docked where the input pill normally is: while a\n * call is open this replaces it, so there is one place to look and one place\n * to hang up. Presentational on purpose, the session itself is owned by the\n * chat view, which is also what writes the transcript into the conversation.\n */\n const props = defineProps<{\n state: 'idle' | 'connecting' | 'listening' | 'speaking' | 'error'\n /** Loudness of whichever side is on air, sampled per animation frame. */\n sample: () => number\n spectrum?: () => Uint8Array | undefined\n remainingSeconds?: number\n muted?: boolean\n error?: string\n /**\n * The provider's own words for the failure, kept for the tooltip when\n * `error` is our localized copy for it.\n */\n rawError?: string\n /**\n * The socket is still open. The state collapses to 'error' whatever\n * the line is doing, and which actions make sense depends on the line:\n * a live failure is still billing and must offer the hang-up, a dead\n * one has nothing left to hang up.\n */\n live?: boolean\n }>()\n\n const emit = defineEmits<{\n 'toggle-mute': []\n 'hang-up': []\n retry: []\n dismiss: []\n }>()\n\n const { t: $t } = useI18n({\n useScope: 'global',\n })\n\n /** One label for the whole session, because the user reads a state, not a protocol. */\n const stateLabel = computed(() => {\n if (props.error) {\n return $t('message.voiceFailed')\n }\n if (props.state === 'connecting') {\n return $t('message.voiceConnecting')\n }\n if (props.state === 'speaking') {\n return $t('message.voiceSpeaking')\n }\n if (props.muted) {\n return $t('message.voiceMuted')\n }\n return $t('message.voiceListening')\n })\n\n const remainingLabel = computed(() => {\n if (props.remainingSeconds === undefined) {\n return undefined\n }\n const minutes = Math.floor(props.remainingSeconds / 60)\n const seconds = props.remainingSeconds % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n })\n\n /** Warn only when the cap is close enough to interrupt a sentence. */\n const isRunningOut = computed(\n () =>\n props.remainingSeconds !== undefined &&\n props.remainingSeconds <= 30,\n )\n\n /** The line is open: audio is flowing in one direction or the other. */\n const isLive = computed(\n () =>\n !props.error &&\n (props.state === 'listening' || props.state === 'speaking'),\n )\n\n /**\n * Colours the state line: brand while the microphone is yours, accent\n * while the agent holds it, nothing while muted, connecting or failed.\n */\n const stateTone = computed(() => {\n if (!isLive.value) {\n return undefined\n }\n if (props.state === 'speaking') {\n return 'speaking'\n }\n return props.muted ? undefined : 'listening'\n })\n</script>\n\n<template>\n <div\n class=\"pk-voice-session\"\n :class=\"{ 'pk-voice-session--failed': !!error }\">\n <!-- A visualiser of a line that is dead has nothing to visualise: the\n orb kept animating an audio level of zero, which is what made a\n failure look like a call still in progress -->\n <span v-if=\"error\" class=\"pk-voice-session__badge\" aria-hidden=\"true\">\n <VvIcon name=\"ri:error-warning-line\" />\n </span>\n <PkVoiceOrb\n v-else\n :state=\"state\"\n :sample=\"sample\"\n :spectrum=\"spectrum\" />\n\n <!-- Only the state is live: the timer ticks every second and would make\n a screen reader read the whole bar again with it -->\n <div class=\"pk-voice-session__status\" role=\"status\">\n <span\n class=\"pk-voice-session__state\"\n :class=\"stateTone && `pk-voice-session__state--${stateTone}`\">\n <!-- The dot marks the connection, the colour marks whose turn\n it is: it stays on while muted (the line is still open) and\n only the tone drops -->\n <span\n v-if=\"isLive\"\n class=\"pk-voice-session__live-dot\"\n aria-hidden=\"true\" />\n {{ stateLabel }}\n </span>\n <!-- One line, ellipsed, with the whole of it on the tooltip: the\n bar stands where the input pill stands, and a failure that grows\n it to three lines shoves the conversation up the screen. The\n provider's own words survive in the tooltip when the line shows\n our copy for them -->\n <p\n v-if=\"error\"\n class=\"pk-voice-session__detail\"\n :title=\"rawError ?? error\">\n {{ error }}\n </p>\n </div>\n\n <span\n v-if=\"remainingLabel\"\n class=\"pk-voice-session__timer\"\n :class=\"{\n 'pk-voice-session__timer--warning': isRunningOut,\n }\"\n :title=\"$t('hint.voiceRemaining')\"\n aria-hidden=\"true\">\n {{ remainingLabel }}\n </span>\n\n <!-- Same icon buttons as the input pill this bar replaces: a call must\n not look like a different piece of software from the thing it took\n over. Recovering from a failure keeps its words, an icon-only refresh\n is not a recovery path -->\n <div class=\"pk-voice-session__actions\">\n <template v-if=\"error\">\n <PkChatButton\n icon=\"ri:refresh-line\"\n :label=\"$t('action.retry')\"\n @click=\"emit('retry')\" />\n <!-- Two actions, chosen by the line rather than three at once.\n A failure does not always end the call: on a socket still open\n (and still billing) the way out is hanging up, while dismissing\n would hide a line that keeps costing. On a dead socket there is\n nothing left to hang up, and closing gives the input back -->\n <PkChatButton\n v-if=\"live\"\n icon=\"ri:stop-circle-line\"\n modifiers=\"danger\"\n :title=\"$t('action.hangUp')\"\n :aria-label=\"$t('action.hangUp')\"\n @click=\"emit('hang-up')\" />\n <PkChatButton\n v-else\n icon=\"ri:close-line\"\n :label=\"$t('action.close')\"\n @click=\"emit('dismiss')\" />\n </template>\n <template v-else>\n <PkChatButton\n :icon=\"muted ? 'ri:mic-off-line' : 'ri:mic-line'\"\n :title=\"muted ? $t('action.unmute') : $t('action.mute')\"\n :aria-label=\"\n muted ? $t('action.unmute') : $t('action.mute')\n \"\n :aria-pressed=\"muted\"\n @click=\"emit('toggle-mute')\" />\n <PkChatButton\n icon=\"ri:stop-circle-line\"\n modifiers=\"danger\"\n :title=\"$t('action.hangUp')\"\n :aria-label=\"$t('action.hangUp')\"\n @click=\"emit('hang-up')\" />\n </template>\n </div>\n </div>\n</template>\n\n<style lang=\"scss\">\n // Sits where the input sits and is built out of its box: same margins, same\n // rounding, same surface, same resting height, so answering by voice does\n // not move the dock. The error state stays inside it rather than pushing a\n // second block below, which is what made a failure look like a stack trace.\n .pk-voice-session {\n // Above the ambient glow, which is painted by an absolutely positioned\n // sibling: the input pill it replaces raises itself the same way\n position: relative;\n z-index: 1;\n\n // The dock is 50px tall in the widget and 60px in fullscreen. It is\n // declared, not derived: deriving it from the tallest child means the\n // box moves whenever a child changes, and this box has to be exactly\n // as tall as the input it took the place of.\n --pk-chat-dock-height: var(--spacing-50);\n\n // Free to be as big as it looks right, now that nothing hangs off it:\n // the height above is a floor no child reaches. It stays well inside\n // that floor, because a filled disc reads heavier than its diameter\n // and the state next to it is what should be read first.\n --pk-voice-orb-size: var(--spacing-32);\n --pk-voice-orb-bars-height: var(--spacing-18);\n\n // Named, because the failure tint is mixed into it and fullscreen\n // swaps it: a plain `background-color` there would outrank the\n // modifier and paint a failed call as a healthy one.\n --pk-voice-session-surface: var(--color-surface);\n\n display: flex;\n align-items: center;\n\n // One row, always. Wrapping put the actions of a failure on a line of\n // their own under a two-line reason, and the dock grew to three rows\n // and shoved the conversation up the screen (reported 2026-08-27).\n flex-wrap: nowrap;\n gap: var(--spacing-12);\n\n // A floor rather than a height: the failure keeps its reason on a\n // second line, and two lines still fit inside it.\n min-height: var(--pk-chat-dock-height);\n margin-inline: var(--spacing-sm);\n margin-bottom: var(--spacing-sm);\n padding-block: 0;\n padding-inline: var(--spacing-14);\n border: 1px solid var(--color-surface-3);\n border-radius: var(--rounded-xl);\n background-color: var(--pk-voice-session-surface);\n box-shadow: var(--shadow-lg);\n\n @include media-breakpoint-up('sm', $breakpoints) {\n padding-inline: var(--spacing-10);\n }\n\n &--failed {\n background-color: color-mix(\n in srgb,\n var(--color-danger) 6%,\n var(--pk-voice-session-surface)\n );\n border-color: color-mix(\n in srgb,\n var(--color-danger) 24%,\n transparent\n );\n }\n\n // Takes the orb's place and its size, so the row keeps its rhythm: the\n // failure changes what the disc means, not where anything sits.\n &__badge {\n display: flex;\n flex-shrink: 0;\n align-items: center;\n justify-content: center;\n width: var(--pk-voice-orb-size);\n height: var(--pk-voice-orb-size);\n border-radius: var(--rounded-full);\n background-color: color-mix(\n in srgb,\n var(--color-danger) 12%,\n transparent\n );\n color: var(--color-surface-danger-readable);\n font-size: var(--text-18);\n }\n\n // Takes the room that is left and gives all of it back when the\n // actions need it: with a basis of its own it pushed them onto a\n // second row in the widget, which is the one place with no room to\n // spare. The label itself is a single ellipsed line, so it has nothing\n // to lose by shrinking.\n &__status {\n display: flex;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n }\n\n &__state {\n overflow: hidden;\n font-size: var(--text-14);\n color: var(--color-word-3);\n text-overflow: ellipsis;\n white-space: nowrap;\n\n // A live turn takes the agent's colour, the brand of the chat, as\n // the orb does; the words say whose turn it is, the orb's fill\n // shows it. Muted and connecting stay in the resting grey, because\n // grey is what makes these read. The readable role keeps the hue\n // and moves the shade only when the colour itself would not read\n // on the surface.\n &--listening,\n &--speaking {\n color: var(--color-brand-readable);\n font-weight: var(--font-medium, 500);\n }\n }\n\n // Blinks as long as the socket is up, whatever the colour of the text\n // around it: a live line and an open microphone are two different\n // facts, and muting must not look like hanging up.\n &__live-dot {\n display: inline-block;\n width: var(--spacing-6);\n height: var(--spacing-6);\n margin-inline-end: var(--spacing-4);\n border-radius: var(--rounded-full);\n background-color: currentcolor;\n vertical-align: middle;\n animation: pk-voice-session-live 2s ease-in-out infinite;\n }\n\n // One line, ellipsed: the reason has to fit the dock, and the whole of\n // it is on the title attribute. Clamped to two it made the box grow by\n // a row exactly when the caller was already looking at a failure.\n &__detail {\n overflow: hidden;\n margin: 0;\n color: var(--color-word-3);\n font-size: var(--text-12);\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n // Softer than the title above it: the state line names the failure, the\n // reason explains it, and two lines of full danger read as an alarm.\n &--failed &__detail {\n color: color-mix(\n in srgb,\n var(--color-danger-readable-strong) 80%,\n var(--color-word-3)\n );\n }\n\n &--failed &__state {\n color: var(--color-danger-readable-strong);\n font-weight: var(--font-medium, 500);\n }\n\n &__timer {\n color: var(--color-word-3);\n font-size: var(--text-12);\n font-variant-numeric: tabular-nums;\n\n &--warning {\n color: var(--color-danger-readable);\n }\n }\n\n // Never squeezed and never wrapped: the way out of a failure is the one\n // thing that must stay reachable, so the reason gives up its width\n // first (it is ellipsed and carries a tooltip).\n &__actions {\n display: flex;\n flex-shrink: 0;\n align-items: center;\n gap: var(--spacing-xs);\n margin-inline-start: auto;\n }\n }\n\n @keyframes pk-voice-session-live {\n 0%,\n 100% {\n opacity: 1;\n }\n\n 50% {\n opacity: 0.35;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .pk-voice-session__live-dot {\n animation: none;\n }\n }\n</style>\n","<script lang=\"ts\" setup>\n import { computed } from 'vue'\n import { useI18n } from 'vue-i18n'\n import PkVoiceOrb from './PkVoiceOrb.vue'\n import PkChatButton from './PkChatButton.vue'\n\n /**\n * The live voice session, docked where the input pill normally is: while a\n * call is open this replaces it, so there is one place to look and one place\n * to hang up. Presentational on purpose, the session itself is owned by the\n * chat view, which is also what writes the transcript into the conversation.\n */\n const props = defineProps<{\n state: 'idle' | 'connecting' | 'listening' | 'speaking' | 'error'\n /** Loudness of whichever side is on air, sampled per animation frame. */\n sample: () => number\n spectrum?: () => Uint8Array | undefined\n remainingSeconds?: number\n muted?: boolean\n error?: string\n /**\n * The provider's own words for the failure, kept for the tooltip when\n * `error` is our localized copy for it.\n */\n rawError?: string\n /**\n * The socket is still open. The state collapses to 'error' whatever\n * the line is doing, and which actions make sense depends on the line:\n * a live failure is still billing and must offer the hang-up, a dead\n * one has nothing left to hang up.\n */\n live?: boolean\n }>()\n\n const emit = defineEmits<{\n 'toggle-mute': []\n 'hang-up': []\n retry: []\n dismiss: []\n }>()\n\n const { t: $t } = useI18n({\n useScope: 'global',\n })\n\n /** One label for the whole session, because the user reads a state, not a protocol. */\n const stateLabel = computed(() => {\n if (props.error) {\n return $t('message.voiceFailed')\n }\n if (props.state === 'connecting') {\n return $t('message.voiceConnecting')\n }\n if (props.state === 'speaking') {\n return $t('message.voiceSpeaking')\n }\n if (props.muted) {\n return $t('message.voiceMuted')\n }\n return $t('message.voiceListening')\n })\n\n const remainingLabel = computed(() => {\n if (props.remainingSeconds === undefined) {\n return undefined\n }\n const minutes = Math.floor(props.remainingSeconds / 60)\n const seconds = props.remainingSeconds % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n })\n\n /** Warn only when the cap is close enough to interrupt a sentence. */\n const isRunningOut = computed(\n () =>\n props.remainingSeconds !== undefined &&\n props.remainingSeconds <= 30,\n )\n\n /** The line is open: audio is flowing in one direction or the other. */\n const isLive = computed(\n () =>\n !props.error &&\n (props.state === 'listening' || props.state === 'speaking'),\n )\n\n /**\n * Colours the state line: brand while the microphone is yours, accent\n * while the agent holds it, nothing while muted, connecting or failed.\n */\n const stateTone = computed(() => {\n if (!isLive.value) {\n return undefined\n }\n if (props.state === 'speaking') {\n return 'speaking'\n }\n return props.muted ? undefined : 'listening'\n })\n</script>\n\n<template>\n <div\n class=\"pk-voice-session\"\n :class=\"{ 'pk-voice-session--failed': !!error }\">\n <!-- A visualiser of a line that is dead has nothing to visualise: the\n orb kept animating an audio level of zero, which is what made a\n failure look like a call still in progress -->\n <span v-if=\"error\" class=\"pk-voice-session__badge\" aria-hidden=\"true\">\n <VvIcon name=\"ri:error-warning-line\" />\n </span>\n <PkVoiceOrb\n v-else\n :state=\"state\"\n :sample=\"sample\"\n :spectrum=\"spectrum\" />\n\n <!-- Only the state is live: the timer ticks every second and would make\n a screen reader read the whole bar again with it -->\n <div class=\"pk-voice-session__status\" role=\"status\">\n <span\n class=\"pk-voice-session__state\"\n :class=\"stateTone && `pk-voice-session__state--${stateTone}`\">\n <!-- The dot marks the connection, the colour marks whose turn\n it is: it stays on while muted (the line is still open) and\n only the tone drops -->\n <span\n v-if=\"isLive\"\n class=\"pk-voice-session__live-dot\"\n aria-hidden=\"true\" />\n {{ stateLabel }}\n </span>\n <!-- One line, ellipsed, with the whole of it on the tooltip: the\n bar stands where the input pill stands, and a failure that grows\n it to three lines shoves the conversation up the screen. The\n provider's own words survive in the tooltip when the line shows\n our copy for them -->\n <p\n v-if=\"error\"\n class=\"pk-voice-session__detail\"\n :title=\"rawError ?? error\">\n {{ error }}\n </p>\n </div>\n\n <span\n v-if=\"remainingLabel\"\n class=\"pk-voice-session__timer\"\n :class=\"{\n 'pk-voice-session__timer--warning': isRunningOut,\n }\"\n :title=\"$t('hint.voiceRemaining')\"\n aria-hidden=\"true\">\n {{ remainingLabel }}\n </span>\n\n <!-- Same icon buttons as the input pill this bar replaces: a call must\n not look like a different piece of software from the thing it took\n over. Recovering from a failure keeps its words, an icon-only refresh\n is not a recovery path -->\n <div class=\"pk-voice-session__actions\">\n <template v-if=\"error\">\n <PkChatButton\n icon=\"ri:refresh-line\"\n :label=\"$t('action.retry')\"\n @click=\"emit('retry')\" />\n <!-- Two actions, chosen by the line rather than three at once.\n A failure does not always end the call: on a socket still open\n (and still billing) the way out is hanging up, while dismissing\n would hide a line that keeps costing. On a dead socket there is\n nothing left to hang up, and closing gives the input back -->\n <PkChatButton\n v-if=\"live\"\n icon=\"ri:stop-circle-line\"\n modifiers=\"danger\"\n :title=\"$t('action.hangUp')\"\n :aria-label=\"$t('action.hangUp')\"\n @click=\"emit('hang-up')\" />\n <PkChatButton\n v-else\n icon=\"ri:close-line\"\n :label=\"$t('action.close')\"\n @click=\"emit('dismiss')\" />\n </template>\n <template v-else>\n <PkChatButton\n :icon=\"muted ? 'ri:mic-off-line' : 'ri:mic-line'\"\n :title=\"muted ? $t('action.unmute') : $t('action.mute')\"\n :aria-label=\"\n muted ? $t('action.unmute') : $t('action.mute')\n \"\n :aria-pressed=\"muted\"\n @click=\"emit('toggle-mute')\" />\n <PkChatButton\n icon=\"ri:stop-circle-line\"\n modifiers=\"danger\"\n :title=\"$t('action.hangUp')\"\n :aria-label=\"$t('action.hangUp')\"\n @click=\"emit('hang-up')\" />\n </template>\n </div>\n </div>\n</template>\n\n<style lang=\"scss\">\n // Sits where the input sits and is built out of its box: same margins, same\n // rounding, same surface, same resting height, so answering by voice does\n // not move the dock. The error state stays inside it rather than pushing a\n // second block below, which is what made a failure look like a stack trace.\n .pk-voice-session {\n // Above the ambient glow, which is painted by an absolutely positioned\n // sibling: the input pill it replaces raises itself the same way\n position: relative;\n z-index: 1;\n\n // The dock is 50px tall in the widget and 60px in fullscreen. It is\n // declared, not derived: deriving it from the tallest child means the\n // box moves whenever a child changes, and this box has to be exactly\n // as tall as the input it took the place of.\n --pk-chat-dock-height: var(--spacing-50);\n\n // Free to be as big as it looks right, now that nothing hangs off it:\n // the height above is a floor no child reaches. It stays well inside\n // that floor, because a filled disc reads heavier than its diameter\n // and the state next to it is what should be read first.\n --pk-voice-orb-size: var(--spacing-32);\n --pk-voice-orb-bars-height: var(--spacing-18);\n\n // Named, because the failure tint is mixed into it and fullscreen\n // swaps it: a plain `background-color` there would outrank the\n // modifier and paint a failed call as a healthy one.\n --pk-voice-session-surface: var(--color-surface);\n\n display: flex;\n align-items: center;\n\n // One row, always. Wrapping put the actions of a failure on a line of\n // their own under a two-line reason, and the dock grew to three rows\n // and shoved the conversation up the screen (reported 2026-08-27).\n flex-wrap: nowrap;\n gap: var(--spacing-12);\n\n // A floor rather than a height: the failure keeps its reason on a\n // second line, and two lines still fit inside it.\n min-height: var(--pk-chat-dock-height);\n margin-inline: var(--spacing-sm);\n margin-bottom: var(--spacing-sm);\n padding-block: 0;\n padding-inline: var(--spacing-14);\n border: 1px solid var(--color-surface-3);\n border-radius: var(--rounded-xl);\n background-color: var(--pk-voice-session-surface);\n box-shadow: var(--shadow-lg);\n\n @include media-breakpoint-up('sm', $breakpoints) {\n padding-inline: var(--spacing-10);\n }\n\n &--failed {\n background-color: color-mix(\n in srgb,\n var(--color-danger) 6%,\n var(--pk-voice-session-surface)\n );\n border-color: color-mix(\n in srgb,\n var(--color-danger) 24%,\n transparent\n );\n }\n\n // Takes the orb's place and its size, so the row keeps its rhythm: the\n // failure changes what the disc means, not where anything sits.\n &__badge {\n display: flex;\n flex-shrink: 0;\n align-items: center;\n justify-content: center;\n width: var(--pk-voice-orb-size);\n height: var(--pk-voice-orb-size);\n border-radius: var(--rounded-full);\n background-color: color-mix(\n in srgb,\n var(--color-danger) 12%,\n transparent\n );\n color: var(--color-surface-danger-readable);\n font-size: var(--text-18);\n }\n\n // Takes the room that is left and gives all of it back when the\n // actions need it: with a basis of its own it pushed them onto a\n // second row in the widget, which is the one place with no room to\n // spare. The label itself is a single ellipsed line, so it has nothing\n // to lose by shrinking.\n &__status {\n display: flex;\n min-width: 0;\n flex: 1 1 auto;\n flex-direction: column;\n }\n\n &__state {\n overflow: hidden;\n font-size: var(--text-14);\n color: var(--color-word-3);\n text-overflow: ellipsis;\n white-space: nowrap;\n\n // A live turn takes the agent's colour, the brand of the chat, as\n // the orb does; the words say whose turn it is, the orb's fill\n // shows it. Muted and connecting stay in the resting grey, because\n // grey is what makes these read. The readable role keeps the hue\n // and moves the shade only when the colour itself would not read\n // on the surface.\n &--listening,\n &--speaking {\n color: var(--color-brand-readable);\n font-weight: var(--font-medium, 500);\n }\n }\n\n // Blinks as long as the socket is up, whatever the colour of the text\n // around it: a live line and an open microphone are two different\n // facts, and muting must not look like hanging up.\n &__live-dot {\n display: inline-block;\n width: var(--spacing-6);\n height: var(--spacing-6);\n margin-inline-end: var(--spacing-4);\n border-radius: var(--rounded-full);\n background-color: currentcolor;\n vertical-align: middle;\n animation: pk-voice-session-live 2s ease-in-out infinite;\n }\n\n // One line, ellipsed: the reason has to fit the dock, and the whole of\n // it is on the title attribute. Clamped to two it made the box grow by\n // a row exactly when the caller was already looking at a failure.\n &__detail {\n overflow: hidden;\n margin: 0;\n color: var(--color-word-3);\n font-size: var(--text-12);\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n // Softer than the title above it: the state line names the failure, the\n // reason explains it, and two lines of full danger read as an alarm.\n &--failed &__detail {\n color: color-mix(\n in srgb,\n var(--color-danger-readable-strong) 80%,\n var(--color-word-3)\n );\n }\n\n &--failed &__state {\n color: var(--color-danger-readable-strong);\n font-weight: var(--font-medium, 500);\n }\n\n &__timer {\n color: var(--color-word-3);\n font-size: var(--text-12);\n font-variant-numeric: tabular-nums;\n\n &--warning {\n color: var(--color-danger-readable);\n }\n }\n\n // Never squeezed and never wrapped: the way out of a failure is the one\n // thing that must stay reachable, so the reason gives up its width\n // first (it is ellipsed and carries a tooltip).\n &__actions {\n display: flex;\n flex-shrink: 0;\n align-items: center;\n gap: var(--spacing-xs);\n margin-inline-start: auto;\n }\n }\n\n @keyframes pk-voice-session-live {\n 0%,\n 100% {\n opacity: 1;\n }\n\n 50% {\n opacity: 0.35;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .pk-voice-session__live-dot {\n animation: none;\n }\n }\n</style>\n","import { computed, onScopeDispose, ref, shallowRef } from 'vue'\nimport type { Mode, Status, VoiceConversation } from '@elevenlabs/client'\nimport { logger } from 'utils'\n\n/** What the backend hands over to open a session, and nothing more. */\nexport type VoiceSessionGrant = {\n /** Opaque server-side session id, echoed back to us through the provider. */\n sessionId: string\n signedUrl: string\n /** Conversation the spoken turns are persisted into. */\n chatId: string\n maxSessionSeconds: number\n}\n\nexport type VoiceTranscriptEntry = {\n role: 'user' | 'agent'\n text: string\n}\n\n/** Which side of the conversation an audio level belongs to. */\nexport type VoiceChannel = 'input' | 'output'\n\n/**\n * A voice conversation with one of our agents.\n *\n * The provider handles microphone, turn detection and playback; the turn itself\n * is answered by our own pipeline, because the provider-side agent is configured\n * to call our OpenAI-compatible surface as a custom LLM. So there is no chat\n * logic here: this composable owns the session lifecycle, the visible state, the\n * duration cap and the audio levels the visualiser reads, and nothing else.\n *\n * `fetchGrant` and `closeGrant` are injected rather than called from here, so the\n * package stays free of any knowledge about backend URLs or authentication.\n */\nexport const useVoiceSession = (options: {\n fetchGrant: () => Promise<VoiceSessionGrant>\n /** Ends the server-side session, which is also what bills its minutes. */\n closeGrant?: (sessionId: string) => Promise<void>\n /**\n * Tools the provider runs in this browser, by name, read once the grant is\n * in: the agent calls them, and what they resolve with goes back to it\n * (the page tools, spec `voice-page-control.md`).\n */\n clientTools?: () =>\n Record<string, (parameters: unknown) => Promise<string>> | undefined\n onTranscript?: (entry: VoiceTranscriptEntry) => void\n /**\n * The agent stopped speaking, so the conversation persisted server-side is\n * now ahead of what the client shows.\n */\n onTurnEnd?: () => void\n}) => {\n const conversation = shallowRef<VoiceConversation>()\n const status = ref<Status>('disconnected')\n const mode = ref<Mode>('listening')\n const error = ref<string>()\n const transcript = ref<VoiceTranscriptEntry[]>([])\n const remainingSeconds = ref<number>()\n const chatId = ref<string>()\n\n let sessionId: string | undefined\n let capTimer: ReturnType<typeof setInterval> | undefined\n /**\n * Bumped by every start and every stop. The provider's callbacks arrive\n * asynchronously and a late one from a closed session would otherwise clear\n * the state of the next: it would wipe the transcript on screen and close\n * the server-side session that is currently billing. Every callback checks\n * the generation it was registered for.\n */\n let generation = 0\n let disposed = false\n\n const clearCap = () => {\n if (capTimer) {\n clearInterval(capTimer)\n capTimer = undefined\n }\n remainingSeconds.value = undefined\n }\n\n /**\n * The provider enforces the same cap on its side (and our backend refuses a\n * turn past it), but a client that stops on its own is what keeps an idle tab\n * from burning provider minutes in the meantime.\n */\n const startCap = (maxSessionSeconds: number) => {\n // Counted from a deadline instead of decremented once per tick: a\n // background tab throttles intervals to about one a minute, and a\n // countdown would have shown minutes left on a call the provider had\n // already hung up, while our own stop never fired.\n const endsAt = Date.now() + maxSessionSeconds * 1000\n const tick = () => {\n const left = Math.max(0, Math.ceil((endsAt - Date.now()) / 1000))\n remainingSeconds.value = left\n if (left === 0) {\n void stop()\n }\n }\n tick()\n capTimer = setInterval(tick, 1000)\n }\n\n /**\n * Closes one server-side session, exactly once, and only the one it was\n * given. Reading the shared `sessionId` here was a real hazard: a `stop()`\n * still awaiting `endSession()` would pick up the id a new `start()` had\n * just stored and close the session that was live, leaving the provider\n * talking to a record we had deleted (every turn refused, minutes billed).\n */\n const releaseGrant = async (id: string | undefined) => {\n if (!id) {\n return\n }\n if (sessionId === id) {\n sessionId = undefined\n }\n await options.closeGrant?.(id).catch(() => undefined)\n }\n\n const stop = async () => {\n generation += 1\n clearCap()\n const mine = sessionId\n sessionId = undefined\n const active = conversation.value\n conversation.value = undefined\n await active?.endSession().catch(() => undefined)\n await releaseGrant(mine)\n status.value = 'disconnected'\n mode.value = 'listening'\n }\n\n const start = async () => {\n if (disposed || conversation.value || status.value === 'connecting') {\n return\n }\n error.value = undefined\n transcript.value = []\n // Both would otherwise survive into the next call: a stale 'speaking'\n // makes the first mode change of the new one look like the end of a turn\n // and fires a reload for a turn that never happened.\n mode.value = 'listening'\n chatId.value = undefined\n status.value = 'connecting'\n generation += 1\n const mine = generation\n const isCurrent = () => mine === generation && !disposed\n /**\n * The grant this attempt opened, if it got that far. The failure path\n * reads it instead of the shared `sessionId`, for the same reason\n * `releaseGrant` takes an id rather than reading one.\n */\n let ownSessionId: string | undefined\n\n try {\n // The provider SDK is loaded here rather than imported at the top:\n // it carries a WebRTC stack that weighs more than the rest of the\n // widget put together, and a page that never opens a call should\n // not pay for it. Started before the grant so it downloads while\n // the backend prepares the session, and awaited after it, so a\n // failure lands in the same catch that releases the grant. Its\n // rejection is claimed right away, because nothing awaits the\n // promise until then and the browser would report it as unhandled.\n const providerModule = import('@elevenlabs/client')\n void providerModule.catch(() => undefined)\n\n const grant = await options.fetchGrant()\n // The surface may have unmounted, or the user may have given up,\n // while the grant was in flight: closing it here is what keeps an\n // orphan session from billing minutes nobody is listening to.\n if (!isCurrent()) {\n await options\n .closeGrant?.(grant.sessionId)\n .catch(() => undefined)\n return\n }\n sessionId = grant.sessionId\n ownSessionId = grant.sessionId\n chatId.value = grant.chatId\n const { VoiceConversation } = await providerModule\n // Downloading the SDK is a wait the caller can give up on, unlike\n // the ones before it: opening the socket now would start provider\n // minutes for a call nobody is on any more.\n if (!isCurrent()) {\n await releaseGrant(grant.sessionId)\n return\n }\n const conversationStarted = await VoiceConversation.startSession({\n signedUrl: grant.signedUrl,\n // The only channel from this browser to our own callback: the\n // provider forwards it verbatim, and it is what tells the turn\n // which conversation (and which user) it belongs to. Requires\n // the extra-body override to be allowed on the provider agent,\n // which the backend sets when it provisions it.\n customLlmExtraBody: { voice_session_id: grant.sessionId },\n clientTools: options.clientTools?.() ?? {},\n onStatusChange: ({ status: next }) => {\n if (!isCurrent()) {\n return\n }\n status.value = next\n },\n onModeChange: ({ mode: next }) => {\n if (!isCurrent()) {\n return\n }\n const wasSpeaking = mode.value === 'speaking'\n mode.value = next\n if (wasSpeaking && next !== 'speaking') {\n options.onTurnEnd?.()\n }\n },\n onMessage: ({ message, role }) => {\n if (!isCurrent()) {\n return\n }\n const entry = { role, text: message }\n transcript.value = [...transcript.value, entry]\n options.onTranscript?.(entry)\n },\n onError: (message) => {\n if (!isCurrent()) {\n return\n }\n error.value = message\n },\n onDisconnect: (details) => {\n if (!isCurrent()) {\n return\n }\n clearCap()\n conversation.value = undefined\n // Said here rather than trusted to arrive: the interface and\n // the reload poll both read `status`, and a disconnect that\n // left it on 'connected' showed a live call that was over.\n status.value = 'disconnected'\n mode.value = 'listening'\n if (details.reason === 'error') {\n error.value = details.message\n }\n void releaseGrant(grant.sessionId)\n options.onTurnEnd?.()\n },\n })\n\n // Closed while the socket was opening: end it rather than leave a\n // live conversation nothing holds a reference to.\n if (!isCurrent()) {\n await conversationStarted.endSession().catch(() => undefined)\n await releaseGrant(grant.sessionId)\n return\n }\n conversation.value = conversationStarted\n startCap(grant.maxSessionSeconds)\n } catch (caught) {\n // Only ever this attempt's own grant: reading the shared id here\n // closed the session a newer attempt had just opened, and the\n // clearing below took its live conversation and its countdown with\n // it. That leaves the provider talking to a record we deleted, with\n // nothing left on this side to hang up on: every turn refused,\n // minutes billed. A user who starts a call, gives up and starts\n // another is all it takes.\n await releaseGrant(ownSessionId)\n if (!isCurrent()) {\n return\n }\n conversation.value = undefined\n clearCap()\n status.value = 'disconnected'\n error.value =\n caught instanceof Error ? caught.message : String(caught)\n }\n }\n\n /** Puts the failure away so the input can come back. */\n const dismissError = () => {\n error.value = undefined\n }\n\n const setMuted = (muted: boolean) => {\n conversation.value?.setMicMuted(muted)\n }\n\n /**\n * Says something on the caller's behalf, without the microphone.\n *\n * What the caller answers on screen during a call (a form, a set of\n * options) has no way back to the agent otherwise: the turn that drew the\n * widget is long over, and nothing the browser posts reaches a conversation\n * the provider is driving. Sent this way it becomes an ordinary user turn,\n * answered out loud like any other.\n *\n * Returns false when there is no live call to say it into, so the caller\n * can fall back to the written path.\n */\n const sendUserMessage = (text: string): boolean => {\n const active = conversation.value\n if (!active || !text.trim()) {\n return false\n }\n try {\n active.sendUserMessage(text)\n return true\n } catch (caught) {\n logger.warn('The spoken answer could not be sent', caught)\n return false\n }\n }\n\n /**\n * Instantaneous loudness of one side, 0 to 1. A function rather than a ref on\n * purpose: the visualiser samples it once per animation frame, and pushing 60\n * reactive writes a second through the whole component tree would cost more\n * than the animation itself.\n */\n const readLevel = (channel: VoiceChannel): number => {\n const active = conversation.value\n if (!active) {\n return 0\n }\n try {\n return channel === 'input'\n ? active.getInputVolume()\n : active.getOutputVolume()\n } catch {\n // The analyser is gone (session closing): silence is the truth.\n return 0\n }\n }\n\n /** Frequency bins of one side, for a visualiser with actual character. */\n const readSpectrum = (channel: VoiceChannel): Uint8Array | undefined => {\n const active = conversation.value\n if (!active) {\n return undefined\n }\n try {\n return channel === 'input'\n ? active.getInputByteFrequencyData()\n : active.getOutputByteFrequencyData()\n } catch {\n return undefined\n }\n }\n\n // A session outlives a route change unless it is closed here: the provider\n // keeps billing a socket nobody is listening to. A call in progress when the\n // tab goes away gets the same treatment, and `closeGrant` is what settles\n // its minutes.\n const releaseOnPageHide = () => {\n // Order matters here and nowhere else: the page may be killed at any\n // moment, so the request that settles the minutes goes out first (it is\n // sent with `keepalive`, which cannot help a fetch that never started),\n // and only then do we ask the provider to end the socket.\n const mine = sessionId\n sessionId = undefined\n generation += 1\n clearCap()\n void releaseGrant(mine)\n const active = conversation.value\n conversation.value = undefined\n void active?.endSession().catch(() => undefined)\n status.value = 'disconnected'\n }\n if (typeof window !== 'undefined') {\n window.addEventListener('pagehide', releaseOnPageHide)\n }\n\n onScopeDispose(() => {\n disposed = true\n if (typeof window !== 'undefined') {\n window.removeEventListener('pagehide', releaseOnPageHide)\n }\n void stop()\n })\n\n return {\n status,\n mode,\n error,\n transcript,\n remainingSeconds,\n chatId,\n isActive: computed(\n () => status.value === 'connected' || status.value === 'connecting',\n ),\n isConnecting: computed(() => status.value === 'connecting'),\n isSpeaking: computed(\n () => status.value === 'connected' && mode.value === 'speaking',\n ),\n isListening: computed(\n () => status.value === 'connected' && mode.value === 'listening',\n ),\n start,\n stop,\n dismissError,\n setMuted,\n sendUserMessage,\n readLevel,\n readSpectrum,\n }\n}\n","import type { InjectionKey, Ref } from 'vue'\nimport { inject, provide } from 'vue'\n\n/**\n * Where the viewer of a chat's Word documents and spreadsheets docks beside\n * the chat (spec `chat-office-files.md`, the viewer of the F6 follow-ups): a\n * page that lays the chat out between columns of its own, as the frontoffice\n * chat page does with its sidebar, gives an element for the viewer to take\n * the page's whole height, outside the chat's header and footer. Where\n * nothing is provided (the widget, the playground) the viewer stays a panel\n * inside the chat.\n */\nexport const ChatFilePreviewDockKey: InjectionKey<\n Readonly<Ref<HTMLElement | null | undefined>>\n> = Symbol('ChatFilePreviewDock')\n\n/** Gives the chats below the element their viewer docks in. */\nexport function provideChatFilePreviewDock(\n dock: Readonly<Ref<HTMLElement | null | undefined>>,\n) {\n provide(ChatFilePreviewDockKey, dock)\n}\n\n/** The element the viewer docks in, when the page gives one. */\nexport function useChatFilePreviewDock() {\n return inject(ChatFilePreviewDockKey, undefined)\n}\n","import { computed, onBeforeUnmount, ref, watch } from 'vue'\nimport type { ChatStatus } from 'ai'\nimport type { PendingWakeup, UIChatMessage } from 'models'\nimport type { ChatbotApiClient } from 'composables'\n\n/** How long after `dueAt` the first look comes: the turn takes a few seconds. */\nconst FIRST_LOOK_MS = 4000\nconst BACKOFF_MS = [3000, 5000, 10_000]\n/** A wakeup whose turn never shows up (skipped, failed) stops being watched. */\nconst WATCH_MAX_MS = 120_000\n/** The server forgets the presence after two lost signals (75 seconds). */\nconst PRESENCE_INTERVAL_MS = 30_000\n\n/**\n * Keeps an open chat in step with its wakeups (spec agent-wakeup, \"Consegna\"):\n * nothing pushes to the page, so it reads the pending wakeup, sleeps until its\n * time and then reloads the conversation until the wakeup's turn is in it,\n * which the seed carrying its id proves (the seed and the answer are written\n * together). Then it reads the next one, if the turn scheduled it. The\n * pending one is read when the chat changes and after every turn of the\n * user, typed or spoken, which may have scheduled it.\n *\n * While a wakeup waits, the page also tells the server it is in front of the\n * user (Fase 1.2): every 30 seconds while the tab is visible, and at once\n * when it comes back in front, so a round with news mails only a user who\n * is away. A page with no wakeup waiting sends nothing.\n */\nexport function useWakeupWatch(options: {\n agentId: () => string\n chatId: () => string\n apiClient: () => ChatbotApiClient\n messages: () => UIChatMessage[]\n refreshMessages: () => Promise<unknown>\n status: () => ChatStatus\n}) {\n const pendingWakeup = ref<PendingWakeup | null>(null)\n const isStopping = ref(false)\n let timer: ReturnType<typeof setTimeout> | undefined\n let isUnmounted = false\n\n const clear = () => {\n clearTimeout(timer)\n timer = undefined\n }\n\n const later = (delayMs: number, run: () => Promise<void>) => {\n clear()\n if (!isUnmounted) {\n timer = setTimeout(() => void run(), delayMs)\n }\n }\n\n const hasTurnOf = (wakeId: string) =>\n options\n .messages()\n .some((message) => message.metadata?.wakeup?.id === wakeId)\n\n /** Reads the pending wakeup and arms the first look at its time. */\n async function check(): Promise<void> {\n clear()\n const chatId = options.chatId()\n try {\n const state = await options\n .apiClient()\n .getChatWakeup(options.agentId(), chatId)\n if (chatId !== options.chatId()) {\n return\n }\n pendingWakeup.value = state.pendingWakeup\n } catch {\n // A chat not written yet, or a request that failed: nothing to\n // watch until the next turn asks again.\n pendingWakeup.value = null\n }\n const pending = pendingWakeup.value\n if (pending) {\n const wait = Date.parse(pending.dueAt) - Date.now() + FIRST_LOOK_MS\n later(Math.max(FIRST_LOOK_MS, wait), () =>\n watchTurn(pending.wakeId, Date.now(), 0),\n )\n }\n }\n\n async function watchTurn(wakeId: string, since: number, step: number) {\n await options.refreshMessages()\n if (isUnmounted) {\n return\n }\n if (hasTurnOf(wakeId) || Date.now() - since >= WATCH_MAX_MS) {\n await check()\n return\n }\n // Still not there: maybe deferred behind a turn of the user, whose\n // new time `check` would read; keep looking until the cap.\n later(BACKOFF_MS[Math.min(step, BACKOFF_MS.length - 1)], () =>\n watchTurn(wakeId, since, step + 1),\n )\n }\n\n /** The user's \"Stop\": the pending wakeup never runs. */\n async function stop(): Promise<void> {\n isStopping.value = true\n try {\n const state = await options\n .apiClient()\n .stopChatWakeup(options.agentId(), options.chatId())\n clear()\n pendingWakeup.value = state.pendingWakeup\n } finally {\n isStopping.value = false\n }\n }\n\n /**\n * Another chat on screen: the watch of the previous one ends, or its\n * timer would go on reloading the new chat for minutes.\n */\n function reset(): void {\n clear()\n pendingWakeup.value = null\n }\n\n // #region spoken turns\n /**\n * The chat of a spoken question whose turn is not written yet. A call\n * leaves the chat `ready`, so the status does not show its turns: the\n * page says when one starts and when the reloaded chat has them all.\n */\n let spokenTurnUnwrittenIn: string | undefined\n\n /** A spoken question entered the chat: the server answers its turn. */\n function spokenTurnStarted(): void {\n spokenTurnUnwrittenIn = options.chatId()\n }\n\n /**\n * The reloaded chat has every spoken question written: their turns may\n * have scheduled a wakeup.\n */\n function spokenTurnsWritten(): void {\n if (spokenTurnUnwrittenIn === options.chatId()) {\n spokenTurnUnwrittenIn = undefined\n void check()\n }\n }\n\n /** The page stopped waiting: a turn still unwritten is not coming. */\n function forgetSpokenTurns(): void {\n spokenTurnUnwrittenIn = undefined\n }\n // #endregion spoken turns\n\n // #region when to read\n const hasQuestions = computed(() =>\n options.messages().some((message) => message.role === 'user'),\n )\n // A chat with no question has none, and the messages of a chat opened\n // later arrive after its id: the read waits for its questions. A question\n // just sent is read after its turn instead, by the watch below or, for a\n // spoken one, by `spokenTurnsWritten`: the first one of a new chat has no\n // row on the server yet, and the read got a 404.\n watch(\n [options.chatId, hasQuestions],\n ([, questions]) => {\n reset()\n const status = options.status()\n const answering =\n status === 'submitted' ||\n status === 'streaming' ||\n spokenTurnUnwrittenIn === options.chatId()\n if (questions && !answering) {\n void check()\n }\n },\n { immediate: true },\n )\n watch(options.status, (status, previous) => {\n if (status === 'ready' && previous !== 'ready' && hasQuestions.value) {\n void check()\n }\n })\n // #endregion when to read\n\n // #region presence\n let presenceTimer: ReturnType<typeof setInterval> | undefined\n\n /** Best effort: a lost signal costs at most one mail the user did not need. */\n function sendPresence(): void {\n if (!pendingWakeup.value || document.visibilityState !== 'visible') {\n return\n }\n options\n .apiClient()\n .markChatWakeupPresence(options.agentId(), options.chatId())\n .catch(() => undefined)\n }\n\n const onVisibilityChange = () => sendPresence()\n document.addEventListener('visibilitychange', onVisibilityChange)\n\n watch(\n () => pendingWakeup.value?.wakeId,\n (wakeId) => {\n clearInterval(presenceTimer)\n presenceTimer = undefined\n if (wakeId && !isUnmounted) {\n sendPresence()\n presenceTimer = setInterval(sendPresence, PRESENCE_INTERVAL_MS)\n }\n },\n )\n // #endregion presence\n\n onBeforeUnmount(() => {\n isUnmounted = true\n clear()\n clearInterval(presenceTimer)\n document.removeEventListener('visibilitychange', onVisibilityChange)\n })\n\n return {\n pendingWakeup,\n isStopping,\n check,\n reset,\n stop,\n spokenTurnStarted,\n spokenTurnsWritten,\n forgetSpokenTurns,\n }\n}\n","import type {\n ChatFilePreview,\n SpreadsheetPreview,\n SpreadsheetPreviewSheet,\n WordPreview,\n WordPreviewBlock,\n WordPreviewCell,\n} from 'models'\n\n/**\n * What a version of a file changed from the one the viewer showed before it\n * (spec `chat-file-selection-edit.md`): the paragraphs of a Word document by\n * their ids in the new version, or the cells of each sheet, by its name, as\n * `row:col`. The viewer marks them for a moment when it follows an edit.\n */\nexport type ChatFilePreviewChanges =\n | { kind: 'word'; paragraphs: ReadonlySet<string> }\n | {\n kind: 'spreadsheet'\n cells: ReadonlyMap<string, ReadonlySet<string>>\n }\n\n/**\n * Past this many pairs the middle of the two lists is not aligned: all of\n * the new one there counts as changed. A thousand paragraphs each side.\n */\nconst MAX_ALIGNED_PAIRS = 1_000_000\n\n/**\n * The items of `after` that `before` does not hold in the same order, each\n * with the item of `before` it took the place of, if any: the one at the\n * same distance from the start of the stretch both lists differ in. The\n * common start and end are skipped, the middle is aligned by its longest\n * common subsequence.\n */\nexport const unmatchedItems = (\n before: readonly string[],\n after: readonly string[],\n): Map<number, number | undefined> => {\n let start = 0\n while (\n start < before.length &&\n start < after.length &&\n before[start] === after[start]\n ) {\n start += 1\n }\n let end = 0\n while (\n end < before.length - start &&\n end < after.length - start &&\n before[before.length - 1 - end] === after[after.length - 1 - end]\n ) {\n end += 1\n }\n const n = before.length - start - end\n const m = after.length - start - end\n const out = new Map<number, number | undefined>()\n // Each stretch between two kept items: its new items stand for its old\n // ones in order\n const gap = (i0: number, i1: number, j0: number, j1: number) => {\n for (let j = j0; j < j1; j++) {\n const i = i0 + (j - j0)\n out.set(j, i < i1 ? i : undefined)\n }\n }\n if (!m) {\n return out\n }\n if (!n || n * m > MAX_ALIGNED_PAIRS) {\n gap(start, start + n, start, start + m)\n return out\n }\n // lengths[i * (m + 1) + j]: the longest common subsequence of the old\n // middle from i and the new one from j\n const lengths = new Uint32Array((n + 1) * (m + 1))\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lengths[i * (m + 1) + j] =\n before[start + i] === after[start + j]\n ? lengths[(i + 1) * (m + 1) + j + 1] + 1\n : Math.max(\n lengths[(i + 1) * (m + 1) + j],\n lengths[i * (m + 1) + j + 1],\n )\n }\n }\n let i = 0\n let j = 0\n let i0 = 0\n let j0 = 0\n while (i < n && j < m) {\n if (before[start + i] === after[start + j]) {\n gap(start + i0, start + i, start + j0, start + j)\n i += 1\n j += 1\n i0 = i\n j0 = j\n } else if (\n lengths[(i + 1) * (m + 1) + j] >= lengths[i * (m + 1) + j + 1]\n ) {\n i += 1\n } else {\n j += 1\n }\n }\n gap(start + i0, start + n, start + j0, start + m)\n return out\n}\n\n/** A paragraph's id moves when one is added before it: it is not its content. */\nconst withoutIds = (key: string, value: unknown) =>\n key === 'id' || key === 'ids' ? undefined : value\n\nconst contentOf = (value: unknown) => JSON.stringify(value, withoutIds)\n\n/** The ids of a table's cells that differ from the table it took the place of. */\nconst changedCellIds = (\n after: WordPreviewBlock & { kind: 'table' },\n before: WordPreviewBlock | undefined,\n): string[] => {\n const idsOf = (cells: WordPreviewCell[]) =>\n cells.flatMap((c) => c.ids ?? [])\n if (before?.kind !== 'table') {\n return idsOf(after.rows.flat())\n }\n const rows = unmatchedItems(\n before.rows.map(contentOf),\n after.rows.map(contentOf),\n )\n return [...rows].flatMap(([r, was]) => {\n const old = was === undefined ? undefined : before.rows[was]\n return idsOf(\n after.rows[r].filter(\n (cell, c) => !old?.[c] || contentOf(old[c]) !== contentOf(cell),\n ),\n )\n })\n}\n\nconst wordChanges = (before: WordPreview, after: WordPreview) => {\n const paragraphs = new Set<string>()\n const blocks = unmatchedItems(\n before.blocks.map(contentOf),\n after.blocks.map(contentOf),\n )\n for (const [b, was] of blocks) {\n const block = after.blocks[b]\n if (block.kind === 'table') {\n const old = was === undefined ? undefined : before.blocks[was]\n for (const id of changedCellIds(block, old)) {\n paragraphs.add(id)\n }\n } else if (block.id) {\n paragraphs.add(block.id)\n }\n }\n return paragraphs\n}\n\n/**\n * A cell as it shows: its look and number format by what they are, as each\n * version numbers its own lists of them.\n */\nconst cellContents = (\n preview: SpreadsheetPreview,\n sheet: SpreadsheetPreviewSheet,\n) => {\n const out = new Map<string, string>()\n for (const r of sheet.rows) {\n for (const cell of r.cells) {\n out.set(\n `${r.row}:${cell.col}`,\n JSON.stringify({\n ...cell,\n style:\n cell.style === undefined\n ? undefined\n : preview.styles[cell.style],\n numFmt:\n cell.numFmt === undefined\n ? undefined\n : preview.numberFormats?.[cell.numFmt],\n }),\n )\n }\n }\n return out\n}\n\nconst spreadsheetChanges = (\n before: SpreadsheetPreview,\n after: SpreadsheetPreview,\n) => {\n const cells = new Map<string, ReadonlySet<string>>()\n for (const sheet of after.sheets) {\n const old = before.sheets.find((s) => s.name === sheet.name)\n const now = cellContents(after, sheet)\n const was = old ? cellContents(before, old) : new Map<string, string>()\n const changed = new Set<string>()\n for (const [at, content] of now) {\n if (was.get(at) !== content) {\n changed.add(at)\n }\n }\n // A cell emptied is gone from the new version's list\n for (const at of was.keys()) {\n if (!now.has(at)) {\n changed.add(at)\n }\n }\n if (changed.size) {\n cells.set(sheet.name, changed)\n }\n }\n return cells\n}\n\n/**\n * What `after` changed from `before`, two versions of the same file: none\n * when nothing the viewer draws differs, or the two are not of one format.\n */\nexport const chatFilePreviewChanges = (\n before: ChatFilePreview,\n after: ChatFilePreview,\n): ChatFilePreviewChanges | undefined => {\n if (before.kind === 'word' && after.kind === 'word') {\n const paragraphs = wordChanges(before, after)\n return paragraphs.size ? { kind: 'word', paragraphs } : undefined\n }\n if (before.kind === 'spreadsheet' && after.kind === 'spreadsheet') {\n const cells = spreadsheetChanges(before, after)\n return cells.size ? { kind: 'spreadsheet', cells } : undefined\n }\n return undefined\n}\n\n/**\n * Brings the first marked change into the middle of the viewer's own scroll\n * box, when it is not in sight already. Not `scrollIntoView`: it would scroll\n * the page around the viewer too. False while there is none drawn yet.\n */\nexport const revealFirstChange = (\n scroller: HTMLElement | null | undefined,\n selector: string,\n): boolean => {\n const el = scroller?.querySelector(selector)\n if (!scroller || !el) {\n return false\n }\n const box = scroller.getBoundingClientRect()\n const at = el.getBoundingClientRect()\n if (at.top < box.top || at.bottom > box.bottom) {\n scroller.scrollTop += at.top - box.top - (box.height - at.height) / 2\n }\n if (at.left < box.left || at.right > box.right) {\n scroller.scrollLeft += at.left - box.left - (box.width - at.width) / 2\n }\n return true\n}\n","import { ref, shallowRef } from 'vue'\nimport type { ChatFilePreview } from 'models'\nimport {\n chatFilePreviewChanges,\n type ChatFilePreviewChanges,\n} from './previewChanges'\nimport type { ChatFilePreviewTarget } from './utils'\n\n/** How long the viewer marks what a version changed. */\nexport const CHAT_FILE_CHANGES_MS = 4000\n\n/**\n * The preview of a Word document or a spreadsheet stored in a chat (spec\n * `chat-office-files.md`, F6, items 3 and 4): the file it shows, its content\n * once read, and the read. `read` asks the server for one stored file of the\n * chat on screen. A version never changes, so each one is read once until\n * `reset`, which a view calls when it shows another chat. Opened `since` the\n * version on screen, as the viewer that follows an edit does, it also tells\n * what changed, for a few seconds (spec `chat-file-selection-edit.md`).\n */\nexport function useChatFilePreview(\n read: (storedFileName: string) => Promise<ChatFilePreview>,\n) {\n const target = ref<ChatFilePreviewTarget>()\n const preview = ref<ChatFilePreview>()\n const loading = ref(false)\n const error = ref(false)\n const changes = shallowRef<ChatFilePreviewChanges>()\n const cache = new Map<string, ChatFilePreview>()\n let changesTimer: ReturnType<typeof setTimeout> | undefined\n /**\n * Counts every `open` and `close`: only the answer of the open still on\n * screen reaches the view. Told apart by call, not by file: the same\n * file opened again while its first read is out took that read's failure\n * as its own and said \"unavailable\" over the content.\n */\n let lastOpen = 0\n /** Bumped by `reset`: a read of the chat before is not kept. */\n let chatGeneration = 0\n\n const dropChanges = () => {\n clearTimeout(changesTimer)\n changes.value = undefined\n }\n /**\n * The preview and what it changed from `before`, set together, so a\n * view that draws it anew finds both at once.\n */\n const show = (\n data: ChatFilePreview | undefined,\n before?: ChatFilePreview,\n ) => {\n dropChanges()\n const changed =\n data && before ? chatFilePreviewChanges(before, data) : undefined\n if (changed) {\n changes.value = changed\n changesTimer = setTimeout(dropChanges, CHAT_FILE_CHANGES_MS)\n }\n preview.value = data\n }\n\n /** `since`: the stored name of the version this one follows on screen. */\n const open = async (next: ChatFilePreviewTarget, since?: string) => {\n const call = ++lastOpen\n const generation = chatGeneration\n const before = since ? cache.get(since) : undefined\n target.value = next\n error.value = false\n const cached = cache.get(next.storedFileName)\n show(cached, before)\n // Another preview may still be loading: this one is not.\n loading.value = false\n if (cached) {\n return\n }\n loading.value = true\n const current = () => call === lastOpen\n try {\n const data = await read(next.storedFileName)\n if (generation === chatGeneration) {\n cache.set(next.storedFileName, data)\n }\n if (current()) {\n show(data, before)\n }\n } catch {\n if (current()) {\n error.value = true\n }\n } finally {\n if (current()) {\n loading.value = false\n }\n }\n }\n\n const close = () => {\n target.value = undefined\n lastOpen += 1\n dropChanges()\n }\n\n const reset = () => {\n close()\n cache.clear()\n chatGeneration += 1\n }\n\n return { target, preview, loading, error, changes, open, close, reset }\n}\n","<script setup lang=\"ts\">\n import {\n computed,\n onBeforeUnmount,\n provide,\n ref,\n useTemplateRef,\n watch,\n defineAsyncComponent,\n } from 'vue'\n import { useI18n } from 'vue-i18n'\n import { useDropZone, useResizeObserver } from '@vueuse/core'\n import { storeToRefs } from 'pinia'\n import { generateId } from 'ai'\n import PkAuroraCanvas from './PkAuroraCanvas.vue'\n import PkAvatar from './PkAvatar.vue'\n import PkChatbotMessages from './PkChatbotMessages.vue'\n import PkChatbotInput from './PkChatbotInput.vue'\n import PkChatbotQueuedMessages from './PkChatbotQueuedMessages.vue'\n import PkChatbotEmptyState from './PkChatbotEmptyState.vue'\n import PkVoiceSession from './PkVoiceSession.vue'\n import PkChatbotWakeupBar from './PkChatbotWakeupBar.vue'\n import { useVoiceSession } from './useVoiceSession'\n import { useChatFilePreviewDock } from './chatFilePreviewDock'\n import { useWakeupWatch } from './useWakeupWatch'\n import { useChatFilePreview } from './useChatFilePreview'\n import { provideImageAnnotation } from '../composables/useLightbox'\n import {\n chatFileName,\n formAnswerAsSpoken,\n getPartState,\n HOST_STEP_CHANGES,\n HOST_STEP_TITLES,\n type ChatFilePreviewTarget,\n type ChatFileRestoreTarget,\n type WordPreviewMode,\n } from './utils'\n import { getFilePartMedia, isFilePart } from 'utils'\n import {\n useChatbotStore,\n useLocalizedString,\n useGreeting,\n VOICE_LINE_ID_PREFIX,\n } from 'composables'\n import {\n chatDropAccepts,\n type FilePointer,\n type UIChatMessage,\n } from 'models'\n\n const PkToolShowForm = defineAsyncComponent(\n () => import('./PkToolShowForm.vue'),\n )\n const PkToolShowContactForm = defineAsyncComponent(\n () => import('./PkToolShowContactForm.vue'),\n )\n const PkToolShowSuggestedReply = defineAsyncComponent(\n () => import('./PkToolShowSuggestedReply.vue'),\n )\n const PkToolShowSources = defineAsyncComponent(\n () => import('./PkToolShowSources.vue'),\n )\n const PkToolRequestGeolocation = defineAsyncComponent(\n () => import('./PkToolRequestGeolocation.vue'),\n )\n const PkToolRequestOAuthConnection = defineAsyncComponent(\n () => import('./PkToolRequestOAuthConnection.vue'),\n )\n const PkToolShowLocation = defineAsyncComponent(\n () => import('./PkToolShowLocation.vue'),\n )\n const PkToolShowChart = defineAsyncComponent(\n () => import('./PkToolShowChart.vue'),\n )\n const PkToolShowDiagram = defineAsyncComponent(\n () => import('./PkToolShowDiagram.vue'),\n )\n const PkToolChatFile = defineAsyncComponent(\n () => import('./PkToolChatFile.vue'),\n )\n const PkToolShareDocument = defineAsyncComponent(\n () => import('./PkToolShareDocument.vue'),\n )\n const PkFilePreview = defineAsyncComponent(\n () => import('./PkFilePreview.vue'),\n )\n const PkFilePreviewDialog = defineAsyncComponent(\n () => import('./PkFilePreviewDialog.vue'),\n )\n\n const props = defineProps<{\n agentId: string\n /** Mirrors the PkChatbot `modifier` prop: `fullscreen` shows a centered empty state (greeting) instead of the welcome message, `panel` behaves like `widget` */\n modifier?: 'widget' | 'fullscreen' | 'panel'\n /** Display name of the current user, used for the `{name}` greeting placeholder */\n userName?: string\n }>()\n\n const emit = defineEmits<{\n 'show-info': [message: UIChatMessage]\n revise: [message: UIChatMessage]\n /** An action of the file viewer's selection bar was sent: the telemetry's properties. */\n 'selection-action': [properties: Record<string, string>]\n }>()\n\n const store = useChatbotStore(props.agentId)\n\n const {\n agentInterface,\n agentFileUpload: storedFileUpload,\n agentType,\n agentVoice,\n actions,\n revisedAnswers,\n messages,\n chat,\n messageFeedbacks,\n feedbackDialogMessage,\n isFeedbackSubmitting,\n isFeedbackSubmitted,\n feedbackSubmitError,\n isLeadSubmitted,\n isLoadingSubmitLead,\n submitLeadError,\n input,\n inputMessagePlaceholder,\n isConversationBlocked,\n baseUrl,\n pendingAttachments,\n isAttachmentLimitReached,\n fileLimitError,\n apiClient,\n isDark,\n hostToolsPending,\n pageNoticeLevel,\n hostConfirmation,\n agentPageAccess,\n hostStepTitles,\n hostStepChanges,\n confirmationMode,\n canQueue,\n queuedMessages,\n backgroundAnswers,\n inputFocusRequest,\n pagePointer,\n pagePointerAvailable,\n pagePointing,\n agentSelectionActions,\n } = storeToRefs(store)\n // The steps of the page name what they act on while the page is open\n provide(HOST_STEP_TITLES, hostStepTitles)\n // And what they changed, when the automatic confirmations asked nothing\n provide(HOST_STEP_CHANGES, hostStepChanges)\n\n // The host asks for the message field (⇧Esc on the chat page)\n const inputEl =\n useTemplateRef<InstanceType<typeof PkChatbotInput>>('inputEl')\n watch(inputFocusRequest, () => {\n inputEl.value?.focus()\n })\n // What the user just pointed at on the page goes with what they write\n // next (spec page-point-and-choose.md, P): the field takes the focus\n watch(pagePointer, (pointer) => {\n if (pointer) {\n inputEl.value?.focus()\n }\n })\n const pointerChip = computed(() =>\n pagePointer.value\n ? { kind: pagePointer.value.kind, label: pagePointer.value.label }\n : undefined,\n )\n\n // A reasoning agent reads no attachment, and the backend refuses one: no\n // attach button and no drop zone, whatever its upload settings say.\n const agentFileUpload = computed(() =>\n agentType.value === 'reasoning' ? undefined : storedFileUpload.value,\n )\n\n // \"Annota e chiedi\" in the lightbox of this conversation (spec\n // `chat-image-editor.md`, F3): the composer takes the annotated copy\n // while it is shown (not during a call), takes images and is not full\n const takesImages = computed(() => {\n const allowed = agentFileUpload.value?.allowedMimeTypes ?? []\n return (\n !!agentFileUpload.value?.enabled &&\n (!allowed.length || allowed.some((m) => m.startsWith('image/')))\n )\n })\n provideImageAnnotation({\n available: () =>\n !!inputEl.value &&\n takesImages.value &&\n !isAttachmentLimitReached.value,\n annotate: (file) => inputEl.value?.annotateImage(file),\n })\n\n /** A file the agent stored in this chat, such as a spreadsheet version. */\n const chatFileDownloadUrl = (storedFileName: string) =>\n apiClient.value.getMediaDownloadUrl(\n props.agentId,\n store.localChatId,\n storedFileName,\n )\n\n const {\n handleSubmit: storeHandleSubmit,\n stopGeneration,\n regenerate,\n onUpvote,\n onDownvote,\n onFeedback,\n onFeedbackSubmit,\n onLeadSubmit,\n startNewChat,\n addToolOutput,\n addToolApprovalResponse,\n handleFileSelect,\n discardPendingAttachment,\n replacePendingAttachment,\n retryPendingAttachment,\n clearFileLimitError,\n refreshMessages,\n appendMessage,\n closePageNotice,\n respondHostConfirmation,\n editQueuedMessage,\n removeQueuedMessage,\n openBackgroundAnswer,\n dismissBackgroundAnswer,\n } = store\n\n const { t: $t } = useI18n({ useScope: 'global' })\n\n // The embedding page runs calls of the last answer (spec `host-tools.md`):\n // the request that announced them is over and the chat reads `ready`, yet\n // the answer is not. The input shows the work and its stop.\n const hostWorking = computed(() => hostToolsPending.value > 0)\n const inputStatus = computed(() =>\n hostWorking.value && chat.value.status === 'ready'\n ? 'streaming'\n : chat.value.status,\n )\n // The customer's own words when the agent has them, else what the\n // level allows.\n const customPageNotice = useLocalizedString(\n () => agentPageAccess.value?.notice,\n )\n const pageNotice = computed(() =>\n pageNoticeLevel.value\n ? customPageNotice.value ||\n $t(`message.pageAccessNotice.${pageNoticeLevel.value}`)\n : undefined,\n )\n\n const attachmentNotice = computed(() => {\n const err = fileLimitError.value\n if (!err) {\n return undefined\n }\n return err.reason === 'per-chat'\n ? $t('message.fileLimitPerChat', { max: err.max })\n : $t('message.fileLimitPerMessage', { max: err.max })\n })\n\n // Answers that ended in a conversation the user left (spec\n // resumable-chat-streams, F2), named by its title when the list has it.\n const answerNotices = computed(() =>\n backgroundAnswers.value.map(({ chatId, title }) => ({\n id: chatId,\n text: title\n ? $t('message.backgroundAnswerReady', { title })\n : $t('message.backgroundAnswerReadyUntitled'),\n })),\n )\n\n const dismissableNotice = useLocalizedString(\n () => agentInterface.value?.dismissableNotice,\n )\n\n // Fullscreen empty state: shown until the user sends the first message.\n // The synthetic welcome message is suppressed by the store in fullscreen\n // (`hideWelcomeMessage`), the greeting takes its place.\n const hasUserMessages = computed(() =>\n messages.value.some((message) => message.role === 'user'),\n )\n const showEmptyState = computed(\n () => props.modifier === 'fullscreen' && !hasUserMessages.value,\n )\n const greeting = useGreeting(agentInterface, () => props.userName)\n\n const chatViewEl = useTemplateRef<HTMLDivElement>('chatViewEl')\n\n // #region file preview\n /**\n * Where the preview of a Word document or a spreadsheet opens (spec\n * `chat-office-files.md`, F6, items 3 and 4): beside the chat when the chat has room for a reading\n * column and the panel, over it in a dialog otherwise. Measured on the\n * chat, not on the window: the floating widget, the playground and a page\n * with the Copilot docked beside it are narrow on a wide screen.\n */\n const PREVIEW_PANEL_MIN_WIDTH = 1000\n /**\n * A page that lays the chat out between its own columns gives the panel\n * a column of the page's height (`provideChatFilePreviewDock`): the\n * panel takes its width from the chat, so the two together are the room\n * the panel opens in.\n */\n const previewDock = useChatFilePreviewDock()\n const previewDocked = computed(() => !!previewDock?.value)\n // A ref read in the template is unwrapped: the target goes through here\n const previewDockTarget = computed(() => previewDock?.value ?? 'body')\n const chatViewWidth = ref(0)\n const dockWidth = ref(0)\n // The border box: the panel's room is padding of the chat, and measured\n // without it the open panel took the width that opened it. One observer\n // for the chat and the dock: with two, the chat narrowed by the panel\n // arrived alone, the panel closed before the dock's width came, and the\n // preview went back and forth between the panel and the dialog.\n useResizeObserver(\n [chatViewEl, computed(() => previewDock?.value ?? undefined)],\n (entries) => {\n for (const entry of entries) {\n const width =\n entry.borderBoxSize?.[0]?.inlineSize ??\n entry.contentRect.width\n if (entry.target === chatViewEl.value) {\n chatViewWidth.value = width\n } else {\n dockWidth.value = width\n }\n }\n },\n { box: 'border-box' },\n )\n const previewInPanel = computed(\n () =>\n chatViewWidth.value + (previewDocked.value ? dockWidth.value : 0) >=\n PREVIEW_PANEL_MIN_WIDTH,\n )\n const previewFullscreen = computed(\n () => chatViewWidth.value > 0 && chatViewWidth.value < 576,\n )\n const {\n target: previewTarget,\n preview: previewData,\n loading: previewLoading,\n error: previewError,\n changes: previewChanges,\n open: openFilePreview,\n close: closeFilePreview,\n reset: resetPreview,\n } = useChatFilePreview((storedFileName) =>\n apiClient.value.getChatFilePreview(\n props.agentId,\n store.localChatId,\n storedFileName,\n ),\n )\n /**\n * How the open file is shown: its revisions, sheet and zoom. The viewer\n * is drawn anew when it moves between the panel and the dialog, and\n * takes these along; another file starts afresh.\n */\n const previewView = ref<{\n mode?: WordPreviewMode\n sheet?: number\n zoom?: number\n fit?: boolean\n }>({})\n\n /** `since`: the version on screen, when the viewer follows an edit. */\n const openPreview = (target: ChatFilePreviewTarget, since?: string) => {\n const fileOf = (t?: ChatFilePreviewTarget) =>\n t?.fileId ?? t?.storedFileName\n if (fileOf(target) !== fileOf(previewTarget.value)) {\n previewView.value = {}\n }\n return openFilePreview(target, since)\n }\n\n /** The panel grown into a dialog over the chat, on the viewer's button. */\n const previewExpanded = ref(false)\n const previewBeside = computed(\n () =>\n !!previewTarget.value &&\n previewInPanel.value &&\n !previewExpanded.value,\n )\n\n const closePreview = () => {\n closeFilePreview()\n previewExpanded.value = false\n }\n\n /**\n * The tools whose calls write a file of this chat, a version each.\n * Declared before the computed that reads it: the watch on that computed\n * runs it during setup, and the welcome message is already there.\n */\n const CHAT_FILE_TOOL_PARTS = new Set([\n 'tool-editSpreadsheet',\n 'tool-editWordDocument',\n 'tool-createSpreadsheet',\n 'tool-createWordDocument',\n ])\n\n /**\n * Every version of each file in the conversation, by its fileId: the\n * file written by the user or the agent is version 1, its stored name is\n * the fileId.\n */\n const chatFileVersions = computed(() => {\n const byFile = new Map<string, Map<number, string>>()\n for (const message of messages.value) {\n for (const part of message.parts) {\n const { type, state, output } = part as {\n type: string\n state?: string\n output?: {\n fileId?: string\n version?: number\n storedFileName?: string\n }\n }\n if (\n CHAT_FILE_TOOL_PARTS.has(type) &&\n state === 'output-available' &&\n output?.fileId &&\n output.version &&\n output.storedFileName\n ) {\n const versions = byFile.get(output.fileId) ?? new Map()\n versions.set(output.version, output.storedFileName)\n byFile.set(output.fileId, versions)\n }\n }\n }\n for (const [fileId, versions] of byFile) {\n if (!versions.has(1)) {\n versions.set(1, fileId)\n }\n }\n return byFile\n })\n const previewVersions = computed(() =>\n [\n ...(chatFileVersions.value\n .get(previewTarget.value?.fileId ?? '')\n ?.keys() ?? []),\n ].sort((a, b) => a - b),\n )\n const showPreviewVersion = (version: number, since?: string) => {\n const target = previewTarget.value\n const storedFileName = chatFileVersions.value\n .get(target?.fileId ?? '')\n ?.get(version)\n if (target && storedFileName) {\n openPreview({ ...target, version, storedFileName }, since)\n }\n }\n /** The shown version is an earlier one the agent can write again. */\n const previewRestorable = computed(() => {\n const target = previewTarget.value\n const versions = previewVersions.value\n return (\n !!chatFileRestore.value &&\n !!target?.fileId &&\n !!target.version &&\n versions.length > 0 &&\n target.version < versions[versions.length - 1]\n )\n })\n const restoreFromPreview = () => {\n const target = previewTarget.value\n if (target?.fileId && target.version) {\n chatFileRestore.value?.({\n fileId: target.fileId,\n version: target.version,\n filename: target.filename,\n })\n closePreview()\n }\n }\n\n // Another chat has other files.\n watch(() => store.localChatId, resetPreview)\n\n // An edit makes a new version: the viewer showing the latest one moves to\n // it and marks what changed (spec chat-file-selection-edit.md), and an\n // earlier one stays put.\n // Read only while a file is open: the versions scan every message, and a\n // watch on all of them ran at each streamed delta, viewer closed too.\n watch(\n () => {\n const fileId = previewTarget.value?.fileId\n return fileId\n ? { fileId, newest: Math.max(0, ...previewVersions.value) }\n : undefined\n },\n (now, before) => {\n if (\n now &&\n before &&\n now.fileId === before.fileId &&\n now.newest > before.newest &&\n previewTarget.value?.version === before.newest\n ) {\n showPreviewVersion(\n now.newest,\n previewTarget.value.storedFileName,\n )\n }\n },\n )\n\n /**\n * The selection bar's actions for the open file's format (spec\n * `chat-file-selection-edit.md`): none in a conversation that takes no\n * message, nor while an answer runs.\n */\n const previewSelectionActions = computed(() => {\n const status = chat.value?.status\n if (\n isConversationBlocked.value ||\n status === 'submitted' ||\n status === 'streaming'\n ) {\n return undefined\n }\n return previewTarget.value?.kind === 'word'\n ? agentSelectionActions.value?.word\n : agentSelectionActions.value?.excel\n })\n const sendFromPreview = (\n text: string,\n pointer: FilePointer,\n action: { id: string; size: number },\n ) => {\n if (store.sendSelection(text, { filePointer: pointer })) {\n emit('selection-action', {\n surface: pointer.format === 'docx' ? 'word' : 'excel',\n action: action.id,\n state: 'chat',\n size: String(action.size),\n })\n }\n }\n // #endregion\n\n const handleExpandSourceContext = async (payload: {\n documentId: string\n chunkIndex: number\n }) => {\n const result = await apiClient.value.expandSourceContext(\n props.agentId,\n payload.documentId,\n payload.chunkIndex,\n )\n return result.content\n }\n\n const handleDownloadSource = async (documentId: string) => {\n const result = await apiClient.value.downloadSourceDocument(\n props.agentId,\n documentId,\n )\n window.open(result.downloadUrl, '_blank')\n }\n\n const handleFileDrop = (files: File[] | null) => {\n if (!agentFileUpload.value?.enabled || !files) {\n return\n }\n for (const file of files) {\n handleFileSelect(file)\n }\n }\n\n const { isOverDropZone } = useDropZone(chatViewEl, {\n dataTypes: (types) =>\n chatDropAccepts(\n types,\n agentFileUpload.value?.allowedMimeTypes ?? [],\n ),\n onDrop: handleFileDrop,\n })\n\n // #region voice\n /**\n * A spoken turn is a normal turn: the provider calls our backend, which\n * persists it into this very conversation. So the client does not answer\n * anything here, it only shows the transcript as it arrives and then reloads\n * the conversation from the server, which is the version that also carries\n * sources and tool results. When the call ends the input comes back with the\n * whole exchange above it, ready to continue in writing.\n */\n const isMuted = ref(false)\n // The session closes asynchronously, so `onTurnEnd` can still fire after\n // this view is gone: without the flag it would schedule a reload of a\n // conversation nobody is showing.\n let isUnmounted = false\n\n /**\n * True between the caller finishing a sentence and the answer starting.\n *\n * On a call nothing of the turn passes through this client, so the feed has\n * no way of its own to show that something is happening: the question sits\n * there alone until the answer is written and reloaded, which on a\n * retrieving turn is a long ten seconds of a screen that looks stuck.\n */\n const isAwaitingSpokenAnswer = ref(false)\n\n /**\n * How the conversation catches up with what the server persisted: one\n * sequential chain of reloads, the next scheduled only when the previous\n * one has answered, so slow responses never pile up. It replaces an\n * interval plus a backed-off retry ladder that could overlap each other.\n *\n * While the call is live it looks every {@link POLL_LIVE_MS}. When the\n * call is over (hang-up, provider disconnect, time cap) it keeps looking:\n * the turn that killed the call is by definition longer than the\n * provider's own timeout, and its write can land minutes later. Measured\n * live (2026-08-26, chat FYYaVLwX1UyU3CnQ): answers persisted 172 seconds\n * and 6.5 minutes after their turn started, both past the fixed 60-second\n * grace this replaces, and the screen stayed frozen until a manual reload.\n */\n const POLL_LIVE_MS = 3000\n const POLL_ENDED_BACKOFF_MS = [3000, 5000, 10_000]\n /**\n * The after-call poll never gives up before this, even with nothing on\n * screen looking missing: a write can land late and leave no trace to wait\n * for, because a turn the provider never transcribed has no spoken line of\n * its own.\n */\n const POLL_ENDED_MIN_MS = 60_000\n /**\n * And this much when the call ended badly, which is the case where a turn\n * is certainly still running server-side: the provider hangs up on a turn\n * it considers too slow, and that turn keeps going and is written when it\n * ends. A minute is not enough for it (measured 172 seconds, and once six\n * and a half minutes).\n */\n const POLL_FAILED_MIN_MS = 300_000\n /** And never survives longer than this, whatever is still missing. */\n const POLL_ENDED_MAX_MS = 600_000\n\n let pollTimer: ReturnType<typeof setTimeout> | undefined\n /** Set by the first look that finds the call over: the after-call clock. */\n let callEndedAt: number | undefined\n /**\n * Whether that call ended on a failure, read once when it ended: the\n * caller can dismiss the error from the bar, and the turn it interrupted\n * would not stop running because the message went away.\n */\n let callEndedBadly = false\n let endedBackoffStep = 0\n /**\n * A look is in flight. Guards the one thing a single timer cannot: a poke\n * (a turn that ended, an answer sent from a card) landing while the\n * previous request is still open would fire a second one beside it.\n */\n let isPolling = false\n\n /**\n * Ends the chain. Also puts the working indicator away: whatever it was\n * waiting for is either on screen or never coming, and an indicator left\n * spinning under the conversation promises an answer nobody is producing.\n */\n function stopPolling() {\n clearTimeout(pollTimer)\n pollTimer = undefined\n callEndedAt = undefined\n callEndedBadly = false\n endedBackoffStep = 0\n isAwaitingSpokenAnswer.value = false\n }\n\n /** One timer for the whole chain, so two looks can never overlap. */\n function schedulePoll(delayMs: number) {\n if (isUnmounted) {\n return\n }\n clearTimeout(pollTimer)\n pollTimer = setTimeout(() => {\n void runPoll()\n }, delayMs)\n }\n\n async function runPoll() {\n // The look that is running will schedule the next one, with fresher\n // data than this one would have asked for.\n if (isUnmounted || isPolling) {\n return\n }\n isPolling = true\n let outcome: Awaited<ReturnType<typeof refreshMessages>>\n try {\n outcome = await refreshMessages()\n } finally {\n isPolling = false\n }\n if (isUnmounted) {\n return\n }\n // Everything spoken is on screen: the wait, if any, is over, and the\n // turns it waited for are written.\n if (outcome === 'caught-up') {\n isAwaitingSpokenAnswer.value = false\n spokenTurnsWritten()\n }\n if (voice.isActive.value) {\n callEndedAt = undefined\n callEndedBadly = false\n endedBackoffStep = 0\n schedulePoll(POLL_LIVE_MS)\n return\n }\n if (callEndedAt === undefined) {\n callEndedAt = Date.now()\n callEndedBadly = !!voice.error.value\n }\n const elapsed = Date.now() - callEndedAt\n // Only a reload that was actually applied and found nothing missing\n // ends the chain, and never before the floor: 'indeterminate' (a\n // failed request, a stale answer) keeps it alive, or a transient\n // failure would strand the last turn.\n const floorMs = callEndedBadly ? POLL_FAILED_MIN_MS : POLL_ENDED_MIN_MS\n const settled = outcome === 'caught-up' && elapsed >= floorMs\n if (settled || elapsed >= POLL_ENDED_MAX_MS) {\n stopPolling()\n // Only here: a call started again restarts the chain too, and the\n // turn the previous call left unwritten is still on its way.\n forgetSpokenTurns()\n return\n }\n const delay =\n POLL_ENDED_BACKOFF_MS[\n Math.min(endedBackoffStep, POLL_ENDED_BACKOFF_MS.length - 1)\n ]\n endedBackoffStep += 1\n schedulePoll(delay)\n }\n\n /** Pulls the next look closer: a turn just ended, an answer was sent. */\n const pokePoll = (delayMs = 1200) => {\n schedulePoll(delayMs)\n }\n\n /**\n * The page tools of the call being opened (spec `voice-page-control.md`):\n * declared with the session, and run by the handlers the provider calls,\n * both taken at the same moment so they name the same tools.\n */\n let callPageTools: ReturnType<typeof store.voicePageTools>\n\n const voice = useVoiceSession({\n fetchGrant: async () => {\n callPageTools = store.voicePageTools()\n const grant = await apiClient.value.createVoiceSession(\n props.agentId,\n store.localChatId,\n {\n deviceContext: store.buildDeviceContext(),\n externalContext: store.externalContext,\n pageTools: callPageTools?.declaration,\n ...(store.confirmationMode === 'automatic' && {\n confirmations: 'automatic' as const,\n }),\n },\n )\n // The backend decides which conversation the call writes into, and\n // it may not be the one asked for: a stale id (a deleted chat, or\n // one left over from another agent) opens a new conversation rather\n // than failing the call. Follow it, or the transcript would land\n // somewhere this view is not showing.\n if (grant.chatId !== store.localChatId) {\n store.localChatId = grant.chatId\n }\n return grant\n },\n closeGrant: (sessionId) =>\n apiClient.value.closeVoiceSession(props.agentId, sessionId),\n clientTools: () => callPageTools?.clientTools,\n onTranscript: (entry) => {\n // What the AGENT says never becomes a message here, only the\n // written turn does. The transcript is text and nothing else, so\n // showing it meant a plain paragraph appearing and then being\n // swapped for the real answer with its sources and its widgets a\n // second later, and any part of it the server never writes (a\n // filler, a sentence the provider reworded) hanging around as the\n // last message until a manual reload (reported 2026-08-27). The\n // wait is shown by `isAwaitingSpokenAnswer` instead, and the\n // answer arrives once, whole.\n if (entry.role !== 'user') {\n // It is still the end of the wait: the agent has the floor.\n isAwaitingSpokenAnswer.value = false\n return\n }\n // The caller stopped talking: from here until the answer lands,\n // the turn is ours to show as working.\n isAwaitingSpokenAnswer.value = true\n spokenTurnStarted()\n appendMessage({\n // Marked as its own id space so a reload of the persisted\n // conversation replaces this rather than duplicating it, and\n // keeps it while the server does not have it yet.\n id: `${VOICE_LINE_ID_PREFIX}user-${generateId()}`,\n role: 'user',\n parts: [{ type: 'text', text: entry.text }],\n })\n },\n // The persisted answer arrives a moment after the provider finished\n // speaking it, so the reload waits for the write to land. The wait\n // indicator is NOT cleared here: a turn can end with nothing spoken\n // (the provider cut it), and the poll clearing it on caught-up is the\n // only signal that tells that apart from an answer on its way.\n onTurnEnd: () => {\n pokePoll()\n },\n })\n\n // A call that ends leaves no one to answer its page actions: they stop,\n // and their card goes with them.\n watch(\n () => voice.isActive.value,\n (active) => {\n if (!active) {\n store.cancelVoicePageCalls()\n }\n },\n )\n\n // A failure takes the stage: the error bar says what happened, and a\n // working indicator under it would promise an answer that may never come.\n watch(\n () => voice.error.value,\n (failure) => {\n if (failure) {\n isAwaitingSpokenAnswer.value = false\n }\n },\n )\n\n const isVoiceEnabled = computed(() => agentVoice.value?.enabled === true)\n\n /** What the session bar and the visualiser render. */\n const voiceState = computed(() => {\n if (voice.error.value) {\n return 'error' as const\n }\n if (voice.isConnecting.value) {\n return 'connecting' as const\n }\n if (voice.isSpeaking.value) {\n return 'speaking' as const\n }\n return voice.isActive.value ? ('listening' as const) : ('idle' as const)\n })\n\n /**\n * What the failure says on screen.\n *\n * Never the provider's own words: those are English prose written for\n * whoever wired the integration (\"custom_llm_error: LLM Cascade Error:\n * Brain returned no response\"), and passing the unrecognized ones through\n * put exactly that in front of a caller (production, 2026-08-27). The two\n * families we can tell apart get copy that says what to do about them,\n * everything else gets the honest generic one, and the raw text stays in\n * the tooltip for whoever is debugging.\n */\n const voiceErrorText = computed(() => {\n const raw = voice.error.value\n if (!raw) {\n return undefined\n }\n if (/took too long/i.test(raw)) {\n return $t('message.voiceTookTooLong')\n }\n // Their word for \"the turn produced nothing I could speak\", whatever\n // broke underneath: a cascade error, an empty completion, a refused\n // model. Trying again is the one thing that helps.\n if (/cascade|no response|custom_llm_error/i.test(raw)) {\n return $t('message.voiceNoAnswer')\n }\n return $t('message.voiceInterrupted')\n })\n\n /** Whoever is on air feeds the bars: the user, then the agent answering. */\n const voiceChannel = computed<'input' | 'output'>(() =>\n voice.isSpeaking.value ? 'output' : 'input',\n )\n const sampleVoiceLevel = () => voice.readLevel(voiceChannel.value)\n const sampleVoiceSpectrum = () => voice.readSpectrum(voiceChannel.value)\n\n const startVoice = async () => {\n isMuted.value = false\n await voice.start()\n if (voice.isActive.value) {\n // A fresh call restarts the clock of the chain: whatever the\n // previous one still owed, this one is live again.\n stopPolling()\n schedulePoll(POLL_LIVE_MS)\n }\n }\n\n const stopVoice = async () => {\n isAwaitingSpokenAnswer.value = false\n await voice.stop()\n if (isUnmounted) {\n return\n }\n // First look right away; the chain deliberately survives the call\n // (see POLL_ENDED_MIN_MS) and covers the write that lands later.\n pokePoll(0)\n }\n\n /** Leaves the failure behind and gives the written input back. */\n const dismissVoiceError = () => {\n voice.dismissError()\n }\n\n /** Same button, one step: forget the failure and open a new call. */\n const retryVoice = async () => {\n voice.dismissError()\n // The provider can report a failure on a socket that is still open,\n // and `start()` refuses while one exists: without this stop the retry\n // button only dismissed the error and never opened a new call.\n await voice.stop()\n await startVoice()\n }\n\n /**\n * Tool calls this client answered while the call was up, by id.\n *\n * On a call the answer does not go back to the tool call (it goes to the\n * agent as speech), so nothing in the persisted part ever changes to say it\n * was given: without this the same widget stays answerable forever and the\n * caller can send the same thing three times.\n */\n const readToolCallId = (part: unknown) =>\n (part as { toolCallId?: string })?.toolCallId ?? ''\n\n const answeredOnCall = ref(new Set<string>())\n const isAnsweredOnCall = (part: unknown) =>\n answeredOnCall.value.has(readToolCallId(part))\n\n /**\n * The verdicts of the confirms answered ON A CALL, by toolCallId. A spoken\n * verdict never resolves the tool part (the answer travels as a user\n * message), so without this the card kept its buttons and every extra tap\n * said \"Confermo\" again (three times in a row, measured 2026-08-07).\n * Recorded only when the send went through: `answerOnCall` leaves a failed\n * send unanswered on purpose, so the caller can tap again.\n */\n const confirmVerdictsOnCall = ref(new Map<string, boolean>())\n\n /**\n * Something the caller answered on screen during a call.\n *\n * In writing an answer resumes the suspended tool call, which is what makes\n * the agent continue. On a call there is no suspended call to resume: the\n * turn that drew the widget closed it on its own (a call cannot wait for a\n * screen), so the answer is said on the caller's behalf and comes back\n * spoken, in the same conversation.\n *\n * Returns true when it was said, and then the written path must NOT run:\n * `addToolOutput` would resume the turn in writing and the caller would get\n * two answers, one of them silent.\n */\n const answerOnCall = (part: unknown, spoken: string): boolean => {\n if (!voice.isActive.value) {\n return false\n }\n if (voice.sendUserMessage(spoken)) {\n answeredOnCall.value = new Set(answeredOnCall.value).add(\n readToolCallId(part),\n )\n pokePoll()\n return true\n }\n // The call is up and the answer did not get through. Saying it in\n // writing here would answer a question nobody asked in writing, so the\n // widget stays as it is and the caller can try again.\n return true\n }\n\n /** A form or a set of options, answered on screen. */\n const onFormAnswer = (\n tool: 'showForm' | 'showMultipleChoice',\n part: unknown,\n answer: string | { answers: { id: string; value: unknown }[] },\n ) => {\n if (answerOnCall(part, formAnswerAsSpoken(part, answer))) {\n return\n }\n addToolOutput({\n tool,\n toolCallId: readToolCallId(part),\n output: answer,\n })\n }\n\n /** A confirmation card, answered on screen. */\n const onConfirmRespond = (payload: {\n toolCallId: string\n confirmed: boolean\n }) => {\n const spoken = payload.confirmed\n ? $t('message.voiceConfirmed')\n : $t('message.voiceCancelled')\n if (answerOnCall({ toolCallId: payload.toolCallId }, spoken)) {\n if (answeredOnCall.value.has(payload.toolCallId)) {\n confirmVerdictsOnCall.value = new Map(\n confirmVerdictsOnCall.value,\n ).set(payload.toolCallId, payload.confirmed)\n }\n return\n }\n addToolOutput({\n tool: 'requestConfirm',\n toolCallId: payload.toolCallId,\n output: payload.confirmed ? 'confirmed' : 'cancelled',\n })\n }\n\n /**\n * The latest version of each file the conversation shows, by its fileId:\n * the card of an earlier version offers to restore it.\n */\n const latestFileVersions = computed(() => {\n const latest = new Map<string, number>()\n for (const message of messages.value) {\n for (const part of message.parts) {\n const { type, state, output } = part as {\n type: string\n state?: string\n output?: { fileId?: string; version?: number }\n }\n if (\n CHAT_FILE_TOOL_PARTS.has(type) &&\n state === 'output-available' &&\n output?.fileId &&\n output.version\n ) {\n latest.set(\n output.fileId,\n Math.max(\n latest.get(output.fileId) ?? 0,\n output.version,\n ),\n )\n }\n }\n }\n return latest\n })\n\n /**\n * The files of the conversation by name, uploaded or written by the\n * agent, as the fileIds the agent knows them by.\n */\n const chatFileIdsByName = computed(() => {\n const byName = new Map<string, Set<string>>()\n const add = (filename?: string, fileId?: string) => {\n if (filename && fileId) {\n const key = filename.toLowerCase()\n byName.set(key, (byName.get(key) ?? new Set()).add(fileId))\n }\n }\n for (const message of messages.value) {\n for (const part of message.parts) {\n if (isFilePart(part)) {\n add(part.filename, getFilePartMedia(part)?.storedFileName)\n continue\n }\n const { type, state, output } = part as {\n type: string\n state?: string\n output?: {\n fileId?: string\n filename?: string\n version?: number\n }\n }\n if (\n CHAT_FILE_TOOL_PARTS.has(type) &&\n state === 'output-available' &&\n output?.filename\n ) {\n add(\n chatFileName(output.filename, output.version),\n output.fileId,\n )\n }\n }\n }\n return byName\n })\n\n /**\n * \"Restore\" on the card of an earlier version: asking the agent for it,\n * in a conversation that can still take a message. When two files share\n * the name, the message names the file by its fileId.\n */\n const chatFileRestore = computed(() =>\n isConversationBlocked.value\n ? undefined\n : (file: ChatFileRestoreTarget) => {\n const twins =\n (chatFileIdsByName.value.get(file.filename.toLowerCase())\n ?.size ?? 0) > 1\n input.value = twins\n ? $t('messagePart.chatFileRestoreRequestById', file)\n : $t('messagePart.chatFileRestoreRequest', file)\n storeHandleSubmit()\n },\n )\n\n /** A suggested reply: tapping it is saying it. */\n const onSuggestedReply = (part: unknown, reply: string) => {\n if (answerOnCall(part, reply)) {\n return\n }\n input.value = reply\n storeHandleSubmit()\n }\n\n /** The position the caller shared from the browser. */\n const onGeolocation = (\n part: unknown,\n result: {\n latitude?: number\n longitude?: number\n displayName?: string\n error?: string\n },\n ) => {\n const spoken = result.error\n ? $t('message.voiceLocationRefused')\n : $t('message.voiceLocationShared', {\n place:\n result.displayName ??\n `${result.latitude}, ${result.longitude}`,\n })\n if (answerOnCall(part, spoken)) {\n return\n }\n addToolOutput({\n tool: 'requestGeolocation',\n toolCallId: readToolCallId(part),\n output: result,\n })\n }\n\n /** An integration the caller connected from the card on screen. */\n const onOAuthConnected = (part: unknown, mcpServerId: string) => {\n if (answerOnCall(part, $t('message.voiceConnectionDone'))) {\n return\n }\n addToolOutput({\n tool: 'requestOAuthConnection',\n toolCallId: readToolCallId(part),\n output: { connected: true, mcpServerId },\n })\n }\n\n const toggleVoiceMute = () => {\n isMuted.value = !isMuted.value\n voice.setMuted(isMuted.value)\n }\n\n onBeforeUnmount(() => {\n isUnmounted = true\n stopPolling()\n })\n // #endregion voice\n\n // #region wakeups\n /** The checks the agent runs by itself (spec agent-wakeup). */\n const {\n pendingWakeup,\n isStopping: isStoppingWakeup,\n stop: stopWakeup,\n spokenTurnStarted,\n spokenTurnsWritten,\n forgetSpokenTurns,\n } = useWakeupWatch({\n agentId: () => props.agentId,\n chatId: () => store.localChatId,\n apiClient: () => apiClient.value,\n messages: () => messages.value,\n refreshMessages,\n status: () => chat.value.status,\n })\n // #endregion wakeups\n</script>\n\n<template>\n <div\n ref=\"chatViewEl\"\n class=\"pk-chatbot-view-chat\"\n :class=\"{\n 'pk-chatbot-view-chat--dragover':\n isOverDropZone && agentFileUpload?.enabled,\n 'pk-chatbot-view-chat--empty': showEmptyState,\n 'pk-chatbot-view-chat--with-preview':\n previewBeside && !previewDocked,\n }\">\n <!-- #region empty state (fullscreen) / messages — crossfade out-in -->\n <Transition name=\"pk-chatbot-view-chat-fade\" mode=\"out-in\">\n <PkChatbotEmptyState\n v-if=\"showEmptyState\"\n :greeting=\"greeting\"\n :logo=\"agentInterface?.logo\"\n :name=\"store.name\" />\n <PkChatbotMessages\n v-else\n class=\"flex flex-col flex-1 min-h-0 p-md overflow-y-auto\"\n interactive\n :messages=\"messages\"\n :confirm-verdicts-on-call=\"confirmVerdictsOnCall\"\n :status=\"chat.status\"\n :error=\"chat.error\"\n :main-color=\"agentInterface?.mainColor\"\n :text-color=\"agentInterface?.textColor\"\n :revised-answers=\"revisedAnswers\"\n :actions=\"actions\"\n :message-feedbacks=\"messageFeedbacks\"\n :feedback-message-id=\"feedbackDialogMessage?.id\"\n :feedback-loading=\"isFeedbackSubmitting\"\n :feedback-submitted=\"isFeedbackSubmitted\"\n :feedback-error=\"feedbackSubmitError\"\n :show-extended-steps=\"agentInterface?.showExtendedSteps\"\n :hide-reasoning=\"agentInterface?.showReasoning === false\"\n :awaiting-spoken-answer=\"isAwaitingSpokenAnswer\"\n :host-working=\"hostWorking\"\n :host-confirmation=\"hostConfirmation\"\n :is-dark=\"isDark\"\n :show-scroll-to-bottom=\"modifier === 'fullscreen'\"\n @feedback-submit=\"onFeedbackSubmit($event)\"\n @feedback-close=\"feedbackDialogMessage = undefined\"\n @regenerate=\"regenerate\"\n @auto-retry=\"regenerate\"\n @reset-chat=\"startNewChat\"\n @show-info=\"emit('show-info', $event)\"\n @revise=\"emit('revise', $event)\"\n @upvote=\"onUpvote\"\n @downvote=\"onDownvote\"\n @feedback=\"onFeedback\"\n @approval-respond=\"addToolApprovalResponse\"\n @confirm-respond=\"onConfirmRespond\"\n @host-confirm-respond=\"respondHostConfirmation\">\n <template #tool-showContactForm=\"{ part }\">\n <PkToolShowContactForm\n :part\n :readonly=\"!baseUrl\"\n :submitted=\"isLeadSubmitted\"\n :loading=\"isLoadingSubmitLead\"\n :error=\"submitLeadError\"\n :privacy-policy-notice=\"\n agentInterface?.privacyPolicyNotice\n \"\n @submit=\"onLeadSubmit\" />\n </template>\n <template #tool-showSuggestedReply=\"{ part }\">\n <PkToolShowSuggestedReply\n :part\n @select=\"onSuggestedReply(part, $event)\" />\n </template>\n <template #tool-showSources=\"{ part }\">\n <PkToolShowSources\n :part\n :on-expand-context=\"handleExpandSourceContext\"\n :on-download=\"handleDownloadSource\" />\n </template>\n <template #tool-showForm=\"{ part }\">\n <transition mode=\"out-in\">\n <PkToolShowForm\n :part\n :answered=\"isAnsweredOnCall(part)\"\n @select=\"onFormAnswer('showForm', part, $event)\" />\n </transition>\n </template>\n <template #tool-showMultipleChoice=\"{ part }\">\n <transition mode=\"out-in\">\n <PkToolShowForm\n :part\n allow-custom-answer\n :answered=\"isAnsweredOnCall(part)\"\n @select=\"\n onFormAnswer('showMultipleChoice', part, $event)\n \" />\n </transition>\n </template>\n <template #tool-requestOAuthConnection=\"{ part }\">\n <PkToolRequestOAuthConnection\n :part\n :backend-url=\"baseUrl\"\n :resolve-connection=\"\n (serverName: string) =>\n apiClient.getOAuthAuthorizeUrl(\n props.agentId,\n serverName,\n )\n \"\n :check-connection=\"\n (serverName: string) =>\n apiClient.getOAuthConnectionStatus(\n props.agentId,\n serverName,\n )\n \"\n @connected=\"onOAuthConnected(part, $event)\" />\n </template>\n <template #tool-requestGeolocation=\"{ part }\">\n <PkToolRequestGeolocation\n :part\n :call-live=\"voice.isActive.value\"\n :reverse-geocode=\"\n (lat: number, lon: number) =>\n apiClient.reverseGeocode(lat, lon)\n \"\n @result=\"onGeolocation(part, $event)\" />\n </template>\n <template #tool-showLocation=\"{ part }\">\n <PkToolShowLocation\n :part\n :is-dark\n :main-color=\"agentInterface?.mainColor\"\n :forward-geocode=\"\n (query: string, lang?: string) =>\n apiClient.forwardGeocode(query, lang)\n \" />\n </template>\n <template #tool-showChart=\"{ part }\">\n <PkToolShowChart :part :is-dark />\n </template>\n <template #tool-showDiagram=\"{ part }\">\n <PkToolShowDiagram :part :is-dark />\n </template>\n <template #tool-editSpreadsheet=\"{ part }\">\n <!-- Keyed on the state like the feed's own tool\n components: the card mounts while the call runs, and\n the SDK writes the output into that same part object,\n which alone would not redraw it. -->\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-editWordDocument=\"{ part }\">\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-createSpreadsheet=\"{ part }\">\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-createWordDocument=\"{ part }\">\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-shareDocument=\"{ part }\">\n <!-- Keyed on the state for the same reason. -->\n <PkToolShareDocument\n :key=\"getPartState(part)\"\n :part\n :on-download=\"handleDownloadSource\" />\n </template>\n </PkChatbotMessages>\n </Transition>\n <!-- #endregion -->\n\n <PkChatbotQueuedMessages\n v-if=\"queuedMessages.length\"\n :messages=\"queuedMessages\"\n @edit=\"editQueuedMessage\"\n @remove=\"removeQueuedMessage\" />\n\n <!-- #region input -->\n <div class=\"pk-chatbot-view-chat__input-stage\">\n <!-- Animated accent glow radiating from the input pill -->\n <Transition name=\"pk-chatbot-view-chat-fade\">\n <PkAuroraCanvas\n v-if=\"showEmptyState\"\n class=\"pk-chatbot-view-chat__aurora\"\n source-selector=\".pk-chatbot-input__form\"\n :main-color=\"agentInterface?.mainColor\"\n :tones=\"agentInterface?.glowTones\"\n :second-color=\"agentInterface?.glowSecondColor\" />\n </Transition>\n <PkChatbotWakeupBar\n v-if=\"pendingWakeup && !isConversationBlocked\"\n :pending=\"pendingWakeup\"\n :stopping=\"isStoppingWakeup\"\n @stop=\"stopWakeup\" />\n <div\n v-if=\"isConversationBlocked\"\n class=\"p-md border-t border-surface-3 text-center text-12 text-danger bg-surface-danger\">\n {{ $t('message.chatErrorConversationBlocked') }}\n </div>\n <!-- A live call takes the place of the input: one thing on air, one\n way to hang up, and the conversation stays above it -->\n <PkVoiceSession\n v-else-if=\"voiceState !== 'idle'\"\n :state=\"voiceState\"\n :sample=\"sampleVoiceLevel\"\n :spectrum=\"sampleVoiceSpectrum\"\n :remaining-seconds=\"voice.remainingSeconds.value\"\n :muted=\"isMuted\"\n :error=\"voiceErrorText\"\n :raw-error=\"voice.error.value\"\n :live=\"voice.isActive.value\"\n class=\"pk-chatbot-view-chat__voice\"\n @toggle-mute=\"toggleVoiceMute\"\n @hang-up=\"stopVoice\"\n @retry=\"retryVoice\"\n @dismiss=\"dismissVoiceError\" />\n <PkChatbotInput\n v-else\n ref=\"inputEl\"\n v-model=\"input\"\n v-model:pending-attachments=\"pendingAttachments\"\n :placeholder=\"inputMessagePlaceholder\"\n :dismissable-notice=\"\n dismissableNotice && chat.messages.length <= 1\n ? dismissableNotice\n : undefined\n \"\n :page-notice=\"pageNotice\"\n :status=\"inputStatus\"\n :max-message-length=\"agentInterface?.maxMessageLength\"\n :file-upload=\"agentFileUpload\"\n :attachment-limit-reached=\"isAttachmentLimitReached\"\n :attachment-notice=\"attachmentNotice\"\n :voice-enabled=\"isVoiceEnabled\"\n :queue-enabled=\"canQueue\"\n :answer-notices=\"answerNotices\"\n :pointer-available=\"pagePointerAvailable\"\n :pointing=\"pagePointing\"\n :pointer=\"pointerChip\"\n :automatic-confirmations=\"confirmationMode === 'automatic'\"\n editable-images\n retryable-attachments\n @point=\"store.pagePointerStart?.()\"\n @remove-pointer=\"pagePointer = undefined\"\n @manual-confirmations=\"store.setConfirmationMode('manual')\"\n @stop-generation=\"stopGeneration\"\n @submit=\"storeHandleSubmit\"\n @file-select=\"handleFileSelect\"\n @remove-attachment=\"discardPendingAttachment\"\n @replace-attachment=\"replacePendingAttachment\"\n @retry-attachment=\"retryPendingAttachment\"\n @dismiss-attachment-notice=\"clearFileLimitError\"\n @dismiss-page-notice=\"closePageNotice\"\n @open-answer-notice=\"openBackgroundAnswer\"\n @dismiss-answer-notice=\"dismissBackgroundAnswer\"\n @voice-start=\"startVoice\">\n <!-- Fullscreen has no header: the agent identity lives in the\n input pill -->\n <template v-if=\"modifier === 'fullscreen'\" #prepend>\n <span class=\"pk-chatbot-view-chat__agent-chip\">\n <PkAvatar\n class=\"pk-chatbot-view-chat__agent-chip-avatar\"\n :img-src=\"agentInterface?.logo\"\n :name=\"store.name\" />\n <strong\n v-if=\"store.name\"\n class=\"pk-chatbot-view-chat__agent-chip-name\">\n {{ store.name }}\n </strong>\n </span>\n </template>\n </PkChatbotInput>\n </div>\n <!-- #endregion -->\n <Transition>\n <div\n v-if=\"isOverDropZone && agentFileUpload?.enabled\"\n class=\"pk-chatbot-view-chat__drop-overlay\">\n <VvIcon\n name=\"ri:upload-cloud-2-line\"\n class=\"pk-chatbot-view-chat__drop-overlay-icon\" />\n <span>{{ $t('action.dropFile') }}</span>\n </div>\n </Transition>\n <!-- #region file preview: beside the chat, in the page's column when\n it gives one, or over it -->\n <Teleport\n v-if=\"previewBeside\"\n :to=\"previewDockTarget\"\n :disabled=\"!previewDocked\">\n <aside\n class=\"pk-chatbot-view-chat__preview\"\n :class=\"{\n 'pk-chatbot-view-chat__preview--docked': previewDocked,\n }\">\n <PkFilePreview\n v-if=\"previewTarget\"\n v-model:mode=\"previewView.mode\"\n v-model:sheet=\"previewView.sheet\"\n v-model:zoom=\"previewView.zoom\"\n v-model:fit=\"previewView.fit\"\n :kind=\"previewTarget.kind\"\n :filename=\"previewTarget.filename\"\n :version=\"previewTarget.version\"\n :versions=\"previewVersions\"\n :download-url=\"\n chatFileDownloadUrl(previewTarget.storedFileName)\n \"\n :preview=\"previewData\"\n :changes=\"previewChanges\"\n :loading=\"previewLoading\"\n :error=\"previewError\"\n :restorable=\"previewRestorable\"\n resize=\"expand\"\n :file-id=\"previewTarget.fileId\"\n :stored-file-name=\"previewTarget.storedFileName\"\n :selection-actions=\"previewSelectionActions\"\n @version=\"showPreviewVersion\"\n @restore=\"restoreFromPreview\"\n @resize=\"previewExpanded = true\"\n @selection-send=\"sendFromPreview\"\n @close=\"closePreview\" />\n </aside>\n </Teleport>\n <PkFilePreviewDialog\n v-if=\"previewTarget && !previewBeside\"\n v-model:mode=\"previewView.mode\"\n v-model:sheet=\"previewView.sheet\"\n v-model:zoom=\"previewView.zoom\"\n v-model:fit=\"previewView.fit\"\n :target=\"previewTarget\"\n :versions=\"previewVersions\"\n :download-url=\"chatFileDownloadUrl(previewTarget.storedFileName)\"\n :preview=\"previewData\"\n :changes=\"previewChanges\"\n :loading=\"previewLoading\"\n :error=\"previewError\"\n :restorable=\"previewRestorable\"\n :resize=\"previewInPanel ? 'shrink' : undefined\"\n :fullscreen=\"previewFullscreen\"\n :selection-actions=\"previewSelectionActions\"\n @version=\"showPreviewVersion\"\n @restore=\"restoreFromPreview\"\n @resize=\"previewExpanded = false\"\n @selection-send=\"sendFromPreview\"\n @close=\"closePreview\" />\n <!-- #endregion -->\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-chatbot-view-chat {\n --pk-chatbot-preview-width: 520px;\n\n position: relative;\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n\n // The preview of a Word document beside the chat: the messages and\n // the input keep a reading column, the panel takes the inline end.\n // Only from PREVIEW_PANEL_MIN_WIDTH of the script, a dialog below.\n &--with-preview {\n padding-inline-end: calc(\n var(--pk-chatbot-preview-width) + var(--spacing-12)\n );\n }\n\n // Where the page gives no column (the widget, the playground), one\n // frame on the ground of the chat, a little in from its edges: cut at\n // the chat's bottom, over the footer of the agent, it read as a panel\n // that stopped short.\n &__preview {\n position: absolute;\n inset-block: var(--spacing-12);\n inset-inline-end: var(--spacing-12);\n z-index: 1;\n width: var(--pk-chatbot-preview-width);\n overflow: hidden;\n border: var(--border) solid var(--color-surface-3);\n border-radius: var(--rounded-lg);\n background-color: var(--color-surface);\n\n // A column of the page, as its sidebar on the other side: the\n // page's height, outside the chat's header and footer. Outside\n // the chat's block, so its width is its own.\n &--docked {\n position: relative;\n inset: auto;\n flex-shrink: 0;\n width: clamp(520px, 38vw, 760px);\n height: 100%;\n border-width: 0 0 0 var(--border);\n border-radius: 0;\n }\n }\n\n // Empty state (fullscreen): center the greeting + input block\n // vertically in the available space\n &--empty {\n justify-content: center;\n gap: var(--spacing-md);\n\n // In a phone-sized chat the input docks to the bottom edge\n // instead (Gemini-like), with the greeting centered in the space\n // above. Keyed on the chat's own width (`--phone`, measured in\n // PkChatbot), not the viewport: a narrow preview frame on a\n // desktop screen docks the same way\n .pk-chatbot--phone & {\n justify-content: flex-start;\n\n .pk-chatbot-empty-state {\n flex: 1;\n justify-content: center;\n }\n }\n }\n\n // Anchors the glow to the input pill\n &__input-stage {\n position: relative;\n }\n\n // Radiates outwards from the pill (the pill itself paints above,\n // being later in the DOM). The shader caps each half of the glow at\n // the room this leaves on its side, so the room fits the glow at\n // rest: with 224px above and 160px below it was cut there instead.\n &__input-stage &__aurora {\n inset: calc(-1 * var(--spacing-320)) calc(-1 * var(--spacing-96));\n\n // With the input docked at the bottom the glow becomes a wide\n // dome filling the lower part of the chat (Gemini-like); same\n // threshold as the docking above\n .pk-chatbot--phone & {\n --aurora-spread: 1.6;\n\n // Tall enough that the glow tail never meets the canvas\n // edge fade (it would draw a visible horizontal band)\n inset: calc(-1 * var(--spacing-384) - var(--spacing-128))\n calc(-1 * var(--spacing-96)) calc(-1 * var(--spacing-160));\n }\n }\n\n // Agent identity inside the input pill (fullscreen has no header).\n // A rounded box rather than a pill: a pill around a tile drew two\n // curves that did not run together.\n &__agent-chip {\n display: inline-flex;\n align-items: center;\n gap: var(--spacing-6);\n flex-shrink: 0;\n padding: var(--spacing-4) var(--spacing-10) var(--spacing-4)\n var(--spacing-4);\n border: 1px solid var(--color-surface-3);\n border-radius: var(--rounded-lg);\n background-color: var(--color-surface);\n\n // Don't crowd the textarea in a narrow chat. Keyed on the chat's\n // own width (`--tight`, measured in PkChatbot), not the viewport:\n // a preview frame squeezed by side panels on a desktop screen is\n // as narrow as a phone page. Below that threshold the chip would\n // leave the textarea a couple of hundred pixels at best, and in a\n // phone-sized frame a few characters, wrapping the placeholder\n // into a tall pill. The empty state shows the avatar at the same\n // threshold: one of the two carries the agent identity.\n .pk-chatbot--tight & {\n display: none;\n }\n }\n\n &__agent-chip-avatar {\n width: var(--spacing-24);\n height: var(--spacing-24);\n font-size: var(--text-10);\n }\n\n &__agent-chip-name {\n font-size: var(--text-12);\n font-weight: var(--font-semibold);\n color: var(--color-word-2);\n white-space: nowrap;\n }\n\n // Crossfade empty state ↔ messages: exit faster than enter so the\n // switch never feels like a snap\n &-fade-enter-active {\n transition: opacity 250ms var(--ease-out);\n }\n\n &-fade-leave-active {\n transition: opacity 150ms var(--ease-out);\n }\n\n &-fade-enter-from,\n &-fade-leave-to {\n opacity: 0;\n }\n\n @media (prefers-reduced-motion: reduce) {\n &-fade-enter-active,\n &-fade-leave-active {\n transition: none;\n }\n }\n\n &__drop-overlay {\n position: absolute;\n inset: var(--spacing-sm) var(--spacing-sm) var(--spacing-sm)\n var(--spacing-sm);\n z-index: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--spacing-xs);\n background-color: color-mix(\n in srgb,\n var(--color-surface) 85%,\n transparent\n );\n border-radius: var(--rounded-xl);\n border: var(--spacing-2) dashed var(--color-surface-5);\n pointer-events: none;\n color: var(--color-word-3);\n\n &-icon {\n font-size: var(--spacing-32);\n }\n }\n }\n</style>\n","<script setup lang=\"ts\">\n import {\n computed,\n onBeforeUnmount,\n provide,\n ref,\n useTemplateRef,\n watch,\n defineAsyncComponent,\n } from 'vue'\n import { useI18n } from 'vue-i18n'\n import { useDropZone, useResizeObserver } from '@vueuse/core'\n import { storeToRefs } from 'pinia'\n import { generateId } from 'ai'\n import PkAuroraCanvas from './PkAuroraCanvas.vue'\n import PkAvatar from './PkAvatar.vue'\n import PkChatbotMessages from './PkChatbotMessages.vue'\n import PkChatbotInput from './PkChatbotInput.vue'\n import PkChatbotQueuedMessages from './PkChatbotQueuedMessages.vue'\n import PkChatbotEmptyState from './PkChatbotEmptyState.vue'\n import PkVoiceSession from './PkVoiceSession.vue'\n import PkChatbotWakeupBar from './PkChatbotWakeupBar.vue'\n import { useVoiceSession } from './useVoiceSession'\n import { useChatFilePreviewDock } from './chatFilePreviewDock'\n import { useWakeupWatch } from './useWakeupWatch'\n import { useChatFilePreview } from './useChatFilePreview'\n import { provideImageAnnotation } from '../composables/useLightbox'\n import {\n chatFileName,\n formAnswerAsSpoken,\n getPartState,\n HOST_STEP_CHANGES,\n HOST_STEP_TITLES,\n type ChatFilePreviewTarget,\n type ChatFileRestoreTarget,\n type WordPreviewMode,\n } from './utils'\n import { getFilePartMedia, isFilePart } from 'utils'\n import {\n useChatbotStore,\n useLocalizedString,\n useGreeting,\n VOICE_LINE_ID_PREFIX,\n } from 'composables'\n import {\n chatDropAccepts,\n type FilePointer,\n type UIChatMessage,\n } from 'models'\n\n const PkToolShowForm = defineAsyncComponent(\n () => import('./PkToolShowForm.vue'),\n )\n const PkToolShowContactForm = defineAsyncComponent(\n () => import('./PkToolShowContactForm.vue'),\n )\n const PkToolShowSuggestedReply = defineAsyncComponent(\n () => import('./PkToolShowSuggestedReply.vue'),\n )\n const PkToolShowSources = defineAsyncComponent(\n () => import('./PkToolShowSources.vue'),\n )\n const PkToolRequestGeolocation = defineAsyncComponent(\n () => import('./PkToolRequestGeolocation.vue'),\n )\n const PkToolRequestOAuthConnection = defineAsyncComponent(\n () => import('./PkToolRequestOAuthConnection.vue'),\n )\n const PkToolShowLocation = defineAsyncComponent(\n () => import('./PkToolShowLocation.vue'),\n )\n const PkToolShowChart = defineAsyncComponent(\n () => import('./PkToolShowChart.vue'),\n )\n const PkToolShowDiagram = defineAsyncComponent(\n () => import('./PkToolShowDiagram.vue'),\n )\n const PkToolChatFile = defineAsyncComponent(\n () => import('./PkToolChatFile.vue'),\n )\n const PkToolShareDocument = defineAsyncComponent(\n () => import('./PkToolShareDocument.vue'),\n )\n const PkFilePreview = defineAsyncComponent(\n () => import('./PkFilePreview.vue'),\n )\n const PkFilePreviewDialog = defineAsyncComponent(\n () => import('./PkFilePreviewDialog.vue'),\n )\n\n const props = defineProps<{\n agentId: string\n /** Mirrors the PkChatbot `modifier` prop: `fullscreen` shows a centered empty state (greeting) instead of the welcome message, `panel` behaves like `widget` */\n modifier?: 'widget' | 'fullscreen' | 'panel'\n /** Display name of the current user, used for the `{name}` greeting placeholder */\n userName?: string\n }>()\n\n const emit = defineEmits<{\n 'show-info': [message: UIChatMessage]\n revise: [message: UIChatMessage]\n /** An action of the file viewer's selection bar was sent: the telemetry's properties. */\n 'selection-action': [properties: Record<string, string>]\n }>()\n\n const store = useChatbotStore(props.agentId)\n\n const {\n agentInterface,\n agentFileUpload: storedFileUpload,\n agentType,\n agentVoice,\n actions,\n revisedAnswers,\n messages,\n chat,\n messageFeedbacks,\n feedbackDialogMessage,\n isFeedbackSubmitting,\n isFeedbackSubmitted,\n feedbackSubmitError,\n isLeadSubmitted,\n isLoadingSubmitLead,\n submitLeadError,\n input,\n inputMessagePlaceholder,\n isConversationBlocked,\n baseUrl,\n pendingAttachments,\n isAttachmentLimitReached,\n fileLimitError,\n apiClient,\n isDark,\n hostToolsPending,\n pageNoticeLevel,\n hostConfirmation,\n agentPageAccess,\n hostStepTitles,\n hostStepChanges,\n confirmationMode,\n canQueue,\n queuedMessages,\n backgroundAnswers,\n inputFocusRequest,\n pagePointer,\n pagePointerAvailable,\n pagePointing,\n agentSelectionActions,\n } = storeToRefs(store)\n // The steps of the page name what they act on while the page is open\n provide(HOST_STEP_TITLES, hostStepTitles)\n // And what they changed, when the automatic confirmations asked nothing\n provide(HOST_STEP_CHANGES, hostStepChanges)\n\n // The host asks for the message field (⇧Esc on the chat page)\n const inputEl =\n useTemplateRef<InstanceType<typeof PkChatbotInput>>('inputEl')\n watch(inputFocusRequest, () => {\n inputEl.value?.focus()\n })\n // What the user just pointed at on the page goes with what they write\n // next (spec page-point-and-choose.md, P): the field takes the focus\n watch(pagePointer, (pointer) => {\n if (pointer) {\n inputEl.value?.focus()\n }\n })\n const pointerChip = computed(() =>\n pagePointer.value\n ? { kind: pagePointer.value.kind, label: pagePointer.value.label }\n : undefined,\n )\n\n // A reasoning agent reads no attachment, and the backend refuses one: no\n // attach button and no drop zone, whatever its upload settings say.\n const agentFileUpload = computed(() =>\n agentType.value === 'reasoning' ? undefined : storedFileUpload.value,\n )\n\n // \"Annota e chiedi\" in the lightbox of this conversation (spec\n // `chat-image-editor.md`, F3): the composer takes the annotated copy\n // while it is shown (not during a call), takes images and is not full\n const takesImages = computed(() => {\n const allowed = agentFileUpload.value?.allowedMimeTypes ?? []\n return (\n !!agentFileUpload.value?.enabled &&\n (!allowed.length || allowed.some((m) => m.startsWith('image/')))\n )\n })\n provideImageAnnotation({\n available: () =>\n !!inputEl.value &&\n takesImages.value &&\n !isAttachmentLimitReached.value,\n annotate: (file) => inputEl.value?.annotateImage(file),\n })\n\n /** A file the agent stored in this chat, such as a spreadsheet version. */\n const chatFileDownloadUrl = (storedFileName: string) =>\n apiClient.value.getMediaDownloadUrl(\n props.agentId,\n store.localChatId,\n storedFileName,\n )\n\n const {\n handleSubmit: storeHandleSubmit,\n stopGeneration,\n regenerate,\n onUpvote,\n onDownvote,\n onFeedback,\n onFeedbackSubmit,\n onLeadSubmit,\n startNewChat,\n addToolOutput,\n addToolApprovalResponse,\n handleFileSelect,\n discardPendingAttachment,\n replacePendingAttachment,\n retryPendingAttachment,\n clearFileLimitError,\n refreshMessages,\n appendMessage,\n closePageNotice,\n respondHostConfirmation,\n editQueuedMessage,\n removeQueuedMessage,\n openBackgroundAnswer,\n dismissBackgroundAnswer,\n } = store\n\n const { t: $t } = useI18n({ useScope: 'global' })\n\n // The embedding page runs calls of the last answer (spec `host-tools.md`):\n // the request that announced them is over and the chat reads `ready`, yet\n // the answer is not. The input shows the work and its stop.\n const hostWorking = computed(() => hostToolsPending.value > 0)\n const inputStatus = computed(() =>\n hostWorking.value && chat.value.status === 'ready'\n ? 'streaming'\n : chat.value.status,\n )\n // The customer's own words when the agent has them, else what the\n // level allows.\n const customPageNotice = useLocalizedString(\n () => agentPageAccess.value?.notice,\n )\n const pageNotice = computed(() =>\n pageNoticeLevel.value\n ? customPageNotice.value ||\n $t(`message.pageAccessNotice.${pageNoticeLevel.value}`)\n : undefined,\n )\n\n const attachmentNotice = computed(() => {\n const err = fileLimitError.value\n if (!err) {\n return undefined\n }\n return err.reason === 'per-chat'\n ? $t('message.fileLimitPerChat', { max: err.max })\n : $t('message.fileLimitPerMessage', { max: err.max })\n })\n\n // Answers that ended in a conversation the user left (spec\n // resumable-chat-streams, F2), named by its title when the list has it.\n const answerNotices = computed(() =>\n backgroundAnswers.value.map(({ chatId, title }) => ({\n id: chatId,\n text: title\n ? $t('message.backgroundAnswerReady', { title })\n : $t('message.backgroundAnswerReadyUntitled'),\n })),\n )\n\n const dismissableNotice = useLocalizedString(\n () => agentInterface.value?.dismissableNotice,\n )\n\n // Fullscreen empty state: shown until the user sends the first message.\n // The synthetic welcome message is suppressed by the store in fullscreen\n // (`hideWelcomeMessage`), the greeting takes its place.\n const hasUserMessages = computed(() =>\n messages.value.some((message) => message.role === 'user'),\n )\n const showEmptyState = computed(\n () => props.modifier === 'fullscreen' && !hasUserMessages.value,\n )\n const greeting = useGreeting(agentInterface, () => props.userName)\n\n const chatViewEl = useTemplateRef<HTMLDivElement>('chatViewEl')\n\n // #region file preview\n /**\n * Where the preview of a Word document or a spreadsheet opens (spec\n * `chat-office-files.md`, F6, items 3 and 4): beside the chat when the chat has room for a reading\n * column and the panel, over it in a dialog otherwise. Measured on the\n * chat, not on the window: the floating widget, the playground and a page\n * with the Copilot docked beside it are narrow on a wide screen.\n */\n const PREVIEW_PANEL_MIN_WIDTH = 1000\n /**\n * A page that lays the chat out between its own columns gives the panel\n * a column of the page's height (`provideChatFilePreviewDock`): the\n * panel takes its width from the chat, so the two together are the room\n * the panel opens in.\n */\n const previewDock = useChatFilePreviewDock()\n const previewDocked = computed(() => !!previewDock?.value)\n // A ref read in the template is unwrapped: the target goes through here\n const previewDockTarget = computed(() => previewDock?.value ?? 'body')\n const chatViewWidth = ref(0)\n const dockWidth = ref(0)\n // The border box: the panel's room is padding of the chat, and measured\n // without it the open panel took the width that opened it. One observer\n // for the chat and the dock: with two, the chat narrowed by the panel\n // arrived alone, the panel closed before the dock's width came, and the\n // preview went back and forth between the panel and the dialog.\n useResizeObserver(\n [chatViewEl, computed(() => previewDock?.value ?? undefined)],\n (entries) => {\n for (const entry of entries) {\n const width =\n entry.borderBoxSize?.[0]?.inlineSize ??\n entry.contentRect.width\n if (entry.target === chatViewEl.value) {\n chatViewWidth.value = width\n } else {\n dockWidth.value = width\n }\n }\n },\n { box: 'border-box' },\n )\n const previewInPanel = computed(\n () =>\n chatViewWidth.value + (previewDocked.value ? dockWidth.value : 0) >=\n PREVIEW_PANEL_MIN_WIDTH,\n )\n const previewFullscreen = computed(\n () => chatViewWidth.value > 0 && chatViewWidth.value < 576,\n )\n const {\n target: previewTarget,\n preview: previewData,\n loading: previewLoading,\n error: previewError,\n changes: previewChanges,\n open: openFilePreview,\n close: closeFilePreview,\n reset: resetPreview,\n } = useChatFilePreview((storedFileName) =>\n apiClient.value.getChatFilePreview(\n props.agentId,\n store.localChatId,\n storedFileName,\n ),\n )\n /**\n * How the open file is shown: its revisions, sheet and zoom. The viewer\n * is drawn anew when it moves between the panel and the dialog, and\n * takes these along; another file starts afresh.\n */\n const previewView = ref<{\n mode?: WordPreviewMode\n sheet?: number\n zoom?: number\n fit?: boolean\n }>({})\n\n /** `since`: the version on screen, when the viewer follows an edit. */\n const openPreview = (target: ChatFilePreviewTarget, since?: string) => {\n const fileOf = (t?: ChatFilePreviewTarget) =>\n t?.fileId ?? t?.storedFileName\n if (fileOf(target) !== fileOf(previewTarget.value)) {\n previewView.value = {}\n }\n return openFilePreview(target, since)\n }\n\n /** The panel grown into a dialog over the chat, on the viewer's button. */\n const previewExpanded = ref(false)\n const previewBeside = computed(\n () =>\n !!previewTarget.value &&\n previewInPanel.value &&\n !previewExpanded.value,\n )\n\n const closePreview = () => {\n closeFilePreview()\n previewExpanded.value = false\n }\n\n /**\n * The tools whose calls write a file of this chat, a version each.\n * Declared before the computed that reads it: the watch on that computed\n * runs it during setup, and the welcome message is already there.\n */\n const CHAT_FILE_TOOL_PARTS = new Set([\n 'tool-editSpreadsheet',\n 'tool-editWordDocument',\n 'tool-createSpreadsheet',\n 'tool-createWordDocument',\n ])\n\n /**\n * Every version of each file in the conversation, by its fileId: the\n * file written by the user or the agent is version 1, its stored name is\n * the fileId.\n */\n const chatFileVersions = computed(() => {\n const byFile = new Map<string, Map<number, string>>()\n for (const message of messages.value) {\n for (const part of message.parts) {\n const { type, state, output } = part as {\n type: string\n state?: string\n output?: {\n fileId?: string\n version?: number\n storedFileName?: string\n }\n }\n if (\n CHAT_FILE_TOOL_PARTS.has(type) &&\n state === 'output-available' &&\n output?.fileId &&\n output.version &&\n output.storedFileName\n ) {\n const versions = byFile.get(output.fileId) ?? new Map()\n versions.set(output.version, output.storedFileName)\n byFile.set(output.fileId, versions)\n }\n }\n }\n for (const [fileId, versions] of byFile) {\n if (!versions.has(1)) {\n versions.set(1, fileId)\n }\n }\n return byFile\n })\n const previewVersions = computed(() =>\n [\n ...(chatFileVersions.value\n .get(previewTarget.value?.fileId ?? '')\n ?.keys() ?? []),\n ].sort((a, b) => a - b),\n )\n const showPreviewVersion = (version: number, since?: string) => {\n const target = previewTarget.value\n const storedFileName = chatFileVersions.value\n .get(target?.fileId ?? '')\n ?.get(version)\n if (target && storedFileName) {\n openPreview({ ...target, version, storedFileName }, since)\n }\n }\n /** The shown version is an earlier one the agent can write again. */\n const previewRestorable = computed(() => {\n const target = previewTarget.value\n const versions = previewVersions.value\n return (\n !!chatFileRestore.value &&\n !!target?.fileId &&\n !!target.version &&\n versions.length > 0 &&\n target.version < versions[versions.length - 1]\n )\n })\n const restoreFromPreview = () => {\n const target = previewTarget.value\n if (target?.fileId && target.version) {\n chatFileRestore.value?.({\n fileId: target.fileId,\n version: target.version,\n filename: target.filename,\n })\n closePreview()\n }\n }\n\n // Another chat has other files.\n watch(() => store.localChatId, resetPreview)\n\n // An edit makes a new version: the viewer showing the latest one moves to\n // it and marks what changed (spec chat-file-selection-edit.md), and an\n // earlier one stays put.\n // Read only while a file is open: the versions scan every message, and a\n // watch on all of them ran at each streamed delta, viewer closed too.\n watch(\n () => {\n const fileId = previewTarget.value?.fileId\n return fileId\n ? { fileId, newest: Math.max(0, ...previewVersions.value) }\n : undefined\n },\n (now, before) => {\n if (\n now &&\n before &&\n now.fileId === before.fileId &&\n now.newest > before.newest &&\n previewTarget.value?.version === before.newest\n ) {\n showPreviewVersion(\n now.newest,\n previewTarget.value.storedFileName,\n )\n }\n },\n )\n\n /**\n * The selection bar's actions for the open file's format (spec\n * `chat-file-selection-edit.md`): none in a conversation that takes no\n * message, nor while an answer runs.\n */\n const previewSelectionActions = computed(() => {\n const status = chat.value?.status\n if (\n isConversationBlocked.value ||\n status === 'submitted' ||\n status === 'streaming'\n ) {\n return undefined\n }\n return previewTarget.value?.kind === 'word'\n ? agentSelectionActions.value?.word\n : agentSelectionActions.value?.excel\n })\n const sendFromPreview = (\n text: string,\n pointer: FilePointer,\n action: { id: string; size: number },\n ) => {\n if (store.sendSelection(text, { filePointer: pointer })) {\n emit('selection-action', {\n surface: pointer.format === 'docx' ? 'word' : 'excel',\n action: action.id,\n state: 'chat',\n size: String(action.size),\n })\n }\n }\n // #endregion\n\n const handleExpandSourceContext = async (payload: {\n documentId: string\n chunkIndex: number\n }) => {\n const result = await apiClient.value.expandSourceContext(\n props.agentId,\n payload.documentId,\n payload.chunkIndex,\n )\n return result.content\n }\n\n const handleDownloadSource = async (documentId: string) => {\n const result = await apiClient.value.downloadSourceDocument(\n props.agentId,\n documentId,\n )\n window.open(result.downloadUrl, '_blank')\n }\n\n const handleFileDrop = (files: File[] | null) => {\n if (!agentFileUpload.value?.enabled || !files) {\n return\n }\n for (const file of files) {\n handleFileSelect(file)\n }\n }\n\n const { isOverDropZone } = useDropZone(chatViewEl, {\n dataTypes: (types) =>\n chatDropAccepts(\n types,\n agentFileUpload.value?.allowedMimeTypes ?? [],\n ),\n onDrop: handleFileDrop,\n })\n\n // #region voice\n /**\n * A spoken turn is a normal turn: the provider calls our backend, which\n * persists it into this very conversation. So the client does not answer\n * anything here, it only shows the transcript as it arrives and then reloads\n * the conversation from the server, which is the version that also carries\n * sources and tool results. When the call ends the input comes back with the\n * whole exchange above it, ready to continue in writing.\n */\n const isMuted = ref(false)\n // The session closes asynchronously, so `onTurnEnd` can still fire after\n // this view is gone: without the flag it would schedule a reload of a\n // conversation nobody is showing.\n let isUnmounted = false\n\n /**\n * True between the caller finishing a sentence and the answer starting.\n *\n * On a call nothing of the turn passes through this client, so the feed has\n * no way of its own to show that something is happening: the question sits\n * there alone until the answer is written and reloaded, which on a\n * retrieving turn is a long ten seconds of a screen that looks stuck.\n */\n const isAwaitingSpokenAnswer = ref(false)\n\n /**\n * How the conversation catches up with what the server persisted: one\n * sequential chain of reloads, the next scheduled only when the previous\n * one has answered, so slow responses never pile up. It replaces an\n * interval plus a backed-off retry ladder that could overlap each other.\n *\n * While the call is live it looks every {@link POLL_LIVE_MS}. When the\n * call is over (hang-up, provider disconnect, time cap) it keeps looking:\n * the turn that killed the call is by definition longer than the\n * provider's own timeout, and its write can land minutes later. Measured\n * live (2026-08-26, chat FYYaVLwX1UyU3CnQ): answers persisted 172 seconds\n * and 6.5 minutes after their turn started, both past the fixed 60-second\n * grace this replaces, and the screen stayed frozen until a manual reload.\n */\n const POLL_LIVE_MS = 3000\n const POLL_ENDED_BACKOFF_MS = [3000, 5000, 10_000]\n /**\n * The after-call poll never gives up before this, even with nothing on\n * screen looking missing: a write can land late and leave no trace to wait\n * for, because a turn the provider never transcribed has no spoken line of\n * its own.\n */\n const POLL_ENDED_MIN_MS = 60_000\n /**\n * And this much when the call ended badly, which is the case where a turn\n * is certainly still running server-side: the provider hangs up on a turn\n * it considers too slow, and that turn keeps going and is written when it\n * ends. A minute is not enough for it (measured 172 seconds, and once six\n * and a half minutes).\n */\n const POLL_FAILED_MIN_MS = 300_000\n /** And never survives longer than this, whatever is still missing. */\n const POLL_ENDED_MAX_MS = 600_000\n\n let pollTimer: ReturnType<typeof setTimeout> | undefined\n /** Set by the first look that finds the call over: the after-call clock. */\n let callEndedAt: number | undefined\n /**\n * Whether that call ended on a failure, read once when it ended: the\n * caller can dismiss the error from the bar, and the turn it interrupted\n * would not stop running because the message went away.\n */\n let callEndedBadly = false\n let endedBackoffStep = 0\n /**\n * A look is in flight. Guards the one thing a single timer cannot: a poke\n * (a turn that ended, an answer sent from a card) landing while the\n * previous request is still open would fire a second one beside it.\n */\n let isPolling = false\n\n /**\n * Ends the chain. Also puts the working indicator away: whatever it was\n * waiting for is either on screen or never coming, and an indicator left\n * spinning under the conversation promises an answer nobody is producing.\n */\n function stopPolling() {\n clearTimeout(pollTimer)\n pollTimer = undefined\n callEndedAt = undefined\n callEndedBadly = false\n endedBackoffStep = 0\n isAwaitingSpokenAnswer.value = false\n }\n\n /** One timer for the whole chain, so two looks can never overlap. */\n function schedulePoll(delayMs: number) {\n if (isUnmounted) {\n return\n }\n clearTimeout(pollTimer)\n pollTimer = setTimeout(() => {\n void runPoll()\n }, delayMs)\n }\n\n async function runPoll() {\n // The look that is running will schedule the next one, with fresher\n // data than this one would have asked for.\n if (isUnmounted || isPolling) {\n return\n }\n isPolling = true\n let outcome: Awaited<ReturnType<typeof refreshMessages>>\n try {\n outcome = await refreshMessages()\n } finally {\n isPolling = false\n }\n if (isUnmounted) {\n return\n }\n // Everything spoken is on screen: the wait, if any, is over, and the\n // turns it waited for are written.\n if (outcome === 'caught-up') {\n isAwaitingSpokenAnswer.value = false\n spokenTurnsWritten()\n }\n if (voice.isActive.value) {\n callEndedAt = undefined\n callEndedBadly = false\n endedBackoffStep = 0\n schedulePoll(POLL_LIVE_MS)\n return\n }\n if (callEndedAt === undefined) {\n callEndedAt = Date.now()\n callEndedBadly = !!voice.error.value\n }\n const elapsed = Date.now() - callEndedAt\n // Only a reload that was actually applied and found nothing missing\n // ends the chain, and never before the floor: 'indeterminate' (a\n // failed request, a stale answer) keeps it alive, or a transient\n // failure would strand the last turn.\n const floorMs = callEndedBadly ? POLL_FAILED_MIN_MS : POLL_ENDED_MIN_MS\n const settled = outcome === 'caught-up' && elapsed >= floorMs\n if (settled || elapsed >= POLL_ENDED_MAX_MS) {\n stopPolling()\n // Only here: a call started again restarts the chain too, and the\n // turn the previous call left unwritten is still on its way.\n forgetSpokenTurns()\n return\n }\n const delay =\n POLL_ENDED_BACKOFF_MS[\n Math.min(endedBackoffStep, POLL_ENDED_BACKOFF_MS.length - 1)\n ]\n endedBackoffStep += 1\n schedulePoll(delay)\n }\n\n /** Pulls the next look closer: a turn just ended, an answer was sent. */\n const pokePoll = (delayMs = 1200) => {\n schedulePoll(delayMs)\n }\n\n /**\n * The page tools of the call being opened (spec `voice-page-control.md`):\n * declared with the session, and run by the handlers the provider calls,\n * both taken at the same moment so they name the same tools.\n */\n let callPageTools: ReturnType<typeof store.voicePageTools>\n\n const voice = useVoiceSession({\n fetchGrant: async () => {\n callPageTools = store.voicePageTools()\n const grant = await apiClient.value.createVoiceSession(\n props.agentId,\n store.localChatId,\n {\n deviceContext: store.buildDeviceContext(),\n externalContext: store.externalContext,\n pageTools: callPageTools?.declaration,\n ...(store.confirmationMode === 'automatic' && {\n confirmations: 'automatic' as const,\n }),\n },\n )\n // The backend decides which conversation the call writes into, and\n // it may not be the one asked for: a stale id (a deleted chat, or\n // one left over from another agent) opens a new conversation rather\n // than failing the call. Follow it, or the transcript would land\n // somewhere this view is not showing.\n if (grant.chatId !== store.localChatId) {\n store.localChatId = grant.chatId\n }\n return grant\n },\n closeGrant: (sessionId) =>\n apiClient.value.closeVoiceSession(props.agentId, sessionId),\n clientTools: () => callPageTools?.clientTools,\n onTranscript: (entry) => {\n // What the AGENT says never becomes a message here, only the\n // written turn does. The transcript is text and nothing else, so\n // showing it meant a plain paragraph appearing and then being\n // swapped for the real answer with its sources and its widgets a\n // second later, and any part of it the server never writes (a\n // filler, a sentence the provider reworded) hanging around as the\n // last message until a manual reload (reported 2026-08-27). The\n // wait is shown by `isAwaitingSpokenAnswer` instead, and the\n // answer arrives once, whole.\n if (entry.role !== 'user') {\n // It is still the end of the wait: the agent has the floor.\n isAwaitingSpokenAnswer.value = false\n return\n }\n // The caller stopped talking: from here until the answer lands,\n // the turn is ours to show as working.\n isAwaitingSpokenAnswer.value = true\n spokenTurnStarted()\n appendMessage({\n // Marked as its own id space so a reload of the persisted\n // conversation replaces this rather than duplicating it, and\n // keeps it while the server does not have it yet.\n id: `${VOICE_LINE_ID_PREFIX}user-${generateId()}`,\n role: 'user',\n parts: [{ type: 'text', text: entry.text }],\n })\n },\n // The persisted answer arrives a moment after the provider finished\n // speaking it, so the reload waits for the write to land. The wait\n // indicator is NOT cleared here: a turn can end with nothing spoken\n // (the provider cut it), and the poll clearing it on caught-up is the\n // only signal that tells that apart from an answer on its way.\n onTurnEnd: () => {\n pokePoll()\n },\n })\n\n // A call that ends leaves no one to answer its page actions: they stop,\n // and their card goes with them.\n watch(\n () => voice.isActive.value,\n (active) => {\n if (!active) {\n store.cancelVoicePageCalls()\n }\n },\n )\n\n // A failure takes the stage: the error bar says what happened, and a\n // working indicator under it would promise an answer that may never come.\n watch(\n () => voice.error.value,\n (failure) => {\n if (failure) {\n isAwaitingSpokenAnswer.value = false\n }\n },\n )\n\n const isVoiceEnabled = computed(() => agentVoice.value?.enabled === true)\n\n /** What the session bar and the visualiser render. */\n const voiceState = computed(() => {\n if (voice.error.value) {\n return 'error' as const\n }\n if (voice.isConnecting.value) {\n return 'connecting' as const\n }\n if (voice.isSpeaking.value) {\n return 'speaking' as const\n }\n return voice.isActive.value ? ('listening' as const) : ('idle' as const)\n })\n\n /**\n * What the failure says on screen.\n *\n * Never the provider's own words: those are English prose written for\n * whoever wired the integration (\"custom_llm_error: LLM Cascade Error:\n * Brain returned no response\"), and passing the unrecognized ones through\n * put exactly that in front of a caller (production, 2026-08-27). The two\n * families we can tell apart get copy that says what to do about them,\n * everything else gets the honest generic one, and the raw text stays in\n * the tooltip for whoever is debugging.\n */\n const voiceErrorText = computed(() => {\n const raw = voice.error.value\n if (!raw) {\n return undefined\n }\n if (/took too long/i.test(raw)) {\n return $t('message.voiceTookTooLong')\n }\n // Their word for \"the turn produced nothing I could speak\", whatever\n // broke underneath: a cascade error, an empty completion, a refused\n // model. Trying again is the one thing that helps.\n if (/cascade|no response|custom_llm_error/i.test(raw)) {\n return $t('message.voiceNoAnswer')\n }\n return $t('message.voiceInterrupted')\n })\n\n /** Whoever is on air feeds the bars: the user, then the agent answering. */\n const voiceChannel = computed<'input' | 'output'>(() =>\n voice.isSpeaking.value ? 'output' : 'input',\n )\n const sampleVoiceLevel = () => voice.readLevel(voiceChannel.value)\n const sampleVoiceSpectrum = () => voice.readSpectrum(voiceChannel.value)\n\n const startVoice = async () => {\n isMuted.value = false\n await voice.start()\n if (voice.isActive.value) {\n // A fresh call restarts the clock of the chain: whatever the\n // previous one still owed, this one is live again.\n stopPolling()\n schedulePoll(POLL_LIVE_MS)\n }\n }\n\n const stopVoice = async () => {\n isAwaitingSpokenAnswer.value = false\n await voice.stop()\n if (isUnmounted) {\n return\n }\n // First look right away; the chain deliberately survives the call\n // (see POLL_ENDED_MIN_MS) and covers the write that lands later.\n pokePoll(0)\n }\n\n /** Leaves the failure behind and gives the written input back. */\n const dismissVoiceError = () => {\n voice.dismissError()\n }\n\n /** Same button, one step: forget the failure and open a new call. */\n const retryVoice = async () => {\n voice.dismissError()\n // The provider can report a failure on a socket that is still open,\n // and `start()` refuses while one exists: without this stop the retry\n // button only dismissed the error and never opened a new call.\n await voice.stop()\n await startVoice()\n }\n\n /**\n * Tool calls this client answered while the call was up, by id.\n *\n * On a call the answer does not go back to the tool call (it goes to the\n * agent as speech), so nothing in the persisted part ever changes to say it\n * was given: without this the same widget stays answerable forever and the\n * caller can send the same thing three times.\n */\n const readToolCallId = (part: unknown) =>\n (part as { toolCallId?: string })?.toolCallId ?? ''\n\n const answeredOnCall = ref(new Set<string>())\n const isAnsweredOnCall = (part: unknown) =>\n answeredOnCall.value.has(readToolCallId(part))\n\n /**\n * The verdicts of the confirms answered ON A CALL, by toolCallId. A spoken\n * verdict never resolves the tool part (the answer travels as a user\n * message), so without this the card kept its buttons and every extra tap\n * said \"Confermo\" again (three times in a row, measured 2026-08-07).\n * Recorded only when the send went through: `answerOnCall` leaves a failed\n * send unanswered on purpose, so the caller can tap again.\n */\n const confirmVerdictsOnCall = ref(new Map<string, boolean>())\n\n /**\n * Something the caller answered on screen during a call.\n *\n * In writing an answer resumes the suspended tool call, which is what makes\n * the agent continue. On a call there is no suspended call to resume: the\n * turn that drew the widget closed it on its own (a call cannot wait for a\n * screen), so the answer is said on the caller's behalf and comes back\n * spoken, in the same conversation.\n *\n * Returns true when it was said, and then the written path must NOT run:\n * `addToolOutput` would resume the turn in writing and the caller would get\n * two answers, one of them silent.\n */\n const answerOnCall = (part: unknown, spoken: string): boolean => {\n if (!voice.isActive.value) {\n return false\n }\n if (voice.sendUserMessage(spoken)) {\n answeredOnCall.value = new Set(answeredOnCall.value).add(\n readToolCallId(part),\n )\n pokePoll()\n return true\n }\n // The call is up and the answer did not get through. Saying it in\n // writing here would answer a question nobody asked in writing, so the\n // widget stays as it is and the caller can try again.\n return true\n }\n\n /** A form or a set of options, answered on screen. */\n const onFormAnswer = (\n tool: 'showForm' | 'showMultipleChoice',\n part: unknown,\n answer: string | { answers: { id: string; value: unknown }[] },\n ) => {\n if (answerOnCall(part, formAnswerAsSpoken(part, answer))) {\n return\n }\n addToolOutput({\n tool,\n toolCallId: readToolCallId(part),\n output: answer,\n })\n }\n\n /** A confirmation card, answered on screen. */\n const onConfirmRespond = (payload: {\n toolCallId: string\n confirmed: boolean\n }) => {\n const spoken = payload.confirmed\n ? $t('message.voiceConfirmed')\n : $t('message.voiceCancelled')\n if (answerOnCall({ toolCallId: payload.toolCallId }, spoken)) {\n if (answeredOnCall.value.has(payload.toolCallId)) {\n confirmVerdictsOnCall.value = new Map(\n confirmVerdictsOnCall.value,\n ).set(payload.toolCallId, payload.confirmed)\n }\n return\n }\n addToolOutput({\n tool: 'requestConfirm',\n toolCallId: payload.toolCallId,\n output: payload.confirmed ? 'confirmed' : 'cancelled',\n })\n }\n\n /**\n * The latest version of each file the conversation shows, by its fileId:\n * the card of an earlier version offers to restore it.\n */\n const latestFileVersions = computed(() => {\n const latest = new Map<string, number>()\n for (const message of messages.value) {\n for (const part of message.parts) {\n const { type, state, output } = part as {\n type: string\n state?: string\n output?: { fileId?: string; version?: number }\n }\n if (\n CHAT_FILE_TOOL_PARTS.has(type) &&\n state === 'output-available' &&\n output?.fileId &&\n output.version\n ) {\n latest.set(\n output.fileId,\n Math.max(\n latest.get(output.fileId) ?? 0,\n output.version,\n ),\n )\n }\n }\n }\n return latest\n })\n\n /**\n * The files of the conversation by name, uploaded or written by the\n * agent, as the fileIds the agent knows them by.\n */\n const chatFileIdsByName = computed(() => {\n const byName = new Map<string, Set<string>>()\n const add = (filename?: string, fileId?: string) => {\n if (filename && fileId) {\n const key = filename.toLowerCase()\n byName.set(key, (byName.get(key) ?? new Set()).add(fileId))\n }\n }\n for (const message of messages.value) {\n for (const part of message.parts) {\n if (isFilePart(part)) {\n add(part.filename, getFilePartMedia(part)?.storedFileName)\n continue\n }\n const { type, state, output } = part as {\n type: string\n state?: string\n output?: {\n fileId?: string\n filename?: string\n version?: number\n }\n }\n if (\n CHAT_FILE_TOOL_PARTS.has(type) &&\n state === 'output-available' &&\n output?.filename\n ) {\n add(\n chatFileName(output.filename, output.version),\n output.fileId,\n )\n }\n }\n }\n return byName\n })\n\n /**\n * \"Restore\" on the card of an earlier version: asking the agent for it,\n * in a conversation that can still take a message. When two files share\n * the name, the message names the file by its fileId.\n */\n const chatFileRestore = computed(() =>\n isConversationBlocked.value\n ? undefined\n : (file: ChatFileRestoreTarget) => {\n const twins =\n (chatFileIdsByName.value.get(file.filename.toLowerCase())\n ?.size ?? 0) > 1\n input.value = twins\n ? $t('messagePart.chatFileRestoreRequestById', file)\n : $t('messagePart.chatFileRestoreRequest', file)\n storeHandleSubmit()\n },\n )\n\n /** A suggested reply: tapping it is saying it. */\n const onSuggestedReply = (part: unknown, reply: string) => {\n if (answerOnCall(part, reply)) {\n return\n }\n input.value = reply\n storeHandleSubmit()\n }\n\n /** The position the caller shared from the browser. */\n const onGeolocation = (\n part: unknown,\n result: {\n latitude?: number\n longitude?: number\n displayName?: string\n error?: string\n },\n ) => {\n const spoken = result.error\n ? $t('message.voiceLocationRefused')\n : $t('message.voiceLocationShared', {\n place:\n result.displayName ??\n `${result.latitude}, ${result.longitude}`,\n })\n if (answerOnCall(part, spoken)) {\n return\n }\n addToolOutput({\n tool: 'requestGeolocation',\n toolCallId: readToolCallId(part),\n output: result,\n })\n }\n\n /** An integration the caller connected from the card on screen. */\n const onOAuthConnected = (part: unknown, mcpServerId: string) => {\n if (answerOnCall(part, $t('message.voiceConnectionDone'))) {\n return\n }\n addToolOutput({\n tool: 'requestOAuthConnection',\n toolCallId: readToolCallId(part),\n output: { connected: true, mcpServerId },\n })\n }\n\n const toggleVoiceMute = () => {\n isMuted.value = !isMuted.value\n voice.setMuted(isMuted.value)\n }\n\n onBeforeUnmount(() => {\n isUnmounted = true\n stopPolling()\n })\n // #endregion voice\n\n // #region wakeups\n /** The checks the agent runs by itself (spec agent-wakeup). */\n const {\n pendingWakeup,\n isStopping: isStoppingWakeup,\n stop: stopWakeup,\n spokenTurnStarted,\n spokenTurnsWritten,\n forgetSpokenTurns,\n } = useWakeupWatch({\n agentId: () => props.agentId,\n chatId: () => store.localChatId,\n apiClient: () => apiClient.value,\n messages: () => messages.value,\n refreshMessages,\n status: () => chat.value.status,\n })\n // #endregion wakeups\n</script>\n\n<template>\n <div\n ref=\"chatViewEl\"\n class=\"pk-chatbot-view-chat\"\n :class=\"{\n 'pk-chatbot-view-chat--dragover':\n isOverDropZone && agentFileUpload?.enabled,\n 'pk-chatbot-view-chat--empty': showEmptyState,\n 'pk-chatbot-view-chat--with-preview':\n previewBeside && !previewDocked,\n }\">\n <!-- #region empty state (fullscreen) / messages — crossfade out-in -->\n <Transition name=\"pk-chatbot-view-chat-fade\" mode=\"out-in\">\n <PkChatbotEmptyState\n v-if=\"showEmptyState\"\n :greeting=\"greeting\"\n :logo=\"agentInterface?.logo\"\n :name=\"store.name\" />\n <PkChatbotMessages\n v-else\n class=\"flex flex-col flex-1 min-h-0 p-md overflow-y-auto\"\n interactive\n :messages=\"messages\"\n :confirm-verdicts-on-call=\"confirmVerdictsOnCall\"\n :status=\"chat.status\"\n :error=\"chat.error\"\n :main-color=\"agentInterface?.mainColor\"\n :text-color=\"agentInterface?.textColor\"\n :revised-answers=\"revisedAnswers\"\n :actions=\"actions\"\n :message-feedbacks=\"messageFeedbacks\"\n :feedback-message-id=\"feedbackDialogMessage?.id\"\n :feedback-loading=\"isFeedbackSubmitting\"\n :feedback-submitted=\"isFeedbackSubmitted\"\n :feedback-error=\"feedbackSubmitError\"\n :show-extended-steps=\"agentInterface?.showExtendedSteps\"\n :hide-reasoning=\"agentInterface?.showReasoning === false\"\n :awaiting-spoken-answer=\"isAwaitingSpokenAnswer\"\n :host-working=\"hostWorking\"\n :host-confirmation=\"hostConfirmation\"\n :is-dark=\"isDark\"\n :show-scroll-to-bottom=\"modifier === 'fullscreen'\"\n @feedback-submit=\"onFeedbackSubmit($event)\"\n @feedback-close=\"feedbackDialogMessage = undefined\"\n @regenerate=\"regenerate\"\n @auto-retry=\"regenerate\"\n @reset-chat=\"startNewChat\"\n @show-info=\"emit('show-info', $event)\"\n @revise=\"emit('revise', $event)\"\n @upvote=\"onUpvote\"\n @downvote=\"onDownvote\"\n @feedback=\"onFeedback\"\n @approval-respond=\"addToolApprovalResponse\"\n @confirm-respond=\"onConfirmRespond\"\n @host-confirm-respond=\"respondHostConfirmation\">\n <template #tool-showContactForm=\"{ part }\">\n <PkToolShowContactForm\n :part\n :readonly=\"!baseUrl\"\n :submitted=\"isLeadSubmitted\"\n :loading=\"isLoadingSubmitLead\"\n :error=\"submitLeadError\"\n :privacy-policy-notice=\"\n agentInterface?.privacyPolicyNotice\n \"\n @submit=\"onLeadSubmit\" />\n </template>\n <template #tool-showSuggestedReply=\"{ part }\">\n <PkToolShowSuggestedReply\n :part\n @select=\"onSuggestedReply(part, $event)\" />\n </template>\n <template #tool-showSources=\"{ part }\">\n <PkToolShowSources\n :part\n :on-expand-context=\"handleExpandSourceContext\"\n :on-download=\"handleDownloadSource\" />\n </template>\n <template #tool-showForm=\"{ part }\">\n <transition mode=\"out-in\">\n <PkToolShowForm\n :part\n :answered=\"isAnsweredOnCall(part)\"\n @select=\"onFormAnswer('showForm', part, $event)\" />\n </transition>\n </template>\n <template #tool-showMultipleChoice=\"{ part }\">\n <transition mode=\"out-in\">\n <PkToolShowForm\n :part\n allow-custom-answer\n :answered=\"isAnsweredOnCall(part)\"\n @select=\"\n onFormAnswer('showMultipleChoice', part, $event)\n \" />\n </transition>\n </template>\n <template #tool-requestOAuthConnection=\"{ part }\">\n <PkToolRequestOAuthConnection\n :part\n :backend-url=\"baseUrl\"\n :resolve-connection=\"\n (serverName: string) =>\n apiClient.getOAuthAuthorizeUrl(\n props.agentId,\n serverName,\n )\n \"\n :check-connection=\"\n (serverName: string) =>\n apiClient.getOAuthConnectionStatus(\n props.agentId,\n serverName,\n )\n \"\n @connected=\"onOAuthConnected(part, $event)\" />\n </template>\n <template #tool-requestGeolocation=\"{ part }\">\n <PkToolRequestGeolocation\n :part\n :call-live=\"voice.isActive.value\"\n :reverse-geocode=\"\n (lat: number, lon: number) =>\n apiClient.reverseGeocode(lat, lon)\n \"\n @result=\"onGeolocation(part, $event)\" />\n </template>\n <template #tool-showLocation=\"{ part }\">\n <PkToolShowLocation\n :part\n :is-dark\n :main-color=\"agentInterface?.mainColor\"\n :forward-geocode=\"\n (query: string, lang?: string) =>\n apiClient.forwardGeocode(query, lang)\n \" />\n </template>\n <template #tool-showChart=\"{ part }\">\n <PkToolShowChart :part :is-dark />\n </template>\n <template #tool-showDiagram=\"{ part }\">\n <PkToolShowDiagram :part :is-dark />\n </template>\n <template #tool-editSpreadsheet=\"{ part }\">\n <!-- Keyed on the state like the feed's own tool\n components: the card mounts while the call runs, and\n the SDK writes the output into that same part object,\n which alone would not redraw it. -->\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-editWordDocument=\"{ part }\">\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-createSpreadsheet=\"{ part }\">\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-createWordDocument=\"{ part }\">\n <PkToolChatFile\n :key=\"getPartState(part)\"\n :part\n :file-url=\"chatFileDownloadUrl\"\n :preview=\"openPreview\"\n :latest-versions=\"latestFileVersions\"\n :restore=\"chatFileRestore\" />\n </template>\n <template #tool-shareDocument=\"{ part }\">\n <!-- Keyed on the state for the same reason. -->\n <PkToolShareDocument\n :key=\"getPartState(part)\"\n :part\n :on-download=\"handleDownloadSource\" />\n </template>\n </PkChatbotMessages>\n </Transition>\n <!-- #endregion -->\n\n <PkChatbotQueuedMessages\n v-if=\"queuedMessages.length\"\n :messages=\"queuedMessages\"\n @edit=\"editQueuedMessage\"\n @remove=\"removeQueuedMessage\" />\n\n <!-- #region input -->\n <div class=\"pk-chatbot-view-chat__input-stage\">\n <!-- Animated accent glow radiating from the input pill -->\n <Transition name=\"pk-chatbot-view-chat-fade\">\n <PkAuroraCanvas\n v-if=\"showEmptyState\"\n class=\"pk-chatbot-view-chat__aurora\"\n source-selector=\".pk-chatbot-input__form\"\n :main-color=\"agentInterface?.mainColor\"\n :tones=\"agentInterface?.glowTones\"\n :second-color=\"agentInterface?.glowSecondColor\" />\n </Transition>\n <PkChatbotWakeupBar\n v-if=\"pendingWakeup && !isConversationBlocked\"\n :pending=\"pendingWakeup\"\n :stopping=\"isStoppingWakeup\"\n @stop=\"stopWakeup\" />\n <div\n v-if=\"isConversationBlocked\"\n class=\"p-md border-t border-surface-3 text-center text-12 text-danger bg-surface-danger\">\n {{ $t('message.chatErrorConversationBlocked') }}\n </div>\n <!-- A live call takes the place of the input: one thing on air, one\n way to hang up, and the conversation stays above it -->\n <PkVoiceSession\n v-else-if=\"voiceState !== 'idle'\"\n :state=\"voiceState\"\n :sample=\"sampleVoiceLevel\"\n :spectrum=\"sampleVoiceSpectrum\"\n :remaining-seconds=\"voice.remainingSeconds.value\"\n :muted=\"isMuted\"\n :error=\"voiceErrorText\"\n :raw-error=\"voice.error.value\"\n :live=\"voice.isActive.value\"\n class=\"pk-chatbot-view-chat__voice\"\n @toggle-mute=\"toggleVoiceMute\"\n @hang-up=\"stopVoice\"\n @retry=\"retryVoice\"\n @dismiss=\"dismissVoiceError\" />\n <PkChatbotInput\n v-else\n ref=\"inputEl\"\n v-model=\"input\"\n v-model:pending-attachments=\"pendingAttachments\"\n :placeholder=\"inputMessagePlaceholder\"\n :dismissable-notice=\"\n dismissableNotice && chat.messages.length <= 1\n ? dismissableNotice\n : undefined\n \"\n :page-notice=\"pageNotice\"\n :status=\"inputStatus\"\n :max-message-length=\"agentInterface?.maxMessageLength\"\n :file-upload=\"agentFileUpload\"\n :attachment-limit-reached=\"isAttachmentLimitReached\"\n :attachment-notice=\"attachmentNotice\"\n :voice-enabled=\"isVoiceEnabled\"\n :queue-enabled=\"canQueue\"\n :answer-notices=\"answerNotices\"\n :pointer-available=\"pagePointerAvailable\"\n :pointing=\"pagePointing\"\n :pointer=\"pointerChip\"\n :automatic-confirmations=\"confirmationMode === 'automatic'\"\n editable-images\n retryable-attachments\n @point=\"store.pagePointerStart?.()\"\n @remove-pointer=\"pagePointer = undefined\"\n @manual-confirmations=\"store.setConfirmationMode('manual')\"\n @stop-generation=\"stopGeneration\"\n @submit=\"storeHandleSubmit\"\n @file-select=\"handleFileSelect\"\n @remove-attachment=\"discardPendingAttachment\"\n @replace-attachment=\"replacePendingAttachment\"\n @retry-attachment=\"retryPendingAttachment\"\n @dismiss-attachment-notice=\"clearFileLimitError\"\n @dismiss-page-notice=\"closePageNotice\"\n @open-answer-notice=\"openBackgroundAnswer\"\n @dismiss-answer-notice=\"dismissBackgroundAnswer\"\n @voice-start=\"startVoice\">\n <!-- Fullscreen has no header: the agent identity lives in the\n input pill -->\n <template v-if=\"modifier === 'fullscreen'\" #prepend>\n <span class=\"pk-chatbot-view-chat__agent-chip\">\n <PkAvatar\n class=\"pk-chatbot-view-chat__agent-chip-avatar\"\n :img-src=\"agentInterface?.logo\"\n :name=\"store.name\" />\n <strong\n v-if=\"store.name\"\n class=\"pk-chatbot-view-chat__agent-chip-name\">\n {{ store.name }}\n </strong>\n </span>\n </template>\n </PkChatbotInput>\n </div>\n <!-- #endregion -->\n <Transition>\n <div\n v-if=\"isOverDropZone && agentFileUpload?.enabled\"\n class=\"pk-chatbot-view-chat__drop-overlay\">\n <VvIcon\n name=\"ri:upload-cloud-2-line\"\n class=\"pk-chatbot-view-chat__drop-overlay-icon\" />\n <span>{{ $t('action.dropFile') }}</span>\n </div>\n </Transition>\n <!-- #region file preview: beside the chat, in the page's column when\n it gives one, or over it -->\n <Teleport\n v-if=\"previewBeside\"\n :to=\"previewDockTarget\"\n :disabled=\"!previewDocked\">\n <aside\n class=\"pk-chatbot-view-chat__preview\"\n :class=\"{\n 'pk-chatbot-view-chat__preview--docked': previewDocked,\n }\">\n <PkFilePreview\n v-if=\"previewTarget\"\n v-model:mode=\"previewView.mode\"\n v-model:sheet=\"previewView.sheet\"\n v-model:zoom=\"previewView.zoom\"\n v-model:fit=\"previewView.fit\"\n :kind=\"previewTarget.kind\"\n :filename=\"previewTarget.filename\"\n :version=\"previewTarget.version\"\n :versions=\"previewVersions\"\n :download-url=\"\n chatFileDownloadUrl(previewTarget.storedFileName)\n \"\n :preview=\"previewData\"\n :changes=\"previewChanges\"\n :loading=\"previewLoading\"\n :error=\"previewError\"\n :restorable=\"previewRestorable\"\n resize=\"expand\"\n :file-id=\"previewTarget.fileId\"\n :stored-file-name=\"previewTarget.storedFileName\"\n :selection-actions=\"previewSelectionActions\"\n @version=\"showPreviewVersion\"\n @restore=\"restoreFromPreview\"\n @resize=\"previewExpanded = true\"\n @selection-send=\"sendFromPreview\"\n @close=\"closePreview\" />\n </aside>\n </Teleport>\n <PkFilePreviewDialog\n v-if=\"previewTarget && !previewBeside\"\n v-model:mode=\"previewView.mode\"\n v-model:sheet=\"previewView.sheet\"\n v-model:zoom=\"previewView.zoom\"\n v-model:fit=\"previewView.fit\"\n :target=\"previewTarget\"\n :versions=\"previewVersions\"\n :download-url=\"chatFileDownloadUrl(previewTarget.storedFileName)\"\n :preview=\"previewData\"\n :changes=\"previewChanges\"\n :loading=\"previewLoading\"\n :error=\"previewError\"\n :restorable=\"previewRestorable\"\n :resize=\"previewInPanel ? 'shrink' : undefined\"\n :fullscreen=\"previewFullscreen\"\n :selection-actions=\"previewSelectionActions\"\n @version=\"showPreviewVersion\"\n @restore=\"restoreFromPreview\"\n @resize=\"previewExpanded = false\"\n @selection-send=\"sendFromPreview\"\n @close=\"closePreview\" />\n <!-- #endregion -->\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-chatbot-view-chat {\n --pk-chatbot-preview-width: 520px;\n\n position: relative;\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n\n // The preview of a Word document beside the chat: the messages and\n // the input keep a reading column, the panel takes the inline end.\n // Only from PREVIEW_PANEL_MIN_WIDTH of the script, a dialog below.\n &--with-preview {\n padding-inline-end: calc(\n var(--pk-chatbot-preview-width) + var(--spacing-12)\n );\n }\n\n // Where the page gives no column (the widget, the playground), one\n // frame on the ground of the chat, a little in from its edges: cut at\n // the chat's bottom, over the footer of the agent, it read as a panel\n // that stopped short.\n &__preview {\n position: absolute;\n inset-block: var(--spacing-12);\n inset-inline-end: var(--spacing-12);\n z-index: 1;\n width: var(--pk-chatbot-preview-width);\n overflow: hidden;\n border: var(--border) solid var(--color-surface-3);\n border-radius: var(--rounded-lg);\n background-color: var(--color-surface);\n\n // A column of the page, as its sidebar on the other side: the\n // page's height, outside the chat's header and footer. Outside\n // the chat's block, so its width is its own.\n &--docked {\n position: relative;\n inset: auto;\n flex-shrink: 0;\n width: clamp(520px, 38vw, 760px);\n height: 100%;\n border-width: 0 0 0 var(--border);\n border-radius: 0;\n }\n }\n\n // Empty state (fullscreen): center the greeting + input block\n // vertically in the available space\n &--empty {\n justify-content: center;\n gap: var(--spacing-md);\n\n // In a phone-sized chat the input docks to the bottom edge\n // instead (Gemini-like), with the greeting centered in the space\n // above. Keyed on the chat's own width (`--phone`, measured in\n // PkChatbot), not the viewport: a narrow preview frame on a\n // desktop screen docks the same way\n .pk-chatbot--phone & {\n justify-content: flex-start;\n\n .pk-chatbot-empty-state {\n flex: 1;\n justify-content: center;\n }\n }\n }\n\n // Anchors the glow to the input pill\n &__input-stage {\n position: relative;\n }\n\n // Radiates outwards from the pill (the pill itself paints above,\n // being later in the DOM). The shader caps each half of the glow at\n // the room this leaves on its side, so the room fits the glow at\n // rest: with 224px above and 160px below it was cut there instead.\n &__input-stage &__aurora {\n inset: calc(-1 * var(--spacing-320)) calc(-1 * var(--spacing-96));\n\n // With the input docked at the bottom the glow becomes a wide\n // dome filling the lower part of the chat (Gemini-like); same\n // threshold as the docking above\n .pk-chatbot--phone & {\n --aurora-spread: 1.6;\n\n // Tall enough that the glow tail never meets the canvas\n // edge fade (it would draw a visible horizontal band)\n inset: calc(-1 * var(--spacing-384) - var(--spacing-128))\n calc(-1 * var(--spacing-96)) calc(-1 * var(--spacing-160));\n }\n }\n\n // Agent identity inside the input pill (fullscreen has no header).\n // A rounded box rather than a pill: a pill around a tile drew two\n // curves that did not run together.\n &__agent-chip {\n display: inline-flex;\n align-items: center;\n gap: var(--spacing-6);\n flex-shrink: 0;\n padding: var(--spacing-4) var(--spacing-10) var(--spacing-4)\n var(--spacing-4);\n border: 1px solid var(--color-surface-3);\n border-radius: var(--rounded-lg);\n background-color: var(--color-surface);\n\n // Don't crowd the textarea in a narrow chat. Keyed on the chat's\n // own width (`--tight`, measured in PkChatbot), not the viewport:\n // a preview frame squeezed by side panels on a desktop screen is\n // as narrow as a phone page. Below that threshold the chip would\n // leave the textarea a couple of hundred pixels at best, and in a\n // phone-sized frame a few characters, wrapping the placeholder\n // into a tall pill. The empty state shows the avatar at the same\n // threshold: one of the two carries the agent identity.\n .pk-chatbot--tight & {\n display: none;\n }\n }\n\n &__agent-chip-avatar {\n width: var(--spacing-24);\n height: var(--spacing-24);\n font-size: var(--text-10);\n }\n\n &__agent-chip-name {\n font-size: var(--text-12);\n font-weight: var(--font-semibold);\n color: var(--color-word-2);\n white-space: nowrap;\n }\n\n // Crossfade empty state ↔ messages: exit faster than enter so the\n // switch never feels like a snap\n &-fade-enter-active {\n transition: opacity 250ms var(--ease-out);\n }\n\n &-fade-leave-active {\n transition: opacity 150ms var(--ease-out);\n }\n\n &-fade-enter-from,\n &-fade-leave-to {\n opacity: 0;\n }\n\n @media (prefers-reduced-motion: reduce) {\n &-fade-enter-active,\n &-fade-leave-active {\n transition: none;\n }\n }\n\n &__drop-overlay {\n position: absolute;\n inset: var(--spacing-sm) var(--spacing-sm) var(--spacing-sm)\n var(--spacing-sm);\n z-index: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--spacing-xs);\n background-color: color-mix(\n in srgb,\n var(--color-surface) 85%,\n transparent\n );\n border-radius: var(--rounded-xl);\n border: var(--spacing-2) dashed var(--color-surface-5);\n pointer-events: none;\n color: var(--color-word-3);\n\n &-icon {\n font-size: var(--spacing-32);\n }\n }\n }\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAeA,SAAgB6E,GACZ,GACA,GACmB;CACnB,IAAM,EAAE,WAAQ,MAAG,UAAOC,GAAQ,EAAE,UAAU,SAAS,CAAC;CAExD,OAAOC,QAEcC,EADNC,GAAQC,CAEf,CAAA,EAAI,WAAW,EAAE,GAAGC,EAAO,UAAU,IACrCF,GAAQG,CAAQ,CAKhB,MACCC,EAAG,6BAA6B,IAC3BC,EAAE,6BAA6B,IAC/B,GAEb;AACL;AAEA,SAASN,EAAuB,GAAkB,GAAuB;CAMrE,QALeO,IACTC,EAAS,QAAQ,aAAaD,CAAI,IAGlCC,EAAS,QAAQ,wBAAwB,EAAE,EAAA,CACnC,KAAK;AACvB;;;;;A,GCEUE,IAAgB,iGAOhBC,IAAkB,iyG;;;;;;;;;EAjCxB,IAAMG,IAAQC,GAWRC,IAASC,GAA4B,QAAQ,GAC7CC,IAAWD,GAAkC,UAAU,GACvDE,IAASC,EAAI,EAAK,GAClBC,IAAQD,EAAsB,IAAI,GAGlCE,IAAYvB,QACdsB,EAAM,QACA;GACI,oBAAoB,OAAOA,EAAM,MAAM,MAAM,KAAK,GAAG,EAAE;GACvD,sBAAsB,QAAQA,EAAM,MAAM,MAAMA,EAAM,MAAM,SAASA,EAAM,MAAM,MAAA,CAAO,KAAK,GAAG,EAAE;EACtG,IACA,KAAA,CACV,GAgGIE,IAAmC,MACnCC,IAAQ,GACRC,IAAwC,MACxCC,IAA4C,MAC5CC,IAAkD,MAClDC,IAA8C,MAC9CC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