@spunto/design-system 0.46.0 → 0.49.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.46.0",
3
+ "version": "0.49.0",
4
4
  "description": "Spunto's shared design system — warm/flame tokens, color constants, and UI primitives.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,10 +1,10 @@
1
1
  "use client"
2
2
 
3
- import { useState } from "react"
4
3
  import { ArrowUpIcon, CornerDownLeftIcon, Loader2Icon, SquareIcon } from "lucide-react"
5
4
 
6
5
  import { cn } from "../../utils"
7
6
  import { Button } from "../button"
7
+ import { useTaskDraft } from "./prompt-draft"
8
8
  import { AttachFileButton, AttachmentDraftStrip, FileDropOverlay, useAttachmentDraft } from "./task-attachments"
9
9
  import type { DraftFile, TaskPendingAction } from "./types"
10
10
 
@@ -65,6 +65,11 @@ export interface TaskComposerProps {
65
65
  * decides, and `TaskCockpitMobile` passes it.
66
66
  */
67
67
  layout?: "default" | "compact"
68
+ /**
69
+ * Keeps what is being written in this browser under this key (the task's id, typically): leave
70
+ * the page mid-sentence and the words are back on return. Forgotten once sent.
71
+ */
72
+ draftKey?: string
68
73
  className?: string
69
74
  }
70
75
 
@@ -78,9 +83,10 @@ export function TaskComposer({
78
83
  pendingAction = null,
79
84
  error = null,
80
85
  layout = "default",
86
+ draftKey,
81
87
  className,
82
88
  }: TaskComposerProps) {
83
- const [prompt, setPrompt] = useState("")
89
+ const [prompt, setPrompt] = useTaskDraft(draftKey)
84
90
  const draft = useAttachmentDraft()
85
91
  const isMobile = layout === "compact"
86
92
 
@@ -106,13 +112,17 @@ export function TaskComposer({
106
112
  ? "No session id was captured for this task, so there is nothing to resume."
107
113
  : null
108
114
 
109
- const disabled = reason !== null || pending
115
+ // A reply on its way does not close the box: it is already held by Spunto (queued, then
116
+ // delivered once the session is back), so the box stays as it was and only Send waits — the
117
+ // next message can be written meanwhile. Greying it all out read as having lost the connection.
118
+ const disabled = reason !== null
119
+ const sendDisabled = disabled || pending
110
120
 
111
121
  function submit() {
112
122
  const text = prompt.trim()
113
123
  // Words are still required with an attachment: "look at this" is a turn, a bare file is a
114
124
  // riddle — and the harness is handed a path, so something has to say what to do with it.
115
- if (!text || disabled) return
125
+ if (!text || sendDisabled) return
116
126
  onSubmit(text, draft.files)
117
127
  setPrompt("")
118
128
  // `release`, not `clear`: the cockpit is now drawing these very thumbnails under the pending
@@ -189,7 +199,7 @@ export function TaskComposer({
189
199
  <button
190
200
  type="button"
191
201
  onClick={submit}
192
- disabled={disabled || !prompt.trim()}
202
+ disabled={sendDisabled || !prompt.trim()}
193
203
  aria-label="Send"
194
204
  className="flex h-10 w-10 shrink-0 touch-manipulation items-center justify-center rounded-full bg-primary text-primary-foreground transition-transform active:scale-95 disabled:opacity-40"
195
205
  >
@@ -223,7 +233,9 @@ export function TaskComposer({
223
233
  <div className="flex items-center gap-2 border-t border-border/60 px-2 py-1.5">
224
234
  <span className="mr-auto truncate text-[10px] text-muted-foreground">
225
235
  {reason ??
226
- (interactive
236
+ (pending
237
+ ? "Your message is queued — Spunto delivers it as soon as the session is ready. Send the next one then."
238
+ : interactive
227
239
  ? // Both paths are real and the composer cannot know which one it will take:
228
240
  // the session is usually still listening, and is resumed if it has exited.
229
241
  "Goes to the live session — or resumes it if it has exited."
@@ -240,7 +252,7 @@ export function TaskComposer({
240
252
  Stop
241
253
  </Button>
242
254
  )}
243
- <Button size="sm" className="h-7 gap-1.5 px-2.5 text-xs" disabled={disabled || !prompt.trim()} onClick={submit}>
255
+ <Button size="sm" className="h-7 gap-1.5 px-2.5 text-xs" disabled={sendDisabled || !prompt.trim()} onClick={submit}>
244
256
  {pending ? <Loader2Icon className="h-3 w-3 animate-spin" /> : <CornerDownLeftIcon className="h-3 w-3" />}
245
257
  Send
246
258
  </Button>
@@ -12,9 +12,23 @@
12
12
  //
13
13
  // Sized by input, not by width: a phone's full-width list and a desktop's 320 px sidebar are the
14
14
  // same width, so what changes is `pointer-coarse` — bigger rows and a drawn chevron for a thumb.
15
+ //
16
+ // Archiving (optional): an « Archived » switch at the end of the chips flips the list to the other
17
+ // side of the archive, a finished row gets its own Archive button on hover, and « Select » turns
18
+ // the rows into checkboxes for doing it in bulk. Only `done`/`failed` rows can be put away — a live
19
+ // conversation is dropped, not archived — so live rows cannot be picked.
15
20
 
16
- import type { ReactNode } from "react"
17
- import { ChevronRightIcon, Loader2Icon, MessagesSquareIcon, SearchIcon } from "lucide-react"
21
+ import { useState, type ReactNode } from "react"
22
+ import {
23
+ ArchiveIcon,
24
+ ArchiveRestoreIcon,
25
+ CheckSquareIcon,
26
+ ChevronRightIcon,
27
+ Loader2Icon,
28
+ MessagesSquareIcon,
29
+ SearchIcon,
30
+ SquareIcon,
31
+ } from "lucide-react"
18
32
 
19
33
  import { cn, formatRelativeTime } from "../../utils"
20
34
  import { Button } from "../button"
@@ -46,6 +60,21 @@ export interface TaskConversationListProps<T extends TaskConversation = TaskConv
46
60
  /** How many the next page brings, for the button's label. @default 40 */
47
61
  pageSize?: number
48
62
 
63
+ /** Which side of the archive is listed. Without `onArchivedChange` there is no « Archived » switch. */
64
+ archived?: boolean
65
+ onArchivedChange?: (archived: boolean) => void
66
+ /** How many archived conversations match the search — drawn on the switch. */
67
+ archivedCount?: number
68
+ /**
69
+ * Archive (`true`) or unarchive (`false`) these conversations — a row's own button, or the
70
+ * selection. Only finished rows offer it. Omitted → no row button and no selection mode.
71
+ */
72
+ onArchiveChange?: (tasks: T[], archived: boolean) => void
73
+ /** « Archive all finished » in selection mode — every done/failed conversation, not just the loaded ones. Omitted → not offered. */
74
+ onArchiveAllFinished?: () => void
75
+ /** An archive change is in flight: the selection's buttons wait for it. */
76
+ archiving?: boolean
77
+
49
78
  /** @default "Agents" */
50
79
  title?: string
51
80
  /** Next to the title — typically the "New" task button. */
@@ -92,21 +121,49 @@ function RowTime({ task }: { task: TaskConversation }) {
92
121
  )
93
122
  }
94
123
 
95
- function ConversationRow({ task, selected, onSelect }: { task: TaskConversation; selected: boolean; onSelect: () => void }) {
124
+ const isFinished = (task: TaskConversation) => task.state === "done" || task.state === "failed"
125
+
126
+ function ConversationRow({
127
+ task,
128
+ selected,
129
+ onSelect,
130
+ picking,
131
+ picked,
132
+ onArchiveChange,
133
+ }: {
134
+ task: TaskConversation
135
+ selected: boolean
136
+ onSelect: () => void
137
+ /** Selection mode: the row is a checkbox, `onSelect` toggles it. */
138
+ picking?: boolean
139
+ picked?: boolean
140
+ /** A finished row's own Archive/Unarchive button, on hover. */
141
+ onArchiveChange?: (archived: boolean) => void
142
+ }) {
96
143
  const tone = task.pendingAction ? taskPendingActionConfig[task.pendingAction].textClass : taskStateStyle(task.state).textClass
97
- return (
144
+ const pickable = isFinished(task) && !task.pendingAction
145
+ const archived = Boolean(task.userArchivedAt)
146
+ const row = (
98
147
  <button
99
148
  type="button"
100
149
  onClick={onSelect}
101
- aria-current={selected || undefined}
150
+ disabled={picking && !pickable}
151
+ aria-current={(!picking && selected) || undefined}
152
+ aria-pressed={picking ? picked : undefined}
102
153
  className={cn(
103
- "w-full touch-manipulation border-b border-border/50 px-3 py-2.5 text-left transition-colors active:bg-muted pointer-coarse:px-4 pointer-coarse:py-3",
104
- selected ? "bg-primary/[0.07]" : "hover:bg-muted/50",
154
+ "w-full touch-manipulation border-b border-border/50 px-3 py-2.5 text-left transition-colors active:bg-muted disabled:opacity-40 pointer-coarse:px-4 pointer-coarse:py-3",
155
+ (picking ? picked : selected) ? "bg-primary/[0.07]" : "hover:bg-muted/50",
105
156
  )}
106
157
  >
107
158
  <div className="flex items-center gap-2">
108
- <span className={cn("shrink-0", tone)}>
109
- {task.pendingAction ? <Loader2Icon className="h-3 w-3 animate-spin" /> : <TaskStateIcon state={task.state} />}
159
+ <span className={cn("shrink-0", picking ? (picked ? "text-primary" : "text-muted-foreground") : tone)}>
160
+ {picking ? (
161
+ picked ? <CheckSquareIcon className="h-3 w-3" /> : <SquareIcon className="h-3 w-3" />
162
+ ) : task.pendingAction ? (
163
+ <Loader2Icon className="h-3 w-3 animate-spin" />
164
+ ) : (
165
+ <TaskStateIcon state={task.state} />
166
+ )}
110
167
  </span>
111
168
  <span className={cn("min-w-0 flex-1 truncate text-xs pointer-coarse:text-sm", selected ? "font-semibold" : "font-medium")}>
112
169
  {task.title}
@@ -125,6 +182,23 @@ function ConversationRow({ task, selected, onSelect }: { task: TaskConversation;
125
182
  )}
126
183
  </button>
127
184
  )
185
+ if (picking || !onArchiveChange || !pickable) return row
186
+ return (
187
+ <div className="group relative">
188
+ {row}
189
+ {/* A sibling of the row, not inside it: a button in a button is not a button. Over the time
190
+ on hover, and absent on touch — which has no hover, and has « Select » instead. */}
191
+ <button
192
+ type="button"
193
+ onClick={() => onArchiveChange(!archived)}
194
+ aria-label={archived ? "Unarchive" : "Archive"}
195
+ title={archived ? "Unarchive" : "Archive"}
196
+ className="absolute top-1.5 right-1.5 flex h-6 w-6 items-center justify-center rounded-md border border-border bg-card text-muted-foreground opacity-0 shadow-sm transition-opacity group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100 pointer-coarse:hidden"
197
+ >
198
+ {archived ? <ArchiveRestoreIcon className="h-3.5 w-3.5" /> : <ArchiveIcon className="h-3.5 w-3.5" />}
199
+ </button>
200
+ </div>
201
+ )
128
202
  }
129
203
 
130
204
  export function TaskConversationList<T extends TaskConversation>({
@@ -140,10 +214,35 @@ export function TaskConversationList<T extends TaskConversation>({
140
214
  onStatesChange,
141
215
  onLoadMore,
142
216
  pageSize = 40,
217
+ archived = false,
218
+ onArchivedChange,
219
+ archivedCount,
220
+ onArchiveChange,
221
+ onArchiveAllFinished,
222
+ archiving = false,
143
223
  title = "Agents",
144
224
  action,
145
225
  className,
146
226
  }: TaskConversationListProps<T>) {
227
+ const [picking, setPicking] = useState(false)
228
+ const [picked, setPicked] = useState<ReadonlySet<string>>(new Set())
229
+ // What is picked *and still listed*: a row that left the page (archived by someone else, or
230
+ // filtered out) is no longer part of the selection.
231
+ const pickedTasks = tasks.filter((t) => picked.has(t.id) && isFinished(t) && !t.pendingAction)
232
+ const stopPicking = () => {
233
+ setPicking(false)
234
+ setPicked(new Set())
235
+ }
236
+ const togglePick = (task: T) =>
237
+ setPicked((prev) => {
238
+ const next = new Set(prev)
239
+ if (next.has(task.id)) next.delete(task.id)
240
+ else next.add(task.id)
241
+ return next
242
+ })
243
+ const finishedLoaded = tasks.filter((t) => isFinished(t) && !t.pendingAction)
244
+ const finishedCount = (counts.done ?? 0) + (counts.failed ?? 0)
245
+
147
246
  const groups = TASK_STATE_ORDER.map((state) => ({ state, rows: tasks.filter((t) => t.state === state) })).filter(
148
247
  (g) => g.rows.length > 0,
149
248
  )
@@ -159,7 +258,20 @@ export function TaskConversationList<T extends TaskConversation>({
159
258
  <span className="text-[10px] text-muted-foreground">
160
259
  {total !== undefined ? `${tasks.length} of ${total}` : loading ? "…" : null}
161
260
  </span>
162
- {action && <div className="ml-auto">{action}</div>}
261
+ <div className="ml-auto flex items-center gap-1">
262
+ {onArchiveChange && (
263
+ <Button
264
+ variant="ghost"
265
+ size="sm"
266
+ aria-pressed={picking}
267
+ onClick={() => (picking ? stopPicking() : setPicking(true))}
268
+ className="h-7 px-2 text-[11px] text-muted-foreground"
269
+ >
270
+ {picking ? "Done" : "Select"}
271
+ </Button>
272
+ )}
273
+ {action}
274
+ </div>
163
275
  </div>
164
276
 
165
277
  <div className="relative">
@@ -187,14 +299,84 @@ export function TaskConversationList<T extends TaskConversation>({
187
299
  onClick={() => toggle(state)}
188
300
  />
189
301
  ))}
302
+ {onArchivedChange && (
303
+ <button
304
+ type="button"
305
+ onClick={() => {
306
+ stopPicking()
307
+ onArchivedChange(!archived)
308
+ }}
309
+ aria-pressed={archived}
310
+ className={cn(
311
+ "flex shrink-0 touch-manipulation items-center gap-1 rounded-full border border-dashed px-2.5 py-1 text-[11px] font-medium transition-colors active:bg-muted pointer-coarse:px-3 pointer-coarse:py-1.5 pointer-coarse:text-[12px]",
312
+ archived ? "border-solid border-foreground/30 bg-muted text-foreground" : "text-muted-foreground hover:bg-muted/60",
313
+ )}
314
+ >
315
+ <ArchiveIcon className="h-3 w-3" />
316
+ Archived
317
+ {archivedCount !== undefined && <span className={cn("tabular-nums", !archived && "text-muted-foreground/70")}>{archivedCount}</span>}
318
+ </button>
319
+ )}
190
320
  </div>
321
+
322
+ {/* The selection's own bar: what is picked, and the two ways to pick faster. */}
323
+ {picking && onArchiveChange && (
324
+ <div className="flex flex-wrap items-center gap-1.5 rounded-md bg-muted/60 px-2 py-1.5 text-[11px]">
325
+ <span className="tabular-nums text-muted-foreground">{pickedTasks.length} selected</span>
326
+ {finishedLoaded.length > 0 && (
327
+ <button
328
+ type="button"
329
+ className="text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
330
+ onClick={() => setPicked(new Set(finishedLoaded.map((t) => t.id)))}
331
+ >
332
+ Select finished ({finishedLoaded.length})
333
+ </button>
334
+ )}
335
+ <Button
336
+ size="sm"
337
+ disabled={pickedTasks.length === 0 || archiving}
338
+ onClick={() => {
339
+ onArchiveChange(pickedTasks, !archived)
340
+ stopPicking()
341
+ }}
342
+ className="ml-auto h-6 gap-1 px-2 text-[11px]"
343
+ >
344
+ {archiving ? (
345
+ <Loader2Icon className="h-3 w-3 animate-spin" />
346
+ ) : archived ? (
347
+ <ArchiveRestoreIcon className="h-3 w-3" />
348
+ ) : (
349
+ <ArchiveIcon className="h-3 w-3" />
350
+ )}
351
+ {archived ? "Unarchive" : "Archive"}
352
+ </Button>
353
+ {/* Not under a search: « all » would then mean more than the list is showing. */}
354
+ {!archived && !query.trim() && onArchiveAllFinished && finishedCount > 0 && (
355
+ <button
356
+ type="button"
357
+ disabled={archiving}
358
+ className="basis-full text-left text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:opacity-50"
359
+ onClick={() => {
360
+ onArchiveAllFinished()
361
+ stopPicking()
362
+ }}
363
+ >
364
+ Archive all finished conversations…
365
+ </button>
366
+ )}
367
+ </div>
368
+ )}
191
369
  </div>
192
370
 
193
371
  <div className="min-h-0 flex-1 overflow-y-auto">
194
372
  {loading && tasks.length === 0 && <p className="px-3 py-4 text-xs text-muted-foreground">Loading…</p>}
195
373
  {!loading && tasks.length === 0 && (
196
374
  <p className="px-3 py-4 text-xs leading-relaxed text-muted-foreground">
197
- {query || states.length > 0 ? "No conversation matches that filter." : "No delegated work yet. Open a project and start a task."}
375
+ {query || states.length > 0
376
+ ? "No conversation matches that filter."
377
+ : archived
378
+ ? "No archived conversation. Archive a finished one to put it here."
379
+ : "No delegated work yet. Open a project and start a task."}
198
380
  </p>
199
381
  )}
200
382
 
@@ -205,7 +387,15 @@ export function TaskConversationList<T extends TaskConversation>({
205
387
  <span className="ml-1.5 tabular-nums opacity-60">{group.rows.length}</span>
206
388
  </p>
207
389
  {group.rows.map((task) => (
208
- <ConversationRow key={task.id} task={task} selected={task.id === selectedId} onSelect={() => onSelect(task)} />
390
+ <ConversationRow
391
+ key={task.id}
392
+ task={task}
393
+ selected={task.id === selectedId}
394
+ onSelect={() => (picking ? togglePick(task) : onSelect(task))}
395
+ picking={picking}
396
+ picked={picked.has(task.id)}
397
+ onArchiveChange={onArchiveChange && ((value) => onArchiveChange([task], value))}
398
+ />
209
399
  ))}
210
400
  </div>
211
401
  ))}
@@ -7,6 +7,7 @@ import {
7
7
  BrainIcon,
8
8
  CheckIcon,
9
9
  ChevronRightIcon,
10
+ CircleAlertIcon,
10
11
  CircleDotIcon,
11
12
  CircleIcon,
12
13
  FlagIcon,
@@ -63,9 +64,27 @@ import type { AttachmentUrl, PendingMessage, TaskEvent } from "./types"
63
64
  const str = (v: unknown): string => (typeof v === "string" ? v : "")
64
65
  const bool = (v: unknown): boolean => v === true
65
66
 
67
+ /**
68
+ * Where a queued reply stands on its way to the session — read off the events that follow it.
69
+ *
70
+ * A reply to a task whose session is not listening (its machine parked, its process gone) is
71
+ * stored by Spunto at once (`message` with `queued: true`) and delivered by a job that may first
72
+ * have to wake the machine: a minute, for a sandbox. The platform writes the steps into the stream
73
+ * (`machine.wake` starting/awake, `reply.failed`), and the harness's own `session.started` is the
74
+ * delivery. Derived here, never stored: the stream is append-only and already says it all.
75
+ */
76
+ export interface ReplyDelivery {
77
+ status: "queued" | "waking" | "resuming" | "delivered" | "failed"
78
+ /** `sandbox` | `worker`, once a wake has said so. */
79
+ machineKind?: string
80
+ wakeStartedAt?: string
81
+ wakeMs?: number
82
+ error?: string
83
+ }
84
+
66
85
  type Item =
67
86
  /** `hideSummary` — see `useTimeline`: the end-of-session result is often the last message again. */
68
- | { kind: "event"; event: TaskEvent; hideSummary?: boolean }
87
+ | { kind: "event"; event: TaskEvent; hideSummary?: boolean; delivery?: ReplyDelivery }
69
88
  | { kind: "tool"; entry: ToolCall }
70
89
  /** A chain of machinery, folded — see `tool-stack.tsx`. */
71
90
  | { kind: "run"; run: ToolRun }
@@ -286,7 +305,95 @@ function EventTime({ ts }: { ts: TaskEvent["ts"] }) {
286
305
  )
287
306
  }
288
307
 
289
- function MessageEntry({ event, attachmentUrl }: { event: TaskEvent; attachmentUrl: AttachmentUrl }) {
308
+ /** "sandbox"/"worker" → what to call it in a sentence. */
309
+ function machineNoun(kind: string | undefined): string {
310
+ return kind === "worker" ? "worker" : kind === "sandbox" ? "sandbox" : "machine"
311
+ }
312
+
313
+ function seconds(ms: number | undefined): string | null {
314
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return null
315
+ return ms < 1000 ? "under a second" : `${Math.round(ms / 1000)} s`
316
+ }
317
+
318
+ function StepLine({ state, children }: { state: "done" | "active" | "failed"; children: ReactNode }) {
319
+ return (
320
+ <li className="flex items-start gap-2 text-[11px] leading-5">
321
+ <span className="mt-1 shrink-0">
322
+ {state === "done" ? (
323
+ <CheckIcon className="h-3 w-3 text-green-600 dark:text-green-500" />
324
+ ) : state === "failed" ? (
325
+ <CircleAlertIcon className="h-3 w-3 text-destructive" />
326
+ ) : (
327
+ <Loader2Icon className="h-3 w-3 animate-spin text-primary" />
328
+ )}
329
+ </span>
330
+ <span className={cn(state === "active" ? "text-foreground" : state === "failed" ? "text-destructive" : "text-muted-foreground")}>
331
+ {children}
332
+ </span>
333
+ </li>
334
+ )
335
+ }
336
+
337
+ /**
338
+ * Under a queued reply: sent, held by Spunto, and where it is on its way — the machine waking,
339
+ * then the session resuming — the same steps, in the same place, a first start shows. Once
340
+ * delivered it folds to one muted line; the reader no longer needs the steps, only that it arrived.
341
+ */
342
+ function DeliveryTracker({ delivery, live, ts }: { delivery: ReplyDelivery; live: boolean; ts: string }) {
343
+ const noun = machineNoun(delivery.machineKind)
344
+ const waking = useElapsed(delivery.status === "waking" ? delivery.wakeStartedAt : null)
345
+ const waited = useElapsed(delivery.status === "queued" || delivery.status === "resuming" ? ts : null)
346
+ const woke = seconds(delivery.wakeMs)
347
+
348
+ if (delivery.status === "delivered") {
349
+ return (
350
+ <p className="mt-1 flex items-center gap-1 text-[10px] text-muted-foreground" data-slot="reply-delivery" data-status="delivered">
351
+ <CheckIcon className="h-3 w-3 text-green-600 dark:text-green-500" />
352
+ Delivered{woke ? ` · the ${noun} woke in ${woke}` : ""}
353
+ </p>
354
+ )
355
+ }
356
+ // A task that moved on (dropped, accepted) without the reply ever starting a turn.
357
+ const failed = delivery.status === "failed" || !live
358
+ return (
359
+ <ul
360
+ className="mt-1.5 space-y-0.5 rounded-md border border-border/70 bg-card/60 px-2.5 py-1.5"
361
+ data-slot="reply-delivery"
362
+ data-status={failed ? "failed" : delivery.status}
363
+ >
364
+ <StepLine state="done">Sent — queued on Spunto</StepLine>
365
+ {delivery.wakeStartedAt && (
366
+ <StepLine state={delivery.status === "waking" && !failed ? "active" : delivery.status === "waking" ? "failed" : "done"}>
367
+ {delivery.status === "waking"
368
+ ? `Waking the ${noun}…${waking ? ` ${waking}` : ""}`
369
+ : `The ${noun} is awake${woke ? ` · ${woke}` : ""}`}
370
+ </StepLine>
371
+ )}
372
+ {failed ? (
373
+ <StepLine state="failed">Not delivered{delivery.error ? ` — ${delivery.error}` : ""}</StepLine>
374
+ ) : (
375
+ delivery.status !== "waking" && (
376
+ <StepLine state="active">
377
+ {delivery.status === "resuming" ? "Resuming the session…" : "Waiting for the session — delivered as soon as it is ready"}
378
+ {waited ? ` ${waited}` : ""}
379
+ </StepLine>
380
+ )
381
+ )}
382
+ </ul>
383
+ )
384
+ }
385
+
386
+ function MessageEntry({
387
+ event,
388
+ attachmentUrl,
389
+ delivery,
390
+ live = true,
391
+ }: {
392
+ event: TaskEvent
393
+ attachmentUrl: AttachmentUrl
394
+ delivery?: ReplyDelivery
395
+ live?: boolean
396
+ }) {
290
397
  // What *you* said, set apart from what the agent said. Without this the timeline reads as one
291
398
  // voice — and a harness does not echo its own stdin, so these lines exist only because the
292
399
  // platform wrote them down (see `appendPlatformEvent`).
@@ -312,6 +419,7 @@ function MessageEntry({ event, attachmentUrl }: { event: TaskEvent; attachmentUr
312
419
  {bool(event.payload.truncated) && (
313
420
  <p className="mt-1 text-[10px] text-muted-foreground">Clipped to the 8 KiB kept per field.</p>
314
421
  )}
422
+ {delivery && <DeliveryTracker delivery={delivery} live={live} ts={event.ts} />}
315
423
  <EventTime ts={event.ts} />
316
424
  </Entry>
317
425
  )
@@ -372,26 +480,30 @@ function ReopenedEntry({ event }: { event: TaskEvent }) {
372
480
  )
373
481
  }
374
482
 
483
+ /**
484
+ * Your message, between the click and its own event. Drawn as what it is — a message of yours,
485
+ * on its way — and not dashed and greyed: that read as being offline, on a reply that can take a
486
+ * minute to start because the machine is waking (the stored message then takes over, with its
487
+ * `DeliveryTracker`).
488
+ */
375
489
  function PendingEntry({ text, previews = [] }: { text: string; previews?: string[] }) {
376
490
  return (
377
491
  <Entry>
378
- <Marker icon={<UserIcon className="h-3 w-3" />} tone="muted" />
379
- <div className="rounded-lg border border-dashed bg-muted/30 px-3 py-2">
380
- <p className="whitespace-pre-wrap break-words text-sm leading-6 text-muted-foreground">
381
- {renderInlineMarkdown(text, "pending")}
382
- </p>
492
+ <Marker icon={<UserIcon className="h-3 w-3" />} tone="primary" />
493
+ <div className="rounded-lg border border-primary/25 bg-primary/[0.06] px-3 py-2">
494
+ <p className="whitespace-pre-wrap break-words text-sm leading-6">{renderInlineMarkdown(text, "pending")}</p>
383
495
  {previews.length > 0 && (
384
496
  <div className="mt-2 flex flex-wrap gap-2">
385
497
  {previews.map((src) => (
386
- <img key={src} src={src} alt="" className="max-h-24 rounded-md border opacity-70" />
498
+ <img key={src} src={src} alt="" className="max-h-24 rounded-md border" />
387
499
  ))}
388
500
  </div>
389
501
  )}
390
- <p className="mt-1 flex items-center gap-1.5 text-[10px] text-muted-foreground">
391
- <span className="h-1 w-1 animate-pulse rounded-full bg-muted-foreground" />
392
- sending…
393
- </p>
394
502
  </div>
503
+ <p className="mt-1 flex items-center gap-1 text-[10px] text-muted-foreground" data-slot="reply-sending">
504
+ <Loader2Icon className="h-3 w-3 animate-spin" />
505
+ Sending…
506
+ </p>
395
507
  </Entry>
396
508
  )
397
509
  }
@@ -428,13 +540,64 @@ const RUN_THRESHOLD = 2
428
540
  * happens here — the stored stream stays flat.
429
541
  */
430
542
  function useTimeline(events: TaskEvent[]) {
431
- return useMemo(() => {
543
+ return useMemo(() => foldTimeline(events), [events])
544
+ }
545
+
546
+ /** `useTimeline`'s fold, pure — exported for the tests (jsdom cannot lay the list out). */
547
+ export function foldTimeline(events: TaskEvent[]) {
548
+ {
432
549
  const flat: Item[] = []
433
550
  const byCallId = new Map<string, ToolCall>()
434
551
  const raw: TaskEvent[] = []
435
552
  let lastMessage = ""
553
+ // The queued reply whose way to the session the events below are still telling.
554
+ let tracking: ReplyDelivery | null = null
436
555
 
437
556
  for (const event of events) {
557
+ // ── A queued reply, and its way to the session ──
558
+ if (event.type === "machine.wake" || event.type === "reply.failed") {
559
+ // Steps of a delivery, drawn under the message they are about rather than as rows. One
560
+ // with no queued message before it (a wake by hand, an older stream) has nothing to add
561
+ // that the machine panel does not already say.
562
+ if (tracking && event.type === "reply.failed") {
563
+ tracking.status = "failed"
564
+ tracking.error = str(event.payload.error) || undefined
565
+ tracking = null
566
+ } else if (tracking && str(event.payload.phase) === "starting") {
567
+ tracking.status = "waking"
568
+ tracking.machineKind = str(event.payload.kind) || undefined
569
+ tracking.wakeStartedAt = event.ts
570
+ } else if (tracking && str(event.payload.phase) === "awake") {
571
+ tracking.status = "resuming"
572
+ tracking.machineKind ??= str(event.payload.kind) || undefined
573
+ tracking.wakeStartedAt ??= event.ts
574
+ tracking.wakeMs = typeof event.payload.ms === "number" ? event.payload.ms : undefined
575
+ }
576
+ continue
577
+ }
578
+ if (event.type === "session.started" && tracking) {
579
+ tracking.status = "delivered"
580
+ tracking = null
581
+ }
582
+ if (event.type === "message" && str(event.payload.role) === "user") {
583
+ tracking = null
584
+ if (bool(event.payload.queued)) {
585
+ const delivery: ReplyDelivery = { status: "queued" }
586
+ flat.push({ kind: "event", event, delivery })
587
+ tracking = delivery
588
+ continue
589
+ }
590
+ }
591
+ // A turn the harness played without calling the model (flagged by the platform, `empty`):
592
+ // Claude Code reporting orphaned background tasks as it resumes. « Session finished » with
593
+ // nothing in it, an instant after a reply, read as the task having ended — so neither it
594
+ // nor the start it closes is drawn.
595
+ if (event.type === "session.ended" && bool(event.payload.empty)) {
596
+ const last = flat[flat.length - 1]
597
+ if (last?.kind === "event" && last.event.type === "session.started") flat.pop()
598
+ continue
599
+ }
600
+
438
601
  if (
439
602
  event.type === "raw" ||
440
603
  event.type === "usage" ||
@@ -527,7 +690,7 @@ function useTimeline(events: TaskEvent[]) {
527
690
  }
528
691
 
529
692
  return { items, raw, calls }
530
- }, [events])
693
+ }
531
694
  }
532
695
 
533
696
 
@@ -551,10 +714,12 @@ function Row({
551
714
  row,
552
715
  attachmentUrl,
553
716
  onOpenStack,
717
+ live,
554
718
  }: {
555
719
  row: Row
556
720
  attachmentUrl: AttachmentUrl
557
721
  onOpenStack: (seq: number) => void
722
+ live: boolean
558
723
  }) {
559
724
  if (row.kind === "pending") return <PendingEntry text={row.text} previews={row.previews} />
560
725
  if (row.kind === "working") return <WorkingEntry />
@@ -564,7 +729,8 @@ function Row({
564
729
  return <ToolEntry entry={row.entry} attachmentUrl={attachmentUrl} onOpenStack={onOpenStack} />
565
730
  if (row.event.type === "thinking") return <ThinkingEntry event={row.event} />
566
731
  if (row.event.type === "plan") return <PlanEntry event={row.event} />
567
- if (row.event.type === "message") return <MessageEntry event={row.event} attachmentUrl={attachmentUrl} />
732
+ if (row.event.type === "message")
733
+ return <MessageEntry event={row.event} attachmentUrl={attachmentUrl} delivery={row.delivery} live={live} />
568
734
  if (row.event.type === "session.reopened") return <ReopenedEntry event={row.event} />
569
735
  return <BoundaryEntry event={row.event} hideSummary={row.hideSummary} />
570
736
  }
@@ -892,7 +1058,7 @@ export function TaskEventStream({
892
1058
  className="absolute left-0 top-0 w-full"
893
1059
  style={{ transform: `translateY(${virtualRow.start}px)` }}
894
1060
  >
895
- <Row row={rows[virtualRow.index]} attachmentUrl={attachmentUrl} onOpenStack={openStack} />
1061
+ <Row row={rows[virtualRow.index]} attachmentUrl={attachmentUrl} onOpenStack={openStack} live={live} />
896
1062
  </div>
897
1063
  ))}
898
1064
  </div>
@@ -33,9 +33,10 @@ export { NewTaskDialog } from "./new-task-dialog"
33
33
  export type { NewTaskCustomField, NewTaskDialogProps, NewTaskModelGroup, NewTaskValue } from "./new-task-dialog"
34
34
  export { NewTaskComposer, newTaskChipClassName } from "./new-task-composer"
35
35
  export type { NewTaskComposerProps } from "./new-task-composer"
36
+ export { clearTaskDraft, readTaskDraft, useTaskDraft } from "./prompt-draft"
36
37
 
37
38
  // ── The cockpit ─────────────────────────────────────────────────────────────────────────────
38
- export { TaskCockpit, TaskPanelTabs } from "./task-cockpit"
39
+ export { TaskArchiveButton, TaskArchivedBadge, TaskCockpit, TaskPanelTabs } from "./task-cockpit"
39
40
  export type { TaskCockpitProps, TaskCockpitView } from "./task-cockpit"
40
41
  export { TaskCockpitMobile, useVisualViewport } from "./task-cockpit-mobile"
41
42
  export type { TaskCockpitMobileProps, VisualViewportState } from "./task-cockpit-mobile"
@@ -46,7 +47,7 @@ export type { TaskDetailsProps } from "./task-details"
46
47
 
47
48
  // ── The conversation ────────────────────────────────────────────────────────────────────────
48
49
  export { TaskEventStream } from "./event-stream"
49
- export type { TaskEventStreamProps } from "./event-stream"
50
+ export type { ReplyDelivery, TaskEventStreamProps } from "./event-stream"
50
51
  export { TaskComposer } from "./composer"
51
52
  export type { TaskComposerProps } from "./composer"
52
53
  export { AgentMarkdown, renderInlineMarkdown } from "./agent-markdown"
@@ -23,9 +23,9 @@ import { cn } from "../../utils"
23
23
  import { Button } from "../button"
24
24
  import { buttonVariants } from "../button-variants"
25
25
  import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxGroup, ComboboxItem, ComboboxList, ComboboxSearch, ComboboxTrigger, ComboboxValue } from "../combobox"
26
- import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../select"
27
26
  import type { LinkRender } from "../workers/worker-card"
28
27
  import type { NewTaskCustomField, NewTaskModelGroup, NewTaskValue } from "./new-task-dialog"
28
+ import { useTaskDraft } from "./prompt-draft"
29
29
  import { AttachFileButton, AttachmentDraftStrip, FileDropOverlay, useAttachmentDraft } from "./task-attachments"
30
30
 
31
31
  /**
@@ -39,6 +39,11 @@ export const newTaskChipClassName =
39
39
  export interface NewTaskComposerProps {
40
40
  /** Pass the org's projects when no project is in scope: a chip then asks for one, and Delegate waits for it. */
41
41
  projects?: { id: string; name: string }[]
42
+ /**
43
+ * The project the chip starts on — the organization's default, typically — until someone picks
44
+ * another. Ignored when it is not in `projects`.
45
+ */
46
+ defaultProjectId?: string | null
42
47
  /** Called when a project is picked, so the app can load that project's branches and default model. */
43
48
  onProjectChange?: (projectId: string) => void
44
49
  /** Branches common to the project's repositories. Any name typed is accepted too. */
@@ -66,6 +71,12 @@ export interface NewTaskComposerProps {
66
71
  submitting?: boolean
67
72
  error?: string | null
68
73
 
74
+ /**
75
+ * Keeps the prompt being written in this browser under this key, so leaving the page does not
76
+ * lose it. The app forgets it (`clearTaskDraft`) once the task exists.
77
+ */
78
+ draftKey?: string
79
+
69
80
  /** Top bar title. @default "New task" */
70
81
  title?: ReactNode
71
82
  /** One line under the question in the empty transcript — where it will run, typically. */
@@ -158,8 +169,57 @@ function FreeTextChip({
158
169
  )
159
170
  }
160
171
 
172
+ /**
173
+ * The project, found by typing: an organization has dozens, and scrolling a menu for one whose
174
+ * name you know is the slow way. Highlighted while nothing is picked — Delegate waits for it.
175
+ */
176
+ function ProjectChip({
177
+ projects,
178
+ value,
179
+ defaultProjectId,
180
+ onChange,
181
+ }: {
182
+ projects: { id: string; name: string }[]
183
+ value: string
184
+ defaultProjectId: string | null
185
+ onChange: (projectId: string) => void
186
+ }) {
187
+ const name = projects.find((p) => p.id === value)?.name
188
+ return (
189
+ <Combobox
190
+ value={value || null}
191
+ // The search row shows a name, never an id.
192
+ itemToStringLabel={(id) => projects.find((p) => p.id === id)?.name ?? ""}
193
+ onValueChange={(next) => {
194
+ if (typeof next === "string" && next) onChange(next)
195
+ }}
196
+ >
197
+ <ComboboxTrigger
198
+ aria-label="Project"
199
+ title="Where the work happens: its repositories, its harness, its settings."
200
+ className={cn(newTaskChipClassName, !value && "bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary")}
201
+ >
202
+ <FolderIcon />
203
+ <ComboboxValue placeholder="Pick a project">{name ? <span className="truncate">{name}</span> : null}</ComboboxValue>
204
+ </ComboboxTrigger>
205
+ <ComboboxContent className="w-72">
206
+ <ComboboxSearch placeholder="Find a project…" />
207
+ <ComboboxList>
208
+ <ComboboxEmpty>No project by that name</ComboboxEmpty>
209
+ {projects.map((p) => (
210
+ <ComboboxItem key={p.id} value={p.id} label={p.name} meta={p.id === defaultProjectId ? "default" : undefined}>
211
+ {p.name}
212
+ </ComboboxItem>
213
+ ))}
214
+ </ComboboxList>
215
+ </ComboboxContent>
216
+ </Combobox>
217
+ )
218
+ }
219
+
161
220
  export function NewTaskComposer({
162
221
  projects,
222
+ defaultProjectId = null,
163
223
  onProjectChange,
164
224
  branches = [],
165
225
  defaultBranch = null,
@@ -168,6 +228,7 @@ export function NewTaskComposer({
168
228
  fields = [],
169
229
  onFieldChange,
170
230
  remembered,
231
+ draftKey,
171
232
  onSubmit,
172
233
  submitting = false,
173
234
  error = null,
@@ -178,10 +239,11 @@ export function NewTaskComposer({
178
239
  render,
179
240
  className,
180
241
  }: NewTaskComposerProps) {
181
- const [prompt, setPrompt] = useState("")
242
+ const [prompt, setPrompt] = useTaskDraft(draftKey)
182
243
  const [baseBranch, setBaseBranch] = useState(remembered?.baseBranch ?? "")
183
244
  const [model, setModel] = useState(remembered?.model ?? "")
184
- const [projectId, setProjectId] = useState("")
245
+ const [pickedProject, setPickedProject] = useState("")
246
+ const projectId = pickedProject || (defaultProjectId && projects?.some((p) => p.id === defaultProjectId) ? defaultProjectId : "")
185
247
  // Only what was picked: a field nobody touched reads its (current) `defaultValue`.
186
248
  const [picked, setPicked] = useState<Record<string, unknown>>({})
187
249
  // Adjusted during render, not in an effect: the chips never show a frame of the old project.
@@ -297,32 +359,17 @@ export function NewTaskComposer({
297
359
  {/* ── Where the work happens: what is used unless picked otherwise ── */}
298
360
  <div className="flex flex-wrap items-center gap-1.5 border-t border-border/60 px-2 py-1.5">
299
361
  {asksProject && (
300
- <Select
301
- value={projectId || null}
302
- onValueChange={(value) => {
303
- const next = (value as string | null) ?? ""
304
- setProjectId(next)
362
+ <ProjectChip
363
+ projects={projects}
364
+ value={projectId}
365
+ defaultProjectId={defaultProjectId}
366
+ onChange={(next) => {
367
+ setPickedProject(next)
305
368
  // The branch list belongs to the previous project.
306
369
  setBaseBranch("")
307
- if (next) onProjectChange?.(next)
370
+ onProjectChange?.(next)
308
371
  }}
309
- >
310
- <SelectTrigger
311
- aria-label="Project"
312
- title="Where the work happens: its repositories, its harness, its settings."
313
- className={cn(newTaskChipClassName, !projectId && "bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary")}
314
- >
315
- <FolderIcon />
316
- <SelectValue>{(value: unknown) => projects.find((p) => p.id === value)?.name ?? "Pick a project"}</SelectValue>
317
- </SelectTrigger>
318
- <SelectContent>
319
- {projects.map((p) => (
320
- <SelectItem key={p.id} value={p.id}>
321
- {p.name}
322
- </SelectItem>
323
- ))}
324
- </SelectContent>
325
- </Select>
372
+ />
326
373
  )}
327
374
 
328
375
  <FreeTextChip
@@ -0,0 +1,82 @@
1
+ "use client"
2
+
3
+ // What was being written, kept when the page is left.
4
+ //
5
+ // A prompt is the one thing in a conversation that exists nowhere but in the box: navigate away
6
+ // to check something — which is precisely what one does while writing it — and it is gone. So
7
+ // each composer that is given a `draftKey` keeps its words in this browser's `localStorage` as
8
+ // they are typed, and finds them there when it is mounted again. A draft is the browser's, not
9
+ // the account's: it is half a sentence, not something to sync.
10
+ //
11
+ // The words only — not the attached files, which can weigh megabytes and live as object URLs.
12
+ // Sent (or emptied), the draft is gone.
13
+
14
+ import { useCallback, useEffect, useState } from "react"
15
+
16
+ const PREFIX = "spunto:task-draft:"
17
+
18
+ /** A draft untouched for this long is not the one anybody is coming back for. */
19
+ const MAX_AGE_MS = 30 * 24 * 3600 * 1000
20
+
21
+ type Stored = { text: string; at: number }
22
+
23
+ function storage(): Storage | null {
24
+ try {
25
+ return typeof window === "undefined" ? null : window.localStorage
26
+ } catch {
27
+ // Blocked storage (private mode, a sandboxed iframe): no drafts, no crash.
28
+ return null
29
+ }
30
+ }
31
+
32
+ export function readTaskDraft(key: string): string {
33
+ const raw = storage()?.getItem(PREFIX + key)
34
+ if (!raw) return ""
35
+ try {
36
+ const stored = JSON.parse(raw) as Stored
37
+ if (typeof stored.text !== "string" || Date.now() - stored.at > MAX_AGE_MS) {
38
+ storage()?.removeItem(PREFIX + key)
39
+ return ""
40
+ }
41
+ return stored.text
42
+ } catch {
43
+ return ""
44
+ }
45
+ }
46
+
47
+ export function writeTaskDraft(key: string, text: string) {
48
+ try {
49
+ if (text.trim()) storage()?.setItem(PREFIX + key, JSON.stringify({ text, at: Date.now() } satisfies Stored))
50
+ else storage()?.removeItem(PREFIX + key)
51
+ } catch {
52
+ // Quota exceeded: the box keeps working, only the draft is not kept.
53
+ }
54
+ }
55
+
56
+ /** Forget a draft — once what it held has been sent and accepted. */
57
+ export function clearTaskDraft(key: string) {
58
+ writeTaskDraft(key, "")
59
+ }
60
+
61
+ /**
62
+ * `useState("")` for a prompt, kept under `key` across mounts. Without a key it is exactly that.
63
+ * Read after mount, not during render: the server has no `localStorage`, and a box that
64
+ * hydrated with other words than the server drew would be a mismatch.
65
+ */
66
+ export function useTaskDraft(key?: string | null) {
67
+ const [text, setText] = useState("")
68
+ useEffect(() => {
69
+ // Another conversation in the same mounted box: its own draft, or an empty box.
70
+ setText(key ? readTaskDraft(key) : "")
71
+ }, [key])
72
+ // Written by the setter, not by an effect on `text`: an effect would run with the first, empty
73
+ // render and erase the draft it was about to read.
74
+ const update = useCallback(
75
+ (next: string) => {
76
+ setText(next)
77
+ if (key) writeTaskDraft(key, next)
78
+ },
79
+ [key],
80
+ )
81
+ return [text, update] as const
82
+ }
@@ -18,7 +18,7 @@
18
18
 
19
19
  import { useEffect, useState, type ReactNode } from "react"
20
20
  import { createPortal } from "react-dom"
21
- import { CheckCircle2Icon, ChevronLeftIcon, Loader2Icon, SlidersHorizontalIcon, XIcon } from "lucide-react"
21
+ import { ArchiveIcon, ArchiveRestoreIcon, CheckCircle2Icon, ChevronLeftIcon, Loader2Icon, SlidersHorizontalIcon, XIcon } from "lucide-react"
22
22
 
23
23
  import { cn, formatRelativeTime } from "../../utils"
24
24
  import { useOverlayContainer } from "../spunto-provider"
@@ -121,6 +121,12 @@ function NavStatus({ task, action, since }: { task: TaskItem; action: TaskPendin
121
121
  {style.label}
122
122
  <span aria-hidden>·</span>
123
123
  {formatRelativeTime(task.lastActivityAt ?? task.createdAt)}
124
+ {task.userArchivedAt && (
125
+ <>
126
+ <span aria-hidden>·</span>
127
+ Archived
128
+ </>
129
+ )}
124
130
  </p>
125
131
  )
126
132
  }
@@ -166,6 +172,8 @@ export function TaskCockpitMobile({
166
172
  onAccept,
167
173
  onTitleChange,
168
174
  titleUpdating,
175
+ onArchiveChange,
176
+ archiveUpdating,
169
177
  backHref,
170
178
  onBack,
171
179
  render,
@@ -244,6 +252,25 @@ export function TaskCockpitMobile({
244
252
  </button>
245
253
  )}
246
254
 
255
+ {/* Finished only, like the desktop bar: a live task is dropped, not archived. */}
256
+ {task && (task.state === "done" || task.state === "failed") && onArchiveChange && (
257
+ <button
258
+ type="button"
259
+ disabled={action !== null || archiveUpdating}
260
+ onClick={() => onArchiveChange(!task.userArchivedAt)}
261
+ aria-label={task.userArchivedAt ? "Unarchive" : "Archive"}
262
+ className={NAV_BUTTON}
263
+ >
264
+ {archiveUpdating ? (
265
+ <Loader2Icon className="h-5 w-5 animate-spin" />
266
+ ) : task.userArchivedAt ? (
267
+ <ArchiveRestoreIcon className="h-5 w-5" />
268
+ ) : (
269
+ <ArchiveIcon className="h-5 w-5" />
270
+ )}
271
+ </button>
272
+ )}
273
+
247
274
  {details && task && (
248
275
  <button type="button" onClick={() => setDetailsOpen(true)} aria-label="Details" className={NAV_BUTTON}>
249
276
  <SlidersHorizontalIcon className="h-5 w-5" />
@@ -24,7 +24,7 @@
24
24
  // mount `TaskCockpitMobile` instead: a different screen, not this one squeezed.
25
25
 
26
26
  import { useState, type ReactNode } from "react"
27
- import { ArrowLeftIcon, CheckCircle2Icon, Loader2Icon, XCircleIcon } from "lucide-react"
27
+ import { ArchiveIcon, ArchiveRestoreIcon, ArrowLeftIcon, CheckCircle2Icon, Loader2Icon, XCircleIcon } from "lucide-react"
28
28
 
29
29
  import { cn } from "../../utils"
30
30
  import { Button } from "../button"
@@ -57,6 +57,14 @@ export interface TaskCockpitProps {
57
57
  onTitleChange?: (title: string) => void
58
58
  /** The rename is in flight — the submitted title stays drawn, with a spinner, until it is false. */
59
59
  titleUpdating?: boolean
60
+ /**
61
+ * Put a finished task away, or bring an archived one back (`task.userArchivedAt` says which is
62
+ * offered). Only drawn on a `done`/`failed` task: a live one is dropped, not archived. Omitted →
63
+ * no button.
64
+ */
65
+ onArchiveChange?: (archived: boolean) => void
66
+ /** The archive toggle is in flight. */
67
+ archiveUpdating?: boolean
60
68
 
61
69
  /** Back arrow in the top bar. Omitted when the cockpit sits next to its own list. */
62
70
  backHref?: string
@@ -172,6 +180,8 @@ export function TaskCockpit({
172
180
  onDrop,
173
181
  onTitleChange,
174
182
  titleUpdating,
183
+ onArchiveChange,
184
+ archiveUpdating,
175
185
  backHref,
176
186
  render,
177
187
  view: viewProp,
@@ -227,8 +237,13 @@ export function TaskCockpit({
227
237
  <TaskTitle title={task.title} onTitleChange={onTitleChange} updating={titleUpdating} className="text-sm font-semibold" />
228
238
  </h1>
229
239
  <TaskStateBadge state={task.state} pendingAction={action} pendingSince={since} />
240
+ {task.userArchivedAt && <TaskArchivedBadge />}
230
241
  </div>
231
242
 
243
+ {!live && onArchiveChange && (
244
+ <TaskArchiveButton archived={Boolean(task.userArchivedAt)} updating={archiveUpdating} disabled={busy} onArchiveChange={onArchiveChange} />
245
+ )}
246
+
232
247
  {live && (onAccept || onDrop) && (
233
248
  <div className="flex shrink-0 items-center gap-2">
234
249
  {task.state === "in-review" && onAccept && (
@@ -276,3 +291,50 @@ export function TaskCockpit({
276
291
  </div>
277
292
  )
278
293
  }
294
+
295
+ /** "Archived", next to the state of a task someone put away. */
296
+ export function TaskArchivedBadge({ className }: { className?: string }) {
297
+ return (
298
+ <span
299
+ className={cn(
300
+ "inline-flex shrink-0 items-center gap-1 rounded-full border border-border bg-muted/60 px-2 py-0.5 text-[10px] font-medium text-muted-foreground",
301
+ className,
302
+ )}
303
+ >
304
+ <ArchiveIcon className="h-3 w-3" />
305
+ Archived
306
+ </span>
307
+ )
308
+ }
309
+
310
+ /**
311
+ * Archive / Unarchive, on a finished task. Quiet on purpose — a ghost button: it files the
312
+ * conversation, it does nothing to the work, so it must not look like Accept or Drop.
313
+ */
314
+ export function TaskArchiveButton({
315
+ archived,
316
+ updating = false,
317
+ disabled = false,
318
+ onArchiveChange,
319
+ className,
320
+ }: {
321
+ archived: boolean
322
+ updating?: boolean
323
+ disabled?: boolean
324
+ onArchiveChange: (archived: boolean) => void
325
+ className?: string
326
+ }) {
327
+ const Icon = updating ? Loader2Icon : archived ? ArchiveRestoreIcon : ArchiveIcon
328
+ return (
329
+ <Button
330
+ variant="ghost"
331
+ size="sm"
332
+ disabled={disabled || updating}
333
+ onClick={() => onArchiveChange(!archived)}
334
+ className={cn("h-8 shrink-0 gap-1.5 px-3 text-xs text-muted-foreground", className)}
335
+ >
336
+ <Icon className={cn("h-3.5 w-3.5", updating && "animate-spin")} />
337
+ {archived ? "Unarchive" : "Archive"}
338
+ </Button>
339
+ )
340
+ }
@@ -70,7 +70,7 @@ export const taskPendingActionConfig: Record<TaskPendingAction, { label: string;
70
70
  className: "bg-destructive/10 text-destructive border-destructive/30",
71
71
  textClass: "text-destructive",
72
72
  },
73
- replying: { label: "Sending", className: "bg-primary/10 text-primary border-primary/30", textClass: "text-primary" },
73
+ replying: { label: "Resuming", className: "bg-primary/10 text-primary border-primary/30", textClass: "text-primary" },
74
74
  }
75
75
 
76
76
  /** Lax lookup: an unknown state reads as `queued` (neutral) instead of throwing. */
@@ -12,8 +12,10 @@ 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
16
  import { TaskBoot, bootSteps } from "./machine"
16
17
  import { NewTaskComposer } from "./new-task-composer"
18
+ import { clearTaskDraft, readTaskDraft } from "./prompt-draft"
17
19
  import { NewTaskDialog, type NewTaskCustomField } from "./new-task-dialog"
18
20
  import { formatCost, formatTokens } from "./session-usage"
19
21
  import { TaskCockpit } from "./task-cockpit"
@@ -302,6 +304,22 @@ describe("TaskList", () => {
302
304
  })
303
305
 
304
306
  describe("TaskComposer", () => {
307
+ it("keeps an unsent answer per task, and forgets it once sent", () => {
308
+ const onSubmit = vi.fn()
309
+ const first = render(<TaskComposer state="in-review" canResume protocol="claude-stream" draftKey="t1" onSubmit={onSubmit} />)
310
+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "in fact, do X" } })
311
+ first.unmount()
312
+ const { rerender } = render(<TaskComposer state="in-review" canResume protocol="claude-stream" draftKey="t1" onSubmit={onSubmit} />)
313
+ expect((screen.getByRole("textbox") as HTMLTextAreaElement).value).toBe("in fact, do X")
314
+ // Another conversation in the same box: its own draft, none here.
315
+ rerender(<TaskComposer state="in-review" canResume protocol="claude-stream" draftKey="t2" onSubmit={onSubmit} />)
316
+ expect((screen.getByRole("textbox") as HTMLTextAreaElement).value).toBe("")
317
+ rerender(<TaskComposer state="in-review" canResume protocol="claude-stream" draftKey="t1" onSubmit={onSubmit} />)
318
+ fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter" })
319
+ expect(onSubmit).toHaveBeenCalledWith("in fact, do X", [])
320
+ expect(readTaskDraft("t1")).toBe("")
321
+ })
322
+
305
323
  it("says why it is closed on a one-shot harness that is still working", () => {
306
324
  render(<TaskComposer state="running" protocol="claude-json" onSubmit={() => {}} />)
307
325
  expect((screen.getByRole("textbox") as HTMLTextAreaElement).disabled).toBe(true)
@@ -531,6 +549,29 @@ describe("NewTaskComposer — delegating where the conversation will be", () =>
531
549
  expect(onSubmit).not.toHaveBeenCalled()
532
550
  })
533
551
 
552
+ it("org-wide, starts on the organization's default project — when it is one of the list", () => {
553
+ const onSubmit = vi.fn()
554
+ const projects = [{ id: "p1", name: "spunto" }, { id: "p2", name: "lite" }]
555
+ const { rerender } = render(<NewTaskComposer projects={projects} defaultProjectId="p2" onSubmit={onSubmit} />)
556
+ expect(screen.getByText("lite")).toBeTruthy()
557
+ fireEvent.change(prompt(), { target: { value: "Fix it" } })
558
+ fireEvent.click(delegate())
559
+ expect(onSubmit.mock.calls[0]![0]).toMatchObject({ projectId: "p2" })
560
+ // A default that is not (or no longer) a project of the list preselects nothing.
561
+ rerender(<NewTaskComposer projects={projects} defaultProjectId="gone" onSubmit={onSubmit} />)
562
+ expect(delegate().disabled).toBe(true)
563
+ })
564
+
565
+ it("keeps the prompt being written as a draft, across mounts", () => {
566
+ const first = render(<NewTaskComposer draftKey="new:org1" onSubmit={vi.fn()} />)
567
+ fireEvent.change(prompt(), { target: { value: "Half a sente" } })
568
+ first.unmount()
569
+ render(<NewTaskComposer draftKey="new:org1" onSubmit={vi.fn()} />)
570
+ expect((prompt() as HTMLTextAreaElement).value).toBe("Half a sente")
571
+ clearTaskDraft("new:org1")
572
+ expect(readTaskDraft("new:org1")).toBe("")
573
+ })
574
+
534
575
  it("sends the app's fields, and reports each pick as it happens", () => {
535
576
  const onSubmit = vi.fn()
536
577
  const onFieldChange = vi.fn()
@@ -570,3 +611,61 @@ describe("NewTaskComposer — delegating where the conversation will be", () =>
570
611
  expect(screen.getByText("Pick “Runs on” first.")).toBeTruthy()
571
612
  })
572
613
  })
614
+
615
+ describe("a queued reply", () => {
616
+ const delivery = (events: TaskEvent[]) =>
617
+ foldTimeline(events).items.flatMap((i) => (i.kind === "event" && i.delivery ? [{ seq: i.event.seq, ...i.delivery }] : []))
618
+ const queued = ev(10, "message", { role: "user", text: "Rebase on main", queued: true })
619
+
620
+ it("is queued until something happens, then follows the machine waking and the session resuming", () => {
621
+ expect(delivery([queued])).toEqual([{ seq: 10, status: "queued" }])
622
+ const starting = ev(11, "machine.wake", { phase: "starting", kind: "sandbox", from: "stopped" })
623
+ expect(delivery([queued, starting])[0]).toMatchObject({ status: "waking", machineKind: "sandbox", wakeStartedAt: starting.ts })
624
+ const awake = ev(12, "machine.wake", { phase: "awake", kind: "sandbox", ms: 54_000 })
625
+ expect(delivery([queued, starting, awake])[0]).toMatchObject({ status: "resuming", wakeMs: 54_000 })
626
+ const started = ev(13, "session.started", { sessionId: "s1" })
627
+ expect(delivery([queued, starting, awake, started])[0]).toMatchObject({ status: "delivered", wakeMs: 54_000 })
628
+ })
629
+
630
+ it("says why it was not delivered", () => {
631
+ expect(delivery([queued, ev(11, "reply.failed", { error: "Branch check failed" })])[0]).toMatchObject({
632
+ status: "failed",
633
+ error: "Branch check failed",
634
+ })
635
+ })
636
+
637
+ it("draws the wake steps under the message, not as rows of their own", () => {
638
+ const { items } = foldTimeline([queued, ev(11, "machine.wake", { phase: "starting", kind: "worker" })])
639
+ expect(items).toHaveLength(1)
640
+ })
641
+
642
+ it("leaves a message delivered live alone", () => {
643
+ expect(delivery([ev(10, "message", { role: "user", text: "Also the footer" })])).toEqual([])
644
+ })
645
+ })
646
+
647
+ describe("an empty turn", () => {
648
+ it("is not drawn — neither its end nor the start it closes", () => {
649
+ const { items } = foldTimeline([
650
+ ev(1, "message", { role: "user", text: "Carry on", queued: true }),
651
+ ev(2, "session.started", { sessionId: "s1" }),
652
+ ev(3, "usage", { scope: "session", turns: 0 }),
653
+ ev(4, "session.ended", { status: "succeeded", summary: "", empty: true }),
654
+ ev(5, "session.started", { sessionId: "s1" }),
655
+ ev(6, "message", { role: "assistant", text: "Rebasing now." }),
656
+ ])
657
+ const types = items.map((i) => (i.kind === "event" ? i.event.seq : i.kind))
658
+ expect(types).toEqual([1, 5, 6])
659
+ })
660
+ })
661
+
662
+ describe("the composer while a reply is on its way", () => {
663
+ it("keeps the box writable and holds Send", () => {
664
+ render(<TaskComposer state="in-review" canResume protocol="claude-stream" pending onSubmit={() => {}} />)
665
+ const box = screen.getByRole("textbox") as HTMLTextAreaElement
666
+ expect(box.disabled).toBe(false)
667
+ fireEvent.change(box, { target: { value: "and the footer too" } })
668
+ expect((screen.getByRole("button", { name: /send/i }) as HTMLButtonElement).disabled).toBe(true)
669
+ expect(screen.getByText(/your message is queued/i)).toBeTruthy()
670
+ })
671
+ })
@@ -44,6 +44,8 @@ export interface TaskItem {
44
44
  pendingAction?: TaskPendingAction | null
45
45
  /** When that was asked for. What the spinner counts from — across reloads and readers. */
46
46
  pendingSince?: string | null
47
+ /** When a member put this finished task away — it then lives in the « Archived » view. Null = not archived. */
48
+ userArchivedAt?: string | null
47
49
  }
48
50
 
49
51
  /** A row of the org-wide conversation list: a task plus the project it belongs to. */