@escapeaihq/client-core 0.12.0 → 0.49.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 (242) hide show
  1. package/README.md +32 -7
  2. package/dist/adapters/capabilities.d.ts +10 -0
  3. package/dist/adapters/capabilities.d.ts.map +1 -0
  4. package/dist/adapters/capabilities.js +2 -0
  5. package/dist/adapters/capabilities.js.map +1 -0
  6. package/dist/adapters/chatAdapter.d.ts +38 -0
  7. package/dist/adapters/chatAdapter.d.ts.map +1 -0
  8. package/dist/adapters/chatAdapter.js +88 -0
  9. package/dist/adapters/chatAdapter.js.map +1 -0
  10. package/dist/adapters/directorAdapter.d.ts +62 -0
  11. package/dist/adapters/directorAdapter.d.ts.map +1 -0
  12. package/dist/adapters/directorAdapter.js +71 -0
  13. package/dist/adapters/directorAdapter.js.map +1 -0
  14. package/dist/adapters/imageAdapter.d.ts +44 -0
  15. package/dist/adapters/imageAdapter.d.ts.map +1 -0
  16. package/dist/adapters/imageAdapter.js +73 -0
  17. package/dist/adapters/imageAdapter.js.map +1 -0
  18. package/dist/adapters/index.d.ts +47 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +41 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/registry.d.ts +98 -0
  23. package/dist/adapters/registry.d.ts.map +1 -0
  24. package/dist/adapters/registry.js +106 -0
  25. package/dist/adapters/registry.js.map +1 -0
  26. package/dist/adapters/worldAdapter.d.ts +142 -0
  27. package/dist/adapters/worldAdapter.d.ts.map +1 -0
  28. package/dist/adapters/worldAdapter.js +164 -0
  29. package/dist/adapters/worldAdapter.js.map +1 -0
  30. package/dist/admin.d.ts +323 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +198 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1512 -4
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +820 -52
  37. package/dist/api.js.map +1 -1
  38. package/dist/audio.d.ts +33 -1
  39. package/dist/audio.d.ts.map +1 -1
  40. package/dist/audio.js +4 -1
  41. package/dist/audio.js.map +1 -1
  42. package/dist/castProjection.d.ts +35 -0
  43. package/dist/castProjection.d.ts.map +1 -0
  44. package/dist/castProjection.js +80 -0
  45. package/dist/castProjection.js.map +1 -0
  46. package/dist/conversation/binding.d.ts +77 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +57 -0
  49. package/dist/conversation/binding.js.map +1 -0
  50. package/dist/conversation/controller.d.ts +209 -0
  51. package/dist/conversation/controller.d.ts.map +1 -0
  52. package/dist/conversation/controller.js +350 -0
  53. package/dist/conversation/controller.js.map +1 -0
  54. package/dist/conversation/effectiveModel.d.ts +62 -0
  55. package/dist/conversation/effectiveModel.d.ts.map +1 -0
  56. package/dist/conversation/effectiveModel.js +73 -0
  57. package/dist/conversation/effectiveModel.js.map +1 -0
  58. package/dist/conversation/index.d.ts +27 -0
  59. package/dist/conversation/index.d.ts.map +1 -0
  60. package/dist/conversation/index.js +27 -0
  61. package/dist/conversation/index.js.map +1 -0
  62. package/dist/conversation/participant.d.ts +66 -0
  63. package/dist/conversation/participant.d.ts.map +1 -0
  64. package/dist/conversation/participant.js +36 -0
  65. package/dist/conversation/participant.js.map +1 -0
  66. package/dist/conversation/presence.d.ts +56 -0
  67. package/dist/conversation/presence.d.ts.map +1 -0
  68. package/dist/conversation/presence.js +34 -0
  69. package/dist/conversation/presence.js.map +1 -0
  70. package/dist/conversation/presenceBus.d.ts +42 -0
  71. package/dist/conversation/presenceBus.d.ts.map +1 -0
  72. package/dist/conversation/presenceBus.js +81 -0
  73. package/dist/conversation/presenceBus.js.map +1 -0
  74. package/dist/conversation/presenceRegistry.d.ts +49 -0
  75. package/dist/conversation/presenceRegistry.d.ts.map +1 -0
  76. package/dist/conversation/presenceRegistry.js +59 -0
  77. package/dist/conversation/presenceRegistry.js.map +1 -0
  78. package/dist/conversation/roster.d.ts +72 -0
  79. package/dist/conversation/roster.d.ts.map +1 -0
  80. package/dist/conversation/roster.js +69 -0
  81. package/dist/conversation/roster.js.map +1 -0
  82. package/dist/conversation/rosterProjection.d.ts +52 -0
  83. package/dist/conversation/rosterProjection.d.ts.map +1 -0
  84. package/dist/conversation/rosterProjection.js +74 -0
  85. package/dist/conversation/rosterProjection.js.map +1 -0
  86. package/dist/conversation/router.d.ts +74 -0
  87. package/dist/conversation/router.d.ts.map +1 -0
  88. package/dist/conversation/router.js +58 -0
  89. package/dist/conversation/router.js.map +1 -0
  90. package/dist/conversation/runtime.d.ts +64 -0
  91. package/dist/conversation/runtime.d.ts.map +1 -0
  92. package/dist/conversation/runtime.js +172 -0
  93. package/dist/conversation/runtime.js.map +1 -0
  94. package/dist/conversation/types.d.ts +99 -0
  95. package/dist/conversation/types.d.ts.map +1 -0
  96. package/dist/conversation/types.js +13 -0
  97. package/dist/conversation/types.js.map +1 -0
  98. package/dist/conversation/voice.d.ts +185 -0
  99. package/dist/conversation/voice.d.ts.map +1 -0
  100. package/dist/conversation/voice.js +307 -0
  101. package/dist/conversation/voice.js.map +1 -0
  102. package/dist/graphSchema.d.ts +201 -13
  103. package/dist/graphSchema.d.ts.map +1 -1
  104. package/dist/graphSchema.js +258 -9
  105. package/dist/graphSchema.js.map +1 -1
  106. package/dist/http.d.ts +20 -0
  107. package/dist/http.d.ts.map +1 -0
  108. package/dist/http.js +57 -0
  109. package/dist/http.js.map +1 -0
  110. package/dist/index.d.ts +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/platformAssistant.d.ts +155 -0
  115. package/dist/platformAssistant.d.ts.map +1 -0
  116. package/dist/platformAssistant.js +256 -0
  117. package/dist/platformAssistant.js.map +1 -0
  118. package/dist/reactor/chunkDistribution.d.ts +43 -0
  119. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  120. package/dist/reactor/chunkDistribution.js +85 -0
  121. package/dist/reactor/chunkDistribution.js.map +1 -0
  122. package/dist/reactor/index.d.ts +2 -0
  123. package/dist/reactor/index.d.ts.map +1 -1
  124. package/dist/reactor/index.js +5 -0
  125. package/dist/reactor/index.js.map +1 -1
  126. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  127. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  128. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  129. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  130. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  131. package/dist/reactor/scenesFromEnrichment.js +2 -66
  132. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  133. package/dist/reactor/seedImageOrchestrator.d.ts +6 -9
  134. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  135. package/dist/reactor/seedImageOrchestrator.js +12 -13
  136. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  137. package/dist/reactor/storyTimeline.d.ts +44 -0
  138. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  139. package/dist/reactor/storyTimeline.js +95 -0
  140. package/dist/reactor/storyTimeline.js.map +1 -0
  141. package/dist/storyGraph.d.ts +70 -0
  142. package/dist/storyGraph.d.ts.map +1 -0
  143. package/dist/storyGraph.js +178 -0
  144. package/dist/storyGraph.js.map +1 -0
  145. package/dist/vision/VisionSourceController.d.ts +127 -0
  146. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  147. package/dist/vision/VisionSourceController.js +284 -0
  148. package/dist/vision/VisionSourceController.js.map +1 -0
  149. package/dist/vision/index.d.ts +4 -0
  150. package/dist/vision/index.d.ts.map +1 -1
  151. package/dist/vision/index.js +2 -0
  152. package/dist/vision/index.js.map +1 -1
  153. package/dist/vision/sourceKinds.d.ts +65 -0
  154. package/dist/vision/sourceKinds.d.ts.map +1 -0
  155. package/dist/vision/sourceKinds.js +26 -0
  156. package/dist/vision/sourceKinds.js.map +1 -0
  157. package/dist/websocket.d.ts +92 -0
  158. package/dist/websocket.d.ts.map +1 -1
  159. package/dist/websocket.js.map +1 -1
  160. package/package.json +1 -1
  161. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  162. package/src/__tests__/adapters-chat.test.ts +172 -0
  163. package/src/__tests__/adapters-director.test.ts +95 -0
  164. package/src/__tests__/adapters-image.test.ts +133 -0
  165. package/src/__tests__/adapters-platform.test.ts +95 -0
  166. package/src/__tests__/adapters-registry.test.ts +189 -0
  167. package/src/__tests__/adapters-world.test.ts +296 -0
  168. package/src/__tests__/admin.test.ts +312 -0
  169. package/src/__tests__/adventures-party.test.ts +219 -0
  170. package/src/__tests__/adventures.test.ts +282 -0
  171. package/src/__tests__/api-pollers.test.ts +4 -0
  172. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  173. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  174. package/src/__tests__/api.test.ts +553 -0
  175. package/src/__tests__/audio.test.ts +65 -0
  176. package/src/__tests__/cast.test.ts +95 -0
  177. package/src/__tests__/castProjection.test.ts +167 -0
  178. package/src/__tests__/conversation/binding.test.ts +62 -0
  179. package/src/__tests__/conversation/controller.test.ts +732 -0
  180. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  181. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  182. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  183. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  184. package/src/__tests__/conversation/roster.test.ts +100 -0
  185. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  186. package/src/__tests__/conversation/router.test.ts +81 -0
  187. package/src/__tests__/conversation/runtime.test.ts +206 -0
  188. package/src/__tests__/conversation/voice.test.ts +440 -0
  189. package/src/__tests__/documents.test.ts +360 -0
  190. package/src/__tests__/graphSchema.test.ts +218 -9
  191. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  192. package/src/__tests__/monitoring.test.ts +162 -0
  193. package/src/__tests__/persona-generation.test.ts +352 -0
  194. package/src/__tests__/platformAssistant.test.ts +484 -0
  195. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  196. package/src/__tests__/regeneration.test.ts +486 -0
  197. package/src/__tests__/stories.test.ts +171 -0
  198. package/src/__tests__/storyGraph.test.ts +134 -0
  199. package/src/__tests__/tools-wrappers.test.ts +272 -0
  200. package/src/__tests__/videoGraph.test.ts +94 -0
  201. package/src/__tests__/websocket.test.ts +263 -0
  202. package/src/adapters/capabilities.ts +24 -0
  203. package/src/adapters/chatAdapter.ts +114 -0
  204. package/src/adapters/directorAdapter.ts +126 -0
  205. package/src/adapters/imageAdapter.ts +100 -0
  206. package/src/adapters/index.ts +67 -0
  207. package/src/adapters/registry.ts +159 -0
  208. package/src/adapters/worldAdapter.ts +272 -0
  209. package/src/admin.ts +517 -0
  210. package/src/api.ts +2215 -95
  211. package/src/audio.ts +35 -0
  212. package/src/castProjection.ts +95 -0
  213. package/src/conversation/binding.ts +100 -0
  214. package/src/conversation/controller.ts +447 -0
  215. package/src/conversation/effectiveModel.ts +111 -0
  216. package/src/conversation/index.ts +27 -0
  217. package/src/conversation/participant.ts +71 -0
  218. package/src/conversation/presence.ts +60 -0
  219. package/src/conversation/presenceBus.ts +109 -0
  220. package/src/conversation/presenceRegistry.ts +83 -0
  221. package/src/conversation/roster.ts +111 -0
  222. package/src/conversation/rosterProjection.ts +98 -0
  223. package/src/conversation/router.ts +96 -0
  224. package/src/conversation/runtime.ts +188 -0
  225. package/src/conversation/types.ts +100 -0
  226. package/src/conversation/voice.ts +402 -0
  227. package/src/graphSchema.ts +396 -13
  228. package/src/http.ts +72 -0
  229. package/src/index.ts +9 -0
  230. package/src/platformAssistant.ts +347 -0
  231. package/src/reactor/chunkDistribution.ts +98 -0
  232. package/src/reactor/index.ts +5 -0
  233. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  234. package/src/reactor/scenesFromEnrichment.ts +11 -76
  235. package/src/reactor/seedImageOrchestrator.ts +12 -13
  236. package/src/reactor/storyTimeline.ts +127 -0
  237. package/src/storyGraph.ts +298 -0
  238. package/src/vision/VisionSourceController.ts +354 -0
  239. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  240. package/src/vision/index.ts +13 -0
  241. package/src/vision/sourceKinds.ts +75 -0
  242. package/src/websocket.ts +99 -3
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Tests for dispatchLongLiveCommand — the LongLive-v2 analogue of
3
+ * dispatchHeliosCommand. Maps each LongLiveCommand to the right
4
+ * `reactor.sendCommand` call(s) over the SAME structural Reactor bridge.
5
+ *
6
+ * Coverage:
7
+ * - set_shot at the opening shot: set_shot + start when !hasStarted; NO start
8
+ * when hasStarted:true.
9
+ * - scene_cut (the hard, memory-purging transition Helios lacks).
10
+ * - schedule_shot / schedule_scene_cut: snake_case `at_session_chunk` wire field.
11
+ * - pause / resume / reset → correct sendCommand names with {} payload.
12
+ * - set_seed → sendCommand('set_seed', { seed }).
13
+ * - an already-aborted signal makes the dispatch a no-op.
14
+ */
15
+
16
+ import {
17
+ dispatchLongLiveCommand,
18
+ type LongLiveCommand,
19
+ type LongLiveToolContext,
20
+ } from '../reactor/longLiveCommandDispatcher';
21
+
22
+ type AnyMock = jest.Mock;
23
+
24
+ function makeReactor() {
25
+ return {
26
+ sendCommand: jest.fn().mockResolvedValue(undefined) as AnyMock,
27
+ };
28
+ }
29
+
30
+ /** Build a minimal LongLiveToolContext over a mock bridge. */
31
+ function makeCtx(
32
+ reactor: ReturnType<typeof makeReactor>,
33
+ overrides: Partial<LongLiveToolContext> = {},
34
+ ): LongLiveToolContext {
35
+ return { reactor, ...overrides };
36
+ }
37
+
38
+ describe('dispatchLongLiveCommand', () => {
39
+ describe('set_shot — opening-shot-then-start guard', () => {
40
+ it('fires set_shot then start at the opening shot when !hasStarted', async () => {
41
+ const reactor = makeReactor();
42
+ await dispatchLongLiveCommand(
43
+ { type: 'set_shot', prompt: 'a neon alley at night' },
44
+ makeCtx(reactor),
45
+ );
46
+ expect(reactor.sendCommand.mock.calls).toEqual([
47
+ ['set_shot', { prompt: 'a neon alley at night' }],
48
+ ['start', {}],
49
+ ]);
50
+ });
51
+
52
+ it('suppresses the start re-emit when hasStarted:true', async () => {
53
+ const reactor = makeReactor();
54
+ await dispatchLongLiveCommand(
55
+ { type: 'set_shot', prompt: 'a wider crane shot' },
56
+ makeCtx(reactor, { hasStarted: true }),
57
+ );
58
+ expect(reactor.sendCommand.mock.calls).toEqual([
59
+ ['set_shot', { prompt: 'a wider crane shot' }],
60
+ ]);
61
+ const names = reactor.sendCommand.mock.calls.map((c) => c[0]);
62
+ expect(names).not.toContain('start');
63
+ });
64
+ });
65
+
66
+ it('scene_cut → sendCommand("scene_cut", { prompt }) — the hard transition', async () => {
67
+ const reactor = makeReactor();
68
+ await dispatchLongLiveCommand(
69
+ { type: 'scene_cut', prompt: 'cut to a sunlit beach' },
70
+ makeCtx(reactor),
71
+ );
72
+ expect(reactor.sendCommand.mock.calls).toEqual([
73
+ ['scene_cut', { prompt: 'cut to a sunlit beach' }],
74
+ ]);
75
+ });
76
+
77
+ it('schedule_shot → snake_case at_session_chunk on the wire', async () => {
78
+ const reactor = makeReactor();
79
+ await dispatchLongLiveCommand(
80
+ { type: 'schedule_shot', prompt: 'pan to the harbor', atSessionChunk: 42 },
81
+ makeCtx(reactor),
82
+ );
83
+ expect(reactor.sendCommand.mock.calls).toEqual([
84
+ ['schedule_shot', { prompt: 'pan to the harbor', at_session_chunk: 42 }],
85
+ ]);
86
+ });
87
+
88
+ it('schedule_scene_cut → snake_case at_session_chunk on the wire', async () => {
89
+ const reactor = makeReactor();
90
+ await dispatchLongLiveCommand(
91
+ {
92
+ type: 'schedule_scene_cut',
93
+ prompt: 'hard cut to the throne room',
94
+ atSessionChunk: 96,
95
+ },
96
+ makeCtx(reactor),
97
+ );
98
+ expect(reactor.sendCommand.mock.calls).toEqual([
99
+ [
100
+ 'schedule_scene_cut',
101
+ { prompt: 'hard cut to the throne room', at_session_chunk: 96 },
102
+ ],
103
+ ]);
104
+ });
105
+
106
+ it.each([
107
+ ['pause', 'pause'],
108
+ ['resume', 'resume'],
109
+ ['reset', 'reset'],
110
+ ])('%s → sendCommand("%s", {})', async (cmdType, expected) => {
111
+ const reactor = makeReactor();
112
+ await dispatchLongLiveCommand(
113
+ { type: cmdType } as LongLiveCommand,
114
+ makeCtx(reactor),
115
+ );
116
+ expect(reactor.sendCommand.mock.calls).toEqual([[expected, {}]]);
117
+ });
118
+
119
+ it('set_seed → sendCommand("set_seed", { seed })', async () => {
120
+ const reactor = makeReactor();
121
+ await dispatchLongLiveCommand(
122
+ { type: 'set_seed', seed: 1234 },
123
+ makeCtx(reactor),
124
+ );
125
+ expect(reactor.sendCommand.mock.calls).toEqual([
126
+ ['set_seed', { seed: 1234 }],
127
+ ]);
128
+ });
129
+
130
+ describe('abort signal', () => {
131
+ it('returns immediately without calling sendCommand when already aborted', async () => {
132
+ const reactor = makeReactor();
133
+ const controller = new AbortController();
134
+ controller.abort();
135
+
136
+ await dispatchLongLiveCommand(
137
+ { type: 'set_shot', prompt: 'should not fire' },
138
+ makeCtx(reactor, { signal: controller.signal }),
139
+ );
140
+
141
+ expect(reactor.sendCommand).not.toHaveBeenCalled();
142
+ });
143
+
144
+ it('is silent and emits no start when an abort is thrown mid set_shot', async () => {
145
+ const reactor = makeReactor();
146
+ // The opening set_shot aborts (DOMException AbortError) before start fires.
147
+ reactor.sendCommand.mockRejectedValueOnce(
148
+ new DOMException('aborted', 'AbortError'),
149
+ );
150
+ await expect(
151
+ dispatchLongLiveCommand(
152
+ { type: 'set_shot', prompt: 'x' },
153
+ makeCtx(reactor),
154
+ ),
155
+ ).resolves.toBeUndefined(); // isAbortError → silent, not a rejection
156
+ // set_shot was attempted; the abort short-circuited the start re-emit.
157
+ expect(reactor.sendCommand.mock.calls).toEqual([
158
+ ['set_shot', { prompt: 'x' }],
159
+ ]);
160
+ });
161
+ });
162
+
163
+ it('swallows a sendCommand failure so the chat keeps working', async () => {
164
+ const reactor = makeReactor();
165
+ reactor.sendCommand.mockRejectedValueOnce(new Error('reactor down'));
166
+ // Must resolve (not reject) — the failure is logged + skipped.
167
+ await expect(
168
+ dispatchLongLiveCommand(
169
+ { type: 'scene_cut', prompt: 'x' },
170
+ makeCtx(reactor),
171
+ ),
172
+ ).resolves.toBeUndefined();
173
+ });
174
+
175
+ it('swallows a non-abort error during set_shot and does NOT emit start', async () => {
176
+ const reactor = makeReactor();
177
+ reactor.sendCommand.mockRejectedValueOnce(new Error('reactor down'));
178
+ await expect(
179
+ dispatchLongLiveCommand({ type: 'set_shot', prompt: 'x' }, makeCtx(reactor)),
180
+ ).resolves.toBeUndefined();
181
+ // set_shot was attempted; the error short-circuited the start re-emit and
182
+ // was swallowed (the opening-shot path Step 3 is most likely to exercise).
183
+ expect(reactor.sendCommand.mock.calls).toEqual([['set_shot', { prompt: 'x' }]]);
184
+ });
185
+ });
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Tests for the additive `MonitoringClient` (C4 Phase 3): the admin monitoring
3
+ * tools surface. Methods go through the shared `requestJson` → fetch (same
4
+ * global-fetch-mock pattern as `admin.test.ts`). The monitoring endpoints live
5
+ * on the chat API base (the router is mounted in `api/chat/app.py`).
6
+ */
7
+
8
+ import { MonitoringClient } from '../admin';
9
+ import type {
10
+ MonitoringMetricCatalogResponse,
11
+ MonitoringMetricSeriesResponse,
12
+ MonitoringTraceDetailResponse,
13
+ MonitoringTraceSummariesResponse,
14
+ } from '../admin';
15
+
16
+ const CHAT_BASE_URL = 'http://test.local/chat';
17
+ const MONITORING = '/api/v1/admin/monitoring';
18
+
19
+ const makeClient = (token: string | undefined = 'test-token') =>
20
+ new MonitoringClient(CHAT_BASE_URL, token);
21
+
22
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
23
+
24
+ afterEach(() => {
25
+ if (originalFetch === undefined) {
26
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
27
+ } else {
28
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
29
+ }
30
+ jest.restoreAllMocks();
31
+ });
32
+
33
+ const mockFetch = (body: unknown, init: { ok?: boolean; status?: number } = {}) => {
34
+ const fetchMock = jest.fn().mockResolvedValue({
35
+ ok: init.ok ?? true,
36
+ status: init.status ?? 200,
37
+ json: async () => body,
38
+ });
39
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
40
+ return fetchMock;
41
+ };
42
+
43
+ describe('MonitoringClient.listMetrics', () => {
44
+ it('GETs the metric catalog on the chat base with a bearer token', async () => {
45
+ const body: MonitoringMetricCatalogResponse = {
46
+ metrics: [
47
+ {
48
+ metricId: 'router.decisions',
49
+ namespace: 'SeerAgent/Router',
50
+ metricName: 'RouteDecision',
51
+ stat: 'Sum',
52
+ unit: 'Count',
53
+ label: 'Router decisions',
54
+ dimensionKeys: [],
55
+ },
56
+ ],
57
+ traceId: 'trace-cat',
58
+ };
59
+ const fetchMock = mockFetch(body);
60
+
61
+ const result = await makeClient().listMetrics();
62
+
63
+ expect(result).toEqual(body);
64
+ const [url, requestInit] = fetchMock.mock.calls[0];
65
+ expect(url).toBe(`${CHAT_BASE_URL}${MONITORING}/metrics`);
66
+ expect(requestInit.method ?? 'GET').toBe('GET');
67
+ expect(requestInit.headers['Authorization']).toBe('Bearer test-token');
68
+ });
69
+ });
70
+
71
+ describe('MonitoringClient.getMetricSeries', () => {
72
+ it('GETs one series, URL-encoding the id and forwarding query params', async () => {
73
+ const body: MonitoringMetricSeriesResponse = {
74
+ metricId: 'router.decisions',
75
+ label: 'Router decisions',
76
+ unit: 'Count',
77
+ periodSeconds: 300,
78
+ startTime: '2026-06-15T11:00:00+00:00',
79
+ endTime: '2026-06-15T12:00:00+00:00',
80
+ datapoints: [{ timestamp: '2026-06-15T11:05:00+00:00', value: 5 }],
81
+ traceId: 'trace-series',
82
+ };
83
+ const fetchMock = mockFetch(body);
84
+
85
+ const result = await makeClient().getMetricSeries('router.decisions', {
86
+ rangeSeconds: 3600,
87
+ periodSeconds: 300,
88
+ });
89
+
90
+ expect(result.datapoints[0].value).toBe(5);
91
+ const [url] = fetchMock.mock.calls[0];
92
+ expect(url).toBe(
93
+ `${CHAT_BASE_URL}${MONITORING}/metrics/router.decisions?rangeSeconds=3600&periodSeconds=300`,
94
+ );
95
+ });
96
+
97
+ it('omits the query string when no params are given', async () => {
98
+ const fetchMock = mockFetch({
99
+ metricId: 'router.decisions',
100
+ label: 'x',
101
+ unit: 'Count',
102
+ periodSeconds: 300,
103
+ startTime: 's',
104
+ endTime: 'e',
105
+ datapoints: [],
106
+ traceId: 't',
107
+ } satisfies MonitoringMetricSeriesResponse);
108
+
109
+ await makeClient().getMetricSeries('router.decisions');
110
+
111
+ const [url] = fetchMock.mock.calls[0];
112
+ expect(url).toBe(`${CHAT_BASE_URL}${MONITORING}/metrics/router.decisions`);
113
+ });
114
+ });
115
+
116
+ describe('MonitoringClient.listTraces', () => {
117
+ it('GETs trace summaries forwarding the annotation filters', async () => {
118
+ const body: MonitoringTraceSummariesResponse = {
119
+ startTime: 's',
120
+ endTime: 'e',
121
+ traces: [
122
+ {
123
+ traceId: '1-abc',
124
+ durationSeconds: 1.2,
125
+ responseTimeSeconds: 0.9,
126
+ hasError: true,
127
+ hasFault: false,
128
+ hasThrottle: false,
129
+ httpStatus: 200,
130
+ },
131
+ ],
132
+ traceId: 'trace-traces',
133
+ };
134
+ const fetchMock = mockFetch(body);
135
+
136
+ const result = await makeClient().listTraces({ jobId: 'job-1', rangeSeconds: 3600 });
137
+
138
+ expect(result.traces[0].traceId).toBe('1-abc');
139
+ const [url] = fetchMock.mock.calls[0];
140
+ expect(url).toBe(
141
+ `${CHAT_BASE_URL}${MONITORING}/traces?jobId=job-1&rangeSeconds=3600`,
142
+ );
143
+ });
144
+ });
145
+
146
+ describe('MonitoringClient.getTraceDetail', () => {
147
+ it('GETs the trace detail (id URL-encoded)', async () => {
148
+ const body: MonitoringTraceDetailResponse = {
149
+ xrayTraceId: '1-abc',
150
+ found: true,
151
+ segments: [{ Id: 's1' }],
152
+ traceId: 'trace-detail',
153
+ };
154
+ const fetchMock = mockFetch(body);
155
+
156
+ const result = await makeClient().getTraceDetail('1-abc');
157
+
158
+ expect(result.found).toBe(true);
159
+ const [url] = fetchMock.mock.calls[0];
160
+ expect(url).toBe(`${CHAT_BASE_URL}${MONITORING}/traces/1-abc`);
161
+ });
162
+ });
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Tests for the C3a persona-generation client-core additions (spec Step 11) —
3
+ * the API methods + types web needs to trigger auto-generation and track job
4
+ * progress against the landed backend endpoints (spec Step 9):
5
+ * - `getPersonaGenSettings()` GET /api/v1/personas/settings/generation
6
+ * - `updatePersonaGenSettings(body)` PUT /api/v1/personas/settings/generation
7
+ * - `generatePersonasForVideo(videoId)` POST /api/v1/videos/{videoId}/personas/generate
8
+ * - `getPersonaJob(jobId)` GET /api/v1/persona-jobs/{jobId}
9
+ * - `listPersonasByVideo(videoId)` GET /api/v1/personas?source_video_id=
10
+ *
11
+ * Most route through `chatRequest` → `makeRequest` → fetch on the CHAT base URL
12
+ * (the personas API is mounted on the chat app). Same global-fetch-mock +
13
+ * save/restore discipline as cast.test.ts.
14
+ *
15
+ * Step 13 (review page) additions — the audition + reclone backend routes landed
16
+ * with tech-debt #477 (PR #356), so this file now also covers:
17
+ * - `auditionPersona(personaId, body?)` POST /api/v1/personas/{id}/audition → Blob
18
+ * - `reclonePersona(personaId)` POST /api/v1/personas/{id}/reclone
19
+ * Both bypass the JSON `chatRequest` wrapper (audition returns binary audio;
20
+ * reclone needs to surface the structured 409 as a typed RecloneConflictError).
21
+ */
22
+
23
+ import { ApiClient, RecloneConflictError } from '../api';
24
+ import type {
25
+ AutoGenerationJob,
26
+ GeneratePersonasJobResponse,
27
+ PersonaGenerationSettings,
28
+ ReclonedPersonaResponse,
29
+ UpdatePersonaGenSettingsRequest,
30
+ } from '../api';
31
+
32
+ const TEST_BASE_URL = 'http://test.local';
33
+ const TEST_CHAT_BASE_URL = 'http://test.local/chat';
34
+
35
+ const makeClient = (sessionToken: string = 'test-token') =>
36
+ new ApiClient(TEST_BASE_URL, sessionToken, TEST_CHAT_BASE_URL);
37
+
38
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
39
+
40
+ afterEach(() => {
41
+ if (originalFetch === undefined) {
42
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
43
+ } else {
44
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
45
+ }
46
+ jest.restoreAllMocks();
47
+ });
48
+
49
+ const mockJson = (body: unknown, init?: { ok?: boolean; status?: number }) => {
50
+ const fetchMock = jest.fn().mockResolvedValue({
51
+ ok: init?.ok ?? true,
52
+ status: init?.status ?? 200,
53
+ json: async () => body,
54
+ });
55
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
56
+ return fetchMock;
57
+ };
58
+
59
+ const buildSettings = (): PersonaGenerationSettings => ({
60
+ user_id: 'u-1',
61
+ default_voice_id: 'voice-default',
62
+ default_tts_model_id: 'inworld-tts-1',
63
+ default_temperature: 1.1,
64
+ default_speaking_rate: 1.0,
65
+ default_audio_format: 'PCM16',
66
+ default_enable_markups: false,
67
+ default_chat_model_id: 'amazon.nova-pro-v1:0',
68
+ default_system_prompt_template: null,
69
+ default_system_prompt_override: false,
70
+ entity_type_filter: ['person'],
71
+ min_dialog_lines: 1,
72
+ min_graph_speakers: 1,
73
+ max_personas: 20,
74
+ auto_generate_enabled: true,
75
+ voice_clone_max_retries: 3,
76
+ voice_clone_min_clip_seconds: 10.0,
77
+ updated_at: '2026-06-14T00:00:00Z',
78
+ });
79
+
80
+ describe('getPersonaGenSettings', () => {
81
+ it('GETs /api/v1/personas/settings/generation on the CHAT base URL', async () => {
82
+ const fetchMock = mockJson(buildSettings());
83
+
84
+ const result = await makeClient().getPersonaGenSettings();
85
+
86
+ expect(fetchMock).toHaveBeenCalledTimes(1);
87
+ const [url, init] = fetchMock.mock.calls[0];
88
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/personas/settings/generation`);
89
+ // Default RequestInit → GET (no method override).
90
+ expect(init?.method).toBeUndefined();
91
+ expect(result?.max_personas).toBe(20);
92
+ expect(result?.entity_type_filter).toEqual(['person']);
93
+ });
94
+
95
+ it('returns null when the user has never saved settings', async () => {
96
+ mockJson(null);
97
+ const result = await makeClient().getPersonaGenSettings();
98
+ expect(result).toBeNull();
99
+ });
100
+ });
101
+
102
+ describe('updatePersonaGenSettings', () => {
103
+ it('PUTs the partial body to settings/generation and returns the merged settings', async () => {
104
+ const merged = { ...buildSettings(), max_personas: 5, min_dialog_lines: 2 };
105
+ const fetchMock = mockJson(merged);
106
+
107
+ const body: UpdatePersonaGenSettingsRequest = {
108
+ max_personas: 5,
109
+ min_dialog_lines: 2,
110
+ };
111
+ const result = await makeClient().updatePersonaGenSettings(body);
112
+
113
+ const [url, init] = fetchMock.mock.calls[0];
114
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/personas/settings/generation`);
115
+ expect(init?.method).toBe('PUT');
116
+ expect(JSON.parse(init?.body as string)).toEqual(body);
117
+ expect(result.max_personas).toBe(5);
118
+ expect(result.min_dialog_lines).toBe(2);
119
+ });
120
+ });
121
+
122
+ describe('generatePersonasForVideo', () => {
123
+ it('POSTs to /api/v1/videos/{videoId}/personas/generate and returns the job envelope', async () => {
124
+ const envelope: GeneratePersonasJobResponse = {
125
+ jobId: 'job-abc',
126
+ status: 'pending',
127
+ traceId: 'trace-xyz',
128
+ };
129
+ const fetchMock = mockJson(envelope, { status: 202 });
130
+
131
+ const result = await makeClient().generatePersonasForVideo('v-123');
132
+
133
+ const [url, init] = fetchMock.mock.calls[0];
134
+ // camelCase wire keys (jobId/traceId) match the backend alias serialization.
135
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/videos/v-123/personas/generate`);
136
+ expect(init?.method).toBe('POST');
137
+ // C3a-f1: with no entityIds the call is byte-identical to before — NO body
138
+ // (the whole-video wire shape; the backend defaults to all characters).
139
+ expect(init?.body).toBeUndefined();
140
+ expect(result.jobId).toBe('job-abc');
141
+ expect(result.status).toBe('pending');
142
+ expect(result.traceId).toBe('trace-xyz');
143
+ });
144
+
145
+ it('URI-encodes the video id', async () => {
146
+ const fetchMock = mockJson({ jobId: 'j', status: 'pending' });
147
+ await makeClient().generatePersonasForVideo('v/with space');
148
+ const [url] = fetchMock.mock.calls[0];
149
+ expect(url).toBe(
150
+ `${TEST_CHAT_BASE_URL}/api/v1/videos/${encodeURIComponent('v/with space')}/personas/generate`,
151
+ );
152
+ });
153
+
154
+ it('C3a-f1: sends a snake_case entity_ids body when an entityIds subset is given', async () => {
155
+ const fetchMock = mockJson({ jobId: 'j', status: 'pending' });
156
+ await makeClient().generatePersonasForVideo('v-1', {
157
+ entityIds: ['ent-A', 'ent-B'],
158
+ });
159
+ const [, init] = fetchMock.mock.calls[0];
160
+ expect(init?.method).toBe('POST');
161
+ // Body mirrors GeneratePersonasRequest (snake_case), NOT the camelCase
162
+ // response model.
163
+ expect(JSON.parse(init?.body as string)).toEqual({
164
+ entity_ids: ['ent-A', 'ent-B'],
165
+ });
166
+ });
167
+
168
+ it('C3a-f1: an empty entityIds subset sends no body (whole-video default)', async () => {
169
+ const fetchMock = mockJson({ jobId: 'j', status: 'pending' });
170
+ await makeClient().generatePersonasForVideo('v-1', { entityIds: [] });
171
+ const [, init] = fetchMock.mock.calls[0];
172
+ expect(init?.body).toBeUndefined();
173
+ });
174
+ });
175
+
176
+ describe('getPersonaJob', () => {
177
+ it('GETs /api/v1/persona-jobs/{jobId} and returns the snake_case job record', async () => {
178
+ const job: AutoGenerationJob = {
179
+ job_id: 'job-abc',
180
+ user_id: 'u-1',
181
+ video_id: 'v-123',
182
+ status: 'cloning',
183
+ created_at: '2026-06-14T18:01:02Z',
184
+ updated_at: '2026-06-14T18:03:14Z',
185
+ progress: { total_characters: 4, synthesized: 4, cloned: 2, failed: 0 },
186
+ persona_ids: ['p-1', 'p-2'],
187
+ errors: [],
188
+ clips_used: { 'p-1': [3, 7] },
189
+ };
190
+ const fetchMock = mockJson(job);
191
+
192
+ const result = await makeClient().getPersonaJob('job-abc');
193
+
194
+ const [url] = fetchMock.mock.calls[0];
195
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/persona-jobs/job-abc`);
196
+ expect(result.status).toBe('cloning');
197
+ expect(result.progress.cloned).toBe(2);
198
+ expect(result.persona_ids).toEqual(['p-1', 'p-2']);
199
+ });
200
+
201
+ it('URI-encodes the job id', async () => {
202
+ const fetchMock = mockJson({});
203
+ await makeClient().getPersonaJob('job/weird');
204
+ const [url] = fetchMock.mock.calls[0];
205
+ expect(url).toBe(
206
+ `${TEST_CHAT_BASE_URL}/api/v1/persona-jobs/${encodeURIComponent('job/weird')}`,
207
+ );
208
+ });
209
+ });
210
+
211
+ describe('listPersonasByVideo', () => {
212
+ it('GETs /api/v1/personas?source_video_id= and returns the list response', async () => {
213
+ const fetchMock = mockJson({
214
+ personas: [],
215
+ total: 0,
216
+ next_token: null,
217
+ });
218
+
219
+ const result = await makeClient().listPersonasByVideo('v-123');
220
+
221
+ const [url] = fetchMock.mock.calls[0];
222
+ expect(url).toBe(
223
+ `${TEST_CHAT_BASE_URL}/api/v1/personas?source_video_id=v-123`,
224
+ );
225
+ expect(result.personas).toEqual([]);
226
+ expect(result.total).toBe(0);
227
+ });
228
+
229
+ it('is also reachable via listPersonas({ sourceVideoId })', async () => {
230
+ const fetchMock = mockJson({ personas: [], total: 0, next_token: null });
231
+ await makeClient().listPersonas({ sourceVideoId: 'v-9' });
232
+ const [url] = fetchMock.mock.calls[0];
233
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/personas?source_video_id=v-9`);
234
+ });
235
+ });
236
+
237
+ // A fetch mock returning a binary body via `.blob()` (the audio/wav response).
238
+ const mockBlob = (
239
+ body: BlobPart,
240
+ init?: { ok?: boolean; status?: number; json?: unknown },
241
+ ) => {
242
+ const blob = new Blob([body], { type: 'audio/wav' });
243
+ const fetchMock = jest.fn().mockResolvedValue({
244
+ ok: init?.ok ?? true,
245
+ status: init?.status ?? 200,
246
+ blob: async () => blob,
247
+ json: async () => init?.json ?? {},
248
+ });
249
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
250
+ return fetchMock;
251
+ };
252
+
253
+ describe('auditionPersona', () => {
254
+ it('POSTs to /personas/{id}/audition with a JSON body and returns the audio blob', async () => {
255
+ const fetchMock = mockBlob('RIFFwav');
256
+
257
+ const blob = await makeClient().auditionPersona('p-1', { text: 'Hi there' });
258
+
259
+ expect(fetchMock).toHaveBeenCalledTimes(1);
260
+ const [url, init] = fetchMock.mock.calls[0];
261
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/personas/p-1/audition`);
262
+ expect(init?.method).toBe('POST');
263
+ expect(JSON.parse(init?.body as string)).toEqual({ text: 'Hi there' });
264
+ expect((init?.headers as Record<string, string>)['Authorization']).toBe('Bearer test-token');
265
+ expect(blob.type).toBe('audio/wav');
266
+ });
267
+
268
+ it('sends an empty JSON object when no body is given (default sample text)', async () => {
269
+ const fetchMock = mockBlob('x');
270
+ await makeClient().auditionPersona('p-2');
271
+ const [, init] = fetchMock.mock.calls[0];
272
+ expect(JSON.parse(init?.body as string)).toEqual({});
273
+ });
274
+
275
+ it('URI-encodes the persona id', async () => {
276
+ const fetchMock = mockBlob('x');
277
+ await makeClient().auditionPersona('p/weird');
278
+ const [url] = fetchMock.mock.calls[0];
279
+ expect(url).toBe(
280
+ `${TEST_CHAT_BASE_URL}/api/v1/personas/${encodeURIComponent('p/weird')}/audition`,
281
+ );
282
+ });
283
+
284
+ it('throws the FastAPI detail when the render fails', async () => {
285
+ mockBlob('x', {
286
+ ok: false,
287
+ status: 502,
288
+ json: { detail: 'Voice audition render failed' },
289
+ });
290
+ await expect(makeClient().auditionPersona('p-1')).rejects.toThrow(
291
+ 'Voice audition render failed',
292
+ );
293
+ });
294
+ });
295
+
296
+ describe('reclonePersona', () => {
297
+ it('POSTs to /personas/{id}/reclone and returns the camelCase response', async () => {
298
+ const body: ReclonedPersonaResponse = {
299
+ personaId: 'p-1',
300
+ voiceId: 'voice-new',
301
+ clipsUsed: [0, 1, 2, 3],
302
+ };
303
+ const fetchMock = mockJson(body);
304
+
305
+ const result = await makeClient().reclonePersona('p-1');
306
+
307
+ const [url, init] = fetchMock.mock.calls[0];
308
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/personas/p-1/reclone`);
309
+ expect(init?.method).toBe('POST');
310
+ expect(result.voiceId).toBe('voice-new');
311
+ expect(result.clipsUsed).toEqual([0, 1, 2, 3]);
312
+ });
313
+
314
+ it('raises a typed RecloneConflictError on a 409 retries-exhausted', async () => {
315
+ mockJson(
316
+ { detail: { error: 'voice_clone_max_retries_exhausted', attempts: 3 } },
317
+ { ok: false, status: 409 },
318
+ );
319
+ const err = await makeClient()
320
+ .reclonePersona('p-1')
321
+ .catch((e) => e);
322
+ expect(err).toBeInstanceOf(RecloneConflictError);
323
+ expect(err.code).toBe('voice_clone_max_retries_exhausted');
324
+ expect(err.attempts).toBe(3);
325
+ });
326
+
327
+ it('raises a typed RecloneConflictError on a 409 no-clips-remaining', async () => {
328
+ mockJson(
329
+ { detail: { error: 'no_candidate_clips_remaining' } },
330
+ { ok: false, status: 409 },
331
+ );
332
+ const err = await makeClient()
333
+ .reclonePersona('p-1')
334
+ .catch((e) => e);
335
+ expect(err).toBeInstanceOf(RecloneConflictError);
336
+ expect(err.code).toBe('no_candidate_clips_remaining');
337
+ });
338
+
339
+ it('throws the FastAPI detail string on a non-conflict failure', async () => {
340
+ mockJson({ detail: 'Voice cloning failed' }, { ok: false, status: 502 });
341
+ await expect(makeClient().reclonePersona('p-1')).rejects.toThrow('Voice cloning failed');
342
+ });
343
+
344
+ it('URI-encodes the persona id', async () => {
345
+ const fetchMock = mockJson({ personaId: 'x', voiceId: 'v', clipsUsed: [] });
346
+ await makeClient().reclonePersona('p/weird');
347
+ const [url] = fetchMock.mock.calls[0];
348
+ expect(url).toBe(
349
+ `${TEST_CHAT_BASE_URL}/api/v1/personas/${encodeURIComponent('p/weird')}/reclone`,
350
+ );
351
+ });
352
+ });