Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: wire up chat widget buttons

Brad Barbinc4ca6ec3785b
diff --git a/apps/erp/app/components/Chat/ChatInput.tsx b/apps/erp/app/components/Chat/ChatInput.tsx
index f1ab5c7ad2..fa45f0271f 100644
--- a/apps/erp/app/components/Chat/ChatInput.tsx
+++ b/apps/erp/app/components/Chat/ChatInput.tsx
@@ -1,7 +1,7 @@
import { useArtifacts } from "@ai-sdk-tools/artifacts/client";
import { useChatActions, useChatId, useChatStatus } from "@ai-sdk-tools/store";
import { cn } from "@carbon/react";
-import { useRef } from "react";
+import { forwardRef, useRef } from "react";
import { CommandMenu } from "./CommandMenu";
import { FollowupQuestions } from "./FollowupQuestions";
import { useChatStore } from "./lib/store";
@@ -17,7 +17,7 @@ import {
PromptInputToolbar,
PromptInputTools,
} from "./PromptInput";
-import { RecordButton } from "./RecordButton";
+import { RecordButton, type RecordButtonRef } from "./RecordButton";
import { SuggestedActionsButton } from "./SuggestedActions";
import { WebSearchButton } from "./WebSearch";
@@ -28,159 +28,163 @@ export interface ChatInputMessage extends PromptInputMessage {
};
}
-export function ChatInput({ hasMessages }: { hasMessages: boolean }) {
- const textareaRef = useRef<HTMLTextAreaElement>(null);
-
- const status = useChatStatus();
- const { sendMessage } = useChatActions();
- const chatId = useChatId();
-
- const { current } = useArtifacts({
- exclude: ["chat-title", "followup-questions"],
- });
- const isCanvasVisible = !!current;
-
- const {
- input,
- isWebSearch,
- isUploading,
- isRecording,
- isProcessing,
- showCommands,
- selectedCommandIndex,
- filteredCommands,
- setInput,
- handleInputChange,
- handleKeyDown,
- resetCommandState,
- } = useChatStore();
-
- const handleSubmit = (message: ChatInputMessage) => {
- // If currently streaming or submitted, stop instead of submitting
- if (status === "streaming" || status === "submitted") {
- stop();
- return;
- }
-
- const hasText = Boolean(message.text);
- const hasAttachments = Boolean(message.files?.length);
-
- if (!(hasText || hasAttachments)) {
- return;
- }
-
- sendMessage({
- text: message.text || "Sent with attachments",
- files: message.files,
- metadata: {
- agentChoice: message.metadata?.agentChoice,
- toolChoice: message.metadata?.toolChoice,
- },
- });
- setInput("");
- };
+export const ChatInput = forwardRef<RecordButtonRef, { hasMessages: boolean }>(
+ function ChatInput({ hasMessages }, ref) {
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ const status = useChatStatus();
+ const { sendMessage } = useChatActions();
+ const chatId = useChatId();
- return (
- <>
- <div
- className={cn(
- "transition-all duration-300 ease-in-out",
- hasMessages ? "absolute bottom-6 left-0 z-20" : "",
- isCanvasVisible ? "right-[603px]" : "right-0"
- )}
- >
- <div className="mx-auto w-full pt-2 relative">
- <FollowupQuestions />
-
- {/* Command Suggestions Menu */}
- <CommandMenu />
-
- <PromptInput onSubmit={handleSubmit} globalDrop multiple>
- <PromptInputBody>
- <PromptInputAttachments>
- {(attachment) => <PromptInputAttachment data={attachment} />}
- </PromptInputAttachments>
- <PromptInputTextarea
- ref={textareaRef}
- autoFocus
- onChange={handleInputChange}
- onKeyDown={(e) => {
- // Handle Enter key for commands
- if (e.key === "Enter" && showCommands) {
- e.preventDefault();
- const selectedCommand =
- filteredCommands[selectedCommandIndex];
- if (selectedCommand) {
- // Execute command through the store
- if (!chatId) return;
-
- sendMessage({
- role: "user",
- parts: [{ type: "text", text: selectedCommand.title }],
- metadata: {
- toolCall: {
- toolName: selectedCommand.toolName,
- toolParams: selectedCommand.toolParams,
+ const { current } = useArtifacts({
+ exclude: ["chat-title", "followup-questions"],
+ });
+ const isCanvasVisible = !!current;
+
+ const {
+ input,
+ isWebSearch,
+ isUploading,
+ isRecording,
+ isProcessing,
+ showCommands,
+ selectedCommandIndex,
+ filteredCommands,
+ setInput,
+ handleInputChange,
+ handleKeyDown,
+ resetCommandState,
+ } = useChatStore();
+
+ const handleSubmit = (message: ChatInputMessage) => {
+ // If currently streaming or submitted, stop instead of submitting
+ if (status === "streaming" || status === "submitted") {
+ stop();
+ return;
+ }
+
+ const hasText = Boolean(message.text);
+ const hasAttachments = Boolean(message.files?.length);
+
+ if (!(hasText || hasAttachments)) {
+ return;
+ }
+
+ sendMessage({
+ text: message.text || "Sent with attachments",
+ files: message.files,
+ metadata: {
+ agentChoice: message.metadata?.agentChoice,
+ toolChoice: message.metadata?.toolChoice,
+ },
+ });
+ setInput("");
+ };
+
+ return (
+ <>
+ <div
+ className={cn(
+ "transition-all duration-300 ease-in-out",
+ hasMessages ? "absolute bottom-6 left-0 z-20" : "",
+ isCanvasVisible ? "right-[603px]" : "right-0"
+ )}
+ >
+ <div className="mx-auto w-full pt-2 relative">
+ <FollowupQuestions />
+
+ {/* Command Suggestions Menu */}
+ <CommandMenu />
+
+ <PromptInput onSubmit={handleSubmit} globalDrop multiple>
+ <PromptInputBody>
+ <PromptInputAttachments>
+ {(attachment) => <PromptInputAttachment data={attachment} />}
+ </PromptInputAttachments>
+ <PromptInputTextarea
+ ref={textareaRef}
+ autoFocus
+ onChange={handleInputChange}
+ onKeyDown={(e) => {
+ // Handle Enter key for commands
+ if (e.key === "Enter" && showCommands) {
+ e.preventDefault();
+ const selectedCommand =
+ filteredCommands[selectedCommandIndex];
+ if (selectedCommand) {
+ // Execute command through the store
+ if (!chatId) return;
+
+ sendMessage({
+ role: "user",
+ parts: [
+ { type: "text", text: selectedCommand.title },
+ ],
+ metadata: {
+ toolCall: {
+ toolName: selectedCommand.toolName,
+ toolParams: selectedCommand.toolParams,
+ },
},
- },
- });
+ });
- setInput("");
- resetCommandState();
+ setInput("");
+ resetCommandState();
+ }
+ return;
}
- return;
- }
- // Handle Enter key for normal messages
- if (e.key === "Enter" && !showCommands) {
- e.preventDefault();
- if (input.trim()) {
- sendMessage({
- text: input,
- files: [],
- metadata: {
- webSearch: isWebSearch,
- },
- });
-
- setInput("");
- resetCommandState();
+ // Handle Enter key for normal messages
+ if (e.key === "Enter" && !showCommands) {
+ e.preventDefault();
+ if (input.trim()) {
+ sendMessage({
+ text: input,
+ files: [],
+ metadata: {
+ webSearch: isWebSearch,
+ },
+ });
+
+ setInput("");
+ resetCommandState();
+ }
+ return;
}
- return;
- }
- // Handle other keys normally
- handleKeyDown(e);
- }}
- value={input}
- placeholder={
- isWebSearch ? "Search the web" : "You can just do things"
- }
- />
- </PromptInputBody>
- <PromptInputToolbar>
- <PromptInputTools>
- <PromptInputActionAddAttachments />
- <SuggestedActionsButton />
- <WebSearchButton />
- </PromptInputTools>
-
- <PromptInputTools>
- <RecordButton size={16} />
- <PromptInputSubmit
- disabled={
- (!input && !status) ||
- isUploading ||
- isRecording ||
- isProcessing
+ // Handle other keys normally
+ handleKeyDown(e);
+ }}
+ value={input}
+ placeholder={
+ isWebSearch ? "Search the web" : "You can just do things"
}
- status={status}
/>
- </PromptInputTools>
- </PromptInputToolbar>
- </PromptInput>
+ </PromptInputBody>
+ <PromptInputToolbar>
+ <PromptInputTools>
+ <PromptInputActionAddAttachments />
+ <SuggestedActionsButton />
+ <WebSearchButton />
+ </PromptInputTools>
+
+ <PromptInputTools>
+ <RecordButton ref={ref} size={16} />
+ <PromptInputSubmit
+ disabled={
+ (!input && !status) ||
+ isUploading ||
+ isRecording ||
+ isProcessing
+ }
+ status={status}
+ />
+ </PromptInputTools>
+ </PromptInputToolbar>
+ </PromptInput>
+ </div>
</div>
- </div>
- </>
- );
-}
+ </>
+ );
+ }
+);
diff --git a/apps/erp/app/components/Chat/ChatInterface.tsx b/apps/erp/app/components/Chat/ChatInterface.tsx
index 775c50fdda..d0c24e898f 100644
--- a/apps/erp/app/components/Chat/ChatInterface.tsx
+++ b/apps/erp/app/components/Chat/ChatInterface.tsx
@@ -3,7 +3,7 @@ import { useChat, useDataPart } from "@ai-sdk-tools/store";
import { SUPABASE_URL, useCarbon } from "@carbon/auth";
import { cn } from "@carbon/react";
import { DefaultChatTransport, generateId } from "ai";
-import { useMemo } from "react";
+import { useMemo, useRef } from "react";
import { Greeting } from "~/components/Greeting";
import { useUser } from "~/hooks";
import { Canvas } from "./Canvas";
@@ -21,6 +21,7 @@ import {
import { useChatInterface } from "./hooks/useChatInterface";
import { useChatStatus } from "./hooks/useChatStatus";
import type { UIChatMessage } from "./lib/types";
+import type { RecordButtonRef } from "./RecordButton";
type Props = {
geo?: {
@@ -31,6 +32,7 @@ type Props = {
export function ChatInterface({ geo }: Props) {
const { chatId: routeChatId } = useChatInterface();
+ const recordButtonRef = useRef<RecordButtonRef>(null);
const chatId = useMemo(() => routeChatId ?? generateId(), [routeChatId]);
const { accessToken } = useCarbon();
@@ -167,10 +169,10 @@ export function ChatInterface({ geo }: Props) {
>
{!hasMessages && <Greeting size="h1" className="font-medium" />}
<div className="w-full pb-2">
- <ChatInput hasMessages={hasMessages} />
+ <ChatInput ref={recordButtonRef} hasMessages={hasMessages} />
</div>
- {!hasMessages && <ChatWidgets />}
+ {!hasMessages && <ChatWidgets recordButtonRef={recordButtonRef} />}
</div>
</div>
</div>
diff --git a/apps/erp/app/components/Chat/ChatWidgets.tsx b/apps/erp/app/components/Chat/ChatWidgets.tsx
index 1937b977aa..b6c91d0834 100644
--- a/apps/erp/app/components/Chat/ChatWidgets.tsx
+++ b/apps/erp/app/components/Chat/ChatWidgets.tsx
@@ -1,22 +1,37 @@
import { Button } from "@carbon/react";
+import type { RefObject } from "react";
import {
LuAudioLines,
LuChevronDown,
LuSearch,
LuSquarePen,
} from "react-icons/lu";
+import { useUIStore } from "~/stores/ui";
import CreateMenu from "../Layout/Topbar/CreateMenu";
+import type { RecordButtonRef } from "./RecordButton";
+
+interface ChatWidgetsProps {
+ recordButtonRef?: RefObject<RecordButtonRef>;
+}
+
+export function ChatWidgets({ recordButtonRef }: ChatWidgetsProps) {
+ const { openSearchModal } = useUIStore();
+
+ const handleVoiceClick = () => {
+ recordButtonRef?.current?.handleRecordClick();
+ };
-export function ChatWidgets() {
return (
<div className="w-full flex gap-3 justify-center items-center">
<Button
variant="secondary"
className="rounded-full"
leftIcon={<LuSearch />}
+ onClick={openSearchModal}
>
Search
</Button>
+
<CreateMenu
trigger={
<Button
@@ -29,10 +44,12 @@ export function ChatWidgets() {
</Button>
}
/>
+
<Button
variant="secondary"
className="rounded-full"
leftIcon={<LuAudioLines />}
+ onClick={handleVoiceClick}
>
Voice
</Button>
diff --git a/apps/erp/app/components/Chat/RecordButton.tsx b/apps/erp/app/components/Chat/RecordButton.tsx
index d134561a76..784baee8d0 100644
--- a/apps/erp/app/components/Chat/RecordButton.tsx
+++ b/apps/erp/app/components/Chat/RecordButton.tsx
@@ -1,5 +1,5 @@
import { cn, IconButton, Spinner } from "@carbon/react";
-import { useCallback } from "react";
+import { forwardRef, useCallback, useImperativeHandle } from "react";
import { useAudioRecording } from "./hooks/useAudioRecording";
import { useChatStore } from "./lib/store";
@@ -140,80 +140,87 @@ export interface RecordButtonProps {
size?: number;
}
-export function RecordButton({
- disabled = false,
- className,
- size = 16,
-}: RecordButtonProps) {
- const {
- input,
- setInput,
- isRecording,
- isProcessing,
- setIsRecording,
- setIsProcessing,
- } = useChatStore();
- const { startRecording, stopRecording, transcribeAudio } =
- useAudioRecording();
+export interface RecordButtonRef {
+ handleRecordClick: () => void;
+}
+
+export const RecordButton = forwardRef<RecordButtonRef, RecordButtonProps>(
+ function RecordButton({ disabled = false, className, size = 16 }, ref) {
+ const {
+ input,
+ setInput,
+ isRecording,
+ isProcessing,
+ setIsRecording,
+ setIsProcessing,
+ } = useChatStore();
+ const { startRecording, stopRecording, transcribeAudio } =
+ useAudioRecording();
- const handleRecordClick = useCallback(async () => {
- if (isRecording) {
- // Stop recording and transcribe
- try {
- setIsProcessing(true);
- const audioBlob = await stopRecording();
+ const handleRecordClick = useCallback(async () => {
+ if (isRecording) {
+ // Stop recording and transcribe
+ try {
+ setIsProcessing(true);
+ const audioBlob = await stopRecording();
- if (audioBlob) {
- const transcribedText = await transcribeAudio(audioBlob);
+ if (audioBlob) {
+ const transcribedText = await transcribeAudio(audioBlob);
- if (transcribedText.trim()) {
- setInput(input ? `${input} ${transcribedText}` : transcribedText);
+ if (transcribedText.trim()) {
+ setInput(input ? `${input} ${transcribedText}` : transcribedText);
+ }
}
+ } catch (error) {
+ console.error("Failed to process recording:", error);
+ } finally {
+ setIsRecording(false);
+ setIsProcessing(false);
+ }
+ } else {
+ // Start recording and reset input
+ try {
+ setInput(""); // Reset input when starting to record
+ await startRecording();
+ setIsRecording(true);
+ } catch (error) {
+ console.error("Failed to start recording:", error);
}
- } catch (error) {
- console.error("Failed to process recording:", error);
- } finally {
- setIsRecording(false);
- setIsProcessing(false);
- }
- } else {
- // Start recording and reset input
- try {
- setInput(""); // Reset input when starting to record
- await startRecording();
- setIsRecording(true);
- } catch (error) {
- console.error("Failed to start recording:", error);
}
- }
- }, [
- isRecording,
- stopRecording,
- startRecording,
- transcribeAudio,
- setInput,
- input,
- setIsRecording,
- setIsProcessing,
- ]);
+ }, [
+ isRecording,
+ stopRecording,
+ startRecording,
+ transcribeAudio,
+ setInput,
+ input,
+ setIsRecording,
+ setIsProcessing,
+ ]);
- return (
- <IconButton
- aria-label="Record"
- variant="ghost"
- isRound
- icon={
- isProcessing ? <Spinner /> : <RecordIcon isRecording={isRecording} />
- }
- isDisabled={isProcessing}
- onClick={handleRecordClick}
- disabled={disabled}
- className={cn(
- isRecording &&
- "text-red-500 hover:text-red-500 [&_svg]:text-red-500 [&_svg]:hover:text-red-500",
- disabled && "opacity-50",
- className
- )}
- />
- );
-}
+ // Expose the handleRecordClick method via ref
+ useImperativeHandle(ref, () => ({
+ handleRecordClick,
+ }));
+
+ return (
+ <IconButton
+ aria-label="Record"
+ variant="ghost"
+ isRound
+ icon={
+ isProcessing ? <Spinner /> : <RecordIcon isRecording={isRecording} />
+ }
+ isDisabled={isProcessing}
+ onClick={handleRecordClick}
+ disabled={disabled}
+ className={cn(
+ isRecording &&
+ "text-red-500 hover:text-red-500 [&_svg]:text-red-500 [&_svg]:hover:text-red-500",
+ disabled && "opacity-50",
+ className
+ )}
+ />
+ );
+ }
+);
diff --git a/apps/erp/app/components/Layout/Topbar/Search.tsx b/apps/erp/app/components/Layout/Topbar/Search.tsx
index ebfc24616f..e7a92e4646 100644
--- a/apps/erp/app/components/Layout/Topbar/Search.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Search.tsx
@@ -16,7 +16,6 @@ import {
ShortcutKey,
VStack,
useDebounce,
- useDisclosure,
useMount,
useShortcutKeys,
} from "@carbon/react";
@@ -56,6 +55,7 @@ import useResourcesSubmodules from "~/modules/resources/ui/useResourcesSubmodule
import useSalesSubmodules from "~/modules/sales/ui/useSalesSubmodules";
import useSettingsSubmodules from "~/modules/settings/ui/useSettingsSubmodules";
import useUsersSubmodules from "~/modules/users/ui/useUsersSubmodules";
+import { useUIStore } from "~/stores/ui";
import type { Authenticated, Route } from "~/types";
@@ -73,17 +73,12 @@ const shortcut: ShortcutDefinition = {
modifiers: ["mod"],
};
-const SearchModal = ({
- isOpen,
- onClose,
-}: {
- isOpen: boolean;
- onClose: () => void;
-}) => {
+const SearchModal = () => {
const { company } = useUser();
const { carbon } = useCarbon();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
+ const { isSearchModalOpen, closeSearchModal } = useUIStore();
const [input, setInput] = useState("");
const debounceSearch = useDebounce((q: string) => {
@@ -95,10 +90,10 @@ const SearchModal = ({
}, 500);
useEffect(() => {
- if (isOpen) {
+ if (isSearchModalOpen) {
setInput("");
}
- }, [isOpen]);
+ }, [isSearchModalOpen]);
const staticResults = useGroupedSubmodules();
@@ -150,7 +145,7 @@ const SearchModal = ({
const onSelect = async (route: Route) => {
const { to, name } = route;
navigate(route.to);
- onClose();
+ closeSearchModal();
const newRecentSearches = [
{ to, name },
...((await idb.getItem<Route[]>("recentSearches"))?.filter(
@@ -164,10 +159,10 @@ const SearchModal = ({
return (
<Modal
- open={isOpen}
+ open={isSearchModalOpen}
onOpenChange={(open) => {
setInput("");
- if (!open) onClose();
+ if (!open) closeSearchModal();
}}
>
<ModalContent
@@ -296,11 +291,11 @@ function ResultIcon({ entity }: { entity: SearchResult["entity"] | "Module" }) {
}
const SearchButton = () => {
- const searchModal = useDisclosure();
+ const { openSearchModal } = useUIStore();
useShortcutKeys({
shortcut: shortcut,
- action: searchModal.onOpen,
+ action: openSearchModal,
});
return (
@@ -309,14 +304,14 @@ const SearchButton = () => {
leftIcon={<LuSearch />}
variant="secondary"
className="w-[200px] px-2"
- onClick={searchModal.onOpen}
+ onClick={openSearchModal}
>
<HStack className="w-full">
<div className="flex flex-grow">Search</div>
<ShortcutKey variant="small" shortcut={shortcut} />
</HStack>
</Button>
- <SearchModal isOpen={searchModal.isOpen} onClose={searchModal.onClose} />
+ <SearchModal />
</div>
);
};
diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsx
index 33c29898fe..02d165a3cb 100644
--- a/apps/erp/app/routes/x+/_index.tsx
+++ b/apps/erp/app/routes/x+/_index.tsx
@@ -8,13 +8,25 @@ import { ChatInterface } from "~/components/Chat";
import { useChatInterface } from "~/components/Chat/hooks/useChatInterface";
import { Greeting } from "~/components/Greeting";
import { useModules } from "~/hooks";
+import { useFlags } from "~/hooks/useFlags";
import type { Authenticated, NavItem } from "~/types";
export default function AppIndexRoute() {
+ const { isCommunity } = useFlags();
+ return isCommunity ? <ChatPage /> : <AppsPage />;
+}
+
+const ChatPage = () => {
const { chatId: currentChatId } = useChatInterface();
- const isCloud = true;
- // const permissions = usePermissions();
+ return (
+ <ChatProvider initialMessages={[]} key={currentChatId || "home"}>
+ <ChatInterface />
+ </ChatProvider>
+ );
+};
+
+const AppsPage = () => {
const modules = useModules();
const { locale } = useLocale();
const date = new Date();
@@ -27,14 +39,9 @@ export default function AppIndexRoute() {
}),
[locale]
);
-
- return isCloud ? (
- <ChatProvider initialMessages={[]} key={currentChatId || "home"}>
- <ChatInterface />
- </ChatProvider>
- ) : (
+ return (
<div className="p-8 w-full h-full bg-muted">
- <Greeting />
+ <Greeting size="h3" />
<Subheading>{formatter.format(date)}</Subheading>
<Hr />
<div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-6 mb-8">
@@ -55,7 +62,7 @@ export default function AppIndexRoute() {
</div>
</div>
);
-}
+};
const Hr = () => (
<hr className="h-px my-8 bg-black/10 border-0 dark:bg-white/10" />
diff --git a/apps/erp/app/stores/ui.ts b/apps/erp/app/stores/ui.ts
new file mode 100644
index 0000000000..b69d252764
--- /dev/null
+++ b/apps/erp/app/stores/ui.ts
@@ -0,0 +1,16 @@
+import { create } from "zustand";
+
+interface UIStore {
+ isSearchModalOpen: boolean;
+ openSearchModal: () => void;
+ closeSearchModal: () => void;
+ toggleSearchModal: () => void;
+}
+
+export const useUIStore = create<UIStore>()((set) => ({
+ isSearchModalOpen: false,
+ openSearchModal: () => set({ isSearchModalOpen: true }),
+ closeSearchModal: () => set({ isSearchModalOpen: false }),
+ toggleSearchModal: () =>
+ set((state) => ({ isSearchModalOpen: !state.isSearchModalOpen })),
+}));