From f7a6fea2dd3525229860f5f993f872b05a3a81d8 Mon Sep 17 00:00:00 2001 From: roble Date: Wed, 25 Nov 2026 10:40:59 +0000 Subject: [PATCH 01/34] feat: stream chat replies with conversations and canned test mode Ported from the whatsthere chat module without the map: ownership-scoped conversations, Vercel protocol streaming, provider errors kept in the stream and stripped of provider wording, and AI_CHAT_TEST_MODE canned replies. Co-Authored-By: Claude Opus 5.5 --- config/config.php | 9 +- ...00001_create_agent_conversations_table.php | 61 ++++ resources/js/react/app.tsx | 25 -- resources/js/react/pages/Index.tsx | 58 ---- routes/web.php | 9 +- src/Ai/ChatAgent.php | 39 +++ src/Http/Controllers/AiChatController.php | 280 +++++++++++++++- src/Providers/AiChatServiceProvider.php | 28 +- src/Testing/CannedReplies.php | 160 ++++++++++ tests/Feature/CannedRepliesTest.php | 135 ++++++++ tests/Feature/ChatStreamTest.php | 300 ++++++++++++++++++ tests/Feature/IndexTest.php | 20 -- tests/Feature/StreamFailureTest.php | 93 ++++++ 13 files changed, 1103 insertions(+), 114 deletions(-) create mode 100644 database/migrations/1000_00_00_000001_create_agent_conversations_table.php delete mode 100644 resources/js/react/app.tsx delete mode 100644 resources/js/react/pages/Index.tsx create mode 100644 src/Ai/ChatAgent.php create mode 100644 src/Testing/CannedReplies.php create mode 100644 tests/Feature/CannedRepliesTest.php create mode 100644 tests/Feature/ChatStreamTest.php delete mode 100644 tests/Feature/IndexTest.php create mode 100644 tests/Feature/StreamFailureTest.php diff --git a/config/config.php b/config/config.php index e0c4035..6472284 100644 --- a/config/config.php +++ b/config/config.php @@ -1,5 +1,12 @@ (bool) env('AI_CHAT_TEST_MODE', false), + ]; diff --git a/database/migrations/1000_00_00_000001_create_agent_conversations_table.php b/database/migrations/1000_00_00_000001_create_agent_conversations_table.php new file mode 100644 index 0000000..d5c0ce7 --- /dev/null +++ b/database/migrations/1000_00_00_000001_create_agent_conversations_table.php @@ -0,0 +1,61 @@ +string('id', 36)->primary(); + $table->string('participant_type')->nullable(); + $table->unsignedBigInteger('participant_id')->nullable(); + $table->string('title'); + $table->timestamps(); + + $table->index(['participant_type', 'participant_id', 'updated_at'], 'participant_updated_at_index'); + }); + + Schema::create($messagesTable, function (Blueprint $table) { + $table->string('id', 36)->primary(); + $table->string('conversation_id', 36)->index(); + $table->string('participant_type')->nullable(); + $table->unsignedBigInteger('participant_id')->nullable(); + $table->string('agent'); + $table->string('role', 25); + $table->text('content'); + $table->text('attachments'); + $table->text('tool_calls'); + $table->text('tool_results'); + $table->text('usage'); + $table->text('meta'); + $table->text('approval_state')->nullable(); + $table->timestamps(); + + $table->index(['conversation_id', 'participant_type', 'participant_id', 'updated_at'], 'conversation_index'); + $table->index(['participant_type', 'participant_id'], 'participant_index'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists(config('ai.conversations.tables.messages', 'agent_conversation_messages')); + Schema::dropIfExists(config('ai.conversations.tables.conversations', 'agent_conversations')); + } +}; diff --git a/resources/js/react/app.tsx b/resources/js/react/app.tsx deleted file mode 100644 index f371333..0000000 --- a/resources/js/react/app.tsx +++ /dev/null @@ -1,25 +0,0 @@ -// import { registerIcon } from '@/lib/navigation'; -// import IconExample from '~icons/lucide/example'; - -// Custom styles: create resources/css/style.css in this module and uncomment. -// import '@modules/aichat/resources/css/style.css'; - -/** - * AiChat module setup - * Called before the first render, on the server too: register things here, - * and leave anything that needs window or document to afterMount() - */ -export function setup() { - console.debug('AiChat module loaded'); - - // Register icons for navigation items defined in routes/navigation.php - // registerIcon('ai-chat', IconExample); -} - -/** - * AiChat module after mount logic - * Called in the browser after the app has mounted - */ -export function afterMount() { - console.debug('AiChat module after mount logic executed'); -} diff --git a/resources/js/react/pages/Index.tsx b/resources/js/react/pages/Index.tsx deleted file mode 100644 index 75defdf..0000000 --- a/resources/js/react/pages/Index.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Button } from '@/components/ui/button'; -import { - Card, - CardDescription, - CardFooter, - CardHeader, - CardTitle, -} from '@/components/ui/card'; -import { useT } from '@saucebase/react/i18n'; -import AppLayout from '@/layouts/AppLayout'; -import { Rocket } from 'lucide-react'; - -const title = 'AiChat'; - -export default function Index() { - const t = useT(); - - return ( - -
- {/* Header Section */} -
-
-

- {t(title)} -

-

- {t('Your AiChat module is ready. Start building something great!')} -

-
-
- - {/* Call to Action Section */} - - - - {t('Get Started')} - - {t('Ready to build something amazing?')} - - - - - - -
-
- ); -} diff --git a/routes/web.php b/routes/web.php index 4acc72a..9248f18 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,8 +1,11 @@ group(function () { - Route::get('ai-chat', [AiChatController::class, 'index'])->name('ai-chat.index'); +Route::middleware(['web', 'auth'])->group(function () { + Route::get('chat', [AiChatController::class, 'index'])->name('ai-chat.index'); + Route::post('chat/messages', [AiChatController::class, 'stream'])->name('ai-chat.stream'); + Route::get('chat/{conversation}/messages', [AiChatController::class, 'messages'])->name('ai-chat.messages'); + Route::get('chat/{conversation}', [AiChatController::class, 'show'])->name('ai-chat.show'); }); diff --git a/src/Ai/ChatAgent.php b/src/Ai/ChatAgent.php new file mode 100644 index 0000000..a5f1d54 --- /dev/null +++ b/src/Ai/ChatAgent.php @@ -0,0 +1,39 @@ + + */ + public function tools(): iterable + { + return []; + } +} diff --git a/src/Http/Controllers/AiChatController.php b/src/Http/Controllers/AiChatController.php index e1dc2be..ac253c5 100644 --- a/src/Http/Controllers/AiChatController.php +++ b/src/Http/Controllers/AiChatController.php @@ -2,18 +2,290 @@ namespace Modules\AiChat\Http\Controllers; +use Closure; +use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; +use Illuminate\Support\Str; use Inertia\Inertia; +use Inertia\Response; +use Laravel\Ai\Messages\Message; +use Laravel\Ai\Messages\ToolResultMessage; +use Laravel\Ai\Models\Conversation; +use Modules\AiChat\Ai\ChatAgent; +use Modules\AiChat\Testing\CannedReplies; +use Symfony\Component\HttpFoundation\Response as SymfonyResponse; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Throwable; class AiChatController { /** - * Display a listing of the resource. + * Show a blank chat. No row exists until the first message is sent. */ - public function index() + public function index(): Response { return Inertia::render('AiChat::Index', [ - 'message' => 'Welcome to AiChat Module', - 'module' => 'aichat', + 'conversationId' => null, + 'initialMessages' => [], ]); } + + /** + * Show an existing conversation belonging to the authenticated user. + */ + public function show(Request $request, string $conversation): Response + { + $owned = $this->ownedConversation($request, $conversation); + + $messages = (new ChatAgent) + ->continue($owned->id, $request->user()) + ->messages(); + + return Inertia::render('AiChat::Index', [ + 'conversationId' => $owned->id, + 'initialMessages' => collect($messages) + // Tool rows carry no prose; an empty assistant turn would reopen as an empty bubble. + ->reject(fn (Message $message): bool => $message instanceof ToolResultMessage || trim((string) $message->content) === '') + ->values() + ->map(fn (Message $message, int $index): array => [ + 'id' => 'history-'.$index, + 'role' => $message->role->value, + 'parts' => [ + ['type' => 'text', 'text' => $message->content ?? ''], + ], + ]) + ->all(), + ]); + } + + /** + * Read one conversation as JSON, for WebMCP tools. + */ + public function messages(Request $request, string $conversation): JsonResponse + { + $owned = $this->ownedConversation($request, $conversation); + + $messages = (new ChatAgent) + ->continue($owned->id, $request->user()) + ->messages(); + + return response()->json([ + 'id' => $owned->id, + 'title' => $owned->getAttribute('title'), + 'messages' => collect($messages) + ->values() + ->map(fn (Message $message): array => [ + 'role' => $message->role->value, + 'text' => $message->content ?? '', + ]) + ->all(), + ]); + } + + /** + * Stream an assistant reply, creating the conversation on first use. + */ + public function stream(Request $request): SymfonyResponse + { + $validated = $request->validate([ + 'message' => ['required', 'string', 'max:4000'], + 'conversation_id' => ['nullable', 'string', 'max:36'], + ]); + + $conversation = isset($validated['conversation_id']) + ? $this->ownedConversation($request, $validated['conversation_id']) + : $this->startConversation($request, $validated['message']); + + if ($this->inTestMode()) { + return $this->cannedStream($request, $conversation->id); + } + + $response = (new ChatAgent) + ->continue($conversation->id, $request->user()) + ->stream($validated['message']) + ->usingVercelDataProtocol() + ->toResponse($request); + + // A new chat moves onto its own URL, so the browser needs the id before + // the first byte; the protocol encoder has no hook for extra frames. + $response->headers->set('X-Conversation-Id', $conversation->id); + + return $this->keepFailuresInTheStream($response); + } + + /** + * Two conditions: the flag a developer turns on, and the environment check + * that stops it mattering if the flag ever reaches production. + */ + protected function inTestMode(): bool + { + return config('ai-chat.test_mode') === true && ! app()->isProduction(); + } + + /** + * Stream a canned reply, picked at random unless `?scenario=` names one. + * + * Nothing is persisted: none of it came from the model, so none of it + * belongs in the history the model later reads back. + */ + protected function cannedStream(Request $request, string $conversationId): SymfonyResponse + { + $scenario = CannedReplies::pick($request->query('scenario')); + $replies = new CannedReplies($conversationId); + + $response = new StreamedResponse(function () use ($replies, $scenario): void { + foreach ($replies->frames($scenario) as $frame) { + $this->writeFrame($frame); + + // Slow enough to watch the reply build. + usleep(40_000); + } + + $this->writeFrame('[DONE]'); + }, headers: [ + 'Cache-Control' => 'no-cache, no-transform', + 'Content-Type' => 'text/event-stream', + 'x-vercel-ai-ui-message-stream' => 'v1', + 'X-Conversation-Id' => $conversationId, + 'X-Chat-Test-Scenario' => $scenario, + ]); + + return $this->keepFailuresInTheStream($response); + } + + /** + * Report a mid-stream failure as a protocol frame rather than an exception. + * + * The encoder iterates the provider with no try/catch, so an expired key or + * a rate limit escapes after the headers are sent, and Laravel renders an + * HTML error page into the event stream. Caught here, the stream ends with + * an error part the browser can show and the terminator the protocol needs. + */ + protected function keepFailuresInTheStream(SymfonyResponse $response): SymfonyResponse + { + if (! $response instanceof StreamedResponse || ($stream = $response->getCallback()) === null) { + return $response; + } + + return $response->setCallback(function () use ($stream): void { + $stopHiding = $this->hideProviderErrors(); + + try { + $stream(); + } catch (Throwable $e) { + report($e); + + $this->writeFrame(['type' => 'error', 'errorText' => $this->failureMessage()]); + $this->writeFrame('[DONE]'); + } finally { + $stopHiding(); + } + }); + } + + /** + * Replace the text of any error frame on its way to the browser. + * + * Providers report failures as an event before raising, and the encoder + * writes its message verbatim: organisation ids, limits, reset times. The + * frame is kept so the browser knows the reply failed; only the wording is + * ours. The full error still reaches the log through `report()`. + * + * @return Closure(): void Stops the rewriting and releases anything held back. + */ + protected function hideProviderErrors(): Closure + { + $partial = ''; + + // Carries the remainder so a frame split across writes is still read. + ob_start(function (string $chunk) use (&$partial): string { + $partial .= $chunk; + $complete = ''; + + while (($end = strpos($partial, "\n\n")) !== false) { + $complete .= $this->withoutProviderDetail(substr($partial, 0, $end + 2)); + $partial = substr($partial, $end + 2); + } + + return $complete; + }, 1); + + return function () use (&$partial): void { + ob_end_flush(); + + if ($partial !== '') { + echo $partial; + flush(); + } + }; + } + + /** + * Swap the provider's wording out of one server-sent event. + */ + protected function withoutProviderDetail(string $frame): string + { + if (! str_starts_with($frame, 'data: ')) { + return $frame; + } + + $payload = json_decode(substr($frame, 6, -2), true); + + if (! is_array($payload) || ($payload['type'] ?? null) !== 'error') { + return $frame; + } + + $payload['errorText'] = $this->failureMessage(); + + return 'data: '.json_encode($payload, JSON_THROW_ON_ERROR)."\n\n"; + } + + protected function failureMessage(): string + { + return __('The assistant could not be reached. Please try again.'); + } + + /** + * Write one server-sent event, flushing as the streamed response does. + * + * @param array|string $frame + */ + protected function writeFrame(array|string $frame): void + { + echo 'data: '.(is_string($frame) ? $frame : json_encode($frame, JSON_THROW_ON_ERROR))."\n\n"; + + if (ob_get_level() > 0) { + ob_flush(); + } + + flush(); + } + + /** + * Create the conversation up front so its id is known before streaming. + */ + protected function startConversation(Request $request, string $message): Conversation + { + return Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => Conversation::participantType($request->user()), + 'participant_id' => Conversation::participantKey($request->user()), + 'title' => Str::limit(trim($message), 50, preserveWords: true) ?: __('New chat'), + ]); + } + + /** + * Resolve a conversation the authenticated user owns. + * + * laravel/ai's continue() performs no ownership check, so every path that + * accepts an id from the client must come through here first. + */ + protected function ownedConversation(Request $request, string $id): Conversation + { + return Conversation::query() + ->where('id', $id) + ->where('participant_type', Conversation::participantType($request->user())) + ->where('participant_id', Conversation::participantKey($request->user())) + ->firstOrFail(); + } } diff --git a/src/Providers/AiChatServiceProvider.php b/src/Providers/AiChatServiceProvider.php index 941e8c8..7fc5b75 100644 --- a/src/Providers/AiChatServiceProvider.php +++ b/src/Providers/AiChatServiceProvider.php @@ -2,11 +2,33 @@ namespace Modules\AiChat\Providers; +use Illuminate\Support\Facades\Auth; +use Inertia\Inertia; +use Laravel\Ai\Models\Conversation; use Saucebase\Core\Providers\ModuleServiceProvider; class AiChatServiceProvider extends ModuleServiceProvider { - protected array $providers = [ - // YourServiceProvider::class, - ]; + /** + * The session list sits in the chat sidebar on every chat page, so it is + * shared rather than passed per page. The conversations table's + * participant/updated_at index covers the query. + */ + protected function shareInertiaData(): void + { + Inertia::share('chat.sessions', function (): array { + $user = Auth::user(); + + if ($user === null || ! request()->routeIs('ai-chat.*')) { + return []; + } + + return Conversation::query() + ->where('participant_type', Conversation::participantType($user)) + ->where('participant_id', Conversation::participantKey($user)) + ->latest('updated_at') + ->get(['id', 'title']) + ->toArray(); + }); + } } diff --git a/src/Testing/CannedReplies.php b/src/Testing/CannedReplies.php new file mode 100644 index 0000000..358a05b --- /dev/null +++ b/src/Testing/CannedReplies.php @@ -0,0 +1,160 @@ + 'a short answer after some reasoning', + 'markdown' => 'a list, a table and a code block', + 'tool_error' => 'a tool that failed', + 'failure' => 'no reply at all', + ]; + + public function __construct(protected string $messageId) {} + + /** + * Pick a scenario at random, or return the one that was asked for. + */ + public static function pick(?string $scenario = null): string + { + return isset(self::SCENARIOS[$scenario]) + ? $scenario + : (string) array_rand(self::SCENARIOS); + } + + /** + * The frames one scenario streams, in order. + * + * @return Generator> + */ + public function frames(string $scenario): Generator + { + yield ['type' => 'start', 'messageId' => $this->messageId]; + + yield from match ($scenario) { + 'markdown' => $this->markdown(), + 'tool_error' => $this->toolError(), + 'failure' => $this->failure(), + default => $this->reply(), + }; + + // A reply that never arrived does not get a 'finish'. + if ($scenario !== 'failure') { + yield ['type' => 'finish']; + } + } + + protected function reply(): Generator + { + yield from $this->thinking('**Reading the question** — a greeting, so a short answer will do.'); + + yield from $this->prose('Hi! I am running in test mode, so this answer is canned. Ask me anything to see how the chat looks.'); + } + + protected function markdown(): Generator + { + yield from $this->prose(<<<'MD' + Here is what Markdown looks like in the chat: + + - **Bold** and *italic* text + - `inline code` + + | Plan | Messages | + | --- | --- | + | Free | 50 | + | Pro | 2,000 | + + ```php + echo 'Hello from a code block'; + ``` + MD); + } + + protected function toolError(): Generator + { + yield ['type' => 'tool-input-available', 'toolCallId' => 'call-error', 'toolName' => 'example_tool', 'input' => []]; + yield ['type' => 'tool-output-error', 'toolCallId' => 'call-error', 'errorText' => 'The tool could not be reached.']; + + yield from $this->prose('That tool is not answering just now. Try again in a minute.'); + } + + protected function failure(): Generator + { + yield from $this->thinking('**Preparing to answer** — and then the provider gives out.'); + + // The sort of message a provider sends, so the controller's sanitiser is + // exercised too: this text must never reach the browser. + yield ['type' => 'error', 'errorText' => 'Rate limit reached for model in organization org-EXAMPLE0000 on requests per day (RPD): Limit 50, Used 50.']; + } + + /** + * A reasoning block, streamed in pieces the way the model sends it. + * + * @return Generator> + */ + protected function thinking(string $text): Generator + { + $id = $this->messageId.'-reasoning'; + + yield ['type' => 'reasoning-start', 'id' => $id]; + + foreach ($this->pieces($text) as $piece) { + yield ['type' => 'reasoning-delta', 'id' => $id, 'delta' => $piece]; + } + + yield ['type' => 'reasoning-end', 'id' => $id]; + } + + /** + * A tool call and its result. + * + * @param array $input + * @return Generator> + */ + protected function tool(string $name, array $input, string $output): Generator + { + $id = 'call-'.$name; + + yield ['type' => 'tool-input-available', 'toolCallId' => $id, 'toolName' => $name, 'input' => $input]; + yield ['type' => 'tool-output-available', 'toolCallId' => $id, 'output' => $output]; + } + + /** + * The reply itself, streamed a few words at a time. + * + * @return Generator> + */ + protected function prose(string $text): Generator + { + yield ['type' => 'text-start', 'id' => $this->messageId]; + + foreach ($this->pieces($text) as $piece) { + yield ['type' => 'text-delta', 'id' => $this->messageId, 'delta' => $piece]; + } + + yield ['type' => 'text-end', 'id' => $this->messageId]; + } + + /** + * Break text into delta-sized pieces, keeping the spaces. + * + * @return list + */ + protected function pieces(string $text): array + { + return preg_split('/(?<= )/', $text, -1, PREG_SPLIT_NO_EMPTY) ?: [$text]; + } +} diff --git a/tests/Feature/CannedRepliesTest.php b/tests/Feature/CannedRepliesTest.php new file mode 100644 index 0000000..ba5c03f --- /dev/null +++ b/tests/Feature/CannedRepliesTest.php @@ -0,0 +1,135 @@ +> + */ + protected function framesFor(string $scenario): array + { + return iterator_to_array((new CannedReplies('mock-1'))->frames($scenario), false); + } + + /** + * Every frame type the installed package can actually emit. + * + * Read out of the event classes rather than restated here: the whole risk + * with canned frames is that the package renames a type and they go on + * describing a protocol nobody speaks any more. + * + * @return list + */ + protected function protocolTypes(): array + { + $types = []; + + foreach (glob(base_path('vendor/laravel/ai/src/Streaming/Events/*.php')) ?: [] as $file) { + preg_match_all("/'type' => '([a-z-]+)'/", (string) file_get_contents($file), $matches); + $types = array_merge($types, $matches[1]); + } + + return array_values(array_unique($types)); + } + + public function test_every_scenario_speaks_the_protocol_the_package_emits(): void + { + $known = $this->protocolTypes(); + + $this->assertContains('tool-input-available', $known, 'the vendor scan found nothing, so this test proves nothing'); + + foreach (array_keys(CannedReplies::SCENARIOS) as $scenario) { + foreach ($this->framesFor($scenario) as $frame) { + $this->assertContains( + $frame['type'], + $known, + "Scenario [{$scenario}] emits [{$frame['type']}], which Laravel\\Ai no longer sends.", + ); + } + } + } + + public function test_every_scenario_opens_with_a_start_frame(): void + { + foreach (array_keys(CannedReplies::SCENARIOS) as $scenario) { + $this->assertSame('start', $this->framesFor($scenario)[0]['type'], $scenario); + } + } + + public function test_only_the_failure_scenario_ends_without_finishing(): void + { + foreach (array_keys(CannedReplies::SCENARIOS) as $scenario) { + $frames = $this->framesFor($scenario); + $last = end($frames)['type']; + + $scenario === 'failure' + ? $this->assertSame('error', $last) + : $this->assertSame('finish', $last, $scenario); + } + } + + public function test_a_named_scenario_is_honoured_and_anything_else_is_random(): void + { + $this->assertSame('markdown', CannedReplies::pick('markdown')); + $this->assertArrayHasKey(CannedReplies::pick('nonsense'), CannedReplies::SCENARIOS); + $this->assertArrayHasKey(CannedReplies::pick(null), CannedReplies::SCENARIOS); + } + + public function test_it_streams_canned_frames_instead_of_calling_the_model(): void + { + config(['ai-chat.test_mode' => true]); + + $response = $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hello?']); + + $response->assertOk(); + $response->assertHeader('x-vercel-ai-ui-message-stream', 'v1'); + + $scenario = $response->headers->get('X-Chat-Test-Scenario'); + $this->assertArrayHasKey($scenario, CannedReplies::SCENARIOS); + + $body = $response->streamedContent(); + $this->assertStringContainsString('data: {"type":"start"', $body); + $this->assertStringContainsString("data: [DONE]\n\n", $body); + } + + public function test_the_failure_scenario_never_leaks_the_provider_wording(): void + { + config(['ai-chat.test_mode' => true]); + + $response = $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream').'?scenario=failure', ['message' => 'Hello?']); + + $body = $response->streamedContent(); + + $this->assertStringNotContainsString('org-EXAMPLE0000', $body); + $this->assertStringNotContainsString('Rate limit reached', $body); + $this->assertStringContainsString('The assistant could not be reached', $body); + } + + public function test_test_mode_is_refused_in_production(): void + { + config(['ai-chat.test_mode' => true]); + $this->app['env'] = 'production'; + + $this->assertTrue($this->app->isProduction()); + + // Reaching the real agent is the proof it did not take the canned path; + // with no provider configured for tests that surfaces as a failure + // frame rather than a scenario header. + $response = $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hello?']); + + $this->assertNull($response->headers->get('X-Chat-Test-Scenario')); + } +} diff --git a/tests/Feature/ChatStreamTest.php b/tests/Feature/ChatStreamTest.php new file mode 100644 index 0000000..4b9caec --- /dev/null +++ b/tests/Feature/ChatStreamTest.php @@ -0,0 +1,300 @@ +get(route('ai-chat.index'))->assertRedirect(route('login')); + } + + public function test_guests_cannot_stream_a_message(): void + { + $response = $this->post(route('ai-chat.stream'), ['message' => 'Hello']); + + $response->assertRedirect(route('login')); + + // The chat page detects an expired session via `response.redirected`, + // because fetch follows the redirect and would otherwise hand the SDK a + // 200 containing the login page. If this ever became a 200 or a JSON + // error, that detection would silently stop working. + $this->assertTrue($response->isRedirect()); + } + + public function test_chat_page_renders_for_an_authenticated_user(): void + { + $response = $this->actingAs(User::factory()->create())->get(route('ai-chat.index')); + + $response->assertOk(); + $response->assertInertia( + // Module pages resolve through module-loader.js, not PHP, so the + // Inertia view finder cannot confirm they exist. Skip that check. + fn ($page) => $page->component('AiChat::Index', false)->has('initialMessages', 0) + ); + } + + public function test_it_streams_a_reply_using_the_vercel_protocol(): void + { + Ai::fakeAgent(ChatAgent::class, ['Hello from the assistant.']); + + $response = $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hi there']); + + $response->assertOk(); + $response->assertHeader('content-type', 'text/event-stream; charset=utf-8'); + $response->assertHeader('x-vercel-ai-ui-message-stream', 'v1'); + + $stream = $response->streamedContent(); + + $this->assertStringContainsString('data: [DONE]', $stream); + $this->assertSame('Hello from the assistant.', $this->textFrom($stream)); + + Ai::assertAgentWasPrompted(ChatAgent::class, 'Hi there'); + } + + public function test_a_provider_failure_stays_inside_the_stream(): void + { + // Thrown while the stream is being iterated, which is where a real + // provider failure lands -- after the response headers have gone out. + Ai::fakeAgent(ChatAgent::class, fn () => throw new RuntimeException('Incorrect API key provided: sk-abc.')); + + $response = $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hi there']); + + // 200, because the headers were committed before the provider was + // reached. The protocol carries the error in a frame instead. + $response->assertOk(); + $response->assertHeader('content-type', 'text/event-stream; charset=utf-8'); + + $stream = $response->streamedContent(); + + $this->assertStringContainsString('"type":"error"', $stream); + $this->assertStringContainsString('data: [DONE]', $stream); + + // Letting it escape the generator made Laravel render a whole HTML + // error page over the top of the stream, which is what sent nginx a + // second set of headers and produced the duplicate Date warning. + $this->assertStringNotContainsString('', $stream); + + // The provider names keys and account state in its errors. + $this->assertStringNotContainsString('sk-abc', $stream); + } + + public function test_the_reply_is_persisted_against_the_user(): void + { + Ai::fakeAgent(ChatAgent::class, ['Stored reply.']); + + $user = User::factory()->create(); + + $this->actingAs($user) + ->post(route('ai-chat.stream'), ['message' => 'Remember this']) + ->streamedContent(); + + $this->assertDatabaseHas('agent_conversations', [ + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + ]); + + $this->assertDatabaseHas('agent_conversation_messages', [ + 'role' => 'user', + 'content' => 'Remember this', + ]); + } + + /** + * Reassemble the assistant's reply from the protocol's text-delta frames. + */ + protected function textFrom(string $stream): string + { + return collect(explode("\n", $stream)) + ->filter(fn (string $line): bool => str_starts_with($line, 'data: {')) + ->map(fn (string $line): array => json_decode(substr($line, 6), true) ?? []) + ->where('type', 'text-delta') + ->pluck('delta') + ->implode(''); + } + + public function test_a_message_is_required(): void + { + $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => '']) + ->assertSessionHasErrors('message'); + } + + public function test_guests_cannot_open_a_conversation(): void + { + $this->get(route('ai-chat.show', 'anything'))->assertRedirect(route('login')); + } + + public function test_a_new_chat_reports_its_conversation_id(): void + { + Ai::fakeAgent(ChatAgent::class, ['Reply.']); + + $user = User::factory()->create(); + + $response = $this->actingAs($user) + ->post(route('ai-chat.stream'), ['message' => 'First message']); + + $response->assertOk(); + + // The browser has no other way to learn the id of a chat it just + // started, and needs it to move onto /chat/{id}. + $id = $response->headers->get('X-Conversation-Id'); + + $this->assertNotNull($id); + $this->assertDatabaseHas('agent_conversations', [ + 'id' => $id, + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'title' => 'First message', + ]); + } + + public function test_a_user_can_read_one_of_their_conversations_as_json(): void + { + Ai::fakeAgent(ChatAgent::class, ['Stored reply.']); + + $user = User::factory()->create(); + $conversationId = $this->sendMessages($user, ['Remember this']); + + $response = $this->actingAs($user)->getJson(route('ai-chat.messages', $conversationId)); + + $response->assertOk(); + $response->assertJsonPath('id', $conversationId); + $response->assertJsonPath('messages.0.role', 'user'); + $response->assertJsonPath('messages.0.text', 'Remember this'); + $response->assertJsonCount(2, 'messages'); + } + + public function test_a_user_cannot_read_another_users_conversation_as_json(): void + { + $conversation = $this->conversationFor(User::factory()->create()); + + $this->actingAs(User::factory()->create()) + ->getJson(route('ai-chat.messages', $conversation->id)) + ->assertNotFound(); + } + + public function test_guests_cannot_read_a_conversation_as_json(): void + { + $this->get(route('ai-chat.messages', 'anything'))->assertRedirect(route('login')); + } + + public function test_an_existing_conversation_restores_its_history(): void + { + Ai::fakeAgent(ChatAgent::class, ['Stored reply.']); + + $user = User::factory()->create(); + + $response = $this->actingAs($user) + ->post(route('ai-chat.stream'), ['message' => 'Remember this']); + $response->streamedContent(); + + $id = $response->headers->get('X-Conversation-Id'); + + $this->actingAs($user) + ->get(route('ai-chat.show', $id)) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('AiChat::Index', false) + ->where('conversationId', $id) + ->has('initialMessages', 2) + ); + } + + public function test_a_user_cannot_open_another_users_conversation(): void + { + $conversation = $this->conversationFor(User::factory()->create()); + + $this->actingAs(User::factory()->create()) + ->get(route('ai-chat.show', $conversation->id)) + ->assertNotFound(); + } + + public function test_a_user_cannot_stream_into_another_users_conversation(): void + { + Ai::fakeAgent(ChatAgent::class, ['Reply.']); + + $conversation = $this->conversationFor(User::factory()->create()); + + $this->actingAs(User::factory()->create())->post(route('ai-chat.stream'), [ + 'message' => 'Hello', + 'conversation_id' => $conversation->id, + ])->assertNotFound(); + + $this->assertDatabaseMissing('agent_conversation_messages', [ + 'conversation_id' => $conversation->id, + ]); + } + + public function test_streaming_into_an_unknown_conversation_is_rejected(): void + { + Ai::fakeAgent(ChatAgent::class, ['Reply.']); + + $this->actingAs(User::factory()->create())->post(route('ai-chat.stream'), [ + 'message' => 'Hello', + 'conversation_id' => 'not-a-conversation', + ])->assertNotFound(); + } + + public function test_the_session_list_only_contains_your_own_conversations(): void + { + $user = User::factory()->create(); + + $this->conversationFor($user, 'Mine'); + $this->conversationFor(User::factory()->create(), 'Theirs'); + + $this->actingAs($user) + ->get(route('ai-chat.index')) + ->assertInertia(fn ($page) => $page + ->has('chat.sessions', 1) + ->where('chat.sessions.0.title', 'Mine') + ); + } + + /** + * Create a conversation owned by the given user. + */ + protected function conversationFor(object $user, string $title = 'A chat'): Conversation + { + return Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'title' => $title, + ]); + } + + /** + * @param list $messages + */ + protected function sendMessages(object $user, array $messages, ?string $conversationId = null): string + { + foreach ($messages as $message) { + $response = $this->actingAs($user)->post(route('ai-chat.stream'), array_filter([ + 'message' => $message, + 'conversation_id' => $conversationId, + ])); + + $response->assertOk(); + $response->streamedContent(); + $conversationId ??= $response->headers->get('X-Conversation-Id'); + } + + $this->assertNotNull($conversationId); + + return $conversationId; + } +} diff --git a/tests/Feature/IndexTest.php b/tests/Feature/IndexTest.php deleted file mode 100644 index 02e91f2..0000000 --- a/tests/Feature/IndexTest.php +++ /dev/null @@ -1,20 +0,0 @@ -get('/ai-chat')->assertOk()->assertInertia(fn ($page) => $page - ->component('AiChat::Index', false) - ->where('module', 'aichat') - ); - } -} diff --git a/tests/Feature/StreamFailureTest.php b/tests/Feature/StreamFailureTest.php new file mode 100644 index 0000000..c7bfced --- /dev/null +++ b/tests/Feature/StreamFailureTest.php @@ -0,0 +1,93 @@ +keepFailuresInTheStream($response); + } + }; + + $response = $controller->decorate(new StreamedResponse($body)); + + ob_start(); + $response->sendContent(); + + return (string) ob_get_clean(); + } + + public function test_it_keeps_the_provider_wording_out_of_the_browser(): void + { + $secret = 'Rate limit reached for gpt-5.4-mini in organization org-9cCpgIsPSDoihTAM13Ripuy3'; + + $sent = $this->streamThrough(function () use ($secret): void { + echo 'data: '.json_encode(['type' => 'start', 'messageId' => 'abc'])."\n\n"; + echo 'data: '.json_encode(['type' => 'error', 'errorText' => $secret])."\n\n"; + echo "data: [DONE]\n\n"; + }); + + $this->assertStringNotContainsString('org-9cCpgIsPSDoihTAM13Ripuy3', $sent); + $this->assertStringNotContainsString('Rate limit reached', $sent); + $this->assertStringContainsString('The assistant could not be reached', $sent); + + // The frame itself has to survive: the browser reads it to know the + // reply failed, and dropping it would put the silence back. + $this->assertStringContainsString('"type":"error"', $sent); + } + + public function test_it_leaves_every_other_frame_alone(): void + { + $sent = $this->streamThrough(function (): void { + echo 'data: '.json_encode(['type' => 'start', 'messageId' => 'abc'])."\n\n"; + echo 'data: '.json_encode(['type' => 'text-delta', 'delta' => 'Kinsale is lovely'])."\n\n"; + echo "data: [DONE]\n\n"; + }); + + $this->assertStringContainsString('Kinsale is lovely', $sent); + $this->assertStringContainsString('"messageId":"abc"', $sent); + $this->assertStringContainsString("data: [DONE]\n\n", $sent); + } + + public function test_a_frame_split_across_writes_is_still_cleaned(): void + { + // The rewriter holds a partial frame back rather than passing it + // through unread, which is the one case that would leak. + $sent = $this->streamThrough(function (): void { + echo 'data: {"type":"error","errorText":"Rate limit reached for '; + echo 'org-9cCpgIsPSDoihTAM13Ripuy3"}'."\n\n"; + echo "data: [DONE]\n\n"; + }); + + $this->assertStringNotContainsString('org-9cCpgIsPSDoihTAM13Ripuy3', $sent); + $this->assertStringContainsString('The assistant could not be reached', $sent); + } + + public function test_an_escaping_exception_becomes_an_error_frame_and_a_terminator(): void + { + $sent = $this->streamThrough(function (): void { + echo 'data: '.json_encode(['type' => 'start', 'messageId' => 'abc'])."\n\n"; + + throw new RuntimeException('sk-secret-key rejected'); + }); + + $this->assertStringNotContainsString('sk-secret-key', $sent); + $this->assertStringContainsString('The assistant could not be reached', $sent); + $this->assertStringContainsString("data: [DONE]\n\n", $sent); + } +} From 62d87da8dd22a05de860d71707fda95ce1b348d4 Mon Sep 17 00:00:00 2001 From: roble Date: Wed, 25 Nov 2026 10:57:14 +0000 Subject: [PATCH 02/34] feat: chat page with session list, steps and markdown replies Vue page on @ai-sdk/vue: new chats move onto their own URL from the X-Conversation-Id header, an expired session is reported instead of an empty reply, reasoning and tool calls fold into a steps list. Co-Authored-By: Claude Opus 5.5 --- package.json | 7 +- resources/js/vue/app.ts | 24 +- .../js/vue/components/ChatMessage.stories.ts | 44 ++++ resources/js/vue/components/ChatMessage.vue | 40 ++++ .../js/vue/components/ChatSessions.stories.ts | 37 +++ resources/js/vue/components/ChatSessions.vue | 43 ++++ .../js/vue/components/ChatSteps.stories.ts | 48 ++++ resources/js/vue/components/ChatSteps.vue | 63 +++++ resources/js/vue/lib/http.ts | 6 + resources/js/vue/lib/tools.ts | 9 + resources/js/vue/pages/Index.vue | 225 ++++++++++++++---- routes/navigation.php | 17 +- tests/e2e/index.spec.ts | 13 - 13 files changed, 487 insertions(+), 89 deletions(-) create mode 100644 resources/js/vue/components/ChatMessage.stories.ts create mode 100644 resources/js/vue/components/ChatMessage.vue create mode 100644 resources/js/vue/components/ChatSessions.stories.ts create mode 100644 resources/js/vue/components/ChatSessions.vue create mode 100644 resources/js/vue/components/ChatSteps.stories.ts create mode 100644 resources/js/vue/components/ChatSteps.vue create mode 100644 resources/js/vue/lib/http.ts create mode 100644 resources/js/vue/lib/tools.ts delete mode 100644 tests/e2e/index.spec.ts diff --git a/package.json b/package.json index bb158be..e7f256f 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,10 @@ { "name": "@saucebase/ai-chat", "private": true, - "type": "module" + "type": "module", + "dependencies": { + "@ai-sdk/vue": "^4.0.181", + "ai": "^7.0.181", + "vue-stream-markdown": "^1.1.0" + } } diff --git a/resources/js/vue/app.ts b/resources/js/vue/app.ts index f371333..2e37184 100644 --- a/resources/js/vue/app.ts +++ b/resources/js/vue/app.ts @@ -1,25 +1,9 @@ -// import { registerIcon } from '@/lib/navigation'; -// import IconExample from '~icons/lucide/example'; - -// Custom styles: create resources/css/style.css in this module and uncomment. -// import '@modules/aichat/resources/css/style.css'; +import { registerIcon } from '@saucebase/vue/lib/navigation'; +import IconChat from '~icons/heroicons/chat-bubble-left-right'; /** - * AiChat module setup - * Called before the first render, on the server too: register things here, - * and leave anything that needs window or document to afterMount() + * Called before the first render, on the server too. */ export function setup() { - console.debug('AiChat module loaded'); - - // Register icons for navigation items defined in routes/navigation.php - // registerIcon('ai-chat', IconExample); -} - -/** - * AiChat module after mount logic - * Called in the browser after the app has mounted - */ -export function afterMount() { - console.debug('AiChat module after mount logic executed'); + registerIcon('ai-chat', IconChat); } diff --git a/resources/js/vue/components/ChatMessage.stories.ts b/resources/js/vue/components/ChatMessage.stories.ts new file mode 100644 index 0000000..0d4384f --- /dev/null +++ b/resources/js/vue/components/ChatMessage.stories.ts @@ -0,0 +1,44 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import ChatMessage from './ChatMessage.vue'; + +/** + * One turn of the chat. The user's message is a plain bubble on the right; the + * assistant's answer renders Markdown, under the steps it took to get there. + */ +const meta = preview.meta({ + title: 'AiChat/ChatMessage', + component: ChatMessage, + decorators: [() => ({ template: '
' })], +}); +export default meta; + +/** What the user typed, line breaks kept. */ +export const User = meta.story({ + args: { message: { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'What plan am I on?\nAnd how many messages are left?' }] } }, + play: async ({ canvas }) => { + await expect(canvas.getByTestId('chat-message-user')).toHaveTextContent('What plan am I on?'); + }, +}); + +/** An answer with a list, a table and code. */ +export const Assistant = meta.story({ + args: { + message: { + id: 'a1', + role: 'assistant', + parts: [ + { type: 'reasoning', text: 'Looking up the account.', state: 'done' }, + { + type: 'text', + state: 'done', + text: "You're on **Pro**.\n\n| Plan | Messages |\n| --- | --- |\n| Free | 50 |\n| Pro | 2,000 |\n\n```php\necho 'hi';\n```", + }, + ], + }, + }, + play: async ({ canvas }) => { + await expect(await canvas.findByRole('table')).toBeVisible(); + await expect(canvas.getByRole('button', { name: 'Steps' })).toBeVisible(); + }, +}); diff --git a/resources/js/vue/components/ChatMessage.vue b/resources/js/vue/components/ChatMessage.vue new file mode 100644 index 0000000..0ee1e82 --- /dev/null +++ b/resources/js/vue/components/ChatMessage.vue @@ -0,0 +1,40 @@ + + + diff --git a/resources/js/vue/components/ChatSessions.stories.ts b/resources/js/vue/components/ChatSessions.stories.ts new file mode 100644 index 0000000..0a7ac74 --- /dev/null +++ b/resources/js/vue/components/ChatSessions.stories.ts @@ -0,0 +1,37 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import ChatSessions from './ChatSessions.vue'; + +const sessions = [ + { id: 'a1', title: 'Plan a product launch email' }, + { id: 'b2', title: 'Explain Laravel queues' }, + { id: 'c3', title: 'Pricing page copy ideas' }, +]; + +/** + * The signed-in user's chats, newest first, beside the conversation. The server + * shares them as `chat.sessions` on chat pages. "New chat" opens a blank one. + */ +const meta = preview.meta({ + title: 'AiChat/ChatSessions', + component: ChatSessions, + decorators: [() => ({ template: '
' })], +}); +export default meta; + +/** A few chats, the second one open. */ +export const WithChats = meta.story({ + args: { sessions, activeId: 'b2' }, + play: async ({ canvas }) => { + await expect(canvas.getByRole('link', { name: 'Explain Laravel queues' })).toHaveAttribute('aria-current', 'page'); + await expect(canvas.getByRole('link', { name: 'New chat' })).toBeVisible(); + }, +}); + +/** Before the first message: nothing to list yet. */ +export const Empty = meta.story({ + args: { sessions: [] }, + play: async ({ canvas }) => { + await expect(canvas.getByText('Your chats will show up here.')).toBeVisible(); + }, +}); diff --git a/resources/js/vue/components/ChatSessions.vue b/resources/js/vue/components/ChatSessions.vue new file mode 100644 index 0000000..a9ce321 --- /dev/null +++ b/resources/js/vue/components/ChatSessions.vue @@ -0,0 +1,43 @@ + + + diff --git a/resources/js/vue/components/ChatSteps.stories.ts b/resources/js/vue/components/ChatSteps.stories.ts new file mode 100644 index 0000000..e9f406d --- /dev/null +++ b/resources/js/vue/components/ChatSteps.stories.ts @@ -0,0 +1,48 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import ChatSteps from './ChatSteps.vue'; + +const reasoning = { type: 'reasoning', text: '**Reading the question**: the user wants their current plan.', state: 'done' } as const; + +/** + * What the assistant did before it answered: its reasoning and each tool it + * called, in order. Open while the reply streams, folded once it's done. + */ +const meta = preview.meta({ + title: 'AiChat/ChatSteps', + component: ChatSteps, +}); +export default meta; + +/** A finished reply: folded, the trigger opens it. */ +export const Done = meta.story({ + args: { + parts: [reasoning, { type: 'tool-about_my_account', toolCallId: 'c1', state: 'output-available', input: {}, output: '{}' }], + }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole('button', { name: 'Steps' })); + await expect(canvas.getByText(/Reading the question/)).toBeVisible(); + }, +}); + +/** Still streaming: open, the running tool spins. */ +export const Streaming = meta.story({ + args: { + streaming: true, + parts: [reasoning, { type: 'tool-web_search', toolCallId: 'c2', state: 'input-available', input: {} }], + }, + play: async ({ canvas }) => { + await expect(canvas.getByRole('button', { name: 'Working…' })).toHaveAttribute('aria-expanded', 'true'); + }, +}); + +/** A tool that failed. */ +export const Failed = meta.story({ + args: { + streaming: true, + parts: [{ type: 'tool-generate_image', toolCallId: 'c3', state: 'output-error', input: {}, errorText: 'Unavailable' }], + }, + play: async ({ canvas }) => { + await expect(canvas.getByText('generate image')).toBeVisible(); + }, +}); diff --git a/resources/js/vue/components/ChatSteps.vue b/resources/js/vue/components/ChatSteps.vue new file mode 100644 index 0000000..7a359dd --- /dev/null +++ b/resources/js/vue/components/ChatSteps.vue @@ -0,0 +1,63 @@ + + + diff --git a/resources/js/vue/lib/http.ts b/resources/js/vue/lib/http.ts new file mode 100644 index 0000000..8c4cac0 --- /dev/null +++ b/resources/js/vue/lib/http.ts @@ -0,0 +1,6 @@ +/** The XSRF cookie Laravel sets, for requests made outside Inertia. */ +export function csrfToken(): string { + const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/); + + return match ? decodeURIComponent(match[1]) : ''; +} diff --git a/resources/js/vue/lib/tools.ts b/resources/js/vue/lib/tools.ts new file mode 100644 index 0000000..78de5a0 --- /dev/null +++ b/resources/js/vue/lib/tools.ts @@ -0,0 +1,9 @@ +/** + * What each tool reads as in a reply's steps. Adding a tool is one entry here; + * a tool without one still shows, under its own name. + */ +export const TOOL_LABELS: Record = {}; + +export function toolLabel(name: string, state: 'running' | 'done' | 'failed'): string { + return TOOL_LABELS[name]?.[state] ?? name.replaceAll('_', ' '); +} diff --git a/resources/js/vue/pages/Index.vue b/resources/js/vue/pages/Index.vue index d92d0a5..79e1549 100644 --- a/resources/js/vue/pages/Index.vue +++ b/resources/js/vue/pages/Index.vue @@ -1,51 +1,196 @@