import { Spinner } from '@inkjs/ui' import { Box, Text, useApp } from 'ink' import { type ReactNode, useEffect, useState } from 'react' import { LlamaPathCard } from './components/LlamaPathCard.js' import { ProviderSelectCard } from './components/ProviderSelectCard.js' import { type BuiltChat, buildChat, type ChatOptions } from './providers.js' // Mutable handle the command holds so it can await session disposal AFTER the // ink app exits. The session owns a persistent daemon socket that keeps the // event loop alive; disposing it from the command (not fire-and-forget on // unmount) is what lets the process actually exit on quit. export type ChatLifecycle = { dispose: (() => Promise) | null } export type ChatLauncherProps = { initialProvider?: string chatOptions: ChatOptions lifecycle: ChatLifecycle } export function ChatLauncher({ initialProvider, chatOptions, lifecycle }: ChatLauncherProps) { const { exit } = useApp() const [provider, setProvider] = useState(initialProvider) const [modelPath, setModelPath] = useState(undefined) const [chat, setChat] = useState(null) const [error, setError] = useState(null) const llamaPath = chatOptions.model ?? modelPath const needsLlamaPath = provider === 'llama' && (llamaPath == null || llamaPath === '') useEffect(() => { if (provider == null) return if (needsLlamaPath) return let cancelled = false const opts = provider === 'llama' ? { ...chatOptions, model: llamaPath } : chatOptions buildChat(provider, opts).then( (built) => { if (cancelled) { // Quit happened while connecting -- dispose the orphaned session. void built.dispose() return } lifecycle.dispose = built.dispose setChat(built) }, (err) => { if (!cancelled) setError((err as Error).message) }, ) return () => { cancelled = true } }, [provider, chatOptions, lifecycle, needsLlamaPath, llamaPath]) useEffect(() => { if (error != null) { process.exitCode = 1 exit() } }, [error, exit]) if (error != null) { return ( error: {error} ) } if (provider == null) { return } if (needsLlamaPath) { return } if (chat == null) { return ( ) } return chat.element as ReactNode }