diff --git a/.env.example b/.env.example index a4956f7e63..c0d7f2dfcd 100644 --- a/.env.example +++ b/.env.example @@ -64,3 +64,8 @@ VITE_DISABLE_FEEDBACK_FEATURE=true VITE_ENABLE_DOCUNINJA=false VITE_DISABLE_QUICKBOOKS_INTEGRATION=true + +VITE_AI_PROVIDER= +VITE_AI_MODEL= +VITE_OPENAI_API_KEY= +VITE_GEMINI_API_KEY= diff --git a/package.json b/package.json index a697b83e81..e8b1f84f7f 100644 --- a/package.json +++ b/package.json @@ -109,6 +109,7 @@ "check": "biome check --write --unsafe src/", "test": "vitest run", "test:watch": "vitest", + "eval:ai": "vitest run --config tests/ai/vitest.config.ts", "test:e2e": "playwright test --workers=1", "test:e2e:parallel": "node scripts/playwright-spec-orchestrator.mjs", "test:e2e:isolated": "node scripts/playwright-spec-orchestrator.mjs", diff --git a/src/common/interfaces/ai.ts b/src/common/interfaces/ai.ts new file mode 100644 index 0000000000..2e6839478b --- /dev/null +++ b/src/common/interfaces/ai.ts @@ -0,0 +1,142 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import { ModuleBitmask } from '$app/common/enums/module-bitmask'; +import { Permissions } from '$app/common/hooks/permissions/useHasPermission'; +import { RefetchKey } from '$app/common/hooks/useRefetch'; + +export interface AiAccess { + permission: Permissions; + bitmask: ModuleBitmask; +} + +export type AiInput = 'text' | 'date' | 'select' | 'client'; + +export interface AiOption { + value: string; + label: string; +} + +export interface AiSummaryField { + key: string; + label: string; + value: string; + text: string; + input?: AiInput; + options?: AiOption[]; +} + +export interface AiSummaryItem { + label: string; + detail: string; + value: string; +} + +export interface AiSummary { + title: string; + fields: AiSummaryField[]; + items?: AiSummaryItem[]; + totals?: AiSummaryField[]; +} + +export interface AiCreated { + entity: RefetchKey; + id: string; + label: string; + detail?: string; +} + +export interface AiFailure { + label: string; + message: string; +} + +export type AiPlanStatus = + | 'collecting' + | 'ready' + | 'confirmed' + | 'executing' + | 'done' + | 'failed' + | 'cancelled'; + +export interface AiStatus { + type: 'status'; + label: string; +} + +export interface AiReply { + type: 'reply'; + text: string; + points?: string[]; + closing?: string; + suggestions?: string[]; +} + +export interface AiQuestion { + type: 'question'; + field: string; + text: string; + input: AiInput; + options?: AiOption[]; +} + +export interface AiPlan { + type: 'plan'; + planId: string; + version: number; + module: string; + status: AiPlanStatus; + summary: AiSummary; + warnings: string[]; + editable: boolean; +} + +export interface AiProgress { + type: 'progress'; + planId: string; + done: number; + total: number; +} + +export interface AiResult { + type: 'result'; + planId: string; + created: AiCreated[]; + failed: AiFailure[]; +} + +export interface AiError { + type: 'error'; + message: string; +} + +export type AiEvent = + | AiStatus + | AiReply + | AiQuestion + | AiPlan + | AiProgress + | AiResult + | AiError; + +export interface AiRun { + provider: string; + model: string; + inputTokens: number; + outputTokens: number; + cost: number; +} + +export interface AiUsage { + provider: string; + model: string; + runs: AiRun[]; +} diff --git a/src/common/queries/ai.ts b/src/common/queries/ai.ts new file mode 100644 index 0000000000..1804ea4bc7 --- /dev/null +++ b/src/common/queries/ai.ts @@ -0,0 +1,58 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import { AiAccess, AiEvent, AiUsage } from '$app/common/interfaces/ai'; +import * as server from '$app/server/ai'; + +export const sendMessage = ( + conversationId: string, + text: string, + value?: string +): AsyncIterable => { + return server.sendMessage(conversationId, text, value); +}; + +export const updatePlan = ( + planId: string, + field: string, + value: string +): AsyncIterable => { + return server.updatePlan(planId, field, value); +}; + +export const confirmPlan = ( + planId: string, + version: number +): AsyncIterable => { + return server.confirmPlan(planId, version); +}; + +export const cancelPlan = (planId: string): AsyncIterable => { + return server.cancelPlan(planId); +}; + +export const completePlan = ( + planId: string, + record: object +): AsyncIterable => { + return server.completePlan(planId, record); +}; + +export const draftPlan = (planId: string): Promise => { + return server.draftPlan(planId); +}; + +export const usage = (): Promise => { + return server.usage(); +}; + +export const access = (): AiAccess[] => { + return server.access(); +}; diff --git a/src/components/ai/AiAssistant.tsx b/src/components/ai/AiAssistant.tsx new file mode 100644 index 0000000000..0bde6a57d1 --- /dev/null +++ b/src/components/ai/AiAssistant.tsx @@ -0,0 +1,49 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import classNames from 'classnames'; +import { useEffect, useRef } from 'react'; +import { useReactSettings } from '$app/common/hooks/useReactSettings'; +import { ChatPanel } from './ChatPanel'; +import { useAiAssistant, useIsAiAvailable } from './common/hooks'; +import { Composer } from './Composer'; + +export function AiAssistant() { + const { isOpen } = useAiAssistant(); + const isAvailable = useIsAiAvailable(); + const reactSettings = useReactSettings(); + + const wasOpen = useRef(isOpen); + + useEffect(() => { + wasOpen.current = isOpen; + }, [isOpen]); + + if (!isAvailable) { + return null; + } + + if (isOpen) { + return ; + } + + return ( +
+
+ +
+
+ ); +} diff --git a/src/components/ai/Bubble.tsx b/src/components/ai/Bubble.tsx new file mode 100644 index 0000000000..7a9268ff16 --- /dev/null +++ b/src/components/ai/Bubble.tsx @@ -0,0 +1,43 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import classNames from 'classnames'; +import { ReactNode } from 'react'; +import { useColorScheme } from '$app/common/colors'; +import { useAccentColor } from '$app/common/hooks/useAccentColor'; + +interface Props { + isUser?: boolean; + children: ReactNode; +} + +export function Bubble({ isUser, children }: Props) { + const colors = useColorScheme(); + const accentColor = useAccentColor(); + + return ( +
+ {children} +
+ ); +} diff --git a/src/components/ai/ChatEntry.tsx b/src/components/ai/ChatEntry.tsx new file mode 100644 index 0000000000..8a17a7a6a0 --- /dev/null +++ b/src/components/ai/ChatEntry.tsx @@ -0,0 +1,61 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import { LuAlertTriangle } from 'react-icons/lu'; +import { Icon } from '$app/components/icons/Icon'; +import { Bubble } from './Bubble'; +import { AiEntry } from './common/hooks'; +import { PlanSummary } from './PlanSummary'; +import { QuestionEntry } from './QuestionEntry'; +import { ReplyEntry } from './ReplyEntry'; +import { ResultCard } from './ResultCard'; + +interface Props { + entry: AiEntry; + isActive: boolean; + isLast: boolean; +} + +export function ChatEntry({ entry, isActive, isLast }: Props) { + if (entry.type === 'message') { + return {entry.text}; + } + + if (entry.type === 'reply') { + return ; + } + + if (entry.type === 'question') { + return ; + } + + if (entry.type === 'plan') { + return ; + } + + if (entry.type === 'result') { + return ; + } + + return ( + + + + + {entry.message} + + + ); +} diff --git a/src/components/ai/ChatPanel.tsx b/src/components/ai/ChatPanel.tsx new file mode 100644 index 0000000000..f088e4d5bc --- /dev/null +++ b/src/components/ai/ChatPanel.tsx @@ -0,0 +1,156 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import classNames from 'classnames'; +import { useEffect, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + LuMaximize2, + LuMinimize2, + LuPenSquare, + LuSparkles, + LuX, +} from 'react-icons/lu'; +import { useColorScheme } from '$app/common/colors'; +import { useAccentColor } from '$app/common/hooks/useAccentColor'; +import { useReactSettings } from '$app/common/hooks/useReactSettings'; +import { Badge } from '$app/components/Badge'; +import { Icon } from '$app/components/icons/Icon'; +import { ChatEntry } from './ChatEntry'; +import { useAiAssistant } from './common/hooks'; +import { Composer } from './Composer'; +import { IconButton } from './IconButton'; +import { Thinking } from './Thinking'; +import { Welcome } from './Welcome'; + +interface Props { + autoFocus: boolean; +} + +export function ChatPanel({ autoFocus }: Props) { + const [t] = useTranslation(); + const colors = useColorScheme(); + const accentColor = useAccentColor(); + const reactSettings = useReactSettings(); + const { + entries, + activity, + isMock, + isBusy, + isExpanded, + close, + newChat, + setIsExpanded, + } = useAiAssistant(); + + const endRef = useRef(null); + + const pending = [...entries] + .reverse() + .find((entry) => entry.type === 'plan' || entry.type === 'question'); + + useEffect(() => { + endRef.current?.scrollIntoView({ block: 'end' }); + }, [entries, activity]); + + useEffect(() => { + return () => setIsExpanded(false); + }, []); + + return ( +
+
+
+ + + {t('ai_assistant')} + + {isMock && {t('ai_mock_mode')}} +
+ +
+ + + setIsExpanded(!isExpanded)} + className="max-sm:hidden" + /> + + +
+
+ +
+
+ {entries.length ? ( + entries.map((entry, index) => ( +
+ +
+ )) + ) : ( + + )} + + {isBusy && activity && } + +
+
+
+ +
+ +
+
+ ); +} diff --git a/src/components/ai/Chip.tsx b/src/components/ai/Chip.tsx new file mode 100644 index 0000000000..31668fd59e --- /dev/null +++ b/src/components/ai/Chip.tsx @@ -0,0 +1,38 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import classNames from 'classnames'; +import { ReactNode } from 'react'; +import { useColorScheme } from '$app/common/colors'; + +interface Props { + onClick: () => unknown; + disabled?: boolean; + children: ReactNode; +} + +export function Chip({ onClick, disabled, children }: Props) { + const colors = useColorScheme(); + + return ( + + ); +} diff --git a/src/components/ai/Composer.tsx b/src/components/ai/Composer.tsx new file mode 100644 index 0000000000..ab9ce19e05 --- /dev/null +++ b/src/components/ai/Composer.tsx @@ -0,0 +1,155 @@ +/** + * Invoice Ninja (https://invoiceninja.com). + * + * @link https://github.com/invoiceninja/invoiceninja source repository + * + * @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com) + * + * @license https://www.elastic.co/licensing/elastic-license + */ + +import { atom, useAtom } from 'jotai'; +import React, { useEffect, useLayoutEffect, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; +import { LuArrowUp, LuMessageSquare, LuSparkles } from 'react-icons/lu'; +import { useColorScheme } from '$app/common/colors'; +import { + eventMatchesBinding, + formatBinding, +} from '$app/common/helpers/keyboard-shortcuts'; +import { useAccentColor } from '$app/common/hooks/useAccentColor'; +import { getHeldKeys } from '$app/common/hooks/useHeldKeys'; +import { isShortcutRecordingActive } from '$app/common/hooks/useShortcutRecorder'; +import { Icon } from '$app/components/icons/Icon'; +import { useAiAssistant } from './common/hooks'; +import { IconButton } from './IconButton'; + +interface Props { + autoFocus?: boolean; +} + +const draftAtom = atom(''); + +export function Composer({ autoFocus }: Props) { + const [t] = useTranslation(); + const colors = useColorScheme(); + const accentColor = useAccentColor(); + const { send, open, isBusy, isOpen, isExpanded, entries } = useAiAssistant(); + + const [text, setText] = useAtom(draftAtom); + + const inputRef = useRef(null); + + const canSend = Boolean(text.trim()) && !isBusy; + + useEffect(() => { + const focus = (event: KeyboardEvent) => { + if ( + !event.defaultPrevented && + !isShortcutRecordingActive() && + eventMatchesBinding(event, 'mod+k', getHeldKeys()) + ) { + event.preventDefault(); + inputRef.current?.focus(); + } + }; + + window.addEventListener('keydown', focus); + + return () => window.removeEventListener('keydown', focus); + }, []); + + useLayoutEffect(() => { + if (inputRef.current) { + inputRef.current.style.height = 'auto'; + inputRef.current.style.height = `${inputRef.current.scrollHeight}px`; + } + }, [text, isExpanded]); + + const submit = () => { + if (canSend) { + send(text.trim()); + setText(''); + } + }; + + const submitOnEnter = (event: React.KeyboardEvent) => { + if ( + event.key === 'Enter' && + !event.shiftKey && + !event.nativeEvent.isComposing && + event.keyCode !== 229 + ) { + event.preventDefault(); + submit(); + } + }; + + return ( +
{ + event.preventDefault(); + submit(); + }} + className="flex items-end gap-2 rounded-[1.75rem] border py-2 pl-4 pr-2 shadow-lg" + style={{ backgroundColor: colors.$1, borderColor: colors.$24 }} + > + {!isOpen && ( +
+ +
+ )} + +