canopy-ui 0.6.3 → 0.8.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.
@@ -8,7 +8,15 @@ import {
8
8
  import type React from "react";
9
9
 
10
10
  import type { Draft } from "./protocol";
11
- import { isDraftIdle, msUntilDraftIdle } from "./drafts";
11
+ import {
12
+ clearStoredDraft,
13
+ defaultDraftStorage,
14
+ isDraftIdle,
15
+ msUntilDraftIdle,
16
+ readStoredDraft,
17
+ writeStoredDraft,
18
+ type DraftStorage,
19
+ } from "./drafts";
12
20
  import { Button } from "../ui/button";
13
21
 
14
22
  /** An attachment the composer is holding, uploaded but not yet sent. */
@@ -28,6 +36,10 @@ interface Props {
28
36
  connected: boolean;
29
37
  currentUserId: number;
30
38
  holderIsPresent: boolean;
39
+ /** Display name of the teammate holding the draft, when it is not you.
40
+ * The composer is where their words appear, so it is where their name
41
+ * belongs — it used to live only in a 28px chip in the opposite corner. */
42
+ holderName?: string | null;
31
43
  isStreaming: boolean;
32
44
  streamingMessageId: string | null;
33
45
  onUpdate: (body: string) => void;
@@ -36,6 +48,10 @@ interface Props {
36
48
  * The server cancels every non-terminal turn regardless, so a null id is
37
49
  * a valid cancel, not a no-op. */
38
50
  onStop: (messageId: string | null) => void;
51
+ /** Whether the stop the human asked for actually landed. Rendered next to the
52
+ * button that asked for it, because that is where the person who pressed it
53
+ * is looking. Undefined = no stop has been asked for on this turn. */
54
+ stopState?: "requested" | "stopped" | "failed";
39
55
  onTakeOver: () => void;
40
56
  /** Optional app-supplied banner rendered above the composer (e.g. an
41
57
  * imported-session note). The kit itself has no CLI-auth banners. */
@@ -49,6 +65,13 @@ interface Props {
49
65
  * paths); it re-renders `attachments` as they progress. */
50
66
  onAttach?: (files: File[]) => void;
51
67
  onRemoveAttachment?: (id: string) => void;
68
+ /** Persist what is typed under this key (the session id) so it survives
69
+ * unmounting — routing away and back, or closing the tab. Omit to keep the
70
+ * purely in-memory behaviour. */
71
+ persistKey?: string;
72
+ /** Storage backing `persistKey`. Defaults to localStorage; inject a fake in
73
+ * tests, or sessionStorage for per-tab drafts. */
74
+ storage?: DraftStorage | null;
52
75
  }
53
76
 
54
77
  export function SendBox({
@@ -56,17 +79,21 @@ export function SendBox({
56
79
  connected,
57
80
  currentUserId,
58
81
  holderIsPresent,
82
+ holderName,
59
83
  isStreaming,
60
84
  streamingMessageId,
61
85
  onUpdate,
62
86
  onSend,
63
87
  onStop,
88
+ stopState,
64
89
  onTakeOver,
65
90
  banner,
66
91
  disabledReason,
67
92
  attachments,
68
93
  onAttach,
69
94
  onRemoveAttachment,
95
+ persistKey,
96
+ storage,
70
97
  }: Props) {
71
98
  const textareaRef = useRef<HTMLTextAreaElement>(null);
72
99
  // Force a re-render when the lock transitions from live to idle.
@@ -94,7 +121,42 @@ export function SendBox({
94
121
  // wholesale), would rewind the composer to a body from 150ms ago. In
95
122
  // single-player that reconciliation protects against nothing at all, since
96
123
  // there is no co-editor whose edits could be lost.
97
- const [localBody, setLocalBody] = useState(draft?.body ?? "");
124
+ //
125
+ // Seeded from persisted storage when there is one, because a body typed
126
+ // before an unmount exists NOWHERE else: single-player never mirrors it to
127
+ // the server (see drafts.shouldSyncDraftLive), and the adopt rule below
128
+ // deliberately ignores our own server draft. A stored body wins over
129
+ // `draft.body` — it is strictly newer, being what was in the box when we
130
+ // last left it.
131
+ const store = storage === undefined ? defaultDraftStorage() : storage;
132
+ const [localBody, setLocalBody] = useState(
133
+ () => readStoredDraft(store, persistKey ?? "") ?? draft?.body ?? "",
134
+ );
135
+
136
+ // Persistence is a synchronous localStorage write per keystroke — no
137
+ // debounce on purpose. The payload is a chat message, the write is
138
+ // microseconds, and every timer-based alternative has to solve flush-on-
139
+ // unmount and flush-on-tab-close to be correct at exactly the moments this
140
+ // feature exists for.
141
+ const persist = (body: string) => {
142
+ if (persistKey) writeStoredDraft(store, persistKey, body);
143
+ };
144
+ // Nothing persists a CO-EDITOR's text, deliberately: a draft someone else is
145
+ // editing is by definition being live-synced to the server, so the existing
146
+ // adopt rule below restores it from `session.state` on the way back in. The
147
+ // gap this whole mechanism closes is the single-player one, where the server
148
+ // is never told at all.
149
+
150
+ // The panel can swap sessions without remounting (same route, new :id), so
151
+ // the box must follow the key rather than carry one session's text into the
152
+ // next. Adjusted during render rather than in an effect — React's documented
153
+ // shape for "reset state when a prop changes", and the one that avoids a
154
+ // paint showing the previous session's text.
155
+ const [keyOnScreen, setKeyOnScreen] = useState(persistKey);
156
+ if (keyOnScreen !== persistKey) {
157
+ setKeyOnScreen(persistKey);
158
+ setLocalBody(readStoredDraft(store, persistKey ?? "") ?? "");
159
+ }
98
160
 
99
161
  // The ONE case where the server genuinely knows better than this client:
100
162
  // somebody ELSE edited the shared draft. Our own echo is ignored, which is
@@ -121,6 +183,10 @@ export function SendBox({
121
183
 
122
184
  const body = localBody;
123
185
  const blocked = Boolean(disabledReason);
186
+ // Locked BY SOMEONE ELSE, as opposed to blocked for an unrelated reason.
187
+ // The two look identical to `disabled` and want opposite treatments: a
188
+ // blocked box is inert, a co-edited one is showing you live content.
189
+ const lockedByTeammate = !canEdit && holderIsPresent && !holderIsIdle && !blocked;
124
190
  // Sending needs a draft (`chat.send` commits the SERVER's copy, so there must
125
191
  // be one) AND a live socket. The socket check is load-bearing now that the
126
192
  // composer clears optimistically: `send()` drops every frame but chat.stop
@@ -136,6 +202,7 @@ export function SendBox({
136
202
 
137
203
  const handleChange = (value: string) => {
138
204
  setLocalBody(value);
205
+ persist(value);
139
206
  onUpdate(value);
140
207
  };
141
208
 
@@ -163,6 +230,7 @@ export function SendBox({
163
230
  // echo back: that echo carries last_editor === us, which the adopt rule
164
231
  // above (correctly) ignores, so nothing else would empty the box.
165
232
  setLocalBody("");
233
+ if (persistKey) clearStoredDraft(store, persistKey);
166
234
  onSend();
167
235
  };
168
236
 
@@ -239,8 +307,37 @@ export function SendBox({
239
307
  ))}
240
308
  </ul>
241
309
  )}
310
+ {/* Co-edit attribution, at the box rather than across the screen.
311
+ Their text arrives INSIDE this textarea, and a disabled textarea
312
+ renders it in muted grey — pixel-identical to a placeholder. So the
313
+ single most important thing multiplayer does (showing you what your
314
+ teammate is writing) read as an EMPTY box with a hint in it. */}
315
+ {lockedByTeammate && (
316
+ <div
317
+ data-testid="coedit-banner"
318
+ className="mb-1.5 flex items-center gap-2 rounded-md border border-primary/30 bg-primary/10 px-2 py-1 text-xs"
319
+ >
320
+ <span className="relative flex h-1.5 w-1.5 shrink-0" aria-hidden="true">
321
+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-60" />
322
+ <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-primary" />
323
+ </span>
324
+ <span className="text-foreground">
325
+ <span className="font-medium">{holderName ?? "A teammate"}</span> is
326
+ writing — you are seeing their draft
327
+ </span>
328
+ <button
329
+ type="button"
330
+ data-testid="take-over"
331
+ onClick={onTakeOver}
332
+ className="ml-auto shrink-0 rounded border border-border px-1.5 py-0.5 font-medium text-foreground hover:bg-muted"
333
+ >
334
+ take over
335
+ </button>
336
+ </div>
337
+ )}
242
338
  <textarea
243
339
  ref={textareaRef}
340
+ data-testid="composer"
244
341
  value={body}
245
342
  disabled={!canEdit || blocked}
246
343
  onChange={(e) => handleChange(e.target.value)}
@@ -248,7 +345,18 @@ export function SendBox({
248
345
  onPaste={handlePaste}
249
346
  placeholder={placeholder}
250
347
  rows={3}
251
- className="w-full resize-none rounded-md border border-input bg-transparent p-2 text-sm text-foreground shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground"
348
+ className={[
349
+ "w-full resize-none rounded-md border bg-transparent p-2 text-sm shadow-sm",
350
+ "placeholder:text-muted-foreground focus-visible:outline-none",
351
+ "focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed",
352
+ // A teammate's draft is CONTENT, not a disabled control. Dimming it
353
+ // to `text-muted-foreground` made their sentence look like the
354
+ // placeholder it sits next to — the one styling choice that made
355
+ // co-editing appear not to work at all.
356
+ lockedByTeammate
357
+ ? "border-primary/40 bg-primary/5 text-foreground"
358
+ : "border-input text-foreground disabled:bg-muted disabled:text-muted-foreground",
359
+ ].join(" ")}
252
360
  />
253
361
  <div className="mt-1 flex items-center justify-end gap-2">
254
362
  {canAttach && (
@@ -281,6 +389,26 @@ export function SendBox({
281
389
  {disabledReason}
282
390
  </span>
283
391
  )}
392
+ {stopState === "failed" ? (
393
+ // The one state that MUST be loud. Everything else here is either
394
+ // self-evident (the reply stopped) or transient. A stop that did not
395
+ // take looks exactly like a stop that worked — the agent keeps
396
+ // running either way — so without this it is invisible, which is the
397
+ // whole reason Stop could not be trusted.
398
+ <span
399
+ role="status"
400
+ className="mr-auto text-xs font-medium text-destructive"
401
+ title="Escape was pressed and the agent is still running. Try again, or stop it in the terminal."
402
+ >
403
+ stop didn&rsquo;t take — still running
404
+ </span>
405
+ ) : null}
406
+ {/* Never DISABLED while a stop is in flight, only relabelled. If the
407
+ runner dies between the request and the verdict, `stopState` never
408
+ advances — and a button that latched off would leave the human with
409
+ no way to ask again, the exact trap #519 documents for the composer
410
+ lock. Pressing again is harmless: the runner dedupes by session_key,
411
+ so three impatient presses are still one Escape. */}
284
412
  {isStreaming ? (
285
413
  <Button
286
414
  type="button"
@@ -288,15 +416,16 @@ export function SendBox({
288
416
  size="sm"
289
417
  onClick={handleStopClick}
290
418
  >
291
- stop
292
- </Button>
293
- ) : null}
294
- {!canEdit && holderIsPresent && !holderIsIdle ? (
295
- <Button type="button" variant="outline" size="sm" onClick={onTakeOver}>
296
- take over
419
+ {stopState === "requested" ? "stopping…" : "stop"}
297
420
  </Button>
298
421
  ) : null}
299
- <Button type="button" size="sm" disabled={!canSend} onClick={handleSend}>
422
+ <Button
423
+ type="button"
424
+ size="sm"
425
+ data-testid="send"
426
+ disabled={!canSend}
427
+ onClick={handleSend}
428
+ >
300
429
  send
301
430
  </Button>
302
431
  </div>
@@ -0,0 +1,235 @@
1
+ [
2
+ {
3
+ "canopy": {
4
+ "event": "chat.stream_start",
5
+ "data": {
6
+ "message_id": "m1",
7
+ "turn_index": 4
8
+ }
9
+ },
10
+ "agui": [
11
+ {
12
+ "metadata": {
13
+ "canopy": {
14
+ "turn_index": 4
15
+ }
16
+ },
17
+ "type": "TEXT_MESSAGE_START",
18
+ "messageId": "m1",
19
+ "role": "assistant"
20
+ }
21
+ ]
22
+ },
23
+ {
24
+ "canopy": {
25
+ "event": "chat.delta",
26
+ "data": {
27
+ "message_id": "m1",
28
+ "text": "hello"
29
+ }
30
+ },
31
+ "agui": [
32
+ {
33
+ "type": "TEXT_MESSAGE_CONTENT",
34
+ "messageId": "m1",
35
+ "delta": "hello"
36
+ }
37
+ ]
38
+ },
39
+ {
40
+ "canopy": {
41
+ "event": "chat.stream_complete",
42
+ "data": {
43
+ "message_id": "m1",
44
+ "plaintext": "hello"
45
+ }
46
+ },
47
+ "agui": [
48
+ {
49
+ "metadata": {
50
+ "canopy": {
51
+ "plaintext": "hello"
52
+ }
53
+ },
54
+ "type": "TEXT_MESSAGE_END",
55
+ "messageId": "m1"
56
+ }
57
+ ]
58
+ },
59
+ {
60
+ "canopy": {
61
+ "event": "chat.user_message",
62
+ "data": {
63
+ "message_id": "u1",
64
+ "turn_index": 3,
65
+ "plaintext": "hi there"
66
+ }
67
+ },
68
+ "agui": [
69
+ {
70
+ "metadata": {
71
+ "canopy": {
72
+ "turn_index": 3
73
+ }
74
+ },
75
+ "type": "TEXT_MESSAGE_CHUNK",
76
+ "messageId": "u1",
77
+ "role": "user",
78
+ "delta": "hi there"
79
+ }
80
+ ]
81
+ },
82
+ {
83
+ "canopy": {
84
+ "event": "chat.tool_use",
85
+ "data": {
86
+ "tool_message_id": "t9",
87
+ "parent_message_id": "m1",
88
+ "turn_index": 5,
89
+ "block": {
90
+ "name": "list_insights",
91
+ "input": {
92
+ "limit": 5
93
+ }
94
+ }
95
+ }
96
+ },
97
+ "agui": [
98
+ {
99
+ "metadata": {
100
+ "canopy": {
101
+ "turn_index": 5,
102
+ "block": {
103
+ "name": "list_insights",
104
+ "input": {
105
+ "limit": 5
106
+ }
107
+ }
108
+ }
109
+ },
110
+ "type": "TOOL_CALL_START",
111
+ "toolCallId": "t9",
112
+ "toolCallName": "list_insights",
113
+ "parentMessageId": "m1"
114
+ },
115
+ {
116
+ "type": "TOOL_CALL_ARGS",
117
+ "toolCallId": "t9",
118
+ "delta": "{\"limit\": 5}"
119
+ },
120
+ {
121
+ "type": "TOOL_CALL_END",
122
+ "toolCallId": "t9"
123
+ }
124
+ ]
125
+ },
126
+ {
127
+ "canopy": {
128
+ "event": "chat.tool_result",
129
+ "data": {
130
+ "tool_message_id": "t9",
131
+ "parent_message_id": "m1",
132
+ "turn_index": 6,
133
+ "block": {
134
+ "type": "tool_result",
135
+ "tool_use_id": "toolu_01ABC",
136
+ "content": "[]"
137
+ }
138
+ }
139
+ },
140
+ "agui": [
141
+ {
142
+ "metadata": {
143
+ "canopy": {
144
+ "turn_index": 6,
145
+ "parent_message_id": "m1",
146
+ "block": {
147
+ "type": "tool_result",
148
+ "tool_use_id": "toolu_01ABC",
149
+ "content": "[]"
150
+ }
151
+ }
152
+ },
153
+ "type": "TOOL_CALL_RESULT",
154
+ "messageId": "t9",
155
+ "toolCallId": "t9",
156
+ "content": "[]"
157
+ }
158
+ ]
159
+ },
160
+ {
161
+ "canopy": {
162
+ "event": "session.title_updated",
163
+ "data": {
164
+ "title": "Insights triage"
165
+ }
166
+ },
167
+ "agui": [
168
+ {
169
+ "type": "STATE_DELTA",
170
+ "delta": [
171
+ {
172
+ "op": "replace",
173
+ "path": "/title",
174
+ "value": "Insights triage"
175
+ }
176
+ ]
177
+ }
178
+ ]
179
+ },
180
+ {
181
+ "canopy": {
182
+ "event": "draft.updated",
183
+ "data": {
184
+ "id": "d1",
185
+ "body": "x",
186
+ "version": 2
187
+ }
188
+ },
189
+ "agui": [
190
+ {
191
+ "type": "CUSTOM",
192
+ "name": "canopy.draft.updated",
193
+ "value": {
194
+ "id": "d1",
195
+ "body": "x",
196
+ "version": 2
197
+ }
198
+ }
199
+ ]
200
+ },
201
+ {
202
+ "canopy": {
203
+ "event": "presence.joined",
204
+ "data": {
205
+ "user_id": 7
206
+ }
207
+ },
208
+ "agui": [
209
+ {
210
+ "type": "CUSTOM",
211
+ "name": "canopy.presence.joined",
212
+ "value": {
213
+ "user_id": 7
214
+ }
215
+ }
216
+ ]
217
+ },
218
+ {
219
+ "canopy": {
220
+ "event": "presence.left",
221
+ "data": {
222
+ "user_id": 7
223
+ }
224
+ },
225
+ "agui": [
226
+ {
227
+ "type": "CUSTOM",
228
+ "name": "canopy.presence.left",
229
+ "value": {
230
+ "user_id": 7
231
+ }
232
+ }
233
+ ]
234
+ }
235
+ ]