reifyui 0.13.9 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -0
- package/dist/agent-chat.cjs +2046 -0
- package/dist/agent-chat.cjs.map +1 -0
- package/dist/agent-chat.d.ts +190 -0
- package/dist/agent-chat.js +157 -0
- package/dist/agent-chat.js.map +1 -0
- package/dist/chunk-6CJPYMR2.js +1892 -0
- package/dist/chunk-6CJPYMR2.js.map +1 -0
- package/dist/chunk-AGSX5YKH.js +177 -0
- package/dist/chunk-AGSX5YKH.js.map +1 -0
- package/dist/chunk-WAND7AYD.js +124 -0
- package/dist/chunk-WAND7AYD.js.map +1 -0
- package/dist/graph.js +2 -1
- package/dist/graph.js.map +1 -1
- package/dist/harness.cjs +4 -0
- package/dist/harness.cjs.map +1 -1
- package/dist/harness.js +4 -0
- package/dist/harness.js.map +1 -1
- package/dist/index.cjs +2269 -741
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.js +50 -6
- package/dist/index.js.map +1 -1
- package/package.json +11 -2
- package/src/agent-chat/components.jsx +777 -0
- package/src/agent-chat/index.d.ts +190 -0
- package/src/agent-chat/index.js +24 -0
- package/src/agent-chat/marks.js +51 -0
- package/src/agent-chat/time.js +55 -0
- package/src/agent-chat/tools.js +357 -0
- package/src/agent-chat/turn.js +476 -0
- package/src/components/ChatPanel.jsx +37 -1
- package/src/harness/index.js +3 -1
- package/src/index.d.ts +11 -0
- package/styles/agent-chat.css +306 -0
- package/styles/chat.css +5 -0
- package/dist/chunk-J7SECRIG.js +0 -295
- package/dist/chunk-J7SECRIG.js.map +0 -1
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
// The agent conversation, drawn the way Claude Code draws it: prose in full, work folded to one
|
|
2
|
+
// past-tense line per run of calls, every call one click from its whole input and output, and a
|
|
3
|
+
// single live line that says what is happening now, with the harness's own mark moving beside it.
|
|
4
|
+
//
|
|
5
|
+
// Components take plain data (a Turn, see turn.js) and callbacks. They fetch nothing.
|
|
6
|
+
//
|
|
7
|
+
// Components take one `props` object and destructure inside, so TypeScript hosts do not infer
|
|
8
|
+
// every optional slot as required (the convention of the rest of the package).
|
|
9
|
+
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
10
|
+
import { describeTool, toolLine, summarizeCalls, resultNote, parseToolArgs } from './tools.js';
|
|
11
|
+
import { liveState, segments, latestPlan } from './turn.js';
|
|
12
|
+
import { formatElapsed, formatDuration, formatTokens, useElapsed } from './time.js';
|
|
13
|
+
import { Chevron, IcTerminal, IcDoc, IcScroll, IcSearch, IcGlobe, IcSpawn, IcList, IcSkill, IcPlug, IcTool, IcThink,
|
|
14
|
+
IcSend, IcX, IcPaperclip } from '../components/icons.jsx';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_AGENT_LABELS = {
|
|
17
|
+
starting: 'Starting',
|
|
18
|
+
thinking: 'Thinking',
|
|
19
|
+
writing: 'Writing',
|
|
20
|
+
tool: 'Running a tool',
|
|
21
|
+
thought: 'Thought',
|
|
22
|
+
thoughtFor: (t) => `Thought for ${t}`,
|
|
23
|
+
workedFor: (t) => `Worked for ${t}`,
|
|
24
|
+
worked: 'Done',
|
|
25
|
+
tokens: (n) => `${n} tokens`,
|
|
26
|
+
stopped: 'Stopped',
|
|
27
|
+
stoppedAfter: (t) => `Stopped after ${t}`,
|
|
28
|
+
failed: 'Failed',
|
|
29
|
+
failedAfter: (t) => `Failed after ${t}`,
|
|
30
|
+
incomplete: 'Stopped before finishing',
|
|
31
|
+
input: 'Input',
|
|
32
|
+
output: 'Output',
|
|
33
|
+
noOutput: 'No output',
|
|
34
|
+
copy: 'Copy',
|
|
35
|
+
copied: 'Copied',
|
|
36
|
+
copyFailed: 'Select and copy',
|
|
37
|
+
moreLines: (n) => (n === 1 ? '+1 line' : `+${n} lines`),
|
|
38
|
+
fewerLines: 'Show less',
|
|
39
|
+
failedCalls: (n) => (n === 1 ? '1 failed' : `${n} failed`),
|
|
40
|
+
stoppedCall: 'stopped',
|
|
41
|
+
plan: 'Plan',
|
|
42
|
+
jump: 'Jump to latest',
|
|
43
|
+
send: 'Send',
|
|
44
|
+
stop: 'Stop',
|
|
45
|
+
stopping: 'Stopping',
|
|
46
|
+
attach: 'Attach a file',
|
|
47
|
+
remove: (name) => `Remove ${name}`,
|
|
48
|
+
working: 'Working',
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g;
|
|
52
|
+
function cleanOutput(s) { return String(s ?? '').replace(ANSI, '').replace(/\r\n?/g, '\n'); }
|
|
53
|
+
function pretty(s) {
|
|
54
|
+
const x = String(s || '').trim();
|
|
55
|
+
if (!/^[[{]/.test(x)) return null;
|
|
56
|
+
try { return JSON.stringify(JSON.parse(x), null, 2); } catch { return null; }
|
|
57
|
+
}
|
|
58
|
+
function firstLine(s, max = 220) {
|
|
59
|
+
const l = cleanOutput(s).split('\n').map((x) => x.trim()).find(Boolean) || '';
|
|
60
|
+
return l.length > max ? `${l.slice(0, max)}…` : l;
|
|
61
|
+
}
|
|
62
|
+
function cls(...xs) { return xs.filter(Boolean).join(' '); }
|
|
63
|
+
|
|
64
|
+
// ── the mark ──────────────────────────────────────────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
/** The harness's mark with its motion, or three jostling dots when there is no mark. */
|
|
67
|
+
export function WorkingMark(props) {
|
|
68
|
+
const { mark, motion, size = 18, still = false } = props;
|
|
69
|
+
const m = mark ? (motion || 'pulse') : 'dots';
|
|
70
|
+
return (
|
|
71
|
+
<span className={cls('uac-mark', still && 'is-still')} data-motion={m} style={{ '--uac-mark': `${size}px` }} aria-hidden="true">
|
|
72
|
+
<span className="uac-mark-aura" />
|
|
73
|
+
<span className="uac-mark-in">
|
|
74
|
+
{mark || (<><i /><i /><i /></>)}
|
|
75
|
+
</span>
|
|
76
|
+
</span>
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The live line: `[mark] 2s · Thinking`. `start` is the epoch ms the clock counts from (the send);
|
|
82
|
+
* without one the line shows no time. `label` is what is happening now.
|
|
83
|
+
*/
|
|
84
|
+
export function WorkingIndicator(props) {
|
|
85
|
+
const { mark, motion, start = null, end = null, label, onToggle, expanded, controls, className, shimmer = true, size } = props;
|
|
86
|
+
const ms = useElapsed(start, end);
|
|
87
|
+
const body = (
|
|
88
|
+
<>
|
|
89
|
+
<WorkingMark mark={mark} motion={motion} size={size} />
|
|
90
|
+
{ms != null ? <span className="uac-elapsed" aria-hidden="true">{formatElapsed(ms)}</span> : null}
|
|
91
|
+
{ms != null ? <span className="uac-sep" aria-hidden="true">·</span> : null}
|
|
92
|
+
<span className={cls('uac-verb', shimmer && 'uac-shimmer')} data-text={label}>{label}</span>
|
|
93
|
+
{onToggle ? <span className="uac-chev" aria-hidden="true"><Chevron dir={expanded ? 'down' : 'right'} size={12} /></span> : null}
|
|
94
|
+
</>
|
|
95
|
+
);
|
|
96
|
+
if (onToggle) {
|
|
97
|
+
return (
|
|
98
|
+
<button type="button" className={cls('uac-working', 'is-button', className)} aria-expanded={!!expanded}
|
|
99
|
+
aria-controls={controls} onClick={onToggle}>
|
|
100
|
+
<span className="uac-sr" role="status">{label}</span>{body}
|
|
101
|
+
</button>
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return <div className={cls('uac-working', className)}><span className="uac-sr" role="status">{label}</span>{body}</div>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ── small parts ───────────────────────────────────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
export function CopyButton(props) {
|
|
110
|
+
const { text, labels = DEFAULT_AGENT_LABELS, label } = props;
|
|
111
|
+
const [state, setState] = useState('');
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
if (!state) return undefined;
|
|
114
|
+
const t = setTimeout(() => setState(''), 1600);
|
|
115
|
+
return () => clearTimeout(t);
|
|
116
|
+
}, [state]);
|
|
117
|
+
const copy = async (e) => {
|
|
118
|
+
e.stopPropagation();
|
|
119
|
+
try {
|
|
120
|
+
await navigator.clipboard.writeText(String(text ?? ''));
|
|
121
|
+
setState('ok');
|
|
122
|
+
} catch {
|
|
123
|
+
setState('no');
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const said = state === 'ok' ? labels.copied : state === 'no' ? labels.copyFailed : (label || labels.copy);
|
|
127
|
+
return (
|
|
128
|
+
<button type="button" className={cls('uac-copy', state && `is-${state}`)} onClick={copy} aria-label={label ? `${labels.copy} ${label}` : labels.copy}>
|
|
129
|
+
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
|
130
|
+
{state === 'ok' ? <path d="M5 12l5 5L20 7" /> : <><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V6a2 2 0 0 1 2-2h9" /></>}
|
|
131
|
+
</svg>
|
|
132
|
+
<span>{said}</span>
|
|
133
|
+
</button>
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function DiffBadge(props) {
|
|
138
|
+
const { diff } = props;
|
|
139
|
+
if (!diff || (!diff.added && !diff.removed && diff.added !== 0)) return null;
|
|
140
|
+
return (
|
|
141
|
+
<span className="uac-diff" aria-label={`${diff.added} lines added, ${diff.removed} removed`}>
|
|
142
|
+
<span className="uac-add">+{diff.added}</span><span className="uac-del">{'−'}{diff.removed}</span>
|
|
143
|
+
</span>
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Lines, the first `limit` shown and the rest one click away. */
|
|
148
|
+
export function LinesBlock(props) {
|
|
149
|
+
const { lines, limit = 12, labels = DEFAULT_AGENT_LABELS, className, numbered = false } = props;
|
|
150
|
+
const [all, setAll] = useState(false);
|
|
151
|
+
const more = Math.max(0, lines.length - limit);
|
|
152
|
+
const shown = all || !more ? lines : lines.slice(0, limit);
|
|
153
|
+
return (
|
|
154
|
+
<div className={cls('uac-lines', className)}>
|
|
155
|
+
<pre>{shown.map((l, i) => (
|
|
156
|
+
<span key={i} className={cls('uac-ln', l.cls)}>{numbered ? <span className="uac-lno">{i + 1}</span> : null}{l.text || ' '}</span>
|
|
157
|
+
))}</pre>
|
|
158
|
+
{more ? (
|
|
159
|
+
<button type="button" className="uac-more" onClick={(e) => { e.stopPropagation(); setAll((v) => !v); }} aria-expanded={all}>
|
|
160
|
+
{all ? labels.fewerLines : labels.moreLines(more)}
|
|
161
|
+
</button>
|
|
162
|
+
) : null}
|
|
163
|
+
</div>
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const asLines = (text, c) => String(text ?? '').replace(/\n$/, '').split('\n').map((t) => ({ text: t, cls: c }));
|
|
168
|
+
|
|
169
|
+
const KIND_ICON = { shell: IcTerminal, shell_output: IcTerminal, read: IcScroll, write: IcDoc, edit: IcDoc, search: IcSearch,
|
|
170
|
+
glob: IcSearch, list: IcList, web_search: IcGlobe, web_fetch: IcGlobe, agent: IcSpawn, todo: IcList, skill: IcSkill,
|
|
171
|
+
think: IcThink, toolsearch: IcSearch, browser: IcGlobe, mcp: IcPlug, tool: IcTool };
|
|
172
|
+
|
|
173
|
+
function StatusGlyph(props) {
|
|
174
|
+
const { status, kind } = props;
|
|
175
|
+
if (status === 'running') return <span className="uac-ring" aria-hidden="true" />;
|
|
176
|
+
if (status === 'failed') return <span className="uac-x" aria-hidden="true"><IcX size={13} /></span>;
|
|
177
|
+
if (status === 'stopped') return <span className="uac-stopped" aria-hidden="true" />;
|
|
178
|
+
const Ic = KIND_ICON[kind] || IcTool;
|
|
179
|
+
return <span className="uac-kind" aria-hidden="true"><Ic /></span>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A call's input, in the shape a person reads: the command, the diff, `key: value` lines. */
|
|
183
|
+
function inputLines(d, item) {
|
|
184
|
+
const a = parseToolArgs(item.args);
|
|
185
|
+
if (d.kind === 'shell') {
|
|
186
|
+
const cmd = d.mono ? d.target : (d.note || d.targetFull);
|
|
187
|
+
const out = asLines(`$ ${cmd || ''}`, 'is-cmd');
|
|
188
|
+
if (!d.mono && d.target) out.unshift({ text: d.target, cls: 'is-note' });
|
|
189
|
+
return { lines: out, copy: cmd };
|
|
190
|
+
}
|
|
191
|
+
if ((d.kind === 'edit' || d.kind === 'write') && d.diff) {
|
|
192
|
+
const lines = [];
|
|
193
|
+
const path = d.targetFull;
|
|
194
|
+
if (path) lines.push({ text: path, cls: 'is-path' });
|
|
195
|
+
const edits = Array.isArray(a.edits) ? a.edits : [a];
|
|
196
|
+
for (const e of edits) {
|
|
197
|
+
const old = e.old_string ?? e.old_str ?? e.oldText ?? e.old_text;
|
|
198
|
+
const neu = e.new_string ?? e.new_str ?? e.newText ?? e.new_text ?? e.content ?? e.file_text ?? e.contents;
|
|
199
|
+
if (old != null && String(old)) lines.push(...asLines(old, 'is-del').map((l) => ({ ...l, text: `- ${l.text}` })));
|
|
200
|
+
if (neu != null && String(neu)) lines.push(...asLines(neu, 'is-add').map((l) => ({ ...l, text: `+ ${l.text}` })));
|
|
201
|
+
}
|
|
202
|
+
const patch = a.patch ?? a.input ?? a._raw ?? a.diff;
|
|
203
|
+
if (lines.length <= (path ? 1 : 0) && typeof patch === 'string') {
|
|
204
|
+
for (const l of patch.split('\n')) lines.push({ text: l, cls: /^\+(?!\+\+)/.test(l) ? 'is-add' : /^-(?!--)/.test(l) ? 'is-del' : '' });
|
|
205
|
+
}
|
|
206
|
+
if (lines.length > (path ? 1 : 0)) return { lines, copy: typeof item.args === 'string' ? item.args : JSON.stringify(a, null, 2) };
|
|
207
|
+
}
|
|
208
|
+
if (a._raw != null) return { lines: asLines(a._raw), copy: a._raw };
|
|
209
|
+
const keys = Object.keys(a);
|
|
210
|
+
const flat = keys.length && keys.every((k) => a[k] == null || typeof a[k] !== 'object');
|
|
211
|
+
if (flat) {
|
|
212
|
+
const lines = [];
|
|
213
|
+
for (const k of keys) {
|
|
214
|
+
const v = a[k] == null ? '' : String(a[k]);
|
|
215
|
+
const vs = v.split('\n');
|
|
216
|
+
lines.push({ text: `${k}: ${vs[0]}`, cls: 'is-kv' });
|
|
217
|
+
for (const more of vs.slice(1)) lines.push({ text: ` ${more}`, cls: 'is-kv' });
|
|
218
|
+
}
|
|
219
|
+
return { lines, copy: typeof item.args === 'string' ? item.args : JSON.stringify(a, null, 2) };
|
|
220
|
+
}
|
|
221
|
+
const js = keys.length ? JSON.stringify(a, null, 2) : '';
|
|
222
|
+
return { lines: js ? asLines(js) : [], copy: js };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function StepDetail(props) {
|
|
226
|
+
const { item, d, labels, id } = props;
|
|
227
|
+
const input = inputLines(d, item);
|
|
228
|
+
const out = item.output === undefined ? null : cleanOutput(item.output);
|
|
229
|
+
const outPretty = out != null ? (pretty(out) || out) : null;
|
|
230
|
+
return (
|
|
231
|
+
<div className="uac-detail" id={id}>
|
|
232
|
+
{input.lines.length ? (
|
|
233
|
+
<section className="uac-sec">
|
|
234
|
+
<header><span>{labels.input}</span><CopyButton text={input.copy} labels={labels} /></header>
|
|
235
|
+
<LinesBlock lines={input.lines} limit={d.kind === 'write' || d.kind === 'edit' ? 24 : 12} labels={labels} />
|
|
236
|
+
</section>
|
|
237
|
+
) : null}
|
|
238
|
+
{outPretty != null ? (
|
|
239
|
+
<section className={cls('uac-sec', item.status === 'failed' && 'is-failed')}>
|
|
240
|
+
<header><span>{labels.output}</span>{outPretty ? <CopyButton text={outPretty} labels={labels} /> : null}</header>
|
|
241
|
+
{outPretty.trim() ? <LinesBlock lines={asLines(outPretty)} labels={labels} /> : <p className="uac-none">{labels.noOutput}</p>}
|
|
242
|
+
{item.truncated ? <p className="uac-none">{`${item.truncated} characters in all`}</p> : null}
|
|
243
|
+
</section>
|
|
244
|
+
) : null}
|
|
245
|
+
</div>
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** One call: what it did, to what, how it went; click for its whole input and output. */
|
|
250
|
+
export function StepRow(props) {
|
|
251
|
+
const { item, labels = DEFAULT_AGENT_LABELS, defaultOpen = false } = props;
|
|
252
|
+
const d = useMemo(() => describeTool(item.name, item.args), [item.name, item.args]);
|
|
253
|
+
const [open, setOpen] = useState(defaultOpen);
|
|
254
|
+
const uid = useRef(`uac-s-${Math.random().toString(36).slice(2, 9)}`).current;
|
|
255
|
+
const running = item.status === 'running';
|
|
256
|
+
const runMs = useElapsed(running ? item.startedAt : null, null);
|
|
257
|
+
const tookMs = !running && item.startedAt != null && item.endedAt != null ? item.endedAt - item.startedAt : null;
|
|
258
|
+
const line = toolLine(d, running ? 'running' : 'done');
|
|
259
|
+
const verb = running ? d.running : d.done;
|
|
260
|
+
// split "Ran npm test" into the verb (quiet) and the target (ink), when the line is verb + target
|
|
261
|
+
const hasTarget = d.target && line === `${verb} ${d.target}`;
|
|
262
|
+
const note = !running && item.status !== 'failed' ? resultNote(d.kind, item.output) : '';
|
|
263
|
+
const hasDetail = !!(item.args && item.args !== '{}' && item.args !== '""') || item.output !== undefined;
|
|
264
|
+
return (
|
|
265
|
+
<div className={cls('uac-step', `is-${item.status}`)} data-kind={d.kind}>
|
|
266
|
+
<button type="button" className="uac-step-h" aria-expanded={hasDetail ? open : undefined} aria-controls={hasDetail ? uid : undefined}
|
|
267
|
+
disabled={!hasDetail} onClick={() => setOpen((v) => !v)} title={d.targetFull || undefined}>
|
|
268
|
+
<StatusGlyph status={item.status} kind={d.kind} />
|
|
269
|
+
<span className="uac-step-t">
|
|
270
|
+
{hasTarget ? (<><span className="uac-step-v">{verb}</span> <span className={cls('uac-step-o', d.mono && 'is-mono')}>{d.target}</span></>)
|
|
271
|
+
: <span className={cls('uac-step-o', d.kind === 'shell' && d.mono && 'is-mono')}>{line}</span>}
|
|
272
|
+
{d.note && d.kind === 'agent' ? <span className="uac-step-n">{d.note}</span> : null}
|
|
273
|
+
</span>
|
|
274
|
+
<DiffBadge diff={item.status === 'failed' ? null : d.diff} />
|
|
275
|
+
{note ? <span className="uac-step-n">{note}</span> : null}
|
|
276
|
+
{item.status === 'stopped' ? <span className="uac-step-n">{labels.stoppedCall}</span> : null}
|
|
277
|
+
{running && runMs != null ? <span className="uac-step-time">{formatElapsed(runMs)}</span>
|
|
278
|
+
: tookMs != null && tookMs >= 1000 ? <span className="uac-step-time">{formatDuration(tookMs)}</span> : null}
|
|
279
|
+
{hasDetail ? <span className="uac-chev" aria-hidden="true"><Chevron dir={open ? 'down' : 'right'} size={12} /></span> : null}
|
|
280
|
+
</button>
|
|
281
|
+
{item.status === 'failed' && item.output ? <div className="uac-step-err">{firstLine(item.output)}</div> : null}
|
|
282
|
+
{open && hasDetail ? <StepDetail item={item} d={d} labels={labels} id={uid} /> : null}
|
|
283
|
+
</div>
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** A thought: "Thinking" while it streams, then "Thought for 6s", expandable to its words. */
|
|
288
|
+
export function ThinkingRow(props) {
|
|
289
|
+
const { item, labels = DEFAULT_AGENT_LABELS } = props;
|
|
290
|
+
const [open, setOpen] = useState(false);
|
|
291
|
+
const uid = useRef(`uac-t-${Math.random().toString(36).slice(2, 9)}`).current;
|
|
292
|
+
const live = item.open && item.endedAt == null;
|
|
293
|
+
const ms = !live && item.startedAt != null && item.endedAt != null ? item.endedAt - item.startedAt : null;
|
|
294
|
+
const label = live ? labels.thinking : ms != null && ms >= 1000 ? labels.thoughtFor(formatElapsed(ms)) : labels.thought;
|
|
295
|
+
const has = !!String(item.text || '').trim();
|
|
296
|
+
return (
|
|
297
|
+
<div className={cls('uac-step', 'is-thought', live && 'is-running')}>
|
|
298
|
+
<button type="button" className="uac-step-h" aria-expanded={has ? open : undefined} aria-controls={has ? uid : undefined}
|
|
299
|
+
disabled={!has} onClick={() => setOpen((v) => !v)}>
|
|
300
|
+
<span className="uac-kind" aria-hidden="true"><IcThink /></span>
|
|
301
|
+
<span className="uac-step-t"><span className={cls('uac-step-v', live && 'uac-shimmer')} data-text={label}>{label}</span></span>
|
|
302
|
+
{has ? <span className="uac-chev" aria-hidden="true"><Chevron dir={open ? 'down' : 'right'} size={12} /></span> : null}
|
|
303
|
+
</button>
|
|
304
|
+
{open && has ? <div className="uac-thought" id={uid}>{item.text}</div> : null}
|
|
305
|
+
</div>
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function sumDiff(tools) {
|
|
310
|
+
let added = 0; let removed = 0; let any = false;
|
|
311
|
+
for (const t of tools) {
|
|
312
|
+
if (t.status === 'failed') continue;
|
|
313
|
+
const d = describeTool(t.name, t.args).diff;
|
|
314
|
+
if (d) { any = true; added += d.added; removed += d.removed; }
|
|
315
|
+
}
|
|
316
|
+
return any ? { added, removed } : null;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* A run of work between two pieces of prose. Finished: one past-tense line ("Ran 3 commands, edited
|
|
321
|
+
* app.ts +12 −4"), click for the calls. Live (the turn's last run while it works): the line IS the
|
|
322
|
+
* live line, `[mark] 1m 4s · Running npm test`, and opens to the calls so far.
|
|
323
|
+
*/
|
|
324
|
+
export function WorkGroup(props) {
|
|
325
|
+
const { items, live = false, liveLabel, start = null, mark, motion, labels = DEFAULT_AGENT_LABELS, defaultOpen = false } = props;
|
|
326
|
+
const [open, setOpen] = useState(defaultOpen);
|
|
327
|
+
const uid = useRef(`uac-g-${Math.random().toString(36).slice(2, 9)}`).current;
|
|
328
|
+
const tools = items.filter((x) => x.kind === 'tool');
|
|
329
|
+
const thoughts = items.filter((x) => x.kind === 'thinking');
|
|
330
|
+
const failed = tools.filter((x) => x.status === 'failed').length;
|
|
331
|
+
let summary = '';
|
|
332
|
+
if (tools.length) summary = summarizeCalls(tools);
|
|
333
|
+
else if (thoughts.length) {
|
|
334
|
+
const t = thoughts[0];
|
|
335
|
+
const ms = t.startedAt != null && t.endedAt != null ? t.endedAt - t.startedAt : null;
|
|
336
|
+
summary = ms != null && ms >= 1000 ? labels.thoughtFor(formatElapsed(ms)) : labels.thought;
|
|
337
|
+
}
|
|
338
|
+
const diff = sumDiff(tools);
|
|
339
|
+
// a lone thought with nothing to read stays out of the way
|
|
340
|
+
if (!live && !tools.length && !thoughts.some((t) => String(t.text || '').trim())) return null;
|
|
341
|
+
const body = open ? (
|
|
342
|
+
<div className="uac-calls" id={uid}>
|
|
343
|
+
{items.map((it) => (it.kind === 'tool'
|
|
344
|
+
? <StepRow key={it.id} item={it} labels={labels} />
|
|
345
|
+
: <ThinkingRow key={it.id} item={it} labels={labels} />))}
|
|
346
|
+
</div>
|
|
347
|
+
) : null;
|
|
348
|
+
if (live) {
|
|
349
|
+
return (
|
|
350
|
+
<div className={cls('uac-group', 'is-live', open && 'is-open')}>
|
|
351
|
+
<WorkingIndicator mark={mark} motion={motion} start={start} label={liveLabel} onToggle={() => setOpen((v) => !v)}
|
|
352
|
+
expanded={open} controls={uid} />
|
|
353
|
+
{body}
|
|
354
|
+
</div>
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
return (
|
|
358
|
+
<div className={cls('uac-group', open && 'is-open', failed && 'has-failed')}>
|
|
359
|
+
<button type="button" className="uac-sum" aria-expanded={open} aria-controls={uid} onClick={() => setOpen((v) => !v)}>
|
|
360
|
+
<span className="uac-sum-t">{summary}</span>
|
|
361
|
+
<DiffBadge diff={diff} />
|
|
362
|
+
{failed ? <span className="uac-fail-n">{labels.failedCalls(failed)}</span> : null}
|
|
363
|
+
<span className="uac-chev" aria-hidden="true"><Chevron dir={open ? 'down' : 'right'} size={12} /></span>
|
|
364
|
+
</button>
|
|
365
|
+
{body}
|
|
366
|
+
</div>
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The plan as the agent last stated it. */
|
|
371
|
+
export function TodoCard(props) {
|
|
372
|
+
const { todos, labels = DEFAULT_AGENT_LABELS, running = false } = props;
|
|
373
|
+
if (!todos || !todos.length) return null;
|
|
374
|
+
const done = todos.filter((t) => t.status === 'completed').length;
|
|
375
|
+
return (
|
|
376
|
+
<div className="uac-todo" role="group" aria-label={`${labels.plan}: ${done} of ${todos.length} done`}>
|
|
377
|
+
{todos.map((t, i) => (
|
|
378
|
+
<div key={i} className={cls('uac-todo-i', `is-${t.status}`, !running && t.status === 'in_progress' && 'is-held')}>
|
|
379
|
+
<span className="uac-todo-m" aria-hidden="true">
|
|
380
|
+
{t.status === 'completed' ? <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7" /></svg> : null}
|
|
381
|
+
</span>
|
|
382
|
+
<span className="uac-todo-t">{t.text}</span>
|
|
383
|
+
</div>
|
|
384
|
+
))}
|
|
385
|
+
</div>
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ── prose ─────────────────────────────────────────────────────────────────────────────────────────
|
|
390
|
+
|
|
391
|
+
const REDUCED = typeof window !== 'undefined' && typeof window.matchMedia === 'function'
|
|
392
|
+
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Streamed prose. Deltas arrive in bursts; the text is let out at a steady pace (faster as the
|
|
396
|
+
* backlog grows) and its newest words fade in, so it reads as ink settling rather than as lumps.
|
|
397
|
+
* Text present when it mounts is history and paints at once.
|
|
398
|
+
*/
|
|
399
|
+
export function StreamingText(props) {
|
|
400
|
+
const { text, active, render } = props;
|
|
401
|
+
const on = !!active && !REDUCED;
|
|
402
|
+
const [n, setN] = useState(() => (text ? text.length : 0));
|
|
403
|
+
const textRef = useRef(text);
|
|
404
|
+
textRef.current = text;
|
|
405
|
+
const acc = useRef(text ? text.length : 0);
|
|
406
|
+
useEffect(() => {
|
|
407
|
+
if (!on) { const l = textRef.current ? textRef.current.length : 0; acc.current = l; setN(l); return undefined; }
|
|
408
|
+
let raf; let prev = null;
|
|
409
|
+
const tick = (t) => {
|
|
410
|
+
if (prev == null) prev = t;
|
|
411
|
+
const dt = Math.min(0.1, (t - prev) / 1000);
|
|
412
|
+
prev = t;
|
|
413
|
+
const len = textRef.current ? textRef.current.length : 0;
|
|
414
|
+
const gap = len - acc.current;
|
|
415
|
+
if (gap > 0) {
|
|
416
|
+
acc.current = Math.min(len, acc.current + Math.max(40, gap / 1.2) * dt);
|
|
417
|
+
setN(Math.floor(acc.current));
|
|
418
|
+
} else if (gap < 0) { acc.current = len; setN(len); }
|
|
419
|
+
raf = requestAnimationFrame(tick);
|
|
420
|
+
};
|
|
421
|
+
raf = requestAnimationFrame(tick);
|
|
422
|
+
return () => cancelAnimationFrame(raf);
|
|
423
|
+
}, [on]);
|
|
424
|
+
const shown = on ? String(text || '').slice(0, n) : String(text || '');
|
|
425
|
+
const rendering = on && n < String(text || '').length;
|
|
426
|
+
return <div className={cls('uac-md', on && 'is-streaming', rendering && 'is-catching-up')}>{render ? render(shown) : <div className="uac-plain">{shown}</div>}</div>;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ── the turn ──────────────────────────────────────────────────────────────────────────────────────
|
|
430
|
+
|
|
431
|
+
export function UserBubble(props) {
|
|
432
|
+
const { user, renderFile, extra } = props;
|
|
433
|
+
if (!user) return null;
|
|
434
|
+
const files = user.files || [];
|
|
435
|
+
return (
|
|
436
|
+
<div className="uac-user">
|
|
437
|
+
<div className="uac-user-b">
|
|
438
|
+
{extra}
|
|
439
|
+
{files.length ? (
|
|
440
|
+
<div className="uac-user-files">
|
|
441
|
+
{files.map((f, i) => {
|
|
442
|
+
if (renderFile) return <React.Fragment key={i}>{renderFile(f, i)}</React.Fragment>;
|
|
443
|
+
const img = f.src && (/^data:image\//.test(f.src) || /\.(png|jpe?g|gif|webp|svg)$/i.test(f.name || ''));
|
|
444
|
+
return img ? <img key={i} className="uac-user-img" src={f.src} alt={f.name} />
|
|
445
|
+
: <span key={i} className="uac-chip"><IcPaperclip size={12} /><span>{f.name}</span></span>;
|
|
446
|
+
})}
|
|
447
|
+
</div>
|
|
448
|
+
) : null}
|
|
449
|
+
{user.text ? <div className="uac-user-t">{user.text}</div> : null}
|
|
450
|
+
</div>
|
|
451
|
+
</div>
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** How the turn ended, from its own clocks and usage; nothing when neither is known. */
|
|
456
|
+
export function TurnOutcome(props) {
|
|
457
|
+
const { turn, labels = DEFAULT_AGENT_LABELS, describeIncomplete } = props;
|
|
458
|
+
if (!turn || turn.status === 'running') return null;
|
|
459
|
+
const ms = turn.startedAt != null && turn.endedAt != null ? turn.endedAt - turn.startedAt : turn.elapsedMs;
|
|
460
|
+
const time = ms != null && ms >= 0 ? formatElapsed(ms) : '';
|
|
461
|
+
const tok = turn.usage && (turn.usage.total_tokens ?? ((turn.usage.input_tokens || 0) + (turn.usage.output_tokens || 0)));
|
|
462
|
+
const tokens = tok ? labels.tokens(formatTokens(tok)) : '';
|
|
463
|
+
if (turn.status === 'done') {
|
|
464
|
+
if (!time && !tokens) return null;
|
|
465
|
+
return <div className="uac-outcome">{[time ? labels.workedFor(time) : labels.worked, tokens].filter(Boolean).join(' · ')}</div>;
|
|
466
|
+
}
|
|
467
|
+
if (turn.status === 'cancelled') {
|
|
468
|
+
return <div className="uac-outcome is-stopped">{time ? labels.stoppedAfter(time) : labels.stopped}</div>;
|
|
469
|
+
}
|
|
470
|
+
if (turn.status === 'incomplete') {
|
|
471
|
+
const why = describeIncomplete ? describeIncomplete(turn.incomplete || {}) : (turn.incomplete && turn.incomplete.detail) || '';
|
|
472
|
+
return (
|
|
473
|
+
<div className="uac-outcome is-incomplete">
|
|
474
|
+
<span>{labels.incomplete}{time ? ` · ${time}` : ''}</span>
|
|
475
|
+
{why ? <p className="uac-outcome-why">{why}</p> : null}
|
|
476
|
+
</div>
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
return (
|
|
480
|
+
<div className="uac-outcome is-failed" role="status">
|
|
481
|
+
<span>{time ? labels.failedAfter(time) : labels.failed}</span>
|
|
482
|
+
{turn.error ? <p className="uac-outcome-why">{turn.error}</p> : null}
|
|
483
|
+
</div>
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* One turn: the person's message, then what the agent did and said, in the order it happened, and
|
|
489
|
+
* how it ended. While it runs, the last line is always what is happening now.
|
|
490
|
+
*/
|
|
491
|
+
export function AgentTurnView(props) {
|
|
492
|
+
const {
|
|
493
|
+
turn, renderMarkdown, mark, motion, labels: labelsIn, showUser = true, renderUserFile, userExtra,
|
|
494
|
+
meta, renderFiles, actions, describeIncomplete, liveStart,
|
|
495
|
+
} = props;
|
|
496
|
+
const labels = useMemo(() => ({ ...DEFAULT_AGENT_LABELS, ...(labelsIn || {}) }), [labelsIn]);
|
|
497
|
+
if (!turn) return null;
|
|
498
|
+
const running = turn.status === 'running';
|
|
499
|
+
const segs = segments(turn);
|
|
500
|
+
const plan = latestPlan(turn, describeTool);
|
|
501
|
+
const now = liveState(turn);
|
|
502
|
+
const start = liveStart ?? turn.startedAt;
|
|
503
|
+
const lastSeg = segs[segs.length - 1];
|
|
504
|
+
const liveWork = running && lastSeg && lastSeg.type === 'work';
|
|
505
|
+
let liveLabel = labels.thinking;
|
|
506
|
+
if (now) {
|
|
507
|
+
if (now.phase === 'tool' && now.tool) liveLabel = toolLine(describeTool(now.tool.name, now.tool.args), 'running');
|
|
508
|
+
else if (now.phase === 'writing') liveLabel = labels.writing;
|
|
509
|
+
else if (now.phase === 'starting') liveLabel = labels.starting;
|
|
510
|
+
}
|
|
511
|
+
const lastTextIdx = (() => { for (let i = segs.length - 1; i >= 0; i--) if (segs[i].type === 'text') return i; return -1; })();
|
|
512
|
+
const files = renderFiles ? renderFiles(turn) : null;
|
|
513
|
+
return (
|
|
514
|
+
<article className={cls('uac-turn', `is-${turn.status}`)} data-status={turn.status}>
|
|
515
|
+
{showUser ? <UserBubble user={turn.user} renderFile={renderUserFile} extra={userExtra} /> : null}
|
|
516
|
+
<div className="uac-agent">
|
|
517
|
+
{meta ? <div className="uac-meta">{meta}</div> : null}
|
|
518
|
+
{segs.map((s, i) => {
|
|
519
|
+
const isLive = liveWork && i === segs.length - 1;
|
|
520
|
+
if (isLive) {
|
|
521
|
+
return (
|
|
522
|
+
<React.Fragment key={`w${i}`}>
|
|
523
|
+
{plan ? <TodoCard todos={plan} labels={labels} running /> : null}
|
|
524
|
+
<WorkGroup items={s.items} live liveLabel={liveLabel} start={start} mark={mark} motion={motion} labels={labels} />
|
|
525
|
+
</React.Fragment>
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
if (s.type === 'text') {
|
|
529
|
+
return <StreamingText key={s.item.id || `t${i}`} text={s.item.text} render={renderMarkdown}
|
|
530
|
+
active={running && i === lastTextIdx && i === segs.length - 1} />;
|
|
531
|
+
}
|
|
532
|
+
return <WorkGroup key={`w${i}-${s.items[0] && s.items[0].id}`} items={s.items} labels={labels} />;
|
|
533
|
+
})}
|
|
534
|
+
{!liveWork && plan ? <TodoCard todos={plan} labels={labels} running={running} /> : null}
|
|
535
|
+
{running && !liveWork ? <WorkingIndicator mark={mark} motion={motion} start={start} label={liveLabel} /> : null}
|
|
536
|
+
{files}
|
|
537
|
+
<TurnOutcome turn={turn} labels={labels} describeIncomplete={describeIncomplete} />
|
|
538
|
+
{!running && actions ? <div className="uac-actions">{actions}</div> : null}
|
|
539
|
+
</div>
|
|
540
|
+
</article>
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// ── the composer ──────────────────────────────────────────────────────────────────────────────────
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* The message box. While a task runs its button is Stop and Enter does not send (a second turn on a
|
|
548
|
+
* running task is refused anyway); the box stays typable so the next message can be drafted.
|
|
549
|
+
*/
|
|
550
|
+
export function AgentComposer(props) {
|
|
551
|
+
const {
|
|
552
|
+
value, onChange, onSend, onStop, running = false, stopping = false, disabled = false, sendDisabled,
|
|
553
|
+
placeholder, runningPlaceholder, attachments = [], onRemoveAttachment, onAttachFiles, accept, multiple = false,
|
|
554
|
+
left, right, footer, inputId, inputRef, autoFocus, maxRows = 10, labels: labelsIn, ariaLabel, className,
|
|
555
|
+
} = props;
|
|
556
|
+
const labels = { ...DEFAULT_AGENT_LABELS, ...(labelsIn || {}) };
|
|
557
|
+
const own = useRef(null);
|
|
558
|
+
const ta = inputRef || own;
|
|
559
|
+
const fileIn = useRef(null);
|
|
560
|
+
const root = useRef(null);
|
|
561
|
+
const [dropping, setDropping] = useState(false);
|
|
562
|
+
const grow = useCallback(() => {
|
|
563
|
+
const el = ta.current;
|
|
564
|
+
if (!el) return;
|
|
565
|
+
el.style.height = 'auto';
|
|
566
|
+
const cs = getComputedStyle(el);
|
|
567
|
+
const lh = parseFloat(cs.lineHeight) || 22;
|
|
568
|
+
const max = lh * maxRows + (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
|
|
569
|
+
el.style.height = `${Math.min(el.scrollHeight, max)}px`;
|
|
570
|
+
el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden';
|
|
571
|
+
}, [ta, maxRows]);
|
|
572
|
+
useLayoutEffect(grow, [value, grow]);
|
|
573
|
+
const blocked = sendDisabled ?? (!String(value || '').trim() && !attachments.length);
|
|
574
|
+
const send = () => { if (!running && !disabled && !blocked) onSend && onSend(); };
|
|
575
|
+
const files = (list) => { if (list && list.length && onAttachFiles) onAttachFiles(list); };
|
|
576
|
+
return (
|
|
577
|
+
<div ref={root} className={cls('uac-composer', running && 'is-running', dropping && 'is-dropping', disabled && 'is-disabled', className)}
|
|
578
|
+
onDragOver={onAttachFiles ? (e) => { if (Array.from(e.dataTransfer.types || []).includes('Files')) { e.preventDefault(); setDropping(true); } } : undefined}
|
|
579
|
+
onDragLeave={onAttachFiles ? (e) => { if (!root.current || !root.current.contains(e.relatedTarget)) setDropping(false); } : undefined}
|
|
580
|
+
onDrop={onAttachFiles ? (e) => { if (e.dataTransfer.files && e.dataTransfer.files.length) { e.preventDefault(); setDropping(false); files(e.dataTransfer.files); } } : undefined}>
|
|
581
|
+
{attachments.length ? (
|
|
582
|
+
<div className="uac-atts">
|
|
583
|
+
{attachments.map((f, i) => (
|
|
584
|
+
<span key={f.id || i} className={cls('uac-att', f.status && `is-${f.status}`)}>
|
|
585
|
+
{f.src && /^(data:image\/|blob:)/.test(f.src) ? <img src={f.src} alt="" /> : <IcPaperclip size={13} />}
|
|
586
|
+
<span className="uac-att-n">{f.name}</span>
|
|
587
|
+
{onRemoveAttachment ? (
|
|
588
|
+
<button type="button" aria-label={labels.remove(f.name)} onClick={() => onRemoveAttachment(i)}><IcX size={12} /></button>
|
|
589
|
+
) : null}
|
|
590
|
+
</span>
|
|
591
|
+
))}
|
|
592
|
+
</div>
|
|
593
|
+
) : null}
|
|
594
|
+
<textarea id={inputId} ref={ta} rows={1} value={value} autoFocus={autoFocus} disabled={disabled}
|
|
595
|
+
placeholder={running && runningPlaceholder ? runningPlaceholder : placeholder}
|
|
596
|
+
aria-label={ariaLabel || placeholder}
|
|
597
|
+
onChange={(e) => onChange && onChange(e.target.value)}
|
|
598
|
+
onPaste={onAttachFiles ? (e) => { const fl = e.clipboardData && e.clipboardData.files; if (fl && fl.length) { e.preventDefault(); files(fl); } } : undefined}
|
|
599
|
+
onKeyDown={(e) => {
|
|
600
|
+
if (e.key !== 'Enter' || e.shiftKey || (e.nativeEvent && e.nativeEvent.isComposing)) return;
|
|
601
|
+
e.preventDefault();
|
|
602
|
+
send();
|
|
603
|
+
}} />
|
|
604
|
+
<div className="uac-composer-row">
|
|
605
|
+
{onAttachFiles ? (
|
|
606
|
+
<>
|
|
607
|
+
<button type="button" className="uac-icon-btn" aria-label={labels.attach} title={labels.attach} disabled={disabled}
|
|
608
|
+
onClick={() => fileIn.current && fileIn.current.click()}>
|
|
609
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.1" strokeLinecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14" /></svg>
|
|
610
|
+
</button>
|
|
611
|
+
<input ref={fileIn} type="file" hidden accept={accept} multiple={multiple}
|
|
612
|
+
onChange={(e) => { files(e.target.files); e.target.value = ''; }} />
|
|
613
|
+
</>
|
|
614
|
+
) : null}
|
|
615
|
+
{left}
|
|
616
|
+
<span className="uac-composer-sp" />
|
|
617
|
+
{right}
|
|
618
|
+
{running ? (
|
|
619
|
+
<button type="button" className="uac-send is-stop" aria-label={stopping ? labels.stopping : labels.stop} title={labels.stop}
|
|
620
|
+
disabled={stopping || !onStop} onClick={() => onStop && onStop()}>
|
|
621
|
+
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2.5" /></svg>
|
|
622
|
+
</button>
|
|
623
|
+
) : (
|
|
624
|
+
<button type="button" className="uac-send" aria-label={labels.send} title={labels.send} disabled={disabled || blocked} onClick={send}>
|
|
625
|
+
<IcSend />
|
|
626
|
+
</button>
|
|
627
|
+
)}
|
|
628
|
+
</div>
|
|
629
|
+
{footer ? <div className="uac-composer-foot">{footer}</div> : null}
|
|
630
|
+
</div>
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// ── the column ────────────────────────────────────────────────────────────────────────────────────
|
|
635
|
+
|
|
636
|
+
function nearestScroller(el) {
|
|
637
|
+
let n = el && el.parentElement;
|
|
638
|
+
while (n && n !== document.body && n !== document.documentElement) {
|
|
639
|
+
const s = getComputedStyle(n);
|
|
640
|
+
if (/(auto|scroll|overlay)/.test(s.overflowY)) return n;
|
|
641
|
+
n = n.parentElement;
|
|
642
|
+
}
|
|
643
|
+
return null; // the window
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Follow the bottom of a growing conversation while the reader is at it; stop following the moment
|
|
648
|
+
* they scroll up, and say so (`atBottom` false) so a "jump to latest" button can appear.
|
|
649
|
+
* `scroller`: an element, or null to find the nearest scrolling ancestor of `contentRef` (or the
|
|
650
|
+
* window). `anchorRef`: the element whose bottom edge is "the bottom" (default: the content), so a
|
|
651
|
+
* conversation with more page below it (a side panel stacked under it on a phone) is followed to
|
|
652
|
+
* its own end, not the page's. `followKey`: change it (a new turn sent) to snap back to the bottom.
|
|
653
|
+
*/
|
|
654
|
+
export function useStickToBottom(contentRef, opts = {}) {
|
|
655
|
+
const { scroller = null, anchorRef = null, followKey, threshold = 80, enabled = true } = opts;
|
|
656
|
+
const stick = useRef(true);
|
|
657
|
+
const [atBottom, setAtBottom] = useState(true);
|
|
658
|
+
const target = useRef(null);
|
|
659
|
+
const resolve = useCallback(() => {
|
|
660
|
+
target.current = scroller || (contentRef.current ? nearestScroller(contentRef.current) : null);
|
|
661
|
+
return target.current;
|
|
662
|
+
}, [scroller, contentRef]);
|
|
663
|
+
// how far the anchor's bottom edge is below the bottom of what can be seen (<= 0: in view)
|
|
664
|
+
const distance = () => {
|
|
665
|
+
const a = (anchorRef && anchorRef.current) || contentRef.current;
|
|
666
|
+
if (!a) return 0;
|
|
667
|
+
const t = target.current;
|
|
668
|
+
const viewBottom = t ? t.getBoundingClientRect().top + t.clientHeight : window.innerHeight;
|
|
669
|
+
return a.getBoundingClientRect().bottom - viewBottom;
|
|
670
|
+
};
|
|
671
|
+
const toBottom = useCallback((smooth = false) => {
|
|
672
|
+
const d = distance();
|
|
673
|
+
if (Math.abs(d) < 1) return;
|
|
674
|
+
const behavior = smooth && !REDUCED ? 'smooth' : 'auto';
|
|
675
|
+
const t = target.current;
|
|
676
|
+
if (t) t.scrollBy({ top: d, behavior });
|
|
677
|
+
else window.scrollBy({ top: d, behavior });
|
|
678
|
+
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
|
679
|
+
useEffect(() => {
|
|
680
|
+
if (!enabled) return undefined;
|
|
681
|
+
const t = resolve();
|
|
682
|
+
const on = () => {
|
|
683
|
+
const at = distance() < threshold;
|
|
684
|
+
stick.current = at;
|
|
685
|
+
setAtBottom(at);
|
|
686
|
+
};
|
|
687
|
+
const el = t || window;
|
|
688
|
+
el.addEventListener('scroll', on, { passive: true });
|
|
689
|
+
on();
|
|
690
|
+
return () => el.removeEventListener('scroll', on);
|
|
691
|
+
}, [enabled, resolve, threshold]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
692
|
+
useEffect(() => {
|
|
693
|
+
const el = contentRef.current;
|
|
694
|
+
if (!enabled || !el || typeof ResizeObserver === 'undefined') return undefined;
|
|
695
|
+
// A reader opening a call grows the content too; that is them reading, not the agent writing,
|
|
696
|
+
// so growth right after their own click or key press never moves the view.
|
|
697
|
+
let quietUntil = 0;
|
|
698
|
+
const touched = () => { quietUntil = Date.now() + 600; };
|
|
699
|
+
el.addEventListener('pointerdown', touched, true);
|
|
700
|
+
el.addEventListener('keydown', touched, true);
|
|
701
|
+
const ro = new ResizeObserver(() => {
|
|
702
|
+
if (!target.current && scroller == null) resolve();
|
|
703
|
+
if (Date.now() < quietUntil) {
|
|
704
|
+
stick.current = distance() < threshold;
|
|
705
|
+
setAtBottom(stick.current);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (stick.current) toBottom(false);
|
|
709
|
+
});
|
|
710
|
+
ro.observe(el);
|
|
711
|
+
return () => { ro.disconnect(); el.removeEventListener('pointerdown', touched, true); el.removeEventListener('keydown', touched, true); };
|
|
712
|
+
}, [enabled, contentRef, toBottom, resolve, scroller, threshold]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
713
|
+
useEffect(() => {
|
|
714
|
+
if (!enabled || followKey === undefined) return;
|
|
715
|
+
resolve();
|
|
716
|
+
stick.current = true;
|
|
717
|
+
setAtBottom(true);
|
|
718
|
+
toBottom(false);
|
|
719
|
+
}, [followKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
720
|
+
return { atBottom, toBottom: () => { stick.current = true; setAtBottom(true); toBottom(true); } };
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* The conversation column: turns that scroll, and a dock that does not (the composer, a notice).
|
|
725
|
+
* mode 'pane' fills a box of fixed height and scrolls inside it; mode 'page' lives in a scrolling
|
|
726
|
+
* page, fills the window below its top edge and pins its dock to the bottom of the window.
|
|
727
|
+
*/
|
|
728
|
+
export function AgentConversation(props) {
|
|
729
|
+
const { children, composer, notice, running = false, mark, motion, mode = 'pane', followKey, labels: labelsIn, className, empty } = props;
|
|
730
|
+
const labels = { ...DEFAULT_AGENT_LABELS, ...(labelsIn || {}) };
|
|
731
|
+
const rootRef = useRef(null);
|
|
732
|
+
const scrollRef = useRef(null);
|
|
733
|
+
const contentRef = useRef(null);
|
|
734
|
+
const [scroller, setScroller] = useState(null);
|
|
735
|
+
useLayoutEffect(() => { if (mode === 'pane') setScroller(scrollRef.current); }, [mode]);
|
|
736
|
+
const { atBottom, toBottom } = useStickToBottom(contentRef, { scroller: mode === 'pane' ? scroller : null, followKey,
|
|
737
|
+
anchorRef: mode === 'page' ? rootRef : null, enabled: mode === 'page' || !!scroller });
|
|
738
|
+
// page mode: the column reaches the bottom of what its scroller shows (the window, or the
|
|
739
|
+
// scrolling box it sits in), so a short conversation still has its dock at the foot of the screen
|
|
740
|
+
// rather than under its last message
|
|
741
|
+
useLayoutEffect(() => {
|
|
742
|
+
if (mode !== 'page' || !rootRef.current) return undefined;
|
|
743
|
+
const set = () => {
|
|
744
|
+
const r = rootRef.current;
|
|
745
|
+
if (!r) return;
|
|
746
|
+
const sc = nearestScroller(r);
|
|
747
|
+
const rect = r.getBoundingClientRect();
|
|
748
|
+
const avail = sc
|
|
749
|
+
? sc.clientHeight - (rect.top - sc.getBoundingClientRect().top + sc.scrollTop)
|
|
750
|
+
: window.innerHeight - (rect.top + window.scrollY);
|
|
751
|
+
r.style.setProperty('--uac-fill', `${Math.max(240, Math.round(avail))}px`);
|
|
752
|
+
};
|
|
753
|
+
set();
|
|
754
|
+
window.addEventListener('resize', set);
|
|
755
|
+
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(set) : null;
|
|
756
|
+
if (ro && rootRef.current.parentElement) ro.observe(rootRef.current.parentElement);
|
|
757
|
+
return () => { window.removeEventListener('resize', set); if (ro) ro.disconnect(); };
|
|
758
|
+
}, [mode]);
|
|
759
|
+
return (
|
|
760
|
+
<div ref={rootRef} className={cls('uac-convo', `is-${mode}`, className)}>
|
|
761
|
+
<div ref={scrollRef} className="uac-scroll">
|
|
762
|
+
<div ref={contentRef} className="uac-thread">{children || empty}</div>
|
|
763
|
+
</div>
|
|
764
|
+
<div className="uac-dock">
|
|
765
|
+
{!atBottom ? (
|
|
766
|
+
<button type="button" className="uac-jump" aria-label={labels.jump} title={labels.jump} onClick={toBottom}>
|
|
767
|
+
{running ? <WorkingMark mark={mark} motion={motion} size={16} /> : (
|
|
768
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M12 5v14M5 12l7 7 7-7" /></svg>
|
|
769
|
+
)}
|
|
770
|
+
</button>
|
|
771
|
+
) : null}
|
|
772
|
+
{notice ? <div className="uac-notice">{notice}</div> : null}
|
|
773
|
+
{composer}
|
|
774
|
+
</div>
|
|
775
|
+
</div>
|
|
776
|
+
);
|
|
777
|
+
}
|