reifyui 0.5.1 → 0.6.1
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 +40 -3
- package/dist/{chunk-2LYV4PIX.js → chunk-NTIWFHR4.js} +26 -2
- package/dist/chunk-NTIWFHR4.js.map +1 -0
- package/dist/harness.cjs +72 -21
- package/dist/harness.cjs.map +1 -1
- package/dist/harness.d.ts +23 -0
- package/dist/harness.js +52 -23
- package/dist/harness.js.map +1 -1
- package/dist/index.cjs +1126 -296
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +260 -1
- package/dist/index.js +1101 -293
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/Card.jsx +49 -0
- package/src/components/Carousel.jsx +80 -0
- package/src/components/ChatPanel.jsx +461 -0
- package/src/components/Chip.jsx +61 -0
- package/src/components/Composer.jsx +20 -1
- package/src/components/Dialog.jsx +5 -10
- package/src/components/Modal.jsx +75 -0
- package/src/components/Popover.jsx +86 -0
- package/src/components/SearchField.jsx +30 -0
- package/src/components/icons.jsx +9 -0
- package/src/components/overlay.js +63 -0
- package/src/format.js +10 -0
- package/src/harness/attach.js +63 -0
- package/src/harness/index.d.ts +23 -0
- package/src/harness/index.js +6 -18
- package/src/hooks/useTypewriter.js +53 -0
- package/src/index.d.ts +260 -1
- package/src/index.js +27 -1
- package/src/input/dictate.js +60 -0
- package/src/state/turns.js +30 -0
- package/styles/chat.css +131 -1
- package/styles/chip.css +53 -0
- package/styles/dialog.css +42 -37
- package/styles/library.css +205 -0
- package/styles/preview.css +73 -0
- package/styles/sheet.css +16 -14
- package/styles/themes/dark.css +20 -0
- package/styles/themes/light.css +23 -0
- package/dist/chunk-2LYV4PIX.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "reifyui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "The open-source rendering & interaction layer for agentic applications. Stream and render any agent's output as polished, application-native UI \u2014 model-agnostic, framework-agnostic, design-system-native. The foundation for building generative-UI and agent products.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Card — art on top, a title row underneath, optional overlay and actions.
|
|
2
|
+
//
|
|
3
|
+
// The structure is the point. Every copy of this made the whole card a <button> and then put
|
|
4
|
+
// more buttons inside it (a preview eye, rename, delete): interactive elements nested inside an
|
|
5
|
+
// interactive element, which no assistive technology can present and which browsers resolve by
|
|
6
|
+
// guessing. Here the root is a plain div, the primary action is ONE button covering art + title,
|
|
7
|
+
// and `overlay` / `actions` are its siblings.
|
|
8
|
+
//
|
|
9
|
+
// `title` takes a node so an inline rename field can live there — pass onClick={undefined} while
|
|
10
|
+
// editing, so the row is not simultaneously a text field and a link to somewhere else.
|
|
11
|
+
import React from 'react';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* art the thumbnail node (this component gives it a box; what goes in it is yours)
|
|
15
|
+
* title the name (node)
|
|
16
|
+
* subtitle quiet trailing text, e.g. when it was last opened
|
|
17
|
+
* onClick opens the thing; omit for a card that is only a display
|
|
18
|
+
* selected this card is the current choice
|
|
19
|
+
* overlay floats over the art on hover, and is ALWAYS visible on touch/narrow (there is no
|
|
20
|
+
* hover to reveal it with)
|
|
21
|
+
* actions sits in the title row, after the subtitle
|
|
22
|
+
*/
|
|
23
|
+
export function Card(props) {
|
|
24
|
+
const { art, title, subtitle, onClick, selected = false, overlay, actions, classNames = {} } = props;
|
|
25
|
+
const foot = (
|
|
26
|
+
<span className="uic-card-foot">
|
|
27
|
+
<span className="uic-card-name">{title}</span>
|
|
28
|
+
{subtitle ? <span className="uic-card-sub">{subtitle}</span> : null}
|
|
29
|
+
</span>
|
|
30
|
+
);
|
|
31
|
+
return (
|
|
32
|
+
<div className={['uic-card', selected ? 'is-selected' : '', classNames.root || '']
|
|
33
|
+
.filter(Boolean).join(' ')}>
|
|
34
|
+
{onClick ? (
|
|
35
|
+
<button type="button" className="uic-card-main" onClick={onClick} aria-pressed={selected || undefined}>
|
|
36
|
+
<span className="uic-card-art">{art}</span>
|
|
37
|
+
{foot}
|
|
38
|
+
</button>
|
|
39
|
+
) : (
|
|
40
|
+
<div className="uic-card-main">
|
|
41
|
+
<span className="uic-card-art">{art}</span>
|
|
42
|
+
{foot}
|
|
43
|
+
</div>
|
|
44
|
+
)}
|
|
45
|
+
{overlay ? <div className="uic-card-overlay">{overlay}</div> : null}
|
|
46
|
+
{actions ? <div className="uic-card-actions">{actions}</div> : null}
|
|
47
|
+
</div>
|
|
48
|
+
);
|
|
49
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Carousel — a horizontal strip of cards with edge buttons.
|
|
2
|
+
//
|
|
3
|
+
// It exists as a component rather than as a stylesheet plus a div because the parts that were
|
|
4
|
+
// wrong in the copies are all behaviour, not paint: the buttons must disable at each end, must
|
|
5
|
+
// not be there at all when everything already fits, and must scroll by an amount related to the
|
|
6
|
+
// viewport. Four landings each hardcoded `scrollBy({ left: ±560 })` — the same magic number, in
|
|
7
|
+
// four files, correct at no particular width.
|
|
8
|
+
//
|
|
9
|
+
// Item width is a custom property (--uic-car-item, default 236px) so a product sets the card size
|
|
10
|
+
// from its own stylesheet without this component knowing what a card is.
|
|
11
|
+
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
|
12
|
+
import { Chevron } from './icons.jsx';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* label what this strip is, for the scroll region and the button names ("Scroll <label> left")
|
|
16
|
+
* step px per press; defaults to 90% of the visible width, so a press always leaves a
|
|
17
|
+
* landmark from the previous screenful on screen
|
|
18
|
+
*/
|
|
19
|
+
// Both edge tests need the SAME tolerance. They did not: the end test allowed a pixel of slack
|
|
20
|
+
// and the start test demanded scrollLeft <= 1, while scroll-snap parks the strip at its first
|
|
21
|
+
// snap point — scrollLeft === 2 on a card with a border. So arriving at the start left the back
|
|
22
|
+
// button enabled, and pressing it moved the strip two pixels: a control that looks live and does
|
|
23
|
+
// nothing, which is the thing this component's own header promises not to ship.
|
|
24
|
+
const EDGE = 2;
|
|
25
|
+
|
|
26
|
+
export function Carousel(props) {
|
|
27
|
+
const { label, step, children, classNames = {} } = props;
|
|
28
|
+
const ref = useRef(null);
|
|
29
|
+
const [edges, setEdges] = useState({ start: true, end: true, overflow: false });
|
|
30
|
+
|
|
31
|
+
const measure = useCallback(() => {
|
|
32
|
+
const el = ref.current;
|
|
33
|
+
if (!el) return;
|
|
34
|
+
const overflow = el.scrollWidth - el.clientWidth > EDGE;
|
|
35
|
+
setEdges({
|
|
36
|
+
overflow,
|
|
37
|
+
start: el.scrollLeft <= EDGE,
|
|
38
|
+
end: el.scrollLeft >= el.scrollWidth - el.clientWidth - EDGE,
|
|
39
|
+
});
|
|
40
|
+
}, []);
|
|
41
|
+
|
|
42
|
+
useEffect(() => {
|
|
43
|
+
const el = ref.current;
|
|
44
|
+
if (!el) return undefined;
|
|
45
|
+
measure();
|
|
46
|
+
// Content arrives asynchronously (templates fetched after mount) and the container resizes
|
|
47
|
+
// with the window, so "does this overflow" has to be answered again, not once.
|
|
48
|
+
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
|
|
49
|
+
ro?.observe(el);
|
|
50
|
+
for (const child of el.children) ro?.observe(child);
|
|
51
|
+
return () => ro?.disconnect();
|
|
52
|
+
}, [measure, children]);
|
|
53
|
+
|
|
54
|
+
const scroll = (dir) => {
|
|
55
|
+
const el = ref.current;
|
|
56
|
+
if (!el) return;
|
|
57
|
+
el.scrollBy({ left: dir * (step || Math.round(el.clientWidth * 0.9)), behavior: 'smooth' });
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
return (
|
|
61
|
+
<div className={['uic-carousel-wrap', classNames.root || ''].filter(Boolean).join(' ')}>
|
|
62
|
+
{edges.overflow ? (
|
|
63
|
+
<button type="button" className={['uic-carousel-nav is-left', classNames.button || ''].filter(Boolean).join(' ')}
|
|
64
|
+
onClick={() => scroll(-1)} disabled={edges.start} aria-label={`Scroll ${label} left`}>
|
|
65
|
+
<Chevron dir="left" />
|
|
66
|
+
</button>
|
|
67
|
+
) : null}
|
|
68
|
+
<div className={['uic-carousel', classNames.viewport || ''].filter(Boolean).join(' ')}
|
|
69
|
+
ref={ref} onScroll={measure} role="group" aria-label={label}>
|
|
70
|
+
{children}
|
|
71
|
+
</div>
|
|
72
|
+
{edges.overflow ? (
|
|
73
|
+
<button type="button" className={['uic-carousel-nav is-right', classNames.button || ''].filter(Boolean).join(' ')}
|
|
74
|
+
onClick={() => scroll(1)} disabled={edges.end} aria-label={`Scroll ${label} right`}>
|
|
75
|
+
<Chevron dir="right" />
|
|
76
|
+
</button>
|
|
77
|
+
) : null}
|
|
78
|
+
</div>
|
|
79
|
+
);
|
|
80
|
+
}
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
// ChatPanel — the whole conversational column beside a document: header, history, live turn,
|
|
2
|
+
// connecting/retry state, attachments, dictation, composer.
|
|
3
|
+
//
|
|
4
|
+
// This existed four times (273 / 336 / 350 / 333 lines) in four products, and every copy had
|
|
5
|
+
// drifted: one shipped a disabled paperclip labelled "coming soon", three shipped a disabled
|
|
6
|
+
// microphone, one never showed that a turn was running when the turn had been started somewhere
|
|
7
|
+
// else, one dropped its staged files before checking whether the send would even happen, and one
|
|
8
|
+
// decided whether a session id was "real" by looking for the prefix "new:" in it.
|
|
9
|
+
//
|
|
10
|
+
// What is HERE is what is the same in all four: the state machine of a conversation.
|
|
11
|
+
// What stays with the CALLER is everything that differs — the transport, the product's prose,
|
|
12
|
+
// and where the panel sits in the page:
|
|
13
|
+
//
|
|
14
|
+
// runTurn run one turn and report it through `handlers`. The panel does not know whether
|
|
15
|
+
// that is one stream, a stream with a fallback, or three requests.
|
|
16
|
+
// loadHistory the conversation so far, already as ChatMessage[]. Callers write
|
|
17
|
+
// `.then(turnsToMessages)`; a caller whose brand-new document has no session
|
|
18
|
+
// short-circuits to [] here and never makes the request. The panel treats the
|
|
19
|
+
// session id as opaque and never parses it, which is what makes that possible.
|
|
20
|
+
//
|
|
21
|
+
// The panel owns `busy` (its own turn is in flight) and takes `externalBusy` (a turn is running
|
|
22
|
+
// that this tab did not start — another window, or the very first turn before the session is
|
|
23
|
+
// queryable). While externalBusy is true and there is nothing local, it polls history so the
|
|
24
|
+
// conversation appears, and when it goes false it reloads once so the final answer lands. A
|
|
25
|
+
// panel that ignores externalBusy shows a blank "describe what you want" prompt while the agent
|
|
26
|
+
// is visibly working, which is what one of the four copies did.
|
|
27
|
+
//
|
|
28
|
+
// Session ids: a document created from a landing page has no session until the first turn opens
|
|
29
|
+
// one, so `sessionId` can change mid-stream from the caller's placeholder to the real id. That is
|
|
30
|
+
// the same conversation renaming itself, not a reason to refetch over blocks arriving live — see
|
|
31
|
+
// the adopt guard below.
|
|
32
|
+
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
|
33
|
+
import { ChatMessages, ChatMessagesSkeleton } from './ChatMessages.jsx';
|
|
34
|
+
import { Composer } from './Composer.jsx';
|
|
35
|
+
import { Chip } from './Chip.jsx';
|
|
36
|
+
import { IcMic, IcPanelRight, IcPaperclip, IcSend } from './icons.jsx';
|
|
37
|
+
import { withReasoning, withResult, withStep, withText } from '../state/blocks.js';
|
|
38
|
+
import { bytesLabel } from '../format.js';
|
|
39
|
+
|
|
40
|
+
// Not props. Every one of the four copies used these exact numbers, so there is nothing to
|
|
41
|
+
// configure — a knob nobody turns is a knob that only makes the call sites longer.
|
|
42
|
+
const POLL_MS = 3000; // catch-up poll while a turn runs elsewhere
|
|
43
|
+
const RETRY_MS = 20000; // resend a message the gateway was not up to receive
|
|
44
|
+
const PIN_PX = 80; // "close enough to the bottom" to keep following the stream
|
|
45
|
+
|
|
46
|
+
// ChatPanel's own defaults, NOT the package's DEFAULT_STATUS_LABELS. All four panels overrode
|
|
47
|
+
// that export with these sentences; promoting them into the export would silently rewrite the
|
|
48
|
+
// badges of every other consumer, which none of them asked for.
|
|
49
|
+
const PANEL_STATUS_LABELS = {
|
|
50
|
+
failed: 'This turn failed. Please try again.',
|
|
51
|
+
cancelled: 'Stopped',
|
|
52
|
+
incomplete: 'The turn hit its limit. Send a follow up to continue.',
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export function ChatPanel(props) {
|
|
56
|
+
const {
|
|
57
|
+
sessionId,
|
|
58
|
+
runTurn,
|
|
59
|
+
loadHistory,
|
|
60
|
+
onSessionStarted,
|
|
61
|
+
onChanged,
|
|
62
|
+
|
|
63
|
+
seed = '',
|
|
64
|
+
onSeedConsumed,
|
|
65
|
+
|
|
66
|
+
externalBusy = false,
|
|
67
|
+
|
|
68
|
+
attachments = null,
|
|
69
|
+
dictation = null,
|
|
70
|
+
|
|
71
|
+
title = '',
|
|
72
|
+
headerRight = null,
|
|
73
|
+
collapsed = false,
|
|
74
|
+
onToggleCollapse,
|
|
75
|
+
width,
|
|
76
|
+
|
|
77
|
+
placeholder = 'Message',
|
|
78
|
+
emptyState = null,
|
|
79
|
+
busyState,
|
|
80
|
+
connectingLabel = 'connecting',
|
|
81
|
+
connectingNote = 'Still connecting. Your message will be sent as soon as it is online.',
|
|
82
|
+
workingLabel = 'Working…',
|
|
83
|
+
statusLabels = PANEL_STATUS_LABELS,
|
|
84
|
+
renderMarkdown,
|
|
85
|
+
userExtras,
|
|
86
|
+
toolLabels,
|
|
87
|
+
classNames = {},
|
|
88
|
+
} = props;
|
|
89
|
+
|
|
90
|
+
const [messages, setMessages] = useState([]);
|
|
91
|
+
const [draft, setDraft] = useState('');
|
|
92
|
+
const [busy, setBusy] = useState(false);
|
|
93
|
+
const [connecting, setConnecting] = useState(false);
|
|
94
|
+
const [histLoading, setHistLoading] = useState(true);
|
|
95
|
+
const [staged, setStaged] = useState([]); // files picked, not yet sent
|
|
96
|
+
const [attachErr, setAttachErr] = useState('');
|
|
97
|
+
const [listening, setListening] = useState(false);
|
|
98
|
+
|
|
99
|
+
const pendingRef = useRef(null); // { text, files } awaiting a live gateway
|
|
100
|
+
const seededRef = useRef(false);
|
|
101
|
+
const adoptedRef = useRef(null);
|
|
102
|
+
const bodyRef = useRef(null);
|
|
103
|
+
const fileRef = useRef(null);
|
|
104
|
+
const pinnedRef = useRef(true);
|
|
105
|
+
const prevExternalBusyRef = useRef(false);
|
|
106
|
+
const prevIdRef = useRef(sessionId);
|
|
107
|
+
|
|
108
|
+
// The callbacks arrive as fresh arrow functions on every render of the page, so they cannot be
|
|
109
|
+
// effect dependencies without re-running the history load on every keystroke. Reading them
|
|
110
|
+
// through a ref keeps the effects keyed on the things that actually changed (the session, the
|
|
111
|
+
// busy flags) while still calling the CURRENT function.
|
|
112
|
+
const api = useRef(null);
|
|
113
|
+
api.current = { runTurn, loadHistory, onSessionStarted, onChanged, onSeedConsumed };
|
|
114
|
+
|
|
115
|
+
// Stop listening when the panel goes away — the recogniser keeps the microphone otherwise.
|
|
116
|
+
// Build `dictation` ONCE at the call site (useState(() => createDictation())): a fresh object
|
|
117
|
+
// per render would stop the recogniser on every keystroke.
|
|
118
|
+
useEffect(() => () => dictation?.stop(), [dictation]);
|
|
119
|
+
|
|
120
|
+
// ── the message list ──────────────────────────────────────────────────────
|
|
121
|
+
function updateLastAsst(fn) {
|
|
122
|
+
setMessages((m) => {
|
|
123
|
+
const out = m.slice();
|
|
124
|
+
for (let i = out.length - 1; i >= 0; i -= 1) {
|
|
125
|
+
if (out[i].role === 'assistant') { out[i] = fn({ ...out[i] }); break; }
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function dropRunningAsst() {
|
|
132
|
+
setMessages((m) => (m.length && m[m.length - 1].role === 'assistant' && m[m.length - 1].status === 'running'
|
|
133
|
+
? m.slice(0, -1) : m));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Follow the stream only when the reader is already at the bottom. Measured on scroll rather
|
|
137
|
+
// than after the update, because by then the new content has already grown the distance.
|
|
138
|
+
const onBodyScroll = () => {
|
|
139
|
+
const el = bodyRef.current;
|
|
140
|
+
if (el) pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight <= PIN_PX;
|
|
141
|
+
};
|
|
142
|
+
useEffect(() => {
|
|
143
|
+
const el = bodyRef.current;
|
|
144
|
+
if (el && pinnedRef.current) el.scrollTo({ top: el.scrollHeight });
|
|
145
|
+
}, [messages, connecting, histLoading]);
|
|
146
|
+
|
|
147
|
+
// ── running a turn ────────────────────────────────────────────────────────
|
|
148
|
+
const deliver = useCallback(async (text, files = []) => {
|
|
149
|
+
setBusy(true);
|
|
150
|
+
setMessages((m) => [...m, { role: 'assistant', blocks: [], status: 'running' }]);
|
|
151
|
+
try {
|
|
152
|
+
const out = await api.current.runTurn({
|
|
153
|
+
sessionId,
|
|
154
|
+
text,
|
|
155
|
+
attachments: files,
|
|
156
|
+
handlers: {
|
|
157
|
+
onSession: (sid) => {
|
|
158
|
+
// Arm the adopt guard only when the id is genuinely CHANGING: a session reporting
|
|
159
|
+
// the id it already has is not a rename and must not suppress a later reload.
|
|
160
|
+
if (sid && sid !== sessionId) adoptedRef.current = sid;
|
|
161
|
+
api.current.onSessionStarted?.(sid);
|
|
162
|
+
},
|
|
163
|
+
onReasoningDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withReasoning(a.blocks, d) })),
|
|
164
|
+
onToolCall: (name, args, callId) => updateLastAsst((a) => ({ ...a, blocks: withStep(a.blocks, { name, args, callId }) })),
|
|
165
|
+
onToolResult: (callId, output) => updateLastAsst((a) => ({ ...a, blocks: withResult(a.blocks, callId, output) })),
|
|
166
|
+
onTextDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withText(a.blocks, d) })),
|
|
167
|
+
onDone: (status) => updateLastAsst((a) => ({ ...a, status: status === 'completed' ? 'done' : status })),
|
|
168
|
+
onError: () => updateLastAsst((a) => ({
|
|
169
|
+
...a,
|
|
170
|
+
blocks: a.blocks.length ? a.blocks : withText([], 'Something went wrong. Please try again.'),
|
|
171
|
+
status: 'failed',
|
|
172
|
+
})),
|
|
173
|
+
},
|
|
174
|
+
}) || {};
|
|
175
|
+
if (out.connecting) {
|
|
176
|
+
// Not a failure: the gateway is still coming up. Take the turn back off the list and
|
|
177
|
+
// hold the message — including its files — for the retry.
|
|
178
|
+
dropRunningAsst();
|
|
179
|
+
pendingRef.current = { text, files };
|
|
180
|
+
setConnecting(true);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
pendingRef.current = null;
|
|
184
|
+
setConnecting(false);
|
|
185
|
+
updateLastAsst((a) => (a.status === 'running' ? { ...a, status: 'done' } : a));
|
|
186
|
+
api.current.onChanged?.();
|
|
187
|
+
} catch {
|
|
188
|
+
dropRunningAsst();
|
|
189
|
+
pendingRef.current = { text, files };
|
|
190
|
+
setConnecting(true);
|
|
191
|
+
} finally {
|
|
192
|
+
setBusy(false);
|
|
193
|
+
}
|
|
194
|
+
}, [sessionId]);
|
|
195
|
+
|
|
196
|
+
const preparing = staged.some((f) => f.pending);
|
|
197
|
+
const sendBlocked = busy || histLoading || preparing;
|
|
198
|
+
|
|
199
|
+
function send() {
|
|
200
|
+
const t = draft.trim();
|
|
201
|
+
// The guard comes FIRST. One copy cleared its staged files above this line, so a send that
|
|
202
|
+
// was refused (mid-turn, or with an empty box) silently threw the attachments away.
|
|
203
|
+
if (!t || sendBlocked) return;
|
|
204
|
+
// Sending ends the utterance: dictation is hands-free, and a recogniser still listening after
|
|
205
|
+
// the message has gone types the next sentence into an empty box the person is not looking at.
|
|
206
|
+
if (listening) { dictation?.stop(); setListening(false); }
|
|
207
|
+
const files = staged;
|
|
208
|
+
// The names ride on the message so the bubble shows what was sent with it. They are not
|
|
209
|
+
// replayed from history — the transcript stores the person's text, not the files — so this is
|
|
210
|
+
// what was attached in this session, not a claim about every past turn.
|
|
211
|
+
setMessages((m) => [...m, { role: 'user', text: t, files: files.map((f) => f.name) }]);
|
|
212
|
+
setDraft('');
|
|
213
|
+
setStaged([]);
|
|
214
|
+
setAttachErr('');
|
|
215
|
+
deliver(t, files);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ── history ───────────────────────────────────────────────────────────────
|
|
219
|
+
// Keyed on sessionId. A placeholder id resolving to the real one is the SAME conversation, and
|
|
220
|
+
// refetching there would setMessages() over blocks arriving live — the panel would show the
|
|
221
|
+
// user's bubble and nothing else while the agent was visibly working. We know it is the same
|
|
222
|
+
// conversation because our own stream just told us so.
|
|
223
|
+
//
|
|
224
|
+
// The guard is consumed on every run, not just the matching one: coming BACK to this id later
|
|
225
|
+
// is a real reason to reload, and a guard that is never cleared would skip that too.
|
|
226
|
+
useEffect(() => {
|
|
227
|
+
const adopted = adoptedRef.current;
|
|
228
|
+
adoptedRef.current = null;
|
|
229
|
+
if (adopted && adopted === sessionId) { prevIdRef.current = sessionId; return undefined; }
|
|
230
|
+
|
|
231
|
+
// A different document: drop the previous conversation instead of leaving it on screen
|
|
232
|
+
// under a new title until (and only if) the new one turns out to be non-empty.
|
|
233
|
+
if (prevIdRef.current !== sessionId) {
|
|
234
|
+
prevIdRef.current = sessionId;
|
|
235
|
+
setMessages([]);
|
|
236
|
+
setHistLoading(true);
|
|
237
|
+
setStaged([]);
|
|
238
|
+
setAttachErr('');
|
|
239
|
+
// A different document gets its own first message. The once-only latch is about not
|
|
240
|
+
// resending THIS document's seed, not about one seed per panel for all time.
|
|
241
|
+
seededRef.current = false;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Fired before the await so the caller can strip ?seed= from the URL immediately — a refresh
|
|
245
|
+
// or a back-button must never resend it. It fires whenever a seed was supplied, including
|
|
246
|
+
// when history turns out to be non-empty and the seed is therefore skipped: making the URL
|
|
247
|
+
// non-replayable is the point, and it is not conditional on the send.
|
|
248
|
+
if (seed) api.current.onSeedConsumed?.();
|
|
249
|
+
|
|
250
|
+
let dead = false;
|
|
251
|
+
Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {
|
|
252
|
+
if (dead) return;
|
|
253
|
+
if (hist?.length) setMessages(hist);
|
|
254
|
+
setHistLoading(false);
|
|
255
|
+
if (seed && !seededRef.current && !hist?.length) {
|
|
256
|
+
seededRef.current = true;
|
|
257
|
+
setMessages([{ role: 'user', text: seed }]);
|
|
258
|
+
deliver(seed);
|
|
259
|
+
}
|
|
260
|
+
}).catch(() => { if (!dead) setHistLoading(false); });
|
|
261
|
+
return () => { dead = true; };
|
|
262
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
263
|
+
}, [sessionId]);
|
|
264
|
+
|
|
265
|
+
// Retry a message the gateway was not up to receive.
|
|
266
|
+
useEffect(() => {
|
|
267
|
+
if (!connecting) return undefined;
|
|
268
|
+
const iv = window.setInterval(() => {
|
|
269
|
+
const p = pendingRef.current;
|
|
270
|
+
if (p && !busy) deliver(p.text, p.files);
|
|
271
|
+
}, RETRY_MS);
|
|
272
|
+
return () => window.clearInterval(iv);
|
|
273
|
+
}, [connecting, busy, deliver]);
|
|
274
|
+
|
|
275
|
+
// A turn may be running that this tab did not start. While that is true and nothing local is
|
|
276
|
+
// streaming, poll history so its messages appear; when it ends, reload once so the final answer
|
|
277
|
+
// and whatever it changed land here without a refresh.
|
|
278
|
+
useEffect(() => {
|
|
279
|
+
let dead = false;
|
|
280
|
+
let poll;
|
|
281
|
+
const reload = () => Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {
|
|
282
|
+
// Never clobber a turn streaming in THIS tab, or a message still waiting to be sent.
|
|
283
|
+
if (!dead && hist?.length && !busy && !pendingRef.current) setMessages(hist);
|
|
284
|
+
}).catch(() => {});
|
|
285
|
+
if (externalBusy && messages.length === 0 && !busy) poll = window.setInterval(reload, POLL_MS);
|
|
286
|
+
if (prevExternalBusyRef.current && !externalBusy) {
|
|
287
|
+
reload();
|
|
288
|
+
api.current.onChanged?.();
|
|
289
|
+
}
|
|
290
|
+
prevExternalBusyRef.current = externalBusy;
|
|
291
|
+
return () => { dead = true; if (poll) window.clearInterval(poll); };
|
|
292
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
293
|
+
}, [externalBusy, messages.length, busy, sessionId]);
|
|
294
|
+
|
|
295
|
+
// ── attachments ───────────────────────────────────────────────────────────
|
|
296
|
+
// Each file appears immediately as a pending chip and resolves in place. prepare() is a real
|
|
297
|
+
// wait — a network upload for one product, base64 of up to 25 MB for another — and a picker
|
|
298
|
+
// that looks inert for three seconds is how people pick the same file twice.
|
|
299
|
+
function pick(list) {
|
|
300
|
+
if (!attachments?.prepare) return;
|
|
301
|
+
setAttachErr('');
|
|
302
|
+
for (const file of list) {
|
|
303
|
+
const entry = { name: file.name, size: file.size, pending: true };
|
|
304
|
+
setStaged((cur) => [...cur, entry]);
|
|
305
|
+
Promise.resolve(attachments.prepare(file)).then((ready) => {
|
|
306
|
+
setStaged((cur) => cur.map((s) => (s === entry ? { name: entry.name, size: entry.size, ...ready } : s)));
|
|
307
|
+
}).catch((e) => {
|
|
308
|
+
// Drop the chip and say why on its own line. The alternative one copy shipped — leaving a
|
|
309
|
+
// chip named "(failed) report.pdf" in the row — looks like a file that is going to be sent.
|
|
310
|
+
setStaged((cur) => cur.filter((s) => s !== entry));
|
|
311
|
+
setAttachErr(e?.message || `${file.name} could not be attached.`);
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function toggleDictation() {
|
|
317
|
+
if (!dictation) return;
|
|
318
|
+
if (listening) { dictation.stop(); setListening(false); return; }
|
|
319
|
+
setListening(true);
|
|
320
|
+
dictation.start({
|
|
321
|
+
onText: (text) => setDraft((cur) => (cur ? `${cur.replace(/\s+$/, '')} ${text}` : text)),
|
|
322
|
+
onEnd: () => setListening(false),
|
|
323
|
+
onError: () => setListening(false),
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ── render ────────────────────────────────────────────────────────────────
|
|
328
|
+
const rootCls = ['uic-chat', collapsed ? 'is-collapsed' : '', classNames.root || '']
|
|
329
|
+
.filter(Boolean).join(' ');
|
|
330
|
+
const toggle = onToggleCollapse ? (
|
|
331
|
+
<button type="button" className="uic-panel-toggle" onClick={onToggleCollapse}
|
|
332
|
+
title={collapsed ? 'Show the conversation' : 'Hide the conversation'}
|
|
333
|
+
aria-label={collapsed ? 'Show the conversation' : 'Hide the conversation'}
|
|
334
|
+
aria-expanded={!collapsed}>
|
|
335
|
+
<IcPanelRight />
|
|
336
|
+
</button>
|
|
337
|
+
) : null;
|
|
338
|
+
|
|
339
|
+
if (collapsed) {
|
|
340
|
+
return (
|
|
341
|
+
<aside className={rootCls}>
|
|
342
|
+
<div className="uic-chat-h">{toggle}</div>
|
|
343
|
+
</aside>
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const empty = messages.length === 0;
|
|
348
|
+
const attachControl = attachments ? (
|
|
349
|
+
<>
|
|
350
|
+
<input ref={fileRef} type="file" hidden
|
|
351
|
+
accept={attachments.accept}
|
|
352
|
+
multiple={attachments.multiple !== false}
|
|
353
|
+
onChange={(e) => { pick([...e.target.files]); e.target.value = ''; }} />
|
|
354
|
+
<button type="button" className="uic-chat-icon" aria-label="Attach a file"
|
|
355
|
+
disabled={busy} onClick={() => fileRef.current?.click()}>
|
|
356
|
+
<IcPaperclip />
|
|
357
|
+
</button>
|
|
358
|
+
</>
|
|
359
|
+
) : null;
|
|
360
|
+
// No control for a capability we do not have: `dictation` is null wherever the browser has no
|
|
361
|
+
// recogniser, and then there is no microphone at all — never a disabled one.
|
|
362
|
+
const micControl = dictation ? (
|
|
363
|
+
<button type="button" className={'uic-chat-icon' + (listening ? ' is-on' : '')}
|
|
364
|
+
aria-label={listening ? 'Stop dictating' : 'Dictate'} aria-pressed={listening}
|
|
365
|
+
disabled={busy} onClick={toggleDictation}>
|
|
366
|
+
<IcMic />
|
|
367
|
+
</button>
|
|
368
|
+
) : null;
|
|
369
|
+
const defaultBusyState = (
|
|
370
|
+
<div className="uic-chat-empty">
|
|
371
|
+
<span className="uic-chat-pulse" aria-hidden="true" />
|
|
372
|
+
<div className="uic-chat-empty-t">{workingLabel}</div>
|
|
373
|
+
</div>
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
return (
|
|
377
|
+
<aside className={rootCls} style={width ? { flex: `0 0 ${width}px` } : undefined}>
|
|
378
|
+
<div className="uic-chat-h">
|
|
379
|
+
{toggle}
|
|
380
|
+
{title ? <span className="uic-chat-title" title={title}>{title}</span> : null}
|
|
381
|
+
{headerRight}
|
|
382
|
+
{connecting ? <span className="uic-chat-conn">{connectingLabel}</span> : null}
|
|
383
|
+
</div>
|
|
384
|
+
|
|
385
|
+
<div className="uic-chat-body" ref={bodyRef} onScroll={onBodyScroll} role="log" aria-live="polite">
|
|
386
|
+
{histLoading ? <ChatMessagesSkeleton />
|
|
387
|
+
: empty && externalBusy ? (busyState === undefined ? defaultBusyState : busyState)
|
|
388
|
+
: empty ? emptyState
|
|
389
|
+
: (
|
|
390
|
+
<ChatMessages
|
|
391
|
+
messages={messages}
|
|
392
|
+
renderMarkdown={renderMarkdown}
|
|
393
|
+
// The caller's slot falls through to the built-in file chips when it returns
|
|
394
|
+
// undefined, the same contract ChatMessages already uses for renderMessage.
|
|
395
|
+
userExtras={(m, i) => {
|
|
396
|
+
const own = userExtras?.(m, i);
|
|
397
|
+
if (own !== undefined) return own;
|
|
398
|
+
if (!m.files?.length) return undefined;
|
|
399
|
+
return (
|
|
400
|
+
<span className="uic-chat-msg-files">
|
|
401
|
+
{m.files.map((n) => (
|
|
402
|
+
<Chip key={n} icon={<IcPaperclip size={11} />} label={n} title={n} />
|
|
403
|
+
))}
|
|
404
|
+
</span>
|
|
405
|
+
);
|
|
406
|
+
}}
|
|
407
|
+
workingLabel={workingLabel}
|
|
408
|
+
// All four panels wrote the same string twice, because ToolGroup carries its own
|
|
409
|
+
// default. One label, one place.
|
|
410
|
+
toolLabels={{ workingLabel, ...(toolLabels || {}) }}
|
|
411
|
+
statusLabels={statusLabels}
|
|
412
|
+
/>
|
|
413
|
+
)}
|
|
414
|
+
{connecting ? (
|
|
415
|
+
<div className="uic-chat-note" role="status">
|
|
416
|
+
<span className="uic-chat-dot" aria-hidden="true" />
|
|
417
|
+
{connectingNote}
|
|
418
|
+
</div>
|
|
419
|
+
) : null}
|
|
420
|
+
</div>
|
|
421
|
+
|
|
422
|
+
<Composer
|
|
423
|
+
value={draft}
|
|
424
|
+
onChange={setDraft}
|
|
425
|
+
onSend={send}
|
|
426
|
+
disabled={histLoading}
|
|
427
|
+
sendDisabled={sendBlocked || !draft.trim()}
|
|
428
|
+
placeholder={placeholder}
|
|
429
|
+
rows={2}
|
|
430
|
+
autoGrow={false}
|
|
431
|
+
classNames={{ root: 'uic-chat-cmp', input: 'uic-chat-cmp-input', row: 'uic-chat-cmp-row' }}
|
|
432
|
+
attachments={(staged.length > 0 || attachErr) ? (
|
|
433
|
+
<div className="uic-chat-files">
|
|
434
|
+
{staged.map((f, i) => (
|
|
435
|
+
<Chip
|
|
436
|
+
key={`${f.name}-${i}`}
|
|
437
|
+
icon={<IcPaperclip size={11} />}
|
|
438
|
+
title={f.name}
|
|
439
|
+
label={<>
|
|
440
|
+
<span className="uic-chip-t">{f.name}</span>
|
|
441
|
+
<span className="uic-chip-meta">{f.pending ? '…' : bytesLabel(f.size)}</span>
|
|
442
|
+
</>}
|
|
443
|
+
onRemove={() => setStaged((c) => c.filter((_, j) => j !== i))}
|
|
444
|
+
removeLabel={`Remove ${f.name}`}
|
|
445
|
+
/>
|
|
446
|
+
))}
|
|
447
|
+
{attachErr ? <span className="uic-chat-file-err">{attachErr}</span> : null}
|
|
448
|
+
</div>
|
|
449
|
+
) : null}
|
|
450
|
+
accessoriesLeft={attachControl}
|
|
451
|
+
accessoriesRight={micControl}
|
|
452
|
+
renderSend={() => (
|
|
453
|
+
<button type="button" className="uic-chat-send" onClick={send}
|
|
454
|
+
disabled={sendBlocked || !draft.trim()} aria-label="Send message">
|
|
455
|
+
<IcSend />
|
|
456
|
+
</button>
|
|
457
|
+
)}
|
|
458
|
+
/>
|
|
459
|
+
</aside>
|
|
460
|
+
);
|
|
461
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Chip — a small labelled token: a staged file, a chosen template, a filter that is set.
|
|
2
|
+
//
|
|
3
|
+
// Three spellings of this existed across four apps, and the interactive ones were built as
|
|
4
|
+
// <span role="button" tabIndex={0}> with a keydown handler that only answered Enter (never
|
|
5
|
+
// Space), inside another button. Here the pressable parts are real <button>s, so the keyboard,
|
|
6
|
+
// the accessibility tree and the browser's own focus ring all work without being re-implemented.
|
|
7
|
+
//
|
|
8
|
+
// Width is CSS, not a prop: two of the copies set maxWidth 180 and 220 inline on the same
|
|
9
|
+
// component in the same app. The label ellipsizes against the row it is in.
|
|
10
|
+
import React from 'react';
|
|
11
|
+
import { IcX } from './icons.jsx';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* label the text (a node — e.g. name + a size span)
|
|
15
|
+
* icon leading glyph
|
|
16
|
+
* title native tooltip, usually the untruncated label
|
|
17
|
+
* selected this chip stands for something chosen (brand fill)
|
|
18
|
+
* onClick makes the chip itself a button; unselected + clickable renders as an open slot
|
|
19
|
+
* onRemove adds a trailing ✕ button; removeLabel is REQUIRED with it, because "✕" alone tells
|
|
20
|
+
* a screen reader nothing about which of five chips it removes
|
|
21
|
+
*/
|
|
22
|
+
export function Chip(props) {
|
|
23
|
+
const { label, icon, title, selected = false, onClick, onRemove, removeLabel, className } = props;
|
|
24
|
+
const cls = ['uic-chip',
|
|
25
|
+
selected ? 'is-selected' : '',
|
|
26
|
+
onClick && !selected ? 'is-open' : '',
|
|
27
|
+
className || ''].filter(Boolean).join(' ');
|
|
28
|
+
|
|
29
|
+
const body = (
|
|
30
|
+
<>
|
|
31
|
+
{icon ? <span className="uic-chip-ic" aria-hidden="true">{icon}</span> : null}
|
|
32
|
+
<span className="uic-chip-l">{label}</span>
|
|
33
|
+
</>
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
// A chip that is both pressable and removable is two controls, so the outer element stays a
|
|
37
|
+
// plain span and the press target becomes its own button — never a button inside a button.
|
|
38
|
+
if (onClick && onRemove) {
|
|
39
|
+
return (
|
|
40
|
+
<span className={cls} title={title}>
|
|
41
|
+
<button type="button" className="uic-chip-press" onClick={onClick}>{body}</button>
|
|
42
|
+
<button type="button" className="uic-chip-x" aria-label={removeLabel} onClick={onRemove}>
|
|
43
|
+
<IcX size={12} />
|
|
44
|
+
</button>
|
|
45
|
+
</span>
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
if (onClick) {
|
|
49
|
+
return <button type="button" className={cls} title={title} onClick={onClick}>{body}</button>;
|
|
50
|
+
}
|
|
51
|
+
return (
|
|
52
|
+
<span className={cls} title={title}>
|
|
53
|
+
{body}
|
|
54
|
+
{onRemove ? (
|
|
55
|
+
<button type="button" className="uic-chip-x" aria-label={removeLabel} onClick={onRemove}>
|
|
56
|
+
<IcX size={12} />
|
|
57
|
+
</button>
|
|
58
|
+
) : null}
|
|
59
|
+
</span>
|
|
60
|
+
);
|
|
61
|
+
}
|