juneau 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,834 +1,924 @@
1
- # Juneau
2
-
3
- React component library for building AI chat interfaces. Streaming-first, adapter-based, fully themeable.
4
-
5
- ```tsx
6
- import { JuneauProvider, AiChatProvider, AiSidebar, createSseAdapter } from 'juneau';
7
- import 'juneau/dist/style.css';
8
-
9
- const adapter = createSseAdapter('/api/chat');
10
-
11
- <JuneauProvider>
12
- <AiChatProvider adapter={adapter}>
13
- <App />
14
- <AiSidebar />
15
- </AiChatProvider>
16
- </JuneauProvider>
17
- ```
18
-
19
- ---
20
-
21
- ## Install
22
-
23
- ```bash
24
- npm install juneau
25
- ```
26
-
27
- **Peer dependencies:** `react ^18 || ^19`, `react-dom ^18 || ^19`
28
-
29
- ---
30
-
31
- ## Core concept — the adapter
32
-
33
- Juneau never calls any AI API directly. **You own the network layer.** Juneau provides the UI, state, and streaming machinery — you provide an adapter that connects it to your backend.
34
-
35
- An adapter is just one method:
36
-
37
- ```ts
38
- interface AiBackendAdapter {
39
- sendMessage(input: AiAdapterInput): AsyncIterable<AiStreamEvent>;
40
- }
41
- ```
42
-
43
- It receives the conversation history and streams back typed events:
44
-
45
- ```ts
46
- type AiStreamEvent =
47
- | { type: 'text'; text: string } // streamed text chunk — append to current bubble
48
- | { type: 'part'; part: AiMessagePart } // rich UI block (table, proposal, activity, error)
49
- | { type: 'done' } // stream finished cleanly
50
- | { type: 'error'; message: string } // stream failed
51
- ```
52
-
53
- This means your API keys stay on your backend, you control auth, rate limiting, model selection — Juneau just renders whatever comes back.
54
-
55
- ---
56
-
57
- ## Built-in adapters
58
-
59
- Juneau ships two factory functions so you don't have to write boilerplate streaming code.
60
-
61
- ### `createSseAdapter(url, options?)` — recommended
62
-
63
- For backends that stream **Server-Sent Events (SSE)** — the format used by OpenAI, Anthropic, and most AI API proxies.
64
-
65
- The default parser understands OpenAI's streaming format out of the box (`choices[0].delta.content`).
66
-
67
- ```ts
68
- import { createSseAdapter } from 'juneau';
69
-
70
- // OpenAI-compatible backend — zero config needed:
71
- const adapter = createSseAdapter('/api/chat');
72
-
73
- // With dynamic auth header:
74
- const adapter = createSseAdapter('/api/chat', {
75
- getHeaders: async () => ({
76
- Authorization: `Bearer ${await getSessionToken()}`,
77
- }),
78
- });
79
-
80
- // Custom request body:
81
- const adapter = createSseAdapter('/api/chat', {
82
- getBody: ({ messages, context }) => ({
83
- messages,
84
- model: 'gpt-4o',
85
- stream: true,
86
- temperature: 0.7,
87
- }),
88
- });
89
-
90
- // Custom SSE event schema (backend streams { text: "..." } instead of OpenAI format):
91
- const adapter = createSseAdapter('/api/chat', {
92
- parseEvent: (data) => {
93
- try {
94
- const json = JSON.parse(data);
95
- return json.text ? [{ type: 'text', text: json.text }] : [];
96
- } catch {
97
- return [];
98
- }
99
- },
100
- });
101
- ```
102
-
103
- | Option | Type | Default | Description |
104
- |---|---|---|---|
105
- | `method` | `string` | `'POST'` | HTTP method |
106
- | `headers` | `Record<string, string>` | `{}` | Static headers, merged with Content-Type |
107
- | `getHeaders` | `(input) => Record<string, string>` | — | Dynamic headers, called per request. Merged on top of `headers`. |
108
- | `getBody` | `(input) => unknown` | `{ messages, context }` | Override request body |
109
- | `parseEvent` | `(data: string) => AiStreamEvent[]` | OpenAI parser | Parse each `data: ...` SSE line into events |
110
-
111
- ---
112
-
113
- ### `createFetchStreamAdapter(url, options?)` — for non-SSE backends
114
-
115
- For backends that stream **newline-delimited JSON (NDJSON)** or plain text — raw chunked HTTP without SSE formatting.
116
-
117
- The default parser expects `{ "text": "..." }` or `{ "done": true }` JSON lines.
118
-
119
- ```ts
120
- import { createFetchStreamAdapter } from 'juneau';
121
-
122
- // NDJSON backend (streams { text: "..." } lines):
123
- const adapter = createFetchStreamAdapter('/api/chat');
124
-
125
- // Plain text — treat every chunk as raw text:
126
- const adapter = createFetchStreamAdapter('/api/chat', {
127
- parseChunk: (chunk) => chunk ? [{ type: 'text', text: chunk }] : [],
128
- });
129
-
130
- // Custom JSON lines schema:
131
- const adapter = createFetchStreamAdapter('/api/chat', {
132
- parseChunk: (chunk) => {
133
- try {
134
- const json = JSON.parse(chunk);
135
- if (json.error) return [{ type: 'error', message: json.error }];
136
- if (json.done) return [{ type: 'done' }];
137
- if (json.delta) return [{ type: 'text', text: json.delta }];
138
- return [];
139
- } catch { return []; }
140
- },
141
- });
142
- ```
143
-
144
- | Option | Type | Default | Description |
145
- |---|---|---|---|
146
- | `method` | `string` | `'POST'` | HTTP method |
147
- | `headers` | `Record<string, string>` | `{}` | Static headers |
148
- | `getHeaders` | `(input) => Record<string, string>` | — | Dynamic headers, called per request |
149
- | `getBody` | `(input) => unknown` | `{ messages, context }` | Override request body |
150
- | `parseChunk` | `(chunk: string) => AiStreamEvent[]` | NDJSON parser | Parse each newline-delimited chunk into events |
151
-
152
- ---
153
-
154
- ### Writing your own adapter
155
-
156
- If neither factory fits, implementing the interface directly takes about 10 lines:
157
-
158
- ```ts
159
- import type { AiBackendAdapter } from 'juneau';
160
-
161
- export const myAdapter: AiBackendAdapter = {
162
- async *sendMessage({ messages, context }) {
163
- const res = await fetch('/api/chat', {
164
- method: 'POST',
165
- headers: { 'Content-Type': 'application/json' },
166
- body: JSON.stringify({ messages }),
167
- });
168
-
169
- const reader = res.body!.getReader();
170
- const decoder = new TextDecoder();
171
-
172
- while (true) {
173
- const { done, value } = await reader.read();
174
- if (done) break;
175
- yield { type: 'text', text: decoder.decode(value) };
176
- }
177
-
178
- yield { type: 'done' };
179
- },
180
- };
181
- ```
182
-
183
- ---
184
-
185
- ### Backend utilities — `juneau/server`
186
-
187
- If your backend uses ai-sdk, Juneau ships server-side helpers that eliminate the boilerplate of history mapping, activity streaming, and tool failure recovery. Import from the `/server` subpath — zod stays out of the browser bundle.
188
-
189
- ```ts
190
- import { toSdkMessages, createSkillSet, withToolRecovery } from 'juneau/server';
191
- ```
192
-
193
- **Full integration in ~15 lines:**
194
-
195
- ```ts
196
- import { toSdkMessages, createSkillSet, withToolRecovery } from 'juneau/server';
197
- import { streamText } from 'ai';
198
- import { z } from 'zod';
199
-
200
- const skillSet = createSkillSet({
201
- search: {
202
- description: 'Search for records.',
203
- input: z.object({ query: z.string() }),
204
- labels: {
205
- running: { en: 'Searching…', cs: 'Vyhledávám…' },
206
- done: { en: 'Results found', cs: 'Nalezeno' },
207
- },
208
- execute: async ({ query }) => db.search(query),
209
- },
210
- }, { language: context.language });
211
-
212
- for await (const chunk of withToolRecovery({
213
- phase1: () => streamText({ model, system, messages: toSdkMessages(input.messages), tools: skillSet.tools, maxSteps: 1 }),
214
- phase2: (ctx) => streamText({ model, system, messages: [...toSdkMessages(input.messages), { role: 'assistant', content: ctx }] }),
215
- skillSet,
216
- })) {
217
- res.write(chunk);
218
- }
219
- ```
220
-
221
- #### `toSdkMessages(messages)`
222
-
223
- Converts `AiMessage[]` to `CoreMessage[]` for ai-sdk. Extracts text from parts, fixes conversation alternation (no two consecutive user turns), filters empty turns.
224
-
225
- #### `createSkillSet(skills, options?)`
226
-
227
- Wraps skill definitions into ai-sdk `tools` with a built-in activity buffer. Each tool call automatically emits `running` / `done` / `failed` Juneau wire SSE strings — no manual activity handling needed.
228
-
229
- `execute` receives a `SkillExecuteContext` as its second argument with an `emit(part)` callback push custom part wire events into the stream alongside the activities, e.g. an invoice card widget the frontend renders via `renderPart`:
230
-
231
- ```ts
232
- execute: async ({ query }, { emit }) => {
233
- const inv = await db.findInvoice(query);
234
- emit({ type: 'invoice-card', invoiceNumber: inv.number, amount: inv.total });
235
- return { found: 1, invoice: inv }; // returned to the model as the tool result
236
- },
237
- ```
238
-
239
- Emitted parts share the activity buffer and are drained by `streamToWire` at the same points — they appear in the stream in emit order, before the model's text response.
240
-
241
- `SkillSet` members: `tools`, `drainActivities()`, `hadFailure`, `failureContext`.
242
-
243
- `SkillSetOptions`: `language?` — selects label variant (`'en'` default). `debug?` — emit `console.debug` logs per skill execution (default: `false`).
244
-
245
- #### `streamToWire(fullStream, skillSet?, options?)`
246
-
247
- Converts ai-sdk `fullStream` to Juneau wire SSE strings. Handles all ai-sdk v7 text chunk types (`text-delta` and `text`), drains activity buffer at the right moment, emits `done` at the end. Pass `{ debug: true }` to log every chunk received from ai-sdk.
248
-
249
- #### `withToolRecovery(options)`
250
-
251
- Multi-phase pattern for Gemini-style tool calls. Phase 1 streams with tools. Phase 2 triggers only when a tool failed **and** no text was produced — it calls the model without tools and injects the failure context to force a text response. Phase 3 (optional) handles the silent-success case Gemini 2.5 Flash often treats a successful tool call as its complete response and never writes text. When the tool succeeded but no text was produced, `phase3` receives the full phase 1 message history (resolved from the ai-sdk result's `messages` promise includes tool-call and tool-result turns, which Gemini requires to accept the history) so a second model call without tools can summarise the result. Errors thrown by phase 2/3 are emitted as wire `error` events instead of a silent `done`. Pass `debug: true` to log phase decisions, the resolved phase 3 history, and the `textProduced` / `hadFailure` state at each decision point.
252
-
253
- ```ts
254
- yield* withToolRecovery({
255
- phase1: () => streamText({ model, system, messages, tools: skillSet.tools, maxSteps: 2 }),
256
- phase2: (ctx) => streamText({ model, system, messages: [...messages, { role: 'assistant', content: ctx }] }),
257
- phase3: (fullMessages) => streamText({ model, system, messages: fullMessages }), // no tools — forced text
258
- skillSet,
259
- });
260
- ```
261
-
262
- ---
263
-
264
- ### Juneau wire protocol for Juneau-compatible backends
265
-
266
- If your backend is built specifically for Juneau (e.g. Tappeer), stream newline-delimited JSON where each line is one of these shapes. Both `createSseAdapter` and `createFetchStreamAdapter` parse this automatically — no custom `parseEvent` or `parseChunk` needed.
267
-
268
- ```ts
269
- // Text chunk — appended to the current assistant bubble
270
- { "type": "text", "text": "Here is what I found:" }
271
-
272
- // Activity shows AI progress (skill selection, tool calls, etc.)
273
- // Send the same `id` with a new status to update in-place
274
- { "type": "activity", "id": "skill-select", "title": "Selecting skill", "description": "Finding the best skill for this request.", "status": "running" }
275
- { "type": "activity", "id": "skill-select", "title": "Skill selected", "description": "Using Document Search.", "status": "done" }
276
- { "type": "activity", "id": "doc-search", "title": "Searching document", "status": "running" }
277
- { "type": "activity", "id": "doc-search", "title": "Document found", "description": "INV-2024-0894", "status": "done" }
278
-
279
- // Rich block — table or proposal
280
- { "type": "part", "part": { "type": "table", "columns": ["Name", "Amount"], "rows": [...] } }
281
- { "type": "part", "part": { "type": "proposal", "proposal": { "id": "...", "title": "..." } } }
282
-
283
- // Stream finished cleanly
284
- { "type": "done" }
285
-
286
- // Stream errorends the stream
287
- { "type": "error", "message": "Something went wrong." }
288
- ```
289
-
290
- **Activity `status` values:** `running` | `done` | `failed`
291
-
292
- **Activity `id` behaviour:**
293
- - With `id` — a later event with the same `id` updates the existing row in-place (running → done)
294
- - Without `id` each activity appends as a new timeline row
295
-
296
- **Activity `metadata`** is an optional opaque object not rendered by Juneau, available for logging or custom renderers. Use it for internal data (tool name, duration, skill ID) that should not be shown to the user.
297
-
298
- `createSseAdapter` also retains OpenAI-format fallback parsing (`choices[0].delta.content`) so it works with both Juneau-compatible backends and standard OpenAI proxies.
299
-
300
- ---
301
-
302
- ### `mockAdapter` — for development
303
-
304
- Shipped for local development. No backend needed — responds to keywords in the message:
305
-
306
- | Say... | Gets you... |
307
- |---|---|
308
- | `"show"`, `"list"`, `"data"`, `"table"` | A rendered data table |
309
- | `"suggest"`, `"recommend"`, `"proposal"` | A proposal card with confirm/cancel |
310
- | `"activity"`, `"progress"`, `"document"` | An activity timeline with running/done states |
311
- | `"help"`, `"what can you do"` | Capability overview |
312
- | `"error"`, `"fail"` | Simulated error response |
313
- | anything else | Explains the available triggers |
314
-
315
- ```ts
316
- import { mockAdapter } from 'juneau';
317
- // Pass to AiChatProvider — see below
318
- ```
319
-
320
- ---
321
-
322
- ## Providers
323
-
324
- ### `<JuneauProvider>`
325
-
326
- Wrap your app once. Provides theme tokens and UI labels to all Juneau components below it.
327
-
328
- ```tsx
329
- import { JuneauProvider, juneauCs } from 'juneau';
330
-
331
- <JuneauProvider
332
- theme={{ colorPrimary: '#0f766e', colorAccent: '#14b8a6' }}
333
- labels={juneauCs}
334
- >
335
- {children}
336
- </JuneauProvider>
337
- ```
338
-
339
- | Prop | Type | Description |
340
- |---|---|---|
341
- | `theme` | `JuneauTheme` | Override design tokens. Only specified keys are applied. |
342
- | `labels` | `Partial<JuneauLabels>` | Override UI strings. Omitted keys fall back to English. |
343
- | `className` | `string` | Added to the root `<div>`. |
344
- | `style` | `CSSProperties` | Inline styles on the root `<div>`. |
345
-
346
- ---
347
-
348
- ### `<AiChatProvider>`
349
-
350
- Holds the shared conversation state. Wrap your app (or layout) once — any page can then render `<AiSidebar />` without losing conversation history on navigation.
351
-
352
- ```tsx
353
- import { AiChatProvider } from 'juneau';
354
-
355
- <AiChatProvider
356
- adapter={myAdapter}
357
- onProposalConfirm={(id, payload) => handleAction(id, payload)}
358
- onProposalCancel={(id) => handleDismiss(id)}
359
- >
360
- <App />
361
- </AiChatProvider>
362
- ```
363
-
364
- | Prop | Type | Description |
365
- |---|---|---|
366
- | `adapter` | `AiBackendAdapter` | **Required.** Your adapter. |
367
- | `context` | `Record<string, unknown>` | Initial context forwarded to every adapter call. Update per-page via `setContext()`. |
368
- | `onProposalConfirm` | `(id, payload) => void` | Called when user confirms a proposal card. |
369
- | `onProposalCancel` | `(id) => void` | Called when user cancels a proposal card. |
370
-
371
- **Updating context per page:**
372
-
373
- Use `setContext()` from `useAiChatContext()` to tell the AI where the user is on each page. The context is forwarded opaquely to every `adapter.sendMessage` call as `input.context`.
374
-
375
- ```tsx
376
- import { useAiChatContext } from 'juneau';
377
-
378
- function InvoicesPage() {
379
- const { setContext } = useAiChatContext();
380
-
381
- useEffect(() => {
382
- setContext({
383
- page: 'invoices',
384
- availableTools: ['search', 'export'],
385
- userRole: 'admin',
386
- });
387
- }, []);
388
-
389
- return <main>...</main>;
390
- }
391
- ```
392
-
393
- ---
394
-
395
- ## Components
396
-
397
- ### `<AiSidebar>`
398
-
399
- Fixed-position chat panel. Reads all state from the nearest `<AiChatProvider>` — renders wherever you place it, conversation persists across navigation.
400
-
401
- The sidebar anchors to the bottom-right of the viewport and opens at 60% screen height by default. Users can minimize it to a compact header bar.
402
-
403
- ```tsx
404
- <AiSidebar
405
- title="AI Assistant"
406
- height="70vh"
407
- />
408
- ```
409
-
410
- | Prop | Type | Description |
411
- |---|---|---|
412
- | `title` | `string` | Overrides the `sidebarTitle` label for this instance. |
413
- | `icon` | `ReactNode` | Override the header + avatar icon. Defaults to a wand icon. |
414
- | `actions` | `AiInputAction[]` | Toolbar buttons left of send. Pass `[]` to hide entirely. |
415
- | `sendIcon` | `ReactNode` | Override the send button icon. |
416
- | `height` | `string` | Height when open. Any CSS value. Defaults to `'60vh'`. |
417
- | `className` | `string` | Added to the `<aside>` element. |
418
- | `style` | `CSSProperties` | Inline styles on the `<aside>`. |
419
-
420
- ---
421
-
422
- ### `<AiChat>`
423
-
424
- Headless chat body — message list + input bar + error banner, no surrounding chrome. Use this when you want to embed chat inside your own layout (dashboard panel, modal, full-page view).
425
-
426
- The parent is responsible for calling `useAiChat` and passing results down as props.
427
-
428
- ```tsx
429
- import { useAiChat, AiChat } from 'juneau';
430
-
431
- function MyPage() {
432
- const chat = useAiChat({ adapter });
433
-
434
- return (
435
- <div className="my-layout">
436
- <MySidebar />
437
- <AiChat
438
- messages={chat.messages}
439
- input={chat.input}
440
- isLoading={chat.isLoading}
441
- error={chat.error}
442
- onInputChange={chat.setInput}
443
- onSend={chat.sendMessage}
444
- onStop={chat.stop}
445
- onProposalConfirm={chat.confirmProposal}
446
- onProposalCancel={chat.cancelProposal}
447
- />
448
- </div>
449
- );
450
- }
451
- ```
452
-
453
- | Prop | Type | Description |
454
- |---|---|---|
455
- | `messages` | `AiMessage[]` | Conversation history. |
456
- | `input` | `string` | Current textarea value. |
457
- | `isLoading` | `boolean` | Whether a stream is in progress. |
458
- | `error` | `string \| null` | Last error message, or `null`. |
459
- | `onInputChange` | `(value: string) => void` | Input change handler. |
460
- | `onSend` | `() => void` | Send the current input. |
461
- | `onStop` | `() => void` | Abort the in-flight stream. Renders a stop button while loading. |
462
- | `onProposalConfirm` | `(id, payload) => void` | Proposal confirmed. |
463
- | `onProposalCancel` | `(id) => void` | Proposal cancelled. |
464
- | `assistantIcon` | `ReactNode` | Override the assistant avatar in all bubbles. |
465
- | `actions` | `AiInputAction[]` | Toolbar buttons. |
466
- | `sendIcon` | `ReactNode` | Override send button icon. |
467
- | `placeholder` | `string` | Input placeholder text. |
468
- | `renderPart` | `RenderPartFn` | Custom part renderer — see below. |
469
-
470
- ---
471
-
472
- ## Custom part rendering `renderPart`
473
-
474
- Both `AiSidebar` and `AiChat` accept a `renderPart` prop an escape hatch for rendering consumer-defined part types (or overriding built-in ones):
475
-
476
- ```ts
477
- type RenderPartFn = (part: AiMessagePart) => ReactNode | null | undefined;
478
- ```
479
-
480
- It is called **before** the built-in renderers for every message part. Return a ReactNode to render it; return `null`/`undefined` to fall through to the built-ins (`text`, `table`, `proposal`, `activity`, `error`).
481
-
482
- The backend can stream any custom part through the standard wire protocol:
483
-
484
- ```json
485
- { "type": "part", "part": { "type": "invoice-card", "invoiceNumber": "23251", "amount": "1200.00" } }
486
- ```
487
-
488
- `AiCustomPart` (`{ type: string; [key: string]: unknown }`) is part of the `AiMessagePart` union, so TypeScript accepts custom shapes on both ends. Juneau applies **no validation or narrowing** to custom parts — the consumer owns all type assertions:
489
-
490
- ```tsx
491
- // Define your part type wherever you likeJuneau doesn't need to know about it
492
- type InvoiceCardPart = { type: 'invoice-card'; invoiceNumber: string; amount: string };
493
-
494
- <AiSidebar renderPart={part => {
495
- if (part.type === 'invoice-card') return <InvoiceCard part={part as InvoiceCardPart} />;
496
- return null; // everything else falls through to the built-ins
497
- }} />
498
- ```
499
-
500
- Unhandled custom part types show a dashed warning outline in development (so they're never a silent mystery) and render nothing in production.
501
-
502
- ---
503
-
504
- ## `useAiChat` hook
505
-
506
- For full control over layout and behaviour. Returns everything needed to build a custom chat UI.
507
-
508
- ```ts
509
- const {
510
- messages, // AiMessage[] — full conversation history
511
- input, // string current textarea value
512
- setInput, // (value: string) => void
513
- sendMessage, // () => Promise<void> sends current input as user message
514
- sendMessageWithText, // (text: string) => Promise<void> — send programmatically, no input state change
515
- sendGreeting, // (contextHint: string) => Promise<void> — assistant speaks first, no user bubble shown
516
- stop, // () => void — abort in-flight stream, keep existing messages
517
- isLoading, // boolean true while streaming
518
- isConnecting, // boolean — true from send until first token arrives
519
- error, // string | null — last error, cleared on next send
520
- reset, // () => void — clear all messages and abort any stream
521
- confirmProposal, // (id: string, payload: unknown) => void
522
- cancelProposal, // (id: string) => void
523
- } = useAiChat({
524
- adapter, // required
525
- context, // optional — forwarded to every adapter.sendMessage call
526
- onProposalConfirm, // optional — called by confirmProposal
527
- onProposalCancel, // optionalcalled by cancelProposal
528
- });
529
- ```
530
-
531
- ## `useAiChatContext` hook
532
-
533
- Reads the shared state from `<AiChatProvider>`. Includes everything from `useAiChat` plus `setContext()`.
534
-
535
- ```ts
536
- const {
537
- // all useAiChat fields +
538
- setContext, // (ctx: Record<string, unknown>) => void — update context forwarded to adapter
539
- } = useAiChatContext();
540
- ```
541
-
542
- Throws a descriptive error if called outside `<AiChatProvider>`.
543
-
544
- ---
545
-
546
- ### Useful patterns
547
-
548
- **Proactive greeting on mount (`sendGreeting`):**
549
-
550
- `sendGreeting(hint)` sends the hint as a `system` role message to the adapter and streams the response as an assistant-only message — no user bubble is added to the conversation. Perfect for page-load summaries where the AI speaks first.
551
-
552
- ```ts
553
- const { sendGreeting } = useAiChatContext();
554
-
555
- useEffect(() => {
556
- sendGreeting(
557
- 'The user is viewing the Invoices page. ' +
558
- 'Briefly introduce what you can help with on this page.'
559
- );
560
- }, []);
561
- ```
562
-
563
- **Trigger from outside the chat (e.g. clicking a data row):**
564
- ```ts
565
- const { sendMessageWithText } = useAiChatContext();
566
- sendMessageWithText(`Summarise order #${order.id} for me`);
567
- ```
568
-
569
- **Pass page context to every request:**
570
- ```tsx
571
- const { setContext } = useAiChatContext();
572
-
573
- useEffect(() => {
574
- setContext({ pageId: 'invoices', entityId: invoice.id, userRole: 'admin' });
575
- }, [invoice.id]);
576
- ```
577
-
578
- The `context` object lands in `input.context` inside every `adapter.sendMessage` call — use it to inject page-level data without polluting the message history.
579
-
580
- **Reading message text in your adapter:**
581
-
582
- Don't dig into `parts` manually — use the exported `getMessageText` helper:
583
-
584
- ```ts
585
- import { getMessageText } from 'juneau';
586
-
587
- async *sendMessage({ messages }) {
588
- const lastUser = [...messages].reverse().find(m => m.role === 'user');
589
- const text = lastUser ? getMessageText(lastUser) : '';
590
- // → plain string, all text parts concatenated
591
- }
592
- ```
593
-
594
- **Auth bearer token from React context:**
595
- ```ts
596
- const adapter = createSseAdapter('/api/chat', {
597
- getHeaders: async () => ({
598
- Authorization: `Bearer ${await getAccessToken()}`,
599
- }),
600
- });
601
- ```
602
-
603
- **Auth — session cookie (no extra config needed):**
604
-
605
- Cookies are sent automatically by `fetch` to same-origin URLs. Just use `createSseAdapter('/api/chat')` with no headers — the browser attaches the session cookie for you.
606
-
607
- For cross-origin backends, add `credentials: 'include'` by writing a custom adapter:
608
-
609
- ```ts
610
- const adapter: AiBackendAdapter = {
611
- async *sendMessage({ messages }) {
612
- const res = await fetch('https://api.example.com/chat', {
613
- method: 'POST',
614
- credentials: 'include', // sends cookies cross-origin
615
- headers: { 'Content-Type': 'application/json' },
616
- body: JSON.stringify({ messages }),
617
- });
618
- // …stream response
619
- },
620
- };
621
- ```
622
-
623
- **Stop button feedback:**
624
-
625
- When `onStop` is provided, the send button becomes a stop button while streaming. After the user hits stop, `isLoading` goes false immediately and the existing partial response stays visible in the conversation there's no error state, the stream just ends cleanly where it was cut.
626
-
627
- ---
628
-
629
- ## Message parts
630
-
631
- Assistant messages are composed of typed **parts**. Text is streamed chunk by chunk; rich UI blocks are emitted as complete `part` events.
632
-
633
- | Part type | Emitted as | Rendered by |
634
- |---|---|---|
635
- | `text` | `{ type: 'text', text: string }` stream events, accumulated | Markdown via `react-markdown` — safe against XSS |
636
- | `table` | `{ type: 'part', part: { type: 'table', ... } }` | `AiTablePart` |
637
- | `proposal` | `{ type: 'part', part: { type: 'proposal', ... } }` | `AiProposalCard` |
638
- | `activity` | `{ type: 'part', part: { type: 'activity', ... } }` | `AiActivityPart` |
639
- | `error` | `{ type: 'error', message: string }` or `{ type: 'part', part: { type: 'error', ... } }` | Inline error in bubble |
640
-
641
- **Emitting an activity from your adapter:**
642
-
643
- Activity parts show the user what the AI is doing while it works — skill selection, document search, tool calls, etc. They have three states: `running`, `done`, `failed`.
644
-
645
- ```ts
646
- // Show a running activity
647
- yield {
648
- type: 'part',
649
- part: {
650
- type: 'activity',
651
- id: 'doc-search', // optional stable ID enables in-place update
652
- title: 'Searching document',
653
- description: 'Looking up document by ID.',
654
- status: 'running',
655
- },
656
- };
657
-
658
- // Later: update the same activity in-place (same id)
659
- yield {
660
- type: 'part',
661
- part: {
662
- type: 'activity',
663
- id: 'doc-search',
664
- title: 'Document found',
665
- description: 'Found document INV-2024-0894.',
666
- status: 'done',
667
- },
668
- };
669
- ```
670
-
671
- If `id` is provided, a later activity part with the same `id` updates the previous one in-place instead of appending a new row. Without `id`, activity parts append as a timeline.
672
-
673
- **Emitting a proposal from your adapter:**
674
- ```ts
675
- yield {
676
- type: 'part',
677
- part: {
678
- type: 'proposal',
679
- proposal: {
680
- id: 'confirm-delete', // passed back to onProposalConfirm
681
- title: 'Delete this item?',
682
- description: 'This cannot be undone.',
683
- confirmLabel: 'Delete', // optional, falls back to labels.proposalConfirm
684
- cancelLabel: 'Keep', // optional, falls back to labels.proposalCancel
685
- payload: { itemId: 42 }, // anything — you get it back in onProposalConfirm
686
- },
687
- },
688
- };
689
- ```
690
-
691
- **Emitting a table:**
692
- ```ts
693
- yield {
694
- type: 'part',
695
- part: {
696
- type: 'table',
697
- columns: ['Name', 'Amount', 'Status'],
698
- rows: [
699
- { Name: 'Item A', Amount: '$1,200', Status: 'Paid' },
700
- { Name: 'Item B', Amount: '$840', Status: 'Pending' },
701
- ],
702
- },
703
- };
704
- ```
705
-
706
- ---
707
-
708
- ## Theming
709
-
710
- All visual values are CSS custom properties prefixed `--juneau-`. Override them via `JuneauProvider`:
711
-
712
- ```tsx
713
- <JuneauProvider theme={{
714
- colorPrimary: '#1d4ed8',
715
- colorAccent: '#7c3aed',
716
- radiusLg: '16px',
717
- fontFamily: '"Inter", sans-serif',
718
- }}>
719
- ```
720
-
721
- Only keys you specify are overridden — everything else keeps its default. Overrides are scoped to the provider's subtree so multiple providers with different themes can coexist.
722
-
723
- ### Full theme reference
724
-
725
- | Key | CSS variable | Default | Usage |
726
- |---|---|---|---|
727
- | `colorPrimary` | `--juneau-color-primary` | `#000000` | Send button, user bubble |
728
- | `colorPrimaryDark` | `--juneau-color-primary-dark` | `#252528` | Primary hover state |
729
- | `colorPrimaryLight` | `--juneau-color-primary-light` | `#ECECEC` | Primary tinted backgrounds |
730
- | `colorAccent` | `--juneau-color-accent` | `#FF49A4` | Header bg, proposal confirm, avatar |
731
- | `colorAccentDark` | `--juneau-color-accent-dark` | `#FF6BB3` | Accent hover |
732
- | `colorAccentLight` | `--juneau-color-accent-light` | `#FFF0F7` | Proposal card background |
733
- | `colorSurface` | `--juneau-color-surface` | `#FFFFFF` | Cards, sidebar, input background |
734
- | `colorSurfaceRaised` | `--juneau-color-surface-raised` | `#F4F4F6` | Page background, table headers |
735
- | `colorSurfaceHover` | `--juneau-color-surface-hover` | `#ECECEC` | Row hover |
736
- | `colorBorder` | `--juneau-color-border` | `#E8E8EC` | Default borders |
737
- | `colorTextPrimary` | `--juneau-color-text-primary` | `#000000` | Main body text |
738
- | `colorTextSecondary` | `--juneau-color-text-secondary` | `#474747` | Supporting text |
739
- | `colorTextMuted` | `--juneau-color-text-muted` | `#474747` | Labels, hints |
740
- | `colorTextFaint` | `--juneau-color-text-faint` | `#9090A0` | Empty states |
741
- | `colorTextInverse` | `--juneau-color-text-inverse` | `#FFFFFF` | Text on dark backgrounds |
742
- | `colorAssistantAvatar` | `--juneau-color-assistant-avatar` | `#FF49A4` | Assistant avatar circle |
743
- | `radiusSm` | `--juneau-radius-sm` | `6px` | Buttons, small elements |
744
- | `radiusMd` | `--juneau-radius-md` | `8px` | Inputs, cards |
745
- | `radiusLg` | `--juneau-radius-lg` | `12px` | Panels, large cards |
746
- | `fontFamily` | `--juneau-font-family` | system-ui | Font used across all components |
747
-
748
- ---
749
-
750
- ## i18n / Labels
751
-
752
- All UI strings are overridable. Built-in locales: `juneauEn` (default) and `juneauCs`.
753
-
754
- ```tsx
755
- import { juneauCs } from 'juneau';
756
- <JuneauProvider labels={juneauCs}>...</JuneauProvider>
757
- ```
758
-
759
- Pass any `Partial<JuneauLabels>` — omitted keys fall back to English:
760
-
761
- ```tsx
762
- <JuneauProvider labels={{ sidebarTitle: 'Ask AI', sendMessage: 'Send' }}>
763
- ```
764
-
765
- ### Full label reference
766
-
767
- | Key | Default (EN) | Used in |
768
- |---|---|---|
769
- | `sidebarTitle` | `AI Assistant` | `AiChatHeader` title |
770
- | `minimizeSidebar` | `Minimize` | `AiChatHeader` minimize button |
771
- | `expandSidebar` | `Expand` | `AiChatHeader` expand button (when minimized) |
772
- | `inputPlaceholder` | `Ask a question… (Enter to send)` | `AiInput` textarea |
773
- | `sendMessage` | `Send message` | `AiInput` send button |
774
- | `stopMessage` | `Stop` | `AiInput` stop button (while streaming) |
775
- | `emptyStateText` | `How can I help you today?` | `AiMessageList` empty state |
776
- | `emptyStateHint` | `Try: "Show me the data" or "Can you suggest something?"` | `AiMessageList` empty state hint |
777
- | `proposalConfirm` | `Confirm` | `AiProposalCard` fallback confirm label |
778
- | `proposalCancel` | `Cancel` | `AiProposalCard` fallback cancel label |
779
- | `errorDismiss` | `Dismiss` | `AiError` dismiss button |
780
- | `actionAddFile` | `Add file` | `AiInput` toolbar |
781
- | `actionQuickActions` | `Quick actions` | `AiInput` toolbar |
782
- | `actionNew` | `New` | `AiInput` toolbar |
783
- | `actionHistory` | `History` | `AiInput` toolbar |
784
- | `actionRules` | `Rules` | `AiInput` toolbar |
785
-
786
- ---
787
-
788
- ## Custom toolbar actions
789
-
790
- The toolbar buttons left of the send button are fully configurable:
791
-
792
- ```tsx
793
- <AiSidebar
794
- actions={[
795
- {
796
- icon: <MyAttachIcon />,
797
- label: 'Attach file',
798
- onClick: () => openFilePicker(),
799
- },
800
- {
801
- icon: <MyTemplatesIcon />,
802
- label: 'Templates',
803
- onClick: () => openTemplateMenu(),
804
- },
805
- ]}
806
- />
807
-
808
- // Hide the toolbar entirely:
809
- <AiSidebar actions={[]} />
810
- ```
811
-
812
- Each action: `{ icon: ReactNode, label: string, onClick?: () => void }`
813
-
814
- ---
815
-
816
- ## Security
817
-
818
- - **No API keys in the library** all AI calls happen in your adapter, which calls your backend. Juneau never sees credentials.
819
- - **XSS-safe markdown** — text parts are rendered via `react-markdown`, which never uses `dangerouslySetInnerHTML`. Malicious model output cannot inject scripts.
820
- - **No data storage** Juneau holds conversation state in React memory only. Nothing is persisted or sent anywhere by the library itself.
821
-
822
- ---
823
-
824
- ## License
825
-
826
- MIT
827
-
828
- ---
829
-
830
- ## Icon attribution
831
-
832
- Icons used internally by Juneau are from [Font Awesome Free](https://fontawesome.com) (v6), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). SVG paths are inlined directly — no runtime dependency on the Font Awesome package.
833
-
834
- Icons used: `crow`, `paper-plane`, `paperclip`, `bolt`, `plus`, `clock-rotate-left`, `scroll`, `arrow-rotate-left`, `window-minimize`, `window-restore`.
1
+ # Juneau
2
+
3
+ React component library for building AI chat interfaces. Streaming-first, adapter-based, fully themeable.
4
+
5
+ ```tsx
6
+ import { JuneauProvider, AiChatProvider, AiSidebar, createSseAdapter } from 'juneau';
7
+ import 'juneau/dist/style.css';
8
+
9
+ const adapter = createSseAdapter('/api/chat');
10
+
11
+ <JuneauProvider>
12
+ <AiChatProvider adapter={adapter}>
13
+ <App />
14
+ <AiSidebar />
15
+ </AiChatProvider>
16
+ </JuneauProvider>
17
+ ```
18
+
19
+ ---
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ npm install juneau
25
+ ```
26
+
27
+ **Peer dependencies:** `react ^18 || ^19`, `react-dom ^18 || ^19`
28
+
29
+ ---
30
+
31
+ ## Core concept — the adapter
32
+
33
+ Juneau never calls any AI API directly. **You own the network layer.** Juneau provides the UI, state, and streaming machinery — you provide an adapter that connects it to your backend.
34
+
35
+ An adapter is just one method:
36
+
37
+ ```ts
38
+ interface AiBackendAdapter {
39
+ sendMessage(input: AiAdapterInput): AsyncIterable<AiStreamEvent>;
40
+ }
41
+ ```
42
+
43
+ It receives the conversation history and streams back typed events:
44
+
45
+ ```ts
46
+ type AiStreamEvent =
47
+ | { type: 'text'; text: string } // streamed text chunk — append to current bubble
48
+ | { type: 'part'; part: AiMessagePart } // rich UI block (table, proposal, activity, error)
49
+ | { type: 'done' } // stream finished cleanly
50
+ | { type: 'error'; message: string } // stream failed
51
+ ```
52
+
53
+ This means your API keys stay on your backend, you control auth, rate limiting, model selection — Juneau just renders whatever comes back.
54
+
55
+ ---
56
+
57
+ ## Built-in adapters
58
+
59
+ Juneau ships two factory functions so you don't have to write boilerplate streaming code.
60
+
61
+ ### `createSseAdapter(url, options?)` — recommended
62
+
63
+ For backends that stream **Server-Sent Events (SSE)** — the format used by OpenAI, Anthropic, and most AI API proxies.
64
+
65
+ The default parser understands OpenAI's streaming format out of the box (`choices[0].delta.content`).
66
+
67
+ ```ts
68
+ import { createSseAdapter } from 'juneau';
69
+
70
+ // OpenAI-compatible backend — zero config needed:
71
+ const adapter = createSseAdapter('/api/chat');
72
+
73
+ // With dynamic auth header:
74
+ const adapter = createSseAdapter('/api/chat', {
75
+ getHeaders: async () => ({
76
+ Authorization: `Bearer ${await getSessionToken()}`,
77
+ }),
78
+ });
79
+
80
+ // Custom request body:
81
+ const adapter = createSseAdapter('/api/chat', {
82
+ getBody: ({ messages, context }) => ({
83
+ messages,
84
+ model: 'gpt-4o',
85
+ stream: true,
86
+ temperature: 0.7,
87
+ }),
88
+ });
89
+
90
+ // Custom SSE event schema (backend streams { text: "..." } instead of OpenAI format):
91
+ const adapter = createSseAdapter('/api/chat', {
92
+ parseEvent: (data) => {
93
+ try {
94
+ const json = JSON.parse(data);
95
+ return json.text ? [{ type: 'text', text: json.text }] : [];
96
+ } catch {
97
+ return [];
98
+ }
99
+ },
100
+ });
101
+ ```
102
+
103
+ | Option | Type | Default | Description |
104
+ |---|---|---|---|
105
+ | `method` | `string` | `'POST'` | HTTP method |
106
+ | `headers` | `Record<string, string>` | `{}` | Static headers, merged with Content-Type |
107
+ | `getHeaders` | `(input) => Record<string, string>` | — | Dynamic headers, called per request. Merged on top of `headers`. |
108
+ | `getBody` | `(input) => unknown` | `{ messages, context }` | Override request body |
109
+ | `parseEvent` | `(data: string) => AiStreamEvent[]` | OpenAI parser | Parse each `data: ...` SSE line into events |
110
+
111
+ ---
112
+
113
+ ### `createFetchStreamAdapter(url, options?)` — for non-SSE backends
114
+
115
+ For backends that stream **newline-delimited JSON (NDJSON)** or plain text — raw chunked HTTP without SSE formatting.
116
+
117
+ The default parser expects `{ "text": "..." }` or `{ "done": true }` JSON lines.
118
+
119
+ ```ts
120
+ import { createFetchStreamAdapter } from 'juneau';
121
+
122
+ // NDJSON backend (streams { text: "..." } lines):
123
+ const adapter = createFetchStreamAdapter('/api/chat');
124
+
125
+ // Plain text — treat every chunk as raw text:
126
+ const adapter = createFetchStreamAdapter('/api/chat', {
127
+ parseChunk: (chunk) => chunk ? [{ type: 'text', text: chunk }] : [],
128
+ });
129
+
130
+ // Custom JSON lines schema:
131
+ const adapter = createFetchStreamAdapter('/api/chat', {
132
+ parseChunk: (chunk) => {
133
+ try {
134
+ const json = JSON.parse(chunk);
135
+ if (json.error) return [{ type: 'error', message: json.error }];
136
+ if (json.done) return [{ type: 'done' }];
137
+ if (json.delta) return [{ type: 'text', text: json.delta }];
138
+ return [];
139
+ } catch { return []; }
140
+ },
141
+ });
142
+ ```
143
+
144
+ | Option | Type | Default | Description |
145
+ |---|---|---|---|
146
+ | `method` | `string` | `'POST'` | HTTP method |
147
+ | `headers` | `Record<string, string>` | `{}` | Static headers |
148
+ | `getHeaders` | `(input) => Record<string, string>` | — | Dynamic headers, called per request |
149
+ | `getBody` | `(input) => unknown` | `{ messages, context }` | Override request body |
150
+ | `parseChunk` | `(chunk: string) => AiStreamEvent[]` | NDJSON parser | Parse each newline-delimited chunk into events |
151
+
152
+ ---
153
+
154
+ ### Writing your own adapter
155
+
156
+ If neither factory fits, implementing the interface directly takes about 10 lines:
157
+
158
+ ```ts
159
+ import type { AiBackendAdapter } from 'juneau';
160
+
161
+ export const myAdapter: AiBackendAdapter = {
162
+ async *sendMessage({ messages, context }) {
163
+ const res = await fetch('/api/chat', {
164
+ method: 'POST',
165
+ headers: { 'Content-Type': 'application/json' },
166
+ body: JSON.stringify({ messages }),
167
+ });
168
+
169
+ const reader = res.body!.getReader();
170
+ const decoder = new TextDecoder();
171
+
172
+ while (true) {
173
+ const { done, value } = await reader.read();
174
+ if (done) break;
175
+ yield { type: 'text', text: decoder.decode(value) };
176
+ }
177
+
178
+ yield { type: 'done' };
179
+ },
180
+ };
181
+ ```
182
+
183
+ ---
184
+
185
+ ### Backend utilities — `juneau/server`
186
+
187
+ If your backend uses ai-sdk, Juneau ships server-side helpers that eliminate the boilerplate of history mapping, activity streaming, and tool failure recovery. Import from the `/server` subpath — zod stays out of the browser bundle.
188
+
189
+ ```ts
190
+ import { toSdkMessages, createSkillSet, buildSkillIndex, selectSkills, withToolRecovery } from 'juneau/server';
191
+ ```
192
+
193
+ **Full integration in ~15 lines:**
194
+
195
+ ```ts
196
+ import { toSdkMessages, createSkillSet, withToolRecovery } from 'juneau/server';
197
+ import { streamText } from 'ai';
198
+ import { z } from 'zod';
199
+
200
+ const skillSet = createSkillSet({
201
+ search: {
202
+ title: 'Record Search',
203
+ description: 'Search for records.',
204
+ instructions: 'Present results concisely. If cards are shown, write one sentence only.',
205
+ input: z.object({ query: z.string() }),
206
+ labels: {
207
+ running: { en: 'Searching…', cs: 'Vyhledávám…' },
208
+ done: { en: 'Results found', cs: 'Nalezeno' },
209
+ },
210
+ execute: async ({ query }) => db.search(query),
211
+ },
212
+ }, { language: context.language });
213
+
214
+ for await (const chunk of withToolRecovery({
215
+ phase1: () => streamText({ model, system, messages: toSdkMessages(input.messages), tools: skillSet.tools, maxSteps: 1 }),
216
+ phase2: (ctx) => streamText({ model, system, messages: [...toSdkMessages(input.messages), { role: 'assistant', content: ctx }] }),
217
+ skillSet,
218
+ })) {
219
+ res.write(chunk);
220
+ }
221
+ ```
222
+
223
+ #### `toSdkMessages(messages)`
224
+
225
+ Converts `AiMessage[]` to `CoreMessage[]` for ai-sdk. Extracts text from parts, fixes conversation alternation (no two consecutive user turns), filters empty turns.
226
+
227
+ #### `createSkillSet(skills, options?)`
228
+
229
+ Wraps skill definitions into ai-sdk `tools` with a built-in activity buffer. Each tool call automatically emits `running` / `done` / `failed` Juneau wire SSE strings no manual activity handling needed.
230
+
231
+ `execute` receives a `SkillExecuteContext` as its second argument with an `emit(part)` callback — push custom part wire events into the stream alongside the activities, e.g. an invoice card widget the frontend renders via `renderPart`:
232
+
233
+ ```ts
234
+ execute: async ({ query }, { emit }) => {
235
+ const inv = await db.findInvoice(query);
236
+ emit({ type: 'invoice-card', invoiceNumber: inv.number, amount: inv.total });
237
+ return { found: 1, invoice: inv }; // returned to the model as the tool result
238
+ },
239
+ ```
240
+
241
+ Emitted parts share the activity buffer and are drained by `streamToWire` at the same points — they appear in the stream in emit order, before the model's text response.
242
+
243
+ Skill metadata: `title` (human-readable name), `instructions?` (agent workflow text lazily loaded via `selectSkills`), `readOnly?` (default `true`), `requiresConfirmation?` (default `false`), `tools?` (skill composition validated at startup, `createSkillSet` throws on a reference to an unknown skill).
244
+
245
+ `SkillSet` members: `tools`, `skills`, `calledSkillNames`, `drainActivities()`, `hadFailure`, `failureContext`.
246
+
247
+ `SkillSetOptions`: `language?` selects label variant (`'en'` default). `debug?` emit `console.debug` logs per skill execution (default: `false`).
248
+
249
+ #### `buildSkillIndex(skillSet)`
250
+
251
+ Generates a compact one-liner-per-skill index for the system promptregistry-driven, so the prompt never drifts from the actual skills:
252
+
253
+ ```
254
+ - invoiceSearch (read): Find invoices by number, supplier, date, or status.
255
+ - invoiceApprove (write, requires confirmation): Approve an invoice.
256
+ ```
257
+
258
+ #### `selectSkills(skillSet, skillNames)`
259
+
260
+ Returns concatenated `instructions` for the given skill names — typically `skillSet.calledSkillNames` after phase 1, injected into phase 3's system prompt. Workflow instructions load lazily, only for skills the model actually used.
261
+
262
+ #### `streamToWire(fullStream, skillSet?, options?)`
263
+
264
+ Converts ai-sdk `fullStream` to Juneau wire SSE strings. Handles all ai-sdk v7 text chunk types (`text-delta` and `text`), drains activity buffer at the right moment, emits `done` at the end. Pass `{ debug: true }` to log every chunk received from ai-sdk.
265
+
266
+ #### `withToolRecovery(options)`
267
+
268
+ Multi-phase pattern for Gemini-style tool calls. Phase 1 streams with tools. Phase 2 triggers only when a tool failed **and** no text was produced — it calls the model without tools and injects the failure context to force a text response. Phase 3 (optional) handles the silent-success case — Gemini 2.5 Flash often treats a successful tool call as its complete response and never writes text. When the tool succeeded but no text was produced, `phase3` receives the full phase 1 message history (resolved from the ai-sdk result's `messages` promise — includes tool-call and tool-result turns, which Gemini requires to accept the history) so a second model call without tools can summarise the result. Errors thrown by phase 2/3 are emitted as wire `error` events instead of a silent `done`. Pass `debug: true` to log phase decisions, the resolved phase 3 history, and the `textProduced` / `hadFailure` state at each decision point.
269
+
270
+ ```ts
271
+ yield* withToolRecovery({
272
+ phase1: () => streamText({ model, system, messages, tools: skillSet.tools, maxSteps: 2 }),
273
+ phase2: (ctx) => streamText({ model, system, messages: [...messages, { role: 'assistant', content: ctx }] }),
274
+ phase3: (fullMessages) => streamText({ model, system, messages: fullMessages }), // no tools forced text
275
+ skillSet,
276
+ });
277
+ ```
278
+
279
+ ---
280
+
281
+ ### Juneau wire protocol for Juneau-compatible backends
282
+
283
+ If your backend is built specifically for Juneau (e.g. Tappeer), stream newline-delimited JSON where each line is one of these shapes. Both `createSseAdapter` and `createFetchStreamAdapter` parse this automatically — no custom `parseEvent` or `parseChunk` needed.
284
+
285
+ ```ts
286
+ // Text chunkappended to the current assistant bubble
287
+ { "type": "text", "text": "Here is what I found:" }
288
+
289
+ // Activity — shows AI progress (skill selection, tool calls, etc.)
290
+ // Send the same `id` with a new status to update in-place
291
+ { "type": "activity", "id": "skill-select", "title": "Selecting skill", "description": "Finding the best skill for this request.", "status": "running" }
292
+ { "type": "activity", "id": "skill-select", "title": "Skill selected", "description": "Using Document Search.", "status": "done" }
293
+ { "type": "activity", "id": "doc-search", "title": "Searching document", "status": "running" }
294
+ { "type": "activity", "id": "doc-search", "title": "Document found", "description": "INV-2024-0894", "status": "done" }
295
+
296
+ // Rich blocktable or proposal
297
+ { "type": "part", "part": { "type": "table", "columns": ["Name", "Amount"], "rows": [...] } }
298
+ { "type": "part", "part": { "type": "proposal", "proposal": { "id": "...", "title": "..." } } }
299
+
300
+ // Stream finished cleanly
301
+ { "type": "done" }
302
+
303
+ // Stream error — ends the stream
304
+ { "type": "error", "message": "Something went wrong." }
305
+ ```
306
+
307
+ **Activity `status` values:** `running` | `done` | `failed`
308
+
309
+ **Activity `id` behaviour:**
310
+ - With `id` — a later event with the same `id` updates the existing row in-place (running done)
311
+ - Without `id` each activity appends as a new timeline row
312
+
313
+ **Activity `metadata`** is an optional opaque object — not rendered by Juneau, available for logging or custom renderers. Use it for internal data (tool name, duration, skill ID) that should not be shown to the user.
314
+
315
+ `createSseAdapter` also retains OpenAI-format fallback parsing (`choices[0].delta.content`) so it works with both Juneau-compatible backends and standard OpenAI proxies.
316
+
317
+ ---
318
+
319
+ ### `mockAdapter` — for development
320
+
321
+ Shipped for local development. No backend needed — responds to keywords in the message:
322
+
323
+ | Say... | Gets you... |
324
+ |---|---|
325
+ | `"show"`, `"list"`, `"data"`, `"table"` | A rendered data table |
326
+ | `"suggest"`, `"recommend"`, `"proposal"` | A proposal card with confirm/cancel |
327
+ | `"activity"`, `"progress"`, `"document"` | An activity timeline with running/done states |
328
+ | `"help"`, `"what can you do"` | Capability overview |
329
+ | `"error"`, `"fail"` | Simulated error response |
330
+ | anything else | Explains the available triggers |
331
+
332
+ ```ts
333
+ import { mockAdapter } from 'juneau';
334
+ // Pass to AiChatProvider — see below
335
+ ```
336
+
337
+ ---
338
+
339
+ ## Providers
340
+
341
+ ### `<JuneauProvider>`
342
+
343
+ Wrap your app once. Provides theme tokens and UI labels to all Juneau components below it.
344
+
345
+ ```tsx
346
+ import { JuneauProvider, juneauCs } from 'juneau';
347
+
348
+ <JuneauProvider
349
+ theme={{ colorPrimary: '#0f766e', colorAccent: '#14b8a6' }}
350
+ labels={juneauCs}
351
+ >
352
+ {children}
353
+ </JuneauProvider>
354
+ ```
355
+
356
+ | Prop | Type | Description |
357
+ |---|---|---|
358
+ | `theme` | `JuneauTheme` | Override design tokens. Only specified keys are applied. |
359
+ | `labels` | `Partial<JuneauLabels>` | Override UI strings. Omitted keys fall back to English. |
360
+ | `className` | `string` | Added to the root `<div>`. |
361
+ | `style` | `CSSProperties` | Inline styles on the root `<div>`. |
362
+
363
+ ---
364
+
365
+ ### `<AiChatProvider>`
366
+
367
+ Holds the shared conversation state. Wrap your app (or layout) once any page can then render `<AiSidebar />` without losing conversation history on navigation.
368
+
369
+ ```tsx
370
+ import { AiChatProvider } from 'juneau';
371
+
372
+ <AiChatProvider
373
+ adapter={myAdapter}
374
+ onProposalConfirm={(id, payload) => handleAction(id, payload)}
375
+ onProposalCancel={(id) => handleDismiss(id)}
376
+ >
377
+ <App />
378
+ </AiChatProvider>
379
+ ```
380
+
381
+ | Prop | Type | Description |
382
+ |---|---|---|
383
+ | `adapter` | `AiBackendAdapter` | **Required.** Your adapter. |
384
+ | `context` | `Record<string, unknown>` | Initial context forwarded to every adapter call. Update per-page via `setContext()`. |
385
+ | `onProposalConfirm` | `(id, payload) => void` | Called when user confirms a proposal card. |
386
+ | `onProposalCancel` | `(id) => void` | Called when user cancels a proposal card. |
387
+
388
+ **Updating context per page:**
389
+
390
+ Use `setContext()` from `useAiChatContext()` to tell the AI where the user is on each page. The context is forwarded opaquely to every `adapter.sendMessage` call as `input.context`.
391
+
392
+ ```tsx
393
+ import { useAiChatContext } from 'juneau';
394
+
395
+ function InvoicesPage() {
396
+ const { setContext } = useAiChatContext();
397
+
398
+ useEffect(() => {
399
+ setContext({
400
+ page: 'invoices',
401
+ availableTools: ['search', 'export'],
402
+ userRole: 'admin',
403
+ });
404
+ }, []);
405
+
406
+ return <main>...</main>;
407
+ }
408
+ ```
409
+
410
+ ---
411
+
412
+ ## Components
413
+
414
+ ### `<AiSidebar>`
415
+
416
+ Fixed-position chat panel. Reads all state from the nearest `<AiChatProvider>` renders wherever you place it, conversation persists across navigation.
417
+
418
+ The sidebar anchors to the bottom-right of the viewport and opens at 60% screen height by default. Users can minimize it to a compact header bar.
419
+
420
+ ```tsx
421
+ <AiSidebar
422
+ title="AI Assistant"
423
+ height="70vh"
424
+ />
425
+ ```
426
+
427
+ | Prop | Type | Description |
428
+ |---|---|---|
429
+ | `title` | `string` | Overrides the `sidebarTitle` label for this instance. |
430
+ | `icon` | `ReactNode` | Override the header + avatar icon. Defaults to a wand icon. |
431
+ | `actions` | `AiInputAction[]` | Toolbar buttons left of send. Pass `[]` to hide entirely. |
432
+ | `sendIcon` | `ReactNode` | Override the send button icon. |
433
+ | `height` | `string` | Height when open. Any CSS value. Defaults to `'60vh'`. |
434
+ | `className` | `string` | Added to the `<aside>` element. |
435
+ | `style` | `CSSProperties` | Inline styles on the `<aside>`. |
436
+
437
+ ---
438
+
439
+ ### `<AiChat>`
440
+
441
+ Headless chat body — message list + input bar + error banner, no surrounding chrome. Use this when you want to embed chat inside your own layout (dashboard panel, modal, full-page view).
442
+
443
+ The parent is responsible for calling `useAiChat` and passing results down as props.
444
+
445
+ ```tsx
446
+ import { useAiChat, AiChat } from 'juneau';
447
+
448
+ function MyPage() {
449
+ const chat = useAiChat({ adapter });
450
+
451
+ return (
452
+ <div className="my-layout">
453
+ <MySidebar />
454
+ <AiChat
455
+ messages={chat.messages}
456
+ input={chat.input}
457
+ isLoading={chat.isLoading}
458
+ error={chat.error}
459
+ onInputChange={chat.setInput}
460
+ onSend={chat.sendMessage}
461
+ onStop={chat.stop}
462
+ onProposalConfirm={chat.confirmProposal}
463
+ onProposalCancel={chat.cancelProposal}
464
+ />
465
+ </div>
466
+ );
467
+ }
468
+ ```
469
+
470
+ | Prop | Type | Description |
471
+ |---|---|---|
472
+ | `messages` | `AiMessage[]` | Conversation history. |
473
+ | `input` | `string` | Current textarea value. |
474
+ | `isLoading` | `boolean` | Whether a stream is in progress. |
475
+ | `error` | `string \| null` | Last error message, or `null`. |
476
+ | `onInputChange` | `(value: string) => void` | Input change handler. |
477
+ | `onSend` | `() => void` | Send the current input. |
478
+ | `onStop` | `() => void` | Abort the in-flight stream. Renders a stop button while loading. |
479
+ | `onProposalConfirm` | `(id, payload) => void` | Proposal confirmed. |
480
+ | `onProposalCancel` | `(id) => void` | Proposal cancelled. |
481
+ | `assistantIcon` | `ReactNode` | Override the assistant avatar in all bubbles. |
482
+ | `actions` | `AiInputAction[]` | Toolbar buttons. |
483
+ | `sendIcon` | `ReactNode` | Override send button icon. |
484
+ | `placeholder` | `string` | Input placeholder text. |
485
+ | `renderPart` | `RenderPartFn` | Custom part renderer see below. |
486
+
487
+ ---
488
+
489
+ ## Custom part rendering — `renderPart`
490
+
491
+ Both `AiSidebar` and `AiChat` accept a `renderPart` propan escape hatch for rendering consumer-defined part types (or overriding built-in ones):
492
+
493
+ ```ts
494
+ type RenderPartFn = (part: AiMessagePart) => ReactNode | null | undefined;
495
+ ```
496
+
497
+ It is called **before** the built-in renderers for every message part. Return a ReactNode to render it; return `null`/`undefined` to fall through to the built-ins (`text`, `table`, `proposal`, `activity`, `error`).
498
+
499
+ The backend can stream any custom part through the standard wire protocol:
500
+
501
+ ```json
502
+ { "type": "part", "part": { "type": "invoice-card", "invoiceNumber": "23251", "amount": "1200.00" } }
503
+ ```
504
+
505
+ `AiCustomPart` (`{ type: string; [key: string]: unknown }`) is part of the `AiMessagePart` union, so TypeScript accepts custom shapes on both ends. Juneau applies **no validation or narrowing** to custom parts — the consumer owns all type assertions:
506
+
507
+ ```tsx
508
+ // Define your part type wherever you like — Juneau doesn't need to know about it
509
+ type InvoiceCardPart = { type: 'invoice-card'; invoiceNumber: string; amount: string };
510
+
511
+ <AiSidebar renderPart={part => {
512
+ if (part.type === 'invoice-card') return <InvoiceCard part={part as InvoiceCardPart} />;
513
+ return null; // everything else falls through to the built-ins
514
+ }} />
515
+ ```
516
+
517
+ Unhandled custom part types show a dashed warning outline in development (so they're never a silent mystery) and render nothing in production.
518
+
519
+ ---
520
+
521
+ ## `useAiChat` hook
522
+
523
+ For full control over layout and behaviour. Returns everything needed to build a custom chat UI.
524
+
525
+ ```ts
526
+ const {
527
+ messages, // AiMessage[]full conversation history
528
+ input, // string — current textarea value
529
+ setInput, // (value: string) => void
530
+ sendMessage, // () => Promise<void> — sends current input as user message
531
+ sendMessageWithText, // (text: string) => Promise<void> — send programmatically, no input state change
532
+ sendGreeting, // (contextHint: string) => Promise<void> — assistant speaks first, no user bubble shown
533
+ stop, // () => void abort in-flight stream, keep existing messages
534
+ isLoading, // boolean — true while streaming
535
+ isConnecting, // boolean — true from send until first token arrives
536
+ error, // string | null — last error, cleared on next send
537
+ reset, // (nextMessages?: AiMessage[]) => void — clear (or replace) messages, abort any stream
538
+ confirmProposal, // (id: string, payload: unknown) => void — marks proposal resolved + fires callback
539
+ cancelProposal, // (id: string) => void — marks proposal resolved + fires callback
540
+ } = useAiChat({
541
+ adapter, // required
542
+ context, // optional forwarded to every adapter.sendMessage call
543
+ onProposalConfirm, // optional — called by confirmProposal
544
+ onProposalCancel, // optional — called by cancelProposal
545
+ initialMessages, // optional — restored conversation to start with (see Chat history)
546
+ historyLimit, // optional — max messages sent to the adapter per request (token saving)
547
+ onMessagesChange, // optional — called when the conversation settles; use to persist
548
+ });
549
+ ```
550
+
551
+ ## `useAiChatContext` hook
552
+
553
+ Reads the shared state from `<AiChatProvider>`. Includes everything from `useAiChat` plus `setContext()`.
554
+
555
+ ```ts
556
+ const {
557
+ // all useAiChat fields +
558
+ setContext, // (ctx: Record<string, unknown>) => void update context forwarded to adapter
559
+ } = useAiChatContext();
560
+ ```
561
+
562
+ Throws a descriptive error if called outside `<AiChatProvider>`.
563
+
564
+ ---
565
+
566
+ ### Useful patterns
567
+
568
+ **Proactive greeting on mount (`sendGreeting`):**
569
+
570
+ `sendGreeting(hint)` sends the hint as a `system` role message to the adapter and streams the response as an assistant-only message — no user bubble is added to the conversation. Perfect for page-load summaries where the AI speaks first.
571
+
572
+ ```ts
573
+ const { sendGreeting } = useAiChatContext();
574
+
575
+ useEffect(() => {
576
+ sendGreeting(
577
+ 'The user is viewing the Invoices page. ' +
578
+ 'Briefly introduce what you can help with on this page.'
579
+ );
580
+ }, []);
581
+ ```
582
+
583
+ **Trigger from outside the chat (e.g. clicking a data row):**
584
+ ```ts
585
+ const { sendMessageWithText } = useAiChatContext();
586
+ sendMessageWithText(`Summarise order #${order.id} for me`);
587
+ ```
588
+
589
+ **Pass page context to every request:**
590
+ ```tsx
591
+ const { setContext } = useAiChatContext();
592
+
593
+ useEffect(() => {
594
+ setContext({ pageId: 'invoices', entityId: invoice.id, userRole: 'admin' });
595
+ }, [invoice.id]);
596
+ ```
597
+
598
+ The `context` object lands in `input.context` inside every `adapter.sendMessage` call — use it to inject page-level data without polluting the message history.
599
+
600
+ **Reading message text in your adapter:**
601
+
602
+ Don't dig into `parts` manually — use the exported `getMessageText` helper:
603
+
604
+ ```ts
605
+ import { getMessageText } from 'juneau';
606
+
607
+ async *sendMessage({ messages }) {
608
+ const lastUser = [...messages].reverse().find(m => m.role === 'user');
609
+ const text = lastUser ? getMessageText(lastUser) : '';
610
+ // plain string, all text parts concatenated
611
+ }
612
+ ```
613
+
614
+ **Auth bearer token from React context:**
615
+ ```ts
616
+ const adapter = createSseAdapter('/api/chat', {
617
+ getHeaders: async () => ({
618
+ Authorization: `Bearer ${await getAccessToken()}`,
619
+ }),
620
+ });
621
+ ```
622
+
623
+ **Auth session cookie (no extra config needed):**
624
+
625
+ Cookies are sent automatically by `fetch` to same-origin URLs. Just use `createSseAdapter('/api/chat')` with no headers the browser attaches the session cookie for you.
626
+
627
+ For cross-origin backends, add `credentials: 'include'` by writing a custom adapter:
628
+
629
+ ```ts
630
+ const adapter: AiBackendAdapter = {
631
+ async *sendMessage({ messages }) {
632
+ const res = await fetch('https://api.example.com/chat', {
633
+ method: 'POST',
634
+ credentials: 'include', // sends cookies cross-origin
635
+ headers: { 'Content-Type': 'application/json' },
636
+ body: JSON.stringify({ messages }),
637
+ });
638
+ // …stream response
639
+ },
640
+ };
641
+ ```
642
+
643
+ **Stop button feedback:**
644
+
645
+ When `onStop` is provided, the send button becomes a stop button while streaming. After the user hits stop, `isLoading` goes false immediately and the existing partial response stays visible in the conversation — there's no error state, the stream just ends cleanly where it was cut.
646
+
647
+ ---
648
+
649
+ ## Message parts
650
+
651
+ Assistant messages are composed of typed **parts**. Text is streamed chunk by chunk; rich UI blocks are emitted as complete `part` events.
652
+
653
+ | Part type | Emitted as | Rendered by |
654
+ |---|---|---|
655
+ | `text` | `{ type: 'text', text: string }` stream events, accumulated | Markdown via `react-markdown` — safe against XSS |
656
+ | `table` | `{ type: 'part', part: { type: 'table', ... } }` | `AiTablePart` |
657
+ | `proposal` | `{ type: 'part', part: { type: 'proposal', ... } }` | `AiProposalCard` |
658
+ | `activity` | `{ type: 'part', part: { type: 'activity', ... } }` | `AiActivityPart` |
659
+ | `error` | `{ type: 'error', message: string }` or `{ type: 'part', part: { type: 'error', ... } }` | Inline error in bubble |
660
+
661
+ **Emitting an activity from your adapter:**
662
+
663
+ Activity parts show the user what the AI is doing while it works — skill selection, document search, tool calls, etc. They have three states: `running`, `done`, `failed`.
664
+
665
+ ```ts
666
+ // Show a running activity
667
+ yield {
668
+ type: 'part',
669
+ part: {
670
+ type: 'activity',
671
+ id: 'doc-search', // optional stable ID enables in-place update
672
+ title: 'Searching document',
673
+ description: 'Looking up document by ID.',
674
+ status: 'running',
675
+ },
676
+ };
677
+
678
+ // Later: update the same activity in-place (same id)
679
+ yield {
680
+ type: 'part',
681
+ part: {
682
+ type: 'activity',
683
+ id: 'doc-search',
684
+ title: 'Document found',
685
+ description: 'Found document INV-2024-0894.',
686
+ status: 'done',
687
+ },
688
+ };
689
+ ```
690
+
691
+ If `id` is provided, a later activity part with the same `id` updates the previous one in-place instead of appending a new row. Without `id`, activity parts append as a timeline.
692
+
693
+ **Emitting a proposal from your adapter:**
694
+ ```ts
695
+ yield {
696
+ type: 'part',
697
+ part: {
698
+ type: 'proposal',
699
+ proposal: {
700
+ id: 'confirm-delete', // passed back to onProposalConfirm
701
+ title: 'Delete this item?',
702
+ description: 'This cannot be undone.',
703
+ confirmLabel: 'Delete', // optional, falls back to labels.proposalConfirm
704
+ cancelLabel: 'Keep', // optional, falls back to labels.proposalCancel
705
+ payload: { itemId: 42 }, // anything — you get it back in onProposalConfirm
706
+ },
707
+ },
708
+ };
709
+ ```
710
+
711
+ **Emitting a table:**
712
+ ```ts
713
+ yield {
714
+ type: 'part',
715
+ part: {
716
+ type: 'table',
717
+ columns: ['Name', 'Amount', 'Status'],
718
+ rows: [
719
+ { Name: 'Item A', Amount: '$1,200', Status: 'Paid' },
720
+ { Name: 'Item B', Amount: '$840', Status: 'Pending' },
721
+ ],
722
+ },
723
+ };
724
+ ```
725
+
726
+ ---
727
+
728
+ ## Chat history
729
+
730
+ Juneau is storage-agnostic: it defines the exact data contract and renders restored conversations (including tables, proposals, and custom parts), but never touches storage itself. You persist chats wherever you want — localStorage, a database — and hand Juneau plain data.
731
+
732
+ **Persist a conversation:**
733
+
734
+ ```tsx
735
+ import { useAiChat, serializeForStorage } from 'juneau';
736
+
737
+ const chat = useAiChat({
738
+ adapter,
739
+ historyLimit: 20, // send at most 20 messages to the adapter per request (token saving)
740
+ onMessagesChange: (messages) => {
741
+ // called when the conversation settles never per streamed token
742
+ localStorage.setItem('chat', JSON.stringify(serializeForStorage(messages)));
743
+ },
744
+ });
745
+ ```
746
+
747
+ `serializeForStorage` prepares messages for persistence:
748
+ - `createdAt` dates become ISO strings
749
+ - unresolved proposals are marked `resolved: 'expired'` — a restored proposal card renders disabled and can never fire callbacks against a stale payload
750
+ - `running` activity parts are dropped (they'd look permanently stuck)
751
+
752
+ **Restore a conversation:**
753
+
754
+ ```tsx
755
+ import { deserializeMessages } from 'juneau';
756
+
757
+ const stored = JSON.parse(localStorage.getItem('chat') ?? '[]');
758
+ const chat = useAiChat({ adapter, initialMessages: deserializeMessages(stored) });
759
+ ```
760
+
761
+ All rich parts re-render exactly as they streamed in — no reconstruction needed. The restored history is also sent to the adapter, so the AI keeps full context.
762
+
763
+ **Rendering trims nothing.** `historyLimit` only caps what is *sent to the adapter*; the cut keeps the most recent messages and never splits a user/assistant exchange, so alternation stays valid.
764
+
765
+ **Multiple chats:**
766
+
767
+ Juneau supports a multi-chat UX via `AiChatSummary` and the `AiChatHistoryList` component. You own the chat list and per-chat storage; Juneau renders the list and switches conversations via `reset(nextMessages)`:
768
+
769
+ ```tsx
770
+ import { AiChatHistoryList, trimChats } from 'juneau';
771
+
772
+ <AiChatHistoryList
773
+ chats={trimChats(myChats, 10)} // keep the 10 most recently updated
774
+ activeChatId={currentChatId}
775
+ onSelect={(chatId) => chat.reset(loadMessagesFor(chatId))}
776
+ onDelete={(chatId) => deleteChat(chatId)} // optional omit to hide delete buttons
777
+ />
778
+ ```
779
+
780
+ ```ts
781
+ type AiChatSummary = {
782
+ id: string;
783
+ title: string;
784
+ createdAt: Date;
785
+ updatedAt: Date;
786
+ };
787
+ ```
788
+
789
+ `trimChats(chats, limit)` returns the `limit` most recently updated chats (sorted newest first) — delete the rest from your storage to enforce an overall chats limit.
790
+
791
+ ---
792
+
793
+ ## Theming
794
+
795
+ All visual values are CSS custom properties prefixed `--juneau-`. Override them via `JuneauProvider`:
796
+
797
+ ```tsx
798
+ <JuneauProvider theme={{
799
+ colorPrimary: '#1d4ed8',
800
+ colorAccent: '#7c3aed',
801
+ radiusLg: '16px',
802
+ fontFamily: '"Inter", sans-serif',
803
+ }}>
804
+ ```
805
+
806
+ Only keys you specify are overridden — everything else keeps its default. Overrides are scoped to the provider's subtree so multiple providers with different themes can coexist.
807
+
808
+ ### Full theme reference
809
+
810
+ | Key | CSS variable | Default | Usage |
811
+ |---|---|---|---|
812
+ | `colorPrimary` | `--juneau-color-primary` | `#000000` | Send button, user bubble |
813
+ | `colorPrimaryDark` | `--juneau-color-primary-dark` | `#252528` | Primary hover state |
814
+ | `colorPrimaryLight` | `--juneau-color-primary-light` | `#ECECEC` | Primary tinted backgrounds |
815
+ | `colorAccent` | `--juneau-color-accent` | `#FF49A4` | Header bg, proposal confirm, avatar |
816
+ | `colorAccentDark` | `--juneau-color-accent-dark` | `#FF6BB3` | Accent hover |
817
+ | `colorAccentLight` | `--juneau-color-accent-light` | `#FFF0F7` | Proposal card background |
818
+ | `colorSurface` | `--juneau-color-surface` | `#FFFFFF` | Cards, sidebar, input background |
819
+ | `colorSurfaceRaised` | `--juneau-color-surface-raised` | `#F4F4F6` | Page background, table headers |
820
+ | `colorSurfaceHover` | `--juneau-color-surface-hover` | `#ECECEC` | Row hover |
821
+ | `colorBorder` | `--juneau-color-border` | `#E8E8EC` | Default borders |
822
+ | `colorTextPrimary` | `--juneau-color-text-primary` | `#000000` | Main body text |
823
+ | `colorTextSecondary` | `--juneau-color-text-secondary` | `#474747` | Supporting text |
824
+ | `colorTextMuted` | `--juneau-color-text-muted` | `#474747` | Labels, hints |
825
+ | `colorTextFaint` | `--juneau-color-text-faint` | `#9090A0` | Empty states |
826
+ | `colorTextInverse` | `--juneau-color-text-inverse` | `#FFFFFF` | Text on dark backgrounds |
827
+ | `colorAssistantAvatar` | `--juneau-color-assistant-avatar` | `#FF49A4` | Assistant avatar circle |
828
+ | `radiusSm` | `--juneau-radius-sm` | `6px` | Buttons, small elements |
829
+ | `radiusMd` | `--juneau-radius-md` | `8px` | Inputs, cards |
830
+ | `radiusLg` | `--juneau-radius-lg` | `12px` | Panels, large cards |
831
+ | `fontFamily` | `--juneau-font-family` | system-ui | Font used across all components |
832
+
833
+ ---
834
+
835
+ ## i18n / Labels
836
+
837
+ All UI strings are overridable. Built-in locales: `juneauEn` (default) and `juneauCs`.
838
+
839
+ ```tsx
840
+ import { juneauCs } from 'juneau';
841
+ <JuneauProvider labels={juneauCs}>...</JuneauProvider>
842
+ ```
843
+
844
+ Pass any `Partial<JuneauLabels>` — omitted keys fall back to English:
845
+
846
+ ```tsx
847
+ <JuneauProvider labels={{ sidebarTitle: 'Ask AI', sendMessage: 'Send' }}>
848
+ ```
849
+
850
+ ### Full label reference
851
+
852
+ | Key | Default (EN) | Used in |
853
+ |---|---|---|
854
+ | `sidebarTitle` | `AI Assistant` | `AiChatHeader` title |
855
+ | `minimizeSidebar` | `Minimize` | `AiChatHeader` minimize button |
856
+ | `expandSidebar` | `Expand` | `AiChatHeader` expand button (when minimized) |
857
+ | `inputPlaceholder` | `Ask a question… (Enter to send)` | `AiInput` textarea |
858
+ | `sendMessage` | `Send message` | `AiInput` send button |
859
+ | `stopMessage` | `Stop` | `AiInput` stop button (while streaming) |
860
+ | `emptyStateText` | `How can I help you today?` | `AiMessageList` empty state |
861
+ | `emptyStateHint` | `Try: "Show me the data" or "Can you suggest something?"` | `AiMessageList` empty state hint |
862
+ | `proposalConfirm` | `Confirm` | `AiProposalCard` fallback confirm label |
863
+ | `proposalCancel` | `Cancel` | `AiProposalCard` fallback cancel label |
864
+ | `proposalConfirmed` | `Confirmed` | `AiProposalCard` badge after confirm |
865
+ | `proposalCancelled` | `Cancelled` | `AiProposalCard` badge after cancel |
866
+ | `proposalExpired` | `No longer available` | `AiProposalCard` badge for restored proposals |
867
+ | `errorDismiss` | `Dismiss` | `AiError` dismiss button |
868
+ | `historyEmpty` | `No previous chats` | `AiChatHistoryList` empty state |
869
+ | `historyDeleteChat` | `Delete chat` | `AiChatHistoryList` delete button |
870
+ | `actionAddFile` | `Add file` | `AiInput` toolbar |
871
+ | `actionQuickActions` | `Quick actions` | `AiInput` toolbar |
872
+ | `actionNew` | `New` | `AiInput` toolbar |
873
+ | `actionHistory` | `History` | `AiInput` toolbar |
874
+ | `actionRules` | `Rules` | `AiInput` toolbar |
875
+
876
+ ---
877
+
878
+ ## Custom toolbar actions
879
+
880
+ The toolbar buttons left of the send button are fully configurable:
881
+
882
+ ```tsx
883
+ <AiSidebar
884
+ actions={[
885
+ {
886
+ icon: <MyAttachIcon />,
887
+ label: 'Attach file',
888
+ onClick: () => openFilePicker(),
889
+ },
890
+ {
891
+ icon: <MyTemplatesIcon />,
892
+ label: 'Templates',
893
+ onClick: () => openTemplateMenu(),
894
+ },
895
+ ]}
896
+ />
897
+
898
+ // Hide the toolbar entirely:
899
+ <AiSidebar actions={[]} />
900
+ ```
901
+
902
+ Each action: `{ icon: ReactNode, label: string, onClick?: () => void }`
903
+
904
+ ---
905
+
906
+ ## Security
907
+
908
+ - **No API keys in the library** — all AI calls happen in your adapter, which calls your backend. Juneau never sees credentials.
909
+ - **XSS-safe markdown** — text parts are rendered via `react-markdown`, which never uses `dangerouslySetInnerHTML`. Malicious model output cannot inject scripts.
910
+ - **No data storage** — Juneau holds conversation state in React memory only. Nothing is persisted or sent anywhere by the library itself.
911
+
912
+ ---
913
+
914
+ ## License
915
+
916
+ MIT
917
+
918
+ ---
919
+
920
+ ## Icon attribution
921
+
922
+ Icons used internally by Juneau are from [Font Awesome Free](https://fontawesome.com) (v6), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). SVG paths are inlined directly — no runtime dependency on the Font Awesome package.
923
+
924
+ Icons used: `crow`, `paper-plane`, `paperclip`, `bolt`, `plus`, `clock-rotate-left`, `scroll`, `arrow-rotate-left`, `window-minimize`, `window-restore`.