feat(ai): Phase 2 — chat assistant with tool-calling

Second phase of the AI feature. Users can now open a slide-in chat drawer from the SiteHeader and ask natural-language questions about their company's invoices, customers, payments, and expenses. The LLM invokes pre-defined read-only tool functions (scoped to the current company at execute time) to fetch data and synthesize answers.

**Database** — new ai_conversations and ai_messages tables. Messages are stored in OpenAI's chat format so AiAssistantService serializes a conversation into an API request with zero translation. Columns: role, content, tool_call_id, tool_calls JSON, model, tokens_in, tokens_out. Conversations are scoped (company_id, user_id) — one user's chats are invisible to everyone else, even inside the same company. Foreign-key cascade deletes.

**Tool infrastructure** — AiTool abstract base + AiToolRegistry singleton (registered in a new AiServiceProvider). The base class enforces the security rule: every tool's execute() receives companyId and userId as injected parameters; tools' JSON schemas NEVER include a company_id field. An LLM physically cannot pass a company_id and escape tenancy. Modules can register their own tools by resolving the registry from their own ServiceProvider::boot().

**Nine built-in tools**: search_invoices, get_invoice, search_customers, get_customer, list_recent_payments, list_overdue_invoices, get_company_stats (aggregates for named periods), search_items, list_expense_categories. All read-only; no mutations. Each returns JSON-encodable data the LLM can parse.

**AiAssistantService orchestration loop** — the heart of Phase 2. Flow: persist user message → build payload from system prompt + recent history (40-message window) + new user message → call driver.chatCompletion with tools → if tool_calls, execute each one via the registry (with injected scope), persist tool result, loop → if plain text, persist and return. Hard cap at 5 iterations to prevent runaway LLMs. System prompt pins the assistant to this company's data and forbids mutation.

**Controllers + policy + rate limit** — POST /api/v1/ai/chat runs the orchestration loop. GET/PATCH/DELETE /api/v1/ai/conversations for CRUD. AiConversationPolicy enforces user_id+company_id match on every action. A new 'ai' RateLimiter in RouteServiceProvider throttles to 30 req/min per (user, company). New 'use ai' Gate defined in AppServiceProvider returns true for any authenticated user — the per-company kill-switch still goes through AiConfigurationService::resolveForCompany.

**Frontend** — new features/company/ai/ folder with a Pinia store (ai-chat.store.ts) holding drawer state, current conversation, messages, and loading flags. AiChatDrawer.vue is a slide-in panel teleported to <body>, mounted globally in CompanyLayout.vue when bootstrap reports ai.enabled && ai.chat_enabled. Sub-components: AiChatMessage (user bubbles vs assistant bubbles), AiChatMessageInput (Enter submits, Shift+Enter newline), AiChatConversationList (sidebar with 'new chat' button, rename, delete). A SparklesIcon button in SiteHeader toggles the drawer.

**Driver test double** — tests use a ScriptedAiDriver registered via AiDriverFactory::register('scripted', ...) that returns pre-queued AiChatResponse objects. Feature tests cover: happy path (new conversation + message persistence), tool-call loop (multi-round-trip with search_invoices), runaway-loop cap, driver-throws path, ai_enabled=NO rejection, chat role disabled rejection, per-user conversation visibility, cross-user policy enforcement, cascade delete.

388 tests pass (was 372, +16 new). Pint clean. npm run build clean. Phase 3 (WYSIWYG text generation popup) is the remaining follow-up.
This commit is contained in:
Darko Gjorgjijoski
2026-04-12 08:00:00 +02:00
parent c7fab5d52f
commit e861fc1fc1
39 changed files with 2776 additions and 1 deletions

View File

@@ -127,6 +127,10 @@ export const API = {
// Installer AI Configuration
INSTALLATION_AI_CONFIG: '/api/v1/installation/ai/config',
// AI Chat (Phase 2)
AI_CHAT: '/api/v1/ai/chat',
AI_CONVERSATIONS: '/api/v1/ai/conversations',
// PDF Configuration
PDF_DRIVERS: '/api/v1/pdf/drivers',
PDF_CONFIG: '/api/v1/pdf/config',

View File

@@ -1,7 +1,10 @@
import { client } from '../client'
import { API } from '../endpoints'
import type {
AiChatSendResponse,
AiConfig,
AiConversationDetail,
AiConversationSummary,
AiDriversResponse,
AiTestPayload,
AiTestResponse,
@@ -48,4 +51,37 @@ export const aiService = {
const { data } = await client.post(API.COMPANY_AI_TEST, payload)
return data
},
// --- Phase 2: chat ---
async sendChatMessage(
conversationId: number | null,
message: string,
): Promise<AiChatSendResponse> {
const { data } = await client.post(API.AI_CHAT, {
conversation_id: conversationId,
message,
})
return data
},
async listConversations(): Promise<{ conversations: AiConversationSummary[] }> {
const { data } = await client.get(API.AI_CONVERSATIONS)
return data
},
async getConversation(id: number): Promise<AiConversationDetail> {
const { data } = await client.get(`${API.AI_CONVERSATIONS}/${id}`)
return data
},
async renameConversation(id: number, title: string): Promise<{ success: boolean }> {
const { data } = await client.patch(`${API.AI_CONVERSATIONS}/${id}`, { title })
return data
},
async deleteConversation(id: number): Promise<{ success: boolean }> {
const { data } = await client.delete(`${API.AI_CONVERSATIONS}/${id}`)
return data
},
}

View File

@@ -0,0 +1,79 @@
<script setup lang="ts">
import { useAiChatStore } from '../stores/ai-chat.store'
import type { AiConversationSummary } from '@/scripts/types/ai-config'
const store = useAiChatStore()
async function select(convo: AiConversationSummary): Promise<void> {
await store.loadConversation(convo.id)
}
async function remove(convo: AiConversationSummary, event: MouseEvent): Promise<void> {
event.stopPropagation()
if (!window.confirm('Delete this conversation?')) return
await store.deleteConversation(convo.id)
}
</script>
<template>
<div class="flex flex-col h-full">
<div class="p-3 border-b border-line-default">
<button
type="button"
class="w-full text-left text-sm font-medium rounded px-3 py-2 bg-btn-primary text-white hover:bg-btn-primary-hover"
@click="store.newConversation()"
>
+ {{ $t('ai.chat.new_conversation') }}
</button>
</div>
<div class="flex-1 overflow-y-auto">
<div
v-if="store.isLoadingConversations && store.conversations.length === 0"
class="p-3 text-xs text-muted"
>
{{ $t('general.loading') }}...
</div>
<div
v-else-if="store.conversations.length === 0"
class="p-3 text-xs text-muted"
>
{{ $t('ai.chat.no_conversations') }}
</div>
<ul v-else class="space-y-1 p-2">
<li
v-for="convo in store.conversations"
:key="convo.id"
>
<button
type="button"
class="
w-full text-left flex items-center justify-between
px-3 py-2 rounded text-sm group
hover:bg-hover
"
:class="{
'bg-hover-strong font-semibold': store.currentConversationId === convo.id,
}"
@click="select(convo)"
>
<span class="truncate text-body">
{{ convo.title ?? $t('ai.chat.untitled') }}
</span>
<span
class="
ml-2 text-xs text-muted opacity-0 group-hover:opacity-100
hover:text-alert-error-text
"
@click="remove(convo, $event)"
>
{{ $t('general.delete') }}
</span>
</button>
</li>
</ul>
</div>
</div>
</template>

View File

@@ -0,0 +1,140 @@
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { useAiChatStore } from '../stores/ai-chat.store'
import AiChatMessage from './AiChatMessage.vue'
import AiChatMessageInput from './AiChatMessageInput.vue'
import AiChatConversationList from './AiChatConversationList.vue'
const store = useAiChatStore()
const messagesEl = ref<HTMLDivElement | null>(null)
// Auto-scroll to the bottom whenever the message list grows.
watch(
() => store.messages.length,
async () => {
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
},
)
async function onSend(message: string): Promise<void> {
await store.sendMessage(message)
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
}
</script>
<template>
<!-- Backdrop -->
<Teleport to="body">
<transition name="ai-drawer-fade">
<div
v-if="store.isOpen"
class="fixed inset-0 bg-black/20 z-40"
@click="store.close()"
/>
</transition>
<!-- Drawer panel -->
<transition name="ai-drawer-slide">
<aside
v-if="store.isOpen"
class="
fixed top-0 right-0 bottom-0 z-50
w-full sm:w-[480px] lg:w-[640px]
bg-surface shadow-2xl
flex
"
>
<!-- Conversation list sidebar -->
<div class="hidden sm:block w-48 border-r border-line-default bg-surface-secondary">
<AiChatConversationList />
</div>
<!-- Messages + input -->
<div class="flex-1 flex flex-col">
<div class="flex items-center justify-between p-3 border-b border-line-default">
<div class="flex items-center gap-2">
<BaseIcon name="SparklesIcon" class="w-5 h-5 text-primary-500" />
<h2 class="text-sm font-semibold text-heading">
{{ $t('ai.chat.title') }}
</h2>
</div>
<button
type="button"
class="text-muted hover:text-heading"
@click="store.close()"
>
<BaseIcon name="XMarkIcon" class="w-5 h-5" />
</button>
</div>
<div
ref="messagesEl"
class="flex-1 overflow-y-auto p-4 space-y-3"
>
<div
v-if="store.messages.length === 0"
class="text-center text-sm text-muted mt-12"
>
<BaseIcon name="SparklesIcon" class="w-10 h-10 mx-auto mb-2 text-subtle" />
<p>{{ $t('ai.chat.empty_state') }}</p>
</div>
<AiChatMessage
v-for="msg in store.messages"
:key="msg.id"
:message="msg"
/>
<div
v-if="store.isSending"
class="flex justify-start"
>
<div class="bg-surface-tertiary rounded-lg px-4 py-2 text-sm text-muted italic">
{{ $t('ai.chat.thinking') }}
</div>
</div>
<div
v-if="store.lastError"
class="p-3 text-xs text-alert-error-text bg-alert-error-bg rounded"
>
{{ store.lastError }}
</div>
</div>
<AiChatMessageInput
:is-sending="store.isSending"
@send="onSend"
/>
</div>
</aside>
</transition>
</Teleport>
</template>
<style scoped>
.ai-drawer-fade-enter-active,
.ai-drawer-fade-leave-active {
transition: opacity 0.2s ease;
}
.ai-drawer-fade-enter-from,
.ai-drawer-fade-leave-to {
opacity: 0;
}
.ai-drawer-slide-enter-active,
.ai-drawer-slide-leave-active {
transition: transform 0.25s ease;
}
.ai-drawer-slide-enter-from,
.ai-drawer-slide-leave-to {
transform: translateX(100%);
}
</style>

View File

@@ -0,0 +1,31 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { AiChatMessage } from '@/scripts/types/ai-config'
const props = defineProps<{
message: AiChatMessage
}>()
const isUser = computed(() => props.message.role === 'user')
</script>
<template>
<div
class="flex"
:class="isUser ? 'justify-end' : 'justify-start'"
>
<div
class="max-w-[85%] rounded-lg px-4 py-2 text-sm"
:class="
isUser
? 'bg-primary-500 text-white'
: 'bg-surface-tertiary text-body'
"
>
<!-- Plain text rendering for v1 markdown support can ship later. -->
<p class="whitespace-pre-wrap break-words">
{{ message.content ?? '' }}
</p>
</div>
</div>
</template>

View File

@@ -0,0 +1,62 @@
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{
isSending?: boolean
}>()
const emit = defineEmits<{
send: [message: string]
}>()
const text = ref<string>('')
function submit(): void {
const trimmed = text.value.trim()
if (!trimmed || props.isSending) return
emit('send', trimmed)
text.value = ''
}
/**
* Shift+Enter → newline, Enter alone → submit (standard chat UX).
*/
function onKeydown(e: KeyboardEvent): void {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
submit()
}
}
</script>
<template>
<form
class="border-t border-line-default p-3 flex items-end gap-2"
@submit.prevent="submit"
>
<textarea
v-model="text"
rows="2"
class="
flex-1 resize-none rounded-md border border-line-default
bg-surface text-body text-sm px-3 py-2
focus:outline-none focus:ring-1 focus:ring-primary-500
"
:placeholder="$t('ai.chat.input_placeholder')"
:disabled="isSending"
@keydown="onKeydown"
/>
<button
type="submit"
class="
rounded-md px-3 py-2 text-sm font-medium
bg-btn-primary text-white hover:bg-btn-primary-hover
disabled:opacity-50 disabled:cursor-not-allowed
"
:disabled="!text.trim() || isSending"
>
{{ isSending ? $t('ai.chat.sending') : $t('ai.chat.send') }}
</button>
</form>
</template>

View File

@@ -0,0 +1,149 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { aiService } from '@/scripts/api/services/ai.service'
import type {
AiChatMessage,
AiConversationSummary,
} from '@/scripts/types/ai-config'
/**
* Chat drawer state + conversation history.
*
* The drawer is a global overlay (not a route), so this store is where its
* open/closed state, current conversation, message list, and loading state all
* live. Message-sending is persisted server-side — we don't keep optimistic
* state across reloads.
*/
export const useAiChatStore = defineStore('ai-chat', () => {
// --- Drawer UI state ---
const isOpen = ref<boolean>(false)
// --- Current conversation ---
const currentConversationId = ref<number | null>(null)
const messages = ref<AiChatMessage[]>([])
const isSending = ref<boolean>(false)
const lastError = ref<string | null>(null)
// --- Conversation list (sidebar inside the drawer) ---
const conversations = ref<AiConversationSummary[]>([])
const isLoadingConversations = ref<boolean>(false)
const hasActiveConversation = computed<boolean>(() => currentConversationId.value !== null)
// --- Actions ---
function open(): void {
isOpen.value = true
// Refresh the sidebar list on open so the user sees any new conversations
// they started in another tab.
void refreshConversations()
}
function close(): void {
isOpen.value = false
}
function toggle(): void {
isOpen.value ? close() : open()
}
function newConversation(): void {
currentConversationId.value = null
messages.value = []
lastError.value = null
}
async function refreshConversations(): Promise<void> {
isLoadingConversations.value = true
try {
const response = await aiService.listConversations()
conversations.value = response.conversations
} catch {
// silent — the drawer stays functional without the sidebar list
} finally {
isLoadingConversations.value = false
}
}
async function loadConversation(id: number): Promise<void> {
lastError.value = null
const response = await aiService.getConversation(id)
currentConversationId.value = response.conversation.id
messages.value = response.messages
}
async function sendMessage(text: string): Promise<void> {
if (!text.trim()) return
if (isSending.value) return
lastError.value = null
isSending.value = true
// Optimistic local append so the user sees their message immediately.
const optimistic: AiChatMessage = {
id: Date.now() * -1,
role: 'user',
content: text,
created_at: new Date().toISOString(),
}
messages.value.push(optimistic)
try {
const response = await aiService.sendChatMessage(currentConversationId.value, text)
// The backend may have started a new conversation for us.
currentConversationId.value = response.conversation.id
messages.value.push(response.message)
// Refresh the sidebar so the new/updated conversation bubbles to the top.
void refreshConversations()
} catch (err) {
// Roll back the optimistic message so the user can retry.
messages.value = messages.value.filter((m) => m.id !== optimistic.id)
const message = err instanceof Error ? err.message : 'Unknown error'
lastError.value = message
} finally {
isSending.value = false
}
}
async function deleteConversation(id: number): Promise<void> {
await aiService.deleteConversation(id)
conversations.value = conversations.value.filter((c) => c.id !== id)
// If the deleted conversation is the one currently shown, start fresh.
if (currentConversationId.value === id) {
newConversation()
}
}
async function renameConversation(id: number, title: string): Promise<void> {
await aiService.renameConversation(id, title)
const existing = conversations.value.find((c) => c.id === id)
if (existing) existing.title = title
}
return {
// state
isOpen,
currentConversationId,
messages,
isSending,
lastError,
conversations,
isLoadingConversations,
// getters
hasActiveConversation,
// actions
open,
close,
toggle,
newConversation,
refreshConversations,
loadConversation,
sendMessage,
deleteConversation,
renameConversation,
}
})

View File

@@ -22,6 +22,9 @@
<router-view />
</div>
</main>
<!-- AI chat drawer always mounted, visibility driven by the store -->
<AiChatDrawer v-if="globalStore.ai?.enabled && globalStore.ai?.chat_enabled" />
</div>
<BaseGlobalLoader v-else />
@@ -39,6 +42,7 @@ import SiteHeader from './partials/SiteHeader.vue'
import SiteSidebar from './partials/SiteSidebar.vue'
import NotificationRoot from '@/scripts/components/notifications/NotificationRoot.vue'
import ImpersonationBanner from './partials/ImpersonationBanner.vue'
import AiChatDrawer from '@/scripts/features/company/ai/components/AiChatDrawer.vue'
interface RouteMeta {
ability?: string | string[]

View File

@@ -99,6 +99,28 @@
/>
</li>
<!-- AI chat drawer trigger -->
<li
v-if="
!companyStore.isAdminMode &&
globalStore.ai?.enabled &&
globalStore.ai?.chat_enabled
"
class="ml-2"
>
<button
type="button"
class="
flex items-center justify-center w-8 h-8 md:w-9 md:h-9 rounded-lg
bg-white/20 hover:bg-white/30 text-white
"
:title="$t('ai.chat.title')"
@click="aiChatStore.toggle()"
>
<BaseIcon name="SparklesIcon" class="w-5 h-5" />
</button>
</li>
<!-- Company switcher -->
<li>
<CompanySwitcher />
@@ -182,6 +204,7 @@ import { useAuthStore } from '@/scripts/stores/auth.store'
import { useUserStore } from '@/scripts/stores/user.store'
import { useGlobalStore } from '@/scripts/stores/global.store'
import { useCompanyStore } from '@/scripts/stores/company.store'
import { useAiChatStore } from '@/scripts/features/company/ai/stores/ai-chat.store'
import { useTheme } from '@/scripts/composables/use-theme'
import { ABILITIES } from '@/scripts/config/abilities'
import { THEME } from '@/scripts/config/constants'
@@ -199,6 +222,7 @@ const authStore = useAuthStore()
const userStore = useUserStore()
const globalStore = useGlobalStore()
const companyStore = useCompanyStore()
const aiChatStore = useAiChatStore()
const router = useRouter()
const { currentTheme, setTheme } = useTheme()

View File

@@ -36,6 +36,11 @@ export const useGlobalStore = defineStore('global', () => {
const mainMenu = ref<MenuItem[]>([])
const settingMenu = ref<MenuItem[]>([])
const userMenu = ref<Array<{ title: string; link: string; icon: string; name: string }>>([])
const ai = ref<{ enabled: boolean; chat_enabled: boolean; text_generation_enabled: boolean }>({
enabled: false,
chat_enabled: false,
text_generation_enabled: false,
})
const isAppLoaded = ref<boolean>(false)
const isSidebarOpen = ref<boolean>(false)
const isSidebarCollapsed = ref<boolean>(localStore.getBoolean('sidebarCollapsed'))
@@ -64,6 +69,11 @@ export const useGlobalStore = defineStore('global', () => {
mainMenu.value = response.main_menu
settingMenu.value = response.setting_menu
userMenu.value = response.user_menu ?? []
ai.value = response.ai ?? {
enabled: false,
chat_enabled: false,
text_generation_enabled: false,
}
config.value = response.config
globalSettings.value = response.global_settings
@@ -292,6 +302,7 @@ export const useGlobalStore = defineStore('global', () => {
mainMenu,
settingMenu,
userMenu,
ai,
isAppLoaded,
isSidebarOpen,
isSidebarCollapsed,

View File

@@ -53,3 +53,31 @@ export interface AiTestResponse {
message?: string
details?: Record<string, unknown>
}
// --- Phase 2: chat types ---
export interface AiConversationSummary {
id: number
title: string | null
model: string | null
created_at: string
updated_at: string
}
export interface AiChatMessage {
id: number
role: 'user' | 'assistant'
content: string | null
created_at: string
}
export interface AiChatSendResponse {
conversation: AiConversationSummary
message: AiChatMessage
error?: string
}
export interface AiConversationDetail {
conversation: AiConversationSummary
messages: AiChatMessage[]
}