@valerypopoff/rivet2-core 2.1.4 → 2.1.5

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 (70) hide show
  1. package/dist/cjs/bundle.cjs +3733 -969
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +605 -16
  4. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  5. package/dist/esm/api/createProcessor.js +5 -1
  6. package/dist/esm/exports.js +3 -0
  7. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  8. package/dist/esm/model/GraphProcessor.js +1127 -82
  9. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  10. package/dist/esm/model/Nodes.js +9 -0
  11. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  12. package/dist/esm/model/RecordingPlayer.js +9 -0
  13. package/dist/esm/model/StoredValueStore.js +226 -0
  14. package/dist/esm/model/SubprocessorBridge.js +50 -19
  15. package/dist/esm/model/ToolCallContinuation.js +1 -0
  16. package/dist/esm/model/UiGraph.js +50 -0
  17. package/dist/esm/model/UiGraphActionProtocol.js +10 -1
  18. package/dist/esm/model/UiGraphBrowserRuntime.js +333 -0
  19. package/dist/esm/model/UiGraphNormalization.js +35 -185
  20. package/dist/esm/model/UiGraphRendererStyles.js +772 -74
  21. package/dist/esm/model/UiGraphRuntimeModel.js +230 -14
  22. package/dist/esm/model/UiGraphSchema.js +91 -0
  23. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  24. package/dist/esm/model/chat/chatMessages.js +5 -9
  25. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  26. package/dist/esm/model/chat-v2/index.js +1 -0
  27. package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
  28. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  29. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  30. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  31. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  32. package/dist/esm/model/nodes/MatchNode.js +7 -7
  33. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  34. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  35. package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
  36. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  37. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  38. package/dist/esm/utils/coerceType.js +3 -0
  39. package/dist/esm/webAppRuntime.js +3 -3
  40. package/dist/types/api/createProcessor.d.ts +4 -0
  41. package/dist/types/exports.d.ts +3 -0
  42. package/dist/types/model/EditorDefinition.d.ts +2 -1
  43. package/dist/types/model/ExecutorProtocol.d.ts +12 -0
  44. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  45. package/dist/types/model/GraphProcessor.d.ts +19 -2
  46. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  47. package/dist/types/model/Nodes.d.ts +5 -2
  48. package/dist/types/model/ProcessContext.d.ts +15 -0
  49. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  50. package/dist/types/model/StoredValueStore.d.ts +55 -0
  51. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  52. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  53. package/dist/types/model/UiGraph.d.ts +21 -0
  54. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  55. package/dist/types/model/UiGraphBrowserRuntime.d.ts +51 -0
  56. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  57. package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
  58. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  59. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  60. package/dist/types/model/chat-v2/index.d.ts +1 -0
  61. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  62. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  63. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  64. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  65. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  66. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  67. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  68. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  69. package/dist/types/webAppRuntime.d.ts +4 -4
  70. package/package.json +1 -1
@@ -22,17 +22,35 @@ 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,
30
35
  getUiGraphActionState: () => getUiGraphActionState,
31
36
  getUiGraphChatDraftStateKey: () => getUiGraphChatDraftStateKey,
37
+ getUiGraphChatMessagesStateKey: () => getUiGraphChatMessagesStateKey,
38
+ getUiGraphChatPersistentState: () => getUiGraphChatPersistentState,
39
+ getUiGraphChatStorageKey: () => getUiGraphChatStorageKey,
32
40
  getUiGraphComponentRenderModel: () => getUiGraphComponentRenderModel,
33
41
  getUiGraphJsonOutputFilename: () => getUiGraphJsonOutputFilename,
42
+ getUiGraphProgressiveJsonOutputChunks: () => getUiGraphProgressiveJsonOutputChunks,
43
+ getUiGraphWebAppStorageKey: () => getUiGraphWebAppStorageKey,
44
+ hasUiGraphChatPersistentStateChanged: () => hasUiGraphChatPersistentStateChanged,
45
+ highlightUiGraphChatSearchMatches: () => highlightUiGraphChatSearchMatches,
46
+ loadUiGraphChatPersistentState: () => loadUiGraphChatPersistentState,
47
+ loadUiGraphWebAppStorage: () => loadUiGraphWebAppStorage,
48
+ observeUiGraphOutputResizeBounds: () => observeUiGraphOutputResizeBounds,
34
49
  parseRivetWebAppClientMessage: () => parseRivetWebAppClientMessage,
35
- parseRivetWebAppServerMessage: () => parseRivetWebAppServerMessage
50
+ parseRivetWebAppServerMessage: () => parseRivetWebAppServerMessage,
51
+ revealUiGraphChatElement: () => revealUiGraphChatElement,
52
+ revealUiGraphChatSearchMatch: () => revealUiGraphChatSearchMatch,
53
+ saveUiGraphChatPersistentState: () => saveUiGraphChatPersistentState
36
54
  });
37
55
  module.exports = __toCommonJS(webAppRuntime_exports);
38
56
 
@@ -45,9 +63,12 @@ function getUiGraphInitialState(uiGraph) {
45
63
  for (const component of uiGraph.components) {
46
64
  if (component.type === "input" || component.type === "textarea") {
47
65
  state[component.stateKey] = component.defaultValue ?? "";
66
+ } else if (component.type === "dropdown") {
67
+ state[component.stateKey] = "";
48
68
  } else if (component.type === "chat") {
49
69
  state[getUiGraphChatDraftStateKey(component.id)] = "";
50
70
  state[getUiGraphChatMessagesStateKey(component.id)] = [];
71
+ state[getUiGraphChatPinsStateKey(component.id)] = [];
51
72
  }
52
73
  }
53
74
  return state;
@@ -58,10 +79,55 @@ function getUiGraphChatDraftStateKey(componentId) {
58
79
  function getUiGraphChatMessagesStateKey(componentId) {
59
80
  return `__rivet_chat_${componentId}_messages`;
60
81
  }
82
+ function getUiGraphChatPinsStateKey(componentId) {
83
+ return `__rivet_chat_${componentId}_pins`;
84
+ }
61
85
  function getUiGraphChatMessages(componentId, state) {
62
86
  const messages = state[getUiGraphChatMessagesStateKey(componentId)];
63
87
  return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];
64
88
  }
89
+ function getUiGraphChatPins(componentId, state) {
90
+ const messages = getUiGraphChatMessages(componentId, state);
91
+ const storedPins = state[getUiGraphChatPinsStateKey(componentId)];
92
+ const messageIndexes = Array.isArray(storedPins) ? [
93
+ ...new Set(
94
+ storedPins.filter(
95
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0
96
+ )
97
+ )
98
+ ].sort((left, right) => left - right) : [];
99
+ const pinnedIndexes = new Set(messageIndexes);
100
+ const pins = [];
101
+ let prompt;
102
+ let promptMessageIndex;
103
+ messages.forEach((message, messageIndex) => {
104
+ if (message.role === "user") {
105
+ prompt = message;
106
+ promptMessageIndex = messageIndex;
107
+ } else if (pinnedIndexes.has(messageIndex)) {
108
+ pins.push({ messageIndex, prompt, promptMessageIndex, response: message });
109
+ }
110
+ });
111
+ return pins;
112
+ }
113
+ function createUiGraphChatPinStatePatch(componentId, state, messageIndex) {
114
+ var _a;
115
+ const messages = getUiGraphChatMessages(componentId, state);
116
+ if (((_a = messages[messageIndex]) == null ? void 0 : _a.role) !== "assistant") {
117
+ return void 0;
118
+ }
119
+ const pinsStateKey = getUiGraphChatPinsStateKey(componentId);
120
+ const pinnedIndexes = getUiGraphChatPins(componentId, state).map((pin) => pin.messageIndex);
121
+ return {
122
+ [pinsStateKey]: pinnedIndexes.includes(messageIndex) ? pinnedIndexes.filter((index) => index !== messageIndex) : [...pinnedIndexes, messageIndex].sort((left, right) => left - right)
123
+ };
124
+ }
125
+ function createUiGraphChatHistoryFlushStatePatch(componentId) {
126
+ return {
127
+ [getUiGraphChatMessagesStateKey(componentId)]: [],
128
+ [getUiGraphChatPinsStateKey(componentId)]: []
129
+ };
130
+ }
65
131
  function createUiGraphChatSubmissionStatePatch(componentId, state) {
66
132
  const draftStateKey = getUiGraphChatDraftStateKey(componentId);
67
133
  const content = `${state[draftStateKey] ?? ""}`.trim();
@@ -132,6 +198,38 @@ var IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:avif|bmp|gif|jpe?g|png|webp));bas
132
198
  var IMAGE_URL_PATTERN = /^(?:https?:\/\/|blob:|\/\/|\/|\.\.?\/)/i;
133
199
  var RELATIVE_IMAGE_PATH_PATTERN = /\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;
134
200
  var BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
201
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD = 128 * 1024;
202
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS = 16 * 1024;
203
+ var UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS = 16 * 1024;
204
+ var ACTION_LOADING_DELAY_MS = 300;
205
+ function getUiGraphActionComponentsById(uiGraph) {
206
+ return new Map(
207
+ uiGraph.components.filter(
208
+ (component) => component.type === "button" || component.type === "chat"
209
+ ).map((component) => [component.id, component])
210
+ );
211
+ }
212
+ function areUiGraphActionValuesEqual(left, right) {
213
+ if (Object.is(left, right)) {
214
+ return true;
215
+ }
216
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") {
217
+ return false;
218
+ }
219
+ if (Array.isArray(left) || Array.isArray(right)) {
220
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => areUiGraphActionValuesEqual(value, right[index]));
221
+ }
222
+ const leftRecord = left;
223
+ const rightRecord = right;
224
+ const leftKeys = Object.keys(leftRecord);
225
+ const rightKeys = Object.keys(rightRecord);
226
+ return leftKeys.length === rightKeys.length && leftKeys.every(
227
+ (key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && areUiGraphActionValuesEqual(leftRecord[key], rightRecord[key])
228
+ );
229
+ }
230
+ function areUiGraphActionComponentsExecutionEquivalent(left, right) {
231
+ return left.type === right.type && areUiGraphActionValuesEqual(left.action, right.action);
232
+ }
135
233
  function createUiGraphActionExecutionController() {
136
234
  let nextVersion = 0;
137
235
  const activeExecutionByComponent = /* @__PURE__ */ new Map();
@@ -184,17 +282,34 @@ function createUiGraphActionExecutionController() {
184
282
  }
185
283
  function createUiGraphInteractionController(initialUiGraph, options = {}) {
186
284
  let uiGraphId = initialUiGraph.id;
187
- let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);
285
+ let actionComponentsById = getUiGraphActionComponentsById(initialUiGraph);
286
+ let outputComponentIds = getUiGraphOutputComponentIds(initialUiGraph);
287
+ let outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(initialUiGraph);
288
+ const initialStateOverride = options.initialState ? { ...options.initialState } : void 0;
289
+ let initialState = normalizeUiGraphDropdownState(
290
+ initialUiGraph,
291
+ initialStateOverride ?? getUiGraphInitialState(initialUiGraph)
292
+ );
293
+ let state = { ...initialState };
188
294
  let actionErrors = {};
189
295
  let actionProgress = {};
296
+ const collapsedOutputComponentIds = /* @__PURE__ */ new Set();
190
297
  let snapshot;
191
298
  const actionController = createUiGraphActionExecutionController();
192
299
  const activeActions = /* @__PURE__ */ new Map();
300
+ const loadingActionIds = /* @__PURE__ */ new Set();
301
+ const loadingDelayTimers = /* @__PURE__ */ new Map();
193
302
  const listeners = /* @__PURE__ */ new Set();
194
303
  const updateSnapshot = () => {
195
304
  snapshot = {
196
305
  actionErrors,
197
306
  actionProgress,
307
+ collapsedOutputComponentIds: new Set(collapsedOutputComponentIds),
308
+ loadingComponentIds: new Set(
309
+ [...activeActions].flatMap(
310
+ ([executionId, { execution }]) => loadingActionIds.has(executionId) ? [execution.componentId] : []
311
+ )
312
+ ),
198
313
  runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
199
314
  state
200
315
  };
@@ -205,6 +320,25 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
205
320
  listener(change);
206
321
  }
207
322
  };
323
+ const clearActionLoadingPresentation = (executionId) => {
324
+ const timer = loadingDelayTimers.get(executionId);
325
+ if (timer != null) {
326
+ clearTimeout(timer);
327
+ loadingDelayTimers.delete(executionId);
328
+ }
329
+ loadingActionIds.delete(executionId);
330
+ };
331
+ const delayActionLoadingPresentation = (execution) => {
332
+ loadingDelayTimers.set(
333
+ execution.id,
334
+ setTimeout(() => {
335
+ loadingDelayTimers.delete(execution.id);
336
+ if (!activeActions.has(execution.id) || !actionController.isCurrent(execution)) return;
337
+ loadingActionIds.add(execution.id);
338
+ publish("action");
339
+ }, ACTION_LOADING_DELAY_MS)
340
+ );
341
+ };
208
342
  const abortMatchingActions = (predicate, notify) => {
209
343
  let changed = false;
210
344
  for (const [executionId, activeAction] of activeActions) {
@@ -213,6 +347,7 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
213
347
  }
214
348
  activeAction.abortController.abort();
215
349
  activeActions.delete(executionId);
350
+ clearActionLoadingPresentation(executionId);
216
351
  actionController.finish(activeAction.execution);
217
352
  changed = true;
218
353
  }
@@ -233,13 +368,26 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
233
368
  }
234
369
  };
235
370
  const removeActionPresentation = (componentId) => {
371
+ let changed = false;
236
372
  if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
237
373
  actionErrors = { ...actionErrors };
238
374
  delete actionErrors[componentId];
375
+ changed = true;
239
376
  }
240
377
  if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
241
378
  actionProgress = { ...actionProgress };
242
379
  delete actionProgress[componentId];
380
+ changed = true;
381
+ }
382
+ return changed;
383
+ };
384
+ const expandOutputsForUpdatedState = (stateKeys, nextState) => {
385
+ for (const stateKey of stateKeys) {
386
+ for (const component of outputComponentsByStateKey.get(stateKey) ?? []) {
387
+ if (getUiGraphOutputRenderModel(nextState, stateKey, component.renderAs ?? "text").hasValue) {
388
+ collapsedOutputComponentIds.delete(component.id);
389
+ }
390
+ }
243
391
  }
244
392
  };
245
393
  updateSnapshot();
@@ -254,6 +402,9 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
254
402
  }
255
403
  },
256
404
  detachActions() {
405
+ for (const executionId of activeActions.keys()) {
406
+ clearActionLoadingPresentation(executionId);
407
+ }
257
408
  activeActions.clear();
258
409
  actionController.reset();
259
410
  actionProgress = {};
@@ -262,6 +413,14 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
262
413
  getSnapshot() {
263
414
  return snapshot;
264
415
  },
416
+ reset() {
417
+ abortAllActions(false);
418
+ state = { ...initialState };
419
+ actionErrors = {};
420
+ actionProgress = {};
421
+ collapsedOutputComponentIds.clear();
422
+ publish("state");
423
+ },
265
424
  async runAction(component, runner) {
266
425
  const execution = actionController.begin(component);
267
426
  if (!execution) {
@@ -269,6 +428,7 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
269
428
  }
270
429
  const abortController = new AbortController();
271
430
  activeActions.set(execution.id, { abortController, execution });
431
+ delayActionLoadingPresentation(execution);
272
432
  removeActionPresentation(component.id);
273
433
  publish("action");
274
434
  try {
@@ -290,7 +450,9 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
290
450
  }
291
451
  const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
292
452
  if (statePatch) {
293
- state = applyUiGraphStatePatch(state, statePatch);
453
+ const nextState = applyUiGraphStatePatch(state, statePatch);
454
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
455
+ state = nextState;
294
456
  }
295
457
  } catch (error) {
296
458
  if (!abortController.signal.aborted && actionController.isCurrent(execution)) {
@@ -301,6 +463,7 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
301
463
  }
302
464
  } finally {
303
465
  if (activeActions.delete(execution.id)) {
466
+ clearActionLoadingPresentation(execution.id);
304
467
  actionController.finish(execution);
305
468
  if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
306
469
  actionProgress = { ...actionProgress };
@@ -314,16 +477,49 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
314
477
  if (nextUiGraph.id !== uiGraphId) {
315
478
  abortAllActions(false);
316
479
  uiGraphId = nextUiGraph.id;
317
- state = getUiGraphInitialState(nextUiGraph);
480
+ initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);
481
+ state = { ...initialState };
318
482
  actionErrors = {};
319
483
  actionProgress = {};
484
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
485
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
486
+ actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
487
+ collapsedOutputComponentIds.clear();
320
488
  publish("graph");
321
489
  return;
322
490
  }
323
- const actionComponentIds = new Set(
324
- nextUiGraph.components.filter((component) => component.type === "button" || component.type === "chat").map((component) => component.id)
491
+ if (!initialStateOverride) {
492
+ initialState = getUiGraphInitialState(nextUiGraph);
493
+ }
494
+ const normalizedState = normalizeUiGraphDropdownState(nextUiGraph, state);
495
+ const stateChanged = normalizedState !== state;
496
+ if (stateChanged) {
497
+ state = normalizedState;
498
+ }
499
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
500
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
501
+ const collapsedOutputIdsBeforeCleanup = collapsedOutputComponentIds.size;
502
+ for (const componentId of collapsedOutputComponentIds) {
503
+ if (!outputComponentIds.has(componentId)) {
504
+ collapsedOutputComponentIds.delete(componentId);
505
+ }
506
+ }
507
+ const nextActionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
508
+ const actionComponentIds = new Set(nextActionComponentsById.keys());
509
+ const changedActionComponentIds = new Set(
510
+ [...nextActionComponentsById].flatMap(([componentId, component]) => {
511
+ const previousComponent = actionComponentsById.get(componentId);
512
+ return previousComponent && !areUiGraphActionComponentsExecutionEquivalent(previousComponent, component) ? [componentId] : [];
513
+ })
325
514
  );
326
- let changed = abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId), false);
515
+ let changed = collapsedOutputComponentIds.size !== collapsedOutputIdsBeforeCleanup || stateChanged || abortMatchingActions(
516
+ ({ execution }) => !actionComponentIds.has(execution.componentId) || changedActionComponentIds.has(execution.componentId),
517
+ false
518
+ );
519
+ for (const componentId of changedActionComponentIds) {
520
+ changed = removeActionPresentation(componentId) || changed;
521
+ }
522
+ actionComponentsById = nextActionComponentsById;
327
523
  const remainingErrors = Object.fromEntries(
328
524
  Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId))
329
525
  );
@@ -346,20 +542,65 @@ function createUiGraphInteractionController(initialUiGraph, options = {}) {
346
542
  listeners.add(listener);
347
543
  return () => listeners.delete(listener);
348
544
  },
545
+ toggleOutputCollapsed(componentId) {
546
+ if (!outputComponentIds.has(componentId)) {
547
+ return;
548
+ }
549
+ if (collapsedOutputComponentIds.has(componentId)) {
550
+ collapsedOutputComponentIds.delete(componentId);
551
+ } else {
552
+ collapsedOutputComponentIds.add(componentId);
553
+ }
554
+ publish("presentation");
555
+ },
349
556
  updateState(stateKey, value) {
350
557
  actionController.noteStateWrite(stateKey);
351
- state = { ...state, [stateKey]: value };
558
+ const nextState = { ...state, [stateKey]: value };
559
+ expandOutputsForUpdatedState([stateKey], nextState);
560
+ state = nextState;
352
561
  publish("state");
353
562
  },
354
563
  updateStatePatch(statePatch) {
355
564
  for (const stateKey of Object.keys(statePatch)) {
356
565
  actionController.noteStateWrite(stateKey);
357
566
  }
358
- state = applyUiGraphStatePatch(state, statePatch);
567
+ const nextState = applyUiGraphStatePatch(state, statePatch);
568
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
569
+ state = nextState;
359
570
  publish("state");
360
571
  }
361
572
  };
362
573
  }
574
+ function getUiGraphOutputComponentIds(uiGraph) {
575
+ return new Set(
576
+ uiGraph.components.filter((component) => component.type === "output").map((component) => component.id)
577
+ );
578
+ }
579
+ function getUiGraphOutputComponentsByStateKey(uiGraph) {
580
+ const componentsByStateKey = /* @__PURE__ */ new Map();
581
+ for (const component of uiGraph.components) {
582
+ if (component.type !== "output") continue;
583
+ const components = componentsByStateKey.get(component.stateKey) ?? [];
584
+ components.push(component);
585
+ componentsByStateKey.set(component.stateKey, components);
586
+ }
587
+ return componentsByStateKey;
588
+ }
589
+ function normalizeUiGraphDropdownState(uiGraph, state) {
590
+ let normalizedState;
591
+ for (const component of uiGraph.components) {
592
+ if (component.type !== "dropdown") {
593
+ continue;
594
+ }
595
+ const selectedValue = `${state[component.stateKey] ?? ""}`;
596
+ if (selectedValue === "" || component.items.some((item) => item.value === selectedValue)) {
597
+ continue;
598
+ }
599
+ normalizedState ??= { ...state };
600
+ normalizedState[component.stateKey] = "";
601
+ }
602
+ return normalizedState ?? state;
603
+ }
363
604
  function getUiGraphComponentRenderModel(component, state) {
364
605
  switch (component.type) {
365
606
  case "text":
@@ -376,6 +617,16 @@ function getUiGraphComponentRenderModel(component, state) {
376
617
  type: component.type,
377
618
  value: `${state[component.stateKey] ?? component.defaultValue ?? ""}`
378
619
  };
620
+ case "dropdown": {
621
+ const selectedValue = `${state[component.stateKey] ?? ""}`;
622
+ return {
623
+ component,
624
+ items: component.items,
625
+ label: getUiGraphComponentLabel(component),
626
+ type: "dropdown",
627
+ value: component.items.some((item) => item.value === selectedValue) ? selectedValue : ""
628
+ };
629
+ }
379
630
  case "button":
380
631
  return { component, label: component.label, type: "button" };
381
632
  case "chat":
@@ -383,6 +634,7 @@ function getUiGraphComponentRenderModel(component, state) {
383
634
  component,
384
635
  draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ""}`,
385
636
  messages: getUiGraphChatMessages(component.id, state),
637
+ pins: getUiGraphChatPins(component.id, state),
386
638
  type: "chat"
387
639
  };
388
640
  case "output":
@@ -399,15 +651,17 @@ function getUiGraphComponentLabel(component) {
399
651
  }
400
652
  function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
401
653
  const value = state[stateKey];
402
- const hasValue = hasUiGraphStateValue(state, stateKey);
403
654
  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;
655
+ const hasStateValue = hasUiGraphStateValue(state, stateKey);
656
+ const hasImageValue = hasStateValue && value != null && value !== "";
657
+ const imageSource = hasImageValue && renderAs === "image" ? getUiGraphImageSource(value) : void 0;
658
+ const imageErrorMessage = hasImageValue && renderAs === "image" && !imageSource ? "Expected an image URL or base64 image." : void 0;
659
+ const hasValue = renderAs === "image" ? imageSource != null || imageErrorMessage != null : renderedValue.trim().length > 0;
406
660
  return {
407
661
  hasValue,
408
662
  ...imageErrorMessage ? { imageErrorMessage } : {},
409
663
  ...imageSource ? { imageSource } : {},
410
- ...hasValue && renderAs === "json" ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {},
664
+ ...hasValue && renderAs === "json" ? { jsonDownloadValue: renderedValue } : {},
411
665
  renderedValue,
412
666
  renderAs
413
667
  };
@@ -421,6 +675,30 @@ function renderUiGraphOutputValue(value, renderAs) {
421
675
  }
422
676
  return typeof value === "string" ? value : value == null ? "" : stringifyUiGraphValue(value) ?? "";
423
677
  }
678
+ function getUiGraphProgressiveJsonOutputChunks(value) {
679
+ if (value.length < UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD) {
680
+ return void 0;
681
+ }
682
+ const chunks = [];
683
+ let offset = 0;
684
+ let chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS;
685
+ while (offset < value.length) {
686
+ let nextOffset = Math.min(value.length, offset + chunkLength);
687
+ if (nextOffset < value.length && isHighSurrogate(value.charCodeAt(nextOffset - 1)) && isLowSurrogate(value.charCodeAt(nextOffset))) {
688
+ nextOffset += 1;
689
+ }
690
+ chunks.push(value.slice(offset, nextOffset));
691
+ offset = nextOffset;
692
+ chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS;
693
+ }
694
+ return chunks;
695
+ }
696
+ function isHighSurrogate(value) {
697
+ return value >= 55296 && value <= 56319;
698
+ }
699
+ function isLowSurrogate(value) {
700
+ return value >= 56320 && value <= 57343;
701
+ }
424
702
  function getUiGraphImageSource(value) {
425
703
  if (typeof value !== "string") {
426
704
  return void 0;
@@ -492,11 +770,12 @@ function parseRivetWebAppClientMessage(value) {
492
770
  case "client.hello":
493
771
  return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? { type: value.type, protocolVersion: value.protocolVersion } : void 0;
494
772
  case "action.start":
495
- return isNonEmptyString(value.requestId) && isNonEmptyString(value.componentId) && isRecord(value.state) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
773
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.componentId) && isRecord(value.state) && (value.storage == null || isRecord(value.storage)) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
496
774
  type: value.type,
497
775
  requestId: value.requestId,
498
776
  componentId: value.componentId,
499
777
  state: value.state,
778
+ ...isRecord(value.storage) ? { storage: value.storage } : {},
500
779
  ...typeof value.revisionKey === "string" ? { revisionKey: value.revisionKey } : {}
501
780
  } : void 0;
502
781
  case "action.cancel":
@@ -548,7 +827,12 @@ function parseRivetWebAppServerMessage(value) {
548
827
  return progress ? { type: value.type, ...base, progress } : void 0;
549
828
  }
550
829
  case "action.completed":
551
- return isRecord(value.statePatch) ? { type: value.type, ...base, statePatch: value.statePatch } : void 0;
830
+ return isRecord(value.statePatch) && (value.storagePatch == null || isRecord(value.storagePatch)) ? {
831
+ type: value.type,
832
+ ...base,
833
+ statePatch: value.statePatch,
834
+ ...isRecord(value.storagePatch) ? { storagePatch: value.storagePatch } : {}
835
+ } : void 0;
552
836
  case "action.failed":
553
837
  return isNonEmptyString(value.error) ? {
554
838
  type: value.type,
@@ -573,6 +857,223 @@ function isNonEmptyString(value) {
573
857
  }
574
858
 
575
859
  // src/model/UiGraphBrowserRuntime.ts
860
+ var OUTPUT_MAX_HEIGHT_PX = 800;
861
+ var OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
862
+ var OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-min-height";
863
+ var OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-max-height";
864
+ var CHAT_SEARCH_MATCH_CLASS = "rivet-web-app-chat-search-match";
865
+ var CHAT_SEARCH_ACTIVE_MATCH_CLASS = "rivet-web-app-chat-search-match-active";
866
+ var UI_GRAPH_CHAT_STORAGE_PREFIX = "rivet-web-app-chat-state:v1";
867
+ var UI_GRAPH_APP_STORAGE_PREFIX = "rivet-web-app-storage:v1";
868
+ var escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
869
+ var getPixelValue = (value, fallback) => {
870
+ const parsed = Number.parseFloat(value);
871
+ return Number.isFinite(parsed) ? parsed : fallback;
872
+ };
873
+ var setStyleProperty = (element, property, value) => {
874
+ if (element.style.getPropertyValue(property) !== value) {
875
+ element.style.setProperty(property, value);
876
+ }
877
+ };
878
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
879
+ var getDefaultUiGraphBrowserStorage = () => {
880
+ var _a;
881
+ try {
882
+ return globalThis.localStorage ?? ((_a = globalThis.window) == null ? void 0 : _a.localStorage);
883
+ } catch {
884
+ return void 0;
885
+ }
886
+ };
887
+ var getDefaultUiGraphStorageLocation = () => {
888
+ var _a;
889
+ try {
890
+ return globalThis.location ?? ((_a = globalThis.window) == null ? void 0 : _a.location);
891
+ } catch {
892
+ return void 0;
893
+ }
894
+ };
895
+ function getUiGraphChatStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
896
+ if (!(location == null ? void 0 : location.origin)) {
897
+ return void 0;
898
+ }
899
+ const pathname = location.pathname.replace(/\/+$/, "") || "/";
900
+ return [
901
+ UI_GRAPH_CHAT_STORAGE_PREFIX,
902
+ encodeURIComponent(location.origin),
903
+ encodeURIComponent(pathname),
904
+ encodeURIComponent(uiGraph.id)
905
+ ].join(":");
906
+ }
907
+ function getUiGraphWebAppStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
908
+ if (!(location == null ? void 0 : location.origin)) {
909
+ return void 0;
910
+ }
911
+ const pathname = location.pathname.replace(/\/+$/, "") || "/";
912
+ return [
913
+ UI_GRAPH_APP_STORAGE_PREFIX,
914
+ encodeURIComponent(location.origin),
915
+ encodeURIComponent(pathname),
916
+ encodeURIComponent(uiGraph.id)
917
+ ].join(":");
918
+ }
919
+ function loadUiGraphWebAppStorage(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
920
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
921
+ if (!key || !storage) return {};
922
+ try {
923
+ const serialized = storage.getItem(key);
924
+ if (!serialized) return {};
925
+ const value = JSON.parse(serialized);
926
+ return isRecord2(value) ? value : {};
927
+ } catch {
928
+ return {};
929
+ }
930
+ }
931
+ function applyUiGraphWebAppStoragePatch(uiGraph, currentStorage, patch, storage = getDefaultUiGraphBrowserStorage(), location) {
932
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
933
+ if (!key || !storage) {
934
+ throw new Error("Browser storage is unavailable for this web app.");
935
+ }
936
+ const nextStorage = { ...currentStorage, ...patch };
937
+ let serialized;
938
+ try {
939
+ serialized = JSON.stringify(nextStorage);
940
+ storage.setItem(key, serialized);
941
+ } catch (error) {
942
+ throw new Error("Web app storage could not be saved. Browser storage may be unavailable or full.", {
943
+ cause: error
944
+ });
945
+ }
946
+ return nextStorage;
947
+ }
948
+ function applyUiGraphWebAppStorageActionPatch(patch, actionNumber, appliedActionByKey, persist) {
949
+ const applicablePatch = Object.fromEntries(
950
+ Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0))
951
+ );
952
+ const applicableKeys = Object.keys(applicablePatch);
953
+ if (applicableKeys.length === 0) return applicablePatch;
954
+ persist(applicablePatch);
955
+ for (const key of applicableKeys) appliedActionByKey.set(key, actionNumber);
956
+ return applicablePatch;
957
+ }
958
+ function getUiGraphChatPersistentState(uiGraph, state) {
959
+ const persistentState = {};
960
+ for (const component of uiGraph.components) {
961
+ if (component.type !== "chat") continue;
962
+ const draftStateKey = getUiGraphChatDraftStateKey(component.id);
963
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
964
+ const pinsStateKey = getUiGraphChatPinsStateKey(component.id);
965
+ const draft = state[draftStateKey];
966
+ const messages = getUiGraphChatMessages(component.id, state);
967
+ const pins = getUiGraphChatPins(component.id, state).map((pin) => pin.messageIndex);
968
+ if (typeof draft === "string" && draft) {
969
+ persistentState[draftStateKey] = draft;
970
+ }
971
+ if (messages.length > 0) {
972
+ persistentState[messagesStateKey] = messages;
973
+ }
974
+ if (pins.length > 0) {
975
+ persistentState[pinsStateKey] = pins;
976
+ }
977
+ }
978
+ return persistentState;
979
+ }
980
+ function hasUiGraphChatPersistentStateChanged(uiGraph, previousState, nextState) {
981
+ return uiGraph.components.some((component) => {
982
+ if (component.type !== "chat") return false;
983
+ 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)];
984
+ });
985
+ }
986
+ function loadUiGraphChatPersistentState(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
987
+ const key = getUiGraphChatStorageKey(uiGraph, location);
988
+ if (!key || !storage) {
989
+ return {};
990
+ }
991
+ try {
992
+ const serializedState = storage.getItem(key);
993
+ if (!serializedState) {
994
+ return {};
995
+ }
996
+ const storedState = JSON.parse(serializedState);
997
+ return isRecord2(storedState) ? getUiGraphChatPersistentState(uiGraph, storedState) : {};
998
+ } catch {
999
+ return {};
1000
+ }
1001
+ }
1002
+ function saveUiGraphChatPersistentState(uiGraph, state, storage = getDefaultUiGraphBrowserStorage(), location) {
1003
+ const key = getUiGraphChatStorageKey(uiGraph, location);
1004
+ if (!key || !storage) {
1005
+ return;
1006
+ }
1007
+ try {
1008
+ const persistentState = getUiGraphChatPersistentState(uiGraph, state);
1009
+ if (Object.keys(persistentState).length === 0) {
1010
+ storage.removeItem(key);
1011
+ return;
1012
+ }
1013
+ const serializedState = JSON.stringify(persistentState);
1014
+ if (storage.getItem(key) !== serializedState) {
1015
+ storage.setItem(key, serializedState);
1016
+ }
1017
+ } catch {
1018
+ }
1019
+ }
1020
+ function observeUiGraphOutputResizeBounds(output) {
1021
+ const ownerWindow = output.ownerDocument.defaultView;
1022
+ let scheduledFrame;
1023
+ const sync = () => {
1024
+ scheduledFrame = void 0;
1025
+ if (!ownerWindow) return;
1026
+ const header = output.querySelector(".rivet-web-app-output-header");
1027
+ const content = output.querySelector(".rivet-web-app-output-content");
1028
+ const body = output.querySelector(".rivet-web-app-output-content-body");
1029
+ if (!header || !content || !body) {
1030
+ output.classList.remove("rivet-web-app-output-resizable");
1031
+ output.classList.remove("rivet-web-app-output-scrollable");
1032
+ output.style.removeProperty(OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY);
1033
+ output.style.removeProperty(OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY);
1034
+ return;
1035
+ }
1036
+ const bodyStyle = ownerWindow.getComputedStyle(body);
1037
+ const lineHeight = getPixelValue(bodyStyle.lineHeight, getPixelValue(bodyStyle.fontSize, 16) * 1.5);
1038
+ const contentStyle = ownerWindow.getComputedStyle(content);
1039
+ const contentPadding = getPixelValue(contentStyle.paddingTop, 0) + getPixelValue(contentStyle.paddingBottom, 0);
1040
+ const verticalBorder = Math.max(0, output.offsetHeight - output.clientHeight);
1041
+ const minimumHeight = Math.ceil(
1042
+ header.getBoundingClientRect().height + contentPadding + lineHeight + verticalBorder
1043
+ );
1044
+ const naturalHeight = Math.ceil(
1045
+ header.getBoundingClientRect().height + contentPadding + Math.max(body.scrollHeight, lineHeight) + verticalBorder
1046
+ );
1047
+ const viewportHeight = (ownerWindow == null ? void 0 : ownerWindow.innerHeight) ?? OUTPUT_MAX_HEIGHT_PX / OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO;
1048
+ const maximumViewportHeight = Math.min(viewportHeight * OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO, OUTPUT_MAX_HEIGHT_PX);
1049
+ output.classList.toggle("rivet-web-app-output-resizable", naturalHeight > maximumViewportHeight);
1050
+ output.classList.toggle("rivet-web-app-output-scrollable", body.scrollHeight > body.clientHeight);
1051
+ setStyleProperty(output, OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY, `${minimumHeight}px`);
1052
+ setStyleProperty(output, OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY, `${naturalHeight}px`);
1053
+ };
1054
+ const scheduleSync = () => {
1055
+ if (scheduledFrame != null) return;
1056
+ if (ownerWindow == null ? void 0 : ownerWindow.requestAnimationFrame) {
1057
+ scheduledFrame = ownerWindow.requestAnimationFrame(sync);
1058
+ } else {
1059
+ sync();
1060
+ }
1061
+ };
1062
+ const resizeObserver = (ownerWindow == null ? void 0 : ownerWindow.ResizeObserver) ? new ownerWindow.ResizeObserver(scheduleSync) : void 0;
1063
+ resizeObserver == null ? void 0 : resizeObserver.observe(output);
1064
+ const mutationObserver = (ownerWindow == null ? void 0 : ownerWindow.MutationObserver) ? new ownerWindow.MutationObserver(scheduleSync) : void 0;
1065
+ mutationObserver == null ? void 0 : mutationObserver.observe(output, { childList: true, characterData: true, subtree: true });
1066
+ output.addEventListener("load", scheduleSync, true);
1067
+ ownerWindow == null ? void 0 : ownerWindow.addEventListener("resize", scheduleSync);
1068
+ sync();
1069
+ return () => {
1070
+ if (scheduledFrame != null) ownerWindow == null ? void 0 : ownerWindow.cancelAnimationFrame(scheduledFrame);
1071
+ resizeObserver == null ? void 0 : resizeObserver.disconnect();
1072
+ mutationObserver == null ? void 0 : mutationObserver.disconnect();
1073
+ output.removeEventListener("load", scheduleSync, true);
1074
+ ownerWindow == null ? void 0 : ownerWindow.removeEventListener("resize", scheduleSync);
1075
+ };
1076
+ }
576
1077
  async function copyUiGraphText(value) {
577
1078
  var _a;
578
1079
  try {
@@ -606,20 +1107,108 @@ function downloadUiGraphJsonOutput(value, appName) {
606
1107
  globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);
607
1108
  }
608
1109
  }
1110
+ function highlightUiGraphChatSearchMatches(messagesElement, query, requestedActiveIndex = 0) {
1111
+ var _a, _b;
1112
+ clearUiGraphChatSearchMatches(messagesElement);
1113
+ const searchText = query.trim();
1114
+ if (!searchText) {
1115
+ return { activeIndex: -1, matches: [] };
1116
+ }
1117
+ const document2 = messagesElement.ownerDocument;
1118
+ const textNodes = [];
1119
+ const walker = document2.createTreeWalker(messagesElement, 4);
1120
+ let node = walker.nextNode();
1121
+ while (node) {
1122
+ if ((_a = node.parentElement) == null ? void 0 : _a.closest("script, style, textarea")) {
1123
+ node = walker.nextNode();
1124
+ continue;
1125
+ }
1126
+ textNodes.push(node);
1127
+ node = walker.nextNode();
1128
+ }
1129
+ const matches = [];
1130
+ for (const textNode of textNodes) {
1131
+ const value = textNode.data;
1132
+ const ranges = [];
1133
+ const expression = new RegExp(escapeRegularExpression(searchText), "gi");
1134
+ for (const match of value.matchAll(expression)) {
1135
+ if (match.index != null && match[0]) {
1136
+ ranges.push({ start: match.index, end: match.index + match[0].length });
1137
+ }
1138
+ }
1139
+ if (ranges.length === 0 || !textNode.parentNode) {
1140
+ continue;
1141
+ }
1142
+ const fragment = document2.createDocumentFragment();
1143
+ let cursor = 0;
1144
+ for (const range of ranges) {
1145
+ fragment.append(value.slice(cursor, range.start));
1146
+ const match = document2.createElement("mark");
1147
+ match.className = CHAT_SEARCH_MATCH_CLASS;
1148
+ match.textContent = value.slice(range.start, range.end);
1149
+ fragment.append(match);
1150
+ matches.push(match);
1151
+ cursor = range.end;
1152
+ }
1153
+ fragment.append(value.slice(cursor));
1154
+ textNode.parentNode.replaceChild(fragment, textNode);
1155
+ }
1156
+ if (matches.length === 0) {
1157
+ return { activeIndex: -1, matches };
1158
+ }
1159
+ const activeIndex = (requestedActiveIndex % matches.length + matches.length) % matches.length;
1160
+ (_b = matches[activeIndex]) == null ? void 0 : _b.classList.add(CHAT_SEARCH_ACTIVE_MATCH_CLASS);
1161
+ return { activeIndex, matches };
1162
+ }
1163
+ function clearUiGraphChatSearchMatches(messagesElement) {
1164
+ for (const match of messagesElement.querySelectorAll(`.${CHAT_SEARCH_MATCH_CLASS}`)) {
1165
+ match.replaceWith(messagesElement.ownerDocument.createTextNode(match.textContent ?? ""));
1166
+ }
1167
+ messagesElement.normalize();
1168
+ }
1169
+ function revealUiGraphChatElement(messagesElement, element, alignment = "center") {
1170
+ if (!element || !messagesElement.contains(element)) {
1171
+ return;
1172
+ }
1173
+ const containerRect = messagesElement.getBoundingClientRect();
1174
+ const elementRect = element.getBoundingClientRect();
1175
+ const maxScrollTop = Math.max(0, messagesElement.scrollHeight - messagesElement.clientHeight);
1176
+ const offset = elementRect.top - containerRect.top - (alignment === "center" ? (messagesElement.clientHeight - elementRect.height) / 2 : 0);
1177
+ messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));
1178
+ }
1179
+ var revealUiGraphChatSearchMatch = revealUiGraphChatElement;
609
1180
  // Annotate the CommonJS export names for ESM import in node:
610
1181
  0 && (module.exports = {
611
1182
  RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
612
1183
  applyUiGraphStatePatch,
1184
+ applyUiGraphWebAppStorageActionPatch,
1185
+ applyUiGraphWebAppStoragePatch,
1186
+ clearUiGraphChatSearchMatches,
613
1187
  copyUiGraphText,
614
1188
  createUiGraphActionExecutionController,
1189
+ createUiGraphChatHistoryFlushStatePatch,
1190
+ createUiGraphChatPinStatePatch,
615
1191
  createUiGraphChatSubmissionStatePatch,
616
1192
  createUiGraphInteractionController,
617
1193
  downloadUiGraphJsonOutput,
618
1194
  getUiGraphActionState,
619
1195
  getUiGraphChatDraftStateKey,
1196
+ getUiGraphChatMessagesStateKey,
1197
+ getUiGraphChatPersistentState,
1198
+ getUiGraphChatStorageKey,
620
1199
  getUiGraphComponentRenderModel,
621
1200
  getUiGraphJsonOutputFilename,
1201
+ getUiGraphProgressiveJsonOutputChunks,
1202
+ getUiGraphWebAppStorageKey,
1203
+ hasUiGraphChatPersistentStateChanged,
1204
+ highlightUiGraphChatSearchMatches,
1205
+ loadUiGraphChatPersistentState,
1206
+ loadUiGraphWebAppStorage,
1207
+ observeUiGraphOutputResizeBounds,
622
1208
  parseRivetWebAppClientMessage,
623
- parseRivetWebAppServerMessage
1209
+ parseRivetWebAppServerMessage,
1210
+ revealUiGraphChatElement,
1211
+ revealUiGraphChatSearchMatch,
1212
+ saveUiGraphChatPersistentState
624
1213
  });
625
1214
  //# sourceMappingURL=webAppRuntime.cjs.map