Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

hook-registry.test.ts

584 lines16.8 KB

1import { describe, expect, it, vi } from 'vitest'
2import {
3 addSavedFixture,
4 applyHookEvent,
5 createHookRegistryState,
6 createToolFixtureRecord,
7 getHookUnseenEventCount,
8 removeSavedFixture,
9 setActiveHook,
10} from '../src/store/hook-registry'
11import type {
12 DevtoolsToolFixtureApplyEvent,
13 HookRegisteredEvent,
14 HookStateSnapshotEvent,
15 HookUnregisteredEvent,
16 RunLifecycleEvent,
17 ToolsRegisteredEvent,
18} from '@tanstack/ai-event-client'
19​
20describe('hook registry', () => {
21 it('tracks hook snapshots and run lifecycle events', () => {
22 const state = createHookRegistryState()
23 const registered = createRegisteredEvent()
24 const snapshot = createSnapshotEvent()
25 const started = createRunEvent('run:started', 'started', 3)
26 const completed = createRunEvent('run:completed', 'completed', 4)
27​
28 applyHookEvent(state, 'hook:registered', registered)
29 applyHookEvent(state, 'hook:state-snapshot', snapshot)
30 applyHookEvent(state, 'run:started', started)
31 applyHookEvent(state, 'run:completed', completed)
32​
33 expect(state.activeHookId).toBe(null)
34 expect(state.hooks['chat-1']?.state.messages).toEqual([
35 { id: 'message-1', role: 'user', content: 'Hello' },
36 ])
37 expect(state.hooks['chat-1']?.runIds).toEqual(['run-1'])
38 expect(state.runs['run-1']?.status).toBe('completed')
39 expect(state.runs['run-1']?.completedAt).toBe(4)
40 expect(Object.keys(state.events)).toHaveLength(4)
41 })
42​
43 it('deduplicates events by event id', () => {
44 const state = createHookRegistryState()
45 const registered = createRegisteredEvent()
46​
47 applyHookEvent(state, 'hook:registered', registered)
48 applyHookEvent(state, 'hook:registered', registered)
49​
50 expect(Object.keys(state.hooks)).toEqual(['chat-1'])
51 expect(state.hooks['chat-1']?.eventIds).toEqual(['evt-registered'])
52 expect(Object.keys(state.events)).toEqual(['evt-registered'])
53 })
54​
55 it('stores hook display names from devtools metadata', () => {
56 const state = createHookRegistryState()
57​
58 applyHookEvent(state, 'hook:registered', {
59 ...createRegisteredEvent(),
60 displayName: 'Recipe Assistant',
61 })
62 applyHookEvent(state, 'hook:state-snapshot', {
63 ...createSnapshotEvent(),
64 eventId: 'evt-snapshot-display-name',
65 displayName: 'Updated Recipe Assistant',
66 })
67​
68 expect(state.hooks['chat-1']?.displayName).toBe('Updated Recipe Assistant')
69 })
70​
71 it('removes hooks and their runs when they unregister', () => {
72 const state = createHookRegistryState()
73​
74 applyHookEvent(state, 'hook:registered', createRegisteredEvent())
75 applyHookEvent(
76 state,
77 'run:started',
78 createRunEvent('run:started', 'started', 2),
79 )
80 setActiveHook(state, 'chat-1')
81​
82 applyHookEvent(state, 'hook:unregistered', createUnregisteredEvent())
83​
84 expect(state.hooks['chat-1']).toBeUndefined()
85 expect(state.runs['run-1']).toBeUndefined()
86 expect(state.activeHookId).toBe(null)
87 expect(getHookUnseenEventCount(state, 'chat-1')).toBe(0)
88 expect(state.events['evt-unregistered']?.eventType).toBe(
89 'hook:unregistered',
90 )
91 })
92​
93 it('ignores unregister events from a previous hook instance', () => {
94 const state = createHookRegistryState()
95​
96 applyHookEvent(state, 'hook:registered', {
97 ...createRegisteredEvent(),
98 eventId: 'evt-registered-a',
99 correlationId: 'bridge-a',
100 timestamp: 1,
101 })
102 applyHookEvent(state, 'hook:registered', {
103 ...createRegisteredEvent(),
104 eventId: 'evt-registered-b',
105 correlationId: 'bridge-b',
106 timestamp: 2,
107 })
108 applyHookEvent(state, 'hook:updated', {
109 ...createRegisteredEvent(),
110 eventId: 'evt-updated-a',
111 lifecycle: 'active',
112 correlationId: 'bridge-a',
113 timestamp: 3,
114 })
115 applyHookEvent(state, 'hook:state-snapshot', {
116 ...createSnapshotEvent(),
117 eventId: 'evt-snapshot-a',
118 correlationId: 'bridge-a',
119 timestamp: 4,
120 })
121 applyHookEvent(state, 'hook:unregistered', {
122 ...createUnregisteredEvent(),
123 eventId: 'evt-unregistered-a',
124 correlationId: 'bridge-a',
125 timestamp: 5,
126 })
127​
128 expect(state.hooks['chat-1']?.hookName).toBe('useChat')
129 expect(state.hooks['chat-1']?.correlationId).toBe('bridge-b')
130 expect(state.unregisteredHookIds['chat-1']).toBeUndefined()
131 })
132​
133 it('does not recreate unmounted hooks from late run events', () => {
134 const state = createHookRegistryState()
135​
136 applyHookEvent(state, 'hook:registered', createRegisteredEvent())
137 applyHookEvent(state, 'hook:unregistered', createUnregisteredEvent())
138 applyHookEvent(
139 state,
140 'run:completed',
141 createRunEvent('run:completed:late', 'completed', 4),
142 )
143​
144 expect(state.hooks['chat-1']).toBeUndefined()
145 expect(state.runs['run-1']).toBeUndefined()
146​
147 applyHookEvent(state, 'hook:registered', {
148 ...createRegisteredEvent(),
149 eventId: 'evt-registered-again',
150 timestamp: 5,
151 })
152​
153 expect(state.hooks['chat-1']?.hookName).toBe('useChat')
154 })
155​
156 it('ignores hook lifecycle events from another browser runtime', () => {
157 const state = createHookRegistryState()
158​
159 applyHookEvent(state, 'hook:registered', {
160 ...createRegisteredEvent(),
161 eventId: 'evt-foreign-registered',
162 runtimeId: 'other-runtime',
163 })
164​
165 expect(state.hooks['chat-1']).toBeUndefined()
166 expect(Object.keys(state.events)).toHaveLength(0)
167​
168 applyHookEvent(state, 'hook:registered', {
169 ...createRegisteredEvent(),
170 eventId: 'evt-local-registered',
171 runtimeId: getLocalRuntimeId(),
172 })
173​
174 expect(state.hooks['chat-1']?.hookName).toBe('useChat')
175 })
176​
177 it('tracks unseen hook updates from user-triggered runs only', () => {
178 const state = createHookRegistryState()
179 const registered = createRegisteredEvent()
180 const imageRegistered: HookRegisteredEvent = {
181 ...registered,
182 eventId: 'evt-image-registered',
183 timestamp: 10,
184 clientId: 'image-1',
185 hookId: 'image-1',
186 threadId: 'thread-image',
187 hookName: 'useGenerateImage',
188 outputKind: 'image',
189 }
190 const imageSnapshot: HookStateSnapshotEvent = {
191 ...createSnapshotEvent(),
192 eventId: 'evt-image-snapshot',
193 timestamp: 11,
194 clientId: 'image-1',
195 hookId: 'image-1',
196 threadId: 'thread-image',
197 hookName: 'useGenerateImage',
198 outputKind: 'image',
199 state: {
200 status: 'generating',
201 isLoading: true,
202 },
203 }
204​
205 applyHookEvent(state, 'hook:registered', registered)
206 expect(getHookUnseenEventCount(state, 'chat-1')).toBe(0)
207​
208 applyHookEvent(state, 'hook:registered', imageRegistered)
209 expect(getHookUnseenEventCount(state, 'image-1')).toBe(0)
210​
211 applyHookEvent(state, 'hook:state-snapshot', imageSnapshot)
212 expect(getHookUnseenEventCount(state, 'image-1')).toBe(0)
213​
214 applyHookEvent(state, 'tools:registered', {
215 eventId: 'evt-image-tools',
216 timestamp: 12,
217 source: 'client',
218 visibility: 'client-state',
219 hookId: 'image-1',
220 hookName: 'useGenerateImage',
221 outputKind: 'image',
222 tools: [],
223 })
224 expect(getHookUnseenEventCount(state, 'image-1')).toBe(0)
225​
226 setActiveHook(state, 'image-1')
227 expect(getHookUnseenEventCount(state, 'image-1')).toBe(0)
228​
229 applyHookEvent(state, 'run:created', {
230 eventId: 'evt-image-run-created',
231 timestamp: 13,
232 source: 'client',
233 visibility: 'client-state',
234 clientId: 'image-1',
235 hookId: 'image-1',
236 threadId: 'thread-image',
237 runId: 'run-image',
238 status: 'created',
239 })
240 expect(getHookUnseenEventCount(state, 'image-1')).toBe(0)
241​
242 setActiveHook(state, 'chat-1')
243 applyHookEvent(state, 'run:updated', {
244 eventId: 'evt-image-run-updated',
245 timestamp: 14,
246 source: 'client',
247 visibility: 'client-state',
248 clientId: 'image-1',
249 hookId: 'image-1',
250 threadId: 'thread-image',
251 runId: 'run-image',
252 status: 'updated',
253 })
254​
255 expect(getHookUnseenEventCount(state, 'image-1')).toBe(0)
256​
257 applyHookEvent(state, 'run:created', {
258 eventId: 'evt-image-run-created-2',
259 timestamp: 15,
260 source: 'client',
261 visibility: 'client-state',
262 clientId: 'image-1',
263 hookId: 'image-1',
264 threadId: 'thread-image',
265 runId: 'run-image-2',
266 status: 'created',
267 })
268​
269 expect(getHookUnseenEventCount(state, 'image-1')).toBe(1)
270 })
271​
272 it('backfills run history from a state snapshot when devtools mounts after run completion', () => {
273 const state = createHookRegistryState()
274 applyHookEvent(state, 'hook:registered', createRegisteredEvent())
275​
276 // Snapshot ships an embedded `runs` array with a fully-completed run —
277 // simulating the case where devtools opens after the run has already
278 // finished, so the run lifecycle events fired before mount are lost.
279 applyHookEvent(state, 'hook:state-snapshot', {
280 ...createSnapshotEvent(),
281 eventId: 'evt-snapshot-backfill',
282 timestamp: 100,
283 state: {
284 status: 'success',
285 runs: [
286 {
287 id: 'run-historical-1',
288 status: 'completed',
289 startedAt: 80,
290 updatedAt: 95,
291 completedAt: 95,
292 },
293 ],
294 },
295 })
296​
297 expect(state.runs['run-historical-1']?.status).toBe('completed')
298 expect(state.runs['run-historical-1']?.completedAt).toBe(95)
299 expect(state.hooks['chat-1']?.runIds).toContain('run-historical-1')
300 })
301​
302 it('maps non-canonical snapshot run statuses and skips unknown statuses', () => {
303 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
304 const state = createHookRegistryState()
305 applyHookEvent(state, 'hook:registered', createRegisteredEvent())
306​
307 applyHookEvent(state, 'hook:state-snapshot', {
308 ...createSnapshotEvent(),
309 eventId: 'evt-snapshot-mixed-statuses',
310 timestamp: 200,
311 state: {
312 runs: [
313 { id: 'run-success', status: 'success', startedAt: 1, updatedAt: 2 },
314 { id: 'run-error', status: 'error', startedAt: 3, updatedAt: 4 },
315 { id: 'run-idle', status: 'idle', startedAt: 5, updatedAt: 6 },
316 {
317 id: 'run-bogus',
318 status: 'not-a-real-status',
319 startedAt: 7,
320 updatedAt: 8,
321 },
322 ],
323 },
324 })
325​
326 expect(state.runs['run-success']?.status).toBe('completed')
327 expect(state.runs['run-error']?.status).toBe('errored')
328 expect(state.runs['run-idle']?.status).toBe('created')
329 expect(state.runs['run-bogus']).toBeUndefined()
330 expect(warnSpy).toHaveBeenCalledWith(
331 expect.stringContaining('unknown run.status in snapshot'),
332 )
333 warnSpy.mockRestore()
334 })
335​
336 it('infers hook lifecycle from snapshot state shape', () => {
337 const state = createHookRegistryState()
338 applyHookEvent(state, 'hook:registered', createRegisteredEvent())
339​
340 applyHookEvent(state, 'hook:state-snapshot', {
341 ...createSnapshotEvent(),
342 eventId: 'evt-snapshot-streaming',
343 timestamp: 10,
344 state: { status: 'generating' },
345 })
346 expect(state.hooks['chat-1']?.lifecycle).toBe('streaming')
347​
348 applyHookEvent(state, 'hook:state-snapshot', {
349 ...createSnapshotEvent(),
350 eventId: 'evt-snapshot-errored',
351 timestamp: 11,
352 state: { status: 'error' },
353 })
354 expect(state.hooks['chat-1']?.lifecycle).toBe('errored')
355​
356 applyHookEvent(state, 'hook:state-snapshot', {
357 ...createSnapshotEvent(),
358 eventId: 'evt-snapshot-active',
359 timestamp: 12,
360 state: { status: 'ready' },
361 })
362 expect(state.hooks['chat-1']?.lifecycle).toBe('active')
363 })
364​
365 it('stores tool metadata without saving replayed devtools fixtures', () => {
366 const state = createHookRegistryState()
367 const toolsEvent: ToolsRegisteredEvent = {
368 eventId: 'evt-tools',
369 timestamp: 5,
370 source: 'client',
371 visibility: 'client-state',
372 hookId: 'chat-1',
373 hookName: 'useChat',
374 outputKind: 'chat',
375 tools: [
376 {
377 name: 'search',
378 description: 'Search docs',
379 inputSchema: {
380 type: 'object',
381 properties: {
382 query: { type: 'string' },
383 },
384 required: ['query'],
385 },
386 },
387 ],
388 }
389 const fixtureEvent: DevtoolsToolFixtureApplyEvent = {
390 eventId: 'fixture-1',
391 timestamp: 6,
392 source: 'devtools',
393 visibility: 'devtools-action',
394 hookId: 'chat-1',
395 threadId: 'thread-1',
396 toolName: 'search',
397 input: { query: 'structured output' },
398 output: { result: 'found' },
399 toolCallId: 'tool-call-1',
400 messageId: 'message-2',
401 }
402​
403 applyHookEvent(state, 'tools:registered', toolsEvent)
404 applyHookEvent(state, 'devtools:tool-fixture:apply', fixtureEvent)
405​
406 expect(state.hooks['chat-1']?.tools).toEqual(toolsEvent.tools)
407 expect(state.fixtures).toEqual([])
408 })
409​
410 it('tracks repeated replay events without mutating saved fixtures', () => {
411 const state = createHookRegistryState()
412 const base: DevtoolsToolFixtureApplyEvent = {
413 eventId: 'apply-1',
414 timestamp: 1000,
415 source: 'devtools',
416 visibility: 'devtools-action',
417 fixtureId: 'fixture-1',
418 hookId: 'chat-1',
419 toolName: 'search',
420 input: { query: 'devtools' },
421 output: { result: 'first' },
422 }
423​
424 applyHookEvent(state, 'devtools:tool-fixture:apply', base)
425 applyHookEvent(state, 'devtools:tool-fixture:apply', {
426 ...base,
427 eventId: 'apply-2',
428 timestamp: 1001,
429 output: { result: 'second' },
430 })
431​
432 expect(Object.keys(state.events)).toHaveLength(2)
433 expect(state.fixtures).toEqual([])
434 })
435​
436 it('creates stable fixtures from observed tool calls', () => {
437 expect(
438 createToolFixtureRecord({
439 createdAt: 123,
440 hookId: 'chat-1',
441 threadId: 'thread-1',
442 toolName: 'recommendGuitar',
443 name: 'Favorite recommendation',
444 input: { id: '6' },
445 message: {
446 id: 'message-2',
447 role: 'assistant',
448 parts: [
449 {
450 type: 'tool-call',
451 id: 'tool-call-1',
452 name: 'recommendGuitar',
453 arguments: '{"id":"6"}',
454 input: { id: '6' },
455 state: 'input-complete',
456 },
457 ],
458 },
459 toolCallId: 'tool-call-1',
460 messageId: 'message-2',
461 }),
462 ).toEqual({
463 id: 'fixture:chat-1:recommendGuitar:tool-call-1',
464 createdAt: 123,
465 hookId: 'chat-1',
466 threadId: 'thread-1',
467 toolName: 'recommendGuitar',
468 name: 'Favorite recommendation',
469 input: { id: '6' },
470 output: null,
471 message: {
472 id: 'message-2',
473 role: 'assistant',
474 parts: [
475 {
476 type: 'tool-call',
477 id: 'tool-call-1',
478 name: 'recommendGuitar',
479 arguments: '{"id":"6"}',
480 input: { id: '6' },
481 state: 'input-complete',
482 },
483 ],
484 },
485 toolCallId: 'tool-call-1',
486 messageId: 'message-2',
487 })
488 })
489​
490 it('removes saved fixtures by id', () => {
491 const state = createHookRegistryState()
492 const fixture = createToolFixtureRecord({
493 id: 'fixture-1',
494 hookId: 'chat-1',
495 toolName: 'search',
496 name: 'Search docs',
497 execute: true,
498 input: { query: 'devtools' },
499 output: { result: 'found' },
500 })
501​
502 addSavedFixture(state, fixture)
503 removeSavedFixture(state, fixture.id)
504​
505 expect(state.fixtures).toEqual([])
506 })
507})
508​
509function getLocalRuntimeId(): string {
510 return (
511 (globalThis as { __TANSTACK_AI_DEVTOOLS_RUNTIME_ID__?: string })
512 .__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__ ?? ''
513 )
515​
516function createRegisteredEvent(): HookRegisteredEvent {
517 return {
518 eventId: 'evt-registered',
519 timestamp: 1,
520 source: 'client',
521 visibility: 'client-state',
522 clientId: 'chat-1',
523 hookId: 'chat-1',
524 threadId: 'thread-1',
525 hookName: 'useChat',
526 framework: 'react',
527 outputKind: 'chat',
528 lifecycle: 'mounted',
529 }
531​
532function createSnapshotEvent(): HookStateSnapshotEvent {
533 return {
534 eventId: 'evt-snapshot',
535 timestamp: 2,
536 source: 'client',
537 visibility: 'client-state',
538 clientId: 'chat-1',
539 hookId: 'chat-1',
540 threadId: 'thread-1',
541 hookName: 'useChat',
542 framework: 'react',
543 outputKind: 'chat',
544 state: {
545 messages: [{ id: 'message-1', role: 'user', content: 'Hello' }],
546 status: 'ready',
547 isLoading: false,
548 },
549 }
551​
552function createUnregisteredEvent(): HookUnregisteredEvent {
553 return {
554 eventId: 'evt-unregistered',
555 timestamp: 3,
556 source: 'client',
557 visibility: 'client-state',
558 clientId: 'chat-1',
559 hookId: 'chat-1',
560 threadId: 'thread-1',
561 hookName: 'useChat',
562 framework: 'react',
563 outputKind: 'chat',
564 reason: 'disposed',
565 }
567​
568function createRunEvent(
569 eventId: string,
570 status: RunLifecycleEvent['status'],
571 timestamp: number,
572): RunLifecycleEvent {
573 return {
574 eventId,
575 timestamp,
576 source: 'client',
577 visibility: 'client-state',
578 clientId: 'chat-1',
579 hookId: 'chat-1',
580 threadId: 'thread-1',
581 runId: 'run-1',
582 status,
583 }