// Actual hook against a changed server catalog, independently of chat activity. import { act, cleanup, renderHook } from '@testing-library/react'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { useTeacherCompanion } from '@/pages/Chat/use-teacher-companion'; import type { TeacherDefinition, TeacherTopic } from '../../shared/coding-teacher'; const api = vi.hoisted(() => ({ config: vi.fn(), catalog: vi.fn(), catalogRevision: vi.fn(), conversation: vi.fn(), list: vi.fn(), read: vi.fn(), events: vi.fn() })); vi.mock('@/lib/coding-teacher', () => ({ teacherApi: api, teacherTopicsPath: (id: string) => id, teacherConversationsPath: (id: string) => id })); vi.mock('@/stores/auth', () => ({ useAuthStore: (select: (state: unknown) => unknown) => select({ user: { userId: 'diagnostic-user' } }) })); const definition: TeacherDefinition = { schema_version: 1, teacher_id: 'coding-teacher', config_id: 'agent-a', name: 'Old name', description: '', avatar_id: 'avatar-06', welcome_message: '', suggested_questions: [], system_prompt: '', skills: [], model: { model_id: 'model', reasoning_choice: { mode: 'default' } }, limits: { max_input_tokens: 8000, max_output_tokens: 1500 } }; const original = { teacher_id: 'agent-a', version: 1, is_default: true, definition }; const updated = { ...original, version: 2, definition: { ...definition, name: 'New name' } }; beforeEach(() => { vi.resetAllMocks(); vi.useFakeTimers(); localStorage.clear(); Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' }); api.config.mockResolvedValue({ enabled: true, definition }); api.catalog.mockResolvedValue({ revision: 1, items: [original] }); api.catalogRevision.mockResolvedValue({ revision: 1 }); api.conversation.mockResolvedValue({ topic: null, before: null }); api.list.mockResolvedValue({ items: [], lastSelectedTopicId: null }); api.events.mockResolvedValue(Object.assign(new EventTarget(), { close: vi.fn() })); }); afterEach(() => { cleanup(); vi.useRealTimers(); }); it.each(['empty-catalog', 'never-started', 'running', 'completed'] as const)('refreshes changed catalog within five seconds with %s chat', async (state) => { if (state === 'empty-catalog') api.catalog.mockResolvedValue({ revision: 1, items: [] }); if (state === 'running' || state === 'completed') { const topic: TeacherTopic = { schemaVersion: 1, revision: 1, id: 'topic', accountId: 'diagnostic-user', projectId: 'project', sourceConversationId: 'project', version: 1, definition, createdAt: 'now', updatedAt: 'now', conversation: { agentId: 'agent-a', segmentTurns: 1, discussions: {} }, requests: [{ id: 'request', text: 'Question', references: [], createdAt: 'now', sourceCursor: { workerGeneration: 1, seq: 1 }, sourceCapturedAt: 'now', includedSourceMessageIds: [], omittedMessages: 0, status: state, response: '' }] }; api.conversation.mockResolvedValue({ topic, before: null }); } let view!: ReturnType, unknown>>; await act(async () => { view = renderHook(() => useTeacherCompanion({ projectId: 'project', sourceId: 'source', sourceBusy: false, sourceArchived: false, teacherOpen: false, teacherComposing: false })); }); expect(view.result.current.selectedAgent?.version).toBe(state === 'empty-catalog' ? undefined : 1); api.catalog.mockResolvedValue({ revision: 2, items: [updated] }); api.catalogRevision.mockResolvedValue({ revision: 2 }); await act(async () => { await vi.advanceTimersByTimeAsync(5_000); }); expect(view.result.current.selectedAgent?.version).toBe(2); if (state === 'running') { expect(view.result.current.topic?.requests[0].status).toBe('running'); expect(view.result.current.topic?.version).toBe(1); } }); it('keeps unchanged catalogs, pauses while hidden, retries failures and refreshes immediately on focus', async () => { let view!: ReturnType, unknown>>; await act(async () => { view = renderHook(() => useTeacherCompanion({ projectId: 'project', sourceId: 'source', sourceBusy: true, sourceArchived: false, teacherOpen: true, teacherComposing: true })); }); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(api.catalog).toHaveBeenCalledTimes(1); expect(api.catalogRevision).toHaveBeenCalledTimes(2); Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' }); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(api.catalogRevision).toHaveBeenCalledTimes(2); Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' }); api.catalogRevision.mockRejectedValueOnce(new Error('offline')); await act(async () => { window.dispatchEvent(new Event('focus')); }); expect(view.result.current.selectedAgent?.version).toBe(1); api.catalogRevision.mockResolvedValue({ revision: 2 }); api.catalog.mockResolvedValue({ revision: 2, items: [updated] }); await act(async () => { window.dispatchEvent(new Event('focus')); }); expect(view.result.current.selectedAgent?.version).toBe(2); view.unmount(); const calls = api.catalogRevision.mock.calls.length; await act(async () => { await vi.advanceTimersByTimeAsync(5_000); window.dispatchEvent(new Event('focus')); }); expect(api.catalogRevision).toHaveBeenCalledTimes(calls); });