@mgamadeus/ddd-agents 0.5.17 → 0.6.1

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 (99) hide show
  1. package/README.md +162 -6
  2. package/boundary.json +13 -0
  3. package/dist/chat.js +148 -773
  4. package/dist/chat.js.map +1 -1
  5. package/dist/chunks/{canvas-title-slot-context-DK4sfhkl.js → ConversationMarkdown-BsCjyhj4.js} +14 -43
  6. package/dist/chunks/ConversationMarkdown-BsCjyhj4.js.map +1 -0
  7. package/dist/chunks/{ConversationMessageInputComposerWidgets-B3Zf69rD.js → ConversationMessageInputComposerWidgets-CE8LpyXY.js} +10 -37
  8. package/dist/chunks/ConversationMessageInputComposerWidgets-CE8LpyXY.js.map +1 -0
  9. package/dist/chunks/VoiceBarsIcon-BIcURsBF.js +643 -0
  10. package/dist/chunks/VoiceBarsIcon-BIcURsBF.js.map +1 -0
  11. package/dist/chunks/{WebSearchResultsConversationWidget-887v8Wen.js → WebSearchResultsConversationWidget-DXhfSikV.js} +2 -2
  12. package/dist/chunks/{WebSearchResultsConversationWidget-887v8Wen.js.map → WebSearchResultsConversationWidget-DXhfSikV.js.map} +1 -1
  13. package/dist/chunks/{browser-request-interception-BdKjYz31.js → browser-request-interception-BnzFbH0m.js} +2 -2
  14. package/dist/chunks/{browser-request-interception-BdKjYz31.js.map → browser-request-interception-BnzFbH0m.js.map} +1 -1
  15. package/dist/chunks/{canvas-reducers-CwFA3rQ6.js → canvas-reducers-D-YxAR4B.js} +2 -2
  16. package/dist/chunks/{canvas-reducers-CwFA3rQ6.js.map → canvas-reducers-D-YxAR4B.js.map} +1 -1
  17. package/dist/chunks/canvas-title-slot-context-D6UXrkdJ.js +36 -0
  18. package/dist/chunks/canvas-title-slot-context-D6UXrkdJ.js.map +1 -0
  19. package/dist/chunks/{canvasBodies-C7qqThc9.js → canvasBodies-CQEBkIVw.js} +4 -4
  20. package/dist/chunks/{canvasBodies-C7qqThc9.js.map → canvasBodies-CQEBkIVw.js.map} +1 -1
  21. package/dist/chunks/{canvasStorage-i2wKVSBf.js → canvasStorage-BbEI3h-8.js} +2 -2
  22. package/dist/chunks/{canvasStorage-i2wKVSBf.js.map → canvasStorage-BbEI3h-8.js.map} +1 -1
  23. package/dist/chunks/format-agent-voice-call-duration-C-3hRc9p.js +10 -0
  24. package/dist/chunks/format-agent-voice-call-duration-C-3hRc9p.js.map +1 -0
  25. package/dist/chunks/{link-navigation-CNX8Am2L.js → link-navigation-BUcy5qWW.js} +2 -2
  26. package/dist/chunks/{link-navigation-CNX8Am2L.js.map → link-navigation-BUcy5qWW.js.map} +1 -1
  27. package/dist/chunks/{realtime-arrival-BTLE3jjt.js → realtime-arrival-BfsAPwqQ.js} +8 -3
  28. package/dist/chunks/realtime-arrival-BfsAPwqQ.js.map +1 -0
  29. package/dist/chunks/use-agents-chat-store-CuIkCz9v.js +34 -0
  30. package/dist/chunks/use-agents-chat-store-CuIkCz9v.js.map +1 -0
  31. package/dist/chunks/{widget-name-resolver-BVEuAsW5.js → widget-name-resolver-B9k-s_cF.js} +3 -3
  32. package/dist/chunks/{widget-name-resolver-BVEuAsW5.js.map → widget-name-resolver-B9k-s_cF.js.map} +1 -1
  33. package/dist/chunks/withPollingChangeSubscription-CnQnubfK.js.map +1 -1
  34. package/dist/client-testing.js +4 -4
  35. package/dist/client.js +14 -3
  36. package/dist/client.js.map +1 -1
  37. package/dist/files/i18n-keys.json +1128 -100
  38. package/dist/image-render.js +7 -7
  39. package/dist/index.js +6 -6
  40. package/dist/kit.js +2 -2
  41. package/dist/preview.js +7 -7
  42. package/dist/provider.js +1 -1
  43. package/dist/renderer.js +25 -24
  44. package/dist/renderer.js.map +1 -1
  45. package/dist/styles.css +531 -93
  46. package/dist/types/client/AgentsConversationClient.d.ts +4 -1
  47. package/dist/types/client/http/createAgentsHttpConversationClient.d.ts +2 -1
  48. package/dist/types/entries/voice-admin.d.ts +7 -0
  49. package/dist/types/entries/voice.d.ts +24 -0
  50. package/dist/types/ui/account-realtime.d.ts +50 -11
  51. package/dist/types/voice/AgentVoiceCallBand/AgentVoiceCallBand.d.ts +49 -0
  52. package/dist/types/voice/AgentVoiceCallBand/agent-voice-call-outcome-title-text-key.d.ts +8 -0
  53. package/dist/types/voice/AgentVoiceCallCaptions/AgentVoiceCallCaptions.d.ts +15 -0
  54. package/dist/types/voice/AgentVoiceCallCaptions/saved-messages-of-agent-voice-chat.d.ts +12 -0
  55. package/dist/types/voice/AgentVoiceCallProvider/AgentVoiceCallProvider.d.ts +21 -0
  56. package/dist/types/voice/AgentVoiceCallProvider/agent-voice-call-context.d.ts +17 -0
  57. package/dist/types/voice/AgentVoiceChatStartButton/AgentVoiceChatStartButton.d.ts +15 -0
  58. package/dist/types/voice/AgentVoiceIcons/AgentVoiceIcons.d.ts +10 -0
  59. package/dist/types/voice/AgentVoiceIncomingCall/AgentVoiceIncomingCall.d.ts +28 -0
  60. package/dist/types/voice/AgentVoiceInputGlow/AgentVoiceInputGlow.d.ts +11 -0
  61. package/dist/types/voice/AgentVoiceInputGlow/agent-voice-input-glow-voice.d.ts +8 -0
  62. package/dist/types/voice/admin/AgentVoiceCallConversationLink/AgentVoiceCallConversationLink.d.ts +10 -0
  63. package/dist/types/voice/admin/AgentVoiceCallDetailScreen/AgentVoiceCallDetailScreen.d.ts +27 -0
  64. package/dist/types/voice/admin/AgentVoiceCallStateBadges/AgentVoiceCallStateBadges.d.ts +12 -0
  65. package/dist/types/voice/admin/AgentVoiceCallsScreen/AgentVoiceCallsScreen.d.ts +33 -0
  66. package/dist/types/voice/admin/agent-voice-admin-api.d.ts +59 -0
  67. package/dist/types/voice/admin/agent-voice-admin-format.d.ts +39 -0
  68. package/dist/types/voice/admin/agent-voice-admin-types.d.ts +114 -0
  69. package/dist/types/voice/agent-voice-api.d.ts +114 -0
  70. package/dist/types/voice/call/agent-voice-call-elapsed-seconds.d.ts +6 -0
  71. package/dist/types/voice/call/agent-voice-call-end-reasons.d.ts +3 -0
  72. package/dist/types/voice/call/agent-voice-call-store.d.ts +111 -0
  73. package/dist/types/voice/call/agent-voice-call-turn.d.ts +4 -0
  74. package/dist/types/voice/call/build-unsaved-agent-voice-call-lines.d.ts +14 -0
  75. package/dist/types/voice/call/format-agent-voice-call-duration.d.ts +2 -0
  76. package/dist/types/voice/call/use-agent-voice-call-elapsed-seconds.d.ts +3 -0
  77. package/dist/types/voice/call/use-agent-voice-call-server-end.d.ts +15 -0
  78. package/dist/types/voice/call/use-agent-voice-call.d.ts +12 -0
  79. package/dist/types/voice/call/use-follow-agent-voice-call-conversation.d.ts +9 -0
  80. package/dist/types/voice/ring/agent-voice-caller-label.d.ts +21 -0
  81. package/dist/types/voice/ring/agent-voice-incoming-ring-list.d.ts +10 -0
  82. package/dist/types/voice/ring/agent-voice-incoming-ring-store.d.ts +47 -0
  83. package/dist/types/voice/ring/agent-voice-ring-source.d.ts +60 -0
  84. package/dist/types/voice/ring/agent-voice-ring.d.ts +35 -0
  85. package/dist/types/voice/ring/answer-incoming-agent-voice-call.d.ts +13 -0
  86. package/dist/types/voice/ring/use-agent-voice-incoming-rings.d.ts +14 -0
  87. package/dist/types/voice/ring/use-agent-voice-ring-tone.d.ts +6 -0
  88. package/dist/ui.js +82 -19
  89. package/dist/ui.js.map +1 -1
  90. package/dist/voice-admin.js +738 -0
  91. package/dist/voice-admin.js.map +1 -0
  92. package/dist/voice.js +1568 -0
  93. package/dist/voice.js.map +1 -0
  94. package/dist/widgets.js +4 -4
  95. package/package.json +27 -1
  96. package/public-api.json +155 -0
  97. package/dist/chunks/ConversationMessageInputComposerWidgets-B3Zf69rD.js.map +0 -1
  98. package/dist/chunks/canvas-title-slot-context-DK4sfhkl.js.map +0 -1
  99. package/dist/chunks/realtime-arrival-BTLE3jjt.js.map +0 -1
package/public-api.json CHANGED
@@ -998,6 +998,7 @@
998
998
  "types": [
999
999
  "AccountRealtimePoll",
1000
1000
  "AccountRealtimePollOptions",
1001
+ "AccountRealtimePollSubscriber",
1001
1002
  "AccountRealtimeRead",
1002
1003
  "AgentRealtimeListenerCredential",
1003
1004
  "AgentRealtimeMessageDelivery",
@@ -1045,5 +1046,159 @@
1045
1046
  "ScreenTargetSource",
1046
1047
  "TableFacts"
1047
1048
  ]
1049
+ },
1050
+ "./voice": {
1051
+ "values": [
1052
+ "AGENT_VOICE_ANSWER_REFUSAL_TEXT_KEYS",
1053
+ "AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT",
1054
+ "AGENT_VOICE_CALL_END_REASON_LIMIT_REACHED",
1055
+ "AGENT_VOICE_ERROR_CODE_INVALID_OPEN_ANSWER",
1056
+ "AGENT_VOICE_RING_MESSAGE_TYPE",
1057
+ "AgentVoiceAccountRealtimeRingSource",
1058
+ "AgentVoiceApiError",
1059
+ "AgentVoiceBarsIcon",
1060
+ "AgentVoiceCallBand",
1061
+ "AgentVoiceCallBandView",
1062
+ "AgentVoiceCallCaptions",
1063
+ "AgentVoiceCallProvider",
1064
+ "AgentVoiceChatStartButton",
1065
+ "AgentVoiceIncomingCall",
1066
+ "AgentVoiceInputGlow",
1067
+ "IDLE_AGENT_VOICE_CALL",
1068
+ "acceptAgentVoiceIncomingRing",
1069
+ "bindAgentVoiceApi",
1070
+ "buildAgentVoiceCallerLabel",
1071
+ "buildAgentVoiceRequests",
1072
+ "buildUnsavedAgentVoiceCallLines",
1073
+ "checkAgentVoiceCallEndedOnServer",
1074
+ "createAgentVoiceApi",
1075
+ "createAgentVoiceFetchBaseApi",
1076
+ "createAgentVoiceRingSource",
1077
+ "declineAgentVoiceIncomingRing",
1078
+ "dismissAgentVoiceCallOutcome",
1079
+ "endAgentVoiceCallFromServer",
1080
+ "formatAgentVoiceCallDuration",
1081
+ "hangUpAgentVoiceCall",
1082
+ "isAgentVoiceCallActive",
1083
+ "isAgentVoiceCallShownInAgentSpace",
1084
+ "pickAgentVoiceCallerLabelTextKey",
1085
+ "pickAgentVoiceIncomingCard",
1086
+ "pickRingingAgentVoiceCall",
1087
+ "readAgentVoiceCallSnapshot",
1088
+ "readAgentVoiceErrorCode",
1089
+ "readAgentVoiceIncomingRingSnapshot",
1090
+ "readAgentVoiceRingOfRealtimeMessage",
1091
+ "startAgentVoiceCall",
1092
+ "toggleAgentVoiceCallMute",
1093
+ "turnOfAgentVoiceCall",
1094
+ "useAgentVoiceCall",
1095
+ "useAgentVoiceCallElapsedSeconds",
1096
+ "useAgentVoiceCallServerEnd",
1097
+ "useAgentVoiceCallSnapshot",
1098
+ "useAgentVoiceCallValue",
1099
+ "useAgentVoiceIncomingRing",
1100
+ "useAgentVoiceRingBandHost",
1101
+ "useAgentVoiceRingCover",
1102
+ "useAgentVoiceRingTone",
1103
+ "useAgentVoiceTranslateText",
1104
+ "useIsAgentVoiceCallActive"
1105
+ ],
1106
+ "types": [
1107
+ "AgentVoiceAdminCall",
1108
+ "AgentVoiceAdminCallDerivedValues",
1109
+ "AgentVoiceAdminCallDirection",
1110
+ "AgentVoiceAdminCallEndReason",
1111
+ "AgentVoiceAdminCallIdArg",
1112
+ "AgentVoiceAdminCallResponse",
1113
+ "AgentVoiceAdminCallState",
1114
+ "AgentVoiceAdminCallsArg",
1115
+ "AgentVoiceAdminCallsResponse",
1116
+ "AgentVoiceAdminChangeHistory",
1117
+ "AgentVoiceAdminCurrency",
1118
+ "AgentVoiceAdminElements",
1119
+ "AgentVoiceAdminMoneyAmount",
1120
+ "AgentVoiceAnswerRefusal",
1121
+ "AgentVoiceApi",
1122
+ "AgentVoiceBaseApi",
1123
+ "AgentVoiceCall",
1124
+ "AgentVoiceCallBandProps",
1125
+ "AgentVoiceCallBandViewProps",
1126
+ "AgentVoiceCallCaptionsProps",
1127
+ "AgentVoiceCallIncomingRing",
1128
+ "AgentVoiceCallLine",
1129
+ "AgentVoiceCallPhase",
1130
+ "AgentVoiceCallProviderProps",
1131
+ "AgentVoiceCallSnapshot",
1132
+ "AgentVoiceCallSpeaker",
1133
+ "AgentVoiceCallTurn",
1134
+ "AgentVoiceCallerLabel",
1135
+ "AgentVoiceCallerLabelTextKey",
1136
+ "AgentVoiceChatStartButtonProps",
1137
+ "AgentVoiceConversationChangeSubscription",
1138
+ "AgentVoiceConversationOfCallChangedHandler",
1139
+ "AgentVoiceFetchOptions",
1140
+ "AgentVoiceIconProps",
1141
+ "AgentVoiceIncomingCallProps",
1142
+ "AgentVoiceIncomingRingSnapshot",
1143
+ "AgentVoiceInputGlowProps",
1144
+ "AgentVoiceRequest",
1145
+ "AgentVoiceRing",
1146
+ "AgentVoiceRingSource",
1147
+ "AgentVoiceTranslateText",
1148
+ "CreateAgentVoiceApiOptions",
1149
+ "CreateAgentVoiceFetchBaseApiOptions",
1150
+ "SavedAgentVoiceCallMessage",
1151
+ "StartAgentVoiceCallParams"
1152
+ ]
1153
+ },
1154
+ "./voice/admin": {
1155
+ "values": [
1156
+ "AGENT_VOICE_ADMIN_ERROR_CALL_NOT_FOUND",
1157
+ "AGENT_VOICE_ADMIN_ERROR_FEATURE_NOT_AVAILABLE",
1158
+ "AGENT_VOICE_CALLS_MAX_PAGE_SIZE",
1159
+ "AGENT_VOICE_CALLS_TAG",
1160
+ "AGENT_VOICE_CALL_DIRECTION",
1161
+ "AGENT_VOICE_CALL_END_REASON",
1162
+ "AGENT_VOICE_CALL_END_REASONS",
1163
+ "AGENT_VOICE_CALL_STATE",
1164
+ "AgentVoiceCallConversationLink",
1165
+ "AgentVoiceCallDetailScreen",
1166
+ "AgentVoiceCallStateBadges",
1167
+ "AgentVoiceCallsScreen",
1168
+ "agentVoiceAdminCallDerivedValuesByCallIdOf",
1169
+ "agentVoiceAdminCallDurationInSecondsOf",
1170
+ "agentVoiceAdminCallStartTimeOf",
1171
+ "agentVoiceAdminEndpointDefinitions",
1172
+ "buildAgentVoiceAdminCallsFilters",
1173
+ "buildAgentVoiceAdminRequests",
1174
+ "createAgentVoiceAdminApi",
1175
+ "createStaticAgentVoiceAdminApi",
1176
+ "formatAgentVoiceAdminCallCosts",
1177
+ "isAgentVoiceAdminError",
1178
+ "readAgentVoiceAdminWholeNumber",
1179
+ "toAgentVoiceAdminDayBound"
1180
+ ],
1181
+ "types": [
1182
+ "AgentVoiceAdminApi",
1183
+ "AgentVoiceAdminCall",
1184
+ "AgentVoiceAdminCallDerivedValues",
1185
+ "AgentVoiceAdminCallDirection",
1186
+ "AgentVoiceAdminCallEndReason",
1187
+ "AgentVoiceAdminCallIdArg",
1188
+ "AgentVoiceAdminCallResponse",
1189
+ "AgentVoiceAdminCallState",
1190
+ "AgentVoiceAdminCallsArg",
1191
+ "AgentVoiceAdminCallsResponse",
1192
+ "AgentVoiceAdminChangeHistory",
1193
+ "AgentVoiceAdminCurrency",
1194
+ "AgentVoiceAdminElements",
1195
+ "AgentVoiceAdminMoneyAmount",
1196
+ "AgentVoiceCallConversationLinkProps",
1197
+ "AgentVoiceCallDetailScreenProps",
1198
+ "AgentVoiceCallStateBadgesProps",
1199
+ "AgentVoiceCallsScreenProps",
1200
+ "CreateAgentVoiceAdminApiOptions",
1201
+ "StaticAgentVoiceAdminData"
1202
+ ]
1048
1203
  }
1049
1204
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"ConversationMessageInputComposerWidgets-B3Zf69rD.js","sources":["../../src/chat/store/agents-chat-state.ts","../../src/chat/store/conversation-error-type.ts","../../src/chat/store/merge-chat-messages.ts","../../src/chat/store/reduce-agents-chat-state.ts","../../src/chat/store/create-agents-chat-store.ts","../../src/chat/store/use-agents-chat-store.tsx","../../src/renderer/ConversationWidgetContext.tsx","../../src/chat/ConversationMessageInput/ConversationMessageInputComposerWidgets/ConversationMessageInputComposerWidgets.tsx"],"sourcesContent":["import type {\n AgentsClientError,\n AgentsConversation,\n AgentsConversationMessage,\n PostedMessage,\n StartedConversation,\n} from \"../../contract/conversation\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { CanvasCreatedEntity, CanvasSliceState } from \"../../renderer/canvas/canvas-reducers\";\nimport type { CanvasOpenRequest } from \"../../renderer/canvas/canvas-state\";\nimport type { ConversationErrorType } from \"./conversation-error-type\";\n\n/**\n * How an entry point outside the chat hands a job over to the chat that opens next (one generic opening\n * request): the first visible message, or an invisible start signal so the agent speaks first, the entry point the\n * start comes from, and a widget to mount without a message (a page handing over a tool). Set before the chat mounts,\n * so a reset keeps it; the chat clears each part once it consumed it.\n */\nexport interface AgentsChatOpeningRequest {\n /** The first visible owner message of the next started conversation. */\n userMessage: string | null;\n /** The invisible start signal of the next started conversation (an empty visible message carries it). */\n startSignalText: string | null;\n /** The entry point the start comes from; the server reopens that entry point's recent conversation instead. */\n entryPointKey: string | null;\n /** The canonical wire name of a deep-linkable widget the chat mounts once, without a message. */\n deepLinkedWidgetName: string | null;\n}\n\n/** The state of one chat instance. */\nexport interface AgentsChatState extends CanvasSliceState {\n /** The conversation shown; null for a cold chat until a start or the metadata read brings it. */\n conversation: AgentsConversation | null;\n /** Null until the first page or a send; ordered by `indexInConversation`, the optimistic message last. */\n messages: ChatMessage[] | null;\n /** A send is on its way. */\n conversationLoading: boolean;\n /** The last read or send for this conversation came back. */\n conversationLoaded: boolean;\n /** An older page exists: the scroll-up load stays armed. */\n hasMoreOlder: boolean;\n /** The agent works on a turn (the controller mirrors the derived activity here; read by the launcher). */\n aiThinking: boolean;\n error: ConversationErrorType | null;\n /** Seconds until the quota frees up again; set only while `error` is RATE_LIMIT. */\n rateLimitRetryAfterSeconds: number | null;\n /**\n * The conversation the newest metadata or page read asked for; null after a reset. A late answer for another\n * conversation — or one that lands after a reset — is dropped.\n */\n requestedConversationId: number | null;\n /** A start is on its way; no second start is sent meanwhile. */\n startingNewConversation: boolean;\n /** The token of the start on its way; its answer applies only while it is still the pending one. */\n pendingStartToken: number | null;\n /**\n * How many starts this chat instance sent — the source of `pendingStartToken`. Survives a reset (like\n * `canvasMountCount`): the store outlives a remount of the chat, so a token is never reused for another start.\n */\n startTokenCount: number;\n openingRequest: AgentsChatOpeningRequest;\n}\n\nexport const EMPTY_AGENTS_CHAT_OPENING_REQUEST: AgentsChatOpeningRequest = {\n userMessage: null,\n startSignalText: null,\n entryPointKey: null,\n deepLinkedWidgetName: null,\n};\n\nexport const INITIAL_AGENTS_CHAT_STATE: AgentsChatState = {\n conversation: null,\n messages: null,\n conversationLoading: false,\n conversationLoaded: false,\n hasMoreOlder: false,\n aiThinking: false,\n error: null,\n rateLimitRetryAfterSeconds: null,\n requestedConversationId: null,\n startingNewConversation: false,\n pendingStartToken: null,\n startTokenCount: 0,\n openingRequest: EMPTY_AGENTS_CHAT_OPENING_REQUEST,\n canvas: null,\n lastClosedCanvas: null,\n canvasMountCount: 0,\n};\n\n/**\n * What happens to a chat instance. The read and send events carry the port's answers (`AgentsConversationClient`);\n * the controller dispatches the `…Requested` event before it calls the port and the `…Received` / `…Failed` event\n * with the answer.\n */\nexport type AgentsChatEvent =\n /** A conversation switch, an empty chat, the chat's unmount: everything goes except the opening request and the two counters. */\n | { type: \"reset\" }\n | { type: \"conversationMetadataRequested\"; conversationId: number }\n | { type: \"conversationMetadataReceived\"; conversationId: number; conversation: AgentsConversation }\n | { type: \"conversationMetadataFailed\"; conversationId: number }\n | { type: \"messagesPageRequested\"; conversationId: number }\n /** `hasMoreOlder` null: a changed-messages read, which says nothing about older pages. */\n | {\n type: \"messagesPageReceived\";\n conversationId: number;\n messages: AgentsConversationMessage[];\n hasMoreOlder: boolean | null;\n }\n | { type: \"messagePostRequested\"; message: ChatMessage }\n | { type: \"messagePostReceived\"; conversationId: number; posted: PostedMessage }\n | { type: \"messagePostFailed\"; error: AgentsClientError }\n /** Takes the next start token (`pendingStartToken`); the controller reads it after the dispatch. */\n | { type: \"startRequested\"; message: ChatMessage }\n | { type: \"startReceived\"; startToken: number; started: StartedConversation }\n | { type: \"startFailed\"; error: AgentsClientError }\n | { type: \"errorSet\"; error: ConversationErrorType | null }\n | { type: \"aiThinkingSet\"; aiThinking: boolean }\n /** Sets the named parts of the opening request; the others stay. */\n | { type: \"openingRequestSet\"; openingRequest: Partial<AgentsChatOpeningRequest> }\n | { type: \"canvasOpened\"; request: CanvasOpenRequest }\n | { type: \"canvasClosed\"; byCustomer: boolean }\n | { type: \"canvasResetForNewTurn\" }\n | { type: \"canvasCleared\" }\n | { type: \"canvasCreatedEntityIdSet\"; created: CanvasCreatedEntity };\n","import type { AgentsClientError } from \"../../contract/conversation\";\n\n/**\n * The error card the chat shows. A plain object with string values (not a TypeScript `enum`), so the chat store, the\n * view and an app's older chat state share one vocabulary without a nominal type in between.\n */\nexport const ConversationErrorType = {\n AI_BUDGET: \"AI_BUDGET\",\n /**\n * HTTP 429 from an AI endpoint — a per-minute/hour/day usage quota was hit. Distinct from AI_BUDGET (monthly budget):\n * this one clears on its own after the Retry-After window.\n */\n RATE_LIMIT: \"RATE_LIMIT\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n CONVERSATION_NOT_FOUND: \"CONVERSATION_NOT_FOUND\",\n /**\n * The backend run FAILED (e.g. the model provider returned an error). The raw provider error is admin-only (never\n * shown here); the owner gets a generic \"something went wrong\" card.\n */\n AGENT_ERROR: \"AGENT_ERROR\",\n /**\n * The conversation is COMPLETED/CANCELLED and refuses further owner input. Set from the server's stable error code\n * `CONVERSATION_CLOSED` or by the chat's own pre-send guard; the error card owns the copy.\n */\n CONVERSATION_CLOSED: \"CONVERSATION_CLOSED\",\n} as const;\n\nexport type ConversationErrorType = (typeof ConversationErrorType)[keyof typeof ConversationErrorType];\n\n/**\n * The error card of a refused send (post or start), read from the port's error. Only the stable outcomes select a\n * dedicated card; every other refusal is a generic network error — the same classification the older chat applies to\n * the server's error codes (`AI_BUDGET_REACHED`, `RATE_LIMIT_EXCEEDED`, `CONVERSATION_CLOSED`).\n */\nexport const readConversationErrorTypeOfRefusedSend = (error: AgentsClientError): ConversationErrorType => {\n if (error.kind === \"budget\") return ConversationErrorType.AI_BUDGET;\n if (error.kind === \"rateLimit\") return ConversationErrorType.RATE_LIMIT;\n if (error.kind === \"closed\") return ConversationErrorType.CONVERSATION_CLOSED;\n return ConversationErrorType.NETWORK_ERROR;\n};\n","import type { ChatMessage } from \"../chat-message\";\n\n/**\n * Merges two message lists by `indexInConversation`, preferring `incoming` on a collision, sorted ascending by index.\n * Messages without an index (the optimistic owner message) cannot be matched, so they follow the indexed ones in order.\n * A start or post answer carries the whole list and a live read brings it again: concatenating would show every\n * message twice.\n */\nexport const mergeChatMessagesByIndex = (existing: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] => {\n const messagesByIndex = new Map<number, ChatMessage>();\n const messagesWithoutIndex: ChatMessage[] = [];\n const collectMessage = (message: ChatMessage) => {\n if (message.indexInConversation != null) {\n messagesByIndex.set(message.indexInConversation, message);\n } else {\n messagesWithoutIndex.push(message);\n }\n };\n existing.forEach(collectMessage);\n incoming.forEach(collectMessage);\n const indexedMessages = Array.from(messagesByIndex.values()).sort(\n (first, second) => (first.indexInConversation ?? 0) - (second.indexInConversation ?? 0),\n );\n return [...indexedMessages, ...messagesWithoutIndex];\n};\n\n/**\n * Tags the messages of a send's answer: `fresh` when the id was not in the list before — the server just delivered it,\n * so its one-shot widgets may fire; a replayed message never fires them again.\n */\nexport const tagFreshChatMessages = (incoming: ChatMessage[], previousMessages: ChatMessage[]): ChatMessage[] => {\n const previousIds = new Set(previousMessages.map((message) => message.id).filter((id): id is number => id != null));\n return incoming.map((message) => ({ ...message, fresh: message.id != null && !previousIds.has(message.id) }));\n};\n\n/**\n * Merges a page of a keyset read (the newest page, an older page, the changed tail) into the loaded messages by index.\n * A message is `fresh` only when it is a live arrival: never shown before and newer than everything loaded — so the\n * streamed reply opens its canvas while a scroll-up page and the first page on open stay history. A message already\n * shown keeps its tag. A page of another conversation than the one shown replaces the list.\n */\nexport const mergeMessagesPage = (\n loadedMessages: ChatMessage[] | null,\n page: ChatMessage[],\n requestedConversationId: number,\n): ChatMessage[] => {\n const shownConversationId = loadedMessages?.find((message) => message.conversationId != null)?.conversationId;\n const replacesShownConversation = shownConversationId != null && shownConversationId !== requestedConversationId;\n const existingMessages = replacesShownConversation ? [] : (loadedMessages ?? []);\n const messagesByIndex = new Map<number, ChatMessage>();\n for (const existingMessage of existingMessages) {\n if (existingMessage.indexInConversation != null) {\n messagesByIndex.set(existingMessage.indexInConversation, existingMessage);\n }\n }\n const hadMessagesBeforeMerge = existingMessages.length > 0;\n const highestShownIndex = Math.max(-1, ...existingMessages.map((message) => message.indexInConversation ?? -1));\n for (const incomingMessage of page) {\n if (incomingMessage.indexInConversation == null) continue;\n const previousMessage = messagesByIndex.get(incomingMessage.indexInConversation);\n const isLiveArrival =\n hadMessagesBeforeMerge && previousMessage == null && incomingMessage.indexInConversation > highestShownIndex;\n messagesByIndex.set(incomingMessage.indexInConversation, {\n ...incomingMessage,\n fresh: previousMessage?.fresh ?? isLiveArrival,\n });\n }\n return Array.from(messagesByIndex.values()).sort(\n (first, second) => (first.indexInConversation ?? 0) - (second.indexInConversation ?? 0),\n );\n};\n","import {\n applyClearCanvas,\n applyCloseCanvas,\n applyOpenCanvas,\n applyResetCanvasForNewTurn,\n applySetCanvasCreatedEntityId,\n} from \"../../renderer/canvas/canvas-reducers\";\nimport type { AgentsClientError } from \"../../contract/conversation\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { type AgentsChatEvent, type AgentsChatState, INITIAL_AGENTS_CHAT_STATE } from \"./agents-chat-state\";\nimport { ConversationErrorType, readConversationErrorTypeOfRefusedSend } from \"./conversation-error-type\";\nimport { mergeChatMessagesByIndex, mergeMessagesPage, tagFreshChatMessages } from \"./merge-chat-messages\";\n\n/** The error card and the quota wait of a refused send. */\nconst withRefusedSendError = (state: AgentsChatState, error: AgentsClientError): AgentsChatState => {\n const conversationErrorType = readConversationErrorTypeOfRefusedSend(error);\n return {\n ...state,\n error: conversationErrorType,\n rateLimitRetryAfterSeconds:\n conversationErrorType === ConversationErrorType.RATE_LIMIT ? (error.retryAfterSeconds ?? null) : null,\n };\n};\n\n/**\n * The messages a send's answer brings, merged over the loaded ones without the optimistic message it answers. The\n * optimistic owner rows are the rows without an index; the answer replaces the one whose text its saved owner row\n * carries (else the oldest one) — not blindly \"the last row\": a live read that merged in between already moved\n * indexed rows behind it, and dropping the last row then removed a real message and kept the optimistic one (a second\n * owner bubble, the activity line stuck on). A second message sent while the first was in flight keeps its bubble.\n */\nconst mergeSendAnswer = (loadedMessages: ChatMessage[] | null, answerMessages: ChatMessage[]): ChatMessage[] => {\n const optimisticMessages = (loadedMessages ?? []).filter((message) => message.indexInConversation == null);\n const answeredOwnerTexts = answerMessages\n .filter((message) => message.role === \"USER\" && message.indexInConversation != null)\n .map((message) => message.message ?? \"\");\n let replacedOptimisticMessage: ChatMessage | undefined =\n optimisticMessages.find((message) => answeredOwnerTexts.includes(message.message ?? \"\")) ?? optimisticMessages[0];\n const messagesWithoutOptimisticMessage = (loadedMessages ?? []).filter((message) => {\n if (message === replacedOptimisticMessage) {\n replacedOptimisticMessage = undefined;\n return false;\n }\n return true;\n });\n return mergeChatMessagesByIndex(\n messagesWithoutOptimisticMessage,\n tagFreshChatMessages(answerMessages, messagesWithoutOptimisticMessage),\n );\n};\n\n/** The canvas transitions mutate the fields of the object they get (`canvas-reducers.ts`); this keeps the state immutable. */\nconst withCanvasTransition = (\n state: AgentsChatState,\n applyCanvasTransition: (nextState: AgentsChatState) => void,\n): AgentsChatState => {\n const nextState = { ...state };\n applyCanvasTransition(nextState);\n const changed =\n nextState.canvas !== state.canvas ||\n nextState.lastClosedCanvas !== state.lastClosedCanvas ||\n nextState.canvasMountCount !== state.canvasMountCount;\n return changed ? nextState : state;\n};\n\n/**\n * The chat store's reducer: plain functions over the contract types. Each case is the one of the older\n * chat state (a Redux slice and its cases) it replaces, reading the port's answers instead of the\n * generated client's actions; the replay spec feeds both the same recorded sequence.\n */\nexport const reduceAgentsChatState = (state: AgentsChatState, event: AgentsChatEvent): AgentsChatState => {\n switch (event.type) {\n case \"reset\":\n // The opening request is set from outside before the chat mounts (a cold chat resets as it comes up); the canvas\n // mount count and the start token count are monotonic sources of identities: all three survive.\n return {\n ...INITIAL_AGENTS_CHAT_STATE,\n openingRequest: state.openingRequest,\n canvasMountCount: state.canvasMountCount,\n startTokenCount: state.startTokenCount,\n };\n\n case \"conversationMetadataRequested\":\n case \"messagesPageRequested\":\n return state.requestedConversationId === event.conversationId\n ? state\n : { ...state, requestedConversationId: event.conversationId };\n\n case \"conversationMetadataReceived\":\n // Dropped after a reset or when another conversation was asked for since: a late answer would put the old\n // conversation back, and the next send would post into it instead of starting a new one.\n if (state.requestedConversationId === null || state.requestedConversationId !== event.conversationId) {\n return state;\n }\n return { ...state, conversation: event.conversation, conversationLoaded: true };\n\n case \"conversationMetadataFailed\":\n // A metadata read is best-effort: the chat stays as it is.\n return { ...state, conversationLoaded: true };\n\n case \"messagesPageReceived\": {\n if (state.requestedConversationId === null || state.requestedConversationId !== event.conversationId) {\n return state;\n }\n if (state.conversation !== null && state.conversation.id !== event.conversationId) {\n return state;\n }\n return {\n ...state,\n messages: mergeMessagesPage(state.messages, event.messages, event.conversationId),\n hasMoreOlder: event.hasMoreOlder ?? state.hasMoreOlder,\n conversationLoaded: true,\n };\n }\n\n case \"messagePostRequested\":\n return {\n ...state,\n conversationLoading: true,\n conversationLoaded: false,\n aiThinking: true,\n error: null,\n rateLimitRetryAfterSeconds: null,\n messages: [...(state.messages ?? []), event.message],\n };\n\n case \"messagePostReceived\":\n if (event.conversationId !== state.conversation?.id) {\n return state;\n }\n // The reply arrives through live updates, not in this answer: `aiThinking` stays as it is.\n return {\n ...state,\n messages: mergeSendAnswer(state.messages, event.posted.messages),\n conversationLoading: false,\n conversationLoaded: true,\n error: null,\n };\n\n case \"messagePostFailed\":\n return withRefusedSendError(\n { ...state, conversationLoading: false, conversationLoaded: true, aiThinking: false },\n event.error,\n );\n\n case \"startRequested\":\n return {\n ...state,\n conversation: null,\n conversationLoading: true,\n conversationLoaded: false,\n aiThinking: true,\n error: null,\n rateLimitRetryAfterSeconds: null,\n startingNewConversation: true,\n startTokenCount: state.startTokenCount + 1,\n pendingStartToken: state.startTokenCount + 1,\n // A signal-only start (an empty visible message carries the start signal) seeds no empty bubble.\n messages: event.message.message ? [event.message] : [],\n };\n\n case \"startReceived\": {\n if (event.startToken !== state.pendingStartToken) {\n return state;\n }\n const { started } = event;\n if (started.reopenedExisting) {\n // The recent conversation of the start's entry point: nothing was appended, no turn started. Its messages are\n // not in the answer — the controller reads its newest page — so the optimistic bubble goes.\n return {\n ...state,\n conversation: started.conversation,\n messages: [],\n conversationLoading: false,\n conversationLoaded: true,\n aiThinking: false,\n startingNewConversation: false,\n pendingStartToken: null,\n };\n }\n // The reply arrives through live updates: `aiThinking` stays on.\n return {\n ...state,\n conversation: started.conversation,\n messages: mergeSendAnswer(state.messages, started.messages),\n conversationLoading: false,\n conversationLoaded: true,\n startingNewConversation: false,\n pendingStartToken: null,\n };\n }\n\n case \"startFailed\":\n return withRefusedSendError(\n {\n ...state,\n conversation: null,\n conversationLoading: false,\n conversationLoaded: true,\n aiThinking: false,\n startingNewConversation: false,\n pendingStartToken: null,\n },\n event.error,\n );\n\n case \"errorSet\":\n return state.error === event.error ? state : { ...state, error: event.error };\n\n case \"aiThinkingSet\":\n return state.aiThinking === event.aiThinking ? state : { ...state, aiThinking: event.aiThinking };\n\n case \"openingRequestSet\":\n return { ...state, openingRequest: { ...state.openingRequest, ...event.openingRequest } };\n\n case \"canvasOpened\":\n return withCanvasTransition(state, (nextState) => {\n applyOpenCanvas(nextState, event.request);\n });\n\n case \"canvasClosed\":\n return withCanvasTransition(state, (nextState) => applyCloseCanvas(nextState, event.byCustomer));\n\n case \"canvasResetForNewTurn\":\n return withCanvasTransition(state, applyResetCanvasForNewTurn);\n\n case \"canvasCleared\":\n return withCanvasTransition(state, applyClearCanvas);\n\n case \"canvasCreatedEntityIdSet\":\n return withCanvasTransition(state, (nextState) => {\n applySetCanvasCreatedEntityId(nextState, event.created);\n });\n }\n};\n","import { type AgentsChatEvent, type AgentsChatState, INITIAL_AGENTS_CHAT_STATE } from \"./agents-chat-state\";\nimport { reduceAgentsChatState } from \"./reduce-agents-chat-state\";\n\n/**\n * The state handle of one chat instance. The app creates one per chat (host application: one per agent\n * window, created before the window's chat mounts) and releases it with the chat; the chat and the app's code outside\n * the chat read and dispatch through the same handle. React reads it through `useAgentsChatSelector`.\n */\nexport interface AgentsChatStore {\n getState: () => AgentsChatState;\n /** Calls the listener after every state change; returns the unsubscribe. */\n subscribe: (listener: () => void) => () => void;\n dispatch: (event: AgentsChatEvent) => void;\n}\n\n/** The plain implementation of `AgentsChatStore`: one state object, replaced by the reducer on every event. */\nexport class AgentsChatStateContainer implements AgentsChatStore {\n protected state: AgentsChatState;\n protected readonly listeners = new Set<() => void>();\n\n constructor(initialState: AgentsChatState = INITIAL_AGENTS_CHAT_STATE) {\n this.state = initialState;\n }\n\n getState = (): AgentsChatState => this.state;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n dispatch = (event: AgentsChatEvent): void => {\n const nextState = reduceAgentsChatState(this.state, event);\n if (nextState === this.state) return;\n this.state = nextState;\n for (const notifyListener of [...this.listeners]) notifyListener();\n };\n}\n\n/** Creates the state handle of one chat instance. */\nexport const createAgentsChatStore = (initialState?: AgentsChatState): AgentsChatStore =>\n new AgentsChatStateContainer(initialState);\n","import { createContext, type ReactNode, useCallback, useContext, useSyncExternalStore } from \"react\";\nimport type { AgentsChatState } from \"./agents-chat-state\";\nimport type { AgentsChatStore } from \"./create-agents-chat-store\";\n\nconst AgentsChatStoreContext = createContext<AgentsChatStore | null>(null);\n\nexport interface AgentsChatStoreProviderProps {\n /** The state handle of the chat below (the app creates and releases it). */\n chatStore: AgentsChatStore;\n children?: ReactNode;\n}\n\n/** Puts one chat instance's state handle in reach of the chat and of the app's components inside it. */\nexport const AgentsChatStoreProvider = (props: AgentsChatStoreProviderProps) => {\n const { chatStore, children } = props;\n return <AgentsChatStoreContext.Provider value={chatStore}>{children}</AgentsChatStoreContext.Provider>;\n};\n\n/** The state handle of the chat this component renders in; throws outside `AgentsChatStoreProvider`. */\nexport const useAgentsChatStore = (): AgentsChatStore => {\n const chatStore = useContext(AgentsChatStoreContext);\n if (chatStore === null) {\n throw new Error(\"A chat component rendered outside AgentsChatStoreProvider: the app has to mount its chat store.\");\n }\n return chatStore;\n};\n\n/** The state handle of the chat this component renders in, or null outside a chat. */\nexport const useOptionalAgentsChatStore = (): AgentsChatStore | null => useContext(AgentsChatStoreContext);\n\nconst subscribeToNothing = () => () => undefined;\n\n/**\n * Reads one value of a chat instance's state and re-renders when it changes. The selector must return a value that\n * keeps its identity while the state does not change (a state field, not a new object). Without a store it returns\n * `valueWithoutStore`.\n */\nexport const useAgentsChatSelector = <Selected,>(\n chatStore: AgentsChatStore | null | undefined,\n selector: (state: AgentsChatState) => Selected,\n valueWithoutStore?: Selected,\n): Selected => {\n const subscribe = chatStore ? chatStore.subscribe : subscribeToNothing;\n const readSelectedValue = useCallback(\n () => (chatStore ? selector(chatStore.getState()) : (valueWithoutStore as Selected)),\n [chatStore, selector, valueWithoutStore],\n );\n return useSyncExternalStore(subscribe, readSelectedValue, readSelectedValue);\n};\n\n/** Reads one value of the state of the chat this component renders in. */\nexport const useAgentsChatState = <Selected,>(selector: (state: AgentsChatState) => Selected): Selected =>\n useAgentsChatSelector(useAgentsChatStore(), selector);\n","import React, { ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useAgentsEnvironment, useAgentsStateDispatch, useAgentsStateSelector } from \"../provider/AgentsProvider\";\nimport type { ConversationWidgetStatePartition } from \"./conversation-widget-state-partition\";\nimport { createAgentsChatStore } from \"../chat/store/create-agents-chat-store\";\nimport type { AgentsChatEvent } from \"../chat/store/agents-chat-state\";\nimport type { AgentsChatStore } from \"../chat/store/create-agents-chat-store\";\nimport { useAgentsChatSelector } from \"../chat/store/use-agents-chat-store\";\nimport type { CanvasState, LastClosedCanvas } from \"./canvas/canvas-state\";\nimport { CanvasViabilityContext, readCanvasViable } from \"../widgets/CanvasLauncherWidget/use-canvas-viable\";\nimport { ConversationComposerWidget } from \"./conversation-composer-widget\";\nimport type { CanvasCreatedEntity } from \"./canvas/canvas-reducers\";\nimport { clearStoredCanvas, storeOpenCanvas } from \"./canvas/canvasStorage\";\nimport {\n type CanvasOpenRequestFromOpener,\n type ConversationWidgetCallbacks,\n ConversationWidgetContext,\n defaultConversationWidgetCallbacks,\n type InjectSignalOptions,\n} from \"./ConversationWidgetCallbacksContext\";\n\n// The callbacks, their context and the chat-free hosts live in `ConversationWidgetCallbacksContext.tsx`; this module\n// adds the provider that reads the chat's state (the package chat store or an app's partition) and re-exports the rest.\nexport * from \"./ConversationWidgetCallbacksContext\";\n\n// Number of mounted agentic chat surfaces (widget, full-page chat, dashboard). Drives the app's \"a chat surface is\n// open\" action (`buildChatSurfaceOpenChangedAction`, e.g. a flag of the app's own flows): true while ≥1 is open.\n// Module-level so multiple providers share one count.\nlet agenticChatMountCount = 0;\n\nexport interface ConversationWidgetProviderProps {\n children: ReactNode;\n callbacks: Partial<ConversationWidgetCallbacks>;\n /**\n * The chat slice partition this provider's canvas lives in. The shell is shared by the two chat doors, so the door\n * says which partition: `AgentChat` passes `AgentChatInstance`; the AI-Extensions chat, every story and every spec\n * keep the default. A prop, not a callback — `callbacks` is `Partial`, and the partition is not optional.\n */\n sliceInstance?: ConversationWidgetStatePartition;\n /**\n * The package chat store of the chat: the agent chat passes its window's store and the provider reads\n * and writes the canvas there. Without it the provider reads a partition of the app's own chat state\n * (`sliceInstance`, else the environment's `defaultChatStatePartition`).\n */\n chatStore?: AgentsChatStore;\n /**\n * False for a host that renders the chat without the split (`ConversationView.disableSplitView`): there is nowhere\n * to open a canvas, so every open request is ignored with reason `noSurface`. Default true.\n */\n hostHasCanvasSurface?: boolean;\n}\n\n/** The canvas transitions the provider dispatches — the canvas events of the package chat store. */\ntype ConversationWidgetCanvasEvent = Extract<\n AgentsChatEvent,\n { type: \"canvasOpened\" | \"canvasClosed\" | \"canvasResetForNewTurn\" | \"canvasCleared\" | \"canvasCreatedEntityIdSet\" }\n>;\n\n/** What the provider reads from the chat's state and how it writes a canvas transition back. */\ninterface ConversationWidgetChatState {\n canvas: CanvasState | null;\n lastClosedCanvas: LastClosedCanvas | null;\n isConversationRunning: boolean;\n runState: string | null | undefined;\n messages: ConversationWidgetCallbacks[\"messages\"];\n dispatchCanvasEvent: (event: ConversationWidgetCanvasEvent) => void;\n}\n\ntype ConversationWidgetProviderBodyProps = Omit<ConversationWidgetProviderProps, \"sliceInstance\" | \"chatStore\"> & {\n chatState: ConversationWidgetChatState;\n};\n\nconst selectCanvas = (state: { canvas: CanvasState | null }) => state.canvas;\nconst selectLastClosedCanvas = (state: { lastClosedCanvas: LastClosedCanvas | null }) => state.lastClosedCanvas;\nconst selectAiThinking = (state: { aiThinking: boolean }) => state.aiThinking;\nconst selectRunState = (state: { conversation: { runState?: string | null } | null }) => state.conversation?.runState;\nconst selectMessages = (state: { messages: ConversationWidgetCallbacks[\"messages\"] }) => state.messages;\n\n/** The provider over the package chat store of the chat. */\nconst ChatStoreConversationWidgetProvider = (\n props: Omit<ConversationWidgetProviderProps, \"sliceInstance\" | \"chatStore\"> & { chatStore: AgentsChatStore },\n) => {\n const { chatStore, ...bodyProps } = props;\n const canvas = useAgentsChatSelector(chatStore, selectCanvas);\n const lastClosedCanvas = useAgentsChatSelector(chatStore, selectLastClosedCanvas);\n const isConversationRunning = useAgentsChatSelector(chatStore, selectAiThinking);\n const runState = useAgentsChatSelector(chatStore, selectRunState);\n const messages = useAgentsChatSelector(chatStore, selectMessages);\n const chatState = useMemo<ConversationWidgetChatState>(\n () => ({\n canvas,\n lastClosedCanvas,\n isConversationRunning,\n runState,\n messages,\n dispatchCanvasEvent: chatStore.dispatch,\n }),\n [canvas, lastClosedCanvas, isConversationRunning, runState, messages, chatStore],\n );\n return <ConversationWidgetProviderBody {...bodyProps} chatState={chatState} />;\n};\n\n/** The provider over a partition of the older chat state (the AI-Extensions chat, stories, specs). */\nconst SliceConversationWidgetProvider = (\n props: Omit<ConversationWidgetProviderProps, \"sliceInstance\" | \"chatStore\"> & {\n sliceInstance: ConversationWidgetStatePartition;\n },\n) => {\n const { sliceInstance, ...bodyProps } = props;\n const dispatch = useAgentsStateDispatch();\n // One selector per field, not one returning an object, so an unrelated store change does not re-render every widget\n // through a fresh object identity.\n const canvas = useAgentsStateSelector((state) => sliceInstance.selectState(state).canvas);\n const lastClosedCanvas = useAgentsStateSelector((state) => sliceInstance.selectState(state).lastClosedCanvas);\n const isConversationRunning = useAgentsStateSelector((state) => sliceInstance.selectState(state).aiThinking);\n const runState = useAgentsStateSelector((state) => sliceInstance.selectState(state).conversation?.runState);\n const messages = useAgentsStateSelector((state) => sliceInstance.selectState(state).messages);\n const dispatchCanvasEvent = useCallback(\n (event: ConversationWidgetCanvasEvent) => {\n const { actions } = sliceInstance;\n if (event.type === \"canvasOpened\") dispatch(actions.openCanvas(event.request));\n else if (event.type === \"canvasClosed\") dispatch(actions.closeCanvas({ byCustomer: event.byCustomer }));\n else if (event.type === \"canvasResetForNewTurn\") dispatch(actions.resetCanvasForNewTurn());\n else if (event.type === \"canvasCleared\") dispatch(actions.clearCanvas());\n else dispatch(actions.setCanvasCreatedEntityId(event.created));\n },\n [dispatch, sliceInstance],\n );\n const chatState = useMemo<ConversationWidgetChatState>(\n () => ({ canvas, lastClosedCanvas, isConversationRunning, runState, messages, dispatchCanvasEvent }),\n [canvas, lastClosedCanvas, isConversationRunning, runState, messages, dispatchCanvasEvent],\n );\n return <ConversationWidgetProviderBody {...bodyProps} chatState={chatState} />;\n};\n\n/** The provider over a chat store of its own — a host that brings neither a chat store nor a partition (a story). */\nconst OwnChatStoreConversationWidgetProvider = (\n props: Omit<ConversationWidgetProviderProps, \"sliceInstance\" | \"chatStore\">,\n) => {\n const [ownChatStore] = useState(createAgentsChatStore);\n return <ChatStoreConversationWidgetProvider {...props} chatStore={ownChatStore} />;\n};\n\n/**\n * The widget callbacks of one chat, the canvas model included. Reads the chat's state from the package chat store when\n * the host passes one (`chatStore`), else from a partition of the app's own chat state (`sliceInstance`, or the\n * environment's `defaultChatStatePartition` — host application: the AI-Extensions chat), else from a store of its own.\n */\nexport const ConversationWidgetProvider = (props: ConversationWidgetProviderProps) => {\n const { sliceInstance, chatStore, ...bodyProps } = props;\n const { defaultChatStatePartition } = useAgentsEnvironment();\n const statePartition = sliceInstance ?? defaultChatStatePartition;\n if (chatStore) return <ChatStoreConversationWidgetProvider {...bodyProps} chatStore={chatStore} />;\n if (statePartition) return <SliceConversationWidgetProvider {...bodyProps} sliceInstance={statePartition} />;\n return <OwnChatStoreConversationWidgetProvider {...bodyProps} />;\n};\n\nconst ConversationWidgetProviderBody = ({\n children,\n callbacks,\n hostHasCanvasSurface = true,\n chatState,\n}: ConversationWidgetProviderBodyProps) => {\n const dispatch = useAgentsStateDispatch();\n const { buildChatSurfaceOpenChangedAction } = useAgentsEnvironment();\n const { canvas, lastClosedCanvas, isConversationRunning, runState, messages } = chatState;\n const isConversationClosed = runState === \"COMPLETED\" || runState === \"CANCELLED\";\n const dispatchCanvasEventRef = useRef(chatState.dispatchCanvasEvent);\n dispatchCanvasEventRef.current = chatState.dispatchCanvasEvent;\n const hostHasCanvasSurfaceRef = useRef(hostHasCanvasSurface);\n hostHasCanvasSurfaceRef.current = hostHasCanvasSurface;\n // The width of the chat's own container when the chat measures it (`AgentChatController`), else the viewport.\n const canvasViability = useContext(CanvasViabilityContext);\n const canvasViabilityRef = useRef(canvasViability);\n canvasViabilityRef.current = canvasViability;\n\n // An agentic chat surface is open: the app hears it through its action (e.g. a flag every connect/create/verify flow\n // launched from inside the chat reads to stay in-widget instead of navigating away).\n // Set here (not at the connect button) so it also covers the verify path, where there is no connect click.\n // Ref-counted so concurrently-mounted chat surfaces don't clear each other's flag.\n const buildChatSurfaceOpenChangedActionRef = useRef(buildChatSurfaceOpenChangedAction);\n buildChatSurfaceOpenChangedActionRef.current = buildChatSurfaceOpenChangedAction;\n useEffect(() => {\n agenticChatMountCount += 1;\n if (agenticChatMountCount === 1 && buildChatSurfaceOpenChangedActionRef.current) {\n dispatch(buildChatSurfaceOpenChangedActionRef.current(true));\n }\n return () => {\n agenticChatMountCount -= 1;\n if (agenticChatMountCount === 0 && buildChatSurfaceOpenChangedActionRef.current) {\n dispatch(buildChatSurfaceOpenChangedActionRef.current(false));\n }\n };\n }, [dispatch]);\n\n // Mirror the latest callbacks in a ref so the exposed functions stay stable across\n // renders even if the parent passes a fresh `callbacks` object every render.\n const callbacksRef = useRef(callbacks);\n callbacksRef.current = callbacks;\n\n // Composer-widget ownership — controlled when the host supplies `composerWidgets` (the builder page, click-bridge\n // F), otherwise uncontrolled: the provider owns the state so a descendant (e.g. an app's editor drawer) can\n // mutate it directly. See ConversationWidgetCallbacks.\n const isComposerWidgetsControlled = callbacks.composerWidgets !== undefined;\n const [internalComposerWidgets, setInternalComposerWidgets] = useState<ConversationComposerWidget[]>([]);\n const composerWidgets = isComposerWidgetsControlled\n ? (callbacks.composerWidgets as ConversationComposerWidget[])\n : internalComposerWidgets;\n\n // Mirrors the latest resolved composerWidgets + controlled flag so the mutator callbacks below can compute the\n // next array off REAL current state while keeping stable identities across renders ([] deps) — same trick as\n // `callbacksRef` above.\n const composerWidgetsStateRef = useRef({ composerWidgets, isComposerWidgetsControlled });\n composerWidgetsStateRef.current = { composerWidgets, isComposerWidgetsControlled };\n\n const publishComposerWidgets = useCallback((next: ConversationComposerWidget[]) => {\n if (composerWidgetsStateRef.current.isComposerWidgetsControlled) {\n callbacksRef.current.onComposerWidgetsChange?.(next);\n } else {\n setInternalComposerWidgets(next);\n }\n }, []);\n\n const addComposerWidget = useCallback(\n (widgetName: string, fields: Record<string, unknown>): string => {\n const composerWidgetId = crypto.randomUUID();\n publishComposerWidgets([\n ...composerWidgetsStateRef.current.composerWidgets,\n { composerWidgetId, widgetName, fields },\n ]);\n return composerWidgetId;\n },\n [publishComposerWidgets],\n );\n\n const replaceComposerWidgetFields = useCallback(\n (composerWidgetId: string, fields: Record<string, unknown>) => {\n publishComposerWidgets(\n composerWidgetsStateRef.current.composerWidgets.map((widget) =>\n widget.composerWidgetId === composerWidgetId ? { ...widget, fields } : widget,\n ),\n );\n },\n [publishComposerWidgets],\n );\n\n const removeComposerWidget = useCallback(\n (composerWidgetId: string) => {\n publishComposerWidgets(\n composerWidgetsStateRef.current.composerWidgets.filter(\n (widget) => widget.composerWidgetId !== composerWidgetId,\n ),\n );\n },\n [publishComposerWidgets],\n );\n\n const clearComposerWidgets = useCallback(() => {\n publishComposerWidgets([]);\n }, [publishComposerWidgets]);\n\n // The one way to open a canvas (all four origins). The provider supplies what only it knows — the split's viability\n // (the chat container's width, like `useCanvasViable`) and whether this host has a canvas surface — and the reducer\n // applies the opening rule. Ignored requests change nothing.\n const openCanvas = useCallback(\n (request: CanvasOpenRequestFromOpener) => {\n dispatchCanvasEventRef.current({\n type: \"canvasOpened\",\n request: {\n ...request,\n viewportViable: readCanvasViable(canvasViabilityRef.current),\n hostHasCanvasSurface: hostHasCanvasSurfaceRef.current,\n },\n });\n },\n [],\n );\n\n // Close the open canvas; it stays re-openable as `lastClosedCanvas`. `byCustomer` = the canvas's own close control,\n // which vetoes a live re-delivery of the same identity until the next send / click / page hand-over.\n const closeCanvas = useCallback(\n (byCustomer: boolean) => {\n dispatchCanvasEventRef.current({ type: \"canvasClosed\", byCustomer });\n },\n [],\n );\n\n const lastClosedCanvasRef = useRef(lastClosedCanvas);\n lastClosedCanvasRef.current = lastClosedCanvas;\n const reopenLastClosedCanvas = useCallback(() => {\n const last = lastClosedCanvasRef.current;\n if (last === null) return;\n dispatchCanvasEventRef.current({\n type: \"canvasOpened\",\n request: {\n canvasId: last.canvasId,\n instanceId: last.instanceId,\n anchor: last.anchor,\n origin: \"widgetClick\",\n justDelivered: false,\n viewportViable: readCanvasViable(canvasViabilityRef.current),\n hostHasCanvasSurface: hostHasCanvasSurfaceRef.current,\n ...(last.createdEntityId !== undefined ? { createdEntityId: last.createdEntityId } : {}),\n },\n });\n }, []);\n\n const setCanvasCreatedEntityId = useCallback(\n (created: CanvasCreatedEntity) => {\n dispatchCanvasEventRef.current({ type: \"canvasCreatedEntityIdSet\", created });\n },\n [],\n );\n\n // The pointer of the OPEN canvas is remembered per conversation for a reload (`canvasStorage.ts`), for any\n // lifetime. Cleared when the canvas closes INSIDE the same conversation; a conversation switch clears the slice too,\n // but the LEFT conversation keeps its entry so coming back restores it.\n const storedCanvasConversationIdRef = useRef<number | undefined>(undefined);\n const conversationIdForStorage = callbacks.conversationId;\n useEffect(() => {\n if (canvas !== null) {\n storeOpenCanvas(conversationIdForStorage, canvas);\n storedCanvasConversationIdRef.current = conversationIdForStorage;\n return;\n }\n if (\n storedCanvasConversationIdRef.current !== undefined &&\n storedCanvasConversationIdRef.current === conversationIdForStorage\n ) {\n clearStoredCanvas(conversationIdForStorage);\n }\n storedCanvasConversationIdRef.current = undefined;\n }, [canvas, conversationIdForStorage]);\n\n // A conversation switch forgets the canvas and the last closed one (the LEFT conversation keeps its stored pointer).\n const resetCanvas = useCallback(() => {\n dispatchCanvasEventRef.current({ type: \"canvasCleared\" });\n }, []);\n\n // The SEND boundary: a turn canvas is over for good, a pinned one stays (`canvas-reducers.ts`).\n const resetCanvasForNewTurn = useCallback(() => {\n dispatchCanvasEventRef.current({ type: \"canvasResetForNewTurn\" });\n }, []);\n\n const sendMessageToChat = useCallback((message: string) => {\n return callbacksRef.current.sendMessageToChat?.(message);\n }, []);\n\n const prefillComposer = useCallback((text: string) => {\n callbacksRef.current.prefillComposer?.(text);\n }, []);\n\n const injectSignal = useCallback((signalText: string, options?: InjectSignalOptions) => {\n return callbacksRef.current.injectSignal?.(signalText, options);\n }, []);\n\n const minimizeChatHost = useCallback(() => {\n callbacksRef.current.minimizeChatHost?.();\n }, []);\n\n const contextValue = useMemo<ConversationWidgetCallbacks>(\n () => ({\n canvas,\n hostHasCanvasSurface,\n lastClosedCanvas,\n openCanvas,\n closeCanvas,\n reopenLastClosedCanvas,\n setCanvasCreatedEntityId,\n resetCanvas,\n resetCanvasForNewTurn,\n sendMessageToChat,\n prefillComposer,\n injectSignal,\n minimizeChatHost,\n chatAgentSpaceKey: callbacks.chatAgentSpaceKey,\n isConversationRunning,\n isConversationClosed,\n conversationId: callbacks.conversationId,\n composerWidgets,\n addComposerWidget,\n replaceComposerWidgetFields,\n removeComposerWidget,\n clearComposerWidgets,\n attachLibraryFilesToComposer: callbacks.attachLibraryFilesToComposer,\n onOpenConversation: callbacks.onOpenConversation,\n onSwitchConversation: callbacks.onSwitchConversation,\n isOnboardingSetupConversation: callbacks.isOnboardingSetupConversation ?? false,\n messages,\n }),\n [\n canvas,\n hostHasCanvasSurface,\n lastClosedCanvas,\n openCanvas,\n closeCanvas,\n reopenLastClosedCanvas,\n setCanvasCreatedEntityId,\n resetCanvas,\n resetCanvasForNewTurn,\n sendMessageToChat,\n prefillComposer,\n injectSignal,\n minimizeChatHost,\n callbacks.chatAgentSpaceKey,\n isConversationRunning,\n isConversationClosed,\n callbacks.conversationId,\n composerWidgets,\n addComposerWidget,\n replaceComposerWidgetFields,\n removeComposerWidget,\n clearComposerWidgets,\n callbacks.attachLibraryFilesToComposer,\n callbacks.onOpenConversation,\n callbacks.onSwitchConversation,\n callbacks.isOnboardingSetupConversation,\n messages,\n ],\n );\n\n return <ConversationWidgetContext.Provider value={contextValue}>{children}</ConversationWidgetContext.Provider>;\n};\n\n","import React from \"react\";\nimport { classNames } from \"../../../provider/class-names\";\nimport styles from \"./ConversationMessageInputComposerWidgets.module.scss\";\nimport { useConversationWidgetContext } from \"../../../renderer/ConversationWidgetContext\";\nimport { conversationWidgetRegistry } from \"../../../renderer/conversationWidgetRegistry\";\n\nexport interface ConversationMessageInputComposerWidgetsProps {\n testId?: string;\n}\n\n/**\n * Generic strip of composer widgets above the chat input's text area — the composer-side twin of\n * `ConversationMessageInputAttachmentsPreviewStrip`, same grid-rows 0fr→1fr reveal. Reads `composerWidgets` from the\n * widget context itself (so every ConversationView host gets it for free, mirroring the deleted selection chip),\n * and for each widget resolves the registry entry by `widgetName` and renders its `composerComponent` with\n * `{ composerWidgetId, fields, replaceFields, remove }`. An unknown name, or an entry without a `composerComponent`,\n * renders nothing for that widget — the same kill switch the fence plugin applies.\n */\nexport const ConversationMessageInputComposerWidgets = (props: ConversationMessageInputComposerWidgetsProps) => {\n const { testId = \"chat-input\" } = props;\n const { composerWidgets, replaceComposerWidgetFields, removeComposerWidget } = useConversationWidgetContext();\n\n const renderableWidgets = composerWidgets.flatMap((widget) => {\n const entry = conversationWidgetRegistry.widgets.find((candidate) => candidate.name === widget.widgetName);\n return entry?.composerComponent ? [{ widget, Component: entry.composerComponent }] : [];\n });\n\n return (\n <div\n className={classNames(styles.stripReveal, { [styles.stripRevealOpen]: renderableWidgets.length > 0 })}\n data-testid={`${testId}-composer-widgets-strip`}\n >\n <div className={styles.stripRevealInner}>\n <div className={styles.strip}>\n {renderableWidgets.map(({ widget, Component }) => (\n <Component\n key={widget.composerWidgetId}\n composerWidgetId={widget.composerWidgetId}\n fields={widget.fields}\n replaceFields={(nextFields) => replaceComposerWidgetFields(widget.composerWidgetId, nextFields)}\n remove={() => removeComposerWidget(widget.composerWidgetId)}\n testId={`${testId}-composer-widget-${widget.composerWidgetId}`}\n />\n ))}\n </div>\n </div>\n </div>\n );\n};\n"],"names":[],"mappings":";;;;;;;;AA+DO,MAAM,oCAA8D;AAAA,EACzE,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,sBAAsB;AACxB;AAEO,MAAM,4BAA6C;AAAA,EACxD,cAAc;AAAA,EACd,UAAU;AAAA,EACV,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,4BAA4B;AAAA,EAC5B,yBAAyB;AAAA,EACzB,yBAAyB;AAAA,EACzB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,kBAAkB;AACpB;ACjFO,MAAM,wBA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AA,CAOf,GACH,EAAA,CACF;AAAA,IAAA;AAAA,EAAA;AAGN;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"canvas-title-slot-context-DK4sfhkl.js","sources":["../../src/renderer/balanced-json-object.ts","../../src/renderer/resolve-deep-linkable-widget.ts","../../src/renderer/render-report/widget-render-report-collector.ts","../../src/renderer/composer-widget-fence.ts","../../src/renderer/widget-windowing.tsx","../../src/renderer/conversationWidgetAstPlugin.ts","../../src/renderer/restoreTextDirectivesPlugin.ts","../../src/renderer/WindowedWidget/WindowedWidget.tsx","../../src/renderer/ConversationWidgetHost.tsx","../../src/renderer/MarkdownLink.tsx","../../src/renderer/ConversationMarkdown.tsx","../../src/renderer/widget-click-signal-sources.ts","../../src/renderer/canvas/canvas-title-slot-context.ts"],"sourcesContent":["/**\n * The one string-aware brace walk every \"how far does this widget JSON payload extend\" question in the pipeline\n * needs — the malformed-fence repairer, the naked-JSON referencer and the unrendered-widget detector all call this\n * single copy of the scan.\n */\n\n/**\n * The index of the `}` closing the first `{ … }` JSON object that begins (after optional whitespace) at or after\n * `fromIndex` in `text`, or null when no object starts there or it never balances within `maxScanLength` characters\n * of its start. Quotes and escapes are tracked so a `{`/`}` inside a JSON string value never affects the brace\n * depth (e.g. a widget's `title` field containing literal `{braces}` text).\n */\nexport const findBalancedJsonObjectEnd = (text: string, fromIndex: number, maxScanLength = 5000): number | null => {\n let objectStart = fromIndex;\n while (objectStart < text.length && /\\s/.test(text[objectStart])) objectStart++;\n if (objectStart >= text.length || text[objectStart] !== \"{\") return null;\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n const scanEnd = Math.min(text.length, objectStart + maxScanLength);\n for (let index = objectStart; index < scanEnd; index++) {\n const char = text[index];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (char === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (char === '\"') inString = !inString;\n if (inString) continue;\n if (char === \"{\") depth++;\n if (char === \"}\") {\n depth--;\n if (depth === 0) return index;\n }\n }\n return null;\n};\n","import type { CanvasId } from \"./canvas/canvas-behaviours\";\nimport { ConversationWidgetEntry, conversationWidgetRegistry } from \"./conversationWidgetRegistry\";\n\n/**\n * Resolves the widget a `?agentWidget=<name>` deep-link (or a restored pinned canvas) may mount, by its CANONICAL\n * registry wire name.\n *\n * A URL is untrusted input, so this is an allow-list rather than a registry lookup: only an entry that declares\n * `deepLinkable: true` can be opened this way. Every other widget is emitted by the agent inside a message, where the\n * conversation itself is the authorisation — a link must not be able to mount an arbitrary widget (some carry\n * mount-time side effects) just because its name was typed into the address bar.\n *\n * Returns the entry (the caller renders its `component`, applying the feature gate the entry declares) or null when the\n * name is empty, unknown, or not deep-linkable.\n */\nexport const resolveDeepLinkableWidget = (widgetName?: string | null): ConversationWidgetEntry | null => {\n if (!widgetName) return null;\n return (\n conversationWidgetRegistry.widgets.find((entry) => entry.name === widgetName && entry.deepLinkable === true) ?? null\n );\n};\n\n/**\n * The reverse direction: which deep-linkable widget re-opens THIS canvas. The open canvas of the agent chat is\n * mirrored into `?agentWidget=` (AgentTrigger) so a reload brings the customer back to the surface they were working\n * on — an editor a cold chat opened has no conversation id yet, so the canvas model's own pointer storage\n * has nothing to restore from.\n *\n * Null for every canvas no deep-linkable widget declares: it is the agent's to open inside a message, and a URL must\n * not be able to mount it (the allow-list above).\n */\nexport const deepLinkableWidgetNameForCanvas = (canvasId: CanvasId | null | undefined): string | null => {\n if (!canvasId) return null;\n return (\n conversationWidgetRegistry.widgets.find(\n (entry) => entry.deepLinkable === true && entry.opensCanvases?.includes(canvasId),\n )?.name ?? null\n );\n};\n","import { createContext } from \"react\";\nimport type { WidgetRenderReporter, WidgetRenderReportEntry } from \"./widget-render-report\";\n\n/**\n * The render reports of the widget blocks of live messages, collected per message. The chat host\n * (`AgentChat`) owns one collector and hands it down; `ConversationWidgetHost` registers every block of a JUST-DELIVERED\n * message (never a replayed one) and gives the widget a reporter for it. A block that reports nothing counts as\n * `mounted`. Once a message's blocks have settled — none `pending` for `settleMs`, or `maxWaitMs` after the first block\n * at the latest — the collector calls `onSettled` ONCE for that message with its blocks in document order; the host\n * sends the signal only when a block is not `mounted` or rendered with a note (a `mounted` entry with a code: figures\n * without a source), so a clean render costs nothing.\n */\n\nexport interface WidgetRenderBlockReport {\n widgetName: string;\n /** The block's offset in the message's markdown — document order, and the block's identity in the message. */\n sourceOffset: number;\n entry: WidgetRenderReportEntry;\n}\n\nexport interface WidgetRenderReportCollector {\n /** Counts one block of one live message as `mounted` unless it already reported (a child reports before its host mounts). */\n registerBlock: (messageId: string | number, widgetName: string, sourceOffset: number) => void;\n /** The reporter of one block of one live message. */\n reporterForBlock: (messageId: string | number, widgetName: string, sourceOffset: number) => WidgetRenderReporter;\n /** Forget every pending timer (the host unmounts or the conversation switches). */\n dispose: () => void;\n}\n\nexport interface WidgetRenderReportCollectorOptions {\n onSettled: (messageId: string, blocks: WidgetRenderBlockReport[]) => void;\n settleMs?: number;\n maxWaitMs?: number;\n}\n\ninterface MessageReports {\n blocksByKey: Map<string, WidgetRenderBlockReport>;\n firstReportAt: number;\n settleTimer: ReturnType<typeof setTimeout> | null;\n isSent: boolean;\n}\n\nexport const createWidgetRenderReportCollector = (\n options: WidgetRenderReportCollectorOptions,\n): WidgetRenderReportCollector => {\n const { onSettled, settleMs = 1500, maxWaitMs = 20000 } = options;\n const reportsByMessageId = new Map<string, MessageReports>();\n\n const scheduleSettleCheck = (messageId: string) => {\n const messageReports = reportsByMessageId.get(messageId);\n if (!messageReports || messageReports.isSent) return;\n if (messageReports.settleTimer !== null) clearTimeout(messageReports.settleTimer);\n const hasPendingBlock = [...messageReports.blocksByKey.values()].some((block) => block.entry.status === \"pending\");\n const waitedMs = Date.now() - messageReports.firstReportAt;\n const delayMs = hasPendingBlock ? Math.max(0, Math.min(settleMs * 4, maxWaitMs - waitedMs)) : settleMs;\n messageReports.settleTimer = setTimeout(() => {\n messageReports.settleTimer = null;\n const isStillPending = [...messageReports.blocksByKey.values()].some((block) => block.entry.status === \"pending\");\n if (isStillPending && Date.now() - messageReports.firstReportAt < maxWaitMs) {\n scheduleSettleCheck(messageId);\n return;\n }\n messageReports.isSent = true;\n onSettled(\n messageId,\n [...messageReports.blocksByKey.values()].sort((first, second) => first.sourceOffset - second.sourceOffset),\n );\n }, delayMs);\n };\n\n const recordBlock = (\n messageId: string,\n widgetName: string,\n sourceOffset: number,\n entry: WidgetRenderReportEntry | null,\n ) => {\n let messageReports = reportsByMessageId.get(messageId);\n if (!messageReports) {\n messageReports = { blocksByKey: new Map(), firstReportAt: Date.now(), settleTimer: null, isSent: false };\n reportsByMessageId.set(messageId, messageReports);\n }\n if (messageReports.isSent) return;\n const blockKey = `${widgetName}@${sourceOffset}`;\n const knownBlock = messageReports.blocksByKey.get(blockKey);\n if (entry === null && knownBlock) return;\n messageReports.blocksByKey.set(blockKey, { widgetName, sourceOffset, entry: entry ?? { status: \"mounted\" } });\n scheduleSettleCheck(messageId);\n };\n\n return {\n registerBlock: (messageId, widgetName, sourceOffset) =>\n recordBlock(String(messageId), widgetName, sourceOffset, null),\n reporterForBlock: (messageId, widgetName, sourceOffset) => ({\n report: (entry: WidgetRenderReportEntry) => recordBlock(String(messageId), widgetName, sourceOffset, entry),\n }),\n dispose: () => {\n for (const messageReports of reportsByMessageId.values()) {\n if (messageReports.settleTimer !== null) clearTimeout(messageReports.settleTimer);\n }\n reportsByMessageId.clear();\n },\n };\n};\n\n/** The collector of the chat the widget lives in; absent = nobody listens (another host, a story, the e-mail capture). */\nexport const WidgetRenderReportCollectorContext = createContext<WidgetRenderReportCollector | null>(null);\n\n/** The stored prefix of a render-report signal — the inspector and the tests read it; never reworded. */\nexport const WIDGET_RENDER_REPORT_SIGNAL_PREFIX = \"Widget render report for message\";\n\n/** The signal source (backend `AIConversationSignalSource::FRONTEND_WIDGET_RENDER_REPORT`). */\nexport const WIDGET_RENDER_REPORT_SIGNAL_SOURCE = \"FRONTEND_WIDGET_RENDER_REPORT\";\n\nconst MAX_DETAIL_CHARACTERS = 400;\n\n/** The backend's cap on a signal text (`AIConversationMessage::MAX_SIGNAL_TEXT_CHARS`). */\nconst MAX_SIGNAL_TEXT_CHARS = 2000;\n/** Room kept for the \"… and N more\" line. */\nconst OMITTED_LINE_RESERVE = 80;\n\n/**\n * The model-visible signal for a settled message — null when every block mounted cleanly (nothing to tell). One line\n * per block that is not `mounted`, or that mounted with a note (a code: `INLINE_VALUE_WITHOUT_SOURCE`): its position\n * among the message's widgets, its name and its occurrence among widgets of that name, its status and code, the\n * detail. The closing sentence asks for the honest answer about a block the owner did not see, and for\n * a note that the next widget fixes it.\n */\nexport const buildWidgetRenderReportSignal = (messageId: string, blocks: WidgetRenderBlockReport[]): string | null => {\n const occurrenceByName = new Map<string, number>();\n const blockLines: string[] = [];\n blocks.forEach((block, blockPosition) => {\n const occurrence = (occurrenceByName.get(block.widgetName) ?? 0) + 1;\n occurrenceByName.set(block.widgetName, occurrence);\n if (block.entry.status === \"mounted\" && !block.entry.code) return;\n const status = block.entry.status === \"pending\" ? \"pending (did not finish loading)\" : block.entry.status;\n const code = block.entry.code ? ` ${block.entry.code}` : \"\";\n const detail = block.entry.detail ? ` — ${block.entry.detail.slice(0, MAX_DETAIL_CHARACTERS)}` : \"\";\n blockLines.push(`- widget ${blockPosition + 1} (${block.widgetName} #${occurrence}): ${status}${code}${detail}`);\n });\n if (blockLines.length === 0) return null;\n const header = `${WIDGET_RENDER_REPORT_SIGNAL_PREFIX} ${messageId}:`;\n const hasBlockNotShown = blocks.some((block) => block.entry.status !== \"mounted\");\n const hasNote = blocks.some((block) => block.entry.status === \"mounted\" && block.entry.code);\n const closing = [\n hasBlockNotShown\n ? \"The owner did not see these widgets as intended. In your next answer say so in one line where it matters and \" +\n 'give the content in prose; never refer to \"the widget above\" for them.'\n : \"\",\n hasNote\n ? \"The widgets marked mounted were shown; fix the noted part in every widget you write from now on (a figure you \" +\n \"researched names its publisher and page in `source`). Do not resend the widget for the note alone.\"\n : \"\",\n ]\n .filter((sentence) => sentence !== \"\")\n .join(\" \");\n // The backend keeps the first MAX_SIGNAL_TEXT_CHARS of a signal: whole lines only, the rest counted in one line.\n const keptLines: string[] = [];\n let signalLength = header.length + 1 + closing.length + OMITTED_LINE_RESERVE;\n for (const blockLine of blockLines) {\n if (signalLength + blockLine.length + 1 > MAX_SIGNAL_TEXT_CHARS) break;\n keptLines.push(blockLine);\n signalLength += blockLine.length + 1;\n }\n const omittedCount = blockLines.length - keptLines.length;\n if (omittedCount > 0) keptLines.push(`- … and ${omittedCount} more widget(s) that did not render as intended`);\n return `${header}\\n${keptLines.join(\"\\n\")}\\n${closing}`;\n};\n\nexport interface ParsedWidgetRenderReport {\n messageId: string;\n blocks: Array<{\n position: number;\n widgetName: string;\n occurrence: number;\n status: string;\n code: string | null;\n detail: string | null;\n }>;\n}\n\nconst REPORT_LINE =\n /^- widget (\\d+) \\(([A-Za-z]+) #(\\d+)\\): (mounted|empty|failed|pending)(?: \\(did not finish loading\\))?(?: ([A-Z_]+))?(?: — (.*))?$/;\n\n/** The report a stored signal text carries, or null for another text — the admin inspector's reader. */\nexport const parseWidgetRenderReportSignal = (signalText: string): ParsedWidgetRenderReport | null => {\n const lines = signalText.split(\"\\n\");\n const header = new RegExp(`^${WIDGET_RENDER_REPORT_SIGNAL_PREFIX} (\\\\S+):$`).exec(lines[0] ?? \"\");\n if (!header) return null;\n const blocks: ParsedWidgetRenderReport[\"blocks\"] = [];\n for (const line of lines.slice(1)) {\n const match = REPORT_LINE.exec(line);\n if (!match) continue;\n blocks.push({\n position: Number(match[1]),\n widgetName: match[2],\n occurrence: Number(match[3]),\n status: match[4],\n code: match[5] ?? null,\n detail: match[6] ?? null,\n });\n }\n return { messageId: header[1], blocks };\n};\n","import { ConversationComposerWidget } from \"./conversation-composer-widget\";\nimport { WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { resolveWidgetName } from \"./widget-name-resolver\";\nimport { findBalancedJsonObjectEnd } from \"./balanced-json-object\";\nimport { conversationWidgetRegistry } from \"./conversationWidgetRegistry\";\n\n/**\n * The FE twin of the backend's `AIConversationMessage::buildWidgetFenceBlock` — assembles / disassembles the\n * ```widget fence(s) a composer widget becomes inside the message TEXT (the record; no DB column, no DTO change). `buildComposerWidgetFenceBlock` / `buildMessageTextWithComposerWidgets` run on SEND;\n * `splitComposerWidgetFencesFromMessageText` runs on the USER BUBBLE to pull the fence back out as a\n * read-only widget above the prose.\n */\n\n/** One ```widget fence block for a composer widget — `type` first, then its own fields, one line of JSON. */\nexport const buildComposerWidgetFenceBlock = (widget: ConversationComposerWidget): string =>\n \"```\" + WIDGET_FENCE_LANG + \"\\n\" + JSON.stringify({ type: widget.widgetName, ...widget.fields }) + \"\\n```\";\n\n/**\n * The message text a send assembles: the typed text first, then one fence block per composer widget in composer\n * order, a blank line between blocks. Empty text + at least one widget is allowed (a fence-only send) — the result\n * is non-empty as long as EITHER side has content; both empty yields `\"\"`, the send guard's cue to no-op.\n */\nexport const buildMessageTextWithComposerWidgets = (text: string, widgets: ConversationComposerWidget[]): string =>\n [text.trim(), ...widgets.map(buildComposerWidgetFenceBlock)].filter(Boolean).join(\"\\n\\n\");\n\n/**\n * The canonical names of every registered widget the customer's own message may carry — an entry that declares a\n * `composerComponent` or `sentInCustomerMessage`.\n */\nconst customerMessageWidgetNames = (): ReadonlySet<string> =>\n new Set(\n conversationWidgetRegistry.widgets\n .filter((entry) => entry.composerComponent !== undefined || entry.sentInCustomerMessage === true)\n .map((entry) => entry.name),\n );\n\nexport interface SplitComposerWidgetFencesResult {\n /** The message text with every extracted fence removed, trimmed. */\n text: string;\n /** The extracted composer widgets, in the order they appeared. */\n widgets: ConversationComposerWidget[];\n}\n\n/**\n * The inverse of {@link buildMessageTextWithComposerWidgets}. Extracts every ```widget fence in `text` whose `type`\n * resolves (canonical or legacy `Directive` form, see `widget-name-resolver.ts`) to a registered widget that\n * declares a `composerComponent` or `sentInCustomerMessage` — the only fences a user bubble renders as a read-only\n * widget instead of leaving as text. Every other fence — prose, and fences for widgets the customer's message never\n * carries — is left in `text` verbatim. Never throws: an unterminated fence, malformed JSON, or an\n * unresolved/non-customer `type` just leaves that fence untouched.\n */\nexport const splitComposerWidgetFencesFromMessageText = (text: string): SplitComposerWidgetFencesResult => {\n const customerMessageNames = customerMessageWidgetNames();\n const widgets: ConversationComposerWidget[] = [];\n const fenceOpen = \"```\" + WIDGET_FENCE_LANG;\n\n let remaining = \"\";\n let cursor = 0;\n while (cursor < text.length) {\n const openIndex = text.indexOf(fenceOpen, cursor);\n if (openIndex === -1) {\n remaining += text.slice(cursor);\n break;\n }\n\n // The fence's info-string line must end right after the lang word (a newline follows) — otherwise this is some\n // other fence whose lang merely starts with \"widget\" (e.g. \"widgetx\"); leave it untouched and keep scanning.\n const afterOpen = openIndex + fenceOpen.length;\n const jsonStart = afterOpen + 1;\n const objectEnd = text[afterOpen] === \"\\n\" ? findBalancedJsonObjectEnd(text, jsonStart) : null;\n if (objectEnd === null) {\n remaining += text.slice(cursor, afterOpen);\n cursor = afterOpen;\n continue;\n }\n\n // The fence must close with ``` right after the JSON object (optional whitespace/newline in between).\n const afterJson = objectEnd + 1;\n const closeMatch = /^\\s*```/.exec(text.slice(afterJson));\n if (!closeMatch) {\n remaining += text.slice(cursor, afterOpen);\n cursor = afterOpen;\n continue;\n }\n const fenceEnd = afterJson + closeMatch[0].length;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text.slice(jsonStart, objectEnd + 1));\n } catch {\n parsed = undefined;\n }\n const { type, ...fields } = (typeof parsed === \"object\" && parsed !== null ? parsed : {}) as Record<\n string,\n unknown\n >;\n const widgetName = typeof type === \"string\" ? resolveWidgetName(type) : undefined;\n\n if (!widgetName || !customerMessageNames.has(widgetName)) {\n // Unknown / non-customer widget fence — leave it in the text verbatim (it still renders normally if this\n // text ever runs through the assistant-side remark pipeline; here it just stays as text).\n remaining += text.slice(cursor, fenceEnd);\n cursor = fenceEnd;\n continue;\n }\n\n remaining += text.slice(cursor, openIndex);\n widgets.push({ composerWidgetId: `${widgetName}:${widgets.length}`, widgetName, fields });\n cursor = fenceEnd;\n }\n\n return { text: remaining.trim(), widgets };\n};\n","import React, { createContext, RefObject, useContext, useEffect, useState } from \"react\";\n\n/**\n * Viewport-windowing for chat widgets. Heavy interactive widgets (maps, lists, hydrating components) are mounted ONLY\n * while near the viewport and unmounted back to a placeholder when far away — so a long conversation keeps a CONSTANT\n * number of widgets mounted no matter how far you scroll. Two thresholds give hysteresis (reveal early, hide late) so a\n * small scroll wobble never thrashes mount/unmount.\n *\n * The IntersectionObserver root is the chat scroll container, supplied via {@link WidgetWindowRootContext} by the chat\n * host (ConversationViewBody). Observers are POOLED per (root, margin): all placeholders share two observers, not two each.\n */\nexport const WidgetWindowRootContext = createContext<HTMLElement | null>(null);\n\n/** Mount when the widget is within this margin of the viewport. */\nconst REVEAL_MARGIN_PX = 600;\n/** Unmount only once it is beyond this (larger) margin — the gap to REVEAL is the hysteresis band. */\nconst HIDE_MARGIN_PX = 2000;\n\ntype Pool = { observer: IntersectionObserver; callbacks: Map<Element, (entry: IntersectionObserverEntry) => void> };\n// Keyed by root (null = viewport) → margin string → the shared observer + its per-element callbacks.\nconst poolsByRoot = new Map<Element | null, Map<string, Pool>>();\n\n/** Register `element` with the shared observer for (root, rootMargin); returns a disposer. */\nconst observeShared = (\n root: Element | null,\n rootMargin: string,\n element: Element,\n onEntry: (entry: IntersectionObserverEntry) => void,\n): (() => void) => {\n let byMargin = poolsByRoot.get(root);\n if (!byMargin) {\n byMargin = new Map();\n poolsByRoot.set(root, byMargin);\n }\n let pool = byMargin.get(rootMargin);\n if (!pool) {\n const callbacks = new Map<Element, (entry: IntersectionObserverEntry) => void>();\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n callbacks.get(entry.target)?.(entry);\n }\n },\n { root, rootMargin },\n );\n pool = { observer, callbacks };\n byMargin.set(rootMargin, pool);\n }\n pool.callbacks.set(element, onEntry);\n pool.observer.observe(element);\n\n return () => {\n const currentByMargin = poolsByRoot.get(root);\n const currentPool = currentByMargin?.get(rootMargin);\n if (!currentPool) return;\n currentPool.observer.unobserve(element);\n currentPool.callbacks.delete(element);\n if (currentPool.callbacks.size === 0) {\n currentPool.observer.disconnect();\n currentByMargin!.delete(rootMargin);\n if (currentByMargin!.size === 0) poolsByRoot.delete(root);\n }\n };\n};\n\n/**\n * Drives a widget's mounted/unmounted state from its viewport proximity.\n *\n * - `pinned` (the freshly-delivered widget) → always revealed, never observed: a live widget must not unmount while its\n * one-shot effects (canvas auto-open) are in play, and re-mounting it later would re-fire them.\n * - otherwise: starts at `initialRevealed` (the cheap index-window guess for first paint), then the reveal observer\n * mounts it when it scrolls within REVEAL_MARGIN and the hide observer unmounts it past HIDE_MARGIN.\n *\n * Returns `[revealed, reveal]` — `reveal` lets the placeholder force a manual mount (the \"Show\" affordance).\n */\nexport const useWidgetWindow = (\n targetRef: RefObject<HTMLElement | null>,\n options: { initialRevealed: boolean; pinned: boolean },\n): [boolean, () => void] => {\n const { initialRevealed, pinned } = options;\n const root = useContext(WidgetWindowRootContext);\n const [revealed, setRevealed] = useState(initialRevealed || pinned);\n\n useEffect(() => {\n if (pinned) {\n setRevealed(true);\n return undefined;\n }\n const element = targetRef.current;\n if (!element || typeof IntersectionObserver === \"undefined\") return undefined;\n\n const disposeReveal = observeShared(root, `${REVEAL_MARGIN_PX}px 0px`, element, (entry) => {\n if (entry.isIntersecting) setRevealed(true);\n });\n const disposeHide = observeShared(root, `${HIDE_MARGIN_PX}px 0px`, element, (entry) => {\n if (!entry.isIntersecting) setRevealed(false);\n });\n return () => {\n disposeReveal();\n disposeHide();\n };\n // Re-attach when the scroll root resolves (it is null on the first frame, then the container element).\n }, [root, pinned, targetRef]);\n\n return [revealed, () => setRevealed(true)];\n};\n","import { visit } from \"unist-util-visit\";\nimport { conversationWidgetRegistry, type ConversationWidgetEntry } from \"./conversationWidgetRegistry\";\nimport { resolveCanonicalWidgetName } from \"./widget-name-resolver\";\nimport { exceedsJsonContainerDepth } from \"./widget-tree/bounded-json\";\n\n/** Whether a `::Name{payload='…'}` payload nests deeper than the backend decodes — MALFORMED there, dropped here. */\nconst isPayloadTooDeep = (payload: unknown): boolean => {\n if (typeof payload !== \"string\") return false;\n try {\n return exceedsJsonContainerDepth(JSON.parse(payload));\n } catch {\n return false;\n }\n};\n\n/**\n * Maps the `::Name` nodes a message carries onto the registered components by rewriting `data.hName` to the CANONICAL\n * registry name — which is what `ConversationMarkdown` keys its component map by.\n *\n * The name on the node is whatever the message contains, so a stored conversation delivers the legacy\n * `::ExampleWidgetDirective{payload='…'}` form (and stored server `component` parts carry `\"name\":\"<Canonical>Directive\"`,\n * which `normalize-server-message-to-markdown` turns into exactly that). Resolution therefore goes\n * through `resolveCanonicalWidgetName` — the one legacy rule — never a direct set lookup, or every old message would\n * degrade to the `:name` plain-text fallback.\n */\nexport default function conversationWidgetAstPlugin() {\n const canonicalNames = new Set(conversationWidgetRegistry.widgets.map((w: ConversationWidgetEntry) => w.name));\n\n return (tree: any) => {\n // `\"leafDirective\"` is remark-directive's node type — its contract, not our vocabulary. It is the only form a\n // widget ever travels in: `remarkWidgetFencePlugin` produces it from a ```widget fence, and the stored `::Name`\n // syntax parses into it.\n visit(tree, [\"leafDirective\"], (node, index, parent) => {\n const canonicalName = resolveCanonicalWidgetName(node.name, canonicalNames);\n\n if (\n canonicalName &&\n index !== undefined &&\n index !== null &&\n parent &&\n isPayloadTooDeep(node.attributes?.payload)\n ) {\n parent.children[index] = { type: \"text\", value: \"\" };\n return;\n }\n\n if (canonicalName) {\n // Map properties to attributes for react-markdown\n node.data = {\n hName: canonicalName,\n hProperties: node.attributes || {},\n ...node.data,\n };\n return node;\n }\n\n // `index === 0` is falsy — a plain `!index` check would skip the text\n // fallback for a node that is its parent's first child.\n if (index === undefined || index === null || !parent) {\n return node;\n }\n\n // An unknown name becomes plain text. Keep the node's children so a `::Unknown[label]` form degrades to its\n // label instead of silently swallowing it.\n const asText = { type: \"text\", value: `:${node.name}` };\n parent.children.splice(index, 1, asText, ...(node.children ?? []));\n const prev = parent.children[index - 1];\n if (prev?.type === \"text\") {\n prev.value += asText.value;\n parent.children.splice(index, 1);\n }\n });\n };\n}\n","import { visit } from \"unist-util-visit\";\n\n/**\n * remark-directive parses EVERY `:name` run as a text directive — including the `:00` / `:30` inside a time such as\n * `08:00–16:30` (digits are valid directive names). Text directives are not part of our widget vocabulary (widgets\n * travel as leaf directives only, see `conversationWidgetAstPlugin`), so a text directive is always prose that the\n * parser misread: without this pass the customer chat rendered \"Montag: 08:00–16:30\" as \"08\" / \"–16\" (the `:00`\n * and `:30` swallowed, the unknown nodes rendered as breaks) while the admin inspector, which does not load\n * remark-directive, showed the line intact.\n *\n * Restores every text directive to the exact source slice it was parsed from, merging it into the neighbouring text\n * nodes so the paragraph reads as one run again.\n */\nexport default function restoreTextDirectivesPlugin() {\n return (tree: any, file: any) => {\n const source = String(file?.value ?? \"\");\n visit(tree, \"textDirective\", (node: any, index: number | undefined, parent: any) => {\n if (index === undefined || index === null || !parent) {\n return;\n }\n const start = node.position?.start?.offset;\n const end = node.position?.end?.offset;\n const literal =\n typeof start === \"number\" && typeof end === \"number\" && end > start\n ? source.slice(start, end)\n : `:${node.name}${node.children?.length ? `[${node.children.map((c: any) => c.value ?? \"\").join(\"\")}]` : \"\"}`;\n const asText = { type: \"text\", value: literal };\n parent.children.splice(index, 1, asText);\n // Merge with the neighbours so \"08\" + \":00\" + \"–16\" becomes one text node again.\n const prev = parent.children[index - 1];\n if (prev?.type === \"text\") {\n prev.value += asText.value;\n parent.children.splice(index, 1);\n const next = parent.children[index];\n if (next?.type === \"text\") {\n prev.value += next.value;\n parent.children.splice(index, 1);\n }\n return index - 1;\n }\n const next = parent.children[index + 1];\n if (next?.type === \"text\") {\n asText.value += next.value;\n parent.children.splice(index + 1, 1);\n }\n return index;\n });\n };\n}\n","import { InteractiveSurface, Text } from \"../../provider/components\";\nimport React, { useEffect, useRef } from \"react\";\nimport { translateText } from \"../../provider/environment\";\nimport { useWidgetWindow } from \"../widget-windowing\";\nimport styles from \"../HiddenWidgetPlaceholder/HiddenWidgetPlaceholder.module.scss\";\n\nexport interface WindowedWidgetProps {\n children: React.ReactNode;\n /** First-paint guess from the index window: recent messages start mounted, older ones start as a placeholder. */\n initialRevealed: boolean;\n /** The freshly-delivered widget — kept mounted (never windowed out) so its one-shot effects don't re-fire. */\n pinned: boolean;\n}\n\n/** Default reserved height for a widget that has never been measured (an old one that has not been scrolled to yet). */\nconst DEFAULT_PLACEHOLDER_MIN_HEIGHT = 80;\n\n/**\n * Mounts a chat widget only while it is near the viewport (see {@link useWidgetWindow}); far from the viewport it\n * collapses to a lightweight placeholder. The wrapper element is STABLE across the toggle so the shared\n * IntersectionObserver keeps tracking it. The placeholder reserves the widget's last measured height, so re-hiding it\n * causes ZERO layout shift (no scroll jump); revealing again restores the real widget (self-hydrating widgets re-fetch\n * with a brief skeleton).\n */\nexport const WindowedWidget = ({ children, initialRevealed, pinned }: WindowedWidgetProps) => {\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [revealed, reveal] = useWidgetWindow(wrapperRef, { initialRevealed, pinned });\n // Remembered so the placeholder can reserve exactly the height the widget occupied.\n const lastHeightRef = useRef<number | undefined>(undefined);\n\n useEffect(() => {\n const element = wrapperRef.current;\n if (!revealed || !element || typeof ResizeObserver === \"undefined\") return undefined;\n const measure = () => {\n if (wrapperRef.current) lastHeightRef.current = wrapperRef.current.offsetHeight;\n };\n measure();\n const resizeObserver = new ResizeObserver(measure);\n resizeObserver.observe(element);\n return () => resizeObserver.disconnect();\n }, [revealed]);\n\n return (\n <div ref={wrapperRef}>\n {revealed ? (\n children\n ) : (\n <InteractiveSurface\n hoverable\n className={styles.placeholder}\n style={{ minHeight: lastHeightRef.current ?? DEFAULT_PLACEHOLDER_MIN_HEIGHT }}\n >\n <button\n type=\"button\"\n className={styles.placeholderButton}\n onClick={reveal}\n aria-label={translateText(\"Show hidden widget\")}\n >\n <Text>Older interactive content is hidden.</Text>\n <span className={styles.cta}>\n <Text>Show</Text>\n </span>\n </button>\n </InteractiveSurface>\n )}\n </div>\n );\n};\n","import React, { useContext, useEffect, useMemo } from \"react\";\nimport styles from \"./ConversationMarkdown.module.scss\";\nimport { ConversationWidgetEntry } from \"./conversationWidgetRegistry\";\nimport { ConversationWidgetFeatureGate } from \"./_access/ConversationWidgetFeatureGate\";\nimport { readWidgetAgentSpaceKeyAttribute } from \"./_agent-space/widget-agent-space-key-attribute\";\nimport { ConversationWidgetErrorBoundary } from \"./ConversationWidgetErrorBoundary\";\nimport { WindowedWidget } from \"./WindowedWidget/WindowedWidget\";\nimport { WidgetRenderReportContext } from \"./render-report/widget-render-report\";\nimport { WidgetRenderReportCollectorContext } from \"./render-report/widget-render-report-collector\";\n\nexport type ConversationWidgetRenderProps = Record<string, unknown> & {\n children?: React.ReactNode;\n fresh?: boolean;\n interactive?: boolean;\n justDelivered?: boolean;\n messageId?: string | number;\n};\n\ninterface ConversationWidgetHostProps {\n widget: ConversationWidgetEntry;\n /** Forwarded into the widget (and as its deprecated alias `fresh`): the widget's controls may be used. */\n interactive: boolean;\n /** Forwarded into the widget: the host message was delivered live right now — the one-shot side-effect gate. */\n justDelivered: boolean;\n /** Id of the host message, forwarded so a widget can identify the canvas it opens. */\n messageId?: string | number;\n /** When true, the widget renders as a lightweight placeholder (cheap scroll). */\n hideWidgets: boolean;\n /** Parsed markdown attributes for this widget instance. */\n conversationWidgetRenderProps: ConversationWidgetRenderProps;\n}\n\n/**\n * Single render path for every widget. Each concern is applied as a sequential gate\n * (innermost → outermost):\n * 1. the widget itself, with `interactive` / `justDelivered`\n * 2. feature-flag gate\n * 3. viewport-windowing (mount near the viewport, placeholder when far — WindowedWidget)\n * 4. block spacing wrapper\n *\n * A block of a JUST-DELIVERED message is also registered with the chat's render-report collector: it\n * counts as `mounted` unless the widget reports otherwise through `useReportWidgetRenderStatus`, and a crash caught by\n * the error boundary reports `failed` (`RENDER_FAILED`). A replayed message reports nothing.\n */\nexport const ConversationWidgetHost = ({\n widget,\n interactive,\n justDelivered,\n messageId,\n hideWidgets,\n conversationWidgetRenderProps,\n}: ConversationWidgetHostProps) => {\n const { component: Component, featureFlag, upsellTrigger } = widget;\n const renderReportCollector = useContext(WidgetRenderReportCollectorContext);\n // The block's offset in the message markdown (react-markdown hands every component its hast node) — its identity and\n // its document order in the render report.\n const sourceOffset = (\n conversationWidgetRenderProps.node as { position?: { start?: { offset?: number } } } | undefined\n )?.position?.start?.offset;\n const isReported = renderReportCollector !== null && justDelivered && messageId !== undefined;\n const renderReporter = useMemo(\n () =>\n isReported && messageId !== undefined\n ? renderReportCollector.reporterForBlock(messageId, widget.name, sourceOffset ?? 0)\n : null,\n [isReported, renderReportCollector, messageId, widget.name, sourceOffset],\n );\n useEffect(() => {\n if (isReported && messageId !== undefined)\n renderReportCollector.registerBlock(messageId, widget.name, sourceOffset ?? 0);\n }, [isReported, renderReportCollector, messageId, widget.name, sourceOffset]);\n\n let node = (\n <Component\n {...conversationWidgetRenderProps}\n fresh={interactive}\n interactive={interactive}\n justDelivered={justDelivered}\n messageId={messageId}\n />\n );\n\n if (featureFlag) {\n node = (\n <ConversationWidgetFeatureGate\n featureFlag={featureFlag}\n UpsellTrigger={upsellTrigger}\n agentSpaceKeyAttribute={readWidgetAgentSpaceKeyAttribute(conversationWidgetRenderProps)}\n >\n {node}\n </ConversationWidgetFeatureGate>\n );\n }\n\n // Viewport-windowing: a widget is mounted only while near the viewport and collapses to a height-preserving\n // placeholder when far away — so a long conversation keeps a constant number of widgets mounted. The INTERACTIVE\n // widget (the live reply, and the newest reply after a reload) is pinned — never unmounted, so its controls stay\n // and its one-shot effects don't re-fire; older widgets start from the cheap index-window guess and reveal/hide as\n // they scroll in and out. The feature gate lives INSIDE, so it only runs once the widget is actually mounted.\n node = (\n // Pinned on delivery as well as on controls: a just-delivered widget that lost its controls (a newer widget of the\n // same type superseded it) must not unmount when scrolled past, or its remount re-fires the one-shot canvas open.\n <WindowedWidget initialRevealed={!hideWidgets} pinned={interactive || justDelivered}>\n {node}\n </WindowedWidget>\n );\n\n // Outermost gate: widget props come from LLM output, so any throw inside the\n // widget (or its gates) must not unmount the whole chat message.\n node = (\n <ConversationWidgetErrorBoundary\n widgetName={widget.name}\n onCrash={() =>\n renderReporter?.report({ status: \"failed\", code: \"RENDER_FAILED\", detail: \"the widget threw while rendering\" })\n }\n >\n <WidgetRenderReportContext.Provider value={renderReporter}>{node}</WidgetRenderReportContext.Provider>\n </ConversationWidgetErrorBoundary>\n );\n\n return <div className={styles.conversationWidgetWrapper}>{node}</div>;\n};\n","import { AgentsLink, type AgentsLinkProps } from \"../provider/link-navigation\";\nimport styles from \"./ConversationMarkdown.module.scss\";\n\nexport type MarkdownLinkProps = AgentsLinkProps;\n\n/**\n * The link of a chat message (the `a` component `ConversationMarkdown` hands to `Markdown`): a new-tab anchor with a\n * dotted underline, or the host's own navigation (`AgentsEnvironment.onNavigate`). A host's `Markdown` replacement may\n * wrap it (`components.a`). `node` is dropped so react-markdown's hast node never lands on the DOM element.\n */\nexport const MarkdownLink = (props: MarkdownLinkProps) => {\n const { node, children, className, ...anchorProps } = props;\n return (\n <AgentsLink {...anchorProps} className={className ? `${styles.markdownLink} ${className}` : styles.markdownLink}>\n {children}\n </AgentsLink>\n );\n};\n","import React, { useContext, useMemo } from \"react\";\nimport { type AgentsMarkdownProps, Markdown } from \"../provider/components\";\nimport remarkDirective from \"remark-directive\";\nimport remarkWidgetFencePlugin from \"./remarkWidgetFencePlugin\";\nimport conversationWidgetAstPlugin from \"./conversationWidgetAstPlugin\";\nimport restoreTextDirectivesPlugin from \"./restoreTextDirectivesPlugin\";\nimport { conversationWidgetRegistry, getConversationWidgetRegistryRevision } from \"./conversationWidgetRegistry\";\nimport { ConversationWidgetHost, ConversationWidgetRenderProps } from \"./ConversationWidgetHost\";\nimport { MarkdownLink } from \"./MarkdownLink\";\n\nexport interface ConversationMarkdownProps {\n markdown: string;\n /**\n * Forwarded into every widget instance as `interactive` (and its deprecated alias `fresh`): the widget's controls\n * may be used. True for a live-delivered message and for the newest assistant reply after a reload.\n */\n interactive?: boolean;\n /**\n * Forwarded into every widget instance as `justDelivered`: the message was delivered live right now. The only gate\n * for one-shot side effects (canvas open, draft creation); never true after a reload or on replay.\n */\n justDelivered?: boolean;\n /** Id of the host message, forwarded so a widget can identify the canvas it opens. */\n messageId?: string | number;\n /**\n * When true, widgets are replaced with a lightweight placeholder.\n * Used for old messages to keep the chat scroll cheap.\n */\n hideWidgets?: boolean;\n}\n\n/**\n * Render flags delivered via context so the widget component map can live at module\n * scope. The map must keep stable component identities across renders: react-markdown\n * reconciles by element type, so a per-render `Wrapped` closure makes React unmount and\n * remount every widget on each streaming tick — resetting one-shot refs (duplicate\n * drawer opens / POSTs) and re-triggering hydration.\n */\nconst ConversationWidgetRenderContext = React.createContext<{\n interactive: boolean;\n justDelivered: boolean;\n hideWidgets: boolean;\n messageId?: string | number;\n}>({\n interactive: false,\n justDelivered: false,\n hideWidgets: false,\n});\n\n// Map every widget name to a component that delegates rendering to ConversationWidgetHost,\n// which owns the per-widget concerns (interactive / justDelivered, feature-flag gate, hidden placeholder, block spacing).\n// Built lazily: the registry imports every widget and a widget can import AgentChat, which renders this file.\nconst buildConversationWidgetComponents = () =>\n conversationWidgetRegistry.widgets.reduce<Record<string, React.ComponentType<ConversationWidgetRenderProps>>>(\n (acc, widget) => {\n const Wrapped: React.ComponentType<ConversationWidgetRenderProps> = (innerProps) => {\n const { interactive, justDelivered, hideWidgets, messageId } = useContext(ConversationWidgetRenderContext);\n\n return (\n <ConversationWidgetHost\n widget={widget}\n interactive={interactive}\n justDelivered={justDelivered}\n messageId={messageId}\n hideWidgets={hideWidgets}\n conversationWidgetRenderProps={innerProps}\n />\n );\n };\n Wrapped.displayName = `ConversationWidget(${widget.name})`;\n acc[widget.name] = Wrapped;\n return acc;\n },\n {},\n );\n\nlet markdownComponents: AgentsMarkdownProps[\"components\"] | undefined;\nlet markdownComponentsRevision = -1;\n\n// Rebuilt only when an app registered more widgets since (`registerConversationWidgets`): the identities stay stable.\nconst getMarkdownComponents = (): AgentsMarkdownProps[\"components\"] => {\n if (markdownComponents === undefined || markdownComponentsRevision !== getConversationWidgetRegistryRevision()) {\n markdownComponents = {\n ...buildConversationWidgetComponents(),\n a: MarkdownLink,\n } as AgentsMarkdownProps[\"components\"];\n markdownComponentsRevision = getConversationWidgetRegistryRevision();\n }\n return markdownComponents;\n};\n\n// remarkWidgetFencePlugin rewrites ```widget fenced blocks into the node type remark-directive parses `::Name{}` into,\n// BEFORE conversationWidgetAstPlugin maps them to components — so the model's ```widget egress and the legacy\n// `::Name{}` egress share one render path (ConversationWidgetHost + feature-gate + hydration).\n// restoreTextDirectivesPlugin runs LAST: remark-directive also parses the `:00` inside \"08:00–16:30\" as a text\n// directive (digits are valid names) and swallowed it in the customer chat — text directives are never widgets.\nconst remarkPlugins = [\n remarkDirective,\n remarkWidgetFencePlugin,\n conversationWidgetAstPlugin,\n restoreTextDirectivesPlugin,\n];\n\nexport const ConversationMarkdown = (props: ConversationMarkdownProps) => {\n const { markdown, interactive = false, justDelivered = false, hideWidgets = false, messageId } = props;\n\n const renderContext = useMemo(\n () => ({ interactive, justDelivered, hideWidgets, messageId }),\n [interactive, justDelivered, hideWidgets, messageId],\n );\n\n return (\n <ConversationWidgetRenderContext.Provider value={renderContext}>\n <Markdown remarkPlugins={remarkPlugins} components={getMarkdownComponents()} markdown={markdown} />\n </ConversationWidgetRenderContext.Provider>\n );\n};\n","import { getFurtherWidgetClickSignalSources } from \"../provider/environment\";\n\n/**\n * The `signalSource`s a widget CLICK posts into the conversation (`injectSignal`): the generic widget click and the\n * dedicated source the former owner-action consent widget sent (no component posts it any more; stored rows keep it),\n * plus the further sources an app's own widgets post (`AgentsEnvironment.furtherWidgetClickSignalSources`, e.g. a form\n * submit that starts its own owner turn). The message list reads them to tell an answered widget from an open one after\n * a reload — a widget the owner already clicked must never come back interactive (a consent widget re-armed is a second\n * confirmation for a destructive tool). Add a source here when a widget of the package starts posting a new one.\n */\nexport const FRONTEND_WIDGET_CLICK_SIGNAL_SOURCE = \"FRONTEND_WIDGET_CLICK\";\nexport const OWNER_ACTION_CONFIRM_SIGNAL_SOURCE = \"OWNER_ACTION_CONFIRM\";\n\n/** The package's own widget click sources (the backend's sources of the package that carry an owner statement). */\nexport const PACKAGE_WIDGET_CLICK_SIGNAL_SOURCES: readonly string[] = [\n FRONTEND_WIDGET_CLICK_SIGNAL_SOURCE,\n OWNER_ACTION_CONFIRM_SIGNAL_SOURCE,\n];\n\n/** Every widget click source: the package's own and the app's further ones. */\nexport const getWidgetClickSignalSources = (): readonly string[] => [\n ...PACKAGE_WIDGET_CLICK_SIGNAL_SOURCES,\n ...getFurtherWidgetClickSignalSources(),\n];\n\nexport const isWidgetClickSignalSource = (signalSource: string | undefined | null): boolean =>\n signalSource != null && getWidgetClickSignalSources().includes(signalSource);\n","import { createContext, useContext } from \"react\";\n\n/**\n * The place beside the canvas pane's close button, for a canvas whose behaviour declares `titleBesideCloseButton`:\n * its body portals its title there. Null outside a canvas pane and for every other canvas.\n */\nexport const CanvasTitleSlotContext = createContext<HTMLElement | null>(null);\n\nexport const useCanvasTitleSlot = (): HTMLElement | null => useContext(CanvasTitleSlotContext);\n"],"names":["next","styles"],"mappings":";;;;;;;;AAYO,MAAM,4BAA4B,CAAC,MAAc,WAAmB,gBAAgB,QAAwB;AACjH,MAAI,cAAc;AAClB,SAAO,cAAc,KAAK,UAAU,KAAK,KAAK,KAAK,WAAW,CAAC,EAAG;AAClE,MAAI,eAAe,KAAK,UAAU,KAAK,WAAW,MAAM,IAAK,QAAO;AAEpE,MAAI,QAAQ;AACZ,MAAI,WAAW;AACf,MAAI,UAAU;AACd,QAAM,UAAU,KAAK,IAAI,KAAK,QAAQ,cAAc,aAAa;AACjE,WAAS,QAAQ,aAAa,QAAQ,SAAS,SAAS;AACtD,UAAM,OAAO,KAAK,KAAK;AACvB,QAAI,SAAS;AACX,gBAAU;AACV;AAAA,IACF;AACA,QAAI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,MAAM,wBAAwB,MAAyC;AACrE,MAAI,uBAAuB,UAAa,+BAA+B,sCAAA,GAAyC;AAC9G,yBAAqB;AAAA,MACnB,GAAG,kCAAA;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,iCAA6B,sCAAA;AAAA,EAC/B;AACA,SAAO;AACT;AAOA,MAAM,gBAAgB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,MAAM,uBAAuB,CAAC,UAAqC;AACxE,QAAM,EAAE,UAAU,cAAc,OAAO,gBAAgB,OAAO,cAAc,OAAO,UAAA,IAAc;AAEjG,QAAM,gBAAgB;AAAA,IACpB,OAAO,EAAE,aAAa,eAAe,aAAa,UAAA;AAAA,IAClD,CAAC,aAAa,eAAe,aAAa,SAAS;AAAA,EAAA;AAGrD,SACE,oBAAC,gCAAgC,UAAhC,EAAyC,OAAO,eAC/C,UAAA,oBAAC,UAAA,EAAS,eAA8B,YAAY,sBAAA,GAAyB,UAAoB,GACnG;AAEJ;AC1GO,MAAM,sCAAsC;AAC5C,MAAM,qCAAqC;AAG3C,MAAM,sCAAyD;AAAA,EACpE;AAAA,EACA;AACF;AAGO,MAAM,8BAA8B,MAAyB;AAAA,EAClE,GAAG;AAAA,EACH,GAAG,mCAAA;AACL;AAEO,MAAM,4BAA4B,CAAC,iBACxC,gBAAgB,QAAQ,4BAAA,EAA8B,SAAS,YAAY;ACpBtE,MAAM,yBAAyB,cAAkC,IAAI;AAErE,MAAM,qBAAqB,MAA0B,WAAW,sBAAsB;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"realtime-arrival-BTLE3jjt.js","sources":["../../src/ui/realtime-arrival.ts"],"sourcesContent":["import type { ClientToolAnswerSender } from \"./ClientToolRequestRunner\";\nimport type { ClientToolAnswer, ClientToolRequestDelivery, ClientToolRequestType } from \"./client-tools\";\n\n/** The message type of a client tool request on the realtime port (`AgentUIRealtimeMessageTypeProviderService`). */\nexport const CLIENT_TOOL_REQUEST_MESSAGE_TYPE = 'agent.ui.clientToolRequest';\n\n/** A message of the realtime port as the run-state read or the host's transport delivers it (`AgentRealtimeMessageDelivery`). */\nexport interface AgentRealtimeMessageDelivery {\n messageType: string;\n messageKey: string;\n /** One JSON object */\n payloadJson: string;\n secondsLeft: number;\n}\n\n/** What a client needs to listen on the host's transport (`AgentRealtimeListenerCredential`). */\nexport interface AgentRealtimeListenerCredential {\n transportName: string;\n credential: string;\n listenPath?: string | null;\n expiresAt?: string | null;\n}\n\n/** The client tool request a realtime message carries, or null for another type or a payload that does not parse. */\nexport const readClientToolRequestOfRealtimeMessage = (message: AgentRealtimeMessageDelivery): ClientToolRequestDelivery | null => {\n if (message.messageType !== CLIENT_TOOL_REQUEST_MESSAGE_TYPE) return null;\n try {\n const payload: unknown = JSON.parse(message.payloadJson);\n if (typeof payload !== 'object' || payload === null) return null;\n const { id, requestType, argumentsJson, secondsLeft } = payload as Record<string, unknown>;\n if (typeof id !== 'number' || !Number.isSafeInteger(id) || typeof requestType !== 'string') return null;\n return {\n id,\n requestType,\n argumentsJson: typeof argumentsJson === 'string' ? argumentsJson : '{}',\n // the transport's own clock: the message's seconds left win when the payload's are older\n secondsLeft: Math.min(typeof secondsLeft === 'number' ? secondsLeft : message.secondsLeft, message.secondsLeft),\n };\n } catch {\n return null;\n }\n};\n\n/** What takes an arrived client tool request (an `AgentUIClient`). */\nexport interface ClientToolRequestAcceptor {\n acceptClientToolRequest(conversationId: number, delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void;\n}\n\n/**\n * The arrival adapter for a host transport: hand it every message the transport receives for a conversation; a\n * client tool request goes to the UI client (which runs a request id once, so the run-state read delivering the same\n * request is harmless), any other type to `onOtherMessage`. Returns whether the message was a client tool request.\n */\nexport const acceptArrivedRealtimeMessage = (\n conversationId: number,\n message: AgentRealtimeMessageDelivery,\n acceptor: ClientToolRequestAcceptor,\n sendAnswer: ClientToolAnswerSender,\n onOtherMessage?: (conversationId: number, message: AgentRealtimeMessageDelivery) => void,\n): boolean => {\n const delivery = readClientToolRequestOfRealtimeMessage(message);\n if (delivery) {\n acceptor.acceptClientToolRequest(conversationId, delivery, sendAnswer);\n return true;\n }\n onOtherMessage?.(conversationId, message);\n return false;\n};\n\n/** The pause before the one re-read of `readRunStateAfterClientToolRequestPing` when the first read found nothing. */\nexport const CLIENT_TOOL_REQUEST_PING_REREAD_DELAY_MS = 400;\n\n/** What counts the client tool requests delivered to the UI client (`AgentUIClient`). */\nexport interface ClientToolRequestDeliveryCounter {\n countAcceptedClientToolRequests(): number;\n}\n\n/**\n * The arrival adapter for a host transport that only pings (it carries no message, e.g. the per-conversation ping of\n * a client tool request): reads the run state, which hands a waiting request to the UI client; when that read\n * delivered none — the ping overtook the server's write — it reads once more after `rereadDelayMs`, so the request is\n * not left to the next regular read. Resolves with whether a request was delivered.\n */\nexport const readRunStateAfterClientToolRequestPing = async (\n conversationId: number,\n readRunState: (conversationId: number) => Promise<unknown>,\n deliveryCounter: ClientToolRequestDeliveryCounter,\n rereadDelayMs: number = CLIENT_TOOL_REQUEST_PING_REREAD_DELAY_MS,\n): Promise<boolean> => {\n const acceptedBefore = deliveryCounter.countAcceptedClientToolRequests();\n await readRunState(conversationId);\n if (deliveryCounter.countAcceptedClientToolRequests() > acceptedBefore) return true;\n await new Promise<void>(resolve => setTimeout(resolve, rereadDelayMs));\n await readRunState(conversationId);\n return deliveryCounter.countAcceptedClientToolRequests() > acceptedBefore;\n};\n\nlet developmentRequestId = 9_000_000_000_000;\n\n/**\n * The dev helper: runs a request through the UI client as if the server had sent it and resolves with the answer, so\n * an application tries its adapters without a model (e.g. from the browser console in development).\n */\nexport const runClientToolRequestForDevelopment = (\n acceptor: ClientToolRequestAcceptor,\n requestType: ClientToolRequestType | string,\n parameters: Record<string, unknown> = {},\n secondsLeft: number = 30,\n): Promise<ClientToolAnswer> =>\n new Promise(resolve => {\n developmentRequestId += 1;\n acceptor.acceptClientToolRequest(\n 0,\n { id: developmentRequestId, requestType, argumentsJson: JSON.stringify(parameters), secondsLeft },\n async (_requestId, answer) => resolve(answer),\n );\n });\n"],"names":[],"mappings":";AAIO,MAAM,mCAAmC;AAoBzC,MAAM,yCAAyC,CAAC,YAA4E;AACjI,MAAI,QAAQ,gBAAgB,iCAAkC,QAAO;AACrE,MAAI;AACF,UAAM,UAAmB,KAAK,MAAM,QAAQ,WAAW;AACvD,QAAI,OAAO,YAAY,YAAY,YAAY,KAAM,QAAO;AAC5D,UAAM,EAAE,IAAI,aAAa,eAAe,gBAAgB;AACxD,QAAI,OAAO,OAAO,YAAY,CAAC,OAAO,cAAc,EAAE,KAAK,OAAO,gBAAgB,SAAU,QAAO;AACnG,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,eAAe,OAAO,kBAAkB,WAAW,gBAAgB;AAAA;AAAA,MAEnE,aAAa,KAAK,IAAI,OAAO,gBAAgB,WAAW,cAAc,QAAQ,aAAa,QAAQ,WAAW;AAAA,IAAA;AAAA,EAElH,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAYO,MAAM,+BAA+B,CAC1C,gBACA,SACA,UACA,YACA,mBACY;AACZ,QAAM,WAAW,uCAAuC,OAAO;AAC/D,MAAI,UAAU;AACZ,aAAS,wBAAwB,gBAAgB,UAAU,UAAU;AACrE,WAAO;AAAA,EACT;AACA,mBAAiB,gBAAgB,OAAO;AACxC,SAAO;AACT;AAGO,MAAM,2CAA2C;AAajD,MAAM,yCAAyC,OACpD,gBACA,cACA,iBACA,gBAAwB,6CACH;AACrB,QAAM,iBAAiB,gBAAgB,gCAAA;AACvC,QAAM,aAAa,cAAc;AACjC,MAAI,gBAAgB,oCAAoC,eAAgB,QAAO;AAC/E,QAAM,IAAI,QAAc,CAAA,YAAW,WAAW,SAAS,aAAa,CAAC;AACrE,QAAM,aAAa,cAAc;AACjC,SAAO,gBAAgB,oCAAoC;AAC7D;AAEA,IAAI,uBAAuB;AAMpB,MAAM,qCAAqC,CAChD,UACA,aACA,aAAsC,CAAA,GACtC,cAAsB,O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