@puredesktop/puredesktop-ui-bridge 1.0.0-beta.1 → 1.0.0-beta.2

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 (439) hide show
  1. package/package.json +4 -2
  2. package/src/agents/appAgentConnectors.test.ts +37 -0
  3. package/src/agents/appAgentConnectors.ts +138 -0
  4. package/src/agents/runtime/agentLiveReducer.test.ts +72 -72
  5. package/src/agents/runtime/agentLiveReducer.ts +139 -139
  6. package/src/agents/runtime/agentRunEventTypes.ts +115 -115
  7. package/src/agents/runtime/contextWindowUsage.test.ts +38 -38
  8. package/src/agents/runtime/contextWindowUsage.ts +25 -25
  9. package/src/agents/runtime/index.ts +24 -24
  10. package/src/agents/runtime/mapAgentMessages.ts +79 -54
  11. package/src/agents/runtime/mapAgentSnapshot.test.ts +98 -0
  12. package/src/agents/runtime/mapAgentSnapshot.ts +124 -71
  13. package/src/agents/runtime/mergeUsageTurn.ts +23 -23
  14. package/src/agents/runtime/pendingToolCalls.test.ts +85 -85
  15. package/src/agents/runtime/pendingToolCalls.ts +14 -14
  16. package/src/agents/runtime/toolRequiresApproval.ts +20 -20
  17. package/src/agents/runtime/unresolvedToolCalls.ts +42 -42
  18. package/src/bridge/agentModelTiers.ts +50 -50
  19. package/src/bridge/agentToolHandlers.ts +23 -23
  20. package/src/bridge/agentToolHelpers.test.ts +27 -27
  21. package/src/bridge/agentToolHelpers.ts +20 -20
  22. package/src/bridge/agentTypes.ts +377 -294
  23. package/src/bridge/agents.d.mts +144 -113
  24. package/src/bridge/agents.mjs +287 -233
  25. package/src/bridge/agents.ts +77 -62
  26. package/src/bridge/appSettings.d.mts +9 -9
  27. package/src/bridge/appSettings.mjs +18 -18
  28. package/src/bridge/appSettings.ts +4 -4
  29. package/src/bridge/applyThemeFromHost.d.mts +7 -7
  30. package/src/bridge/applyThemeFromHost.mjs +33 -33
  31. package/src/bridge/assets.d.mts +66 -66
  32. package/src/bridge/assets.mjs +121 -121
  33. package/src/bridge/calendarDraftIntent.ts +55 -0
  34. package/src/bridge/calendarInviteIntent.ts +64 -0
  35. package/src/bridge/catalog.d.mts +5 -5
  36. package/src/bridge/catalog.mjs +24 -24
  37. package/src/bridge/catalog.ts +1 -1
  38. package/src/bridge/client.d.mts +19 -19
  39. package/src/bridge/client.mjs +102 -102
  40. package/src/bridge/collectionAssetAdapter.ts +63 -63
  41. package/src/bridge/collectionAssets.d.mts +1 -1
  42. package/src/bridge/collectionAssets.mjs +2 -2
  43. package/src/bridge/collectionAssets.ts +1 -1
  44. package/src/bridge/collectionDocumentHtml.test.ts +71 -71
  45. package/src/bridge/collectionDocumentHtml.ts +118 -118
  46. package/src/bridge/collectionImagePaste.test.ts +32 -32
  47. package/src/bridge/collectionImagePaste.ts +130 -130
  48. package/src/bridge/context.mjs +12 -12
  49. package/src/bridge/credentials.mjs +22 -22
  50. package/src/bridge/dialog.d.mts +5 -5
  51. package/src/bridge/dialog.mjs +13 -13
  52. package/src/bridge/events.d.mts +14 -14
  53. package/src/bridge/events.mjs +12 -12
  54. package/src/bridge/filePreviewKind.test.ts +43 -43
  55. package/src/bridge/filePreviewKind.ts +76 -76
  56. package/src/bridge/fs.d.mts +41 -41
  57. package/src/bridge/fs.mjs +82 -82
  58. package/src/bridge/fs.test.ts +16 -16
  59. package/src/bridge/fs.ts +10 -10
  60. package/src/bridge/googleAuth.ts +159 -0
  61. package/src/bridge/googleProviderConfig.ts +73 -0
  62. package/src/bridge/index.ts +12 -12
  63. package/src/bridge/inlinePreview.d.mts +35 -35
  64. package/src/bridge/inlinePreview.mjs +99 -99
  65. package/src/bridge/inlinePreview.test.ts +56 -56
  66. package/src/bridge/inlinePreview.ts +13 -13
  67. package/src/bridge/methods.d.mts +125 -115
  68. package/src/bridge/methods.mjs +143 -132
  69. package/src/bridge/os.d.mts +11 -11
  70. package/src/bridge/os.mjs +26 -26
  71. package/src/bridge/plugins.d.mts +9 -9
  72. package/src/bridge/plugins.mjs +31 -31
  73. package/src/bridge/plugins.ts +5 -5
  74. package/src/bridge/preferences.d.mts +7 -7
  75. package/src/bridge/preferences.mjs +17 -17
  76. package/src/bridge/preferences.ts +13 -13
  77. package/src/bridge/printDocument.test.ts +47 -47
  78. package/src/bridge/printDocument.ts +75 -75
  79. package/src/bridge/pureRender/adapters.test.ts +144 -144
  80. package/src/bridge/pureRender/adapters.ts +175 -175
  81. package/src/bridge/pureRender/assets.test.ts +44 -44
  82. package/src/bridge/pureRender/base.css +76 -76
  83. package/src/bridge/pureRender/compiler.test.ts +279 -279
  84. package/src/bridge/pureRender/compiler.ts +660 -660
  85. package/src/bridge/pureRender/document.test.ts +283 -283
  86. package/src/bridge/pureRender/document.ts +35 -35
  87. package/src/bridge/pureRender/extraction.test.ts +432 -432
  88. package/src/bridge/pureRender/extraction.ts +1023 -1023
  89. package/src/bridge/pureRender/flow.css +3 -3
  90. package/src/bridge/pureRender/index.ts +66 -66
  91. package/src/bridge/pureRender/normalize.test.ts +442 -442
  92. package/src/bridge/pureRender/normalize.ts +682 -682
  93. package/src/bridge/pureRender/presets.ts +365 -365
  94. package/src/bridge/pureRender/profiles/book.css +19 -19
  95. package/src/bridge/pureRender/profiles/manuscript.css +11 -11
  96. package/src/bridge/pureRender/profiles/writer.css +10 -10
  97. package/src/bridge/pureRender/reset.css +5 -5
  98. package/src/bridge/pureRender/samples.ts +94 -94
  99. package/src/bridge/pureRender/styles.ts +164 -164
  100. package/src/bridge/pureRender/theme.test.ts +53 -53
  101. package/src/bridge/pureRender/theme.ts +258 -258
  102. package/src/bridge/pureRender/tokens/default.css +36 -36
  103. package/src/bridge/pureRender/tokens/default.json +32 -32
  104. package/src/bridge/pureRender/types.ts +264 -264
  105. package/src/bridge/pureRender/visualLayoutInspection.test.ts +57 -57
  106. package/src/bridge/pureRender/visualLayoutInspection.ts +161 -161
  107. package/src/bridge/react/useDebouncedEffect.ts +21 -21
  108. package/src/bridge/react/useIpc.tsx +75 -75
  109. package/src/bridge/react/usePlatformAgentRunLiveState.tsx +78 -78
  110. package/src/bridge/react/usePlatformAgentSessionDrive.test.tsx +134 -0
  111. package/src/bridge/react/usePlatformAgentSessionDrive.tsx +749 -729
  112. package/src/bridge/react/usePlatformAgentSessions.tsx +60 -60
  113. package/src/bridge/react/usePlatformAgentTools.tsx +82 -82
  114. package/src/bridge/react/usePlatformAppManifest.tsx +32 -32
  115. package/src/bridge/react/usePlatformBridge.tsx +56 -56
  116. package/src/bridge/react/usePlatformDeepLink.tsx +57 -57
  117. package/src/bridge/react/usePlatformFileBinaryDataUrl.tsx +54 -54
  118. package/src/bridge/react/usePlatformFilePreview.tsx +92 -92
  119. package/src/bridge/react/usePlatformPreferences.tsx +77 -77
  120. package/src/bridge/react/usePlatformThemeDocumentAttrs.ts +35 -35
  121. package/src/bridge/react/usePlatformThemeFromBridge.tsx +16 -16
  122. package/src/bridge/react/usePlatformViewportResource.test.tsx +106 -106
  123. package/src/bridge/react/usePlatformViewportResource.tsx +72 -72
  124. package/src/bridge/react/useScheduledTask.tsx +59 -59
  125. package/src/bridge/render.d.mts +31 -31
  126. package/src/bridge/render.mjs +62 -62
  127. package/src/bridge/render.ts +8 -8
  128. package/src/bridge/screenAnnotation.test.ts +103 -103
  129. package/src/bridge/screenAnnotation.ts +269 -269
  130. package/src/bridge/theme.d.mts +3 -3
  131. package/src/bridge/theme.mjs +9 -9
  132. package/src/bridge/types.ts +447 -439
  133. package/src/bridge/vision.d.mts +22 -0
  134. package/src/bridge/vision.mjs +20 -0
  135. package/src/bridge/watch.d.mts +9 -9
  136. package/src/bridge/watch.mjs +34 -34
  137. package/src/bridge/watch.ts +1 -1
  138. package/src/bridge/window.d.mts +44 -44
  139. package/src/bridge/window.mjs +33 -33
  140. package/src/chrome/index.ts +1 -1
  141. package/src/commitments/commitments.test.ts +201 -0
  142. package/src/commitments/commitments.ts +358 -0
  143. package/src/components/accessibility/AccessibilityReviewDialog.test.tsx +104 -104
  144. package/src/components/accessibility/AccessibilityReviewDialog.tsx +350 -350
  145. package/src/components/accessibility/accessibilityReview.test.ts +101 -101
  146. package/src/components/accessibility/accessibilityReview.ts +639 -639
  147. package/src/components/accessibility/index.ts +16 -16
  148. package/src/components/agent-feedback/ScreenAnnotationAgentDialog.tsx +509 -509
  149. package/src/components/agent-feedback/index.ts +5 -5
  150. package/src/components/agents/AgentComposer.tsx +135 -34
  151. package/src/components/agents/AgentContextUsageBar.tsx +127 -127
  152. package/src/components/agents/AgentDrawerPanel.test.tsx +361 -0
  153. package/src/components/agents/AgentDrawerPanel.tsx +122 -82
  154. package/src/components/agents/AgentFollowUpList.tsx +56 -0
  155. package/src/components/agents/AgentMarkdown.tsx +12 -12
  156. package/src/components/agents/AgentMessageBubble.tsx +171 -82
  157. package/src/components/agents/AgentMessageList.tsx +50 -47
  158. package/src/components/agents/AgentModelMenu.tsx +59 -55
  159. package/src/components/agents/AgentQuestionPromptList.tsx +284 -0
  160. package/src/components/agents/AgentThinkingBlock.tsx +66 -66
  161. package/src/components/agents/AgentToolApprovalActions.tsx +65 -65
  162. package/src/components/agents/AgentToolCallCard.tsx +13 -8
  163. package/src/components/agents/AgentToolPendingList.tsx +39 -39
  164. package/src/components/agents/AgentToolPendingReview.tsx +118 -118
  165. package/src/components/agents/agentPanelStyles.ts +150 -79
  166. package/src/components/agents/agentToolDisplay.ts +87 -0
  167. package/src/components/agents/agentTypes.ts +139 -96
  168. package/src/components/agents/formatToolCallArguments.test.ts +16 -16
  169. package/src/components/agents/formatToolCallArguments.ts +9 -9
  170. package/src/components/agents/index.ts +40 -40
  171. package/src/components/assets/AssetLibraryDialog.tsx +5 -5
  172. package/src/components/assets/asset-library/AssetLibraryDialog.tsx +43 -43
  173. package/src/components/assets/asset-library/AssetLibraryWorkspace.tsx +54 -54
  174. package/src/components/assets/asset-library/detail/AssetLibraryDetailActions.tsx +68 -68
  175. package/src/components/assets/asset-library/detail/AssetLibraryDetailHeader.tsx +56 -56
  176. package/src/components/assets/asset-library/detail/AssetLibraryDetailPane.tsx +90 -90
  177. package/src/components/assets/asset-library/detail/AssetLibraryDetailPreview.tsx +67 -67
  178. package/src/components/assets/asset-library/detail/AssetLibraryInlinePreview.tsx +87 -87
  179. package/src/components/assets/asset-library/detail/AssetLibraryInlineSourceField.tsx +29 -29
  180. package/src/components/assets/asset-library/detail/AssetLibraryMetadataFields.tsx +34 -34
  181. package/src/components/assets/asset-library/detail/AssetLibraryUsagePanel.tsx +46 -46
  182. package/src/components/assets/asset-library/detail/AssetLibraryVersionsPanel.tsx +145 -145
  183. package/src/components/assets/asset-library/helpers/assetKind.ts +74 -74
  184. package/src/components/assets/asset-library/helpers.ts +41 -41
  185. package/src/components/assets/asset-library/hooks/useAssetDetailDraft.ts +81 -81
  186. package/src/components/assets/asset-library/hooks/useAssetLibraryDialog.ts +233 -233
  187. package/src/components/assets/asset-library/hooks/useAssetLibraryMutations.ts +266 -266
  188. package/src/components/assets/asset-library/hooks/useAssetLibrarySelectionSync.ts +24 -24
  189. package/src/components/assets/asset-library/hooks/useAssetLibraryVersions.ts +145 -145
  190. package/src/components/assets/asset-library/hooks/useInlineAssetPreview.ts +44 -44
  191. package/src/components/assets/asset-library/index.ts +19 -19
  192. package/src/components/assets/asset-library/layout/assetLibraryLayout.ts +201 -201
  193. package/src/components/assets/asset-library/shared/fieldStyles.ts +62 -62
  194. package/src/components/assets/asset-library/sidebar/AssetLibraryFilterPills.tsx +89 -89
  195. package/src/components/assets/asset-library/sidebar/AssetLibraryList.tsx +91 -91
  196. package/src/components/assets/asset-library/sidebar/AssetLibraryListRow.tsx +99 -99
  197. package/src/components/assets/asset-library/sidebar/AssetLibraryListStatus.tsx +24 -24
  198. package/src/components/assets/asset-library/sidebar/AssetLibrarySidebar.tsx +48 -48
  199. package/src/components/assets/asset-library/sidebar/AssetLibrarySidebarActions.tsx +38 -38
  200. package/src/components/assets/asset-library/sidebar/AssetLibrarySidebarToolbar.tsx +78 -78
  201. package/src/components/assets/asset-library/sidebar/AssetListThumbnail.tsx +86 -86
  202. package/src/components/assets/asset-library/types.ts +128 -128
  203. package/src/components/assets/asset-library/utils/assetLibraryUtils.ts +181 -181
  204. package/src/components/assets/asset-library/utils/pathBasename.ts +5 -5
  205. package/src/components/assets/asset-library/utils/sanitizeUploadFileName.ts +7 -7
  206. package/src/components/assets/asset-library/utils/uploadCollectionAsset.ts +52 -52
  207. package/src/components/chrome/OverlayActionCapsule.test.tsx +82 -82
  208. package/src/components/chrome/OverlayActionCapsule.tsx +90 -90
  209. package/src/components/chrome/PanelTabStrip.tsx +113 -113
  210. package/src/components/chrome/PlatformIcon.tsx +27 -27
  211. package/src/components/chrome/PureAppWordmark.tsx +94 -89
  212. package/src/components/chrome/ShellWindowControls.tsx +58 -51
  213. package/src/components/chrome/ThemeModeButton.tsx +16 -16
  214. package/src/components/chrome/Titlebar.tsx +79 -79
  215. package/src/components/chrome/WorkspaceTabStrip.tsx +321 -300
  216. package/src/components/chrome/index.ts +31 -31
  217. package/src/components/chrome/workspaceTabTypes.ts +29 -29
  218. package/src/components/common/buttons/Button.tsx +241 -241
  219. package/src/components/common/buttons/ChoiceChip.tsx +73 -73
  220. package/src/components/common/buttons/CleanButton.tsx +34 -34
  221. package/src/components/common/buttons/IconButton.tsx +89 -89
  222. package/src/components/common/buttons/QuietAction.tsx +29 -29
  223. package/src/components/common/buttons/SegmentedControl.tsx +67 -67
  224. package/src/components/common/buttons/TextActionButton.tsx +55 -55
  225. package/src/components/common/buttons/TextLink.tsx +38 -38
  226. package/src/components/common/canvas/CanvasElementFrame.test.tsx +79 -79
  227. package/src/components/common/canvas/CanvasElementFrame.tsx +182 -182
  228. package/src/components/common/canvas/canvasGeometry.test.ts +66 -66
  229. package/src/components/common/canvas/canvasGeometry.ts +133 -133
  230. package/src/components/common/canvas/index.ts +27 -27
  231. package/src/components/common/canvas/useCanvasDragResize.test.tsx +152 -152
  232. package/src/components/common/canvas/useCanvasDragResize.ts +161 -161
  233. package/src/components/common/cards/OpenReviewCard.tsx +209 -0
  234. package/src/components/common/cards/index.ts +5 -0
  235. package/src/components/common/chat/ChatAssistantMessage.tsx +81 -81
  236. package/src/components/common/chat/ChatBox.test.tsx +61 -0
  237. package/src/components/common/chat/ChatBox.tsx +193 -189
  238. package/src/components/common/chat/ChatMarkdown.tsx +109 -109
  239. package/src/components/common/chat/ChatModelMenu.tsx +290 -258
  240. package/src/components/common/chat/ChatStatusRow.tsx +24 -24
  241. package/src/components/common/chat/ChatThinkingIndicator.tsx +54 -54
  242. package/src/components/common/chat/ChatThread.tsx +59 -59
  243. package/src/components/common/chat/ChatToolRow.tsx +147 -141
  244. package/src/components/common/chat/ChatUserBubble.tsx +45 -45
  245. package/src/components/common/chat/chatUtils.ts +7 -7
  246. package/src/components/common/chat/index.ts +24 -24
  247. package/src/components/common/connections/ConnectionSetup.tsx +534 -529
  248. package/src/components/common/connections/index.ts +26 -26
  249. package/src/components/common/containers/AppFrame.test.tsx +87 -41
  250. package/src/components/common/containers/AppFrame.tsx +66 -65
  251. package/src/components/common/containers/AppHeader.tsx +60 -60
  252. package/src/components/common/containers/AutoFillGrid.tsx +43 -37
  253. package/src/components/common/containers/Collapsible.tsx +43 -43
  254. package/src/components/common/containers/CollapsibleGrid.tsx +185 -174
  255. package/src/components/common/containers/MotionScope.tsx +32 -32
  256. package/src/components/common/containers/PageHeader.tsx +35 -35
  257. package/src/components/common/containers/PanelToolbarHeader.tsx +114 -113
  258. package/src/components/common/containers/QuietDisclosure.tsx +91 -91
  259. package/src/components/common/containers/QuietSurface.tsx +40 -41
  260. package/src/components/common/containers/ScrollPanel.tsx +33 -33
  261. package/src/components/common/containers/StatusBar.tsx +42 -42
  262. package/src/components/common/containers/SurfacePanel.tsx +66 -66
  263. package/src/components/common/containers/ToolbarStrip.tsx +80 -80
  264. package/src/components/common/containers/flex.ts +117 -117
  265. package/src/components/common/containers/useOpacityPresence.ts +80 -0
  266. package/src/components/common/containers/useOpenTransition.ts +33 -33
  267. package/src/components/common/context/ContextSelector.tsx +277 -269
  268. package/src/components/common/context/index.ts +7 -7
  269. package/src/components/common/desk/ActionReader.tsx +270 -270
  270. package/src/components/common/desk/ActivityLedger.tsx +143 -143
  271. package/src/components/common/desk/CreationDesk.tsx +139 -139
  272. package/src/components/common/desk/DailyBrief.tsx +160 -160
  273. package/src/components/common/desk/DeskCard.tsx +157 -157
  274. package/src/components/common/desk/index.ts +30 -30
  275. package/src/components/common/dropdown/ContextMenu.tsx +87 -87
  276. package/src/components/common/dropdown/MenuButtonDropdown.tsx +121 -121
  277. package/src/components/common/dropdown/MenuDropdown.tsx +63 -63
  278. package/src/components/common/dropdown/MenuDropdownEntry.tsx +51 -51
  279. package/src/components/common/dropdown/MenuDropdownItem.tsx +82 -82
  280. package/src/components/common/dropdown/MenuDropdownSubmenu.tsx +145 -145
  281. package/src/components/common/dropdown/MenuPanel.tsx +75 -69
  282. package/src/components/common/dropdown/MenuPortal.tsx +164 -162
  283. package/src/components/common/dropdown/MenuPortalLayer.tsx +6 -6
  284. package/src/components/common/dropdown/SelectMenu.tsx +246 -243
  285. package/src/components/common/dropdown/SelectMenuControl.tsx +23 -23
  286. package/src/components/common/dropdown/SelectMenuOptions.tsx +60 -38
  287. package/src/components/common/dropdown/menuPortalConstants.ts +11 -11
  288. package/src/components/common/dropdown/menuTypes.ts +71 -71
  289. package/src/components/common/dropdown/menuViewportPosition.test.ts +139 -139
  290. package/src/components/common/dropdown/menuViewportPosition.ts +122 -122
  291. package/src/components/common/dropdown/selectMenuLayout.test.ts +42 -42
  292. package/src/components/common/dropdown/selectMenuLayout.ts +123 -123
  293. package/src/components/common/dropdown/useMenuAnchorPosition.ts +109 -109
  294. package/src/components/common/dropdown/useSelectMenuAnchor.ts +30 -30
  295. package/src/components/common/evidence/StructuredEvidenceView.test.tsx +77 -77
  296. package/src/components/common/evidence/StructuredEvidenceView.tsx +312 -312
  297. package/src/components/common/evidence/index.ts +13 -13
  298. package/src/components/common/feedback/Badge.tsx +35 -33
  299. package/src/components/common/feedback/CapabilityPills.tsx +36 -36
  300. package/src/components/common/feedback/EmptyState.tsx +166 -132
  301. package/src/components/common/feedback/InfoHint.tsx +67 -67
  302. package/src/components/common/feedback/InlineBanner.tsx +82 -82
  303. package/src/components/common/feedback/PlatformChip.tsx +104 -104
  304. package/src/components/common/feedback/QuietPill.tsx +75 -75
  305. package/src/components/common/feedback/WorkProgressPanel.tsx +156 -156
  306. package/src/components/common/feedback/index.ts +33 -33
  307. package/src/components/common/files/FileTable.tsx +225 -0
  308. package/src/components/common/inputs/BareInput.tsx +31 -31
  309. package/src/components/common/inputs/BareTextarea.tsx +10 -10
  310. package/src/components/common/inputs/Checkbox.tsx +13 -13
  311. package/src/components/common/inputs/EditableSecretField.tsx +292 -0
  312. package/src/components/common/inputs/FieldControlShell.tsx +49 -49
  313. package/src/components/common/inputs/FormField.tsx +40 -40
  314. package/src/components/common/inputs/HybridSearchField.tsx +295 -280
  315. package/src/components/common/inputs/InlineComposer.tsx +197 -197
  316. package/src/components/common/inputs/PaletteCirclePicker.tsx +26 -26
  317. package/src/components/common/inputs/PaletteDropdown.tsx +418 -413
  318. package/src/components/common/inputs/Radio.tsx +19 -19
  319. package/src/components/common/inputs/SearchField.tsx +128 -128
  320. package/src/components/common/inputs/SelectField.tsx +170 -169
  321. package/src/components/common/inputs/SurfacePalettePicker.tsx +54 -54
  322. package/src/components/common/inputs/TextAreaField.tsx +22 -22
  323. package/src/components/common/inputs/TextField.tsx +51 -51
  324. package/src/components/common/inputs/ToggleSwitch.tsx +110 -110
  325. package/src/components/common/inputs/WorkspacePicker.tsx +349 -349
  326. package/src/components/common/inputs/fieldStyles.ts +141 -137
  327. package/src/components/common/layout/PanelGroup.tsx +485 -479
  328. package/src/components/common/layout/index.ts +31 -31
  329. package/src/components/common/layout/panelLayoutConstants.ts +7 -7
  330. package/src/components/common/layout/panelLayoutPersistence.ts +35 -35
  331. package/src/components/common/layout/panelLayoutState.test.ts +38 -38
  332. package/src/components/common/layout/panelLayoutState.ts +174 -174
  333. package/src/components/common/layout/panelLayoutTypes.ts +19 -19
  334. package/src/components/common/layout/tabs/Tabs.tsx +136 -136
  335. package/src/components/common/lists/listRowStyles.ts +32 -32
  336. package/src/components/common/lists/quiet-ledger/QuietActivityList.tsx +64 -64
  337. package/src/components/common/lists/quiet-ledger/QuietLedgerRow.tsx +119 -119
  338. package/src/components/common/lists/quiet-ledger/index.ts +9 -9
  339. package/src/components/common/lists/reorderable/DragHandle.tsx +65 -65
  340. package/src/components/common/lists/reorderable/ReorderableList.tsx +280 -280
  341. package/src/components/common/lists/reorderable/ReorderableListRow.tsx +102 -102
  342. package/src/components/common/lists/reorderable/ReorderableSections.tsx +344 -344
  343. package/src/components/common/lists/reorderable/ReorderableSectionsDemo.tsx +94 -94
  344. package/src/components/common/lists/reorderable/index.ts +15 -15
  345. package/src/components/common/lists/reorderable/reorderableUtils.test.ts +28 -28
  346. package/src/components/common/lists/reorderable/reorderableUtils.ts +23 -23
  347. package/src/components/common/lists/reorderable/types.ts +40 -40
  348. package/src/components/common/lists/reorderable/useReorderableDragState.ts +49 -49
  349. package/src/components/common/media/ImageReferencePicker.tsx +242 -242
  350. package/src/components/common/menubar/MenuBar.tsx +78 -78
  351. package/src/components/common/menubar/MenuBarTrigger.tsx +70 -70
  352. package/src/components/common/narrative/NarrativeMention.tsx +74 -74
  353. package/src/components/common/navigation/NavigationCardRow.tsx +98 -0
  354. package/src/components/common/navigation/PathBreadcrumbs.tsx +78 -78
  355. package/src/components/common/navigation/UnderlineTabs.tsx +83 -83
  356. package/src/components/common/navigation/index.ts +15 -0
  357. package/src/components/common/overlays/InstallAppPromptDialog.tsx +59 -59
  358. package/src/components/common/overlays/Modal.tsx +292 -285
  359. package/src/components/common/overlays/ModalChromeHeader.tsx +105 -105
  360. package/src/components/common/overlays/ObjectActionStrip.tsx +80 -80
  361. package/src/components/common/people/AutoUpdateReviewList.tsx +182 -182
  362. package/src/components/common/people/EntityList.tsx +122 -122
  363. package/src/components/common/people/EntityPortrait.tsx +64 -64
  364. package/src/components/common/people/LinkedDossierList.tsx +99 -99
  365. package/src/components/common/people/OpportunityList.tsx +94 -94
  366. package/src/components/common/people/PeopleSourceList.tsx +145 -145
  367. package/src/components/common/people/RelationshipDossier.tsx +168 -168
  368. package/src/components/common/people/RelationshipMap.tsx +362 -362
  369. package/src/components/common/people/index.ts +40 -40
  370. package/src/components/common/preview/FileAudioPreview.tsx +89 -89
  371. package/src/components/common/preview/FileImagePreview.tsx +88 -88
  372. package/src/components/common/preview/FilePdfPreview.tsx +87 -87
  373. package/src/components/common/preview/FileTextPreview.tsx +96 -96
  374. package/src/components/common/preview/FileVideoPreview.tsx +87 -87
  375. package/src/components/common/preview/PlatformFilePreview.tsx +166 -166
  376. package/src/components/common/preview/previewLayout.ts +27 -27
  377. package/src/components/common/render/Each.tsx +42 -42
  378. package/src/components/common/research/EvidenceDossier.tsx +904 -894
  379. package/src/components/common/research/index.ts +7 -7
  380. package/src/components/common/tiles/CatalogCard.tsx +116 -116
  381. package/src/components/common/tiles/Tile.tsx +45 -45
  382. package/src/components/common/tiles/TileGrid.tsx +19 -13
  383. package/src/components/common/typography/Heading.tsx +27 -27
  384. package/src/components/common/typography/Kicker.tsx +36 -30
  385. package/src/components/common/typography/Text.tsx +80 -80
  386. package/src/components/credentials/CredentialsPanel.tsx +236 -169
  387. package/src/components/credentials/credentialProviderIcon.tsx +79 -0
  388. package/src/components/credentials/credentialsTypes.ts +14 -14
  389. package/src/components/credentials/lobeIcons.d.ts +4 -0
  390. package/src/components/data/DataChart.tsx +913 -913
  391. package/src/components/data/dataTable.ts +99 -99
  392. package/src/components/editor/EditorCommentPromptDialog.tsx +124 -124
  393. package/src/components/editor/EditorLinkPromptDialog.tsx +65 -65
  394. package/src/components/print-design/PrintDesignPanel.test.tsx +1446 -1446
  395. package/src/components/print-design/PrintDesignPanel.tsx +3045 -3043
  396. package/src/components/print-design/index.ts +9 -9
  397. package/src/components/proofing/PagedProofDialog.tsx +453 -453
  398. package/src/components/proofing/index.ts +4 -4
  399. package/src/editor/DocumentEditor.tsx +28 -28
  400. package/src/editor/EditorViewModeToggle.tsx +38 -35
  401. package/src/editor/index.ts +98 -97
  402. package/src/editor/toolbarOverlays.ts +8 -8
  403. package/src/index.ts +231 -209
  404. package/src/theme/ThemeProvider.tsx +115 -113
  405. package/src/theme/appAccents.ts +115 -87
  406. package/src/theme/buildThemeBridgePayload.ts +23 -23
  407. package/src/theme/composePlatformTheme.test.ts +47 -30
  408. package/src/theme/composePlatformTheme.ts +23 -23
  409. package/src/theme/platformFont.d.mts +7 -7
  410. package/src/theme/platformFont.mjs +20 -20
  411. package/src/theme/platformFont.ts +6 -6
  412. package/src/theme/reportsShellChromeSelectors.ts +136 -136
  413. package/src/theme/styled.d.ts +5 -5
  414. package/src/theme/surfacePalettes.ts +179 -178
  415. package/src/theme/surfaceRoleSelectors.ts +113 -113
  416. package/src/theme/themeVars.ts +13 -13
  417. package/src/theme/themes/dark.ts +59 -59
  418. package/src/theme/themes/light.ts +60 -60
  419. package/src/theme/themes/palette.ts +44 -44
  420. package/src/theme/themes/shared.ts +68 -68
  421. package/src/theme/tokens.ts +114 -114
  422. package/src/theme/utils/GlobalStyles.ts +88 -88
  423. package/src/theme/utils/appFrameDocumentStyles.d.mts +5 -5
  424. package/src/theme/utils/appFrameDocumentStyles.mjs +89 -89
  425. package/src/theme/utils/appFrameDocumentStyles.ts +5 -5
  426. package/src/theme/utils/applyTheme.test.ts +19 -0
  427. package/src/theme/utils/applyTheme.ts +59 -50
  428. package/src/theme/utils/cssVariables.ts +49 -49
  429. package/src/theme/utils/useInjectThemeIntoIframe.ts +40 -40
  430. package/src/utils/extensionIconMap.ts +123 -123
  431. package/src/utils/generalUtils.ts +157 -157
  432. package/src/writing/DraftAssistantDialog.tsx +279 -279
  433. package/src/writing/WritingStyleManager.tsx +416 -416
  434. package/src/writing/condenseWritingStyle.ts +103 -103
  435. package/src/writing/draftTextWithAgent.ts +134 -134
  436. package/src/writing/index.ts +39 -39
  437. package/src/writing/styleStore.ts +32 -32
  438. package/src/writing/writingStyle.test.ts +122 -122
  439. package/src/writing/writingStyle.ts +217 -217
@@ -1,729 +1,749 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
- import {
3
- AgentRunEventType,
4
- createIdleLiveTurn,
5
- isComposerEnabled,
6
- mapAgentMessages,
7
- mapApprovalPendingToolCalls,
8
- mapRunState,
9
- mergeUsageTurn,
10
- reduceAgentLiveTurn,
11
- withContextWindowUsage,
12
- type PlatformAgentRunEventPayload,
13
- } from '../../agents/runtime/index.js'
14
- import type {
15
- AgentLiveTurn,
16
- AgentUiMessage,
17
- AgentUiRunState,
18
- AgentUiRunUsage,
19
- AgentUiToolCall,
20
- } from '../../components/agents/agentTypes.js'
21
- import type {
22
- PlatformAgentLlmMenuOption,
23
- PlatformAgentRunSnapshot,
24
- PlatformAgentSessionConfigPatch,
25
- PlatformAgentSessionRecord,
26
- PlatformAgentSessionScope,
27
- PlatformAgentSessionSummary,
28
- PlatformAgentSessionToolPolicy,
29
- } from '../agentTypes.js'
30
- import { isAgentAutoModelId, DEFAULT_AGENT_HIGH_LEVEL_MODEL_ID } from '../agentModelTiers.js'
31
- import {
32
- getPlatformPreferences,
33
- patchPlatformPreferences,
34
- } from '../preferences.mjs'
35
- import {
36
- advanceAgentSessionPending,
37
- approveAgentSessionTools,
38
- createAgentSession,
39
- deleteAgentSession,
40
- interruptAgentSession,
41
- listAgentSessions,
42
- onAgentRunEvent,
43
- readAgentLlmMenuOptions,
44
- readAgentSession,
45
- rejectAgentSessionTools,
46
- sendAgentSessionMessage,
47
- updateAgentSession,
48
- } from '../agents.mjs'
49
-
50
- const DEFAULT_SESSION_TITLE = 'New chat'
51
-
52
- export interface UsePlatformAgentSessionDriveOptions {
53
- /** App slug that owns app-scoped sessions and tool routing. */
54
- appSlug: string
55
- scope?: PlatformAgentSessionScope
56
- enabled?: boolean
57
- /**
58
- * Bind to one specific session (e.g. an ephemeral thread that lives only while
59
- * a modal is open). When set, the hook drives exactly this session and skips
60
- * list auto-load and auto-create — the app owns its create/delete lifecycle.
61
- */
62
- sessionId?: string
63
- /** Persisted to session metadata so the shell can restore the bound tab. */
64
- restoreTabId?: string
65
- /** Create a fresh session when the scope has none. Ignored when `sessionId` is set. Defaults to true. */
66
- autoCreate?: boolean
67
- rejectReason?: string
68
- }
69
-
70
- export interface UsePlatformAgentSessionDrive {
71
- scope: PlatformAgentSessionScope
72
- setScope: (scope: PlatformAgentSessionScope) => void
73
- sessionRecord: PlatformAgentSessionRecord | null
74
- sessionSummaries: PlatformAgentSessionSummary[]
75
- sessionId: string | null
76
- messages: AgentUiMessage[]
77
- liveTurn: AgentLiveTurn
78
- pendingToolCalls: AgentUiToolCall[]
79
- runState: AgentUiRunState | null
80
- busy: boolean
81
- error: string | null
82
- composerValue: string
83
- setComposerValue: (value: string) => void
84
- modelId: string
85
- setModelId: (modelId: string) => Promise<void>
86
- modelOptions: PlatformAgentLlmMenuOption[]
87
- modelUnavailableReason: string | null
88
- usage: AgentUiRunUsage | null
89
- canSend: boolean
90
- canInterrupt: boolean
91
- interruptRun: (reason?: string) => Promise<void>
92
- /** Send the composer value, or an explicit message (programmatic). Returns the final snapshot. */
93
- sendMessage: (message?: string) => Promise<PlatformAgentRunSnapshot | null>
94
- approveTools: (toolCallIds?: readonly string[]) => Promise<void>
95
- approveToolAlwaysForSession: (
96
- qualifiedName: string,
97
- toolCallId: string,
98
- ) => Promise<void>
99
- rejectTools: (toolCallIds?: readonly string[]) => Promise<void>
100
- selectSession: (sessionId: string) => Promise<void>
101
- createNewSession: () => Promise<void>
102
- deleteSession: () => Promise<void>
103
- renameSession: (title: string) => Promise<void>
104
- allowedTargetApps: string[]
105
- setAllowedTargetApps: (slugs: readonly string[]) => Promise<void>
106
- setToolApprovalOverride: (
107
- qualifiedName: string,
108
- requiresApproval: boolean,
109
- ) => Promise<void>
110
- refresh: () => Promise<void>
111
- }
112
-
113
- interface DriveResult {
114
- session: PlatformAgentSessionRecord
115
- snapshot: PlatformAgentRunSnapshot
116
- effectiveToolPolicy?: PlatformAgentSessionToolPolicy
117
- manualPendingToolCalls: AgentUiToolCall[]
118
- }
119
-
120
- /** Display snapshot from a persisted session record (before any live run this turn). */
121
- function recordSnapshot(
122
- record: PlatformAgentSessionRecord | null,
123
- ): PlatformAgentRunSnapshot | null {
124
- if (!record) return null
125
- return {
126
- runId: record.runId ?? '',
127
- state: record.snapshot.state,
128
- turn: record.snapshot.turn,
129
- messages: record.snapshot.messages,
130
- error: record.snapshot.error,
131
- interruptedReason: record.snapshot.interruptedReason,
132
- }
133
- }
134
-
135
- function mergeScopeDefaultPatch(
136
- base: PlatformAgentSessionConfigPatch | undefined,
137
- patch: PlatformAgentSessionConfigPatch,
138
- ): PlatformAgentSessionConfigPatch {
139
- const toolPolicy =
140
- patch.toolPolicy || base?.toolPolicy
141
- ? {
142
- ...base?.toolPolicy,
143
- ...patch.toolPolicy,
144
- approvalOverrides: {
145
- ...base?.toolPolicy?.approvalOverrides,
146
- ...patch.toolPolicy?.approvalOverrides,
147
- },
148
- }
149
- : undefined
150
- return { ...base, ...patch, ...(toolPolicy ? { toolPolicy } : {}) }
151
- }
152
-
153
- export function usePlatformAgentSessionDrive({
154
- appSlug,
155
- scope: initialScope = 'app',
156
- enabled = true,
157
- sessionId: boundSessionId,
158
- restoreTabId,
159
- autoCreate = true,
160
- rejectReason,
161
- }: UsePlatformAgentSessionDriveOptions): UsePlatformAgentSessionDrive {
162
- const [scope, setScope] = useState<PlatformAgentSessionScope>(initialScope)
163
- const [sessionRecord, setSessionRecord] =
164
- useState<PlatformAgentSessionRecord | null>(null)
165
- const [sessionSummaries, setSessionSummaries] = useState<
166
- PlatformAgentSessionSummary[]
167
- >([])
168
- const [snapshot, setSnapshot] = useState<PlatformAgentRunSnapshot | null>(
169
- null,
170
- )
171
- const [policy, setPolicy] = useState<
172
- PlatformAgentSessionToolPolicy | undefined
173
- >(undefined)
174
- const [drivePendingToolCalls, setDrivePendingToolCalls] = useState<
175
- AgentUiToolCall[] | undefined
176
- >(undefined)
177
- const [liveTurn, setLiveTurn] = useState<AgentLiveTurn>(createIdleLiveTurn)
178
- const [busy, setBusy] = useState(false)
179
- const [error, setError] = useState<string | null>(null)
180
- const [composerValue, setComposerValue] = useState('')
181
- const [optimisticModelId, setOptimisticModelId] = useState<string | null>(
182
- null,
183
- )
184
- const [modelOptions, setModelOptions] = useState<
185
- PlatformAgentLlmMenuOption[]
186
- >([])
187
-
188
- // one active run per hook instance. Latches runId from the first
189
- // forwarded event so first-turn streaming works before the RPC resolves.
190
- // Upgrade path: thread an explicit runId if one iframe drives many runs at once.
191
- const activeRunIdRef = useRef<string | undefined>(undefined)
192
- const stopRequestedRef = useRef(false)
193
-
194
- const scopeAppSlug = scope === 'app' ? appSlug : undefined
195
-
196
- const sessionQuery = useCallback(
197
- (sessionId: string) => ({ scope, sessionId, appSlug: scopeAppSlug }),
198
- [scope, scopeAppSlug],
199
- )
200
-
201
- const refreshSessionList = useCallback(async () => {
202
- const listed = await listAgentSessions({ scope, appSlug: scopeAppSlug })
203
- setSessionSummaries(listed)
204
- return listed
205
- }, [scope, scopeAppSlug])
206
-
207
- const adoptRecord = useCallback((record: PlatformAgentSessionRecord) => {
208
- setSessionRecord(record)
209
- setSnapshot(null)
210
- setPolicy(undefined)
211
- setDrivePendingToolCalls(undefined)
212
- setLiveTurn(createIdleLiveTurn())
213
- activeRunIdRef.current = record.runId
214
- }, [])
215
-
216
- const applyDriveResult = useCallback((result: DriveResult) => {
217
- setSessionRecord(result.session)
218
- setSnapshot(result.snapshot)
219
- setPolicy(result.effectiveToolPolicy)
220
- setDrivePendingToolCalls(result.manualPendingToolCalls)
221
- activeRunIdRef.current = result.snapshot.runId
222
- setLiveTurn(createIdleLiveTurn())
223
- }, [])
224
-
225
- const settlePersistedPending = useCallback(
226
- async (record: PlatformAgentSessionRecord) => {
227
- if (record.snapshot.state !== 'pending_tools') return
228
- const result = await advanceAgentSessionPending({
229
- session: sessionQuery(record.sessionId),
230
- })
231
- if (result) applyDriveResult(result)
232
- },
233
- [applyDriveResult, sessionQuery],
234
- )
235
-
236
- const loadSession = useCallback(async () => {
237
- // Bound mode: drive exactly the app-owned session, no list/auto-create.
238
- if (boundSessionId) {
239
- const record = await readAgentSession(sessionQuery(boundSessionId))
240
- adoptRecord(record)
241
- await settlePersistedPending(record)
242
- return
243
- }
244
- const listed = await refreshSessionList()
245
- const first = listed[0]
246
- if (first) {
247
- const record = await readAgentSession(sessionQuery(first.sessionId))
248
- adoptRecord(record)
249
- await settlePersistedPending(record)
250
- return
251
- }
252
- if (!autoCreate) {
253
- setSessionRecord(null)
254
- return
255
- }
256
- const created = await createAgentSession({
257
- scope,
258
- appSlug: scopeAppSlug,
259
- title: DEFAULT_SESSION_TITLE,
260
- restoreTabId,
261
- })
262
- adoptRecord(created)
263
- await refreshSessionList()
264
- }, [
265
- adoptRecord,
266
- autoCreate,
267
- boundSessionId,
268
- refreshSessionList,
269
- restoreTabId,
270
- scope,
271
- scopeAppSlug,
272
- sessionQuery,
273
- settlePersistedPending,
274
- ])
275
-
276
- useEffect(() => {
277
- if (!enabled) return
278
- let cancelled = false
279
- void loadSession().catch((cause: unknown) => {
280
- if (!cancelled) {
281
- setError(cause instanceof Error ? cause.message : String(cause))
282
- }
283
- })
284
- return () => {
285
- cancelled = true
286
- }
287
- }, [enabled, loadSession])
288
-
289
- useEffect(() => {
290
- if (!enabled) return
291
- let cancelled = false
292
- void readAgentLlmMenuOptions({})
293
- .then(options => {
294
- if (!cancelled) setModelOptions(options)
295
- })
296
- .catch(() => {
297
- if (!cancelled) setModelOptions([])
298
- })
299
- return () => {
300
- cancelled = true
301
- }
302
- }, [enabled])
303
-
304
- useEffect(() => {
305
- setOptimisticModelId(null)
306
- }, [sessionRecord?.sessionId])
307
-
308
- // Streaming: persistent listener; latches runId from forwarded events.
309
- useEffect(() => {
310
- if (!enabled) return
311
- let live = createIdleLiveTurn()
312
- const unsubscribe = onAgentRunEvent(event => {
313
- const payload = event as PlatformAgentRunEventPayload
314
- const runId = activeRunIdRef.current
315
- if (runId && payload.runId !== runId) return
316
- if (!runId) activeRunIdRef.current = payload.runId
317
-
318
- if (
319
- payload.type === AgentRunEventType.StateChanged &&
320
- 'snapshot' in payload
321
- ) {
322
- setSnapshot({ ...payload.snapshot })
323
- }
324
- if (payload.type === AgentRunEventType.UsageUpdated) {
325
- setSnapshot(current =>
326
- current
327
- ? {
328
- ...current,
329
- usage: mergeUsageTurn(
330
- current.usage,
331
- payload.usage,
332
- payload.estimated,
333
- ),
334
- }
335
- : current,
336
- )
337
- }
338
-
339
- live = reduceAgentLiveTurn(live, payload)
340
- setLiveTurn(live)
341
- })
342
- return unsubscribe
343
- }, [enabled, sessionRecord?.sessionId])
344
-
345
- const refresh = useCallback(async () => {
346
- if (!sessionRecord) return
347
- const record = await readAgentSession(sessionQuery(sessionRecord.sessionId))
348
- setSessionRecord(record)
349
- }, [sessionQuery, sessionRecord])
350
-
351
- const drive = useCallback(
352
- async (
353
- run: () => Promise<DriveResult | null>,
354
- ): Promise<DriveResult | null> => {
355
- if (!enabled || busy) return null
356
- setBusy(true)
357
- setError(null)
358
- try {
359
- const result = await run()
360
- if (!result) return null
361
- applyDriveResult(result)
362
- await refreshSessionList()
363
- return result
364
- } catch (cause) {
365
- if (!stopRequestedRef.current) {
366
- setError(cause instanceof Error ? cause.message : String(cause))
367
- }
368
- setLiveTurn(createIdleLiveTurn())
369
- return null
370
- } finally {
371
- stopRequestedRef.current = false
372
- setBusy(false)
373
- }
374
- },
375
- [applyDriveResult, busy, enabled, refreshSessionList],
376
- )
377
-
378
- const committed = useMemo(
379
- () => snapshot ?? recordSnapshot(sessionRecord),
380
- [sessionRecord, snapshot],
381
- )
382
- const displaySnapshot = useMemo(
383
- () => recordSnapshot(sessionRecord),
384
- [sessionRecord],
385
- )
386
- const threadSnapshot = useMemo(() => {
387
- if (busy && snapshot) return snapshot
388
- return committed
389
- }, [busy, committed, snapshot])
390
- const runState = displaySnapshot ? mapRunState(displaySnapshot.state) : null
391
-
392
- const selectedModelId =
393
- optimisticModelId ?? sessionRecord?.config.modelId ?? 'auto'
394
-
395
- const modelUnavailableReason = useMemo(() => {
396
- if (isAgentAutoModelId(selectedModelId)) return null
397
- if (modelOptions.length === 0) return null
398
- const known = modelOptions.some(option => option.value === selectedModelId)
399
- return known
400
- ? null
401
- : 'This model is not available. Check API keys or local runtime in Settings.'
402
- }, [modelOptions, selectedModelId])
403
-
404
- const toolPolicy =
405
- policy ?? sessionRecord?.config?.toolPolicy ?? undefined
406
-
407
- const pendingToolCalls = useMemo(() => {
408
- if (drivePendingToolCalls !== undefined) return drivePendingToolCalls
409
- return mapApprovalPendingToolCalls(threadSnapshot, toolPolicy)
410
- }, [drivePendingToolCalls, threadSnapshot, toolPolicy])
411
- const messages = useMemo(
412
- () => mapAgentMessages(threadSnapshot, liveTurn),
413
- [liveTurn, threadSnapshot],
414
- )
415
- const canSend =
416
- enabled &&
417
- isComposerEnabled(runState, busy) &&
418
- !modelUnavailableReason &&
419
- composerValue.trim().length > 0
420
-
421
- const canInterrupt = enabled && busy && sessionRecord !== null
422
-
423
- const contextWindowByModelId = useMemo(() => {
424
- const map = new Map<string, number>()
425
- for (const option of modelOptions) {
426
- if (option.contextWindowTokens) {
427
- map.set(option.value, option.contextWindowTokens)
428
- }
429
- }
430
- return map
431
- }, [modelOptions])
432
-
433
- const usage = useMemo<AgentUiRunUsage | null>(() => {
434
- const raw = threadSnapshot?.usage
435
- if (!raw) return null
436
- if (raw.contextWindowTokens) return raw
437
- const modelId =
438
- threadSnapshot?.effectiveModelId ??
439
- (isAgentAutoModelId(selectedModelId)
440
- ? DEFAULT_AGENT_HIGH_LEVEL_MODEL_ID
441
- : selectedModelId)
442
- return (
443
- withContextWindowUsage(raw, contextWindowByModelId.get(modelId)) ?? raw
444
- )
445
- }, [contextWindowByModelId, selectedModelId, threadSnapshot])
446
-
447
- const sendMessage = useCallback(
448
- async (
449
- messageOverride?: string,
450
- ): Promise<PlatformAgentRunSnapshot | null> => {
451
- const message = (messageOverride ?? composerValue).trim()
452
- if (!message || !sessionRecord) return null
453
- // Composer sends respect canSend; programmatic sends only respect busy.
454
- if (messageOverride === undefined && !canSend) return null
455
- const result = await drive(async () => {
456
- const driven = await sendAgentSessionMessage({
457
- session: sessionQuery(sessionRecord.sessionId),
458
- message,
459
- })
460
- if (messageOverride === undefined) setComposerValue('')
461
- return driven
462
- })
463
- return result?.snapshot ?? null
464
- },
465
- [canSend, composerValue, drive, sessionQuery, sessionRecord],
466
- )
467
-
468
- const approveTools = useCallback(
469
- async (toolCallIds?: readonly string[]) => {
470
- if (!sessionRecord || pendingToolCalls.length === 0) return
471
- await drive(async () => {
472
- const driven = await approveAgentSessionTools({
473
- session: sessionQuery(sessionRecord.sessionId),
474
- ...(toolCallIds?.length ? { toolCallIds: [...toolCallIds] } : {}),
475
- })
476
- return driven
477
- })
478
- },
479
- [drive, pendingToolCalls.length, sessionQuery, sessionRecord],
480
- )
481
-
482
- const rejectTools = useCallback(
483
- async (toolCallIds?: readonly string[]) => {
484
- if (!sessionRecord || pendingToolCalls.length === 0) return
485
- await drive(async () =>
486
- rejectAgentSessionTools({
487
- session: sessionQuery(sessionRecord.sessionId),
488
- rejectReason,
489
- ...(toolCallIds?.length ? { toolCallIds: [...toolCallIds] } : {}),
490
- }),
491
- )
492
- },
493
- [drive, pendingToolCalls.length, rejectReason, sessionQuery, sessionRecord],
494
- )
495
-
496
- const interruptRun = useCallback(
497
- async (reason?: string) => {
498
- if (!enabled || !sessionRecord || !canInterrupt) return
499
- stopRequestedRef.current = true
500
- setError(null)
501
- try {
502
- const result = await interruptAgentSession({
503
- session: sessionQuery(sessionRecord.sessionId),
504
- reason,
505
- })
506
- applyDriveResult(result)
507
- await refreshSessionList()
508
- } catch (cause) {
509
- if (!stopRequestedRef.current) {
510
- setError(cause instanceof Error ? cause.message : String(cause))
511
- }
512
- } finally {
513
- stopRequestedRef.current = false
514
- setBusy(false)
515
- }
516
- },
517
- [applyDriveResult, canInterrupt, enabled, refreshSessionList, sessionQuery, sessionRecord],
518
- )
519
-
520
- const selectSession = useCallback(
521
- async (sessionId: string) => {
522
- const record = await readAgentSession(sessionQuery(sessionId))
523
- adoptRecord(record)
524
- setComposerValue('')
525
- setError(null)
526
- await settlePersistedPending(record)
527
- },
528
- [adoptRecord, sessionQuery, settlePersistedPending],
529
- )
530
-
531
- const createNewSession = useCallback(async () => {
532
- const created = await createAgentSession({
533
- scope,
534
- appSlug: scopeAppSlug,
535
- title: DEFAULT_SESSION_TITLE,
536
- restoreTabId,
537
- })
538
- adoptRecord(created)
539
- setComposerValue('')
540
- await refreshSessionList()
541
- }, [adoptRecord, refreshSessionList, restoreTabId, scope, scopeAppSlug])
542
-
543
- const deleteSession = useCallback(async () => {
544
- if (!sessionRecord) return
545
- await deleteAgentSession(sessionQuery(sessionRecord.sessionId))
546
- const listed = await refreshSessionList()
547
- const next = listed[0]
548
- if (next) {
549
- await selectSession(next.sessionId)
550
- return
551
- }
552
- if (autoCreate) await createNewSession()
553
- else setSessionRecord(null)
554
- }, [
555
- autoCreate,
556
- createNewSession,
557
- refreshSessionList,
558
- selectSession,
559
- sessionQuery,
560
- sessionRecord,
561
- ])
562
-
563
- const renameSession = useCallback(
564
- async (title: string) => {
565
- if (!sessionRecord) return
566
- const trimmed = title.trim()
567
- if (!trimmed) return
568
- const updated = await updateAgentSession({
569
- query: sessionQuery(sessionRecord.sessionId),
570
- patch: { metadata: { title: trimmed } },
571
- })
572
- setSessionRecord(updated)
573
- await refreshSessionList()
574
- },
575
- [refreshSessionList, sessionQuery, sessionRecord],
576
- )
577
-
578
- const persistScopeDefault = useCallback(
579
- async (patch: PlatformAgentSessionConfigPatch) => {
580
- try {
581
- const prefs = (await getPlatformPreferences()) as {
582
- agentSessionDefaults?: {
583
- global?: PlatformAgentSessionConfigPatch
584
- apps?: Record<string, PlatformAgentSessionConfigPatch>
585
- }
586
- }
587
- const stored = prefs.agentSessionDefaults ?? {}
588
- if (scope === 'global') {
589
- await patchPlatformPreferences({
590
- agentSessionDefaults: {
591
- ...stored,
592
- global: mergeScopeDefaultPatch(stored.global, patch),
593
- },
594
- })
595
- return
596
- }
597
- if (!scopeAppSlug) return
598
- const apps = { ...(stored.apps ?? {}) }
599
- apps[scopeAppSlug] = mergeScopeDefaultPatch(apps[scopeAppSlug], patch)
600
- await patchPlatformPreferences({
601
- agentSessionDefaults: { ...stored, apps },
602
- })
603
- } catch {
604
- /* scope defaults are best-effort */
605
- }
606
- },
607
- [scope, scopeAppSlug],
608
- )
609
-
610
- const setModelId = useCallback(
611
- async (modelId: string) => {
612
- if (!sessionRecord) return
613
- setOptimisticModelId(modelId)
614
- try {
615
- const updated = await updateAgentSession({
616
- query: sessionQuery(sessionRecord.sessionId),
617
- patch: { config: { modelId } },
618
- })
619
- setSessionRecord(updated)
620
- setOptimisticModelId(null)
621
- await persistScopeDefault({ modelId })
622
- } catch (cause) {
623
- setOptimisticModelId(null)
624
- setError(cause instanceof Error ? cause.message : String(cause))
625
- }
626
- },
627
- [persistScopeDefault, sessionQuery, sessionRecord],
628
- )
629
-
630
- const allowedTargetApps =
631
- sessionRecord?.config.toolPolicy?.allowedTargetApps ?? []
632
-
633
- const setAllowedTargetApps = useCallback(
634
- async (slugs: readonly string[]) => {
635
- if (!sessionRecord) return
636
- const normalized = [
637
- ...new Set(slugs.map(slug => slug.trim()).filter(Boolean)),
638
- ]
639
- const updated = await updateAgentSession({
640
- query: sessionQuery(sessionRecord.sessionId),
641
- patch: { config: { toolPolicy: { allowedTargetApps: normalized } } },
642
- })
643
- setSessionRecord(updated)
644
- await persistScopeDefault({
645
- toolPolicy: { allowedTargetApps: normalized },
646
- })
647
- },
648
- [persistScopeDefault, sessionQuery, sessionRecord],
649
- )
650
-
651
- const setToolApprovalOverride = useCallback(
652
- async (qualifiedName: string, requiresApproval: boolean) => {
653
- if (!sessionRecord) return
654
- const overrides = {
655
- ...sessionRecord.config.toolPolicy?.approvalOverrides,
656
- [qualifiedName]: requiresApproval,
657
- }
658
- const updated = await updateAgentSession({
659
- query: sessionQuery(sessionRecord.sessionId),
660
- patch: { config: { toolPolicy: { approvalOverrides: overrides } } },
661
- })
662
- setSessionRecord(updated)
663
- await persistScopeDefault({
664
- toolPolicy: { approvalOverrides: overrides },
665
- })
666
- },
667
- [persistScopeDefault, sessionQuery, sessionRecord],
668
- )
669
-
670
- const approveToolAlwaysForSession = useCallback(
671
- async (qualifiedName: string, toolCallId: string) => {
672
- if (!sessionRecord) return
673
- await drive(async () => {
674
- const overrides = {
675
- ...sessionRecord.config.toolPolicy?.approvalOverrides,
676
- [qualifiedName]: false,
677
- }
678
- const updated = await updateAgentSession({
679
- query: sessionQuery(sessionRecord.sessionId),
680
- patch: { config: { toolPolicy: { approvalOverrides: overrides } } },
681
- })
682
- await persistScopeDefault({
683
- toolPolicy: { approvalOverrides: overrides },
684
- })
685
- return approveAgentSessionTools({
686
- session: sessionQuery(updated.sessionId),
687
- toolCallIds: [toolCallId],
688
- })
689
- })
690
- },
691
- [drive, persistScopeDefault, sessionQuery, sessionRecord],
692
- )
693
-
694
- return {
695
- scope,
696
- setScope,
697
- sessionRecord,
698
- sessionSummaries,
699
- sessionId: sessionRecord?.sessionId ?? null,
700
- messages,
701
- liveTurn,
702
- pendingToolCalls,
703
- runState,
704
- busy,
705
- error,
706
- composerValue,
707
- setComposerValue,
708
- modelId: selectedModelId,
709
- setModelId,
710
- modelOptions,
711
- modelUnavailableReason,
712
- usage,
713
- canSend,
714
- canInterrupt,
715
- sendMessage,
716
- interruptRun,
717
- approveTools,
718
- approveToolAlwaysForSession,
719
- rejectTools,
720
- selectSession,
721
- createNewSession,
722
- deleteSession,
723
- renameSession,
724
- allowedTargetApps,
725
- setAllowedTargetApps,
726
- setToolApprovalOverride,
727
- refresh,
728
- }
729
- }
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
+ import {
3
+ AgentRunEventType,
4
+ createIdleLiveTurn,
5
+ isComposerEnabled,
6
+ mapAgentMessages,
7
+ mapApprovalPendingToolCalls,
8
+ mapRunState,
9
+ mergeUsageTurn,
10
+ reduceAgentLiveTurn,
11
+ withContextWindowUsage,
12
+ type PlatformAgentRunEventPayload,
13
+ } from '../../agents/runtime/index.js'
14
+ import type {
15
+ AgentLiveTurn,
16
+ AgentUiMessage,
17
+ AgentUiRunState,
18
+ AgentUiRunUsage,
19
+ AgentUiToolCall,
20
+ } from '../../components/agents/agentTypes.js'
21
+ import type {
22
+ PlatformAgentLlmMenuOption,
23
+ PlatformAgentRunSnapshot,
24
+ PlatformAgentSessionConfigPatch,
25
+ PlatformAgentSessionRecord,
26
+ PlatformAgentSessionScope,
27
+ PlatformAgentSessionSummary,
28
+ PlatformAgentSessionToolPolicy,
29
+ } from '../agentTypes.js'
30
+ import { isAgentAutoModelId, DEFAULT_AGENT_HIGH_LEVEL_MODEL_ID } from '../agentModelTiers.js'
31
+ import {
32
+ getPlatformPreferences,
33
+ patchPlatformPreferences,
34
+ } from '../preferences.mjs'
35
+ import {
36
+ advanceAgentSessionPending,
37
+ approveAgentSessionTools,
38
+ createAgentSession,
39
+ deleteAgentSession,
40
+ interruptAgentSession,
41
+ listAgentSessions,
42
+ onAgentRunEvent,
43
+ readAgentLlmMenuOptions,
44
+ readAgentSession,
45
+ rejectAgentSessionTools,
46
+ sendAgentSessionMessage,
47
+ updateAgentSession,
48
+ } from '../agents.mjs'
49
+
50
+ const DEFAULT_SESSION_TITLE = 'New chat'
51
+
52
+ export interface UsePlatformAgentSessionDriveOptions {
53
+ /** App slug that owns app-scoped sessions and tool routing. */
54
+ appSlug: string
55
+ scope?: PlatformAgentSessionScope
56
+ enabled?: boolean
57
+ /**
58
+ * Bind to one specific session (e.g. an ephemeral thread that lives only while
59
+ * a modal is open). When set, the hook drives exactly this session and skips
60
+ * list auto-load and auto-create — the app owns its create/delete lifecycle.
61
+ */
62
+ sessionId?: string
63
+ /** Persisted to session metadata so the shell can restore the bound tab. */
64
+ restoreTabId?: string
65
+ /** Create a fresh session when the scope has none. Ignored when `sessionId` is set. Defaults to true. */
66
+ autoCreate?: boolean
67
+ rejectReason?: string
68
+ }
69
+
70
+ export interface UsePlatformAgentSessionDrive {
71
+ scope: PlatformAgentSessionScope
72
+ setScope: (scope: PlatformAgentSessionScope) => void
73
+ sessionRecord: PlatformAgentSessionRecord | null
74
+ sessionSummaries: PlatformAgentSessionSummary[]
75
+ sessionId: string | null
76
+ messages: AgentUiMessage[]
77
+ liveTurn: AgentLiveTurn
78
+ pendingToolCalls: AgentUiToolCall[]
79
+ runState: AgentUiRunState | null
80
+ busy: boolean
81
+ error: string | null
82
+ composerValue: string
83
+ setComposerValue: (value: string) => void
84
+ modelId: string
85
+ setModelId: (modelId: string) => Promise<void>
86
+ modelOptions: PlatformAgentLlmMenuOption[]
87
+ modelUnavailableReason: string | null
88
+ usage: AgentUiRunUsage | null
89
+ canSend: boolean
90
+ canInterrupt: boolean
91
+ interruptRun: (reason?: string) => Promise<void>
92
+ /** Send the composer value, or an explicit message (programmatic). Returns the final snapshot. */
93
+ sendMessage: (message?: string) => Promise<PlatformAgentRunSnapshot | null>
94
+ approveTools: (toolCallIds?: readonly string[]) => Promise<void>
95
+ approveToolAlwaysForSession: (
96
+ qualifiedName: string,
97
+ toolCallId: string,
98
+ ) => Promise<void>
99
+ rejectTools: (toolCallIds?: readonly string[]) => Promise<void>
100
+ selectSession: (sessionId: string) => Promise<void>
101
+ createNewSession: () => Promise<void>
102
+ deleteSession: () => Promise<void>
103
+ renameSession: (title: string) => Promise<void>
104
+ allowedTargetApps: string[]
105
+ setAllowedTargetApps: (slugs: readonly string[]) => Promise<void>
106
+ setToolApprovalOverride: (
107
+ qualifiedName: string,
108
+ requiresApproval: boolean,
109
+ ) => Promise<void>
110
+ refresh: () => Promise<void>
111
+ }
112
+
113
+ interface DriveResult {
114
+ session: PlatformAgentSessionRecord
115
+ snapshot: PlatformAgentRunSnapshot
116
+ effectiveToolPolicy?: PlatformAgentSessionToolPolicy
117
+ manualPendingToolCalls: AgentUiToolCall[]
118
+ }
119
+
120
+ /** Display snapshot from a persisted session record (before any live run this turn). */
121
+ function recordSnapshot(
122
+ record: PlatformAgentSessionRecord | null,
123
+ ): PlatformAgentRunSnapshot | null {
124
+ if (!record) return null
125
+ return {
126
+ runId: record.runId ?? '',
127
+ state: record.snapshot.state,
128
+ turn: record.snapshot.turn,
129
+ messages: record.snapshot.messages,
130
+ error: record.snapshot.error,
131
+ interruptedReason: record.snapshot.interruptedReason,
132
+ }
133
+ }
134
+
135
+ function mergeScopeDefaultPatch(
136
+ base: PlatformAgentSessionConfigPatch | undefined,
137
+ patch: PlatformAgentSessionConfigPatch,
138
+ ): PlatformAgentSessionConfigPatch {
139
+ const toolPolicy =
140
+ patch.toolPolicy || base?.toolPolicy
141
+ ? {
142
+ ...base?.toolPolicy,
143
+ ...patch.toolPolicy,
144
+ approvalOverrides: {
145
+ ...base?.toolPolicy?.approvalOverrides,
146
+ ...patch.toolPolicy?.approvalOverrides,
147
+ },
148
+ }
149
+ : undefined
150
+ return { ...base, ...patch, ...(toolPolicy ? { toolPolicy } : {}) }
151
+ }
152
+
153
+ export function usePlatformAgentSessionDrive({
154
+ appSlug,
155
+ scope: initialScope = 'app',
156
+ enabled = true,
157
+ sessionId: boundSessionId,
158
+ restoreTabId,
159
+ autoCreate = true,
160
+ rejectReason,
161
+ }: UsePlatformAgentSessionDriveOptions): UsePlatformAgentSessionDrive {
162
+ const [scope, setScope] = useState<PlatformAgentSessionScope>(initialScope)
163
+ const [sessionRecord, setSessionRecord] =
164
+ useState<PlatformAgentSessionRecord | null>(null)
165
+ const [sessionSummaries, setSessionSummaries] = useState<
166
+ PlatformAgentSessionSummary[]
167
+ >([])
168
+ const [snapshot, setSnapshot] = useState<PlatformAgentRunSnapshot | null>(
169
+ null,
170
+ )
171
+ const [policy, setPolicy] = useState<
172
+ PlatformAgentSessionToolPolicy | undefined
173
+ >(undefined)
174
+ const [drivePendingToolCalls, setDrivePendingToolCalls] = useState<
175
+ AgentUiToolCall[] | undefined
176
+ >(undefined)
177
+ const [liveTurn, setLiveTurn] = useState<AgentLiveTurn>(createIdleLiveTurn)
178
+ const [busy, setBusy] = useState(false)
179
+ const [error, setError] = useState<string | null>(null)
180
+ const [composerValue, setComposerValue] = useState('')
181
+ const [optimisticModelId, setOptimisticModelId] = useState<string | null>(
182
+ null,
183
+ )
184
+ const [modelOptions, setModelOptions] = useState<
185
+ PlatformAgentLlmMenuOption[]
186
+ >([])
187
+
188
+ // one active run per hook instance. Latches runId from the first
189
+ // forwarded event so first-turn streaming works before the RPC resolves.
190
+ // Upgrade path: thread an explicit runId if one iframe drives many runs at once.
191
+ const activeRunIdRef = useRef<string | undefined>(undefined)
192
+ const stopRequestedRef = useRef(false)
193
+
194
+ const scopeAppSlug = scope === 'app' ? appSlug : undefined
195
+
196
+ const sessionQuery = useCallback(
197
+ (sessionId: string) => ({ scope, sessionId, appSlug: scopeAppSlug }),
198
+ [scope, scopeAppSlug],
199
+ )
200
+
201
+ const refreshSessionList = useCallback(async () => {
202
+ const listed = await listAgentSessions({ scope, appSlug: scopeAppSlug })
203
+ setSessionSummaries(listed)
204
+ return listed
205
+ }, [scope, scopeAppSlug])
206
+
207
+ const adoptRecord = useCallback((record: PlatformAgentSessionRecord) => {
208
+ setSessionRecord(record)
209
+ setSnapshot(null)
210
+ setPolicy(undefined)
211
+ setDrivePendingToolCalls(undefined)
212
+ setLiveTurn(createIdleLiveTurn())
213
+ activeRunIdRef.current = record.runId
214
+ }, [])
215
+
216
+ const applyDriveResult = useCallback((result: DriveResult) => {
217
+ setSessionRecord(result.session)
218
+ setSnapshot(result.snapshot)
219
+ setPolicy(result.effectiveToolPolicy)
220
+ setDrivePendingToolCalls(result.manualPendingToolCalls)
221
+ activeRunIdRef.current = result.snapshot.runId
222
+ setLiveTurn(createIdleLiveTurn())
223
+ }, [])
224
+
225
+ const settlePersistedPending = useCallback(
226
+ async (record: PlatformAgentSessionRecord) => {
227
+ if (record.snapshot.state !== 'pending_tools') return
228
+ const result = await advanceAgentSessionPending({
229
+ session: sessionQuery(record.sessionId),
230
+ })
231
+ if (result) applyDriveResult(result)
232
+ },
233
+ [applyDriveResult, sessionQuery],
234
+ )
235
+
236
+ const loadSession = useCallback(async () => {
237
+ // Bound mode: drive exactly the app-owned session, no list/auto-create.
238
+ if (boundSessionId) {
239
+ const record = await readAgentSession(sessionQuery(boundSessionId))
240
+ adoptRecord(record)
241
+ await settlePersistedPending(record)
242
+ return
243
+ }
244
+ const listed = await refreshSessionList()
245
+ const first = listed[0]
246
+ if (first) {
247
+ const record = await readAgentSession(sessionQuery(first.sessionId))
248
+ adoptRecord(record)
249
+ await settlePersistedPending(record)
250
+ return
251
+ }
252
+ if (!autoCreate) {
253
+ setSessionRecord(null)
254
+ return
255
+ }
256
+ const created = await createAgentSession({
257
+ scope,
258
+ appSlug: scopeAppSlug,
259
+ title: DEFAULT_SESSION_TITLE,
260
+ restoreTabId,
261
+ })
262
+ adoptRecord(created)
263
+ await refreshSessionList()
264
+ }, [
265
+ adoptRecord,
266
+ autoCreate,
267
+ boundSessionId,
268
+ refreshSessionList,
269
+ restoreTabId,
270
+ scope,
271
+ scopeAppSlug,
272
+ sessionQuery,
273
+ settlePersistedPending,
274
+ ])
275
+
276
+ useEffect(() => {
277
+ if (!enabled) return
278
+ let cancelled = false
279
+ void loadSession().catch((cause: unknown) => {
280
+ if (!cancelled) {
281
+ setError(cause instanceof Error ? cause.message : String(cause))
282
+ }
283
+ })
284
+ return () => {
285
+ cancelled = true
286
+ }
287
+ }, [enabled, loadSession])
288
+
289
+ useEffect(() => {
290
+ if (!enabled) return
291
+ let cancelled = false
292
+ void readAgentLlmMenuOptions({})
293
+ .then(options => {
294
+ if (!cancelled) setModelOptions(options)
295
+ })
296
+ .catch(() => {
297
+ if (!cancelled) setModelOptions([])
298
+ })
299
+ return () => {
300
+ cancelled = true
301
+ }
302
+ }, [enabled])
303
+
304
+ useEffect(() => {
305
+ setOptimisticModelId(null)
306
+ }, [sessionRecord?.sessionId])
307
+
308
+ // Streaming: persistent listener; latches runId from forwarded events.
309
+ useEffect(() => {
310
+ if (!enabled) return
311
+ let live = createIdleLiveTurn()
312
+ const unsubscribe = onAgentRunEvent(event => {
313
+ const payload = event as PlatformAgentRunEventPayload
314
+ const runId = activeRunIdRef.current
315
+ if (runId && payload.runId !== runId) return
316
+ if (!runId) activeRunIdRef.current = payload.runId
317
+
318
+ if (
319
+ payload.type === AgentRunEventType.StateChanged &&
320
+ 'snapshot' in payload
321
+ ) {
322
+ setSnapshot({ ...payload.snapshot })
323
+ }
324
+ if (payload.type === AgentRunEventType.UsageUpdated) {
325
+ setSnapshot(current =>
326
+ current
327
+ ? {
328
+ ...current,
329
+ usage: mergeUsageTurn(
330
+ current.usage,
331
+ payload.usage,
332
+ payload.estimated,
333
+ ),
334
+ }
335
+ : current,
336
+ )
337
+ }
338
+
339
+ live = reduceAgentLiveTurn(live, payload)
340
+ setLiveTurn(live)
341
+ })
342
+ return unsubscribe
343
+ }, [enabled, sessionRecord?.sessionId])
344
+
345
+ const refresh = useCallback(async () => {
346
+ if (!sessionRecord) return
347
+ const record = await readAgentSession(sessionQuery(sessionRecord.sessionId))
348
+ setSessionRecord(record)
349
+ }, [sessionQuery, sessionRecord])
350
+
351
+ const drive = useCallback(
352
+ async (
353
+ run: () => Promise<DriveResult | null>,
354
+ ): Promise<DriveResult | null> => {
355
+ if (!enabled || busy) return null
356
+ setBusy(true)
357
+ setError(null)
358
+ try {
359
+ const result = await run()
360
+ if (!result) return null
361
+ applyDriveResult(result)
362
+ await refreshSessionList()
363
+ return result
364
+ } catch (cause) {
365
+ if (!stopRequestedRef.current) {
366
+ setError(cause instanceof Error ? cause.message : String(cause))
367
+ }
368
+ setLiveTurn(createIdleLiveTurn())
369
+ return null
370
+ } finally {
371
+ stopRequestedRef.current = false
372
+ setBusy(false)
373
+ }
374
+ },
375
+ [applyDriveResult, busy, enabled, refreshSessionList],
376
+ )
377
+
378
+ const committed = useMemo(
379
+ () => snapshot ?? recordSnapshot(sessionRecord),
380
+ [sessionRecord, snapshot],
381
+ )
382
+ const displaySnapshot = useMemo(
383
+ () => recordSnapshot(sessionRecord),
384
+ [sessionRecord],
385
+ )
386
+ const threadSnapshot = useMemo(() => {
387
+ if (busy && snapshot) return snapshot
388
+ return committed
389
+ }, [busy, committed, snapshot])
390
+ const runState = displaySnapshot ? mapRunState(displaySnapshot.state) : null
391
+
392
+ const selectedModelId =
393
+ optimisticModelId ?? sessionRecord?.config.modelId ?? 'auto'
394
+
395
+ const modelUnavailableReason = useMemo(() => {
396
+ if (isAgentAutoModelId(selectedModelId)) return null
397
+ if (modelOptions.length === 0) return null
398
+ const known = modelOptions.some(option => option.value === selectedModelId)
399
+ return known
400
+ ? null
401
+ : 'This model is not available. Check API keys or local runtime in Settings.'
402
+ }, [modelOptions, selectedModelId])
403
+
404
+ const toolPolicy =
405
+ policy ?? sessionRecord?.config?.toolPolicy ?? undefined
406
+ const acceptedPendingToolCallIds = useMemo(
407
+ () =>
408
+ sessionRecord?.runId && sessionRecord.runId === threadSnapshot?.runId
409
+ ? sessionRecord.snapshot.acceptedPendingToolCallIds ?? []
410
+ : [],
411
+ [
412
+ sessionRecord?.runId,
413
+ sessionRecord?.snapshot.acceptedPendingToolCallIds,
414
+ threadSnapshot?.runId,
415
+ ],
416
+ )
417
+
418
+ const pendingToolCalls = useMemo(() => {
419
+ if (drivePendingToolCalls !== undefined) return drivePendingToolCalls
420
+ return mapApprovalPendingToolCalls(
421
+ threadSnapshot,
422
+ toolPolicy,
423
+ acceptedPendingToolCallIds,
424
+ )
425
+ }, [
426
+ acceptedPendingToolCallIds,
427
+ drivePendingToolCalls,
428
+ threadSnapshot,
429
+ toolPolicy,
430
+ ])
431
+ const messages = useMemo(
432
+ () => mapAgentMessages(threadSnapshot, liveTurn),
433
+ [liveTurn, threadSnapshot],
434
+ )
435
+ const canSend =
436
+ enabled &&
437
+ isComposerEnabled(runState, busy) &&
438
+ !modelUnavailableReason &&
439
+ composerValue.trim().length > 0
440
+
441
+ const canInterrupt = enabled && busy && sessionRecord !== null
442
+
443
+ const contextWindowByModelId = useMemo(() => {
444
+ const map = new Map<string, number>()
445
+ for (const option of modelOptions) {
446
+ if (option.contextWindowTokens) {
447
+ map.set(option.value, option.contextWindowTokens)
448
+ }
449
+ }
450
+ return map
451
+ }, [modelOptions])
452
+
453
+ const usage = useMemo<AgentUiRunUsage | null>(() => {
454
+ const raw = threadSnapshot?.usage
455
+ if (!raw) return null
456
+ if (raw.contextWindowTokens) return raw
457
+ const modelId =
458
+ threadSnapshot?.effectiveModelId ??
459
+ (isAgentAutoModelId(selectedModelId)
460
+ ? DEFAULT_AGENT_HIGH_LEVEL_MODEL_ID
461
+ : selectedModelId)
462
+ return (
463
+ withContextWindowUsage(raw, contextWindowByModelId.get(modelId)) ?? raw
464
+ )
465
+ }, [contextWindowByModelId, selectedModelId, threadSnapshot])
466
+
467
+ const sendMessage = useCallback(
468
+ async (
469
+ messageOverride?: string,
470
+ ): Promise<PlatformAgentRunSnapshot | null> => {
471
+ const message = (messageOverride ?? composerValue).trim()
472
+ if (!message || !sessionRecord) return null
473
+ // Composer sends respect canSend; programmatic sends only respect busy.
474
+ if (messageOverride === undefined && !canSend) return null
475
+ const result = await drive(async () => {
476
+ const driven = await sendAgentSessionMessage({
477
+ session: sessionQuery(sessionRecord.sessionId),
478
+ message,
479
+ })
480
+ if (messageOverride === undefined) setComposerValue('')
481
+ return driven
482
+ })
483
+ return result?.snapshot ?? null
484
+ },
485
+ [canSend, composerValue, drive, sessionQuery, sessionRecord],
486
+ )
487
+
488
+ const approveTools = useCallback(
489
+ async (toolCallIds?: readonly string[]) => {
490
+ if (!sessionRecord || pendingToolCalls.length === 0) return
491
+ await drive(async () => {
492
+ const driven = await approveAgentSessionTools({
493
+ session: sessionQuery(sessionRecord.sessionId),
494
+ ...(toolCallIds?.length ? { toolCallIds: [...toolCallIds] } : {}),
495
+ })
496
+ return driven
497
+ })
498
+ },
499
+ [drive, pendingToolCalls.length, sessionQuery, sessionRecord],
500
+ )
501
+
502
+ const rejectTools = useCallback(
503
+ async (toolCallIds?: readonly string[]) => {
504
+ if (!sessionRecord || pendingToolCalls.length === 0) return
505
+ await drive(async () =>
506
+ rejectAgentSessionTools({
507
+ session: sessionQuery(sessionRecord.sessionId),
508
+ rejectReason,
509
+ ...(toolCallIds?.length ? { toolCallIds: [...toolCallIds] } : {}),
510
+ }),
511
+ )
512
+ },
513
+ [drive, pendingToolCalls.length, rejectReason, sessionQuery, sessionRecord],
514
+ )
515
+
516
+ const interruptRun = useCallback(
517
+ async (reason?: string) => {
518
+ if (!enabled || !sessionRecord || !canInterrupt) return
519
+ stopRequestedRef.current = true
520
+ setError(null)
521
+ try {
522
+ const result = await interruptAgentSession({
523
+ session: sessionQuery(sessionRecord.sessionId),
524
+ reason,
525
+ })
526
+ applyDriveResult(result)
527
+ await refreshSessionList()
528
+ } catch (cause) {
529
+ if (!stopRequestedRef.current) {
530
+ setError(cause instanceof Error ? cause.message : String(cause))
531
+ }
532
+ } finally {
533
+ stopRequestedRef.current = false
534
+ setBusy(false)
535
+ }
536
+ },
537
+ [applyDriveResult, canInterrupt, enabled, refreshSessionList, sessionQuery, sessionRecord],
538
+ )
539
+
540
+ const selectSession = useCallback(
541
+ async (sessionId: string) => {
542
+ const record = await readAgentSession(sessionQuery(sessionId))
543
+ adoptRecord(record)
544
+ setComposerValue('')
545
+ setError(null)
546
+ await settlePersistedPending(record)
547
+ },
548
+ [adoptRecord, sessionQuery, settlePersistedPending],
549
+ )
550
+
551
+ const createNewSession = useCallback(async () => {
552
+ const created = await createAgentSession({
553
+ scope,
554
+ appSlug: scopeAppSlug,
555
+ title: DEFAULT_SESSION_TITLE,
556
+ restoreTabId,
557
+ })
558
+ adoptRecord(created)
559
+ setComposerValue('')
560
+ await refreshSessionList()
561
+ }, [adoptRecord, refreshSessionList, restoreTabId, scope, scopeAppSlug])
562
+
563
+ const deleteSession = useCallback(async () => {
564
+ if (!sessionRecord) return
565
+ await deleteAgentSession(sessionQuery(sessionRecord.sessionId))
566
+ const listed = await refreshSessionList()
567
+ const next = listed[0]
568
+ if (next) {
569
+ await selectSession(next.sessionId)
570
+ return
571
+ }
572
+ if (autoCreate) await createNewSession()
573
+ else setSessionRecord(null)
574
+ }, [
575
+ autoCreate,
576
+ createNewSession,
577
+ refreshSessionList,
578
+ selectSession,
579
+ sessionQuery,
580
+ sessionRecord,
581
+ ])
582
+
583
+ const renameSession = useCallback(
584
+ async (title: string) => {
585
+ if (!sessionRecord) return
586
+ const trimmed = title.trim()
587
+ if (!trimmed) return
588
+ const updated = await updateAgentSession({
589
+ query: sessionQuery(sessionRecord.sessionId),
590
+ patch: { metadata: { title: trimmed } },
591
+ })
592
+ setSessionRecord(updated)
593
+ await refreshSessionList()
594
+ },
595
+ [refreshSessionList, sessionQuery, sessionRecord],
596
+ )
597
+
598
+ const persistScopeDefault = useCallback(
599
+ async (patch: PlatformAgentSessionConfigPatch) => {
600
+ try {
601
+ const prefs = (await getPlatformPreferences()) as {
602
+ agentSessionDefaults?: {
603
+ global?: PlatformAgentSessionConfigPatch
604
+ apps?: Record<string, PlatformAgentSessionConfigPatch>
605
+ }
606
+ }
607
+ const stored = prefs.agentSessionDefaults ?? {}
608
+ if (scope === 'global') {
609
+ await patchPlatformPreferences({
610
+ agentSessionDefaults: {
611
+ ...stored,
612
+ global: mergeScopeDefaultPatch(stored.global, patch),
613
+ },
614
+ })
615
+ return
616
+ }
617
+ if (!scopeAppSlug) return
618
+ const apps = { ...(stored.apps ?? {}) }
619
+ apps[scopeAppSlug] = mergeScopeDefaultPatch(apps[scopeAppSlug], patch)
620
+ await patchPlatformPreferences({
621
+ agentSessionDefaults: { ...stored, apps },
622
+ })
623
+ } catch {
624
+ /* scope defaults are best-effort */
625
+ }
626
+ },
627
+ [scope, scopeAppSlug],
628
+ )
629
+
630
+ const setModelId = useCallback(
631
+ async (modelId: string) => {
632
+ if (!sessionRecord) return
633
+ setOptimisticModelId(modelId)
634
+ try {
635
+ const updated = await updateAgentSession({
636
+ query: sessionQuery(sessionRecord.sessionId),
637
+ patch: { config: { modelId } },
638
+ })
639
+ setSessionRecord(updated)
640
+ setOptimisticModelId(null)
641
+ await persistScopeDefault({ modelId })
642
+ } catch (cause) {
643
+ setOptimisticModelId(null)
644
+ setError(cause instanceof Error ? cause.message : String(cause))
645
+ }
646
+ },
647
+ [persistScopeDefault, sessionQuery, sessionRecord],
648
+ )
649
+
650
+ const allowedTargetApps =
651
+ sessionRecord?.config.toolPolicy?.allowedTargetApps ?? []
652
+
653
+ const setAllowedTargetApps = useCallback(
654
+ async (slugs: readonly string[]) => {
655
+ if (!sessionRecord) return
656
+ const normalized = [
657
+ ...new Set(slugs.map(slug => slug.trim()).filter(Boolean)),
658
+ ]
659
+ const updated = await updateAgentSession({
660
+ query: sessionQuery(sessionRecord.sessionId),
661
+ patch: { config: { toolPolicy: { allowedTargetApps: normalized } } },
662
+ })
663
+ setSessionRecord(updated)
664
+ await persistScopeDefault({
665
+ toolPolicy: { allowedTargetApps: normalized },
666
+ })
667
+ },
668
+ [persistScopeDefault, sessionQuery, sessionRecord],
669
+ )
670
+
671
+ const setToolApprovalOverride = useCallback(
672
+ async (qualifiedName: string, requiresApproval: boolean) => {
673
+ if (!sessionRecord) return
674
+ const overrides = {
675
+ ...sessionRecord.config.toolPolicy?.approvalOverrides,
676
+ [qualifiedName]: requiresApproval,
677
+ }
678
+ const updated = await updateAgentSession({
679
+ query: sessionQuery(sessionRecord.sessionId),
680
+ patch: { config: { toolPolicy: { approvalOverrides: overrides } } },
681
+ })
682
+ setSessionRecord(updated)
683
+ await persistScopeDefault({
684
+ toolPolicy: { approvalOverrides: overrides },
685
+ })
686
+ },
687
+ [persistScopeDefault, sessionQuery, sessionRecord],
688
+ )
689
+
690
+ const approveToolAlwaysForSession = useCallback(
691
+ async (qualifiedName: string, toolCallId: string) => {
692
+ if (!sessionRecord) return
693
+ await drive(async () => {
694
+ const overrides = {
695
+ ...sessionRecord.config.toolPolicy?.approvalOverrides,
696
+ [qualifiedName]: false,
697
+ }
698
+ const updated = await updateAgentSession({
699
+ query: sessionQuery(sessionRecord.sessionId),
700
+ patch: { config: { toolPolicy: { approvalOverrides: overrides } } },
701
+ })
702
+ await persistScopeDefault({
703
+ toolPolicy: { approvalOverrides: overrides },
704
+ })
705
+ return approveAgentSessionTools({
706
+ session: sessionQuery(updated.sessionId),
707
+ toolCallIds: [toolCallId],
708
+ })
709
+ })
710
+ },
711
+ [drive, persistScopeDefault, sessionQuery, sessionRecord],
712
+ )
713
+
714
+ return {
715
+ scope,
716
+ setScope,
717
+ sessionRecord,
718
+ sessionSummaries,
719
+ sessionId: sessionRecord?.sessionId ?? null,
720
+ messages,
721
+ liveTurn,
722
+ pendingToolCalls,
723
+ runState,
724
+ busy,
725
+ error,
726
+ composerValue,
727
+ setComposerValue,
728
+ modelId: selectedModelId,
729
+ setModelId,
730
+ modelOptions,
731
+ modelUnavailableReason,
732
+ usage,
733
+ canSend,
734
+ canInterrupt,
735
+ sendMessage,
736
+ interruptRun,
737
+ approveTools,
738
+ approveToolAlwaysForSession,
739
+ rejectTools,
740
+ selectSession,
741
+ createNewSession,
742
+ deleteSession,
743
+ renameSession,
744
+ allowedTargetApps,
745
+ setAllowedTargetApps,
746
+ setToolApprovalOverride,
747
+ refresh,
748
+ }
749
+ }