mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-07-17 22:35:19 +00:00
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.
291 lines
9.7 KiB
PHP
291 lines
9.7 KiB
PHP
<?php
|
|
|
|
use App\Models\AiConversation;
|
|
use App\Models\AiMessage;
|
|
use App\Models\User;
|
|
use App\Services\AiConfigurationService;
|
|
use App\Support\Ai\AiChatResponse;
|
|
use App\Support\Ai\AiDriver;
|
|
use App\Support\Ai\AiDriverFactory;
|
|
use App\Support\Ai\AiException;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Laravel\Sanctum\Sanctum;
|
|
|
|
use function Pest\Laravel\getJson;
|
|
use function Pest\Laravel\postJson;
|
|
|
|
/**
|
|
* Test double for AiDriver that returns pre-queued responses from an array,
|
|
* so tests can script tool-call loops without hitting any real LLM API.
|
|
*
|
|
* Usage:
|
|
* ScriptedAiDriver::setResponses([
|
|
* new AiChatResponse(message: null, toolCalls: [...]),
|
|
* new AiChatResponse(message: 'Final answer'),
|
|
* ]);
|
|
*/
|
|
class ScriptedAiDriver extends AiDriver
|
|
{
|
|
/** @var array<int, AiChatResponse> */
|
|
public static array $responses = [];
|
|
|
|
public static int $callCount = 0;
|
|
|
|
/** @var array<int, array<string, mixed>> */
|
|
public static array $lastMessages = [];
|
|
|
|
public static function reset(): void
|
|
{
|
|
self::$responses = [];
|
|
self::$callCount = 0;
|
|
self::$lastMessages = [];
|
|
}
|
|
|
|
/**
|
|
* @param array<int, AiChatResponse> $responses
|
|
*/
|
|
public static function setResponses(array $responses): void
|
|
{
|
|
self::$responses = $responses;
|
|
self::$callCount = 0;
|
|
}
|
|
|
|
public function chatCompletion(
|
|
array $messages,
|
|
string $model,
|
|
array $tools = [],
|
|
array $options = [],
|
|
): AiChatResponse {
|
|
self::$lastMessages = $messages;
|
|
$response = self::$responses[self::$callCount] ?? new AiChatResponse(message: 'Default test reply');
|
|
self::$callCount++;
|
|
|
|
return $response;
|
|
}
|
|
|
|
public function textCompletion(string $prompt, string $model, array $options = []): string
|
|
{
|
|
return 'text completion test';
|
|
}
|
|
|
|
public function validateConnection(): array
|
|
{
|
|
return ['ok' => true];
|
|
}
|
|
}
|
|
|
|
beforeEach(function () {
|
|
Artisan::call('db:seed', ['--class' => 'DatabaseSeeder', '--force' => true]);
|
|
Artisan::call('db:seed', ['--class' => 'DemoSeeder', '--force' => true]);
|
|
|
|
$this->user = User::find(1);
|
|
$this->companyId = $this->user->companies()->first()->id;
|
|
|
|
$this->withHeaders(['company' => $this->companyId]);
|
|
Sanctum::actingAs($this->user, ['*']);
|
|
|
|
// Enable AI globally so resolveForCompany returns a config
|
|
app(AiConfigurationService::class)->saveGlobalConfig([
|
|
'ai_enabled' => 'YES',
|
|
'ai_driver' => 'scripted',
|
|
'ai_api_key' => 'test-key',
|
|
'ai_chat_enabled' => 'YES',
|
|
'ai_chat_model' => 'test-model',
|
|
]);
|
|
|
|
// Register the scripted driver so AiDriverFactory returns it for 'scripted'
|
|
AiDriverFactory::register('scripted', ScriptedAiDriver::class);
|
|
ScriptedAiDriver::reset();
|
|
});
|
|
|
|
afterEach(function () {
|
|
ScriptedAiDriver::reset();
|
|
});
|
|
|
|
test('chat endpoint creates a new conversation and persists user + assistant messages', function () {
|
|
ScriptedAiDriver::setResponses([
|
|
new AiChatResponse(message: 'Hello back!'),
|
|
]);
|
|
|
|
$response = postJson('/api/v1/ai/chat', [
|
|
'message' => 'Hi assistant',
|
|
])->assertOk();
|
|
|
|
$conversationId = $response->json('conversation.id');
|
|
expect($conversationId)->toBeInt();
|
|
expect($response->json('message.content'))->toBe('Hello back!');
|
|
expect($response->json('message.role'))->toBe('assistant');
|
|
|
|
// Both user and assistant messages should be persisted
|
|
$conversation = AiConversation::find($conversationId);
|
|
expect($conversation->user_id)->toBe($this->user->id);
|
|
expect($conversation->company_id)->toBe($this->companyId);
|
|
|
|
$messages = $conversation->messages()->orderBy('created_at')->get();
|
|
expect($messages->pluck('role')->all())->toBe(['user', 'assistant']);
|
|
expect($messages[0]->content)->toBe('Hi assistant');
|
|
expect($messages[1]->content)->toBe('Hello back!');
|
|
});
|
|
|
|
test('chat endpoint runs a tool-call loop and returns the final answer', function () {
|
|
// Round 1: LLM requests search_invoices
|
|
// Round 2: LLM produces final text
|
|
ScriptedAiDriver::setResponses([
|
|
new AiChatResponse(
|
|
message: null,
|
|
toolCalls: [[
|
|
'id' => 'call_1',
|
|
'name' => 'search_invoices',
|
|
'arguments' => ['limit' => 5],
|
|
]],
|
|
finishReason: 'tool_calls',
|
|
),
|
|
new AiChatResponse(message: 'Here are your invoices.'),
|
|
]);
|
|
|
|
$response = postJson('/api/v1/ai/chat', [
|
|
'message' => 'Show me recent invoices',
|
|
])->assertOk();
|
|
|
|
expect($response->json('message.content'))->toBe('Here are your invoices.');
|
|
expect(ScriptedAiDriver::$callCount)->toBe(2);
|
|
|
|
// Conversation should now contain: user, assistant(tool_calls), tool(result), assistant(final)
|
|
$conversation = AiConversation::find($response->json('conversation.id'));
|
|
$roles = $conversation->messages()->orderBy('id')->pluck('role')->all();
|
|
expect($roles)->toBe(['user', 'assistant', 'tool', 'assistant']);
|
|
});
|
|
|
|
test('chat endpoint caps runaway tool-call loops at MAX_TOOL_ITERATIONS', function () {
|
|
// All responses are tool_calls — simulating a model stuck in a loop
|
|
$loopResponse = new AiChatResponse(
|
|
message: null,
|
|
toolCalls: [[
|
|
'id' => 'call_loop',
|
|
'name' => 'search_invoices',
|
|
'arguments' => [],
|
|
]],
|
|
finishReason: 'tool_calls',
|
|
);
|
|
// Queue 10 of them — way more than the 5-iteration cap
|
|
ScriptedAiDriver::setResponses(array_fill(0, 10, $loopResponse));
|
|
|
|
$response = postJson('/api/v1/ai/chat', [
|
|
'message' => 'Loop forever',
|
|
])->assertOk();
|
|
|
|
// We should hit the cap and the service should return a graceful error message.
|
|
expect($response->json('message.content'))->toContain('tool-call budget');
|
|
// 5 calls + the "I give up" turn shouldn't exceed the hard cap
|
|
expect(ScriptedAiDriver::$callCount)->toBeLessThanOrEqual(5);
|
|
});
|
|
|
|
test('chat endpoint persists an error message when the driver throws', function () {
|
|
ScriptedAiDriver::setResponses([]); // no responses queued → driver returns default
|
|
|
|
// Inject a failing driver via the factory
|
|
$failingDriver = new class('fake', []) extends AiDriver
|
|
{
|
|
public function chatCompletion(array $messages, string $model, array $tools = [], array $options = []): AiChatResponse
|
|
{
|
|
throw new AiException('test failure', 'server_error');
|
|
}
|
|
|
|
public function textCompletion(string $prompt, string $model, array $options = []): string
|
|
{
|
|
return '';
|
|
}
|
|
|
|
public function validateConnection(): array
|
|
{
|
|
return [];
|
|
}
|
|
};
|
|
AiDriverFactory::register('failing', $failingDriver::class);
|
|
|
|
app(AiConfigurationService::class)->saveGlobalConfig([
|
|
'ai_enabled' => 'YES',
|
|
'ai_driver' => 'failing',
|
|
'ai_api_key' => 'k',
|
|
'ai_chat_enabled' => 'YES',
|
|
'ai_chat_model' => 'test',
|
|
]);
|
|
|
|
$response = postJson('/api/v1/ai/chat', [
|
|
'message' => 'Hello',
|
|
])->assertOk();
|
|
|
|
expect($response->json('message.content'))->toContain('Error:');
|
|
});
|
|
|
|
test('chat endpoint rejects when AI is disabled for the company', function () {
|
|
app(AiConfigurationService::class)->saveGlobalConfig([
|
|
'ai_enabled' => 'NO',
|
|
]);
|
|
|
|
postJson('/api/v1/ai/chat', [
|
|
'message' => 'Hi',
|
|
])->assertStatus(422);
|
|
});
|
|
|
|
test('chat endpoint rejects when chat role is disabled even if AI is enabled', function () {
|
|
app(AiConfigurationService::class)->saveGlobalConfig([
|
|
'ai_enabled' => 'YES',
|
|
'ai_driver' => 'scripted',
|
|
'ai_api_key' => 'k',
|
|
'ai_chat_enabled' => 'NO', // <— off
|
|
'ai_chat_model' => 'test',
|
|
]);
|
|
|
|
postJson('/api/v1/ai/chat', [
|
|
'message' => 'Hi',
|
|
])->assertStatus(422);
|
|
});
|
|
|
|
test('conversation index returns only the current user\'s conversations', function () {
|
|
// Create a conversation for the authenticated user
|
|
ScriptedAiDriver::setResponses([new AiChatResponse(message: 'hi')]);
|
|
postJson('/api/v1/ai/chat', ['message' => 'First message'])->assertOk();
|
|
|
|
// Create a conversation for a different user in the same company — should NOT be visible
|
|
$otherUser = User::factory()->create();
|
|
$otherUser->companies()->attach($this->companyId);
|
|
AiConversation::create([
|
|
'company_id' => $this->companyId,
|
|
'user_id' => $otherUser->id,
|
|
'title' => 'Other users secret chat',
|
|
]);
|
|
|
|
$response = getJson('/api/v1/ai/conversations')->assertOk();
|
|
|
|
$titles = collect($response->json('conversations'))->pluck('title');
|
|
expect($titles)->not->toContain('Other users secret chat');
|
|
});
|
|
|
|
test('conversation show enforces ownership via policy', function () {
|
|
$otherUser = User::factory()->create();
|
|
$otherUser->companies()->attach($this->companyId);
|
|
|
|
$foreignConvo = AiConversation::create([
|
|
'company_id' => $this->companyId,
|
|
'user_id' => $otherUser->id,
|
|
'title' => 'Not yours',
|
|
]);
|
|
|
|
getJson("/api/v1/ai/conversations/{$foreignConvo->id}")->assertForbidden();
|
|
});
|
|
|
|
test('conversation delete cascades messages', function () {
|
|
ScriptedAiDriver::setResponses([new AiChatResponse(message: 'reply')]);
|
|
$sendResponse = postJson('/api/v1/ai/chat', ['message' => 'First'])->assertOk();
|
|
$conversationId = $sendResponse->json('conversation.id');
|
|
|
|
// There should now be 2 messages
|
|
expect(AiMessage::where('conversation_id', $conversationId)->count())->toBe(2);
|
|
|
|
$this->deleteJson("/api/v1/ai/conversations/{$conversationId}")->assertOk();
|
|
|
|
expect(AiConversation::find($conversationId))->toBeNull();
|
|
expect(AiMessage::where('conversation_id', $conversationId)->count())->toBe(0);
|
|
});
|