juneau 0.3.4 → 0.4.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.
Files changed (33) hide show
  1. package/README.md +834 -789
  2. package/dist/adapters/dashboardAdapter.d.ts.map +1 -1
  3. package/dist/adapters/mockAdapter.d.ts.map +1 -1
  4. package/dist/components/AiChat/AiChat.d.ts +8 -1
  5. package/dist/components/AiChat/AiChat.d.ts.map +1 -1
  6. package/dist/components/AiMessageBubble/AiMessageBubble.d.ts +4 -1
  7. package/dist/components/AiMessageBubble/AiMessageBubble.d.ts.map +1 -1
  8. package/dist/components/AiMessageList/AiMessageList.d.ts +4 -1
  9. package/dist/components/AiMessageList/AiMessageList.d.ts.map +1 -1
  10. package/dist/components/AiSidebar/AiSidebar.d.ts +8 -1
  11. package/dist/components/AiSidebar/AiSidebar.d.ts.map +1 -1
  12. package/dist/components/parts/AiMessagePartRenderer.d.ts +11 -1
  13. package/dist/components/parts/AiMessagePartRenderer.d.ts.map +1 -1
  14. package/dist/core/types.d.ts +14 -4
  15. package/dist/core/types.d.ts.map +1 -1
  16. package/dist/index.cjs +28 -28
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2635 -2613
  21. package/dist/index.js.map +1 -1
  22. package/dist/server/createSkillSet.d.ts +5 -1
  23. package/dist/server/createSkillSet.d.ts.map +1 -1
  24. package/dist/server/index.cjs +5 -5
  25. package/dist/server/index.cjs.map +1 -1
  26. package/dist/server/index.d.ts +1 -1
  27. package/dist/server/index.d.ts.map +1 -1
  28. package/dist/server/index.js +62 -57
  29. package/dist/server/index.js.map +1 -1
  30. package/dist/server/types.d.ts +16 -1
  31. package/dist/server/types.d.ts.map +1 -1
  32. package/dist/style.css +1 -1
  33. package/package.json +1 -1
package/README.md CHANGED
@@ -1,789 +1,834 @@
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
- `SkillSet` members: `tools`, `drainActivities()`, `hadFailure`, `failureContext`.
230
-
231
- `SkillSetOptions`: `language?` — selects label variant (`'en'` default). `debug?` — emit `console.debug` logs per skill execution (default: `false`).
232
-
233
- #### `streamToWire(fullStream, skillSet?, options?)`
234
-
235
- 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.
236
-
237
- #### `withToolRecovery(options)`
238
-
239
- 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 caseGemini 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.
240
-
241
- ```ts
242
- yield* withToolRecovery({
243
- phase1: () => streamText({ model, system, messages, tools: skillSet.tools, maxSteps: 2 }),
244
- phase2: (ctx) => streamText({ model, system, messages: [...messages, { role: 'assistant', content: ctx }] }),
245
- phase3: (fullMessages) => streamText({ model, system, messages: fullMessages }), // no tools — forced text
246
- skillSet,
247
- });
248
- ```
249
-
250
- ---
251
-
252
- ### Juneau wire protocol — for Juneau-compatible backends
253
-
254
- 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.
255
-
256
- ```ts
257
- // Text chunk appended to the current assistant bubble
258
- { "type": "text", "text": "Here is what I found:" }
259
-
260
- // Activity — shows AI progress (skill selection, tool calls, etc.)
261
- // Send the same `id` with a new status to update in-place
262
- { "type": "activity", "id": "skill-select", "title": "Selecting skill", "description": "Finding the best skill for this request.", "status": "running" }
263
- { "type": "activity", "id": "skill-select", "title": "Skill selected", "description": "Using Document Search.", "status": "done" }
264
- { "type": "activity", "id": "doc-search", "title": "Searching document", "status": "running" }
265
- { "type": "activity", "id": "doc-search", "title": "Document found", "description": "INV-2024-0894", "status": "done" }
266
-
267
- // Rich block — table or proposal
268
- { "type": "part", "part": { "type": "table", "columns": ["Name", "Amount"], "rows": [...] } }
269
- { "type": "part", "part": { "type": "proposal", "proposal": { "id": "...", "title": "..." } } }
270
-
271
- // Stream finished cleanly
272
- { "type": "done" }
273
-
274
- // Stream error ends the stream
275
- { "type": "error", "message": "Something went wrong." }
276
- ```
277
-
278
- **Activity `status` values:** `running` | `done` | `failed`
279
-
280
- **Activity `id` behaviour:**
281
- - With `id` a later event with the same `id` updates the existing row in-place (running → done)
282
- - Without `id` — each activity appends as a new timeline row
283
-
284
- **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.
285
-
286
- `createSseAdapter` also retains OpenAI-format fallback parsing (`choices[0].delta.content`) so it works with both Juneau-compatible backends and standard OpenAI proxies.
287
-
288
- ---
289
-
290
- ### `mockAdapter` for development
291
-
292
- Shipped for local development. No backend needed — responds to keywords in the message:
293
-
294
- | Say... | Gets you... |
295
- |---|---|
296
- | `"show"`, `"list"`, `"data"`, `"table"` | A rendered data table |
297
- | `"suggest"`, `"recommend"`, `"proposal"` | A proposal card with confirm/cancel |
298
- | `"activity"`, `"progress"`, `"document"` | An activity timeline with running/done states |
299
- | `"help"`, `"what can you do"` | Capability overview |
300
- | `"error"`, `"fail"` | Simulated error response |
301
- | anything else | Explains the available triggers |
302
-
303
- ```ts
304
- import { mockAdapter } from 'juneau';
305
- // Pass to AiChatProvider — see below
306
- ```
307
-
308
- ---
309
-
310
- ## Providers
311
-
312
- ### `<JuneauProvider>`
313
-
314
- Wrap your app once. Provides theme tokens and UI labels to all Juneau components below it.
315
-
316
- ```tsx
317
- import { JuneauProvider, juneauCs } from 'juneau';
318
-
319
- <JuneauProvider
320
- theme={{ colorPrimary: '#0f766e', colorAccent: '#14b8a6' }}
321
- labels={juneauCs}
322
- >
323
- {children}
324
- </JuneauProvider>
325
- ```
326
-
327
- | Prop | Type | Description |
328
- |---|---|---|
329
- | `theme` | `JuneauTheme` | Override design tokens. Only specified keys are applied. |
330
- | `labels` | `Partial<JuneauLabels>` | Override UI strings. Omitted keys fall back to English. |
331
- | `className` | `string` | Added to the root `<div>`. |
332
- | `style` | `CSSProperties` | Inline styles on the root `<div>`. |
333
-
334
- ---
335
-
336
- ### `<AiChatProvider>`
337
-
338
- Holds the shared conversation state. Wrap your app (or layout) once — any page can then render `<AiSidebar />` without losing conversation history on navigation.
339
-
340
- ```tsx
341
- import { AiChatProvider } from 'juneau';
342
-
343
- <AiChatProvider
344
- adapter={myAdapter}
345
- onProposalConfirm={(id, payload) => handleAction(id, payload)}
346
- onProposalCancel={(id) => handleDismiss(id)}
347
- >
348
- <App />
349
- </AiChatProvider>
350
- ```
351
-
352
- | Prop | Type | Description |
353
- |---|---|---|
354
- | `adapter` | `AiBackendAdapter` | **Required.** Your adapter. |
355
- | `context` | `Record<string, unknown>` | Initial context forwarded to every adapter call. Update per-page via `setContext()`. |
356
- | `onProposalConfirm` | `(id, payload) => void` | Called when user confirms a proposal card. |
357
- | `onProposalCancel` | `(id) => void` | Called when user cancels a proposal card. |
358
-
359
- **Updating context per page:**
360
-
361
- 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`.
362
-
363
- ```tsx
364
- import { useAiChatContext } from 'juneau';
365
-
366
- function InvoicesPage() {
367
- const { setContext } = useAiChatContext();
368
-
369
- useEffect(() => {
370
- setContext({
371
- page: 'invoices',
372
- availableTools: ['search', 'export'],
373
- userRole: 'admin',
374
- });
375
- }, []);
376
-
377
- return <main>...</main>;
378
- }
379
- ```
380
-
381
- ---
382
-
383
- ## Components
384
-
385
- ### `<AiSidebar>`
386
-
387
- Fixed-position chat panel. Reads all state from the nearest `<AiChatProvider>` — renders wherever you place it, conversation persists across navigation.
388
-
389
- 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.
390
-
391
- ```tsx
392
- <AiSidebar
393
- title="AI Assistant"
394
- height="70vh"
395
- />
396
- ```
397
-
398
- | Prop | Type | Description |
399
- |---|---|---|
400
- | `title` | `string` | Overrides the `sidebarTitle` label for this instance. |
401
- | `icon` | `ReactNode` | Override the header + avatar icon. Defaults to a wand icon. |
402
- | `actions` | `AiInputAction[]` | Toolbar buttons left of send. Pass `[]` to hide entirely. |
403
- | `sendIcon` | `ReactNode` | Override the send button icon. |
404
- | `height` | `string` | Height when open. Any CSS value. Defaults to `'60vh'`. |
405
- | `className` | `string` | Added to the `<aside>` element. |
406
- | `style` | `CSSProperties` | Inline styles on the `<aside>`. |
407
-
408
- ---
409
-
410
- ### `<AiChat>`
411
-
412
- 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).
413
-
414
- The parent is responsible for calling `useAiChat` and passing results down as props.
415
-
416
- ```tsx
417
- import { useAiChat, AiChat } from 'juneau';
418
-
419
- function MyPage() {
420
- const chat = useAiChat({ adapter });
421
-
422
- return (
423
- <div className="my-layout">
424
- <MySidebar />
425
- <AiChat
426
- messages={chat.messages}
427
- input={chat.input}
428
- isLoading={chat.isLoading}
429
- error={chat.error}
430
- onInputChange={chat.setInput}
431
- onSend={chat.sendMessage}
432
- onStop={chat.stop}
433
- onProposalConfirm={chat.confirmProposal}
434
- onProposalCancel={chat.cancelProposal}
435
- />
436
- </div>
437
- );
438
- }
439
- ```
440
-
441
- | Prop | Type | Description |
442
- |---|---|---|
443
- | `messages` | `AiMessage[]` | Conversation history. |
444
- | `input` | `string` | Current textarea value. |
445
- | `isLoading` | `boolean` | Whether a stream is in progress. |
446
- | `error` | `string \| null` | Last error message, or `null`. |
447
- | `onInputChange` | `(value: string) => void` | Input change handler. |
448
- | `onSend` | `() => void` | Send the current input. |
449
- | `onStop` | `() => void` | Abort the in-flight stream. Renders a stop button while loading. |
450
- | `onProposalConfirm` | `(id, payload) => void` | Proposal confirmed. |
451
- | `onProposalCancel` | `(id) => void` | Proposal cancelled. |
452
- | `assistantIcon` | `ReactNode` | Override the assistant avatar in all bubbles. |
453
- | `actions` | `AiInputAction[]` | Toolbar buttons. |
454
- | `sendIcon` | `ReactNode` | Override send button icon. |
455
- | `placeholder` | `string` | Input placeholder text. |
456
-
457
- ---
458
-
459
- ## `useAiChat` hook
460
-
461
- For full control over layout and behaviour. Returns everything needed to build a custom chat UI.
462
-
463
- ```ts
464
- const {
465
- messages, // AiMessage[] full conversation history
466
- input, // string current textarea value
467
- setInput, // (value: string) => void
468
- sendMessage, // () => Promise<void> sends current input as user message
469
- sendMessageWithText, // (text: string) => Promise<void> — send programmatically, no input state change
470
- sendGreeting, // (contextHint: string) => Promise<void> — assistant speaks first, no user bubble shown
471
- stop, // () => void — abort in-flight stream, keep existing messages
472
- isLoading, // boolean true while streaming
473
- isConnecting, // boolean — true from send until first token arrives
474
- error, // string | nulllast error, cleared on next send
475
- reset, // () => void — clear all messages and abort any stream
476
- confirmProposal, // (id: string, payload: unknown) => void
477
- cancelProposal, // (id: string) => void
478
- } = useAiChat({
479
- adapter, // required
480
- context, // optional forwarded to every adapter.sendMessage call
481
- onProposalConfirm, // optional — called by confirmProposal
482
- onProposalCancel, // optional called by cancelProposal
483
- });
484
- ```
485
-
486
- ## `useAiChatContext` hook
487
-
488
- Reads the shared state from `<AiChatProvider>`. Includes everything from `useAiChat` plus `setContext()`.
489
-
490
- ```ts
491
- const {
492
- // all useAiChat fields +
493
- setContext, // (ctx: Record<string, unknown>) => void — update context forwarded to adapter
494
- } = useAiChatContext();
495
- ```
496
-
497
- Throws a descriptive error if called outside `<AiChatProvider>`.
498
-
499
- ---
500
-
501
- ### Useful patterns
502
-
503
- **Proactive greeting on mount (`sendGreeting`):**
504
-
505
- `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.
506
-
507
- ```ts
508
- const { sendGreeting } = useAiChatContext();
509
-
510
- useEffect(() => {
511
- sendGreeting(
512
- 'The user is viewing the Invoices page. ' +
513
- 'Briefly introduce what you can help with on this page.'
514
- );
515
- }, []);
516
- ```
517
-
518
- **Trigger from outside the chat (e.g. clicking a data row):**
519
- ```ts
520
- const { sendMessageWithText } = useAiChatContext();
521
- sendMessageWithText(`Summarise order #${order.id} for me`);
522
- ```
523
-
524
- **Pass page context to every request:**
525
- ```tsx
526
- const { setContext } = useAiChatContext();
527
-
528
- useEffect(() => {
529
- setContext({ pageId: 'invoices', entityId: invoice.id, userRole: 'admin' });
530
- }, [invoice.id]);
531
- ```
532
-
533
- The `context` object lands in `input.context` inside every `adapter.sendMessage` call — use it to inject page-level data without polluting the message history.
534
-
535
- **Reading message text in your adapter:**
536
-
537
- Don't dig into `parts` manually — use the exported `getMessageText` helper:
538
-
539
- ```ts
540
- import { getMessageText } from 'juneau';
541
-
542
- async *sendMessage({ messages }) {
543
- const lastUser = [...messages].reverse().find(m => m.role === 'user');
544
- const text = lastUser ? getMessageText(lastUser) : '';
545
- // → plain string, all text parts concatenated
546
- }
547
- ```
548
-
549
- **Auth — bearer token from React context:**
550
- ```ts
551
- const adapter = createSseAdapter('/api/chat', {
552
- getHeaders: async () => ({
553
- Authorization: `Bearer ${await getAccessToken()}`,
554
- }),
555
- });
556
- ```
557
-
558
- **Auth session cookie (no extra config needed):**
559
-
560
- 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.
561
-
562
- For cross-origin backends, add `credentials: 'include'` by writing a custom adapter:
563
-
564
- ```ts
565
- const adapter: AiBackendAdapter = {
566
- async *sendMessage({ messages }) {
567
- const res = await fetch('https://api.example.com/chat', {
568
- method: 'POST',
569
- credentials: 'include', // sends cookies cross-origin
570
- headers: { 'Content-Type': 'application/json' },
571
- body: JSON.stringify({ messages }),
572
- });
573
- // …stream response
574
- },
575
- };
576
- ```
577
-
578
- **Stop button feedback:**
579
-
580
- 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.
581
-
582
- ---
583
-
584
- ## Message parts
585
-
586
- Assistant messages are composed of typed **parts**. Text is streamed chunk by chunk; rich UI blocks are emitted as complete `part` events.
587
-
588
- | Part type | Emitted as | Rendered by |
589
- |---|---|---|
590
- | `text` | `{ type: 'text', text: string }` stream events, accumulated | Markdown via `react-markdown` — safe against XSS |
591
- | `table` | `{ type: 'part', part: { type: 'table', ... } }` | `AiTablePart` |
592
- | `proposal` | `{ type: 'part', part: { type: 'proposal', ... } }` | `AiProposalCard` |
593
- | `activity` | `{ type: 'part', part: { type: 'activity', ... } }` | `AiActivityPart` |
594
- | `error` | `{ type: 'error', message: string }` or `{ type: 'part', part: { type: 'error', ... } }` | Inline error in bubble |
595
-
596
- **Emitting an activity from your adapter:**
597
-
598
- 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`.
599
-
600
- ```ts
601
- // Show a running activity
602
- yield {
603
- type: 'part',
604
- part: {
605
- type: 'activity',
606
- id: 'doc-search', // optional stable ID — enables in-place update
607
- title: 'Searching document',
608
- description: 'Looking up document by ID.',
609
- status: 'running',
610
- },
611
- };
612
-
613
- // Later: update the same activity in-place (same id)
614
- yield {
615
- type: 'part',
616
- part: {
617
- type: 'activity',
618
- id: 'doc-search',
619
- title: 'Document found',
620
- description: 'Found document INV-2024-0894.',
621
- status: 'done',
622
- },
623
- };
624
- ```
625
-
626
- 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.
627
-
628
- **Emitting a proposal from your adapter:**
629
- ```ts
630
- yield {
631
- type: 'part',
632
- part: {
633
- type: 'proposal',
634
- proposal: {
635
- id: 'confirm-delete', // passed back to onProposalConfirm
636
- title: 'Delete this item?',
637
- description: 'This cannot be undone.',
638
- confirmLabel: 'Delete', // optional, falls back to labels.proposalConfirm
639
- cancelLabel: 'Keep', // optional, falls back to labels.proposalCancel
640
- payload: { itemId: 42 }, // anything — you get it back in onProposalConfirm
641
- },
642
- },
643
- };
644
- ```
645
-
646
- **Emitting a table:**
647
- ```ts
648
- yield {
649
- type: 'part',
650
- part: {
651
- type: 'table',
652
- columns: ['Name', 'Amount', 'Status'],
653
- rows: [
654
- { Name: 'Item A', Amount: '$1,200', Status: 'Paid' },
655
- { Name: 'Item B', Amount: '$840', Status: 'Pending' },
656
- ],
657
- },
658
- };
659
- ```
660
-
661
- ---
662
-
663
- ## Theming
664
-
665
- All visual values are CSS custom properties prefixed `--juneau-`. Override them via `JuneauProvider`:
666
-
667
- ```tsx
668
- <JuneauProvider theme={{
669
- colorPrimary: '#1d4ed8',
670
- colorAccent: '#7c3aed',
671
- radiusLg: '16px',
672
- fontFamily: '"Inter", sans-serif',
673
- }}>
674
- ```
675
-
676
- 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.
677
-
678
- ### Full theme reference
679
-
680
- | Key | CSS variable | Default | Usage |
681
- |---|---|---|---|
682
- | `colorPrimary` | `--juneau-color-primary` | `#000000` | Send button, user bubble |
683
- | `colorPrimaryDark` | `--juneau-color-primary-dark` | `#252528` | Primary hover state |
684
- | `colorPrimaryLight` | `--juneau-color-primary-light` | `#ECECEC` | Primary tinted backgrounds |
685
- | `colorAccent` | `--juneau-color-accent` | `#FF49A4` | Header bg, proposal confirm, avatar |
686
- | `colorAccentDark` | `--juneau-color-accent-dark` | `#FF6BB3` | Accent hover |
687
- | `colorAccentLight` | `--juneau-color-accent-light` | `#FFF0F7` | Proposal card background |
688
- | `colorSurface` | `--juneau-color-surface` | `#FFFFFF` | Cards, sidebar, input background |
689
- | `colorSurfaceRaised` | `--juneau-color-surface-raised` | `#F4F4F6` | Page background, table headers |
690
- | `colorSurfaceHover` | `--juneau-color-surface-hover` | `#ECECEC` | Row hover |
691
- | `colorBorder` | `--juneau-color-border` | `#E8E8EC` | Default borders |
692
- | `colorTextPrimary` | `--juneau-color-text-primary` | `#000000` | Main body text |
693
- | `colorTextSecondary` | `--juneau-color-text-secondary` | `#474747` | Supporting text |
694
- | `colorTextMuted` | `--juneau-color-text-muted` | `#474747` | Labels, hints |
695
- | `colorTextFaint` | `--juneau-color-text-faint` | `#9090A0` | Empty states |
696
- | `colorTextInverse` | `--juneau-color-text-inverse` | `#FFFFFF` | Text on dark backgrounds |
697
- | `colorAssistantAvatar` | `--juneau-color-assistant-avatar` | `#FF49A4` | Assistant avatar circle |
698
- | `radiusSm` | `--juneau-radius-sm` | `6px` | Buttons, small elements |
699
- | `radiusMd` | `--juneau-radius-md` | `8px` | Inputs, cards |
700
- | `radiusLg` | `--juneau-radius-lg` | `12px` | Panels, large cards |
701
- | `fontFamily` | `--juneau-font-family` | system-ui | Font used across all components |
702
-
703
- ---
704
-
705
- ## i18n / Labels
706
-
707
- All UI strings are overridable. Built-in locales: `juneauEn` (default) and `juneauCs`.
708
-
709
- ```tsx
710
- import { juneauCs } from 'juneau';
711
- <JuneauProvider labels={juneauCs}>...</JuneauProvider>
712
- ```
713
-
714
- Pass any `Partial<JuneauLabels>` — omitted keys fall back to English:
715
-
716
- ```tsx
717
- <JuneauProvider labels={{ sidebarTitle: 'Ask AI', sendMessage: 'Send' }}>
718
- ```
719
-
720
- ### Full label reference
721
-
722
- | Key | Default (EN) | Used in |
723
- |---|---|---|
724
- | `sidebarTitle` | `AI Assistant` | `AiChatHeader` title |
725
- | `minimizeSidebar` | `Minimize` | `AiChatHeader` minimize button |
726
- | `expandSidebar` | `Expand` | `AiChatHeader` expand button (when minimized) |
727
- | `inputPlaceholder` | `Ask a question… (Enter to send)` | `AiInput` textarea |
728
- | `sendMessage` | `Send message` | `AiInput` send button |
729
- | `stopMessage` | `Stop` | `AiInput` stop button (while streaming) |
730
- | `emptyStateText` | `How can I help you today?` | `AiMessageList` empty state |
731
- | `emptyStateHint` | `Try: "Show me the data" or "Can you suggest something?"` | `AiMessageList` empty state hint |
732
- | `proposalConfirm` | `Confirm` | `AiProposalCard` fallback confirm label |
733
- | `proposalCancel` | `Cancel` | `AiProposalCard` fallback cancel label |
734
- | `errorDismiss` | `Dismiss` | `AiError` dismiss button |
735
- | `actionAddFile` | `Add file` | `AiInput` toolbar |
736
- | `actionQuickActions` | `Quick actions` | `AiInput` toolbar |
737
- | `actionNew` | `New` | `AiInput` toolbar |
738
- | `actionHistory` | `History` | `AiInput` toolbar |
739
- | `actionRules` | `Rules` | `AiInput` toolbar |
740
-
741
- ---
742
-
743
- ## Custom toolbar actions
744
-
745
- The toolbar buttons left of the send button are fully configurable:
746
-
747
- ```tsx
748
- <AiSidebar
749
- actions={[
750
- {
751
- icon: <MyAttachIcon />,
752
- label: 'Attach file',
753
- onClick: () => openFilePicker(),
754
- },
755
- {
756
- icon: <MyTemplatesIcon />,
757
- label: 'Templates',
758
- onClick: () => openTemplateMenu(),
759
- },
760
- ]}
761
- />
762
-
763
- // Hide the toolbar entirely:
764
- <AiSidebar actions={[]} />
765
- ```
766
-
767
- Each action: `{ icon: ReactNode, label: string, onClick?: () => void }`
768
-
769
- ---
770
-
771
- ## Security
772
-
773
- - **No API keys in the library** all AI calls happen in your adapter, which calls your backend. Juneau never sees credentials.
774
- - **XSS-safe markdown** — text parts are rendered via `react-markdown`, which never uses `dangerouslySetInnerHTML`. Malicious model output cannot inject scripts.
775
- - **No data storage** Juneau holds conversation state in React memory only. Nothing is persisted or sent anywhere by the library itself.
776
-
777
- ---
778
-
779
- ## License
780
-
781
- MIT
782
-
783
- ---
784
-
785
- ## Icon attribution
786
-
787
- 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.
788
-
789
- 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, 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 pointsthey 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 error ends 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 like — Juneau 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, // optional — called 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`.