rdesign/frontend/node_modules/@copilotkitnext/react/dist/components/chat/CopilotChat.cjs

227 lines
9.1 KiB
JavaScript

const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
const require_CopilotChatConfigurationProvider = require('../../providers/CopilotChatConfigurationProvider.cjs');
const require_slots = require('../../lib/slots.cjs');
const require_CopilotKitProvider = require('../../providers/CopilotKitProvider.cjs');
const require_use_agent = require('../../hooks/use-agent.cjs');
const require_use_suggestions = require('../../hooks/use-suggestions.cjs');
const require_CopilotChatView = require('./CopilotChatView.cjs');
const require_transcription_client = require('../../lib/transcription-client.cjs');
let _ag_ui_client = require("@ag-ui/client");
let react = require("react");
let _copilotkitnext_shared = require("@copilotkitnext/shared");
let react_jsx_runtime = require("react/jsx-runtime");
let ts_deepmerge = require("ts-deepmerge");
//#region src/components/chat/CopilotChat.tsx
function CopilotChat({ agentId, threadId, labels, chatView, onError, ...props }) {
const existingConfig = require_CopilotChatConfigurationProvider.useCopilotChatConfiguration();
const resolvedAgentId = agentId ?? existingConfig?.agentId ?? _copilotkitnext_shared.DEFAULT_AGENT_ID;
const resolvedThreadId = (0, react.useMemo)(() => threadId ?? existingConfig?.threadId ?? (0, _copilotkitnext_shared.randomUUID)(), [threadId, existingConfig?.threadId]);
const { agent } = require_use_agent.useAgent({ agentId: resolvedAgentId });
const { copilotkit } = require_CopilotKitProvider.useCopilotKit();
const { suggestions: autoSuggestions } = require_use_suggestions.useSuggestions({ agentId: resolvedAgentId });
const onErrorRef = (0, react.useRef)(onError);
(0, react.useEffect)(() => {
onErrorRef.current = onError;
}, [onError]);
(0, react.useEffect)(() => {
if (!onErrorRef.current) return;
const subscription = copilotkit.subscribe({ onError: (event) => {
if (event.context?.agentId === resolvedAgentId || !event.context?.agentId) onErrorRef.current?.({
error: event.error,
code: event.code,
context: event.context
});
} });
return () => {
subscription.unsubscribe();
};
}, [copilotkit, resolvedAgentId]);
const [transcribeMode, setTranscribeMode] = (0, react.useState)("input");
const [inputValue, setInputValue] = (0, react.useState)("");
const [transcriptionError, setTranscriptionError] = (0, react.useState)(null);
const [isTranscribing, setIsTranscribing] = (0, react.useState)(false);
const isTranscriptionEnabled = copilotkit.audioFileTranscriptionEnabled;
const isMediaRecorderSupported = typeof window !== "undefined" && typeof MediaRecorder !== "undefined";
const { messageView: providedMessageView, suggestionView: providedSuggestionView, onStop: providedStopHandler, ...restProps } = props;
(0, react.useEffect)(() => {
let detached = false;
const connectAbortController = new AbortController();
if (agent instanceof _ag_ui_client.HttpAgent) agent.abortController = connectAbortController;
const connect = async (agent) => {
try {
await copilotkit.connectAgent({ agent });
} catch (error) {
if (detached) return;
console.error("CopilotChat: connectAgent failed", error);
}
};
agent.threadId = resolvedThreadId;
connect(agent);
return () => {
detached = true;
connectAbortController.abort();
agent.detachActiveRun();
};
}, [
resolvedThreadId,
agent,
resolvedAgentId
]);
const onSubmitInput = (0, react.useCallback)(async (value) => {
agent.addMessage({
id: (0, _copilotkitnext_shared.randomUUID)(),
role: "user",
content: value
});
setInputValue("");
try {
await copilotkit.runAgent({ agent });
} catch (error) {
console.error("CopilotChat: runAgent failed", error);
}
}, [agent]);
const handleSelectSuggestion = (0, react.useCallback)(async (suggestion) => {
agent.addMessage({
id: (0, _copilotkitnext_shared.randomUUID)(),
role: "user",
content: suggestion.message
});
try {
await copilotkit.runAgent({ agent });
} catch (error) {
console.error("CopilotChat: runAgent failed after selecting suggestion", error);
}
}, [agent]);
const stopCurrentRun = (0, react.useCallback)(() => {
try {
copilotkit.stopAgent({ agent });
} catch (error) {
console.error("CopilotChat: stopAgent failed", error);
try {
agent.abortRun();
} catch (abortError) {
console.error("CopilotChat: abortRun fallback failed", abortError);
}
}
}, [agent]);
const handleStartTranscribe = (0, react.useCallback)(() => {
setTranscriptionError(null);
setTranscribeMode("transcribe");
}, []);
const handleCancelTranscribe = (0, react.useCallback)(() => {
setTranscriptionError(null);
setTranscribeMode("input");
}, []);
const handleFinishTranscribe = (0, react.useCallback)(() => {
setTranscribeMode("input");
}, []);
const handleFinishTranscribeWithAudio = (0, react.useCallback)(async (audioBlob) => {
setIsTranscribing(true);
try {
setTranscriptionError(null);
const result = await require_transcription_client.transcribeAudio(copilotkit, audioBlob);
setInputValue((prev) => {
const trimmedPrev = prev.trim();
if (trimmedPrev) return `${trimmedPrev} ${result.text}`;
return result.text;
});
} catch (error) {
console.error("CopilotChat: Transcription failed", error);
if (error instanceof require_transcription_client.TranscriptionError) {
const { code, retryable, message } = error.info;
switch (code) {
case _copilotkitnext_shared.TranscriptionErrorCode.RATE_LIMITED:
setTranscriptionError("Too many requests. Please wait a moment.");
break;
case _copilotkitnext_shared.TranscriptionErrorCode.AUTH_FAILED:
setTranscriptionError("Authentication error. Please check your configuration.");
break;
case _copilotkitnext_shared.TranscriptionErrorCode.AUDIO_TOO_LONG:
setTranscriptionError("Recording is too long. Please try a shorter recording.");
break;
case _copilotkitnext_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT:
setTranscriptionError("Recording is too short. Please try again.");
break;
case _copilotkitnext_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT:
setTranscriptionError("Audio format not supported.");
break;
case _copilotkitnext_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED:
setTranscriptionError("Transcription service is not available.");
break;
case _copilotkitnext_shared.TranscriptionErrorCode.NETWORK_ERROR:
setTranscriptionError("Network error. Please check your connection.");
break;
default: setTranscriptionError(retryable ? "Transcription failed. Please try again." : message);
}
} else setTranscriptionError("Transcription failed. Please try again.");
} finally {
setIsTranscribing(false);
}
}, []);
(0, react.useEffect)(() => {
if (transcriptionError) {
const timer = setTimeout(() => {
setTranscriptionError(null);
}, 5e3);
return () => clearTimeout(timer);
}
}, [transcriptionError]);
const mergedProps = (0, ts_deepmerge.merge)({
isRunning: agent.isRunning,
suggestions: autoSuggestions,
onSelectSuggestion: handleSelectSuggestion,
suggestionView: providedSuggestionView
}, {
...restProps,
...typeof providedMessageView === "string" ? { messageView: { className: providedMessageView } } : providedMessageView !== void 0 ? { messageView: providedMessageView } : {}
});
const hasMessages = agent.messages.length > 0;
const effectiveStopHandler = agent.isRunning && hasMessages ? providedStopHandler ?? stopCurrentRun : providedStopHandler;
const showTranscription = isTranscriptionEnabled && isMediaRecorderSupported;
const effectiveMode = isTranscribing ? "processing" : transcribeMode;
const RenderedChatView = require_slots.renderSlot(chatView, require_CopilotChatView.CopilotChatView, (0, ts_deepmerge.merge)(mergedProps, {
messages: (0, react.useMemo)(() => [...agent.messages], [JSON.stringify(agent.messages)]),
onSubmitMessage: onSubmitInput,
onStop: effectiveStopHandler,
inputMode: effectiveMode,
inputValue,
onInputChange: setInputValue,
onStartTranscribe: showTranscription ? handleStartTranscribe : void 0,
onCancelTranscribe: showTranscription ? handleCancelTranscribe : void 0,
onFinishTranscribe: showTranscription ? handleFinishTranscribe : void 0,
onFinishTranscribeWithAudio: showTranscription ? handleFinishTranscribeWithAudio : void 0
}));
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_CopilotChatConfigurationProvider.CopilotChatConfigurationProvider, {
agentId: resolvedAgentId,
threadId: resolvedThreadId,
labels,
children: [transcriptionError && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
style: {
position: "absolute",
bottom: "100px",
left: "50%",
transform: "translateX(-50%)",
backgroundColor: "#ef4444",
color: "white",
padding: "8px 16px",
borderRadius: "8px",
fontSize: "14px",
zIndex: 50
},
children: transcriptionError
}), RenderedChatView]
});
}
(function(_CopilotChat) {
_CopilotChat.View = require_CopilotChatView.CopilotChatView;
})(CopilotChat || (CopilotChat = {}));
//#endregion
Object.defineProperty(exports, 'CopilotChat', {
enumerable: true,
get: function () {
return CopilotChat;
}
});
//# sourceMappingURL=CopilotChat.cjs.map