@spunto/design-system 0.56.0 → 0.57.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spunto/design-system",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "description": "Spunto's shared design system — green tokens (conservatory + sprout), color constants, and UI primitives.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -74,7 +74,7 @@
74
74
  "brand:export": "node scripts/export-logo.ts"
75
75
  },
76
76
  "dependencies": {
77
- "@tanstack/react-virtual": "^3.14.13",
77
+ "@legendapp/list": "3.3.5",
78
78
  "@xterm/addon-fit": "^0.11.0",
79
79
  "@xterm/addon-search": "^0.16.0",
80
80
  "@xterm/addon-web-links": "^0.12.0",
@@ -1,7 +1,7 @@
1
1
  "use client"
2
2
 
3
3
  import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"
4
- import { useVirtualizer } from "@tanstack/react-virtual"
4
+ import { LegendList, type LegendListRef, type LegendListRenderItemProps, type MaintainScrollAtEndOptions } from "@legendapp/list/react"
5
5
  import {
6
6
  ArrowUpIcon,
7
7
  BrainIcon,
@@ -41,7 +41,7 @@ import {
41
41
  runStats,
42
42
  toolSubject,
43
43
  } from "./tool-stack"
44
- import type { AttachmentUrl, PendingMessage, TaskEvent } from "./types"
44
+ import type { AttachmentUrl, PendingMessage, TaskDraft, TaskEvent } from "./types"
45
45
 
46
46
  /**
47
47
  * The agent session, as it happens (RFC 0020) — the central panel of the task cockpit.
@@ -511,7 +511,9 @@ function PendingEntry({ text, previews = [] }: { text: string; previews?: string
511
511
  /** The last row while the session can still move: the logo, alive. */
512
512
  function WorkingEntry() {
513
513
  return (
514
- <Entry className="pb-0">
514
+ // `min-h-8`: the logo (24 px, 2 px down, plus its shadow) is taller than the line of text
515
+ // beside it, and the list clips each row to its box — it was cut off at the bottom.
516
+ <Entry className="min-h-8 pb-0">
515
517
  {/* The logo *is* the marker: its flame tile is opaque, so the rail stops behind it. */}
516
518
  <SpuntoLogo
517
519
  working
@@ -525,6 +527,68 @@ function WorkingEntry() {
525
527
  )
526
528
  }
527
529
 
530
+ /**
531
+ * Reveal `target` progressively instead of in the jumps it arrives in.
532
+ *
533
+ * Tokens reach the reader in batches — one per poll, a second or two of writing at once — and a
534
+ * paragraph appearing in a single block reads as "loaded", not as "being written". So the text on
535
+ * screen trails the text received and catches up at a pace that drains any backlog in about
536
+ * `CATCH_UP_MS`, never slower than a reading pace: a long batch arrives as quick typing, a short
537
+ * one as a word or two. A target that does not extend what is shown (a new block started) is
538
+ * shown from its own start.
539
+ */
540
+ const CATCH_UP_MS = 700
541
+ const MIN_CHARS_PER_SECOND = 60
542
+
543
+ function useSmoothText(target: string): string {
544
+ const [shown, setShown] = useState(target)
545
+ const shownRef = useRef(target)
546
+ useEffect(() => {
547
+ if (!target.startsWith(shownRef.current)) shownRef.current = ""
548
+ const startLength = shownRef.current.length
549
+ const backlog = target.length - startLength
550
+ const rate = Math.max(MIN_CHARS_PER_SECOND, (backlog * 1000) / CATCH_UP_MS)
551
+ const startedAt = performance.now()
552
+ let frame = 0
553
+ const step = (now: number) => {
554
+ const length = Math.min(target.length, startLength + Math.ceil(((now - startedAt) * rate) / 1000))
555
+ shownRef.current = target.slice(0, length)
556
+ setShown(shownRef.current)
557
+ if (length < target.length) frame = requestAnimationFrame(step)
558
+ }
559
+ frame = requestAnimationFrame(step)
560
+ return () => cancelAnimationFrame(frame)
561
+ }, [target])
562
+ return shown
563
+ }
564
+
565
+ /**
566
+ * The message the agent is writing, before it has finished — what `WorkingEntry` turns into the
567
+ * moment there are words to show. Same marker (the logo, alive), same prose as a finished
568
+ * message, plus a caret: the reader should see one thing growing, then settling into the stored
569
+ * message that replaces it, not two different rows trading places.
570
+ */
571
+ function DraftEntry({ draft, onGrow }: { draft: TaskDraft; onGrow?: () => void }) {
572
+ const text = useSmoothText(draft.text)
573
+ // After the DOM has the new words, before paint: the stream pins the view in the same frame.
574
+ useLayoutEffect(() => {
575
+ onGrow?.()
576
+ }, [text, onGrow])
577
+ return (
578
+ <Entry className="pb-0">
579
+ <SpuntoLogo working tone="flame" size={24} className="absolute left-0 top-0.5 -translate-x-1/2 shadow-sm" />
580
+ <div className="pt-0.5" data-slot="task-draft">
581
+ <AgentMarkdown text={text} />
582
+ <span
583
+ className="ml-0.5 inline-block h-3.5 w-1.5 animate-pulse rounded-[1px] bg-primary/70 align-[-2px]"
584
+ aria-hidden
585
+ />
586
+ </div>
587
+ <p className="mt-1 text-[10px] text-muted-foreground">writing…</p>
588
+ </Entry>
589
+ )
590
+ }
591
+
528
592
  /**
529
593
  * How many tool calls in a row it takes before folding them is worth a disclosure.
530
594
  *
@@ -543,6 +607,24 @@ function useTimeline(events: TaskEvent[]) {
543
607
  return useMemo(() => foldTimeline(events), [events])
544
608
  }
545
609
 
610
+ /**
611
+ * Whether the session's **latest** turn has ended — not whether any turn ever did. A follow-up
612
+ * (a reply, a resume) reopens a session that already has a `session.ended` in its past; reading
613
+ * "any end" as "the end" left every later turn without its "working…" row, or its draft.
614
+ * Walked from the tail: whichever comes first, an end or something that set the agent going
615
+ * again — a new start, a reopening, a message from you.
616
+ */
617
+ export function handedBack(events: TaskEvent[]): boolean {
618
+ for (let i = events.length - 1; i >= 0; i--) {
619
+ const e = events[i]
620
+ // An empty turn (no model call, see `foldTimeline`) is not the agent handing back.
621
+ if (e.type === "session.ended" && !bool(e.payload.empty)) return true
622
+ if (e.type === "session.started" || e.type === "session.reopened") return false
623
+ if (e.type === "message" && str(e.payload.role) === "user") return false
624
+ }
625
+ return false
626
+ }
627
+
546
628
  /** `useTimeline`'s fold, pure — exported for the tests (jsdom cannot lay the list out). */
547
629
  export function foldTimeline(events: TaskEvent[]) {
548
630
  {
@@ -695,13 +777,14 @@ export function foldTimeline(events: TaskEvent[]) {
695
777
 
696
778
 
697
779
 
698
- /** What the virtualizer actually renders — the timeline's items, plus the two rows that are not
699
- * events at all: the reader's own message before it lands, and the "still working" pulse. */
780
+ /** What the list actually renders — the timeline's items, plus the two rows that are not events
781
+ * at all: the reader's own message before it lands, and the "still working" pulse. (The message
782
+ * being written is not a row: see `footer`.) */
700
783
  type Row = Item | { kind: "pending"; text: string; previews?: string[] } | { kind: "working" }
701
784
 
702
785
  /** Content-derived, never the row's index — the index shifts every time older history is
703
- * prepended, and the virtualizer needs a stable key to keep the reader's scroll position across
704
- * that prepend (see the tanstack-virtual chat guide). `seq` is dense and unique per task, so a
786
+ * prepended, and the list needs a stable key to keep the reader's scroll position across that
787
+ * prepend. `seq` is dense and unique per task, so a
705
788
  * tool entry's own call (or the orphaned result standing in for it) is already enough. */
706
789
  function rowKey(row: Row): string | number {
707
790
  if (row.kind === "tool") return row.entry.call.seq
@@ -710,6 +793,25 @@ function rowKey(row: Row): string | number {
710
793
  return row.kind
711
794
  }
712
795
 
796
+ function rowKeyString(row: Row): string {
797
+ return String(rowKey(row))
798
+ }
799
+
800
+ /** What the list averages unknown sizes by — a tool line and a long message are not alike. */
801
+ function rowType(row: Row): string {
802
+ return row.kind === "event" ? row.event.type : row.kind
803
+ }
804
+
805
+ /** Pinned to the end on new rows, on rows that grow, on the panel resizing — never animated:
806
+ * a smooth scroll per token would always be behind. (t3code's `TIMELINE_MAINTAIN_SCROLL_AT_END`.) */
807
+ const MAINTAIN_SCROLL_AT_END: MaintainScrollAtEndOptions = {
808
+ animated: false,
809
+ on: { dataChange: true, itemLayout: true, layout: true, footerLayout: false },
810
+ }
811
+
812
+ /** Older pages prepended, rows above the fold resizing: what the reader looks at stays put. */
813
+ const MAINTAIN_VISIBLE_CONTENT_POSITION = { data: true, size: true }
814
+
713
815
  function Row({
714
816
  row,
715
817
  attachmentUrl,
@@ -735,10 +837,12 @@ function Row({
735
837
  return <BoundaryEntry event={row.event} hideSummary={row.hideSummary} />
736
838
  }
737
839
 
738
- /** How close to the end still counts as "following" — both for the virtualizer's own
739
- * follow-on-append and for the "Jump to latest" button's visibility. */
840
+ /** How close to the end still counts as "at the latest" — the "Jump to latest" button. */
740
841
  const SCROLL_END_THRESHOLD = 48
741
842
 
843
+ /** How long after a wheel, touch, key or pointer press a scroll still counts as the reader's. */
844
+ const GESTURE_WINDOW_MS = 400
845
+
742
846
  /**
743
847
  * How far above the top of the loaded history the next page starts loading, as a multiple of the
744
848
  * viewport — two screens of runway, floored so a short panel (a phone, the cockpit's sidebar)
@@ -771,6 +875,11 @@ export interface TaskEventStreamProps {
771
875
  onLoadOlder?: () => void
772
876
  /** The reader's own message, drawn until its event lands. */
773
877
  pending?: PendingMessage | null
878
+ /**
879
+ * What the agent is writing right now, token by token — drawn in place of "working…" until the
880
+ * finished message lands. Ignored once the session has ended.
881
+ */
882
+ draft?: TaskDraft | null
774
883
  /**
775
884
  * Drawn instead of the default sentence when there is nothing to show yet. A task that has no
776
885
  * session *because its machine is still being built* has plenty to say — it just isn't the
@@ -796,13 +905,13 @@ export function TaskEventStream({
796
905
  olderError = false,
797
906
  onLoadOlder = () => {},
798
907
  pending = null,
908
+ draft = null,
799
909
  emptyState,
800
910
  tabs,
801
911
  className,
802
912
  }: TaskEventStreamProps) {
803
913
  const { items, raw, calls } = useTimeline(events)
804
914
  const [showRaw, setShowRaw] = useState(false)
805
- const parentRef = useRef<HTMLDivElement>(null)
806
915
  const count = events.length
807
916
 
808
917
  // The stack sheet is owned here rather than by the row it is opened from: the list is
@@ -814,7 +923,7 @@ export function TaskEventStream({
814
923
  // An interactive session does not exit between turns, so the task can still read `running`
815
924
  // after the agent has handed back — until something reads the stream. The stream itself knows
816
925
  // about its own end, and says so without waiting for the task row to catch up.
817
- const streaming = live && !events.some((e) => e.type === "session.ended")
926
+ const streaming = live && !handedBack(events)
818
927
 
819
928
  // Derived, never cleared: the optimistic bubble disappears exactly when its own event lands.
820
929
  // Storing "is it still pending?" as state would mean an effect to clear it — a cascade of
@@ -829,76 +938,117 @@ export function TaskEventStream({
829
938
  e.seq > pending.sinceSeq,
830
939
  )
831
940
 
832
- // The two rows that are not events at all, appended so they scroll and anchor like every other
833
- // row instead of living outside the virtualizer's own height accounting.
941
+ // A draft whose finished message is already the last thing on the timeline is the same words
942
+ // twice — possible for one poll if the two ever travel separately.
943
+ const lastEvent = events[events.length - 1]
944
+ const showDraft =
945
+ !!draft?.text.trim() &&
946
+ !(lastEvent?.type === "message" && str(lastEvent.payload.text).trim() === draft.text.trim())
947
+
948
+ // The rows that are not events at all, appended so they scroll and anchor like every other
949
+ // row instead of living outside the list's own height accounting.
834
950
  const rows: Row[] = useMemo(() => {
835
951
  const list: Row[] = items
836
952
  const extra: Row[] = []
837
953
  if (stillPending) extra.push({ kind: "pending", text: pending!.text, previews: pending!.previews })
838
- if (streaming) extra.push({ kind: "working" })
954
+ if (streaming && !showDraft) extra.push({ kind: "working" })
839
955
  return extra.length > 0 ? [...list, ...extra] : list
840
- }, [items, stillPending, pending, streaming])
956
+ }, [items, stillPending, pending, streaming, showDraft])
957
+ const drafting = streaming && showDraft
841
958
 
842
- // ── Scrolling, the way a terminal does ────────────────────────────────────────────────
959
+ // ── Scrolling, the way a chat does ──────────────────────────────────────────────────────
843
960
  //
844
- // Two rules, and the second is the one that makes it feel right rather than merely automatic:
961
+ // The list is `@legendapp/list` (MIT), the one t3code's chat runs on, and the rules are the
962
+ // ones a reader expects of a conversation:
845
963
  //
846
- // 1. **Open at the bottom.** A conversation's newest turn is the one you came for — which is
847
- // also why the cockpit opens this stream on its *tail* rather than its start (see
848
- // the app's events hook). Jumping there instantly (no smooth scroll) on the first paint is what a
849
- // terminal does; animating it would just be a long distraction on a session with hundreds
850
- // of events.
851
- // 2. **Follow only while stuck to the bottom.** The moment the reader scrolls up — to re-read
852
- // a tool result — following would yank the view away every two seconds. `anchorTo: "end"`
853
- // plus `followOnAppend` is tanstack-virtual's own answer to exactly this (its chat guide is
854
- // written for this shape of list): it keeps pinning new rows to the bottom while the reader
855
- // is there, and leaves the scroll position alone — even across a prepend from `onLoadOlder`
856
- // — the moment they are not.
857
- const virtualizer = useVirtualizer({
858
- count: rows.length,
859
- getScrollElement: () => parentRef.current,
860
- estimateSize: () => 64,
861
- getItemKey: (index) => rowKey(rows[index]),
862
- anchorTo: "end",
863
- followOnAppend: true,
864
- scrollEndThreshold: SCROLL_END_THRESHOLD,
865
- overscan: 8,
866
- })
867
-
868
- const firstPaint = useRef(true)
869
- useLayoutEffect(() => {
870
- if (rows.length === 0 || !firstPaint.current) return
871
- firstPaint.current = false
872
- virtualizer.scrollToEnd({ behavior: "instant" })
873
- }, [rows.length, virtualizer])
964
+ // 1. **Open at the bottom** (`initialScrollAtEnd`). The newest turn is the one you came for —
965
+ // which is also why the cockpit opens this stream on its *tail*.
966
+ // 2. **Follow only while stuck to the bottom** (`maintainScrollAtEnd`, plus `pinToEnd` for the
967
+ // draft): a new row, a row that grows, the message being written, or the panel resizing
968
+ // keeps the view at the end *if the reader was there*. Scroll up to re-read a tool result
969
+ // and nothing yanks you back.
970
+ // 3. **Never jump** (`maintainVisibleContentPosition`): older history prepended above, or a row
971
+ // above the fold changing height, leaves what you are reading where it is.
972
+ //
973
+ // These were hand-rolled over `@tanstack/react-virtual` before — scroll-to-end that had to be
974
+ // observed landing, a pin re-applied on every growth of the draft — and still slipped in a
975
+ // real browser. Same settings as t3code's timeline (`MessagesTimeline.tsx`), which does this
976
+ // well: pinned on data, item and layout changes, not animated.
977
+ const listRef = useRef<LegendListRef>(null)
978
+ const [atEnd, setAtEnd] = useState(true)
979
+ // Following, as the **reader** decided it. Only a gesture of theirs — wheel, touch, keys, the
980
+ // scrollbar — can turn it off; a scroll the layout caused cannot. Measured: when the finished
981
+ // message replaced the draft, the content grew 157 px, the list compensated half of it and fired
982
+ // a scroll event 84 px from the end — which, read as "the reader left", stopped following for
983
+ // good. Now such a scroll is put back at the end instead.
984
+ const atEndRef = useRef(true)
985
+ const gestureAt = useRef(0)
986
+ const onScroll = useCallback(() => {
987
+ const root = listRef.current?.getScrollableNode()
988
+ if (!root) return
989
+ const atEndNow = root.scrollHeight - root.scrollTop - root.clientHeight <= SCROLL_END_THRESHOLD
990
+ const byReader = performance.now() - gestureAt.current < GESTURE_WINDOW_MS
991
+ if (atEndNow) atEndRef.current = true
992
+ else if (byReader) atEndRef.current = false
993
+ else if (atEndRef.current) {
994
+ root.scrollTop = root.scrollHeight
995
+ return
996
+ }
997
+ setAtEnd(atEndNow)
998
+ }, [])
999
+ // The draft grows on every frame of its reveal. As a row of the list it was re-pinned one
1000
+ // measurement late — on a real session the last lines trailed up to 81 px below the fold, close
1001
+ // to the list's own "still at the end" threshold, past which it would stop following at all.
1002
+ // So it is not a row: it is the list's footer, in normal flow, whose growth moves the end of
1003
+ // the scroll range in the same layout pass — and each growth pins the view there, before paint,
1004
+ // for a reader who was at the end.
1005
+ const pinToEnd = useCallback(() => {
1006
+ const root = listRef.current?.getScrollableNode()
1007
+ if (root && atEndRef.current) root.scrollTop = root.scrollHeight
1008
+ }, [])
1009
+ // The hand-over: the draft leaves the footer and its finished message arrives as a row, sized
1010
+ // by estimate until measured. Once that row has had a frame to measure, a reader who was
1011
+ // following is put back at the very end — natively, footer included.
1012
+ const wasDrafting = useRef(drafting)
1013
+ useEffect(() => {
1014
+ if (wasDrafting.current === drafting) return
1015
+ wasDrafting.current = drafting
1016
+ if (drafting || !atEndRef.current) return
1017
+ let frame = requestAnimationFrame(() => {
1018
+ frame = requestAnimationFrame(() => {
1019
+ if (atEndRef.current) {
1020
+ const root = listRef.current?.getScrollableNode()
1021
+ if (root) root.scrollTop = root.scrollHeight
1022
+ }
1023
+ })
1024
+ })
1025
+ return () => cancelAnimationFrame(frame)
1026
+ }, [drafting])
874
1027
 
875
1028
  /**
876
- * Has the opening jump *landed*? Until it has, the container is still at offset 0 — which is to
877
- * say sitting on the top sentinel — and arming the observer there reads "the reader is at the
878
- * start of the history" off a view that has not been positioned yet. Measured: it pages
879
- * backwards once, immediately, on every open.
880
- *
881
- * Asking the DOM rather than trusting the call above, because the call above is not the moment:
882
- * the virtualizer lands `scrollToEnd` across the following frames, re-aligning as rows measure
883
- * for real. `scrollTop > 0` is that landing, observed. A stream short enough not to scroll at
884
- * all never gets one — and needs no gate either: its sentinel is honestly on screen, and
885
- * filling the viewport is the right answer.
886
- *
887
- * In dev only, Strict Mode's second mount hands the container back at offset 0 before the
888
- * virtualizer re-lands it, so one extra page is read on open. Nothing to gate: at that instant
889
- * the view really is at the top of what is loaded. It does not happen in a production build.
1029
+ * Has the opening jump *landed*? Until it has, the view is still at offset 0 — sitting on the
1030
+ * top sentinel — and arming the observer there reads "the reader is at the start of the
1031
+ * history" off a view that has not been positioned yet: it paged backwards once, immediately,
1032
+ * on every open. The list says when it is laid out and positioned (`onLoad`).
890
1033
  */
891
1034
  const [opened, setOpened] = useState(false)
1035
+ const onLoad = useCallback(() => setOpened(true), [])
1036
+
892
1037
  useEffect(() => {
893
- const root = parentRef.current
894
- if (opened || !root || rows.length === 0) return
895
- const landed = () => {
896
- if (root.scrollTop > 0 || root.scrollHeight <= root.clientHeight + 1) setOpened(true)
1038
+ const root = listRef.current?.getScrollableNode()
1039
+ if (!root) return
1040
+ const mark = () => {
1041
+ gestureAt.current = performance.now()
1042
+ }
1043
+ const events = ["wheel", "touchmove", "pointerdown"] as const
1044
+ for (const name of events) root.addEventListener(name, mark, { passive: true })
1045
+ // Keys scroll whatever has focus, which is not necessarily the list itself.
1046
+ window.addEventListener("keydown", mark)
1047
+ return () => {
1048
+ for (const name of events) root.removeEventListener(name, mark)
1049
+ window.removeEventListener("keydown", mark)
897
1050
  }
898
- landed()
899
- root.addEventListener("scroll", landed, { passive: true })
900
- return () => root.removeEventListener("scroll", landed)
901
- }, [opened, rows.length])
1051
+ }, [opened])
902
1052
 
903
1053
  // ── Paging backwards, without a button ───────────────────────────────────────────────
904
1054
  //
@@ -923,7 +1073,7 @@ export function TaskEventStream({
923
1073
  loadOlderRef.current = onLoadOlder
924
1074
  })
925
1075
  useEffect(() => {
926
- const root = parentRef.current
1076
+ const root = listRef.current?.getScrollableNode()
927
1077
  const sentinel = topRef.current
928
1078
  if (!root || !sentinel || !opened || !hasMore || olderError || loadingOlder) return
929
1079
  const runway = Math.max(MIN_PREFETCH_DISTANCE, Math.round(root.clientHeight * PREFETCH_SCREENS))
@@ -939,11 +1089,92 @@ export function TaskEventStream({
939
1089
 
940
1090
  const empty = protocol === "none" || count === 0
941
1091
  // Only while there is something to come back to: on a finished session the reader scrolling up
942
- // is just reading, not falling behind.
943
- // Never over the empty state either: that is not a transcript (a queued task's boot panel
944
- // scrolls once its setup timeline unfolds), and a virtualizer measuring nothing always reads as
945
- // "not at the end".
946
- const showJumpToLatest = !empty && streaming && rows.length > 0 && !virtualizer.isAtEnd(SCROLL_END_THRESHOLD)
1092
+ // is just reading, not falling behind. Never over the empty state either: that is not a
1093
+ // transcript (a queued task's boot panel scrolls once its setup timeline unfolds).
1094
+ const showJumpToLatest = !empty && streaming && rows.length > 0 && !atEnd
1095
+
1096
+ // The head of the loaded history, and the observer's sentinel. Always drawn, and always the
1097
+ // **same height**, whichever of its three things it is saying: a block that appeared or
1098
+ // disappeared up here would move every row below it — the one visible jump this whole
1099
+ // mechanism exists to avoid.
1100
+ const header = (
1101
+ // Padding, never margins: the list measures its header's box, and margins outside it were
1102
+ // the 27 px the opening jump fell short of the end by.
1103
+ <div ref={topRef} className="box-content flex h-7 items-center justify-center pb-3 pt-4">
1104
+ {!hasMore ? (
1105
+ <span className="text-[11px] text-muted-foreground/60">Beginning of the session</span>
1106
+ ) : olderError ? (
1107
+ <button
1108
+ type="button"
1109
+ onClick={onLoadOlder}
1110
+ className="rounded-full border border-dashed px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted/50"
1111
+ >
1112
+ Couldn&apos;t load earlier messages — retry
1113
+ </button>
1114
+ ) : (
1115
+ // Reached on its own in the normal case, so this is mostly a status line. It stays a
1116
+ // button for the reader the observer cannot serve: no pointer, a scroll that never fires
1117
+ // it, or simply a wish to go faster than the runway.
1118
+ <button
1119
+ type="button"
1120
+ onClick={onLoadOlder}
1121
+ disabled={loadingOlder}
1122
+ className="flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted/50 disabled:hover:bg-transparent"
1123
+ >
1124
+ {loadingOlder ? (
1125
+ <>
1126
+ <Loader2Icon className="h-3 w-3 animate-spin" />
1127
+ Loading earlier messages…
1128
+ </>
1129
+ ) : (
1130
+ <>
1131
+ <ArrowUpIcon className="h-3 w-3" />
1132
+ Load earlier messages
1133
+ </>
1134
+ )}
1135
+ </button>
1136
+ )}
1137
+ </div>
1138
+ )
1139
+
1140
+ // The bottom space lives here, as padding, rather than on the scroller: the list measures its
1141
+ // own content, and space outside it is space the opening jump falls short of the end by.
1142
+ const footer = (
1143
+ <div className="pb-4">
1144
+ {drafting && (
1145
+ <div className="relative pl-3">
1146
+ <span className="absolute bottom-4 left-3 top-0 w-px bg-border" aria-hidden />
1147
+ <DraftEntry draft={draft!} onGrow={pinToEnd} />
1148
+ </div>
1149
+ )}
1150
+ {showRaw && raw.length > 0 && (
1151
+ <div className="pt-4">
1152
+ <p className="mb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Unmapped events</p>
1153
+ <pre className="max-h-64 overflow-auto rounded-md border bg-muted/40 px-2.5 py-1.5 font-mono text-[10px] leading-relaxed whitespace-pre-wrap break-words">
1154
+ {raw.map((e) => JSON.stringify(e.payload)).join("\n")}
1155
+ </pre>
1156
+ </div>
1157
+ )}
1158
+ </div>
1159
+ )
1160
+
1161
+ const renderItem = useCallback(
1162
+ ({ item, index, data }: LegendListRenderItemProps<Row>) => (
1163
+ // `pl-3`: the list clips each row to its box, and a marker sits centred *on* the rail —
1164
+ // half of it used to hang outside the row. The rail moves in with it.
1165
+ <div className="relative pl-3">
1166
+ {/* The rail, one segment per row: rows are positioned by the list, so a single line
1167
+ drawn behind them would not know where the first marker starts or the last one ends —
1168
+ and a finished session must not trail a line into nothing. */}
1169
+ <span
1170
+ className={cn("absolute left-3 w-px bg-border", index === 0 ? "top-2" : "top-0", index === data.length - 1 && !drafting ? "bottom-4" : "bottom-0")}
1171
+ aria-hidden
1172
+ />
1173
+ <Row row={item} attachmentUrl={attachmentUrl} onOpenStack={openStack} live={live} />
1174
+ </div>
1175
+ ),
1176
+ [attachmentUrl, openStack, live, drafting],
1177
+ )
947
1178
 
948
1179
  return (
949
1180
  <div className={cn("flex min-h-0 flex-1 flex-col", className)}>
@@ -982,110 +1213,66 @@ export function TaskEventStream({
982
1213
  )}
983
1214
  </div>
984
1215
 
985
- <div ref={parentRef} className="relative min-h-0 flex-1 overflow-y-auto px-5 py-4 md:px-8">
986
- {empty && emptyState ? (
987
- emptyState
988
- ) : empty ? (
989
- <div className="flex h-full items-center justify-center">
990
- <p className="max-w-sm text-center text-xs leading-relaxed text-muted-foreground">
991
- {protocol === "none" ? (
992
- <>
993
- This project doesn&apos;t capture its agent session. Set{" "}
994
- <span className="font-mono">Session stream</span> in its delegated-work settings to watch the work as
995
- it happens.
996
- </>
997
- ) : live ? (
998
- "Waiting for the session's first event…"
999
- ) : (
1000
- "The session produced no readable events."
1001
- )}
1002
- </p>
1003
- </div>
1004
- ) : (
1005
- <>
1006
- {/* The head of the loaded history, and the observer's sentinel.
1007
- Always drawn, and always the **same height**, whichever of its three things it is
1008
- saying. A block that appears or disappears up here changes the distance between
1009
- the top of the scroll content and every row below it, which is exactly the
1010
- measurement the virtualizer anchors a prepend against — so a zone that collapsed
1011
- when history ran out would pay for its own tidiness with the one visible jump this
1012
- whole mechanism exists to avoid. */}
1013
- <div ref={topRef} className="mx-auto mb-3 flex h-7 max-w-3xl items-center justify-center">
1014
- {!hasMore ? (
1015
- <span className="text-[11px] text-muted-foreground/60">Beginning of the session</span>
1016
- ) : olderError ? (
1017
- <button
1018
- type="button"
1019
- onClick={onLoadOlder}
1020
- className="rounded-full border border-dashed px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted/50"
1021
- >
1022
- Couldn&apos;t load earlier messages — retry
1023
- </button>
1024
- ) : (
1025
- // Reached on its own in the normal case, so this is mostly a status line. It stays
1026
- // a button for the reader the observer cannot serve: no pointer, a scroll that
1027
- // never fires it, or simply a wish to go faster than the runway.
1028
- <button
1029
- type="button"
1030
- onClick={onLoadOlder}
1031
- disabled={loadingOlder}
1032
- className="flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted/50 disabled:hover:bg-transparent"
1033
- >
1034
- {loadingOlder ? (
1035
- <>
1036
- <Loader2Icon className="h-3 w-3 animate-spin" />
1037
- Loading earlier messages…
1038
- </>
1039
- ) : (
1040
- <>
1041
- <ArrowUpIcon className="h-3 w-3" />
1042
- Load earlier messages
1043
- </>
1044
- )}
1045
- </button>
1046
- )}
1047
- </div>
1048
-
1049
- <div className="relative mx-auto max-w-3xl" style={{ height: virtualizer.getTotalSize() }}>
1050
- {/* The rail. Stops at the last marker rather than the container's edge, so a
1051
- finished session doesn't trail a line into nothing. */}
1052
- <span className="absolute bottom-4 left-0 top-2 w-px bg-border" aria-hidden />
1053
- {virtualizer.getVirtualItems().map((virtualRow) => (
1054
- <div
1055
- key={virtualRow.key}
1056
- data-index={virtualRow.index}
1057
- ref={virtualizer.measureElement}
1058
- className="absolute left-0 top-0 w-full"
1059
- style={{ transform: `translateY(${virtualRow.start}px)` }}
1060
- >
1061
- <Row row={rows[virtualRow.index]} attachmentUrl={attachmentUrl} onOpenStack={openStack} live={live} />
1062
- </div>
1063
- ))}
1216
+ {empty ? (
1217
+ <div className="relative min-h-0 flex-1 overflow-y-auto px-5 py-4 md:px-8">
1218
+ {emptyState ?? (
1219
+ <div className="flex h-full items-center justify-center">
1220
+ <p className="max-w-sm text-center text-xs leading-relaxed text-muted-foreground">
1221
+ {protocol === "none" ? (
1222
+ <>
1223
+ This project doesn&apos;t capture its agent session. Set{" "}
1224
+ <span className="font-mono">Session stream</span> in its delegated-work settings to watch the work as
1225
+ it happens.
1226
+ </>
1227
+ ) : live ? (
1228
+ "Waiting for the session's first event…"
1229
+ ) : (
1230
+ "The session produced no readable events."
1231
+ )}
1232
+ </p>
1064
1233
  </div>
1065
- </>
1066
- )}
1067
-
1068
- {showJumpToLatest && (
1069
- <button
1070
- type="button"
1071
- onClick={() => virtualizer.scrollToEnd({ behavior: "smooth" })}
1072
- className="sticky bottom-2 left-1/2 z-10 -translate-x-1/2 rounded-full border bg-background/95 px-3 py-1 text-[11px] shadow-sm backdrop-blur transition-colors hover:bg-muted"
1073
- >
1074
- Jump to latest ↓
1075
- </button>
1076
- )}
1077
-
1078
- {showRaw && raw.length > 0 && (
1079
- <div className="mx-auto mt-4 max-w-3xl">
1080
- <p className="mb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
1081
- Unmapped events
1082
- </p>
1083
- <pre className="max-h-64 overflow-auto rounded-md border bg-muted/40 px-2.5 py-1.5 font-mono text-[10px] leading-relaxed whitespace-pre-wrap break-words">
1084
- {raw.map((e) => JSON.stringify(e.payload)).join("\n")}
1085
- </pre>
1086
- </div>
1087
- )}
1088
- </div>
1234
+ )}
1235
+ </div>
1236
+ ) : (
1237
+ <div className="relative flex min-h-0 flex-1 flex-col">
1238
+ <LegendList<Row>
1239
+ ref={listRef}
1240
+ data-slot="task-event-list"
1241
+ data={rows}
1242
+ extraData={renderItem}
1243
+ renderItem={renderItem}
1244
+ keyExtractor={rowKeyString}
1245
+ getItemType={rowType}
1246
+ estimatedItemSize={64}
1247
+ initialScrollAtEnd
1248
+ maintainScrollAtEnd={MAINTAIN_SCROLL_AT_END}
1249
+ maintainVisibleContentPosition={MAINTAIN_VISIBLE_CONTENT_POSITION}
1250
+ onScroll={onScroll}
1251
+ onLoad={onLoad}
1252
+ ListHeaderComponent={header}
1253
+ ListFooterComponent={footer}
1254
+ className="min-h-0 flex-1 overflow-x-hidden overscroll-y-contain px-2 [overflow-anchor:none] md:px-5"
1255
+ contentContainerClassName="mx-auto w-full max-w-3xl"
1256
+ />
1257
+ {showJumpToLatest && (
1258
+ <button
1259
+ type="button"
1260
+ // Instant, native, and following again from here. Not the list's `scrollToEnd`: it
1261
+ // aims at the end of the last *row* and stopped short of the footer (67 px, every
1262
+ // time); an animated scroll aims at where the end *was* while a draft moves it.
1263
+ onClick={() => {
1264
+ atEndRef.current = true
1265
+ setAtEnd(true)
1266
+ const root = listRef.current?.getScrollableNode()
1267
+ if (root) root.scrollTop = root.scrollHeight
1268
+ }}
1269
+ className="absolute bottom-2 left-1/2 z-10 -translate-x-1/2 rounded-full border bg-background/95 px-3 py-1 text-[11px] shadow-sm backdrop-blur transition-colors hover:bg-muted"
1270
+ >
1271
+ Jump to latest ↓
1272
+ </button>
1273
+ )}
1274
+ </div>
1275
+ )}
1089
1276
 
1090
1277
  <TaskToolStackSheet
1091
1278
  open={stack.open}
@@ -96,6 +96,7 @@ export type {
96
96
  AttachmentUrl,
97
97
  DraftFile,
98
98
  PendingMessage,
99
+ TaskDraft,
99
100
  TaskCommand,
100
101
  TaskConversation,
101
102
  TaskDiff,
@@ -12,7 +12,7 @@ import { render, screen, fireEvent, waitFor } from "@testing-library/react"
12
12
  import { renderInlineMarkdown } from "./agent-markdown"
13
13
  import { emptyCommandTerminalState, planCommandTerminalWrites } from "./command-terminal"
14
14
  import { TaskComposer } from "./composer"
15
- import { foldTimeline } from "./event-stream"
15
+ import { foldTimeline, handedBack } from "./event-stream"
16
16
  import { TaskBoot, TaskMachine, bootSteps } from "./machine"
17
17
  import { NewTaskComposer } from "./new-task-composer"
18
18
  import { clearTaskDraft, readTaskDraft } from "./prompt-draft"
@@ -715,6 +715,30 @@ describe("an empty turn", () => {
715
715
  })
716
716
  })
717
717
 
718
+ describe("whether the agent has handed back", () => {
719
+ // Taken from a real three-turn task (2026-10-28): a reply, then a resume after the sandbox woke.
720
+ const turns = [
721
+ ev(1, "message", { role: "user", text: "Write a guide" }),
722
+ ev(2, "session.started", { sessionId: "s1" }),
723
+ ev(13, "message", { role: "assistant", text: "# Guide" }),
724
+ ev(15, "message", { role: "user", text: "Now in English" }),
725
+ ev(24, "message", { role: "assistant", text: "# Guide (en)" }),
726
+ ev(27, "session.ended", { status: "succeeded" }),
727
+ ]
728
+
729
+ it("reads the latest turn, not any turn — a follow-up is live again", () => {
730
+ expect(handedBack(turns.slice(0, 3))).toBe(false)
731
+ expect(handedBack(turns)).toBe(true)
732
+ // A reply sent after the end: the agent is on it, even before its session restarts.
733
+ expect(handedBack([...turns, ev(28, "message", { role: "user", text: "Now in Spanish" })])).toBe(false)
734
+ expect(handedBack([...turns, ev(31, "session.started", { sessionId: "s1" }), ev(33, "message", { role: "assistant", text: "# Guía" })])).toBe(false)
735
+ })
736
+
737
+ it("does not count an empty turn as an end", () => {
738
+ expect(handedBack([...turns, ev(28, "session.started", {}), ev(29, "session.ended", { status: "succeeded", empty: true })])).toBe(false)
739
+ })
740
+ })
741
+
718
742
  describe("the composer while a reply is on its way", () => {
719
743
  it("keeps the box writable and holds Send", () => {
720
744
  render(<TaskComposer state="in-review" canResume protocol="claude-stream" pending onSubmit={() => {}} />)
@@ -73,6 +73,16 @@ export interface TaskEvent {
73
73
  payload: Record<string, unknown>
74
74
  }
75
75
 
76
+ /**
77
+ * What the agent is writing **right now** — the text block of a message not finished yet, as its
78
+ * tokens arrive. Transient: the finished `message` event replaces it, and nothing stores it.
79
+ */
80
+ export interface TaskDraft {
81
+ text: string
82
+ /** Cut at the length the finished message will keep. */
83
+ truncated?: boolean
84
+ }
85
+
76
86
  /** A command the platform ran for a task (branch setup, the session, accept…), with its captured tail. */
77
87
  export interface TaskCommand {
78
88
  id: string