@deepseek-ai/dsh-client-ui-chat 0.2.2-alpha.3 → 0.2.2-rc.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 (355) hide show
  1. package/README.i18n.yaml +16 -16
  2. package/README.md +17 -5
  3. package/README.zh.md +17 -5
  4. package/lib/client.js +18 -15587
  5. package/lib/client.js.map +1 -0
  6. package/lib/types/chat-settings.d.ts.map +1 -0
  7. package/lib/types/chat-settings.js.map +1 -0
  8. package/lib/types/client/apply.d.ts.map +1 -0
  9. package/lib/types/client/apply.js.map +1 -0
  10. package/lib/types/client/chat/ApprovalCommand.d.ts +4 -3
  11. package/lib/types/client/chat/ApprovalCommand.d.ts.map +1 -0
  12. package/lib/types/client/chat/ApprovalCommand.js.map +1 -0
  13. package/lib/types/client/chat/AssistantMarkdown.d.ts.map +1 -0
  14. package/lib/types/client/chat/AssistantMarkdown.js.map +1 -0
  15. package/lib/types/client/chat/AssistantNodeView.d.ts.map +1 -0
  16. package/lib/types/client/chat/AssistantNodeView.js.map +1 -0
  17. package/lib/types/client/chat/ChatFlow.d.ts.map +1 -0
  18. package/lib/types/client/chat/ChatFlow.js.map +1 -0
  19. package/lib/types/client/chat/ChatGroupSeat.d.ts.map +1 -0
  20. package/lib/types/client/chat/ChatGroupSeat.js.map +1 -0
  21. package/lib/types/client/chat/ChatNodeSeat.d.ts.map +1 -0
  22. package/lib/types/client/chat/ChatNodeSeat.js.map +1 -0
  23. package/lib/types/client/chat/ChatView.d.ts +1 -1
  24. package/lib/types/client/chat/ChatView.d.ts.map +1 -0
  25. package/lib/types/client/chat/ChatView.js.map +1 -0
  26. package/lib/types/client/chat/CommandNodeView.d.ts.map +1 -0
  27. package/lib/types/client/chat/CommandNodeView.js.map +1 -0
  28. package/lib/types/client/chat/CompactionCommandCard.d.ts.map +1 -0
  29. package/lib/types/client/chat/CompactionCommandCard.js.map +1 -0
  30. package/lib/types/client/chat/CompactionItem.d.ts.map +1 -0
  31. package/lib/types/client/chat/CompactionItem.js.map +1 -0
  32. package/lib/types/client/chat/ContextBody.d.ts.map +1 -0
  33. package/lib/types/client/chat/ContextBody.js.map +1 -0
  34. package/lib/types/client/chat/ContextInjectionRow.d.ts.map +1 -0
  35. package/lib/types/client/chat/ContextInjectionRow.js.map +1 -0
  36. package/lib/types/client/chat/GenericCommandCard.d.ts.map +1 -0
  37. package/lib/types/client/chat/GenericCommandCard.js.map +1 -0
  38. package/lib/types/client/chat/MessageIconActions.d.ts.map +1 -0
  39. package/lib/types/client/chat/MessageIconActions.js.map +1 -0
  40. package/lib/types/client/chat/MessageItem.d.ts.map +1 -0
  41. package/lib/types/client/chat/MessageItem.js.map +1 -0
  42. package/lib/types/client/chat/QuotaNoticeHost.d.ts.map +1 -0
  43. package/lib/types/client/chat/QuotaNoticeHost.js.map +1 -0
  44. package/lib/types/client/chat/ReasoningContent.d.ts.map +1 -0
  45. package/lib/types/client/chat/ReasoningContent.js.map +1 -0
  46. package/lib/types/client/chat/ReasoningRow.d.ts.map +1 -0
  47. package/lib/types/client/chat/ReasoningRow.js.map +1 -0
  48. package/lib/types/client/chat/RunningStatus.d.ts.map +1 -0
  49. package/lib/types/client/chat/RunningStatus.js.map +1 -0
  50. package/lib/types/client/chat/RunningWhaleTail.d.ts.map +1 -0
  51. package/lib/types/client/chat/RunningWhaleTail.js.map +1 -0
  52. package/lib/types/client/chat/StatsPills.d.ts.map +1 -0
  53. package/lib/types/client/chat/StatsPills.js.map +1 -0
  54. package/lib/types/client/chat/SystemPromptRow.d.ts.map +1 -0
  55. package/lib/types/client/chat/SystemPromptRow.js.map +1 -0
  56. package/lib/types/client/chat/TurnNavigator.d.ts.map +1 -0
  57. package/lib/types/client/chat/TurnNavigator.js.map +1 -0
  58. package/lib/types/client/chat/TurnProcessNodeView.d.ts.map +1 -0
  59. package/lib/types/client/chat/TurnProcessNodeView.js.map +1 -0
  60. package/lib/types/client/chat/TurnTailNodeView.d.ts.map +1 -0
  61. package/lib/types/client/chat/TurnTailNodeView.js.map +1 -0
  62. package/lib/types/client/chat/TurnTriggerNodeView.d.ts.map +1 -0
  63. package/lib/types/client/chat/TurnTriggerNodeView.js.map +1 -0
  64. package/lib/types/client/chat/TurnUsagePanel.d.ts.map +1 -0
  65. package/lib/types/client/chat/TurnUsagePanel.js.map +1 -0
  66. package/lib/types/client/chat/UserContent.d.ts.map +1 -0
  67. package/lib/types/client/chat/UserContent.js.map +1 -0
  68. package/lib/types/client/chat/flow-motion.d.ts +2 -0
  69. package/lib/types/client/chat/flow-motion.d.ts.map +1 -0
  70. package/lib/types/client/chat/flow-motion.js.map +1 -0
  71. package/lib/types/client/chat/message-chrome.d.ts.map +1 -0
  72. package/lib/types/client/chat/message-chrome.js.map +1 -0
  73. package/lib/types/client/chat/register-node-renderers.d.ts.map +1 -0
  74. package/lib/types/client/chat/register-node-renderers.js.map +1 -0
  75. package/lib/types/client/chat/render-entry.d.ts.map +1 -0
  76. package/lib/types/client/chat/render-entry.js.map +1 -0
  77. package/lib/types/client/chat/searchable-hidden.d.ts.map +1 -0
  78. package/lib/types/client/chat/searchable-hidden.js.map +1 -0
  79. package/lib/types/client/chat/stat-dialog.d.ts +5 -10
  80. package/lib/types/client/chat/stat-dialog.d.ts.map +1 -0
  81. package/lib/types/client/chat/stat-dialog.js.map +1 -0
  82. package/lib/types/client/chat/step-process.d.ts.map +1 -0
  83. package/lib/types/client/chat/step-process.js.map +1 -0
  84. package/lib/types/client/chat/text-interaction.d.ts.map +1 -0
  85. package/lib/types/client/chat/text-interaction.js.map +1 -0
  86. package/lib/types/client/chat/text-selection.d.ts.map +1 -0
  87. package/lib/types/client/chat/text-selection.js.map +1 -0
  88. package/lib/types/client/chat/token-format.d.ts.map +1 -0
  89. package/lib/types/client/chat/token-format.js.map +1 -0
  90. package/lib/types/client/chat/turn-assistant.d.ts.map +1 -0
  91. package/lib/types/client/chat/turn-assistant.js.map +1 -0
  92. package/lib/types/client/chat/turn-rail-items.d.ts.map +1 -0
  93. package/lib/types/client/chat/turn-rail-items.js.map +1 -0
  94. package/lib/types/client/chat/turn-trigger.d.ts +3 -2
  95. package/lib/types/client/chat/turn-trigger.d.ts.map +1 -0
  96. package/lib/types/client/chat/turn-trigger.js.map +1 -0
  97. package/lib/types/client/chat/use-calendar-day.d.ts.map +1 -0
  98. package/lib/types/client/chat/use-calendar-day.js.map +1 -0
  99. package/lib/types/client/chat/use-chat-navigation.d.ts +21 -5
  100. package/lib/types/client/chat/use-chat-navigation.d.ts.map +1 -0
  101. package/lib/types/client/chat/use-chat-navigation.js.map +1 -0
  102. package/lib/types/client/chat/use-chat-reading.d.ts.map +1 -0
  103. package/lib/types/client/chat/use-chat-reading.js.map +1 -0
  104. package/lib/types/client/chat/use-chat-scroll.d.ts +5 -2
  105. package/lib/types/client/chat/use-chat-scroll.d.ts.map +1 -0
  106. package/lib/types/client/chat/use-chat-scroll.js.map +1 -0
  107. package/lib/types/client/chat/use-chat-viewport.d.ts +53 -0
  108. package/lib/types/client/chat/use-chat-viewport.d.ts.map +1 -0
  109. package/lib/types/client/chat/use-chat-viewport.js.map +1 -0
  110. package/lib/types/client/chat/use-disclosure.d.ts.map +1 -0
  111. package/lib/types/client/chat/use-disclosure.js.map +1 -0
  112. package/lib/types/client/chat/use-process-scroll.d.ts.map +1 -0
  113. package/lib/types/client/chat/use-process-scroll.js.map +1 -0
  114. package/lib/types/client/chat/use-scroll-follow.d.ts.map +1 -0
  115. package/lib/types/client/chat/use-scroll-follow.js.map +1 -0
  116. package/lib/types/client/chat/use-turn-data.d.ts.map +1 -0
  117. package/lib/types/client/chat/use-turn-data.js.map +1 -0
  118. package/lib/types/client/contract/assistant-content.d.ts.map +1 -0
  119. package/lib/types/client/contract/assistant-content.js.map +1 -0
  120. package/lib/types/client/contract/chat-nodes.d.ts.map +1 -0
  121. package/lib/types/client/contract/chat-nodes.js.map +1 -0
  122. package/lib/types/client/contract/chat-visibility.d.ts +2 -2
  123. package/lib/types/client/contract/chat-visibility.d.ts.map +1 -0
  124. package/lib/types/client/contract/chat-visibility.js.map +1 -0
  125. package/lib/types/client/contract/group-tree.d.ts.map +1 -0
  126. package/lib/types/client/contract/group-tree.js.map +1 -0
  127. package/lib/types/client/contract/process-groups.d.ts +6 -3
  128. package/lib/types/client/contract/process-groups.d.ts.map +1 -0
  129. package/lib/types/client/contract/process-groups.js.map +1 -0
  130. package/lib/types/client/contract/slots.d.ts +11 -2
  131. package/lib/types/client/contract/slots.d.ts.map +1 -0
  132. package/lib/types/client/contract/slots.js.map +1 -0
  133. package/lib/types/client/contract/snapshot.d.ts.map +1 -0
  134. package/lib/types/client/contract/snapshot.js.map +1 -0
  135. package/lib/types/client/contract/store.d.ts.map +1 -0
  136. package/lib/types/client/contract/store.js.map +1 -0
  137. package/lib/types/client/contract/turn-metrics.d.ts.map +1 -0
  138. package/lib/types/client/contract/turn-metrics.js.map +1 -0
  139. package/lib/types/client/contract/turn-process.d.ts.map +1 -0
  140. package/lib/types/client/contract/turn-process.js.map +1 -0
  141. package/lib/types/client/conversation-nodes/assistant.d.ts.map +1 -0
  142. package/lib/types/client/conversation-nodes/assistant.js.map +1 -0
  143. package/lib/types/client/conversation-nodes/chat-snapshot-builder.d.ts.map +1 -0
  144. package/lib/types/client/conversation-nodes/chat-snapshot-builder.js.map +1 -0
  145. package/lib/types/client/conversation-nodes/command.d.ts.map +1 -0
  146. package/lib/types/client/conversation-nodes/command.js.map +1 -0
  147. package/lib/types/client/conversation-nodes/common.d.ts.map +1 -0
  148. package/lib/types/client/conversation-nodes/common.js.map +1 -0
  149. package/lib/types/client/conversation-nodes/compaction.d.ts.map +1 -0
  150. package/lib/types/client/conversation-nodes/compaction.js.map +1 -0
  151. package/lib/types/client/conversation-nodes/event-projection.d.ts.map +1 -0
  152. package/lib/types/client/conversation-nodes/event-projection.js.map +1 -0
  153. package/lib/types/client/conversation-nodes/fallback.d.ts.map +1 -0
  154. package/lib/types/client/conversation-nodes/fallback.js.map +1 -0
  155. package/lib/types/client/conversation-nodes/group-tree-segments.d.ts.map +1 -0
  156. package/lib/types/client/conversation-nodes/group-tree-segments.js.map +1 -0
  157. package/lib/types/client/conversation-nodes/inbox.d.ts.map +1 -0
  158. package/lib/types/client/conversation-nodes/inbox.js.map +1 -0
  159. package/lib/types/client/conversation-nodes/message.d.ts +1 -1
  160. package/lib/types/client/conversation-nodes/message.d.ts.map +1 -0
  161. package/lib/types/client/conversation-nodes/message.js.map +1 -0
  162. package/lib/types/client/conversation-nodes/process-activity.d.ts +1 -0
  163. package/lib/types/client/conversation-nodes/process-activity.d.ts.map +1 -0
  164. package/lib/types/client/conversation-nodes/process-activity.js.map +1 -0
  165. package/lib/types/client/conversation-nodes/process-groups.d.ts.map +1 -0
  166. package/lib/types/client/conversation-nodes/process-groups.js.map +1 -0
  167. package/lib/types/client/conversation-nodes/register.d.ts.map +1 -0
  168. package/lib/types/client/conversation-nodes/register.js.map +1 -0
  169. package/lib/types/client/conversation-nodes/request-prompt.d.ts.map +1 -0
  170. package/lib/types/client/conversation-nodes/request-prompt.js.map +1 -0
  171. package/lib/types/client/conversation-nodes/retry.d.ts.map +1 -0
  172. package/lib/types/client/conversation-nodes/retry.js.map +1 -0
  173. package/lib/types/client/conversation-nodes/tool.d.ts.map +1 -0
  174. package/lib/types/client/conversation-nodes/tool.js.map +1 -0
  175. package/lib/types/client/conversation-nodes/turn-error.d.ts.map +1 -0
  176. package/lib/types/client/conversation-nodes/turn-error.js.map +1 -0
  177. package/lib/types/client/conversation-nodes/turn-max-tokens.d.ts.map +1 -0
  178. package/lib/types/client/conversation-nodes/turn-max-tokens.js.map +1 -0
  179. package/lib/types/client/conversation-nodes/turn-navigation.d.ts.map +1 -0
  180. package/lib/types/client/conversation-nodes/turn-navigation.js.map +1 -0
  181. package/lib/types/client/conversation-nodes/turn-process-presentation.d.ts.map +1 -0
  182. package/lib/types/client/conversation-nodes/turn-process-presentation.js.map +1 -0
  183. package/lib/types/client/conversation-nodes/turn-process.d.ts.map +1 -0
  184. package/lib/types/client/conversation-nodes/turn-process.js.map +1 -0
  185. package/lib/types/client/conversation-nodes/turn-tail.d.ts.map +1 -0
  186. package/lib/types/client/conversation-nodes/turn-tail.js.map +1 -0
  187. package/lib/types/client/fence/FenceLayers.d.ts +21 -0
  188. package/lib/types/client/fence/FenceLayers.d.ts.map +1 -0
  189. package/lib/types/client/fence/FenceLayers.js.map +1 -0
  190. package/lib/types/client/fence/register.d.ts +10 -0
  191. package/lib/types/client/fence/register.d.ts.map +1 -0
  192. package/lib/types/client/fence/register.js.map +1 -0
  193. package/lib/types/client/file-path.d.ts.map +1 -0
  194. package/lib/types/client/file-path.js.map +1 -0
  195. package/lib/types/client/index.d.ts +1 -1
  196. package/lib/types/client/index.d.ts.map +1 -0
  197. package/lib/types/client/index.js.map +1 -0
  198. package/lib/types/client/locale.d.ts +96 -0
  199. package/lib/types/client/locale.d.ts.map +1 -0
  200. package/lib/types/client/locale.js.map +1 -0
  201. package/lib/types/client/markdown-labels.d.ts.map +1 -0
  202. package/lib/types/client/markdown-labels.js.map +1 -0
  203. package/lib/types/client/model/conversation-context.d.ts.map +1 -0
  204. package/lib/types/client/model/conversation-context.js.map +1 -0
  205. package/lib/types/client/model/steering-history.d.ts.map +1 -0
  206. package/lib/types/client/model/steering-history.js.map +1 -0
  207. package/lib/types/client/model/tool-call-tree.d.ts.map +1 -0
  208. package/lib/types/client/model/tool-call-tree.js.map +1 -0
  209. package/lib/types/client/performance-usage.d.ts.map +1 -0
  210. package/lib/types/client/performance-usage.js.map +1 -0
  211. package/lib/types/client/presentation-policy.d.ts.map +1 -0
  212. package/lib/types/client/presentation-policy.js.map +1 -0
  213. package/lib/types/client/reasoning-text.d.ts.map +1 -0
  214. package/lib/types/client/reasoning-text.js.map +1 -0
  215. package/lib/types/client/settings/LinkOpeningRow.d.ts.map +1 -0
  216. package/lib/types/client/settings/LinkOpeningRow.js.map +1 -0
  217. package/lib/types/client/settings/PerformanceUsageRow.d.ts.map +1 -0
  218. package/lib/types/client/settings/PerformanceUsageRow.js.map +1 -0
  219. package/lib/types/client/settings/PreferenceRow.d.ts.map +1 -0
  220. package/lib/types/client/settings/PreferenceRow.js.map +1 -0
  221. package/lib/types/client/settings/TranscriptViewRow.d.ts.map +1 -0
  222. package/lib/types/client/settings/TranscriptViewRow.js.map +1 -0
  223. package/lib/types/client/stores.d.ts.map +1 -0
  224. package/lib/types/client/stores.js.map +1 -0
  225. package/lib/types/client/transcript-view.d.ts.map +1 -0
  226. package/lib/types/client/transcript-view.js.map +1 -0
  227. package/lib/types/index.d.ts.map +1 -0
  228. package/lib/types/index.js.map +1 -0
  229. package/package.json +47 -44
  230. package/src/chat-settings.ts +98 -0
  231. package/src/client/apply.ts +355 -0
  232. package/src/client/assets/running-whale@2x.png +0 -0
  233. package/src/client/chat/ApprovalCommand.tsx +42 -0
  234. package/src/client/chat/AssistantMarkdown.module.css +88 -0
  235. package/src/client/chat/AssistantMarkdown.tsx +170 -0
  236. package/src/client/chat/AssistantNodeView.tsx +67 -0
  237. package/src/client/chat/ChatFlow.tsx +100 -0
  238. package/src/client/chat/ChatGroupSeat.module.css +166 -0
  239. package/src/client/chat/ChatGroupSeat.tsx +208 -0
  240. package/src/client/chat/ChatNodeSeat.tsx +179 -0
  241. package/src/client/chat/ChatView.module.css +426 -0
  242. package/src/client/chat/ChatView.tsx +351 -0
  243. package/src/client/chat/CommandNodeView.tsx +40 -0
  244. package/src/client/chat/CompactionCommandCard.tsx +26 -0
  245. package/src/client/chat/CompactionItem.tsx +76 -0
  246. package/src/client/chat/ContextBody.module.css +161 -0
  247. package/src/client/chat/ContextBody.tsx +592 -0
  248. package/src/client/chat/ContextInjectionRow.module.css +68 -0
  249. package/src/client/chat/ContextInjectionRow.tsx +94 -0
  250. package/src/client/chat/GenericCommandCard.module.css +49 -0
  251. package/src/client/chat/GenericCommandCard.tsx +75 -0
  252. package/src/client/chat/MessageIconActions.module.css +116 -0
  253. package/src/client/chat/MessageIconActions.tsx +90 -0
  254. package/src/client/chat/MessageItem.module.css +360 -0
  255. package/src/client/chat/MessageItem.tsx +410 -0
  256. package/src/client/chat/QuotaNoticeHost.tsx +27 -0
  257. package/src/client/chat/ReasoningContent.tsx +26 -0
  258. package/src/client/chat/ReasoningRow.module.css +77 -0
  259. package/src/client/chat/ReasoningRow.tsx +112 -0
  260. package/src/client/chat/RunningStatus.tsx +48 -0
  261. package/src/client/chat/RunningWhaleTail.tsx +19 -0
  262. package/src/client/chat/StatsPills.module.css +63 -0
  263. package/src/client/chat/StatsPills.tsx +348 -0
  264. package/src/client/chat/SystemPromptRow.tsx +50 -0
  265. package/src/client/chat/TurnNavigator.module.css +223 -0
  266. package/src/client/chat/TurnNavigator.tsx +295 -0
  267. package/src/client/chat/TurnProcessNodeView.module.css +62 -0
  268. package/src/client/chat/TurnProcessNodeView.tsx +62 -0
  269. package/src/client/chat/TurnTailNodeView.module.css +12 -0
  270. package/src/client/chat/TurnTailNodeView.tsx +81 -0
  271. package/src/client/chat/TurnTriggerNodeView.module.css +50 -0
  272. package/src/client/chat/TurnTriggerNodeView.tsx +57 -0
  273. package/src/client/chat/TurnUsagePanel.module.css +79 -0
  274. package/src/client/chat/TurnUsagePanel.tsx +110 -0
  275. package/src/client/chat/UserContent.tsx +60 -0
  276. package/src/client/chat/accessibility.module.css +8 -0
  277. package/src/client/chat/flow-motion.ts +556 -0
  278. package/src/client/chat/message-chrome.ts +100 -0
  279. package/src/client/chat/register-node-renderers.ts +100 -0
  280. package/src/client/chat/render-entry.ts +16 -0
  281. package/src/client/chat/searchable-hidden.ts +45 -0
  282. package/src/client/chat/stat-dialog.module.css +149 -0
  283. package/src/client/chat/stat-dialog.ts +55 -0
  284. package/src/client/chat/step-process.ts +28 -0
  285. package/src/client/chat/text-interaction.ts +298 -0
  286. package/src/client/chat/text-selection.ts +180 -0
  287. package/src/client/chat/token-format.ts +98 -0
  288. package/src/client/chat/turn-assistant.ts +10 -0
  289. package/src/client/chat/turn-rail-items.ts +89 -0
  290. package/src/client/chat/turn-trigger.ts +88 -0
  291. package/src/client/chat/use-calendar-day.ts +25 -0
  292. package/src/client/chat/use-chat-navigation.ts +309 -0
  293. package/src/client/chat/use-chat-reading.ts +283 -0
  294. package/src/client/chat/use-chat-scroll.ts +209 -0
  295. package/src/client/chat/use-chat-viewport.ts +1130 -0
  296. package/src/client/chat/use-disclosure.ts +35 -0
  297. package/src/client/chat/use-process-scroll.ts +88 -0
  298. package/src/client/chat/use-scroll-follow.ts +182 -0
  299. package/src/client/chat/use-turn-data.ts +23 -0
  300. package/src/client/contract/assistant-content.ts +15 -0
  301. package/src/client/contract/chat-nodes.ts +135 -0
  302. package/src/client/contract/chat-visibility.ts +20 -0
  303. package/src/client/contract/group-tree.ts +37 -0
  304. package/src/client/contract/process-groups.ts +30 -0
  305. package/src/client/contract/slots.ts +508 -0
  306. package/src/client/contract/snapshot.ts +171 -0
  307. package/src/client/contract/store.ts +17 -0
  308. package/src/client/contract/turn-metrics.ts +43 -0
  309. package/src/client/contract/turn-process.ts +58 -0
  310. package/src/client/conversation-nodes/README.i18n.yaml +64 -0
  311. package/src/client/conversation-nodes/README.md +338 -0
  312. package/src/client/conversation-nodes/README.zh.md +338 -0
  313. package/src/client/conversation-nodes/assistant.ts +384 -0
  314. package/src/client/conversation-nodes/chat-snapshot-builder.ts +1244 -0
  315. package/src/client/conversation-nodes/command.ts +227 -0
  316. package/src/client/conversation-nodes/common.ts +83 -0
  317. package/src/client/conversation-nodes/compaction.ts +65 -0
  318. package/src/client/conversation-nodes/event-projection.ts +179 -0
  319. package/src/client/conversation-nodes/fallback.ts +41 -0
  320. package/src/client/conversation-nodes/group-tree-segments.ts +91 -0
  321. package/src/client/conversation-nodes/inbox.ts +148 -0
  322. package/src/client/conversation-nodes/message.ts +182 -0
  323. package/src/client/conversation-nodes/process-activity.ts +170 -0
  324. package/src/client/conversation-nodes/process-groups.ts +303 -0
  325. package/src/client/conversation-nodes/register.ts +38 -0
  326. package/src/client/conversation-nodes/request-prompt.ts +169 -0
  327. package/src/client/conversation-nodes/retry.ts +97 -0
  328. package/src/client/conversation-nodes/tool.ts +371 -0
  329. package/src/client/conversation-nodes/turn-error.ts +120 -0
  330. package/src/client/conversation-nodes/turn-max-tokens.ts +82 -0
  331. package/src/client/conversation-nodes/turn-navigation.ts +97 -0
  332. package/src/client/conversation-nodes/turn-process-presentation.ts +149 -0
  333. package/src/client/conversation-nodes/turn-process.ts +374 -0
  334. package/src/client/conversation-nodes/turn-tail.ts +164 -0
  335. package/src/client/fence/FenceLayers.tsx +33 -0
  336. package/src/client/fence/register.ts +22 -0
  337. package/src/client/file-path.ts +19 -0
  338. package/src/client/index.ts +69 -0
  339. package/src/client/locale.ts +1695 -0
  340. package/src/client/markdown-labels.ts +16 -0
  341. package/src/client/model/conversation-context.ts +24 -0
  342. package/src/client/model/steering-history.ts +64 -0
  343. package/src/client/model/tool-call-tree.ts +204 -0
  344. package/src/client/performance-usage.ts +34 -0
  345. package/src/client/presentation-policy.ts +109 -0
  346. package/src/client/reasoning-text.ts +25 -0
  347. package/src/client/settings/LinkOpeningRow.tsx +47 -0
  348. package/src/client/settings/PerformanceUsageRow.tsx +46 -0
  349. package/src/client/settings/PreferenceRow.module.css +66 -0
  350. package/src/client/settings/PreferenceRow.tsx +59 -0
  351. package/src/client/settings/TranscriptViewRow.tsx +93 -0
  352. package/src/client/stores.ts +62 -0
  353. package/src/client/transcript-view.ts +81 -0
  354. package/src/css-modules.d.ts +6 -0
  355. package/src/index.ts +45 -0
@@ -0,0 +1,1130 @@
1
+ /** Turn-aware DOM scrolling and geometry, without history-loading or follow policy. */
2
+ import { useLayoutEffect, useRef, useState, type RefObject } from 'react'
3
+ import type { ChatScrollPosition } from '../contract/slots.ts'
4
+ import type { ChatSnapshot } from '../contract/snapshot.ts'
5
+ import { createFlowMotion, type InputFoldBox, type InputFoldDriver } from './flow-motion.ts'
6
+ import { scrollMetrics, ScrollFollow, type ViewportMetrics } from './use-scroll-follow.ts'
7
+ export type { ViewportMetrics } from './use-scroll-follow.ts'
8
+
9
+ /** Scroll geometry attributed against the last acknowledged position. */
10
+ export interface ViewportScroll {
11
+ readonly metrics: ViewportMetrics
12
+ readonly movedByReader: boolean
13
+ }
14
+
15
+ /** Actual clamped scroll result, including any known semantic anchor and turn. */
16
+ export interface ViewportLanding {
17
+ readonly metrics: ViewportMetrics
18
+ readonly position: ChatScrollPosition | null
19
+ readonly turn: number | null
20
+ }
21
+
22
+ interface ViewportEvents {
23
+ scroll: (event: ViewportScroll) => void
24
+ scrollEnd: (outer: boolean) => void
25
+ resize: () => void
26
+ interact: () => void
27
+ /** Any reading gesture, before paging ownership is consulted. */
28
+ intent?: () => void
29
+ /** Recheck a prepared history page after an input or transition settles. */
30
+ history?: () => void
31
+ }
32
+
33
+ interface ViewportElements {
34
+ readonly list: HTMLElement
35
+ readonly column: HTMLElement
36
+ readonly scroller: HTMLElement
37
+ readonly composer: HTMLElement | null
38
+ /** Room below closing rows, retained until scrolling or content growth makes it unnecessary. */
39
+ readonly spacer: HTMLElement | null
40
+ }
41
+
42
+ /** Reading policy that fold batches consult and report tail landings to. */
43
+ export interface FoldReader {
44
+ /** Follow intent at batch start selects the tail landing; tail landings commit it. */
45
+ readonly follow: ScrollFollow
46
+ /** @param landing - the actual geometry after a batch landed at the tail. */
47
+ readonly landedAtTail: (landing: ViewportLanding) => void
48
+ /** @returns whether reader movement awaits sampling; until then follow intent is undecided. */
49
+ readonly pending: () => boolean
50
+ }
51
+
52
+ /** A top-level row a closing shrink may keep still, measured before the rows close. */
53
+ interface ShrinkAnchor {
54
+ readonly element: HTMLElement
55
+ /** Distance from the row's top to the end of the content last painted. */
56
+ readonly fromEnd: number
57
+ }
58
+
59
+ /** Layout measured at the first instant hide of a commit; only the size observation of that frame uses it. */
60
+ interface ClosingLayout {
61
+ /** The first visible row, then the rows above it within one scrollport. */
62
+ readonly rows: readonly ShrinkAnchor[]
63
+ /** Content height without fold room when the rows were measured. */
64
+ readonly content: number
65
+ }
66
+
67
+ interface PagingPosition {
68
+ readonly row: HTMLElement
69
+ readonly position: ChatScrollPosition
70
+ readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number } | null
71
+ }
72
+
73
+ const READING_INTENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown', 'beforematch'] as const
74
+ const SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '])
75
+
76
+ /** Owns one Chat scrollport's DOM operations, event listeners, and size observer. */
77
+ export class ChatViewport {
78
+ private elements: ViewportElements | null = null
79
+ private observer: ResizeObserver | null = null
80
+ private events: ViewportEvents | null = null
81
+ private turns: ReturnType<ChatSnapshot['navigation']['items']> = []
82
+ private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null }
83
+ private paging: PagingPosition | null = null
84
+ private historyPrepend: PagingPosition | null = null
85
+ private reader: FoldReader | null = null
86
+ private historyEdge: HTMLElement | null = null
87
+ private historyHeight = 0
88
+ private historyScrolling = new Set<EventTarget>()
89
+ private historyPointer = false
90
+ private historyTouch = false
91
+ /** Rows measured before an instant close; see {@link ChatViewport.keepAboveClosing}. */
92
+ private closing: ClosingLayout | null = null
93
+ /** Discards a closing measurement that no size observation consumed by the end of its frame. */
94
+ private closingFrame: number | null = null
95
+ /** Content height without fold room at the latest size observation: the content that frame painted. */
96
+ private settledContent = 0
97
+ /** The pending or running fold batch lands at the tail. */
98
+ private tailRequested = false
99
+ /** The tail request came from the reader's own input rather than from a content change. */
100
+ private tailInput = false
101
+ /** Switches the running batch to a tail landing; null while no batch runs. */
102
+ private retarget: (() => void) | null = null
103
+ /** Transition state and row callbacks owned by this viewport's attachment. */
104
+ readonly motion = createFlowMotion(
105
+ () => this.foldDriver(),
106
+ (active) => {
107
+ if (this.elements !== null) this.elements.scroller.style.overflowAnchor = active ? 'none' : ''
108
+ },
109
+ (element) => { this.measureClosing(element) },
110
+ )
111
+
112
+ /**
113
+ * Bind to the containing scrollport and observe content and viewport sizes.
114
+ * @param list - Chat root inside an optional shared conversation scrollport.
115
+ * @param column - ordered outer Node/Group boxes; its size changes invalidate cached landings.
116
+ */
117
+ attach(list: HTMLElement, column: HTMLElement): void {
118
+ this.detach()
119
+ const scroller = list.closest<HTMLElement>('[data-conversation-scroll]') ?? list
120
+ const composer = scroller.querySelector<HTMLElement>('[data-composer-seat]')
121
+ const spacer = list.querySelector<HTMLElement>('[data-chat-turn-spacer]')
122
+ const elements = { list, column, scroller, composer, spacer }
123
+ this.elements = elements
124
+ if (spacer !== null) spacer.style.height = ''
125
+ scroller.addEventListener('scroll', this.onHistoryScroll, { passive: true, capture: true })
126
+ scroller.addEventListener('pointerdown', this.onHistoryPointerDown, { passive: true, capture: true })
127
+ scroller.addEventListener('touchstart', this.onHistoryTouch, { passive: true, capture: true })
128
+ for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) {
129
+ scroller.ownerDocument.addEventListener(type, this.onHistoryRelease, true)
130
+ }
131
+ scroller.addEventListener('scroll', this.onScroll, { passive: true })
132
+ scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true, capture: true })
133
+ for (const type of READING_INTENTS) scroller.addEventListener(type, this.onIntent, { passive: true, capture: true })
134
+ if (typeof ResizeObserver !== 'undefined') {
135
+ this.observer = new ResizeObserver((entries) => {
136
+ if (this.elements !== elements) return
137
+ // Read while layout is still clean, before this callback writes room or scroll positions. Those writes
138
+ // leave the content height unchanged, so it is also the content this frame paints.
139
+ if (entries.some(entry => entry.target === elements.scroller)) this.historyHeight = elements.scroller.clientHeight
140
+ this.settledContent = elements.scroller.scrollHeight - this.spacerHeight()
141
+ this.keepAboveClosing()
142
+ this.reclaimBelow()
143
+ this.invalidate()
144
+ this.pruneHistoryScrolling()
145
+ this.events?.resize()
146
+ })
147
+ this.observer.observe(column)
148
+ this.observer.observe(scroller)
149
+ if (composer !== null) this.observer.observe(composer)
150
+ }
151
+ }
152
+
153
+ /** Disconnect DOM resources and clear observations for the detached view. */
154
+ detach(): void {
155
+ this.historyPrepend = null
156
+ this.stopPreserving()
157
+ this.motion.clear()
158
+ if (this.elements !== null) this.elements.scroller.style.overflowAnchor = ''
159
+ this.dropClosing()
160
+ const scroller = this.elements?.scroller
161
+ scroller?.removeEventListener('scroll', this.onHistoryScroll, true)
162
+ scroller?.removeEventListener('pointerdown', this.onHistoryPointerDown, true)
163
+ scroller?.removeEventListener('touchstart', this.onHistoryTouch, true)
164
+ for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) {
165
+ scroller?.ownerDocument.removeEventListener(type, this.onHistoryRelease, true)
166
+ }
167
+ this.historyHeight = 0
168
+ this.historyScrolling.clear()
169
+ this.historyPointer = false
170
+ this.historyTouch = false
171
+ this.elements?.scroller.removeEventListener('scroll', this.onScroll)
172
+ this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd, true)
173
+ for (const type of READING_INTENTS) this.elements?.scroller.removeEventListener(type, this.onIntent, true)
174
+ this.observer?.disconnect()
175
+ this.observer = null
176
+ this.elements = null
177
+ this.events = null
178
+ this.tailRequested = false
179
+ this.tailInput = false
180
+ this.retarget = null
181
+ this.turns = []
182
+ this.observation = { top: 0, landing: null }
183
+ }
184
+
185
+ /**
186
+ * Connect business policy without changing DOM listener ownership.
187
+ * @param events - business handlers for scroll and layout changes.
188
+ * @returns a disposer that disconnects only these handlers.
189
+ */
190
+ connect(events: ViewportEvents): () => void {
191
+ this.events = events
192
+ return () => { if (this.events === events) this.events = null }
193
+ }
194
+
195
+ /**
196
+ * Adopt the loaded turn anchors without querying the DOM.
197
+ * @param turns - ordered loaded turns from the committed Chat snapshot.
198
+ */
199
+ updateTurns(turns: ReturnType<ChatSnapshot['navigation']['items']>): void {
200
+ this.turns = turns
201
+ }
202
+
203
+ /**
204
+ * Resolve the tail from the committed turn index.
205
+ * @returns the latest loaded turn, or null for an empty window.
206
+ */
207
+ get latestTurn(): number | null {
208
+ return this.turns.at(-1)?.turn ?? null
209
+ }
210
+
211
+ /** Discard geometry-dependent landing knowledge while retaining scroll attribution. */
212
+ invalidate(): void {
213
+ this.observation.landing = null
214
+ }
215
+
216
+ private spacerHeight(): number {
217
+ const spacer = this.elements?.spacer
218
+ return spacer == null ? 0 : Number.parseFloat(spacer.style.height) || 0
219
+ }
220
+
221
+ private setSpacer(height: number): void {
222
+ const spacer = this.elements?.spacer
223
+ if (spacer == null) return
224
+ const next = height <= 0 ? '' : `${Math.ceil(height)}px`
225
+ if (spacer.style.height !== next) spacer.style.height = next
226
+ }
227
+
228
+ /**
229
+ * Connect the reading policy that fold batches consult.
230
+ * @param reader - follow intent and the tail-landing commit.
231
+ * @returns a disposer that disconnects only this reader.
232
+ */
233
+ bindReader(reader: FoldReader): () => void {
234
+ this.reader = reader
235
+ return () => { if (this.reader === reader) this.reader = null }
236
+ }
237
+
238
+ /**
239
+ * Land the pending or running fold batch at the tail instead of starting a separate scroll.
240
+ * @param follow - follow controller whose native animation yields to the batch.
241
+ * @param input - whether the reader's own input requests the landing; a content change, such as a Turn
242
+ * ending, requests it in place of the immediate follow.
243
+ * @returns whether a fold owns the tail movement.
244
+ */
245
+ followInputFold(follow: ScrollFollow, input: boolean): boolean {
246
+ // Rows still closing on CSS transitions after a batch have no batch to consume the request.
247
+ if (this.elements === null || this.reader === null || !this.motion.inputActive()) return false
248
+ this.interruptFollow(follow)
249
+ this.tailRequested = true
250
+ this.tailInput ||= input
251
+ this.retarget?.()
252
+ return true
253
+ }
254
+
255
+ /**
256
+ * Drive one fold batch on its frame clock. A tail landing ends at the floor, never above the reader's
257
+ * compensated position; a reader landing keeps the visible content still. Both install only the room
258
+ * the landing lacks.
259
+ * @returns the batch driver, or null while detached or without a reading policy.
260
+ */
261
+ private foldDriver(): InputFoldDriver | null {
262
+ const elements = this.elements
263
+ const reader = this.reader
264
+ if (elements === null || reader === null) return null
265
+ const { follow } = reader
266
+ let tail = false
267
+ let start = 0
268
+ let base = 0
269
+ let target = 0
270
+ let removed = 0
271
+ let growth = 0
272
+ let initialHeight = 0
273
+ let finalRoom = 0
274
+ let previousColumnHeight = 0
275
+ let previousProgress = 0
276
+ let segmentProgress = 0
277
+ let segmentTop = 0
278
+ let written = 0
279
+ const closing: InputFoldBox[] = []
280
+ const travelling = new Set<HTMLElement>()
281
+ // A visible row outside the batch measures spacing that snaps when the batch starts and ends.
282
+ let reference: HTMLElement | null = null
283
+ let referenceTop = 0
284
+ let viewportTop = 0
285
+ const screenTop = (element: HTMLElement): number => element.getBoundingClientRect().top - viewportTop
286
+ const aim = (): void => {
287
+ const finalHeight = initialHeight - removed + growth
288
+ const height = elements.scroller.clientHeight
289
+ target = tail ? Math.max(base, finalHeight - height, 0) : base
290
+ finalRoom = target === 0 ? 0 : Math.max(0, target + height - finalHeight)
291
+ }
292
+ const restart = (): void => {
293
+ segmentTop = elements.scroller.scrollTop
294
+ segmentProgress = previousProgress
295
+ }
296
+ const automatic = (cancelled: boolean): boolean => !(cancelled && tail)
297
+ const position = (progress: number, cancelled: boolean): number => {
298
+ if (!automatic(cancelled)) return elements.scroller.scrollTop
299
+ const remaining = segmentProgress === 1 ? 1 : (progress - segmentProgress) / (1 - segmentProgress)
300
+ return segmentTop + (target - segmentTop) * remaining
301
+ }
302
+ const room = (top: number, progress: number, cancelled: boolean): number => Math.max(
303
+ automatic(cancelled) ? finalRoom : 0,
304
+ top + elements.scroller.clientHeight - (initialHeight + (growth - removed) * progress),
305
+ )
306
+ return {
307
+ begin: (boxes) => {
308
+ // Own input lands at the tail; otherwise an unsampled reading movement outranks follow intent.
309
+ tail = this.tailRequested || (follow.active && !reader.pending())
310
+ const input = this.tailInput
311
+ this.tailRequested = false
312
+ this.tailInput = false
313
+ viewportTop = elements.scroller.getBoundingClientRect().top
314
+ start = elements.scroller.scrollTop
315
+ const originalRoom = this.spacerHeight()
316
+ initialHeight = Math.max(elements.column.offsetHeight, elements.scroller.scrollHeight - originalRoom)
317
+ if (tail && !input) {
318
+ // The batch replaces the immediate follow of a reader pinned to the tail, following content that
319
+ // overflows with no fold room: content that grew outside the batch since that paint, such as a Turn's
320
+ // duration control, is taken before the first frame as following takes streaming growth, so the
321
+ // batch only animates its own rows.
322
+ const pinned = originalRoom === 0 && this.settledContent > elements.scroller.clientHeight
323
+ && follow.active && !reader.pending() && !follow.animating
324
+ const external = elements.scroller.scrollHeight - originalRoom - this.settledContent
325
+ if (external > 0.5 && pinned) {
326
+ elements.scroller.scrollTop = start + external
327
+ start = elements.scroller.scrollTop
328
+ this.observation = { top: start, landing: null }
329
+ }
330
+ }
331
+ let above = 0
332
+ const below: HTMLElement[] = []
333
+ for (const box of boxes) {
334
+ const amount = box.height + box.marginTop
335
+ const top = box.element.getBoundingClientRect().top - box.marginTop
336
+ if (box.closing) {
337
+ removed += amount
338
+ above += Math.max(0, Math.min(amount, viewportTop - top))
339
+ if (top >= viewportTop) below.push(box.element)
340
+ closing.push(box)
341
+ } else {
342
+ growth += amount
343
+ if (top < viewportTop) above -= amount
344
+ }
345
+ }
346
+ if (!tail) reference = this.readingReference()
347
+ const referenceBefore = reference === null ? 0 : screenTop(reference)
348
+ elements.column.dataset.inputFold = ''
349
+ if (reference !== null) {
350
+ referenceTop = screenTop(reference)
351
+ above -= referenceTop - referenceBefore
352
+ }
353
+ base = Math.max(0, start - above)
354
+ segmentTop = start
355
+ written = start
356
+ previousColumnHeight = elements.column.offsetHeight
357
+ aim()
358
+ // This reserve only prevents an intermediate clamp; the final frame installs the exact deficit.
359
+ this.setSpacer(Math.max(originalRoom, finalRoom, removed))
360
+ if (tail) follow.setFollowing(true)
361
+ // A newer tail request also takes over a batch whose target a reading gesture cancelled.
362
+ this.retarget = () => {
363
+ tail = true
364
+ follow.setFollowing(true)
365
+ this.motion.resumeInput()
366
+ aim()
367
+ restart()
368
+ if (target <= segmentTop) return
369
+ for (const box of closing) {
370
+ // A box fading in place carries a visual translate; its layout position excludes it.
371
+ const shift = Number.parseFloat(box.element.style.translate.split(' ')[1] ?? '') || 0
372
+ if (box.element.getBoundingClientRect().top - shift - box.marginTop >= viewportTop) travelling.add(box.element)
373
+ }
374
+ }
375
+ // Scrolling forward past closing rows shows them shrinking; faded rows would leave their space empty.
376
+ if (tail && target > start) for (const element of below) travelling.add(element)
377
+ return travelling
378
+ },
379
+ prepare: (progress, cancelled) => {
380
+ if (this.elements !== elements) return
381
+ if (!tail) {
382
+ // Reader scrolling between frames moves the reading position the batch keeps still.
383
+ const drift = elements.scroller.scrollTop - written
384
+ if (Math.abs(drift) > 0.5) {
385
+ base = Math.max(0, base + drift)
386
+ segmentTop += drift
387
+ // The reference moves on screen with the reader's scroll; only layout changes are corrected.
388
+ referenceTop -= drift
389
+ aim()
390
+ }
391
+ }
392
+ const added = elements.column.offsetHeight - previousColumnHeight
393
+ if (added !== 0) {
394
+ initialHeight += added
395
+ aim()
396
+ restart()
397
+ }
398
+ const top = position(progress, cancelled)
399
+ // Growing the room before shrinking boxes avoids a native clamp between writes.
400
+ this.setSpacer(Math.max(this.spacerHeight(), room(top, progress, cancelled)))
401
+ },
402
+ frame: (progress, cancelled) => {
403
+ if (this.elements !== elements) return 0
404
+ const top = position(progress, cancelled)
405
+ elements.scroller.scrollTop = top
406
+ this.setSpacer(room(top, progress, cancelled))
407
+ written = elements.scroller.scrollTop
408
+ // Earlier frames keep the reference still; only its final position is compared at finish.
409
+ if (reference !== null && progress === 1) referenceTop = screenTop(reference)
410
+ if (automatic(cancelled)) this.observation = { top: written, landing: null }
411
+ previousColumnHeight = elements.column.offsetHeight
412
+ previousProgress = progress
413
+ return written - start
414
+ },
415
+ finish: (cancelled) => {
416
+ this.retarget = null
417
+ this.tailRequested = false
418
+ this.tailInput = false
419
+ if (this.elements !== elements) return
420
+ // Commit the final sibling margins while their fold transition override still applies.
421
+ void elements.column.offsetHeight
422
+ delete elements.column.dataset.inputFold
423
+ if (!tail || cancelled) {
424
+ if (!tail && reference?.isConnected === true && reference.closest('[hidden]') === null) {
425
+ // Committing the hidden rows settles their neighbours' spacing; keep the reference still.
426
+ const shift = screenTop(reference) - referenceTop
427
+ if (Math.abs(shift) > 0.5) {
428
+ const top = elements.scroller.scrollTop + shift
429
+ const content = elements.scroller.scrollHeight - this.spacerHeight()
430
+ this.setSpacer(Math.max(this.spacerHeight(), top + elements.scroller.clientHeight - content))
431
+ elements.scroller.scrollTop = top
432
+ }
433
+ }
434
+ const metrics = scrollMetrics(elements.scroller)
435
+ const height = elements.scroller.scrollHeight - this.spacerHeight()
436
+ this.setSpacer(metrics.top === 0 ? 0 : Math.max(0, metrics.top + metrics.height - height))
437
+ if (tail) this.invalidate()
438
+ else this.observation = { top: elements.scroller.scrollTop, landing: null }
439
+ return
440
+ }
441
+ // The estimate can differ from the committed layout, for example settled sibling spacing.
442
+ // Land on the actual content: never above the target, and at the real floor when content reaches past it.
443
+ const content = elements.scroller.scrollHeight - this.spacerHeight()
444
+ const clientHeight = elements.scroller.clientHeight
445
+ const top = Math.max(target, content - clientHeight, 0)
446
+ this.setSpacer(top === 0 ? 0 : Math.max(0, top + clientHeight - content))
447
+ elements.scroller.scrollTop = top
448
+ const metrics = scrollMetrics(elements.scroller)
449
+ const landing = { metrics, position: null, turn: this.latestTurn }
450
+ this.observation = { top: metrics.top, landing }
451
+ reader.landedAtTail(landing)
452
+ },
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Find the first visible top-level row at or below the scrollport top that holds no batch box.
458
+ * Binary search over the ordered top-level rows reads O(log n) boxes.
459
+ * @returns the reference row, or null when every visible row folds.
460
+ */
461
+ private readingReference(): HTMLElement | null {
462
+ const elements = this.elements
463
+ if (elements === null) return null
464
+ const viewport = elements.scroller.getBoundingClientRect()
465
+ // Slot anchors use display:contents: their children are the top-level rows.
466
+ const rows = (elements.column.querySelector(':scope > [data-slot="conversation.chat.flow"]') ?? elements.column).children
467
+ let low = 0
468
+ let high = rows.length
469
+ while (low < high) {
470
+ const middle = (low + high) >>> 1
471
+ if ((rows[middle] as Element).getBoundingClientRect().bottom > viewport.top) high = middle
472
+ else low = middle + 1
473
+ }
474
+ for (let index = low; index < rows.length; index++) {
475
+ const row = rows[index] as HTMLElement
476
+ if (row.hasAttribute('hidden')) continue
477
+ const rect = row.getBoundingClientRect()
478
+ if (rect.top >= viewport.bottom) return null
479
+ if (rect.height === 0 || rect.bottom <= viewport.top) continue
480
+ if (row.hasAttribute('data-chat-motion') || row.querySelector('[data-chat-motion]') !== null) continue
481
+ return row
482
+ }
483
+ return null
484
+ }
485
+
486
+ /**
487
+ * Measure, before the first row of a commit closes at once, the rows a following reader's shrink keeps
488
+ * still: the first row visible in the last painted layout, the rows after it that were on screen, and the
489
+ * rows above it within one scrollport.
490
+ * Rows above the closing rows keep their painted screen positions, which the commit did not move; the same
491
+ * commit can add rows between them and the closing rows, as a Turn's duration control does, so rows from
492
+ * the closing rows on are placed against the current end. Reads happen only when rows close, never on the
493
+ * following path's size observations. A measurement the same frame's size observation does not use is
494
+ * discarded after that frame.
495
+ * @param element - the first row of this commit to close.
496
+ */
497
+ private measureClosing(element: HTMLElement): void {
498
+ const elements = this.elements
499
+ const reader = this.reader
500
+ if (elements === null || reader === null || this.closing !== null || !element.isConnected) return
501
+ if (!reader.follow.active || reader.follow.animating || reader.pending()) return
502
+ if (this.paging !== null || this.motion.foldActive() || this.motion.inputActive()) return
503
+ const scroller = elements.scroller
504
+ const scrollHeight = scroller.scrollHeight
505
+ const height = scroller.clientHeight
506
+ // The commit has not moved the scroll position, so it is the painted one, within the follow threshold too.
507
+ const painted = scroller.scrollTop + height
508
+ const origin = scroller.getBoundingClientRect().top - scroller.scrollTop
509
+ const rows = (elements.column.querySelector(':scope > [data-slot="conversation.chat.flow"]') ?? elements.column).children
510
+ // End is the content end each row is placed against: painted for rows above the closing rows.
511
+ const end = (row: Element): number => row !== element && !row.contains(element)
512
+ && (element.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_PRECEDING) !== 0 ? painted : scrollHeight
513
+ const screen = (row: Element, offset: number): number => offset - origin - (end(row) - height)
514
+ let low = 0
515
+ let high = rows.length
516
+ while (low < high) {
517
+ const middle = (low + high) >>> 1
518
+ const row = rows[middle] as Element
519
+ if (screen(row, row.getBoundingClientRect().bottom) > 0) high = middle
520
+ else low = middle + 1
521
+ }
522
+ let first = -1
523
+ for (let index = low; index < rows.length && first < 0; index++) {
524
+ const row = rows[index] as HTMLElement
525
+ const rect = row.getBoundingClientRect()
526
+ if (screen(row, rect.top) >= height) break
527
+ if (rect.height > 0 && !row.hasAttribute('hidden')) first = index
528
+ }
529
+ if (first < 0) return
530
+ const anchors: ShrinkAnchor[] = []
531
+ const add = (row: HTMLElement, rect: DOMRect): void => {
532
+ if (rect.height > 0 && !row.hasAttribute('hidden')) anchors.push({ element: row, fromEnd: end(row) - (rect.top - origin) })
533
+ }
534
+ add(rows[first] as HTMLElement, (rows[first] as HTMLElement).getBoundingClientRect())
535
+ // When the first visible row closes, the reader's eyes are on the rows that follow it on screen.
536
+ for (let index = first + 1; index < rows.length; index++) {
537
+ const row = rows[index] as HTMLElement
538
+ const rect = row.getBoundingClientRect()
539
+ if (screen(row, rect.top) >= height) break
540
+ add(row, rect)
541
+ }
542
+ for (let index = first - 1; index >= 0; index--) {
543
+ const row = rows[index] as HTMLElement
544
+ const rect = row.getBoundingClientRect()
545
+ if (screen(row, rect.bottom) <= -height) break
546
+ add(row, rect)
547
+ }
548
+ this.closing = { rows: anchors, content: scrollHeight - this.spacerHeight() }
549
+ if (typeof requestAnimationFrame === 'function') {
550
+ // This frame's size observation runs before the second callback; nothing later may use the measurement.
551
+ this.closingFrame = requestAnimationFrame(() => {
552
+ this.closingFrame = requestAnimationFrame(() => {
553
+ this.closingFrame = null
554
+ this.closing = null
555
+ })
556
+ })
557
+ }
558
+ }
559
+
560
+ private dropClosing(): void {
561
+ this.closing = null
562
+ if (this.closingFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.closingFrame)
563
+ this.closingFrame = null
564
+ }
565
+
566
+ /**
567
+ * Keep a following reader's content still after rows closed at once, for example work details at Turn
568
+ * completion: the first visible row keeps its screen position, or, when it closed, the first surviving row
569
+ * that followed it on screen, else the nearest surviving row above it. Room below fills the gap, at most half
570
+ * the scrollport; beyond that the content end stops at the scrollport's middle. Called from the size
571
+ * observation, after layout and before paint; only the observation of the frame that closed the rows uses
572
+ * the measurement, and only while the reader still follows the tail with no fold batch, native animation,
573
+ * unsampled movement, or paging writing positions.
574
+ */
575
+ private keepAboveClosing(): void {
576
+ const closing = this.closing
577
+ const elements = this.elements
578
+ const reader = this.reader
579
+ if (closing === null) return
580
+ this.dropClosing()
581
+ if (elements === null || reader === null || !reader.follow.active || reader.follow.animating || reader.pending()) return
582
+ if (this.paging !== null || this.motion.foldActive() || this.motion.inputActive()) return
583
+ const scroller = elements.scroller
584
+ const content = scroller.scrollHeight - this.spacerHeight()
585
+ // Growth in the same commit can outweigh the closed rows; nothing then shrank to compensate.
586
+ if (content >= closing.content - 0.5) return
587
+ const height = scroller.clientHeight
588
+ const origin = scroller.getBoundingClientRect().top - scroller.scrollTop
589
+ const cap = height / 2
590
+ let top = content + cap - height
591
+ for (const row of closing.rows) {
592
+ if (!row.element.isConnected || row.element.closest('[hidden]') !== null) continue
593
+ const rect = row.element.getBoundingClientRect()
594
+ if (rect.height === 0) continue
595
+ top = rect.top - origin - (height - row.fromEnd)
596
+ break
597
+ }
598
+ if (top + height - content > cap) top = content + cap - height
599
+ top = Math.max(0, top)
600
+ this.setSpacer(top === 0 ? 0 : Math.max(0, top + height - content))
601
+ if (scroller.scrollTop !== top) scroller.scrollTop = top
602
+ const metrics = scrollMetrics(scroller)
603
+ this.observation = { top: metrics.top, landing: { metrics, position: null, turn: this.latestTurn } }
604
+ }
605
+
606
+ /** Clear fold reservations after a display-mode change, allowing the scroll range to shrink. */
607
+ resetBelow(): void {
608
+ this.dropClosing()
609
+ this.setSpacer(0)
610
+ this.invalidate()
611
+ }
612
+
613
+ /**
614
+ * Give reserved room back after acknowledged scrolling or content growth without clamping the reader.
615
+ * Holds still during folds and unsampled movement; following includes the room that remains.
616
+ */
617
+ reclaimBelow(): void {
618
+ const elements = this.elements
619
+ if (elements === null || elements.spacer === null) return
620
+ const current = this.spacerHeight()
621
+ if (current === 0 || this.motion.foldActive()) return
622
+ const scroll = this.readScroll()
623
+ // Trimming the range before sampling could misclassify a reader's move as a layout clamp.
624
+ if (scroll === null || scroll.movedByReader) return
625
+ const floorWithoutSpacer = scroll.metrics.floor - current
626
+ this.setSpacer(Math.min(current, Math.max(0, scroll.metrics.top - floorWithoutSpacer)))
627
+ }
628
+
629
+ /**
630
+ * Stop an outstanding native follow animation at its current position before a reading gesture.
631
+ * @param follow - follow controller bound to this scrollport.
632
+ */
633
+ interruptFollow(follow: ScrollFollow): void {
634
+ if (!follow.animating) return
635
+ const metrics = this.metrics()
636
+ if (metrics === null || this.elements === null) return
637
+ follow.interrupt(this.elements.scroller, metrics)
638
+ this.observation = { top: metrics.top, landing: null }
639
+ }
640
+
641
+ /**
642
+ * Accept a sampled reader position without retaining a known landing.
643
+ * @param metrics - settled reader position used as the next attribution baseline.
644
+ */
645
+ acknowledge(metrics: ViewportMetrics): void {
646
+ this.observation = { top: metrics.top, landing: null }
647
+ this.reclaimBelow()
648
+ }
649
+
650
+ /**
651
+ * Compare the current scroll geometry with the last acknowledged position.
652
+ * @returns current metrics and movement attribution, or null while detached.
653
+ */
654
+ readScroll(): ViewportScroll | null {
655
+ const metrics = this.metrics()
656
+ if (metrics === null) return null
657
+ return {
658
+ metrics,
659
+ movedByReader: Math.abs(metrics.top - Math.min(this.observation.top, metrics.floor)) > 0.5,
660
+ }
661
+ }
662
+
663
+ private metrics(): ViewportMetrics | null {
664
+ const scroller = this.elements?.scroller
665
+ if (scroller === undefined) return null
666
+ return scrollMetrics(scroller)
667
+ }
668
+
669
+ private anchor(key: string, identity: 'position' | 'node' = 'position'): HTMLElement | null {
670
+ if (this.elements === null) return null
671
+ // Reading anchors name exact parts; Turn navigation names the original Node.
672
+ let nodePart: HTMLElement | null = null
673
+ for (const row of this.elements.list.querySelectorAll<HTMLElement>('[data-chat-anchor-key]:not([hidden]):not([hidden] *)')) {
674
+ if (row.dataset.chatAnchorKey === key || (identity === 'node' && row.dataset.chatNodeKey === key)) return row
675
+ if (nodePart === null && row.dataset.chatNodeKey === key) nodePart = row
676
+ }
677
+ return nodePart
678
+ }
679
+
680
+ /**
681
+ * Capture visible transcript content, excluding Turn controls that relocate when history expands.
682
+ * @returns a visible semantic anchor, or null when no anchor can be resolved.
683
+ */
684
+ capturePosition(): ChatScrollPosition | null {
685
+ const elements = this.elements
686
+ if (elements === null) return null
687
+ const { list, scroller, composer } = elements
688
+ const viewport = scroller.getBoundingClientRect()
689
+ const bottom = composer?.getBoundingClientRect().top ?? viewport.bottom
690
+ let anchor: HTMLElement | null = null
691
+ if (typeof document.elementsFromPoint === 'function' && bottom > viewport.top) {
692
+ const content = list.getBoundingClientRect()
693
+ const left = Math.max(viewport.left, content.left)
694
+ const right = Math.min(viewport.right, content.right)
695
+ for (const element of document.elementsFromPoint(left + Math.max(0, right - left) / 2, viewport.top + 1)) {
696
+ const row = element instanceof HTMLElement ? element.closest<HTMLElement>('[data-chat-anchor-key]') : null
697
+ if (row !== null && row.dataset.chatFlowKind !== 'turn-process' && list.contains(row)) {
698
+ // An open group's header stays put while older members enter above its body content.
699
+ anchor = row.dataset.chatGroupKey === undefined ? row
700
+ : row.querySelector<HTMLElement>('[data-step-process-content] > [data-chat-anchor-key]:not(:empty):not([hidden]):not([hidden] *)') ?? row
701
+ break
702
+ }
703
+ }
704
+ }
705
+ if (anchor === null) {
706
+ const rows = list.querySelectorAll<HTMLElement>(
707
+ '[data-chat-flow-key]:not([data-chat-group-key]):not([data-chat-flow-kind="turn-process"])'
708
+ + ':not(:empty):not([hidden]):not([hidden] *)',
709
+ )
710
+ let low = 0
711
+ let high = rows.length
712
+ while (low < high) {
713
+ const middle = (low + high) >>> 1
714
+ if (rows.item(middle).getBoundingClientRect().bottom > viewport.top) high = middle
715
+ else low = middle + 1
716
+ }
717
+ const row = rows[low]
718
+ anchor = row !== undefined && row.getBoundingClientRect().top < bottom ? row : rows[0] ?? null
719
+ }
720
+ const key = anchor?.dataset.chatAnchorKey
721
+ return anchor === null || key === undefined ? null : {
722
+ anchorKey: key,
723
+ anchorTop: anchor.getBoundingClientRect().top - viewport.top,
724
+ scrollTop: scroller.scrollTop,
725
+ }
726
+ }
727
+
728
+ /**
729
+ * Approximate the active Turn by binary-searching outer Node/Group boxes.
730
+ * Gaps retain the last visited Turn candidate, not necessarily the immediate predecessor.
731
+ * A known landing bypasses measurement while its position is unchanged.
732
+ * @param metrics - reusable scroll metrics; omitted callers request a fresh read.
733
+ * @returns the Turn near the reading line, or null while detached or empty.
734
+ */
735
+ readVisibleTurn(metrics = this.metrics()): number | null {
736
+ const knownTurn = this.observation.landing?.turn
737
+ if (knownTurn != null && metrics?.top === this.observation.top) return knownTurn
738
+ const elements = this.elements
739
+ const first = this.turns[0]
740
+ if (elements === null || metrics === null || first === undefined) return null
741
+ const line = elements.scroller.getBoundingClientRect().top + Math.min(96, metrics.height * 0.2)
742
+ // Slot anchors use display:contents: measure their rows, not the anchor's empty box.
743
+ const rows = (elements.column.querySelector(':scope > [data-slot="conversation.chat.flow"]') ?? elements.column).children
744
+ let low = 0
745
+ let high = rows.length
746
+ let reading = first.turn
747
+ while (low < high) {
748
+ const middle = (low + high) >>> 1
749
+ const row = rows[middle] as Element
750
+ if (row.getBoundingClientRect().top > line) high = middle
751
+ else {
752
+ const value = row.getAttribute('data-chat-turn')
753
+ const turn = value === null ? NaN : Number(value)
754
+ if (Number.isSafeInteger(turn)) reading = turn
755
+ low = middle + 1
756
+ }
757
+ }
758
+ return reading
759
+ }
760
+
761
+ /**
762
+ * Align a known loaded turn and return its actual clamped position.
763
+ * A split Node anchor selects its first visible part.
764
+ * @param turn - loaded turn to align below the scrollport's top edge.
765
+ * @returns the actual landing, or null when its anchor is unavailable.
766
+ */
767
+ scrollToTurn(turn: number): ViewportLanding | null {
768
+ const item = this.turns.find(candidate => candidate.turn === turn)
769
+ if (item === undefined) return null
770
+ const row = this.anchor(item.anchorKey, 'node')
771
+ return row === null ? null : this.align(row, 24, turn)
772
+ }
773
+
774
+ /**
775
+ * Align the nearest available fallback for an unavailable turn anchor.
776
+ * @param turn - minimum turn number for a mounted fallback row.
777
+ * @returns the fallback landing, or null when no eligible row exists.
778
+ */
779
+ scrollToTurnAtOrAfter(turn: number): ViewportLanding | null {
780
+ if (this.elements === null) return null
781
+ for (const row of this.elements.list.querySelectorAll<HTMLElement>('[data-chat-turn]:not([hidden]):not([hidden] *)')) {
782
+ const candidate = Number(row.dataset.chatTurn)
783
+ if (Number.isSafeInteger(candidate) && candidate >= turn) return this.align(row, 24, candidate)
784
+ }
785
+ return null
786
+ }
787
+
788
+ /**
789
+ * Restore a semantic anchor with a raw-position fallback.
790
+ * @param position - semantic scroll memory; raw top is used only if its row is absent.
791
+ * @returns the actual landing, or null while detached.
792
+ */
793
+ restore(position: ChatScrollPosition): ViewportLanding | null {
794
+ const row = this.anchor(position.anchorKey)
795
+ if (row !== null) return this.align(row, position.anchorTop, null)
796
+ const metrics = this.metrics()
797
+ return metrics === null ? null : this.write(position.scrollTop, metrics, null)
798
+ }
799
+
800
+ /** Capture a manual paging anchor without consulting automatic-consumption blockers. */
801
+ beginManualPaging(): void {
802
+ if (this.elements === null) return
803
+ if (this.elements.scroller.scrollTop <= 0.5) this.beginPaging()
804
+ else {
805
+ this.beginPreserving()
806
+ if (!this.preserving) this.beginPaging()
807
+ }
808
+ }
809
+
810
+ /** Retain the first eligible transcript seat in DOM order; selection reads no geometry. */
811
+ beginPaging(): void {
812
+ this.stopPreserving()
813
+ const row = this.pagingAnchor()
814
+ if (row !== null) this.retain(row)
815
+ }
816
+
817
+ private pagingAnchor(): HTMLElement | null {
818
+ return this.elements?.list.querySelector<HTMLElement>(
819
+ '[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)',
820
+ ) ?? null
821
+ }
822
+
823
+ /**
824
+ * Retain one old row and its inner/outer offsets for paging and later content growth.
825
+ * @param position - an explicit landing to retain; omitted callers capture the current reading position.
826
+ */
827
+ beginPreserving(position: ChatScrollPosition | null = this.capturePosition()): void {
828
+ this.stopPreserving()
829
+ if (position === null) return
830
+ const row = this.anchor(position.anchorKey)
831
+ if (row === null) return
832
+ this.retain(row, position)
833
+ }
834
+
835
+ private measurePaging(row: HTMLElement, position?: ChatScrollPosition, previousGroup?: PagingPosition['group']): PagingPosition | null {
836
+ const elements = this.elements
837
+ const key = row.dataset.chatAnchorKey
838
+ if (elements === null || key === undefined) return null
839
+ const top = row.getBoundingClientRect().top
840
+ const body = row.closest<HTMLElement>('[data-step-process-body]')
841
+ const content = body?.querySelector<HTMLElement>('[data-step-process-content]')
842
+ const group = body === null || content == null ? null
843
+ : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top }
844
+ return {
845
+ row, group,
846
+ position: position ?? {
847
+ anchorKey: key,
848
+ anchorTop: top - elements.scroller.getBoundingClientRect().top,
849
+ scrollTop: elements.scroller.scrollTop,
850
+ },
851
+ }
852
+ }
853
+
854
+ private retain(row: HTMLElement, position?: ChatScrollPosition): PagingPosition | null {
855
+ const paging = this.measurePaging(row, position)
856
+ if (paging === null) return null
857
+ this.retainPaging(paging)
858
+ return paging
859
+ }
860
+
861
+ private retainPaging(paging: PagingPosition): void {
862
+ this.stopPreserving()
863
+ this.paging = paging
864
+ if (paging.group !== null) this.observer?.observe(paging.group.content)
865
+ }
866
+
867
+ /** Release paging ownership and its content-size observation. */
868
+ stopPreserving(): void {
869
+ const group = this.paging?.group
870
+ if (group != null) this.observer?.unobserve(group.content)
871
+ this.paging = null
872
+ }
873
+
874
+ /**
875
+ * Expose retained paging ownership to navigation and resize policy.
876
+ * @returns whether a paging row is retained for subsequent layout changes.
877
+ */
878
+ get preserving(): boolean { return this.paging !== null }
879
+
880
+ /**
881
+ * Compensate inner scrolling first, then the outer scrollport, within their actual scroll ranges.
882
+ * An inner write pauses its bound follow controller so the reading anchor takes priority.
883
+ * @returns the actual landing, or null when no visible retained row remains.
884
+ */
885
+ preserve(): ViewportLanding | null {
886
+ const paging = this.resolvePaging(this.paging)
887
+ if (paging === null) {
888
+ this.stopPreserving()
889
+ return null
890
+ }
891
+ if (paging !== this.paging) this.retainPaging(paging)
892
+ return this.applyPaging(paging)
893
+ }
894
+
895
+ private resolvePaging(paging: PagingPosition | null): PagingPosition | null {
896
+ const elements = this.elements
897
+ if (paging === null || elements === null) return null
898
+ if (!elements.list.contains(paging.row)) {
899
+ // Segmentation can remount the same semantic row under another group.
900
+ const replacement = this.anchor(paging.position.anchorKey)
901
+ if (replacement === null) return null
902
+ paging = this.measurePaging(replacement, paging.position, paging.group)
903
+ if (paging === null) return null
904
+ }
905
+ return paging.row.closest('[hidden]') !== null || paging.row.matches(':empty') ? null : paging
906
+ }
907
+
908
+ /** Restore the captured screen position; native anchoring already applied to this change needs no further correction. */
909
+ private applyPaging(paging: PagingPosition): ViewportLanding | null {
910
+ const elements = this.elements
911
+ if (elements === null) return null
912
+ const { row, group, position } = paging
913
+ if (group !== null && group.body.contains(row)) {
914
+ const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top
915
+ const metrics = scrollMetrics(group.body)
916
+ const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top))
917
+ if (metrics.top !== target) {
918
+ const follow = ScrollFollow.forElement(group.body)
919
+ if (follow === undefined) group.body.scrollTop = target
920
+ else {
921
+ follow.jump(group.body, metrics, target)
922
+ follow.setFollowing(false)
923
+ }
924
+ }
925
+ }
926
+ const metrics = this.metrics()
927
+ if (metrics === null) return null
928
+ const top = row.getBoundingClientRect().top - elements.scroller.getBoundingClientRect().top
929
+ const target = metrics.top + top - position.anchorTop
930
+ return this.write(target, metrics, null, { key: position.anchorKey, top })
931
+ }
932
+
933
+ /**
934
+ * Align with the physical floor, including fold room that newer content has not yet filled.
935
+ * @param follow - independent follow intent and scrolling controller.
936
+ * @param behavior - immediate positioning, or one native animation for a reader-caused tail change.
937
+ * @returns the actual floor landing, or null while detached. A smooth landing reports the starting
938
+ * position; native scroll delivery moves it.
939
+ */
940
+ scrollToBottom(follow: ScrollFollow, behavior: 'instant' | 'smooth' = 'instant'): ViewportLanding | null {
941
+ const metrics = this.metrics()
942
+ if (metrics === null || this.elements === null) return null
943
+ this.observation = { top: metrics.top, landing: null }
944
+ this.reclaimBelow()
945
+ const landing: ViewportLanding = {
946
+ metrics: follow.toBottom(this.elements.scroller, scrollMetrics(this.elements.scroller), behavior),
947
+ position: null,
948
+ turn: this.latestTurn,
949
+ }
950
+ this.observation = { top: landing.metrics.top, landing }
951
+ return landing
952
+ }
953
+
954
+ private align(row: HTMLElement, offset: number, turn: number | null): ViewportLanding | null {
955
+ const metrics = this.metrics()
956
+ if (metrics === null || this.elements === null) return null
957
+ const top = row.getBoundingClientRect().top - this.elements.scroller.getBoundingClientRect().top
958
+ return this.write(metrics.top + top - offset, metrics, turn, { key: row.dataset.chatAnchorKey, top })
959
+ }
960
+
961
+ private write(
962
+ target: number, metrics: ViewportMetrics, turn: number | null,
963
+ anchor?: { key: string | undefined; top: number },
964
+ ): ViewportLanding | null {
965
+ if (this.elements === null) return null
966
+ const top = Math.max(0, Math.min(metrics.floor, target))
967
+ if (top !== metrics.top) this.elements.scroller.scrollTop = top
968
+ const actual = this.elements.scroller.scrollTop
969
+ const landing: ViewportLanding = {
970
+ metrics: { ...metrics, top: actual },
971
+ turn,
972
+ position: anchor?.key === undefined ? null : {
973
+ anchorKey: anchor.key,
974
+ anchorTop: anchor.top - (actual - metrics.top),
975
+ scrollTop: actual,
976
+ },
977
+ }
978
+ this.observation = { top: actual, landing }
979
+ return landing
980
+ }
981
+
982
+ /**
983
+ * Track the history control for request-distance checks.
984
+ * @param element - stable history control, or null when its view unmounts.
985
+ */
986
+ readonly setHistoryEdge = (element: HTMLDivElement | null): void => {
987
+ this.historyEdge = element
988
+ }
989
+
990
+ private pruneHistoryScrolling(): void {
991
+ for (const target of this.historyScrolling) {
992
+ if (!(target instanceof HTMLElement) || this.elements?.scroller.contains(target) !== true) {
993
+ this.historyScrolling.delete(target)
994
+ }
995
+ }
996
+ }
997
+
998
+ /**
999
+ * Confirm the actual history distance immediately before an automatic request.
1000
+ * @returns whether the control is within two viewport heights.
1001
+ */
1002
+ confirmHistoryStart(): boolean {
1003
+ const scroller = this.elements?.scroller
1004
+ if (scroller === undefined || this.historyEdge === null || this.historyHeight <= 0) return false
1005
+ const distance = scroller.getBoundingClientRect().top - this.historyEdge.getBoundingClientRect().bottom
1006
+ return distance <= this.historyHeight * 2
1007
+ }
1008
+
1009
+ /**
1010
+ * Expose held input to history status copy.
1011
+ * @returns whether a touch or pointer remains down.
1012
+ */
1013
+ get historyInputHeld(): boolean { return this.historyTouch || this.historyPointer }
1014
+
1015
+ /**
1016
+ * Select consumption behavior from current input and motion state.
1017
+ * @returns the blocker or positioning path for a prepared page.
1018
+ */
1019
+ historyConsumption(): 'motion' | 'touch' | 'pointer' | 'inner-scroll' | 'unavailable' | 'native' | 'preserve' | 'prepend' {
1020
+ const elements = this.elements
1021
+ if (elements === null) return 'unavailable'
1022
+ if (this.historyTouch) return 'touch'
1023
+ if (this.historyScrolling.size > 0
1024
+ && (this.historyScrolling.size !== 1 || !this.historyScrolling.has(elements.scroller))) return 'inner-scroll'
1025
+ if (this.motion.active() || this.reader?.follow.animating) return 'motion'
1026
+ if (this.historyPointer) return 'pointer'
1027
+ if (this.historyScrolling.size === 0) return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'preserve'
1028
+ if (this.preserving || typeof CSS === 'undefined' || !CSS.supports('overflow-anchor', 'auto')) return 'unavailable'
1029
+ return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'native'
1030
+ }
1031
+
1032
+ /**
1033
+ * Capture one top-edge prepend anchor without acquiring continuous scroll ownership.
1034
+ * @returns whether an old paging row was captured.
1035
+ */
1036
+ beginHistoryPrepend(): boolean {
1037
+ const row = this.pagingAnchor()
1038
+ this.historyPrepend = row === null ? null : this.measurePaging(row)
1039
+ return this.historyPrepend !== null
1040
+ }
1041
+
1042
+ /** Clear an unapplied one-shot correction when its page was not consumed. */
1043
+ cancelHistoryPrepend(): void { this.historyPrepend = null }
1044
+
1045
+ /**
1046
+ * Correct a committed prepend once, then release positioning ownership.
1047
+ * @returns the compensated landing for reading memory, or null when no anchor remains.
1048
+ */
1049
+ finishHistoryPrepend(): ViewportLanding | null {
1050
+ const pending = this.historyPrepend
1051
+ this.historyPrepend = null
1052
+ const paging = this.resolvePaging(pending)
1053
+ return paging === null ? null : this.applyPaging(paging)
1054
+ }
1055
+
1056
+ private readonly onHistoryScroll = (event: Event): void => {
1057
+ if (event.target === this.elements?.scroller || event.target instanceof HTMLElement
1058
+ && event.target.hasAttribute('data-step-process-body')) {
1059
+ this.historyScrolling.add(event.target)
1060
+ }
1061
+ }
1062
+
1063
+ private readonly onHistoryPointerDown = (): void => {
1064
+ this.historyPointer = true
1065
+ this.events?.history?.()
1066
+ }
1067
+ private readonly onHistoryTouch = (): void => {
1068
+ this.historyTouch = true
1069
+ this.events?.history?.()
1070
+ }
1071
+ private readonly onHistoryRelease = (event: Event): void => {
1072
+ if (event.type === 'pointerup' || event.type === 'pointercancel') this.historyPointer = false
1073
+ if (event.type === 'touchend' || event.type === 'touchcancel') {
1074
+ this.historyTouch = typeof TouchEvent !== 'undefined' && event instanceof TouchEvent && event.touches.length > 0
1075
+ }
1076
+ this.events?.history?.()
1077
+ }
1078
+
1079
+ private readonly onScroll = (event: Event): void => {
1080
+ if (this.elements === null || event.target !== this.elements.scroller) return
1081
+ if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return
1082
+ this.invalidate()
1083
+ if (this.paging !== null) {
1084
+ this.events?.resize()
1085
+ return
1086
+ }
1087
+ const scroll = this.readScroll()
1088
+ if (scroll !== null) this.events?.scroll(scroll)
1089
+ }
1090
+
1091
+ private readonly onScrollEnd = (event: Event): void => {
1092
+ if (event.target !== null) this.historyScrolling.delete(event.target)
1093
+ this.events?.history?.()
1094
+ if (event.target === this.elements?.scroller) {
1095
+ this.events?.scrollEnd(true)
1096
+ this.reclaimBelow()
1097
+ } else if (event.target instanceof HTMLElement && event.target.hasAttribute('data-step-process-body')) this.events?.scrollEnd(false)
1098
+ }
1099
+
1100
+ private readonly onIntent = (event: Event): void => {
1101
+ if (event.type === 'keydown' || event.type === 'pointerdown') {
1102
+ if (event.target instanceof Element && event.target.closest('[data-composer-seat]') !== null) return
1103
+ if (event.type === 'keydown' && (!(event instanceof KeyboardEvent) || !SCROLL_KEYS.has(event.key))) return
1104
+ }
1105
+ this.events?.intent?.()
1106
+ if (this.paging === null) return
1107
+ this.stopPreserving()
1108
+ this.events?.interact()
1109
+ }
1110
+ }
1111
+
1112
+ /**
1113
+ * Bind viewport resource ownership to the component's layout lifetime.
1114
+ * @returns one viewport owner and the element refs attached for this mount.
1115
+ */
1116
+ export function useChatViewport(): {
1117
+ viewport: ChatViewport
1118
+ listRef: RefObject<HTMLDivElement>
1119
+ columnRef: RefObject<HTMLDivElement>
1120
+ } {
1121
+ const listRef = useRef<HTMLDivElement | null>(null)
1122
+ const columnRef = useRef<HTMLDivElement | null>(null)
1123
+ const [viewport] = useState(() => new ChatViewport())
1124
+ useLayoutEffect(() => {
1125
+ if (listRef.current === null || columnRef.current === null) return
1126
+ viewport.attach(listRef.current, columnRef.current)
1127
+ return () => { viewport.detach() }
1128
+ }, [viewport])
1129
+ return { viewport, listRef, columnRef }
1130
+ }