import { ContextHost } from '@mokei/host' import type { AggregatedMessage, MessagePart, ModelProvider, ProviderTypes, StreamChatRequest, } from '@mokei/model-provider' import { describe, expect, test } from 'vitest' import { Session } from '../src/session.js' type FakeProviderTypes = ProviderTypes function hangingProvider(): ModelProvider { // Minimal provider: streamChat returns a StreamChatRequest (a Promise with // .abort) that resolves to an empty stream only after abort. const makeRequest = (): StreamChatRequest => { let abortFn: () => void = () => {} const promise = new Promise>>((resolve) => { abortFn = () => resolve(new ReadableStream({ start: (c) => c.close() })) }) ;(promise as unknown as { abort: () => void }).abort = abortFn // Partial mock: `Session.chat()` only ever calls `abort()` on the request, so the // rest of the AbortController surface (`signal`) is deliberately not implemented. return promise as unknown as StreamChatRequest } return { streamChat: makeRequest, aggregateMessage: (): AggregatedMessage => ({ source: 'aggregated', role: 'assistant', text: '', toolCalls: [], inputTokens: 0, outputTokens: 0, }), embed: async () => ({ embeddings: [] }), listModels: async () => [], toolFromMCP: (tool: unknown) => tool, } } describe('Session.chat active-request guard', () => { test('a third concurrent chat is rejected after one replaces another', async () => { const session = new Session() session.addProvider('fake', hangingProvider()) const base = { provider: 'fake', model: 'm', messages: [] } const chatA = session.chat(base).catch(() => 'A-done') await new Promise((r) => setTimeout(r, 5)) // B replaces A by aborting it. const chatB = session.chat({ ...base, abortActiveRequest: true }).catch(() => 'B-done') await new Promise((r) => setTimeout(r, 5)) // C must see B still active and be rejected. await expect(session.chat(base)).rejects.toThrow('already active') // Cleanup: abort B. session.activeChatRequest?.abort() await Promise.all([chatA, chatB]) }) }) describe('Session elicitation', () => { test('Session forwards elicit to its new host', async () => { const session = new Session({ elicit: true }) expect(session.contextHost.elicitationEnabled).toBe(true) await session.dispose() }) test('Session rejects contextHost together with elicit', async () => { const contextHost = new ContextHost() expect(() => new Session({ contextHost, elicit: true })).toThrow(/contextHost.*elicit/i) await contextHost.dispose() }) test('default Session and NodeSession remain disabled', async () => { const session = new Session() expect(session.contextHost.elicitationEnabled).toBe(false) await session.dispose() }) })