@gemies/sdk 10.4.0 → 10.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 10.7.0
4
+
5
+ ### A turn is sent once
6
+
7
+ Every chat turn request now carries an `Idempotency-Key` equal to the turn's own id, the id the
8
+ server already names the turn by. A request that reaches the API twice (a replay after a token
9
+ refresh, a dropped response, a retry through another instance) starts the turn once. When the server
10
+ answers the second one from its receipt (`Idempotency-Replayed: true`), the SDK resumes the first
11
+ request's stream (`GET /v1/chat/turns/:turnId/stream`, 10.3.0) from its beginning. If that stream
12
+ cannot be followed to its end, the person's message is kept and no Retry is offered, since it would
13
+ send the message again. Requires the API of ADR 0049, which lists the header in CORS and answers
14
+ the replay.
15
+
16
+ ## 10.6.0
17
+
18
+ `isDeviceModelId` also accepts `computer/<model>`, the ChatGPT on the person's own computer that
19
+ Gemies lists with their device models when it is switched on and its daemon is connected: it is
20
+ kept as the choice while connected and replaced by `auto` when it is not, like a `local/` model.
21
+
22
+ ## 10.5.0
23
+
24
+ ### A coding agent's work, as one row, with a command's output
25
+
26
+ A turn in which a coding agent on the person's computer (Codex, Claude Code, OpenCode) used tools
27
+ now draws ONE work row, "Worked for 12s · 5 steps", closed until pressed (`AgentWork`; the pure
28
+ model is `buildAgentWork`, exported from `@gemies/sdk/model`). Open, each step is a line: its glyph,
29
+ what it is (the command, the path), where it stands (running, done, failed, declined, stopped) and
30
+ how long it took. Domain cards (weather, charts…) and a model's own tools draw as they did; only an
31
+ external agent's steps (`ext_…` call ids) are grouped.
32
+
33
+ A command's line opens to its output (`CommandOutput`): monospace, terminal escapes removed, tail
34
+ following with "Jump to latest" once the reader scrolls up, "Earlier output not shown" when it was
35
+ cut to its tail, and Copy. A running command's output is followed live on the new realtime topic
36
+ `step-output:<conversation>:<call>` (`useStepOutput`, the `step.output` signal) **only while its line
37
+ is open**; a closed line receives its status alone, and a finished command shows the output stored
38
+ with it, so it reads the same after a reload.
39
+
40
+ `useRealtimeTopic` takes the signal `type` it listens for (default `agent.activity`). Needs an API
41
+ that carries command output (this release's `@alia/api`); against an older API the steps are drawn
42
+ without output. New words: `work.*` (en, es).
43
+
44
+ An edit step whose call carries the files it changed opens the diff viewer (10.2.0) on that step's
45
+ files; the turn's "N files changed" chip stays, opening it on all of them.
46
+
3
47
  ## 10.4.0
4
48
 
5
49
  ### Richer answers to a coding CLI's permission questions
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "10.4.0",
3
+ "version": "10.7.0",
4
4
  "description": "The Gemies SDK: the conversation runtime, chat UI, voice calls and dictation for Oxy apps that talk to a gemie",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -0,0 +1,262 @@
1
+ import { Item } from '@oxy.so/bloom/item';
2
+ import { Loading } from '@oxy.so/bloom/loading';
3
+ import { RiArrowDownSLine } from '@oxy.so/bloom/icons/RiArrowDownSLine';
4
+ import { RiArrowRightSLine } from '@oxy.so/bloom/icons/RiArrowRightSLine';
5
+ import { RiCheckboxCircleLine } from '@oxy.so/bloom/icons/RiCheckboxCircleLine';
6
+ import { RiCloseCircleLine } from '@oxy.so/bloom/icons/RiCloseCircleLine';
7
+ import { RiEditLine } from '@oxy.so/bloom/icons/RiEditLine';
8
+ import { RiFileTextLine } from '@oxy.so/bloom/icons/RiFileTextLine';
9
+ import { RiForbidLine } from '@oxy.so/bloom/icons/RiForbidLine';
10
+ import { RiGlobalLine } from '@oxy.so/bloom/icons/RiGlobalLine';
11
+ import { RiSearchLine } from '@oxy.so/bloom/icons/RiSearchLine';
12
+ import { RiTerminalBoxLine } from '@oxy.so/bloom/icons/RiTerminalBoxLine';
13
+ import { RiToolsLine } from '@oxy.so/bloom/icons/RiToolsLine';
14
+ import { useTheme } from '@oxy.so/bloom/theme';
15
+ import { Muted } from '@oxy.so/bloom/typography';
16
+ import { useEffect, useState } from 'react';
17
+ import { StyleSheet, View } from 'react-native';
18
+ import { useLabels } from '../../lib/labels';
19
+ import {
20
+ type AgentStep,
21
+ type AgentStepKind,
22
+ type AgentWork as AgentWorkLog,
23
+ formatStepDuration,
24
+ workElapsedMs,
25
+ } from '../../runtime/thread/agent-work';
26
+ import { fileChangeTotals } from '../../runtime/thread/file-changes';
27
+ import { formatElapsed } from '../../runtime/thread/thought-utils';
28
+ import { useStepOutput } from '../../runtime/use-step-output';
29
+ import { FileChangesViewer } from '../diff/FileChangesViewer';
30
+ import { CommandOutput } from './CommandOutput';
31
+
32
+ const KIND_ICONS = {
33
+ command: RiTerminalBoxLine,
34
+ read: RiFileTextLine,
35
+ edit: RiEditLine,
36
+ search: RiSearchLine,
37
+ web: RiGlobalLine,
38
+ tool: RiToolsLine,
39
+ } satisfies Record<AgentStepKind, unknown>;
40
+
41
+ /** The clock a running log ticks on, once a second, only while something runs. */
42
+ function useNow(active: boolean): number {
43
+ const [now, setNow] = useState(() => Date.now());
44
+ useEffect(() => {
45
+ if (!active) return;
46
+ setNow(Date.now());
47
+ const timer = setInterval(() => setNow(Date.now()), 1000);
48
+ return () => clearInterval(timer);
49
+ }, [active]);
50
+ return now;
51
+ }
52
+
53
+ export interface AgentWorkProps {
54
+ work: AgentWorkLog;
55
+ /** The conversation the turn is in: a step's live output is followed on its topic. */
56
+ conversationId: string | null | undefined;
57
+ }
58
+
59
+ /**
60
+ * What a coding agent did in a turn, as ONE row: "Worked for 12s · 5 steps", closed until it is
61
+ * pressed. Open, each step is a line — its glyph, what it is (the command, the path), where it
62
+ * stands and how long it took — and a command's line opens to its output, an edit's line to the
63
+ * diff viewer on the files it changed.
64
+ *
65
+ * A step's output is followed live only while its line is open and its command still runs; a
66
+ * closed line costs nothing but the status the turn's own stream carries. A finished command shows
67
+ * the output that was stored with it, so it reads the same after a reload.
68
+ */
69
+ export function AgentWork({ work, conversationId }: AgentWorkProps) {
70
+ const { t } = useLabels();
71
+ const { colors } = useTheme();
72
+ const [open, setOpen] = useState(false);
73
+ const [openSteps, setOpenSteps] = useState<ReadonlySet<string>>(new Set());
74
+ const now = useNow(work.running > 0);
75
+
76
+ const elapsed = workElapsedMs(work, now);
77
+ const steps = t('work.steps', { count: work.steps.length });
78
+ const running = work.running > 0;
79
+ const title =
80
+ elapsed === undefined
81
+ ? t(running ? 'work.working' : 'work.worked', { steps })
82
+ : t(running ? 'work.workingFor' : 'work.workedFor', {
83
+ elapsed: formatElapsed(elapsed),
84
+ steps,
85
+ });
86
+ const Chevron = open ? RiArrowDownSLine : RiArrowRightSLine;
87
+ const toggleStep = (id: string) =>
88
+ setOpenSteps((current) => {
89
+ const next = new Set(current);
90
+ if (!next.delete(id)) next.add(id);
91
+ return next;
92
+ });
93
+
94
+ return (
95
+ <View>
96
+ <Item
97
+ density="compact"
98
+ leading={
99
+ running ? (
100
+ <Loading size="sm" iconSize={14} />
101
+ ) : work.failed > 0 ? (
102
+ <RiCloseCircleLine size="sm" fill={colors.error} />
103
+ ) : (
104
+ <RiCheckboxCircleLine size="sm" fill={colors.success} />
105
+ )
106
+ }
107
+ title={title}
108
+ trailing={
109
+ <View style={styles.trailing}>
110
+ {work.failed > 0 ? (
111
+ <Muted>{t('work.failedCount', { count: work.failed })}</Muted>
112
+ ) : null}
113
+ <Chevron size="sm" fill={colors.textSecondary} />
114
+ </View>
115
+ }
116
+ expanded={open}
117
+ onPress={() => setOpen((value) => !value)}
118
+ accessibilityLabel={title}
119
+ />
120
+ {open ? (
121
+ <View role="list" style={styles.steps}>
122
+ {work.steps.map((step) => (
123
+ <AgentStepRow
124
+ key={step.id}
125
+ step={step}
126
+ conversationId={conversationId}
127
+ now={now}
128
+ expanded={openSteps.has(step.id)}
129
+ onToggle={() => toggleStep(step.id)}
130
+ />
131
+ ))}
132
+ </View>
133
+ ) : null}
134
+ </View>
135
+ );
136
+ }
137
+
138
+ function AgentStepRow({
139
+ step,
140
+ conversationId,
141
+ now,
142
+ expanded,
143
+ onToggle,
144
+ }: {
145
+ step: AgentStep;
146
+ conversationId: string | null | undefined;
147
+ now: number;
148
+ expanded: boolean;
149
+ onToggle: () => void;
150
+ }) {
151
+ const { t } = useLabels();
152
+ const { colors } = useTheme();
153
+ const Icon = KIND_ICONS[step.kind];
154
+ const failed = step.status === 'failed';
155
+ const word =
156
+ step.status === 'failed'
157
+ ? t('work.failed')
158
+ : step.status === 'declined'
159
+ ? t('work.declined')
160
+ : step.status === 'interrupted'
161
+ ? t('work.interrupted')
162
+ : null;
163
+ const duration =
164
+ step.durationMs !== undefined
165
+ ? formatStepDuration(step.durationMs)
166
+ : step.status === 'running' && step.startedAt !== undefined
167
+ ? formatStepDuration(now - step.startedAt)
168
+ : null;
169
+ const title = step.target ?? step.tool;
170
+ // An edit that recorded its files opens the diff viewer on them; a command opens its output.
171
+ const [viewing, setViewing] = useState(false);
172
+ const totals = step.changes.length > 0 ? fileChangeTotals(step.changes) : null;
173
+ const press = totals !== null ? () => setViewing(true) : step.hasOutput ? onToggle : undefined;
174
+ const Chevron = expanded && totals === null ? RiArrowDownSLine : RiArrowRightSLine;
175
+ const label = [
176
+ title,
177
+ word,
178
+ totals === null
179
+ ? null
180
+ : t('chat.fileChanges.open', {
181
+ count: totals.files,
182
+ additions: totals.additions,
183
+ deletions: totals.deletions,
184
+ }),
185
+ ]
186
+ .filter((part) => part !== null)
187
+ .join(', ');
188
+
189
+ return (
190
+ <View role="listitem">
191
+ <Item
192
+ density="compact"
193
+ leading={
194
+ step.status === 'running' ? (
195
+ <Loading size="sm" iconSize={14} />
196
+ ) : step.status === 'declined' || step.status === 'interrupted' ? (
197
+ <RiForbidLine size="sm" fill={colors.textSecondary} />
198
+ ) : (
199
+ <Icon size="sm" fill={failed ? colors.error : colors.text} />
200
+ )
201
+ }
202
+ title={title}
203
+ subtitle={step.target === undefined ? undefined : step.tool}
204
+ destructive={failed}
205
+ trailing={
206
+ <View style={styles.trailing}>
207
+ {word === null ? null : <Muted>{word}</Muted>}
208
+ {totals === null ? null : <Muted>{`+${totals.additions} −${totals.deletions}`}</Muted>}
209
+ {duration === null ? null : <Muted>{duration}</Muted>}
210
+ {press === undefined ? null : <Chevron size="sm" fill={colors.textSecondary} />}
211
+ </View>
212
+ }
213
+ expanded={totals === null && step.hasOutput ? expanded : undefined}
214
+ onPress={press}
215
+ accessibilityLabel={label}
216
+ />
217
+ {totals === null && step.hasOutput && expanded ? (
218
+ <StepOutputPanel step={step} conversationId={conversationId} />
219
+ ) : null}
220
+ {viewing ? (
221
+ <FileChangesViewer
222
+ changes={step.changes}
223
+ open={viewing}
224
+ onClose={() => setViewing(false)}
225
+ />
226
+ ) : null}
227
+ </View>
228
+ );
229
+ }
230
+
231
+ /**
232
+ * An open command's output. Mounted only while the line is open, so the topic it follows is
233
+ * released the moment the line is closed.
234
+ */
235
+ function StepOutputPanel({
236
+ step,
237
+ conversationId,
238
+ }: {
239
+ step: AgentStep;
240
+ conversationId: string | null | undefined;
241
+ }) {
242
+ const { t } = useLabels();
243
+ const running = step.status === 'running';
244
+ const live = useStepOutput(conversationId, step.id, running);
245
+ return (
246
+ <View style={styles.output}>
247
+ <CommandOutput
248
+ output={running ? (live ?? step.output ?? null) : (step.output ?? null)}
249
+ running={running}
250
+ />
251
+ {step.exitCode !== undefined && step.exitCode !== 0 ? (
252
+ <Muted>{t('work.exitCode', { code: step.exitCode })}</Muted>
253
+ ) : null}
254
+ </View>
255
+ );
256
+ }
257
+
258
+ const styles = StyleSheet.create({
259
+ trailing: { flexDirection: 'row', alignItems: 'center', gap: 6 },
260
+ steps: { paddingLeft: 12 },
261
+ output: { paddingLeft: 12, paddingBottom: 8, gap: 4 },
262
+ });
@@ -0,0 +1,106 @@
1
+ import { Button } from '@oxy.so/bloom/button';
2
+ import { Pre } from '@oxy.so/bloom/code';
3
+ import { Muted } from '@oxy.so/bloom/typography';
4
+ import { useCallback, useMemo, useRef, useState } from 'react';
5
+ import {
6
+ type NativeScrollEvent,
7
+ type NativeSyntheticEvent,
8
+ ScrollView,
9
+ type ScrollViewInstance,
10
+ StyleSheet,
11
+ View,
12
+ } from 'react-native';
13
+ import { copyText } from '../../lib/clipboard';
14
+ import { useLabels } from '../../lib/labels';
15
+ import { displayOutput } from '../../runtime/thread/command-output';
16
+ import type { StepOutput } from '../../runtime/thread/agent-work';
17
+
18
+ /** How far from the end still counts as following it. */
19
+ const FOLLOW_SLACK_PX = 24;
20
+ const MAX_HEIGHT = 240;
21
+
22
+ export interface CommandOutputProps {
23
+ /** What the command printed, as far as known; `null` before anything arrived. */
24
+ output: StepOutput | null;
25
+ /** The command is still running: more may come. */
26
+ running: boolean;
27
+ }
28
+
29
+ /**
30
+ * What one command printed: monospace, escapes removed, the tail of it, with Copy.
31
+ *
32
+ * It follows the end while the reader is at the end: output that arrives scrolls in. Scroll up to
33
+ * read something and it stops following and offers "Jump to latest", so reading is never fought
34
+ * by the next line. Output cut to its tail says so above it.
35
+ *
36
+ * It draws what it is given and knows nothing of how it arrives: the step mounts it when opened
37
+ * and hands it the live output (`useStepOutput`) or what was stored.
38
+ */
39
+ export function CommandOutput({ output, running }: CommandOutputProps) {
40
+ const { t } = useLabels();
41
+ const scroll = useRef<ScrollViewInstance>(null);
42
+ const following = useRef(true);
43
+ const [away, setAway] = useState(false);
44
+ const raw = output?.text ?? '';
45
+ const text = useMemo(() => displayOutput(raw), [raw]);
46
+
47
+ const onScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
48
+ const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
49
+ const atEnd =
50
+ contentSize.height - (contentOffset.y + layoutMeasurement.height) <= FOLLOW_SLACK_PX;
51
+ following.current = atEnd;
52
+ setAway(!atEnd);
53
+ }, []);
54
+
55
+ const onContentSizeChange = useCallback(() => {
56
+ if (following.current) scroll.current?.scrollToEnd({ animated: false });
57
+ }, []);
58
+
59
+ const jumpToLatest = useCallback(() => {
60
+ following.current = true;
61
+ setAway(false);
62
+ scroll.current?.scrollToEnd({ animated: true });
63
+ }, []);
64
+
65
+ if (text === '') {
66
+ return <Muted>{running ? t('work.waitingOutput') : t('work.noOutput')}</Muted>;
67
+ }
68
+
69
+ return (
70
+ <View style={styles.root}>
71
+ <View style={styles.header}>
72
+ {output?.truncated ? <Muted>{t('work.outputTruncated')}</Muted> : <View />}
73
+ <Button appearance="plain" tone="neutral" size="xs" onPress={() => void copyText(text, t)}>
74
+ {t('work.copy')}
75
+ </Button>
76
+ </View>
77
+ <View>
78
+ <ScrollView
79
+ ref={scroll}
80
+ style={styles.scroll}
81
+ nestedScrollEnabled
82
+ scrollEventThrottle={32}
83
+ onScroll={onScroll}
84
+ onContentSizeChange={onContentSizeChange}
85
+ testID="command-output-scroll"
86
+ >
87
+ <Pre selectable>{text}</Pre>
88
+ </ScrollView>
89
+ {away ? (
90
+ <View style={styles.jump}>
91
+ <Button appearance="outline" tone="neutral" size="xs" onPress={jumpToLatest}>
92
+ {t('work.jumpToLatest')}
93
+ </Button>
94
+ </View>
95
+ ) : null}
96
+ </View>
97
+ </View>
98
+ );
99
+ }
100
+
101
+ const styles = StyleSheet.create({
102
+ root: { gap: 4 },
103
+ header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
104
+ scroll: { maxHeight: MAX_HEIGHT },
105
+ jump: { position: 'absolute', right: 8, bottom: 8 },
106
+ });
@@ -36,9 +36,11 @@ import { isWebInvocation, taskListLog, webSearchLog } from '../../lib/work-log';
36
36
  import { useGemieRuntime } from '../../runtime/config';
37
37
  import {
38
38
  type Message,
39
+ buildAgentWork,
39
40
  cardOf,
40
41
  formatElapsed,
41
42
  getToolPillLabel,
43
+ isExternalStep,
42
44
  turnFileChanges,
43
45
  } from '../../runtime/model';
44
46
  import type { OpenThought } from '../../hooks/useOpenThought';
@@ -46,6 +48,7 @@ import { PlanPreviewCard } from '../PlanPreviewCard';
46
48
  import { AskedQuestions } from '../QuestionCard';
47
49
  import { CanvasComponent } from '../canvas/CanvasComponent';
48
50
  import { ReplyMarkdown } from '../ReplyMarkdown';
51
+ import { AgentWork } from './AgentWork';
49
52
  import { MessageBlockBoundary } from './MessageBlockBoundary';
50
53
  import { FileChangesCard } from '../diff/FileChangesCard';
51
54
  import { ToolResultCard } from './ToolResultCard';
@@ -219,6 +222,7 @@ export const ThreadRow = memo(function ThreadRow({
219
222
  isLastReply={isLastReply}
220
223
  isLoading={isLoading}
221
224
  storedIn={storedIn}
225
+ conversationId={conversationId}
222
226
  actions={actions}
223
227
  copyAction={copyAction}
224
228
  readAloudState={readAloudState}
@@ -238,6 +242,8 @@ interface ReplyTurnProps {
238
242
  isLastReply: boolean;
239
243
  isLoading: boolean;
240
244
  storedIn: string | undefined;
245
+ /** The conversation the turn is in, saved or not: a running step's output is followed under it. */
246
+ conversationId: string | undefined;
241
247
  actions: ThreadActions;
242
248
  copyAction: AiChatTurnAction | null;
243
249
  readAloudState: ReadAloudState;
@@ -254,6 +260,7 @@ function ReplyTurn({
254
260
  isLastReply,
255
261
  isLoading,
256
262
  storedIn,
263
+ conversationId,
257
264
  actions,
258
265
  copyAction,
259
266
  readAloudState,
@@ -321,8 +328,13 @@ function ReplyTurn({
321
328
 
322
329
  // The calls the work summary lists: every one that did not draw its own card. Read on each
323
330
  // render — the list changes per streamed tool event and the row is memoised on `message`.
331
+ // An external agent's steps are not in it: they are their own work log, whatever draws the turn.
324
332
  const workInvocations = toolInvocations.filter(
325
- (call) => cardOf(call) === null && !isQuestionInvocation(call) && !renderedCalls.has(call),
333
+ (call) =>
334
+ cardOf(call) === null &&
335
+ !isQuestionInvocation(call) &&
336
+ !renderedCalls.has(call) &&
337
+ !isExternalStep(call),
326
338
  );
327
339
  const questions = toolInvocations.flatMap((call) => askedQuestions(call) ?? []);
328
340
  const toolCards = toolInvocations.flatMap((call, index) => {
@@ -334,6 +346,8 @@ function ReplyTurn({
334
346
  const fileChanges = turnFileChanges(toolInvocations);
335
347
  /** The template swaps the steps for the reply once the turn is done. */
336
348
  const turnWorking = isLoading && isLastReply && message.isStreaming === true;
349
+ // What a coding agent on the person's computer did: one row, whoever's turn it is.
350
+ const agentWork = buildAgentWork(toolInvocations, turnWorking);
337
351
 
338
352
  // Where the turn went — searches, page visits, research — as a `WebSearch` trail with its
339
353
  // sources, and everything else it did as a `TaskList`. Both are driven by `revealed` from the
@@ -426,6 +440,7 @@ function ReplyTurn({
426
440
  agent !== undefined ||
427
441
  text.length > 0 ||
428
442
  hasWorkLog ||
443
+ agentWork !== null ||
429
444
  toolCards.length > 0 ||
430
445
  fileChanges.length > 0 ||
431
446
  rendered.length > 0 ||
@@ -535,6 +550,11 @@ function ReplyTurn({
535
550
  onPress={viewDetails}
536
551
  />
537
552
  )}
553
+ {agentWork === null ? null : (
554
+ <MessageBlockBoundary>
555
+ <AgentWork work={agentWork} conversationId={conversationId} />
556
+ </MessageBlockBoundary>
557
+ )}
538
558
  {taskLog === null ? null : (
539
559
  <TaskList
540
560
  tasks={taskLog.tasks}
@@ -530,4 +530,19 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
530
530
  'weather.condition.snow-showers': 'Snow showers',
531
531
  'weather.condition.thunderstorm': 'Thunderstorm',
532
532
  'weather.toggleUnit': 'Switch temperature unit',
533
+ 'work.copy': 'Copy output',
534
+ 'work.declined': 'Declined',
535
+ 'work.exitCode': 'Exit code {{code}}',
536
+ 'work.failed': 'Failed',
537
+ 'work.failedCount': { one: '1 failed', other: '{{count}} failed' },
538
+ 'work.interrupted': 'Stopped',
539
+ 'work.jumpToLatest': 'Jump to latest',
540
+ 'work.noOutput': 'No output',
541
+ 'work.outputTruncated': 'Earlier output not shown',
542
+ 'work.steps': { one: '1 step', other: '{{count}} steps' },
543
+ 'work.waitingOutput': 'No output yet',
544
+ 'work.worked': 'Worked · {{steps}}',
545
+ 'work.workedFor': 'Worked for {{elapsed}} · {{steps}}',
546
+ 'work.working': 'Working · {{steps}}',
547
+ 'work.workingFor': 'Working for {{elapsed}} · {{steps}}',
533
548
  };
@@ -535,4 +535,19 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
535
535
  'weather.condition.snow-showers': 'Chubascos de nieve',
536
536
  'weather.condition.thunderstorm': 'Tormenta',
537
537
  'weather.toggleUnit': 'Cambiar unidad de temperatura',
538
+ 'work.copy': 'Copiar salida',
539
+ 'work.declined': 'Rechazado',
540
+ 'work.exitCode': 'Código de salida {{code}}',
541
+ 'work.failed': 'Falló',
542
+ 'work.failedCount': { one: '1 con error', other: '{{count}} con error' },
543
+ 'work.interrupted': 'Detenido',
544
+ 'work.jumpToLatest': 'Ir a lo último',
545
+ 'work.noOutput': 'Sin salida',
546
+ 'work.outputTruncated': 'No se muestra la salida anterior',
547
+ 'work.steps': { one: '1 paso', other: '{{count}} pasos' },
548
+ 'work.waitingOutput': 'Aún sin salida',
549
+ 'work.worked': 'Trabajó · {{steps}}',
550
+ 'work.workedFor': 'Trabajó durante {{elapsed}} · {{steps}}',
551
+ 'work.working': 'Trabajando · {{steps}}',
552
+ 'work.workingFor': 'Trabajando durante {{elapsed}} · {{steps}}',
538
553
  };
@@ -12,11 +12,16 @@ import type { Message } from '../runtime/types';
12
12
  export const REALTIME_EVENT = 'rt';
13
13
  /** Client → server: catch up from a cursor. */
14
14
  export const REALTIME_SYNC = 'rt:sync';
15
- /** Client → server: follow a topic (`agent:<id>`, `agent-session:<id>`). */
15
+ /** Client → server: follow a topic (`agent:<id>`, `agent-session:<id>`, `step-output:<conversation>:<call>`). */
16
16
  export const REALTIME_SUBSCRIBE = 'rt:subscribe';
17
17
  /** Client → server: stop following a topic. */
18
18
  export const REALTIME_UNSUBSCRIBE = 'rt:unsubscribe';
19
19
 
20
+ /** What a client names to follow one command step's output (the API's `stepOutputTopic`). */
21
+ export function stepOutputTopic(conversationId: string, toolCallId: string): string {
22
+ return `step-output:${conversationId}:${toolCallId}`;
23
+ }
24
+
20
25
  /** Durable: numbered per account, replayed to a client that reconnects. */
21
26
  export const REALTIME_DURABLE_TYPES = [
22
27
  'conversation',
@@ -36,6 +41,7 @@ export const REALTIME_SIGNAL_TYPES = [
36
41
  'presence',
37
42
  'runtimes',
38
43
  'agent.activity',
44
+ 'step.output',
39
45
  ] as const;
40
46
 
41
47
  export type RealtimeDurableType = (typeof REALTIME_DURABLE_TYPES)[number];
@@ -150,6 +156,17 @@ export interface RealtimeData {
150
156
  readonly sessionId: string;
151
157
  readonly agentId: string;
152
158
  };
159
+ /**
160
+ * What a command step has printed, on `step-output:<conversation>:<call>`: the TAIL of its
161
+ * output so far, whole (a late follower is right again on the next frame), never a diff.
162
+ */
163
+ 'step.output': {
164
+ readonly conversationId: string;
165
+ readonly toolCallId: string;
166
+ readonly text: string;
167
+ /** Output before `text` was dropped. */
168
+ readonly truncated: boolean;
169
+ };
153
170
  }
154
171
 
155
172
  const TYPES: ReadonlySet<string> = new Set<string>([
@@ -21,7 +21,7 @@ import {
21
21
  import { useRealtimeActivityStore } from './activity';
22
22
  import { attachRealtimeStore } from './store';
23
23
  import { acquireRealtime, type RealtimeConnection, type RealtimeListener } from './connection';
24
- import type { RealtimeActivity, RealtimeFrame, RealtimeType } from './contract';
24
+ import type { RealtimeActivity, RealtimeFrame, RealtimeSignalType, RealtimeType } from './contract';
25
25
 
26
26
  interface RealtimeHold {
27
27
  readonly apiUrl: string;
@@ -158,12 +158,15 @@ export function useRealtimeReset(handler: () => void): void {
158
158
  }
159
159
 
160
160
  /**
161
- * Follow a topic (`agent:<id>`, `agent-session:<id>`) while mounted, and hear its frames. The
162
- * server checks the person may; a refused topic simply never speaks.
161
+ * Follow a topic (`agent:<id>`, `agent-session:<id>`, `step-output:<conversation>:<call>`) while
162
+ * mounted, and hear its frames of one `type` (an agent run's detail by default). The server checks
163
+ * the person may; a refused topic simply never speaks. A `null` topic follows nothing: that is how
164
+ * a caller says "not now", and the subscription is released.
163
165
  */
164
166
  export function useRealtimeTopic(
165
167
  topic: string | null,
166
168
  handler: (frame: RealtimeFrame) => void,
169
+ type: RealtimeSignalType = 'agent.activity',
167
170
  ): void {
168
171
  const connection = useGemieRealtime();
169
172
  const ref = useRef(handler);
@@ -171,14 +174,14 @@ export function useRealtimeTopic(
171
174
  useEffect(() => {
172
175
  if (!connection || !topic) return;
173
176
  const release = connection.follow(topic);
174
- const off = connection.on('agent.activity', (frame) => {
177
+ const off = connection.on(type, (frame) => {
175
178
  if (frame.topic === topic) ref.current(frame);
176
179
  });
177
180
  return () => {
178
181
  off();
179
182
  release();
180
183
  };
181
- }, [connection, topic]);
184
+ }, [connection, topic, type]);
182
185
  }
183
186
 
184
187
  /**
@@ -13,7 +13,9 @@ export * from './power-levels';
13
13
  export { englishCopy } from '../lib/copy';
14
14
  export type { Translate } from '../lib/copy';
15
15
  export * from './thread/agent-activity';
16
+ export * from './thread/agent-work';
16
17
  export * from './thread/automation-labels';
18
+ export * from './thread/command-output';
17
19
  export * from './thread/conversation-export';
18
20
  export * from './thread/file-changes';
19
21
  export * from './thread/message-days';
@@ -22,9 +22,16 @@ export function isPowerLevel(value: unknown): value is PowerLevel {
22
22
  return typeof value === 'string' && (POWER_LEVELS as readonly string[]).includes(value);
23
23
  }
24
24
 
25
- /** A model served by one of the person's own devices. */
25
+ /**
26
+ * A model served by one of the person's own devices: `local/<runtime>/<model>`, or the ChatGPT on
27
+ * their computer that Gemies offers when its daemon is connected (`computer/chatgpt`, ADR 0047).
28
+ */
26
29
  export function isDeviceModelId(value: unknown): value is string {
27
- return typeof value === 'string' && value.startsWith('local/') && value.length > 'local/'.length;
30
+ return (
31
+ typeof value === 'string' &&
32
+ ((value.startsWith('local/') && value.length > 'local/'.length) ||
33
+ (value.startsWith('computer/') && value.length > 'computer/'.length))
34
+ );
28
35
  }
29
36
 
30
37
  export interface ModeSelection {
@@ -72,8 +72,12 @@ function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
72
72
  }
73
73
 
74
74
  export interface ResumableFrameSourceOptions {
75
- /** The turn's first response, already known to be `ok` with a body. */
76
- response: Response;
75
+ /**
76
+ * The turn's first response, already known to be `ok` with a body; or null when the server said it
77
+ * already has this turn (ADR 0049) and there is no first stream: reading starts by resuming it
78
+ * from its first frame.
79
+ */
80
+ response: Response | null;
77
81
  /** Open the turn's stream again, after the frame numbered `cursor`. */
78
82
  reconnect(cursor: number, signal: AbortSignal): Promise<Response>;
79
83
  /** The turn's own signal: a Stop or a detach ends the stream, never a resume. */
@@ -176,7 +180,7 @@ export function createResumableFrameSource(
176
180
  else options.signal.addEventListener('abort', followTurn, { once: true });
177
181
  const { signal } = lifetime;
178
182
 
179
- let reader = options.response.body?.getReader();
183
+ let reader = options.response?.body?.getReader();
180
184
  let decoder = new TextDecoder();
181
185
  let frames = createSseFrameReader();
182
186
  /** The number of the newest frame passed on. */
@@ -277,17 +281,20 @@ export function createResumableFrameSource(
277
281
  while (true) {
278
282
  failure = undefined;
279
283
  try {
280
- if (!reader) return { done: true };
281
- const { done, value } = await reader.read();
282
- if (!done) {
283
- const accepted = accept(frames.push(decoder.decode(value, { stream: true })));
284
- if (accepted.length > 0) {
285
- attempts = 0;
286
- return { done: false, frames: accepted };
284
+ if (reader) {
285
+ const { done, value } = await reader.read();
286
+ if (!done) {
287
+ const accepted = accept(frames.push(decoder.decode(value, { stream: true })));
288
+ if (accepted.length > 0) {
289
+ attempts = 0;
290
+ return { done: false, frames: accepted };
291
+ }
292
+ continue;
287
293
  }
288
- continue;
294
+ if (sawTerminal) return { done: true };
295
+ } else if (options.response !== null) {
296
+ return { done: true };
289
297
  }
290
- if (sawTerminal) return { done: true };
291
298
  } catch (error) {
292
299
  if (signal.aborted) throw error;
293
300
  failure = error;
@@ -0,0 +1,192 @@
1
+ import { toolCallStatus } from '../../lib/tool-call-status';
2
+ import type { ToolInvocation } from '../types';
3
+ import { type CallFileChange, fileChangesOf } from './file-changes';
4
+
5
+ /**
6
+ * What a coding agent did in a turn, as one work log: the tool calls of an external agent
7
+ * (Codex, Claude Code, OpenCode on the person's computer, ADR 0043 §5) in the order they started,
8
+ * each a step with what it is, where it stands and how long it took.
9
+ *
10
+ * Pure: the stored invocations go in, the log the thread draws comes out. A turn has ONE log, not
11
+ * one per run of consecutive calls: the turn stores its calls beside its text, not between, so the
12
+ * text cannot split a run. Calls that draw their own card (weather, a chart, a question) are not
13
+ * steps; they never are an external agent's.
14
+ */
15
+
16
+ /**
17
+ * An external agent's step is stored under its CLI's own id with this prefix (the API's
18
+ * `EXTERNAL_STEP_PREFIX`), which is how a step of one is told from a tool of the turn's own model.
19
+ */
20
+ export const EXTERNAL_STEP_PREFIX = 'ext_';
21
+
22
+ export function isExternalStep(call: Pick<ToolInvocation, 'toolCallId'>): boolean {
23
+ return call.toolCallId.startsWith(EXTERNAL_STEP_PREFIX);
24
+ }
25
+
26
+ /** What kind of work a step is: it picks the glyph, and whether the step has output to show. */
27
+ export type AgentStepKind = 'command' | 'read' | 'edit' | 'search' | 'web' | 'tool';
28
+
29
+ /**
30
+ * - `running`: still going in a live turn.
31
+ * - `ok`: it finished.
32
+ * - `failed`: it finished with an error (a CLI error, a non-zero exit).
33
+ * - `declined`: the person said no to it.
34
+ * - `interrupted`: it never finished and its turn is over.
35
+ */
36
+ export type AgentStepStatus = 'running' | 'ok' | 'failed' | 'declined' | 'interrupted';
37
+
38
+ export interface StepOutput {
39
+ readonly text: string;
40
+ /** What came before `text` was dropped to keep it a bounded size. */
41
+ readonly truncated: boolean;
42
+ }
43
+
44
+ export interface AgentStep {
45
+ /** The stored call's id: what a step is addressed by (its realtime topic, its row key). */
46
+ readonly id: string;
47
+ readonly kind: AgentStepKind;
48
+ /** The tool the CLI named (`Bash`, `Read`, `Edit`…). */
49
+ readonly tool: string;
50
+ /** What it acts on: the command, the path, the pattern. */
51
+ readonly target: string | undefined;
52
+ readonly status: AgentStepStatus;
53
+ /** Epoch ms the step began, when the server said. */
54
+ readonly startedAt: number | undefined;
55
+ /** How long it ran, once it finished. */
56
+ readonly durationMs: number | undefined;
57
+ readonly exitCode: number | undefined;
58
+ /** What a command printed, as stored (bounded). Absent for a step with none. */
59
+ readonly output: StepOutput | undefined;
60
+ /** Whether the step's output is something to show: a command's, running or finished. */
61
+ readonly hasOutput: boolean;
62
+ /** The files an edit changed, as the diff viewer draws them; none for any other step. */
63
+ readonly changes: readonly CallFileChange[];
64
+ }
65
+
66
+ export interface AgentWork {
67
+ readonly steps: readonly AgentStep[];
68
+ readonly running: number;
69
+ readonly failed: number;
70
+ /** First step's start to the last step's end, when the server stamped them. */
71
+ readonly startedAt: number | undefined;
72
+ readonly endedAt: number | undefined;
73
+ }
74
+
75
+ const KINDS: ReadonlyArray<readonly [AgentStepKind, readonly string[]]> = [
76
+ ['command', ['bash', 'shell', 'exec', 'execcommand', 'command', 'terminal', 'run', 'powershell']],
77
+ ['read', ['read', 'view', 'cat', 'open']],
78
+ ['edit', ['edit', 'write', 'multiedit', 'notebookedit', 'patch', 'applypatch', 'filechange']],
79
+ ['search', ['grep', 'glob', 'ls', 'find', 'list', 'search', 'codesearch']],
80
+ ['web', ['websearch', 'webfetch', 'fetch', 'browse', 'browser']],
81
+ ];
82
+
83
+ /** The kind of work a CLI's tool name is. Names differ by CLI (`Bash`, `Shell`, `exec_command`). */
84
+ export function stepKind(tool: string): AgentStepKind {
85
+ const name = tool.toLowerCase().replace(/[^a-z]/g, '');
86
+ for (const [kind, names] of KINDS) if (names.includes(name)) return kind;
87
+ return 'tool';
88
+ }
89
+
90
+ function record(value: unknown): Record<string, unknown> | undefined {
91
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
92
+ ? (value as Record<string, unknown>)
93
+ : undefined;
94
+ }
95
+
96
+ const text = (value: unknown): string | undefined =>
97
+ typeof value === 'string' && value !== '' ? value : undefined;
98
+ const count = (value: unknown): number | undefined =>
99
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
100
+
101
+ function stampOf(value: unknown): number | undefined {
102
+ const at = typeof value === 'string' ? Date.parse(value) : Number.NaN;
103
+ return Number.isNaN(at) ? undefined : at;
104
+ }
105
+
106
+ function statusOf(call: ToolInvocation, live: boolean, exitCode: number | undefined) {
107
+ const result = record(call.result);
108
+ const reported = result?.status;
109
+ if (reported === 'declined' || reported === 'denied') return 'declined';
110
+ const base = toolCallStatus(call, live);
111
+ if (base === 'running') return 'running';
112
+ if (base === 'interrupted') return 'interrupted';
113
+ if (base === 'error' || reported === 'error' || (exitCode !== undefined && exitCode !== 0)) {
114
+ return 'failed';
115
+ }
116
+ return 'ok';
117
+ }
118
+
119
+ /** One stored call as a step. */
120
+ export function agentStepOf(call: ToolInvocation, live: boolean): AgentStep {
121
+ const args = record(call.args);
122
+ const result = call.state === 'result' ? record(call.result) : undefined;
123
+ const kind = stepKind(call.toolName);
124
+ const exitCode = count(result?.exitCode);
125
+ const stored = text(result?.output);
126
+ return {
127
+ id: call.toolCallId,
128
+ kind,
129
+ tool: call.toolName,
130
+ target: text(args?.summary) ?? text(result?.summary),
131
+ status: statusOf(call, live, exitCode),
132
+ startedAt: stampOf(args?.startedAt),
133
+ durationMs: count(result?.durationMs),
134
+ exitCode,
135
+ output:
136
+ stored === undefined
137
+ ? undefined
138
+ : { text: stored, truncated: result?.outputTruncated === true },
139
+ hasOutput: kind === 'command' || stored !== undefined,
140
+ changes: fileChangesOf(call),
141
+ };
142
+ }
143
+
144
+ /**
145
+ * The turn's work log, or `null` when an external agent did nothing in it.
146
+ *
147
+ * `live` is whether the turn is still running: a call with no result is `running` then and
148
+ * `interrupted` after, so a log never says "done" about work that did not finish.
149
+ */
150
+ export function buildAgentWork(
151
+ calls: readonly ToolInvocation[] | undefined,
152
+ live: boolean,
153
+ ): AgentWork | null {
154
+ const steps = (calls ?? []).filter(isExternalStep).map((call) => agentStepOf(call, live));
155
+ if (steps.length === 0) return null;
156
+ const first = steps.find((step) => step.startedAt !== undefined);
157
+ const ends = steps.flatMap((step) =>
158
+ step.startedAt !== undefined && step.durationMs !== undefined
159
+ ? [step.startedAt + step.durationMs]
160
+ : [],
161
+ );
162
+ return {
163
+ steps,
164
+ running: steps.filter((step) => step.status === 'running').length,
165
+ failed: steps.filter((step) => step.status === 'failed').length,
166
+ startedAt: first?.startedAt,
167
+ endedAt: ends.length > 0 ? Math.max(...ends) : undefined,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * How long the work took: to its last finished step, or — while a step is still running — to
173
+ * `now`. `undefined` when the server stamped nothing (a turn stored before steps carried times).
174
+ */
175
+ export function workElapsedMs(work: AgentWork, now: number): number | undefined {
176
+ if (work.startedAt === undefined) return undefined;
177
+ const end = work.running > 0 ? now : work.endedAt;
178
+ return end === undefined ? undefined : Math.max(0, end - work.startedAt);
179
+ }
180
+
181
+ /** A step's duration as a row prints it: `340ms`, `2.4s`, `1m 5s`. */
182
+ export function formatStepDuration(ms: number): string {
183
+ if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`;
184
+ if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
185
+ const total = Math.round(ms / 1000);
186
+ const hours = Math.floor(total / 3600);
187
+ const minutes = Math.floor((total % 3600) / 60);
188
+ const seconds = total % 60;
189
+ if (hours > 0) return `${hours}h ${minutes}m`;
190
+ if (minutes > 0) return `${minutes}m ${seconds}s`;
191
+ return `${seconds}s`;
192
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * A command's output as the thread draws it: plain text, readable, bounded.
3
+ *
4
+ * What a CLI prints is for a terminal: colour escapes, a progress bar redrawn in place with `\r`,
5
+ * a bell. None of that means anything in a conversation, and rendering escapes is how terminal
6
+ * output becomes a way to put things on a person's screen, so they are removed rather than drawn.
7
+ * The text that remains is what a person would copy.
8
+ */
9
+
10
+ /** Characters of output the thread holds and draws at most (the server sends no more than its tail). */
11
+ export const COMMAND_OUTPUT_VIEW_CHARS = 32 * 1024;
12
+
13
+ // Control Sequence Introducer (`ESC [ … final`), Operating System Command (`ESC ] … BEL | ST`), and the
14
+ // two-character escapes (`ESC c`, `ESC =`…). Built from char codes so no control byte is written in
15
+ // the source.
16
+ const ESC = String.fromCharCode(0x1b);
17
+ const BEL = String.fromCharCode(0x07);
18
+ const CSI = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, 'g');
19
+ const OSC = new RegExp(`${ESC}\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`, 'g');
20
+ const SHORT = new RegExp(`${ESC}[@-Z\\\\-_=>]`, 'g');
21
+ // Every control character but tab and newline (and `\r`, handled on its own).
22
+ const CONTROLS = new RegExp(
23
+ `[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(0x0b)}${String.fromCharCode(0x0c)}${String.fromCharCode(0x0e)}-${String.fromCharCode(0x1f)}${String.fromCharCode(0x7f)}]`,
24
+ 'g',
25
+ );
26
+
27
+ /** `text` without terminal escapes, bells and the like. */
28
+ export function stripAnsi(text: string): string {
29
+ return text.replace(OSC, '').replace(CSI, '').replace(SHORT, '').replace(CONTROLS, '');
30
+ }
31
+
32
+ /**
33
+ * A line a progress bar redrew with `\r` is the last thing it drew; `\r\n` is a newline.
34
+ */
35
+ function settleCarriageReturns(text: string): string {
36
+ if (!text.includes('\r')) return text;
37
+ return text
38
+ .replace(/\r\n/g, '\n')
39
+ .split('\n')
40
+ .map((line) => {
41
+ const last = line.lastIndexOf('\r');
42
+ return last === -1 ? line : line.slice(last + 1);
43
+ })
44
+ .join('\n');
45
+ }
46
+
47
+ /** What the thread draws for a step's output. */
48
+ export function displayOutput(raw: string): string {
49
+ const text = settleCarriageReturns(stripAnsi(raw));
50
+ return text.length > COMMAND_OUTPUT_VIEW_CHARS ? text.slice(-COMMAND_OUTPUT_VIEW_CHARS) : text;
51
+ }
@@ -817,6 +817,9 @@ export function useConversationStream({
817
817
  ...appAssertion,
818
818
  Accept: 'text/event-stream',
819
819
  'Content-Type': 'application/json',
820
+ // This action's id, the one the turn is named by: a request that reaches the server
821
+ // twice (a replay after a token refresh, a network retry) starts the turn once.
822
+ 'Idempotency-Key': turnControl.id,
820
823
  ...(deviceInfo === undefined ? {} : { 'X-Device-Info': JSON.stringify(deviceInfo) }),
821
824
  },
822
825
  body: JSON.stringify({
@@ -942,7 +945,13 @@ export function useConversationStream({
942
945
  throw new Error(errorMessage);
943
946
  }
944
947
 
945
- if (!response.body) {
948
+ // The server already has this very turn: this request reached it twice, and it ran nothing
949
+ // again (ADR 0049). The answer is the first request's, so it is read by resuming that turn
950
+ // rather than from this response, which carries only its receipt.
951
+ const replayed = response.headers.get('Idempotency-Replayed') === 'true';
952
+ if (replayed) {
953
+ await response.body?.cancel();
954
+ } else if (!response.body) {
946
955
  throw new Error('No response received from server');
947
956
  }
948
957
  setComposerPhase('streaming');
@@ -967,7 +976,7 @@ export function useConversationStream({
967
976
  const turnId = turnControl.id;
968
977
  const client = linked.client;
969
978
  const source = createResumableFrameSource({
970
- response,
979
+ response: replayed ? null : response,
971
980
  signal: controller.signal,
972
981
  reconnect: async (cursor, signal) =>
973
982
  client.requestAuthenticatedResponse({
@@ -993,6 +1002,16 @@ export function useConversationStream({
993
1002
  // Flush any remaining batched content before checking
994
1003
  flushPendingUpdates();
995
1004
 
1005
+ // A turn the server already had, whose stream cannot be followed to its end (a group
1006
+ // room has none to resume). The message did reach the server, so it is kept and offered
1007
+ // no Retry, which would send it a second time.
1008
+ if (replayed && !sawTerminal) {
1009
+ setError(
1010
+ new Error('This message was already received; its answer will appear here.'),
1011
+ );
1012
+ return keepFailedTurn(false);
1013
+ }
1014
+
996
1015
  // The server answered with a stand-in, or with nothing usable at
997
1016
  // all: the turn stays, with the error under it. (With real output
998
1017
  // AND a synthetic tail, this keeps the output and marks the tail.)
@@ -0,0 +1,42 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { stepOutputTopic } from '../realtime/contract';
3
+ import { useRealtimeTopic } from '../realtime/react';
4
+ import type { RealtimeFrame } from '../realtime/contract';
5
+ import type { StepOutput } from './thread/agent-work';
6
+
7
+ /**
8
+ * What a running command has printed, live, while a person has its step open.
9
+ *
10
+ * The step's topic is followed ONLY while `enabled`: a collapsed step costs the connection nothing
11
+ * (its status arrives with the turn's own stream), and collapsing a step releases its topic. Each
12
+ * frame is the tail of the output so far, whole, so the latest frame is the whole truth and a
13
+ * missed one costs nothing. `null` until the first frame (a command that has printed nothing yet,
14
+ * or one the server did not let this person follow): the step then shows what was stored, if any.
15
+ *
16
+ * @param conversationId - The conversation the step is in; `null` for one not created yet.
17
+ * @param toolCallId - The step's call id.
18
+ * @param enabled - The step is open and still running.
19
+ */
20
+ export function useStepOutput(
21
+ conversationId: string | null | undefined,
22
+ toolCallId: string,
23
+ enabled: boolean,
24
+ ): StepOutput | null {
25
+ const topic = enabled && conversationId ? stepOutputTopic(conversationId, toolCallId) : null;
26
+ const [live, setLive] = useState<StepOutput | null>(null);
27
+
28
+ // A different step, or the same one reopened, starts from nothing: the next frame is whole.
29
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `topic` is the reset key.
30
+ useEffect(() => setLive(null), [topic]);
31
+
32
+ const onFrame = useCallback(
33
+ (frame: RealtimeFrame) => {
34
+ const data = frame.data as Partial<RealtimeFrame<'step.output'>['data']> | undefined;
35
+ if (data?.toolCallId !== toolCallId || typeof data.text !== 'string') return;
36
+ setLive({ text: data.text, truncated: data.truncated === true });
37
+ },
38
+ [toolCallId],
39
+ );
40
+ useRealtimeTopic(topic, onFrame, 'step.output');
41
+ return live;
42
+ }