@saadnvd1/agent-os 0.3.479 → 0.3.482

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.
@@ -0,0 +1,146 @@
1
+ import "./composer/test-dom";
2
+ import { act, createElement } from "react";
3
+ import { createRoot, type Root } from "react-dom/client";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import type { ChatItem } from "@/lib/chat/events";
6
+ import { groupTimeline } from "@/lib/chat/group";
7
+ import { copySelection } from "./copy-selection";
8
+ import { TimelineRows } from "./ChatPanel";
9
+
10
+ (
11
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
12
+ ).IS_REACT_ACT_ENVIRONMENT = true;
13
+
14
+ const user = (id: string, text: string): ChatItem => ({
15
+ id,
16
+ kind: "user",
17
+ createdAt: 1,
18
+ text,
19
+ tagged: true,
20
+ });
21
+ const reply = (id: string, text: string, streaming = false): ChatItem => ({
22
+ id,
23
+ kind: "assistant",
24
+ createdAt: 2,
25
+ text,
26
+ streaming,
27
+ });
28
+
29
+ describe("the conversation's rows", () => {
30
+ let host: HTMLElement;
31
+ let root: Root;
32
+ const actions = () => ({ respond: vi.fn() }) as never;
33
+ const show = (items: ChatItem[], a = actions()) =>
34
+ act(() =>
35
+ root.render(
36
+ createElement(TimelineRows, {
37
+ blocks: groupTimeline(items),
38
+ actions: a,
39
+ })
40
+ )
41
+ );
42
+ const rows = () => [...host.querySelectorAll("[data-block]")];
43
+
44
+ beforeEach(() => {
45
+ host = document.createElement("div");
46
+ document.body.append(host);
47
+ root = createRoot(host);
48
+ });
49
+ afterEach(() => {
50
+ act(() => root.unmount());
51
+ host.remove();
52
+ document.getSelection()?.removeAllRanges();
53
+ });
54
+
55
+ it("keeps a selection across messages through streaming updates", async () => {
56
+ const items = [
57
+ user("u1", "first"),
58
+ reply("a1", "second", true),
59
+ user("u2", "third"),
60
+ ];
61
+ await show(items);
62
+ const [r1, , r3] = rows();
63
+ const range = document.createRange();
64
+ range.setStart(r1, 0);
65
+ range.setEnd(r3, r3.childNodes.length);
66
+ document.getSelection()!.removeAllRanges();
67
+ document.getSelection()!.addRange(range);
68
+
69
+ await show([
70
+ items[0],
71
+ reply("a1", "second, and more words streamed in", true),
72
+ items[2],
73
+ reply("a2", "a new reply at the end", true),
74
+ ]);
75
+ await show(
76
+ [
77
+ items[0],
78
+ reply("a1", "second, and more words streamed in", false),
79
+ items[2],
80
+ reply("a2", "a new reply at the end, done", false),
81
+ ],
82
+ actions()
83
+ );
84
+
85
+ const after = rows();
86
+ expect(after).toHaveLength(4);
87
+ expect(after[0]).toBe(r1);
88
+ expect(after[2]).toBe(r3);
89
+ expect(r1.isConnected && r3.isConnected).toBe(true);
90
+ expect(after.map((r) => r.getAttribute("data-block"))).toEqual([
91
+ "u1",
92
+ "a1",
93
+ "u2",
94
+ "a2",
95
+ ]);
96
+ const sel = document.getSelection()!;
97
+ expect(sel.rangeCount).toBe(1);
98
+ expect(sel.isCollapsed).toBe(false);
99
+ expect(sel.getRangeAt(0).startContainer).toBe(r1);
100
+ expect(sel.getRangeAt(0).endContainer).toBe(r3);
101
+ });
102
+
103
+ describe("copying", () => {
104
+ const copy = (items: ChatItem[]) => {
105
+ const data: Record<string, string> = {};
106
+ const e = {
107
+ currentTarget: host,
108
+ clipboardData: { setData: (t: string, v: string) => (data[t] = v) },
109
+ preventDefault: vi.fn(),
110
+ };
111
+ copySelection(e as never, new Map(items.map((i) => [i.id, i])));
112
+ return { data, prevented: e.preventDefault.mock.calls.length > 0 };
113
+ };
114
+
115
+ it("gives speakers and blank lines across messages, from their source", async () => {
116
+ const items = [
117
+ user("u1", "fix `the` bug"),
118
+ reply("a1", "Done.\n\n- one\n- two"),
119
+ user("u2", "thanks"),
120
+ ];
121
+ await show(items);
122
+ const [r1, , r3] = rows();
123
+ const range = document.createRange();
124
+ range.selectNodeContents(host);
125
+ range.setStart(r1, 0);
126
+ range.setEnd(r3, r3.childNodes.length);
127
+ document.getSelection()!.addRange(range);
128
+ const { data, prevented } = copy(items);
129
+ expect(prevented).toBe(true);
130
+ expect(data["text/plain"]).toBe(
131
+ "User:\nfix `the` bug\n\nAssistant:\nDone.\n\n- one\n- two\n\nUser:\nthanks"
132
+ );
133
+ });
134
+
135
+ it("leaves a selection inside one message to the browser", async () => {
136
+ const items = [user("u1", "first"), reply("a1", "second words")];
137
+ await show(items);
138
+ const text = rows()[1].querySelector("p")!.firstChild!;
139
+ const range = document.createRange();
140
+ range.setStart(text, 1);
141
+ range.setEnd(text, 4);
142
+ document.getSelection()!.addRange(range);
143
+ expect(copy(items)).toEqual({ data: {}, prevented: false });
144
+ });
145
+ });
146
+ });
@@ -8,6 +8,8 @@ import { usePauseOrchestrator } from "@/data/orchestrators";
8
8
  import { useOrchestratorHeader } from "@/hooks/useOrchestratorHeader";
9
9
  import { headerParts } from "@/lib/orchestrator/header-line";
10
10
  import { cn } from "@/lib/utils";
11
+ import { useSchedulesGlance } from "@/components/SessionList/useSchedulesGlance";
12
+ import { schedulesUiActions } from "@/stores/schedulesUi";
11
13
  import { NO_PASSKEYS_HERE, passkeysHere } from "@/data/presence";
12
14
  import { AsksList } from "./AsksList";
13
15
 
@@ -21,6 +23,7 @@ export const OrchestratorBar = memo(function OrchestratorBar({
21
23
  }) {
22
24
  const { overview, counts } = useOrchestratorHeader(workspaceId);
23
25
  const pause = usePauseOrchestrator(workspaceId);
26
+ const { upcomingText } = useSchedulesGlance(workspaceId);
24
27
  const [open, setOpen] = useState(true);
25
28
  const canProve = useSyncExternalStore(
26
29
  () => () => {},
@@ -73,6 +76,15 @@ export const OrchestratorBar = memo(function OrchestratorBar({
73
76
  {counts.paused ? "Resume" : "Pause"}
74
77
  </Button>
75
78
  </div>
79
+ {upcomingText && (
80
+ <button
81
+ type="button"
82
+ onClick={() => schedulesUiActions.open(workspaceId)}
83
+ className="text-muted-foreground hover:text-foreground flex min-h-11 w-full items-center px-1 text-left text-xs md:min-h-8"
84
+ >
85
+ {upcomingText}
86
+ </button>
87
+ )}
76
88
  {counts.paused && (
77
89
  <p className="text-muted-foreground px-1 text-xs">
78
90
  Paused: events wait and it won&apos;t start, merge or message anything
@@ -31,8 +31,10 @@ import {
31
31
  minGapMinutes,
32
32
  nextRuns,
33
33
  presetCron,
34
+ wall,
34
35
  type PresetKind,
35
36
  } from "@/lib/schedules/cron";
37
+ import { parseWhen, relativeTime } from "@/lib/schedules/when";
36
38
 
37
39
  const KINDS: { value: ScheduleKind; label: string; hint: string }[] = [
38
40
  {
@@ -57,7 +59,10 @@ const KINDS: { value: ScheduleKind; label: string; hint: string }[] = [
57
59
  },
58
60
  ];
59
61
 
60
- const PRESETS: { value: PresetKind | "custom"; label: string }[] = [
62
+ type Preset = PresetKind | "custom" | "once";
63
+
64
+ const PRESETS: { value: Preset; label: string }[] = [
65
+ { value: "once", label: "Once" },
61
66
  { value: "every", label: "Every…" },
62
67
  { value: "hourly", label: "Hourly" },
63
68
  { value: "daily", label: "Daily" },
@@ -115,6 +120,17 @@ function Segmented<T extends string>({
115
120
  );
116
121
  }
117
122
 
123
+ const pad = (n: number) => String(n).padStart(2, "0");
124
+
125
+ // The date and time inputs' values for an instant, as the zone's wall clock.
126
+ function wallParts(ms: number, tz: string) {
127
+ const w = wall(ms, tz);
128
+ return {
129
+ date: `${w.y}-${pad(w.m)}-${pad(w.d)}`,
130
+ time: `${pad(w.h)}:${pad(w.mi)}`,
131
+ };
132
+ }
133
+
118
134
  const Field = ({
119
135
  label,
120
136
  children,
@@ -148,7 +164,8 @@ export function ScheduleForm({
148
164
  const update = useUpdateSchedule();
149
165
  const mutation = existing ? update : create;
150
166
 
151
- const initialPreset = existing ? cronPreset(existing.cron) : null;
167
+ const initialPreset =
168
+ existing && existing.run_at == null ? cronPreset(existing.cron) : null;
152
169
  const [wsId, setWsId] = useState(
153
170
  existing?.workspace_id ?? workspaceId ?? workspaces[0]?.id ?? ""
154
171
  );
@@ -161,9 +178,24 @@ export function ScheduleForm({
161
178
  );
162
179
  const [projectId, setProjectId] = useState(existing?.project_id ?? "");
163
180
  const [prompt, setPrompt] = useState(existing?.prompt ?? "");
164
- const [preset, setPreset] = useState<PresetKind | "custom">(
165
- existing ? (initialPreset?.kind ?? "custom") : draft ? "every" : "weekdays"
181
+ const [preset, setPreset] = useState<Preset>(
182
+ existing?.run_at != null
183
+ ? "once"
184
+ : existing
185
+ ? (initialPreset?.kind ?? "custom")
186
+ : draft
187
+ ? "every"
188
+ : "weekdays"
189
+ );
190
+ // A new one-off starts an hour out.
191
+ const [initialAt] = useState(() =>
192
+ wallParts(
193
+ existing?.run_at ?? Date.now() + 3_600_000,
194
+ existing?.timezone ?? DEFAULT_TIMEZONE
195
+ )
166
196
  );
197
+ const [atDate, setAtDate] = useState(initialAt.date);
198
+ const [atTime, setAtTime] = useState(initialAt.time);
167
199
  const [every, setEvery] = useState(initialPreset?.every ?? 30);
168
200
  const [hour, setHour] = useState(initialPreset?.hour ?? 9);
169
201
  const [minute, setMinute] = useState(initialPreset?.minute ?? 0);
@@ -197,12 +229,14 @@ export function ScheduleForm({
197
229
  .sort((a, b) => a.name.localeCompare(b.name));
198
230
  const target = targets.find((s) => s.id === targetId)?.id ?? "";
199
231
 
200
- const cron =
201
- preset === "custom"
232
+ const once = preset === "once";
233
+ const cron = once
234
+ ? ""
235
+ : preset === "custom"
202
236
  ? custom.trim()
203
237
  : presetCron({ kind: preset, hour, minute, weekday, every });
204
238
  const tzOk = isTimezone(timezone);
205
- const cronProblem = cronError(cron);
239
+ const cronProblem = once ? null : cronError(cron);
206
240
  // The preview counts from now, kept fresh while the form is open.
207
241
  const [openedAt, setOpenedAt] = useState(() => Date.now());
208
242
  useEffect(() => {
@@ -214,13 +248,32 @@ export function ScheduleForm({
214
248
  [cron, cronProblem, timezone, tzOk, openedAt]
215
249
  );
216
250
 
251
+ // The picked wall time in the zone, or null while it's incomplete.
252
+ const runAt = useMemo(() => {
253
+ if (!once || !tzOk || !atDate || !atTime) return null;
254
+ try {
255
+ return parseWhen(`${atDate}T${atTime}`, timezone);
256
+ } catch {
257
+ return null;
258
+ }
259
+ }, [once, tzOk, atDate, atTime, timezone]);
260
+ // Saving a done one-off at its old time can't reopen it; a new time must be ahead.
261
+ const atProblem =
262
+ once && tzOk
263
+ ? runAt === null
264
+ ? "Pick a date and time"
265
+ : runAt <= openedAt && runAt !== existing?.run_at
266
+ ? "That time has passed"
267
+ : null
268
+ : null;
269
+
217
270
  const submit = (e: React.FormEvent) => {
218
271
  e.preventDefault();
219
272
  const input = {
220
273
  workspaceId: workspace,
221
274
  projectId: project || null,
222
275
  name,
223
- cron,
276
+ ...(once ? { at: runAt } : { cron }),
224
277
  timezone,
225
278
  prompt,
226
279
  kind,
@@ -242,10 +295,11 @@ export function ScheduleForm({
242
295
  const tooOften = useMemo(
243
296
  () =>
244
297
  minGap > 0 &&
298
+ !once &&
245
299
  !cronProblem &&
246
300
  tzOk &&
247
301
  minGapMinutes(cron, timezone, openedAt) < minGap,
248
- [minGap, cron, cronProblem, timezone, tzOk, openedAt]
302
+ [minGap, once, cron, cronProblem, timezone, tzOk, openedAt]
249
303
  );
250
304
 
251
305
  const ready =
@@ -253,6 +307,7 @@ export function ScheduleForm({
253
307
  prompt.trim() &&
254
308
  workspace &&
255
309
  !cronProblem &&
310
+ !atProblem &&
256
311
  tzOk &&
257
312
  !tooOften &&
258
313
  (kind === "message" ? target : kind === "orchestrator" || project);
@@ -362,7 +417,24 @@ export function ScheduleForm({
362
417
  setPreset(v);
363
418
  }}
364
419
  />
365
- {preset === "custom" ? (
420
+ {once ? (
421
+ <div className="flex flex-wrap gap-2">
422
+ <Input
423
+ type="date"
424
+ aria-label="Date"
425
+ value={atDate}
426
+ onChange={(e) => setAtDate(e.target.value)}
427
+ className="h-11 w-44 md:h-9"
428
+ />
429
+ <Input
430
+ type="time"
431
+ aria-label="Time"
432
+ value={atTime}
433
+ onChange={(e) => setAtTime(e.target.value)}
434
+ className="h-11 w-32 md:h-9"
435
+ />
436
+ </div>
437
+ ) : preset === "custom" ? (
366
438
  <Input
367
439
  aria-label="Cron expression"
368
440
  value={custom}
@@ -450,10 +522,20 @@ export function ScheduleForm({
450
522
  className="text-muted-foreground h-11 md:h-8 md:text-xs"
451
523
  />
452
524
  <div className="bg-primary/[0.06] rounded-lg px-3 py-2.5 text-sm">
453
- {cronProblem || !tzOk ? (
525
+ {cronProblem || !tzOk || atProblem ? (
454
526
  <p className="text-destructive">
455
- {cronProblem ?? `Unknown time zone "${timezone}"`}
527
+ {!tzOk
528
+ ? `Unknown time zone "${timezone}"`
529
+ : (cronProblem ?? atProblem)}
456
530
  </p>
531
+ ) : once && runAt !== null ? (
532
+ <>
533
+ <p className="font-medium">{formatRunTime(runAt, timezone)}</p>
534
+ <p className="text-muted-foreground mt-1 text-xs">
535
+ Runs once, {relativeTime(runAt, openedAt)}, then turns itself
536
+ off.
537
+ </p>
538
+ </>
457
539
  ) : (
458
540
  <>
459
541
  <p className="font-medium">{describeCron(cron)}</p>
@@ -25,6 +25,7 @@ import {
25
25
  } from "@/data/schedules";
26
26
  import type { ScheduleView } from "@/lib/schedules";
27
27
  import { formatRunTime } from "@/lib/schedules/cron";
28
+ import { relativeTime } from "@/lib/schedules/when";
28
29
  import { schedulesUi, schedulesUiActions } from "@/stores/schedulesUi";
29
30
  import { ScheduleForm } from "./ScheduleForm";
30
31
  import { OutcomeChip, RunHistory } from "./RunHistory";
@@ -50,10 +51,14 @@ const where = (s: ScheduleView) =>
50
51
  : "";
51
52
 
52
53
  function NextRun({ s }: { s: ScheduleView }) {
54
+ if (s.done_at) return <>Done {formatRunTime(s.done_at, s.timezone)}</>;
53
55
  if (!s.enabled) return <>Off</>;
54
56
  if (s.paused) return <>Paused with the orchestrator</>;
55
57
  return s.nextRunAt ? (
56
- <>Next {formatRunTime(s.nextRunAt, s.timezone)}</>
58
+ <>
59
+ {s.oneOff ? "Runs" : "Next"} {formatRunTime(s.nextRunAt, s.timezone)}
60
+ {s.oneOff && ` (${relativeTime(s.nextRunAt)})`}
61
+ </>
57
62
  ) : (
58
63
  <>No upcoming run</>
59
64
  );
@@ -98,15 +103,44 @@ function ScheduleRow({ s, onOpen }: { s: ScheduleView; onOpen: () => void }) {
98
103
  </span>
99
104
  </div>
100
105
  <p className="text-muted-foreground truncate text-xs">
101
- {s.description} · <NextRun s={s} />
106
+ {s.oneOff ? (
107
+ <NextRun s={s} />
108
+ ) : (
109
+ <>
110
+ {s.description} · <NextRun s={s} />
111
+ </>
112
+ )}
113
+ {s.oneOff && ` · by ${s.createdBy.name}`}
102
114
  </p>
103
115
  </div>
104
116
  {s.lastRun && <OutcomeChip run={s.lastRun} />}
105
- <EnableSwitch s={s} />
117
+ {!s.done_at && <EnableSwitch s={s} />}
106
118
  </div>
107
119
  );
108
120
  }
109
121
 
122
+ function Group({
123
+ title,
124
+ rows,
125
+ onOpen,
126
+ }: {
127
+ title: string;
128
+ rows: ScheduleView[];
129
+ onOpen: (id: string) => void;
130
+ }) {
131
+ if (rows.length === 0) return null;
132
+ return (
133
+ <section className="space-y-2">
134
+ <h4 className="text-muted-foreground px-1 text-xs font-medium">
135
+ {title} · {rows.length}
136
+ </h4>
137
+ {rows.map((s) => (
138
+ <ScheduleRow key={s.id} s={s} onOpen={() => onOpen(s.id)} />
139
+ ))}
140
+ </section>
141
+ );
142
+ }
143
+
110
144
  function Detail({
111
145
  id,
112
146
  onEdit,
@@ -134,11 +168,12 @@ function Detail({
134
168
  <div className="space-y-1">
135
169
  <div className="flex items-center gap-2">
136
170
  <h3 className="min-w-0 flex-1 truncate font-semibold">{s.name}</h3>
137
- <EnableSwitch s={s} />
171
+ {!s.done_at && <EnableSwitch s={s} />}
138
172
  </div>
139
173
  <p className="text-muted-foreground text-sm">
140
174
  {KIND_LABEL[s.kind]}
141
175
  {where(s)} · {s.description}
176
+ {s.oneOff && ` · by ${s.createdBy.name}`}
142
177
  </p>
143
178
  <p className="text-muted-foreground text-xs">
144
179
  <NextRun s={s} /> · {s.timezone}
@@ -151,7 +186,7 @@ function Detail({
151
186
  <Button
152
187
  size="sm"
153
188
  className="h-11 md:h-8"
154
- disabled={run.isPending}
189
+ disabled={run.isPending || !!s.done_at}
155
190
  onClick={() => run.mutate(s.id)}
156
191
  >
157
192
  <Play className="h-3.5 w-3.5" />
@@ -174,7 +209,7 @@ function Detail({
174
209
  disabled={archive.isPending}
175
210
  onClick={() => archive.mutate(s.id, { onSuccess: onGone })}
176
211
  >
177
- Remove (keeps history)
212
+ {s.oneOff && !s.done_at ? "Cancel it" : "Remove (keeps history)"}
178
213
  </Button>
179
214
  ) : (
180
215
  <Button
@@ -184,7 +219,7 @@ function Detail({
184
219
  onClick={() => setConfirm(true)}
185
220
  >
186
221
  <Trash2 className="h-3.5 w-3.5" />
187
- Remove
222
+ {s.oneOff && !s.done_at ? "Cancel" : "Remove"}
188
223
  </Button>
189
224
  )}
190
225
  </div>
@@ -300,13 +335,24 @@ export function SchedulesPanel() {
300
335
  </p>
301
336
  </div>
302
337
  )}
303
- {schedules.map((s) => (
304
- <ScheduleRow
305
- key={s.id}
306
- s={s}
307
- onOpen={() => setView({ mode: "detail", id: s.id })}
308
- />
309
- ))}
338
+ {(() => {
339
+ const open = (id: string) => setView({ mode: "detail", id });
340
+ const upcoming = schedules
341
+ .filter((s) => s.oneOff && !s.done_at)
342
+ .sort((a, b) => (a.run_at ?? 0) - (b.run_at ?? 0));
343
+ const done = schedules.filter((s) => s.done_at);
344
+ return (
345
+ <>
346
+ <Group title="Upcoming" rows={upcoming} onOpen={open} />
347
+ <Group
348
+ title="Recurring"
349
+ rows={schedules.filter((s) => !s.oneOff)}
350
+ onOpen={open}
351
+ />
352
+ <Group title="Done" rows={done} onOpen={open} />
353
+ </>
354
+ );
355
+ })()}
310
356
  {!isPending && <PhoneLine />}
311
357
  </div>
312
358
  )}
@@ -97,7 +97,7 @@ export function SidebarHeader(props: SidebarHeaderProps) {
97
97
  // Opens Settings > Schedules.
98
98
  menuItem("Schedules", () => schedulesUiActions.open(workspaceId), {
99
99
  icon: Clock,
100
- description: schedules.nextText,
100
+ description: schedules.upcomingText ?? schedules.nextText,
101
101
  badge: schedules.failed > 0 && (
102
102
  <span className="text-destructive flex items-center gap-1.5 text-xs font-medium tabular-nums">
103
103
  <span aria-hidden className={failedDot} />
@@ -3,12 +3,13 @@
3
3
  import { useSchedulesQuery } from "@/data/schedules";
4
4
  import { schedulesBadge } from "@/lib/schedules/badge";
5
5
  import { formatRunTime } from "@/lib/schedules/cron";
6
+ import { relativeTime } from "@/lib/schedules/when";
6
7
 
7
8
  // Schedules at a glance for the header's menu: how many failed their last
8
9
  // run (a red badge) and when the next one runs (a line under the item).
9
10
  export function useSchedulesGlance(workspaceId: string | null) {
10
11
  const { data: schedules = [] } = useSchedulesQuery(workspaceId);
11
- const { next, failed } = schedulesBadge(schedules);
12
+ const { next, failed, upcoming, nextUpcoming } = schedulesBadge(schedules);
12
13
  const failedText = failed
13
14
  ? `${failed} schedule${failed === 1 ? "" : "s"} failed last run`
14
15
  : null;
@@ -17,5 +18,8 @@ export function useSchedulesGlance(workspaceId: string | null) {
17
18
  : schedules.length
18
19
  ? "Nothing scheduled to run"
19
20
  : "No schedules yet";
20
- return { failed, failedText, nextText };
21
+ const upcomingText = upcoming
22
+ ? `${upcoming} upcoming${nextUpcoming ? ` · next ${relativeTime(nextUpcoming.at)}` : ""}`
23
+ : null;
24
+ return { failed, failedText, nextText, upcoming, upcomingText };
21
25
  }
@@ -0,0 +1,58 @@
1
+ import type { ChatItem } from "./events";
2
+ import { eventParts, originOf } from "./origin";
3
+
4
+ export interface TranscriptPart {
5
+ speaker: string;
6
+ text: string;
7
+ }
8
+
9
+ // Who a message is from when copied, or null for rows that aren't part of the
10
+ // conversation itself (tools, turn markers, plans, approvals...).
11
+ export function speakerOf(item: ChatItem): string | null {
12
+ switch (item.kind) {
13
+ case "user": {
14
+ const origin = originOf(item);
15
+ if (!origin) return "User";
16
+ return origin.kind === "decision" ? "Decision" : origin.label;
17
+ }
18
+ case "assistant":
19
+ return "Assistant";
20
+ case "error":
21
+ return "Error";
22
+ default:
23
+ return null;
24
+ }
25
+ }
26
+
27
+ // The whole message as written, for one a selection covers entirely.
28
+ export function sourceText(item: ChatItem): string {
29
+ switch (item.kind) {
30
+ case "user": {
31
+ const origin = originOf(item);
32
+ if (!origin) return item.text;
33
+ const { body, decided } = eventParts(item, origin);
34
+ return [...decided, body].join("\n\n");
35
+ }
36
+ case "assistant":
37
+ return item.text;
38
+ case "error":
39
+ return item.message;
40
+ default:
41
+ return "";
42
+ }
43
+ }
44
+
45
+ // `Speaker:` then the text, a blank line between messages. Neighbours from
46
+ // the same speaker (a reply split around its tools) read as one message.
47
+ export function formatTranscript(parts: TranscriptPart[]): string {
48
+ const merged: TranscriptPart[] = [];
49
+ for (const p of parts) {
50
+ const text = p.text.trim();
51
+ if (!text) continue;
52
+ const last = merged.at(-1);
53
+ if (last && last.speaker === p.speaker)
54
+ last.text = `${last.text}\n\n${text}`;
55
+ else merged.push({ speaker: p.speaker, text });
56
+ }
57
+ return merged.map((p) => `${p.speaker}:\n${p.text}`).join("\n\n");
58
+ }
@@ -64,7 +64,8 @@ export function demoConversation(stepMs = 40): ChatConversation {
64
64
  const words = DEMO_REPLY.split(/(?<= )/);
65
65
  let i = 0;
66
66
  for (; i < words.length && !stopped && !closed; i++) {
67
- await sleep(stepMs);
67
+ // A step of 0 (tests) streams with no timer per word.
68
+ if (stepMs) await sleep(stepMs);
68
69
  out.push({ type: "delta", id, text: words[i] });
69
70
  }
70
71
  out.push({