@theoremjs/react 0.3.5-next.975.g3529c32 → 0.3.5-next.978.g2ef222f

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.
@@ -14,16 +14,19 @@ import { VStack } from '@astryxdesign/core/VStack';
14
14
  import { IconAdjustmentsHorizontal, IconArchive, IconArrowBigRightLines, IconArrowDown, IconArrowUp, IconBrain, IconCornerDownLeft, IconInputAi, IconListNumbers, IconMicrophone, IconPaperclip, IconPencil, IconPlayerRecordFilled, IconSend, IconStack2, IconSteeringWheel, IconX, } from '@tabler/icons-react';
15
15
  import { attachmentIssueText, labelText } from '@theoremjs/agents';
16
16
  import { composerPendingMoves, composerPendingPreview, effortSelectEnabled, interfaceEffortOptions, interfaceModelOptions, modelSelectEnabled, } from '@theoremjs/agents/interface';
17
- import { composerActionState, composerDrawerSummary, isStashShortcut, resolveComposerHint, STASH_SHORTCUT, } from '@theoremjs/web/client';
17
+ import { COMPOSER_SHORTCUTS, composerActionState, composerDrawerSummary, composerShortcut, resolveComposerHint, } from '@theoremjs/web/client';
18
18
  import { useCallback, useEffect, useMemo, useRef, useState, } from 'react';
19
19
  import { stageComposerFiles } from "../client/composer-attachments.js";
20
20
  import { useComposerVoice } from "../components/use-composer-voice.js";
21
21
  import { useEditorSelection } from "../components/use-editor-selection.js";
22
+ import { ChatComposerRow } from "./ChatComposerRow.js";
22
23
  import { ComposerControls, ComposerSelector } from "./ComposerControls.js";
23
24
  import { composerDrawerLabel } from "./labels.js";
24
25
  import { TheoremLabelsProvider, useLabels } from "./labels-provider.js";
25
26
  import { VoiceNote } from "./VoiceNote.js";
26
27
  const NO_FOCUS_RING = { '--focus-outline-width': '0px' };
28
+ /** why: A hint stays one line; the pill row scrolls its pills instead. */
29
+ const NO_WRAP = { whiteSpace: 'nowrap', flexShrink: 0 };
27
30
  /** An option the profile declares: its allowed values, the one chosen, and how to choose another. */
28
31
  /** The effort selector's icon. The studio's Agents list shows the same one. */
29
32
  export const EFFORT_ICON = IconBrain;
@@ -138,16 +141,15 @@ function composerStatus(args) {
138
141
  return warning ? { type: 'warning', message: warning } : undefined;
139
142
  }
140
143
  /** Pending messages, then two uniform rows: 64px tiles (images, voice notes), then file tokens. */
141
- function PendingDrawer(props) {
142
- const t = useLabels();
143
- return (_jsx(ChatComposerDrawer, { count: props.summary.count, label: composerDrawerLabel(t, props.summary), children: _jsxs(VStack, { gap: 2, width: "100%", children: [props.messages.map((message) => (_jsx(PendingRow, { message: message, moves: composerPendingMoves(props.messages, message.id), ...props.pendingActions }, message.id))), props.imageFiles.length + props.voiceFiles.length > 0 ? (_jsxs(HStack, { gap: 2, wrap: "wrap", vAlign: "center", children: [props.imageFiles.map(({ file, index, preview }) => (_jsx(Thumbnail, { src: preview, alt: file.name, label: file.name, onRemove: () => props.onAttachmentRemove(index) }, `${file.name}:${String(index)}`))), props.voiceFiles.map((file, index) => {
144
- const src = props.voiceUrls[index];
145
- // why: An empty src makes the browser fetch the page again; a note draws once it has its URL.
146
- return src === undefined ? null : (_jsx(VoiceNote, { src: src, mimeType: file.type || undefined, onRemove: props.onVoiceRemove }, `voice:${file.name}`));
147
- })] })) : null, props.otherFiles.length > 0 ? (_jsx(HStack, { gap: 2, wrap: "wrap", children: props.otherFiles.map(({ file, index }) => (_jsx(Token, { label: file.name, onRemove: () => props.onAttachmentRemove(index) }, `${file.name}:${String(index)}`))) })) : null] }) }));
144
+ function PendingDrawerContent(props) {
145
+ return (_jsxs(VStack, { gap: 2, width: "100%", children: [props.messages.map((message) => (_jsx(PendingRow, { message: message, moves: composerPendingMoves(props.messages, message.id), ...props.pendingActions }, message.id))), props.imageFiles.length + props.voiceFiles.length > 0 ? (_jsxs(HStack, { gap: 2, wrap: "wrap", vAlign: "center", children: [props.imageFiles.map(({ file, index, preview }) => (_jsx(Thumbnail, { src: preview, alt: file.name, label: file.name, onRemove: () => props.onAttachmentRemove(index) }, `${file.name}:${String(index)}`))), props.voiceFiles.map((file, index) => {
146
+ const src = props.voiceUrls[index];
147
+ // why: An empty src makes the browser fetch the page again; a note draws once it has its URL.
148
+ return src === undefined ? null : (_jsx(VoiceNote, { src: src, mimeType: file.type || undefined, onRemove: props.onVoiceRemove }, `voice:${file.name}`));
149
+ })] })) : null, props.otherFiles.length > 0 ? (_jsx(HStack, { gap: 2, wrap: "wrap", children: props.otherFiles.map(({ file, index }) => (_jsx(Token, { label: file.name, onRemove: () => props.onAttachmentRemove(index) }, `${file.name}:${String(index)}`))) })) : null] }));
148
150
  }
149
151
  /** A hidden file input behind the paperclip button. */
150
- function AttachFilesButton({ accept, onFiles, }) {
152
+ function AttachFilesButton({ accept, size, onFiles, }) {
151
153
  const t = useLabels();
152
154
  const label = t('@theorem.composer.attach');
153
155
  const fileInputRef = useRef(null);
@@ -158,25 +160,38 @@ function AttachFilesButton({ accept, onFiles, }) {
158
160
  if (incoming.length > 0)
159
161
  onFiles(incoming);
160
162
  }
161
- return (_jsxs(_Fragment, { children: [_jsx("input", { ref: fileInputRef, type: "file", multiple: true, hidden: true, accept: accept, onChange: handleChange }), _jsx(IconButton, { label: label, tooltip: label, size: "sm", variant: "ghost", icon: _jsx(IconPaperclip, { size: 16 }), onClick: () => fileInputRef.current?.click() })] }));
163
+ return (_jsxs(_Fragment, { children: [_jsx("input", { ref: fileInputRef, type: "file", multiple: true, hidden: true, accept: accept, onChange: handleChange }), _jsx(IconButton, { label: label, tooltip: label, size: size, variant: "ghost", icon: _jsx(IconPaperclip, { size: 16 }), onClick: () => fileInputRef.current?.click() })] }));
164
+ }
165
+ /** What a send-menu item says it does; while a step waits, queue and send now are about the step. */
166
+ function menuDescriptionKey(action, phase) {
167
+ if (phase === 'gated' && (action === 'queue' || action === 'send_now'))
168
+ return `@theorem.composer.menu.${action}.gated.description`;
169
+ return `@theorem.composer.menu.${action}.description`;
162
170
  }
163
- function SendMenu({ actions, onAction, }) {
171
+ function SendMenu({ actions, phase, onAction, trigger = 'more', }) {
164
172
  const t = useLabels();
165
173
  if (actions.length === 0)
166
174
  return null;
167
- return (_jsx(DropdownMenu, { button: {
168
- label: t('@theorem.composer.send_options'),
169
- isIconOnly: true,
170
- icon: _jsx(IconStack2, { size: 16 }),
171
- variant: 'ghost',
172
- }, hasChevron: false, placement: "above", items: actions.map((action) => {
175
+ return (_jsx(DropdownMenu, { button: trigger === 'send'
176
+ ? {
177
+ label: t('@theorem.composer.send_menu'),
178
+ isIconOnly: true,
179
+ icon: _jsx(IconListNumbers, { size: 16 }),
180
+ variant: 'primary',
181
+ }
182
+ : {
183
+ label: t('@theorem.composer.send_options'),
184
+ isIconOnly: true,
185
+ icon: _jsx(IconStack2, { size: 16 }),
186
+ variant: 'ghost',
187
+ }, hasChevron: false, placement: "above", alignment: "end", items: actions.map((action) => {
173
188
  const Glyph = SEND_ICON[action];
174
189
  return {
175
190
  id: action,
176
191
  label: t(`@theorem.composer.menu.${action}`),
177
- description: t(`@theorem.composer.menu.${action}.description`),
192
+ description: t(menuDescriptionKey(action, phase)),
178
193
  icon: _jsx(Glyph, { size: 16 }),
179
- ...(action === 'stash' ? { endContent: _jsx(Kbd, { keys: STASH_SHORTCUT }) } : {}),
194
+ endContent: _jsx(ShortcutKeys, { keys: COMPOSER_SHORTCUTS[action] }),
180
195
  onClick: () => onAction(action),
181
196
  };
182
197
  }) }));
@@ -186,10 +201,23 @@ function RecordButton({ recording, onToggle }) {
186
201
  const label = t(recording ? '@theorem.composer.stop_recording' : '@theorem.composer.record');
187
202
  return (_jsx(IconButton, { label: label, tooltip: label, size: "md", variant: recording ? 'destructive' : 'ghost', icon: recording ? _jsx(IconPlayerRecordFilled, { size: 16 }) : _jsx(IconMicrophone, { size: 16 }), onClick: onToggle }));
188
203
  }
204
+ /**
205
+ * A shortcut, worded and named as Astryx's Kbd does it, drawn with the ghost look: no key fill
206
+ * and no key edge, in secondary text.
207
+ * why: Kbd paints its keys from these tokens, so setting them here restyles only these keys.
208
+ */
209
+ const GHOST_KEYS = {
210
+ '--color-neutral': 'transparent',
211
+ '--color-border-emphasized': 'transparent',
212
+ '--color-text-primary': 'var(--color-text-secondary)',
213
+ };
214
+ function ShortcutKeys({ keys }) {
215
+ return _jsx(Kbd, { keys: keys, className: "theorem-composer-shortcut", style: GHOST_KEYS });
216
+ }
189
217
  /** Astryx's slot for contextual info (header, right side). */
190
218
  function ComposerHint({ hint, onAction }) {
191
219
  const t = useLabels();
192
- return (_jsxs(HStack, { gap: 2, vAlign: "center", children: [_jsx(Text, { size: "sm", color: "secondary", children: t(`@theorem.composer.hint.${hint.id}.message`) }), _jsx(Button, { label: t(`@theorem.composer.hint.${hint.id}.action`), size: "sm", variant: "ghost", onClick: onAction }), _jsx(Kbd, { keys: hint.shortcut })] }));
220
+ return (_jsxs(HStack, { gap: 2, vAlign: "center", style: NO_WRAP, children: [_jsx(Text, { size: "sm", color: "secondary", children: t(`@theorem.composer.hint.${hint.id}.message`) }), _jsx(Button, { label: t(`@theorem.composer.hint.${hint.id}.action`), size: "sm", variant: "ghost", onClick: onAction }), _jsx(ShortcutKeys, { keys: hint.shortcut })] }));
193
221
  }
194
222
  /** Staged files split into image tiles and file tokens, with object URLs for previews and voice notes. */
195
223
  function useStagedFiles(pendingFiles, pendingVoice) {
@@ -229,29 +257,41 @@ function ComposerRecordButton({ hasVoice, voice, }) {
229
257
  return null;
230
258
  return _jsx(RecordButton, { recording: voice.recording, onToggle: () => void voice.toggleRecording() });
231
259
  }
232
- /** The drawer of messages and files waiting to send; absent while nothing waits. */
233
- function composerDrawer(props, stagedFiles, onVoiceRemove) {
260
+ /** The tray of messages and files waiting to send; absent while nothing waits. */
261
+ function composerTray(t, props, stagedFiles, onVoiceRemove) {
234
262
  const summary = composerDrawerSummary({
235
263
  pendingMessages: props.pendingMessages,
236
264
  attachmentCount: props.pendingFiles.length + props.pendingVoice.length,
237
265
  });
238
266
  if (!summary)
239
267
  return undefined;
240
- return (_jsx(PendingDrawer, { summary: summary, messages: props.pendingMessages, ...stagedFiles, voiceFiles: props.pendingVoice, pendingActions: {
268
+ const content = (_jsx(PendingDrawerContent, { messages: props.pendingMessages, ...stagedFiles, voiceFiles: props.pendingVoice, pendingActions: {
241
269
  onMove: props.onPendingMove,
242
270
  onRemove: props.onPendingRemove,
243
271
  onQueue: props.onPendingQueue,
244
272
  onRestore: props.onPendingRestore,
245
273
  onSendNow: props.onPendingSendNow,
246
274
  }, onAttachmentRemove: props.onAttachmentRemove, onVoiceRemove: onVoiceRemove }));
275
+ return { count: summary.count, label: composerDrawerLabel(t, summary), content };
247
276
  }
248
- /** The text field, with Seance's stash shortcut while it has focus; `onStash` is absent when there is nothing to stash. */
249
- function ComposerTextInput({ editorRef, handleRef, onStash, }) {
250
- return (_jsx(ChatComposerInput, { ref: editorRef, handleRef: handleRef, onKeyDown: (event) => {
251
- if (!isStashShortcut(event))
277
+ /**
278
+ * The text field, with the send menu's shortcuts while it has focus: each acts only when the
279
+ * menu offers it. `field` wires it up when it stands outside Astryx's composer (the row layout).
280
+ */
281
+ function ComposerTextInput({ editorRef, handleRef, menuActions, onMenuAction, field, }) {
282
+ return (_jsx(ChatComposerInput, { ref: editorRef, handleRef: handleRef, ...(field
283
+ ? {
284
+ value: field.value,
285
+ onChange: field.onChange,
286
+ onSubmit: field.onSubmit,
287
+ placeholder: field.placeholder,
288
+ }
289
+ : {}), onKeyDown: (event) => {
290
+ const action = composerShortcut(event);
291
+ if (!action || !menuActions.includes(action))
252
292
  return;
253
293
  event.preventDefault();
254
- onStash?.();
294
+ onMenuAction(action);
255
295
  } }));
256
296
  }
257
297
  function isLiveComposer(props) {
@@ -290,8 +330,20 @@ function LiveComposerBarBody(props) {
290
330
  }), input: _jsx(ChatComposerInput, { handleRef: setEditor }), sendButton: _jsx(ChatSendButton, { isDisabled: props.isDisabled, onSend: submitTyped }) }));
291
331
  }
292
332
  function ChatComposerBarBody(props) {
293
- const { iface, phase } = props;
333
+ const parts = useComposerParts(props);
334
+ return props.layout === 'row' ? (_jsx(RowComposerBar, { props: props, parts: parts })) : (_jsx(StackedComposerBar, { props: props, parts: parts }));
335
+ }
336
+ /** What the field shows: listening while it records, else the builder's text or the default. */
337
+ function useComposerPlaceholder(props, recording) {
338
+ const t = useLabels();
339
+ if (recording)
340
+ return t('@theorem.composer.listening');
341
+ return (props.placeholder ?? t('@theorem.composer.placeholder', { handle: props.iface.identity.handle }));
342
+ }
343
+ /** Everything both layouts draw, worked out once so the two cannot drift. */
344
+ function useComposerParts(props) {
294
345
  const t = useLabels();
346
+ const { iface, phase } = props;
295
347
  const inputs = iface.inputs;
296
348
  const pendingFiles = useMemo(() => [...props.pendingFiles], [props.pendingFiles]);
297
349
  const voice = useComposerVoice({
@@ -303,7 +355,7 @@ function ChatComposerBarBody(props) {
303
355
  });
304
356
  const stagedFiles = useStagedFiles(props.pendingFiles, props.pendingVoice);
305
357
  useEffect(() => () => voice.disposeRecorder(), [voice.disposeRecorder]);
306
- const { primary, menuActions, primaryDisabled } = composerActionState({
358
+ const actions = composerActionState({
307
359
  iface,
308
360
  phase,
309
361
  draftText: props.draftText,
@@ -311,39 +363,68 @@ function ChatComposerBarBody(props) {
311
363
  pendingVoice: props.pendingVoice,
312
364
  recording: voice.recording,
313
365
  });
314
- const canStash = menuActions.includes('stash');
315
366
  const editorRef = useRef(null);
316
367
  const hint = resolveComposerHint({
317
368
  draftText: props.draftText,
318
369
  selectedText: useEditorSelection(editorRef),
319
- canStash,
370
+ canStash: actions.menuActions.includes('stash'),
320
371
  });
321
- function runPrimary() {
322
- if (primaryDisabled)
372
+ const runPrimary = () => {
373
+ if (actions.primaryDisabled)
323
374
  return;
324
- if (primary === 'stop')
375
+ if (actions.primary === 'stop')
325
376
  props.onStop();
326
377
  else
327
378
  props.onSubmit();
328
- }
379
+ };
329
380
  const { stageFiles, stagingIssues } = useFileStaging(pendingFiles, inputs.maxFiles, props);
381
+ const placeholder = useComposerPlaceholder(props, voice.recording);
382
+ return {
383
+ ...actions,
384
+ runPrimary,
385
+ editorRef,
386
+ placeholder,
387
+ // why: A profile that takes no text has no text field (false, not null: null gets Astryx's default one).
388
+ input: inputs.text && (_jsx(ComposerTextInput, { editorRef: editorRef, handleRef: props.inputRef, menuActions: actions.menuActions, onMenuAction: props.onMenuAction,
389
+ // why: The row draws its own surface, outside Astryx's ChatComposer, so the field takes its value here.
390
+ field: props.layout === 'row'
391
+ ? {
392
+ value: props.draftText,
393
+ onChange: props.onDraftTextChange,
394
+ onSubmit: runPrimary,
395
+ placeholder,
396
+ }
397
+ : undefined })),
398
+ tray: composerTray(t, props, stagedFiles, () => voice.discardRecordingOrVoice()),
399
+ attach: inputs.attachments ? (_jsx(AttachFilesButton, { accept: inputs.attachments.acceptAttr, size: props.layout === 'row' ? 'md' : 'sm', onFiles: stageFiles })) : undefined,
400
+ hintNode: hint ? (_jsx(ComposerHint, { hint: hint, onAction: () => props.onMenuAction('stash') })) : undefined,
401
+ controls: (_jsx(GenerationSelect, { iface: iface, optionChoices: props.optionChoices, selectedModel: props.selectedModel, selectedEffort: props.selectedEffort, isDisabled: phase === 'streaming', onChange: props.onGenerationChange, control: props.generationSelect })),
402
+ record: _jsx(ComposerRecordButton, { hasVoice: Boolean(inputs.voice), voice: voice }),
403
+ status: composerStatus({
404
+ failure: props.failure,
405
+ issues: [...props.issues, ...stagingIssues],
406
+ voiceFailure: voice.failure,
407
+ labels: iface.labels,
408
+ }),
409
+ };
410
+ }
411
+ /** The one-row layout. */
412
+ function RowComposerBar({ props, parts, }) {
413
+ // why: Stop lives on the working pill, so the button only sends; while a reply runs or a
414
+ // step waits, a draft opens the send menu instead (Enter still queues).
415
+ const opensMenu = props.phase !== 'idle' && parts.menuActions.length > 0;
416
+ return (_jsx(ChatComposerRow, { isWorking: props.phase === 'streaming', workingSince: props.workingSince, icons: props.icons, backgroundJobs: props.backgroundJobs ?? [], onStop: props.onStop, hint: parts.hintNode, tray: parts.tray, attach: parts.attach, input: parts.input, editorRef: parts.editorRef, draftText: props.draftText, controls: parts.controls, record: parts.record, action: opensMenu ? (_jsx(SendMenu, { actions: parts.menuActions, phase: props.phase, onAction: props.onMenuAction, trigger: "send" })) : (_jsx(ChatSendButton, { isDisabled: parts.primaryDisabled || parts.primary === 'stop', onSend: parts.runPrimary })), status: parts.status }));
417
+ }
418
+ /** Today's layout: Astryx's ChatComposer. */
419
+ function StackedComposerBar({ props, parts, }) {
420
+ const isStopShown = parts.primary === 'stop';
330
421
  return (_jsx(ChatComposer
331
422
  // why: No keyboard focus ring on the composer (product choice): zero Astryx's
332
423
  // focus-outline token for this subtree. The editor still shows its caret.
333
424
  , {
334
425
  // why: No keyboard focus ring on the composer (product choice): zero Astryx's
335
426
  // focus-outline token for this subtree. The editor still shows its caret.
336
- style: NO_FOCUS_RING, value: props.draftText, onChange: props.onDraftTextChange, onSubmit: runPrimary, onStop: props.onStop, isStopShown: primary === 'stop', placeholder: voice.recording
337
- ? t('@theorem.composer.listening')
338
- : (props.placeholder ??
339
- t('@theorem.composer.placeholder', { handle: iface.identity.handle })),
340
- // why: A profile that takes no text has no text field (false, not null: null gets Astryx's default one).
341
- input: inputs.text && (_jsx(ComposerTextInput, { editorRef: editorRef, handleRef: props.inputRef, onStash: canStash ? () => props.onMenuAction('stash') : undefined })), drawer: composerDrawer(props, stagedFiles, () => voice.discardRecordingOrVoice()), headerActions: inputs.attachments ? (_jsx(AttachFilesButton, { accept: inputs.attachments.acceptAttr, onFiles: stageFiles })) : undefined, headerContext: hint ? _jsx(ComposerHint, { hint: hint, onAction: () => props.onMenuAction('stash') }) : undefined, footerActions: _jsx(GenerationSelect, { iface: iface, optionChoices: props.optionChoices, selectedModel: props.selectedModel, selectedEffort: props.selectedEffort, isDisabled: phase === 'streaming', onChange: props.onGenerationChange, control: props.generationSelect }),
427
+ style: NO_FOCUS_RING, value: props.draftText, onChange: props.onDraftTextChange, onSubmit: parts.runPrimary, onStop: props.onStop, isStopShown: isStopShown, placeholder: parts.placeholder, input: parts.input, drawer: parts.tray && (_jsx(ChatComposerDrawer, { count: parts.tray.count, label: parts.tray.label, children: parts.tray.content })), headerActions: parts.attach, headerContext: parts.hintNode, footerActions: parts.controls,
342
428
  // why: Astryx: sendActions render to the left of the send button, at size="md".
343
- sendActions: _jsxs(_Fragment, { children: [_jsx(SendMenu, { actions: menuActions, onAction: props.onMenuAction }), _jsx(ComposerRecordButton, { hasVoice: Boolean(inputs.voice), voice: voice })] }), sendButton: _jsx(ChatSendButton, { isStopShown: primary === 'stop', isDisabled: primaryDisabled, onSend: runPrimary, onStop: props.onStop }), status: composerStatus({
344
- failure: props.failure,
345
- issues: [...props.issues, ...stagingIssues],
346
- voiceFailure: voice.failure,
347
- labels: iface.labels,
348
- }) }));
429
+ sendActions: _jsxs(_Fragment, { children: [_jsx(SendMenu, { actions: parts.menuActions, phase: props.phase, onAction: props.onMenuAction }), parts.record] }), sendButton: _jsx(ChatSendButton, { isStopShown: isStopShown, isDisabled: parts.primaryDisabled, onSend: parts.runPrimary, onStop: props.onStop }), status: parts.status }));
349
430
  }
@@ -0,0 +1,54 @@
1
+ import type { ChatComposerStatus } from '@astryxdesign/core/Chat';
2
+ import { type ReactNode, type RefObject } from 'react';
3
+ import type { BackgroundJob } from '../client/transcript-groups.ts';
4
+ /**
5
+ * The glyphs the row composer draws. Each one left out keeps Theorem's.
6
+ * Text is in the labels (`@theorem.composer.pill.*`, `@theorem.composer.tray.*`); sizes, colours,
7
+ * radii and spacing are the `--theorem-composer-*` CSS properties.
8
+ */
9
+ export type ComposerRowIcons = {
10
+ /** Before the working pill's text. Default: Astryx's Spinner. */
11
+ working?: ReactNode;
12
+ /** Before each background job's name. Default: Astryx's Spinner. */
13
+ backgroundJob?: ReactNode;
14
+ /** In the working pill's stop button. Default: a filled square. */
15
+ stop?: ReactNode;
16
+ };
17
+ /** What waits to send: the count and label for the tray's header, and the content it folds. */
18
+ export type ComposerTray = {
19
+ count: number;
20
+ label: string;
21
+ content: ReactNode;
22
+ };
23
+ /** What the row composer draws; the bar works each piece out, so both layouts share it. */
24
+ export type ComposerRowParts = {
25
+ /** The pill row: the working pill while a reply runs, then the background jobs. */
26
+ isWorking: boolean;
27
+ /** When the reply in progress started; the working pill counts from it. */
28
+ workingSince?: number;
29
+ icons?: ComposerRowIcons;
30
+ backgroundJobs: readonly BackgroundJob[];
31
+ onStop: () => void;
32
+ /** Contextual hint, at the end of the pill row. */
33
+ hint?: ReactNode;
34
+ /** What waits to send, in the tray above the surface. */
35
+ tray?: ComposerTray;
36
+ attach?: ReactNode;
37
+ /** The text field; `false` when the profile takes no text. */
38
+ input: ReactNode;
39
+ /** The field's root, measured to know when the text wraps. */
40
+ editorRef: RefObject<HTMLDivElement | null>;
41
+ /** The draft; when it empties the row comes back from the stacked layout. */
42
+ draftText: string;
43
+ controls?: ReactNode;
44
+ record?: ReactNode;
45
+ /** The send button, or the send menu while a reply runs. */
46
+ action: ReactNode;
47
+ status?: ChatComposerStatus;
48
+ };
49
+ /**
50
+ * Theorem's one-row composer: the field, then the controls, the mic, and send, on one line.
51
+ * Text that wraps moves the field onto its own line above them, the stacked layout. Above
52
+ * it, the pill row: the reply in progress (stop is on its pill) and the background jobs.
53
+ */
54
+ export declare function ChatComposerRow(props: ComposerRowParts): import("react").JSX.Element;
@@ -0,0 +1,194 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Badge } from '@astryxdesign/core/Badge';
3
+ import { Banner } from '@astryxdesign/core/Banner';
4
+ import { Card } from '@astryxdesign/core/Card';
5
+ import { useCollapsible } from '@astryxdesign/core/Collapsible';
6
+ import { HStack } from '@astryxdesign/core/HStack';
7
+ import { IconButton } from '@astryxdesign/core/IconButton';
8
+ import { Spinner } from '@astryxdesign/core/Spinner';
9
+ import { StackItem } from '@astryxdesign/core/Stack';
10
+ import { Text } from '@astryxdesign/core/Text';
11
+ import { Token } from '@astryxdesign/core/Token';
12
+ import { VStack } from '@astryxdesign/core/VStack';
13
+ import { IconChevronDown, IconChevronUp, IconPlayerStopFilled } from '@tabler/icons-react';
14
+ import { useId, useLayoutEffect, useState, } from 'react';
15
+ import { useSecondTicker } from "../hooks/use-second-ticker.js";
16
+ import { liveDuration } from "./labels.js";
17
+ import { useLabels } from "./labels-provider.js";
18
+ /**
19
+ * A `--theorem-composer-*` property, or Theorem's value when the page sets none.
20
+ * why: Inline styles beat Astryx's own, so every look the row has goes through one of these and
21
+ * a builder sets it in CSS, on any element above the composer, or in their Astryx theme's
22
+ * `localTokens`.
23
+ */
24
+ const knob = (name, fallback) => `var(--theorem-composer-${name}, ${fallback})`;
25
+ const RADIUS = knob('radius', 'var(--radius-chat)');
26
+ const FILL = knob('fill', 'var(--color-background-popover)');
27
+ const SHADOW = knob('shadow', 'var(--shadow-low)');
28
+ const PADDING = knob('padding', 'var(--spacing-3)');
29
+ const GAP = knob('gap', 'var(--spacing-2)');
30
+ const INSET = knob('inset', '0px');
31
+ const TRAY_RADIUS = knob('tray-radius', RADIUS);
32
+ const TRAY_PADDING = knob('tray-padding', 'var(--spacing-3)');
33
+ const TRAY_HEADER_HEIGHT = 'var(--size-element-sm)';
34
+ /** why: Half the folded height, so the folded tray is round at both ends. */
35
+ const TRAY_FOLDED_RADIUS = knob('tray-folded-radius', `calc(${TRAY_PADDING} + ${TRAY_HEADER_HEIGHT} / 2)`);
36
+ const PILL_HEIGHT = knob('pill-height', 'var(--size-element-lg)');
37
+ const PILL_RADIUS = knob('pill-radius', 'var(--radius-full)');
38
+ const PILL_FILL = knob('pill-fill', FILL);
39
+ const PILL_SHADOW = knob('pill-shadow', SHADOW);
40
+ const PILL_ALIGN = knob('pill-align', 'center');
41
+ /** The pill shape, kept whole when the row scrolls. */
42
+ const PILL = {
43
+ height: PILL_HEIGHT,
44
+ flexShrink: 0,
45
+ border: 'none',
46
+ borderRadius: PILL_RADIUS,
47
+ background: PILL_FILL,
48
+ boxShadow: PILL_SHADOW,
49
+ '--_button-radius': PILL_RADIUS,
50
+ };
51
+ /** why: The stop button sits in the pill's end with the same ring of space all round it. */
52
+ const WORKING_PILL = {
53
+ ...PILL,
54
+ paddingInlineEnd: `calc((${PILL_HEIGHT} - var(--size-element-sm)) / 2)`,
55
+ };
56
+ /** invariant: The pill row keeps one pill's height whatever it holds, so the composer never moves. */
57
+ const PILL_ROW = { paddingInline: INSET, minHeight: PILL_HEIGHT };
58
+ /** why: One pill sits where `pill-align` puts it; more start at the edge and scroll sideways. */
59
+ const PILLS_ONE = { display: 'flex', justifyContent: PILL_ALIGN };
60
+ const PILLS_MANY = {
61
+ overflowX: 'auto',
62
+ scrollbarWidth: 'none',
63
+ // why: Pills that scroll fade out at the end instead of being cut against the hint.
64
+ maskImage: 'linear-gradient(to right, black calc(100% - var(--spacing-6)), transparent)',
65
+ };
66
+ /** The tray: a card of its own over the surface, a gap between them. */
67
+ /** why: The radius moves with the height, so the tray's ends stay round as it folds. */
68
+ const trayStyle = (open) => ({
69
+ marginInline: INSET,
70
+ border: 'none',
71
+ borderRadius: open ? TRAY_RADIUS : TRAY_FOLDED_RADIUS,
72
+ background: FILL,
73
+ boxShadow: SHADOW,
74
+ padding: TRAY_PADDING,
75
+ transition: 'border-radius var(--duration-medium) var(--ease-standard)',
76
+ });
77
+ const TRAY_HEADER = { cursor: 'pointer', minHeight: TRAY_HEADER_HEIGHT };
78
+ /** why: Folding animates the row's height to zero, so the tray closes in place. */
79
+ const trayBody = (open) => ({
80
+ display: 'grid',
81
+ gridTemplateRows: open ? '1fr' : '0fr',
82
+ transition: 'grid-template-rows var(--duration-medium) var(--ease-standard)',
83
+ });
84
+ const TRAY_BODY_INNER = { overflow: 'hidden', minHeight: 0 };
85
+ const TRAY_CONTENT = { paddingBlockStart: 'var(--spacing-3)' };
86
+ /**
87
+ * The working pill: what runs and for how long, and its stop button.
88
+ * why: It counts from the chat's turn clock, the one the transcript's status line reads, so the
89
+ * two agree and a wait on approval does not count.
90
+ */
91
+ function WorkingPill({ since, icons, onStop, }) {
92
+ const t = useLabels();
93
+ const now = useSecondTicker(since !== undefined);
94
+ const stop = t('@theorem.composer.pill.stop');
95
+ const label = since === undefined
96
+ ? t('@theorem.composer.pill.working')
97
+ : t('@theorem.composer.pill.working_for', { duration: liveDuration(t, now - since) });
98
+ return (_jsx(Token, { size: "lg", className: "theorem-composer-pill", "data-pill": "working", style: WORKING_PILL, label: label, icon: icons?.working ?? _jsx(Spinner, { size: "sm", shade: "inherit", "aria-label": label }), endContent: _jsx(IconButton, { label: stop, tooltip: stop, size: "sm", variant: "secondary", icon: icons?.stop ?? _jsx(IconPlayerStopFilled, { size: 12 }), onClick: onStop }) }));
99
+ }
100
+ /**
101
+ * The pill row. One pill sits centred over the composer (see `pill-align`); with more, the working
102
+ * pill leads and the rest follow it, scrolling sideways once they outgrow the row.
103
+ */
104
+ function PillRow(props) {
105
+ const t = useLabels();
106
+ const pills = [
107
+ props.isWorking ? (_jsx(WorkingPill, { since: props.workingSince, icons: props.icons, onStop: props.onStop }, "working")) : null,
108
+ ...props.backgroundJobs.map((job) => (_jsx(Token, { size: "lg", className: "theorem-composer-pill", "data-pill": "background", style: PILL, label: job.label, description: t('@theorem.composer.pill.background'), icon: props.icons?.backgroundJob ?? (_jsx(Spinner, { size: "sm", shade: "inherit", "aria-label": t('@theorem.composer.pill.background') })) }, job.callId))),
109
+ ].filter(Boolean);
110
+ if (pills.length === 0 && !props.hint)
111
+ return null;
112
+ return (_jsxs(HStack, { gap: 2, vAlign: "center", className: "theorem-composer-pills", style: PILL_ROW, children: [_jsx(StackItem, { size: "fill", style: pills.length > 1 ? PILLS_MANY : PILLS_ONE, children: _jsx(HStack, { gap: 1, vAlign: "center", children: pills }) }), props.hint] }));
113
+ }
114
+ /**
115
+ * What waits to send, on a card of its own above the surface: a header with the count, then the
116
+ * content, which folds away under the header.
117
+ */
118
+ function RowTray({ tray }) {
119
+ const t = useLabels();
120
+ const { isOpen, toggle } = useCollapsible({ isCollapsible: true });
121
+ const contentId = useId();
122
+ const Chevron = isOpen ? IconChevronDown : IconChevronUp;
123
+ return (_jsxs(Card, { elevation: "none", className: "theorem-composer-tray", "data-open": isOpen, style: trayStyle(isOpen), children: [_jsxs(HStack, { gap: 2, vAlign: "center", role: "button", tabIndex: 0, "aria-expanded": isOpen, "aria-controls": contentId, "aria-label": t(isOpen ? '@theorem.composer.tray.collapse' : '@theorem.composer.tray.expand', {
124
+ label: tray.label,
125
+ }), style: TRAY_HEADER, onClick: toggle, onKeyDown: (event) => {
126
+ if (event.key !== 'Enter' && event.key !== ' ')
127
+ return;
128
+ event.preventDefault();
129
+ toggle();
130
+ }, children: [_jsx(Badge, { variant: "neutral", label: tray.count }), _jsx(StackItem, { size: "fill", children: _jsx(Text, { size: "sm", color: "secondary", children: tray.label }) }), _jsx(Chevron, { size: 16, "aria-hidden": true })] }), _jsx("div", { id: contentId, style: trayBody(isOpen), inert: !isOpen, children: _jsx("div", { style: TRAY_BODY_INNER, children: _jsx("div", { style: TRAY_CONTENT, children: tray.content }) }) })] }));
131
+ }
132
+ /**
133
+ * Whether the field's text has wrapped past one line. Once it has, the row stays stacked until
134
+ * the draft empties.
135
+ * why: In the stacked layout the field is wider, so the same text may fit one line again; going
136
+ * back then would flip the layout on every keystroke.
137
+ */
138
+ function useWrapped(editorRef, draftText) {
139
+ const [wrapped, setWrapped] = useState(false);
140
+ const empty = draftText.trim() === '' && !draftText.includes('\n');
141
+ if (empty && wrapped)
142
+ setWrapped(false);
143
+ useLayoutEffect(() => {
144
+ const root = editorRef.current;
145
+ if (!root || wrapped)
146
+ return;
147
+ const field = root.querySelector('[contenteditable]') ?? root;
148
+ const measure = () => {
149
+ const line = Number.parseFloat(getComputedStyle(field).lineHeight);
150
+ if (Number.isFinite(line) && field.scrollHeight > line * 1.5)
151
+ setWrapped(true);
152
+ };
153
+ measure();
154
+ const observer = new ResizeObserver(measure);
155
+ observer.observe(field);
156
+ return () => observer.disconnect();
157
+ }, [editorRef, wrapped]);
158
+ return wrapped && !empty;
159
+ }
160
+ /** The field's slot: it shares the row, or takes a line of its own once the text wraps. */
161
+ function RowField({ input, stacked }) {
162
+ if (!input)
163
+ return null;
164
+ return (_jsx(StackItem, { size: "fill", crossAlignSelf: "center", style: stacked ? { flexBasis: '100%' } : { width: 0 }, children: input }));
165
+ }
166
+ /** The surface: Astryx's composer body, its look from the knobs above. */
167
+ const ROW_SURFACE = {
168
+ border: 'none',
169
+ borderRadius: RADIUS,
170
+ background: FILL,
171
+ boxShadow: SHADOW,
172
+ padding: PADDING,
173
+ // why: As in ChatComposer: buttons follow the shell's curve, so send and the send menu are round.
174
+ '--_button-radius': `max(var(--radius-element), calc(${RADIUS} - ${PADDING}))`,
175
+ };
176
+ /** The surface: attach, the field, then the controls, the mic, and send. */
177
+ function RowSurface(props) {
178
+ const attach = props.attach ? _jsx(StackItem, { children: props.attach }) : null;
179
+ return (_jsx(Card, { elevation: "none", className: "theorem-composer-surface", style: ROW_SURFACE, children: _jsxs(HStack, { gap: 1, wrap: "wrap", vAlign: "end", children: [props.stacked ? null : attach, _jsx(RowField, { input: props.input, stacked: props.stacked }), props.stacked ? attach : null, _jsx(StackItem, { size: props.stacked ? 'fill' : 'static', children: _jsxs(HStack, { gap: 1, vAlign: "center", hAlign: "end", children: [props.controls, props.record, props.action] }) })] }) }));
180
+ }
181
+ function RowStatus({ status }) {
182
+ if (!status)
183
+ return null;
184
+ return (_jsx(Banner, { status: status.type, role: status.type === 'error' ? 'alert' : 'status', title: status.message }));
185
+ }
186
+ /**
187
+ * Theorem's one-row composer: the field, then the controls, the mic, and send, on one line.
188
+ * Text that wraps moves the field onto its own line above them, the stacked layout. Above
189
+ * it, the pill row: the reply in progress (stop is on its pill) and the background jobs.
190
+ */
191
+ export function ChatComposerRow(props) {
192
+ const stacked = useWrapped(props.editorRef, props.draftText);
193
+ return (_jsxs(VStack, { gap: 0, width: "100%", className: "theorem-composer-row", style: { gap: GAP }, children: [_jsx(PillRow, { isWorking: props.isWorking, workingSince: props.workingSince, icons: props.icons, backgroundJobs: props.backgroundJobs, onStop: props.onStop, hint: props.hint }), props.tray ? _jsx(RowTray, { tray: props.tray }) : null, _jsx(RowSurface, { stacked: stacked, attach: props.attach, input: props.input, controls: props.controls, record: props.record, action: props.action }), _jsx(RowStatus, { status: props.status })] }));
194
+ }
@@ -4,6 +4,7 @@ import { type TranscriptBlock } from '@theoremjs/agents/interface';
4
4
  import type { AnsweringGate } from '@theoremjs/web/client';
5
5
  import { type ReactNode } from 'react';
6
6
  import { type ComposeAssistantTurnOptions } from '../client/transcript-groups.ts';
7
+ import { type TurnClock } from '../hooks/use-turn-clock.ts';
7
8
  import { type ToolDecision } from './ToolGateCard.tsx';
8
9
  import { type MediaReference } from './tool-media.tsx';
9
10
  export type ChatTranscriptProps = {
@@ -24,6 +25,11 @@ export type ChatTranscriptProps = {
24
25
  * starts at its block, and that block always starts a turn of its own.
25
26
  */
26
27
  dividers?: Readonly<Record<string, string>>;
28
+ /**
29
+ * The chat's turn clock (`useTheoremChat().turnClock`), so the times here agree with the
30
+ * composer's working pill. Without it the transcript keeps its own.
31
+ */
32
+ clock?: TurnClock;
27
33
  /**
28
34
  * Set for image profiles: generated images show large, framed to their own
29
35
  * aspect ratio, with a matching skeleton while one generates.
@@ -23,8 +23,9 @@ import { IconCheck, IconCopy } from '@tabler/icons-react';
23
23
  import { stopText } from '@theoremjs/agents/interface';
24
24
  import { citationsFromBlock } from '@theoremjs/web/client';
25
25
  import { createContext, useContext, useEffect, useMemo, useRef, useState, } from 'react';
26
- import { assistantTurnCopyText, assistantTurnTiming, composeAssistantTurn, groupTranscriptBlocks, pendingPromptOf, promptReplyKey, promptTime, replyKey, toolCallLabel, workStatus, } from "../client/transcript-groups.js";
26
+ import { assistantTurnCopyText, assistantTurnTiming, composeAssistantTurn, groupTranscriptBlocks, pendingPromptOf, promptReplyKey, promptTime, toolCallLabel, workStatus, } from "../client/transcript-groups.js";
27
27
  import { useSecondTicker } from "../hooks/use-second-ticker.js";
28
+ import { useTurnClock } from "../hooks/use-turn-clock.js";
28
29
  import { useDisclosureMotion } from "./disclosure-motion.js";
29
30
  import { usageLine, workDuration, workStatusLabel } from "./labels.js";
30
31
  import { TheoremLabelsProvider, useLabels } from "./labels-provider.js";
@@ -39,39 +40,6 @@ import { VoiceNote } from "./VoiceNote.js";
39
40
  const ShowUsage = createContext(false);
40
41
  /** Largest a generated image renders in the transcript. */
41
42
  const GENERATED_IMAGE_MAX_WIDTH = 512;
42
- /** First-seen time per group key, so timestamps don't jump while streaming. */
43
- function useFirstSeen(keys) {
44
- const times = useRef(new Map());
45
- const now = Date.now();
46
- for (const key of keys) {
47
- if (!times.current.has(key))
48
- times.current.set(key, now);
49
- }
50
- return (key) => times.current.get(key) ?? now;
51
- }
52
- /**
53
- * Each turn's span, keyed by the user group that started it. A turn stops at
54
- * a gate and streams again under the same prompt once it's answered; the wait
55
- * in between counts as paused, not worked.
56
- */
57
- function useTurnSpans(streaming, lastUserKey) {
58
- const spans = useRef(new Map());
59
- // why: The first send mounts the transcript already streaming; that's the start.
60
- const wasStreaming = useRef(false);
61
- if (lastUserKey && streaming !== wasStreaming.current) {
62
- const now = Date.now();
63
- const span = spans.current.get(lastUserKey);
64
- if (streaming) {
65
- const pausedMs = span?.endedAt === undefined ? 0 : span.pausedMs + now - span.endedAt;
66
- spans.current.set(lastUserKey, { pausedMs });
67
- }
68
- else if (span) {
69
- spans.current.set(lastUserKey, { ...span, endedAt: now });
70
- }
71
- }
72
- wasStreaming.current = streaming;
73
- return spans.current;
74
- }
75
43
  function CopyButton({ text }) {
76
44
  const t = useLabels();
77
45
  const [copied, setCopied] = useState(false);
@@ -659,10 +627,10 @@ function isBareFailure(group) {
659
627
  export function ChatTranscript(props) {
660
628
  return (_jsx(TheoremLabelsProvider, { children: _jsx(ShowUsage.Provider, { value: props.usage === true, children: _jsx(ChatTranscriptBody, { ...props }) }) }));
661
629
  }
662
- function ChatTranscriptBody({ blocks, handle, streaming = false, delivery, onToolDecision, answering = null, onAuthenticated, emptyState, dividers, imageOutput, bodyKindPlacement, labels, }) {
630
+ function ChatTranscriptBody({ blocks, handle, streaming = false, delivery, onToolDecision, answering = null, onAuthenticated, emptyState, dividers, imageOutput, bodyKindPlacement, labels, clock, }) {
663
631
  const groups = useMemo(() => groupTranscriptBlocks(blocks, dividers && new Set(Object.keys(dividers))), [blocks, dividers]);
664
- const timeOf = useFirstSeen(groups.map((group, index) => (group.kind === 'user' ? group.key : replyKey(groups, index))));
665
- const spans = useTurnSpans(streaming, groups.findLast((group) => group.kind === 'user')?.key);
632
+ const own = useTurnClock(groups, streaming);
633
+ const { timeOf, spans } = clock ?? own;
666
634
  const pendingPrompt = streaming ? pendingPromptOf(groups) : undefined;
667
635
  const listRef = useRef(null);
668
636
  useDisclosureMotion(listRef);