@memori.ai/memori-react 8.43.0 → 8.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/components/Avatar/AvatarView/AvatarComponent/constants.d.ts +1 -1
  3. package/dist/components/Avatar/AvatarView/AvatarComponent/constants.js +1 -1
  4. package/dist/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js +1 -0
  5. package/dist/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js.map +1 -1
  6. package/dist/components/MemoriArtifactSystem/components/ArtifactHandler/ArtifactHandler.js +204 -59
  7. package/dist/components/MemoriArtifactSystem/components/ArtifactHandler/ArtifactHandler.js.map +1 -1
  8. package/dist/components/MemoriArtifactSystem/context/ArtifactContext.d.ts +3 -1
  9. package/dist/components/MemoriArtifactSystem/context/ArtifactContext.js +76 -16
  10. package/dist/components/MemoriArtifactSystem/context/ArtifactContext.js.map +1 -1
  11. package/dist/components/MemoriArtifactSystem/types/artifact.types.d.ts +11 -0
  12. package/dist/components/MemoriArtifactSystem/utils/ArtifactAPI.js +18 -13
  13. package/dist/components/MemoriArtifactSystem/utils/ArtifactAPI.js.map +1 -1
  14. package/dist/components/MemoriArtifactSystem/utils/applyEdits.d.ts +8 -0
  15. package/dist/components/MemoriArtifactSystem/utils/applyEdits.js +117 -0
  16. package/dist/components/MemoriArtifactSystem/utils/applyEdits.js.map +1 -0
  17. package/dist/components/MemoriWidget/MemoriWidget.d.ts +1 -0
  18. package/dist/components/MemoriWidget/MemoriWidget.js +59 -1
  19. package/dist/components/MemoriWidget/MemoriWidget.js.map +1 -1
  20. package/dist/helpers/message.js +3 -0
  21. package/dist/helpers/message.js.map +1 -1
  22. package/dist/helpers/nats/getNatsConfig.d.ts +1 -1
  23. package/dist/helpers/nats/getNatsConfig.js +2 -2
  24. package/dist/helpers/nats/getNatsConfig.js.map +1 -1
  25. package/dist/helpers/nats/useNats.d.ts +2 -1
  26. package/dist/helpers/nats/useNats.js +87 -20
  27. package/dist/helpers/nats/useNats.js.map +1 -1
  28. package/dist/helpers/nats/useNatsSession.d.ts +6 -1
  29. package/dist/helpers/nats/useNatsSession.js +49 -8
  30. package/dist/helpers/nats/useNatsSession.js.map +1 -1
  31. package/dist/locales/de.json +3 -0
  32. package/dist/locales/en.json +3 -0
  33. package/dist/locales/es.json +3 -0
  34. package/dist/locales/fr.json +3 -0
  35. package/dist/locales/it.json +3 -0
  36. package/dist/version.d.ts +1 -1
  37. package/dist/version.js +1 -1
  38. package/esm/components/Avatar/AvatarView/AvatarComponent/constants.d.ts +1 -1
  39. package/esm/components/Avatar/AvatarView/AvatarComponent/constants.js +1 -1
  40. package/esm/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js +1 -0
  41. package/esm/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js.map +1 -1
  42. package/esm/components/MemoriArtifactSystem/components/ArtifactHandler/ArtifactHandler.js +205 -60
  43. package/esm/components/MemoriArtifactSystem/components/ArtifactHandler/ArtifactHandler.js.map +1 -1
  44. package/esm/components/MemoriArtifactSystem/context/ArtifactContext.d.ts +3 -1
  45. package/esm/components/MemoriArtifactSystem/context/ArtifactContext.js +77 -17
  46. package/esm/components/MemoriArtifactSystem/context/ArtifactContext.js.map +1 -1
  47. package/esm/components/MemoriArtifactSystem/types/artifact.types.d.ts +11 -0
  48. package/esm/components/MemoriArtifactSystem/utils/ArtifactAPI.js +18 -13
  49. package/esm/components/MemoriArtifactSystem/utils/ArtifactAPI.js.map +1 -1
  50. package/esm/components/MemoriArtifactSystem/utils/applyEdits.d.ts +8 -0
  51. package/esm/components/MemoriArtifactSystem/utils/applyEdits.js +112 -0
  52. package/esm/components/MemoriArtifactSystem/utils/applyEdits.js.map +1 -0
  53. package/esm/components/MemoriWidget/MemoriWidget.d.ts +1 -0
  54. package/esm/components/MemoriWidget/MemoriWidget.js +57 -1
  55. package/esm/components/MemoriWidget/MemoriWidget.js.map +1 -1
  56. package/esm/helpers/message.js +3 -0
  57. package/esm/helpers/message.js.map +1 -1
  58. package/esm/helpers/nats/getNatsConfig.d.ts +1 -1
  59. package/esm/helpers/nats/getNatsConfig.js +2 -2
  60. package/esm/helpers/nats/getNatsConfig.js.map +1 -1
  61. package/esm/helpers/nats/useNats.d.ts +2 -1
  62. package/esm/helpers/nats/useNats.js +87 -20
  63. package/esm/helpers/nats/useNats.js.map +1 -1
  64. package/esm/helpers/nats/useNatsSession.d.ts +6 -1
  65. package/esm/helpers/nats/useNatsSession.js +48 -8
  66. package/esm/helpers/nats/useNatsSession.js.map +1 -1
  67. package/esm/locales/de.json +3 -0
  68. package/esm/locales/en.json +3 -0
  69. package/esm/locales/es.json +3 -0
  70. package/esm/locales/fr.json +3 -0
  71. package/esm/locales/it.json +3 -0
  72. package/esm/version.d.ts +1 -1
  73. package/esm/version.js +1 -1
  74. package/package.json +1 -1
  75. package/src/components/Avatar/AvatarView/AvatarComponent/constants.ts +1 -1
  76. package/src/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.tsx +1 -0
  77. package/src/components/MemoriArtifactSystem/components/ArtifactHandler/ArtifactHandler.tsx +324 -133
  78. package/src/components/MemoriArtifactSystem/context/ArtifactContext.tsx +122 -24
  79. package/src/components/MemoriArtifactSystem/types/artifact.types.ts +20 -1
  80. package/src/components/MemoriArtifactSystem/utils/ArtifactAPI.test.tsx +1 -0
  81. package/src/components/MemoriArtifactSystem/utils/ArtifactAPI.tsx +19 -13
  82. package/src/components/MemoriArtifactSystem/utils/applyEdits.test.ts +85 -0
  83. package/src/components/MemoriArtifactSystem/utils/applyEdits.ts +173 -0
  84. package/src/components/MemoriWidget/MemoriWidget.tsx +65 -1
  85. package/src/helpers/message.ts +15 -0
  86. package/src/helpers/nats/getNatsConfig.ts +8 -3
  87. package/src/helpers/nats/useNats.test.tsx +81 -0
  88. package/src/helpers/nats/useNats.ts +109 -29
  89. package/src/helpers/nats/useNatsSession.test.ts +16 -0
  90. package/src/helpers/nats/useNatsSession.ts +79 -13
  91. package/src/locales/de.json +3 -0
  92. package/src/locales/en.json +3 -0
  93. package/src/locales/es.json +3 -0
  94. package/src/locales/fr.json +3 -0
  95. package/src/locales/it.json +3 -0
  96. package/src/version.ts +1 -1
  97. package/dist/components/ChatHistoryDrawer/ChatResumeDrawer.css +0 -372
  98. package/dist/components/DrawerFooter/DrawerFooter.css +0 -62
  99. package/dist/components/IconButton/IconButton.css +0 -144
  100. package/dist/components/MobileSessionPanel/MobileSessionPanel.css +0 -459
  101. package/dist/components/PositionPopover/PositionPopover.css +0 -219
  102. package/dist/components/layouts/WebsiteAssistant/website-assistant.css +0 -806
  103. package/dist/components/layouts/fullpage.css +0 -522
  104. package/esm/components/ChatHistoryDrawer/ChatResumeDrawer.css +0 -372
  105. package/esm/components/ChatHistoryDrawer/ChatResumeDrawer.d.ts +0 -36
  106. package/esm/components/ChatHistoryDrawer/ChatResumeDrawer.js +0 -113
  107. package/esm/components/ChatHistoryDrawer/ChatResumeDrawer.js.map +0 -1
  108. package/esm/components/DrawerFooter/DrawerFooter.css +0 -62
  109. package/esm/components/DrawerFooter/DrawerFooter.d.ts +0 -12
  110. package/esm/components/DrawerFooter/DrawerFooter.js +0 -8
  111. package/esm/components/DrawerFooter/DrawerFooter.js.map +0 -1
  112. package/esm/components/IconButton/IconButton.css +0 -144
  113. package/esm/components/IconButton/IconButton.d.ts +0 -9
  114. package/esm/components/IconButton/IconButton.js +0 -33
  115. package/esm/components/IconButton/IconButton.js.map +0 -1
  116. package/esm/components/MobileSessionPanel/MobileSessionPanel.css +0 -459
  117. package/esm/components/MobileSessionPanel/MobileSessionPanel.d.ts +0 -65
  118. package/esm/components/MobileSessionPanel/MobileSessionPanel.js +0 -291
  119. package/esm/components/MobileSessionPanel/MobileSessionPanel.js.map +0 -1
  120. package/esm/components/PositionPopover/PositionPopover.css +0 -219
  121. package/esm/components/PositionPopover/PositionPopover.d.ts +0 -22
  122. package/esm/components/PositionPopover/PositionPopover.js +0 -190
  123. package/esm/components/PositionPopover/PositionPopover.js.map +0 -1
  124. package/esm/components/layouts/WebsiteAssistant/WebsiteAssistant.d.ts +0 -4
  125. package/esm/components/layouts/WebsiteAssistant/WebsiteAssistant.js +0 -61
  126. package/esm/components/layouts/WebsiteAssistant/WebsiteAssistant.js.map +0 -1
  127. package/esm/components/layouts/WebsiteAssistant/website-assistant.css +0 -806
  128. package/esm/components/layouts/fullpage.css +0 -522
  129. package/esm/context/widgetSurfaceContext.d.ts +0 -3
  130. package/esm/context/widgetSurfaceContext.js +0 -7
  131. package/esm/context/widgetSurfaceContext.js.map +0 -1
  132. package/esm/helpers/positionPopover.d.ts +0 -1
  133. package/esm/helpers/positionPopover.js +0 -4
  134. package/esm/helpers/positionPopover.js.map +0 -1
  135. package/esm/helpers/tts/muteSpeaker.d.ts +0 -13
  136. package/esm/helpers/tts/muteSpeaker.js +0 -21
  137. package/esm/helpers/tts/muteSpeaker.js.map +0 -1
  138. package/esm/helpers/usePressTooltip.d.ts +0 -13
  139. package/esm/helpers/usePressTooltip.js +0 -20
  140. package/esm/helpers/usePressTooltip.js.map +0 -1
  141. package/esm/icons/FacebookIcon.d.ts +0 -3
  142. package/esm/icons/FacebookIcon.js +0 -4
  143. package/esm/icons/FacebookIcon.js.map +0 -1
  144. package/esm/icons/LinkedinIcon.d.ts +0 -3
  145. package/esm/icons/LinkedinIcon.js +0 -4
  146. package/esm/icons/LinkedinIcon.js.map +0 -1
  147. package/esm/icons/MemoriIcon.d.ts +0 -3
  148. package/esm/icons/MemoriIcon.js +0 -6
  149. package/esm/icons/MemoriIcon.js.map +0 -1
  150. package/esm/icons/TelegramIcon.d.ts +0 -3
  151. package/esm/icons/TelegramIcon.js +0 -4
  152. package/esm/icons/TelegramIcon.js.map +0 -1
  153. package/esm/icons/TwitterIcon.d.ts +0 -3
  154. package/esm/icons/TwitterIcon.js +0 -4
  155. package/esm/icons/TwitterIcon.js.map +0 -1
  156. package/esm/icons/WhatsappIcon.d.ts +0 -3
  157. package/esm/icons/WhatsappIcon.js +0 -4
  158. package/esm/icons/WhatsappIcon.js.map +0 -1
  159. package/esm/icons/artifacts/DocumentIcon.d.ts +0 -3
  160. package/esm/icons/artifacts/DocumentIcon.js +0 -4
  161. package/esm/icons/artifacts/DocumentIcon.js.map +0 -1
  162. package/esm/icons/artifacts/HtmlIcon.d.ts +0 -3
  163. package/esm/icons/artifacts/HtmlIcon.js +0 -4
  164. package/esm/icons/artifacts/HtmlIcon.js.map +0 -1
  165. package/esm/icons/artifacts/JavascriptIcon.d.ts +0 -3
  166. package/esm/icons/artifacts/JavascriptIcon.js +0 -4
  167. package/esm/icons/artifacts/JavascriptIcon.js.map +0 -1
  168. package/esm/icons/artifacts/MarkdownIcon.d.ts +0 -3
  169. package/esm/icons/artifacts/MarkdownIcon.js +0 -4
  170. package/esm/icons/artifacts/MarkdownIcon.js.map +0 -1
  171. package/esm/icons/artifacts/PythonIcon.d.ts +0 -3
  172. package/esm/icons/artifacts/PythonIcon.js +0 -4
  173. package/esm/icons/artifacts/PythonIcon.js.map +0 -1
  174. package/esm/icons/artifacts/SvgIcon.d.ts +0 -3
  175. package/esm/icons/artifacts/SvgIcon.js +0 -4
  176. package/esm/icons/artifacts/SvgIcon.js.map +0 -1
  177. package/esm/icons/artifacts/XmlIcon.d.ts +0 -3
  178. package/esm/icons/artifacts/XmlIcon.js +0 -4
  179. package/esm/icons/artifacts/XmlIcon.js.map +0 -1
  180. package/esm/icons/artifacts/cssIcon.d.ts +0 -3
  181. package/esm/icons/artifacts/cssIcon.js +0 -4
  182. package/esm/icons/artifacts/cssIcon.js.map +0 -1
  183. package/esm/testUtils.d.ts +0 -5
  184. package/esm/testUtils.js +0 -15
  185. package/esm/testUtils.js.map +0 -1
@@ -114,6 +114,21 @@ export const renderMsg = (
114
114
  /<output\s+class\s*=\s*["\']memori-artifact["\'][^>]*data-mimetype\s*=\s*["\']([^"']+)["\'][^>]*>([\s\S]*?)(?:<\/output>|$)/gi,
115
115
  ''
116
116
  )
117
+ // Preferred: data-action="update" on memori-artifact
118
+ .replaceAll(
119
+ /<output\s+class\s*=\s*["\']memori-artifact["\'][^>]*data-action\s*=\s*["\']update["\'][^>]*>([\s\S]*?)(?:<\/output>|$)/gi,
120
+ ''
121
+ )
122
+ // data-action may appear before class
123
+ .replaceAll(
124
+ /<output\s+[^>]*data-action\s*=\s*["\']update["\'][^>]*class\s*=\s*["\'][^"']*memori-artifact[^"']*["\'][^>]*>([\s\S]*?)(?:<\/output>|$)/gi,
125
+ ''
126
+ )
127
+ // Legacy class name
128
+ .replaceAll(
129
+ /<output\s+class\s*=\s*["\']memori-artifact-update["\'][^>]*>([\s\S]*?)(?:<\/output>|$)/gi,
130
+ ''
131
+ )
117
132
  .replaceAll(/```markdown([^```]+)```/g, '$1')
118
133
  .replaceAll('($', '( $')
119
134
  .replaceAll(':$', ': $')
@@ -7,7 +7,10 @@
7
7
  export interface NatsConfig {
8
8
  /** WebSocket URL of the NATS server (e.g. wss://nats.hz.slnode.net:8080). */
9
9
  url: string;
10
- /** Bearer token used to authenticate the WebSocket connection. */
10
+ /**
11
+ * Per-session NATS user JWT. Presented with `jwtAuthenticator` (bearer:
12
+ * no nkey seed on the client).
13
+ */
11
14
  token: string;
12
15
  /**
13
16
  * JetStream stream that stores session events. When set, the client consumes
@@ -104,7 +107,7 @@ export function parseNatsConfig(raw: Record<string, unknown>): NatsConfig {
104
107
  * @param signal Optional AbortSignal to cancel the request.
105
108
  */
106
109
  export async function getNatsConfig(
107
- baseUrl: string,
110
+ _baseUrl: string,
108
111
  sessionId: string,
109
112
  signal?: AbortSignal
110
113
  ): Promise<NatsConfig> {
@@ -113,7 +116,9 @@ export async function getNatsConfig(
113
116
  }
114
117
 
115
118
  const response = await fetch(
116
- `${baseUrl}/api/nats?sessionId=${encodeURIComponent(sessionId)}`,
119
+ `${'http://localhost:3000'}/api/nats?sessionId=${encodeURIComponent(
120
+ sessionId
121
+ )}`,
117
122
  { signal }
118
123
  );
119
124
 
@@ -0,0 +1,81 @@
1
+ import { act, renderHook, waitFor } from '@testing-library/react';
2
+ import { getNatsConfig } from './getNatsConfig';
3
+ import { useNats } from './useNats';
4
+ import { NatsSessionLifecycle, useNatsSession } from './useNatsSession';
5
+
6
+ jest.mock('./getNatsConfig', () => ({
7
+ getNatsConfig: jest.fn(),
8
+ }));
9
+
10
+ jest.mock('./useNatsSession', () => ({
11
+ useNatsSession: jest.fn(),
12
+ }));
13
+
14
+ const mockGetNatsConfig = getNatsConfig as jest.MockedFunction<
15
+ typeof getNatsConfig
16
+ >;
17
+ const mockUseNatsSession = useNatsSession as jest.MockedFunction<
18
+ typeof useNatsSession
19
+ >;
20
+
21
+ function latestLifecycle(): NatsSessionLifecycle {
22
+ return mockUseNatsSession.mock.calls.at(-1)?.[3] ?? {};
23
+ }
24
+
25
+ describe('useNats credential lifecycle', () => {
26
+ beforeEach(() => {
27
+ jest.clearAllMocks();
28
+ mockGetNatsConfig.mockResolvedValue({
29
+ url: 'wss://nats.example.test',
30
+ token: 'fresh-jwt',
31
+ });
32
+ Object.defineProperty(document, 'visibilityState', {
33
+ configurable: true,
34
+ value: 'visible',
35
+ });
36
+ });
37
+
38
+ it('refreshes the JWT on resume and catches up after reconnecting', async () => {
39
+ const onCatchUp = jest.fn();
40
+ renderHook(() =>
41
+ useNats({
42
+ baseUrl: 'https://dashboard.example.test',
43
+ sessionId: 'session-a',
44
+ onCatchUp,
45
+ })
46
+ );
47
+
48
+ await waitFor(() => expect(mockGetNatsConfig).toHaveBeenCalledTimes(1));
49
+
50
+ act(() => {
51
+ (document.dispatchEvent as (event: Event) => boolean)(
52
+ new Event('visibilitychange')
53
+ );
54
+ });
55
+ await waitFor(() => expect(mockGetNatsConfig).toHaveBeenCalledTimes(2));
56
+
57
+ act(() => latestLifecycle().onConnected?.());
58
+ expect(onCatchUp).toHaveBeenCalledTimes(1);
59
+ });
60
+
61
+ it('refreshes the JWT after an authorization error', async () => {
62
+ const onCatchUp = jest.fn();
63
+ renderHook(() =>
64
+ useNats({
65
+ baseUrl: 'https://dashboard.example.test',
66
+ sessionId: 'session-a',
67
+ onCatchUp,
68
+ })
69
+ );
70
+
71
+ await waitFor(() => expect(mockGetNatsConfig).toHaveBeenCalledTimes(1));
72
+
73
+ act(() => {
74
+ latestLifecycle().onAuthError?.(new Error('Authorization Violation'));
75
+ });
76
+ await waitFor(() => expect(mockGetNatsConfig).toHaveBeenCalledTimes(2));
77
+
78
+ act(() => latestLifecycle().onConnected?.());
79
+ expect(onCatchUp).toHaveBeenCalledTimes(1);
80
+ });
81
+ });
@@ -24,6 +24,11 @@ export interface UseNatsOptions {
24
24
  onDialogResponse?: (event: NatsDialogResponseEvent) => void;
25
25
  /** `error` events (logging / user notification). */
26
26
  onError?: (event: NatsErrorEvent) => void;
27
+ /**
28
+ * Reconcile a pending turn from the engine after a resumed or reauthenticated
29
+ * subscription is installed.
30
+ */
31
+ onCatchUp?: () => void | Promise<void>;
27
32
  }
28
33
 
29
34
  /**
@@ -38,6 +43,7 @@ export function useNats({
38
43
  onProgress,
39
44
  onDialogResponse,
40
45
  onError,
46
+ onCatchUp,
41
47
  }: UseNatsOptions) {
42
48
  const [config, setConfig] = useState<NatsConfig | null>(null);
43
49
  const [configError, setConfigError] = useState<Error | null>(null);
@@ -46,33 +52,42 @@ export function useNats({
46
52
  const onProgressRef = useRef(onProgress);
47
53
  const onDialogResponseRef = useRef(onDialogResponse);
48
54
  const onErrorRef = useRef(onError);
55
+ const onCatchUpRef = useRef(onCatchUp);
56
+ const abortRef = useRef<AbortController | null>(null);
57
+ const catchUpAfterConnectRef = useRef(false);
58
+ const refreshInFlightRef = useRef(false);
59
+ const lastAuthRefreshRef = useRef(0);
49
60
  useEffect(() => {
50
61
  onProgressRef.current = onProgress;
51
62
  onDialogResponseRef.current = onDialogResponse;
52
63
  onErrorRef.current = onError;
53
- }, [onProgress, onDialogResponse, onError]);
64
+ onCatchUpRef.current = onCatchUp;
65
+ }, [onProgress, onDialogResponse, onError, onCatchUp]);
54
66
 
55
- // Fetch connection config whenever the active session changes.
56
- useEffect(() => {
57
- if (!sessionId) {
58
- console.debug('[NATS] no sessionId, skipping config fetch');
59
- setConfig(null);
60
- setConfigError(null);
61
- return;
62
- }
67
+ const refreshConfig = useCallback(
68
+ async (reason: 'initial' | 'resume' | 'auth') => {
69
+ if (!sessionId || refreshInFlightRef.current) return;
70
+ if (reason === 'auth' && Date.now() - lastAuthRefreshRef.current < 5000) {
71
+ return;
72
+ }
63
73
 
64
- const controller = new AbortController();
65
- let cancelled = false;
66
-
67
- console.info(
68
- '[NATS] fetching config from',
69
- `${baseUrl}/api/nats`,
70
- 'for session',
71
- sessionId
72
- );
73
- getNatsConfig(baseUrl, sessionId, controller.signal)
74
- .then(cfg => {
75
- if (!cancelled) {
74
+ refreshInFlightRef.current = true;
75
+ if (reason === 'auth') lastAuthRefreshRef.current = Date.now();
76
+ abortRef.current?.abort();
77
+ const controller = new AbortController();
78
+ abortRef.current = controller;
79
+
80
+ console.info(
81
+ '[NATS] fetching config from',
82
+ `${baseUrl}/api/nats`,
83
+ 'for session',
84
+ sessionId,
85
+ `(${reason})`
86
+ );
87
+ try {
88
+ const cfg = await getNatsConfig(baseUrl, sessionId, controller.signal);
89
+ if (!controller.signal.aborted) {
90
+ catchUpAfterConnectRef.current = reason !== 'initial';
76
91
  console.info('[NATS] config received', {
77
92
  url: cfg.url,
78
93
  jetStream: !!cfg.stream,
@@ -81,20 +96,65 @@ export function useNats({
81
96
  setConfig(cfg);
82
97
  setConfigError(null);
83
98
  }
84
- })
85
- .catch(err => {
86
- if (!cancelled && err?.name !== 'AbortError') {
99
+ } catch (err: any) {
100
+ if (!controller.signal.aborted && err?.name !== 'AbortError') {
87
101
  console.error('[NATS] config error', err);
88
102
  setConfig(null);
89
103
  setConfigError(err instanceof Error ? err : new Error(String(err)));
90
104
  }
91
- });
105
+ } finally {
106
+ if (abortRef.current === controller) {
107
+ abortRef.current = null;
108
+ refreshInFlightRef.current = false;
109
+ }
110
+ }
111
+ },
112
+ [baseUrl, sessionId]
113
+ );
92
114
 
115
+ // Fetch connection config whenever the active session changes.
116
+ useEffect(() => {
117
+ if (!sessionId) {
118
+ console.debug('[NATS] no sessionId, skipping config fetch');
119
+ setConfig(null);
120
+ setConfigError(null);
121
+ return;
122
+ }
123
+
124
+ void refreshConfig('initial');
93
125
  return () => {
94
- cancelled = true;
95
- controller.abort();
126
+ abortRef.current?.abort();
127
+ abortRef.current = null;
128
+ refreshInFlightRef.current = false;
96
129
  };
97
- }, [baseUrl, sessionId]);
130
+ }, [sessionId, refreshConfig]);
131
+
132
+ // A suspended browser may lose core NATS messages. Refresh the short-lived
133
+ // JWT, reconnect, then reconcile the pending turn from the engine.
134
+ useEffect(() => {
135
+ if (!sessionId) return;
136
+
137
+ const requestResume = () => {
138
+ if (document.visibilityState === 'visible') {
139
+ void refreshConfig('resume');
140
+ }
141
+ };
142
+ const onVisibilityChange = () => {
143
+ if (document.visibilityState === 'visible') requestResume();
144
+ };
145
+ const onPageShow = (event: PageTransitionEvent) => {
146
+ if (event.persisted) requestResume();
147
+ };
148
+
149
+ document.addEventListener('visibilitychange', onVisibilityChange);
150
+ window.addEventListener('online', requestResume);
151
+ window.addEventListener('pageshow', onPageShow);
152
+ return () => {
153
+ document.removeEventListener('visibilitychange', onVisibilityChange);
154
+ window.removeEventListener('online', requestResume);
155
+ window.removeEventListener('pageshow', onPageShow);
156
+ };
157
+ }, [sessionId, refreshConfig]);
98
158
 
99
159
  const handleMessage = useCallback((event: NatsSessionEvent) => {
100
160
  console.debug('[NATS] dispatching event', { eventType: event.eventType });
@@ -113,7 +173,27 @@ export function useNats({
113
173
  }
114
174
  }, []);
115
175
 
116
- useNatsSession(sessionId, config ?? undefined, handleMessage);
176
+ const handleConnected = useCallback(() => {
177
+ if (!catchUpAfterConnectRef.current) return;
178
+ catchUpAfterConnectRef.current = false;
179
+ void onCatchUpRef.current?.();
180
+ }, []);
181
+
182
+ const handleAuthError = useCallback(
183
+ (error: Error) => {
184
+ console.warn(
185
+ '[NATS] JWT rejected or expired; refreshing credentials',
186
+ error
187
+ );
188
+ void refreshConfig('auth');
189
+ },
190
+ [refreshConfig]
191
+ );
192
+
193
+ useNatsSession(sessionId, config ?? undefined, handleMessage, {
194
+ onConnected: handleConnected,
195
+ onAuthError: handleAuthError,
196
+ });
117
197
 
118
198
  return {
119
199
  /** True once connection config has been retrieved. */
@@ -0,0 +1,16 @@
1
+ import { AuthorizationError } from '@nats-io/nats-core';
2
+ import { isNatsAuthError } from './useNatsSession';
3
+
4
+ describe('isNatsAuthError', () => {
5
+ it('recognizes typed NATS authorization failures', () => {
6
+ expect(isNatsAuthError(new AuthorizationError('test'))).toBe(true);
7
+ });
8
+
9
+ it('recognizes the server authorization violation message', () => {
10
+ expect(isNatsAuthError(new Error('Authorization Violation'))).toBe(true);
11
+ });
12
+
13
+ it('does not classify unrelated connection failures as auth failures', () => {
14
+ expect(isNatsAuthError(new Error('connection refused'))).toBe(false);
15
+ });
16
+ });
@@ -11,7 +11,13 @@
11
11
  // The cleanup (`consumerMessages.stop()` + `nc.close()`) is essential: without
12
12
  // it, every `sessionId` change would leave orphan connections / iterators.
13
13
  import { useEffect, useRef, useState, type MutableRefObject } from 'react';
14
- import { wsconnect, NatsConnection } from '@nats-io/nats-core';
14
+ import {
15
+ wsconnect,
16
+ jwtAuthenticator,
17
+ AuthorizationError,
18
+ NatsConnection,
19
+ UserAuthenticationExpiredError,
20
+ } from '@nats-io/nats-core';
15
21
  import {
16
22
  jetstream,
17
23
  DeliverPolicy,
@@ -66,6 +72,24 @@ export type NatsSessionEvent =
66
72
 
67
73
  type JetStreamConsumeMode = 'live' | 'catch-up';
68
74
 
75
+ export interface NatsSessionLifecycle {
76
+ /** Called after the live subscription is installed. */
77
+ onConnected?: () => void;
78
+ /** Called once when this connection is rejected because its JWT expired. */
79
+ onAuthError?: (error: Error) => void;
80
+ }
81
+
82
+ export function isNatsAuthError(error: unknown): error is Error {
83
+ return (
84
+ error instanceof AuthorizationError ||
85
+ error instanceof UserAuthenticationExpiredError ||
86
+ (error instanceof Error &&
87
+ /authorization violation|authentication expired|user authentication expired/i.test(
88
+ error.message
89
+ ))
90
+ );
91
+ }
92
+
69
93
  function readString(
70
94
  raw: Record<string, unknown>,
71
95
  camelKey: string,
@@ -107,7 +131,9 @@ function unwrapDialogState(value: unknown): unknown {
107
131
  /**
108
132
  * Normalizes raw NATS payloads (snake_case or camelCase) into typed events.
109
133
  */
110
- export function normalizeNatsEvent(raw: Record<string, unknown>): NatsSessionEvent {
134
+ export function normalizeNatsEvent(
135
+ raw: Record<string, unknown>
136
+ ): NatsSessionEvent {
111
137
  const eventType = (readString(raw, 'eventType', 'event_type') ??
112
138
  'unknown') as NatsSessionEvent['eventType'];
113
139
 
@@ -130,8 +156,7 @@ export function normalizeNatsEvent(raw: Record<string, unknown>): NatsSessionEve
130
156
  if (eventType === 'dialog_text_entered_response') {
131
157
  return {
132
158
  eventType: 'dialog_text_entered_response',
133
- requestID:
134
- typeof raw.requestID === 'string' ? raw.requestID : undefined,
159
+ requestID: typeof raw.requestID === 'string' ? raw.requestID : undefined,
135
160
  resultCode:
136
161
  typeof raw.resultCode === 'number' ? raw.resultCode : undefined,
137
162
  resultMessage:
@@ -144,7 +169,10 @@ export function normalizeNatsEvent(raw: Record<string, unknown>): NatsSessionEve
144
169
  if (eventType === 'error') {
145
170
  return {
146
171
  eventType: 'error',
147
- errorCode: (raw.errorCode ?? raw.error_code) as string | number | undefined,
172
+ errorCode: (raw.errorCode ?? raw.error_code) as
173
+ | string
174
+ | number
175
+ | undefined,
148
176
  errorMessage: readString(raw, 'errorMessage', 'error_message'),
149
177
  backtrace: typeof raw.backtrace === 'string' ? raw.backtrace : undefined,
150
178
  correlationID,
@@ -174,10 +202,12 @@ function decodeMessage(
174
202
  async function consumeCoreSubscription(
175
203
  nc: NatsConnection,
176
204
  subject: string,
177
- onMessage: (event: NatsSessionEvent) => void
205
+ onMessage: (event: NatsSessionEvent) => void,
206
+ onReady: () => void
178
207
  ) {
179
208
  const sub = nc.subscribe(subject);
180
209
  console.info('[NATS] subscribed to subject', subject);
210
+ onReady();
181
211
  let received = 0;
182
212
  for await (const msg of sub) {
183
213
  received += 1;
@@ -203,7 +233,8 @@ async function consumeJetStream(
203
233
  subject: string,
204
234
  mode: JetStreamConsumeMode,
205
235
  onMessage: (event: NatsSessionEvent) => void,
206
- setConsumerMessages: (messages: ConsumerMessages) => void
236
+ setConsumerMessages: (messages: ConsumerMessages) => void,
237
+ onReady: () => void
207
238
  ) {
208
239
  const js = jetstream(nc);
209
240
  const consumer = config.consumer
@@ -225,6 +256,7 @@ async function consumeJetStream(
225
256
 
226
257
  const messages = await consumer.consume();
227
258
  setConsumerMessages(messages);
259
+ onReady();
228
260
  let received = 0;
229
261
  for await (const msg of messages) {
230
262
  received += 1;
@@ -258,17 +290,19 @@ function closeNatsSession(
258
290
  * change.
259
291
  *
260
292
  * @param sessionId Current session UUID (subscription is skipped when falsy).
261
- * @param config Connection config from `/api/nats` (url + token required).
293
+ * @param config Connection config from `/api/nats` (url + per-session JWT).
262
294
  * @param onMessage Callback invoked for each decoded event.
263
295
  */
264
296
  export function useNatsSession(
265
297
  sessionId: string | undefined,
266
298
  config: NatsConfig | undefined,
267
- onMessage: (event: NatsSessionEvent) => void
299
+ onMessage: (event: NatsSessionEvent) => void,
300
+ lifecycle: NatsSessionLifecycle = {}
268
301
  ) {
269
302
  const connRef = useRef<NatsConnection | null>(null);
270
303
  const consumerMessagesRef = useRef<ConsumerMessages | null>(null);
271
304
  const onMessageRef = useRef(onMessage);
305
+ const lifecycleRef = useRef(lifecycle);
272
306
  const wasHiddenRef = useRef(false);
273
307
  const [resumeGeneration, setResumeGeneration] = useState(0);
274
308
 
@@ -277,6 +311,10 @@ export function useNatsSession(
277
311
  onMessageRef.current = onMessage;
278
312
  }, [onMessage]);
279
313
 
314
+ useEffect(() => {
315
+ lifecycleRef.current = lifecycle;
316
+ }, [lifecycle]);
317
+
280
318
  // Reconnect when the tab returns from background or the network comes back.
281
319
  useEffect(() => {
282
320
  if (!sessionId || !config?.stream) {
@@ -348,7 +386,7 @@ export function useNatsSession(
348
386
  );
349
387
  const nc = await wsconnect({
350
388
  servers: [config.url],
351
- token: config.token,
389
+ authenticator: jwtAuthenticator(config.token),
352
390
  });
353
391
  if (closed) {
354
392
  console.debug(
@@ -363,6 +401,28 @@ export function useNatsSession(
363
401
  const dispatch = (event: NatsSessionEvent) => {
364
402
  onMessageRef.current(event);
365
403
  };
404
+ const ready = () => lifecycleRef.current.onConnected?.();
405
+ let authRefreshRequested = false;
406
+ const requestAuthRefresh = (error: Error) => {
407
+ if (closed || authRefreshRequested) return;
408
+ authRefreshRequested = true;
409
+ lifecycleRef.current.onAuthError?.(error);
410
+ };
411
+
412
+ void (async () => {
413
+ for await (const status of nc.status()) {
414
+ if (status.type === 'error' && isNatsAuthError(status.error)) {
415
+ requestAuthRefresh(status.error);
416
+ return;
417
+ }
418
+ }
419
+ })();
420
+
421
+ void nc.closed().then(error => {
422
+ if (error && isNatsAuthError(error)) {
423
+ requestAuthRefresh(error);
424
+ }
425
+ });
366
426
 
367
427
  if (useJetStream) {
368
428
  await consumeJetStream(
@@ -373,12 +433,18 @@ export function useNatsSession(
373
433
  dispatch,
374
434
  messages => {
375
435
  consumerMessagesRef.current = messages;
376
- }
436
+ },
437
+ ready
377
438
  );
378
439
  } else {
379
- await consumeCoreSubscription(nc, subject, dispatch);
440
+ await consumeCoreSubscription(nc, subject, dispatch, ready);
441
+ }
442
+ })().catch(err => {
443
+ console.error('[NATS] connection error', err);
444
+ if (!closed && isNatsAuthError(err)) {
445
+ lifecycleRef.current.onAuthError?.(err);
380
446
  }
381
- })().catch(err => console.error('[NATS] connection error', err));
447
+ });
382
448
 
383
449
  return () => {
384
450
  console.info('[NATS] cleanup: closing connection for subject', subject);
@@ -197,6 +197,9 @@
197
197
  "artifact": {
198
198
  "close": "Schließen",
199
199
  "size": "Größe",
200
+ "updated": "aktualisiert",
201
+ "updateFailed": "Update konnte nicht angewendet werden",
202
+ "updateFailedHint": "Der Patch stimmt nicht mit dem aktuellen Inhalt überein. Bitten Sie um ein Neuschreiben des Artifacts.",
200
203
  "generated": "Generiert",
201
204
  "download": "Herunterladen",
202
205
  "print": "Drucken",
@@ -210,6 +210,9 @@
210
210
  "artifact": {
211
211
  "close": "Close",
212
212
  "size": "Size",
213
+ "updated": "updated",
214
+ "updateFailed": "Update could not be applied",
215
+ "updateFailedHint": "The patch did not match the current content. Ask to rewrite the artifact.",
213
216
  "generated": "Generated",
214
217
  "download": "Download",
215
218
  "print": "Print",
@@ -197,6 +197,9 @@
197
197
  "artifact": {
198
198
  "close": "Cerrar",
199
199
  "size": "Tamaño",
200
+ "updated": "actualizado",
201
+ "updateFailed": "No se pudo aplicar la actualización",
202
+ "updateFailedHint": "El parche no coincide con el contenido actual. Pide reescribir el artifact.",
200
203
  "generated": "Generado",
201
204
  "download": "Descargar",
202
205
  "print": "Imprimir",
@@ -196,6 +196,9 @@
196
196
  "artifact": {
197
197
  "close": "Fermer",
198
198
  "size": "Taille",
199
+ "updated": "mis à jour",
200
+ "updateFailed": "Mise à jour non appliquée",
201
+ "updateFailedHint": "Le correctif ne correspond pas au contenu actuel. Demandez de réécrire l'artifact.",
199
202
  "generated": "Généré",
200
203
  "download": "Télécharger",
201
204
  "print": "Imprimer",
@@ -212,6 +212,9 @@
212
212
  "artifact": {
213
213
  "close": "Chiudi",
214
214
  "size": "Dimensione",
215
+ "updated": "aggiornato",
216
+ "updateFailed": "Aggiornamento non applicato",
217
+ "updateFailedHint": "Il patch non corrisponde al contenuto attuale. Chiedi di riscrivere l'artifact.",
215
218
  "generated": "Generato",
216
219
  "download": "Scarica",
217
220
  "print": "Stampa",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // This file is auto-generated. Do not edit manually.
2
- export const version = '8.43.0';
2
+ export const version = '8.45.0';