Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-rea
- **Dictation** in the message box
- **Admin panel**: provider API keys, the models users can pick, extra instructions, image settings, and a read-only conversation viewer
- **Test mode**: a demo provider answers, so you can build and try the chat without a key or tokens
- **WebMCP**: the visitor's own browser agent can ask the assistant and read or switch chats
- **WebMCP** (beta, off until turned on): the visitor's own browser agent can ask the assistant and read or switch chats
- **Two layouts**: a "Chat" item in the app sidebar and the chats in a panel of their own, or the chats in the app sidebar for a chat-first app
- **Vue** (React to come)
- **Vue and React**

## Install

Expand All @@ -49,12 +49,12 @@ It needs [Auth](https://github.com/saucebase-dev/auth) for sign-in. Conversation

## Configuration

In the admin panel, under **Settings → AI chat** (people with the `manage ai chat` permission, and admins):
In the admin panel, under **Settings → AI chat** (people with the `manage ai chat` permission, and admins), in four sections:

- **API keys** for each provider, stored encrypted. A key set in `.env` (laravel/ai's `config/ai.php`) works too, and the admin shows which keys come from there.
- **Models**: the ones users can pick, and the default. Only providers with a key are offered.
- **Instructions** added to the assistant's own.
- **Models**: each provider with its API key (stored encrypted; a key set in `.env`, laravel/ai's `config/ai.php`, works too) and the models users can pick, and the default model. Only providers with a key are offered. In test mode the page says the demos replace them.
- **Assistant**: instructions added to the assistant's own.
- **Images**: the provider, model and quality `generate_image` uses. `.env` can set them too (`AI_CHAT_IMAGE_PROVIDER`, `AI_CHAT_IMAGE_MODEL`, `AI_CHAT_IMAGE_QUALITY`); without either, laravel/ai's default for images.
- **WebMCP (beta)**: off by default. On, the chat offers its tools to the visitor's own browser agent, in browsers that support WebMCP (a draft standard).

The conversation viewer is under **Chats**.

Expand Down
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
},
"saucebase": {
"frameworks": [
"vue"
"vue",
"react"
]
},
"branch-alias": {
Expand All @@ -29,7 +30,8 @@
"psr-4": {
"Modules\\AiChat\\": "src/",
"Modules\\AiChat\\Database\\Factories\\": "database/factories/",
"Modules\\AiChat\\Database\\Seeders\\": "database/seeders/"
"Modules\\AiChat\\Database\\Seeders\\": "database/seeders/",
"Modules\\AiChat\\Tests\\Support\\": "tests/Support/"
}
},
"autoload-dev": {
Expand Down
14 changes: 14 additions & 0 deletions database/settings/1000_00_00_000004_add_ai_chat_webmcp_setting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

use Spatie\LaravelSettings\Migrations\SettingsMigration;

return new class extends SettingsMigration
{
public function up(): void
{
// Beta: off until an admin turns it on.
if (! $this->migrator->exists('ai_chat.webmcp_enabled')) {
$this->migrator->add('ai_chat.webmcp_enabled', false);
}
}
};
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
"private": true,
"type": "module",
"dependencies": {
"@ai-sdk/react": "^4.0.181",
"@ai-sdk/vue": "^4.0.181",
"@shadcn/react": "^0.3.1",
"ai": "^7.0.181",
"shiki": "^4.6.0",
"streamdown": "^2.8.1",
"vue-stream-markdown": "^1.1.0"
}
}
12 changes: 9 additions & 3 deletions resources/boost/skills/saucebase-ai-chat-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ Paths are relative to `modules/ai-chat/` unless they say otherwise. Commands run
| 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) |
| Page | Vue and React mirror each other, same names and test ids: `resources/js/{vue,react}/pages/Index`, `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). Plain TypeScript, shared by both stacks: no `vue` or `react` imports here |

## Adding a tool

Expand Down Expand Up @@ -66,7 +66,7 @@ Search: `GET chat/sessions/search?q=` (`Sessions::search()`), the user's chats b

## 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.
Beta: off until an admin turns it on (`AiChatSettings::$webmcp_enabled`, the page's `webmcp` prop). The page then registers its tools with `registerWebMcpTools()`; `offeredTools()` lists them (`onOfferedToolsChange()` to follow: React's `useSyncExternalStore`, a ref in Vue) for the sidebar's WebMCP panel (`dashboard::sidebar.end`), also in browsers without WebMCP, where it shows the steps to turn it on.

## Limits

Expand All @@ -83,6 +83,12 @@ Search: `GET chat/sessions/search?q=` (`Sessions::search()`), the user's chats b
- `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.
- React renders Markdown with Streamdown, whose own elements carry Tailwind classes from its dist files, which the app doesn't scan (`@source` covers modules, not `node_modules`). `ChatMarkdown.tsx` gives every element it uses its own classes, vue-stream-markdown's values so replies match Vue, and drops Streamdown's `node` prop (`domProps()`), which would land in the HTML; `inlineCode` set makes `code` receive fenced blocks only (Streamdown's `pre` marks them, so leave `pre` alone). Vue's tables have a copy/download/fullscreen bar; React's have none yet.
- React's `ChatScrollButton` scrolls to the end when the last question's id changes, not the count: older pages prepended above raised the count and slid the view off them.
- The two stacks' UI kits differ in defaults; match Vue by hand: React's model `SelectContent` takes `position="popper"` (Radix defaults to item-aligned, a short scrolling list), and its phone sheet `preventDefault`s `onOpenAutoFocus` (Radix skips links and focuses the search box, bringing up a phone's keyboard). The React highlighter's languages mirror Vue's `ui/code-block/highlighter.ts`.
- A `SidebarMenuButton` tooltip opens on focus even when hidden (expanded, or on a phone) and takes the first Escape: in Vue's phone sheet Escape closed an invisible tooltip, not the sheet. `ChatSessions` gives New chat a tooltip only when collapsed to icons.
- React's page: the SDK's `onFinish`/`onError` are made with the first render, so they only record the event in state; effects act on it with current values.
- The panel's resize handle reads "Resize sidebar" in React (core's React `SidebarResizer` takes no label); Vue's falls through "Resize chat list".
- 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.

Expand Down
12 changes: 12 additions & 0 deletions resources/js/lib/sessions.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { Session } from './sessions';

const ago = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();

/** A user's chats across the date groups, one pinned: the stories' `chat.sessions`. */
export const sessions: Session[] = [
{ id: 'pinned-1', title: 'Launch checklist', updated_at: ago(60 * 24 * 20), pinned_at: ago(60) },
{ id: 'today-1', title: 'Plan a trip to Lisbon', updated_at: ago(5), pinned_at: null },
{ id: 'today-2', title: 'Tax questions', updated_at: ago(90), pinned_at: null },
{ id: 'yesterday-1', title: 'Banner ideas', updated_at: ago(60 * 26), pinned_at: null },
{ id: 'older-1', title: 'Pricing page copy', updated_at: ago(60 * 24 * 12), pinned_at: null },
];
51 changes: 51 additions & 0 deletions resources/js/lib/stored.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { readStored, subscribeStored, writeStored } from './stored';

function storage(failWrites = false) {
const items = new Map<string, string>();

return {
getItem: (key: string) => items.get(key) ?? null,
setItem: (key: string, value: string) => {
if (failWrites) {
throw new Error('QuotaExceededError');
}

items.set(key, value);
},
};
}

describe('stored values', () => {
afterEach(() => vi.unstubAllGlobals());

it('keeps a value in localStorage', () => {
vi.stubGlobal('localStorage', storage());

writeStored('ai-chat:test-kept', '320');

expect(readStored('ai-chat:test-kept')).toBe('320');
});

// Private mode or a full quota: the change still holds for this page.
it('holds a value it could not store for the rest of the page', () => {
vi.stubGlobal('localStorage', storage(true));

writeStored('ai-chat:test-refused', '320');

expect(readStored('ai-chat:test-refused')).toBe('320');
});

it('tells subscribers about a write', () => {
vi.stubGlobal('localStorage', storage());
vi.stubGlobal('window', { addEventListener: vi.fn(), removeEventListener: vi.fn() });
const listener = vi.fn();
const stop = subscribeStored(listener);

writeStored('ai-chat:test-told', '1');
stop();
writeStored('ai-chat:test-told', '2');

expect(listener).toHaveBeenCalledTimes(1);
});
});
41 changes: 41 additions & 0 deletions resources/js/lib/stored.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Values kept in localStorage (as strings), with a store's subscribe for React's
* useSyncExternalStore. A value the browser refuses to store (private mode, a full quota)
* is held in memory instead, so the change still holds for the rest of the page.
*/
const refused = new Map<string, string>();
const listeners = new Set<() => void>();

export function readStored(key: string): string | null {
if (refused.has(key)) {
return refused.get(key) ?? null;
}

try {
return localStorage.getItem(key);
} catch {
return null;
}
}

export function writeStored(key: string, value: string): void {
try {
localStorage.setItem(key, value);
refused.delete(key);
} catch {
refused.set(key, value);
}

listeners.forEach((listener) => listener());
}

/** Writes here, and in other tabs (the `storage` event). Returns the unsubscribe. */
export function subscribeStored(listener: () => void): () => void {
listeners.add(listener);
window.addEventListener('storage', listener);

return () => {
listeners.delete(listener);
window.removeEventListener('storage', listener);
};
}
23 changes: 20 additions & 3 deletions resources/js/lib/webmcp.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import { chatTools, type ChatToolsContext } from './chatTools';
import { offeredTools, registerWebMcpTools, type WebMcpTool } from './webmcp';
import { offeredTools, onOfferedToolsChange, registerWebMcpTools, type WebMcpTool } from './webmcp';

function context(overrides: Partial<ChatToolsContext> = {}): ChatToolsContext {
return {
Expand Down Expand Up @@ -77,10 +77,27 @@ describe('registerWebMcpTools', () => {
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));
expect(offeredTools().map((offered) => offered.name)).toEqual(tools.map((offered) => offered.name));

withdraw();
expect(offeredTools.value).toEqual([]);
expect(offeredTools()).toEqual([]);
});

// Plain JavaScript, so both stacks read it: React through useSyncExternalStore, Vue through a ref.
it('tells listeners when the offer changes, and keeps one list between changes', () => {
const listener = vi.fn();
const stop = onOfferedToolsChange(listener);

const withdraw = registerWebMcpTools(tools, {});
expect(listener).toHaveBeenCalledTimes(1);
expect(offeredTools()).toBe(offeredTools());

withdraw();
expect(listener).toHaveBeenCalledTimes(2);

stop();
registerWebMcpTools(tools, {})();
expect(listener).toHaveBeenCalledTimes(2);
});

it('registers every tool and withdraws them all together', () => {
Expand Down
28 changes: 22 additions & 6 deletions resources/js/lib/webmcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
* 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;
Expand All @@ -26,8 +24,26 @@ interface ModelContext {
): Promise<void>;
}

/** What the open page offers, listed by the WebMCP panel even where the browser can't call it yet. */
export const offeredTools = shallowRef<WebMcpTool[]>([]);
let offered: WebMcpTool[] = [];
const listeners = new Set<() => void>();

function offer(tools: WebMcpTool[]): void {
offered = tools;
listeners.forEach((listener) => listener());
}

/**
* What the open page offers, listed by the WebMCP panel even where the browser can't call it
* yet. The same list until the offer changes, so React's useSyncExternalStore can read it.
*/
export const offeredTools = (): WebMcpTool[] => offered;

/** Called on every change of the offer; returns the unsubscribe. Plain JavaScript, so both stacks read it. */
export function onOfferedToolsChange(listener: () => void): () => void {
listeners.add(listener);

return () => listeners.delete(listener);
}

/** Whether this browser can hand the tools to an agent. */
export const webMcpSupported = typeof document !== 'undefined' && 'modelContext' in document;
Expand All @@ -52,8 +68,8 @@ export function registerWebMcpTools(
): () => void {
const context = target?.modelContext;

offeredTools.value = [...offeredTools.value, ...tools];
const withdraw = () => (offeredTools.value = offeredTools.value.filter((offered) => !tools.includes(offered)));
offer([...offered, ...tools]);
const withdraw = () => offer(offered.filter((tool) => !tools.includes(tool)));

if (!context) {
return withdraw;
Expand Down
33 changes: 33 additions & 0 deletions resources/js/react/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { usePage } from '@inertiajs/react';
import { registerGlobalComponent } from '@saucebase/react/lib/globalComponents';
import { registerIcon } from '@saucebase/react/lib/navigation';
import type { ComponentType } from 'react';
import IconChat from '~icons/heroicons/chat-bubble-left-right';
import { ChatSessions } from './components/ChatSessions';
import { WebMcpMenuItem } from './components/WebMcpMenuItem';

/** Only while the list lives in the app sidebar (`ai-chat.sessions` = sidebar); else the chat's own panel holds it. */
function inAppSidebar(Component: ComponentType): ComponentType {
return function InAppSidebar() {
const page = usePage();
const where = (page.props.chat as { sessions_in?: string } | undefined)
?.sessions_in;

return where === 'sidebar' ? <Component /> : null;
};
}

const SidebarSessions = inAppSidebar(ChatSessions);
const SidebarWebMcp = inAppSidebar(WebMcpMenuItem);

/**
* Called before the first render, on the server too.
*/
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', SidebarSessions);
// What the visitor's browser agent can do here, while a page offers WebMCP tools.
registerGlobalComponent('dashboard::sidebar.end', SidebarWebMcp);
}
60 changes: 60 additions & 0 deletions resources/js/react/chat.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* The chat fills the window below the header and scrolls inside, never the page.
* height: 1px makes the layout's min-height (the window, less an announcement
* banner) a definite height its flex children can fill.
*/
[data-slot='sidebar-wrapper']:has([data-chat-page]) {
height: 1px;
}

[data-slot='sidebar-inset']:has([data-chat-page]) {
min-height: 0;
overflow: hidden;
}

[data-slot='sidebar-inset'] > main:has([data-chat-page]) {
display: flex;
min-height: 0;
flex-direction: column;
}

[data-slot='sidebar-inset']
> main:has([data-chat-page])
> .page-transition-wrapper {
min-height: 0;
flex: 1;
}

/* The scroll button's dots while a reply streams. A fixed travel: animate-bounce moves a
quarter of the element's height, a 1px twitch on a 4px dot. */
[data-chat-dots] > span {
width: 0.25rem;
height: 0.25rem;
border-radius: calc(infinity * 1px);
background-color: currentColor;
animation: ai-chat-dot-bounce 0.9s ease-in-out infinite;
}

[data-chat-dots] > span:nth-child(2) {
animation-delay: 0.15s;
}

[data-chat-dots] > span:nth-child(3) {
animation-delay: 0.3s;
}

@keyframes ai-chat-dot-bounce {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-4px);
}
}

@media (prefers-reduced-motion: reduce) {
[data-chat-dots] > span {
animation: none;
}
}
Loading