@valerypopoff/rivet2-core 2.3.0 → 2.5.0
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.
- package/dist/cjs/bundle.cjs +1947 -765
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +1578 -0
- package/dist/cjs/interpolationRuntime.cjs.map +7 -0
- package/dist/cjs/interpolationSyntax.cjs +186 -0
- package/dist/cjs/interpolationSyntax.cjs.map +7 -0
- package/dist/cjs/webAppRuntime.cjs +1537 -121
- package/dist/cjs/webAppRuntime.cjs.map +4 -4
- package/dist/esm/api/createProcessor.js +2 -0
- package/dist/esm/exports.js +4 -1
- package/dist/esm/integrations/CodeRunner.js +5 -0
- package/dist/esm/integrations/mcp/MCPBase.js +16 -6
- package/dist/esm/interpolationRuntime.js +5 -0
- package/dist/esm/model/AgentResponseTrace.js +16 -0
- package/dist/esm/model/GraphBoundaryCache.js +0 -6
- package/dist/esm/model/GraphBoundaryEffects.js +5 -1
- package/dist/esm/model/GraphOutputSelection.js +34 -0
- package/dist/esm/model/GraphProcessor.js +150 -44
- package/dist/esm/model/NodeExclusionPolicy.js +9 -1
- package/dist/esm/model/ProcessContextBuilder.js +4 -1
- package/dist/esm/model/RecordingPlayer.js +19 -6
- package/dist/esm/model/StoredValueStore.js +4 -3
- package/dist/esm/model/SubprocessorBridge.js +1 -0
- package/dist/esm/model/UiGraphActionProtocol.js +46 -4
- package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
- package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
- package/dist/esm/model/UiGraphRendererStyles.js +14 -0
- package/dist/esm/model/WebAppBrowserStorage.js +653 -0
- package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +1 -0
- package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -33
- package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +1 -0
- package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
- package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
- package/dist/esm/model/chat-v2/llmProfile.js +17 -1
- package/dist/esm/model/chat-v2/llmProfileFallback.js +17 -5
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +2 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +4 -0
- package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
- package/dist/esm/model/nodes/CodeNewNode.js +16 -16
- package/dist/esm/model/nodes/DestructureNode.js +2 -2
- package/dist/esm/model/nodes/ExpressionNode.js +16 -16
- package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
- package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
- package/dist/esm/model/nodes/JSFilterNode.js +3 -1
- package/dist/esm/model/nodes/JSMapNode.js +3 -1
- package/dist/esm/model/nodes/LLMChatV2Node.js +21 -2
- package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
- package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
- package/dist/esm/model/nodes/ObjectNode.js +19 -20
- package/dist/esm/model/nodes/PromptNode.js +10 -11
- package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
- package/dist/esm/model/nodes/SubGraphNode.js +40 -26
- package/dist/esm/model/nodes/TextNode.js +11 -32
- package/dist/esm/model/nodes/ToTreeNode.js +6 -13
- package/dist/esm/model/nodes/ToolNode.js +33 -16
- package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
- package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
- package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
- package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
- package/dist/esm/recording/ExecutionRecorder.js +1 -0
- package/dist/esm/utils/index.js +2 -0
- package/dist/esm/utils/interpolation.js +478 -221
- package/dist/esm/utils/interpolationSyntax.js +175 -0
- package/dist/esm/utils/jsonPath.js +129 -0
- package/dist/esm/webAppRuntime.js +5 -2
- package/dist/types/api/createProcessor.d.ts +2 -0
- package/dist/types/exports.d.ts +5 -1
- package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
- package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
- package/dist/types/interpolationRuntime.d.ts +5 -0
- package/dist/types/model/AgentResponseTrace.d.ts +1 -0
- package/dist/types/model/ExecutorProtocol.d.ts +9 -1
- package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
- package/dist/types/model/GraphOutputSelection.d.ts +8 -0
- package/dist/types/model/GraphProcessor.d.ts +7 -4
- package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
- package/dist/types/model/ProcessContext.d.ts +36 -2
- package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
- package/dist/types/model/UiGraphActionProtocol.d.ts +8 -3
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
- package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
- package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
- package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
- package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
- package/dist/types/model/chat-v2/chatV2Types.d.ts +3 -1
- package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
- package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +4 -0
- package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +10 -0
- package/dist/types/model/chat-v2/llmProfileTypes.d.ts +6 -0
- package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
- package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
- package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
- package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
- package/dist/types/model/nodes/ToolNode.d.ts +13 -1
- package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
- package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
- package/dist/types/recording/RecordedEvents.d.ts +11 -0
- package/dist/types/utils/index.d.ts +2 -0
- package/dist/types/utils/interpolation.d.ts +93 -8
- package/dist/types/utils/interpolationSyntax.d.ts +21 -0
- package/dist/types/utils/jsonPath.d.ts +15 -0
- package/dist/types/webAppRuntime.d.ts +8 -2
- package/package.json +11 -1
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import { isAgentResponseTrace } from './AgentResponseTrace.js';
|
|
2
|
+
import { getUiGraphChatPersistentState, getUiGraphChatStorageKey, getUiGraphResponseTraceStorageKey, getUiGraphWebAppStorageKey, loadUiGraphChatPersistentState, loadUiGraphWebAppStorage, saveUiGraphChatPersistentState, } from './UiGraphBrowserRuntime.js';
|
|
3
|
+
import { getUiGraphChatMessages } from './UiGraph.js';
|
|
4
|
+
import { IndexedDbWebAppBrowserStorage, RIVET_WEB_APP_LEGACY_RETENTION_MS, WebAppBrowserStoragePersistenceError, } from './WebAppBrowserStorage.js';
|
|
5
|
+
import { cloneRivetStoredValue, cloneRivetStoredValueRecord, } from './StoredValueStore.js';
|
|
6
|
+
const CHAT_STATE_RECORD_KEY = 'state';
|
|
7
|
+
const RESPONSE_TRACE_LIMIT = 100;
|
|
8
|
+
/**
|
|
9
|
+
* UI-graph-specific adapter over the generic IndexedDB store. It owns exact
|
|
10
|
+
* legacy-key migration and keeps localStorage out of the new runtime path.
|
|
11
|
+
*/
|
|
12
|
+
export class UiGraphBrowserPersistence {
|
|
13
|
+
#store;
|
|
14
|
+
#uiGraph;
|
|
15
|
+
#legacyStorage;
|
|
16
|
+
#location;
|
|
17
|
+
#now;
|
|
18
|
+
#onDiagnostic;
|
|
19
|
+
#listeners = new Set();
|
|
20
|
+
#warningListeners = new Set();
|
|
21
|
+
#status = { durable: false, reason: 'indexeddb-unavailable' };
|
|
22
|
+
#warning;
|
|
23
|
+
#disposeStoreSubscription;
|
|
24
|
+
#responseTraceMutationQueue = Promise.resolve();
|
|
25
|
+
#useLegacyStorage = true;
|
|
26
|
+
constructor(uiGraph, options = {}) {
|
|
27
|
+
this.#uiGraph = uiGraph;
|
|
28
|
+
this.#legacyStorage = options.legacyStorage ?? getDefaultLegacyStorage();
|
|
29
|
+
this.#now = options.now ?? Date.now;
|
|
30
|
+
this.#onDiagnostic = options.onDiagnostic ?? defaultBrowserStorageDiagnostic;
|
|
31
|
+
this.#location = options.location ?? getDefaultLocation();
|
|
32
|
+
this.#store = new IndexedDbWebAppBrowserStorage(options);
|
|
33
|
+
}
|
|
34
|
+
async initialize() {
|
|
35
|
+
const location = this.#location;
|
|
36
|
+
if (!location?.origin) {
|
|
37
|
+
this.#reportDiagnostic({ operation: 'open', outcome: 'fallback' });
|
|
38
|
+
this.#setWarning({
|
|
39
|
+
code: 'indexeddb-unavailable',
|
|
40
|
+
message: 'Saved browser data is unavailable. Changes will last only until this page is closed.',
|
|
41
|
+
});
|
|
42
|
+
return this.#status;
|
|
43
|
+
}
|
|
44
|
+
this.#status = await this.#store.initialize({
|
|
45
|
+
origin: location.origin,
|
|
46
|
+
pathname: location.pathname,
|
|
47
|
+
uiGraphId: String(this.#uiGraph.id),
|
|
48
|
+
});
|
|
49
|
+
this.#reportDiagnostic({ operation: 'open', outcome: this.#status.durable ? 'success' : 'fallback' });
|
|
50
|
+
this.#disposeStoreSubscription = this.#store.subscribe((change) => {
|
|
51
|
+
for (const listener of this.#listeners)
|
|
52
|
+
listener(change);
|
|
53
|
+
});
|
|
54
|
+
if (!this.#status.durable) {
|
|
55
|
+
this.#setWarning({
|
|
56
|
+
code: 'indexeddb-unavailable',
|
|
57
|
+
message: 'Saved browser data is unavailable. Changes will use limited legacy storage for this page.',
|
|
58
|
+
});
|
|
59
|
+
return this.#status;
|
|
60
|
+
}
|
|
61
|
+
// Once IndexedDB is available, new writes must use it even if importing a
|
|
62
|
+
// frozen legacy value fails. Reads below can still recover an exact legacy
|
|
63
|
+
// record until its migration ledger entry is committed.
|
|
64
|
+
this.#useLegacyStorage = false;
|
|
65
|
+
const migratedLegacyRecords = await this.#tryMigrateLegacyRecords();
|
|
66
|
+
if (migratedLegacyRecords) {
|
|
67
|
+
try {
|
|
68
|
+
await this.#cleanupExpiredLegacyRecords();
|
|
69
|
+
this.#reportDiagnostic({ operation: 'cleanup', outcome: 'success' });
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
this.#reportDiagnostic({ operation: 'cleanup', outcome: 'failure' });
|
|
73
|
+
}
|
|
74
|
+
this.#setWarning(undefined);
|
|
75
|
+
}
|
|
76
|
+
return this.#status;
|
|
77
|
+
}
|
|
78
|
+
get status() {
|
|
79
|
+
return this.#status;
|
|
80
|
+
}
|
|
81
|
+
get warning() {
|
|
82
|
+
return this.#warning;
|
|
83
|
+
}
|
|
84
|
+
subscribe(listener) {
|
|
85
|
+
this.#listeners.add(listener);
|
|
86
|
+
return () => this.#listeners.delete(listener);
|
|
87
|
+
}
|
|
88
|
+
subscribeWarning(listener) {
|
|
89
|
+
this.#warningListeners.add(listener);
|
|
90
|
+
return () => this.#warningListeners.delete(listener);
|
|
91
|
+
}
|
|
92
|
+
async loadChatState() {
|
|
93
|
+
if (this.#useLegacyStorage) {
|
|
94
|
+
return loadUiGraphChatPersistentState(this.#uiGraph, this.#legacyStorage, this.#location);
|
|
95
|
+
}
|
|
96
|
+
const value = await this.#store.get('chat-state', CHAT_STATE_RECORD_KEY);
|
|
97
|
+
if (isRecord(value))
|
|
98
|
+
return getUiGraphChatPersistentState(this.#uiGraph, value);
|
|
99
|
+
return await this.#loadLegacyChatStateIfUnmigrated();
|
|
100
|
+
}
|
|
101
|
+
async saveChatState(state) {
|
|
102
|
+
if (this.#useLegacyStorage) {
|
|
103
|
+
saveUiGraphChatPersistentState(this.#uiGraph, state, this.#legacyStorage, this.#location);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
await this.#tryMigrateLegacyRecords();
|
|
107
|
+
const persistentState = getUiGraphChatPersistentState(this.#uiGraph, state);
|
|
108
|
+
await this.#persist(() => Object.keys(persistentState).length === 0
|
|
109
|
+
? this.#store.delete('chat-state', CHAT_STATE_RECORD_KEY)
|
|
110
|
+
: this.#store.set('chat-state', CHAT_STATE_RECORD_KEY, cloneRivetStoredValue(persistentState)));
|
|
111
|
+
}
|
|
112
|
+
async loadStoredValues() {
|
|
113
|
+
if (this.#useLegacyStorage) {
|
|
114
|
+
return cloneRivetStoredValueRecord(loadUiGraphWebAppStorage(this.#uiGraph, this.#legacyStorage, this.#location), 'Stored Value browser snapshot');
|
|
115
|
+
}
|
|
116
|
+
const indexedDbValues = Object.fromEntries((await this.#store.list('stored-values')).map(({ key, value }) => [key, value]));
|
|
117
|
+
const legacyValues = await this.#loadLegacyStoredValuesIfUnmigrated();
|
|
118
|
+
return cloneRivetStoredValueRecord({ ...legacyValues, ...indexedDbValues }, 'Stored Value browser snapshot');
|
|
119
|
+
}
|
|
120
|
+
async loadStoredValue(key) {
|
|
121
|
+
if (this.#useLegacyStorage) {
|
|
122
|
+
const values = await this.loadStoredValues();
|
|
123
|
+
return Object.prototype.hasOwnProperty.call(values, key)
|
|
124
|
+
? cloneRivetStoredValue(values[key], 'Stored Value browser value')
|
|
125
|
+
: undefined;
|
|
126
|
+
}
|
|
127
|
+
const value = await this.#store.get('stored-values', key);
|
|
128
|
+
if (value !== undefined)
|
|
129
|
+
return cloneRivetStoredValue(value, 'Stored Value browser value');
|
|
130
|
+
const legacyValues = await this.#loadLegacyStoredValuesIfUnmigrated();
|
|
131
|
+
return Object.prototype.hasOwnProperty.call(legacyValues, key)
|
|
132
|
+
? cloneRivetStoredValue(legacyValues[key], 'Stored Value browser value')
|
|
133
|
+
: undefined;
|
|
134
|
+
}
|
|
135
|
+
async applyStoredValuePatch(patch, options = {}) {
|
|
136
|
+
const portablePatch = cloneRivetStoredValueRecord(patch, 'Stored Value browser patch');
|
|
137
|
+
if (this.#useLegacyStorage) {
|
|
138
|
+
const legacyKey = getUiGraphWebAppStorageKey(this.#uiGraph, this.#location);
|
|
139
|
+
if (!legacyKey || !this.#legacyStorage)
|
|
140
|
+
throw new Error('Browser storage is unavailable for this web app.');
|
|
141
|
+
const current = await this.loadStoredValues();
|
|
142
|
+
const next = cloneRivetStoredValueRecord({ ...current, ...portablePatch }, 'Stored Value browser snapshot');
|
|
143
|
+
this.#legacyStorage.setItem(legacyKey, JSON.stringify(next));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
await this.#tryMigrateLegacyRecords();
|
|
147
|
+
await this.#persist(() => this.#store.commitBatch(Object.entries(portablePatch).map(([key, value]) => ({ key, namespace: 'stored-values', value }))), options.requireDurable === true);
|
|
148
|
+
}
|
|
149
|
+
async loadResponseTrace(componentId, traceId) {
|
|
150
|
+
const traces = await this.#loadResponseTraces(componentId);
|
|
151
|
+
return traces.find((trace) => trace.traceId === traceId);
|
|
152
|
+
}
|
|
153
|
+
async saveResponseTrace(componentId, trace) {
|
|
154
|
+
if (!isAgentResponseTrace(trace) || !this.#isResponseInspectionEnabled(componentId))
|
|
155
|
+
return;
|
|
156
|
+
await this.#enqueueResponseTraceMutation(async () => {
|
|
157
|
+
const traces = (await this.#loadResponseTraces(componentId)).filter((candidate) => candidate.traceId !== trace.traceId);
|
|
158
|
+
traces.push(trace);
|
|
159
|
+
await this.#saveResponseTraces(componentId, traces.slice(-RESPONSE_TRACE_LIMIT));
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
async pruneResponseTraces(state) {
|
|
163
|
+
await this.#enqueueResponseTraceMutation(async () => {
|
|
164
|
+
for (const component of this.#uiGraph.components) {
|
|
165
|
+
if (component.type !== 'chat')
|
|
166
|
+
continue;
|
|
167
|
+
const referenced = component.allowResponseInspection === true
|
|
168
|
+
? new Set(getUiGraphChatMessages(component.id, state).flatMap((message) => typeof message.responseTraceId === 'string' ? [message.responseTraceId] : []))
|
|
169
|
+
: new Set();
|
|
170
|
+
const retained = (await this.#loadResponseTraces(String(component.id))).filter((trace) => referenced.has(trace.traceId));
|
|
171
|
+
await this.#saveResponseTraces(String(component.id), retained);
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
reportTransportIncompatibility(message) {
|
|
176
|
+
this.#reportDiagnostic({ operation: 'transport', outcome: 'failure' });
|
|
177
|
+
if (this.#warning && this.#warning.code !== 'transport-incompatible')
|
|
178
|
+
return;
|
|
179
|
+
this.#setWarning({ code: 'transport-incompatible', message });
|
|
180
|
+
}
|
|
181
|
+
clearTransportIncompatibility() {
|
|
182
|
+
if (this.#warning?.code === 'transport-incompatible') {
|
|
183
|
+
this.#setWarning(undefined);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
async estimateUsage() {
|
|
187
|
+
return await this.#store.estimateUsage();
|
|
188
|
+
}
|
|
189
|
+
dispose() {
|
|
190
|
+
this.#disposeStoreSubscription?.();
|
|
191
|
+
this.#disposeStoreSubscription = undefined;
|
|
192
|
+
this.#listeners.clear();
|
|
193
|
+
this.#warningListeners.clear();
|
|
194
|
+
this.#store.dispose();
|
|
195
|
+
}
|
|
196
|
+
async #loadResponseTraces(componentId) {
|
|
197
|
+
if (!this.#isResponseInspectionEnabled(componentId))
|
|
198
|
+
return [];
|
|
199
|
+
if (this.#useLegacyStorage)
|
|
200
|
+
return this.#loadLegacyResponseTraces(componentId);
|
|
201
|
+
const value = await this.#store.get('response-traces', componentId);
|
|
202
|
+
return Array.isArray(value) ? value.filter(isAgentResponseTrace).slice(-RESPONSE_TRACE_LIMIT) : [];
|
|
203
|
+
}
|
|
204
|
+
async #saveResponseTraces(componentId, traces) {
|
|
205
|
+
if (this.#useLegacyStorage) {
|
|
206
|
+
const legacyKey = getUiGraphResponseTraceStorageKey(this.#uiGraph, componentId, this.#location);
|
|
207
|
+
if (!legacyKey || !this.#legacyStorage)
|
|
208
|
+
return;
|
|
209
|
+
if (traces.length === 0)
|
|
210
|
+
this.#legacyStorage.removeItem(legacyKey);
|
|
211
|
+
else
|
|
212
|
+
this.#legacyStorage.setItem(legacyKey, JSON.stringify(traces));
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
await this.#persist(() => traces.length === 0
|
|
216
|
+
? this.#store.delete('response-traces', componentId)
|
|
217
|
+
: this.#store.set('response-traces', componentId, cloneRivetStoredValue(traces)));
|
|
218
|
+
}
|
|
219
|
+
#loadLegacyResponseTraces(componentId) {
|
|
220
|
+
const legacyKey = getUiGraphResponseTraceStorageKey(this.#uiGraph, componentId, this.#location);
|
|
221
|
+
if (!legacyKey || !this.#legacyStorage)
|
|
222
|
+
return [];
|
|
223
|
+
try {
|
|
224
|
+
const raw = this.#legacyStorage.getItem(legacyKey);
|
|
225
|
+
const value = raw ? JSON.parse(raw) : undefined;
|
|
226
|
+
return Array.isArray(value) ? value.filter(isAgentResponseTrace).slice(-RESPONSE_TRACE_LIMIT) : [];
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
#isResponseInspectionEnabled(componentId) {
|
|
233
|
+
return this.#uiGraph.components.some((component) => component.type === 'chat' && String(component.id) === componentId && component.allowResponseInspection === true);
|
|
234
|
+
}
|
|
235
|
+
async #enqueueResponseTraceMutation(operation) {
|
|
236
|
+
const result = this.#responseTraceMutationQueue.catch(() => undefined).then(operation);
|
|
237
|
+
this.#responseTraceMutationQueue = result.then(() => undefined, () => undefined);
|
|
238
|
+
return await result;
|
|
239
|
+
}
|
|
240
|
+
async #tryMigrateLegacyRecords() {
|
|
241
|
+
try {
|
|
242
|
+
if (!(await this.#migrateLegacyRecords())) {
|
|
243
|
+
this.#reportDiagnostic({ operation: 'migration', outcome: 'success' });
|
|
244
|
+
if (this.#warning?.code === 'migration-failed')
|
|
245
|
+
this.#setWarning(undefined);
|
|
246
|
+
return true;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
// The original localStorage value remains untouched. New writes still use IndexedDB.
|
|
251
|
+
}
|
|
252
|
+
this.#reportMigrationFailure('Existing browser data could not be migrated safely. Rivet kept the original copy and will try again later.');
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
#reportMigrationFailure(message) {
|
|
256
|
+
this.#reportDiagnostic({ operation: 'migration', outcome: 'failure' });
|
|
257
|
+
this.#setWarning({ code: 'migration-failed', message });
|
|
258
|
+
}
|
|
259
|
+
async #loadLegacyChatStateIfUnmigrated() {
|
|
260
|
+
const legacyKey = getUiGraphChatStorageKey(this.#uiGraph, this.#location);
|
|
261
|
+
if (!legacyKey || (await this.#store.getMigration(legacyKey)))
|
|
262
|
+
return {};
|
|
263
|
+
const raw = this.#legacyStorage?.getItem(legacyKey);
|
|
264
|
+
if (raw == null)
|
|
265
|
+
return {};
|
|
266
|
+
try {
|
|
267
|
+
const value = JSON.parse(raw);
|
|
268
|
+
assertValidLegacyChatState(this.#uiGraph, value);
|
|
269
|
+
const state = getUiGraphChatPersistentState(this.#uiGraph, value);
|
|
270
|
+
await this.#tryMigrateLegacyRecords();
|
|
271
|
+
return state;
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
this.#reportMigrationFailure('Some existing browser data was invalid and could not be migrated. Rivet kept its original copy.');
|
|
275
|
+
return {};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async #loadLegacyStoredValuesIfUnmigrated() {
|
|
279
|
+
const legacyKey = getUiGraphWebAppStorageKey(this.#uiGraph, this.#location);
|
|
280
|
+
if (!legacyKey || (await this.#store.getMigration(legacyKey)))
|
|
281
|
+
return {};
|
|
282
|
+
const raw = this.#legacyStorage?.getItem(legacyKey);
|
|
283
|
+
if (raw == null)
|
|
284
|
+
return {};
|
|
285
|
+
try {
|
|
286
|
+
const values = cloneRivetStoredValueRecord(JSON.parse(raw), 'Legacy Stored Value snapshot');
|
|
287
|
+
await this.#tryMigrateLegacyRecords();
|
|
288
|
+
return values;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
this.#reportMigrationFailure('Some existing browser data was invalid and could not be migrated. Rivet kept its original copy.');
|
|
292
|
+
return {};
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
async #migrateLegacyRecords() {
|
|
296
|
+
const legacyStorage = this.#legacyStorage;
|
|
297
|
+
if (!legacyStorage)
|
|
298
|
+
return false;
|
|
299
|
+
let hasUnmigratedLegacyRecords = false;
|
|
300
|
+
const now = this.#now();
|
|
301
|
+
const migrations = [
|
|
302
|
+
{
|
|
303
|
+
key: CHAT_STATE_RECORD_KEY,
|
|
304
|
+
legacyKey: getUiGraphChatStorageKey(this.#uiGraph, this.#location),
|
|
305
|
+
namespace: 'chat-state',
|
|
306
|
+
parse: (raw) => {
|
|
307
|
+
const value = JSON.parse(raw);
|
|
308
|
+
assertValidLegacyChatState(this.#uiGraph, value);
|
|
309
|
+
const state = getUiGraphChatPersistentState(this.#uiGraph, value);
|
|
310
|
+
return Object.keys(state).length > 0
|
|
311
|
+
? [{ key: CHAT_STATE_RECORD_KEY, namespace: 'chat-state', value: cloneRivetStoredValue(state) }]
|
|
312
|
+
: [];
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
{
|
|
316
|
+
key: 'legacy-snapshot',
|
|
317
|
+
legacyKey: getUiGraphWebAppStorageKey(this.#uiGraph, this.#location),
|
|
318
|
+
namespace: 'stored-values',
|
|
319
|
+
parse: (raw) => Object.entries(cloneRivetStoredValueRecord(JSON.parse(raw), 'Legacy Stored Value snapshot')).map(([key, value]) => ({ key, namespace: 'stored-values', value })),
|
|
320
|
+
},
|
|
321
|
+
...this.#uiGraph.components.flatMap((component) => component.type !== 'chat'
|
|
322
|
+
? []
|
|
323
|
+
: [
|
|
324
|
+
{
|
|
325
|
+
key: String(component.id),
|
|
326
|
+
legacyKey: getUiGraphResponseTraceStorageKey(this.#uiGraph, String(component.id), this.#location),
|
|
327
|
+
namespace: 'response-traces',
|
|
328
|
+
parse: (raw) => {
|
|
329
|
+
const value = JSON.parse(raw);
|
|
330
|
+
if (!Array.isArray(value) || !value.every(isAgentResponseTrace)) {
|
|
331
|
+
throw new Error('Legacy Chat response traces are invalid.');
|
|
332
|
+
}
|
|
333
|
+
const traces = value.slice(-RESPONSE_TRACE_LIMIT);
|
|
334
|
+
return traces.length > 0
|
|
335
|
+
? [
|
|
336
|
+
{
|
|
337
|
+
key: String(component.id),
|
|
338
|
+
namespace: 'response-traces',
|
|
339
|
+
value: cloneRivetStoredValue(traces),
|
|
340
|
+
},
|
|
341
|
+
]
|
|
342
|
+
: [];
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
]),
|
|
346
|
+
];
|
|
347
|
+
for (const migration of migrations) {
|
|
348
|
+
if (!migration.legacyKey || (await this.#store.getMigration(migration.legacyKey)))
|
|
349
|
+
continue;
|
|
350
|
+
const raw = legacyStorage.getItem(migration.legacyKey);
|
|
351
|
+
if (raw == null)
|
|
352
|
+
continue;
|
|
353
|
+
let parsed;
|
|
354
|
+
try {
|
|
355
|
+
parsed = migration.parse(raw);
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
hasUnmigratedLegacyRecords = true;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
const missing = [];
|
|
362
|
+
let hasMemoryOnlyRecord = false;
|
|
363
|
+
for (const change of parsed) {
|
|
364
|
+
if (this.#store.hasMemoryOnlyRecord(change.namespace, change.key)) {
|
|
365
|
+
hasMemoryOnlyRecord = true;
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
if ((await this.#store.get(change.namespace, change.key)) === undefined)
|
|
369
|
+
missing.push(change);
|
|
370
|
+
}
|
|
371
|
+
if (hasMemoryOnlyRecord) {
|
|
372
|
+
hasUnmigratedLegacyRecords = true;
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (missing.length > 0)
|
|
376
|
+
await this.#store.commitBatch(missing);
|
|
377
|
+
await this.#store.recordMigration({
|
|
378
|
+
cleanupAfter: now + RIVET_WEB_APP_LEGACY_RETENTION_MS,
|
|
379
|
+
completedAt: now,
|
|
380
|
+
key: migration.key,
|
|
381
|
+
legacyKey: migration.legacyKey,
|
|
382
|
+
namespace: migration.namespace,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
return hasUnmigratedLegacyRecords;
|
|
386
|
+
}
|
|
387
|
+
async #cleanupExpiredLegacyRecords() {
|
|
388
|
+
if (!this.#legacyStorage)
|
|
389
|
+
return;
|
|
390
|
+
const now = this.#now();
|
|
391
|
+
for (const migration of await this.#store.listMigrations()) {
|
|
392
|
+
if (migration.cleanupAfter <= now)
|
|
393
|
+
this.#legacyStorage.removeItem(migration.legacyKey);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async #persist(operation, requireDurable = false) {
|
|
397
|
+
try {
|
|
398
|
+
const result = await operation();
|
|
399
|
+
if (isStorageStatus(result) && !result.durable) {
|
|
400
|
+
this.#reportDiagnostic({ operation: 'write', outcome: 'failure' });
|
|
401
|
+
this.#status = result;
|
|
402
|
+
const warning = {
|
|
403
|
+
code: 'persistence-failed',
|
|
404
|
+
message: 'Some browser data exists only in memory and will not survive a reload.',
|
|
405
|
+
};
|
|
406
|
+
this.#setWarning(warning);
|
|
407
|
+
if (requireDurable)
|
|
408
|
+
throw new Error(warning.message);
|
|
409
|
+
}
|
|
410
|
+
else if (isStorageCommitResult(result) && result.hasMemoryOnlyRecords) {
|
|
411
|
+
this.#reportDiagnostic({ operation: 'write', outcome: 'failure' });
|
|
412
|
+
this.#status = { durable: false, reason: 'write-failed' };
|
|
413
|
+
this.#setWarning({
|
|
414
|
+
code: 'persistence-failed',
|
|
415
|
+
message: 'Some browser data exists only in memory and will not survive a reload.',
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
else {
|
|
419
|
+
this.#status = { durable: true };
|
|
420
|
+
if (this.#warning?.code === 'persistence-failed')
|
|
421
|
+
this.#setWarning(undefined);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
catch (error) {
|
|
425
|
+
if (error instanceof WebAppBrowserStoragePersistenceError) {
|
|
426
|
+
this.#reportDiagnostic({ operation: 'write', outcome: 'failure' });
|
|
427
|
+
this.#status = { durable: false, reason: 'write-failed' };
|
|
428
|
+
const warning = isQuotaExceededError(error)
|
|
429
|
+
? {
|
|
430
|
+
code: 'quota-exhausted',
|
|
431
|
+
message: 'Browser storage is full. Changes will last only until this page is closed.',
|
|
432
|
+
}
|
|
433
|
+
: { code: 'persistence-failed', message: error.message };
|
|
434
|
+
this.#setWarning(warning);
|
|
435
|
+
if (requireDurable)
|
|
436
|
+
throw new Error(warning.message, { cause: error });
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
throw error;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
#reportDiagnostic(diagnostic) {
|
|
443
|
+
try {
|
|
444
|
+
this.#onDiagnostic(diagnostic);
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
// Diagnostics must never affect browser persistence.
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
#setWarning(warning) {
|
|
451
|
+
if (this.#warning?.code === warning?.code && this.#warning?.message === warning?.message)
|
|
452
|
+
return;
|
|
453
|
+
this.#warning = warning;
|
|
454
|
+
for (const listener of this.#warningListeners)
|
|
455
|
+
listener(warning);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function defaultBrowserStorageDiagnostic(diagnostic) {
|
|
459
|
+
globalThis.console?.debug?.('[rivet-web-app-storage]', diagnostic);
|
|
460
|
+
}
|
|
461
|
+
function isQuotaExceededError(error) {
|
|
462
|
+
let current = error;
|
|
463
|
+
for (let depth = 0; depth < 4 && current instanceof Error; depth += 1) {
|
|
464
|
+
if (current.name === 'QuotaExceededError')
|
|
465
|
+
return true;
|
|
466
|
+
current = current.cause;
|
|
467
|
+
}
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
function isStorageStatus(value) {
|
|
471
|
+
return isRecord(value) && typeof value.durable === 'boolean';
|
|
472
|
+
}
|
|
473
|
+
function isStorageCommitResult(value) {
|
|
474
|
+
return isStorageStatus(value) && ('revision' in value || 'hasMemoryOnlyRecords' in value);
|
|
475
|
+
}
|
|
476
|
+
function getDefaultLegacyStorage() {
|
|
477
|
+
try {
|
|
478
|
+
return globalThis.localStorage ?? globalThis.window?.localStorage;
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
return undefined;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function getDefaultLocation() {
|
|
485
|
+
try {
|
|
486
|
+
return globalThis.location ?? globalThis.window?.location;
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
return undefined;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function isRecord(value) {
|
|
493
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
494
|
+
}
|
|
495
|
+
function assertValidLegacyChatState(uiGraph, value) {
|
|
496
|
+
if (!isRecord(value))
|
|
497
|
+
throw new Error('Legacy Chat state must be a JSON object.');
|
|
498
|
+
for (const component of uiGraph.components) {
|
|
499
|
+
if (component.type !== 'chat')
|
|
500
|
+
continue;
|
|
501
|
+
const draft = value[`__rivet_chat_${component.id}_draft`];
|
|
502
|
+
const messages = value[`__rivet_chat_${component.id}_messages`];
|
|
503
|
+
const pins = value[`__rivet_chat_${component.id}_pins`];
|
|
504
|
+
if (draft !== undefined && typeof draft !== 'string') {
|
|
505
|
+
throw new Error('Legacy Chat draft is invalid.');
|
|
506
|
+
}
|
|
507
|
+
if (messages !== undefined && (!Array.isArray(messages) || !messages.every(isValidLegacyChatMessage))) {
|
|
508
|
+
throw new Error('Legacy Chat messages are invalid.');
|
|
509
|
+
}
|
|
510
|
+
if (pins !== undefined &&
|
|
511
|
+
(!Array.isArray(pins) || !pins.every((pin) => typeof pin === 'number' && Number.isSafeInteger(pin) && pin >= 0))) {
|
|
512
|
+
throw new Error('Legacy Chat pins are invalid.');
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function isValidLegacyChatMessage(value) {
|
|
517
|
+
if (!isRecord(value))
|
|
518
|
+
return false;
|
|
519
|
+
return ((value.role === 'user' || value.role === 'assistant') &&
|
|
520
|
+
typeof value.content === 'string' &&
|
|
521
|
+
(value.timestamp === undefined || typeof value.timestamp === 'string') &&
|
|
522
|
+
(value.responseTraceId === undefined || typeof value.responseTraceId === 'string'));
|
|
523
|
+
}
|
|
@@ -1460,6 +1460,20 @@ button.rivet-web-app-output-header:focus-visible {
|
|
|
1460
1460
|
margin-bottom: 0;
|
|
1461
1461
|
}
|
|
1462
1462
|
|
|
1463
|
+
.rivet-web-app-loading,
|
|
1464
|
+
.rivet-web-app-storage-warning {
|
|
1465
|
+
border: 1px solid color-mix(in srgb, var(--rivet-web-app-error-color) 52%, transparent);
|
|
1466
|
+
border-radius: 10px;
|
|
1467
|
+
background: color-mix(in srgb, var(--rivet-web-app-error-color) 10%, var(--rivet-web-app-card-background));
|
|
1468
|
+
color: var(--rivet-web-app-foreground);
|
|
1469
|
+
padding: 12px 14px;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
.rivet-web-app-loading {
|
|
1473
|
+
margin: 24px auto;
|
|
1474
|
+
max-width: 720px;
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1463
1477
|
.rivet-web-app-error {
|
|
1464
1478
|
color: var(--rivet-web-app-error-color);
|
|
1465
1479
|
font-weight: 700;
|