|
| 1 | +import { createContext, useContext, useReducer, useCallback, type ReactNode } from "react"; |
| 2 | +import { useAllFiles } from "@app/contexts/FileContext"; |
| 3 | + |
| 4 | +export interface ChatMessage { |
| 5 | + id: string; |
| 6 | + role: "user" | "assistant"; |
| 7 | + content: string; |
| 8 | + timestamp: number; |
| 9 | +} |
| 10 | + |
| 11 | +type AiWorkflowOutcome = |
| 12 | + | "answer" |
| 13 | + | "not_found" |
| 14 | + | "need_content" |
| 15 | + | "plan" |
| 16 | + | "need_clarification" |
| 17 | + | "cannot_do" |
| 18 | + | "tool_call" |
| 19 | + | "completed" |
| 20 | + | "unsupported_capability" |
| 21 | + | "cannot_continue"; |
| 22 | + |
| 23 | +interface AiWorkflowResponse { |
| 24 | + outcome: AiWorkflowOutcome; |
| 25 | + answer?: string; |
| 26 | + summary?: string; |
| 27 | + rationale?: string; |
| 28 | + reason?: string; |
| 29 | + question?: string; |
| 30 | + capability?: string; |
| 31 | + message?: string; |
| 32 | + evidence?: Array<{ pageNumber: number; text: string }>; |
| 33 | + steps?: Array<Record<string, unknown>>; |
| 34 | +} |
| 35 | + |
| 36 | +interface ChatState { |
| 37 | + messages: ChatMessage[]; |
| 38 | + isOpen: boolean; |
| 39 | + isLoading: boolean; |
| 40 | +} |
| 41 | + |
| 42 | +type ChatAction = |
| 43 | + | { type: "ADD_MESSAGE"; message: ChatMessage } |
| 44 | + | { type: "SET_LOADING"; loading: boolean } |
| 45 | + | { type: "TOGGLE_OPEN" } |
| 46 | + | { type: "SET_OPEN"; open: boolean }; |
| 47 | + |
| 48 | +function chatReducer(state: ChatState, action: ChatAction): ChatState { |
| 49 | + switch (action.type) { |
| 50 | + case "ADD_MESSAGE": |
| 51 | + return { ...state, messages: [...state.messages, action.message] }; |
| 52 | + case "SET_LOADING": |
| 53 | + return { ...state, isLoading: action.loading }; |
| 54 | + case "TOGGLE_OPEN": |
| 55 | + return { ...state, isOpen: !state.isOpen }; |
| 56 | + case "SET_OPEN": |
| 57 | + return { ...state, isOpen: action.open }; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +function formatWorkflowResponse(data: AiWorkflowResponse): string { |
| 62 | + switch (data.outcome) { |
| 63 | + case "answer": |
| 64 | + case "completed": |
| 65 | + return data.answer ?? data.summary ?? "Done."; |
| 66 | + case "need_clarification": |
| 67 | + return data.question ?? "Could you clarify your request?"; |
| 68 | + case "cannot_do": |
| 69 | + return data.reason ?? "I'm unable to do that."; |
| 70 | + case "not_found": |
| 71 | + return data.reason ?? "I couldn't find the requested information."; |
| 72 | + case "unsupported_capability": |
| 73 | + return data.message ?? `Unsupported capability: ${data.capability ?? "unknown"}`; |
| 74 | + case "cannot_continue": |
| 75 | + return data.reason ?? "Something went wrong and I can't continue."; |
| 76 | + case "plan": |
| 77 | + return data.rationale |
| 78 | + ? `${data.rationale}\n\n${(data.steps ?? []).map((s, i) => `${i + 1}. ${JSON.stringify(s)}`).join("\n")}` |
| 79 | + : JSON.stringify(data.steps, null, 2); |
| 80 | + case "need_content": |
| 81 | + case "tool_call": |
| 82 | + return data.rationale ?? data.summary ?? `Processing (${data.outcome})...`; |
| 83 | + default: |
| 84 | + return data.answer ?? data.summary ?? data.message ?? JSON.stringify(data); |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +interface ChatContextValue { |
| 89 | + messages: ChatMessage[]; |
| 90 | + isOpen: boolean; |
| 91 | + isLoading: boolean; |
| 92 | + toggleOpen: () => void; |
| 93 | + setOpen: (open: boolean) => void; |
| 94 | + sendMessage: (content: string) => Promise<void>; |
| 95 | +} |
| 96 | + |
| 97 | +const ChatContext = createContext<ChatContextValue | null>(null); |
| 98 | + |
| 99 | +const initialState: ChatState = { |
| 100 | + messages: [], |
| 101 | + isOpen: false, |
| 102 | + isLoading: false, |
| 103 | +}; |
| 104 | + |
| 105 | +export function ChatProvider({ children }: { children: ReactNode }) { |
| 106 | + const [state, dispatch] = useReducer(chatReducer, initialState); |
| 107 | + const { files: activeFiles } = useAllFiles(); |
| 108 | + |
| 109 | + const toggleOpen = useCallback(() => dispatch({ type: "TOGGLE_OPEN" }), []); |
| 110 | + const setOpen = useCallback((open: boolean) => dispatch({ type: "SET_OPEN", open }), []); |
| 111 | + |
| 112 | + const sendMessage = useCallback(async (content: string) => { |
| 113 | + const userMessage: ChatMessage = { |
| 114 | + id: crypto.randomUUID(), |
| 115 | + role: "user", |
| 116 | + content, |
| 117 | + timestamp: Date.now(), |
| 118 | + }; |
| 119 | + dispatch({ type: "ADD_MESSAGE", message: userMessage }); |
| 120 | + dispatch({ type: "SET_LOADING", loading: true }); |
| 121 | + |
| 122 | + try { |
| 123 | + const formData = new FormData(); |
| 124 | + formData.append("userMessage", content); |
| 125 | + activeFiles.forEach((file, i) => { |
| 126 | + formData.append(`fileInputs[${i}].fileInput`, file); |
| 127 | + }); |
| 128 | + |
| 129 | + const response = await fetch("/api/v1/ai/orchestrate", { |
| 130 | + method: "POST", |
| 131 | + body: formData, |
| 132 | + }); |
| 133 | + |
| 134 | + if (!response.ok) { |
| 135 | + throw new Error(`AI engine request failed: ${response.status}`); |
| 136 | + } |
| 137 | + |
| 138 | + const data: AiWorkflowResponse = await response.json(); |
| 139 | + const replyContent = formatWorkflowResponse(data); |
| 140 | + const assistantMessage: ChatMessage = { |
| 141 | + id: crypto.randomUUID(), |
| 142 | + role: "assistant", |
| 143 | + content: replyContent, |
| 144 | + timestamp: Date.now(), |
| 145 | + }; |
| 146 | + dispatch({ type: "ADD_MESSAGE", message: assistantMessage }); |
| 147 | + } catch { |
| 148 | + const errorMessage: ChatMessage = { |
| 149 | + id: crypto.randomUUID(), |
| 150 | + role: "assistant", |
| 151 | + content: "Failed to get a response. The AI engine may not be available yet.", |
| 152 | + timestamp: Date.now(), |
| 153 | + }; |
| 154 | + dispatch({ type: "ADD_MESSAGE", message: errorMessage }); |
| 155 | + } finally { |
| 156 | + dispatch({ type: "SET_LOADING", loading: false }); |
| 157 | + } |
| 158 | + }, [activeFiles]); |
| 159 | + |
| 160 | + return ( |
| 161 | + <ChatContext.Provider value={{ |
| 162 | + messages: state.messages, |
| 163 | + isOpen: state.isOpen, |
| 164 | + isLoading: state.isLoading, |
| 165 | + toggleOpen, |
| 166 | + setOpen, |
| 167 | + sendMessage, |
| 168 | + }}> |
| 169 | + {children} |
| 170 | + </ChatContext.Provider> |
| 171 | + ); |
| 172 | +} |
| 173 | + |
| 174 | +export function useChat(): ChatContextValue { |
| 175 | + const context = useContext(ChatContext); |
| 176 | + if (!context) { |
| 177 | + throw new Error("useChat must be used within a ChatProvider"); |
| 178 | + } |
| 179 | + return context; |
| 180 | +} |
0 commit comments