@novu/react 3.19.0 → 3.19.1-rc.852194fa77
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/hooks/useAgentChat.cjs +220 -121
- package/dist/cjs/hooks/useAgentChat.cjs.map +1 -1
- package/dist/cjs/hooks/useAgentChat.d.cts +77 -8
- package/dist/cjs/server/index.cjs +17 -2
- package/dist/cjs/server/index.cjs.map +1 -1
- package/dist/esm/hooks/useAgentChat.d.ts +77 -8
- package/dist/esm/hooks/useAgentChat.js +214 -119
- package/dist/esm/hooks/useAgentChat.js.map +1 -1
- package/dist/esm/server/index.js +17 -2
- package/dist/esm/server/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -26,147 +26,246 @@ module.exports = __toCommonJS(useAgentChat_exports);
|
|
|
26
26
|
var import_react = require("react");
|
|
27
27
|
var import_useDataRef = require("./internal/useDataRef.cjs");
|
|
28
28
|
var import_NovuProvider = require("./NovuProvider.cjs");
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
var EMPTY_SERVER_SNAPSHOT = {
|
|
30
|
+
key: "ssr",
|
|
31
|
+
status: "ready",
|
|
32
|
+
run: { isRunning: false },
|
|
33
|
+
conversationStatus: "active",
|
|
34
|
+
pagination: { hasMore: false, status: "idle" },
|
|
35
|
+
messages: [],
|
|
36
|
+
pendingActions: [],
|
|
37
|
+
isRecovering: false
|
|
38
|
+
};
|
|
39
|
+
function handlePublicationCallbacks(args) {
|
|
40
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
|
|
41
|
+
const {
|
|
42
|
+
snapshot,
|
|
43
|
+
meta,
|
|
44
|
+
conversationIdProp,
|
|
45
|
+
propsRef,
|
|
46
|
+
loadNotifiedRef,
|
|
47
|
+
notifiedCatchUpErrorRef,
|
|
48
|
+
lastReportedErrorKeyRef
|
|
49
|
+
} = args;
|
|
50
|
+
if (((meta == null ? void 0 : meta.historyLoaded) || ((_a = meta == null ? void 0 : meta.change) == null ? void 0 : _a.kind) === "history") && !loadNotifiedRef.current && conversationIdProp) {
|
|
51
|
+
if (snapshot.conversationId) {
|
|
52
|
+
loadNotifiedRef.current = true;
|
|
53
|
+
(_c = (_b = propsRef.current).onSuccess) == null ? void 0 : _c.call(_b, {
|
|
54
|
+
conversationId: snapshot.conversationId,
|
|
55
|
+
messages: [...snapshot.messages],
|
|
56
|
+
hasMore: snapshot.pagination.hasMore
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (snapshot.catchUpError && snapshot.catchUpError !== notifiedCatchUpErrorRef.current) {
|
|
61
|
+
notifiedCatchUpErrorRef.current = snapshot.catchUpError;
|
|
62
|
+
(_e = (_d = propsRef.current).onError) == null ? void 0 : _e.call(_d, snapshot.catchUpError);
|
|
63
|
+
} else if (!snapshot.catchUpError) {
|
|
64
|
+
notifiedCatchUpErrorRef.current = void 0;
|
|
65
|
+
}
|
|
66
|
+
if (snapshot.error) {
|
|
67
|
+
const originalMessage = "originalError" in snapshot.error ? ((_f = snapshot.error.originalError) == null ? void 0 : _f.message) ?? "" : "";
|
|
68
|
+
const errorKey = `${snapshot.error.message}:${originalMessage}`;
|
|
69
|
+
if (lastReportedErrorKeyRef.current !== errorKey) {
|
|
70
|
+
lastReportedErrorKeyRef.current = errorKey;
|
|
71
|
+
(_h = (_g = propsRef.current).onError) == null ? void 0 : _h.call(_g, snapshot.error);
|
|
72
|
+
}
|
|
73
|
+
} else {
|
|
74
|
+
lastReportedErrorKeyRef.current = void 0;
|
|
75
|
+
}
|
|
76
|
+
const change = meta == null ? void 0 : meta.change;
|
|
77
|
+
if ((change == null ? void 0 : change.kind) === "live") {
|
|
78
|
+
(_j = (_i = propsRef.current).onEvent) == null ? void 0 : _j.call(_i, change.envelope);
|
|
79
|
+
}
|
|
80
|
+
if (change && change.kind !== "history") {
|
|
81
|
+
for (const message of change.addedMessages) {
|
|
82
|
+
(_l = (_k = propsRef.current).onMessage) == null ? void 0 : _l.call(_k, message);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (change) {
|
|
86
|
+
for (const action of change.newActions) {
|
|
87
|
+
(_n = (_m = propsRef.current).onActionRequested) == null ? void 0 : _n.call(_m, action);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function getCreateFlowKey(agentId, agentHash) {
|
|
92
|
+
return `${agentId}\0${agentHash ?? ""}`;
|
|
93
|
+
}
|
|
94
|
+
function resolveOwnedRuntime(args) {
|
|
95
|
+
const key = getCreateFlowKey(args.agentId, args.agentHash);
|
|
96
|
+
const current = args.ownedRuntimeRef.current;
|
|
97
|
+
if ((current == null ? void 0 : current.key) === key) {
|
|
98
|
+
return current.runtime;
|
|
32
99
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
100
|
+
current == null ? void 0 : current.runtime.dispose();
|
|
101
|
+
const result = args.novu.agentChat.conversation({ agentId: args.agentId, agentHash: args.agentHash });
|
|
102
|
+
if (!result.ok) {
|
|
103
|
+
args.ownedRuntimeRef.current = null;
|
|
104
|
+
return null;
|
|
37
105
|
}
|
|
38
|
-
|
|
106
|
+
args.ownedRuntimeRef.current = { key, runtime: result.data };
|
|
107
|
+
return result.data;
|
|
39
108
|
}
|
|
40
109
|
var useAgentChat = (props) => {
|
|
41
|
-
|
|
42
|
-
const propsRef = (0, import_useDataRef.useDataRef)(props);
|
|
110
|
+
var _a;
|
|
43
111
|
const novu = (0, import_NovuProvider.useNovu)();
|
|
44
|
-
const
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
const
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const [error, setError] = (0, import_react.useState)();
|
|
54
|
-
const [isLoading, setIsLoading] = (0, import_react.useState)(Boolean(conversationIdProp));
|
|
55
|
-
const [isFetching, setIsFetching] = (0, import_react.useState)(false);
|
|
56
|
-
const fetchGenerationRef = (0, import_react.useRef)(0);
|
|
57
|
-
(0, import_react.useEffect)(() => {
|
|
58
|
-
const agentChanged = prevAgentIdRef.current !== agentId;
|
|
59
|
-
const prevConversationIdProp = prevConversationIdPropRef.current;
|
|
60
|
-
prevAgentIdRef.current = agentId;
|
|
61
|
-
prevConversationIdPropRef.current = conversationIdProp;
|
|
62
|
-
if (agentChanged) {
|
|
63
|
-
setAssignedConversationId(void 0);
|
|
64
|
-
setLocalSessionKey(createLocalSessionKey());
|
|
65
|
-
setMessages([]);
|
|
66
|
-
setError(void 0);
|
|
67
|
-
setIsLoading(Boolean(conversationIdProp));
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
70
|
-
if (conversationIdProp) {
|
|
71
|
-
setAssignedConversationId(void 0);
|
|
72
|
-
return;
|
|
112
|
+
const propsRef = (0, import_useDataRef.useDataRef)(props);
|
|
113
|
+
const sharedRuntime = "conversation" in props ? props.conversation : void 0;
|
|
114
|
+
const agentId = (sharedRuntime == null ? void 0 : sharedRuntime.agentId) ?? props.agentId;
|
|
115
|
+
const conversationIdProp = sharedRuntime ? void 0 : props.conversationId;
|
|
116
|
+
const agentHash = sharedRuntime ? void 0 : props.agentHash;
|
|
117
|
+
const ownedRuntimeRef = (0, import_react.useRef)(null);
|
|
118
|
+
const cachedRuntime = (0, import_react.useMemo)(() => {
|
|
119
|
+
if (sharedRuntime) {
|
|
120
|
+
return sharedRuntime;
|
|
73
121
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
setAssignedConversationId(void 0);
|
|
77
|
-
setLocalSessionKey(createLocalSessionKey());
|
|
78
|
-
setMessages([]);
|
|
122
|
+
if (!conversationIdProp) {
|
|
123
|
+
return null;
|
|
79
124
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
125
|
+
const result = novu.agentChat.conversation({
|
|
126
|
+
agentId,
|
|
127
|
+
conversationId: conversationIdProp,
|
|
128
|
+
agentHash
|
|
129
|
+
});
|
|
130
|
+
return result.ok ? result.data : null;
|
|
131
|
+
}, [sharedRuntime, novu, agentId, conversationIdProp, agentHash]);
|
|
132
|
+
if (sharedRuntime || conversationIdProp) {
|
|
133
|
+
(_a = ownedRuntimeRef.current) == null ? void 0 : _a.runtime.dispose();
|
|
134
|
+
ownedRuntimeRef.current = null;
|
|
135
|
+
}
|
|
136
|
+
const ownedRuntime = sharedRuntime || conversationIdProp ? null : resolveOwnedRuntime({ novu, agentId, agentHash, ownedRuntimeRef });
|
|
137
|
+
const runtime = sharedRuntime ?? cachedRuntime ?? ownedRuntime;
|
|
138
|
+
(0, import_react.useEffect)(() => {
|
|
139
|
+
return () => {
|
|
140
|
+
var _a2;
|
|
141
|
+
(_a2 = ownedRuntimeRef.current) == null ? void 0 : _a2.runtime.dispose();
|
|
142
|
+
ownedRuntimeRef.current = null;
|
|
143
|
+
};
|
|
144
|
+
}, []);
|
|
145
|
+
const loadNotifiedRef = (0, import_react.useRef)(false);
|
|
146
|
+
const replayedActionsRef = (0, import_react.useRef)(false);
|
|
147
|
+
const notifiedCatchUpErrorRef = (0, import_react.useRef)();
|
|
148
|
+
const lastReportedErrorKeyRef = (0, import_react.useRef)();
|
|
149
|
+
(0, import_react.useEffect)(() => {
|
|
150
|
+
loadNotifiedRef.current = false;
|
|
151
|
+
replayedActionsRef.current = false;
|
|
152
|
+
notifiedCatchUpErrorRef.current = void 0;
|
|
153
|
+
lastReportedErrorKeyRef.current = void 0;
|
|
154
|
+
}, [runtime]);
|
|
155
|
+
const subscribe = (0, import_react.useCallback)(
|
|
156
|
+
(onStoreChange) => {
|
|
157
|
+
var _a2, _b;
|
|
158
|
+
if (!runtime) {
|
|
159
|
+
return () => {
|
|
160
|
+
};
|
|
94
161
|
}
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
(
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
(_d = (_c = propsRef.current).onSuccess) == null ? void 0 : _d.call(_c, response.data);
|
|
162
|
+
if (!replayedActionsRef.current) {
|
|
163
|
+
replayedActionsRef.current = true;
|
|
164
|
+
for (const action of runtime.getSnapshot().pendingActions) {
|
|
165
|
+
(_b = (_a2 = propsRef.current).onActionRequested) == null ? void 0 : _b.call(_a2, action);
|
|
166
|
+
}
|
|
101
167
|
}
|
|
102
|
-
|
|
103
|
-
|
|
168
|
+
return runtime.subscribe((snapshot2, meta) => {
|
|
169
|
+
onStoreChange();
|
|
170
|
+
handlePublicationCallbacks({
|
|
171
|
+
snapshot: snapshot2,
|
|
172
|
+
meta,
|
|
173
|
+
conversationIdProp,
|
|
174
|
+
propsRef,
|
|
175
|
+
loadNotifiedRef,
|
|
176
|
+
notifiedCatchUpErrorRef,
|
|
177
|
+
lastReportedErrorKeyRef
|
|
178
|
+
});
|
|
179
|
+
});
|
|
104
180
|
},
|
|
105
|
-
[
|
|
181
|
+
[runtime, conversationIdProp, propsRef]
|
|
106
182
|
);
|
|
107
|
-
(0, import_react.
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
setMessages([]);
|
|
120
|
-
}
|
|
121
|
-
const cleanup = novu.on("agent_chat.messages.updated", ({ data }) => {
|
|
122
|
-
if (data.key !== sessionKeyRef.current) {
|
|
123
|
-
return;
|
|
183
|
+
const getSnapshot = (0, import_react.useCallback)(() => {
|
|
184
|
+
return (runtime == null ? void 0 : runtime.getSnapshot()) ?? EMPTY_SERVER_SNAPSHOT;
|
|
185
|
+
}, [runtime]);
|
|
186
|
+
const getServerSnapshot = (0, import_react.useCallback)(() => {
|
|
187
|
+
return (runtime == null ? void 0 : runtime.getServerSnapshot()) ?? EMPTY_SERVER_SNAPSHOT;
|
|
188
|
+
}, [runtime]);
|
|
189
|
+
const snapshot = (0, import_react.useSyncExternalStore)(subscribe, getSnapshot, getServerSnapshot);
|
|
190
|
+
const callRuntime = (0, import_react.useCallback)(
|
|
191
|
+
async (action) => {
|
|
192
|
+
var _a2, _b;
|
|
193
|
+
if (!runtime) {
|
|
194
|
+
return { error: void 0 };
|
|
124
195
|
}
|
|
125
|
-
|
|
126
|
-
if (
|
|
127
|
-
|
|
196
|
+
const response = await action(runtime);
|
|
197
|
+
if (response.error) {
|
|
198
|
+
(_b = (_a2 = propsRef.current).onError) == null ? void 0 : _b.call(_a2, response.error);
|
|
128
199
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
return cleanup;
|
|
134
|
-
}, [novu, agentId, conversationIdProp, sessionKey, sessionKeyRef, conversationIdRef, propsRef, fetchConversation]);
|
|
200
|
+
return response;
|
|
201
|
+
},
|
|
202
|
+
[runtime, propsRef]
|
|
203
|
+
);
|
|
135
204
|
const refetch = (0, import_react.useCallback)(async () => {
|
|
136
|
-
|
|
137
|
-
if (!
|
|
205
|
+
var _a2, _b;
|
|
206
|
+
if (!runtime) {
|
|
138
207
|
return;
|
|
139
208
|
}
|
|
140
|
-
await
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const response = await novu.agentChat.sendMessage({
|
|
147
|
-
agentId,
|
|
148
|
-
text,
|
|
149
|
-
key: sessionKeyRef.current,
|
|
150
|
-
conversationId: conversationIdRef.current
|
|
209
|
+
const response = await runtime.load();
|
|
210
|
+
if (response.data) {
|
|
211
|
+
(_b = (_a2 = propsRef.current).onSuccess) == null ? void 0 : _b.call(_a2, {
|
|
212
|
+
conversationId: response.data.conversationId,
|
|
213
|
+
messages: [...response.data.messages],
|
|
214
|
+
hasMore: response.data.hasMore
|
|
151
215
|
});
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
216
|
+
}
|
|
217
|
+
}, [runtime, propsRef]);
|
|
218
|
+
const fetchMore = (0, import_react.useCallback)(async () => {
|
|
219
|
+
const response = await callRuntime((target) => target.fetchMore());
|
|
220
|
+
return {
|
|
221
|
+
...response,
|
|
222
|
+
error: response.error,
|
|
223
|
+
data: response.data ? {
|
|
224
|
+
messages: [...response.data.messages],
|
|
225
|
+
hasMore: response.data.hasMore
|
|
226
|
+
} : void 0
|
|
227
|
+
};
|
|
228
|
+
}, [callRuntime]);
|
|
229
|
+
const paginationWithFetch = (0, import_react.useMemo)(
|
|
230
|
+
() => ({
|
|
231
|
+
status: snapshot.pagination.status,
|
|
232
|
+
hasMore: snapshot.pagination.hasMore,
|
|
233
|
+
fetchMore
|
|
234
|
+
}),
|
|
235
|
+
[snapshot.pagination.status, snapshot.pagination.hasMore, fetchMore]
|
|
236
|
+
);
|
|
237
|
+
const sendMessage = (0, import_react.useCallback)((text) => callRuntime((target) => target.sendMessage(text)), [callRuntime]);
|
|
238
|
+
const respondToAction = (0, import_react.useCallback)(
|
|
239
|
+
(args) => callRuntime((target) => target.respondToAction(args)),
|
|
240
|
+
[callRuntime]
|
|
241
|
+
);
|
|
242
|
+
const sendAction = (0, import_react.useCallback)(
|
|
243
|
+
(args) => callRuntime((target) => target.sendAction(args)),
|
|
244
|
+
[callRuntime]
|
|
245
|
+
);
|
|
246
|
+
const retryMessage = (0, import_react.useCallback)(
|
|
247
|
+
(messageId) => callRuntime((target) => target.retryMessage(messageId)),
|
|
248
|
+
[callRuntime]
|
|
161
249
|
);
|
|
162
250
|
return {
|
|
163
|
-
messages,
|
|
251
|
+
messages: [...snapshot.messages],
|
|
252
|
+
pendingActions: [...snapshot.pendingActions],
|
|
253
|
+
conversationId: snapshot.conversationId,
|
|
254
|
+
error: snapshot.error,
|
|
255
|
+
isLoading: snapshot.status === "loading",
|
|
256
|
+
isRunning: snapshot.run.isRunning,
|
|
257
|
+
typing: snapshot.run.typing,
|
|
258
|
+
status: snapshot.conversationStatus,
|
|
259
|
+
conversationStatus: snapshot.conversationStatus,
|
|
260
|
+
run: snapshot.run,
|
|
261
|
+
pagination: paginationWithFetch,
|
|
262
|
+
isRecovering: snapshot.isRecovering,
|
|
263
|
+
catchUpError: snapshot.catchUpError,
|
|
264
|
+
refetch,
|
|
164
265
|
sendMessage,
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
isFetching,
|
|
169
|
-
refetch
|
|
266
|
+
respondToAction,
|
|
267
|
+
sendAction,
|
|
268
|
+
retryMessage
|
|
170
269
|
};
|
|
171
270
|
};
|
|
172
271
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/hooks/useAgentChat.ts"],"sourcesContent":["import type { AgentMessage, LoadConversationResult, NovuError, SendMessageResult } from '@novu/js';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useDataRef } from './internal/useDataRef';\nimport { useNovu } from './NovuProvider';\n\nexport type UseAgentChatProps = {\n agentId: string;\n /**\n * Resume this conversation. The hook loads history on mount.\n * Omit this prop to start a new chat. The first send creates a conversation.\n * Later sends pass the returned id. Remount or clear this prop to start another chat.\n */\n conversationId?: string;\n onSuccess?: (data: LoadConversationResult) => void;\n onError?: (error: NovuError) => void;\n};\n\nexport type UseAgentChatResult = {\n messages: AgentMessage[];\n conversationId?: string;\n error?: NovuError;\n /** True until the first history fetch completes. False when there is no `conversationId` prop. */\n isLoading: boolean;\n isFetching: boolean;\n refetch: () => Promise<void>;\n sendMessage: (text: string) => Promise<{\n data?: SendMessageResult;\n error?: NovuError;\n }>;\n};\n\nfunction createLocalSessionKey(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return `local_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;\n }\n\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(6);\n crypto.getRandomValues(bytes);\n\n return `local_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;\n }\n\n return `local_${Date.now().toString(36)}`;\n}\n\nexport const useAgentChat = (props: UseAgentChatProps): UseAgentChatResult => {\n const { agentId, conversationId: conversationIdProp } = props;\n const propsRef = useDataRef(props);\n const novu = useNovu();\n\n // Resume: the prop is the key on the same render (no effect lag).\n // Create: keep a `local_*` key until remount, prop clear, or agent change.\n const [localSessionKey, setLocalSessionKey] = useState(createLocalSessionKey);\n const sessionKey = conversationIdProp ?? localSessionKey;\n const sessionKeyRef = useDataRef(sessionKey);\n const prevAgentIdRef = useRef(agentId);\n const prevConversationIdPropRef = useRef(conversationIdProp);\n\n const [assignedConversationId, setAssignedConversationId] = useState<string>();\n const conversationId = conversationIdProp ?? assignedConversationId;\n const conversationIdRef = useDataRef(conversationId);\n\n const [messages, setMessages] = useState<AgentMessage[]>([]);\n const [error, setError] = useState<NovuError>();\n const [isLoading, setIsLoading] = useState(Boolean(conversationIdProp));\n const [isFetching, setIsFetching] = useState(false);\n const fetchGenerationRef = useRef(0);\n\n useEffect(() => {\n const agentChanged = prevAgentIdRef.current !== agentId;\n const prevConversationIdProp = prevConversationIdPropRef.current;\n prevAgentIdRef.current = agentId;\n prevConversationIdPropRef.current = conversationIdProp;\n\n if (agentChanged) {\n setAssignedConversationId(undefined);\n setLocalSessionKey(createLocalSessionKey());\n setMessages([]);\n setError(undefined);\n setIsLoading(Boolean(conversationIdProp));\n\n return;\n }\n\n if (conversationIdProp) {\n setAssignedConversationId(undefined);\n\n return;\n }\n\n setIsLoading(false);\n if (prevConversationIdProp !== undefined) {\n setAssignedConversationId(undefined);\n setLocalSessionKey(createLocalSessionKey());\n setMessages([]);\n }\n }, [agentId, conversationIdProp]);\n\n const fetchConversation = useCallback(\n async (targetConversationId: string) => {\n const generation = ++fetchGenerationRef.current;\n setError(undefined);\n setIsLoading(true);\n setIsFetching(true);\n\n const response = await novu.agentChat.loadConversation({\n agentId,\n conversationId: targetConversationId,\n });\n\n if (generation !== fetchGenerationRef.current) {\n return;\n }\n\n if (response.error) {\n setError(response.error);\n propsRef.current.onError?.(response.error);\n } else if (response.data) {\n setMessages(response.data.messages);\n propsRef.current.onSuccess?.(response.data);\n }\n\n setIsLoading(false);\n setIsFetching(false);\n },\n [novu, agentId, propsRef]\n );\n\n useEffect(() => {\n const snapshot = novu.agentChat.getConversation({\n agentId,\n key: sessionKey,\n conversationId: conversationIdProp,\n });\n if (snapshot) {\n setMessages(snapshot.messages);\n if (snapshot.conversationId && !conversationIdProp) {\n setAssignedConversationId(snapshot.conversationId);\n }\n } else if (!conversationIdProp) {\n setMessages([]);\n }\n\n const cleanup = novu.on('agent_chat.messages.updated', ({ data }) => {\n if (data.key !== sessionKeyRef.current) {\n return;\n }\n\n setMessages(data.messages);\n if (data.conversationId && !propsRef.current.conversationId) {\n setAssignedConversationId(data.conversationId);\n }\n });\n\n if (conversationIdProp) {\n void fetchConversation(conversationIdProp);\n }\n\n return cleanup;\n }, [novu, agentId, conversationIdProp, sessionKey, sessionKeyRef, conversationIdRef, propsRef, fetchConversation]);\n\n const refetch = useCallback(async () => {\n const id = conversationIdRef.current;\n if (!id) {\n return;\n }\n\n await fetchConversation(id);\n }, [conversationIdRef, fetchConversation]);\n\n const sendMessage = useCallback(\n async (text: string) => {\n setError(undefined);\n\n const response = await novu.agentChat.sendMessage({\n agentId,\n text,\n key: sessionKeyRef.current,\n conversationId: conversationIdRef.current,\n });\n\n if (response.error) {\n setError(response.error);\n propsRef.current.onError?.(response.error);\n } else if (response.data && !propsRef.current.conversationId) {\n setAssignedConversationId(response.data.conversationId);\n }\n\n return response;\n },\n [novu, agentId, sessionKeyRef, conversationIdRef, propsRef]\n );\n\n return {\n messages,\n sendMessage,\n conversationId,\n error,\n isLoading,\n isFetching,\n refetch,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA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IACA,CAAC,MAAM,SAAS,eAAe,mBAAmB,QAAQ;AAAA,EAC5D;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/hooks/useAgentChat.ts"],"sourcesContent":["import type {\n AgentChatPagination,\n AgentChatPlanLimitError,\n AgentConversationPublicationMeta,\n AgentConversationRunSnapshot,\n AgentConversationRuntime,\n AgentConversationSnapshot,\n AgentConversationStatus,\n AgentEventEnvelope,\n AgentHashFields,\n AgentMessage,\n AgentPendingAction,\n AgentToolApprovalDecision,\n LoadConversationResult,\n NovuError,\n RespondToActionResult,\n SendActionResult,\n SendMessageResult,\n} from '@novu/js';\nimport { type MutableRefObject, useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { useDataRef } from './internal/useDataRef';\nimport { useNovu } from './NovuProvider';\n\ntype UseAgentChatCallbacks = {\n onSuccess?: (data: LoadConversationResult) => void;\n onError?: (error: NovuError | AgentChatPlanLimitError) => void;\n /**\n * Fires once per message, when the message id first appears on the conversation.\n * History pages are silent: only new activity fires.\n * An agent message can still be empty at this point, because the first envelope of a\n * turn creates the message before any text is folded into it.\n * A send that never reaches the server does not fire: the message flips to `failed` instead.\n */\n onMessage?: (message: AgentMessage) => void;\n /**\n * Fires once per pending action, including actions still pending on mount, so a\n * resumed conversation reports what it is blocked on. Paging backwards is silent.\n */\n onActionRequested?: (action: AgentPendingAction) => void;\n /**\n * Raw envelopes for this conversation, before the derived callbacks for the same fold.\n * A duplicate envelope that the store drops does not fire. Neither does an envelope that\n * arrives before a newly created conversation claims its id.\n * The store folds the envelope before this callback runs, so `messages` here is one render old.\n */\n onEvent?: (envelope: AgentEventEnvelope) => void;\n};\n\nexport type UseAgentChatProps = UseAgentChatCallbacks &\n AgentHashFields &\n (\n | {\n agentId: string;\n /**\n * Resume this conversation. The hook loads history on mount.\n * Omit this prop to start a new chat. The first send creates a conversation.\n * Later sends pass the returned id. Remount or clear this prop to start another chat.\n */\n conversationId?: string;\n conversation?: never;\n }\n | {\n /** Share an existing conversation runtime across multiple hook instances. */\n conversation: AgentConversationRuntime;\n agentId?: never;\n conversationId?: never;\n agentHash?: never;\n }\n );\n\nexport type UseAgentChatResult = {\n messages: AgentMessage[];\n pendingActions: AgentPendingAction[];\n conversationId?: string;\n error?: NovuError | AgentChatPlanLimitError;\n /** True until the first history fetch completes. False when there is no `conversationId` prop. */\n isLoading: boolean;\n isRunning: boolean;\n typing?: AgentConversationRunSnapshot['typing'];\n /** Conversation lifecycle status (`active`, etc.). */\n status: AgentConversationStatus;\n /** Explicit alias for `status`. */\n conversationStatus: AgentConversationStatus;\n /** Current agent run snapshot. */\n run: AgentConversationRunSnapshot;\n pagination: AgentChatPagination & {\n fetchMore: () => Promise<{\n data?: { messages: AgentMessage[]; hasMore: boolean };\n error?: NovuError;\n }>;\n };\n /** True while reconnect catch-up is in flight for this conversation. */\n isRecovering: boolean;\n /** Set when reconnect catch-up fails. Separate from send/fetch `error`. */\n catchUpError?: NovuError;\n refetch: () => Promise<void>;\n sendMessage: (text: string) => Promise<{\n data?: SendMessageResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n respondToAction: (args: { actionId: string; decision: AgentToolApprovalDecision }) => Promise<{\n data?: RespondToActionResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n sendAction: (args: { actionId: string; sourceMessageId: string; value?: string }) => Promise<{\n data?: SendActionResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n retryMessage: (messageId: string) => Promise<{\n data?: SendMessageResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n};\n\nconst EMPTY_SERVER_SNAPSHOT: AgentConversationSnapshot = {\n key: 'ssr',\n status: 'ready',\n run: { isRunning: false },\n conversationStatus: 'active',\n pagination: { hasMore: false, status: 'idle' },\n messages: [],\n pendingActions: [],\n isRecovering: false,\n};\n\ntype RuntimeActionResult<T> = {\n data?: T;\n error?: NovuError | AgentChatPlanLimitError;\n};\n\nfunction handlePublicationCallbacks(args: {\n snapshot: AgentConversationSnapshot;\n meta: AgentConversationPublicationMeta | undefined;\n conversationIdProp: string | undefined;\n propsRef: ReturnType<typeof useDataRef<UseAgentChatProps>>;\n loadNotifiedRef: MutableRefObject<boolean>;\n notifiedCatchUpErrorRef: MutableRefObject<NovuError | undefined>;\n lastReportedErrorKeyRef: MutableRefObject<string | undefined>;\n}): void {\n const {\n snapshot,\n meta,\n conversationIdProp,\n propsRef,\n loadNotifiedRef,\n notifiedCatchUpErrorRef,\n lastReportedErrorKeyRef,\n } = args;\n\n if ((meta?.historyLoaded || meta?.change?.kind === 'history') && !loadNotifiedRef.current && conversationIdProp) {\n if (snapshot.conversationId) {\n loadNotifiedRef.current = true;\n propsRef.current.onSuccess?.({\n conversationId: snapshot.conversationId,\n messages: [...snapshot.messages],\n hasMore: snapshot.pagination.hasMore,\n });\n }\n }\n\n if (snapshot.catchUpError && snapshot.catchUpError !== notifiedCatchUpErrorRef.current) {\n notifiedCatchUpErrorRef.current = snapshot.catchUpError;\n propsRef.current.onError?.(snapshot.catchUpError);\n } else if (!snapshot.catchUpError) {\n notifiedCatchUpErrorRef.current = undefined;\n }\n\n if (snapshot.error) {\n const originalMessage = 'originalError' in snapshot.error ? (snapshot.error.originalError?.message ?? '') : '';\n const errorKey = `${snapshot.error.message}:${originalMessage}`;\n if (lastReportedErrorKeyRef.current !== errorKey) {\n lastReportedErrorKeyRef.current = errorKey;\n propsRef.current.onError?.(snapshot.error as NovuError | AgentChatPlanLimitError);\n }\n } else {\n lastReportedErrorKeyRef.current = undefined;\n }\n\n const change = meta?.change;\n if (change?.kind === 'live') {\n propsRef.current.onEvent?.(change.envelope);\n }\n\n if (change && change.kind !== 'history') {\n for (const message of change.addedMessages) {\n propsRef.current.onMessage?.(message);\n }\n }\n\n if (change) {\n for (const action of change.newActions) {\n propsRef.current.onActionRequested?.(action);\n }\n }\n}\n\ntype OwnedRuntimeEntry = {\n key: string;\n runtime: AgentConversationRuntime;\n};\n\nfunction getCreateFlowKey(agentId: string, agentHash?: string): string {\n return `${agentId}\\0${agentHash ?? ''}`;\n}\n\nfunction resolveOwnedRuntime(args: {\n novu: ReturnType<typeof useNovu>;\n agentId: string;\n agentHash?: string;\n ownedRuntimeRef: MutableRefObject<OwnedRuntimeEntry | null>;\n}): AgentConversationRuntime | null {\n const key = getCreateFlowKey(args.agentId, args.agentHash);\n const current = args.ownedRuntimeRef.current;\n\n if (current?.key === key) {\n return current.runtime;\n }\n\n current?.runtime.dispose();\n\n const result = args.novu.agentChat.conversation({ agentId: args.agentId, agentHash: args.agentHash });\n if (!result.ok) {\n args.ownedRuntimeRef.current = null;\n return null;\n }\n\n args.ownedRuntimeRef.current = { key, runtime: result.data };\n return result.data;\n}\n\nexport const useAgentChat = (props: UseAgentChatProps): UseAgentChatResult => {\n const novu = useNovu();\n const propsRef = useDataRef(props);\n\n const sharedRuntime = 'conversation' in props ? props.conversation : undefined;\n const agentId = sharedRuntime?.agentId ?? props.agentId!;\n const conversationIdProp = sharedRuntime ? undefined : props.conversationId;\n const agentHash = sharedRuntime ? undefined : props.agentHash;\n\n const ownedRuntimeRef = useRef<OwnedRuntimeEntry | null>(null);\n\n const cachedRuntime = useMemo(() => {\n if (sharedRuntime) {\n return sharedRuntime;\n }\n\n if (!conversationIdProp) {\n return null;\n }\n\n const result = novu.agentChat.conversation({\n agentId,\n conversationId: conversationIdProp,\n agentHash,\n });\n\n return result.ok ? result.data : null;\n }, [sharedRuntime, novu, agentId, conversationIdProp, agentHash]);\n\n if (sharedRuntime || conversationIdProp) {\n ownedRuntimeRef.current?.runtime.dispose();\n ownedRuntimeRef.current = null;\n }\n\n const ownedRuntime =\n sharedRuntime || conversationIdProp ? null : resolveOwnedRuntime({ novu, agentId, agentHash, ownedRuntimeRef });\n\n const runtime = sharedRuntime ?? cachedRuntime ?? ownedRuntime;\n\n useEffect(() => {\n return () => {\n ownedRuntimeRef.current?.runtime.dispose();\n ownedRuntimeRef.current = null;\n };\n }, []);\n\n const loadNotifiedRef = useRef(false);\n const replayedActionsRef = useRef(false);\n const notifiedCatchUpErrorRef = useRef<NovuError | undefined>();\n const lastReportedErrorKeyRef = useRef<string>();\n\n useEffect(() => {\n loadNotifiedRef.current = false;\n replayedActionsRef.current = false;\n notifiedCatchUpErrorRef.current = undefined;\n lastReportedErrorKeyRef.current = undefined;\n }, [runtime]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!runtime) {\n return () => {};\n }\n\n if (!replayedActionsRef.current) {\n replayedActionsRef.current = true;\n for (const action of runtime.getSnapshot().pendingActions) {\n propsRef.current.onActionRequested?.(action);\n }\n }\n\n return runtime.subscribe((snapshot, meta) => {\n onStoreChange();\n handlePublicationCallbacks({\n snapshot,\n meta,\n conversationIdProp,\n propsRef,\n loadNotifiedRef,\n notifiedCatchUpErrorRef,\n lastReportedErrorKeyRef,\n });\n });\n },\n [runtime, conversationIdProp, propsRef]\n );\n\n const getSnapshot = useCallback(() => {\n return runtime?.getSnapshot() ?? EMPTY_SERVER_SNAPSHOT;\n }, [runtime]);\n\n const getServerSnapshot = useCallback(() => {\n return runtime?.getServerSnapshot() ?? EMPTY_SERVER_SNAPSHOT;\n }, [runtime]);\n\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n const callRuntime = useCallback(\n async <T>(action: (target: AgentConversationRuntime) => Promise<RuntimeActionResult<T>>) => {\n if (!runtime) {\n return { error: undefined };\n }\n\n const response = await action(runtime);\n if (response.error) {\n propsRef.current.onError?.(response.error);\n }\n\n return response;\n },\n [runtime, propsRef]\n );\n\n const refetch = useCallback(async () => {\n if (!runtime) {\n return;\n }\n\n const response = await runtime.load();\n if (response.data) {\n propsRef.current.onSuccess?.({\n conversationId: response.data.conversationId,\n messages: [...response.data.messages],\n hasMore: response.data.hasMore,\n });\n }\n }, [runtime, propsRef]);\n\n const fetchMore = useCallback(async () => {\n const response = await callRuntime((target) => target.fetchMore());\n\n return {\n ...response,\n error: response.error as NovuError | undefined,\n data: response.data\n ? {\n messages: [...response.data.messages],\n hasMore: response.data.hasMore,\n }\n : undefined,\n };\n }, [callRuntime]);\n\n const paginationWithFetch = useMemo(\n () => ({\n status: snapshot.pagination.status,\n hasMore: snapshot.pagination.hasMore,\n fetchMore,\n }),\n [snapshot.pagination.status, snapshot.pagination.hasMore, fetchMore]\n );\n\n const sendMessage = useCallback((text: string) => callRuntime((target) => target.sendMessage(text)), [callRuntime]);\n const respondToAction = useCallback(\n (args: { actionId: string; decision: AgentToolApprovalDecision }) =>\n callRuntime((target) => target.respondToAction(args)),\n [callRuntime]\n );\n const sendAction = useCallback(\n (args: { actionId: string; sourceMessageId: string; value?: string }) =>\n callRuntime((target) => target.sendAction(args)),\n [callRuntime]\n );\n const retryMessage = useCallback(\n (messageId: string) => callRuntime((target) => target.retryMessage(messageId)),\n [callRuntime]\n );\n\n return {\n messages: [...snapshot.messages],\n pendingActions: [...snapshot.pendingActions],\n conversationId: snapshot.conversationId,\n error: snapshot.error as UseAgentChatResult['error'],\n isLoading: snapshot.status === 'loading',\n isRunning: snapshot.run.isRunning,\n typing: snapshot.run.typing,\n status: snapshot.conversationStatus,\n conversationStatus: snapshot.conversationStatus,\n run: snapshot.run,\n pagination: paginationWithFetch,\n isRecovering: snapshot.isRecovering,\n catchUpError: snapshot.catchUpError,\n refetch,\n sendMessage,\n respondToAction,\n sendAction,\n retryMessage,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,mBAAqG;AACrG,wBAA2B;AAC3B,0BAAwB;AA6FxB,IAAM,wBAAmD;AAAA,EACvD,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,KAAK,EAAE,WAAW,MAAM;AAAA,EACxB,oBAAoB;AAAA,EACpB,YAAY,EAAE,SAAS,OAAO,QAAQ,OAAO;AAAA,EAC7C,UAAU,CAAC;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AACF;","names":["_a","snapshot"]}
|
|
@@ -1,6 +1,30 @@
|
|
|
1
|
-
import { LoadConversationResult, NovuError, AgentMessage, SendMessageResult } from '@novu/js';
|
|
1
|
+
import { LoadConversationResult, NovuError, AgentChatPlanLimitError, AgentMessage, AgentPendingAction, AgentEventEnvelope, AgentHashFields, AgentConversationRuntime, AgentConversationRunSnapshot, AgentConversationStatus, AgentChatPagination, SendMessageResult, AgentToolApprovalDecision, RespondToActionResult, SendActionResult } from '@novu/js';
|
|
2
2
|
|
|
3
|
-
type
|
|
3
|
+
type UseAgentChatCallbacks = {
|
|
4
|
+
onSuccess?: (data: LoadConversationResult) => void;
|
|
5
|
+
onError?: (error: NovuError | AgentChatPlanLimitError) => void;
|
|
6
|
+
/**
|
|
7
|
+
* Fires once per message, when the message id first appears on the conversation.
|
|
8
|
+
* History pages are silent: only new activity fires.
|
|
9
|
+
* An agent message can still be empty at this point, because the first envelope of a
|
|
10
|
+
* turn creates the message before any text is folded into it.
|
|
11
|
+
* A send that never reaches the server does not fire: the message flips to `failed` instead.
|
|
12
|
+
*/
|
|
13
|
+
onMessage?: (message: AgentMessage) => void;
|
|
14
|
+
/**
|
|
15
|
+
* Fires once per pending action, including actions still pending on mount, so a
|
|
16
|
+
* resumed conversation reports what it is blocked on. Paging backwards is silent.
|
|
17
|
+
*/
|
|
18
|
+
onActionRequested?: (action: AgentPendingAction) => void;
|
|
19
|
+
/**
|
|
20
|
+
* Raw envelopes for this conversation, before the derived callbacks for the same fold.
|
|
21
|
+
* A duplicate envelope that the store drops does not fire. Neither does an envelope that
|
|
22
|
+
* arrives before a newly created conversation claims its id.
|
|
23
|
+
* The store folds the envelope before this callback runs, so `messages` here is one render old.
|
|
24
|
+
*/
|
|
25
|
+
onEvent?: (envelope: AgentEventEnvelope) => void;
|
|
26
|
+
};
|
|
27
|
+
type UseAgentChatProps = UseAgentChatCallbacks & AgentHashFields & ({
|
|
4
28
|
agentId: string;
|
|
5
29
|
/**
|
|
6
30
|
* Resume this conversation. The hook loads history on mount.
|
|
@@ -8,20 +32,65 @@ type UseAgentChatProps = {
|
|
|
8
32
|
* Later sends pass the returned id. Remount or clear this prop to start another chat.
|
|
9
33
|
*/
|
|
10
34
|
conversationId?: string;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
35
|
+
conversation?: never;
|
|
36
|
+
} | {
|
|
37
|
+
/** Share an existing conversation runtime across multiple hook instances. */
|
|
38
|
+
conversation: AgentConversationRuntime;
|
|
39
|
+
agentId?: never;
|
|
40
|
+
conversationId?: never;
|
|
41
|
+
agentHash?: never;
|
|
42
|
+
});
|
|
14
43
|
type UseAgentChatResult = {
|
|
15
44
|
messages: AgentMessage[];
|
|
45
|
+
pendingActions: AgentPendingAction[];
|
|
16
46
|
conversationId?: string;
|
|
17
|
-
error?: NovuError;
|
|
47
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
18
48
|
/** True until the first history fetch completes. False when there is no `conversationId` prop. */
|
|
19
49
|
isLoading: boolean;
|
|
20
|
-
|
|
50
|
+
isRunning: boolean;
|
|
51
|
+
typing?: AgentConversationRunSnapshot['typing'];
|
|
52
|
+
/** Conversation lifecycle status (`active`, etc.). */
|
|
53
|
+
status: AgentConversationStatus;
|
|
54
|
+
/** Explicit alias for `status`. */
|
|
55
|
+
conversationStatus: AgentConversationStatus;
|
|
56
|
+
/** Current agent run snapshot. */
|
|
57
|
+
run: AgentConversationRunSnapshot;
|
|
58
|
+
pagination: AgentChatPagination & {
|
|
59
|
+
fetchMore: () => Promise<{
|
|
60
|
+
data?: {
|
|
61
|
+
messages: AgentMessage[];
|
|
62
|
+
hasMore: boolean;
|
|
63
|
+
};
|
|
64
|
+
error?: NovuError;
|
|
65
|
+
}>;
|
|
66
|
+
};
|
|
67
|
+
/** True while reconnect catch-up is in flight for this conversation. */
|
|
68
|
+
isRecovering: boolean;
|
|
69
|
+
/** Set when reconnect catch-up fails. Separate from send/fetch `error`. */
|
|
70
|
+
catchUpError?: NovuError;
|
|
21
71
|
refetch: () => Promise<void>;
|
|
22
72
|
sendMessage: (text: string) => Promise<{
|
|
23
73
|
data?: SendMessageResult;
|
|
24
|
-
error?: NovuError;
|
|
74
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
75
|
+
}>;
|
|
76
|
+
respondToAction: (args: {
|
|
77
|
+
actionId: string;
|
|
78
|
+
decision: AgentToolApprovalDecision;
|
|
79
|
+
}) => Promise<{
|
|
80
|
+
data?: RespondToActionResult;
|
|
81
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
82
|
+
}>;
|
|
83
|
+
sendAction: (args: {
|
|
84
|
+
actionId: string;
|
|
85
|
+
sourceMessageId: string;
|
|
86
|
+
value?: string;
|
|
87
|
+
}) => Promise<{
|
|
88
|
+
data?: SendActionResult;
|
|
89
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
90
|
+
}>;
|
|
91
|
+
retryMessage: (messageId: string) => Promise<{
|
|
92
|
+
data?: SendMessageResult;
|
|
93
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
25
94
|
}>;
|
|
26
95
|
};
|
|
27
96
|
declare const useAgentChat: (props: UseAgentChatProps) => UseAgentChatResult;
|
|
@@ -95,10 +95,25 @@ function useNovu() {
|
|
|
95
95
|
function useAgentChat(_) {
|
|
96
96
|
return {
|
|
97
97
|
messages: [],
|
|
98
|
+
pendingActions: [],
|
|
98
99
|
isLoading: false,
|
|
99
|
-
|
|
100
|
+
isRunning: false,
|
|
101
|
+
typing: void 0,
|
|
102
|
+
status: "active",
|
|
103
|
+
conversationStatus: "active",
|
|
104
|
+
run: { isRunning: false },
|
|
105
|
+
pagination: {
|
|
106
|
+
status: "idle",
|
|
107
|
+
hasMore: false,
|
|
108
|
+
fetchMore: () => Promise.resolve({ data: void 0, error: void 0 })
|
|
109
|
+
},
|
|
110
|
+
isRecovering: false,
|
|
111
|
+
catchUpError: void 0,
|
|
100
112
|
refetch: () => Promise.resolve(),
|
|
101
|
-
sendMessage: () => Promise.resolve({ data: void 0, error: void 0 })
|
|
113
|
+
sendMessage: () => Promise.resolve({ data: void 0, error: void 0 }),
|
|
114
|
+
respondToAction: () => Promise.resolve({ data: void 0, error: void 0 }),
|
|
115
|
+
sendAction: () => Promise.resolve({ data: void 0, error: void 0 }),
|
|
116
|
+
retryMessage: () => Promise.resolve({ data: void 0, error: void 0 })
|
|
102
117
|
};
|
|
103
118
|
}
|
|
104
119
|
function useCounts(_) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/index.tsx"],"sourcesContent":["import type { InboxProps } from '../components/Inbox';\nimport { ShadowRootDetector } from '../components/ShadowRootDetector';\nimport type {\n UseAgentChatProps,\n UseAgentChatResult,\n UseCreateSubscriptionProps,\n UseCreateSubscriptionResult,\n UseNotificationsProps,\n UseNotificationsResult,\n UsePreferencesProps,\n UsePreferencesResult,\n UseRemoveSubscriptionProps,\n UseRemoveSubscriptionResult,\n UseScheduleProps,\n UseScheduleResult,\n UseSubscriptionProps,\n UseSubscriptionResult,\n UseSubscriptionsProps,\n UseSubscriptionsResult,\n UseUpdateSubscriptionProps,\n UseUpdateSubscriptionResult,\n} from '../hooks';\nimport type { NovuProviderProps } from '../hooks/NovuProvider';\nimport type { UseCountsProps, UseCountsResult } from '../hooks/useCounts';\n\n/**\n * Exporting all components from the components folder\n * as empty functions to fix build errors in SSR\n * This will be replaced with actual components\n * when we implement the SSR components in @novu/js/ui\n */\nexport function Inbox(props: InboxProps) {\n return <ShadowRootDetector />;\n}\n\nexport function InboxContent() {}\n\nexport function Notifications() {}\n\nexport function Preferences() {}\n\nexport function Bell() {}\n\nexport function NovuProvider(props: NovuProviderProps) {\n return <>{props.children}</>;\n}\n\nexport function Subscription() {\n return <ShadowRootDetector />;\n}\n\nexport function SubscriptionButton() {}\n\nexport function SubscriptionPreferences() {}\n\nexport function SlackConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function SlackLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function TelegramConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function useNovu() {\n return null;\n}\n\nexport function useAgentChat(_: UseAgentChatProps): UseAgentChatResult {\n return {\n messages: [],\n isLoading: false,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/server/index.tsx"],"sourcesContent":["import type { InboxProps } from '../components/Inbox';\nimport { ShadowRootDetector } from '../components/ShadowRootDetector';\nimport type {\n UseAgentChatProps,\n UseAgentChatResult,\n UseCreateSubscriptionProps,\n UseCreateSubscriptionResult,\n UseNotificationsProps,\n UseNotificationsResult,\n UsePreferencesProps,\n UsePreferencesResult,\n UseRemoveSubscriptionProps,\n UseRemoveSubscriptionResult,\n UseScheduleProps,\n UseScheduleResult,\n UseSubscriptionProps,\n UseSubscriptionResult,\n UseSubscriptionsProps,\n UseSubscriptionsResult,\n UseUpdateSubscriptionProps,\n UseUpdateSubscriptionResult,\n} from '../hooks';\nimport type { NovuProviderProps } from '../hooks/NovuProvider';\nimport type { UseCountsProps, UseCountsResult } from '../hooks/useCounts';\n\n/**\n * Exporting all components from the components folder\n * as empty functions to fix build errors in SSR\n * This will be replaced with actual components\n * when we implement the SSR components in @novu/js/ui\n */\nexport function Inbox(props: InboxProps) {\n return <ShadowRootDetector />;\n}\n\nexport function InboxContent() {}\n\nexport function Notifications() {}\n\nexport function Preferences() {}\n\nexport function Bell() {}\n\nexport function NovuProvider(props: NovuProviderProps) {\n return <>{props.children}</>;\n}\n\nexport function Subscription() {\n return <ShadowRootDetector />;\n}\n\nexport function SubscriptionButton() {}\n\nexport function SubscriptionPreferences() {}\n\nexport function SlackConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function SlackLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function TelegramConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function useNovu() {\n return null;\n}\n\nexport function useAgentChat(_: UseAgentChatProps): UseAgentChatResult {\n return {\n messages: [],\n pendingActions: [],\n isLoading: false,\n isRunning: false,\n typing: undefined,\n status: 'active',\n conversationStatus: 'active',\n run: { isRunning: false },\n pagination: {\n status: 'idle',\n hasMore: false,\n fetchMore: () => Promise.resolve({ data: undefined, error: undefined }),\n },\n isRecovering: false,\n catchUpError: undefined,\n refetch: () => Promise.resolve(),\n sendMessage: () => Promise.resolve({ data: undefined, error: undefined }),\n respondToAction: () => Promise.resolve({ data: undefined, error: undefined }),\n sendAction: () => Promise.resolve({ data: undefined, error: undefined }),\n retryMessage: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useCounts(_: UseCountsProps): UseCountsResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useNotifications(_: UseNotificationsProps): UseNotificationsResult {\n return {\n isLoading: false,\n isFetching: false,\n hasMore: false,\n readAll: () => Promise.resolve({ data: undefined, error: undefined }),\n seenAll: () => Promise.resolve({ data: undefined, error: undefined }),\n archiveAll: () => Promise.resolve({ data: undefined, error: undefined }),\n archiveAllRead: () => Promise.resolve({ data: undefined, error: undefined }),\n refetch: () => Promise.resolve(),\n fetchMore: () => Promise.resolve(),\n };\n}\n\nexport function usePreferences(_: UsePreferencesProps): UsePreferencesResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useSchedule(_: UseScheduleProps): UseScheduleResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useSubscription(_: UseSubscriptionProps): UseSubscriptionResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useCreateSubscription(_: UseCreateSubscriptionProps = {}): UseCreateSubscriptionResult {\n return {\n isCreating: false,\n error: undefined,\n create: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useUpdateSubscription(_: UseUpdateSubscriptionProps = {}): UseUpdateSubscriptionResult {\n return {\n isUpdating: false,\n error: undefined,\n update: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useRemoveSubscription(_: UseRemoveSubscriptionProps = {}): UseRemoveSubscriptionResult {\n return {\n isRemoving: false,\n error: undefined,\n remove: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useSubscriptions(_: UseSubscriptionsProps): UseSubscriptionsResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport type * from '@novu/js';\nexport { PreferenceLevel, SeverityLevelEnum, WorkflowCriticalityEnum } from '@novu/js';\n\nexport type {\n AllLocalization,\n AllLocalizationKey,\n ElementStyles,\n InboxAppearance,\n InboxAppearanceCallback,\n InboxAppearanceCallbackFunction,\n InboxAppearanceCallbackKeys,\n InboxAppearanceKey,\n InboxElements,\n InboxLocalization,\n InboxLocalizationKey,\n InboxTheme,\n NotificationActionClickHandler,\n NotificationClickHandler,\n NotificationRenderer,\n PreferenceGroups,\n PreferencesFilter,\n RouterPush,\n SubscriptionAppearance,\n SubscriptionAppearanceCallback,\n SubscriptionAppearanceCallbackFunction,\n SubscriptionAppearanceCallbackKeys,\n SubscriptionAppearanceKey,\n SubscriptionElements,\n SubscriptionLocalization,\n SubscriptionLocalizationKey,\n SubscriptionTheme,\n Tab,\n Variables,\n} from '@novu/js/ui';\n\nexport type { BellProps, InboxContentProps, InboxProps, NotificationProps, NovuProviderProps } from '../components';\n\nexport type {\n UseAgentChatProps,\n UseAgentChatResult,\n UseCountsProps,\n UseCountsResult,\n UseNotificationsProps,\n UseNotificationsResult,\n UsePreferencesResult,\n UseScheduleProps as UsePreferencesProps,\n} from '../hooks';\n\nexport type {\n BaseProps,\n BellRenderer,\n BodyRenderer,\n DefaultInboxProps,\n DefaultProps,\n NoRendererProps,\n NotificationRenderer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EACjC;AACF;AAEO,SAAS,YAAY,GAAwC;AAClE,SAAO;AAAA,IACL,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,SAAS,MAAM,QAAQ,QAAQ;AAAA,EACjC;AACF;AAEO,SAAS,gBAAgB,GAAgD;AAC9E,SAAO;AAAA,IACL,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,SAAS,MAAM,QAAQ,QAAQ;AAAA,EACjC;AACF;AAEO,SAAS,sBAAsB,IAAgC,CAAC,GAAgC;AACrG,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,QAAQ,MAAM,QAAQ,QAAQ,EAAE,MAAM,QAAW,OAAO,OAAU,CAAC;AAAA,EACrE;AACF;AAEO,SAAS,sBAAsB,IAAgC,CAAC,GAAgC;AACrG,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,QAAQ,MAAM,QAAQ,QAAQ,EAAE,MAAM,QAAW,OAAO,OAAU,CAAC;AAAA,EACrE;AACF;AAEO,SAAS,sBAAsB,IAAgC,CAAC,GAAgC;AACrG,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,QAAQ,MAAM,QAAQ,QAAQ,EAAE,MAAM,QAAW,OAAO,OAAU,CAAC;AAAA,EACrE;AACF;AAEO,SAAS,iBAAiB,GAAkD;AACjF,SAAO;AAAA,IACL,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,SAAS,MAAM,QAAQ,QAAQ;AAAA,EACjC;AACF;","names":[]}
|
|
@@ -1,6 +1,30 @@
|
|
|
1
|
-
import { LoadConversationResult, NovuError, AgentMessage, SendMessageResult } from '@novu/js';
|
|
1
|
+
import { LoadConversationResult, NovuError, AgentChatPlanLimitError, AgentMessage, AgentPendingAction, AgentEventEnvelope, AgentHashFields, AgentConversationRuntime, AgentConversationRunSnapshot, AgentConversationStatus, AgentChatPagination, SendMessageResult, AgentToolApprovalDecision, RespondToActionResult, SendActionResult } from '@novu/js';
|
|
2
2
|
|
|
3
|
-
type
|
|
3
|
+
type UseAgentChatCallbacks = {
|
|
4
|
+
onSuccess?: (data: LoadConversationResult) => void;
|
|
5
|
+
onError?: (error: NovuError | AgentChatPlanLimitError) => void;
|
|
6
|
+
/**
|
|
7
|
+
* Fires once per message, when the message id first appears on the conversation.
|
|
8
|
+
* History pages are silent: only new activity fires.
|
|
9
|
+
* An agent message can still be empty at this point, because the first envelope of a
|
|
10
|
+
* turn creates the message before any text is folded into it.
|
|
11
|
+
* A send that never reaches the server does not fire: the message flips to `failed` instead.
|
|
12
|
+
*/
|
|
13
|
+
onMessage?: (message: AgentMessage) => void;
|
|
14
|
+
/**
|
|
15
|
+
* Fires once per pending action, including actions still pending on mount, so a
|
|
16
|
+
* resumed conversation reports what it is blocked on. Paging backwards is silent.
|
|
17
|
+
*/
|
|
18
|
+
onActionRequested?: (action: AgentPendingAction) => void;
|
|
19
|
+
/**
|
|
20
|
+
* Raw envelopes for this conversation, before the derived callbacks for the same fold.
|
|
21
|
+
* A duplicate envelope that the store drops does not fire. Neither does an envelope that
|
|
22
|
+
* arrives before a newly created conversation claims its id.
|
|
23
|
+
* The store folds the envelope before this callback runs, so `messages` here is one render old.
|
|
24
|
+
*/
|
|
25
|
+
onEvent?: (envelope: AgentEventEnvelope) => void;
|
|
26
|
+
};
|
|
27
|
+
type UseAgentChatProps = UseAgentChatCallbacks & AgentHashFields & ({
|
|
4
28
|
agentId: string;
|
|
5
29
|
/**
|
|
6
30
|
* Resume this conversation. The hook loads history on mount.
|
|
@@ -8,20 +32,65 @@ type UseAgentChatProps = {
|
|
|
8
32
|
* Later sends pass the returned id. Remount or clear this prop to start another chat.
|
|
9
33
|
*/
|
|
10
34
|
conversationId?: string;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
35
|
+
conversation?: never;
|
|
36
|
+
} | {
|
|
37
|
+
/** Share an existing conversation runtime across multiple hook instances. */
|
|
38
|
+
conversation: AgentConversationRuntime;
|
|
39
|
+
agentId?: never;
|
|
40
|
+
conversationId?: never;
|
|
41
|
+
agentHash?: never;
|
|
42
|
+
});
|
|
14
43
|
type UseAgentChatResult = {
|
|
15
44
|
messages: AgentMessage[];
|
|
45
|
+
pendingActions: AgentPendingAction[];
|
|
16
46
|
conversationId?: string;
|
|
17
|
-
error?: NovuError;
|
|
47
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
18
48
|
/** True until the first history fetch completes. False when there is no `conversationId` prop. */
|
|
19
49
|
isLoading: boolean;
|
|
20
|
-
|
|
50
|
+
isRunning: boolean;
|
|
51
|
+
typing?: AgentConversationRunSnapshot['typing'];
|
|
52
|
+
/** Conversation lifecycle status (`active`, etc.). */
|
|
53
|
+
status: AgentConversationStatus;
|
|
54
|
+
/** Explicit alias for `status`. */
|
|
55
|
+
conversationStatus: AgentConversationStatus;
|
|
56
|
+
/** Current agent run snapshot. */
|
|
57
|
+
run: AgentConversationRunSnapshot;
|
|
58
|
+
pagination: AgentChatPagination & {
|
|
59
|
+
fetchMore: () => Promise<{
|
|
60
|
+
data?: {
|
|
61
|
+
messages: AgentMessage[];
|
|
62
|
+
hasMore: boolean;
|
|
63
|
+
};
|
|
64
|
+
error?: NovuError;
|
|
65
|
+
}>;
|
|
66
|
+
};
|
|
67
|
+
/** True while reconnect catch-up is in flight for this conversation. */
|
|
68
|
+
isRecovering: boolean;
|
|
69
|
+
/** Set when reconnect catch-up fails. Separate from send/fetch `error`. */
|
|
70
|
+
catchUpError?: NovuError;
|
|
21
71
|
refetch: () => Promise<void>;
|
|
22
72
|
sendMessage: (text: string) => Promise<{
|
|
23
73
|
data?: SendMessageResult;
|
|
24
|
-
error?: NovuError;
|
|
74
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
75
|
+
}>;
|
|
76
|
+
respondToAction: (args: {
|
|
77
|
+
actionId: string;
|
|
78
|
+
decision: AgentToolApprovalDecision;
|
|
79
|
+
}) => Promise<{
|
|
80
|
+
data?: RespondToActionResult;
|
|
81
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
82
|
+
}>;
|
|
83
|
+
sendAction: (args: {
|
|
84
|
+
actionId: string;
|
|
85
|
+
sourceMessageId: string;
|
|
86
|
+
value?: string;
|
|
87
|
+
}) => Promise<{
|
|
88
|
+
data?: SendActionResult;
|
|
89
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
90
|
+
}>;
|
|
91
|
+
retryMessage: (messageId: string) => Promise<{
|
|
92
|
+
data?: SendMessageResult;
|
|
93
|
+
error?: NovuError | AgentChatPlanLimitError;
|
|
25
94
|
}>;
|
|
26
95
|
};
|
|
27
96
|
declare const useAgentChat: (props: UseAgentChatProps) => UseAgentChatResult;
|
|
@@ -1,146 +1,241 @@
|
|
|
1
1
|
// src/hooks/useAgentChat.ts
|
|
2
|
-
import { useCallback, useEffect, useRef,
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
|
|
3
3
|
import { useDataRef } from "./internal/useDataRef.js";
|
|
4
4
|
import { useNovu } from "./NovuProvider.js";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
var EMPTY_SERVER_SNAPSHOT = {
|
|
6
|
+
key: "ssr",
|
|
7
|
+
status: "ready",
|
|
8
|
+
run: { isRunning: false },
|
|
9
|
+
conversationStatus: "active",
|
|
10
|
+
pagination: { hasMore: false, status: "idle" },
|
|
11
|
+
messages: [],
|
|
12
|
+
pendingActions: [],
|
|
13
|
+
isRecovering: false
|
|
14
|
+
};
|
|
15
|
+
function handlePublicationCallbacks(args) {
|
|
16
|
+
const {
|
|
17
|
+
snapshot,
|
|
18
|
+
meta,
|
|
19
|
+
conversationIdProp,
|
|
20
|
+
propsRef,
|
|
21
|
+
loadNotifiedRef,
|
|
22
|
+
notifiedCatchUpErrorRef,
|
|
23
|
+
lastReportedErrorKeyRef
|
|
24
|
+
} = args;
|
|
25
|
+
if ((meta?.historyLoaded || meta?.change?.kind === "history") && !loadNotifiedRef.current && conversationIdProp) {
|
|
26
|
+
if (snapshot.conversationId) {
|
|
27
|
+
loadNotifiedRef.current = true;
|
|
28
|
+
propsRef.current.onSuccess?.({
|
|
29
|
+
conversationId: snapshot.conversationId,
|
|
30
|
+
messages: [...snapshot.messages],
|
|
31
|
+
hasMore: snapshot.pagination.hasMore
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (snapshot.catchUpError && snapshot.catchUpError !== notifiedCatchUpErrorRef.current) {
|
|
36
|
+
notifiedCatchUpErrorRef.current = snapshot.catchUpError;
|
|
37
|
+
propsRef.current.onError?.(snapshot.catchUpError);
|
|
38
|
+
} else if (!snapshot.catchUpError) {
|
|
39
|
+
notifiedCatchUpErrorRef.current = void 0;
|
|
40
|
+
}
|
|
41
|
+
if (snapshot.error) {
|
|
42
|
+
const originalMessage = "originalError" in snapshot.error ? snapshot.error.originalError?.message ?? "" : "";
|
|
43
|
+
const errorKey = `${snapshot.error.message}:${originalMessage}`;
|
|
44
|
+
if (lastReportedErrorKeyRef.current !== errorKey) {
|
|
45
|
+
lastReportedErrorKeyRef.current = errorKey;
|
|
46
|
+
propsRef.current.onError?.(snapshot.error);
|
|
47
|
+
}
|
|
48
|
+
} else {
|
|
49
|
+
lastReportedErrorKeyRef.current = void 0;
|
|
50
|
+
}
|
|
51
|
+
const change = meta?.change;
|
|
52
|
+
if (change?.kind === "live") {
|
|
53
|
+
propsRef.current.onEvent?.(change.envelope);
|
|
54
|
+
}
|
|
55
|
+
if (change && change.kind !== "history") {
|
|
56
|
+
for (const message of change.addedMessages) {
|
|
57
|
+
propsRef.current.onMessage?.(message);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (change) {
|
|
61
|
+
for (const action of change.newActions) {
|
|
62
|
+
propsRef.current.onActionRequested?.(action);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function getCreateFlowKey(agentId, agentHash) {
|
|
67
|
+
return `${agentId}\0${agentHash ?? ""}`;
|
|
68
|
+
}
|
|
69
|
+
function resolveOwnedRuntime(args) {
|
|
70
|
+
const key = getCreateFlowKey(args.agentId, args.agentHash);
|
|
71
|
+
const current = args.ownedRuntimeRef.current;
|
|
72
|
+
if (current?.key === key) {
|
|
73
|
+
return current.runtime;
|
|
8
74
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
75
|
+
current?.runtime.dispose();
|
|
76
|
+
const result = args.novu.agentChat.conversation({ agentId: args.agentId, agentHash: args.agentHash });
|
|
77
|
+
if (!result.ok) {
|
|
78
|
+
args.ownedRuntimeRef.current = null;
|
|
79
|
+
return null;
|
|
13
80
|
}
|
|
14
|
-
|
|
81
|
+
args.ownedRuntimeRef.current = { key, runtime: result.data };
|
|
82
|
+
return result.data;
|
|
15
83
|
}
|
|
16
84
|
var useAgentChat = (props) => {
|
|
17
|
-
const { agentId, conversationId: conversationIdProp } = props;
|
|
18
|
-
const propsRef = useDataRef(props);
|
|
19
85
|
const novu = useNovu();
|
|
20
|
-
const
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
const
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const [error, setError] = useState();
|
|
30
|
-
const [isLoading, setIsLoading] = useState(Boolean(conversationIdProp));
|
|
31
|
-
const [isFetching, setIsFetching] = useState(false);
|
|
32
|
-
const fetchGenerationRef = useRef(0);
|
|
33
|
-
useEffect(() => {
|
|
34
|
-
const agentChanged = prevAgentIdRef.current !== agentId;
|
|
35
|
-
const prevConversationIdProp = prevConversationIdPropRef.current;
|
|
36
|
-
prevAgentIdRef.current = agentId;
|
|
37
|
-
prevConversationIdPropRef.current = conversationIdProp;
|
|
38
|
-
if (agentChanged) {
|
|
39
|
-
setAssignedConversationId(void 0);
|
|
40
|
-
setLocalSessionKey(createLocalSessionKey());
|
|
41
|
-
setMessages([]);
|
|
42
|
-
setError(void 0);
|
|
43
|
-
setIsLoading(Boolean(conversationIdProp));
|
|
44
|
-
return;
|
|
45
|
-
}
|
|
46
|
-
if (conversationIdProp) {
|
|
47
|
-
setAssignedConversationId(void 0);
|
|
48
|
-
return;
|
|
86
|
+
const propsRef = useDataRef(props);
|
|
87
|
+
const sharedRuntime = "conversation" in props ? props.conversation : void 0;
|
|
88
|
+
const agentId = sharedRuntime?.agentId ?? props.agentId;
|
|
89
|
+
const conversationIdProp = sharedRuntime ? void 0 : props.conversationId;
|
|
90
|
+
const agentHash = sharedRuntime ? void 0 : props.agentHash;
|
|
91
|
+
const ownedRuntimeRef = useRef(null);
|
|
92
|
+
const cachedRuntime = useMemo(() => {
|
|
93
|
+
if (sharedRuntime) {
|
|
94
|
+
return sharedRuntime;
|
|
49
95
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
setAssignedConversationId(void 0);
|
|
53
|
-
setLocalSessionKey(createLocalSessionKey());
|
|
54
|
-
setMessages([]);
|
|
96
|
+
if (!conversationIdProp) {
|
|
97
|
+
return null;
|
|
55
98
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
99
|
+
const result = novu.agentChat.conversation({
|
|
100
|
+
agentId,
|
|
101
|
+
conversationId: conversationIdProp,
|
|
102
|
+
agentHash
|
|
103
|
+
});
|
|
104
|
+
return result.ok ? result.data : null;
|
|
105
|
+
}, [sharedRuntime, novu, agentId, conversationIdProp, agentHash]);
|
|
106
|
+
if (sharedRuntime || conversationIdProp) {
|
|
107
|
+
ownedRuntimeRef.current?.runtime.dispose();
|
|
108
|
+
ownedRuntimeRef.current = null;
|
|
109
|
+
}
|
|
110
|
+
const ownedRuntime = sharedRuntime || conversationIdProp ? null : resolveOwnedRuntime({ novu, agentId, agentHash, ownedRuntimeRef });
|
|
111
|
+
const runtime = sharedRuntime ?? cachedRuntime ?? ownedRuntime;
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
return () => {
|
|
114
|
+
ownedRuntimeRef.current?.runtime.dispose();
|
|
115
|
+
ownedRuntimeRef.current = null;
|
|
116
|
+
};
|
|
117
|
+
}, []);
|
|
118
|
+
const loadNotifiedRef = useRef(false);
|
|
119
|
+
const replayedActionsRef = useRef(false);
|
|
120
|
+
const notifiedCatchUpErrorRef = useRef();
|
|
121
|
+
const lastReportedErrorKeyRef = useRef();
|
|
122
|
+
useEffect(() => {
|
|
123
|
+
loadNotifiedRef.current = false;
|
|
124
|
+
replayedActionsRef.current = false;
|
|
125
|
+
notifiedCatchUpErrorRef.current = void 0;
|
|
126
|
+
lastReportedErrorKeyRef.current = void 0;
|
|
127
|
+
}, [runtime]);
|
|
128
|
+
const subscribe = useCallback(
|
|
129
|
+
(onStoreChange) => {
|
|
130
|
+
if (!runtime) {
|
|
131
|
+
return () => {
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
if (!replayedActionsRef.current) {
|
|
135
|
+
replayedActionsRef.current = true;
|
|
136
|
+
for (const action of runtime.getSnapshot().pendingActions) {
|
|
137
|
+
propsRef.current.onActionRequested?.(action);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return runtime.subscribe((snapshot2, meta) => {
|
|
141
|
+
onStoreChange();
|
|
142
|
+
handlePublicationCallbacks({
|
|
143
|
+
snapshot: snapshot2,
|
|
144
|
+
meta,
|
|
145
|
+
conversationIdProp,
|
|
146
|
+
propsRef,
|
|
147
|
+
loadNotifiedRef,
|
|
148
|
+
notifiedCatchUpErrorRef,
|
|
149
|
+
lastReportedErrorKeyRef
|
|
150
|
+
});
|
|
66
151
|
});
|
|
67
|
-
|
|
68
|
-
|
|
152
|
+
},
|
|
153
|
+
[runtime, conversationIdProp, propsRef]
|
|
154
|
+
);
|
|
155
|
+
const getSnapshot = useCallback(() => {
|
|
156
|
+
return runtime?.getSnapshot() ?? EMPTY_SERVER_SNAPSHOT;
|
|
157
|
+
}, [runtime]);
|
|
158
|
+
const getServerSnapshot = useCallback(() => {
|
|
159
|
+
return runtime?.getServerSnapshot() ?? EMPTY_SERVER_SNAPSHOT;
|
|
160
|
+
}, [runtime]);
|
|
161
|
+
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
162
|
+
const callRuntime = useCallback(
|
|
163
|
+
async (action) => {
|
|
164
|
+
if (!runtime) {
|
|
165
|
+
return { error: void 0 };
|
|
69
166
|
}
|
|
167
|
+
const response = await action(runtime);
|
|
70
168
|
if (response.error) {
|
|
71
|
-
setError(response.error);
|
|
72
169
|
propsRef.current.onError?.(response.error);
|
|
73
|
-
} else if (response.data) {
|
|
74
|
-
setMessages(response.data.messages);
|
|
75
|
-
propsRef.current.onSuccess?.(response.data);
|
|
76
170
|
}
|
|
77
|
-
|
|
78
|
-
setIsFetching(false);
|
|
171
|
+
return response;
|
|
79
172
|
},
|
|
80
|
-
[
|
|
173
|
+
[runtime, propsRef]
|
|
81
174
|
);
|
|
82
|
-
useEffect(() => {
|
|
83
|
-
const snapshot = novu.agentChat.getConversation({
|
|
84
|
-
agentId,
|
|
85
|
-
key: sessionKey,
|
|
86
|
-
conversationId: conversationIdProp
|
|
87
|
-
});
|
|
88
|
-
if (snapshot) {
|
|
89
|
-
setMessages(snapshot.messages);
|
|
90
|
-
if (snapshot.conversationId && !conversationIdProp) {
|
|
91
|
-
setAssignedConversationId(snapshot.conversationId);
|
|
92
|
-
}
|
|
93
|
-
} else if (!conversationIdProp) {
|
|
94
|
-
setMessages([]);
|
|
95
|
-
}
|
|
96
|
-
const cleanup = novu.on("agent_chat.messages.updated", ({ data }) => {
|
|
97
|
-
if (data.key !== sessionKeyRef.current) {
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
setMessages(data.messages);
|
|
101
|
-
if (data.conversationId && !propsRef.current.conversationId) {
|
|
102
|
-
setAssignedConversationId(data.conversationId);
|
|
103
|
-
}
|
|
104
|
-
});
|
|
105
|
-
if (conversationIdProp) {
|
|
106
|
-
void fetchConversation(conversationIdProp);
|
|
107
|
-
}
|
|
108
|
-
return cleanup;
|
|
109
|
-
}, [novu, agentId, conversationIdProp, sessionKey, sessionKeyRef, conversationIdRef, propsRef, fetchConversation]);
|
|
110
175
|
const refetch = useCallback(async () => {
|
|
111
|
-
|
|
112
|
-
if (!id) {
|
|
176
|
+
if (!runtime) {
|
|
113
177
|
return;
|
|
114
178
|
}
|
|
115
|
-
await
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
agentId,
|
|
122
|
-
text,
|
|
123
|
-
key: sessionKeyRef.current,
|
|
124
|
-
conversationId: conversationIdRef.current
|
|
179
|
+
const response = await runtime.load();
|
|
180
|
+
if (response.data) {
|
|
181
|
+
propsRef.current.onSuccess?.({
|
|
182
|
+
conversationId: response.data.conversationId,
|
|
183
|
+
messages: [...response.data.messages],
|
|
184
|
+
hasMore: response.data.hasMore
|
|
125
185
|
});
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
186
|
+
}
|
|
187
|
+
}, [runtime, propsRef]);
|
|
188
|
+
const fetchMore = useCallback(async () => {
|
|
189
|
+
const response = await callRuntime((target) => target.fetchMore());
|
|
190
|
+
return {
|
|
191
|
+
...response,
|
|
192
|
+
error: response.error,
|
|
193
|
+
data: response.data ? {
|
|
194
|
+
messages: [...response.data.messages],
|
|
195
|
+
hasMore: response.data.hasMore
|
|
196
|
+
} : void 0
|
|
197
|
+
};
|
|
198
|
+
}, [callRuntime]);
|
|
199
|
+
const paginationWithFetch = useMemo(
|
|
200
|
+
() => ({
|
|
201
|
+
status: snapshot.pagination.status,
|
|
202
|
+
hasMore: snapshot.pagination.hasMore,
|
|
203
|
+
fetchMore
|
|
204
|
+
}),
|
|
205
|
+
[snapshot.pagination.status, snapshot.pagination.hasMore, fetchMore]
|
|
206
|
+
);
|
|
207
|
+
const sendMessage = useCallback((text) => callRuntime((target) => target.sendMessage(text)), [callRuntime]);
|
|
208
|
+
const respondToAction = useCallback(
|
|
209
|
+
(args) => callRuntime((target) => target.respondToAction(args)),
|
|
210
|
+
[callRuntime]
|
|
211
|
+
);
|
|
212
|
+
const sendAction = useCallback(
|
|
213
|
+
(args) => callRuntime((target) => target.sendAction(args)),
|
|
214
|
+
[callRuntime]
|
|
215
|
+
);
|
|
216
|
+
const retryMessage = useCallback(
|
|
217
|
+
(messageId) => callRuntime((target) => target.retryMessage(messageId)),
|
|
218
|
+
[callRuntime]
|
|
135
219
|
);
|
|
136
220
|
return {
|
|
137
|
-
messages,
|
|
221
|
+
messages: [...snapshot.messages],
|
|
222
|
+
pendingActions: [...snapshot.pendingActions],
|
|
223
|
+
conversationId: snapshot.conversationId,
|
|
224
|
+
error: snapshot.error,
|
|
225
|
+
isLoading: snapshot.status === "loading",
|
|
226
|
+
isRunning: snapshot.run.isRunning,
|
|
227
|
+
typing: snapshot.run.typing,
|
|
228
|
+
status: snapshot.conversationStatus,
|
|
229
|
+
conversationStatus: snapshot.conversationStatus,
|
|
230
|
+
run: snapshot.run,
|
|
231
|
+
pagination: paginationWithFetch,
|
|
232
|
+
isRecovering: snapshot.isRecovering,
|
|
233
|
+
catchUpError: snapshot.catchUpError,
|
|
234
|
+
refetch,
|
|
138
235
|
sendMessage,
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
isFetching,
|
|
143
|
-
refetch
|
|
236
|
+
respondToAction,
|
|
237
|
+
sendAction,
|
|
238
|
+
retryMessage
|
|
144
239
|
};
|
|
145
240
|
};
|
|
146
241
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/hooks/useAgentChat.ts"],"sourcesContent":["import type { AgentMessage, LoadConversationResult, NovuError, SendMessageResult } from '@novu/js';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useDataRef } from './internal/useDataRef';\nimport { useNovu } from './NovuProvider';\n\nexport type UseAgentChatProps = {\n agentId: string;\n /**\n * Resume this conversation. The hook loads history on mount.\n * Omit this prop to start a new chat. The first send creates a conversation.\n * Later sends pass the returned id. Remount or clear this prop to start another chat.\n */\n conversationId?: string;\n onSuccess?: (data: LoadConversationResult) => void;\n onError?: (error: NovuError) => void;\n};\n\nexport type UseAgentChatResult = {\n messages: AgentMessage[];\n conversationId?: string;\n error?: NovuError;\n /** True until the first history fetch completes. False when there is no `conversationId` prop. */\n isLoading: boolean;\n isFetching: boolean;\n refetch: () => Promise<void>;\n sendMessage: (text: string) => Promise<{\n data?: SendMessageResult;\n error?: NovuError;\n }>;\n};\n\nfunction createLocalSessionKey(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return `local_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;\n }\n\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(6);\n crypto.getRandomValues(bytes);\n\n return `local_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;\n }\n\n return `local_${Date.now().toString(36)}`;\n}\n\nexport const useAgentChat = (props: UseAgentChatProps): UseAgentChatResult => {\n const { agentId, conversationId: conversationIdProp } = props;\n const propsRef = useDataRef(props);\n const novu = useNovu();\n\n // Resume: the prop is the key on the same render (no effect lag).\n // Create: keep a `local_*` key until remount, prop clear, or agent change.\n const [localSessionKey, setLocalSessionKey] = useState(createLocalSessionKey);\n const sessionKey = conversationIdProp ?? localSessionKey;\n const sessionKeyRef = useDataRef(sessionKey);\n const prevAgentIdRef = useRef(agentId);\n const prevConversationIdPropRef = useRef(conversationIdProp);\n\n const [assignedConversationId, setAssignedConversationId] = useState<string>();\n const conversationId = conversationIdProp ?? assignedConversationId;\n const conversationIdRef = useDataRef(conversationId);\n\n const [messages, setMessages] = useState<AgentMessage[]>([]);\n const [error, setError] = useState<NovuError>();\n const [isLoading, setIsLoading] = useState(Boolean(conversationIdProp));\n const [isFetching, setIsFetching] = useState(false);\n const fetchGenerationRef = useRef(0);\n\n useEffect(() => {\n const agentChanged = prevAgentIdRef.current !== agentId;\n const prevConversationIdProp = prevConversationIdPropRef.current;\n prevAgentIdRef.current = agentId;\n prevConversationIdPropRef.current = conversationIdProp;\n\n if (agentChanged) {\n setAssignedConversationId(undefined);\n setLocalSessionKey(createLocalSessionKey());\n setMessages([]);\n setError(undefined);\n setIsLoading(Boolean(conversationIdProp));\n\n return;\n }\n\n if (conversationIdProp) {\n setAssignedConversationId(undefined);\n\n return;\n }\n\n setIsLoading(false);\n if (prevConversationIdProp !== undefined) {\n setAssignedConversationId(undefined);\n setLocalSessionKey(createLocalSessionKey());\n setMessages([]);\n }\n }, [agentId, conversationIdProp]);\n\n const fetchConversation = useCallback(\n async (targetConversationId: string) => {\n const generation = ++fetchGenerationRef.current;\n setError(undefined);\n setIsLoading(true);\n setIsFetching(true);\n\n const response = await novu.agentChat.loadConversation({\n agentId,\n conversationId: targetConversationId,\n });\n\n if (generation !== fetchGenerationRef.current) {\n return;\n }\n\n if (response.error) {\n setError(response.error);\n propsRef.current.onError?.(response.error);\n } else if (response.data) {\n setMessages(response.data.messages);\n propsRef.current.onSuccess?.(response.data);\n }\n\n setIsLoading(false);\n setIsFetching(false);\n },\n [novu, agentId, propsRef]\n );\n\n useEffect(() => {\n const snapshot = novu.agentChat.getConversation({\n agentId,\n key: sessionKey,\n conversationId: conversationIdProp,\n });\n if (snapshot) {\n setMessages(snapshot.messages);\n if (snapshot.conversationId && !conversationIdProp) {\n setAssignedConversationId(snapshot.conversationId);\n }\n } else if (!conversationIdProp) {\n setMessages([]);\n }\n\n const cleanup = novu.on('agent_chat.messages.updated', ({ data }) => {\n if (data.key !== sessionKeyRef.current) {\n return;\n }\n\n setMessages(data.messages);\n if (data.conversationId && !propsRef.current.conversationId) {\n setAssignedConversationId(data.conversationId);\n }\n });\n\n if (conversationIdProp) {\n void fetchConversation(conversationIdProp);\n }\n\n return cleanup;\n }, [novu, agentId, conversationIdProp, sessionKey, sessionKeyRef, conversationIdRef, propsRef, fetchConversation]);\n\n const refetch = useCallback(async () => {\n const id = conversationIdRef.current;\n if (!id) {\n return;\n }\n\n await fetchConversation(id);\n }, [conversationIdRef, fetchConversation]);\n\n const sendMessage = useCallback(\n async (text: string) => {\n setError(undefined);\n\n const response = await novu.agentChat.sendMessage({\n agentId,\n text,\n key: sessionKeyRef.current,\n conversationId: conversationIdRef.current,\n });\n\n if (response.error) {\n setError(response.error);\n propsRef.current.onError?.(response.error);\n } else if (response.data && !propsRef.current.conversationId) {\n setAssignedConversationId(response.data.conversationId);\n }\n\n return response;\n },\n [novu, agentId, sessionKeyRef, conversationIdRef, propsRef]\n );\n\n return {\n messages,\n sendMessage,\n conversationId,\n error,\n isLoading,\n isFetching,\n refetch,\n };\n};\n"],"mappings":";AACA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AA4BxB,SAAS,wBAAgC;AACvC,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,YAAY;AAC5E,WAAO,SAAS,OAAO,WAAW,EAAE,QAAQ,MAAM,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAAA,EACpE;AAEA,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,oBAAoB,YAAY;AACjF,UAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,WAAO,gBAAgB,KAAK;AAE5B,WAAO,SAAS,MAAM,KAAK,OAAO,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC;AAAA,EAC1F;AAEA,SAAO,SAAS,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;AACzC;AAEO,IAAM,eAAe,CAAC,UAAiD;AAC5E,QAAM,EAAE,SAAS,gBAAgB,mBAAmB,IAAI;AACxD,QAAM,WAAW,WAAW,KAAK;AACjC,QAAM,OAAO,QAAQ;AAIrB,QAAM,C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,UAAM,kBAAkB,EAAE;AAAA,EAC5B,GAAG,CAAC,mBAAmB,iBAAiB,CAAC;AAEzC,QAAM,cAAc;AAAA,IAClB,OAAO,SAAiB;AACtB,eAAS,MAAS;AAElB,YAAM,WAAW,MAAM,KAAK,UAAU,YAAY;AAAA,QAChD;AAAA,QACA;AAAA,QACA,KAAK,cAAc;AAAA,QACnB,gBAAgB,kBAAkB;AAAA,MACpC,CAAC;AAED,UAAI,SAAS,OAAO;AAClB,iBAAS,SAAS,KAAK;AACvB,iBAAS,QAAQ,UAAU,SAAS,KAAK;AAAA,MAC3C,WAAW,SAAS,QAAQ,CAAC,SAAS,QAAQ,gBAAgB;AAC5D,kCAA0B,SAAS,KAAK,cAAc;AAAA,MACxD;AAEA,aAAO;AAAA,IACT;AAAA,IACA,CAAC,MAAM,SAAS,eAAe,mBAAmB,QAAQ;AAAA,EAC5D;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/hooks/useAgentChat.ts"],"sourcesContent":["import type {\n AgentChatPagination,\n AgentChatPlanLimitError,\n AgentConversationPublicationMeta,\n AgentConversationRunSnapshot,\n AgentConversationRuntime,\n AgentConversationSnapshot,\n AgentConversationStatus,\n AgentEventEnvelope,\n AgentHashFields,\n AgentMessage,\n AgentPendingAction,\n AgentToolApprovalDecision,\n LoadConversationResult,\n NovuError,\n RespondToActionResult,\n SendActionResult,\n SendMessageResult,\n} from '@novu/js';\nimport { type MutableRefObject, useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { useDataRef } from './internal/useDataRef';\nimport { useNovu } from './NovuProvider';\n\ntype UseAgentChatCallbacks = {\n onSuccess?: (data: LoadConversationResult) => void;\n onError?: (error: NovuError | AgentChatPlanLimitError) => void;\n /**\n * Fires once per message, when the message id first appears on the conversation.\n * History pages are silent: only new activity fires.\n * An agent message can still be empty at this point, because the first envelope of a\n * turn creates the message before any text is folded into it.\n * A send that never reaches the server does not fire: the message flips to `failed` instead.\n */\n onMessage?: (message: AgentMessage) => void;\n /**\n * Fires once per pending action, including actions still pending on mount, so a\n * resumed conversation reports what it is blocked on. Paging backwards is silent.\n */\n onActionRequested?: (action: AgentPendingAction) => void;\n /**\n * Raw envelopes for this conversation, before the derived callbacks for the same fold.\n * A duplicate envelope that the store drops does not fire. Neither does an envelope that\n * arrives before a newly created conversation claims its id.\n * The store folds the envelope before this callback runs, so `messages` here is one render old.\n */\n onEvent?: (envelope: AgentEventEnvelope) => void;\n};\n\nexport type UseAgentChatProps = UseAgentChatCallbacks &\n AgentHashFields &\n (\n | {\n agentId: string;\n /**\n * Resume this conversation. The hook loads history on mount.\n * Omit this prop to start a new chat. The first send creates a conversation.\n * Later sends pass the returned id. Remount or clear this prop to start another chat.\n */\n conversationId?: string;\n conversation?: never;\n }\n | {\n /** Share an existing conversation runtime across multiple hook instances. */\n conversation: AgentConversationRuntime;\n agentId?: never;\n conversationId?: never;\n agentHash?: never;\n }\n );\n\nexport type UseAgentChatResult = {\n messages: AgentMessage[];\n pendingActions: AgentPendingAction[];\n conversationId?: string;\n error?: NovuError | AgentChatPlanLimitError;\n /** True until the first history fetch completes. False when there is no `conversationId` prop. */\n isLoading: boolean;\n isRunning: boolean;\n typing?: AgentConversationRunSnapshot['typing'];\n /** Conversation lifecycle status (`active`, etc.). */\n status: AgentConversationStatus;\n /** Explicit alias for `status`. */\n conversationStatus: AgentConversationStatus;\n /** Current agent run snapshot. */\n run: AgentConversationRunSnapshot;\n pagination: AgentChatPagination & {\n fetchMore: () => Promise<{\n data?: { messages: AgentMessage[]; hasMore: boolean };\n error?: NovuError;\n }>;\n };\n /** True while reconnect catch-up is in flight for this conversation. */\n isRecovering: boolean;\n /** Set when reconnect catch-up fails. Separate from send/fetch `error`. */\n catchUpError?: NovuError;\n refetch: () => Promise<void>;\n sendMessage: (text: string) => Promise<{\n data?: SendMessageResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n respondToAction: (args: { actionId: string; decision: AgentToolApprovalDecision }) => Promise<{\n data?: RespondToActionResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n sendAction: (args: { actionId: string; sourceMessageId: string; value?: string }) => Promise<{\n data?: SendActionResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n retryMessage: (messageId: string) => Promise<{\n data?: SendMessageResult;\n error?: NovuError | AgentChatPlanLimitError;\n }>;\n};\n\nconst EMPTY_SERVER_SNAPSHOT: AgentConversationSnapshot = {\n key: 'ssr',\n status: 'ready',\n run: { isRunning: false },\n conversationStatus: 'active',\n pagination: { hasMore: false, status: 'idle' },\n messages: [],\n pendingActions: [],\n isRecovering: false,\n};\n\ntype RuntimeActionResult<T> = {\n data?: T;\n error?: NovuError | AgentChatPlanLimitError;\n};\n\nfunction handlePublicationCallbacks(args: {\n snapshot: AgentConversationSnapshot;\n meta: AgentConversationPublicationMeta | undefined;\n conversationIdProp: string | undefined;\n propsRef: ReturnType<typeof useDataRef<UseAgentChatProps>>;\n loadNotifiedRef: MutableRefObject<boolean>;\n notifiedCatchUpErrorRef: MutableRefObject<NovuError | undefined>;\n lastReportedErrorKeyRef: MutableRefObject<string | undefined>;\n}): void {\n const {\n snapshot,\n meta,\n conversationIdProp,\n propsRef,\n loadNotifiedRef,\n notifiedCatchUpErrorRef,\n lastReportedErrorKeyRef,\n } = args;\n\n if ((meta?.historyLoaded || meta?.change?.kind === 'history') && !loadNotifiedRef.current && conversationIdProp) {\n if (snapshot.conversationId) {\n loadNotifiedRef.current = true;\n propsRef.current.onSuccess?.({\n conversationId: snapshot.conversationId,\n messages: [...snapshot.messages],\n hasMore: snapshot.pagination.hasMore,\n });\n }\n }\n\n if (snapshot.catchUpError && snapshot.catchUpError !== notifiedCatchUpErrorRef.current) {\n notifiedCatchUpErrorRef.current = snapshot.catchUpError;\n propsRef.current.onError?.(snapshot.catchUpError);\n } else if (!snapshot.catchUpError) {\n notifiedCatchUpErrorRef.current = undefined;\n }\n\n if (snapshot.error) {\n const originalMessage = 'originalError' in snapshot.error ? (snapshot.error.originalError?.message ?? '') : '';\n const errorKey = `${snapshot.error.message}:${originalMessage}`;\n if (lastReportedErrorKeyRef.current !== errorKey) {\n lastReportedErrorKeyRef.current = errorKey;\n propsRef.current.onError?.(snapshot.error as NovuError | AgentChatPlanLimitError);\n }\n } else {\n lastReportedErrorKeyRef.current = undefined;\n }\n\n const change = meta?.change;\n if (change?.kind === 'live') {\n propsRef.current.onEvent?.(change.envelope);\n }\n\n if (change && change.kind !== 'history') {\n for (const message of change.addedMessages) {\n propsRef.current.onMessage?.(message);\n }\n }\n\n if (change) {\n for (const action of change.newActions) {\n propsRef.current.onActionRequested?.(action);\n }\n }\n}\n\ntype OwnedRuntimeEntry = {\n key: string;\n runtime: AgentConversationRuntime;\n};\n\nfunction getCreateFlowKey(agentId: string, agentHash?: string): string {\n return `${agentId}\\0${agentHash ?? ''}`;\n}\n\nfunction resolveOwnedRuntime(args: {\n novu: ReturnType<typeof useNovu>;\n agentId: string;\n agentHash?: string;\n ownedRuntimeRef: MutableRefObject<OwnedRuntimeEntry | null>;\n}): AgentConversationRuntime | null {\n const key = getCreateFlowKey(args.agentId, args.agentHash);\n const current = args.ownedRuntimeRef.current;\n\n if (current?.key === key) {\n return current.runtime;\n }\n\n current?.runtime.dispose();\n\n const result = args.novu.agentChat.conversation({ agentId: args.agentId, agentHash: args.agentHash });\n if (!result.ok) {\n args.ownedRuntimeRef.current = null;\n return null;\n }\n\n args.ownedRuntimeRef.current = { key, runtime: result.data };\n return result.data;\n}\n\nexport const useAgentChat = (props: UseAgentChatProps): UseAgentChatResult => {\n const novu = useNovu();\n const propsRef = useDataRef(props);\n\n const sharedRuntime = 'conversation' in props ? props.conversation : undefined;\n const agentId = sharedRuntime?.agentId ?? props.agentId!;\n const conversationIdProp = sharedRuntime ? undefined : props.conversationId;\n const agentHash = sharedRuntime ? undefined : props.agentHash;\n\n const ownedRuntimeRef = useRef<OwnedRuntimeEntry | null>(null);\n\n const cachedRuntime = useMemo(() => {\n if (sharedRuntime) {\n return sharedRuntime;\n }\n\n if (!conversationIdProp) {\n return null;\n }\n\n const result = novu.agentChat.conversation({\n agentId,\n conversationId: conversationIdProp,\n agentHash,\n });\n\n return result.ok ? result.data : null;\n }, [sharedRuntime, novu, agentId, conversationIdProp, agentHash]);\n\n if (sharedRuntime || conversationIdProp) {\n ownedRuntimeRef.current?.runtime.dispose();\n ownedRuntimeRef.current = null;\n }\n\n const ownedRuntime =\n sharedRuntime || conversationIdProp ? null : resolveOwnedRuntime({ novu, agentId, agentHash, ownedRuntimeRef });\n\n const runtime = sharedRuntime ?? cachedRuntime ?? ownedRuntime;\n\n useEffect(() => {\n return () => {\n ownedRuntimeRef.current?.runtime.dispose();\n ownedRuntimeRef.current = null;\n };\n }, []);\n\n const loadNotifiedRef = useRef(false);\n const replayedActionsRef = useRef(false);\n const notifiedCatchUpErrorRef = useRef<NovuError | undefined>();\n const lastReportedErrorKeyRef = useRef<string>();\n\n useEffect(() => {\n loadNotifiedRef.current = false;\n replayedActionsRef.current = false;\n notifiedCatchUpErrorRef.current = undefined;\n lastReportedErrorKeyRef.current = undefined;\n }, [runtime]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!runtime) {\n return () => {};\n }\n\n if (!replayedActionsRef.current) {\n replayedActionsRef.current = true;\n for (const action of runtime.getSnapshot().pendingActions) {\n propsRef.current.onActionRequested?.(action);\n }\n }\n\n return runtime.subscribe((snapshot, meta) => {\n onStoreChange();\n handlePublicationCallbacks({\n snapshot,\n meta,\n conversationIdProp,\n propsRef,\n loadNotifiedRef,\n notifiedCatchUpErrorRef,\n lastReportedErrorKeyRef,\n });\n });\n },\n [runtime, conversationIdProp, propsRef]\n );\n\n const getSnapshot = useCallback(() => {\n return runtime?.getSnapshot() ?? EMPTY_SERVER_SNAPSHOT;\n }, [runtime]);\n\n const getServerSnapshot = useCallback(() => {\n return runtime?.getServerSnapshot() ?? EMPTY_SERVER_SNAPSHOT;\n }, [runtime]);\n\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n const callRuntime = useCallback(\n async <T>(action: (target: AgentConversationRuntime) => Promise<RuntimeActionResult<T>>) => {\n if (!runtime) {\n return { error: undefined };\n }\n\n const response = await action(runtime);\n if (response.error) {\n propsRef.current.onError?.(response.error);\n }\n\n return response;\n },\n [runtime, propsRef]\n );\n\n const refetch = useCallback(async () => {\n if (!runtime) {\n return;\n }\n\n const response = await runtime.load();\n if (response.data) {\n propsRef.current.onSuccess?.({\n conversationId: response.data.conversationId,\n messages: [...response.data.messages],\n hasMore: response.data.hasMore,\n });\n }\n }, [runtime, propsRef]);\n\n const fetchMore = useCallback(async () => {\n const response = await callRuntime((target) => target.fetchMore());\n\n return {\n ...response,\n error: response.error as NovuError | undefined,\n data: response.data\n ? {\n messages: [...response.data.messages],\n hasMore: response.data.hasMore,\n }\n : undefined,\n };\n }, [callRuntime]);\n\n const paginationWithFetch = useMemo(\n () => ({\n status: snapshot.pagination.status,\n hasMore: snapshot.pagination.hasMore,\n fetchMore,\n }),\n [snapshot.pagination.status, snapshot.pagination.hasMore, fetchMore]\n );\n\n const sendMessage = useCallback((text: string) => callRuntime((target) => target.sendMessage(text)), [callRuntime]);\n const respondToAction = useCallback(\n (args: { actionId: string; decision: AgentToolApprovalDecision }) =>\n callRuntime((target) => target.respondToAction(args)),\n [callRuntime]\n );\n const sendAction = useCallback(\n (args: { actionId: string; sourceMessageId: string; value?: string }) =>\n callRuntime((target) => target.sendAction(args)),\n [callRuntime]\n );\n const retryMessage = useCallback(\n (messageId: string) => callRuntime((target) => target.retryMessage(messageId)),\n [callRuntime]\n );\n\n return {\n messages: [...snapshot.messages],\n pendingActions: [...snapshot.pendingActions],\n conversationId: snapshot.conversationId,\n error: snapshot.error as UseAgentChatResult['error'],\n isLoading: snapshot.status === 'loading',\n isRunning: snapshot.run.isRunning,\n typing: snapshot.run.typing,\n status: snapshot.conversationStatus,\n conversationStatus: snapshot.conversationStatus,\n run: snapshot.run,\n pagination: paginationWithFetch,\n isRecovering: snapshot.isRecovering,\n catchUpError: snapshot.catchUpError,\n refetch,\n sendMessage,\n respondToAction,\n sendAction,\n retryMessage,\n };\n};\n"],"mappings":";AAmBA,SAAgC,aAAa,WAAW,SAAS,QAAQ,4BAA4B;AACrG,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AA6FxB,IAAM,wBAAmD;AAAA,EACvD,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,KAAK,EAAE,WAAW,MAAM;AAAA,EACxB,oBAAoB;AAAA,EACpB,YAAY,EAAE,SAAS,OAAO,QAAQ,OAAO;AAAA,EAC7C,UAAU,CAAC;AAAA,EACX,gBAAgB,CAAC;AAAA,EACjB,cAAc;AAChB;AAOA,SAAS,2BAA2B,MAQ3B;AACP,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,OAAK,MAAM,iBAAiB,MAAM,QAAQ,SAAS,cAAc,CAAC,gBAAgB,WAAW,oBAAoB;AAC/G,QAAI,SAAS,gBAAgB;AAC3B,sBAAgB,UAAU;AAC1B,eAAS,QAAQ,YAAY;AAAA,QAC3B,gBAAgB,SAAS;AAAA,QACzB,UAAU,CAAC,GAAG,SAAS,QAAQ;AAAA,QAC/B,SAAS,SAAS,WAAW;AAAA,MAC/B,CAAC;AAAA,IACH;AAAA,EACF;AAEA,MAAI,SAAS,gBAAgB,SAAS,iBAAiB,wBAAwB,SAAS;AACtF,4BAAwB,UAAU,SAAS;AAC3C,aAAS,QAAQ,UAAU,SAAS,YAAY;AAAA,EAClD,WAAW,CAAC,SAAS,cAAc;AACjC,4BAAwB,UAAU;AAAA,EACpC;AAEA,MAAI,SAAS,OAAO;AAClB,UAAM,kBAAkB,mBAAmB,SAAS,QAAS,SAAS,MAAM,eAAe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,SAAS,IAAI;AAAA,IACrB,QAAQ,SAAS;AAAA,IACjB,oBAAoB,SAAS;AAAA,IAC7B,KAAK,SAAS;AAAA,IACd,YAAY;AAAA,IACZ,cAAc,SAAS;AAAA,IACvB,cAAc,SAAS;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["snapshot"]}
|
package/dist/esm/server/index.js
CHANGED
|
@@ -44,10 +44,25 @@ function useNovu() {
|
|
|
44
44
|
function useAgentChat(_) {
|
|
45
45
|
return {
|
|
46
46
|
messages: [],
|
|
47
|
+
pendingActions: [],
|
|
47
48
|
isLoading: false,
|
|
48
|
-
|
|
49
|
+
isRunning: false,
|
|
50
|
+
typing: void 0,
|
|
51
|
+
status: "active",
|
|
52
|
+
conversationStatus: "active",
|
|
53
|
+
run: { isRunning: false },
|
|
54
|
+
pagination: {
|
|
55
|
+
status: "idle",
|
|
56
|
+
hasMore: false,
|
|
57
|
+
fetchMore: () => Promise.resolve({ data: void 0, error: void 0 })
|
|
58
|
+
},
|
|
59
|
+
isRecovering: false,
|
|
60
|
+
catchUpError: void 0,
|
|
49
61
|
refetch: () => Promise.resolve(),
|
|
50
|
-
sendMessage: () => Promise.resolve({ data: void 0, error: void 0 })
|
|
62
|
+
sendMessage: () => Promise.resolve({ data: void 0, error: void 0 }),
|
|
63
|
+
respondToAction: () => Promise.resolve({ data: void 0, error: void 0 }),
|
|
64
|
+
sendAction: () => Promise.resolve({ data: void 0, error: void 0 }),
|
|
65
|
+
retryMessage: () => Promise.resolve({ data: void 0, error: void 0 })
|
|
51
66
|
};
|
|
52
67
|
}
|
|
53
68
|
function useCounts(_) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/index.tsx"],"sourcesContent":["import type { InboxProps } from '../components/Inbox';\nimport { ShadowRootDetector } from '../components/ShadowRootDetector';\nimport type {\n UseAgentChatProps,\n UseAgentChatResult,\n UseCreateSubscriptionProps,\n UseCreateSubscriptionResult,\n UseNotificationsProps,\n UseNotificationsResult,\n UsePreferencesProps,\n UsePreferencesResult,\n UseRemoveSubscriptionProps,\n UseRemoveSubscriptionResult,\n UseScheduleProps,\n UseScheduleResult,\n UseSubscriptionProps,\n UseSubscriptionResult,\n UseSubscriptionsProps,\n UseSubscriptionsResult,\n UseUpdateSubscriptionProps,\n UseUpdateSubscriptionResult,\n} from '../hooks';\nimport type { NovuProviderProps } from '../hooks/NovuProvider';\nimport type { UseCountsProps, UseCountsResult } from '../hooks/useCounts';\n\n/**\n * Exporting all components from the components folder\n * as empty functions to fix build errors in SSR\n * This will be replaced with actual components\n * when we implement the SSR components in @novu/js/ui\n */\nexport function Inbox(props: InboxProps) {\n return <ShadowRootDetector />;\n}\n\nexport function InboxContent() {}\n\nexport function Notifications() {}\n\nexport function Preferences() {}\n\nexport function Bell() {}\n\nexport function NovuProvider(props: NovuProviderProps) {\n return <>{props.children}</>;\n}\n\nexport function Subscription() {\n return <ShadowRootDetector />;\n}\n\nexport function SubscriptionButton() {}\n\nexport function SubscriptionPreferences() {}\n\nexport function SlackConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function SlackLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function TelegramConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function useNovu() {\n return null;\n}\n\nexport function useAgentChat(_: UseAgentChatProps): UseAgentChatResult {\n return {\n messages: [],\n isLoading: false,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/server/index.tsx"],"sourcesContent":["import type { InboxProps } from '../components/Inbox';\nimport { ShadowRootDetector } from '../components/ShadowRootDetector';\nimport type {\n UseAgentChatProps,\n UseAgentChatResult,\n UseCreateSubscriptionProps,\n UseCreateSubscriptionResult,\n UseNotificationsProps,\n UseNotificationsResult,\n UsePreferencesProps,\n UsePreferencesResult,\n UseRemoveSubscriptionProps,\n UseRemoveSubscriptionResult,\n UseScheduleProps,\n UseScheduleResult,\n UseSubscriptionProps,\n UseSubscriptionResult,\n UseSubscriptionsProps,\n UseSubscriptionsResult,\n UseUpdateSubscriptionProps,\n UseUpdateSubscriptionResult,\n} from '../hooks';\nimport type { NovuProviderProps } from '../hooks/NovuProvider';\nimport type { UseCountsProps, UseCountsResult } from '../hooks/useCounts';\n\n/**\n * Exporting all components from the components folder\n * as empty functions to fix build errors in SSR\n * This will be replaced with actual components\n * when we implement the SSR components in @novu/js/ui\n */\nexport function Inbox(props: InboxProps) {\n return <ShadowRootDetector />;\n}\n\nexport function InboxContent() {}\n\nexport function Notifications() {}\n\nexport function Preferences() {}\n\nexport function Bell() {}\n\nexport function NovuProvider(props: NovuProviderProps) {\n return <>{props.children}</>;\n}\n\nexport function Subscription() {\n return <ShadowRootDetector />;\n}\n\nexport function SubscriptionButton() {}\n\nexport function SubscriptionPreferences() {}\n\nexport function SlackConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function SlackLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function MsTeamsLinkUser() {\n return <ShadowRootDetector />;\n}\n\nexport function TelegramConnectButton() {\n return <ShadowRootDetector />;\n}\n\nexport function useNovu() {\n return null;\n}\n\nexport function useAgentChat(_: UseAgentChatProps): UseAgentChatResult {\n return {\n messages: [],\n pendingActions: [],\n isLoading: false,\n isRunning: false,\n typing: undefined,\n status: 'active',\n conversationStatus: 'active',\n run: { isRunning: false },\n pagination: {\n status: 'idle',\n hasMore: false,\n fetchMore: () => Promise.resolve({ data: undefined, error: undefined }),\n },\n isRecovering: false,\n catchUpError: undefined,\n refetch: () => Promise.resolve(),\n sendMessage: () => Promise.resolve({ data: undefined, error: undefined }),\n respondToAction: () => Promise.resolve({ data: undefined, error: undefined }),\n sendAction: () => Promise.resolve({ data: undefined, error: undefined }),\n retryMessage: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useCounts(_: UseCountsProps): UseCountsResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useNotifications(_: UseNotificationsProps): UseNotificationsResult {\n return {\n isLoading: false,\n isFetching: false,\n hasMore: false,\n readAll: () => Promise.resolve({ data: undefined, error: undefined }),\n seenAll: () => Promise.resolve({ data: undefined, error: undefined }),\n archiveAll: () => Promise.resolve({ data: undefined, error: undefined }),\n archiveAllRead: () => Promise.resolve({ data: undefined, error: undefined }),\n refetch: () => Promise.resolve(),\n fetchMore: () => Promise.resolve(),\n };\n}\n\nexport function usePreferences(_: UsePreferencesProps): UsePreferencesResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useSchedule(_: UseScheduleProps): UseScheduleResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useSubscription(_: UseSubscriptionProps): UseSubscriptionResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport function useCreateSubscription(_: UseCreateSubscriptionProps = {}): UseCreateSubscriptionResult {\n return {\n isCreating: false,\n error: undefined,\n create: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useUpdateSubscription(_: UseUpdateSubscriptionProps = {}): UseUpdateSubscriptionResult {\n return {\n isUpdating: false,\n error: undefined,\n update: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useRemoveSubscription(_: UseRemoveSubscriptionProps = {}): UseRemoveSubscriptionResult {\n return {\n isRemoving: false,\n error: undefined,\n remove: () => Promise.resolve({ data: undefined, error: undefined }),\n };\n}\n\nexport function useSubscriptions(_: UseSubscriptionsProps): UseSubscriptionsResult {\n return {\n isLoading: false,\n isFetching: false,\n refetch: () => Promise.resolve(),\n };\n}\n\nexport type * from '@novu/js';\nexport { PreferenceLevel, SeverityLevelEnum, WorkflowCriticalityEnum } from '@novu/js';\n\nexport type {\n AllLocalization,\n AllLocalizationKey,\n ElementStyles,\n InboxAppearance,\n InboxAppearanceCallback,\n InboxAppearanceCallbackFunction,\n InboxAppearanceCallbackKeys,\n InboxAppearanceKey,\n InboxElements,\n InboxLocalization,\n InboxLocalizationKey,\n InboxTheme,\n NotificationActionClickHandler,\n NotificationClickHandler,\n NotificationRenderer,\n PreferenceGroups,\n PreferencesFilter,\n RouterPush,\n SubscriptionAppearance,\n SubscriptionAppearanceCallback,\n SubscriptionAppearanceCallbackFunction,\n SubscriptionAppearanceCallbackKeys,\n SubscriptionAppearanceKey,\n SubscriptionElements,\n SubscriptionLocalization,\n SubscriptionLocalizationKey,\n SubscriptionTheme,\n Tab,\n Variables,\n} from '@novu/js/ui';\n\nexport type { BellProps, InboxContentProps, InboxProps, NotificationProps, NovuProviderProps } from '../components';\n\nexport type {\n UseAgentChatProps,\n UseAgentChatResult,\n UseCountsProps,\n UseCountsResult,\n UseNotificationsProps,\n UseNotificationsResult,\n UsePreferencesResult,\n UseScheduleProps as UsePreferencesProps,\n} from '../hooks';\n\nexport type {\n BaseProps,\n BellRenderer,\n BodyRenderer,\n DefaultInboxProps,\n DefaultProps,\n NoRendererProps,\n NotificationRendererProps,\n NotificationsRenderer,\n SubjectBodyRendererProps,\n SubjectRenderer,\n WithChildrenProps,\n} from '../utils/types';\n"],"mappings":";AACA,SAAS,0BAA0B;AAsLnC,SAAS,iBAAiB,mBAAmB,+BAA+B;AAvJnE,SAYA,UAZA;AADF,SAAS,MAAM,OAAmB;AACvC,SAAO,oBAAC,sBAAmB;AAC7B;AAEO,SAAS,eAAe;AAAC;AAEzB,SAAS,gBAAgB;AAAC;AAE1B,SAAS,cAAc;AAAC;AAExB,SAAS,OAAO;AAAC;AAEjB,SAAS,aAAa,OAA0B;AACrD,SAAO,gCAAG,gBAAM,UAAS;AAC3B;AAEO,SAAS,eAAe;AAC7B,SAAO,oBAAC,sBAAmB;AAC7B;AAEO,SAA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SAAS,sBAAsB,IAAgC,CAAC,GAAgC;AACrG,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,QAAQ,MAAM,QAAQ,QAAQ,EAAE,MAAM,QAAW,OAAO,OAAU,CAAC;AAAA,EACrE;AACF;AAEO,SAAS,iBAAiB,GAAkD;AACjF,SAAO;AAAA,IACL,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,SAAS,MAAM,QAAQ,QAAQ;AAAA,EACjC;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@novu/react",
|
|
3
|
-
"version": "3.19.
|
|
3
|
+
"version": "3.19.1-rc.852194fa77",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/novuhq/novu",
|
|
@@ -121,7 +121,7 @@
|
|
|
121
121
|
}
|
|
122
122
|
},
|
|
123
123
|
"dependencies": {
|
|
124
|
-
"@novu/js": "3.19.
|
|
124
|
+
"@novu/js": "3.19.1-rc.852194fa77"
|
|
125
125
|
},
|
|
126
126
|
"nx": {
|
|
127
127
|
"tags": [
|