diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c2d85be..6114a32 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,4 +14,5 @@ jobs: uses: saucebase-dev/core/.github/workflows/test-module.yml@main with: module: ai-chat - # dependencies: saucebase/auth # add space-separated packages if needed + # Login (guests are sent to it) and billing's plans (the message and image limits). + dependencies: saucebase/auth saucebase/billing diff --git a/README.md b/README.md index d10227c..995ad56 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,18 @@ -# AiChat Module +# AI Chat -A Laravel module that extends Saucebase core functionality. Designed for seamless integration with the ecosystem. +A streaming AI chat for Saucebase apps, at `/chat`. -This module is part of **[Saucebase](https://github.com/saucebase-dev/saucebase)** +- Conversations per user, titled automatically, with a session list. +- Tools: web search (the provider's own), image generation, and `about_my_account`, which reads the signed-in user's profile, plan and workspace from the installed modules. It is the example to copy for your own tools. +- Monthly limits per plan (`ai_chat_messages`, `ai_chat_images`) with the Billing module. +- Admin: extra instructions, the models users can pick, and a read-only conversation viewer. +- WebMCP: the visitor's own browser agent can ask the assistant and read or switch chats. -**[Documentation →](https://saucebase-dev.github.io/docs/modules)** +## Install + +```bash +php artisan saucebase:module-install ai-chat +npm install && npm run build +``` + +Set a provider key in `.env` (see `config/ai.php` from laravel/ai). Without one, `AI_CHAT_TEST_MODE=true` answers through a demo provider (the replies in `resources/demos/`, offered as models in the picker) so the chat can be built and tried for free. diff --git a/composer.json b/composer.json index 3508941..c589fea 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "description": "AI chat with streaming replies, web search, image generation, account-aware tools, plan usage limits and WebMCP.", "type": "saucebase-module", "license": "proprietary", - "version": "v0.1.0", + "version": "v1.0.0", "authors": [ { "name": "Saucebase", @@ -22,7 +22,7 @@ ] }, "branch-alias": { - "dev-dev": "0.x-dev" + "dev-dev": "1.x-dev" } }, "autoload": { @@ -39,7 +39,7 @@ }, "minimum-stability": "stable", "require": { - "saucebase/core": "^3.1", + "saucebase/core": "^3.3", "laravel/ai": "^0.11" } } diff --git a/config/config.php b/config/config.php index e0c4035..d81677e 100644 --- a/config/config.php +++ b/config/config.php @@ -1,5 +1,30 @@ 'page', + + /* + | Answer through the demo provider (replies from resources/demos) instead of + | a real model, so the chat can be + | worked on without a provider key or tokens. Refused in production whatever + | this says: invented answers for real users are worse than an outage. + */ + 'test_mode' => (bool) env('AI_CHAT_TEST_MODE', false), + + /* + | Where generate_image sends its prompts. Null: laravel/ai's defaults + | (`ai.default_for_images`, which is Gemini). Quality: low, medium or high. + */ + 'images' => [ + 'provider' => env('AI_CHAT_IMAGE_PROVIDER'), + 'model' => env('AI_CHAT_IMAGE_MODEL'), + 'quality' => env('AI_CHAT_IMAGE_QUALITY'), + ], + ]; 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/database/migrations/2026_11_28_000001_add_renamed_at_to_agent_conversations_table.php b/database/migrations/2026_11_28_000001_add_renamed_at_to_agent_conversations_table.php new file mode 100644 index 0000000..2367120 --- /dev/null +++ b/database/migrations/2026_11_28_000001_add_renamed_at_to_agent_conversations_table.php @@ -0,0 +1,27 @@ + $blueprint->timestamp('renamed_at')->nullable()); + } + } + + public function down(): void + { + $table = config('ai.conversations.tables.conversations', 'agent_conversations'); + + Schema::table($table, fn (Blueprint $blueprint) => $blueprint->dropColumn('renamed_at')); + } +}; diff --git a/database/migrations/2026_11_28_000002_add_pinned_at_to_agent_conversations_table.php b/database/migrations/2026_11_28_000002_add_pinned_at_to_agent_conversations_table.php new file mode 100644 index 0000000..fc3e227 --- /dev/null +++ b/database/migrations/2026_11_28_000002_add_pinned_at_to_agent_conversations_table.php @@ -0,0 +1,27 @@ + $blueprint->timestamp('pinned_at')->nullable()); + } + } + + public function down(): void + { + $table = config('ai.conversations.tables.conversations', 'agent_conversations'); + + Schema::table($table, fn (Blueprint $blueprint) => $blueprint->dropColumn('pinned_at')); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php new file mode 100644 index 0000000..bf3fc69 --- /dev/null +++ b/database/seeders/DatabaseSeeder.php @@ -0,0 +1,67 @@ +models !== []) { + return; + } + + $settings->models = $this->commonModels(); + $settings->default_model ??= $settings->models[0]['model'] ?? null; + $settings->save(); + } + + /** + * Each provider's cheapest, default and smartest text model, cheapest first. + * + * @return list + */ + protected function commonModels(): array + { + $rows = []; + + foreach (self::PROVIDERS as $provider) { + $label = Providers::label($provider); + + try { + $text = app(AiManager::class)->textProvider($provider); + $models = [$text->cheapestTextModel(), $text->defaultTextModel(), $text->smartestTextModel()]; + } catch (Throwable) { + // A provider this laravel/ai build can't construct: leave it out. + continue; + } + + foreach (array_unique($models) as $model) { + $rows[] = ['label' => "{$label} {$model}", 'provider' => $provider, 'model' => $model]; + } + } + + return $rows; + } +} diff --git a/database/settings/1000_00_00_000002_create_ai_chat_settings.php b/database/settings/1000_00_00_000002_create_ai_chat_settings.php new file mode 100644 index 0000000..194d376 --- /dev/null +++ b/database/settings/1000_00_00_000002_create_ai_chat_settings.php @@ -0,0 +1,21 @@ + '', + 'ai_chat.models' => [], + 'ai_chat.default_model' => null, + ]; + + foreach ($defaults as $name => $value) { + if (! $this->migrator->exists($name)) { + $this->migrator->add($name, $value); + } + } + } +}; diff --git a/database/settings/1000_00_00_000003_add_ai_chat_provider_settings.php b/database/settings/1000_00_00_000003_add_ai_chat_provider_settings.php new file mode 100644 index 0000000..c9c3fe1 --- /dev/null +++ b/database/settings/1000_00_00_000003_add_ai_chat_provider_settings.php @@ -0,0 +1,19 @@ +migrator->exists('ai_chat.api_keys')) { + $this->migrator->addEncrypted('ai_chat.api_keys', []); + } + + foreach (['ai_chat.image_provider', 'ai_chat.image_model', 'ai_chat.image_quality'] as $name) { + if (! $this->migrator->exists($name)) { + $this->migrator->add($name, null); + } + } + } +}; diff --git a/package.json b/package.json index bb158be..33fc0c5 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,11 @@ { "name": "@saucebase/ai-chat", "private": true, - "type": "module" + "type": "module", + "dependencies": { + "@ai-sdk/vue": "^4.0.181", + "ai": "^7.0.181", + "shiki": "^4.6.0", + "vue-stream-markdown": "^1.1.0" + } } diff --git a/resources/boost/guidelines/core.md b/resources/boost/guidelines/core.md index e66cb60..701147b 100644 --- a/resources/boost/guidelines/core.md +++ b/resources/boost/guidelines/core.md @@ -1,7 +1,9 @@ -## Ai Chat module +## AI Chat module -`modules/ai-chat` (namespace `Modules\AiChat`) — describe what this module owns in one or two sentences. +`modules/ai-chat` (namespace `Modules\AiChat`) owns the streaming AI chat at `/chat`: conversations (laravel/ai's `agent_conversations` tables), the agent and its tools, monthly plan limits, the admin settings and conversation viewer, and the page's WebMCP tools. -- List the two to four conventions an agent must never break here. +- Resolve every client-sent conversation id through `AiChatController::ownedConversation()`: laravel/ai's `continue()` checks no ownership. +- A tool acts on the user the agent was built with (`new ChatAgent($request->user())`), never on an id the model passes. +- The browser may pick only a model listed in `AiChatSettings::$models`. Activate the `saucebase-ai-chat-development` skill before changing this module. diff --git a/resources/boost/skills/saucebase-ai-chat-development/SKILL.md b/resources/boost/skills/saucebase-ai-chat-development/SKILL.md index 368e1f2..ea019d6 100644 --- a/resources/boost/skills/saucebase-ai-chat-development/SKILL.md +++ b/resources/boost/skills/saucebase-ai-chat-development/SKILL.md @@ -1,9 +1,9 @@ --- name: saucebase-ai-chat-development -description: Work on the Ai Chat module (modules/ai-chat). Use when changing its routes, models, pages, or tests. +description: Develop the Saucebase AI Chat module: the chat agent and its tools, streaming and the test-mode demo provider, conversation titles, plan usage limits, admin settings and model picker, and the page's WebMCP tools. Use when working under modules/ai-chat or adding a tool to the assistant. --- -# Ai Chat Module +# AI Chat Module Paths are relative to `modules/ai-chat/` unless they say otherwise. Commands run from the application root. @@ -11,13 +11,87 @@ Paths are relative to `modules/ai-chat/` unless they say otherwise. Commands run | Layer | Files | |-------|-------| -| Provider | `AiChatServiceProvider` | -| Controller | `AiChatController` | -| Filament | `AiChatPlugin` | +| Agent | `src/Ai/ChatAgent.php` (instructions, tools), `src/Ai/ConversationTitleAgent.php` | +| Tools | `src/Ai/Tools/AboutMyAccount.php` (the example of an app tool), `GenerateImage.php`; web search is laravel/ai's provider `WebSearch` | +| HTTP | `src/Http/Controllers/AiChatController.php` (index, show, messages, stream, update, destroy) | +| Sidebar list | `src/Sessions.php` (pinned + newest, Show more) | +| Limits | `src/Usage.php`, `routes/capabilities.php` | +| Admin | `src/Settings/AiChatSettings.php`, `src/Filament/Pages/AiChatSettings.php`, `src/Filament/Resources/Conversations/` | +| Jobs | `src/Jobs/GenerateConversationTitle.php` | +| Test mode | `src/Ai/Demo/` (`Demos`, `DemoProvider`, `DemoGateway`), demos in `resources/demos/*.json` | +| Page | `resources/js/vue/pages/Index.vue`, `components/ChatMessage.vue`, `ChatSteps.vue`, `ChatSessions.vue` (date groups, search, rename, delete), `ChatPanel.vue` (the list's own sidebar), `ChatScrollButton.vue`, `ChatInputBar.vue` (the strip above the box, `ChatInput`'s `top` slot), `ChatUsageBar.vue`, `WebMcpMenuItem.vue` | +| Browser lib | `resources/js/lib/tools.ts` (step labels, images), `sessions.ts` (date groups), `dictation.ts`, `chatTools.ts` + `webmcp.ts` (WebMCP) | + +## Adding a tool + +1. A class in `src/Ai/Tools/` implementing `Laravel\Ai\Contracts\Tool`, with a `NAME` constant. Take the user in the constructor; return a string (JSON for structured results). +2. Return it from `ChatAgent::tools()`. +3. Give it labels in `TOOL_LABELS` (`resources/js/lib/tools.ts`), or it shows under its name. +4. Optional: a demo in `resources/demos/` so test mode can show it. + +Provider-hosted tools (`WebSearch`) stream no parts: the steps list never shows them. + +## Streaming + +- `stream()` creates the conversation first and returns its id in `X-Conversation-Id`; the page moves onto `/chat/{id}` with a partial visit (`only: ['chat']`). +- `keepFailuresInTheStream()` turns a provider exception into an `error` frame and rewrites every error frame's text, so keys and account details never reach the browser. +- Over the monthly message limit the route answers 429 JSON before creating anything. The page shows the message and puts the text back in the box (422 too). +- laravel/ai stores the turn only after the stream completes. So the stream sets `ignore_user_abort(true)` (Stop would otherwise end PHP before storing; the reply finishes and is kept) and `set_time_limit(300)` (the default 30 s cuts long replies). +- `regenerate: true` (Ask again, Try again) deletes the previous turn after the new one is stored, only when its question matches: a failed reply stores nothing, so the turn before it stays. +- A chat opens on its newest 50 messages (`AiChatController::MESSAGES_PER_PAGE`, `hasOlder`). Older pages come from `GET chat/{id}/history?before=` when the marker above the messages scrolls into view, and go before the ones shown. The marker sits outside `MessageScrollerContent`: the scroller treats each of its children as a message, and keeps the view in place on a prepend by its first one. +- Steps are built on `trace`, like shadcn-vue's Reasoning: a thought is a plain "Thinking…" line until its first words, then a closed line that opens onto it, rendered as markdown (models write bold and headings). Closed while streaming too: a thought that opened, grew and closed again moved the reply under the reader and pulled the view back. Until a reply shows anything, `ChatMessage` renders that same line (`showsNothing()`), and before the reply exists the page renders an empty `ChatMessage` in its place: the line never moves when the thought takes over. The `thinking` demo has a long thought. +- Scrolling, as in ChatGPT minus the blank screen: a chat opens at the end, and a new question takes the view there once (`ChatScrollButton`, by the question count); nothing else moves it. No `auto-scroll` (chasing the reply moved the text from under the reader) and no `scroll-anchor` (holding the question at the top took a spacer up to a screen tall, which, shrinking, yanked the view). Instead a fixed `pb-48` under the messages, and while the end is out of view the button over it shows dots while a reply streams, an arrow after. +- The page reloads `initialMessages` on back/forward (Inertia's `navigate` event, type `history`): history keeps each page's first props. + +## Test mode + +`AI_CHAT_TEST_MODE=true` swaps every provider call for the demo provider; refused in production. Test mode offers the demos as the picker's models (`Demo: Steps`…), and titles and images use the demo provider too, so nothing reaches a paid API. The real agent, tools, storage and stream all run. Tests that need a real provider set `config(['ai-chat.test_mode' => false])` in `setUp()`, so a local `.env` can't change them. + +Each demo is a file, `resources/demos/.json`: `description`, `messages` (a short conversation in the AI SDK's UI message shape: `text`, `reasoning`, `tool-`, `source-url` parts) and an optional `error` (the provider message a failed reply ends on). `DemoGateway` plays the last assistant message one model step at a time: a step ends after each run of tool calls, laravel/ai runs the real tools (their output in the file is for Storybook only), and the next step follows. Images are drawn by the demo provider (a PNG from the prompt). A call to a tool that doesn't exist fails that call only (`#[RepairToolCalls]` on `ChatAgent`). Adding a demo is adding a file; Storybook stories can import the same files. + +`Demos::provider()` registers the provider with laravel/ai on first use, never at boot: the admin's provider list reads every configured provider. + +## Sessions + +`PATCH chat/{id}` renames (sets `renamed_at`, so `GenerateConversationTitle` leaves it alone; `updated_at` untouched) or pins (`pinned: bool` sets or clears `pinned_at`; pinned chats lead the list under Pinned, `groupSessions()`), `DELETE chat/{id}` removes the chat and its messages and returns to the open chat, or to a new one when that was the one deleted. `chat.sessions` is `{data, has_more}`: every pinned chat and the newest 50 others (`Sessions::PER_PAGE`), each with `updated_at` for the date groups. Show more (`POST chat/sessions/more`) raises the count for the rest of the login session, so every reload of the shared list (a message, a rename, another page) returns the same list and nothing is kept in the browser. + +## Where the list lives + +`ai-chat.sessions` (config, shared as `chat.sessions_in`): + +- `page` (default): the app sidebar gets a "Chat" item (`routes/navigation.php`, `active` on every `ai-chat.*` route) and starts collapsed to its icons on the chat (AppLayout's `collapseSidebar`, not saved over the reader's choice). The list, search and WebMCP sit in `ChatPanel`, a nested `SidebarProvider` with a static `Sidebar`, resizable with core's `SidebarResizer` (width in `ai-chat:panel-width`). On phones a "Chats" button opens it in a sheet. `chat.sessions` is shared only on the chat routes; other pages skip the query. +- `sidebar`: a chat-first app (the chat template sets it at boot). `app.ts` renders the list and WebMCP in the app sidebar slots on every page, with no item and no panel; the app sidebar itself is resizable on the chat. + +Search: `GET chat/sessions/search?q=` (`Sessions::search()`), the user's chats by title, newest 20, `LOWER(title) LIKE ? ESCAPE '!'`: case-insensitive on MySQL and Postgres; SQLite's `LOWER()` folds ASCII only, so there "École" and "école" differ. The box replaces the date groups while it has text. + +## WebMCP + +`Index.vue` registers its tools with `registerWebMcpTools()`; `offeredTools` lists them for the sidebar's WebMCP panel (`dashboard::sidebar.end`), also in browsers without WebMCP, where it shows the steps to turn it on. + +## Limits + +`ai_chat_messages` and `ai_chat_images` are billing limits. The chat page's `usage` prop (`used`, `limit`, `upgrade_url` when billing has `billing.plans`; null without a limit) feeds `ChatUsageBar` in the box's `top` slot: nothing below 80% (`lib/usage.ts`), a muted "You've used 40 of 50" bar from there (✕ hides it until next month, `localStorage` `ai-chat:usage-dismissed`), an orange one at the limit, which stays, and Send is disabled. The page counts a message as it is sent (optimistic); each reload of `usage` (with the chat list after a reply, or on an error) replaces it with the server's count. A key none of the user's plans declares is unlimited (billing would read it as 0). Messages are counted from stored user messages since the 1st; images from files in `ai-chat/images/{user}/{Y-m}` on the public disk. + +## Gotchas + +- Message ids are UUIDv7 (time-ordered): order transcripts by `id`. +- A rename must not touch `updated_at`, which orders the session list (`GenerateConversationTitle` sets `timestamps = false`). +- Titles need a queue worker; restart it after changing the job. +- Every button inside the message form other than Send needs `type="button"`: the default is submit, which sent the text and stopped dictation. +- The page body must not remount when a new chat moves onto its URL: core's `PageTransition` is keyed on the page component, not the URL. +- A reka tooltip never wraps a menu trigger (the chat's `…`): poppers find their root by inject, so the menu would anchor nowhere and open off-screen. The tooltip's trigger goes inside the button. +- `ui/message-scroller/useMessageScroller.ts` is patched (`markHandled`): anchors already in a loaded transcript or a prepended page count as handled. Upstream, the first swap that kept the child count took the transcript's first question for a new one and scrolled to the top. Keep the patch when updating the component. +- Messages are `content-visibility: auto`, sized at a 10rem estimate until laid out. A message arriving in the session starts `visible` and joins them two frames later (`settled` in `Index.vue`), once the browser has its real size: at the estimate, the scroller placed a new question 118px off and the view dropped, then jumped back when the reply ended. Loaded messages (the page's, older pages) are settled from the start. +- The message box is opaque in dark mode too (`InputGroup`'s own `dark:bg-input/30` is see-through): a top bar runs under its edge. +- A vue-stream-markdown node renderer (`ChatCodeBlock`) sets `inheritAttrs: false`: the library passes it `parentNode`, `markdownParser` and more, which would land on its root element, and `parentNode` warns on every streamed chunk. +- `AiChatSettings` properties carry no `@var` array shapes: spatie/laravel-settings parses them for casts. ## Testing ```bash -php artisan test --testsuite=Modules --filter='^Modules\\AiChat\\Tests' # PHPUnit -npx playwright test --project="@ai-chat*" # E2E +php artisan test --compact modules/ai-chat/tests # PHPUnit +npx vitest run modules/ai-chat # lib unit tests +npx playwright test modules/ai-chat/tests/e2e --project="@ai-chat*" # E2E ``` + +E2E specs turn test mode on per test (`laravel.config('ai-chat.test_mode', true)` in `beforeEach`, as themes does), so no key is needed in CI or locally. diff --git a/resources/demos/account.json b/resources/demos/account.json new file mode 100644 index 0000000..0d0d205 --- /dev/null +++ b/resources/demos/account.json @@ -0,0 +1,34 @@ +{ + "description": "The account tool, then an answer from it.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Which plan am I on?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Checking the account** — the question is about their plan." + }, + { + "type": "tool-about_my_account", + "toolCallId": "call-about_my_account", + "input": {}, + "state": "output-available", + "output": "{\"name\": \"Chef\", \"email\": \"chef@example.com\", \"member_since\": \"2026-01-15\", \"plan\": {\"name\": \"Pro\", \"paid\": true, \"limits\": {\"ai_chat_messages\": 2000}}}" + }, + { + "type": "text", + "text": "You are on the **Pro** plan, with 2,000 chat messages a month." + } + ] + } + ] +} diff --git a/resources/demos/artifact.json b/resources/demos/artifact.json new file mode 100644 index 0000000..74bf4fd --- /dev/null +++ b/resources/demos/artifact.json @@ -0,0 +1,27 @@ +{ + "description": "A whole file in the reply: the case for the side panel.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Write me a Vue counter component." + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**A complete component** — script, template and a little style, in one file." + }, + { + "type": "text", + "text": "Here is a counter component. Save it as `Counter.vue`:\n\n```vue\n\n\n\n\n\n```\n\nUse it with ``." + } + ] + } + ] +} diff --git a/resources/demos/code.json b/resources/demos/code.json new file mode 100644 index 0000000..71406ff --- /dev/null +++ b/resources/demos/code.json @@ -0,0 +1,27 @@ +{ + "description": "Code blocks in several languages, for highlighting and copy.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "How do I call the chat API from a script?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Choosing examples** — a curl call, then the same in TypeScript and PHP." + }, + { + "type": "text", + "text": "Send the message as JSON; the reply streams back as server-sent events.\n\n```bash\ncurl -N https://example.test/chat/stream \\\n -H 'Content-Type: application/json' \\\n -d '{\"message\": \"Hello\"}'\n```\n\nThe same from the browser:\n\n```ts\nimport { Chat } from '@ai-sdk/vue';\nimport { DefaultChatTransport } from 'ai';\n\nconst chat = new Chat({\n transport: new DefaultChatTransport({ api: '/chat/stream' }),\n});\n\nawait chat.sendMessage({ text: 'Hello' });\n```\n\nAnd from Laravel, with the HTTP client:\n\n```php\n$response = Http::withToken($token)\n ->post('https://example.test/chat/stream', ['message' => 'Hello']);\n```\n\nA reply is a list of parts:\n\n```json\n{ \"role\": \"assistant\", \"parts\": [{ \"type\": \"text\", \"text\": \"Hi!\" }] }\n```" + } + ] + } + ] +} diff --git a/resources/demos/failure.json b/resources/demos/failure.json new file mode 100644 index 0000000..7c8cf72 --- /dev/null +++ b/resources/demos/failure.json @@ -0,0 +1,24 @@ +{ + "description": "No reply at all: the provider gives out.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Hello?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Preparing to answer** — and then the provider gives out." + } + ] + } + ], + "error": "Rate limit reached for model in organization org-EXAMPLE0000 on requests per day (RPD): Limit 50, Used 50." +} diff --git a/resources/demos/image.json b/resources/demos/image.json new file mode 100644 index 0000000..fe34d5a --- /dev/null +++ b/resources/demos/image.json @@ -0,0 +1,32 @@ +{ + "description": "A generated image.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Draw a sunset over a calm sea." + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "tool-generate_image", + "toolCallId": "call-generate_image", + "input": { + "prompt": "A sunset over a calm sea" + }, + "state": "output-available", + "output": "{\"url\": \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj48cmVjdCB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgZmlsbD0iIzFlMjkzYiIvPjxjaXJjbGUgY3g9IjI1NiIgY3k9IjIwMCIgcj0iOTAiIGZpbGw9IiNmNTllMGIiLz48cmVjdCB5PSIzMzAiIHdpZHRoPSI1MTIiIGhlaWdodD0iMTgyIiBmaWxsPSIjMGY3NjZlIi8+PC9zdmc+\", \"prompt\": \"A sunset over a calm sea\"}" + }, + { + "type": "text", + "text": "Here is a sunset over a calm sea." + } + ] + } + ] +} diff --git a/resources/demos/images.json b/resources/demos/images.json new file mode 100644 index 0000000..8a3e211 --- /dev/null +++ b/resources/demos/images.json @@ -0,0 +1,45 @@ +{ + "description": "Two images in one reply, after a first try that failed.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Make two versions: dusk and night." + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Two images** — one per version, the same scene in different light." + }, + { + "type": "tool-generate_image", + "toolCallId": "call-dusk", + "input": { + "prompt": "A calm sea at dusk" + }, + "state": "output-available", + "output": "{\"url\": \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj48cmVjdCB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgZmlsbD0iIzdjMmQxMiIvPjxjaXJjbGUgY3g9IjI1NiIgY3k9IjIwMCIgcj0iOTAiIGZpbGw9IiNmYjkyM2MiLz48cmVjdCB5PSIzMzAiIHdpZHRoPSI1MTIiIGhlaWdodD0iMTgyIiBmaWxsPSIjMTU1ZTc1Ii8+PC9zdmc+\", \"prompt\": \"A calm sea at dusk\"}" + }, + { + "type": "tool-generate_image", + "toolCallId": "call-night", + "input": { + "prompt": "A calm sea at night" + }, + "state": "output-available", + "output": "{\"url\": \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj48cmVjdCB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgZmlsbD0iIzAyMDYxNyIvPjxjaXJjbGUgY3g9IjI1NiIgY3k9IjIwMCIgcj0iOTAiIGZpbGw9IiNlMmU4ZjAiLz48cmVjdCB5PSIzMzAiIHdpZHRoPSI1MTIiIGhlaWdodD0iMTgyIiBmaWxsPSIjMWUzYThhIi8+PC9zdmc+\", \"prompt\": \"A calm sea at night\"}" + }, + { + "type": "text", + "text": "Dusk first, then night: the same sea under a different sky." + } + ] + } + ] +} diff --git a/resources/demos/long.json b/resources/demos/long.json new file mode 100644 index 0000000..510b3dc --- /dev/null +++ b/resources/demos/long.json @@ -0,0 +1,27 @@ +{ + "description": "A long answer, for scrolling while it streams.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Explain how a chat reply streams, in detail." + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**A long answer** — one section per stage, from the request to the stored message." + }, + { + "type": "text", + "text": "## 1. The request\n\nThe page posts the message, the chosen model and the conversation id. The server checks the conversation belongs to the user and that the plan still has messages left this month.\n\n## 2. The agent\n\nThe agent reads the conversation so far, its instructions and the tools it may call. It sends all of it to the provider, which starts answering at once.\n\n## 3. Reasoning\n\nModels that think aloud send their reasoning first. It streams as its own part, so the page can show it apart from the answer and fold it away when the answer starts.\n\n## 4. Tools\n\nWhen the model needs something it cannot know, it calls a tool: the account tool reads the user's plan, the image tool draws a picture. Each call streams its input, then its result.\n\n## 5. The answer\n\nThe answer arrives a few words at a time. The page renders the Markdown as it grows, so lists and tables take shape while the reader watches.\n\n## 6. Sources\n\nA web search sends the links it used alongside the answer. They show under the reply, so the reader can check the claims.\n\n## 7. The end\n\nA finish frame closes the reply. The server stores both turns, and the conversation title is written in the background after the first few messages.\n\n## 8. Failures\n\nIf the provider gives out halfway, the stream ends with an error part instead of a broken page, and the reader can try again.\n\n## 1. The request\n\nThe page posts the message, the chosen model and the conversation id. The server checks the conversation belongs to the user and that the plan still has messages left this month.\n\n## 2. The agent\n\nThe agent reads the conversation so far, its instructions and the tools it may call. It sends all of it to the provider, which starts answering at once.\n\n## 3. Reasoning\n\nModels that think aloud send their reasoning first. It streams as its own part, so the page can show it apart from the answer and fold it away when the answer starts.\n\n## 4. Tools\n\nWhen the model needs something it cannot know, it calls a tool: the account tool reads the user's plan, the image tool draws a picture. Each call streams its input, then its result.\n\n## 5. The answer\n\nThe answer arrives a few words at a time. The page renders the Markdown as it grows, so lists and tables take shape while the reader watches.\n\n## 6. Sources\n\nA web search sends the links it used alongside the answer. They show under the reply, so the reader can check the claims.\n\n## 7. The end\n\nA finish frame closes the reply. The server stores both turns, and the conversation title is written in the background after the first few messages.\n\n## 8. Failures\n\nIf the provider gives out halfway, the stream ends with an error part instead of a broken page, and the reader can try again." + } + ] + } + ] +} diff --git a/resources/demos/markdown.json b/resources/demos/markdown.json new file mode 100644 index 0000000..4aa21de --- /dev/null +++ b/resources/demos/markdown.json @@ -0,0 +1,23 @@ +{ + "description": "Markdown: a list, a table and a code block.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Show me some formatting." + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "text", + "text": "Here is what Markdown looks like in the chat:\n\n- **Bold** and *italic* text\n- `inline code`\n- A [link](https://laravel.com)\n\n> A quote, for good measure.\n\n| Plan | Messages | Images |\n| --- | --- | --- |\n| Free | 50 | 5 |\n| Pro | 2,000 | 100 |\n\n```php\necho 'Hello from a code block';\n```" + } + ] + } + ] +} diff --git a/resources/demos/reply.json b/resources/demos/reply.json new file mode 100644 index 0000000..6222c42 --- /dev/null +++ b/resources/demos/reply.json @@ -0,0 +1,27 @@ +{ + "description": "A short answer after some reasoning.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Hi there!" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Reading the question** — a greeting, so a short answer will do." + }, + { + "type": "text", + "text": "Hi! I am running in test mode, so this answer is canned. Ask me anything to see how the chat looks." + } + ] + } + ] +} diff --git a/resources/demos/sources.json b/resources/demos/sources.json new file mode 100644 index 0000000..7e44607 --- /dev/null +++ b/resources/demos/sources.json @@ -0,0 +1,45 @@ +{ + "description": "A web search answer, with the links it used.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "What's new in Laravel 13?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Searching the web** — release notes first, then the upgrade guide." + }, + { + "type": "source-url", + "sourceId": "https://laravel.com/docs/13.x/releases", + "url": "https://laravel.com/docs/13.x/releases", + "title": "Release Notes - Laravel 13.x" + }, + { + "type": "source-url", + "sourceId": "https://laravel.com/docs/13.x/upgrade", + "url": "https://laravel.com/docs/13.x/upgrade", + "title": "Upgrade Guide - Laravel 13.x" + }, + { + "type": "source-url", + "sourceId": "https://laravel-news.com/laravel-13", + "url": "https://laravel-news.com/laravel-13", + "title": "Laravel 13 is now released - Laravel News" + }, + { + "type": "text", + "text": "Laravel 13 needs **PHP 8.3** or newer and brings first-party AI support through `laravel/ai`. The upgrade guide lists the few breaking changes; most apps move up in under an hour." + } + ] + } + ] +} diff --git a/resources/demos/steps.json b/resources/demos/steps.json new file mode 100644 index 0000000..93db983 --- /dev/null +++ b/resources/demos/steps.json @@ -0,0 +1,47 @@ +{ + "description": "Several tools between its reasoning: a long steps list.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "Can I afford to generate a banner this month?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Planning** — check the plan's image allowance first, then make the image." + }, + { + "type": "tool-about_my_account", + "toolCallId": "call-account", + "input": {}, + "state": "output-available", + "output": "{\"name\": \"Chef\", \"plan\": {\"name\": \"Pro\", \"limits\": {\"ai_chat_images\": 100}}, \"usage\": {\"ai_chat_images\": 12}}" + }, + { + "type": "reasoning", + "text": "**88 images left** — plenty. Now the banner itself." + }, + { + "type": "tool-generate_image", + "toolCallId": "call-banner", + "input": { + "prompt": "A wide banner of a calm sea" + }, + "state": "output-available", + "output": "{\"url\": \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj48cmVjdCB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgZmlsbD0iIzBjNGE2ZSIvPjxjaXJjbGUgY3g9IjI1NiIgY3k9IjIwMCIgcj0iOTAiIGZpbGw9IiNmZGU2OGEiLz48cmVjdCB5PSIzMzAiIHdpZHRoPSI1MTIiIGhlaWdodD0iMTgyIiBmaWxsPSIjMGY3NjZlIi8+PC9zdmc+\", \"prompt\": \"A wide banner of a calm sea\"}" + }, + { + "type": "text", + "text": "Yes: you have used 12 of your 100 images this month. Here is the banner." + } + ] + } + ] +} diff --git a/resources/demos/thinking.json b/resources/demos/thinking.json new file mode 100644 index 0000000..2401292 --- /dev/null +++ b/resources/demos/thinking.json @@ -0,0 +1,27 @@ +{ + "description": "A long thought before a short answer, as reasoning models give.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "How does the reply reach the page?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "reasoning", + "text": "**Reading the question** \u2014 they want the path a reply takes, end to end.\n\nThe page posts the message, and the server opens a stream before it has any words. Each chunk of the model's answer becomes a frame: text deltas, reasoning, tool calls and their results. The browser's chat state applies each frame to the last message, so the reply grows in place. Only once the stream has finished is the turn stored, which is why Stop lets the reply finish on the server.\n\n**Checking the edges** \u2014 a failed provider call ends on an error frame whose text is rewritten, so no key or account detail reaches the page. A reply that is asked again replaces the last turn only once the new one is stored. Long replies need more than the default thirty seconds of PHP time, so the stream raises it.\n\n**Shaping the answer** \u2014 short, the request and the stream, then where it is stored." + }, + { + "type": "text", + "text": "The page posts your message and the server streams the reply back frame by frame; the browser grows the message as frames arrive, and the turn is stored once the stream ends." + } + ] + } + ] +} diff --git a/resources/demos/tool_error.json b/resources/demos/tool_error.json new file mode 100644 index 0000000..c6efe51 --- /dev/null +++ b/resources/demos/tool_error.json @@ -0,0 +1,32 @@ +{ + "description": "A call to a tool that doesn't exist: that call fails, the reply goes on.", + "messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "text": "What's the weather in Lisbon?" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "tool-check_weather", + "toolCallId": "call-weather", + "input": { + "city": "Lisbon" + }, + "state": "output-error", + "errorText": "Tool 'check_weather' does not exist." + }, + { + "type": "text", + "text": "I can't check the weather from here. A weather site will have Lisbon's forecast." + } + ] + } + ] +} diff --git a/resources/js/lib/chatTools.ts b/resources/js/lib/chatTools.ts new file mode 100644 index 0000000..ecf4030 --- /dev/null +++ b/resources/js/lib/chatTools.ts @@ -0,0 +1,78 @@ +import type { WebMcpTool } from './webmcp'; + +/** What the tools need from the chat page, read when a tool runs, never captured. */ +export interface ChatToolsContext { + conversationId: () => string | null; + sessions: () => { id: string; title: string }[]; + messages: () => { role: string; text: string }[]; + /** Resolves once the reply has finished streaming. */ + send: (text: string) => Promise; + open: (id: string) => void; +} + +/** The chat page's WebMCP tools. Adding one is one more entry here. */ +export function chatTools(chat: ChatToolsContext): WebMcpTool[] { + return [ + { + name: 'ask_this_assistant', + description: + "Ask this site's assistant and wait for its full reply. It can read the user's account, search the web and create images.", + inputSchema: { + type: 'object', + properties: { message: { type: 'string', description: 'The question to put to the assistant.' } }, + required: ['message'], + }, + execute: async (args) => { + const text = String(args.message ?? '').trim(); + + if (!text) { + return 'A non-empty message is required.'; + } + + await chat.send(text); + + return { conversation_id: chat.conversationId(), reply: chat.messages().at(-1)?.text ?? '' }; + }, + }, + { + name: 'read_current_chat', + description: 'Transcript of the conversation on screen, most recent last.', + inputSchema: { + type: 'object', + properties: { limit: { type: 'integer', description: 'How many of the most recent messages to return. Default 20.' } }, + }, + readOnly: true, + execute: (args) => ({ + conversation_id: chat.conversationId(), + messages: chat.messages().slice(-Math.max(1, Number(args.limit) || 20)), + }), + }, + { + name: 'list_chat_sessions', + description: 'Saved conversations, newest first. Returns ids for open_chat_session.', + inputSchema: { type: 'object', properties: {} }, + readOnly: true, + execute: () => ({ current: chat.conversationId(), sessions: chat.sessions() }), + }, + { + name: 'open_chat_session', + description: 'Switch the page to a saved conversation. Ids come from list_chat_sessions.', + inputSchema: { + type: 'object', + properties: { session_id: { type: 'string', description: 'Id from list_chat_sessions.' } }, + required: ['session_id'], + }, + execute: (args) => { + const id = String(args.session_id); + + if (!chat.sessions().some((session) => session.id === id)) { + return `No such session: ${id}. Call list_chat_sessions first.`; + } + + chat.open(id); + + return `Opened session ${id}.`; + }, + }, + ]; +} diff --git a/resources/js/lib/dictation.test.ts b/resources/js/lib/dictation.test.ts new file mode 100644 index 0000000..f926c76 --- /dev/null +++ b/resources/js/lib/dictation.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { dictatedText, dictationProblem } from './dictation'; + +/** Speech results the way the browser hands them over: a list of results, each with its best alternative first. */ +const results = (...segments: string[]) => segments.map((transcript) => [{ transcript }]); + +describe('dictatedText', () => { + it('keeps every segment of the session, not only the latest', () => { + expect(dictatedText('', results('Plan a weekend', ' in Lisbon'))).toBe('Plan a weekend in Lisbon'); + }); + + it('adds to what was typed before, with one space between', () => { + expect(dictatedText('Hi.', results('Draw a cat'))).toBe('Hi. Draw a cat'); + }); + + it('leaves the typed text alone until something is heard', () => { + expect(dictatedText('Hi.', results())).toBe('Hi.'); + }); +}); + +describe('dictationProblem', () => { + it('stays quiet when the user stopped on purpose', () => { + expect(dictationProblem('aborted')).toBeNull(); + }); + + it('tells the user what to check when the browser heard nothing or was refused', () => { + expect(dictationProblem('no-speech')).toBe('No sound reached the browser. Check which microphone it uses, then try again.'); + expect(dictationProblem('audio-capture')).toBe('No sound reached the browser. Check which microphone it uses, then try again.'); + expect(dictationProblem('not-allowed')).toBe('Allow the microphone for this site, then try again.'); + }); + + it('passes any other error through', () => { + expect(dictationProblem('network')).toBe('network'); + }); +}); diff --git a/resources/js/lib/dictation.ts b/resources/js/lib/dictation.ts new file mode 100644 index 0000000..9a5cdea --- /dev/null +++ b/resources/js/lib/dictation.ts @@ -0,0 +1,35 @@ +/** + * The message box's text while dictating: what was typed before, then everything heard + * this session. Continuous recognition rewrites the whole utterance on every event, so + * it is rebuilt from all the results each time, interim ones included: they are what + * makes words appear while the user speaks. + */ +export function dictatedText(before: string, results: ArrayLike>): string { + let heard = ''; + + for (let i = 0; i < results.length; i++) { + heard += results[i][0]?.transcript ?? ''; + } + + heard = heard.trim(); + + return before && heard ? `${before} ${heard}` : before || heard; +} + +const SILENT = 'No sound reached the browser. Check which microphone it uses, then try again.'; + +/** + * What to tell the user when recognition fails, as a translation key, or null when + * nothing went wrong: stopping on purpose reports as 'aborted'. Silence ('no-speech') + * is reported too, since a wrong or muted input device looks exactly like that. + */ +export function dictationProblem(error: string): string | null { + const messages: Record = { + aborted: null, + 'no-speech': SILENT, + 'audio-capture': SILENT, + 'not-allowed': 'Allow the microphone for this site, then try again.', + }; + + return error in messages ? messages[error] : error; +} diff --git a/resources/js/lib/http.ts b/resources/js/lib/http.ts new file mode 100644 index 0000000..8c4cac0 --- /dev/null +++ b/resources/js/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/lib/sessions.test.ts b/resources/js/lib/sessions.test.ts new file mode 100644 index 0000000..7547ba4 --- /dev/null +++ b/resources/js/lib/sessions.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { groupSessions } from './sessions'; + +const now = new Date('2026-11-28T15:00:00'); +const at = (iso: string, id = iso) => ({ id, title: id, updated_at: iso }); + +describe('groupSessions', () => { + it('groups newest first under Today, Yesterday, Previous 7 days, Previous 30 days and Older', () => { + const groups = groupSessions( + [ + at('2026-11-28T09:00:00', 'today'), + at('2026-11-27T23:59:00', 'yesterday'), + at('2026-11-23T10:00:00', 'week'), + at('2026-11-05T10:00:00', 'month'), + at('2026-01-01T10:00:00', 'older'), + ], + now, + ); + + expect(groups.map((group) => [group.label, group.sessions.map((session) => session.id)])).toEqual([ + ['Today', ['today']], + ['Yesterday', ['yesterday']], + ['Previous 7 days', ['week']], + ['Previous 30 days', ['month']], + ['Older', ['older']], + ]); + }); + + it('leaves out empty groups and keeps the order it was given', () => { + const groups = groupSessions([at('2026-11-28T14:00:00', 'b'), at('2026-11-28T08:00:00', 'a')], now); + + expect(groups).toEqual([{ label: 'Today', sessions: [at('2026-11-28T14:00:00', 'b'), at('2026-11-28T08:00:00', 'a')] }]); + }); + + it('counts calendar days, not 24 hours', () => { + const lateNight = groupSessions([at('2026-11-27T22:00:00')], new Date('2026-11-28T01:00:00')); + + expect(lateNight[0].label).toBe('Yesterday'); + }); + + it('puts pinned chats first, under Pinned, whatever their age', () => { + const pinned = { ...at('2026-01-01T10:00:00', 'old-pinned'), pinned_at: '2026-11-28T10:00:00' }; + const groups = groupSessions([at('2026-11-28T09:00:00', 'today'), pinned], now); + + expect(groups.map((group) => [group.label, group.sessions.map((session) => session.id)])).toEqual([ + ['Pinned', ['old-pinned']], + ['Today', ['today']], + ]); + }); +}); diff --git a/resources/js/lib/sessions.ts b/resources/js/lib/sessions.ts new file mode 100644 index 0000000..a9fcfd2 --- /dev/null +++ b/resources/js/lib/sessions.ts @@ -0,0 +1,49 @@ +export interface Session { + id: string; + title: string; + updated_at: string; + pinned_at?: string | null; +} + +/** The shared `chat.sessions`: pinned chats and the newest others; `has_more` when older ones aren't listed. */ +export interface SessionList { + data: Session[]; + has_more: boolean; +} + +const GROUPS: { label: string; days: number }[] = [ + { label: 'Today', days: 0 }, + { label: 'Yesterday', days: 1 }, + { label: 'Previous 7 days', days: 7 }, + { label: 'Previous 30 days', days: 30 }, + { label: 'Older', days: Infinity }, +]; + +/** Whole calendar days between two dates, in the browser's time zone. */ +function daysBetween(from: Date, to: Date): number { + const midnight = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); + + return Math.round((midnight(to) - midnight(from)) / 86_400_000); +} + +/** + * The sidebar's chats under date headings, in the order given (newest first), empty headings left out. + * Pinned chats come first, under Pinned, whatever their age. + */ +export function groupSessions(sessions: Session[], now: Date = new Date()): { label: string; sessions: Session[] }[] { + const pinned = { label: 'Pinned', sessions: [] as Session[] }; + const groups = GROUPS.map((group) => ({ label: group.label, sessions: [] as Session[] })); + + for (const session of sessions) { + if (session.pinned_at) { + pinned.sessions.push(session); + continue; + } + + const age = daysBetween(new Date(session.updated_at), now); + + groups[GROUPS.findIndex((group) => age <= group.days)].sessions.push(session); + } + + return [pinned, ...groups].filter((group) => group.sessions.length > 0); +} diff --git a/resources/js/lib/tools.test.ts b/resources/js/lib/tools.test.ts new file mode 100644 index 0000000..e4ee794 --- /dev/null +++ b/resources/js/lib/tools.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it } from 'vitest'; +import sources from '../../demos/sources.json'; +import steps from '../../demos/steps.json'; +import toolError from '../../demos/tool_error.json'; +import { imagesIn, showsNothing, sourcesIn, stepsIn, toolLabel } from './tools'; + +/** A demo's reply: the parts of its last assistant message. */ +const reply = (demo: { messages: { role: string; parts: { type: string }[] }[] }) => + demo.messages.filter((message) => message.role === 'assistant').at(-1)!.parts; + +describe('imagesIn', () => { + it('reads finished generate_image results and skips the rest', () => { + const parts = [ + { + type: 'tool-generate_image', + state: 'output-available', + output: JSON.stringify({ url: '/a.png', prompt: 'A kite' }), + }, + { type: 'tool-generate_image', state: 'input-available' }, + { + type: 'tool-generate_image', + state: 'output-available', + output: 'No image was described, so none was generated.', + }, + { + type: 'tool-about_my_account', + state: 'output-available', + output: '{}', + }, + ]; + + expect(imagesIn(parts)).toEqual([{ url: '/a.png', prompt: 'A kite' }]); + }); +}); + +describe('toolLabel', () => { + it('falls back to the tool name', () => { + expect(toolLabel('generate_image', 'done')).toBe('Created an image'); + expect(toolLabel('web_search', 'running')).toBe('web search'); + }); +}); + +describe('stepsIn', () => { + it('lists a finished real tool call (input arrives as [] from PHP)', () => { + const parts = [ + { type: 'step-start' }, + { + type: 'tool-about_my_account', + toolCallId: 'fc_1', + state: 'output-available', + input: [], + output: '{"name":"Chef"}', + }, + { type: 'step-start' }, + { type: 'text', text: 'Your name is Chef.', state: 'done' }, + ]; + + expect(stepsIn(parts)).toEqual([ + { + kind: 'tool', + name: 'about_my_account', + state: 'done', + input: [], + output: '{"name":"Chef"}', + }, + ]); + }); + + it('keeps reasoning with text and drops empty reasoning', () => { + expect( + stepsIn([ + { type: 'reasoning', text: 'Thinking.' }, + { type: 'reasoning', text: ' ' }, + ]), + ).toEqual([{ kind: 'reasoning', text: 'Thinking.', streaming: false }]); + }); + + it('marks reasoning that is still streaming', () => { + expect(stepsIn([{ type: 'reasoning', text: 'Thinking', state: 'streaming' }])).toEqual([ + { kind: 'reasoning', text: 'Thinking', streaming: true }, + ]); + }); + + it('reads a multi-step reply in order, tools with their input and output', () => { + const list = stepsIn(reply(steps)); + + expect(list.map((step) => step.kind)).toEqual(['reasoning', 'tool', 'reasoning', 'tool']); + expect(list[3]).toMatchObject({ + kind: 'tool', + name: 'generate_image', + state: 'done', + input: { prompt: 'A wide banner of a calm sea' }, + }); + }); + + it('keeps a failed tool call with its error', () => { + expect(stepsIn(reply(toolError))[0]).toMatchObject({ + kind: 'tool', + name: 'check_weather', + state: 'failed', + error: "Tool 'check_weather' does not exist.", + }); + }); +}); + +describe('sourcesIn', () => { + it('lists the links a reply cited, once each', () => { + const parts = [...reply(sources), reply(sources)[1]]; + + expect(sourcesIn(parts)).toEqual([ + { + url: 'https://laravel.com/docs/13.x/releases', + title: 'Release Notes - Laravel 13.x', + }, + { + url: 'https://laravel.com/docs/13.x/upgrade', + title: 'Upgrade Guide - Laravel 13.x', + }, + { + url: 'https://laravel-news.com/laravel-13', + title: 'Laravel 13 is now released - Laravel News', + }, + ]); + }); + + it('names a link without a title by its host', () => { + expect(sourcesIn([{ type: 'source-url', url: 'https://www.example.com/a/b' }])).toEqual([ + { url: 'https://www.example.com/a/b', title: 'example.com' }, + ]); + }); +}); + +describe('showsNothing', () => { + it('is true until a part has something to show', () => { + expect(showsNothing([])).toBe(true); + expect(showsNothing([{ type: 'step-start' }])).toBe(true); + expect(showsNothing([{ type: 'step-start' }, { type: 'reasoning', text: '' }])).toBe(true); + expect(showsNothing([{ type: 'text', text: ' ' }])).toBe(true); + }); + + it('is false once a part shows', () => { + expect(showsNothing([{ type: 'step-start' }, { type: 'reasoning', text: 'Hmm' }])).toBe(false); + expect(showsNothing([{ type: 'tool-generate_image' }])).toBe(false); + expect(showsNothing([{ type: 'text', text: 'Hi' }])).toBe(false); + }); +}); diff --git a/resources/js/lib/tools.ts b/resources/js/lib/tools.ts new file mode 100644 index 0000000..0123403 --- /dev/null +++ b/resources/js/lib/tools.ts @@ -0,0 +1,143 @@ +/** + * 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 = { + about_my_account: { + running: 'Looking up your account', + done: 'Looked up your account', + failed: 'Could not read your account', + }, + generate_image: { + running: 'Creating an image', + done: 'Created an image', + failed: 'Could not create the image', + }, +}; + +export function toolLabel(name: string, state: 'running' | 'done' | 'failed'): string { + return TOOL_LABELS[name]?.[state] ?? name.replaceAll('_', ' '); +} + +export interface GeneratedImage { + url: string; + prompt: string; +} + +/** The images a reply generated, read from its generate_image results. */ +export function imagesIn(parts: { type: string; state?: string; output?: unknown }[]): GeneratedImage[] { + return parts.flatMap((part) => { + if (part.type !== 'tool-generate_image' || part.state !== 'output-available') { + return []; + } + + try { + const image = JSON.parse(String(part.output)) as Partial; + + return image.url ? [{ url: image.url, prompt: image.prompt ?? '' }] : []; + } catch { + // A prose answer ("No image was described…") is not an image. + return []; + } + }); +} + +export type Step = + | { kind: 'reasoning'; text: string; streaming: boolean } + | { + kind: 'tool'; + name: string; + state: 'running' | 'done' | 'failed'; + input?: unknown; + output?: unknown; + error?: string; + }; + +const STATES: Record = { + 'output-available': 'done', + 'output-error': 'failed', +}; + +type Part = { + type: string; + text?: string; + state?: string; + input?: unknown; + output?: unknown; + errorText?: string; +}; + +/** What a reply did before answering, in the order it streamed: reasoning and tool calls. */ +export function stepsIn(parts: Part[]): Step[] { + return parts.flatMap((part): Step[] => { + if (part.type === 'reasoning') { + return part.text?.trim() + ? [ + { + kind: 'reasoning', + text: part.text, + streaming: part.state === 'streaming', + }, + ] + : []; + } + + if (part.type.startsWith('tool-')) { + const step: Step = { + kind: 'tool', + name: part.type.slice(5), + state: STATES[part.state ?? ''] ?? 'running', + }; + + return [ + { + ...step, + ...('input' in part && { input: part.input }), + ...('output' in part && { output: part.output }), + ...(part.errorText !== undefined && { + error: part.errorText, + }), + }, + ]; + } + + return []; + }); +} + +export interface Source { + url: string; + title: string; +} + +/** The links a reply cited (web search), once each, in the order they came. */ +export function sourcesIn(parts: { type: string; url?: string; title?: string }[]): Source[] { + const seen = new Map(); + + for (const part of parts) { + if (part.type === 'source-url' && part.url && !seen.has(part.url)) { + seen.set(part.url, { + url: part.url, + title: part.title || hostOf(part.url), + }); + } + } + + return [...seen.values()]; +} + +function hostOf(url: string): string { + try { + return new URL(url).hostname.replace(/^www\./, ''); + } catch { + return url; + } +} + +/** + * A reply with nothing to show yet: the stream opens with an empty step and empty + * parts before the first words, and text and reasoning show nothing until then. + */ +export function showsNothing(parts: { type: string; text?: string }[]): boolean { + return !parts.some((part) => part.type !== 'step-start' && (part.text === undefined || part.text.trim() !== '')); +} diff --git a/resources/js/lib/usage.test.ts b/resources/js/lib/usage.test.ts new file mode 100644 index 0000000..4b1f703 --- /dev/null +++ b/resources/js/lib/usage.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { usageState } from './usage'; + +const usage = (used: number, limit = 50) => ({ used, limit, upgrade_url: '/pricing' }); + +describe('usageState', () => { + it('is hidden without a limit and below 80% of it', () => { + expect(usageState(null)).toBe('hidden'); + expect(usageState(usage(39))).toBe('hidden'); + }); + + it('counts from 80% of the limit', () => { + expect(usageState(usage(40))).toBe('counting'); + expect(usageState(usage(49))).toBe('counting'); + expect(usageState(usage(4, 5))).toBe('counting'); + }); + + it('is reached at the limit, and past it', () => { + expect(usageState(usage(50))).toBe('reached'); + expect(usageState(usage(51))).toBe('reached'); + }); +}); diff --git a/resources/js/lib/usage.ts b/resources/js/lib/usage.ts new file mode 100644 index 0000000..fe04946 --- /dev/null +++ b/resources/js/lib/usage.ts @@ -0,0 +1,22 @@ +/** This month's messages against the plan's limit; null when the plan sets none. */ +export interface Usage { + used: number; + limit: number; + /** Billing's plans page, when billing is installed. */ + upgrade_url: string | null; +} + +/** The counter shows from this share of the allowance: below it, it would only add pressure. */ +const SHOW_FROM = 0.8; + +export function usageState(usage: Usage | null): 'hidden' | 'counting' | 'reached' { + if (!usage) { + return 'hidden'; + } + + if (usage.used >= usage.limit) { + return 'reached'; + } + + return usage.used >= Math.ceil(usage.limit * SHOW_FROM) ? 'counting' : 'hidden'; +} diff --git a/resources/js/lib/webmcp.test.ts b/resources/js/lib/webmcp.test.ts new file mode 100644 index 0000000..46b1704 --- /dev/null +++ b/resources/js/lib/webmcp.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it, vi } from 'vitest'; +import { chatTools, type ChatToolsContext } from './chatTools'; +import { offeredTools, registerWebMcpTools, type WebMcpTool } from './webmcp'; + +function context(overrides: Partial = {}): ChatToolsContext { + return { + conversationId: () => 'c1', + sessions: () => [ + { id: 'c1', title: 'Launch email' }, + { id: 'c2', title: 'Queues' }, + ], + messages: () => [ + { role: 'user', text: 'one' }, + { role: 'assistant', text: 'two' }, + { role: 'user', text: 'three' }, + ], + send: vi.fn(async () => {}), + open: vi.fn(), + ...overrides, + }; +} + +function tool(ctx: ChatToolsContext, name: string): WebMcpTool { + const found = chatTools(ctx).find((candidate) => candidate.name === name); + + if (!found) { + throw new Error(`no tool ${name}`); + } + + return found; +} + +describe('chatTools', () => { + it('lists the sessions and which one is open', async () => { + const ctx = context(); + + expect(await tool(ctx, 'list_chat_sessions').execute({})).toEqual({ current: 'c1', sessions: ctx.sessions() }); + }); + + it('opens only a session the user has', async () => { + const ctx = context(); + + expect(await tool(ctx, 'open_chat_session').execute({ session_id: 'nope' })).toContain('No such session'); + expect(ctx.open).not.toHaveBeenCalled(); + + await tool(ctx, 'open_chat_session').execute({ session_id: 'c2' }); + expect(ctx.open).toHaveBeenCalledWith('c2'); + }); + + it('reads the most recent messages, up to the limit', async () => { + const result = (await tool(context(), 'read_current_chat').execute({ limit: 2 })) as { messages: unknown[] }; + + expect(result.messages).toEqual([ + { role: 'assistant', text: 'two' }, + { role: 'user', text: 'three' }, + ]); + }); + + it('asks the assistant and returns its reply', async () => { + const ctx = context({ messages: () => [{ role: 'assistant', text: 'Hello back' }] }); + + expect(await tool(ctx, 'ask_this_assistant').execute({ message: ' ' })).toContain('non-empty'); + expect(ctx.send).not.toHaveBeenCalled(); + + expect(await tool(ctx, 'ask_this_assistant').execute({ message: 'Hello' })).toEqual({ conversation_id: 'c1', reply: 'Hello back' }); + expect(ctx.send).toHaveBeenCalledWith('Hello'); + }); +}); + +describe('registerWebMcpTools', () => { + const tools = chatTools(context()); + + it('does nothing where the browser has no WebMCP', () => { + expect(() => registerWebMcpTools(tools, {})()).not.toThrow(); + }); + + it('lists what the page offers until withdrawn, with or without WebMCP, so the panel can show it', () => { + const withdraw = registerWebMcpTools(tools, {}); + + expect(offeredTools.value.map((offered) => offered.name)).toEqual(tools.map((offered) => offered.name)); + + withdraw(); + expect(offeredTools.value).toEqual([]); + }); + + it('registers every tool and withdraws them all together', () => { + const signals: AbortSignal[] = []; + const registerTool = vi.fn((_tool: unknown, options?: { signal?: AbortSignal }) => { + signals.push(options!.signal!); + + return Promise.resolve(); + }); + + const unregister = registerWebMcpTools(tools, { modelContext: { registerTool } }); + + expect(registerTool).toHaveBeenCalledTimes(tools.length); + expect(signals.every((signal) => !signal.aborted)).toBe(true); + + unregister(); + expect(signals.every((signal) => signal.aborted)).toBe(true); + }); + + it('wraps a plain result in the content the protocol expects', async () => { + let execute: ((args: Record) => Promise) | undefined; + const registerTool = vi.fn((definition: { execute: typeof execute }) => { + execute ??= definition.execute; + + return Promise.resolve(); + }); + + registerWebMcpTools([{ name: 't', description: 'd', inputSchema: { type: 'object' }, execute: () => ({ ok: true }) }], { + modelContext: { registerTool }, + }); + + expect(await execute!({})).toEqual({ content: [{ type: 'text', text: '{"ok":true}' }] }); + }); +}); diff --git a/resources/js/lib/webmcp.ts b/resources/js/lib/webmcp.ts new file mode 100644 index 0000000..48de0da --- /dev/null +++ b/resources/js/lib/webmcp.ts @@ -0,0 +1,88 @@ +/** + * WebMCP: tools the page offers the visitor's own browser agent. They run in + * the page, inside the user's session, so there are no tokens and no second + * auth surface. https://github.com/webmachinelearning/webmcp + */ +import { shallowRef } from 'vue'; + +export interface WebMcpTool { + name: string; + description: string; + inputSchema: { type: 'object'; properties?: Record; required?: string[] }; + readOnly?: boolean; + execute: (args: Record) => unknown; +} + +interface ModelContext { + registerTool( + tool: { + name: string; + description: string; + inputSchema: object; + annotations?: Record; + execute: (args: Record) => Promise; + }, + options?: { signal?: AbortSignal }, + ): Promise; +} + +/** What the open page offers, listed by the WebMCP panel even where the browser can't call it yet. */ +export const offeredTools = shallowRef([]); + +/** Whether this browser can hand the tools to an agent. */ +export const webMcpSupported = typeof document !== 'undefined' && 'modelContext' in document; + +/** The protocol wants `{ content: [...] }`; tools return plain values. */ +function toContent(result: unknown): unknown { + if (result && typeof result === 'object' && 'content' in result) { + return result; + } + + return { content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result ?? null) }] }; +} + +/** + * Offer the tools until the returned function is called. A browser without + * WebMCP gets nothing. Chrome has no unregister: aborting the signal a tool + * was registered with is how it is withdrawn. + */ +export function registerWebMcpTools( + tools: WebMcpTool[], + target: { modelContext?: ModelContext } = globalThis.document as { modelContext?: ModelContext }, +): () => void { + const context = target?.modelContext; + + offeredTools.value = [...offeredTools.value, ...tools]; + const withdraw = () => (offeredTools.value = offeredTools.value.filter((offered) => !tools.includes(offered))); + + if (!context) { + return withdraw; + } + + const controller = new AbortController(); + + for (const tool of tools) { + context + .registerTool( + { + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + annotations: { readOnlyHint: tool.readOnly === true }, + execute: async (args) => toContent(await tool.execute(args ?? {})), + }, + { signal: controller.signal }, + ) + // Aborting rejects the registration: that is the withdrawal, not a failure. + .catch((error: Error) => { + if (error?.name !== 'AbortError') { + console.error(`WebMCP: failed to register "${tool.name}"`, error); + } + }); + } + + return () => { + controller.abort(); + withdraw(); + }; +} 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/resources/js/vue/app.ts b/resources/js/vue/app.ts index f371333..e9cbbcc 100644 --- a/resources/js/vue/app.ts +++ b/resources/js/vue/app.ts @@ -1,25 +1,30 @@ -// import { registerIcon } from '@/lib/navigation'; -// import IconExample from '~icons/lucide/example'; +import { usePage } from '@inertiajs/vue3'; +import { registerGlobalComponent } from '@saucebase/vue/lib/globalComponents'; +import { registerIcon } from '@saucebase/vue/lib/navigation'; +import { type Component, defineComponent, h } from 'vue'; +import IconChat from '~icons/heroicons/chat-bubble-left-right'; +import ChatSessions from './components/ChatSessions.vue'; +import WebMcpMenuItem from './components/WebMcpMenuItem.vue'; -// Custom styles: create resources/css/style.css in this module and uncomment. -// import '@modules/aichat/resources/css/style.css'; +/** Only while the list lives in the app sidebar (`ai-chat.sessions` = sidebar); else the chat's own panel holds it. */ +function inAppSidebar(component: Component): Component { + return defineComponent({ + setup() { + const page = usePage(); -/** - * 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); + return () => ((page.props.chat as { sessions_in?: string } | undefined)?.sessions_in === 'sidebar' ? h(component) : null); + }, + }); } /** - * AiChat module after mount logic - * Called in the browser after the app has mounted + * Called before the first render, on the server too. */ -export function afterMount() { - console.debug('AiChat module after mount logic executed'); +export function setup() { + // The "Chat" item (routes/navigation.php), with the list on the chat page. + registerIcon('chat', IconChat); + // New chat and the history, in the app sidebar between the nav and the bottom links. + registerGlobalComponent('dashboard::sidebar.content', inAppSidebar(ChatSessions)); + // What the visitor's browser agent can do here, while a page offers WebMCP tools. + registerGlobalComponent('dashboard::sidebar.end', inAppSidebar(WebMcpMenuItem)); } diff --git a/resources/js/vue/components/ChatArtifact.vue b/resources/js/vue/components/ChatArtifact.vue new file mode 100644 index 0000000..05c19b7 --- /dev/null +++ b/resources/js/vue/components/ChatArtifact.vue @@ -0,0 +1,73 @@ + + + diff --git a/resources/js/vue/components/ChatCodeBlock.vue b/resources/js/vue/components/ChatCodeBlock.vue new file mode 100644 index 0000000..f8b4740 --- /dev/null +++ b/resources/js/vue/components/ChatCodeBlock.vue @@ -0,0 +1,60 @@ + + + diff --git a/resources/js/vue/components/ChatImage.vue b/resources/js/vue/components/ChatImage.vue new file mode 100644 index 0000000..a7a1aea --- /dev/null +++ b/resources/js/vue/components/ChatImage.vue @@ -0,0 +1,44 @@ + + + diff --git a/resources/js/vue/components/ChatInput.vue b/resources/js/vue/components/ChatInput.vue new file mode 100644 index 0000000..7c7c0ad --- /dev/null +++ b/resources/js/vue/components/ChatInput.vue @@ -0,0 +1,137 @@ + + + diff --git a/resources/js/vue/components/ChatInputBar.vue b/resources/js/vue/components/ChatInputBar.vue new file mode 100644 index 0000000..1415cd0 --- /dev/null +++ b/resources/js/vue/components/ChatInputBar.vue @@ -0,0 +1,44 @@ + + + diff --git a/resources/js/vue/components/ChatMarkdown.vue b/resources/js/vue/components/ChatMarkdown.vue new file mode 100644 index 0000000..5f840c2 --- /dev/null +++ b/resources/js/vue/components/ChatMarkdown.vue @@ -0,0 +1,24 @@ + + + + + diff --git a/resources/js/vue/components/ChatMessage.vue b/resources/js/vue/components/ChatMessage.vue new file mode 100644 index 0000000..6fdede6 --- /dev/null +++ b/resources/js/vue/components/ChatMessage.vue @@ -0,0 +1,74 @@ + + + diff --git a/resources/js/vue/components/ChatPanel.vue b/resources/js/vue/components/ChatPanel.vue new file mode 100644 index 0000000..d8db14e --- /dev/null +++ b/resources/js/vue/components/ChatPanel.vue @@ -0,0 +1,42 @@ + + + diff --git a/resources/js/vue/components/ChatScrollButton.vue b/resources/js/vue/components/ChatScrollButton.vue new file mode 100644 index 0000000..dbb5bc3 --- /dev/null +++ b/resources/js/vue/components/ChatScrollButton.vue @@ -0,0 +1,72 @@ + + + + + diff --git a/resources/js/vue/components/ChatSessions.vue b/resources/js/vue/components/ChatSessions.vue new file mode 100644 index 0000000..30a0be6 --- /dev/null +++ b/resources/js/vue/components/ChatSessions.vue @@ -0,0 +1,286 @@ + + + diff --git a/resources/js/vue/components/ChatSources.vue b/resources/js/vue/components/ChatSources.vue new file mode 100644 index 0000000..557efd7 --- /dev/null +++ b/resources/js/vue/components/ChatSources.vue @@ -0,0 +1,37 @@ + + + diff --git a/resources/js/vue/components/ChatSteps.vue b/resources/js/vue/components/ChatSteps.vue new file mode 100644 index 0000000..0cd4656 --- /dev/null +++ b/resources/js/vue/components/ChatSteps.vue @@ -0,0 +1,91 @@ + + + diff --git a/resources/js/vue/components/ChatUsageBar.vue b/resources/js/vue/components/ChatUsageBar.vue new file mode 100644 index 0000000..249d8ba --- /dev/null +++ b/resources/js/vue/components/ChatUsageBar.vue @@ -0,0 +1,50 @@ + + + diff --git a/resources/js/vue/components/WebMcpMenuItem.vue b/resources/js/vue/components/WebMcpMenuItem.vue new file mode 100644 index 0000000..41bcb3f --- /dev/null +++ b/resources/js/vue/components/WebMcpMenuItem.vue @@ -0,0 +1,132 @@ + + + diff --git a/resources/js/vue/components/artifact.ts b/resources/js/vue/components/artifact.ts new file mode 100644 index 0000000..0260b2b --- /dev/null +++ b/resources/js/vue/components/artifact.ts @@ -0,0 +1,10 @@ +import type { InjectionKey } from 'vue'; + +/** A piece of a reply opened on its own, beside the chat: a long code block or an image. */ +export type Artifact = { kind: 'code'; title: string; language: string; code: string } | { kind: 'image'; title: string; url: string }; + +/** Provided by the chat page; replies call it to open an artifact in the side panel. */ +export const openArtifactKey: InjectionKey<(artifact: Artifact) => void> = Symbol('openArtifact'); + +/** Code at least this long is worth a panel of its own. */ +export const ARTIFACT_MIN_LINES = 15; diff --git a/resources/js/vue/components/ui/bubble/Bubble.vue b/resources/js/vue/components/ui/bubble/Bubble.vue new file mode 100644 index 0000000..d85d670 --- /dev/null +++ b/resources/js/vue/components/ui/bubble/Bubble.vue @@ -0,0 +1,33 @@ + + + diff --git a/resources/js/vue/components/ui/bubble/BubbleContent.vue b/resources/js/vue/components/ui/bubble/BubbleContent.vue new file mode 100644 index 0000000..05b5089 --- /dev/null +++ b/resources/js/vue/components/ui/bubble/BubbleContent.vue @@ -0,0 +1,30 @@ + + + diff --git a/resources/js/vue/components/ui/bubble/BubbleGroup.vue b/resources/js/vue/components/ui/bubble/BubbleGroup.vue new file mode 100644 index 0000000..81e8247 --- /dev/null +++ b/resources/js/vue/components/ui/bubble/BubbleGroup.vue @@ -0,0 +1,20 @@ + + + diff --git a/resources/js/vue/components/ui/bubble/BubbleReactions.vue b/resources/js/vue/components/ui/bubble/BubbleReactions.vue new file mode 100644 index 0000000..86b33f9 --- /dev/null +++ b/resources/js/vue/components/ui/bubble/BubbleReactions.vue @@ -0,0 +1,33 @@ + + + diff --git a/resources/js/vue/components/ui/bubble/index.ts b/resources/js/vue/components/ui/bubble/index.ts new file mode 100644 index 0000000..6566c57 --- /dev/null +++ b/resources/js/vue/components/ui/bubble/index.ts @@ -0,0 +1,53 @@ +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; + +export { default as Bubble } from './Bubble.vue'; +export { default as BubbleContent } from './BubbleContent.vue'; +export { default as BubbleGroup } from './BubbleGroup.vue'; +export { default as BubbleReactions } from './BubbleReactions.vue'; + +export const bubbleVariants = cva( + 'gap-1 data-[align=end]:self-end max-w-[80%] data-[variant=ghost]:max-w-full group-data-[align=end]/message:self-end group/bubble relative flex w-fit min-w-0 flex-col', + { + variants: { + variant: { + default: + '*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80', + secondary: + '*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]', + muted: '*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]', + tinted: '*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] *:data-[slot=bubble-content]:text-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]', + outline: + '*:data-[slot=bubble-content]:bg-background *:data-[slot=bubble-content]:border-border [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30', + ghost: '*:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50 border-none', + destructive: + '*:data-[slot=bubble-content]:bg-destructive/10 dark:*:data-[slot=bubble-content]:bg-destructive/20 *:data-[slot=bubble-content]:text-destructive [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30', + }, + }, + defaultVariants: { + variant: 'default', + }, + }, +); +export type BubbleVariants = VariantProps; + +export const bubbleReactionsVariants = cva( + 'rounded-full ring-3 ring-card bg-muted shrink-0 gap-1 px-1.5 py-0.5 has-[button]:p-0 text-sm absolute z-10 flex w-fit items-center justify-center', + { + variants: { + side: { + top: 'top-0 -translate-y-3/4', + bottom: 'bottom-0 translate-y-3/4', + }, + align: { + start: 'left-3', + end: 'right-3', + }, + }, + defaultVariants: { + side: 'bottom', + align: 'end', + }, + }, +); +export type BubbleReactionsVariants = VariantProps; diff --git a/resources/js/vue/components/ui/button/Button.vue b/resources/js/vue/components/ui/button/Button.vue new file mode 100644 index 0000000..d9e3520 --- /dev/null +++ b/resources/js/vue/components/ui/button/Button.vue @@ -0,0 +1,31 @@ + + + diff --git a/resources/js/vue/components/ui/button/index.ts b/resources/js/vue/components/ui/button/index.ts new file mode 100644 index 0000000..30ede54 --- /dev/null +++ b/resources/js/vue/components/ui/button/index.ts @@ -0,0 +1,37 @@ +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; + +export { default as Button } from './Button.vue'; + +export const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground hover:bg-primary/90', + destructive: + 'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60', + outline: + 'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50', + secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80', + ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50', + link: 'text-primary underline-offset-4 hover:underline', + }, + size: { + default: 'h-9 px-4 py-2 has-[>svg]:px-3', + xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5', + lg: 'h-10 rounded-md px-6 has-[>svg]:px-4', + icon: 'size-9', + 'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", + 'icon-sm': 'size-8', + 'icon-lg': 'size-10', + }, + }, + defaultVariants: { + variant: 'default', + size: 'default', + }, + }, +); +export type ButtonVariants = VariantProps; diff --git a/resources/js/vue/components/ui/code-block/CodeBlock.vue b/resources/js/vue/components/ui/code-block/CodeBlock.vue new file mode 100644 index 0000000..67829ca --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlock.vue @@ -0,0 +1,24 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockActions.vue b/resources/js/vue/components/ui/code-block/CodeBlockActions.vue new file mode 100644 index 0000000..bfb683c --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockActions.vue @@ -0,0 +1,22 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockContent.vue b/resources/js/vue/components/ui/code-block/CodeBlockContent.vue new file mode 100644 index 0000000..e45c2fc --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockContent.vue @@ -0,0 +1,80 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockCopyButton.vue b/resources/js/vue/components/ui/code-block/CodeBlockCopyButton.vue new file mode 100644 index 0000000..5d8c815 --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockCopyButton.vue @@ -0,0 +1,49 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockFooter.vue b/resources/js/vue/components/ui/code-block/CodeBlockFooter.vue new file mode 100644 index 0000000..753699a --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockFooter.vue @@ -0,0 +1,22 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockHeader.vue b/resources/js/vue/components/ui/code-block/CodeBlockHeader.vue new file mode 100644 index 0000000..632c886 --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockHeader.vue @@ -0,0 +1,22 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockLine.vue b/resources/js/vue/components/ui/code-block/CodeBlockLine.vue new file mode 100644 index 0000000..490fa61 --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockLine.vue @@ -0,0 +1,41 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockTitle.vue b/resources/js/vue/components/ui/code-block/CodeBlockTitle.vue new file mode 100644 index 0000000..f00b152 --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockTitle.vue @@ -0,0 +1,22 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/CodeBlockToken.vue b/resources/js/vue/components/ui/code-block/CodeBlockToken.vue new file mode 100644 index 0000000..9abd347 --- /dev/null +++ b/resources/js/vue/components/ui/code-block/CodeBlockToken.vue @@ -0,0 +1,11 @@ + + + diff --git a/resources/js/vue/components/ui/code-block/highlighter.ts b/resources/js/vue/components/ui/code-block/highlighter.ts new file mode 100644 index 0000000..1ed7ba2 --- /dev/null +++ b/resources/js/vue/components/ui/code-block/highlighter.ts @@ -0,0 +1,110 @@ +import type { GrammarState, HighlighterCore } from 'shiki/core'; +import { createHighlighterCore } from 'shiki/core'; +import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'; + +export interface HighlightedToken { + content: string; + htmlStyle?: Record; +} + +// Add the languages you need. Each one loads the first time it is used. +const languages = { + bash: () => import('shiki/langs/shellscript.mjs'), + css: () => import('shiki/langs/css.mjs'), + diff: () => import('shiki/langs/diff.mjs'), + html: () => import('shiki/langs/html.mjs'), + javascript: () => import('shiki/langs/javascript.mjs'), + json: () => import('shiki/langs/json.mjs'), + jsx: () => import('shiki/langs/jsx.mjs'), + markdown: () => import('shiki/langs/markdown.mjs'), + php: () => import('shiki/langs/php.mjs'), + python: () => import('shiki/langs/python.mjs'), + sql: () => import('shiki/langs/sql.mjs'), + tsx: () => import('shiki/langs/tsx.mjs'), + typescript: () => import('shiki/langs/typescript.mjs'), + vue: () => import('shiki/langs/vue.mjs'), + yaml: () => import('shiki/langs/yaml.mjs'), +}; + +const aliases: Record = { + js: 'javascript', + md: 'markdown', + py: 'python', + sh: 'bash', + shell: 'bash', + shellscript: 'bash', + ts: 'typescript', + yml: 'yaml', + zsh: 'bash', +}; + +let highlighter: Promise | undefined; + +function getHighlighter() { + highlighter ??= createHighlighterCore({ + themes: [import('shiki/themes/github-light.mjs'), import('shiki/themes/github-dark.mjs')], + langs: [], + engine: createJavaScriptRegexEngine({ forgiving: true }), + }); + + return highlighter; +} + +function getLanguage(language: string) { + const name = language.toLowerCase(); + + if (name === 'ansi') return name; + + if (name in languages) return name as keyof typeof languages; + + return aliases[name] ?? null; +} + +// Loads a language and returns a highlighter for it, or null for a language +// that is not listed. +export async function loadHighlighter(language: string) { + const lang = getLanguage(language); + + if (!lang) return null; + + const shiki = await getHighlighter(); + + if (lang !== 'ansi' && !shiki.getLoadedLanguages().includes(lang)) await shiki.loadLanguage(languages[lang]); + + return { + // Returns the tokens of each line, and the grammar state after the last + // line. Pass that state back to continue where the code left off. + highlight(code: string, state?: GrammarState) { + const tokenize = (text: string) => + shiki.codeToTokens(text, { + lang, + themes: { light: 'github-light', dark: 'github-dark' }, + defaultColor: false, + grammarState: state, + }).tokens; + + // ANSI has no grammar state, so each line is tokenized on its own and + // gets the same colors whether it arrives in one piece or streams. + const tokens = lang === 'ansi' ? code.split('\n').flatMap((line) => tokenize(line)) : tokenize(code); + + return { + lines: tokens.map((line) => + line.map((token): HighlightedToken => ({ + content: token.content, + htmlStyle: token.htmlStyle as Record | undefined, + })), + ), + state: shiki.getLastGrammarState(tokens), + }; + }, + }; +} + +export type Highlighter = NonNullable>>; + +// Returns the tokens of each line, or null for a language that is not listed. +export async function highlightCode(code: string, language: string) { + const highlighter = await loadHighlighter(language); + + return highlighter ? highlighter.highlight(code).lines : null; +} diff --git a/resources/js/vue/components/ui/code-block/index.ts b/resources/js/vue/components/ui/code-block/index.ts new file mode 100644 index 0000000..b2f991f --- /dev/null +++ b/resources/js/vue/components/ui/code-block/index.ts @@ -0,0 +1,50 @@ +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; + +export { default as CodeBlock } from './CodeBlock.vue'; +export { default as CodeBlockActions } from './CodeBlockActions.vue'; +export { default as CodeBlockContent } from './CodeBlockContent.vue'; +export { default as CodeBlockCopyButton } from './CodeBlockCopyButton.vue'; +export { default as CodeBlockFooter } from './CodeBlockFooter.vue'; +export { default as CodeBlockHeader } from './CodeBlockHeader.vue'; +export { default as CodeBlockLine } from './CodeBlockLine.vue'; +export { default as CodeBlockTitle } from './CodeBlockTitle.vue'; +export { default as CodeBlockToken } from './CodeBlockToken.vue'; +export { highlightCode, loadHighlighter } from './highlighter'; +export type { HighlightedToken } from './highlighter'; +export { useHighlightedCode } from './useHighlightedCode'; + +export const codeBlockVariants = cva( + 'rounded-lg text-sm data-[size=sm]:text-xs has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 group/code-block relative flex w-full min-w-0 flex-col overflow-hidden', + { + variants: { + variant: { + default: + 'border border-input text-foreground dark:bg-input/30 has-[>[data-slot=code-block-content]:focus-visible]:border-ring', + destructive: 'border border-destructive/30 text-destructive dark:border-destructive/40', + }, + }, + defaultVariants: { + variant: 'default', + }, + }, +); +export type CodeBlockVariants = VariantProps; + +export const codeBlockLineVariants = cva( + "-mx-3 px-3 in-data-numbered:gap-x-3 before:min-w-6 before:text-end before:text-muted-foreground after:start-1 after:text-muted-foreground group-data-[size=sm]/code-block:-mx-2.5 group-data-[size=sm]/code-block:px-2.5 relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']", + { + variants: { + variant: { + default: '', + added: "bg-muted after:content-['+']", + removed: "bg-destructive/10 after:text-destructive after:content-['−']", + highlighted: 'bg-muted', + }, + }, + defaultVariants: { + variant: 'default', + }, + }, +); +export type CodeBlockLineVariants = VariantProps; diff --git a/resources/js/vue/components/ui/code-block/useHighlightedCode.ts b/resources/js/vue/components/ui/code-block/useHighlightedCode.ts new file mode 100644 index 0000000..a2fccca --- /dev/null +++ b/resources/js/vue/components/ui/code-block/useHighlightedCode.ts @@ -0,0 +1,66 @@ +import type { GrammarState } from 'shiki/core'; +import type { MaybeRefOrGetter } from 'vue'; +import { computed, shallowRef, toValue, watch } from 'vue'; +import type { HighlightedToken, Highlighter } from './highlighter'; +import { loadHighlighter } from './highlighter'; + +export function useHighlightedCode(value: MaybeRefOrGetter, language: MaybeRefOrGetter) { + const highlighter = shallowRef(null); + + watch( + () => toValue(language), + (lang, _, onCleanup) => { + // Highlighting runs in the browser. The server renders the plain lines. + if (typeof window === 'undefined') return; + + let cancelled = false; + onCleanup(() => (cancelled = true)); + highlighter.value = null; + + loadHighlighter(lang) + .then((next) => { + if (!cancelled) highlighter.value = next; + }) + .catch(() => {}); + }, + { immediate: true }, + ); + + // The complete lines, highlighted. While the code streams, only the new + // lines are tokenized, starting from the grammar state of the last one. + let done: { + highlighter: Highlighter | null; + text: string; + lines: HighlightedToken[][]; + state?: GrammarState; + } = { highlighter: null, text: '', lines: [] }; + + return computed(() => { + const raw = toValue(value); + // A trailing newline would render as an extra empty line. + const code = raw.endsWith('\n') ? raw.slice(0, -1) : raw; + const current = highlighter.value; + + if (!current) return code.split('\n').map((line) => (line ? [{ content: line }] : [])); + + if (done.highlighter !== current || !code.startsWith(done.text)) done = { highlighter: current, text: '', lines: [] }; + + const end = code.lastIndexOf('\n') + 1; + + if (end > done.text.length) { + const result = current.highlight(code.slice(done.text.length, end - 1), done.state); + + done = { + highlighter: current, + text: code.slice(0, end), + lines: [...done.lines, ...result.lines], + state: result.state, + }; + } + + // The last line is still being written, so it is tokenized on every change. + const tail = current.highlight(code.slice(end), done.state).lines[0] ?? []; + + return [...done.lines, tail]; + }); +} diff --git a/resources/js/vue/components/ui/hover-card/HoverCard.vue b/resources/js/vue/components/ui/hover-card/HoverCard.vue new file mode 100644 index 0000000..d78afa0 --- /dev/null +++ b/resources/js/vue/components/ui/hover-card/HoverCard.vue @@ -0,0 +1,15 @@ + + + diff --git a/resources/js/vue/components/ui/hover-card/HoverCardContent.vue b/resources/js/vue/components/ui/hover-card/HoverCardContent.vue new file mode 100644 index 0000000..bcc6049 --- /dev/null +++ b/resources/js/vue/components/ui/hover-card/HoverCardContent.vue @@ -0,0 +1,36 @@ + + + diff --git a/resources/js/vue/components/ui/hover-card/HoverCardTrigger.vue b/resources/js/vue/components/ui/hover-card/HoverCardTrigger.vue new file mode 100644 index 0000000..c319cfa --- /dev/null +++ b/resources/js/vue/components/ui/hover-card/HoverCardTrigger.vue @@ -0,0 +1,12 @@ + + + diff --git a/resources/js/vue/components/ui/hover-card/index.ts b/resources/js/vue/components/ui/hover-card/index.ts new file mode 100644 index 0000000..dd4a1ef --- /dev/null +++ b/resources/js/vue/components/ui/hover-card/index.ts @@ -0,0 +1,3 @@ +export { default as HoverCard } from './HoverCard.vue'; +export { default as HoverCardContent } from './HoverCardContent.vue'; +export { default as HoverCardTrigger } from './HoverCardTrigger.vue'; diff --git a/resources/js/vue/components/ui/message-scroller/MessageScroller.vue b/resources/js/vue/components/ui/message-scroller/MessageScroller.vue new file mode 100644 index 0000000..8ba9e2c --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/MessageScroller.vue @@ -0,0 +1,22 @@ + + + diff --git a/resources/js/vue/components/ui/message-scroller/MessageScrollerButton.vue b/resources/js/vue/components/ui/message-scroller/MessageScrollerButton.vue new file mode 100644 index 0000000..593ae70 --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/MessageScrollerButton.vue @@ -0,0 +1,64 @@ + + + diff --git a/resources/js/vue/components/ui/message-scroller/MessageScrollerContent.vue b/resources/js/vue/components/ui/message-scroller/MessageScrollerContent.vue new file mode 100644 index 0000000..fafe2fb --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/MessageScrollerContent.vue @@ -0,0 +1,65 @@ + + + diff --git a/resources/js/vue/components/ui/message-scroller/MessageScrollerItem.vue b/resources/js/vue/components/ui/message-scroller/MessageScrollerItem.vue new file mode 100644 index 0000000..c156447 --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/MessageScrollerItem.vue @@ -0,0 +1,51 @@ + + + diff --git a/resources/js/vue/components/ui/message-scroller/MessageScrollerProvider.vue b/resources/js/vue/components/ui/message-scroller/MessageScrollerProvider.vue new file mode 100644 index 0000000..7e3330d --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/MessageScrollerProvider.vue @@ -0,0 +1,12 @@ + + + diff --git a/resources/js/vue/components/ui/message-scroller/MessageScrollerViewport.vue b/resources/js/vue/components/ui/message-scroller/MessageScrollerViewport.vue new file mode 100644 index 0000000..f46d285 --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/MessageScrollerViewport.vue @@ -0,0 +1,72 @@ + + + diff --git a/resources/js/vue/components/ui/message-scroller/index.ts b/resources/js/vue/components/ui/message-scroller/index.ts new file mode 100644 index 0000000..9f052c1 --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/index.ts @@ -0,0 +1,18 @@ +export { default as MessageScroller } from './MessageScroller.vue'; +export { default as MessageScrollerButton } from './MessageScrollerButton.vue'; +export { default as MessageScrollerContent } from './MessageScrollerContent.vue'; +export { default as MessageScrollerItem } from './MessageScrollerItem.vue'; +export { default as MessageScrollerProvider } from './MessageScrollerProvider.vue'; +export { default as MessageScrollerViewport } from './MessageScrollerViewport.vue'; + +export type { + MessageScrollerButtonDirection, + MessageScrollerDefaultScrollPosition, + MessageScrollerProviderProps, + MessageScrollerScrollAlign, + MessageScrollerScrollOptions, + MessageScrollerScrollable, + MessageScrollerVisibilityState, +} from './useMessageScroller'; + +export { useMessageScroller, useMessageScrollerScrollable, useMessageScrollerVisibility } from './useMessageScroller'; diff --git a/resources/js/vue/components/ui/message-scroller/useMessageScroller.ts b/resources/js/vue/components/ui/message-scroller/useMessageScroller.ts new file mode 100644 index 0000000..a0b2f41 --- /dev/null +++ b/resources/js/vue/components/ui/message-scroller/useMessageScroller.ts @@ -0,0 +1,925 @@ +import type { ComputedRef, InjectionKey, Ref, ShallowRef } from 'vue'; +import { computed, getCurrentScope, inject, onMounted, onScopeDispose, provide, shallowRef, watch } from 'vue'; + +// ----------------------------------------------------------------------------- +// Public types +// ----------------------------------------------------------------------------- + +export type MessageScrollerDefaultScrollPosition = 'start' | 'end' | 'last-anchor'; +export type MessageScrollerButtonDirection = 'start' | 'end'; +export type MessageScrollerScrollAlign = 'start' | 'center' | 'end' | 'nearest'; + +export interface MessageScrollerScrollOptions { + align?: MessageScrollerScrollAlign; + behavior?: ScrollBehavior; + scrollMargin?: number; +} + +export interface MessageScrollerScrollable { + start: boolean; + end: boolean; +} + +export interface MessageScrollerVisibilityState { + currentAnchorId: string | null; + visibleMessageIds: string[]; +} + +export interface MessageScrollerProviderProps { + autoScroll?: boolean; + defaultScrollPosition?: MessageScrollerDefaultScrollPosition; + scrollEdgeThreshold?: number; + scrollPreviousItemPeek?: number; + scrollMargin?: number; +} + +// ----------------------------------------------------------------------------- +// Constants +// ----------------------------------------------------------------------------- + +const DEFAULT_SCROLL_EDGE_THRESHOLD = 8; +const DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK = 64; +const DEFAULT_SCROLL_MARGIN = 0; +const SCROLL_EPSILON = 0.5; +const AUTOSCROLLING_TIMEOUT = 180; + +const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']); + +const EMPTY_SCROLLABLE: MessageScrollerScrollable = { start: false, end: false }; +const EMPTY_VISIBLE_IDS: string[] = []; +const EMPTY_VISIBILITY: MessageScrollerVisibilityState = { + currentAnchorId: null, + visibleMessageIds: EMPTY_VISIBLE_IDS, +}; + +type Mode = 'following-bottom' | 'free-scrolling' | 'anchored-to-message' | 'settling-jump'; + +interface PrependRestore { + element: HTMLElement; + viewportTop: number; +} + +interface PendingScrollToMessage { + messageId: string; + options?: MessageScrollerScrollOptions; +} + +function scrollableEqual(a: MessageScrollerScrollable, b: MessageScrollerScrollable) { + return a.start === b.start && a.end === b.end; +} + +function visibilityEqual(a: MessageScrollerVisibilityState, b: MessageScrollerVisibilityState) { + if (a.currentAnchorId !== b.currentAnchorId || a.visibleMessageIds.length !== b.visibleMessageIds.length) { + return false; + } + return a.visibleMessageIds.every((id, index) => id === b.visibleMessageIds[index]); +} + +// ----------------------------------------------------------------------------- +// DOM measurement helpers +// ----------------------------------------------------------------------------- + +function parseNumber(value: string | null | undefined): number { + if (!value) return 0; + const parsed = Number.parseFloat(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function getPadding(element: HTMLElement): { start: number; end: number } { + const style = window.getComputedStyle(element); + return { + end: parseNumber(style.paddingBlockEnd || style.paddingBottom), + start: parseNumber(style.paddingBlockStart || style.paddingTop), + }; +} + +function getContentPadding(spacer: HTMLElement | null): { start: number; end: number } { + const parent = spacer?.parentElement; + return parent ? getPadding(parent) : { end: 0, start: 0 }; +} + +function getRowGap(element: HTMLElement | null): number { + if (!element) return 0; + const style = window.getComputedStyle(element); + const gap = style.rowGap === 'normal' ? style.gap : style.rowGap; + return parseNumber(gap); +} + +function getMessageChildren(content: HTMLElement, spacer: HTMLElement | null): HTMLElement[] { + return Array.from(content.children).filter((child): child is HTMLElement => child instanceof HTMLElement && child !== spacer); +} + +function getElementOffsetTop(element: HTMLElement, viewport: HTMLElement): number { + const elementRect = element.getBoundingClientRect(); + const viewportRect = viewport.getBoundingClientRect(); + return elementRect.top - viewportRect.top + viewport.scrollTop; +} + +function getRelativeTop(element: HTMLElement, viewport: HTMLElement): number { + return element.getBoundingClientRect().top - viewport.getBoundingClientRect().top; +} + +function measureContentHeight({ + content, + spacer, + viewport, +}: { + content: HTMLElement; + spacer: HTMLElement | null; + viewport: HTMLElement; +}): number { + const children = getMessageChildren(content, spacer); + const padding = getPadding(content); + const viewportRect = viewport.getBoundingClientRect(); + const scrollTop = viewport.scrollTop; + let height = padding.start + padding.end; + for (const child of children) { + const rect = child.getBoundingClientRect(); + height = Math.max(height, rect.bottom - viewportRect.top + scrollTop + padding.end); + } + return height; +} + +function maxScrollTop(element: HTMLElement): number { + return Math.max(0, element.scrollHeight - element.clientHeight); +} + +function computeSpacerHeight({ + content, + scrollTop, + spacer, + viewport, +}: { + content: HTMLElement; + scrollTop: number; + spacer: HTMLElement | null; + viewport: HTMLElement; +}): number { + const contentHeight = measureContentHeight({ content, spacer, viewport }); + return scrollTop + viewport.clientHeight - contentHeight; +} + +function computeScrollTopForElement({ + align, + element, + scrollMargin, + spacer, + viewport, +}: { + align: MessageScrollerScrollAlign; + element: HTMLElement; + scrollMargin: number; + spacer: HTMLElement | null; + viewport: HTMLElement; +}): number { + const offsetTop = getElementOffsetTop(element, viewport); + const height = element.getBoundingClientRect().height; + const padding = getContentPadding(spacer); + + if (align === 'center') { + const available = Math.max(0, viewport.clientHeight - padding.start - padding.end); + return offsetTop - padding.start - (available - height) / 2 - scrollMargin; + } + if (align === 'end') return offsetTop - viewport.clientHeight + height + padding.end + scrollMargin; + if (align === 'nearest') { + const bottom = offsetTop + height; + const visibleTop = viewport.scrollTop + padding.start; + const visibleBottom = viewport.scrollTop + viewport.clientHeight - padding.end; + if (offsetTop >= visibleTop && bottom <= visibleBottom) return viewport.scrollTop; + return offsetTop < visibleTop + ? offsetTop - padding.start - scrollMargin + : bottom - viewport.clientHeight + padding.end + scrollMargin; + } + return offsetTop - padding.start - scrollMargin; +} + +function computeScrollable({ + content, + scrollEdgeThreshold, + spacer, + viewport, +}: { + content: HTMLElement | null; + scrollEdgeThreshold: number; + spacer: HTMLElement | null; + viewport: HTMLElement | null; +}): MessageScrollerScrollable { + if (!viewport || !content) return EMPTY_SCROLLABLE; + const contentHeight = measureContentHeight({ content, spacer, viewport }); + return { + start: viewport.scrollTop > scrollEdgeThreshold, + end: contentHeight - viewport.scrollTop - viewport.clientHeight > scrollEdgeThreshold, + }; +} + +function computeVisibility({ + content, + scrollMargin, + scrollPreviousItemPeek, + spacer, + viewport, + visibleMessageIds, +}: { + content: HTMLElement | null; + scrollMargin: number; + scrollPreviousItemPeek: number; + spacer: HTMLElement | null; + viewport: HTMLElement | null; + visibleMessageIds: Set; +}): MessageScrollerVisibilityState { + if (!content || !viewport) return EMPTY_VISIBILITY; + const viewportRect = viewport.getBoundingClientRect(); + const anchorLine = viewportRect.top + scrollMargin + scrollPreviousItemPeek; + const noIntersectionObserver = typeof IntersectionObserver === 'undefined'; + const visible: string[] = []; + let currentAnchorId: string | null = null; + + for (const child of getMessageChildren(content, spacer)) { + const messageId = child.dataset.messageId; + if (!messageId) continue; + const isAnchor = child.dataset.scrollAnchor === 'true'; + const rect = isAnchor || noIntersectionObserver ? child.getBoundingClientRect() : null; + const isVisible = + noIntersectionObserver && rect ? rect.bottom > anchorLine && rect.top < viewportRect.bottom : visibleMessageIds.has(messageId); + if (isVisible) visible.push(messageId); + if (isAnchor && rect && rect.top <= anchorLine + SCROLL_EPSILON) currentAnchorId = messageId; + } + + return visible.length === 0 && currentAnchorId === null ? EMPTY_VISIBILITY : { currentAnchorId, visibleMessageIds: visible }; +} + +function findFirstAnchorFrom(elements: HTMLElement[], startIndex: number): HTMLElement | null { + for (let i = startIndex; i < elements.length; i++) { + const element = elements[i]; + if (element?.dataset.scrollAnchor === 'true') return element; + } + return null; +} + +function findFirstUnhandledAnchor(elements: HTMLElement[], handled: WeakSet): HTMLElement | null { + for (const element of elements) { + if (element.dataset.scrollAnchor === 'true' && !handled.has(element)) return element; + } + return null; +} + +function hasMultipleAnchorsFrom(elements: HTMLElement[], startIndex: number): boolean { + let count = 0; + for (let i = startIndex; i < elements.length; i++) { + if (elements[i]?.dataset.scrollAnchor === 'true') { + count += 1; + if (count > 1) return true; + } + } + return false; +} + +function findLastAnchor(elements: HTMLElement[]): HTMLElement | null { + for (let i = elements.length - 1; i >= 0; i--) { + const element = elements[i]; + if (element?.dataset.scrollAnchor === 'true') return element; + } + return null; +} + +function findFirstVisibleMessage({ + content, + spacer, + viewport, +}: { + content: HTMLElement; + spacer: HTMLElement | null; + viewport: HTMLElement; +}): HTMLElement | null { + const viewportRect = viewport.getBoundingClientRect(); + for (const child of getMessageChildren(content, spacer)) { + if (!child.dataset.messageId) continue; + const rect = child.getBoundingClientRect(); + if (rect.bottom > viewportRect.top && rect.top < viewportRect.bottom) return child; + } + return null; +} + +// ----------------------------------------------------------------------------- +// Engine +// ----------------------------------------------------------------------------- + +export interface MessageScrollerContext { + autoscrolling: Readonly>; + scrollable: Readonly>; + scrollableAttr: ComputedRef; + visibility: Readonly>; + acquireVisibility: () => void; + releaseVisibility: () => void; + handleContentChange: () => void; + handleResize: () => void; + scrollToEnd: (options?: { behavior?: ScrollBehavior }) => boolean; + scrollToMessage: (messageId: string, options?: MessageScrollerScrollOptions) => boolean; + scrollToStart: (options?: { behavior?: ScrollBehavior }) => boolean; + setContentElement: (element: HTMLElement | null) => void; + setSpacerElement: (element: HTMLElement | null) => void; + setViewportElement: (element: HTMLElement | null) => void; + setPreserveScrollOnPrepend: (value: boolean) => void; + syncAfterScroll: () => void; + userScrollIntent: () => void; +} + +export type RegisterMessage = (messageId: string, element: HTMLElement | null, previousElement: HTMLElement | null) => void; + +const CONTEXT_KEY: InjectionKey = Symbol('MessageScrollerContext'); +const REGISTER_KEY: InjectionKey = Symbol('MessageScrollerRegister'); + +function createEngine(props: MessageScrollerProviderProps) { + const autoScroll = () => props.autoScroll ?? false; + const defaultScrollPosition = () => props.defaultScrollPosition ?? 'end'; + const scrollEdgeThreshold = () => props.scrollEdgeThreshold ?? DEFAULT_SCROLL_EDGE_THRESHOLD; + const scrollPreviousItemPeek = () => props.scrollPreviousItemPeek ?? DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK; + const scrollMargin = () => props.scrollMargin ?? DEFAULT_SCROLL_MARGIN; + + let viewport: HTMLElement | null = null; + let content: HTMLElement | null = null; + let spacer: HTMLElement | null = null; + let spacerGap = 0; + let spacerHeight = 0; + let mode: Mode = autoScroll() ? 'following-bottom' : 'free-scrolling'; + let streamingTurn: HTMLElement | null = null; + let firstItem: HTMLElement | null = null; + let itemCount = 0; + let lastScrollTop = 0; + let defaultScrollPositionApplied = false; + let preserveScrollOnPrepend = true; + let prependRestore: PrependRestore | null = null; + let pendingScrollToMessage: PendingScrollToMessage | null = null; + let stateFrame: number | null = null; + let visibilityFrame: number | null = null; + let pendingScrollFrame: number | null = null; + let autoscrollingTimeout: number | null = null; + let visibilityObserver: IntersectionObserver | null = null; + let visibilityConsumers = 0; + const messageElements = new Map(); + const visibleMessageIds = new Set(); + const handledScrollAnchors = new WeakSet(); + + const autoscrolling = shallowRef(false); + const scrollable = shallowRef(EMPTY_SCROLLABLE); + const visibility = shallowRef(EMPTY_VISIBILITY); + const scrollableAttr = computed(() => { + const attr = [scrollable.value.start && 'start', scrollable.value.end && 'end'].filter(Boolean).join(' '); + return attr || undefined; + }); + + // --- scroll-state commit / visibility scheduling --------------------------- + + function updateModeFromScroll(next: MessageScrollerScrollable) { + const scrollTop = viewport?.scrollTop ?? 0; + const scrolledUp = scrollTop < lastScrollTop - SCROLL_EPSILON; + lastScrollTop = scrollTop; + if (autoScroll() && !next.end && mode !== 'settling-jump' && mode !== 'anchored-to-message') { + mode = 'following-bottom'; + } else if (mode === 'following-bottom' && next.end && scrolledUp && !autoscrolling.value) { + mode = 'free-scrolling'; + } + } + + function commitScrollState() { + const measured = computeScrollable({ + content, + scrollEdgeThreshold: scrollEdgeThreshold(), + spacer, + viewport, + }); + updateModeFromScroll(measured); + const next = mode === 'following-bottom' ? { ...measured, end: false } : measured; + if (!scrollableEqual(scrollable.value, next)) scrollable.value = next; + } + + function scheduleStateCommit() { + if (stateFrame === null) { + stateFrame = window.requestAnimationFrame(() => { + stateFrame = null; + commitScrollState(); + }); + } + } + + function scheduleVisibilitySync() { + if (visibilityConsumers === 0) return; + if (visibilityFrame === null) { + visibilityFrame = window.requestAnimationFrame(() => { + visibilityFrame = null; + if (visibilityConsumers > 0) { + const next = computeVisibility({ + content, + scrollMargin: scrollMargin(), + scrollPreviousItemPeek: scrollPreviousItemPeek(), + spacer, + viewport, + visibleMessageIds, + }); + if (!visibilityEqual(visibility.value, next)) visibility.value = next; + } + }); + } + } + + // --- imperative scroll primitives ------------------------------------------ + + function setAutoscrolling(active: boolean) { + if (autoscrollingTimeout !== null) { + window.clearTimeout(autoscrollingTimeout); + autoscrollingTimeout = null; + } + if (autoscrolling.value !== active) { + autoscrolling.value = active; + commitScrollState(); + } + if (active) { + autoscrollingTimeout = window.setTimeout(() => { + autoscrollingTimeout = null; + autoscrolling.value = false; + commitScrollState(); + }, AUTOSCROLLING_TIMEOUT); + } + } + + function setSpacerHeight(height: number) { + if (!spacer) return; + const next = Math.max(0, Math.ceil(height)); + if (spacerHeight !== next) { + spacerHeight = next; + spacer.hidden = next === 0; + spacer.style.height = `${next}px`; + spacer.style.marginTop = next > 0 ? `${-spacerGap}px` : ''; + } + } + + function scrollTo( + top: number, + { behavior = 'auto', autoscrolling: isAutoscrolling = false }: { behavior?: ScrollBehavior; autoscrolling?: boolean } = {}, + ) { + if (!viewport) return; + const target = Math.max(0, top); + if (Math.abs(viewport.scrollTop - target) <= SCROLL_EPSILON) { + viewport.scrollTop = target; + commitScrollState(); + return; + } + if (isAutoscrolling) setAutoscrolling(true); + viewport.scrollTo({ top: target, behavior }); + scheduleStateCommit(); + } + + function scrollToStart({ behavior = 'auto' }: { behavior?: ScrollBehavior } = {}): boolean { + if (!viewport) return false; + setSpacerHeight(0); + streamingTurn = null; + mode = 'free-scrolling'; + scrollTo(0, { behavior }); + scheduleVisibilitySync(); + return true; + } + + function scrollToEnd({ behavior = 'auto' }: { behavior?: ScrollBehavior } = {}): boolean { + if (!viewport) return false; + setSpacerHeight(0); + streamingTurn = null; + mode = autoScroll() ? 'following-bottom' : 'free-scrolling'; + scrollTo(maxScrollTop(viewport), { autoscrolling: true, behavior }); + scheduleVisibilitySync(); + return true; + } + + function scrollToElement( + element: HTMLElement, + { align = 'start', behavior = 'auto', scrollMargin: margin = scrollMargin() }: MessageScrollerScrollOptions = {}, + { keepPreviousPeek = false }: { keepPreviousPeek?: boolean } = {}, + ): boolean { + if (!content || !viewport || !content.contains(element)) return false; + const targetScrollTop = computeScrollTopForElement({ + align, + element, + scrollMargin: keepPreviousPeek ? margin + scrollPreviousItemPeek() : margin, + spacer, + viewport, + }); + setSpacerHeight( + computeSpacerHeight({ + content, + scrollTop: targetScrollTop, + spacer, + viewport, + }), + ); + prependRestore = { element, viewportTop: getRelativeTop(element, viewport) }; + mode = keepPreviousPeek ? 'anchored-to-message' : 'settling-jump'; + streamingTurn = keepPreviousPeek ? element : null; + scrollTo(targetScrollTop, { behavior }); + scheduleVisibilitySync(); + return true; + } + + function reanchorToAnchoredMessage(): boolean { + if (!streamingTurn || !streamingTurn.isConnected || mode !== 'anchored-to-message') return false; + return scrollToElement(streamingTurn, { align: 'start' }, { keepPreviousPeek: true }); + } + + function scrollToMessage(messageId: string, options?: MessageScrollerScrollOptions): boolean { + const element = messageElements.get(messageId); + if (element) { + defaultScrollPositionApplied = true; + if (scrollToElement(element, options)) { + pendingScrollToMessage = null; + return true; + } + pendingScrollToMessage = { messageId, options }; + return true; + } + if (itemCount === 0) { + pendingScrollToMessage = { messageId, options }; + defaultScrollPositionApplied = true; + return true; + } + return false; + } + + function flushPendingScrollToMessage(): boolean { + if (!pendingScrollToMessage) return false; + const element = messageElements.get(pendingScrollToMessage.messageId); + if (!element || !scrollToElement(element, pendingScrollToMessage.options)) return false; + pendingScrollToMessage = null; + defaultScrollPositionApplied = true; + return true; + } + + // --- prepend preservation -------------------------------------------------- + + function applyPrependRestore(): boolean { + if (!prependRestore || !viewport || !prependRestore.element.isConnected) return false; + const delta = getRelativeTop(prependRestore.element, viewport) - prependRestore.viewportTop; + if (Math.abs(delta) <= SCROLL_EPSILON) return false; + viewport.scrollTop += delta; + prependRestore.viewportTop = getRelativeTop(prependRestore.element, viewport); + scheduleStateCommit(); + scheduleVisibilitySync(); + return true; + } + + function capturePrependAnchor() { + if (!content || !viewport) { + prependRestore = null; + return; + } + const element = findFirstVisibleMessage({ content, spacer, viewport }); + prependRestore = element ? { element, viewportTop: getRelativeTop(element, viewport) } : null; + } + + function schedulePrependFlush() { + if (pendingScrollFrame === null) { + pendingScrollFrame = window.requestAnimationFrame(() => { + pendingScrollFrame = null; + if (flushPendingScrollToMessage()) capturePrependAnchor(); + }); + } + } + + // --- default scroll position ----------------------------------------------- + + function applyDefaultScrollPosition(): boolean { + if (defaultScrollPositionApplied || itemCount === 0) return false; + const position = defaultScrollPosition(); + let applied = false; + if (position === 'last-anchor') { + const lastAnchor = content && viewport ? findLastAnchor(getMessageChildren(content, spacer)) : null; + if (!content || !viewport || !lastAnchor) { + applied = scrollToEnd({ behavior: 'auto' }); + } else { + const anchorOffset = getElementOffsetTop(lastAnchor, viewport); + const contentHeight = measureContentHeight({ content, spacer, viewport }); + applied = + contentHeight - anchorOffset <= viewport.clientHeight + ? scrollToEnd({ behavior: 'auto' }) + : scrollToElement(lastAnchor, { align: 'start' }, { keepPreviousPeek: true }); + } + } else { + applied = position === 'end' ? scrollToEnd({ behavior: 'auto' }) : scrollToStart({ behavior: 'auto' }); + } + if (applied) { + defaultScrollPositionApplied = true; + return true; + } + return false; + } + + // --- content / resize handling --------------------------------------------- + + /** + * Anchors that were already there (a loaded transcript, a prepended page) are not new turns. + * Left unhandled, the first swap that kept the count (a placeholder out, the reply in) took + * the transcript's first question for a new one and scrolled to the top. + */ + function markHandled(elements: HTMLElement[]) { + for (const element of elements) { + if (element.dataset.scrollAnchor === 'true') handledScrollAnchors.add(element); + } + } + + function applyContentChange(children: HTMLElement[], previousCount: number, previousFirst: HTMLElement | null) { + if (previousCount === 0) markHandled(children); + if (flushPendingScrollToMessage()) return; + if (previousCount === 0) { + if (applyDefaultScrollPosition() || (children.length > 0 && autoScroll() && scrollToEnd({ behavior: 'auto' }))) { + return; + } + commitScrollState(); + scheduleVisibilitySync(); + return; + } + const previousIndex = previousFirst ? children.indexOf(previousFirst) : -1; + if (previousIndex > 0) markHandled(children.slice(0, previousIndex)); + if (preserveScrollOnPrepend && previousIndex > 0) { + applyPrependRestore(); + return; + } + if (children.length > previousCount) { + const anchor = findFirstAnchorFrom(children, previousCount); + if (anchor) { + if (autoScroll() && mode === 'following-bottom' && hasMultipleAnchorsFrom(children, previousCount)) { + scrollToEnd({ behavior: 'auto' }); + return; + } + scrollToElement(anchor, { align: 'start' }, { keepPreviousPeek: true }); + handledScrollAnchors.add(anchor); + return; + } + } + if (children.length === previousCount) { + const anchor = findFirstUnhandledAnchor(children, handledScrollAnchors); + if (anchor) { + scrollToElement(anchor, { align: 'start' }, { keepPreviousPeek: true }); + handledScrollAnchors.add(anchor); + return; + } + } + if (mode === 'following-bottom' && autoScroll()) { + scrollToEnd({ behavior: 'auto' }); + } else { + commitScrollState(); + scheduleVisibilitySync(); + } + } + + function handleContentChange() { + if (!content) return; + const children = getMessageChildren(content, spacer); + const previousCount = itemCount; + const previousFirst = firstItem; + itemCount = children.length; + firstItem = children[0] ?? null; + + applyContentChange(children, previousCount, previousFirst); + capturePrependAnchor(); + } + + function handleResize() { + if (mode === 'following-bottom' && autoScroll()) { + scrollToEnd({ behavior: 'auto' }); + return; + } + const previousSpacerHeight = spacerHeight; + if (reanchorToAnchoredMessage()) { + // The reply streaming below the anchor consumes the tail spacer as it + // grows. Once the last of it is gone the reply has filled the viewport + // and the reader is genuinely at the live edge, so autoScroll hands off + // from the anchor hold to following the bottom. Requiring the >0 → 0 + // transition keeps a turn taller than the viewport (placed with no + // spacer) held instead of yanked to the end. + if (autoScroll() && previousSpacerHeight > 0 && spacerHeight === 0) scrollToEnd({ behavior: 'auto' }); + return; + } + scheduleStateCommit(); + scheduleVisibilitySync(); + } + + // --- visibility observation ------------------------------------------------ + + function observeVisibility() { + if (!viewport || visibilityConsumers === 0) return; + if (typeof IntersectionObserver === 'undefined') { + scheduleVisibilitySync(); + return; + } + if (!visibilityObserver) { + visibilityObserver = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + const messageId = (entry.target as HTMLElement).dataset.messageId; + if (!messageId) continue; + if (entry.isIntersecting) visibleMessageIds.add(messageId); + else visibleMessageIds.delete(messageId); + } + scheduleVisibilitySync(); + }, + { + root: viewport, + rootMargin: `${-(scrollMargin() + scrollPreviousItemPeek())}px 0px 0px 0px`, + threshold: [0, 0.01, 0.5, 1], + }, + ); + } + messageElements.forEach((element) => { + visibilityObserver?.observe(element); + }); + scheduleVisibilitySync(); + } + + function unobserveVisibility() { + if (visibilityFrame !== null) { + window.cancelAnimationFrame(visibilityFrame); + visibilityFrame = null; + } + visibilityObserver?.disconnect(); + visibilityObserver = null; + visibleMessageIds.clear(); + if (!visibilityEqual(visibility.value, EMPTY_VISIBILITY)) visibility.value = EMPTY_VISIBILITY; + } + + function acquireVisibility() { + visibilityConsumers += 1; + if (visibilityConsumers === 1) observeVisibility(); + } + + function releaseVisibility() { + visibilityConsumers -= 1; + if (visibilityConsumers === 0) unobserveVisibility(); + } + + const registerMessage: RegisterMessage = (messageId, element, previousElement) => { + if (element) { + messageElements.set(messageId, element); + visibilityObserver?.observe(element); + scheduleVisibilitySync(); + if (pendingScrollToMessage?.messageId === messageId) schedulePrependFlush(); + return; + } + if (previousElement && messageElements.get(messageId) === previousElement) { + messageElements.delete(messageId); + visibleMessageIds.delete(messageId); + visibilityObserver?.unobserve(previousElement); + scheduleVisibilitySync(); + } + }; + + // --- user intent + element setters ----------------------------------------- + + function userScrollIntent() { + if (mode === 'following-bottom' || mode === 'anchored-to-message' || mode === 'settling-jump') { + streamingTurn = null; + mode = 'free-scrolling'; + } + } + + function setViewportElement(element: HTMLElement | null) { + viewport = element; + // A visibility consumer may have subscribed before the viewport mounted, + // in which case observeVisibility() bailed out. Retry now it exists. + if (element) observeVisibility(); + } + + function setContentElement(element: HTMLElement | null) { + content = element; + } + + function setSpacerElement(element: HTMLElement | null) { + spacer = element; + spacerGap = getRowGap(element?.parentElement ?? null); + } + + function setPreserveScrollOnPrepend(value: boolean) { + preserveScrollOnPrepend = value; + } + + function syncAfterScroll() { + commitScrollState(); + scheduleVisibilitySync(); + capturePrependAnchor(); + } + + function onAutoScrollChange() { + if (autoScroll() && mode === 'following-bottom' && itemCount > 0) { + scrollToEnd({ behavior: 'auto' }); + return; + } + commitScrollState(); + } + + function destroy() { + if (stateFrame !== null) { + window.cancelAnimationFrame(stateFrame); + stateFrame = null; + } + if (visibilityFrame !== null) { + window.cancelAnimationFrame(visibilityFrame); + visibilityFrame = null; + } + if (autoscrollingTimeout !== null) { + window.clearTimeout(autoscrollingTimeout); + autoscrollingTimeout = null; + } + if (pendingScrollFrame !== null) { + window.cancelAnimationFrame(pendingScrollFrame); + pendingScrollFrame = null; + } + visibilityObserver?.disconnect(); + visibilityObserver = null; + } + + const context: MessageScrollerContext = { + autoscrolling, + scrollable, + scrollableAttr, + visibility, + acquireVisibility, + releaseVisibility, + handleContentChange, + handleResize, + scrollToEnd, + scrollToMessage, + scrollToStart, + setContentElement, + setSpacerElement, + setViewportElement, + setPreserveScrollOnPrepend, + syncAfterScroll, + userScrollIntent, + }; + + return { + context, + registerMessage, + applyDefaultScrollPosition, + onAutoScrollChange, + destroy, + }; +} + +// ----------------------------------------------------------------------------- +// Provider wiring (provide/inject) +// ----------------------------------------------------------------------------- + +export function provideMessageScroller(props: MessageScrollerProviderProps) { + const engine = createEngine(props); + provide(CONTEXT_KEY, engine.context); + provide(REGISTER_KEY, engine.registerMessage); + + watch( + () => props.autoScroll ?? false, + () => engine.onAutoScrollChange(), + ); + + onMounted(() => { + engine.applyDefaultScrollPosition(); + // The viewport element attaches in MessageScrollerViewport's onMounted, + // after MessageScrollerContent ran its initial handleContentChange without + // it. Re-sync now that every element is wired up. + engine.context.syncAfterScroll(); + }); + + onScopeDispose(() => engine.destroy()); + + return engine; +} + +export function useMessageScrollerContext(): MessageScrollerContext { + const context = inject(CONTEXT_KEY, null); + if (!context) throw new Error('useMessageScroller must be used within a MessageScroller.'); + return context; +} + +export function useMessageScrollerRegister(): RegisterMessage { + const register = inject(REGISTER_KEY, null); + if (!register) throw new Error('MessageScrollerItem must be used within a MessageScroller.'); + return register; +} + +// ----------------------------------------------------------------------------- +// Public composables +// ----------------------------------------------------------------------------- + +export function useMessageScroller() { + const { scrollToEnd, scrollToMessage, scrollToStart } = useMessageScrollerContext(); + return { scrollToEnd, scrollToMessage, scrollToStart }; +} + +export function useMessageScrollerScrollable(): Ref { + const { scrollable } = useMessageScrollerContext(); + return computed(() => scrollable.value); +} + +export function useMessageScrollerVisibility(): Ref { + const { acquireVisibility, releaseVisibility, visibility } = useMessageScrollerContext(); + acquireVisibility(); + if (getCurrentScope()) onScopeDispose(releaseVisibility); + return computed(() => visibility.value); +} + +export { SCROLL_KEYS }; diff --git a/resources/js/vue/components/ui/message/Message.vue b/resources/js/vue/components/ui/message/Message.vue new file mode 100644 index 0000000..240f32a --- /dev/null +++ b/resources/js/vue/components/ui/message/Message.vue @@ -0,0 +1,27 @@ + + + diff --git a/resources/js/vue/components/ui/message/MessageAvatar.vue b/resources/js/vue/components/ui/message/MessageAvatar.vue new file mode 100644 index 0000000..4f731cc --- /dev/null +++ b/resources/js/vue/components/ui/message/MessageAvatar.vue @@ -0,0 +1,29 @@ + + + diff --git a/resources/js/vue/components/ui/message/MessageContent.vue b/resources/js/vue/components/ui/message/MessageContent.vue new file mode 100644 index 0000000..ca92c1b --- /dev/null +++ b/resources/js/vue/components/ui/message/MessageContent.vue @@ -0,0 +1,24 @@ + + + diff --git a/resources/js/vue/components/ui/message/MessageFooter.vue b/resources/js/vue/components/ui/message/MessageFooter.vue new file mode 100644 index 0000000..3902948 --- /dev/null +++ b/resources/js/vue/components/ui/message/MessageFooter.vue @@ -0,0 +1,29 @@ + + + diff --git a/resources/js/vue/components/ui/message/MessageGroup.vue b/resources/js/vue/components/ui/message/MessageGroup.vue new file mode 100644 index 0000000..4316338 --- /dev/null +++ b/resources/js/vue/components/ui/message/MessageGroup.vue @@ -0,0 +1,19 @@ + + + diff --git a/resources/js/vue/components/ui/message/MessageHeader.vue b/resources/js/vue/components/ui/message/MessageHeader.vue new file mode 100644 index 0000000..aa49844 --- /dev/null +++ b/resources/js/vue/components/ui/message/MessageHeader.vue @@ -0,0 +1,29 @@ + + + diff --git a/resources/js/vue/components/ui/message/index.ts b/resources/js/vue/components/ui/message/index.ts new file mode 100644 index 0000000..e03cfbd --- /dev/null +++ b/resources/js/vue/components/ui/message/index.ts @@ -0,0 +1,6 @@ +export { default as Message } from './Message.vue'; +export { default as MessageAvatar } from './MessageAvatar.vue'; +export { default as MessageContent } from './MessageContent.vue'; +export { default as MessageFooter } from './MessageFooter.vue'; +export { default as MessageGroup } from './MessageGroup.vue'; +export { default as MessageHeader } from './MessageHeader.vue'; diff --git a/resources/js/vue/components/ui/spinner/Spinner.vue b/resources/js/vue/components/ui/spinner/Spinner.vue new file mode 100644 index 0000000..f5108f8 --- /dev/null +++ b/resources/js/vue/components/ui/spinner/Spinner.vue @@ -0,0 +1,13 @@ + + + diff --git a/resources/js/vue/components/ui/spinner/index.ts b/resources/js/vue/components/ui/spinner/index.ts new file mode 100644 index 0000000..b2cd020 --- /dev/null +++ b/resources/js/vue/components/ui/spinner/index.ts @@ -0,0 +1 @@ +export { default as Spinner } from './Spinner.vue'; diff --git a/resources/js/vue/components/ui/trace/Trace.vue b/resources/js/vue/components/ui/trace/Trace.vue new file mode 100644 index 0000000..c050514 --- /dev/null +++ b/resources/js/vue/components/ui/trace/Trace.vue @@ -0,0 +1,22 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceCollapsible.vue b/resources/js/vue/components/ui/trace/TraceCollapsible.vue new file mode 100644 index 0000000..6535a42 --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceCollapsible.vue @@ -0,0 +1,25 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceCollapsibleContent.vue b/resources/js/vue/components/ui/trace/TraceCollapsibleContent.vue new file mode 100644 index 0000000..0a8d640 --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceCollapsibleContent.vue @@ -0,0 +1,31 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceCollapsibleTrigger.vue b/resources/js/vue/components/ui/trace/TraceCollapsibleTrigger.vue new file mode 100644 index 0000000..b8c5360 --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceCollapsibleTrigger.vue @@ -0,0 +1,32 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceDescription.vue b/resources/js/vue/components/ui/trace/TraceDescription.vue new file mode 100644 index 0000000..392b56c --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceDescription.vue @@ -0,0 +1,14 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceIcon.vue b/resources/js/vue/components/ui/trace/TraceIcon.vue new file mode 100644 index 0000000..bea77be --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceIcon.vue @@ -0,0 +1,23 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceLine.vue b/resources/js/vue/components/ui/trace/TraceLine.vue new file mode 100644 index 0000000..568309e --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceLine.vue @@ -0,0 +1,24 @@ + + + diff --git a/resources/js/vue/components/ui/trace/TraceTitle.vue b/resources/js/vue/components/ui/trace/TraceTitle.vue new file mode 100644 index 0000000..e465eb2 --- /dev/null +++ b/resources/js/vue/components/ui/trace/TraceTitle.vue @@ -0,0 +1,14 @@ + + + diff --git a/resources/js/vue/components/ui/trace/index.ts b/resources/js/vue/components/ui/trace/index.ts new file mode 100644 index 0000000..f7ad0d6 --- /dev/null +++ b/resources/js/vue/components/ui/trace/index.ts @@ -0,0 +1,8 @@ +export { default as Trace } from './Trace.vue'; +export { default as TraceCollapsible } from './TraceCollapsible.vue'; +export { default as TraceCollapsibleContent } from './TraceCollapsibleContent.vue'; +export { default as TraceCollapsibleTrigger } from './TraceCollapsibleTrigger.vue'; +export { default as TraceDescription } from './TraceDescription.vue'; +export { default as TraceIcon } from './TraceIcon.vue'; +export { default as TraceLine } from './TraceLine.vue'; +export { default as TraceTitle } from './TraceTitle.vue'; diff --git a/resources/js/vue/composables/useDictation.ts b/resources/js/vue/composables/useDictation.ts new file mode 100644 index 0000000..7329632 --- /dev/null +++ b/resources/js/vue/composables/useDictation.ts @@ -0,0 +1,64 @@ +import { trans } from 'laravel-vue-i18n'; +import { onBeforeUnmount, ref, type Ref } from 'vue'; +import { toast } from 'vue-sonner'; +import { dictatedText, dictationProblem } from '../../lib/dictation'; + +type Recognition = { + continuous: boolean; + interimResults: boolean; + lang: string; + start(): void; + stop(): void; + onstart: (() => void) | null; + onend: (() => void) | null; + onresult: ((event: { results: ArrayLike> }) => void) | null; + onerror: ((event: { error: string }) => void) | null; +}; + +/** + * Voice input into a text box, with the browser's speech recognition (the Web Speech + * API: Chrome, Edge, Safari; not Firefox). Words appear while the user speaks and add + * to what was already typed. + */ +export function useDictation(text: Ref) { + const browser = window as unknown as { SpeechRecognition?: new () => Recognition; webkitSpeechRecognition?: new () => Recognition }; + const Recognition = browser.SpeechRecognition ?? browser.webkitSpeechRecognition; + const supported = Recognition !== undefined; + const listening = ref(false); + const recognition = Recognition ? new Recognition() : null; + + if (recognition) { + recognition.continuous = true; + recognition.interimResults = true; + // The page's language, so it hears the words the user types in. + recognition.lang = document.documentElement.lang || 'en-US'; + + // ponytail: typing while dictating is overwritten by the next result; track the caret if that matters. + let before = ''; + + recognition.onstart = () => { + listening.value = true; + before = text.value.trimEnd(); + }; + recognition.onend = () => (listening.value = false); + recognition.onresult = (event) => (text.value = dictatedText(before, event.results)); + recognition.onerror = (event) => { + listening.value = false; + + const problem = dictationProblem(event.error); + + if (problem) { + toast.error(trans('Dictation failed'), { description: trans(problem) }); + } + }; + } + + onBeforeUnmount(() => recognition?.stop()); + + return { + supported, + listening, + toggle: () => (listening.value ? recognition?.stop() : recognition?.start()), + stop: () => recognition?.stop(), + }; +} diff --git a/resources/js/vue/pages/Index.vue b/resources/js/vue/pages/Index.vue index d92d0a5..82e8749 100644 --- a/resources/js/vue/pages/Index.vue +++ b/resources/js/vue/pages/Index.vue @@ -1,51 +1,545 @@ + + diff --git a/routes/capabilities.php b/routes/capabilities.php new file mode 100644 index 0000000..c6667cc --- /dev/null +++ b/routes/capabilities.php @@ -0,0 +1,18 @@ + [ + 'label' => 'AI chat messages per month', + 'description' => 'How many messages a user can send the assistant each month. Unlimited: no cap.', + 'type' => 'limit', + ], + Usage::IMAGES => [ + 'label' => 'AI images per month', + 'description' => 'How many images the assistant can generate for a user each month. Unlimited: no cap.', + 'type' => 'limit', + ], +]); diff --git a/routes/navigation.php b/routes/navigation.php index fcf3c2e..fa03cfe 100644 --- a/routes/navigation.php +++ b/routes/navigation.php @@ -3,24 +3,19 @@ use Saucebase\Core\Facades\Navigation; use Saucebase\Core\Navigation\Section; -/* -|-------------------------------------------------------------------------- -| AiChat Module Navigation -|-------------------------------------------------------------------------- -| -| Define AiChat module navigation items here. -| These items will be loaded automatically when the module is enabled. -| -*/ - -Navigation::add('AiChat', fn () => route('ai-chat.index'), function (Section $section) { - $section->attributes([ - 'group' => 'main', - 'slug' => 'ai-chat', - 'icon' => 'ai-chat', - 'badge' => [ - 'content' => 'New', - 'variant' => 'info', - ], - ]); -}); +// With `ai-chat.sessions` = `sidebar` the list leads the app sidebar instead (resources/js/vue/app.ts). +Navigation::addWhen( + fn () => config('ai-chat.sessions') === 'page', + 'Chat', + fn () => route('ai-chat.index'), + function (Section $section) { + $section->attributes([ + 'group' => 'main', + 'slug' => 'chat', + 'icon' => 'chat', + 'order' => 20, + // Active on every chat, not only on /chat. + 'active' => fn () => request()->routeIs('ai-chat.*'), + ]); + } +); diff --git a/routes/web.php b/routes/web.php index 4acc72a..45c4526 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,8 +1,16 @@ 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::get('chat/sessions/search', [AiChatController::class, 'search'])->name('ai-chat.sessions.search'); + Route::post('chat/sessions/more', [AiChatController::class, 'more'])->name('ai-chat.sessions.more'); + Route::post('chat/messages', [AiChatController::class, 'stream'])->name('ai-chat.stream'); + Route::get('chat/{conversation}/history', [AiChatController::class, 'history'])->name('ai-chat.history'); + Route::get('chat/{conversation}/messages', [AiChatController::class, 'messages'])->name('ai-chat.messages'); + Route::get('chat/{conversation}', [AiChatController::class, 'show'])->name('ai-chat.show'); + Route::patch('chat/{conversation}', [AiChatController::class, 'update'])->name('ai-chat.update'); + Route::delete('chat/{conversation}', [AiChatController::class, 'destroy'])->name('ai-chat.destroy'); }); diff --git a/src/Ai/ChatAgent.php b/src/Ai/ChatAgent.php new file mode 100644 index 0000000..65453f5 --- /dev/null +++ b/src/Ai/ChatAgent.php @@ -0,0 +1,63 @@ +instructions); + + return trim(<< + */ + public function tools(): iterable + { + // Provider-hosted: it streams no parts, so the browser never sees a search step. + $tools = [new WebSearch]; + + if ($this->user !== null) { + $tools[] = new AboutMyAccount($this->user); + $tools[] = new GenerateImage($this->user); + } + + return $tools; + } +} diff --git a/src/Ai/ConversationTitleAgent.php b/src/Ai/ConversationTitleAgent.php new file mode 100644 index 0000000..e2b9c53 --- /dev/null +++ b/src/Ai/ConversationTitleAgent.php @@ -0,0 +1,33 @@ +generateStreamStep('', $provider, $model, $instructions, $messages, $tools, $schema, $options, $timeout, $stepContext); + + foreach ($stream as $event) { + // Drained: only the step's result matters here. + } + + return $stream->getReturn(); + } + + public function generateStreamStep( + string $invocationId, + TextProvider $provider, + string $model, + ?string $instructions, + array $messages, + array $tools, + ?array $schema, + ?TextGenerationOptions $options, + ?int $timeout, + StepContext $stepContext, + ): Generator { + yield (new StreamStart(ulid(), $provider->name(), $model, time()))->withInvocationId($invocationId); + + if ($model === self::TITLE) { + // The transcript opens with the user's first message: "User: …". + $title = Str::of(strtok($this->lastPrompt($messages), "\n") ?: '')->after(':')->squish()->words(6, '')->toString(); + + return $this->response($provider, $model, $title ?: 'Demo chat'); + } + + $demo = Demos::load(in_array($model, Demos::names(), true) ? $model : 'reply'); + $steps = $this->steps(collect($demo['messages'])->last(fn (array $message): bool => $message['role'] === 'assistant')['parts']); + $index = min($this->stepsTaken($messages), count($steps) - 1); + $messageId = ulid(); + $text = ''; + $calls = []; + $citations = []; + + foreach ($steps[$index] as $part) { + $type = $part['type']; + + if ($type === 'text' || $type === 'reasoning') { + $id = ulid(); + + yield ($type === 'text' ? new TextStart(ulid(), $messageId, time()) : new ReasoningStart(ulid(), $id, time()))->withInvocationId($invocationId); + + foreach (preg_split('/(?<= )/', $part['text'], -1, PREG_SPLIT_NO_EMPTY) ?: [] as $piece) { + $this->pause(); + + yield ($type === 'text' ? new TextDelta(ulid(), $messageId, $piece, time()) : new ReasoningDelta(ulid(), $id, $piece, time()))->withInvocationId($invocationId); + } + + yield ($type === 'text' ? new TextEnd(ulid(), $messageId, time()) : new ReasoningEnd(ulid(), $id, time()))->withInvocationId($invocationId); + + $text .= $type === 'text' ? $part['text'] : ''; + } elseif ($type === 'source-url') { + $citation = new UrlCitation($part['url'], $part['title'] ?? null); + $citations[] = $citation; + + yield (new Citation(ulid(), $messageId, $citation, time()))->withInvocationId($invocationId); + } elseif (str_starts_with($type, 'tool-')) { + $call = new ToolCall($part['toolCallId'].'-'.ulid(), substr($type, 5), $part['input'] ?? []); + $calls[] = $call; + + yield (new ToolCallEvent(ulid(), $call, time()))->withInvocationId($invocationId); + } + } + + // The provider gives out at the end of the reply: the loop throws, the controller reports it. + if (isset($demo['error']) && $index === count($steps) - 1) { + yield (new Error(ulid(), 'demo_failure', $demo['error'], false, time()))->withInvocationId($invocationId); + + return null; + } + + return $this->response($provider, $model, $text, $calls, $citations); + } + + public function generateImage( + ImageProvider $provider, + string $model, + string $prompt, + array $attachments = [], + ?string $size = null, + ?string $quality = null, + ?int $timeout = null, + ): ImageResponse { + return new ImageResponse( + new Collection([new GeneratedImage(base64_encode($this->drawing($prompt)), 'image/png')]), + new Usage, + new Meta($provider->name(), $model), + ); + } + + /** + * A reply's parts as steps: each ends after a run of tool calls. + * + * @param list> $parts + * @return list>> + */ + protected function steps(array $parts): array + { + $steps = [[]]; + + foreach ($parts as $i => $part) { + $steps[array_key_last($steps)][] = $part; + + $isTool = str_starts_with($part['type'], 'tool-'); + $nextIsTool = str_starts_with($parts[$i + 1]['type'] ?? 'tool-', 'tool-'); + + if ($isTool && ! $nextIsTool) { + $steps[] = []; + } + } + + return $steps; + } + + /** + * How many steps of this reply have run: the tool results since the user's message. + * + * @param array $messages + */ + protected function stepsTaken(array $messages): int + { + $taken = 0; + + foreach (array_reverse($messages) as $message) { + if ($message instanceof UserMessage) { + break; + } + + $taken += $message instanceof ToolResultMessage ? 1 : 0; + } + + return $taken; + } + + /** + * @param array $messages + */ + protected function lastPrompt(array $messages): string + { + $message = collect($messages)->last(fn ($message): bool => $message instanceof UserMessage); + + return $message instanceof UserMessage ? $message->content : ''; + } + + /** + * @param list $calls + * @param list $citations + */ + protected function response(TextProvider $provider, string $model, string $text, array $calls = [], array $citations = []): StepResponse + { + return new StepResponse( + $text, + $calls, + $calls === [] ? FinishReason::Stop : FinishReason::ToolCalls, + new Usage, + new Meta($provider->name(), $model, new Collection($citations)), + ); + } + + /** + * About a real model's pace (~80 words a second); instant under tests. + */ + protected function pause(): void + { + if (! app()->runningUnitTests()) { + usleep(12_000); + } + } + + /** + * A sun over the sea, its colours picked from the prompt: the same prompt, the same picture. + */ + protected function drawing(string $prompt): string + { + $hue = crc32($prompt) % 360; + [$sky, $sun, $sea] = [$this->hsl($hue, 45, 22), $this->hsl(($hue + 40) % 360, 90, 65), $this->hsl(($hue + 180) % 360, 55, 30)]; + + $image = imagecreatetruecolor(512, 512); + imagefill($image, 0, 0, imagecolorallocate($image, ...$sky)); + imagefilledellipse($image, 256, 210, 180, 180, imagecolorallocate($image, ...$sun)); + imagefilledrectangle($image, 0, 330, 511, 511, imagecolorallocate($image, ...$sea)); + + ob_start(); + imagepng($image); + + return (string) ob_get_clean(); + } + + /** + * @return array{int, int, int} + */ + protected function hsl(int $h, int $s, int $l): array + { + $s /= 100; + $l /= 100; + $k = fn (int $n): float => fmod($n + $h / 30, 12); + $a = $s * min($l, 1 - $l); + $f = fn (int $n): int => (int) round(255 * ($l - $a * max(-1, min($k($n) - 3, 9 - $k($n), 1)))); + + return [$f(0), $f(8), $f(4)]; + } +} diff --git a/src/Ai/Demo/DemoProvider.php b/src/Ai/Demo/DemoProvider.php new file mode 100644 index 0000000..91b3abb --- /dev/null +++ b/src/Ai/Demo/DemoProvider.php @@ -0,0 +1,53 @@ +textGateway = $this->imageGateway = new DemoGateway; + } + + public function defaultTextModel(): string + { + return 'reply'; + } + + /** What the title agent asks for: it gets a title, not a demo. */ + public function cheapestTextModel(): string + { + return DemoGateway::TITLE; + } + + public function smartestTextModel(): string + { + return 'reply'; + } + + public function defaultImageModel(): string + { + return 'demo'; + } + + public function defaultImageOptions(?string $size = null, ?string $quality = null): array + { + return []; + } +} diff --git a/src/Ai/Demo/Demos.php b/src/Ai/Demo/Demos.php new file mode 100644 index 0000000..fa3dce6 --- /dev/null +++ b/src/Ai/Demo/Demos.php @@ -0,0 +1,77 @@ +isProduction(); + } + + /** + * The demo provider's name, registered with laravel/ai on first use. Never + * up front: the admin's provider list reads every configured provider. + */ + public static function provider(): string + { + if (! config()->has('ai.providers.'.self::PROVIDER)) { + config(['ai.providers.'.self::PROVIDER => ['driver' => self::PROVIDER, 'name' => self::PROVIDER, 'key' => self::PROVIDER]]); + + app(AiManager::class)->extend(self::PROVIDER, fn ($app, array $config) => new DemoProvider($config, $app['events'])); + } + + return self::PROVIDER; + } + + /** + * @return list + */ + public static function names(): array + { + return array_map(fn (string $file): string => basename($file, '.json'), glob(self::path('*')) ?: []); + } + + /** + * @return array{description: string, messages: list>}>, error?: string} + */ + public static function load(string $name): array + { + return json_decode((string) file_get_contents(self::path($name)), true, flags: JSON_THROW_ON_ERROR); + } + + /** + * The demos as the picker's rows, `reply` first: the default. + * + * @return list + */ + public static function models(): array + { + $provider = self::provider(); + + return collect(self::names()) + ->sortBy(fn (string $name): string => $name === 'reply' ? '' : $name) + ->map(fn (string $name): array => ['label' => 'Demo: '.Str::headline($name), 'provider' => $provider, 'model' => $name]) + ->values() + ->all(); + } + + protected static function path(string $name): string + { + return dirname(__DIR__, 3)."/resources/demos/{$name}.json"; + } +} diff --git a/src/Ai/Providers.php b/src/Ai/Providers.php new file mode 100644 index 0000000..d61734f --- /dev/null +++ b/src/Ai/Providers.php @@ -0,0 +1,83 @@ + 'Anthropic', + 'azure' => 'Azure OpenAI', + 'bedrock' => 'Amazon Bedrock', + 'cohere' => 'Cohere', + 'deepseek' => 'DeepSeek', + 'eleven' => 'ElevenLabs', + 'gemini' => 'Gemini', + 'groq' => 'Groq', + 'jina' => 'Jina', + 'mistral' => 'Mistral', + 'ollama' => 'Ollama', + 'openai' => 'OpenAI', + 'openai-compatible' => 'OpenAI-compatible', + 'openrouter' => 'OpenRouter', + 'voyageai' => 'Voyage AI', + 'xai' => 'xAI', + ]; + + public static function label(string $provider): string + { + return self::LABELS[$provider] ?? str($provider)->headline()->toString(); + } + + /** + * Providers that can answer the chat, name => label. + * + * @return array + */ + public static function text(): array + { + return self::capable(fn (AiManager $ai, string $name) => $ai->textProvider($name)); + } + + /** + * Providers that can generate images, name => label. + * + * @return array + */ + public static function images(): array + { + return self::capable(fn (AiManager $ai, string $name) => $ai->imageProvider($name)); + } + + /** + * @return array + */ + protected static function capable(callable $resolve): array + { + $ai = app(AiManager::class); + + return collect(array_keys(config('ai.providers', []))) + ->filter(function (string $name) use ($ai, $resolve): bool { + try { + $resolve($ai, $name); + + return true; + } catch (Throwable) { + return false; + } + }) + ->mapWithKeys(fn (string $name): array => [$name => self::label($name)]) + ->all(); + } +} diff --git a/src/Ai/Tools/AboutMyAccount.php b/src/Ai/Tools/AboutMyAccount.php new file mode 100644 index 0000000..652ddb2 --- /dev/null +++ b/src/Ai/Tools/AboutMyAccount.php @@ -0,0 +1,69 @@ +user; + + $account = [ + 'name' => $user->getAttribute('name'), + 'email' => $user->getAttribute('email'), + 'member_since' => $user->getAttribute('created_at')?->toDateString(), + ]; + + // Billing module. + if ($user instanceof BillingOwner) { + $account['plan'] = [ + 'name' => $user->planName() ?? 'none', + 'paid' => $user->hasPaidPlan(), + 'limits' => $user->entitlements()->toArray(), + ]; + } + + // Tenancy module. + if (method_exists($user, 'currentTenant') && method_exists($user, 'tenantRole') && ($tenant = $user->currentTenant()) !== null) { + $account['workspace'] = [ + 'name' => $tenant->getAttribute('name'), + 'role' => $user->tenantRole($tenant)?->value, + ]; + } + + return json_encode($account, JSON_THROW_ON_ERROR); + } + + public function schema(JsonSchema $schema): array + { + return []; + } +} diff --git a/src/Ai/Tools/GenerateImage.php b/src/Ai/Tools/GenerateImage.php new file mode 100644 index 0000000..6d9e163 --- /dev/null +++ b/src/Ai/Tools/GenerateImage.php @@ -0,0 +1,77 @@ +string('prompt')); + + if ($prompt === '') { + return 'No image was described, so none was generated. Ask the user what to draw.'; + } + + if (Usage::reached($this->user, Usage::IMAGES)) { + $limit = Usage::limit($this->user, Usage::IMAGES); + + return "The user has reached their plan's limit of {$limit} image(s) this month, so none was generated. Tell them, and that upgrading their plan raises it."; + } + + $settings = app(AiChatSettings::class); + $config = Demos::enabled() ? ['provider' => Demos::provider()] : [ + 'provider' => $settings->image_provider ?? config('ai-chat.images.provider'), + 'model' => $settings->image_model ?? config('ai-chat.images.model'), + 'quality' => $settings->image_quality ?? config('ai-chat.images.quality'), + ]; + + $path = Image::of($prompt) + ->square() + ->when($config['quality'] ?? null, fn ($image, string $quality) => $image->quality($quality)) + ->generate($config['provider'] ?? null, $config['model'] ?? null) + ->storePublicly(Usage::imageFolder($this->user), 'public'); + + return json_encode([ + 'url' => Storage::disk('public')->url($path), + 'prompt' => $prompt, + ], JSON_THROW_ON_ERROR); + } + + public function schema(JsonSchema $schema): array + { + return [ + 'prompt' => $schema->string()->description('A detailed description of the image: subject, style, colours, composition.')->required(), + ]; + } +} diff --git a/src/Filament/AiChatPlugin.php b/src/Filament/AiChatPlugin.php index c40f517..b191191 100644 --- a/src/Filament/AiChatPlugin.php +++ b/src/Filament/AiChatPlugin.php @@ -4,6 +4,8 @@ use Filament\Contracts\Plugin; use Filament\Panel; +use Modules\AiChat\Filament\Pages\AiChatSettings; +use Modules\AiChat\Filament\Resources\Conversations\ConversationResource; use Saucebase\Core\Filament\ModulePlugin; class AiChatPlugin implements Plugin @@ -20,6 +22,11 @@ public function getId(): string return 'aichat'; } + public function register(Panel $panel): void + { + $panel->pages([AiChatSettings::class])->resources([ConversationResource::class]); + } + public function boot(Panel $panel): void { // diff --git a/src/Filament/Pages/AiChatSettings.php b/src/Filament/Pages/AiChatSettings.php new file mode 100644 index 0000000..78039d8 --- /dev/null +++ b/src/Filament/Pages/AiChatSettings.php @@ -0,0 +1,196 @@ + key map. The fill and + * save hooks convert between the two. + */ +class AiChatSettings extends SettingsPage +{ + protected static ?int $navigationSort = 95; + + protected static string $settings = Settings::class; + + protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedChatBubbleLeftRight; + + public static function canAccess(): bool + { + return auth()->user()?->can('manage ai chat') ?? false; + } + + public static function getNavigationLabel(): string + { + return __('AI chat'); + } + + public function getTitle(): string + { + return __('AI chat'); + } + + /** + * Settings to groups: providers in the order their models appear, then any + * with only a saved key. Keys never travel to the browser. + * + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeFill(array $data): array + { + $data = parent::mutateFormDataBeforeFill($data); + $models = collect($data['models'] ?? []); + + $data['providers'] = $models->pluck('provider') + ->merge(array_keys(array_filter($data['api_keys'] ?? []))) + ->filter() + ->unique() + ->map(fn (string $provider): array => [ + 'provider' => $provider, + 'key' => null, + 'forget_key' => false, + 'models' => $models->where('provider', $provider) + ->map(fn (array $row): array => ['label' => $row['label'], 'model' => $row['model']]) + ->values() + ->all(), + ]) + ->values() + ->all(); + + unset($data['models'], $data['api_keys']); + + return $data; + } + + /** + * Groups back to settings. A blank key keeps the saved one, a filled one + * replaces it, "Remove saved key" or a removed group deletes it. + * + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeSave(array $data): array + { + $data = parent::mutateFormDataBeforeSave($data); + $saved = app(Settings::class)->api_keys; + $groups = collect($data['providers'] ?? []); + + $data['api_keys'] = $groups + ->mapWithKeys(fn (array $group): array => [$group['provider'] => match (true) { + filled($group['key'] ?? null) => $group['key'], + (bool) ($group['forget_key'] ?? false) => null, + default => $saved[$group['provider']] ?? null, + }]) + ->filter() + ->all(); + + $data['models'] = $groups + ->flatMap(fn (array $group): array => collect($group['models'] ?? []) + ->map(fn (array $row): array => ['label' => $row['label'], 'provider' => $group['provider'], 'model' => $row['model']]) + ->all()) + ->values() + ->all(); + + unset($data['providers']); + + // A cleared textarea arrives as null; the setting is a string. + $data['instructions'] ??= ''; + + return $data; + } + + protected function keyPlaceholder(?string $provider): string + { + return match (true) { + filled(app(Settings::class)->api_keys[$provider] ?? null) => __('Saved: leave blank to keep'), + filled(config("ai.providers.{$provider}.key")) => __('From your server environment: leave blank to use it'), + default => __('Paste the key'), + }; + } + + public function form(Schema $schema): Schema + { + return $schema->columns(1)->components([ + Repeater::make('providers') + ->label(__('Providers')) + ->helperText(__('Keys are saved encrypted and never shown again; a key here wins over the one in the server environment. Only models whose provider has a key are offered to users.')) + ->schema([ + Grid::make(2)->schema([ + Select::make('provider') + ->label(__('Provider')) + ->options(fn (): array => Providers::text()) + ->required() + ->distinct() + ->live(), + TextInput::make('key') + ->label(__('API key')) + ->password() + ->autocomplete('new-password') + ->placeholder(fn (Get $get): string => $this->keyPlaceholder($get('provider'))), + ]), + Checkbox::make('forget_key') + ->label(__('Remove saved key')) + ->visible(fn (Get $get): bool => filled(app(Settings::class)->api_keys[$get('provider')] ?? null)), + Repeater::make('models') + ->label(__('Models')) + ->table([ + TableColumn::make(__('Label')), + TableColumn::make(__('Model')), + ]) + ->schema([ + TextInput::make('label')->hiddenLabel()->required(), + TextInput::make('model')->hiddenLabel()->required()->placeholder('gpt-5.6-luna'), + ]) + ->defaultItems(0) + ->reorderable() + ->addActionLabel(__('Add a model')), + ]) + ->itemLabel(fn (array $state): ?string => filled($state['provider'] ?? null) ? Providers::label($state['provider']) : null) + ->collapsible() + ->defaultItems(0) + ->addActionLabel(__('Add a provider')) + ->live(), + Select::make('default_model') + ->label(__('Default model')) + ->helperText(__('Already selected in the chat\'s model picker on every new chat, and used when no model is chosen. If its provider has no key, the first offered model is used instead.')) + // Grouped by provider, as the picker above. + ->options(fn (Get $get): array => collect($get('providers') ?? []) + ->filter(fn ($group) => filled($group['provider'] ?? null)) + ->mapWithKeys(fn ($group) => [Providers::label($group['provider']) => collect($group['models'] ?? []) + ->filter(fn ($row) => filled($row['model'] ?? null)) + ->mapWithKeys(fn ($row) => [$row['model'] => $row['label'] ?: $row['model']]) + ->all()]) + ->filter() + ->all()), + Textarea::make('instructions') + ->label(__('Instructions')) + ->helperText(__('Added to the assistant\'s own instructions: what your product is, the tone to take, what to stay away from.')) + ->rows(5), + Section::make(__('Images')) + ->description(__('Where generate_image sends its prompts. Blank: the AI_CHAT_IMAGE_* settings in .env, then laravel/ai\'s default.')) + ->schema([ + Select::make('image_provider')->label(__('Provider'))->options(fn (): array => Providers::images()), + TextInput::make('image_model')->label(__('Model'))->placeholder('gpt-image-2'), + Select::make('image_quality')->label(__('Quality'))->options(['low' => __('Low'), 'medium' => __('Medium'), 'high' => __('High')]), + ]) + ->columns(3), + ]); + } +} diff --git a/src/Filament/Resources/Conversations/ConversationResource.php b/src/Filament/Resources/Conversations/ConversationResource.php new file mode 100644 index 0000000..f32e9da --- /dev/null +++ b/src/Filament/Resources/Conversations/ConversationResource.php @@ -0,0 +1,85 @@ +user()?->can('manage ai chat') ?? false; + } + + public static function canCreate(): bool + { + return false; + } + + public static function table(Table $table): Table + { + return $table + ->modifyQueryUsing(fn ($query) => $query->with('participant')->withCount(['messages' => fn ($messages) => $messages->where('role', 'user')])) + ->defaultSort('updated_at', 'desc') + ->columns([ + TextColumn::make('title')->label(__('Title'))->searchable()->limit(60), + TextColumn::make('participant.name')->label(__('User')), + TextColumn::make('messages_count')->label(__('Messages'))->numeric(), + TextColumn::make('updated_at')->label(__('Last message'))->since()->sortable(), + ]) + ->recordActions([ViewAction::make()]); + } + + public static function infolist(Schema $schema): Schema + { + return $schema->columns(1)->components([ + TextEntry::make('participant.name')->label(__('User')), + // Ordered by id: laravel/ai keys messages with time-ordered UUIDv7. + RepeatableEntry::make('transcript') + ->label(__('Transcript')) + ->state(fn (Conversation $record) => $record->messages()->whereIn('role', ['user', 'assistant'])->orderBy('id')->get(['role', 'content'])->toArray()) + ->schema([ + TextEntry::make('role')->hiddenLabel()->badge(), + TextEntry::make('content')->hiddenLabel()->markdown(), + ]), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListConversations::route('/'), + 'view' => ViewConversation::route('/{record}'), + ]; + } +} diff --git a/src/Filament/Resources/Conversations/Pages/ListConversations.php b/src/Filament/Resources/Conversations/Pages/ListConversations.php new file mode 100644 index 0000000..6d445d0 --- /dev/null +++ b/src/Filament/Resources/Conversations/Pages/ListConversations.php @@ -0,0 +1,11 @@ +record->getAttribute('title'); + } +} diff --git a/src/Http/Controllers/AiChatController.php b/src/Http/Controllers/AiChatController.php index e1dc2be..4fd6585 100644 --- a/src/Http/Controllers/AiChatController.php +++ b/src/Http/Controllers/AiChatController.php @@ -2,18 +2,456 @@ namespace Modules\AiChat\Http\Controllers; +use Closure; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\JsonResponse; +use Illuminate\Http\RedirectResponse; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Route; +use Illuminate\Support\Str; +use Illuminate\Validation\Rule; use Inertia\Inertia; +use Inertia\Response; +use Laravel\Ai\Messages\Message; +use Laravel\Ai\Models\Conversation; +use Laravel\Ai\Models\ConversationMessage; +use Modules\AiChat\Ai\ChatAgent; +use Modules\AiChat\Ai\Tools\GenerateImage; +use Modules\AiChat\Jobs\GenerateConversationTitle; +use Modules\AiChat\Sessions; +use Modules\AiChat\Settings\AiChatSettings; +use Modules\AiChat\Usage; +use Symfony\Component\HttpFoundation\Response as SymfonyResponse; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Throwable; class AiChatController { + /** Messages a chat opens with, and each "older" page after that. */ + public const int MESSAGES_PER_PAGE = 50; + + /** + * Show a blank chat. No row exists until the first message is sent. + */ + public function index(Request $request): Response + { + return Inertia::render('AiChat::Index', [ + 'conversationId' => null, + 'initialMessages' => [], + 'hasOlder' => false, + 'usage' => fn () => $this->usageProps($request->user()), + ...$this->modelProps(), + ]); + } + /** - * Display a listing of the resource. + * Show an existing conversation belonging to the authenticated user. */ - public function index() + public function show(Request $request, string $conversation): Response { + $owned = $this->ownedConversation($request, $conversation); + + ['messages' => $messages, 'has_older' => $hasOlder] = $this->transcript($owned); + return Inertia::render('AiChat::Index', [ - 'message' => 'Welcome to AiChat Module', - 'module' => 'aichat', + 'conversationId' => $owned->id, + 'initialMessages' => $messages, + 'hasOlder' => $hasOlder, + 'usage' => fn () => $this->usageProps($request->user()), + ...$this->modelProps(), + ]); + } + + /** + * The messages before another one, for the page's "older" loads as the reader scrolls up. + */ + public function history(Request $request, string $conversation): JsonResponse + { + $owned = $this->ownedConversation($request, $conversation); + $validated = $request->validate(['before' => ['nullable', 'string', 'max:36']]); + + return response()->json($this->transcript($owned, $validated['before'] ?? null)); + } + + /** + * A page of the conversation as the page's UI messages, oldest first: each turn's + * text, plus the images generate_image made, so a reopened chat still shows them. + * The newest page, or the one before the message `$before`. Ordered by id: + * laravel/ai keys messages with time-ordered UUIDv7. + * + * @return array{messages: list>}>, has_older: bool} + */ + protected function transcript(Conversation $conversation, ?string $before = null): array + { + // One more than a page, to tell whether there are older ones. + $rows = $conversation->messages() + ->whereIn('role', ['user', 'assistant']) + ->when($before, fn ($query) => $query->where('id', '<', $before)) + ->orderByDesc('id') + ->limit(self::MESSAGES_PER_PAGE + 1) + ->get(['id', 'role', 'content', 'tool_results']); + + $messages = $rows->take(self::MESSAGES_PER_PAGE)->reverse() + ->map(function (ConversationMessage $message): array { + // Cast to an array by the model; decoded here too in case a store keeps raw JSON. + $results = $message->getAttribute('tool_results'); + $images = collect(is_array($results) ? $results : (json_decode((string) $results, true) ?: [])) + ->filter(fn (array $result): bool => ($result['name'] ?? null) === GenerateImage::NAME && empty($result['failed'])) + ->map(fn (array $result): array => [ + 'type' => 'tool-'.GenerateImage::NAME, + 'toolCallId' => $result['id'], + 'state' => 'output-available', + 'input' => $result['arguments'] ?? [], + 'output' => is_string($result['result']) ? $result['result'] : json_encode($result['result']), + ]); + + $text = trim((string) $message->getAttribute('content')); + + return [ + 'id' => (string) $message->getKey(), + 'role' => (string) $message->getAttribute('role'), + 'parts' => [...$images->values()->all(), ...($text === '' ? [] : [['type' => 'text', 'text' => $text]])], + ]; + }) + // A failed reply leaves an assistant row with nothing to show. The next page + // starts before the first message shown, so it skips nothing. + ->reject(fn (array $message): bool => $message['parts'] === []) + ->values() + ->all(); + + return ['messages' => $messages, 'has_older' => $rows->count() > self::MESSAGES_PER_PAGE]; + } + + /** + * This month's messages against the plan's limit, for the counter under the box. + * None without a limit; the upgrade link only when billing is installed. + * + * @return array{used: int, limit: int, upgrade_url: ?string}|null + */ + protected function usageProps(Model $user): ?array + { + $limit = Usage::limit($user, Usage::MESSAGES); + + return $limit === null ? null : [ + 'used' => Usage::messagesThisMonth($user), + 'limit' => $limit, + 'upgrade_url' => Route::has('billing.plans') ? route('billing.plans') : null, + ]; + } + + /** + * The picker's choices. Only labels and names: providers stay on the server. + * + * @return array{models: list, defaultModel: ?string} + */ + protected function modelProps(): array + { + $settings = app(AiChatSettings::class); + + return [ + 'models' => collect($settings->available())->map(fn (array $row): array => ['label' => $row['label'], 'model' => $row['model']])->values()->all(), + 'defaultModel' => $settings->defaultModel(), + ]; + } + + /** + * 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'], + // Ask again: the new answer replaces the last turn instead of adding one. + 'regenerate' => ['boolean'], + // Only what the admin offers: the browser must not pick an arbitrary (expensive) model. + 'model' => ['nullable', 'string', Rule::in(collect(app(AiChatSettings::class)->available())->pluck('model'))], + ]); + + // Before the conversation is created, so a refused first message leaves no empty chat. + if (Usage::reached($request->user(), Usage::MESSAGES)) { + return response()->json([ + 'message' => __('You have used all :limit messages in your plan this month.', ['limit' => Usage::limit($request->user(), Usage::MESSAGES)]), + 'limit' => Usage::limit($request->user(), Usage::MESSAGES), + ], 429); + } + + $conversation = isset($validated['conversation_id']) + ? $this->ownedConversation($request, $validated['conversation_id']) + : $this->startConversation($request, $validated['message']); + + $settings = app(AiChatSettings::class); + $offered = $settings->offered($validated['model'] ?? $settings->defaultModel()); + $replaced = $request->boolean('regenerate') && isset($validated['conversation_id']) ? $this->lastTurn($conversation, $validated['message']) : []; + + $response = (new ChatAgent($request->user())) + ->continue($conversation->id, $request->user()) + ->stream($validated['message'], provider: $offered['provider'] ?? null, model: $offered['model'] ?? null) + // After laravel/ai stores the new turn, so a failed retry keeps the old answer. + ->then(function () use ($conversation, $replaced): void { + $conversation->messages()->whereKey($replaced)->delete(); + $this->retitle($conversation); + }) + ->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); + } + + /** + * Ids of the latest turn: its user message and everything after it. None + * when that message isn't the one asked again: a failed reply stores + * nothing, so retrying it must leave the turn before it alone. + * + * @return list + */ + protected function lastTurn(Conversation $conversation, string $message): array + { + $last = $conversation->messages()->where('role', 'user')->orderByDesc('id')->first(['id', 'content']); + + if ($last === null || trim((string) $last->getAttribute('content')) !== trim($message)) { + return []; + } + + return $conversation->messages()->where('id', '>=', $last->getKey())->pluck('id')->all(); + } + + /** + * The user's chats matching the search box, by title. + */ + public function search(Request $request): JsonResponse + { + $validated = $request->validate(['q' => ['required', 'string', 'max:100']]); + + return response()->json(['data' => Sessions::search($request->user(), $validated['q'])]); + } + + /** + * Show the next page of older chats in the sidebar, from now on in this session. + */ + public function more(): RedirectResponse + { + Sessions::showMore(); + + return back(); + } + + /** + * Rename or pin a chat. Not activity: the list keeps its order. + */ + public function update(Request $request, string $conversation): RedirectResponse + { + $owned = $this->ownedConversation($request, $conversation); + $validated = $request->validate([ + 'title' => ['required_without:pinned', 'string', 'max:100'], + 'pinned' => ['sometimes', 'boolean'], + ]); + + $owned->timestamps = false; + $owned->update([ + ...isset($validated['title']) ? ['title' => $validated['title'], 'renamed_at' => now()] : [], + ...isset($validated['pinned']) ? ['pinned_at' => $validated['pinned'] ? now() : null] : [], + ]); + + return back(); + } + + /** + * Delete a chat and its messages. + */ + public function destroy(Request $request, string $conversation): RedirectResponse + { + $owned = $this->ownedConversation($request, $conversation); + + $owned->messages()->delete(); + $owned->delete(); + + // Stay on the chat that's open, unless it was the one deleted. + $previous = url()->previous(); + $stay = str_starts_with($previous, route('ai-chat.index')) && $previous !== route('ai-chat.show', $owned->id); + + return $stay ? back() : to_route('ai-chat.index'); + } + + /** + * Queue a better title at the user-message counts where the chat may have drifted. + */ + protected function retitle(Conversation $conversation): void + { + $count = $conversation->messages()->where('role', 'user')->count(); + + if (in_array($count, GenerateConversationTitle::RETITLE_AT, true)) { + GenerateConversationTitle::dispatch($conversation->id, $count); + } + } + + /** + * 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 { + // Stop aborts the request, and PHP would end at its next write before + // laravel/ai stores the turn. Finishing keeps the reply. + // ponytail: the model keeps generating after Stop; store the partial text if that cost matters. + ignore_user_abort(true); + // A long answer, or one with tool calls, can take minutes; PHP's default 30 seconds ends it mid-stream. + set_time_limit(300); + $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/Jobs/GenerateConversationTitle.php b/src/Jobs/GenerateConversationTitle.php new file mode 100644 index 0000000..40cc811 --- /dev/null +++ b/src/Jobs/GenerateConversationTitle.php @@ -0,0 +1,111 @@ + + */ + public const array RETITLE_AT = [3, 10, 25, 60]; + + public const int USER_MESSAGE_THRESHOLD = 3; + + /** How many recent messages to summarise. */ + protected const int TRANSCRIPT_SIZE = 12; + + public int $tries = 3; + + public int $uniqueFor = 3600; + + /** @var array */ + public array $backoff = [5, 30]; + + public function __construct( + public string $conversationId, + public int $atMessageCount = self::USER_MESSAGE_THRESHOLD, + ) {} + + public function handle(ConversationTitleAgent $agent): void + { + $conversation = Conversation::query()->find($this->conversationId); + + // A title the user chose is theirs to keep. + if ($conversation === null || $conversation->getAttribute('renamed_at') !== null || $this->userMessageCount($conversation) < self::USER_MESSAGE_THRESHOLD) { + return; + } + + // Read oldest-first and skip to the tail, rather than ordering DESC and + // reversing: timestamps have second precision, so same-second messages + // have no tiebreaker and reversing a DESC read scrambles them. + $messages = $conversation->messages()->whereIn('role', ['user', 'assistant']); + + $transcript = (clone $messages) + ->oldest() + ->skip(max(0, $messages->count() - self::TRANSCRIPT_SIZE)) + ->take(self::TRANSCRIPT_SIZE) + ->get(['role', 'content']) + ->map(function (ConversationMessage $message): string { + $role = $message->getAttribute('role'); + $content = $message->getAttribute('content'); + + return Str::headline(is_string($role) ? $role : '') + .': '.(is_string($content) ? $content : ''); + }) + ->implode("\n\n"); + + $response = $agent->prompt($transcript, provider: Demos::enabled() ? Demos::provider() : null); + $title = Str::of($response->text) + ->squish() + ->trim('"\'') + ->limit(100) + ->toString(); + + if ($title !== '') { + // Renaming is not activity. The sidebar orders by updated_at, which + // laravel/ai touches on every stored message, so bumping it here + // would shove a silent conversation to the top of the list. + $conversation->timestamps = false; + $conversation->update(['title' => $title]); + } + } + + public function uniqueId(): string + { + // Includes the milestone: keyed on the conversation alone, the run at + // three messages would swallow the run at ten for a whole $uniqueFor. + return $this->conversationId.':'.$this->atMessageCount; + } + + public function failed(?Throwable $exception): void + { + Log::warning('Conversation title generation failed.', [ + 'conversation_id' => $this->conversationId, + 'exception' => $exception, + ]); + } + + protected function userMessageCount(Conversation $conversation): int + { + return $conversation->messages()->where('role', 'user')->count(); + } +} diff --git a/src/Providers/AiChatServiceProvider.php b/src/Providers/AiChatServiceProvider.php index 941e8c8..70f78f3 100644 --- a/src/Providers/AiChatServiceProvider.php +++ b/src/Providers/AiChatServiceProvider.php @@ -2,11 +2,40 @@ namespace Modules\AiChat\Providers; +use Illuminate\Support\Facades\Auth; +use Inertia\Inertia; +use Laravel\Ai\AiManager; +use Modules\AiChat\Jobs\GenerateConversationTitle; +use Modules\AiChat\Sessions; use Saucebase\Core\Providers\ModuleServiceProvider; class AiChatServiceProvider extends ModuleServiceProvider { - protected array $providers = [ - // YourServiceProvider::class, - ]; + public function boot(): void + { + parent::boot(); + + $this->app->afterResolving(AiManager::class, fn () => ApplyProviderKeys::apply()); + } + + /** + * The session list: the newest chats and the pinned ones; "Show more" + * (`ai-chat.sessions.more`) raises how many. Shared, as the app sidebar shows it + * on every page when `ai-chat.sessions` is `sidebar`; with `page` only the chat + * pages need it, and the rest skip the query. + */ + protected function shareInertiaData(): void + { + // The page reloads the list a few seconds after these counts, when a new title may have landed. + Inertia::share('chat.retitle_at', GenerateConversationTitle::RETITLE_AT); + + Inertia::share('chat.sessions_in', fn (): string => config('ai-chat.sessions')); + + Inertia::share('chat.sessions', function (): array { + $user = Auth::user(); + $needed = config('ai-chat.sessions') === 'sidebar' || request()->routeIs('ai-chat.*'); + + return $user === null || ! $needed ? ['data' => [], 'has_more' => false] : Sessions::shared($user); + }); + } } diff --git a/src/Providers/ApplyProviderKeys.php b/src/Providers/ApplyProviderKeys.php new file mode 100644 index 0000000..ac8d16c --- /dev/null +++ b/src/Providers/ApplyProviderKeys.php @@ -0,0 +1,30 @@ +api_keys; + } catch (Throwable) { + // Settings not migrated yet (install, a fresh test database): config keys stand. + return; + } + + foreach (array_filter($keys) as $provider => $key) { + config(["ai.providers.{$provider}.key" => $key]); + } + } +} diff --git a/src/Sessions.php b/src/Sessions.php new file mode 100644 index 0000000..a9d74d3 --- /dev/null +++ b/src/Sessions.php @@ -0,0 +1,77 @@ +>, has_more: bool} + */ + public static function shared(object $user): array + { + $shown = self::shown(); + // One more than shown, to tell whether there are more. + $recent = self::owned($user)->whereNull('pinned_at')->latest('updated_at')->limit($shown + 1)->get(self::COLUMNS); + $pinned = self::owned($user)->whereNotNull('pinned_at')->latest('updated_at')->get(self::COLUMNS); + + return [ + 'data' => [...$pinned->toArray(), ...$recent->take($shown)->toArray()], + 'has_more' => $recent->count() > $shown, + ]; + } + + public const SEARCH_LIMIT = 20; + + /** + * The user's chats whose title holds the text, newest first; `%` and `_` match themselves. + * + * @return list> + */ + public static function search(object $user, string $text): array + { + // `!` escapes: SQLite has no default escape character, and Postgres's LIKE is case-sensitive. + // `!` first, so the escapes added after it aren't doubled. + $like = '%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], mb_strtolower($text, 'UTF-8')).'%'; + + return self::owned($user) + ->whereRaw("LOWER(title) LIKE ? ESCAPE '!'", [$like]) + ->latest('updated_at') + ->limit(self::SEARCH_LIMIT) + ->get(self::COLUMNS) + ->toArray(); + } + + // ponytail: grows a page per click with no ceiling; a user who opens hundreds gets them on every page. + public static function showMore(): void + { + session()->put(self::SHOWN, self::shown() + self::PER_PAGE); + } + + protected static function shown(): int + { + return (int) session(self::SHOWN, self::PER_PAGE); + } + + /** @return Builder */ + protected static function owned(object $user): Builder + { + return Conversation::query() + ->where('participant_type', Conversation::participantType($user)) + ->where('participant_id', Conversation::participantKey($user)); + } +} diff --git a/src/Settings/AiChatSettings.php b/src/Settings/AiChatSettings.php new file mode 100644 index 0000000..6473082 --- /dev/null +++ b/src/Settings/AiChatSettings.php @@ -0,0 +1,92 @@ +api_keys[$provider] ?? null) || filled(config("ai.providers.{$provider}.key")); + } + + /** + * The offered models whose provider has a key: what users may pick. In + * test mode, the demos instead: nothing reaches a paid provider. + * + * @return list> + */ + public function available(): array + { + if (Demos::enabled()) { + return Demos::models(); + } + + return collect($this->models)->filter(fn (array $row): bool => $this->hasKey($row['provider'] ?? null))->values()->all(); + } + + /** + * The model a chat starts on: the admin's default while its provider has a + * key, else the first offered model; null leaves laravel/ai's default. + */ + public function defaultModel(): ?string + { + $available = collect($this->available())->pluck('model'); + + return $available->contains($this->default_model) ? $this->default_model : $available->first(); + } + + /** + * The offered row for a model name, or null when it isn't offered. + * + * @return array{label: string, provider: ?string, model: string}|null + */ + public function offered(?string $model): ?array + { + return collect($this->available())->firstWhere('model', $model); + } +} diff --git a/src/Usage.php b/src/Usage.php new file mode 100644 index 0000000..fffc3ff --- /dev/null +++ b/src/Usage.php @@ -0,0 +1,80 @@ +entitlements()->declares($key)) { + return null; + } + + return $user->planLimit($key); + } + + public static function messagesThisMonth(Model $user): int + { + return ConversationMessage::query() + ->where('participant_type', Conversation::participantType($user)) + ->where('participant_id', Conversation::participantKey($user)) + ->where('role', 'user') + ->where('created_at', '>=', now()->startOfMonth()) + ->count(); + } + + public static function imagesThisMonth(Model $user): int + { + return count(Storage::disk('public')->files(self::imageFolder($user))); + } + + /** + * Where this month's images for the user are stored, so counting them is a folder listing. + */ + public static function imageFolder(Model $user): string + { + return 'ai-chat/images/'.$user->getKey().'/'.now()->format('Y-m'); + } + + /** + * Whether the user has used up a monthly allowance. + */ + public static function reached(Model $user, string $key): bool + { + $limit = self::limit($user, $key); + + if ($limit === null) { + return false; + } + + $used = $key === self::IMAGES ? self::imagesThisMonth($user) : self::messagesThisMonth($user); + + return $used >= $limit; + } +} diff --git a/tests/Feature/AdminTest.php b/tests/Feature/AdminTest.php new file mode 100644 index 0000000..370590e --- /dev/null +++ b/tests/Feature/AdminTest.php @@ -0,0 +1,156 @@ +withoutVite(); + + config(['ai-chat.test_mode' => false]); + // Only models whose provider has a key are offered; these rows use the default provider. + config(['ai.providers.'.config('ai.default').'.key' => 'test-key']); + $this->seed(DatabaseSeeder::class); + } + + /** + * @param list $models + */ + protected function offer(array $models, ?string $default = null, string $instructions = ''): void + { + $settings = app(AiChatSettings::class); + $settings->models = $models; + $settings->default_model = $default; + $settings->instructions = $instructions; + $settings->save(); + } + + protected function manager(): User + { + $user = User::factory()->create(); + $user->givePermissionTo(['access admin panel', 'manage ai chat']); + + return $user; + } + + public function test_a_fresh_install_has_no_instructions_and_no_saved_keys(): void + { + $settings = app(AiChatSettings::class); + + $this->assertSame('', $settings->instructions); + $this->assertSame([], $settings->api_keys); + } + + public function test_the_admins_instructions_reach_the_agent(): void + { + $this->offer([], instructions: 'Always answer like a pirate.'); + + $this->assertStringContainsString('Always answer like a pirate.', (string) (new ChatAgent)->instructions()); + } + + public function test_the_chat_page_lists_the_offered_models(): void + { + $this->offer([['label' => 'Fast', 'provider' => null, 'model' => 'fast-1'], ['label' => 'Smart', 'provider' => null, 'model' => 'smart-1']], default: 'smart-1'); + + $this->actingAs(User::factory()->create()) + ->get(route('ai-chat.index')) + ->assertInertia(fn ($page) => $page + ->where('models', [['label' => 'Fast', 'model' => 'fast-1'], ['label' => 'Smart', 'model' => 'smart-1']]) + ->where('defaultModel', 'smart-1') + ); + } + + public function test_the_chosen_model_answers(): void + { + $this->offer([['label' => 'Smart', 'provider' => null, 'model' => 'smart-1']]); + // The fake hands the closure (prompt, attachments, provider, model). + Ai::fakeAgent(ChatAgent::class, fn ($prompt, $attachments, $provider, string $model): string => "answered by {$model}"); + + $stream = $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hi', 'model' => 'smart-1']) + ->streamedContent(); + + $this->assertStringContainsString('smart-1', $stream); + } + + public function test_a_model_that_is_not_offered_is_refused(): void + { + $this->offer([['label' => 'Smart', 'provider' => null, 'model' => 'smart-1']]); + + $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hi', 'model' => 'expensive-9']) + ->assertSessionHasErrors('model'); + } + + public function test_managers_can_save_the_settings(): void + { + $this->actingAs($this->manager()); + + Livewire::test(SettingsPage::class) + ->fillForm([ + 'instructions' => 'Be brief.', + 'providers' => [['provider' => 'openai', 'key' => '', 'forget_key' => false, 'models' => [['label' => 'Smart', 'model' => 'smart-1']]]], + 'default_model' => 'smart-1', + ]) + ->call('save') + ->assertHasNoFormErrors(); + + $settings = new AiChatSettings; + $this->assertSame('Be brief.', $settings->instructions); + $this->assertSame('smart-1', $settings->default_model); + $this->assertSame('openai', $settings->models[0]['provider']); + } + + public function test_panel_access_alone_does_not_reach_the_chat_admin(): void + { + $user = User::factory()->create(); + $user->givePermissionTo('access admin panel'); + + $this->actingAs($user)->get(SettingsPage::getUrl())->assertForbidden(); + $this->actingAs($user)->get(ConversationResource::getUrl())->assertForbidden(); + } + + public function test_managers_can_read_a_conversation(): void + { + $owner = User::factory()->create(['name' => 'Ada']); + $conversation = Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $owner->getMorphClass(), + 'participant_id' => $owner->getKey(), + 'title' => 'Launch email', + ]); + $conversation->messages()->create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $owner->getMorphClass(), + 'participant_id' => $owner->getKey(), + 'agent' => ChatAgent::class, + 'role' => 'user', + 'content' => 'Draft our launch email', + 'attachments' => '[]', 'tool_calls' => '[]', 'tool_results' => '[]', 'usage' => '[]', 'meta' => '[]', + ]); + + $this->actingAs($this->manager()); + + $this->get(ConversationResource::getUrl())->assertOk()->assertSee('Launch email')->assertSee('Ada'); + $this->get(ConversationResource::getUrl('view', ['record' => $conversation]))->assertOk()->assertSee('Draft our launch email'); + } +} diff --git a/tests/Feature/ChatStreamTest.php b/tests/Feature/ChatStreamTest.php new file mode 100644 index 0000000..14990dd --- /dev/null +++ b/tests/Feature/ChatStreamTest.php @@ -0,0 +1,329 @@ +withoutVite(); + + // A local .env may turn test mode on; these tests need the agent. + config(['ai-chat.test_mode' => false]); + } + + public function test_guests_cannot_reach_the_chat_page(): void + { + $this->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'); + // nginx (Herd, Forge) buffers responses by default: the reply would arrive in one piece. + $response->assertHeader('X-Accel-Buffering', 'no'); + + $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.data', 1) + ->where('chat.sessions.data.0.title', 'Mine') + ); + } + + public function test_in_the_app_sidebar_the_session_list_is_shared_on_every_signed_in_page(): void + { + config(['ai-chat.sessions' => 'sidebar']); + $user = User::factory()->create(); + $this->conversationFor($user, 'Mine'); + + // The history lives in the app sidebar, which every signed-in page renders. + Route::middleware(['web', 'auth'])->get('/some-app-page', fn () => Inertia::render('Somewhere')); + + $this->actingAs($user) + ->get('/some-app-page') + ->assertInertia(fn ($page) => $page->where('chat.sessions.data.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/ConversationTitleTest.php b/tests/Feature/ConversationTitleTest.php new file mode 100644 index 0000000..f4a6290 --- /dev/null +++ b/tests/Feature/ConversationTitleTest.php @@ -0,0 +1,148 @@ + false]); + } + + public function test_title_generation_is_queued_after_the_third_user_message(): void + { + Queue::fake([GenerateConversationTitle::class]); + Ai::fakeAgent(ChatAgent::class, ['First reply.', 'Second reply.', 'Third reply.', 'Fourth reply.']); + + $user = User::factory()->create(); + $conversationId = $this->sendMessages($user, [ + 'First message', + 'Second message', + ]); + + Queue::assertNotPushed(GenerateConversationTitle::class); + + $this->sendMessages($user, ['Third message'], $conversationId); + + Queue::assertPushed( + GenerateConversationTitle::class, + fn (GenerateConversationTitle $job): bool => $job->conversationId === $conversationId, + ); + + $this->sendMessages($user, ['Fourth message'], $conversationId); + + // Four is not a milestone, so no second job. + Queue::assertPushed(GenerateConversationTitle::class, 1); + } + + public function test_the_title_is_regenerated_at_later_milestones(): void + { + Queue::fake([GenerateConversationTitle::class]); + Ai::fakeAgent(ChatAgent::class, array_fill(0, 12, 'Reply.')); + + $user = User::factory()->create(); + $conversationId = $this->sendMessages($user, ['Message 1', 'Message 2', 'Message 3']); + + for ($i = 4; $i <= 10; $i++) { + $this->sendMessages($user, ["Message {$i}"], $conversationId); + } + + // Milestones 3 and 10 both fire, and carry distinct unique ids so the + // first does not suppress the second. + Queue::assertPushed(GenerateConversationTitle::class, 2); + Queue::assertPushed( + GenerateConversationTitle::class, + fn (GenerateConversationTitle $job): bool => $job->atMessageCount === 10 + && $job->uniqueId() === $conversationId.':10', + ); + } + + public function test_renaming_a_conversation_does_not_reorder_the_sidebar(): void + { + // Without this the sync queue runs the job inline on the third message, + // consuming the single faked title before the assertion below. + Queue::fake([GenerateConversationTitle::class]); + Ai::fakeAgent(ChatAgent::class, ['Reply one.', 'Reply two.', 'Reply three.']); + Ai::fakeAgent(ConversationTitleAgent::class, ['A better title']); + + $user = User::factory()->create(); + $conversationId = $this->sendMessages($user, ['One', 'Two', 'Three']); + + $before = Conversation::query()->findOrFail($conversationId)->getAttribute('updated_at'); + + $this->travel(10)->minutes(); + (new GenerateConversationTitle($conversationId))->handle(new ConversationTitleAgent); + + $conversation = Conversation::query()->findOrFail($conversationId); + + $this->assertSame('A better title', $conversation->getAttribute('title')); + $this->assertEquals( + $before, + $conversation->getAttribute('updated_at'), + 'Renaming must not touch updated_at, which orders the session list.', + ); + } + + public function test_the_title_agent_renames_the_conversation_from_its_first_three_turns(): void + { + Queue::fake([GenerateConversationTitle::class]); + Ai::fakeAgent(ChatAgent::class, ['First reply.', 'Second reply.', 'Third reply.']); + Ai::fakeAgent(ConversationTitleAgent::class, ['Laravel queue monitoring']); + + $user = User::factory()->create(); + $conversationId = $this->sendMessages($user, [ + 'How do I monitor my Laravel queues?', + 'I am using the database driver.', + 'Can I see failed jobs too?', + ]); + + (new GenerateConversationTitle($conversationId))->handle(new ConversationTitleAgent); + + $this->assertSame( + 'Laravel queue monitoring', + Conversation::query()->findOrFail($conversationId)->getAttribute('title'), + ); + + Ai::assertAgentWasPrompted( + ConversationTitleAgent::class, + fn ($prompt): bool => $prompt->contains('How do I monitor my Laravel queues?') + && $prompt->contains('Can I see failed jobs too?'), + ); + } + + /** + * @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/DemoProviderTest.php b/tests/Feature/DemoProviderTest.php new file mode 100644 index 0000000..34832ca --- /dev/null +++ b/tests/Feature/DemoProviderTest.php @@ -0,0 +1,159 @@ + true]); + Storage::fake('public'); + $this->withoutVite(); + } + + /** + * @return Collection> + */ + protected function frames(TestResponse $response): Collection + { + return collect(explode("\n\n", $response->streamedContent())) + ->map(fn (string $line): mixed => json_decode(substr(trim($line), 6), true)) + ->filter(fn (mixed $frame): bool => is_array($frame)) + ->values(); + } + + protected function ask(string $demo, ?User $user = null): TestResponse + { + return $this->actingAs($user ?? User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hello?', 'model' => $demo]); + } + + public function test_every_demo_file_ends_in_a_reply(): void + { + $this->assertNotEmpty(Demos::names()); + + foreach (Demos::names() as $name) { + $demo = Demos::load($name); + + $this->assertNotEmpty($demo['description'], $name); + $this->assertSame('assistant', end($demo['messages'])['role'], $name); + } + } + + public function test_every_demo_heading_starts_its_own_line(): void + { + foreach (Demos::names() as $name) { + foreach (Demos::load($name)['messages'] as $message) { + foreach ($message['parts'] as $part) { + if ($part['type'] === 'text') { + $this->assertDoesNotMatchRegularExpression('/[^\n#]#{1,6} /', $part['text'], "{$name}: a heading runs on from the line before it"); + } + } + } + } + } + + public function test_test_mode_offers_the_demos_as_models(): void + { + $this->actingAs(User::factory()->create())->get(route('ai-chat.index')) + ->assertInertia(fn ($page) => $page + ->where('models', fn (Collection $models) => $models->pluck('model')->sort()->values()->all() === collect(Demos::names())->sort()->values()->all()) + ->where('defaultModel', 'reply') + ); + } + + public function test_a_demo_reply_streams_its_reasoning_and_text(): void + { + $frames = $this->frames($this->ask('reply')); + + $this->assertContains('reasoning-delta', $frames->pluck('type')); + $this->assertStringContainsString('test mode', $frames->where('type', 'text-delta')->pluck('delta')->implode('')); + $this->assertSame('finish', $frames->last()['type']); + } + + public function test_the_tools_a_demo_calls_really_run(): void + { + $user = User::factory()->create(['email' => 'cook@example.com']); + $frames = $this->frames($this->ask('steps', $user)); + + $this->assertCount(2, $frames->where('type', 'tool-input-available')); + + $outputs = $frames->where('type', 'tool-output-available')->pluck('output'); + $this->assertStringContainsString('cook@example.com', $outputs->first()); + + $image = json_decode($outputs->last(), true); + $this->assertStringEndsWith('.png', $image['url']); + $this->assertCount(1, Storage::disk('public')->allFiles()); + } + + public function test_a_search_demo_streams_its_sources(): void + { + $sources = $this->frames($this->ask('sources'))->where('type', 'source-url'); + + $this->assertCount(3, $sources); + $this->assertStringStartsWith('https://', $sources->first()['url']); + } + + public function test_a_call_to_a_tool_that_does_not_exist_fails_that_step_only(): void + { + $frames = $this->frames($this->ask('tool_error')); + + $this->assertSame(1, $frames->where('type', 'tool-output-error')->count()); + $this->assertSame('finish', $frames->last()['type']); + } + + public function test_a_failing_demo_never_leaks_the_provider_wording(): void + { + $body = $this->ask('failure')->streamedContent(); + + $this->assertStringNotContainsString('org-EXAMPLE0000', $body); + $this->assertStringContainsString('The assistant could not be reached', $body); + } + + public function test_titles_come_from_the_demo_provider_too(): void + { + $user = User::factory()->create(); + $id = null; + + // The job names a chat from its third user message on. + foreach (['A weekend in Lisbon', 'And the food?', 'Thanks!'] as $message) { + $response = $this->actingAs($user)->post(route('ai-chat.stream'), array_filter(['message' => $message, 'model' => 'reply', 'conversation_id' => $id])); + $response->streamedContent(); + $id = $response->headers->get('X-Conversation-Id'); + } + + Conversation::query()->whereKey($id)->update(['title' => 'Untitled']); + (new GenerateConversationTitle($id, 3))->handle(app(ConversationTitleAgent::class)); + + // The first line of the transcript only: the user's first message. + $this->assertSame('A weekend in Lisbon', (string) Conversation::query()->findOrFail($id)->title); + } + + public function test_production_never_offers_the_demos(): void + { + $this->app['env'] = 'production'; + + $this->assertNotContains(Demos::PROVIDER, array_column(app(AiChatSettings::class)->available(), 'provider')); + $this->assertFalse(config()->has('ai.providers.demo')); + } +} diff --git a/tests/Feature/HistoryTest.php b/tests/Feature/HistoryTest.php new file mode 100644 index 0000000..c026315 --- /dev/null +++ b/tests/Feature/HistoryTest.php @@ -0,0 +1,174 @@ +withoutVite(); + } + + /** + * A chat of $count messages, "Message 1" the oldest, alternating user and assistant. + */ + protected function longChat(User $user, int $count): string + { + $conversation = Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'title' => 'Long', + ]); + + foreach (range(1, $count) as $n) { + $conversation->messages()->create([ + // Spaced a millisecond apart: ids generated in the same millisecond have no set order. + 'id' => (string) Str::uuid7(now()->subSeconds(10)->addMilliseconds($n)), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'agent' => ChatAgent::class, + 'role' => $n % 2 ? 'user' : 'assistant', + 'content' => "Message {$n}", + 'attachments' => '[]', + 'tool_calls' => '[]', + 'tool_results' => '[]', + 'usage' => '[]', + 'meta' => '[]', + ]); + } + + return $conversation->id; + } + + /** @param list> $messages */ + protected function texts(array $messages): array + { + return array_map(fn (array $message): string => $message['parts'][0]['text'], $messages); + } + + public function test_a_long_chat_opens_on_its_latest_messages(): void + { + $user = User::factory()->create(); + $id = $this->longChat($user, 120); + + $props = $this->actingAs($user)->get(route('ai-chat.show', $id))->viewData('page')['props']; + + $this->assertSame(array_map(fn ($n) => "Message {$n}", range(71, 120)), $this->texts($props['initialMessages'])); + $this->assertTrue($props['hasOlder']); + $this->assertSame(AiChatController::MESSAGES_PER_PAGE, 50); + } + + public function test_older_messages_load_a_page_at_a_time(): void + { + $user = User::factory()->create(); + $id = $this->longChat($user, 120); + $first = $this->actingAs($user)->get(route('ai-chat.show', $id))->viewData('page')['props']['initialMessages'][0]['id']; + + $page = $this->actingAs($user)->getJson(route('ai-chat.history', ['conversation' => $id, 'before' => $first]))->assertOk(); + $this->assertSame(array_map(fn ($n) => "Message {$n}", range(21, 70)), $this->texts($page->json('messages'))); + $this->assertTrue($page->json('has_older')); + + $last = $this->actingAs($user)->getJson(route('ai-chat.history', ['conversation' => $id, 'before' => $page->json('messages.0.id')])); + $this->assertSame(array_map(fn ($n) => "Message {$n}", range(1, 20)), $this->texts($last->json('messages'))); + $this->assertFalse($last->json('has_older')); + } + + public function test_a_short_chat_has_nothing_older(): void + { + $user = User::factory()->create(); + + $this->actingAs($user)->get(route('ai-chat.show', $this->longChat($user, 4))) + ->assertInertia(fn ($page) => $page->has('initialMessages', 4)->where('hasOlder', false)); + } + + public function test_no_one_else_reads_a_chats_history(): void + { + $id = $this->longChat(User::factory()->create(), 4); + + $this->actingAs(User::factory()->create())->getJson(route('ai-chat.history', ['conversation' => $id]))->assertNotFound(); + } + + public function test_a_test_mode_chat_reopens_with_its_history(): void + { + config(['ai-chat.test_mode' => true]); + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post(route('ai-chat.stream'), ['message' => 'Show me Markdown', 'model' => 'markdown']); + $response->streamedContent(); + $id = $response->headers->get('X-Conversation-Id'); + + $this->actingAs($user)->get(route('ai-chat.show', $id))->assertInertia(fn ($page) => $page + ->has('initialMessages', 2) + ->where('initialMessages.0.parts.0.text', 'Show me Markdown') + ->where('initialMessages.1.role', 'assistant') + ->where('initialMessages.1.parts.0.text', fn (string $text) => str_contains($text, '| Plan | Messages |')) + ); + } + + public function test_a_failed_reply_stores_nothing_as_a_real_one(): void + { + config(['ai-chat.test_mode' => true]); + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post(route('ai-chat.stream'), ['message' => 'Hello?', 'model' => 'failure']); + $response->streamedContent(); + + $this->actingAs($user)->get(route('ai-chat.show', $response->headers->get('X-Conversation-Id'))) + ->assertInertia(fn ($page) => $page->has('initialMessages', 0)); + } + + public function test_a_reopened_chat_shows_its_generated_images(): void + { + $user = User::factory()->create(); + $conversation = Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'title' => 'Kites', + ]); + + $row = fn (string $role, string $content, array $toolResults = []) => $conversation->messages()->create([ + 'id' => (string) Str::uuid7(), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'agent' => ChatAgent::class, + 'role' => $role, + 'content' => $content, + 'attachments' => '[]', + 'tool_calls' => '[]', + 'tool_results' => json_encode($toolResults), + 'usage' => '[]', + 'meta' => '[]', + ]); + + $row('user', 'Draw a red kite'); + $row('assistant', 'Here is your kite.', [[ + 'id' => 'call-1', + 'name' => 'generate_image', + 'arguments' => ['prompt' => 'A red kite'], + 'result' => json_encode(['url' => '/storage/ai-chat/images/1/2026-11/kite.png', 'prompt' => 'A red kite']), + 'result_id' => null, + ]]); + + $this->actingAs($user)->get(route('ai-chat.show', $conversation->id))->assertInertia(fn ($page) => $page + ->has('initialMessages', 2) + ->where('initialMessages.1.parts.0.type', 'tool-generate_image') + ->where('initialMessages.1.parts.0.state', 'output-available') + ->where('initialMessages.1.parts.0.output', fn (string $output) => str_contains($output, 'kite.png')) + ->where('initialMessages.1.parts.1.text', 'Here is your kite.') + ); + } +} 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/PlacementTest.php b/tests/Feature/PlacementTest.php new file mode 100644 index 0000000..3353039 --- /dev/null +++ b/tests/Feature/PlacementTest.php @@ -0,0 +1,129 @@ +withoutVite(); + // Any other page of the app. + Route::middleware(['web', 'auth'])->get('/_placement-other', fn () => Inertia::render('Other')); + } + + protected function chat(User $user, string $title): Conversation + { + return Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->id, + 'title' => $title, + ]); + } + + /** @return array */ + protected function props(User $user, string $url): array + { + return $this->actingAs($user)->get($url)->assertOk()->viewData('page')['props']; + } + + /** @return list */ + protected function mainSlugs(array $props): array + { + return collect($props['navigation']['main'] ?? [])->pluck('slug')->all(); + } + + public function test_the_list_lives_on_the_chat_page_by_default(): void + { + config(['ai-chat.sessions' => 'page']); + $user = User::factory()->create(); + $chat = $this->chat($user, 'Trip plans'); + + $props = $this->props($user, route('ai-chat.show', $chat->id)); + + $this->assertSame('page', $props['chat']['sessions_in']); + $this->assertSame(['Trip plans'], collect($props['chat']['sessions']['data'])->pluck('title')->all()); + $this->assertContains('chat', $this->mainSlugs($props)); + } + + public function test_the_chat_item_stays_active_on_every_chat(): void + { + config(['ai-chat.sessions' => 'page']); + $user = User::factory()->create(); + $chat = $this->chat($user, 'Trip plans'); + + $item = collect($this->props($user, route('ai-chat.show', $chat->id))['navigation']['main'])->firstWhere('slug', 'chat'); + + $this->assertTrue($item['active']); + $this->assertSame(route('ai-chat.index'), $item['url']); + } + + public function test_other_pages_skip_the_list_when_it_lives_on_the_chat_page(): void + { + config(['ai-chat.sessions' => 'page']); + $user = User::factory()->create(); + $this->chat($user, 'Trip plans'); + + $props = $this->props($user, '/_placement-other'); + + $this->assertSame([], $props['chat']['sessions']['data']); + } + + public function test_in_the_sidebar_the_list_is_on_every_page_and_there_is_no_chat_item(): void + { + config(['ai-chat.sessions' => 'sidebar']); + $user = User::factory()->create(); + $this->chat($user, 'Trip plans'); + + $props = $this->props($user, '/_placement-other'); + + $this->assertSame('sidebar', $props['chat']['sessions_in']); + $this->assertSame(['Trip plans'], collect($props['chat']['sessions']['data'])->pluck('title')->all()); + $this->assertNotContains('chat', $this->mainSlugs($props)); + } + + public function test_search_finds_the_users_own_chats_by_title(): void + { + $user = User::factory()->create(); + $this->chat($user, 'Trip plans for May'); + $this->chat($user, 'Tax questions'); + $this->chat(User::factory()->create(), 'Trip to Rome'); + + $this->actingAs($user)->getJson(route('ai-chat.sessions.search', ['q' => 'trip'])) + ->assertOk() + ->assertJsonCount(1, 'data') + ->assertJsonPath('data.0.title', 'Trip plans for May'); + } + + public function test_search_treats_wildcards_as_text(): void + { + $user = User::factory()->create(); + $this->chat($user, '100% done'); + $this->chat($user, 'Anything'); + + $this->actingAs($user)->getJson(route('ai-chat.sessions.search', ['q' => '%'])) + ->assertOk() + ->assertJsonCount(1, 'data'); + } + + public function test_search_needs_a_query(): void + { + $this->actingAs(User::factory()->create())->getJson(route('ai-chat.sessions.search'))->assertUnprocessable(); + } +} diff --git a/tests/Feature/ProviderCatalogTest.php b/tests/Feature/ProviderCatalogTest.php new file mode 100644 index 0000000..31a73ea --- /dev/null +++ b/tests/Feature/ProviderCatalogTest.php @@ -0,0 +1,72 @@ +assertArrayHasKey('openai', $text); + $this->assertArrayHasKey('anthropic', $text); + $this->assertArrayHasKey('gemini', $text); + + // Embeddings, reranking and audio only: laravel/ai has no text provider for them. + foreach (['cohere', 'jina', 'voyageai', 'eleven'] as $provider) { + $this->assertArrayNotHasKey($provider, $text, $provider); + } + } + + public function test_only_providers_that_make_images_are_offered_for_images(): void + { + $images = Providers::images(); + + $this->assertArrayHasKey('openai', $images); + $this->assertArrayHasKey('gemini', $images); + $this->assertArrayNotHasKey('anthropic', $images); + $this->assertArrayNotHasKey('cohere', $images); + } + + public function test_providers_have_their_own_names(): void + { + $this->assertSame('OpenAI', Providers::label('openai')); + $this->assertSame('OpenAI-compatible', Providers::label('openai-compatible')); + $this->assertSame('xAI', Providers::label('xai')); + $this->assertSame('DeepSeek', Providers::label('deepseek')); + $this->assertSame('OpenRouter', Providers::label('openrouter')); + // A provider added to config/ai.php later still gets a readable name. + $this->assertSame('Some New Lab', Providers::label('some-new-lab')); + } + + public function test_the_settings_form_refuses_providers_that_cannot_do_the_job(): void + { + $this->seed(DatabaseSeeder::class); + $user = User::factory()->create(); + $user->givePermissionTo(['access admin panel', 'manage ai chat']); + $this->actingAs($user); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->fillForm([ + 'default_model' => null, + 'providers' => [['provider' => 'cohere', 'key' => '', 'forget_key' => false, 'models' => []]], + 'image_provider' => 'anthropic', + ]) + ->call('save') + ->assertHasFormErrors(['providers.0.provider' => 'in', 'image_provider' => 'in']); + + $repeater(); + } +} diff --git a/tests/Feature/ProvidersTest.php b/tests/Feature/ProvidersTest.php new file mode 100644 index 0000000..558500b --- /dev/null +++ b/tests/Feature/ProvidersTest.php @@ -0,0 +1,296 @@ +withoutVite(); + config(['ai-chat.test_mode' => false]); + config(['ai.providers.openai.key' => null, 'ai.providers.anthropic.key' => null, 'ai.providers.gemini.key' => null]); + } + + /** + * @param array $values + */ + protected function settings(array $values): void + { + $settings = app(AiChatSettings::class); + + foreach ($values as $key => $value) { + $settings->{$key} = $value; + } + + $settings->save(); + } + + protected function manager(): User + { + $this->seed(DatabaseSeeder::class); + $user = User::factory()->create(); + $user->givePermissionTo(['access admin panel', 'manage ai chat']); + + return $user; + } + + public function test_a_key_saved_in_settings_reaches_laravel_ai(): void + { + config(['ai.providers.openai.key' => 'from-env']); + $this->settings(['api_keys' => ['openai' => 'from-settings']]); + + ApplyProviderKeys::apply(); + + $this->assertSame('from-settings', config('ai.providers.openai.key')); + } + + public function test_the_env_key_is_kept_when_settings_have_none(): void + { + config(['ai.providers.openai.key' => 'from-env']); + + ApplyProviderKeys::apply(); + + $this->assertSame('from-env', config('ai.providers.openai.key')); + } + + public function test_keys_apply_when_laravel_ai_is_first_used(): void + { + $this->settings(['api_keys' => ['anthropic' => 'from-settings']]); + $this->app->forgetInstance(AiManager::class); + + app(AiManager::class); + + $this->assertSame('from-settings', config('ai.providers.anthropic.key')); + } + + public function test_keys_are_stored_encrypted(): void + { + $this->settings(['api_keys' => ['openai' => 'sk-secret-value']]); + + $stored = DB::table('settings')->where('group', 'ai_chat')->where('name', 'api_keys')->value('payload'); + + $this->assertStringNotContainsString('sk-secret-value', (string) $stored); + $this->assertSame('sk-secret-value', app(AiChatSettings::class)->api_keys['openai']); + } + + public function test_the_picker_offers_only_models_whose_provider_has_a_key(): void + { + config(['ai.providers.anthropic.key' => 'from-env']); + $this->settings(['api_keys' => ['openai' => 'from-settings'], 'models' => [ + ['label' => 'Luna', 'provider' => 'openai', 'model' => 'gpt-5.6-luna'], + ['label' => 'Haiku', 'provider' => 'anthropic', 'model' => 'claude-haiku'], + ['label' => 'Flash', 'provider' => 'gemini', 'model' => 'gemini-flash'], + ]]); + + $this->actingAs(User::factory()->create()) + ->get(route('ai-chat.index')) + ->assertInertia(fn ($page) => $page->where('models', [ + ['label' => 'Luna', 'model' => 'gpt-5.6-luna'], + ['label' => 'Haiku', 'model' => 'claude-haiku'], + ])); + } + + public function test_a_default_model_without_a_key_falls_back_to_the_first_offered(): void + { + $this->settings([ + 'api_keys' => ['openai' => 'from-settings'], + 'models' => [ + ['label' => 'Flash', 'provider' => 'gemini', 'model' => 'gemini-flash'], + ['label' => 'Luna', 'provider' => 'openai', 'model' => 'gpt-5.6-luna'], + ], + 'default_model' => 'gemini-flash', + ]); + + // Preselecting a model the server refuses would fail every message. + $this->actingAs(User::factory()->create()) + ->get(route('ai-chat.index')) + ->assertInertia(fn ($page) => $page->where('defaultModel', 'gpt-5.6-luna')); + } + + public function test_a_model_without_a_key_is_refused(): void + { + $this->settings(['models' => [['label' => 'Flash', 'provider' => 'gemini', 'model' => 'gemini-flash']]]); + + $this->actingAs(User::factory()->create()) + ->post(route('ai-chat.stream'), ['message' => 'Hi', 'model' => 'gemini-flash']) + ->assertSessionHasErrors('model'); + } + + public function test_models_load_grouped_by_provider_with_the_key_left_out(): void + { + $this->actingAs($this->manager()); + $this->settings([ + 'api_keys' => ['openai' => 'sk-keep-me'], + 'models' => [ + ['label' => 'Luna', 'provider' => 'openai', 'model' => 'luna'], + ['label' => 'Haiku', 'provider' => 'anthropic', 'model' => 'haiku'], + ['label' => 'Sol', 'provider' => 'openai', 'model' => 'sol'], + ], + ]); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->assertDontSee('sk-keep-me') + ->assertSchemaStateSet(['providers' => [ + ['provider' => 'openai', 'key' => null, 'forget_key' => false, 'models' => [['label' => 'Luna', 'model' => 'luna'], ['label' => 'Sol', 'model' => 'sol']]], + ['provider' => 'anthropic', 'key' => null, 'forget_key' => false, 'models' => [['label' => 'Haiku', 'model' => 'haiku']]], + ]]); + + $repeater(); + } + + public function test_saving_groups_back_to_models_and_keys(): void + { + $this->actingAs($this->manager()); + $this->settings(['api_keys' => ['openai' => 'sk-keep-me'], 'models' => []]); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->fillForm(['default_model' => null, 'providers' => [ + ['provider' => 'openai', 'key' => '', 'forget_key' => false, 'models' => [['label' => 'Luna', 'model' => 'luna']]], + ['provider' => 'anthropic', 'key' => 'sk-ant-new', 'forget_key' => false, 'models' => [['label' => 'Haiku', 'model' => 'haiku']]], + ]]) + ->call('save') + ->assertHasNoFormErrors(); + + $repeater(); + $settings = app(AiChatSettings::class)->refresh(); + $this->assertSame(['openai' => 'sk-keep-me', 'anthropic' => 'sk-ant-new'], $settings->api_keys); + $this->assertSame([ + ['label' => 'Luna', 'provider' => 'openai', 'model' => 'luna'], + ['label' => 'Haiku', 'provider' => 'anthropic', 'model' => 'haiku'], + ], $settings->models); + } + + public function test_removing_a_group_deletes_its_key_and_models(): void + { + $this->actingAs($this->manager()); + $this->settings(['api_keys' => ['openai' => 'sk-one', 'anthropic' => 'sk-two'], 'models' => [['label' => 'Luna', 'provider' => 'openai', 'model' => 'luna']]]); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->fillForm(['default_model' => null, 'providers' => [['provider' => 'anthropic', 'key' => '', 'forget_key' => false, 'models' => []]]]) + ->call('save') + ->assertHasNoFormErrors(); + + $repeater(); + $settings = app(AiChatSettings::class)->refresh(); + $this->assertSame(['anthropic' => 'sk-two'], $settings->api_keys); + $this->assertSame([], $settings->models); + } + + public function test_a_saved_key_can_be_removed_while_its_models_stay(): void + { + $this->actingAs($this->manager()); + $this->settings(['api_keys' => ['openai' => 'sk-one'], 'models' => [['label' => 'Luna', 'provider' => 'openai', 'model' => 'luna']]]); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->fillForm(['default_model' => null, 'providers' => [['provider' => 'openai', 'key' => '', 'forget_key' => true, 'models' => [['label' => 'Luna', 'model' => 'luna']]]]]) + ->call('save') + ->assertHasNoFormErrors(); + + $repeater(); + $settings = app(AiChatSettings::class)->refresh(); + $this->assertSame([], $settings->api_keys); + $this->assertCount(1, $settings->models); + } + + public function test_a_provider_is_one_group(): void + { + $this->actingAs($this->manager()); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->fillForm(['providers' => [ + ['provider' => 'openai', 'key' => '', 'forget_key' => false, 'models' => []], + ['provider' => 'openai', 'key' => '', 'forget_key' => false, 'models' => []], + ]]) + ->call('save') + ->assertHasFormErrors(['providers.1.provider']); + + $repeater(); + } + + public function test_a_group_names_a_provider_laravel_ai_knows(): void + { + $this->actingAs($this->manager()); + $repeater = Repeater::fake(); + + Livewire::test(SettingsPage::class) + ->fillForm(['providers' => [['provider' => 'opnai', 'key' => '', 'forget_key' => false, 'models' => []]]]) + ->call('save') + ->assertHasFormErrors(['providers.0.provider' => 'in']); + + $repeater(); + } + + public function test_a_key_from_the_server_environment_is_named_in_its_group(): void + { + $this->actingAs($this->manager()); + config(['ai.providers.openai.key' => 'from-env']); + $this->settings(['api_keys' => [], 'models' => [['label' => 'Luna', 'provider' => 'openai', 'model' => 'luna']]]); + + Livewire::test(SettingsPage::class) + ->assertSee('From your server environment') + ->assertDontSee('from-env'); + } + + public function test_the_seeder_offers_common_models_and_defaults_to_the_cheapest(): void + { + $this->seed(DatabaseSeeder::class); + $this->seed(DatabaseSeeder::class); + + $settings = app(AiChatSettings::class)->refresh(); + $providers = collect($settings->models)->pluck('provider')->unique()->values()->all(); + $cheapest = app(AiManager::class)->textProvider('openai')->cheapestTextModel(); + + $this->assertSame(['openai', 'anthropic', 'gemini'], $providers); + $this->assertSame($cheapest, $settings->default_model); + $this->assertSame(count(collect($settings->models)->unique('model')), count($settings->models), 'Seeding twice must not duplicate.'); + } + + public function test_the_seeder_leaves_an_admins_models_alone(): void + { + $this->settings(['models' => [['label' => 'Mine', 'provider' => 'openai', 'model' => 'my-model']]]); + + $this->seed(DatabaseSeeder::class); + + $this->assertSame('my-model', app(AiChatSettings::class)->refresh()->models[0]['model']); + $this->assertCount(1, app(AiChatSettings::class)->models); + } + + public function test_image_settings_win_over_config(): void + { + Storage::fake('public'); + Image::fake(); + config(['ai-chat.images' => ['provider' => 'gemini', 'model' => 'from-config', 'quality' => 'high']]); + $this->settings(['image_provider' => 'openai', 'image_model' => 'gpt-image-2', 'image_quality' => 'low']); + + (new GenerateImage(User::factory()->create()))->handle(new Request(['prompt' => 'A kite'])); + + Image::assertGenerated(fn ($prompt): bool => $prompt->provider->name() === 'openai' + && $prompt->model === 'gpt-image-2' + && $prompt->quality === 'low'); + } +} diff --git a/tests/Feature/SessionsTest.php b/tests/Feature/SessionsTest.php new file mode 100644 index 0000000..5560e19 --- /dev/null +++ b/tests/Feature/SessionsTest.php @@ -0,0 +1,278 @@ +withoutVite(); + config(['ai-chat.test_mode' => true]); + Queue::fake(); + } + + protected function tearDown(): void + { + ignore_user_abort(false); + set_time_limit(0); + + parent::tearDown(); + } + + /** + * Send one message and play the stream through, as the browser would. + */ + protected function send(User $user, string $message, array $extra = []): string + { + $response = $this->actingAs($user)->post(route('ai-chat.stream'), ['message' => $message, 'model' => 'reply', ...$extra]); + $response->streamedContent(); + + return $response->headers->get('X-Conversation-Id'); + } + + /** @return list role: content, oldest first */ + protected function transcript(string $id): array + { + return ConversationMessage::query()->where('conversation_id', $id)->orderBy('id')->get() + ->map(fn (ConversationMessage $m): string => $m->getAttribute('role').': '.$m->getAttribute('content')) + ->all(); + } + + public function test_asking_again_replaces_the_last_answer_instead_of_adding_a_turn(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'First question'); + $this->send($user, 'Second question', ['conversation_id' => $id]); + + $this->send($user, 'Second question', ['conversation_id' => $id, 'regenerate' => true]); + + $roles = $this->transcript($id); + $this->assertCount(4, $roles); + $this->assertSame(['user: First question', 'user: Second question'], array_values(array_filter($roles, fn ($r) => str_starts_with($r, 'user: ')))); + } + + public function test_asking_again_keeps_the_old_answer_when_the_new_one_fails(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'Question'); + $before = $this->transcript($id); + + $this->send($user, 'Question', ['conversation_id' => $id, 'regenerate' => true, 'model' => 'failure']); + + $this->assertSame($before, $this->transcript($id)); + } + + public function test_trying_again_after_a_failed_reply_keeps_the_turn_before_it(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'First question'); + $this->send($user, 'Second question', ['conversation_id' => $id, 'model' => 'failure']); + + // The failed turn was never stored: retrying it must not replace the first one. + $this->send($user, 'Second question', ['conversation_id' => $id, 'regenerate' => true]); + + $users = array_values(array_filter($this->transcript($id), fn ($r) => str_starts_with($r, 'user: '))); + $this->assertSame(['user: First question', 'user: Second question'], $users); + } + + public function test_the_reply_is_kept_when_the_user_stops_it(): void + { + $user = User::factory()->create(); + + $this->send($user, 'Hello'); + + // Stop aborts the browser's request; PHP would end at its next write and store nothing. + $this->assertSame(1, ignore_user_abort()); + } + + public function test_a_long_reply_outlives_the_default_time_limit(): void + { + $user = User::factory()->create(); + set_time_limit(30); + + $this->send($user, 'Hello'); + + // PHP's default 30 seconds ends a long answer mid-stream, before anything is stored. + $this->assertSame('300', ini_get('max_execution_time')); + } + + public function test_a_user_renames_their_chat_without_moving_it_in_the_list(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'Hello'); + $updated = Conversation::find($id)->updated_at; + $this->travel(5)->minutes(); + + $this->actingAs($user)->patch(route('ai-chat.update', $id), ['title' => ' Trip plans '])->assertRedirect(); + + $conversation = Conversation::find($id); + $this->assertSame('Trip plans', $conversation->title); + $this->assertEquals($updated, $conversation->updated_at); + } + + public function test_a_renamed_chat_keeps_its_title_when_a_new_one_is_generated(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'One'); + $this->send($user, 'Two', ['conversation_id' => $id]); + $this->send($user, 'Three', ['conversation_id' => $id]); + $this->actingAs($user)->patch(route('ai-chat.update', $id), ['title' => 'Mine']); + + (new GenerateConversationTitle($id, 3))->handle(app(ConversationTitleAgent::class)); + + $this->assertSame('Mine', Conversation::find($id)->title); + } + + public function test_a_user_pins_and_unpins_a_chat_without_moving_it_in_the_list(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'Hello'); + $updated = Conversation::find($id)->updated_at; + $this->travel(5)->minutes(); + + $this->actingAs($user)->patch(route('ai-chat.update', $id), ['pinned' => true])->assertRedirect()->assertSessionHasNoErrors(); + + $conversation = Conversation::find($id); + $this->assertNotNull($conversation->pinned_at); + $this->assertEquals($updated, $conversation->updated_at); + $this->actingAs($user)->get(route('ai-chat.index'))->assertInertia(fn ($page) => $page + ->whereNot('chat.sessions.data.0.pinned_at', null) + ); + + $this->actingAs($user)->patch(route('ai-chat.update', $id), ['pinned' => false]); + + $this->assertNull(Conversation::find($id)->pinned_at); + } + + public function test_a_title_is_required_and_short(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'Hello'); + + $this->actingAs($user)->patch(route('ai-chat.update', $id), ['title' => ' '])->assertSessionHasErrors('title'); + $this->actingAs($user)->patch(route('ai-chat.update', $id), ['title' => str_repeat('a', 101)])->assertSessionHasErrors('title'); + } + + public function test_a_user_deletes_their_chat_and_its_messages(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'Hello'); + + $this->actingAs($user)->delete(route('ai-chat.destroy', $id))->assertRedirect(route('ai-chat.index')); + + $this->assertNull(Conversation::find($id)); + $this->assertSame(0, ConversationMessage::query()->where('conversation_id', $id)->count()); + } + + public function test_deleting_another_chat_stays_on_the_one_open(): void + { + $user = User::factory()->create(); + $open = $this->send($user, 'Open'); + $other = $this->send($user, 'Other'); + + $this->actingAs($user)->from(route('ai-chat.show', $open)) + ->delete(route('ai-chat.destroy', $other)) + ->assertRedirect(route('ai-chat.show', $open)); + + $this->actingAs($user)->from(route('ai-chat.show', $other)) + ->delete(route('ai-chat.destroy', $open)) + ->assertRedirect(route('ai-chat.show', $other)); + } + + public function test_deleting_the_open_chat_goes_to_a_new_one(): void + { + $user = User::factory()->create(); + $id = $this->send($user, 'Open'); + + $this->actingAs($user)->from(route('ai-chat.show', $id)) + ->delete(route('ai-chat.destroy', $id)) + ->assertRedirect(route('ai-chat.index')); + } + + public function test_no_one_else_can_rename_or_delete_a_chat(): void + { + $id = $this->send(User::factory()->create(), 'Mine'); + $other = User::factory()->create(); + + $this->actingAs($other)->patch(route('ai-chat.update', $id), ['title' => 'Theirs'])->assertNotFound(); + $this->actingAs($other)->delete(route('ai-chat.destroy', $id))->assertNotFound(); + $this->assertNotNull(Conversation::find($id)); + } + + /** + * $count chats for the user, chat 1 the newest, a minute apart. + * + * @return list ids, newest first + */ + protected function chats(User $user, int $count): array + { + return collect(range(1, $count))->map(function (int $n) use ($user): string { + $conversation = Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $user->getMorphClass(), + 'participant_id' => $user->getKey(), + 'title' => "Chat {$n}", + ]); + $conversation->timestamps = false; + $conversation->forceFill(['updated_at' => now()->subMinutes($n)])->save(); + + return $conversation->id; + })->all(); + } + + /** @return array{data: list>, has_more: bool} */ + protected function sidebar(User $user): array + { + return $this->actingAs($user)->get(route('ai-chat.index'))->viewData('page')['props']['chat']['sessions']; + } + + public function test_the_sidebar_gets_the_newest_chats_and_every_pinned_one(): void + { + $user = User::factory()->create(); + $ids = $this->chats($user, Sessions::PER_PAGE + 2); + Conversation::whereKey(end($ids))->update(['pinned_at' => now()]); + + $sessions = $this->sidebar($user); + + $this->assertSame([end($ids), ...array_slice($ids, 0, Sessions::PER_PAGE)], array_column($sessions['data'], 'id')); + $this->assertTrue($sessions['has_more']); + } + + public function test_show_more_adds_the_next_chats_and_keeps_them_on_every_page(): void + { + $user = User::factory()->create(); + $ids = $this->chats($user, Sessions::PER_PAGE + 2); + + $this->actingAs($user)->post(route('ai-chat.sessions.more'))->assertRedirect(); + + $sessions = $this->sidebar($user); + $this->assertSame($ids, array_column($sessions['data'], 'id')); + $this->assertFalse($sessions['has_more']); + $this->assertCount(Sessions::PER_PAGE + 2, $this->sidebar($user)['data']); + } + + public function test_the_list_carries_when_each_chat_was_last_active(): void + { + $user = User::factory()->create(); + $this->send($user, 'Hello'); + + $this->actingAs($user)->get(route('ai-chat.index'))->assertInertia(fn ($page) => $page + ->has('chat.sessions.data.0.updated_at') + ); + } +} 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); + } +} diff --git a/tests/Feature/ToolsTest.php b/tests/Feature/ToolsTest.php new file mode 100644 index 0000000..cbfddcf --- /dev/null +++ b/tests/Feature/ToolsTest.php @@ -0,0 +1,108 @@ + false]); + } + + public function test_the_agent_offers_web_search_the_account_and_images(): void + { + $tools = collect((new ChatAgent(User::factory()->create()))->tools()); + + $this->assertTrue($tools->contains(fn ($tool) => $tool instanceof WebSearch)); + $this->assertTrue($tools->contains(fn ($tool) => $tool instanceof AboutMyAccount)); + $this->assertTrue($tools->contains(fn ($tool) => $tool instanceof GenerateImage)); + } + + public function test_without_a_user_only_web_search_is_offered(): void + { + $tools = collect((new ChatAgent)->tools()); + + $this->assertCount(1, $tools); + $this->assertInstanceOf(WebSearch::class, $tools->first()); + } + + public function test_the_account_tool_describes_the_signed_in_user(): void + { + $user = User::factory()->create(['name' => 'Ada Lovelace', 'email' => 'ada@example.com']); + User::factory()->create(['name' => 'Someone Else']); + + $account = json_decode((string) (new AboutMyAccount($user))->handle(new Request), true); + + $this->assertSame('Ada Lovelace', $account['name']); + $this->assertSame('ada@example.com', $account['email']); + $this->assertArrayHasKey('member_since', $account); + $this->assertStringNotContainsString('Someone Else', json_encode($account)); + } + + public function test_the_account_tool_includes_the_plan_when_billing_is_installed(): void + { + $user = User::factory()->create(); + + if (! method_exists($user, 'planName')) { + $this->markTestSkipped('Billing is not installed.'); + } + + $account = json_decode((string) (new AboutMyAccount($user))->handle(new Request), true); + + $this->assertArrayHasKey('plan', $account); + $this->assertArrayHasKey('paid', $account['plan']); + } + + public function test_the_image_tool_generates_and_stores_an_image(): void + { + Storage::fake('public'); + Image::fake(); + + $result = json_decode((string) (new GenerateImage(User::factory()->create()))->handle(new Request(['prompt' => 'A lighthouse at dusk'])), true); + + $this->assertSame('A lighthouse at dusk', $result['prompt']); + $this->assertStringContainsString('/storage/ai-chat/images/', $result['url']); + $this->assertCount(1, Storage::disk('public')->allFiles('ai-chat/images')); + + Image::assertGenerated(fn ($prompt): bool => $prompt->prompt === 'A lighthouse at dusk'); + } + + public function test_the_image_provider_model_and_quality_come_from_config(): void + { + Storage::fake('public'); + Image::fake(); + config(['ai-chat.images' => ['provider' => 'openai', 'model' => 'gpt-image-2', 'quality' => 'low']]); + + (new GenerateImage(User::factory()->create()))->handle(new Request(['prompt' => 'A red kite'])); + + Image::assertGenerated(fn ($prompt): bool => $prompt->model === 'gpt-image-2' + && $prompt->quality === 'low' + && $prompt->provider->name() === 'openai'); + } + + public function test_the_image_tool_needs_a_prompt(): void + { + Image::fake(); + + $result = (string) (new GenerateImage(User::factory()->create()))->handle(new Request(['prompt' => ' '])); + + $this->assertStringContainsString('No image was described', $result); + Image::assertNothingGenerated(); + } +} diff --git a/tests/Feature/UsageLimitsTest.php b/tests/Feature/UsageLimitsTest.php new file mode 100644 index 0000000..b5b9cc0 --- /dev/null +++ b/tests/Feature/UsageLimitsTest.php @@ -0,0 +1,147 @@ +markTestSkipped('Billing is not installed.'); + } + + config(['ai-chat.test_mode' => false]); + Ai::fakeAgent(ChatAgent::class, array_fill(0, 5, 'Reply.')); + } + + /** + * Every user gets the Free plan's entitlements, so a limit on it applies to everyone. + * + * @param array $limits + */ + protected function freePlanWithLimits(array $limits): void + { + Product::factory()->free()->create(['entitlements' => ['limits' => $limits]]); + } + + protected function send(User $user, string $message = 'Hello'): TestResponse + { + $response = $this->actingAs($user)->post(route('ai-chat.stream'), ['message' => $message]); + + if ($response->isOk()) { + $response->streamedContent(); + } + + return $response; + } + + public function test_the_chat_page_shows_messages_used_against_the_plan_limit(): void + { + $this->withoutVite(); + $this->freePlanWithLimits(['ai_chat_messages' => 50]); + $user = User::factory()->create(); + $this->send($user)->assertOk(); + $this->send($user)->assertOk(); + + $this->actingAs($user)->get(route('ai-chat.index'))->assertInertia(fn ($page) => $page + ->where('usage.used', 2) + ->where('usage.limit', 50) + ->where('usage.upgrade_url', route('billing.plans')) + ); + } + + public function test_the_chat_page_shows_no_usage_without_a_limit(): void + { + $this->withoutVite(); + $this->freePlanWithLimits(['seats' => 3]); + + $this->actingAs(User::factory()->create())->get(route('ai-chat.index')) + ->assertInertia(fn ($page) => $page->where('usage', null)); + } + + public function test_without_a_limit_on_any_plan_messages_are_unlimited(): void + { + $user = User::factory()->create(); + + foreach (range(1, 3) as $i) { + $this->send($user)->assertOk(); + } + } + + public function test_a_plan_that_does_not_mention_the_key_leaves_messages_unlimited(): void + { + // Billing reads an unmentioned limit as zero; the chat must not switch off on install. + $this->freePlanWithLimits(['seats' => 3]); + $user = User::factory()->create(); + + $this->send($user)->assertOk(); + } + + public function test_messages_stop_at_the_plan_limit(): void + { + $this->freePlanWithLimits(['ai_chat_messages' => 2]); + $user = User::factory()->create(); + + $this->send($user)->assertOk(); + $this->send($user)->assertOk(); + + $this->send($user, 'One too many') + ->assertStatus(429) + ->assertJsonPath('limit', 2); + + $this->assertDatabaseMissing('agent_conversation_messages', ['content' => 'One too many']); + $this->assertDatabaseCount('agent_conversations', 2); + } + + public function test_last_months_messages_do_not_count(): void + { + $this->freePlanWithLimits(['ai_chat_messages' => 1]); + $user = User::factory()->create(); + + $this->travel(-1)->months(); + $this->send($user)->assertOk(); + $this->travelBack(); + + $this->send($user)->assertOk(); + } + + public function test_images_stop_at_the_plan_limit(): void + { + Storage::fake('public'); + Image::fake(); + $this->freePlanWithLimits(['ai_chat_images' => 1]); + $tool = new GenerateImage(User::factory()->create()); + + $first = (string) $tool->handle(new Request(['prompt' => 'A red kite'])); + $second = (string) $tool->handle(new Request(['prompt' => 'A blue kite'])); + + $this->assertStringContainsString('"url"', $first); + $this->assertStringContainsString('limit of 1 image', $second); + Image::assertNotGenerated(fn ($prompt): bool => $prompt->prompt === 'A blue kite'); + } + + public function test_the_limits_are_offered_in_the_product_form(): void + { + $billing = Capabilities::group('billing'); + + $this->assertSame('limit', $billing['ai_chat_messages']['type']); + $this->assertSame('limit', $billing['ai_chat_images']['type']); + } +} diff --git a/tests/e2e/index.spec.ts b/tests/e2e/index.spec.ts deleted file mode 100644 index 61ff806..0000000 --- a/tests/e2e/index.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { expect, test } from '@e2e/fixtures'; - -test.describe('AiChat index page', () => { - test('responds successfully', async ({ page }) => { - const response = await page.goto('/ai-chat'); - - expect(response, 'Expected a navigation response').toBeTruthy(); - expect( - response?.ok(), - 'Expected a successful status code', - ).toBeTruthy(); - }); -}); diff --git a/tests/e2e/tests/chat.spec.ts b/tests/e2e/tests/chat.spec.ts new file mode 100644 index 0000000..7dbf367 --- /dev/null +++ b/tests/e2e/tests/chat.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from '@e2e/fixtures'; + +test.describe('Chat', () => { + // Off by default, as anywhere: each test turns test mode on, so the demo provider + // answers and nothing reaches a paid API. + test.beforeEach(async ({ laravel }) => { + await laravel.config('ai-chat.test_mode', true); + }); + + test('a question gets a streamed reply and the chat its own URL', async ({ + page, + credentials, + loginAs, + }) => { + await loginAs(credentials.user); + await page.goto('/chat'); + + await page.getByTestId('chat-input').fill('Hello'); + await page.getByTestId('chat-send').click(); + + await expect(page.getByTestId('chat-message-user')).toContainText( + 'Hello', + ); + // The `reply` demo, the picker's default in test mode. + await expect(page.getByTestId('chat-message-assistant')).toContainText( + 'running in test mode', + ); + await expect(page).toHaveURL(/\/chat\/[0-9a-f-]{36}$/); + }); + + test('guests are sent to sign in', async ({ page }) => { + await page.goto('/chat'); + + await expect(page).toHaveURL(/\/auth\/login/); + }); +});