@theoremjs/react 0.3.5-next.975.g3529c32 → 0.3.5-next.977.g42c51f5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -176,9 +176,53 @@ To draw your own figures like the trace panel does, `@theoremjs/react/ui` also e
176
176
  | `initialPending` | The messages that the composer starts with set aside: queued, stashed, or steering, as `createComposerPendingMessage` from `@theoremjs/agents/interface` makes them. The component reads them once, when it mounts. |
177
177
  | `chatRef` | Sends a message, stops a reply, or focuses the composer from your code. See below. |
178
178
  | `composer` | `false` leaves the composer out. The chat is the transcript alone, and your own control sends through `chatRef`. Default: `true`. |
179
+ | `composerLayout` | `'stacked'` or `'row'`. In `'row'`, the field, the mic and send share one line, and text that wraps moves the field onto its own line. Above them, a pill shows the reply in progress, with its stop button, and a pill shows each background call. While a reply runs or a step waits, Enter queues a draft and send opens the send menu. Default: `'stacked'`. |
180
+ | `composerIcons` | The glyphs the `'row'` composer draws: `working`, before the working pill's text; `backgroundJob`, before each background call's name; `stop`, in the working pill's stop button. Each one you leave out keeps Theorem's. See [The row composer's look](#the-row-composers-look). |
179
181
  | `media` | Which media from tools the chat shows. `'sent'` shows only what a tool sent to the person. `'all'` also shows what only the model read, for an evaluation view. Default: `'sent'`. See [Tool media](#tool-media). |
180
182
  | `resolveMedia` | Turns a tool's reference into an address the page can load. See [Tool media](#tool-media). |
181
183
 
184
+ ### The row composer's look
185
+
186
+ The `'row'` composer has three parts: the pill row, the tray of what waits to send, and the surface with the field. The working pill reads "Working for 12s". It counts from the time the reply started and leaves out the time a step waited for approval, the same as the transcript's status line.
187
+
188
+ Each part of the look is a CSS custom property. Set it on any element above the composer, in your stylesheet or in `style`, or in your Astryx theme's `localTokens`. A property you do not set keeps Theorem's value.
189
+
190
+ | Property | What it sets | Default |
191
+ | --- | --- | --- |
192
+ | `--theorem-composer-radius` | The surface's corner radius. Send and the send menu follow its curve. | `var(--radius-chat)` |
193
+ | `--theorem-composer-fill` | The fill of the surface and the tray. | `var(--color-background-popover)` |
194
+ | `--theorem-composer-shadow` | The shadow of the surface and the tray. | `var(--shadow-low)` |
195
+ | `--theorem-composer-padding` | The space inside the surface. | `var(--spacing-3)` |
196
+ | `--theorem-composer-gap` | The space between the pill row, the tray and the surface. | `var(--spacing-2)` |
197
+ | `--theorem-composer-inset` | How far the pill row and the tray sit in from the surface's sides. | `0px` |
198
+ | `--theorem-composer-tray-radius` | The open tray's corner radius. | the surface's radius |
199
+ | `--theorem-composer-tray-folded-radius` | The folded tray's corner radius. | half the folded tray's height, so its ends are round |
200
+ | `--theorem-composer-tray-padding` | The space inside the tray. | `var(--spacing-3)` |
201
+ | `--theorem-composer-pill-height` | The height of each pill. | `var(--size-element-lg)` |
202
+ | `--theorem-composer-pill-radius` | The corner radius of each pill and of the stop button. | `var(--radius-full)` |
203
+ | `--theorem-composer-pill-fill` | The fill of each pill. | the surface's fill |
204
+ | `--theorem-composer-pill-shadow` | The shadow of each pill. | the surface's shadow |
205
+ | `--theorem-composer-pill-align` | Where one pill sits in the row, as `justify-content`. Two or more pills start at the row's start, and scroll once they do not fit. | `center` |
206
+
207
+ ```tsx
208
+ <TheoremChat
209
+ endpoint="/api/theorem"
210
+ composerLayout="row"
211
+ composerIcons={{ working: <LeafSpinner /> }}
212
+ labels={{ en: { '@theorem.composer.pill.working_for': 'Thinking · {duration}' } }}
213
+ className="chat"
214
+ />
215
+ ```
216
+
217
+ ```css
218
+ .chat {
219
+ --theorem-composer-radius: 22px;
220
+ --theorem-composer-pill-align: start;
221
+ }
222
+ ```
223
+
224
+ The words are labels: `@theorem.composer.pill.working_for`, `@theorem.composer.pill.working` (before the start is known), `@theorem.composer.pill.stop`, `@theorem.composer.pill.background`, `@theorem.composer.tray.expand` and `@theorem.composer.tray.collapse`. See [Wording](#wording). For a rule that no property covers, each part has a class: `theorem-composer-row`, `theorem-composer-pills`, `theorem-composer-pill` (with `data-pill="working"` or `"background"`), `theorem-composer-tray` (with `data-open`) and `theorem-composer-surface`.
225
+
182
226
  ### Tool media
183
227
 
184
228
  A tool can return media for the model, for the person, or for both. The chat shows media from a tool only when the tool marked it `sent`, unless you pass `media="all"`. Media that a model generated and files that the user attached always show.
@@ -411,7 +455,7 @@ Three more values for `useLiveCall` come from the page. The profile declares eac
411
455
 
412
456
  `stated` is a fourth value, for a page you trust as yourself. It says the `path` and the `options` from `identity.options` that choose the call's prompt lines, and the server reads it only with `pageStatesTurn` set. A change during a call takes the call up again, as an option does. `TheoremChat` takes the same prop, on each turn.
413
457
 
414
- `model` and `effort` pick the call's model when the profile sets `allowModelSelect`. They are read when the call starts.
458
+ `model` and `effort` pick the call's model and effort. The host refuses them unless the profile sets `allowModelSelect` (and the binding `allowEffortSelect`). They are read when the call starts.
415
459
 
416
460
  ```tsx
417
461
  const call = useLiveCall({
@@ -497,6 +541,8 @@ function MyChat() {
497
541
 
498
542
  `chat.phase` is `'idle'`, `'streaming'`, or `'gated'`. The actions are `handleSubmit`, `handleStop`, `handleSendNow`, and `handleToolDecision`.
499
543
 
544
+ `chat.backgroundJobs` lists the tool calls that still run in the background, each as `{ callId, label }`. A call leaves the list when its late result lands. `backgroundJobs(blocks)` gives the same list from a transcript. `ChatComposerBar` takes `layout` and `backgroundJobs`, as `TheoremChat` takes `composerLayout`.
545
+
500
546
  `handlePendingMove(id, direction)` moves a pending message among those of its kind. `ChatComposerBar` draws a move only when `composerPendingMoves` from `@theoremjs/agents/interface` says the message can go that way: a message alone in its kind has none.
501
547
 
502
548
  To show the transcript and the composer, use `ChatTranscript` and `ChatComposerBar` from `/ui`. You can also draw your own from `chat.blocks`.
@@ -150,3 +150,13 @@ export declare function assistantTurnTiming(args: {
150
150
  export declare function toolCallLabel(tool: Extract<TranscriptBlock, {
151
151
  kind: 'tool';
152
152
  }>['tool']): string;
153
+ /** A tool call still running in the background, as the composer's pill row shows it. */
154
+ export type BackgroundJob = {
155
+ callId: string;
156
+ label: string;
157
+ };
158
+ /**
159
+ * The calls still running in the background, oldest first: each tool call whose last phase is
160
+ * `background`, until a late-results message carries its result.
161
+ */
162
+ export declare function backgroundJobs(blocks: readonly TranscriptBlock[]): BackgroundJob[];
@@ -243,3 +243,25 @@ export function toolCallLabel(tool) {
243
243
  const settled = phase === 'complete' || phase === 'error';
244
244
  return (settled ? tool.activityPast : tool.activity) ?? humanize(tool.name);
245
245
  }
246
+ /**
247
+ * The calls still running in the background, oldest first: each tool call whose last phase is
248
+ * `background`, until a late-results message carries its result.
249
+ */
250
+ export function backgroundJobs(blocks) {
251
+ const landed = new Set();
252
+ for (const block of blocks) {
253
+ if (block.kind === 'late-results')
254
+ for (const id of block.operationIds)
255
+ landed.add(id);
256
+ }
257
+ const jobs = [];
258
+ for (const block of blocks) {
259
+ if (block.kind !== 'tool' || block.tool.state?.phase !== 'background')
260
+ continue;
261
+ const { operationId } = block.tool;
262
+ if (operationId && landed.has(operationId))
263
+ continue;
264
+ jobs.push({ callId: block.tool.callId, label: toolCallLabel(block.tool) });
265
+ }
266
+ return jobs;
267
+ }
@@ -10,23 +10,25 @@ export type UseTheoremChatOptions = ChatOptions;
10
10
  export declare function useTheoremChat(options: UseTheoremChatOptions): {
11
11
  optionChoices: {
12
12
  onChange: (name: string, value: string) => void;
13
- declared: import("../../../mod").ProfileOptions;
13
+ declared: import("../../../mod.ts").ProfileOptions;
14
14
  values: Record<string, string>;
15
15
  } | undefined;
16
+ /** The tool calls still running in the background, oldest first, until their results land. */
17
+ backgroundJobs: import("../index.ts").BackgroundJob[];
16
18
  setDraftText: (value: import("@theoremjs/web/client").ChatUpdate<string>) => void;
17
19
  setPendingFiles: (value: import("@theoremjs/web/client").ChatUpdate<File[]>) => void;
18
20
  setPendingVoice: (value: import("@theoremjs/web/client").ChatUpdate<File[]>) => void;
19
- setPendingMessages: (value: import("@theoremjs/web/client").ChatUpdate<import("../../../src/interface/pending").ComposerPendingMessage[]>) => void;
20
- setIssues: (value: import("@theoremjs/web/client").ChatUpdate<import("../../../mod").AttachmentValidationIssue[]>) => void;
21
+ setPendingMessages: (value: import("@theoremjs/web/client").ChatUpdate<import("../../../src/interface/pending.ts").ComposerPendingMessage[]>) => void;
22
+ setIssues: (value: import("@theoremjs/web/client").ChatUpdate<import("../../../mod.ts").AttachmentValidationIssue[]>) => void;
21
23
  handleAuthenticated: (_index: number, secret?: string) => Promise<void>;
22
24
  handleBranch: (index: number) => Promise<void>;
23
25
  handleSubmit: () => Promise<void>;
24
26
  handleStop: () => void;
25
- handleMenuAction: (action: import("../../../src/interface/composer-actions").ComposerMenuAction) => void;
27
+ handleMenuAction: (action: import("../../../src/interface/composer-actions.ts").ComposerMenuAction) => void;
26
28
  handlePendingQueue: (id: string) => void;
27
29
  handlePendingMove: (id: string, direction: "up" | "down") => void;
28
30
  handlePendingRestore: (id: string) => Promise<void>;
29
- handleSendNow: (source?: import("../../../src/interface/pending").ComposerPendingMessage) => Promise<void>;
31
+ handleSendNow: (source?: import("../../../src/interface/pending.ts").ComposerPendingMessage) => Promise<void>;
30
32
  handleToolDecision: (_index: number, action: ToolDecisionAction) => Promise<void>;
31
33
  handleGenerationChange: (next: {
32
34
  modelId: string;
@@ -35,19 +37,19 @@ export declare function useTheoremChat(options: UseTheoremChatOptions): {
35
37
  sendText: (text: string, options?: SendTextOptions) => Promise<SentTurn | null>;
36
38
  /** The controller under it all, for a host that drives the chat from outside. */
37
39
  controller: import("@theoremjs/web/client").ChatController;
38
- iface: import("../../../src/interface/types").ComposerProfileInterface | null;
39
- blocks: import("../../../src/interface/types").TranscriptBlock[];
40
- streamBlocks: import("../../../src/interface/types").TranscriptBlock[];
40
+ iface: import("../../../src/interface/types.ts").ComposerProfileInterface | null;
41
+ blocks: import("../../../src/interface/types.ts").TranscriptBlock[];
42
+ streamBlocks: import("../../../src/interface/types.ts").TranscriptBlock[];
41
43
  chatStarted: boolean;
42
44
  draftText: string;
43
45
  pendingFiles: File[];
44
46
  pendingVoice: File[];
45
- pendingMessages: import("../../../src/interface/pending").ComposerPendingMessage[];
46
- issues: import("../../../mod").AttachmentValidationIssue[];
47
+ pendingMessages: import("../../../src/interface/pending.ts").ComposerPendingMessage[];
48
+ issues: import("../../../mod.ts").AttachmentValidationIssue[];
47
49
  failure: import("@theoremjs/web/client").ClientFailure | null;
48
50
  answering: import("@theoremjs/web/client").AnsweringGate | null;
49
- phase: import("../../../src/interface/composer-actions").ComposerRunPhase;
50
- session: import("../../../src/interface/session").InterfaceTurnSession;
51
+ phase: import("../../../src/interface/composer-actions.ts").ComposerRunPhase;
52
+ session: import("../../../src/interface/session.ts").InterfaceTurnSession;
51
53
  delivery: import("@theoremjs/web/client").MessageDelivery | null;
52
54
  streaming: boolean;
53
55
  options: import("@theoremjs/web/client").ChatOptionPicks | undefined;
@@ -1,5 +1,6 @@
1
1
  import { createChatController, } from '@theoremjs/web/client';
2
2
  import { useCallback, useEffect, useLayoutEffect, useMemo, useState, useSyncExternalStore, } from 'react';
3
+ import { backgroundJobs } from "../client/transcript-groups.js";
3
4
  // why: Options reach the chat before the browser paints, and before a line can arrive; a server render runs no effects.
4
5
  const useOptionsEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
5
6
  /**
@@ -13,12 +14,15 @@ export function useTheoremChat(options) {
13
14
  useOptionsEffect(() => chat.update(options));
14
15
  const state = useSyncExternalStore(chat.subscribe, chat.getState, chat.getState);
15
16
  const optionChoices = useMemo(() => (state.options ? { ...state.options, onChange: chat.pickOption } : undefined), [chat, state.options]);
17
+ const jobs = useMemo(() => backgroundJobs([...state.blocks, ...state.streamBlocks]), [state.blocks, state.streamBlocks]);
16
18
  // why: The transcript draws each gate by its index; the chat answers the one gate that waits.
17
19
  const handleAuthenticated = useCallback((_index, secret) => chat.authenticate(secret), [chat]);
18
20
  const handleToolDecision = useCallback((_index, action) => chat.decide(action), [chat]);
19
21
  return {
20
22
  ...state,
21
23
  optionChoices,
24
+ /** The tool calls still running in the background, oldest first, until their results land. */
25
+ backgroundJobs: jobs,
22
26
  setDraftText: chat.setDraftText,
23
27
  setPendingFiles: chat.setPendingFiles,
24
28
  setPendingVoice: chat.setPendingVoice,
@@ -0,0 +1,18 @@
1
+ import { type TranscriptTurnGroup, type TurnSpan } from '../client/transcript-groups.ts';
2
+ /**
3
+ * When each turn was first seen, and how long each sat paused on approvals.
4
+ * invariant: One clock per chat: the transcript's status line and the composer's working pill
5
+ * read the same one, so they show the same time.
6
+ */
7
+ export type TurnClock = {
8
+ timeOf: (key: string) => number;
9
+ spans: ReadonlyMap<string, TurnSpan>;
10
+ };
11
+ /** The chat's turn clock over its grouped transcript. */
12
+ export declare function useTurnClock(groups: readonly TranscriptTurnGroup[], streaming: boolean): TurnClock;
13
+ /** When the reply in progress started, its approval waits skipped; `undefined` when none runs. */
14
+ export declare function liveTurnStart(groups: readonly TranscriptTurnGroup[], clock: TurnClock, streaming: boolean): number | undefined;
15
+ /** The clock a chat shares with its transcript; a transcript on its own keeps its own. */
16
+ export declare const TurnClockContext: import("react").Context<TurnClock | null>;
17
+ /** The shared clock when a chat provides one, else this transcript's own. */
18
+ export declare function useSharedTurnClock(groups: readonly TranscriptTurnGroup[], streaming: boolean): TurnClock;
@@ -0,0 +1,59 @@
1
+ import { createContext, useContext, useRef } from 'react';
2
+ import { replyKey } from "../client/transcript-groups.js";
3
+ /** First-seen time per group key, so timestamps don't jump while streaming. */
4
+ function useFirstSeen(keys) {
5
+ const times = useRef(new Map());
6
+ const now = Date.now();
7
+ for (const key of keys) {
8
+ if (!times.current.has(key))
9
+ times.current.set(key, now);
10
+ }
11
+ return (key) => times.current.get(key) ?? now;
12
+ }
13
+ /**
14
+ * Each turn's span, keyed by the user group that started it. A turn stops at
15
+ * a gate and streams again under the same prompt once it's answered; the wait
16
+ * in between counts as paused, not worked.
17
+ */
18
+ function useTurnSpans(streaming, lastUserKey) {
19
+ const spans = useRef(new Map());
20
+ // why: A transcript can mount already streaming, on the first send; that's the start.
21
+ const wasStreaming = useRef(false);
22
+ if (lastUserKey && streaming !== wasStreaming.current) {
23
+ const now = Date.now();
24
+ const span = spans.current.get(lastUserKey);
25
+ if (streaming) {
26
+ const pausedMs = span?.endedAt === undefined ? 0 : span.pausedMs + now - span.endedAt;
27
+ spans.current.set(lastUserKey, { pausedMs });
28
+ }
29
+ else if (span) {
30
+ spans.current.set(lastUserKey, { ...span, endedAt: now });
31
+ }
32
+ }
33
+ wasStreaming.current = streaming;
34
+ return spans.current;
35
+ }
36
+ /** The chat's turn clock over its grouped transcript. */
37
+ export function useTurnClock(groups, streaming) {
38
+ const timeOf = useFirstSeen(groups.map((group, index) => (group.kind === 'user' ? group.key : replyKey(groups, index))));
39
+ const spans = useTurnSpans(streaming, groups.findLast((group) => group.kind === 'user')?.key);
40
+ return { timeOf, spans };
41
+ }
42
+ /** When the reply in progress started, its approval waits skipped; `undefined` when none runs. */
43
+ export function liveTurnStart(groups, clock, streaming) {
44
+ if (!streaming)
45
+ return undefined;
46
+ const prompt = groups.findLast((group) => group.kind === 'user');
47
+ if (!prompt)
48
+ return undefined;
49
+ const span = clock.spans.get(prompt.key);
50
+ return span ? clock.timeOf(prompt.key) + span.pausedMs : undefined;
51
+ }
52
+ /** The clock a chat shares with its transcript; a transcript on its own keeps its own. */
53
+ export const TurnClockContext = createContext(null);
54
+ /** The shared clock when a chat provides one, else this transcript's own. */
55
+ export function useSharedTurnClock(groups, streaming) {
56
+ const shared = useContext(TurnClockContext);
57
+ const own = useTurnClock(groups, streaming);
58
+ return shared ?? own;
59
+ }
package/index.d.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * @module
9
9
  */
10
10
  export * from '@theoremjs/web/client';
11
+ export { type BackgroundJob, backgroundJobs } from './client/transcript-groups.ts';
11
12
  export { type EmbeddingIndex, type IndexProgress, useEmbeddingIndex, } from './hooks/use-embedding-index.ts';
12
13
  export { type SendTextOptions, type SentTurn, type UseTheoremChatOptions, useTheoremChat, } from './hooks/use-theorem-chat.ts';
13
14
  export { type TheoremDecisionState, useTheoremDecision } from './hooks/use-theorem-decision.ts';
package/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * @module
9
9
  */
10
10
  export * from '@theoremjs/web/client';
11
+ export { backgroundJobs } from "./client/transcript-groups.js";
11
12
  export { useEmbeddingIndex, } from "./hooks/use-embedding-index.js";
12
13
  export { useTheoremChat, } from "./hooks/use-theorem-chat.js";
13
14
  export { useTheoremDecision } from "./hooks/use-theorem-decision.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/react",
3
- "version": "0.3.5-next.975.g3529c32",
3
+ "version": "0.3.5-next.977.g42c51f5",
4
4
  "description": "React bindings for Theorem: headless hooks + transport, an Astryx chat UI, and a Web-standard server handler.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -60,8 +60,8 @@
60
60
  "@stylexjs/stylex": "0.19.0",
61
61
  "react": "^19.0.0",
62
62
  "react-dom": "^19.0.0",
63
- "@theoremjs/agents": "^0.3.5-next.975.g3529c32",
64
- "@theoremjs/web": "^0.3.5-next.975.g3529c32"
63
+ "@theoremjs/agents": "^0.3.5-next.977.g42c51f5",
64
+ "@theoremjs/web": "^0.3.5-next.977.g42c51f5"
65
65
  },
66
66
  "peerDependenciesMeta": {
67
67
  "@astryxdesign/core": {
@@ -2,6 +2,8 @@ import { type ChatComposerInputHandle } from '@astryxdesign/core/Chat';
2
2
  import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerPendingMessage, type ComposerProfileInterface, type ComposerRunPhase, type LiveProfileInterface } from '@theoremjs/agents/interface';
3
3
  import type { ClientFailure } from '@theoremjs/web/client';
4
4
  import { type ReactNode } from 'react';
5
+ import type { BackgroundJob } from '../client/transcript-groups.ts';
6
+ import { type ComposerRowIcons } from './ChatComposerRow.tsx';
5
7
  /** An option the profile declares: its allowed values, the one chosen, and how to choose another. */
6
8
  /** The effort selector's icon. The studio's Agents list shows the same one. */
7
9
  export declare const EFFORT_ICON: import("react").ForwardRefExoticComponent<import("@tabler/icons-react").IconProps & import("react").RefAttributes<SVGSVGElement>>;
@@ -18,8 +20,23 @@ export type OptionChoices = {
18
20
  values: Readonly<Record<string, string>>;
19
21
  onChange: (name: string, value: string) => void;
20
22
  };
23
+ /**
24
+ * How the composer is laid out. `stacked` (default): Astryx's composer, the field above a row of
25
+ * controls, with stop on the send button. `row`: the field and its buttons on one line, which
26
+ * stacks once the text wraps; a pill row above it shows the reply in progress, with stop on its
27
+ * pill, and the background jobs; while a reply runs the one button opens the send menu.
28
+ */
29
+ export type ComposerLayout = 'stacked' | 'row';
21
30
  export type ChatComposerBarProps = {
22
31
  iface: ComposerProfileInterface;
32
+ /** Default `stacked`. */
33
+ layout?: ComposerLayout;
34
+ /** The tool calls running in the background; the `row` layout shows each as a pill. */
35
+ backgroundJobs?: readonly BackgroundJob[];
36
+ /** When the reply in progress started, its approval waits skipped; the `row` layout's working pill counts from it. */
37
+ workingSince?: number;
38
+ /** Glyphs the `row` layout draws; each one left out keeps Theorem's. See {@link ComposerRowIcons}. */
39
+ icons?: ComposerRowIcons;
23
40
  draftText: string;
24
41
  pendingFiles: readonly File[];
25
42
  pendingVoice: readonly File[];
@@ -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
+ }
@@ -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 { useSharedTurnClock } 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);
@@ -661,8 +629,7 @@ export function ChatTranscript(props) {
661
629
  }
662
630
  function ChatTranscriptBody({ blocks, handle, streaming = false, delivery, onToolDecision, answering = null, onAuthenticated, emptyState, dividers, imageOutput, bodyKindPlacement, labels, }) {
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 { timeOf, spans } = useSharedTurnClock(groups, streaming);
666
633
  const pendingPrompt = streaming ? pendingPromptOf(groups) : undefined;
667
634
  const listRef = useRef(null);
668
635
  useDisclosureMotion(listRef);
@@ -4,6 +4,8 @@ import type { ChatController, PageTools, StatedTurn } from '@theoremjs/web/clien
4
4
  import { type ConversationView, type HttpTransportOptions, type TheoremTransport } from '@theoremjs/web/client';
5
5
  import { type ReactNode, type Ref } from 'react';
6
6
  import { type SendTextOptions, type SentTurn, type UseTheoremChatOptions } from '../hooks/use-theorem-chat.ts';
7
+ import { type ComposerLayout } from './ChatComposerBar.tsx';
8
+ import type { ComposerRowIcons } from './ChatComposerRow.tsx';
7
9
  import type { TheoremLabels } from './labels.ts';
8
10
  import type { ResolveMedia, ToolMediaShown } from './tool-media.tsx';
9
11
  export type TheoremChatProps = {
@@ -124,6 +126,18 @@ export type TheoremChatProps = {
124
126
  * through `chatRef`. Gates are still answered in the transcript. Default `true`.
125
127
  */
126
128
  composer?: boolean;
129
+ /**
130
+ * How the composer is laid out: `stacked` (default), Astryx's composer with the field above its
131
+ * controls; or `row`, the field and its buttons on one line, with a pill row above it for the
132
+ * reply in progress and the background jobs. See {@link ComposerLayout}.
133
+ */
134
+ composerLayout?: ComposerLayout;
135
+ /**
136
+ * Glyphs the `row` composer draws: the working pill's, each background job's, and stop's. Each
137
+ * one left out keeps Theorem's. Its text is in `labels`; its look is the
138
+ * `--theorem-composer-*` CSS properties.
139
+ */
140
+ composerIcons?: ComposerRowIcons;
127
141
  };
128
142
  /** What a host can do to a mounted {@link TheoremChat}. */
129
143
  export type TheoremChatHandle = {
package/ui/TheoremChat.js CHANGED
@@ -9,8 +9,10 @@ import { removeComposerPendingMessage, } from '@theoremjs/agents/interface';
9
9
  import { createHttpTransport, } from '@theoremjs/web/client';
10
10
  import { useImperativeHandle, useMemo, useRef, } from 'react';
11
11
  import { parseAspectRatio } from "../client/image-output.js";
12
+ import { groupTranscriptBlocks } from "../client/transcript-groups.js";
12
13
  import { useTheoremChat, } from "../hooks/use-theorem-chat.js";
13
14
  import { useTheoremInterface } from "../hooks/use-theorem-interface.js";
15
+ import { liveTurnStart, TurnClockContext, useTurnClock } from "../hooks/use-turn-clock.js";
14
16
  import { ChatComposerBar } from "./ChatComposerBar.js";
15
17
  import { ChatTranscript } from "./ChatTranscript.js";
16
18
  import { useGlide } from "./glide.js";
@@ -29,8 +31,8 @@ function ChatColumn({ maxWidth, ref, children, }) {
29
31
  return (_jsx(Center, { axis: "horizontal", width: "100%", children: _jsx(VStack, { ref: ref, width: "100%", maxWidth: maxWidth, children: children }) }));
30
32
  }
31
33
  /** The composer bar wired to a `useTheoremChat` model. */
32
- function ChatComposerForChat({ chat, iface, placeholder, inputRef, }) {
33
- return (_jsx(ChatComposerBar, { iface: iface, draftText: chat.draftText, pendingFiles: chat.pendingFiles, pendingVoice: chat.pendingVoice, pendingMessages: chat.pendingMessages, issues: chat.issues, phase: chat.phase, failure: chat.failure, selectedModel: chat.session.selectedModel, selectedEffort: chat.session.selectedEffort, placeholder: placeholder, inputRef: inputRef, onDraftTextChange: chat.setDraftText, onFilesSelected: (files) => {
34
+ function ChatComposerForChat({ chat, iface, placeholder, inputRef, layout, icons, workingSince, }) {
35
+ return (_jsx(ChatComposerBar, { iface: iface, layout: layout, icons: icons, workingSince: workingSince, backgroundJobs: chat.backgroundJobs, draftText: chat.draftText, pendingFiles: chat.pendingFiles, pendingVoice: chat.pendingVoice, pendingMessages: chat.pendingMessages, issues: chat.issues, phase: chat.phase, failure: chat.failure, selectedModel: chat.session.selectedModel, selectedEffort: chat.session.selectedEffort, placeholder: placeholder, inputRef: inputRef, onDraftTextChange: chat.setDraftText, onFilesSelected: (files) => {
34
36
  chat.setPendingFiles((prev) => [...prev, ...files]);
35
37
  chat.setIssues([]);
36
38
  }, onAttachmentRemove: (index) => {
@@ -50,7 +52,28 @@ function ChatComposerForChat({ chat, iface, placeholder, inputRef, }) {
50
52
  void chat.handleSendNow(message);
51
53
  } }));
52
54
  }
53
- function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth = DEFAULT_CHAT_MAX_WIDTH, scrollRef, trace, usage, className, style, conversation, conversationView, initialText, initialFiles, initialVoice, initialPending, onConversationChange, chatRef, composer: hasComposer = true, options, onOptionsChange, stated, context, pageTools, onTurnEvent, }) {
55
+ /** The handle `chatRef` gets: send, stop, focus and the controller. */
56
+ function useChatHandle(chatRef, chat) {
57
+ const { sendText, handleStop, controller } = chat;
58
+ const inputRef = useRef(null);
59
+ useImperativeHandle(chatRef, () => ({
60
+ send: sendText,
61
+ stop: handleStop,
62
+ focus: () => {
63
+ inputRef.current?.focus();
64
+ },
65
+ controller,
66
+ }), [sendText, handleStop, controller]);
67
+ return inputRef;
68
+ }
69
+ /** The composer, or, with none, the failed turn's error where the composer was. */
70
+ function ChatBodyComposer({ hasComposer, ...props }) {
71
+ if (hasComposer)
72
+ return _jsx(ChatComposerForChat, { ...props });
73
+ const failure = props.chat.failure;
74
+ return failure ? _jsx(Banner, { status: "error", role: "alert", title: failure.error }) : null;
75
+ }
76
+ function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth = DEFAULT_CHAT_MAX_WIDTH, scrollRef, trace, usage, className, style, conversation, conversationView, initialText, initialFiles, initialVoice, initialPending, onConversationChange, chatRef, composer: hasComposer = true, composerLayout, composerIcons, options, onOptionsChange, stated, context, pageTools, onTurnEvent, }) {
54
77
  const t = useLabels();
55
78
  const chat = useTheoremChat({
56
79
  transport,
@@ -69,26 +92,18 @@ function ChatBody({ transport, iface, placeholder, emptyState, density, maxWidth
69
92
  pageTools,
70
93
  onTurnEvent,
71
94
  });
72
- const { sendText, handleStop, controller } = chat;
73
95
  const blocks = useMemo(() => [...chat.blocks, ...chat.streamBlocks], [chat.blocks, chat.streamBlocks]);
96
+ const groups = useMemo(() => groupTranscriptBlocks(blocks), [blocks]);
97
+ const clock = useTurnClock(groups, chat.streaming);
74
98
  const handle = t('@theorem.agent.handle', { handle: iface.identity.handle });
75
99
  const landing = blocks.length === 0;
76
- const inputRef = useRef(null);
77
- useImperativeHandle(chatRef, () => ({
78
- send: sendText,
79
- stop: handleStop,
80
- focus: () => {
81
- inputRef.current?.focus();
82
- },
83
- controller,
84
- }), [sendText, handleStop, controller]);
100
+ const inputRef = useChatHandle(chatRef, chat);
85
101
  const composerRef = useGlide(landing, () => inputRef.current?.focus());
86
102
  const inspector = useTraceInspector(iface, transport.traces, trace);
87
103
  const header = _jsx(SidePanelHeader, { floating: true, children: inspector.toggle });
88
- // why: the composer says when a turn failed. Without one, the chat says it where the composer was.
89
- const composer = hasComposer ? (_jsx(ChatComposerForChat, { chat: chat, iface: iface, placeholder: placeholder, inputRef: inputRef })) : (chat.failure && _jsx(Banner, { status: "error", role: "alert", title: chat.failure.error }));
104
+ const composer = (_jsx(ChatBodyComposer, { hasComposer: hasComposer, chat: chat, iface: iface, placeholder: placeholder, inputRef: inputRef, layout: composerLayout, icons: composerIcons, workingSince: liveTurnStart(groups, clock, chat.streaming) }));
90
105
  const docked = { composer, composerRef, maxWidth };
91
- return (_jsx(WithTrace, { inspector: inspector, children: _jsx(Layout, { height: "fill", className: className, style: { position: 'relative', ...style }, header: header, content: _jsx(LayoutContent, { padding: 0, isScrollable: landing, children: landing ? (_jsx(ChatLanding, { ...docked, handle: handle, emptyState: emptyState })) : (_jsx(ChatThread, { ...docked, chat: chat, iface: iface, blocks: blocks, handle: handle, density: density, scrollRef: scrollRef, usage: usage })) }) }) }));
106
+ return (_jsx(TurnClockContext, { value: clock, children: _jsx(WithTrace, { inspector: inspector, children: _jsx(Layout, { height: "fill", className: className, style: { position: 'relative', ...style }, header: header, content: _jsx(LayoutContent, { padding: 0, isScrollable: landing, children: landing ? (_jsx(ChatLanding, { ...docked, handle: handle, emptyState: emptyState })) : (_jsx(ChatThread, { ...docked, chat: chat, iface: iface, blocks: blocks, handle: handle, density: density, scrollRef: scrollRef, usage: usage })) }) }) }) }));
92
107
  }
93
108
  const CHAT_SCROLL = { overscrollBehavior: 'none' };
94
109
  /**
package/ui/index.d.ts CHANGED
@@ -14,7 +14,8 @@ export { useLiveCaptionLog } from '../client/live/use-live-caption-log.ts';
14
14
  export { InkWaveform, type InkWaveformProps, type InkWaveLevels, } from '../components/InkWaveform.tsx';
15
15
  export { type LiveCall, type LiveCallInput, useLiveCall, } from '../components/live/use-live-call.ts';
16
16
  export { theoremTheme } from './built/theorem.js';
17
- export { ChatComposerBar, type ChatComposerBarProps, EFFORT_ICON, generationOptions, type LiveComposerBarProps, } from './ChatComposerBar.tsx';
17
+ export { ChatComposerBar, type ChatComposerBarProps, type ComposerLayout, EFFORT_ICON, generationOptions, type LiveComposerBarProps, } from './ChatComposerBar.tsx';
18
+ export type { ComposerRowIcons } from './ChatComposerRow.tsx';
18
19
  export { ChatTranscript, type ChatTranscriptProps } from './ChatTranscript.tsx';
19
20
  export { ConsoleFrame, type ConsoleFrameProps, type ConsolePageProps, RequestCard, ResponseColumn, RunBar, useBytes, } from './ConsoleFrame.tsx';
20
21
  export { TheoremDecisionAnswers, type TheoremDecisionAnswersProps } from './DecisionAnswers.tsx';
package/ui/labels.d.ts CHANGED
@@ -89,6 +89,45 @@ export declare const THEOREM_UI_CATALOG: {
89
89
  readonly defaultMessage: "Set it aside to send later.";
90
90
  readonly description: "Send menu item detail: the message waits in the composer until sent.";
91
91
  };
92
+ readonly '@theorem.composer.menu.queue.gated.description': {
93
+ readonly defaultMessage: "Send it once you answer the waiting step.";
94
+ readonly description: "Send menu item detail while a step waits for approval: the message waits for the answer.";
95
+ };
96
+ readonly '@theorem.composer.menu.send_now.gated.description': {
97
+ readonly defaultMessage: "Cancel the waiting step and send this instead.";
98
+ readonly description: "Send menu item detail while a step waits for approval: ends the wait, then sends.";
99
+ };
100
+ readonly '@theorem.composer.send_menu': {
101
+ readonly defaultMessage: "Send options";
102
+ readonly description: "The row composer's button while a reply runs: it opens the send menu.";
103
+ };
104
+ readonly '@theorem.composer.pill.working': {
105
+ readonly defaultMessage: "Working";
106
+ readonly description: "The row composer's pill while the agent replies, before its start is known.";
107
+ };
108
+ readonly '@theorem.composer.pill.working_for': {
109
+ readonly defaultMessage: "Working for {duration}";
110
+ readonly description: "The row composer's pill while the agent replies, with how long it has run.";
111
+ readonly params: readonly ["duration"];
112
+ };
113
+ readonly '@theorem.composer.tray.expand': {
114
+ readonly defaultMessage: "Expand {label}";
115
+ readonly description: "Names the row composer's tray toggle while the tray is folded.";
116
+ readonly params: readonly ["label"];
117
+ };
118
+ readonly '@theorem.composer.tray.collapse': {
119
+ readonly defaultMessage: "Collapse {label}";
120
+ readonly description: "Names the row composer's tray toggle while the tray is open.";
121
+ readonly params: readonly ["label"];
122
+ };
123
+ readonly '@theorem.composer.pill.stop': {
124
+ readonly defaultMessage: "Stop";
125
+ readonly description: "The stop button on the working pill.";
126
+ };
127
+ readonly '@theorem.composer.pill.background': {
128
+ readonly defaultMessage: "Running in the background";
129
+ readonly description: "Read by screen readers on a background job pill, after its name.";
130
+ };
92
131
  readonly '@theorem.composer.hint.stash-selected-draft.message': {
93
132
  readonly defaultMessage: "Replacing this?";
94
133
  readonly description: "Hint when the whole draft is selected and could be stashed.";
package/ui/labels.js CHANGED
@@ -76,6 +76,45 @@ export const THEOREM_UI_CATALOG = {
76
76
  defaultMessage: 'Set it aside to send later.',
77
77
  description: 'Send menu item detail: the message waits in the composer until sent.',
78
78
  },
79
+ '@theorem.composer.menu.queue.gated.description': {
80
+ defaultMessage: 'Send it once you answer the waiting step.',
81
+ description: 'Send menu item detail while a step waits for approval: the message waits for the answer.',
82
+ },
83
+ '@theorem.composer.menu.send_now.gated.description': {
84
+ defaultMessage: 'Cancel the waiting step and send this instead.',
85
+ description: 'Send menu item detail while a step waits for approval: ends the wait, then sends.',
86
+ },
87
+ '@theorem.composer.send_menu': {
88
+ defaultMessage: 'Send options',
89
+ description: "The row composer's button while a reply runs: it opens the send menu.",
90
+ },
91
+ '@theorem.composer.pill.working': {
92
+ defaultMessage: 'Working',
93
+ description: "The row composer's pill while the agent replies, before its start is known.",
94
+ },
95
+ '@theorem.composer.pill.working_for': {
96
+ defaultMessage: 'Working for {duration}',
97
+ description: "The row composer's pill while the agent replies, with how long it has run.",
98
+ params: ['duration'],
99
+ },
100
+ '@theorem.composer.tray.expand': {
101
+ defaultMessage: 'Expand {label}',
102
+ description: "Names the row composer's tray toggle while the tray is folded.",
103
+ params: ['label'],
104
+ },
105
+ '@theorem.composer.tray.collapse': {
106
+ defaultMessage: 'Collapse {label}',
107
+ description: "Names the row composer's tray toggle while the tray is open.",
108
+ params: ['label'],
109
+ },
110
+ '@theorem.composer.pill.stop': {
111
+ defaultMessage: 'Stop',
112
+ description: 'The stop button on the working pill.',
113
+ },
114
+ '@theorem.composer.pill.background': {
115
+ defaultMessage: 'Running in the background',
116
+ description: 'Read by screen readers on a background job pill, after its name.',
117
+ },
79
118
  '@theorem.composer.hint.stash-selected-draft.message': {
80
119
  defaultMessage: 'Replacing this?',
81
120
  description: 'Hint when the whole draft is selected and could be stashed.',