@opengeni/react 6.1.0 → 7.0.0-canary.35625901699001

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 (214) hide show
  1. package/README.md +83 -2
  2. package/dist/approvals.d.ts +2 -1
  3. package/dist/artifacts-document.js +1 -1
  4. package/dist/artifacts-presentation.js +1 -1
  5. package/dist/artifacts-spreadsheet.js +1 -1
  6. package/dist/artifacts.js +3 -3
  7. package/dist/{browser-viewer-NTD6UIPR.js → browser-viewer-LGH4IP47.js} +3 -3
  8. package/dist/capability-catalog-row.d.ts +20 -0
  9. package/dist/capability-logo-fallback.d.ts +3 -0
  10. package/dist/{chunk-NOSYBS2D.js → chunk-2VHARTBL.js} +2 -1
  11. package/dist/{chunk-VRBL3F5E.js → chunk-5GAL23FF.js} +10 -2
  12. package/dist/{chunk-VRBL3F5E.js.map → chunk-5GAL23FF.js.map} +1 -1
  13. package/dist/chunk-5UONOQ3Y.js +635 -0
  14. package/dist/chunk-5UONOQ3Y.js.map +1 -0
  15. package/dist/{chunk-NYESIADM.js → chunk-AKOMC3VO.js} +3 -3
  16. package/dist/chunk-AKOMC3VO.js.map +1 -0
  17. package/dist/chunk-BRM6FVZA.js +302 -0
  18. package/dist/chunk-BRM6FVZA.js.map +1 -0
  19. package/dist/{chunk-KANFU34B.js → chunk-DBPVUGQT.js} +11 -2
  20. package/dist/chunk-DBPVUGQT.js.map +1 -0
  21. package/dist/chunk-FHIGTPME.js +1589 -0
  22. package/dist/chunk-FHIGTPME.js.map +1 -0
  23. package/dist/{chunk-5M6VTFJ5.js → chunk-GBPCZH3Y.js} +2 -2
  24. package/dist/{chunk-YBM6CQRU.js → chunk-GEN54DU5.js} +4 -4
  25. package/dist/{chunk-UMECRJRV.js → chunk-HJ5VJ4JB.js} +21 -12
  26. package/dist/chunk-HJ5VJ4JB.js.map +1 -0
  27. package/dist/{chunk-R4KRSFGA.js → chunk-IP4BUBKH.js} +3 -3
  28. package/dist/{chunk-NLTS7JHI.js → chunk-JPHDWKZE.js} +5 -5
  29. package/dist/{chunk-TDSEILUH.js → chunk-MI6ALLLD.js} +1297 -1535
  30. package/dist/chunk-MI6ALLLD.js.map +1 -0
  31. package/dist/{chunk-ICA6R6TW.js → chunk-OWHPKAOV.js} +28 -20
  32. package/dist/chunk-OWHPKAOV.js.map +1 -0
  33. package/dist/{chunk-24M4YBCL.js → chunk-PNAVEK2U.js} +4 -4
  34. package/dist/{chunk-L2NBTKRX.js → chunk-TXCBE32L.js} +203 -19
  35. package/dist/chunk-TXCBE32L.js.map +1 -0
  36. package/dist/{chunk-45XEUVTK.js → chunk-UXE5SSNN.js} +293 -463
  37. package/dist/chunk-UXE5SSNN.js.map +1 -0
  38. package/dist/{chunk-PEI6RANI.js → chunk-VR4Z73EU.js} +203 -9
  39. package/dist/chunk-VR4Z73EU.js.map +1 -0
  40. package/dist/{chunk-HUIKIDM5.js → chunk-XMXRI5JK.js} +65 -18
  41. package/dist/chunk-XMXRI5JK.js.map +1 -0
  42. package/dist/client.d.ts +1 -1
  43. package/dist/components/artifacts/spreadsheet-general-display.d.ts +24 -0
  44. package/dist/components/chat-composer.d.ts +13 -3
  45. package/dist/components/markdown.d.ts +6 -3
  46. package/dist/components/message-timeline.d.ts +7 -2
  47. package/dist/components/preview-loading.d.ts +2 -0
  48. package/dist/components/session-capability-frame.d.ts +24 -0
  49. package/dist/components/session-chrome.d.ts +1 -2
  50. package/dist/components/session-commands.d.ts +6 -0
  51. package/dist/components/session-connection-request.d.ts +8 -0
  52. package/dist/components/session-conversation.d.ts +3 -0
  53. package/dist/components/session-mcp-capability-card.d.ts +22 -0
  54. package/dist/components/timeline-search.d.ts +34 -0
  55. package/dist/composer.js +7 -7
  56. package/dist/connect-account-identity.d.ts +8 -0
  57. package/dist/connect-accounts.d.ts +5 -0
  58. package/dist/connect-chooser.d.ts +6 -0
  59. package/dist/connect-panel.d.ts +9 -2
  60. package/dist/connect-setup.d.ts +5 -1
  61. package/dist/connect.d.ts +5 -21
  62. package/dist/connect.js +1268 -584
  63. package/dist/connect.js.map +1 -1
  64. package/dist/connection-catalog.d.ts +6 -1
  65. package/dist/connection-discovery.d.ts +12 -0
  66. package/dist/connection-installed.d.ts +1 -0
  67. package/dist/connection-logo.d.ts +5 -2
  68. package/dist/connection-service-logo.d.ts +8 -0
  69. package/dist/connection-service-presentation.d.ts +13 -0
  70. package/dist/connection-skeleton.d.ts +5 -0
  71. package/dist/discovery-cache.d.ts +5 -0
  72. package/dist/hooks/use-codex-accounts.d.ts +11 -5
  73. package/dist/hooks/use-connect.d.ts +22 -0
  74. package/dist/hooks/use-session-events.d.ts +5 -0
  75. package/dist/hooks/use-session-mcp-approval-policy.d.ts +2 -2
  76. package/dist/hooks/use-workspace-sessions.d.ts +2 -0
  77. package/dist/index.d.ts +8 -2
  78. package/dist/index.js +771 -793
  79. package/dist/index.js.map +1 -1
  80. package/dist/interaction.js +2 -2
  81. package/dist/machines.js +2 -2
  82. package/dist/mcp-connection-status.d.ts +14 -0
  83. package/dist/{model-policy-picker-menu-3R336DP2.js → model-policy-picker-menu-RVOQ4ZZG.js} +4 -4
  84. package/dist/model-policy.d.ts +6 -2
  85. package/dist/model-policy.js +1 -1
  86. package/dist/{platform-activity-row-DUE2W74J.js → platform-activity-row-HLOH7FW4.js} +9 -4
  87. package/dist/platform-activity-row-HLOH7FW4.js.map +1 -0
  88. package/dist/plugin-discovery.d.ts +6 -0
  89. package/dist/{queue-surface-implementation-LK3S4BIW.js → queue-surface-implementation-3RIFK2BS.js} +4 -4
  90. package/dist/realtime.js +22 -22
  91. package/dist/realtime.js.map +1 -1
  92. package/dist/session-auth-recommendation.d.ts +5 -0
  93. package/dist/session-capability-policy.d.ts +12 -0
  94. package/dist/session-ui.d.ts +2 -0
  95. package/dist/session-ui.js +14 -12
  96. package/dist/session.d.ts +1 -0
  97. package/dist/session.js +6 -4
  98. package/dist/skill-discovery.d.ts +11 -0
  99. package/dist/timeline/compaction-copy.d.ts +10 -0
  100. package/dist/timeline/projection.d.ts +3 -1
  101. package/dist/timeline/tool-display-name.d.ts +2 -1
  102. package/dist/timeline/turn-summary.d.ts +2 -2
  103. package/dist/timeline/types.d.ts +24 -2
  104. package/dist/{timeline-annotation-markers-DRSTLEM6.js → timeline-annotation-markers-OY6OWR3V.js} +2 -2
  105. package/dist/{timeline-annotation-selection-IHLUGVND.js → timeline-annotation-selection-BOXA2TIN.js} +2 -2
  106. package/dist/{timeline-annotations-dialog-6Q53N5FG.js → timeline-annotations-dialog-RGY3MHL3.js} +3 -3
  107. package/package.json +3 -3
  108. package/src/approvals.ts +8 -1
  109. package/src/assets/README.md +8 -0
  110. package/src/assets/gmail.ico +0 -0
  111. package/src/assets/outlook.ico +0 -0
  112. package/src/capability-catalog-row.tsx +94 -0
  113. package/src/capability-logo-fallback.ts +22 -0
  114. package/src/client.ts +0 -9
  115. package/src/components/approval-surface.tsx +12 -2
  116. package/src/components/artifacts/document-editor.tsx +63 -6
  117. package/src/components/artifacts/presentation-editor.tsx +214 -9
  118. package/src/components/artifacts/spreadsheet-canvas.ts +3 -8
  119. package/src/components/artifacts/spreadsheet-general-display.ts +43 -0
  120. package/src/components/artifacts/spreadsheet-grid.tsx +10 -11
  121. package/src/components/chat-composer.tsx +26 -3
  122. package/src/components/composer.tsx +10 -4
  123. package/src/components/human-input-form.tsx +12 -2
  124. package/src/components/markdown.tsx +133 -9
  125. package/src/components/message-timeline.tsx +104 -36
  126. package/src/components/model-picker.tsx +11 -3
  127. package/src/components/model-policy-picker-menu.tsx +10 -3
  128. package/src/components/preview-loading.tsx +154 -0
  129. package/src/components/sandbox-workspace.tsx +20 -36
  130. package/src/components/session-capability-frame.tsx +163 -0
  131. package/src/components/session-chrome.tsx +46 -77
  132. package/src/components/session-commands.tsx +18 -0
  133. package/src/components/session-connection-request.tsx +97 -0
  134. package/src/components/session-conversation.tsx +10 -5
  135. package/src/components/session-mcp-capability-card.tsx +532 -0
  136. package/src/components/session-status.tsx +2 -2
  137. package/src/components/timeline-anchor.tsx +9 -8
  138. package/src/components/timeline-search.tsx +168 -0
  139. package/src/components/user-message-body.tsx +7 -0
  140. package/src/connect-account-identity.tsx +34 -0
  141. package/src/connect-accounts.tsx +114 -52
  142. package/src/connect-chooser.tsx +171 -39
  143. package/src/connect-panel.tsx +73 -9
  144. package/src/connect-setup.tsx +72 -25
  145. package/src/connect.ts +13 -22
  146. package/src/connection-assets.d.ts +4 -0
  147. package/src/connection-catalog.tsx +61 -39
  148. package/src/connection-discovery.tsx +235 -0
  149. package/src/connection-installed.tsx +2 -0
  150. package/src/connection-logo.tsx +18 -10
  151. package/src/connection-service-logo.tsx +55 -0
  152. package/src/connection-service-presentation.ts +46 -0
  153. package/src/connection-skeleton.tsx +16 -0
  154. package/src/conversation-timeline.ts +1 -0
  155. package/src/discovery-cache.ts +42 -0
  156. package/src/hooks/use-codex-accounts.ts +33 -14
  157. package/src/hooks/use-composer.ts +4 -5
  158. package/src/hooks/use-connect.ts +23 -0
  159. package/src/hooks/use-session-events.ts +114 -1
  160. package/src/hooks/use-session-mcp-approval-policy.ts +13 -5
  161. package/src/hooks/use-workspace-sessions.ts +10 -0
  162. package/src/index.ts +22 -2
  163. package/src/mcp-connection-status.ts +35 -0
  164. package/src/model-policy.ts +21 -0
  165. package/src/plugin-details.tsx +8 -5
  166. package/src/plugin-discovery.tsx +92 -72
  167. package/src/realtime/realtime-control.tsx +6 -8
  168. package/src/session-auth-recommendation.ts +48 -0
  169. package/src/session-capability-policy.ts +83 -0
  170. package/src/session-ui.ts +2 -0
  171. package/src/session.ts +1 -0
  172. package/src/skill-discovery.tsx +101 -56
  173. package/src/timeline/compaction-copy.ts +40 -0
  174. package/src/timeline/platform-activity-row.tsx +8 -3
  175. package/src/timeline/projection.ts +78 -2
  176. package/src/timeline/rolling-activity.tsx +4 -2
  177. package/src/timeline/shared.tsx +6 -1
  178. package/src/timeline/startup-timings.tsx +1 -1
  179. package/src/timeline/tool-display-name.ts +8 -6
  180. package/src/timeline/tool-renderers.tsx +5 -3
  181. package/src/timeline/turn-summary.tsx +17 -3
  182. package/src/timeline/types.ts +24 -2
  183. package/styles/compiled.css +325 -27
  184. package/styles/connect.css +90 -15
  185. package/styles/index.css +46 -0
  186. package/styles/session-capability.css +42 -0
  187. package/dist/chunk-45XEUVTK.js.map +0 -1
  188. package/dist/chunk-HQV2I5HV.js +0 -124
  189. package/dist/chunk-HQV2I5HV.js.map +0 -1
  190. package/dist/chunk-HUIKIDM5.js.map +0 -1
  191. package/dist/chunk-ICA6R6TW.js.map +0 -1
  192. package/dist/chunk-IHQII5WO.js +0 -886
  193. package/dist/chunk-IHQII5WO.js.map +0 -1
  194. package/dist/chunk-KANFU34B.js.map +0 -1
  195. package/dist/chunk-L2NBTKRX.js.map +0 -1
  196. package/dist/chunk-NYESIADM.js.map +0 -1
  197. package/dist/chunk-PEI6RANI.js.map +0 -1
  198. package/dist/chunk-TDSEILUH.js.map +0 -1
  199. package/dist/chunk-UMECRJRV.js.map +0 -1
  200. package/dist/hooks/use-packs.d.ts +0 -32
  201. package/dist/platform-activity-row-DUE2W74J.js.map +0 -1
  202. package/src/hooks/use-packs.ts +0 -157
  203. /package/dist/{browser-viewer-NTD6UIPR.js.map → browser-viewer-LGH4IP47.js.map} +0 -0
  204. /package/dist/{chunk-NOSYBS2D.js.map → chunk-2VHARTBL.js.map} +0 -0
  205. /package/dist/{chunk-5M6VTFJ5.js.map → chunk-GBPCZH3Y.js.map} +0 -0
  206. /package/dist/{chunk-YBM6CQRU.js.map → chunk-GEN54DU5.js.map} +0 -0
  207. /package/dist/{chunk-R4KRSFGA.js.map → chunk-IP4BUBKH.js.map} +0 -0
  208. /package/dist/{chunk-NLTS7JHI.js.map → chunk-JPHDWKZE.js.map} +0 -0
  209. /package/dist/{chunk-24M4YBCL.js.map → chunk-PNAVEK2U.js.map} +0 -0
  210. /package/dist/{model-policy-picker-menu-3R336DP2.js.map → model-policy-picker-menu-RVOQ4ZZG.js.map} +0 -0
  211. /package/dist/{queue-surface-implementation-LK3S4BIW.js.map → queue-surface-implementation-3RIFK2BS.js.map} +0 -0
  212. /package/dist/{timeline-annotation-markers-DRSTLEM6.js.map → timeline-annotation-markers-OY6OWR3V.js.map} +0 -0
  213. /package/dist/{timeline-annotation-selection-IHLUGVND.js.map → timeline-annotation-selection-BOXA2TIN.js.map} +0 -0
  214. /package/dist/{timeline-annotations-dialog-6Q53N5FG.js.map → timeline-annotations-dialog-RGY3MHL3.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/copy-button.tsx","../src/components/markdown.tsx","../src/lib/motion.ts","../src/lib/motion-inspect.ts","../src/components/soften-streaming-markdown.ts","../src/components/stream-reveal.ts"],"sourcesContent":["import { CheckIcon, CopyIcon } from \"lucide-react\";\nimport { useEffect, useRef, useState, type MouseEvent, type ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { copyTextToClipboard } from \"../lib/clipboard\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"./tooltip\";\n\nconst COPIED_MS = 1600;\n\nexport type CopyButtonProps = {\n /** Plain text to copy, or a lazy getter (tables / late DOM). */\n text: string | (() => string);\n /** Accessible name + tooltip while idle. */\n label?: string | undefined;\n className?: string | undefined;\n /**\n * `always` — visible control.\n * `group-hover` — parent must use `group/copy`; fades in on hover/focus-visible.\n */\n reveal?: \"always\" | \"group-hover\" | undefined;\n};\n\n/**\n * Ghost icon copy control — no chrome box, no \"Copy code\" label.\n * Copy → check flash. Hover-reveal via `group/copy` on a parent.\n */\nexport function CopyButton({\n text,\n label = \"Copy\",\n className,\n reveal = \"group-hover\",\n}: CopyButtonProps) {\n const [copied, setCopied] = useState(false);\n const [tipOpen, setTipOpen] = useState(false);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n };\n }, []);\n\n const onClick = async (event: MouseEvent<HTMLButtonElement>) => {\n event.preventDefault();\n event.stopPropagation();\n // Capture before any await: React nulls `currentTarget` after the\n // synchronous handler turn. Blurring via the stale target throws and used\n // to skip the copied-reset timer, leaving the tip stuck on \"Copied\".\n const button = event.currentTarget;\n const pointerActivated = event.detail > 0;\n const value = typeof text === \"function\" ? text() : text;\n const ok = await copyTextToClipboard(value);\n if (!ok) {\n return;\n }\n setCopied(true);\n setTipOpen(true);\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n // Always arm the reset before blur — a throw here must not leave the\n // forced \"Copied\" tip open forever.\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n setCopied(false);\n setTipOpen(false);\n }, COPIED_MS);\n // Pointer activation focuses the button and leaves `group-focus-within`\n // stuck after the cursor leaves — chrome never \"unhovers\". Keyboard\n // activation (`detail === 0`) keeps focus for a11y.\n if (pointerActivated) {\n button.blur();\n }\n };\n\n const tip = copied ? \"Copied\" : label;\n\n return (\n <Tooltip\n open={copied ? true : tipOpen}\n onOpenChange={(next) => {\n if (!copied) {\n setTipOpen(next);\n }\n }}\n >\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n data-og-copy=\"\"\n data-state={copied ? \"copied\" : \"idle\"}\n aria-label={tip}\n onClick={onClick}\n className={cn(\n \"inline-flex size-7 shrink-0 items-center justify-center rounded-og-sm pointer-coarse:size-11\",\n \"text-og-fg-subtle transition-[opacity,color,background-color] duration-150\",\n \"hover:bg-og-surface-2/80 hover:text-og-fg\",\n \"focus-visible:opacity-100 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent/40\",\n reveal === \"group-hover\" &&\n \"opacity-0 group-hover/copy:opacity-100 group-focus-within/copy:opacity-100 pointer-coarse:opacity-70\",\n copied && \"opacity-100 text-og-accent\",\n className,\n )}\n >\n {copied ? (\n <CheckIcon className=\"size-3.5\" aria-hidden />\n ) : (\n <CopyIcon className=\"size-3.5\" aria-hidden />\n )}\n </button>\n </TooltipTrigger>\n <TooltipContent side=\"top\">{tip}</TooltipContent>\n </Tooltip>\n );\n}\n\n/** Hover-reveal chrome around a message / turn so {@link CopyButton} can fade in. */\nexport function CopyHoverFrame({\n children,\n className,\n copyText,\n label,\n align = \"end\",\n trailing,\n}: {\n children: ReactNode;\n className?: string | undefined;\n copyText: string;\n label: string;\n align?: \"start\" | \"end\" | undefined;\n /** Optional footer meta (e.g. sent/finished clock) — immediately after the copy control. */\n trailing?: ReactNode | undefined;\n}) {\n if (copyText.trim().length === 0) {\n return <div className={className}>{children}</div>;\n }\n return (\n <div className={cn(\"group/copy\", className)}>\n {children}\n {/* Sit under the body — top-right overlay collided with the first line. */}\n <div\n data-og-annotation-chrome=\"\"\n className={cn(\n \"flex h-6 items-center gap-1.5 pointer-coarse:h-11\",\n align === \"end\" ? \"justify-end\" : \"justify-start\",\n )}\n >\n <CopyButton\n text={copyText}\n label={label}\n reveal=\"group-hover\"\n className=\"size-6 pointer-coarse:size-11\"\n />\n {trailing}\n </div>\n </div>\n );\n}\n","import {\n Children,\n createContext,\n useContext,\n isValidElement,\n memo,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from \"react\";\nimport ReactMarkdown, {\n defaultUrlTransform,\n type Components,\n type ExtraProps,\n type UrlTransform,\n} from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport { cn } from \"../lib/cn\";\nimport { tableElementToTsv } from \"../lib/clipboard\";\nimport { prefersReducedMotion } from \"../lib/motion\";\nimport { MOTION_INSPECT_SCALE } from \"../lib/motion-inspect\";\nimport { CopyButton } from \"./copy-button\";\nimport type { observeMarkdownTableLayout } from \"./markdown-table-layout\";\nimport { softenStreamingMarkdown } from \"./soften-streaming-markdown\";\nimport { createStreamReveal, rehypeStreamReveal, type StreamReveal } from \"./stream-reveal\";\nimport { TooltipProvider } from \"./tooltip\";\n\n/**\n * The default renderer for chat message bodies in {@link MessageTimeline}.\n *\n * Agent (and user) messages arrive as GitHub-flavored markdown. This turns the\n * raw text into styled HTML using `react-markdown` + `remark-gfm`, themed to the\n * package's `og-*` design tokens so it reads as one cohesive dark surface — no\n * stock Tailwind colors leak in.\n *\n * It re-parses on every render, which is exactly right for streaming: a body\n * that is still arriving (an unterminated `**`, a half-open code fence, a table\n * mid-row) renders as best-effort markdown and resolves cleanly as the rest of\n * the tokens land. Consumers who want a different renderer can still pass\n * `renderMessageText` to `MessageTimeline` to override this entirely.\n */\nexport type MarkdownInteractiveBlock = { kind: \"html\" | \"site\"; content: string };\nconst InteractiveContext = createContext<{\n source: string;\n render?: (block: MarkdownInteractiveBlock) => ReactNode;\n renderImage?: (image: { src: string; alt: string }) => ReactNode;\n}>({ source: \"\" });\n\nexport type MarkdownProps = {\n renderImage?: ((image: { src: string; alt: string }) => ReactNode) | undefined;\n /** Host opt-in for assistant-authored interactive fences. */\n renderInteractiveBlock?: ((block: MarkdownInteractiveBlock) => ReactNode) | undefined;\n children: string;\n className?: string | undefined;\n /**\n * While true, newly arrived source fades in through tip ink (`.og-stream-ink`):\n * an age window over each append batch — fast streams keep a large soft band,\n * slow streams a tight tip. Paint-only: the DOM always holds the full truthful\n * text. Once streaming ends and trailing ink settles, the body re-renders as\n * plain markdown with a short local settle breath (no page-wide view\n * transition — that blinked the whole document).\n */\n streaming?: boolean | undefined;\n /**\n * Open a session-local file link in the host's Files surface. The path is the\n * exact decoded `sandbox:` payload; `line`, when present, is 1-based.\n */\n onSandboxFile?: ((path: string, line?: number) => void | Promise<void>) | undefined;\n};\n\n/** Exact target path plus optional 1-based line from a markdown href. */\nexport type SandboxFileLocation = {\n path: string;\n line: number | null;\n};\n\n/* --- element renderers (themed to og-* tokens) ------------------------------ */\n\nconst baseComponents: Components = {\n h1: ({ children, ...props }) => (\n <h1\n className=\"mt-5 mb-2.5 text-xl font-semibold tracking-tight text-og-fg first:mt-0\"\n {...props}\n >\n {children}\n </h1>\n ),\n h2: ({ children, ...props }) => (\n <h2 className=\"mt-5 mb-2 text-lg font-semibold tracking-tight text-og-fg first:mt-0\" {...props}>\n {children}\n </h2>\n ),\n h3: ({ children, ...props }) => (\n <h3\n className=\"mt-4 mb-1.5 text-og-md font-semibold tracking-tight text-og-fg first:mt-0\"\n {...props}\n >\n {children}\n </h3>\n ),\n h4: ({ children, ...props }) => (\n <h4\n className=\"mt-4 mb-1.5 text-og-sm font-semibold uppercase tracking-[0.04em] text-og-fg-muted first:mt-0\"\n {...props}\n >\n {children}\n </h4>\n ),\n p: ({ children, ...props }) => (\n <p className=\"my-2.5 leading-7 first:mt-0 last:mb-0\" {...props}>\n {children}\n </p>\n ),\n strong: ({ children, ...props }) => (\n <strong className=\"font-semibold text-og-fg\" {...props}>\n {children}\n </strong>\n ),\n em: ({ children, ...props }) => (\n <em className=\"italic\" {...props}>\n {children}\n </em>\n ),\n ul: ({ children, ...props }) => (\n <ul\n className=\"my-2.5 ml-5 flex list-disc flex-col gap-1 marker:text-og-fg-subtle first:mt-0 last:mb-0\"\n {...props}\n >\n {children}\n </ul>\n ),\n ol: ({ children, ...props }) => (\n <ol\n className=\"my-2.5 ml-5 flex list-decimal flex-col gap-1 marker:text-og-fg-subtle first:mt-0 last:mb-0\"\n {...props}\n >\n {children}\n </ol>\n ),\n // GFM task-list items carry a leading checkbox <input>; `list-none` + a\n // negative margin pull the checkbox back to the bullet column so it aligns\n // with the text.\n li: ({ children, ...props }) => (\n <li\n className=\"leading-7 marker:text-og-fg-subtle [&>ul]:my-1 [&>ol]:my-1 [&:has(>input)]:list-none [&:has(>input)]:-ml-5\"\n {...props}\n >\n {children}\n </li>\n ),\n input: ({ type, ...props }) =>\n type === \"checkbox\" ? (\n <input\n {...props}\n type=\"checkbox\"\n disabled\n className=\"mr-2 size-3.5 translate-y-[2px] cursor-default accent-og-accent align-baseline\"\n />\n ) : (\n <input type={type} {...props} />\n ),\n blockquote: ({ children, ...props }) => (\n <blockquote\n className=\"my-3 border-l-2 border-og-border-strong pl-3.5 text-og-fg-muted [&>p]:my-1.5 first:mt-0 last:mb-0\"\n {...props}\n >\n {children}\n </blockquote>\n ),\n hr: (props) => <hr className=\"my-4 border-0 border-t border-og-border\" {...props} />,\n // Inline `code` vs fenced code blocks. react-markdown v10 no longer passes an\n // `inline` flag; a fenced block is a <code> whose parent is <pre> (styled by\n // the `pre` renderer), so a `code` reaching here is treated as inline.\n code: ({ children, className: _className, ...props }) => (\n <code\n className=\"rounded-og-xs bg-og-surface-1 px-1 py-0.5 font-og-mono text-og-sm text-og-fg\"\n {...props}\n >\n {children}\n </code>\n ),\n // Fenced code — quiet mono block (no card / no nested vertical scroll).\n pre: InteractiveCodeBlock,\n // Tables stay unboxed (hairline rules); hover reveals a TSV copy control.\n table: ({ children, ...props }) => <MarkdownTable {...props}>{children}</MarkdownTable>,\n thead: ({ children, ...props }) => <thead {...props}>{children}</thead>,\n th: ({ children, ...props }) => (\n <th\n className=\"border-b border-og-border px-0 py-1.5 pr-4 text-left font-medium text-og-fg first:pl-0\"\n {...props}\n >\n {children}\n </th>\n ),\n td: ({ children, ...props }) => (\n <td\n className=\"border-b border-og-border/70 px-0 py-1.5 pr-4 align-top text-og-fg-muted [tr:last-child>&]:border-b-0\"\n {...props}\n >\n {children}\n </td>\n ),\n img: MarkdownImage,\n};\n\nconst MARKDOWN_LINK_CLASS =\n \"break-words font-medium text-og-accent-strong underline-offset-2 hover:underline\";\n\nfunction markdownComponents(onSandboxFile: MarkdownProps[\"onSandboxFile\"]): Components {\n return {\n ...baseComponents,\n a: ({ children, href, ...props }) => {\n const location = sandboxFileLocationFromHref(href);\n if (location !== null) {\n return (\n <SandboxMarkdownLink location={location} onSandboxFile={onSandboxFile}>\n {children}\n </SandboxMarkdownLink>\n );\n }\n if (isSandboxHref(href) || !href) {\n return (\n <span\n className=\"break-words font-medium text-og-fg-subtle underline decoration-dotted underline-offset-2\"\n aria-disabled=\"true\"\n title={\n isSandboxHref(href)\n ? \"This sandbox file reference is invalid\"\n : \"This link is unavailable\"\n }\n >\n {children}\n </span>\n );\n }\n return (\n <a\n className={MARKDOWN_LINK_CLASS}\n target=\"_blank\"\n rel=\"noreferrer noopener\"\n href={href}\n {...props}\n >\n {children}\n </a>\n );\n },\n };\n}\n\nfunction SandboxMarkdownLink({\n location,\n onSandboxFile,\n children,\n}: {\n location: SandboxFileLocation;\n onSandboxFile: MarkdownProps[\"onSandboxFile\"];\n children: ReactNode;\n}) {\n const [state, setState] = useState<\"idle\" | \"loading\" | \"error\">(\"idle\");\n const { path, line } = location;\n if (!onSandboxFile) {\n return (\n <span\n className=\"break-words font-medium text-og-fg-subtle underline decoration-dotted underline-offset-2\"\n aria-disabled=\"true\"\n title=\"This sandbox file requires a session-aware handler\"\n >\n {children}\n </span>\n );\n }\n const idleTitle = line !== null ? `Open ${path} at line ${line}` : `Open ${path}`;\n return (\n <button\n type=\"button\"\n className={cn(\n MARKDOWN_LINK_CLASS,\n \"inline-flex min-h-7 cursor-pointer items-center disabled:cursor-wait disabled:opacity-70 pointer-coarse:min-h-11\",\n )}\n disabled={state === \"loading\"}\n aria-busy={state === \"loading\"}\n title={state === \"error\" ? \"Couldn't open this file. Select to retry.\" : idleTitle}\n onClick={() => {\n setState(\"loading\");\n void Promise.resolve(onSandboxFile(path, line ?? undefined)).then(\n () => setState(\"idle\"),\n () => setState(\"error\"),\n );\n }}\n >\n {children}\n {state === \"loading\" ? \" (opening…)\" : state === \"error\" ? \" (retry)\" : null}\n </button>\n );\n}\n\nconst SANDBOX_SCHEME = \"sandbox:\";\nconst LEGACY_WORKSPACE_PREFIX = \"/workspace/\";\nconst TRAILING_LINE = /:([0-9]+)$/u;\nconst TRAILING_INVALID_LINE = /:-(?:[0-9]+)$|:[0-9]+-[0-9]+$/u;\nconst CONTROL_CHARACTER = /[\\u0000-\\u001f\\u007f]/u;\n\nfunction isSandboxHref(href: string | undefined): boolean {\n return href?.startsWith(SANDBOX_SCHEME) ?? false;\n}\n\n/**\n * Parse an OpenGeni `sandbox:` application href (plus the historical bare\n * `/workspace/...` form). The decoded path is intentionally opaque here:\n * target selection, path policy, and filesystem authority belong to the\n * session-aware host and its FileSystem boundary.\n */\nexport function sandboxFileLocationFromHref(href: string | undefined): SandboxFileLocation | null {\n if (!href) return null;\n const encodedLocation = isSandboxHref(href)\n ? href.slice(SANDBOX_SCHEME.length)\n : href.startsWith(LEGACY_WORKSPACE_PREFIX)\n ? href\n : null;\n if (!encodedLocation || encodedLocation.includes(\"?\") || encodedLocation.includes(\"#\")) {\n return null;\n }\n if (TRAILING_INVALID_LINE.test(encodedLocation)) return null;\n const lineMatch = TRAILING_LINE.exec(encodedLocation);\n const encodedPath = lineMatch ? encodedLocation.slice(0, -lineMatch[0].length) : encodedLocation;\n const line = lineMatch?.[1] ? Number(lineMatch[1]) : null;\n if (line !== null && (!Number.isSafeInteger(line) || line < 1)) return null;\n if (!encodedPath) return null;\n try {\n const path = decodeURIComponent(encodedPath);\n return path && !CONTROL_CHARACTER.test(path) ? { path, line } : null;\n } catch {\n return null;\n }\n}\n\n/** Return the exact decoded path for a supported sandbox-link href. */\nexport function sandboxFilePathFromHref(href: string | undefined): string | null {\n return sandboxFileLocationFromHref(href)?.path ?? null;\n}\n\nexport function retainedImageId(src: string): string | null {\n return (\n /^artifact:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i\n .exec(src)?.[1]\n ?.toLowerCase() ?? null\n );\n}\nfunction MarkdownImage({ src, alt }: ComponentPropsWithoutRef<\"img\">) {\n const { renderImage } = useContext(InteractiveContext);\n if (!src) return <span>{alt ?? \"Image unavailable\"}</span>;\n if (retainedImageId(src))\n return renderImage ? (\n <>{renderImage({ src, alt: alt ?? \"\" })}</>\n ) : (\n <span>{alt || \"Image\"} (preview unavailable)</span>\n );\n return <img src={src} alt={alt ?? \"\"} loading=\"lazy\" className=\"my-3 max-w-full rounded-og-md\" />;\n}\n\nconst markdownUrlTransform: UrlTransform = (url, key, node) =>\n (key === \"href\" && node.tagName === \"a\" && isSandboxHref(url)) ||\n (key === \"src\" && node.tagName === \"img\" && retainedImageId(url))\n ? url\n : defaultUrlTransform(url);\n\n/** How long after the stream ends the reveal pipeline stays for trailing animations. */\n/** Trailing ink window after stream end — keep ≥ {@link INK_FADE_MS}. */\nconst REVEAL_LINGER_MS = 480 * MOTION_INSPECT_SCALE;\n/** Keep in sync with `--og-duration-markdown-crystallize` / view-transition CSS. */\nconst MARKDOWN_SETTLE_MS = 480 * MOTION_INSPECT_SCALE;\n\nfunction nodeText(node: ReactNode): string {\n if (node == null || typeof node === \"boolean\") {\n return \"\";\n }\n if (typeof node === \"string\" || typeof node === \"number\") {\n return String(node);\n }\n if (Array.isArray(node)) {\n return node.map(nodeText).join(\"\");\n }\n if (isValidElement<{ children?: ReactNode }>(node)) {\n return nodeText(node.props.children);\n }\n return \"\";\n}\n\nfunction fenceLanguage(children: ReactNode): string | null {\n let found: string | null = null;\n Children.forEach(children, (child) => {\n if (found || !isValidElement<{ className?: string }>(child)) {\n return;\n }\n const match = /language-([a-zA-Z0-9_+-]+)/.exec(child.props.className ?? \"\");\n if (match?.[1]) {\n found = match[1];\n }\n });\n return found;\n}\n\nfunction InteractiveCodeBlock({ children, node }: ComponentPropsWithoutRef<\"pre\"> & ExtraProps) {\n const { source, render } = useContext(InteractiveContext);\n const language = fenceLanguage(children);\n if (render && (language === \"opengeni-html\" || language === \"opengeni-site\")) {\n const start = node?.position?.start.offset;\n const end = node?.position?.end.offset;\n const original =\n start !== undefined && end !== undefined && end <= source.length\n ? source.slice(start, end)\n : \"\";\n const lines = original.trimEnd().split(\"\\n\");\n const opening = lines[0]?.match(/^ {0,3}([\\x60]{3,}|~{3,})/);\n\n const closing = lines\n .at(-1)\n ?.replace(/^\\s*(?:>\\s*)+/, \"\")\n .trim();\n const complete =\n opening &&\n lines.length > 1 &&\n closing &&\n closing.length >= opening[1]!.length &&\n [...closing].every((c) => c === opening[1]![0]);\n if (!complete) return <p role=\"status\">Preparing preview…</p>;\n return (\n <>\n {render({\n kind: language === \"opengeni-html\" ? \"html\" : \"site\",\n content: nodeText(children).replace(/\\n$/, \"\"),\n })}\n </>\n );\n }\n return <MarkdownCodeBlock>{children}</MarkdownCodeBlock>;\n}\n\nfunction MarkdownCodeBlock({ children }: { children?: ReactNode }) {\n const code = nodeText(children).replace(/\\n$/, \"\");\n const language = fenceLanguage(children);\n // mt-only (no mb / last:mb-0): next sibling streaming in used to flip a\n // previous block's bottom margin on and yank tip-follow. Copy is overlay-only.\n // Fixed leading + overflow-x:auto with stable block chrome so wide ASCII lines\n // don't pop a scrollbar gutters mid-stream (another tip bob).\n return (\n <div className=\"group/copy relative mt-3 first:mt-0\">\n <div className=\"pointer-events-none absolute top-1.5 right-1.5 z-10 flex items-center gap-1\">\n {language ? (\n <span className=\"rounded px-1 py-0.5 font-og-mono text-[10px] uppercase tracking-wide text-og-fg-subtle/80 opacity-0 transition-opacity group-hover/copy:opacity-100 pointer-coarse:opacity-70\">\n {language}\n </span>\n ) : null}\n <div className=\"pointer-events-auto\">\n <CopyButton text={code} label=\"Copy code\" reveal=\"group-hover\" />\n </div>\n </div>\n <pre\n tabIndex={0}\n className=\"overflow-x-auto overflow-y-hidden rounded-og-md bg-og-surface-1/70 px-3 py-2.5 font-og-mono text-og-sm leading-5 text-og-fg-muted [scrollbar-gutter:stable] [&>code]:block [&>code]:border-0 [&>code]:bg-transparent [&>code]:p-0 [&>code]:leading-5 [&>code]:text-inherit\"\n >\n {children}\n </pre>\n </div>\n );\n}\n\nfunction MarkdownTable({ children, className, ...props }: ComponentPropsWithoutRef<\"table\">) {\n const wrapperRef = useRef<HTMLDivElement>(null);\n const tableRef = useRef<HTMLTableElement>(null);\n const layoutRef = useRef<ReturnType<typeof observeMarkdownTableLayout>>(undefined);\n useEffect(() => {\n const wrapper = wrapperRef.current;\n const table = tableRef.current;\n if (!wrapper?.closest(\"[data-og-wide-table-message]\") || !table) return;\n let disposed = false;\n // Ordinary tables remain usable even if this optional layout chunk fails.\n void import(\"./markdown-table-layout\")\n .then(({ observeMarkdownTableLayout }) => {\n if (!disposed) layoutRef.current = observeMarkdownTableLayout(wrapper, table);\n })\n .catch(() => {});\n return () => {\n disposed = true;\n layoutRef.current?.disconnect();\n layoutRef.current = undefined;\n };\n }, []);\n // ReactMarkdown recreates table children even when only later prose changes.\n // Remeasure genuine content changes without collapsing the expanded wrapper\n // between cleanup and the asynchronous observer-module import on each update.\n useEffect(() => {\n layoutRef.current?.measure();\n }, [children]);\n return (\n <div ref={wrapperRef} className=\"group/copy relative mt-3 max-w-full first:mt-0\">\n <div className=\"pointer-events-none absolute top-0 right-0 z-10\">\n <div className=\"pointer-events-auto\">\n <CopyButton\n text={() => tableElementToTsv(tableRef.current)}\n label=\"Copy table\"\n reveal=\"group-hover\"\n />\n </div>\n </div>\n <div className=\"overflow-x-auto\" tabIndex={0}>\n <table\n ref={tableRef}\n className={cn(\"w-full min-w-0 border-collapse text-og-base\", className)}\n {...props}\n >\n {children}\n </table>\n </div>\n </div>\n );\n}\n\nfunction MarkdownImpl({\n children,\n className,\n streaming = false,\n onSandboxFile,\n renderInteractiveBlock,\n renderImage,\n}: MarkdownProps) {\n // Tip-ink engine for THIS body: created on the first streaming render, kept\n // through a short linger after the stream ends (so the last age window can\n // finish), then dropped so settled bodies pay zero cost. Observing during\n // render is idempotent per text length — StrictMode double-renders are safe.\n const revealRef = useRef<StreamReveal | null>(null);\n const bodyRef = useRef<HTMLDivElement | null>(null);\n const [, bump] = useReducer((n: number) => n + 1, 0);\n const [settling, setSettling] = useState(false);\n const hadRevealRef = useRef(false);\n const now = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // Local settle breath only — View Transitions with `::view-transition-*(*)`\n // were fading the document root and felt like a full-page blink / focus loss\n // right as a turn ended (just before the next user message in the seed loop).\n const crystallize = (mutate: () => void) => {\n mutate();\n setSettling(true);\n bump();\n return setTimeout(() => setSettling(false), MARKDOWN_SETTLE_MS);\n };\n if (streaming && revealRef.current === null && !prefersReducedMotion()) {\n revealRef.current = createStreamReveal();\n }\n const reveal = revealRef.current;\n if (reveal !== null && streaming) {\n reveal.observe(children, now);\n }\n if (reveal !== null) {\n hadRevealRef.current = true;\n }\n const revealActive = reveal !== null && (streaming || reveal.hasActive(now));\n // The plugin walks the standard hast tree; a structural local type keeps the\n // module dependency-free, at the cost of this narrowing cast at the seam.\n const rehypePlugins =\n revealActive && reveal !== null\n ? ([[rehypeStreamReveal, { reveal, now }]] as unknown as NonNullable<\n Parameters<typeof ReactMarkdown>[0][\"rehypePlugins\"]\n >)\n : undefined;\n\n // Drop tip ink after trailing age windows finish. Same commit crystallizes:\n // ink spans → final plain markdown (soften off) + a short local settle breath.\n useEffect(() => {\n if (streaming || revealRef.current === null) {\n return;\n }\n let clearSettle: ReturnType<typeof setTimeout> | undefined;\n const timer = setTimeout(() => {\n const shouldSettle = hadRevealRef.current && !prefersReducedMotion();\n if (shouldSettle) {\n hadRevealRef.current = false;\n }\n if (shouldSettle) {\n clearSettle = crystallize(() => {\n revealRef.current = null;\n });\n } else {\n revealRef.current = null;\n bump();\n }\n }, REVEAL_LINGER_MS);\n return () => {\n clearTimeout(timer);\n if (clearSettle !== undefined) {\n clearTimeout(clearSettle);\n }\n };\n }, [streaming]);\n\n // No-reveal path (stream ended before any ink batch): soften already dropped\n // with `streaming`; keep the same local settle breath.\n const wasStreamingRef = useRef(streaming);\n useEffect(() => {\n const ended = wasStreamingRef.current && !streaming;\n wasStreamingRef.current = streaming;\n if (!ended || revealRef.current !== null || prefersReducedMotion()) {\n return;\n }\n setSettling(true);\n const timer = setTimeout(() => setSettling(false), MARKDOWN_SETTLE_MS);\n return () => clearTimeout(timer);\n }, [streaming]);\n\n // Soften unfinished markers for DISPLAY while the reveal pipeline is alive\n // (stream + linger) — not only while `streaming` — so task lists / tables /\n // fences don't snap to final GFM one commit before the crystallize morph.\n // Reveal identity still tracks the true source (`children`).\n const parseText = streaming || revealActive ? softenStreamingMarkdown(children) : children;\n const components = useMemo(() => markdownComponents(onSandboxFile), [onSandboxFile]);\n\n const interactiveContext = useMemo(\n () => ({\n source: children,\n ...(renderInteractiveBlock ? { render: renderInteractiveBlock } : {}),\n ...(renderImage ? { renderImage } : {}),\n }),\n [children, renderInteractiveBlock, renderImage],\n );\n\n // `min-w-0` lets the prose shrink inside flex parents (message bubbles) so\n // long links and code blocks wrap/scroll instead of forcing overflow.\n return (\n <InteractiveContext.Provider value={interactiveContext}>\n <TooltipProvider delayDuration={400}>\n <div\n ref={bodyRef}\n className={cn(\n \"og-markdown-body min-w-0 break-words\",\n settling && \"og-markdown-settle\",\n className,\n )}\n >\n <ReactMarkdown\n remarkPlugins={[remarkGfm]}\n rehypePlugins={rehypePlugins}\n components={components}\n urlTransform={markdownUrlTransform}\n >\n {parseText}\n </ReactMarkdown>\n </div>\n </TooltipProvider>\n </InteractiveContext.Provider>\n );\n}\n\n/** Memoized so streaming re-renders of the parent don't re-parse settled bodies. */\nexport const Markdown = memo(MarkdownImpl);\n","import { flushSync } from \"react-dom\";\n\n/**\n * Live `prefers-reduced-motion` check for JS-driven motion (scroll glides,\n * streaming word reveals). CSS animations are already neutralized globally in\n * styles/index.css; this lets the imperative paths skip their work entirely.\n */\nlet query: MediaQueryList | null | undefined;\n\nexport function prefersReducedMotion(): boolean {\n if (query === undefined) {\n query =\n typeof window !== \"undefined\" && typeof window.matchMedia === \"function\"\n ? window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n : null;\n }\n return query?.matches ?? false;\n}\n\n/** Test seam: forget the cached MediaQueryList so a stubbed matchMedia applies. */\nexport function resetReducedMotionCache(): void {\n query = undefined;\n}\n\ntype ViewTransitionResult = { finished: Promise<void> };\ntype ViewTransitionCallback = () => void;\ntype ViewTransitionOptions = {\n update: ViewTransitionCallback;\n types?: string[];\n};\ntype ViewTransitionStarter = {\n (callback: ViewTransitionCallback): ViewTransitionResult;\n (options: ViewTransitionOptions): ViewTransitionResult;\n};\n\n/** Active VT type for markdown crystallize — scoped CSS, not a full-page blink. */\nexport const MARKDOWN_CRYSTALLIZE_VT_TYPE = \"og-md-crystallize\";\n\n/**\n * Run a DOM update inside the browser View Transition API when available.\n * Snapshots the before/after paint and cross-fades (or custom CSS morphs)\n * between them — the platform \"morph\" primitive React's experimental\n * `<ViewTransition>` wraps. Falls back to a synchronous update.\n */\nexport function runViewTransition(update: () => void, options?: { types?: string[] }): void {\n if (prefersReducedMotion()) {\n update();\n return;\n }\n const doc = typeof document !== \"undefined\" ? document : null;\n const start = doc\n ? ((doc as Document & { startViewTransition?: ViewTransitionStarter }).startViewTransition ??\n null)\n : null;\n if (typeof start !== \"function\") {\n update();\n return;\n }\n const types = options?.types;\n if (types && types.length > 0) {\n try {\n Reflect.apply(start, doc, [\n {\n update: () => {\n flushSync(update);\n },\n types,\n },\n ]);\n return;\n } catch {\n // Older engines only accept the callback form.\n }\n }\n Reflect.apply(start, doc, [\n () => {\n flushSync(update);\n },\n ]);\n}\n","/**\n * TEMP eyeball scale for vertical motion (tip-follow, settle fold, CSS).\n * Set back to `1` before landing — not a product knob.\n */\nexport const MOTION_INSPECT_SCALE = 1;\n","/**\n * Display-only softener for mid-stream markdown.\n *\n * While tokens are still arriving, incomplete markers (`**bold`, an open\n * fence, a half-finished link) would otherwise render as raw punctuation —\n * the hard \"breaking\" flash. This closes a small set of common unfinished\n * constructs so the parse looks settled; the SOURCE string is never mutated\n * (callers pass the softened copy only into the markdown parser).\n *\n * When the real closers land, the softened and true parses converge and the\n * crystallize breath covers the remount.\n */\n\nexport function softenStreamingMarkdown(source: string): string {\n if (source.length === 0) {\n return source;\n }\n let text = source;\n\n // Unclosed fenced code block: an odd count of ``` line-openers means the\n // trailing fence is still in flight. Always soft-close — including an empty\n // opener — so code chrome (padding/tint) appears once at ``` and lines only\n // grow the body. Stripping empty openers deferred chrome until the first\n // body line, which landed as one fat height spike (yank around fences).\n //\n // If the body already ends with `\\n`, append only ``` — a second `\\n``` would\n // invent a blank line that vanishes when the real closer lands (height shrink\n // → tip-follow compensate + mid soft-rise cancel = up/down flicker).\n if (countFences(text) % 2 === 1) {\n text += text.endsWith(\"\\n\") ? \"```\" : \"\\n```\";\n }\n\n // Work outside fenced blocks so we don't \"fix\" markers that are literal\n // code content.\n const segments = splitByFences(text);\n for (const segment of segments) {\n if (segment.kind === \"fence\") {\n continue;\n }\n segment.value = closeInlineMarkers(segment.value);\n }\n let result = segments.map((segment) => segment.value).join(\"\");\n // split(\"\\n\") drops a trailing newline into an empty final line; restore it\n // so balanced finished fences round-trip byte-identical.\n if (text.endsWith(\"\\n\") && !result.endsWith(\"\\n\")) {\n result += \"\\n\";\n }\n return result;\n}\n\nfunction countFences(text: string): number {\n let count = 0;\n for (const line of text.split(\"\\n\")) {\n if (/^ {0,3}```/.test(line)) {\n count += 1;\n }\n }\n return count;\n}\n\ntype Segment = { kind: \"prose\" | \"fence\"; value: string };\n\nfunction splitByFences(text: string): Segment[] {\n const segments: Segment[] = [];\n const lines = text.split(\"\\n\");\n let buf: string[] = [];\n let inFence = false;\n /**\n * `boundary`: prose → fence. `join` alone drops a blank line before ```\n * (`[\"a\",\"\"].join` → `\"a\\n\"`, need `\"a\\n\\n\"`), so append an extra `\\n`.\n * `end`: final segment. Trailing `\"\"` from `split(\"\\n\")` already encodes a\n * terminating newline — do NOT append another (that was inventing `\\n\\n`\n * on every streamed line and shrinking it away at crystallize).\n */\n const flush = (kind: Segment[\"kind\"], mode: \"boundary\" | \"end\") => {\n if (buf.length === 0) {\n return;\n }\n let value = buf.join(\"\\n\");\n if (mode === \"boundary\") {\n value += \"\\n\";\n }\n segments.push({ kind, value });\n buf = [];\n };\n for (const line of lines) {\n const isFence = /^ {0,3}```/.test(line);\n if (isFence) {\n if (inFence) {\n buf.push(line);\n flush(\"fence\", \"end\");\n inFence = false;\n } else {\n flush(\"prose\", \"boundary\");\n buf.push(line);\n inFence = true;\n }\n continue;\n }\n buf.push(line);\n }\n flush(inFence ? \"fence\" : \"prose\", \"end\");\n return segments;\n}\n\n/**\n * Close unmatched **, *, ~~, and ` in prose. Order matters: handle the\n * longer bold/strike markers before single `*` so we don't steal from `**`.\n */\nfunction closeInlineMarkers(prose: string): string {\n let text = prose;\n text = closeDelimiter(text, \"~~\");\n text = closeDelimiter(text, \"**\");\n text = closeDelimiter(text, \"__\");\n text = closeSingleBackticks(text);\n text = closeSingleAsterisks(text);\n text = closeUnfinishedLink(text);\n return text;\n}\n\nfunction closeDelimiter(text: string, delimiter: string): string {\n // Count occurrences that aren't escaped. Odd → append a closer.\n let count = 0;\n let i = 0;\n while (i < text.length) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i += 2;\n continue;\n }\n if (text.startsWith(delimiter, i)) {\n count += 1;\n i += delimiter.length;\n continue;\n }\n i += 1;\n }\n return count % 2 === 1 ? insertBeforeTrailingNewlines(text, delimiter) : text;\n}\n\n/** Soft closers belong before trailing `\\n`s so restore/round-trip stay stable. */\nfunction insertBeforeTrailingNewlines(text: string, suffix: string): string {\n let end = text.length;\n while (end > 0 && text[end - 1] === \"\\n\") {\n end -= 1;\n }\n return text.slice(0, end) + suffix + text.slice(end);\n}\n\nfunction closeSingleBackticks(text: string): string {\n // Ignore ``` (fences already stripped) and even pairs. A trailing unmatched\n // ` is the common \"inline code still typing\" case.\n let count = 0;\n for (let i = 0; i < text.length; i += 1) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i += 1;\n continue;\n }\n if (text[i] === \"`\") {\n // Skip triple backticks if any leaked into prose.\n if (text.startsWith(\"```\", i)) {\n i += 2;\n continue;\n }\n count += 1;\n }\n }\n return count % 2 === 1 ? insertBeforeTrailingNewlines(text, \"`\") : text;\n}\n\nfunction closeSingleAsterisks(text: string): string {\n // Count `*` that are NOT part of `**` (already handled). Odd → close italic.\n let count = 0;\n for (let i = 0; i < text.length; i += 1) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i += 1;\n continue;\n }\n if (text[i] === \"*\" && text[i + 1] === \"*\") {\n i += 1;\n continue;\n }\n if (text[i] === \"*\") {\n count += 1;\n }\n }\n return count % 2 === 1 ? insertBeforeTrailingNewlines(text, \"*\") : text;\n}\n\nfunction closeUnfinishedLink(text: string): string {\n // `[label](url` without the trailing `)` — close it. Bare `[label` without\n // `](` is left alone (too ambiguous with footnotes / prose brackets).\n const open = text.lastIndexOf(\"](\");\n if (open === -1) {\n return text;\n }\n const after = text.slice(open + 2);\n if (after.includes(\")\")) {\n return text;\n }\n // Don't close if a later `[` started something else after.\n if (after.includes(\"[\")) {\n return text;\n }\n return insertBeforeTrailingNewlines(text, \")\");\n}\n","/* ----------------------------------------------------------------------------\n Streaming tip ink (age-window fade)\n\n Append-only markdown grows at the tip. Rather than staggering per-word\n onsets (glitter under fast models), each append batch is born at wall time\n and fades in over a fixed age window:\n\n opacity progress = clamp((now − birth) / INK_FADE_MS, 0, 1)\n\n Fast arrival → many recent characters still young → a large soft band.\n Slow arrival → only the tip is young → a tight tip wash.\n Same rule both ways; time does the work. No per-word stagger, no artificial\n content lag — layout always holds the truthful text; paint only.\n\n Identity is the character offset into the source. CSS animation-delay =\n birth − now (often negative) so mid-fade re-renders resume, never restart.\n Runs settle back to plain text once age ≥ INK_FADE_MS (zero span cost).\n -------------------------------------------------------------------------- */\n\nimport { MOTION_INSPECT_SCALE } from \"../lib/motion-inspect\";\n\n/** Keep in sync with `--og-duration-stream` / `.og-stream-ink` in styles. */\nexport const INK_FADE_MS = 420 * MOTION_INSPECT_SCALE;\n/** @deprecated Use {@link INK_FADE_MS}. */\nexport const WORD_ANIMATION_MS = INK_FADE_MS;\n\n/**\n * A first observation larger than this is pre-existing history (timeline\n * opened mid-stream), not live tip — it renders instantly.\n */\nconst INITIAL_ANIMATED_LIMIT = 400;\n\ntype InkBatch = {\n start: number;\n end: number;\n birth: number;\n};\n\nexport type StreamReveal = {\n /** Register the full current source text; new suffix becomes an ink batch. */\n observe(text: string, now: number): void;\n /**\n * CSS animation-delay (ms) for the run covering `offset`, or null when that\n * ink has settled and should render as plain text. Negative = resume mid-fade.\n */\n delayFor(offset: number, now: number): number | null;\n /** True while any batch is still inside its fade window. */\n hasActive(now: number): boolean;\n};\n\nexport function createStreamReveal(): StreamReveal {\n let batches: InkBatch[] = [];\n let revealedChars = -1;\n\n return {\n observe(text, now) {\n if (revealedChars === -1) {\n revealedChars = text.length > INITIAL_ANIMATED_LIMIT ? text.length : 0;\n }\n if (text.length <= revealedChars) {\n // Idempotent re-observation (StrictMode) or defensive no-op on shrink.\n revealedChars = Math.max(revealedChars, text.length);\n return;\n }\n batches.push({ start: revealedChars, end: text.length, birth: now });\n revealedChars = text.length;\n batches = batches.filter((batch) => batch.birth + INK_FADE_MS > now);\n },\n\n delayFor(offset, now) {\n const batch = findBatch(batches, offset);\n if (!batch) {\n return null;\n }\n const delay = batch.birth - now;\n return delay + INK_FADE_MS <= 0 ? null : delay;\n },\n\n hasActive(now) {\n const last = batches[batches.length - 1];\n return last !== undefined && last.birth + INK_FADE_MS > now;\n },\n };\n}\n\nfunction findBatch(batches: readonly InkBatch[], offset: number): InkBatch | null {\n let low = 0;\n let high = batches.length - 1;\n while (low <= high) {\n const mid = (low + high) >> 1;\n const batch = batches[mid]!;\n if (offset < batch.start) {\n high = mid - 1;\n } else if (offset >= batch.end) {\n low = mid + 1;\n } else {\n return batch;\n }\n }\n return null;\n}\n\n/* ----------------------------------------------------------------------------\n rehype: wrap still-fading source runs in `.og-stream-ink` spans.\n\n Contiguous offsets that share one birth (one append batch) become ONE span —\n a continuous ink surface, not per-word glitter. Code/pre stay plain. Nodes\n without source positions (syntax rewritten around them) render plain too.\n -------------------------------------------------------------------------- */\n\ntype HastText = {\n type: \"text\";\n value: string;\n position?: { start?: { offset?: number | undefined } | undefined } | undefined;\n};\n\ntype HastParent = {\n type: string;\n tagName?: string;\n value?: string;\n children?: HastChild[];\n};\n\ntype HastChild = (HastText | HastParent) & Record<string, unknown>;\n\nexport function rehypeStreamReveal(options: { reveal: StreamReveal; now: number }) {\n const { reveal, now } = options;\n return (tree: HastParent) => {\n walk(tree, false);\n };\n\n function walk(node: HastParent, insideVerbatim: boolean): void {\n if (!node.children) {\n return;\n }\n const verbatim = insideVerbatim || node.tagName === \"code\" || node.tagName === \"pre\";\n const next: HastChild[] = [];\n for (const child of node.children) {\n if (child.type === \"text\" && !verbatim) {\n next.push(...splitTextNode(child as HastText));\n continue;\n }\n walk(child as HastParent, verbatim);\n next.push(child);\n }\n node.children = next;\n }\n\n function splitTextNode(node: HastText): HastChild[] {\n const sourceOffset = node.position?.start?.offset;\n if (sourceOffset === undefined) {\n return [node as HastChild];\n }\n const value = node.value;\n const out: HastChild[] = [];\n let plain = \"\";\n const flushPlain = () => {\n if (plain.length > 0) {\n out.push({ type: \"text\", value: plain } as HastChild);\n plain = \"\";\n }\n };\n\n let i = 0;\n while (i < value.length) {\n const delay = reveal.delayFor(sourceOffset + i, now);\n let j = i + 1;\n while (j < value.length) {\n const nextDelay = reveal.delayFor(sourceOffset + j, now);\n if (nextDelay !== delay) {\n break;\n }\n j += 1;\n }\n const slice = value.slice(i, j);\n if (delay === null) {\n plain += slice;\n } else {\n flushPlain();\n out.push({\n type: \"element\",\n tagName: \"span\",\n properties: {\n className: [\"og-stream-ink\"],\n style: `animation-delay:${Math.round(delay)}ms`,\n },\n children: [{ type: \"text\", value: slice }],\n } as unknown as HastChild);\n }\n i = j;\n }\n flushPlain();\n return out.length > 0 ? out : [node as HastChild];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,WAAW,gBAAgB;AACpC,SAAS,WAAW,QAAQ,gBAAiD;AA8EzE,SA2BQ,KA3BR;AAzEJ,IAAM,YAAY;AAmBX,SAAS,WAAW;AAAA,EACzB;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA,SAAS;AACX,GAAoB;AAClB,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAS,KAAK;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,KAAK;AAC5C,QAAM,WAAW,OAA6C,IAAI;AAElE,YAAU,MAAM;AACd,WAAO,MAAM;AACX,UAAI,SAAS,YAAY,MAAM;AAC7B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;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,WAAW;AAAA,QACT;AAAA,QACA,YAAY;AAAA,QACZ;AAAA,MACF;AAAA,MAEA,0BAAAA;AAAA,QAAC;AAAA;AAAA,UACC,eAAe,CAAC,SAAS;AAAA,UACzB;AAAA,UACA;AAAA,UACA,cAAc;AAAA,UAEb;AAAA;AAAA,MACH;AAAA;AAAA,EACF,GACF,GACF;AAEJ;AAGO,IAAM,WAAW,KAAK,YAAY;","names":["useEffect","useRef","useState","jsx","jsxs","useState","useRef","useEffect"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/embedded-session-client.ts","../src/hooks/use-file-attachments.ts","../src/hooks/use-goal.ts","../src/hooks/use-session-control.ts","../src/hooks/use-session-mcp-approval-policy.ts","../src/hooks/use-session-lineage.ts","../src/approvals.ts"],"sourcesContent":["import type { ComposerDraft } from \"@opengeni/sdk\";\nimport type { EmbeddedSessionClientLike } from \"./client\";\n\nexport type ComposerDraftMapContext = {\n operation: \"read\" | \"save\" | \"submit\";\n workspaceId: string;\n sessionId: string;\n};\n\nexport type CreateEmbeddedSessionClientOptions = {\n /**\n * Explicit host-owned method replacements. Methods inherited from `base`\n * retain `base` as their receiver; overrides retain this object as theirs.\n */\n overrides?: Partial<EmbeddedSessionClientLike> | undefined;\n /** Presentation/policy projection for every draft entering the React layer. */\n mapComposerDraft?:\n | ((draft: ComposerDraft, context: ComposerDraftMapContext) => ComposerDraft)\n | undefined;\n};\n\nconst requiredMethods = [\n \"getSession\",\n \"listEvents\",\n \"streamEvents\",\n \"getComposerDraft\",\n \"saveComposerDraft\",\n \"submitComposerDraft\",\n \"sendMessage\",\n \"steerMessage\",\n \"getQueue\",\n \"moveQueueItem\",\n \"editQueueItem\",\n \"steerQueueItem\",\n \"deleteQueueItem\",\n \"pauseSession\",\n \"resumeSession\",\n \"sendApprovalDecision\",\n] as const satisfies readonly (keyof EmbeddedSessionClientLike)[];\n\n/**\n * Build the exact client required by `@opengeni/react/session` from a full SDK\n * client or host proxy. The constructor binds every delegated method once,\n * supports a host-owned atomic composer-submit override, and fails at creation\n * time instead of waiting for a missing method to be exercised by a hook.\n */\nexport function createEmbeddedSessionClient(\n base: EmbeddedSessionClientLike,\n options: CreateEmbeddedSessionClientOptions = {},\n): EmbeddedSessionClientLike {\n const overrides = options.overrides ?? {};\n const client = {} as EmbeddedSessionClientLike;\n for (const key of requiredMethods) {\n const override = overrides[key];\n const method = override ?? base[key];\n if (typeof method !== \"function\") {\n throw new TypeError(`Embedded session client method is required: ${key}`);\n }\n client[key] = method.bind(override === undefined ? base : overrides) as never;\n }\n\n const inferenceOverride = overrides.setWorkspaceInferenceState;\n const inferenceBase = base.setWorkspaceInferenceState;\n const inferenceMethod = inferenceOverride ?? inferenceBase;\n if (typeof inferenceMethod === \"function\") {\n client.setWorkspaceInferenceState = inferenceMethod.bind(\n inferenceOverride === undefined ? base : overrides,\n );\n }\n\n const mapDraft = options.mapComposerDraft;\n if (!mapDraft) return client;\n\n const getComposerDraft = client.getComposerDraft;\n client.getComposerDraft = async (workspaceId, sessionId) =>\n mapDraft(await getComposerDraft(workspaceId, sessionId), {\n operation: \"read\",\n workspaceId,\n sessionId,\n });\n\n const saveComposerDraft = client.saveComposerDraft;\n client.saveComposerDraft = async (workspaceId, sessionId, request) =>\n mapDraft(await saveComposerDraft(workspaceId, sessionId, request), {\n operation: \"save\",\n workspaceId,\n sessionId,\n });\n\n const submitComposerDraft = client.submitComposerDraft;\n client.submitComposerDraft = async (workspaceId, sessionId, request) => {\n const response = await submitComposerDraft(workspaceId, sessionId, request);\n return {\n ...response,\n draft: mapDraft(response.draft, {\n operation: \"submit\",\n workspaceId,\n sessionId,\n }),\n };\n };\n\n return client;\n}\n","import type { FileAsset, FileResourceRef } from \"@opengeni/sdk\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n useEmbeddedFileAttachments,\n type EmbeddedFileAttachmentClientOverride,\n} from \"../session-context\";\n\nexport type UseFileAttachmentsOptions = EmbeddedFileAttachmentClientOverride & {\n /**\n * Only files matching this predicate are accepted by {@link\n * UseFileAttachmentsResult.addFromPaste} (the clipboard path). Defaults to\n * `image/*` — the console's historical paste filter. {@link\n * UseFileAttachmentsResult.addFiles} (the explicit picker / drop path)\n * bypasses it.\n */\n /** Retain original uploads in the chat owner’s personal scope when private. */\n scope?: \"workspace\" | \"personal\";\n pasteFilter?: ((file: File) => boolean) | undefined;\n};\n\nexport type FileAttachment = {\n id: string;\n name: string;\n contentType: string;\n sizeBytes: number;\n status: \"uploading\" | \"ready\" | \"failed\";\n /** The SDK `FileAsset` once the upload finishes. */\n file?: FileAsset | undefined;\n /** Object-URL for an inline preview; minted for `image/*` files only. */\n previewUrl?: string | undefined;\n /** Stable SDK failure code for UI behavior that must not parse error copy. */\n errorCode?: \"secure_context_required\" | undefined;\n error?: string | undefined;\n};\n\nexport type UseFileAttachmentsResult = {\n attachments: FileAttachment[];\n /**\n * `FileResourceRef[]` for every attachment that finished uploading — feed\n * straight into `useComposer`'s `sendExtras.resources`.\n */\n readyResources: FileResourceRef[];\n /** True while any attachment is still uploading (drives progress UI). */\n uploading: boolean;\n /**\n * True while any attachment still needs an explicit outcome: wait for an\n * upload, retry a failure, or remove it. This is the loss-prevention send\n * gate; failed cards must never be silently omitted from a message.\n */\n hasUnresolved: boolean;\n /** Explicit picker / drop path — uploads every file, no filter. */\n addFiles: (files: Iterable<File>) => void;\n /** Clipboard path — applies `pasteFilter` (default `image/*`) then uploads. */\n addFromPaste: (event: { clipboardData: DataTransfer | null }) => void;\n /** Restore already-ready server assets without recreating browser-local bytes. */\n restoreReadyFiles: (files: Iterable<FileAsset>) => void;\n /**\n * Resolve a ready image's short-lived server preview URL on demand. Optional\n * for upload-only embedded clients; local object-URL previews remain usable\n * without it.\n */\n loadPreview?: ((id: string, signal?: AbortSignal) => Promise<string | undefined>) | undefined;\n /**\n * Re-run the upload for a `failed` attachment, in place (same id, same\n * source file). No-op for an id that isn't a known failed upload.\n */\n retry: (id: string) => void;\n /**\n * Keep an attachment's object-URL alive for a consumer that outlives its\n * queue entry (for example, an open route-level lightbox). The returned\n * release is idempotent; pending revocation finishes after the last holder\n * releases. Returns `undefined` when the attachment has no local preview.\n */\n retainPreview: (id: string) => (() => void) | undefined;\n /** Remove one attachment; revokes its object-URL after retained users finish. */\n remove: (id: string) => void;\n /**\n * Remove only finalized files whose durable ids were accepted by a send.\n * Attachments added while that request was in flight remain queued for the\n * next message.\n */\n removeReadyFiles: (fileIds: Iterable<string>) => void;\n /** Remove all attachments and revoke every unretained object-URL. */\n clear: () => void;\n};\n\nconst isImage = (file: File): boolean => file.type.startsWith(\"image/\");\n\nlet fallbackAttachmentId = 0;\n\nfunction createAttachmentId(): string {\n const cryptoSource = globalThis.crypto;\n if (typeof cryptoSource?.randomUUID === \"function\") return cryptoSource.randomUUID();\n fallbackAttachmentId += 1;\n // This id is only a browser-local React key and retry lookup, never durable\n // authority. Keep attachment tracking usable when HTTP withholds randomUUID\n // or Web Crypto is unavailable so the SDK's typed failure reaches the card.\n return `attachment:${Date.now().toString(36)}:${fallbackAttachmentId.toString(36)}`;\n}\n\nfunction secureContextRequiredErrorCode(error: unknown): \"secure_context_required\" | undefined {\n return typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"secure_context_required\"\n ? error.code\n : undefined;\n}\n\n/**\n * Upload-and-track state for files attached to the next message. Owns the\n * full client-side upload layer: a per-file `uploading | ready | failed`\n * status machine driven by the SDK's `client.uploadFile`, object-URL image\n * previews with create/revoke lifecycle, the `image/*` clipboard paste filter,\n * and a `FileResourceRef[]` projection that drops straight into a message's\n * `resources`. Workspace-scoped, so it resolves both client and workspace from\n * the {@link OpenGeniProvider} (or a per-call `{ client, workspaceId }`).\n */\nexport function useFileAttachments(\n options: UseFileAttachmentsOptions = {},\n): UseFileAttachmentsResult {\n const { client, workspaceId } = useEmbeddedFileAttachments(options);\n const pasteFilter = options.pasteFilter ?? isImage;\n const [attachments, setAttachments] = useState<FileAttachment[]>([]);\n const attachmentsRef = useRef(attachments);\n attachmentsRef.current = attachments;\n // Keep the source File per attachment id so a failed upload can be retried\n // in place. Cleared on remove/clear so it never outlives its attachment.\n const sources = useRef<Map<string, File>>(new Map());\n // Object URLs must be owned synchronously: React may discard an attachment\n // state update when its component unmounts in the same batch that minted the\n // preview. The registry remains available to cleanup even before a render.\n const previewUrls = useRef<Map<string, string>>(new Map());\n const previewRetainers = useRef<Map<string, number>>(new Map());\n const pendingPreviewRevocations = useRef<Set<string>>(new Set());\n const revokePreview = useCallback((id: string) => {\n const previewUrl = previewUrls.current.get(id);\n if (!previewUrl) return;\n if ((previewRetainers.current.get(id) ?? 0) > 0) {\n pendingPreviewRevocations.current.add(id);\n return;\n }\n previewUrls.current.delete(id);\n pendingPreviewRevocations.current.delete(id);\n URL.revokeObjectURL(previewUrl);\n }, []);\n const revokeAllPreviews = useCallback(() => {\n for (const id of previewUrls.current.keys()) revokePreview(id);\n }, [revokePreview]);\n const retainPreview = useCallback(\n (id: string): (() => void) | undefined => {\n if (!previewUrls.current.has(id)) return undefined;\n previewRetainers.current.set(id, (previewRetainers.current.get(id) ?? 0) + 1);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const remaining = (previewRetainers.current.get(id) ?? 1) - 1;\n if (remaining > 0) {\n previewRetainers.current.set(id, remaining);\n return;\n }\n previewRetainers.current.delete(id);\n if (pendingPreviewRevocations.current.has(id)) revokePreview(id);\n };\n },\n [revokePreview],\n );\n // Ready-file reconciliation uses functional state updaters, which React may\n // evaluate during a concurrent render that later suspends or is abandoned.\n // Diff only committed attachment sets here so URL revocation cannot run from\n // render-phase code while the previously committed DOM still uses a preview.\n const committedAttachmentIds = useRef<Set<string>>(new Set());\n useEffect(() => {\n const currentIds = new Set(attachments.map((attachment) => attachment.id));\n for (const id of committedAttachmentIds.current) {\n if (!currentIds.has(id)) revokePreview(id);\n }\n committedAttachmentIds.current = currentIds;\n }, [attachments, revokePreview]);\n // Upload promises are not cancellable at this layer. Fence their settlements\n // when the hook changes client/workspace or unmounts so an old tenant/session\n // cannot mutate the next attachment queue (or an already-unmounted component).\n const scopeGeneration = useRef(0);\n const previousScope = useRef({ client, workspaceId });\n\n useEffect(() => {\n const previous = previousScope.current;\n if (previous.client === client && previous.workspaceId === workspaceId) return;\n previousScope.current = { client, workspaceId };\n scopeGeneration.current += 1;\n sources.current.clear();\n revokeAllPreviews();\n setAttachments([]);\n }, [client, revokeAllPreviews, workspaceId]);\n\n useEffect(\n () => () => {\n scopeGeneration.current += 1;\n sources.current.clear();\n revokeAllPreviews();\n },\n [revokeAllPreviews],\n );\n\n // Run (or re-run) the upload for one already-tracked attachment id. Sets it\n // back to `uploading`, then resolves to `ready` (with the asset) or `failed`\n // (with the error message).\n const startUpload = useCallback(\n (id: string, file: File) => {\n const generation = scopeGeneration.current;\n void client\n .uploadFile(workspaceId, {\n filename: file.name || \"file\",\n contentType: file.type || \"application/octet-stream\",\n data: file,\n ...(options.scope ? { scope: options.scope } : {}),\n })\n .then((asset) => {\n if (scopeGeneration.current !== generation) return;\n // Retry bytes are useful only until durable finalization succeeds.\n // Drop the source File immediately; restored/ready attachments must\n // never retain browser-local byte authority.\n sources.current.delete(id);\n setAttachments((current) =>\n current.map((attachment) =>\n attachment.id === id\n ? {\n ...attachment,\n status: \"ready\",\n file: asset,\n name: asset.filename,\n contentType: asset.contentType,\n sizeBytes: asset.sizeBytes,\n errorCode: undefined,\n error: undefined,\n }\n : attachment,\n ),\n );\n })\n .catch((error: unknown) => {\n if (scopeGeneration.current !== generation) return;\n setAttachments((current) =>\n current.map((attachment) =>\n attachment.id === id\n ? {\n ...attachment,\n status: \"failed\",\n errorCode: secureContextRequiredErrorCode(error),\n error: error instanceof Error ? error.message : String(error),\n }\n : attachment,\n ),\n );\n });\n },\n [client, workspaceId, options.scope],\n );\n\n const addFiles = useCallback(\n (files: Iterable<File>) => {\n for (const file of files) {\n const id = createAttachmentId();\n sources.current.set(id, file);\n const previewUrl = isImage(file) ? URL.createObjectURL(file) : undefined;\n if (previewUrl) previewUrls.current.set(id, previewUrl);\n setAttachments((current) => [\n ...current,\n {\n id,\n name: file.name || \"image\",\n contentType: file.type || \"application/octet-stream\",\n sizeBytes: file.size,\n status: \"uploading\",\n ...(previewUrl ? { previewUrl } : {}),\n },\n ]);\n startUpload(id, file);\n }\n },\n [startUpload],\n );\n\n const retry = useCallback(\n (id: string) => {\n const file = sources.current.get(id);\n if (!file) {\n return;\n }\n setAttachments((current) =>\n current.map((attachment) =>\n attachment.id === id\n ? { ...attachment, status: \"uploading\", errorCode: undefined, error: undefined }\n : attachment,\n ),\n );\n startUpload(id, file);\n },\n [startUpload],\n );\n\n const addFromPaste = useCallback(\n (event: { clipboardData: DataTransfer | null }) => {\n const clipboardFiles = event.clipboardData?.files;\n if (!clipboardFiles) {\n return;\n }\n const files = [...clipboardFiles].filter(pasteFilter);\n if (files.length > 0) {\n addFiles(files);\n }\n },\n [addFiles, pasteFilter],\n );\n\n const restoreReadyFiles = useCallback(\n (files: Iterable<FileAsset>) => {\n const incoming = new Map<string, FileAsset>();\n for (const file of files) {\n if (file.status === \"ready\" && file.workspaceId === workspaceId) {\n incoming.set(file.id, file);\n }\n }\n setAttachments((current) => {\n const unresolved = current.filter((attachment) => attachment.status !== \"ready\");\n const existingReady = new Map(\n current.flatMap((attachment) =>\n attachment.status === \"ready\" && attachment.file\n ? ([[attachment.file.id, attachment]] as const)\n : [],\n ),\n );\n const restored = [...incoming.values()].map((file): FileAttachment => {\n const existing = existingReady.get(file.id);\n return existing\n ? {\n ...existing,\n name: file.filename,\n contentType: file.contentType,\n sizeBytes: file.sizeBytes,\n status: \"ready\",\n file,\n errorCode: undefined,\n error: undefined,\n }\n : {\n id: `restored:${file.id}`,\n name: file.filename,\n contentType: file.contentType,\n sizeBytes: file.sizeBytes,\n status: \"ready\",\n file,\n // No source File and no object URL: server metadata is the\n // only authority restored across page/device boundaries.\n };\n });\n // A server restoration is authoritative for finalized assets, but an\n // upload that has not finalized still belongs to the local actor. Keep\n // those unresolved entries while replacing the ready set exactly.\n return [...unresolved, ...restored];\n });\n },\n [workspaceId],\n );\n\n const loadPreview = useCallback(\n async (id: string, signal?: AbortSignal): Promise<string | undefined> => {\n const generation = scopeGeneration.current;\n const attachment = attachmentsRef.current.find((candidate) => candidate.id === id);\n const createDownloadUrl = client.createFileDownloadUrl;\n if (\n !attachment ||\n attachment.status !== \"ready\" ||\n !attachment.file ||\n !attachment.contentType.startsWith(\"image/\") ||\n typeof createDownloadUrl !== \"function\" ||\n signal?.aborted\n ) {\n return undefined;\n }\n const fileId = attachment.file.id;\n const signed = await createDownloadUrl.call(client, workspaceId, fileId, { signal });\n if (scopeGeneration.current !== generation || signal?.aborted) return undefined;\n const current = attachmentsRef.current.find((candidate) => candidate.id === id);\n if (current?.status !== \"ready\" || current.file?.id !== fileId) return undefined;\n return signed.url;\n },\n [client, workspaceId],\n );\n\n const remove = useCallback(\n (id: string) => {\n sources.current.delete(id);\n revokePreview(id);\n setAttachments((current) => current.filter((attachment) => attachment.id !== id));\n },\n [revokePreview],\n );\n\n const removeReadyFiles = useCallback((fileIds: Iterable<string>) => {\n const accepted = new Set(fileIds);\n if (accepted.size === 0) return;\n setAttachments((current) =>\n current.filter((attachment) => {\n return !(\n attachment.status === \"ready\" &&\n attachment.file !== undefined &&\n accepted.has(attachment.file.id)\n );\n }),\n );\n }, []);\n\n const clear = useCallback(() => {\n sources.current.clear();\n revokeAllPreviews();\n setAttachments([]);\n }, [revokeAllPreviews]);\n\n return {\n attachments,\n readyResources: attachments.flatMap((attachment): FileResourceRef[] =>\n attachment.status === \"ready\" && attachment.file\n ? [{ kind: \"file\", fileId: attachment.file.id }]\n : [],\n ),\n uploading: attachments.some((attachment) => attachment.status === \"uploading\"),\n hasUnresolved: attachments.some((attachment) => attachment.status !== \"ready\"),\n addFiles,\n addFromPaste,\n restoreReadyFiles,\n ...(typeof client.createFileDownloadUrl === \"function\" ? { loadPreview } : {}),\n retry,\n retainPreview,\n remove,\n removeReadyFiles,\n clear,\n };\n}\n","import { OpenGeniApiError, type SessionEvent, type SessionGoal } from \"@opengeni/sdk\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useEmbeddedGoal, type EmbeddedGoalClientOverride } from \"../session-context\";\nimport {\n useDebouncedCallback,\n useMutationRunner,\n usePageLiveActivity,\n useSessionEventTrigger,\n type SessionEventFeedOptions,\n} from \"./internal\";\n\n/** Event types that change the session goal (set/updated/completed/paused/...). */\nexport function isGoalEvent(event: Pick<SessionEvent, \"type\">): boolean {\n return event.type.startsWith(\"goal.\");\n}\n\n/**\n * Events that can change the server-authoritative continuation projection.\n * The projection is derived from durable turn, session, control, and system\n * update state, so those events refresh the goal without model polling.\n */\nexport function isGoalRefreshEvent(event: Pick<SessionEvent, \"type\">): boolean {\n const type = event.type;\n return (\n isGoalEvent(event) ||\n type.startsWith(\"turn.\") ||\n type.startsWith(\"session.\") ||\n type.startsWith(\"system.update.\") ||\n type.startsWith(\"workspace.inference.\") ||\n type.startsWith(\"user.\")\n );\n}\n\nexport type UseGoalOptions = EmbeddedGoalClientOverride &\n SessionEventFeedOptions & {\n /** Optional safety-net polling (ms). Off by default — event refreshes drive updates. */\n pollIntervalMs?: number | undefined;\n };\n\nexport type UseGoalResult = {\n /** The session goal, or null when the session has none. */\n goal: SessionGoal | null;\n /** Convenience flags over `goal.status`. */\n isActive: boolean;\n isPaused: boolean;\n isCompleted: boolean;\n loading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n /** Pause the goal loop (PATCH status=paused). */\n pause: (rationale?: string) => Promise<SessionGoal | null>;\n /** Resume a paused goal: resets counters and re-arms continuations. */\n resume: () => Promise<SessionGoal | null>;\n /** Clear the session goal; goal-less sessions remain a successful no-op. */\n clearGoal: () => Promise<void>;\n /** Alias for `clearGoal`. */\n deleteGoal: () => Promise<void>;\n /** True while a pause/resume/clear is in flight. */\n updating: boolean;\n mutationError: Error | null;\n clearMutationError: () => void;\n};\n\n/**\n * The session's goal: state, the autonomy counters (`autoContinuations`,\n * `noProgressStreak`), and pause/resume control. A goal-less session yields\n * `goal: null` (the 404 is absorbed). Live-updates on goal, turn, session,\n * control, and system-update events — pass `options.events` from\n * `useSessionEvents` to reuse its stream.\n */\nexport function useGoal(\n sessionId: string | null | undefined,\n options: UseGoalOptions = {},\n): UseGoalResult {\n const { client, workspaceId } = useEmbeddedGoal(options);\n const enabled = (options.enabled ?? true) && Boolean(sessionId);\n const sharedEvents = options.events;\n const sharedFeed = sharedEvents !== undefined;\n const pageLive = usePageLiveActivity();\n const [goal, setGoal] = useState<SessionGoal | null>(null);\n const [loading, setLoading] = useState(enabled);\n const [error, setError] = useState<Error | null>(null);\n const { run, mutating, mutationError, clearMutationError } = useMutationRunner();\n const generation = useRef(0);\n const targetKeyRef = useRef<string | null>(null);\n const loadAbort = useRef<AbortController | null>(null);\n\n const retireLoads = useCallback(() => {\n generation.current += 1;\n loadAbort.current?.abort();\n loadAbort.current = null;\n }, []);\n\n const load = useCallback(async (): Promise<void> => {\n if (!sessionId) {\n return;\n }\n const ticket = ++generation.current;\n loadAbort.current?.abort();\n const controller = new AbortController();\n loadAbort.current = controller;\n try {\n const fetched = await client.getGoal(workspaceId, sessionId, {\n signal: controller.signal,\n });\n if (ticket === generation.current) {\n setGoal(fetched);\n setError(null);\n setLoading(false);\n }\n } catch (cause) {\n if (ticket !== generation.current) {\n return;\n }\n if (cause instanceof OpenGeniApiError && cause.status === 404) {\n // No goal is a normal state, not an error.\n setGoal(null);\n setError(null);\n } else {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n }\n setLoading(false);\n } finally {\n if (loadAbort.current === controller) loadAbort.current = null;\n }\n }, [client, workspaceId, sessionId]);\n\n useEffect(() => {\n const targetKey = `${workspaceId} ${sessionId ?? \"\"}`;\n if (targetKeyRef.current !== targetKey) {\n targetKeyRef.current = targetKey;\n setGoal(null);\n setError(null);\n }\n if (!enabled || !pageLive) {\n retireLoads();\n setLoading(false);\n return;\n }\n if (sharedFeed) {\n // A shared log supplies invalidations, not the authoritative goal snapshot.\n setLoading(true);\n void load();\n return () => {\n retireLoads();\n };\n }\n setLoading(true);\n const pollIntervalMs = options.pollIntervalMs;\n if (pollIntervalMs === undefined || pollIntervalMs <= 0) {\n void load();\n return () => {\n retireLoads();\n };\n }\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const schedule = () => {\n if (cancelled) return;\n timer = setTimeout(() => {\n timer = null;\n void load().finally(schedule);\n }, pollIntervalMs);\n };\n void load().finally(schedule);\n return () => {\n cancelled = true;\n if (timer !== null) clearTimeout(timer);\n retireLoads();\n };\n }, [\n load,\n enabled,\n pageLive,\n workspaceId,\n sessionId,\n options.pollIntervalMs,\n retireLoads,\n sharedFeed,\n ]);\n\n const scheduleRefresh = useDebouncedCallback(() => void load());\n useSessionEventTrigger(client, workspaceId, sessionId, isGoalRefreshEvent, scheduleRefresh, {\n enabled,\n ...(sharedEvents !== undefined ? { events: sharedEvents } : {}),\n });\n\n const pause = useCallback(\n async (rationale?: string): Promise<SessionGoal | null> => {\n if (!sessionId) {\n return null;\n }\n const result = await run(() =>\n client.updateGoal(workspaceId, sessionId, {\n status: \"paused\",\n ...(rationale !== undefined ? { rationale } : {}),\n }),\n );\n if (result) {\n setGoal(result);\n }\n return result;\n },\n [client, workspaceId, sessionId, run],\n );\n\n const resume = useCallback(async (): Promise<SessionGoal | null> => {\n if (!sessionId) {\n return null;\n }\n const result = await run(() => client.updateGoal(workspaceId, sessionId, { status: \"active\" }));\n if (result) {\n setGoal(result);\n }\n return result;\n }, [client, workspaceId, sessionId, run]);\n\n const clearGoal = useCallback(async (): Promise<void> => {\n if (!sessionId) {\n return;\n }\n // deleteGoal resolves void, so distinguish success (a truthy sentinel) from\n // mutation.run's null-on-failure. Only a SUCCESSFUL delete hides the goal:\n // a failed one leaves the pill up so its mutationError renders. And invalidate\n // any in-flight load first so a slower getGoal started before the delete can't\n // commit and repopulate the just-cleared goal.\n const ok = await run(async () => {\n await client.deleteGoal(workspaceId, sessionId);\n return true as const;\n });\n if (ok) {\n retireLoads();\n setGoal(null);\n setError(null);\n }\n }, [client, workspaceId, sessionId, run, retireLoads]);\n\n return {\n goal,\n isActive: goal?.status === \"active\",\n isPaused: goal?.status === \"paused\",\n isCompleted: goal?.status === \"completed\",\n loading,\n error,\n refresh: load,\n pause,\n resume,\n clearGoal,\n deleteGoal: clearGoal,\n updating: mutating,\n mutationError,\n clearMutationError,\n };\n}\n","import type { SessionControlResponse, SessionEvent } from \"@opengeni/sdk\";\nimport { useCallback, useLayoutEffect, useRef } from \"react\";\nimport { useEmbeddedSession, type EmbeddedSessionClientOverride } from \"../session-context\";\nimport { useMutationRunner } from \"./internal\";\n\nexport type UseSessionControlOptions = EmbeddedSessionClientOverride;\n\nexport type UseSessionControlResult = {\n pause: (reason?: string) => Promise<SessionControlResponse | null>;\n resume: (reason?: string) => Promise<SessionControlResponse | null>;\n controlling: boolean;\n /** Approve a pending `requires_action` approval. */\n approve: (approvalId: string, message?: string) => Promise<SessionEvent | null>;\n /** Reject a pending `requires_action` approval. */\n reject: (approvalId: string, message?: string) => Promise<SessionEvent | null>;\n /** True while an approval decision is in flight. */\n responding: boolean;\n error: Error | null;\n clearError: () => void;\n};\n\n/**\n * Session pause/resume and approval decisions. Pair with\n * `useSessionEvents` (for `session.requiresAction` payloads carrying the\n * `approvalId`) to render an approval bar.\n */\nexport function useSessionControl(\n sessionId: string | null | undefined,\n options: UseSessionControlOptions = {},\n): UseSessionControlResult {\n const { client, workspaceId } = useEmbeddedSession(options);\n const approvalTargetKey = `${workspaceId}\\u0000${sessionId ?? \"\"}`;\n const pendingApproval = useRef<{\n targetKey: string;\n decisionKey: string;\n clientEventId: string;\n } | null>(null);\n useLayoutEffect(() => {\n if (pendingApproval.current?.targetKey !== approvalTargetKey) {\n pendingApproval.current = null;\n }\n }, [approvalTargetKey]);\n const {\n run: runControl,\n mutating: controlling,\n mutationError: controlError,\n clearMutationError: clearControlError,\n } = useMutationRunner(approvalTargetKey);\n const {\n run: runApproval,\n mutating: responding,\n mutationError: approvalError,\n clearMutationError: clearApprovalError,\n } = useMutationRunner(approvalTargetKey);\n\n const pause = useCallback(\n async (reason?: string): Promise<SessionControlResponse | null> => {\n if (!sessionId) {\n return null;\n }\n return await runControl(() =>\n client.pauseSession(workspaceId, sessionId, reason !== undefined ? { reason } : {}),\n );\n },\n [client, workspaceId, sessionId, runControl],\n );\n\n const resume = useCallback(\n async (reason?: string): Promise<SessionControlResponse | null> => {\n if (!sessionId) return null;\n return await runControl(() =>\n client.resumeSession(workspaceId, sessionId, reason !== undefined ? { reason } : {}),\n );\n },\n [client, workspaceId, sessionId, runControl],\n );\n\n const decide = useCallback(\n async (\n approvalId: string,\n decision: \"approve\" | \"reject\",\n message?: string,\n ): Promise<SessionEvent | null> => {\n if (!sessionId) {\n return null;\n }\n const decisionKey = JSON.stringify([approvalId, decision, message ?? null]);\n if (pendingApproval.current?.decisionKey !== decisionKey) {\n pendingApproval.current = {\n targetKey: approvalTargetKey,\n decisionKey,\n clientEventId: crypto.randomUUID(),\n };\n }\n const clientEventId = pendingApproval.current.clientEventId;\n const accepted = await runApproval(() =>\n client.sendApprovalDecision(workspaceId, sessionId, {\n approvalId,\n decision,\n ...(message !== undefined ? { message } : {}),\n clientEventId,\n }),\n );\n if (\n accepted !== null &&\n pendingApproval.current?.targetKey === approvalTargetKey &&\n pendingApproval.current.clientEventId === clientEventId\n ) {\n pendingApproval.current = null;\n }\n return accepted;\n },\n [approvalTargetKey, client, workspaceId, sessionId, runApproval],\n );\n\n const approve = useCallback(\n async (approvalId: string, message?: string) => await decide(approvalId, \"approve\", message),\n [decide],\n );\n const reject = useCallback(\n async (approvalId: string, message?: string) => await decide(approvalId, \"reject\", message),\n [decide],\n );\n\n const error = approvalError ?? controlError;\n const clearError = useCallback(() => {\n clearControlError();\n clearApprovalError();\n }, [clearControlError, clearApprovalError]);\n\n return {\n pause,\n resume,\n controlling,\n approve,\n reject,\n responding,\n error,\n clearError,\n };\n}\n","import type {\n SessionEvent,\n SessionMcpApprovalPolicy,\n SessionMcpServerMetadata,\n UpdateSessionMcpApprovalPolicyResponse,\n} from \"@opengeni/sdk\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport {\n useEmbeddedSessionMcpApprovalPolicy,\n type EmbeddedSessionMcpApprovalPolicyClientOverride,\n} from \"../session-context\";\nimport {\n useDebouncedCallback,\n useMutationRunner,\n usePolledValue,\n useSessionEventTrigger,\n type SessionEventFeedOptions,\n} from \"./internal\";\n\nexport function isSessionMcpApprovalPolicyEvent(\n event: Pick<SessionEvent, \"type\" | \"payload\">,\n serverId?: string,\n): boolean {\n if (event.type !== \"session.mcp.approval_policy.updated\") {\n return false;\n }\n if (serverId === undefined) {\n return true;\n }\n const payload = event.payload as { serverId?: unknown } | null;\n return payload?.serverId === serverId;\n}\n\nexport type UseSessionMcpApprovalPolicyOptions = EmbeddedSessionMcpApprovalPolicyClientOverride &\n SessionEventFeedOptions & {\n /** Optional safety-net polling (ms). Off by default; policy events drive refreshes. */\n pollIntervalMs?: number | undefined;\n };\n\nexport type UseSessionMcpApprovalPolicyResult = {\n server: SessionMcpServerMetadata | null;\n policy: SessionMcpApprovalPolicy | null;\n loading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n update: (\n policy: SessionMcpApprovalPolicy,\n ) => Promise<UpdateSessionMcpApprovalPolicyResponse | null>;\n updating: boolean;\n clearError: () => void;\n};\n\n/**\n * Read and update one existing session MCP server's approval policy. Updates\n * become effective for the next claimed attempt; current work is unchanged.\n */\nexport function useSessionMcpApprovalPolicy(\n sessionId: string | null | undefined,\n serverId: string | null | undefined,\n options: UseSessionMcpApprovalPolicyOptions = {},\n): UseSessionMcpApprovalPolicyResult {\n const { client, workspaceId } = useEmbeddedSessionMcpApprovalPolicy(options);\n const enabled = (options.enabled ?? true) && Boolean(sessionId && serverId);\n const [override, setOverride] = useState<SessionMcpServerMetadata | null>(null);\n const targetKey = `${workspaceId}\\u0000${sessionId ?? \"\"}\\u0000${serverId ?? \"\"}`;\n const authoritativeGeneration = useRef(0);\n const mutationIdentity = useMemo(() => ({ client, targetKey }), [client, targetKey]);\n const { run, mutating, mutationError, clearMutationError } = useMutationRunner(mutationIdentity);\n\n useLayoutEffect(() => {\n authoritativeGeneration.current += 1;\n setOverride(null);\n }, [client, targetKey]);\n\n type PolicyRead = {\n targetKey: string;\n generation: number;\n server: SessionMcpServerMetadata | null;\n };\n const load = useCallback(async (): Promise<PolicyRead> => {\n const generation = authoritativeGeneration.current;\n if (!sessionId || !serverId) {\n return { targetKey, generation, server: null };\n }\n const session = await client.getSession(workspaceId, sessionId);\n return {\n targetKey,\n generation,\n server: session.mcpServers.find((server) => server.id === serverId) ?? null,\n };\n }, [client, serverId, sessionId, targetKey, workspaceId]);\n const {\n data,\n loading,\n error: loadError,\n refresh,\n } = usePolledValue(load, {\n enabled,\n pollIntervalMs: options.pollIntervalMs,\n });\n useEffect(() => {\n if (data?.targetKey === targetKey && data.generation === authoritativeGeneration.current) {\n setOverride(null);\n }\n }, [data, targetKey]);\n\n const scheduleRefresh = useDebouncedCallback(() => void refresh());\n const matchesPolicyEvent = useCallback(\n (event: Pick<SessionEvent, \"type\" | \"payload\">) =>\n isSessionMcpApprovalPolicyEvent(event, serverId ?? undefined),\n [serverId],\n );\n useSessionEventTrigger(\n client,\n workspaceId,\n sessionId,\n matchesPolicyEvent,\n scheduleRefresh,\n {\n enabled,\n ...(options.events !== undefined ? { events: options.events } : {}),\n },\n async () => await refresh(),\n );\n\n const update = useCallback(\n async (\n policy: SessionMcpApprovalPolicy,\n ): Promise<UpdateSessionMcpApprovalPolicyResponse | null> => {\n if (!sessionId || !serverId) {\n return null;\n }\n const response = await run(() =>\n client.updateSessionMcpApprovalPolicy(workspaceId, sessionId, serverId, {\n requireApproval: policy,\n }),\n );\n if (response) {\n authoritativeGeneration.current += 1;\n setOverride(response.server);\n void refresh();\n }\n return response;\n },\n [client, refresh, run, serverId, sessionId, workspaceId],\n );\n\n const server = override ?? data?.server ?? null;\n return {\n server,\n policy: server?.requireApproval ?? null,\n loading,\n error: mutationError ?? loadError,\n refresh: async () => {\n await refresh();\n },\n update,\n updating: mutating,\n clearError: clearMutationError,\n };\n}\n","import type { SessionEvent, SessionLineageResponse } from \"@opengeni/sdk\";\nimport { useCallback, useEffect, useRef } from \"react\";\nimport {\n useEmbeddedSessionLineage,\n type EmbeddedSessionLineageClientOverride,\n} from \"../session-context\";\nimport { useDebouncedCallback, usePolledValue, useSessionEventTrigger } from \"./internal\";\n\nexport type UseSessionLineageOptions = EmbeddedSessionLineageClientOverride & {\n events?: SessionEvent[] | undefined;\n /** Refresh interval (ms). Off by default. */\n pollIntervalMs?: number | undefined;\n enabled?: boolean | undefined;\n /** Optional shared causal clock invoked when each network read starts. */\n beginRead?: (() => number) | undefined;\n};\n\nexport type UseSessionLineageResult = {\n lineage: SessionLineageResponse | null;\n loading: boolean;\n error: Error | null;\n /** Causal generation captured when the accepted lineage read started. */\n readGeneration: number;\n refresh: () => Promise<void>;\n};\n\nexport function isLineageRefreshEvent(event: SessionEvent): boolean {\n if (event.type === \"session.status.changed\" || event.type === \"session.created\") {\n return true;\n }\n // A child's creation never appears on the PARENT's stream as session.created —\n // the parent sees its own spawn as an agent.toolCall.* for session_create.\n // Created events are handled separately so they can refresh immediately and\n // once after the child row has had time to commit.\n if (event.type === \"agent.toolCall.output\") {\n const payload = event.payload as { name?: unknown; toolName?: unknown } | null | undefined;\n const name =\n typeof payload?.name === \"string\"\n ? payload.name\n : typeof payload?.toolName === \"string\"\n ? payload.toolName\n : \"\";\n return name === \"session_create\" || name.endsWith(\"__session_create\");\n }\n return false;\n}\n\nfunction isSessionCreateToolCallCreated(event: SessionEvent): boolean {\n if (event.type !== \"agent.toolCall.created\") {\n return false;\n }\n const payload = event.payload as { name?: unknown; toolName?: unknown } | null | undefined;\n const name =\n typeof payload?.name === \"string\"\n ? payload.name\n : typeof payload?.toolName === \"string\"\n ? payload.toolName\n : \"\";\n return name === \"session_create\" || name.endsWith(\"__session_create\");\n}\n\n/** Read the ancestors + descendant tree for one session. Data-only; no UI state. */\nexport function useSessionLineage(\n sessionId: string | null | undefined,\n options: UseSessionLineageOptions = {},\n): UseSessionLineageResult {\n const { client, workspaceId, workspaceControlEvent, registerSessionReconciler } =\n useEmbeddedSessionLineage(options);\n const enabled = (options.enabled ?? true) && Boolean(sessionId);\n const nextReadGeneration = useRef(0);\n const beginRead = options.beginRead;\n const load = useCallback(\n async (signal?: AbortSignal) => {\n if (!sessionId) {\n return {\n lineage: { ancestors: [], children: [], truncated: false },\n readGeneration: 0,\n };\n }\n let readGeneration = 0;\n const lineage = await client.getSessionLineage(workspaceId, sessionId, {\n signal,\n onRequestStart: (sharedReadGeneration) => {\n readGeneration = sharedReadGeneration ?? beginRead?.() ?? ++nextReadGeneration.current;\n },\n });\n return {\n lineage,\n readGeneration,\n };\n },\n [beginRead, client, workspaceId, sessionId],\n );\n const state = usePolledValue(load, { pollIntervalMs: options.pollIntervalMs, enabled });\n const refresh = state.refresh;\n useEffect(() => {\n if (enabled && workspaceControlEvent) void refresh();\n }, [enabled, refresh, workspaceControlEvent]);\n useEffect(() => {\n if (!sessionId || !enabled) return;\n return registerSessionReconciler(sessionId, \"lineage\", refresh);\n }, [enabled, refresh, registerSessionReconciler, sessionId]);\n const refreshSoon = useDebouncedCallback(() => void refresh(), 150);\n const delayedChildRefreshRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n // Clear a pending delayed refresh on session/workspace SWITCH (not just\n // unmount): otherwise a timer scheduled for the previous session can fire\n // ~2.5s later and commit that session's lineage onto the new one.\n useEffect(() => {\n return () => {\n if (delayedChildRefreshRef.current !== null) {\n clearTimeout(delayedChildRefreshRef.current);\n delayedChildRefreshRef.current = null;\n }\n };\n }, [sessionId, workspaceId]);\n const refreshAfterChildCreate = useCallback(() => {\n void refresh();\n if (delayedChildRefreshRef.current !== null) {\n clearTimeout(delayedChildRefreshRef.current);\n }\n delayedChildRefreshRef.current = setTimeout(() => {\n delayedChildRefreshRef.current = null;\n void refresh();\n }, 2500);\n }, [refresh]);\n useSessionEventTrigger(\n client,\n workspaceId,\n sessionId,\n isLineageRefreshEvent,\n refreshSoon,\n // SHARED-FEED ONLY: without a caller-provided events log the trigger would\n // open its OWN streamEvents tail — a second live SSE connection next to the\n // session route's useSessionEvents. A caller with no feed opts into polling\n // (pollIntervalMs), never a duplicate stream.\n { events: options.events, enabled: enabled && options.events !== undefined },\n );\n useSessionEventTrigger(\n client,\n workspaceId,\n sessionId,\n isSessionCreateToolCallCreated,\n refreshAfterChildCreate,\n { events: options.events, enabled: enabled && options.events !== undefined },\n );\n return {\n lineage: state.data?.lineage ?? null,\n loading: state.loading,\n error: state.error,\n readGeneration: state.data?.readGeneration ?? 0,\n refresh,\n };\n}\n","import type { SessionEvent } from \"@opengeni/sdk\";\n\n/* ----------------------------------------------------------------------------\n Pending-approvals projection\n\n `session.requiresAction` events live forever in the durable log, so a\n console that replays the log from sequence 0 must not render every\n historical approval as actionable. `projectPendingApprovals` folds the\n ordered event log into the approvals that are still undecided *now*:\n\n - `session.requiresAction` replaces the pending set with the payload's\n approvals (the producer always emits the full currently-pending set, so\n re-emission after a worker re-dispatch cannot duplicate cards);\n - `user.approvalDecision` subtracts the decided approval;\n - the owning turn finishing (`turn.completed`/`turn.failed`/\n `turn.cancelled`) clears the set — whatever was pending died with the\n turn. A `turn.cancelled` for a *different* turn (deleting a queued turn\n while the session waits on an approval) leaves the set alone.\n\n Pure function — same events in, same approvals out — so approve-then-reload\n projects to an empty set instead of a zombie Approve button.\n -------------------------------------------------------------------------- */\n\nexport type PendingApproval = {\n /** The id to send back via `user.approvalDecision` (`approvalId`). */\n id: string;\n /** Tool/function name awaiting the decision. */\n name: string;\n arguments?: unknown;\n /** The raw approval entry from the `session.requiresAction` payload. */\n raw?: unknown;\n};\n\n/** The approvals carried by one `session.requiresAction` payload. */\nexport function approvalsFromRequiresAction(payload: unknown): PendingApproval[] {\n const approvals =\n payload && typeof payload === \"object\"\n ? (payload as { approvals?: unknown }).approvals\n : undefined;\n if (!Array.isArray(approvals)) {\n return [];\n }\n return approvals.map((approval, index) => {\n const raw = (approval && typeof approval === \"object\" ? approval : {}) as Record<\n string,\n unknown\n >;\n const rawItem =\n raw.rawItem && typeof raw.rawItem === \"object\"\n ? (raw.rawItem as Record<string, unknown>)\n : {};\n return {\n // Mirror the runtime's canonical interruption identity before retaining\n // the legacy top-level callId fallback for already-normalized payloads.\n id: String(rawItem.callId ?? rawItem.id ?? raw.id ?? raw.callId ?? raw.name ?? index),\n name: String(raw.name ?? raw.toolName ?? rawItem.name ?? \"approval\"),\n arguments: raw.arguments ?? rawItem.arguments,\n raw: approval,\n };\n });\n}\n\n/** The approvals still awaiting a decision after replaying `events` in order. */\nexport function projectPendingApprovals(events: SessionEvent[]): PendingApproval[] {\n let pending: PendingApproval[] = [];\n let owningTurnId: string | null = null;\n for (const event of events) {\n switch (event.type) {\n case \"session.requiresAction\": {\n pending = approvalsFromRequiresAction(event.payload);\n owningTurnId = event.turnId ?? null;\n break;\n }\n case \"user.approvalDecision\": {\n const payload =\n event.payload && typeof event.payload === \"object\"\n ? (event.payload as { approvalId?: unknown })\n : {};\n if (typeof payload.approvalId === \"string\") {\n pending = pending.filter((approval) => approval.id !== payload.approvalId);\n }\n break;\n }\n case \"turn.completed\":\n case \"turn.failed\":\n case \"turn.cancelled\": {\n // Scope clearing to the turn that raised the approvals when both\n // sides carry a turn id; clear conservatively when either is unknown.\n if (owningTurnId === null || event.turnId == null || event.turnId === owningTurnId) {\n pending = [];\n owningTurnId = null;\n }\n break;\n }\n default:\n break;\n }\n }\n return pending;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,IAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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IACJ;AAAA,EACF;AACA,SAAO;AACT;","names":["useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect","useCallback","useRef","useRef","useCallback","useCallback","useEffect","useLayoutEffect","useRef","useState","useState","useRef","useLayoutEffect","useCallback","server","useEffect","useCallback","useEffect","useRef","useRef","useCallback","useEffect"]}