import type { ChatTransport, ChatMessage } from './ChatPane'; import { detectNavTarget, getNavigationAction, getNavigationResponse, navigateToUrl } from '@buzztrail/shared-utils'; export class ProxyTransport implements ChatTransport { constructor( private apiBase: string, private options?: { headers?: Record; sessionId?: string } ) {} async send(message: string): Promise { const url = this.apiBase.replace(/\/$/, '') + '/chat/messages'; const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(this.options?.headers ?? {}) }, body: JSON.stringify({ sessionId: this.options?.sessionId, message }), }); if (!r.ok) throw new Error(`Proxy chat ${r.status}`); const data = await r.json(); const text: string = data?.text ?? ''; const id: string = data?.id ?? `${Date.now()}`; return { id, role: 'assistant', text, ts: Date.now() }; } } export class FallbackTransport implements ChatTransport { constructor(private primary: ChatTransport, private fallback: ChatTransport) {} async send(message: string): Promise { try { return await this.primary.send(message); } catch (err) { try { console.warn('[Chatbot][Chat] proxy failed, using fallback:', err); } catch { // Ignore console.warn errors } return await this.fallback.send(message); } } } export class NavigationTransport implements ChatTransport { constructor( private transport: ChatTransport, private onNavigate?: (url: string) => void ) {} async send(message: string): Promise { const navTarget = detectNavTarget(message); if (navTarget) { const action = getNavigationAction(navTarget); const response = getNavigationResponse(navTarget); if (action.type === 'url') { if (this.onNavigate) { this.onNavigate(action.value as string); } else { navigateToUrl(action.value as string); } } return { id: `${Date.now()}-nav`, role: 'assistant', text: response, ts: Date.now() }; } return await this.transport.send(message); } } // Self-contained transport for local testing without backend export class LocalTestTransport implements ChatTransport { send(message: string): Promise { const navTarget = detectNavTarget(message); if (navTarget) { const action = getNavigationAction(navTarget); const response = getNavigationResponse(navTarget); if (action.type === 'url') { const url = action.value as string; navigateToUrl(url); } return Promise.resolve({ id: `${Date.now()}-nav`, role: 'assistant', text: response, ts: Date.now() }); } // Echo response for non-navigation messages return Promise.resolve({ id: `${Date.now()}-echo`, role: 'assistant', text: `I received your message: "${message}". This is a local test mode. Try asking about "home", "size", "theme", "tracking", "returns", or "success" to test navigation!`, ts: Date.now() }); } }