@valerypopoff/rivet2-core 2.1.4 → 2.1.6

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 (107) hide show
  1. package/dist/cjs/bundle.cjs +6651 -1022
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +733 -19
  4. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  5. package/dist/esm/api/createProcessor.js +6 -1
  6. package/dist/esm/exports.js +7 -0
  7. package/dist/esm/integrations/KnowledgeStore.js +1 -0
  8. package/dist/esm/integrations/KnowledgeStoreProvider.js +292 -0
  9. package/dist/esm/integrations/KnowledgeStoreValidation.js +428 -0
  10. package/dist/esm/integrations/ManagedKnowledgeStore.js +539 -0
  11. package/dist/esm/model/DataValue.js +22 -2
  12. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  13. package/dist/esm/model/GraphProcessor.js +1141 -82
  14. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  15. package/dist/esm/model/Nodes.js +27 -0
  16. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  17. package/dist/esm/model/RecordingPlayer.js +9 -0
  18. package/dist/esm/model/StoredValueStore.js +226 -0
  19. package/dist/esm/model/SubprocessorBridge.js +50 -19
  20. package/dist/esm/model/ToolCallContinuation.js +1 -0
  21. package/dist/esm/model/UiGraph.js +52 -2
  22. package/dist/esm/model/UiGraphActionProtocol.js +10 -1
  23. package/dist/esm/model/UiGraphBrowserRuntime.js +444 -0
  24. package/dist/esm/model/UiGraphNormalization.js +35 -185
  25. package/dist/esm/model/UiGraphRendererStyles.js +878 -78
  26. package/dist/esm/model/UiGraphRuntimeModel.js +255 -15
  27. package/dist/esm/model/UiGraphSchema.js +91 -0
  28. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  29. package/dist/esm/model/chat/chatMessages.js +5 -9
  30. package/dist/esm/model/chat/openAIChatRequest.js +8 -2
  31. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +8 -8
  33. package/dist/esm/model/chat-v2/index.js +1 -0
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -1
  35. package/dist/esm/model/chat-v2/parallelToolCalls.js +38 -0
  36. package/dist/esm/model/chat-v2/toolContinuation.js +45 -8
  37. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  38. package/dist/esm/model/nodes/BuildKnowledgeContextNode.js +157 -0
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +79 -0
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/KnowledgeDocumentNode.js +88 -0
  43. package/dist/esm/model/nodes/KnowledgeSourceNode.js +94 -0
  44. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  45. package/dist/esm/model/nodes/MatchNode.js +7 -7
  46. package/dist/esm/model/nodes/SearchKnowledgeNode.js +127 -0
  47. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  48. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  49. package/dist/esm/model/nodes/StoredValueNodeUtils.js +57 -0
  50. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +149 -0
  51. package/dist/esm/model/nodes/ToolNode.js +14 -0
  52. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  53. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +553 -0
  54. package/dist/esm/plugins/pinecone/plugin.js +32 -0
  55. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  56. package/dist/esm/utils/coerceType.js +27 -2
  57. package/dist/esm/utils/getPluginConfig.js +12 -6
  58. package/dist/esm/utils/serialization/serialization.js +4 -1
  59. package/dist/esm/utils/serialization/serializationUtils.js +59 -1
  60. package/dist/esm/webAppRuntime.js +3 -3
  61. package/dist/types/api/createProcessor.d.ts +6 -0
  62. package/dist/types/exports.d.ts +7 -0
  63. package/dist/types/integrations/KnowledgeStore.d.ts +131 -0
  64. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +46 -0
  65. package/dist/types/integrations/KnowledgeStoreValidation.d.ts +16 -0
  66. package/dist/types/integrations/ManagedKnowledgeStore.d.ts +57 -0
  67. package/dist/types/model/DataValue.d.ts +10 -3
  68. package/dist/types/model/EditorDefinition.d.ts +9 -2
  69. package/dist/types/model/ExecutorProtocol.d.ts +12 -0
  70. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  71. package/dist/types/model/GraphProcessor.d.ts +21 -2
  72. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  73. package/dist/types/model/Nodes.d.ts +11 -2
  74. package/dist/types/model/ProcessContext.d.ts +18 -0
  75. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  76. package/dist/types/model/Project.d.ts +11 -0
  77. package/dist/types/model/StoredValueStore.d.ts +55 -0
  78. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  79. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  80. package/dist/types/model/UiGraph.d.ts +24 -1
  81. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  82. package/dist/types/model/UiGraphBrowserRuntime.d.ts +75 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  84. package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
  85. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  86. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  87. package/dist/types/model/chat-v2/index.d.ts +1 -0
  88. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +9 -0
  89. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  90. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  91. package/dist/types/model/nodes/BuildKnowledgeContextNode.d.ts +23 -0
  92. package/dist/types/model/nodes/GetKnowledgeSourceStatusNode.d.ts +19 -0
  93. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  94. package/dist/types/model/nodes/KnowledgeDocumentNode.d.ts +26 -0
  95. package/dist/types/model/nodes/KnowledgeSourceNode.d.ts +25 -0
  96. package/dist/types/model/nodes/SearchKnowledgeNode.d.ts +25 -0
  97. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  98. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  99. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  100. package/dist/types/model/nodes/SyncKnowledgeSourceNode.d.ts +27 -0
  101. package/dist/types/model/nodes/ToolNode.d.ts +2 -0
  102. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  103. package/dist/types/plugins/pinecone/PineconeKnowledgeStore.d.ts +11 -0
  104. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  105. package/dist/types/utils/serialization/serializationUtils.d.ts +4 -0
  106. package/dist/types/webAppRuntime.d.ts +5 -4
  107. package/package.json +1 -1
@@ -22,17 +22,37 @@ var webAppRuntime_exports = {};
22
22
  __export(webAppRuntime_exports, {
23
23
  RIVET_WEB_APP_ACTION_PROTOCOL_VERSION: () => RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
24
24
  applyUiGraphStatePatch: () => applyUiGraphStatePatch,
25
+ applyUiGraphWebAppStorageActionPatch: () => applyUiGraphWebAppStorageActionPatch,
26
+ applyUiGraphWebAppStoragePatch: () => applyUiGraphWebAppStoragePatch,
27
+ clearUiGraphChatSearchMatches: () => clearUiGraphChatSearchMatches,
25
28
  copyUiGraphText: () => copyUiGraphText,
26
29
  createUiGraphActionExecutionController: () => createUiGraphActionExecutionController,
30
+ createUiGraphChatHistoryFlushStatePatch: () => createUiGraphChatHistoryFlushStatePatch,
31
+ createUiGraphChatPinStatePatch: () => createUiGraphChatPinStatePatch,
27
32
  createUiGraphChatSubmissionStatePatch: () => createUiGraphChatSubmissionStatePatch,
28
33
  createUiGraphInteractionController: () => createUiGraphInteractionController,
29
34
  downloadUiGraphJsonOutput: () => downloadUiGraphJsonOutput,
35
+ enhanceUiGraphChatJsonCodeBlocks: () => enhanceUiGraphChatJsonCodeBlocks,
30
36
  getUiGraphActionState: () => getUiGraphActionState,
31
37
  getUiGraphChatDraftStateKey: () => getUiGraphChatDraftStateKey,
38
+ getUiGraphChatMessagePresentations: () => getUiGraphChatMessagePresentations,
39
+ getUiGraphChatMessagesStateKey: () => getUiGraphChatMessagesStateKey,
40
+ getUiGraphChatPersistentState: () => getUiGraphChatPersistentState,
41
+ getUiGraphChatStorageKey: () => getUiGraphChatStorageKey,
32
42
  getUiGraphComponentRenderModel: () => getUiGraphComponentRenderModel,
33
43
  getUiGraphJsonOutputFilename: () => getUiGraphJsonOutputFilename,
44
+ getUiGraphProgressiveJsonOutputChunks: () => getUiGraphProgressiveJsonOutputChunks,
45
+ getUiGraphWebAppStorageKey: () => getUiGraphWebAppStorageKey,
46
+ hasUiGraphChatPersistentStateChanged: () => hasUiGraphChatPersistentStateChanged,
47
+ highlightUiGraphChatSearchMatches: () => highlightUiGraphChatSearchMatches,
48
+ loadUiGraphChatPersistentState: () => loadUiGraphChatPersistentState,
49
+ loadUiGraphWebAppStorage: () => loadUiGraphWebAppStorage,
50
+ observeUiGraphOutputResizeBounds: () => observeUiGraphOutputResizeBounds,
34
51
  parseRivetWebAppClientMessage: () => parseRivetWebAppClientMessage,
35
- parseRivetWebAppServerMessage: () => parseRivetWebAppServerMessage
52
+ parseRivetWebAppServerMessage: () => parseRivetWebAppServerMessage,
53
+ revealUiGraphChatElement: () => revealUiGraphChatElement,
54
+ revealUiGraphChatSearchMatch: () => revealUiGraphChatSearchMatch,
55
+ saveUiGraphChatPersistentState: () => saveUiGraphChatPersistentState
36
56
  });
37
57
  module.exports = __toCommonJS(webAppRuntime_exports);
38
58
 
@@ -45,9 +65,12 @@ function getUiGraphInitialState(uiGraph) {
45
65
  for (const component of uiGraph.components) {
46
66
  if (component.type === "input" || component.type === "textarea") {
47
67
  state[component.stateKey] = component.defaultValue ?? "";
68
+ } else if (component.type === "dropdown") {
69
+ state[component.stateKey] = "";
48
70
  } else if (component.type === "chat") {
49
71
  state[getUiGraphChatDraftStateKey(component.id)] = "";
50
72
  state[getUiGraphChatMessagesStateKey(component.id)] = [];
73
+ state[getUiGraphChatPinsStateKey(component.id)] = [];
51
74
  }
52
75
  }
53
76
  return state;
@@ -58,11 +81,56 @@ function getUiGraphChatDraftStateKey(componentId) {
58
81
  function getUiGraphChatMessagesStateKey(componentId) {
59
82
  return `__rivet_chat_${componentId}_messages`;
60
83
  }
84
+ function getUiGraphChatPinsStateKey(componentId) {
85
+ return `__rivet_chat_${componentId}_pins`;
86
+ }
61
87
  function getUiGraphChatMessages(componentId, state) {
62
88
  const messages = state[getUiGraphChatMessagesStateKey(componentId)];
63
89
  return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];
64
90
  }
65
- function createUiGraphChatSubmissionStatePatch(componentId, state) {
91
+ function getUiGraphChatPins(componentId, state) {
92
+ const messages = getUiGraphChatMessages(componentId, state);
93
+ const storedPins = state[getUiGraphChatPinsStateKey(componentId)];
94
+ const messageIndexes = Array.isArray(storedPins) ? [
95
+ ...new Set(
96
+ storedPins.filter(
97
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0
98
+ )
99
+ )
100
+ ].sort((left, right) => left - right) : [];
101
+ const pinnedIndexes = new Set(messageIndexes);
102
+ const pins = [];
103
+ let prompt;
104
+ let promptMessageIndex;
105
+ messages.forEach((message, messageIndex) => {
106
+ if (message.role === "user") {
107
+ prompt = message;
108
+ promptMessageIndex = messageIndex;
109
+ } else if (pinnedIndexes.has(messageIndex)) {
110
+ pins.push({ messageIndex, prompt, promptMessageIndex, response: message });
111
+ }
112
+ });
113
+ return pins;
114
+ }
115
+ function createUiGraphChatPinStatePatch(componentId, state, messageIndex) {
116
+ var _a;
117
+ const messages = getUiGraphChatMessages(componentId, state);
118
+ if (((_a = messages[messageIndex]) == null ? void 0 : _a.role) !== "assistant") {
119
+ return void 0;
120
+ }
121
+ const pinsStateKey = getUiGraphChatPinsStateKey(componentId);
122
+ const pinnedIndexes = getUiGraphChatPins(componentId, state).map((pin) => pin.messageIndex);
123
+ return {
124
+ [pinsStateKey]: pinnedIndexes.includes(messageIndex) ? pinnedIndexes.filter((index) => index !== messageIndex) : [...pinnedIndexes, messageIndex].sort((left, right) => left - right)
125
+ };
126
+ }
127
+ function createUiGraphChatHistoryFlushStatePatch(componentId) {
128
+ return {
129
+ [getUiGraphChatMessagesStateKey(componentId)]: [],
130
+ [getUiGraphChatPinsStateKey(componentId)]: []
131
+ };
132
+ }
133
+ function createUiGraphChatSubmissionStatePatch(componentId, state, timestamp = (/* @__PURE__ */ new Date()).toISOString()) {
66
134
  const draftStateKey = getUiGraphChatDraftStateKey(componentId);
67
135
  const content = `${state[draftStateKey] ?? ""}`.trim();
68
136
  if (!content) {
@@ -72,7 +140,7 @@ function createUiGraphChatSubmissionStatePatch(componentId, state) {
72
140
  [draftStateKey]: "",
73
141
  [getUiGraphChatMessagesStateKey(componentId)]: [
74
142
  ...getUiGraphChatMessages(componentId, state),
75
- { role: "user", content }
143
+ { role: "user", content, timestamp }
76
144
  ]
77
145
  };
78
146
  }
@@ -132,6 +200,38 @@ var IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:avif|bmp|gif|jpe?g|png|webp));bas
132
200
  var IMAGE_URL_PATTERN = /^(?:https?:\/\/|blob:|\/\/|\/|\.\.?\/)/i;
133
201
  var RELATIVE_IMAGE_PATH_PATTERN = /\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;
134
202
  var BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
203
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD = 128 * 1024;
204
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS = 16 * 1024;
205
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS = 16 * 1024;
206
+ var ACTION_LOADING_DELAY_MS = 300;
207
+ function getUiGraphActionComponentsById(uiGraph) {
208
+ return new Map(
209
+ uiGraph.components.filter(
210
+ (component) => component.type === "button" || component.type === "chat"
211
+ ).map((component) => [component.id, component])
212
+ );
213
+ }
214
+ function areUiGraphActionValuesEqual(left, right) {
215
+ if (Object.is(left, right)) {
216
+ return true;
217
+ }
218
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") {
219
+ return false;
220
+ }
221
+ if (Array.isArray(left) || Array.isArray(right)) {
222
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => areUiGraphActionValuesEqual(value, right[index]));
223
+ }
224
+ const leftRecord = left;
225
+ const rightRecord = right;
226
+ const leftKeys = Object.keys(leftRecord);
227
+ const rightKeys = Object.keys(rightRecord);
228
+ return leftKeys.length === rightKeys.length && leftKeys.every(
229
+ (key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && areUiGraphActionValuesEqual(leftRecord[key], rightRecord[key])
230
+ );
231
+ }
232
+ function areUiGraphActionComponentsExecutionEquivalent(left, right) {
233
+ return left.type === right.type && areUiGraphActionValuesEqual(left.action, right.action);
234
+ }
135
235
  function createUiGraphActionExecutionController() {
136
236
  let nextVersion = 0;
137
237
  const activeExecutionByComponent = /* @__PURE__ */ new Map();
@@ -184,17 +284,34 @@ function createUiGraphActionExecutionController() {
184
284
  }
185
285
  function createUiGraphInteractionController(initialUiGraph, options = {}) {
186
286
  let uiGraphId = initialUiGraph.id;
187
- let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);
287
+ let actionComponentsById = getUiGraphActionComponentsById(initialUiGraph);
288
+ let outputComponentIds = getUiGraphOutputComponentIds(initialUiGraph);
289
+ let outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(initialUiGraph);
290
+ const initialStateOverride = options.initialState ? { ...options.initialState } : void 0;
291
+ let initialState = normalizeUiGraphDropdownState(
292
+ initialUiGraph,
293
+ initialStateOverride ?? getUiGraphInitialState(initialUiGraph)
294
+ );
295
+ let state = { ...initialState };
188
296
  let actionErrors = {};
189
297
  let actionProgress = {};
298
+ const collapsedOutputComponentIds = /* @__PURE__ */ new Set();
190
299
  let snapshot;
191
300
  const actionController = createUiGraphActionExecutionController();
192
301
  const activeActions = /* @__PURE__ */ new Map();
302
+ const loadingActionIds = /* @__PURE__ */ new Set();
303
+ const loadingDelayTimers = /* @__PURE__ */ new Map();
193
304
  const listeners = /* @__PURE__ */ new Set();
194
305
  const updateSnapshot = () => {
195
306
  snapshot = {
196
307
  actionErrors,
197
308
  actionProgress,
309
+ collapsedOutputComponentIds: new Set(collapsedOutputComponentIds),
310
+ loadingComponentIds: new Set(
311
+ [...activeActions].flatMap(
312
+ ([executionId, { execution }]) => loadingActionIds.has(executionId) ? [execution.componentId] : []
313
+ )
314
+ ),
198
315
  runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
199
316
  state
200
317
  };
@@ -205,6 +322,25 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
205
322
  listener(change);
206
323
  }
207
324
  };
325
+ const clearActionLoadingPresentation = (executionId) => {
326
+ const timer = loadingDelayTimers.get(executionId);
327
+ if (timer != null) {
328
+ clearTimeout(timer);
329
+ loadingDelayTimers.delete(executionId);
330
+ }
331
+ loadingActionIds.delete(executionId);
332
+ };
333
+ const delayActionLoadingPresentation = (execution) => {
334
+ loadingDelayTimers.set(
335
+ execution.id,
336
+ setTimeout(() => {
337
+ loadingDelayTimers.delete(execution.id);
338
+ if (!activeActions.has(execution.id) || !actionController.isCurrent(execution)) return;
339
+ loadingActionIds.add(execution.id);
340
+ publish("action");
341
+ }, ACTION_LOADING_DELAY_MS)
342
+ );
343
+ };
208
344
  const abortMatchingActions = (predicate, notify) => {
209
345
  let changed = false;
210
346
  for (const [executionId, activeAction] of activeActions) {
@@ -213,6 +349,7 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
213
349
  }
214
350
  activeAction.abortController.abort();
215
351
  activeActions.delete(executionId);
352
+ clearActionLoadingPresentation(executionId);
216
353
  actionController.finish(activeAction.execution);
217
354
  changed = true;
218
355
  }
@@ -233,14 +370,48 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
233
370
  }
234
371
  };
235
372
  const removeActionPresentation = (componentId) => {
373
+ let changed = false;
236
374
  if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
237
375
  actionErrors = { ...actionErrors };
238
376
  delete actionErrors[componentId];
377
+ changed = true;
239
378
  }
240
379
  if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
241
380
  actionProgress = { ...actionProgress };
242
381
  delete actionProgress[componentId];
382
+ changed = true;
383
+ }
384
+ return changed;
385
+ };
386
+ const expandOutputsForUpdatedState = (stateKeys, nextState) => {
387
+ for (const stateKey of stateKeys) {
388
+ for (const component of outputComponentsByStateKey.get(stateKey) ?? []) {
389
+ if (getUiGraphOutputRenderModel(nextState, stateKey, component.renderAs ?? "text").hasValue) {
390
+ collapsedOutputComponentIds.delete(component.id);
391
+ }
392
+ }
393
+ }
394
+ };
395
+ const stampChatResponseAtBrowserReceipt = (component, statePatch) => {
396
+ if (component.type !== "chat" || !statePatch) {
397
+ return statePatch;
398
+ }
399
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
400
+ const messages = statePatch[messagesStateKey];
401
+ if (!Array.isArray(messages) || messages.length === 0) {
402
+ return statePatch;
403
+ }
404
+ const lastMessage = messages[messages.length - 1];
405
+ if (!lastMessage || typeof lastMessage !== "object" || lastMessage.role !== "assistant" || typeof lastMessage.content !== "string") {
406
+ return statePatch;
243
407
  }
408
+ return {
409
+ ...statePatch,
410
+ [messagesStateKey]: [
411
+ ...messages.slice(0, -1),
412
+ { ...lastMessage, timestamp: (/* @__PURE__ */ new Date()).toISOString() }
413
+ ]
414
+ };
244
415
  };
245
416
  updateSnapshot();
246
417
  return {
@@ -254,6 +425,9 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
254
425
  }
255
426
  },
256
427
  detachActions() {
428
+ for (const executionId of activeActions.keys()) {
429
+ clearActionLoadingPresentation(executionId);
430
+ }
257
431
  activeActions.clear();
258
432
  actionController.reset();
259
433
  actionProgress = {};
@@ -262,6 +436,14 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
262
436
  getSnapshot() {
263
437
  return snapshot;
264
438
  },
439
+ reset() {
440
+ abortAllActions(false);
441
+ state = { ...initialState };
442
+ actionErrors = {};
443
+ actionProgress = {};
444
+ collapsedOutputComponentIds.clear();
445
+ publish("state");
446
+ },
265
447
  async runAction(component, runner) {
266
448
  const execution = actionController.begin(component);
267
449
  if (!execution) {
@@ -269,6 +451,7 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
269
451
  }
270
452
  const abortController = new AbortController();
271
453
  activeActions.set(execution.id, { abortController, execution });
454
+ delayActionLoadingPresentation(execution);
272
455
  removeActionPresentation(component.id);
273
456
  publish("action");
274
457
  try {
@@ -288,9 +471,14 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
288
471
  if (!actionController.isCurrent(execution)) {
289
472
  return;
290
473
  }
291
- const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
474
+ const statePatch = actionController.resolveStatePatch(
475
+ execution,
476
+ stampChatResponseAtBrowserReceipt(component, result.statePatch)
477
+ );
292
478
  if (statePatch) {
293
- state = applyUiGraphStatePatch(state, statePatch);
479
+ const nextState = applyUiGraphStatePatch(state, statePatch);
480
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
481
+ state = nextState;
294
482
  }
295
483
  } catch (error) {
296
484
  if (!abortController.signal.aborted && actionController.isCurrent(execution)) {
@@ -301,6 +489,7 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
301
489
  }
302
490
  } finally {
303
491
  if (activeActions.delete(execution.id)) {
492
+ clearActionLoadingPresentation(execution.id);
304
493
  actionController.finish(execution);
305
494
  if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
306
495
  actionProgress = { ...actionProgress };
@@ -314,16 +503,49 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
314
503
  if (nextUiGraph.id !== uiGraphId) {
315
504
  abortAllActions(false);
316
505
  uiGraphId = nextUiGraph.id;
317
- state = getUiGraphInitialState(nextUiGraph);
506
+ initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);
507
+ state = { ...initialState };
318
508
  actionErrors = {};
319
509
  actionProgress = {};
510
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
511
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
512
+ actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
513
+ collapsedOutputComponentIds.clear();
320
514
  publish("graph");
321
515
  return;
322
516
  }
323
- const actionComponentIds = new Set(
324
- nextUiGraph.components.filter((component) => component.type === "button" || component.type === "chat").map((component) => component.id)
517
+ if (!initialStateOverride) {
518
+ initialState = getUiGraphInitialState(nextUiGraph);
519
+ }
520
+ const normalizedState = normalizeUiGraphDropdownState(nextUiGraph, state);
521
+ const stateChanged = normalizedState !== state;
522
+ if (stateChanged) {
523
+ state = normalizedState;
524
+ }
525
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
526
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
527
+ const collapsedOutputIdsBeforeCleanup = collapsedOutputComponentIds.size;
528
+ for (const componentId of collapsedOutputComponentIds) {
529
+ if (!outputComponentIds.has(componentId)) {
530
+ collapsedOutputComponentIds.delete(componentId);
531
+ }
532
+ }
533
+ const nextActionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
534
+ const actionComponentIds = new Set(nextActionComponentsById.keys());
535
+ const changedActionComponentIds = new Set(
536
+ [...nextActionComponentsById].flatMap(([componentId, component]) => {
537
+ const previousComponent = actionComponentsById.get(componentId);
538
+ return previousComponent && !areUiGraphActionComponentsExecutionEquivalent(previousComponent, component) ? [componentId] : [];
539
+ })
325
540
  );
326
- let changed = abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId), false);
541
+ let changed = collapsedOutputComponentIds.size !== collapsedOutputIdsBeforeCleanup || stateChanged || abortMatchingActions(
542
+ ({ execution }) => !actionComponentIds.has(execution.componentId) || changedActionComponentIds.has(execution.componentId),
543
+ false
544
+ );
545
+ for (const componentId of changedActionComponentIds) {
546
+ changed = removeActionPresentation(componentId) || changed;
547
+ }
548
+ actionComponentsById = nextActionComponentsById;
327
549
  const remainingErrors = Object.fromEntries(
328
550
  Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId))
329
551
  );
@@ -346,20 +568,65 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
346
568
  listeners.add(listener);
347
569
  return () => listeners.delete(listener);
348
570
  },
571
+ toggleOutputCollapsed(componentId) {
572
+ if (!outputComponentIds.has(componentId)) {
573
+ return;
574
+ }
575
+ if (collapsedOutputComponentIds.has(componentId)) {
576
+ collapsedOutputComponentIds.delete(componentId);
577
+ } else {
578
+ collapsedOutputComponentIds.add(componentId);
579
+ }
580
+ publish("presentation");
581
+ },
349
582
  updateState(stateKey, value) {
350
583
  actionController.noteStateWrite(stateKey);
351
- state = { ...state, [stateKey]: value };
584
+ const nextState = { ...state, [stateKey]: value };
585
+ expandOutputsForUpdatedState([stateKey], nextState);
586
+ state = nextState;
352
587
  publish("state");
353
588
  },
354
589
  updateStatePatch(statePatch) {
355
590
  for (const stateKey of Object.keys(statePatch)) {
356
591
  actionController.noteStateWrite(stateKey);
357
592
  }
358
- state = applyUiGraphStatePatch(state, statePatch);
593
+ const nextState = applyUiGraphStatePatch(state, statePatch);
594
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
595
+ state = nextState;
359
596
  publish("state");
360
597
  }
361
598
  };
362
599
  }
600
+ function getUiGraphOutputComponentIds(uiGraph) {
601
+ return new Set(
602
+ uiGraph.components.filter((component) => component.type === "output").map((component) => component.id)
603
+ );
604
+ }
605
+ function getUiGraphOutputComponentsByStateKey(uiGraph) {
606
+ const componentsByStateKey = /* @__PURE__ */ new Map();
607
+ for (const component of uiGraph.components) {
608
+ if (component.type !== "output") continue;
609
+ const components = componentsByStateKey.get(component.stateKey) ?? [];
610
+ components.push(component);
611
+ componentsByStateKey.set(component.stateKey, components);
612
+ }
613
+ return componentsByStateKey;
614
+ }
615
+ function normalizeUiGraphDropdownState(uiGraph, state) {
616
+ let normalizedState;
617
+ for (const component of uiGraph.components) {
618
+ if (component.type !== "dropdown") {
619
+ continue;
620
+ }
621
+ const selectedValue = `${state[component.stateKey] ?? ""}`;
622
+ if (selectedValue === "" || component.items.some((item) => item.value === selectedValue)) {
623
+ continue;
624
+ }
625
+ normalizedState ??= { ...state };
626
+ normalizedState[component.stateKey] = "";
627
+ }
628
+ return normalizedState ?? state;
629
+ }
363
630
  function getUiGraphComponentRenderModel(component, state) {
364
631
  switch (component.type) {
365
632
  case "text":
@@ -376,6 +643,16 @@ function getUiGraphComponentRenderModel(component, state) {
376
643
  type: component.type,
377
644
  value: `${state[component.stateKey] ?? component.defaultValue ?? ""}`
378
645
  };
646
+ case "dropdown": {
647
+ const selectedValue = `${state[component.stateKey] ?? ""}`;
648
+ return {
649
+ component,
650
+ items: component.items,
651
+ label: getUiGraphComponentLabel(component),
652
+ type: "dropdown",
653
+ value: component.items.some((item) => item.value === selectedValue) ? selectedValue : ""
654
+ };
655
+ }
379
656
  case "button":
380
657
  return { component, label: component.label, type: "button" };
381
658
  case "chat":
@@ -383,6 +660,7 @@ function getUiGraphComponentRenderModel(component, state) {
383
660
  component,
384
661
  draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ""}`,
385
662
  messages: getUiGraphChatMessages(component.id, state),
663
+ pins: getUiGraphChatPins(component.id, state),
386
664
  type: "chat"
387
665
  };
388
666
  case "output":
@@ -399,15 +677,17 @@ function getUiGraphComponentLabel(component) {
399
677
  }
400
678
  function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
401
679
  const value = state[stateKey];
402
- const hasValue = hasUiGraphStateValue(state, stateKey);
403
680
  const renderedValue = renderUiGraphOutputValue(value, renderAs);
404
- const imageSource = hasValue && renderAs === "image" ? getUiGraphImageSource(value) : void 0;
405
- const imageErrorMessage = hasValue && renderAs === "image" && !imageSource ? "Expected an image URL or base64 image." : void 0;
681
+ const hasStateValue = hasUiGraphStateValue(state, stateKey);
682
+ const hasImageValue = hasStateValue && value != null && value !== "";
683
+ const imageSource = hasImageValue && renderAs === "image" ? getUiGraphImageSource(value) : void 0;
684
+ const imageErrorMessage = hasImageValue && renderAs === "image" && !imageSource ? "Expected an image URL or base64 image." : void 0;
685
+ const hasValue = renderAs === "image" ? imageSource != null || imageErrorMessage != null : renderedValue.trim().length > 0;
406
686
  return {
407
687
  hasValue,
408
688
  ...imageErrorMessage ? { imageErrorMessage } : {},
409
689
  ...imageSource ? { imageSource } : {},
410
- ...hasValue && renderAs === "json" ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {},
690
+ ...hasValue && renderAs === "json" ? { jsonDownloadValue: renderedValue } : {},
411
691
  renderedValue,
412
692
  renderAs
413
693
  };
@@ -421,6 +701,30 @@ function renderUiGraphOutputValue(value, renderAs) {
421
701
  }
422
702
  return typeof value === "string" ? value : value == null ? "" : stringifyUiGraphValue(value) ?? "";
423
703
  }
704
+ function getUiGraphProgressiveJsonOutputChunks(value) {
705
+ if (value.length < UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD) {
706
+ return void 0;
707
+ }
708
+ const chunks = [];
709
+ let offset = 0;
710
+ let chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS;
711
+ while (offset < value.length) {
712
+ let nextOffset = Math.min(value.length, offset + chunkLength);
713
+ if (nextOffset < value.length && isHighSurrogate(value.charCodeAt(nextOffset - 1)) && isLowSurrogate(value.charCodeAt(nextOffset))) {
714
+ nextOffset += 1;
715
+ }
716
+ chunks.push(value.slice(offset, nextOffset));
717
+ offset = nextOffset;
718
+ chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS;
719
+ }
720
+ return chunks;
721
+ }
722
+ function isHighSurrogate(value) {
723
+ return value >= 55296 && value <= 56319;
724
+ }
725
+ function isLowSurrogate(value) {
726
+ return value >= 56320 && value <= 57343;
727
+ }
424
728
  function getUiGraphImageSource(value) {
425
729
  if (typeof value !== "string") {
426
730
  return void 0;
@@ -492,11 +796,12 @@ function parseRivetWebAppClientMessage(value) {
492
796
  case "client.hello":
493
797
  return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? { type: value.type, protocolVersion: value.protocolVersion } : void 0;
494
798
  case "action.start":
495
- return isNonEmptyString(value.requestId) && isNonEmptyString(value.componentId) && isRecord(value.state) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
799
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.componentId) && isRecord(value.state) && (value.storage == null || isRecord(value.storage)) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
496
800
  type: value.type,
497
801
  requestId: value.requestId,
498
802
  componentId: value.componentId,
499
803
  state: value.state,
804
+ ...isRecord(value.storage) ? { storage: value.storage } : {},
500
805
  ...typeof value.revisionKey === "string" ? { revisionKey: value.revisionKey } : {}
501
806
  } : void 0;
502
807
  case "action.cancel":
@@ -548,7 +853,12 @@ function parseRivetWebAppServerMessage(value) {
548
853
  return progress ? { type: value.type, ...base, progress } : void 0;
549
854
  }
550
855
  case "action.completed":
551
- return isRecord(value.statePatch) ? { type: value.type, ...base, statePatch: value.statePatch } : void 0;
856
+ return isRecord(value.statePatch) && (value.storagePatch == null || isRecord(value.storagePatch)) ? {
857
+ type: value.type,
858
+ ...base,
859
+ statePatch: value.statePatch,
860
+ ...isRecord(value.storagePatch) ? { storagePatch: value.storagePatch } : {}
861
+ } : void 0;
552
862
  case "action.failed":
553
863
  return isNonEmptyString(value.error) ? {
554
864
  type: value.type,
@@ -573,6 +883,270 @@ function isNonEmptyString(value) {
573
883
  }
574
884
 
575
885
  // src/model/UiGraphBrowserRuntime.ts
886
+ var OUTPUT_MAX_HEIGHT_PX = 800;
887
+ var OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
888
+ var OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-min-height";
889
+ var OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-max-height";
890
+ var CHAT_SEARCH_MATCH_CLASS = "rivet-web-app-chat-search-match";
891
+ var CHAT_SEARCH_ACTIVE_MATCH_CLASS = "rivet-web-app-chat-search-match-active";
892
+ var UI_GRAPH_CHAT_STORAGE_PREFIX = "rivet-web-app-chat-state:v1";
893
+ var UI_GRAPH_APP_STORAGE_PREFIX = "rivet-web-app-storage:v1";
894
+ var escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
895
+ var getPixelValue = (value, fallback) => {
896
+ const parsed = Number.parseFloat(value);
897
+ return Number.isFinite(parsed) ? parsed : fallback;
898
+ };
899
+ var setStyleProperty = (element, property, value) => {
900
+ if (element.style.getPropertyValue(property) !== value) {
901
+ element.style.setProperty(property, value);
902
+ }
903
+ };
904
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
905
+ var getDefaultUiGraphBrowserStorage = () => {
906
+ var _a;
907
+ try {
908
+ return globalThis.localStorage ?? ((_a = globalThis.window) == null ? void 0 : _a.localStorage);
909
+ } catch {
910
+ return void 0;
911
+ }
912
+ };
913
+ var getDefaultUiGraphStorageLocation = () => {
914
+ var _a;
915
+ try {
916
+ return globalThis.location ?? ((_a = globalThis.window) == null ? void 0 : _a.location);
917
+ } catch {
918
+ return void 0;
919
+ }
920
+ };
921
+ function getUiGraphChatMessagePresentations(messages, options = {}) {
922
+ const { locales, timeZone } = options;
923
+ const timeFormatter = new Intl.DateTimeFormat(locales, {
924
+ hour: "2-digit",
925
+ hourCycle: "h23",
926
+ minute: "2-digit",
927
+ ...timeZone ? { timeZone } : {}
928
+ });
929
+ const dateFormatter = new Intl.DateTimeFormat(locales, {
930
+ day: "numeric",
931
+ month: "long",
932
+ year: "numeric",
933
+ ...timeZone ? { timeZone } : {}
934
+ });
935
+ const dateKeyFormatter = new Intl.DateTimeFormat("en-CA", {
936
+ day: "2-digit",
937
+ month: "2-digit",
938
+ year: "numeric",
939
+ ...timeZone ? { timeZone } : {}
940
+ });
941
+ const entries = messages.map((message) => {
942
+ const timestamp = parseUiGraphChatTimestamp(message.timestamp);
943
+ if (!timestamp) return void 0;
944
+ return {
945
+ dateKey: dateKeyFormatter.format(timestamp),
946
+ dateTime: timestamp.toISOString(),
947
+ dateLabel: dateFormatter.format(timestamp),
948
+ timeLabel: timeFormatter.format(timestamp)
949
+ };
950
+ });
951
+ const hasMultipleDates = new Set(entries.flatMap((entry) => entry ? [entry.dateKey] : [])).size > 1;
952
+ let previousDateKey;
953
+ return entries.map((entry) => {
954
+ if (!entry) return {};
955
+ const dateSeparator = hasMultipleDates && previousDateKey != null && previousDateKey !== entry.dateKey ? { dateTime: entry.dateTime, label: entry.dateLabel } : void 0;
956
+ previousDateKey = entry.dateKey;
957
+ return {
958
+ ...dateSeparator ? { dateSeparator } : {},
959
+ timestamp: { dateTime: entry.dateTime, label: entry.timeLabel }
960
+ };
961
+ });
962
+ }
963
+ var parseUiGraphChatTimestamp = (value) => {
964
+ if (typeof value !== "string") return void 0;
965
+ const timestamp = new Date(value);
966
+ return Number.isNaN(timestamp.getTime()) ? void 0 : timestamp;
967
+ };
968
+ function getUiGraphChatStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
969
+ if (!(location == null ? void 0 : location.origin)) {
970
+ return void 0;
971
+ }
972
+ const pathname = location.pathname.replace(/\/+$/, "") || "/";
973
+ return [
974
+ UI_GRAPH_CHAT_STORAGE_PREFIX,
975
+ encodeURIComponent(location.origin),
976
+ encodeURIComponent(pathname),
977
+ encodeURIComponent(uiGraph.id)
978
+ ].join(":");
979
+ }
980
+ function getUiGraphWebAppStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
981
+ if (!(location == null ? void 0 : location.origin)) {
982
+ return void 0;
983
+ }
984
+ const pathname = location.pathname.replace(/\/+$/, "") || "/";
985
+ return [
986
+ UI_GRAPH_APP_STORAGE_PREFIX,
987
+ encodeURIComponent(location.origin),
988
+ encodeURIComponent(pathname),
989
+ encodeURIComponent(uiGraph.id)
990
+ ].join(":");
991
+ }
992
+ function loadUiGraphWebAppStorage(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
993
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
994
+ if (!key || !storage) return {};
995
+ try {
996
+ const serialized = storage.getItem(key);
997
+ if (!serialized) return {};
998
+ const value = JSON.parse(serialized);
999
+ return isRecord2(value) ? value : {};
1000
+ } catch {
1001
+ return {};
1002
+ }
1003
+ }
1004
+ function applyUiGraphWebAppStoragePatch(uiGraph, currentStorage, patch, storage = getDefaultUiGraphBrowserStorage(), location) {
1005
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
1006
+ if (!key || !storage) {
1007
+ throw new Error("Browser storage is unavailable for this web app.");
1008
+ }
1009
+ const nextStorage = { ...currentStorage, ...patch };
1010
+ let serialized;
1011
+ try {
1012
+ serialized = JSON.stringify(nextStorage);
1013
+ storage.setItem(key, serialized);
1014
+ } catch (error) {
1015
+ throw new Error("Web app storage could not be saved. Browser storage may be unavailable or full.", {
1016
+ cause: error
1017
+ });
1018
+ }
1019
+ return nextStorage;
1020
+ }
1021
+ function applyUiGraphWebAppStorageActionPatch(patch, actionNumber, appliedActionByKey, persist) {
1022
+ const applicablePatch = Object.fromEntries(
1023
+ Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0))
1024
+ );
1025
+ const applicableKeys = Object.keys(applicablePatch);
1026
+ if (applicableKeys.length === 0) return applicablePatch;
1027
+ persist(applicablePatch);
1028
+ for (const key of applicableKeys) appliedActionByKey.set(key, actionNumber);
1029
+ return applicablePatch;
1030
+ }
1031
+ function getUiGraphChatPersistentState(uiGraph, state) {
1032
+ const persistentState = {};
1033
+ for (const component of uiGraph.components) {
1034
+ if (component.type !== "chat") continue;
1035
+ const draftStateKey = getUiGraphChatDraftStateKey(component.id);
1036
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
1037
+ const pinsStateKey = getUiGraphChatPinsStateKey(component.id);
1038
+ const draft = state[draftStateKey];
1039
+ const messages = getUiGraphChatMessages(component.id, state);
1040
+ const pins = getUiGraphChatPins(component.id, state).map((pin) => pin.messageIndex);
1041
+ if (typeof draft === "string" && draft) {
1042
+ persistentState[draftStateKey] = draft;
1043
+ }
1044
+ if (messages.length > 0) {
1045
+ persistentState[messagesStateKey] = messages;
1046
+ }
1047
+ if (pins.length > 0) {
1048
+ persistentState[pinsStateKey] = pins;
1049
+ }
1050
+ }
1051
+ return persistentState;
1052
+ }
1053
+ function hasUiGraphChatPersistentStateChanged(uiGraph, previousState, nextState) {
1054
+ return uiGraph.components.some((component) => {
1055
+ if (component.type !== "chat") return false;
1056
+ return previousState[getUiGraphChatDraftStateKey(component.id)] !== nextState[getUiGraphChatDraftStateKey(component.id)] || previousState[getUiGraphChatMessagesStateKey(component.id)] !== nextState[getUiGraphChatMessagesStateKey(component.id)] || previousState[getUiGraphChatPinsStateKey(component.id)] !== nextState[getUiGraphChatPinsStateKey(component.id)];
1057
+ });
1058
+ }
1059
+ function loadUiGraphChatPersistentState(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
1060
+ const key = getUiGraphChatStorageKey(uiGraph, location);
1061
+ if (!key || !storage) {
1062
+ return {};
1063
+ }
1064
+ try {
1065
+ const serializedState = storage.getItem(key);
1066
+ if (!serializedState) {
1067
+ return {};
1068
+ }
1069
+ const storedState = JSON.parse(serializedState);
1070
+ return isRecord2(storedState) ? getUiGraphChatPersistentState(uiGraph, storedState) : {};
1071
+ } catch {
1072
+ return {};
1073
+ }
1074
+ }
1075
+ function saveUiGraphChatPersistentState(uiGraph, state, storage = getDefaultUiGraphBrowserStorage(), location) {
1076
+ const key = getUiGraphChatStorageKey(uiGraph, location);
1077
+ if (!key || !storage) {
1078
+ return;
1079
+ }
1080
+ try {
1081
+ const persistentState = getUiGraphChatPersistentState(uiGraph, state);
1082
+ if (Object.keys(persistentState).length === 0) {
1083
+ storage.removeItem(key);
1084
+ return;
1085
+ }
1086
+ const serializedState = JSON.stringify(persistentState);
1087
+ if (storage.getItem(key) !== serializedState) {
1088
+ storage.setItem(key, serializedState);
1089
+ }
1090
+ } catch {
1091
+ }
1092
+ }
1093
+ function observeUiGraphOutputResizeBounds(output) {
1094
+ const ownerWindow = output.ownerDocument.defaultView;
1095
+ let scheduledFrame;
1096
+ const sync = () => {
1097
+ scheduledFrame = void 0;
1098
+ if (!ownerWindow) return;
1099
+ const header = output.querySelector(".rivet-web-app-output-header");
1100
+ const content = output.querySelector(".rivet-web-app-output-content");
1101
+ const body = output.querySelector(".rivet-web-app-output-content-body");
1102
+ if (!header || !content || !body) {
1103
+ output.classList.remove("rivet-web-app-output-resizable");
1104
+ output.classList.remove("rivet-web-app-output-scrollable");
1105
+ output.style.removeProperty(OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY);
1106
+ output.style.removeProperty(OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY);
1107
+ return;
1108
+ }
1109
+ const bodyStyle = ownerWindow.getComputedStyle(body);
1110
+ const lineHeight = getPixelValue(bodyStyle.lineHeight, getPixelValue(bodyStyle.fontSize, 16) * 1.5);
1111
+ const contentStyle = ownerWindow.getComputedStyle(content);
1112
+ const contentPadding = getPixelValue(contentStyle.paddingTop, 0) + getPixelValue(contentStyle.paddingBottom, 0);
1113
+ const verticalBorder = Math.max(0, output.offsetHeight - output.clientHeight);
1114
+ const minimumHeight = Math.ceil(
1115
+ header.getBoundingClientRect().height + contentPadding + lineHeight + verticalBorder
1116
+ );
1117
+ const naturalHeight = Math.ceil(
1118
+ header.getBoundingClientRect().height + contentPadding + Math.max(body.scrollHeight, lineHeight) + verticalBorder
1119
+ );
1120
+ const viewportHeight = (ownerWindow == null ? void 0 : ownerWindow.innerHeight) ?? OUTPUT_MAX_HEIGHT_PX / OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO;
1121
+ const maximumViewportHeight = Math.min(viewportHeight * OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO, OUTPUT_MAX_HEIGHT_PX);
1122
+ output.classList.toggle("rivet-web-app-output-resizable", naturalHeight > maximumViewportHeight);
1123
+ output.classList.toggle("rivet-web-app-output-scrollable", body.scrollHeight > body.clientHeight);
1124
+ setStyleProperty(output, OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY, `${minimumHeight}px`);
1125
+ setStyleProperty(output, OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY, `${naturalHeight}px`);
1126
+ };
1127
+ const scheduleSync = () => {
1128
+ if (scheduledFrame != null) return;
1129
+ if (ownerWindow == null ? void 0 : ownerWindow.requestAnimationFrame) {
1130
+ scheduledFrame = ownerWindow.requestAnimationFrame(sync);
1131
+ } else {
1132
+ sync();
1133
+ }
1134
+ };
1135
+ const resizeObserver = (ownerWindow == null ? void 0 : ownerWindow.ResizeObserver) ? new ownerWindow.ResizeObserver(scheduleSync) : void 0;
1136
+ resizeObserver == null ? void 0 : resizeObserver.observe(output);
1137
+ const mutationObserver = (ownerWindow == null ? void 0 : ownerWindow.MutationObserver) ? new ownerWindow.MutationObserver(scheduleSync) : void 0;
1138
+ mutationObserver == null ? void 0 : mutationObserver.observe(output, { childList: true, characterData: true, subtree: true });
1139
+ output.addEventListener("load", scheduleSync, true);
1140
+ ownerWindow == null ? void 0 : ownerWindow.addEventListener("resize", scheduleSync);
1141
+ sync();
1142
+ return () => {
1143
+ if (scheduledFrame != null) ownerWindow == null ? void 0 : ownerWindow.cancelAnimationFrame(scheduledFrame);
1144
+ resizeObserver == null ? void 0 : resizeObserver.disconnect();
1145
+ mutationObserver == null ? void 0 : mutationObserver.disconnect();
1146
+ output.removeEventListener("load", scheduleSync, true);
1147
+ ownerWindow == null ? void 0 : ownerWindow.removeEventListener("resize", scheduleSync);
1148
+ };
1149
+ }
576
1150
  async function copyUiGraphText(value) {
577
1151
  var _a;
578
1152
  try {
@@ -606,20 +1180,160 @@ function downloadUiGraphJsonOutput(value, appName) {
606
1180
  globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);
607
1181
  }
608
1182
  }
1183
+ function enhanceUiGraphChatJsonCodeBlocks(root, appName) {
1184
+ var _a;
1185
+ const codeBlocks = root.querySelectorAll("pre > code.language-json");
1186
+ root.classList.toggle("rivet-web-app-chat-markdown-has-json", codeBlocks.length > 0);
1187
+ for (const code of codeBlocks) {
1188
+ const pre = code.parentElement;
1189
+ const existingWrapper = pre == null ? void 0 : pre.parentElement;
1190
+ if (!pre) {
1191
+ continue;
1192
+ }
1193
+ if (existingWrapper == null ? void 0 : existingWrapper.classList.contains("rivet-web-app-chat-json-block")) {
1194
+ existingWrapper.dataset.rivetChatJsonAppName = appName;
1195
+ continue;
1196
+ }
1197
+ const value = code.textContent ?? "";
1198
+ const document2 = root.ownerDocument;
1199
+ const wrapper = document2.createElement("div");
1200
+ wrapper.className = "rivet-web-app-chat-json-block";
1201
+ wrapper.dataset.rivetChatJsonAppName = appName;
1202
+ const actions = document2.createElement("div");
1203
+ actions.className = "rivet-web-app-chat-json-actions";
1204
+ actions.dataset.rivetChatSearchIgnore = "true";
1205
+ const copyButton = document2.createElement("button");
1206
+ copyButton.type = "button";
1207
+ copyButton.className = "rivet-web-app-output-action-button rivet-web-app-output-copy-button";
1208
+ copyButton.title = "Copy JSON";
1209
+ copyButton.setAttribute("aria-label", "Copy JSON");
1210
+ copyButton.addEventListener("click", (event) => {
1211
+ event.stopPropagation();
1212
+ void copyUiGraphText(value);
1213
+ });
1214
+ const downloadButton = document2.createElement("button");
1215
+ downloadButton.type = "button";
1216
+ downloadButton.className = "rivet-web-app-output-action-button rivet-web-app-output-download-button";
1217
+ downloadButton.title = "Download JSON";
1218
+ downloadButton.setAttribute("aria-label", "Download JSON");
1219
+ downloadButton.addEventListener("click", (event) => {
1220
+ event.stopPropagation();
1221
+ downloadUiGraphJsonOutput(value, wrapper.dataset.rivetChatJsonAppName ?? appName);
1222
+ });
1223
+ actions.append(copyButton, downloadButton);
1224
+ pre.replaceWith(wrapper);
1225
+ wrapper.append(pre, actions);
1226
+ const syncScrollableState = () => {
1227
+ wrapper.classList.toggle("rivet-web-app-chat-json-block-scrollable", pre.scrollHeight > pre.clientHeight);
1228
+ };
1229
+ syncScrollableState();
1230
+ (_a = root.ownerDocument.defaultView) == null ? void 0 : _a.requestAnimationFrame(syncScrollableState);
1231
+ }
1232
+ }
1233
+ function highlightUiGraphChatSearchMatches(messagesElement, query, requestedActiveIndex = 0) {
1234
+ var _a, _b;
1235
+ clearUiGraphChatSearchMatches(messagesElement);
1236
+ const searchText = query.trim();
1237
+ if (!searchText) {
1238
+ return { activeIndex: -1, matches: [] };
1239
+ }
1240
+ const document2 = messagesElement.ownerDocument;
1241
+ const textNodes = [];
1242
+ const walker = document2.createTreeWalker(messagesElement, 4);
1243
+ let node = walker.nextNode();
1244
+ while (node) {
1245
+ if ((_a = node.parentElement) == null ? void 0 : _a.closest("script, style, textarea, [data-rivet-chat-search-ignore]")) {
1246
+ node = walker.nextNode();
1247
+ continue;
1248
+ }
1249
+ textNodes.push(node);
1250
+ node = walker.nextNode();
1251
+ }
1252
+ const matches = [];
1253
+ for (const textNode of textNodes) {
1254
+ const value = textNode.data;
1255
+ const ranges = [];
1256
+ const expression = new RegExp(escapeRegularExpression(searchText), "gi");
1257
+ for (const match of value.matchAll(expression)) {
1258
+ if (match.index != null && match[0]) {
1259
+ ranges.push({ start: match.index, end: match.index + match[0].length });
1260
+ }
1261
+ }
1262
+ if (ranges.length === 0 || !textNode.parentNode) {
1263
+ continue;
1264
+ }
1265
+ const fragment = document2.createDocumentFragment();
1266
+ let cursor = 0;
1267
+ for (const range of ranges) {
1268
+ fragment.append(value.slice(cursor, range.start));
1269
+ const match = document2.createElement("mark");
1270
+ match.className = CHAT_SEARCH_MATCH_CLASS;
1271
+ match.textContent = value.slice(range.start, range.end);
1272
+ fragment.append(match);
1273
+ matches.push(match);
1274
+ cursor = range.end;
1275
+ }
1276
+ fragment.append(value.slice(cursor));
1277
+ textNode.parentNode.replaceChild(fragment, textNode);
1278
+ }
1279
+ if (matches.length === 0) {
1280
+ return { activeIndex: -1, matches };
1281
+ }
1282
+ const activeIndex = (requestedActiveIndex % matches.length + matches.length) % matches.length;
1283
+ (_b = matches[activeIndex]) == null ? void 0 : _b.classList.add(CHAT_SEARCH_ACTIVE_MATCH_CLASS);
1284
+ return { activeIndex, matches };
1285
+ }
1286
+ function clearUiGraphChatSearchMatches(messagesElement) {
1287
+ for (const match of messagesElement.querySelectorAll(`.${CHAT_SEARCH_MATCH_CLASS}`)) {
1288
+ match.replaceWith(messagesElement.ownerDocument.createTextNode(match.textContent ?? ""));
1289
+ }
1290
+ messagesElement.normalize();
1291
+ }
1292
+ function revealUiGraphChatElement(messagesElement, element, alignment = "center") {
1293
+ if (!element || !messagesElement.contains(element)) {
1294
+ return;
1295
+ }
1296
+ const containerRect = messagesElement.getBoundingClientRect();
1297
+ const elementRect = element.getBoundingClientRect();
1298
+ const maxScrollTop = Math.max(0, messagesElement.scrollHeight - messagesElement.clientHeight);
1299
+ const offset = elementRect.top - containerRect.top - (alignment === "center" ? (messagesElement.clientHeight - elementRect.height) / 2 : 0);
1300
+ messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));
1301
+ }
1302
+ var revealUiGraphChatSearchMatch = revealUiGraphChatElement;
609
1303
  // Annotate the CommonJS export names for ESM import in node:
610
1304
  0 && (module.exports = {
611
1305
  RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
612
1306
  applyUiGraphStatePatch,
1307
+ applyUiGraphWebAppStorageActionPatch,
1308
+ applyUiGraphWebAppStoragePatch,
1309
+ clearUiGraphChatSearchMatches,
613
1310
  copyUiGraphText,
614
1311
  createUiGraphActionExecutionController,
1312
+ createUiGraphChatHistoryFlushStatePatch,
1313
+ createUiGraphChatPinStatePatch,
615
1314
  createUiGraphChatSubmissionStatePatch,
616
1315
  createUiGraphInteractionController,
617
1316
  downloadUiGraphJsonOutput,
1317
+ enhanceUiGraphChatJsonCodeBlocks,
618
1318
  getUiGraphActionState,
619
1319
  getUiGraphChatDraftStateKey,
1320
+ getUiGraphChatMessagePresentations,
1321
+ getUiGraphChatMessagesStateKey,
1322
+ getUiGraphChatPersistentState,
1323
+ getUiGraphChatStorageKey,
620
1324
  getUiGraphComponentRenderModel,
621
1325
  getUiGraphJsonOutputFilename,
1326
+ getUiGraphProgressiveJsonOutputChunks,
1327
+ getUiGraphWebAppStorageKey,
1328
+ hasUiGraphChatPersistentStateChanged,
1329
+ highlightUiGraphChatSearchMatches,
1330
+ loadUiGraphChatPersistentState,
1331
+ loadUiGraphWebAppStorage,
1332
+ observeUiGraphOutputResizeBounds,
622
1333
  parseRivetWebAppClientMessage,
623
- parseRivetWebAppServerMessage
1334
+ parseRivetWebAppServerMessage,
1335
+ revealUiGraphChatElement,
1336
+ revealUiGraphChatSearchMatch,
1337
+ saveUiGraphChatPersistentState
624
1338
  });
625
1339
  //# sourceMappingURL=webAppRuntime.cjs.map