@useavalon/caelence-agent 0.2.1-canary.0 → 0.2.1

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.
Files changed (71) hide show
  1. package/README.md +8 -5
  2. package/desktop/README.md +26 -0
  3. package/desktop/bun.lock +321 -0
  4. package/desktop/index.html +20 -0
  5. package/desktop/package.json +28 -0
  6. package/desktop/scripts/make-icons.ts +105 -0
  7. package/desktop/scripts/run-tauri.ts +40 -0
  8. package/desktop/src/App.tsx +2657 -0
  9. package/desktop/src/ComposerAttach.tsx +111 -0
  10. package/desktop/src/FloatNotice.test.ts +23 -0
  11. package/desktop/src/FloatNotice.tsx +30 -0
  12. package/desktop/src/LogoMark.tsx +37 -0
  13. package/desktop/src/SkillsPanel.tsx +409 -0
  14. package/desktop/src/api.ts +503 -0
  15. package/desktop/src/app.css +1749 -0
  16. package/desktop/src/composer-files.test.ts +46 -0
  17. package/desktop/src/composer-files.ts +135 -0
  18. package/desktop/src/dictation.test.ts +22 -0
  19. package/desktop/src/dictation.ts +59 -0
  20. package/desktop/src/integration-search.test.ts +13 -0
  21. package/desktop/src/integration-search.ts +8 -0
  22. package/desktop/src/main.tsx +43 -0
  23. package/desktop/src/picker-nav.test.ts +27 -0
  24. package/desktop/src/picker-nav.ts +26 -0
  25. package/desktop/src/queue.test.ts +37 -0
  26. package/desktop/src/queue.ts +40 -0
  27. package/desktop/src/rich-text.test.ts +85 -0
  28. package/desktop/src/rich-text.ts +193 -0
  29. package/desktop/src/session-menu.test.ts +19 -0
  30. package/desktop/src/session-menu.ts +12 -0
  31. package/desktop/src/skill-search.test.ts +37 -0
  32. package/desktop/src/skill-search.ts +25 -0
  33. package/desktop/src/stream.test.ts +93 -0
  34. package/desktop/src/stream.ts +197 -0
  35. package/desktop/src/styles/fonts/chivo-mono-latin-ext-wght-normal.woff2 +0 -0
  36. package/desktop/src/styles/fonts/chivo-mono-latin-wght-normal.ttf +0 -0
  37. package/desktop/src/styles/fonts/chivo-mono-latin-wght-normal.woff2 +0 -0
  38. package/desktop/src/styles/fonts/instrument-sans-latin-ext-wght-normal.woff2 +0 -0
  39. package/desktop/src/styles/fonts/instrument-sans-latin-wght-normal.ttf +0 -0
  40. package/desktop/src/styles/fonts/instrument-sans-latin-wght-normal.woff2 +0 -0
  41. package/desktop/src/styles/fonts.css +53 -0
  42. package/desktop/src/styles/primitives.css +600 -0
  43. package/desktop/src/styles/tokens-matte.css +354 -0
  44. package/desktop/src/thought.test.ts +96 -0
  45. package/desktop/src/thought.ts +87 -0
  46. package/desktop/src/tool-label.test.ts +17 -0
  47. package/desktop/src/tool-label.ts +70 -0
  48. package/desktop/src/vite-env.d.ts +15 -0
  49. package/desktop/src-tauri/Cargo.lock +4791 -0
  50. package/desktop/src-tauri/Cargo.toml +21 -0
  51. package/desktop/src-tauri/Entitlements.plist +8 -0
  52. package/desktop/src-tauri/Info.plist +12 -0
  53. package/desktop/src-tauri/build.rs +16 -0
  54. package/desktop/src-tauri/capabilities/default.json +15 -0
  55. package/desktop/src-tauri/icons/128x128.png +0 -0
  56. package/desktop/src-tauri/icons/16x16.png +0 -0
  57. package/desktop/src-tauri/icons/32x32.png +0 -0
  58. package/desktop/src-tauri/icons/henry.w@example.net +0 -0
  59. package/desktop/src-tauri/icons/icon.icns +0 -0
  60. package/desktop/src-tauri/icons/icon.ico +0 -0
  61. package/desktop/src-tauri/icons/icon.png +0 -0
  62. package/desktop/src-tauri/icons/icon.svg +7 -0
  63. package/desktop/src-tauri/permissions/bridge.toml +24 -0
  64. package/desktop/src-tauri/src/main.rs +312 -0
  65. package/desktop/src-tauri/src/mic.rs +216 -0
  66. package/desktop/src-tauri/tauri.conf.json +46 -0
  67. package/desktop/tsconfig.json +21 -0
  68. package/desktop/vite.config.ts +18 -0
  69. package/package.json +5 -4
  70. package/src/cli/main.test.ts +6 -0
  71. package/src/cli/main.ts +5 -2
@@ -0,0 +1,2657 @@
1
+ import { ArrowUpRightIcon } from "@phosphor-icons/react/dist/csr/ArrowUpRight";
2
+ import { CaretDownIcon } from "@phosphor-icons/react/dist/csr/CaretDown";
3
+ import { CheckIcon } from "@phosphor-icons/react/dist/csr/Check";
4
+ import { FolderSimpleIcon } from "@phosphor-icons/react/dist/csr/FolderSimple";
5
+ import { GearIcon } from "@phosphor-icons/react/dist/csr/Gear";
6
+ import { MicrophoneIcon } from "@phosphor-icons/react/dist/csr/Microphone";
7
+ import { PaperPlaneTiltIcon } from "@phosphor-icons/react/dist/csr/PaperPlaneTilt";
8
+ import { PencilSimpleIcon } from "@phosphor-icons/react/dist/csr/PencilSimple";
9
+ import { PlugsIcon } from "@phosphor-icons/react/dist/csr/Plugs";
10
+ import { PlusIcon } from "@phosphor-icons/react/dist/csr/Plus";
11
+ import { PuzzlePieceIcon } from "@phosphor-icons/react/dist/csr/PuzzlePiece";
12
+ import { SidebarSimpleIcon } from "@phosphor-icons/react/dist/csr/SidebarSimple";
13
+ import { SquareIcon } from "@phosphor-icons/react/dist/csr/Square";
14
+ import { TrashIcon } from "@phosphor-icons/react/dist/csr/Trash";
15
+ import { XIcon } from "@phosphor-icons/react/dist/csr/X";
16
+ import {
17
+ type Dispatch,
18
+ type SetStateAction,
19
+ useCallback,
20
+ useEffect,
21
+ useLayoutEffect,
22
+ useRef,
23
+ useState,
24
+ } from "react";
25
+ import {
26
+ draftAfterPicker,
27
+ PICKS_WHEN_EMPTY,
28
+ parseSlashLine,
29
+ resolveSlashSubmit,
30
+ } from "../../src/cli/slash";
31
+ import { errorMessage } from "../../src/core/errors";
32
+ import { AGENT_MODES } from "../../src/core/mode";
33
+ import {
34
+ type AgentEvent,
35
+ abortTurn,
36
+ approve,
37
+ type BridgeClient,
38
+ connectIntegration,
39
+ type DesktopSettings,
40
+ type DesktopState,
41
+ deleteSession,
42
+ disconnectIntegration,
43
+ embedPreview,
44
+ filesFromDroppedPaths,
45
+ getIntegrations,
46
+ getModels,
47
+ getSessions,
48
+ getSettings,
49
+ getSlash,
50
+ getState,
51
+ isAbortError,
52
+ micStart,
53
+ micStop,
54
+ openExternal,
55
+ openLocalFile,
56
+ type PickerItem,
57
+ type PublicIntegration,
58
+ postPicker,
59
+ postSession,
60
+ renameSession,
61
+ resolveBridge,
62
+ type SlashCommand,
63
+ type SlashOutcome,
64
+ type SlashPickerKind,
65
+ saveSettings,
66
+ startTurn,
67
+ transcribe,
68
+ } from "./api";
69
+ import { AttachmentThumbs } from "./ComposerAttach";
70
+ import {
71
+ type ComposerAttachment,
72
+ droppedPaths,
73
+ filesFromTransfer,
74
+ mergeAttachments,
75
+ releaseAttachment,
76
+ serializeComposerAttachments,
77
+ toAttachmentPreviews,
78
+ transferHasFiles,
79
+ } from "./composer-files";
80
+ import {
81
+ audioFormatFromMime,
82
+ blobToBase64,
83
+ canUseWebMic,
84
+ dictationErrorMessage,
85
+ isMicPermissionDenied,
86
+ pickRecorderMime,
87
+ } from "./dictation";
88
+ import { FloatNotice } from "./FloatNotice";
89
+ import { integrationMatches } from "./integration-search";
90
+ import { LogoMark } from "./LogoMark";
91
+ import { pickerKeyAction, pickerStartIndex, stepIndex } from "./picker-nav";
92
+ import {
93
+ enqueueMessage,
94
+ type QueuedMessage,
95
+ removeQueued,
96
+ setQueuedText,
97
+ updateQueued,
98
+ } from "./queue";
99
+ import { canvaViewUrl, splitRichText } from "./rich-text";
100
+ import { SkillsPanel } from "./SkillsPanel";
101
+ import { clampMenuPosition } from "./session-menu";
102
+ import {
103
+ applyEvent,
104
+ linesFromTranscript,
105
+ nextUserTurnIndex,
106
+ previewInput,
107
+ type StreamLine,
108
+ truncateAfterUserTurn,
109
+ } from "./stream";
110
+ import {
111
+ type FoldEntry,
112
+ groupTranscriptLines,
113
+ type ToolLine,
114
+ thoughtSummary,
115
+ thoughtTools,
116
+ } from "./thought";
117
+ import { eventCountSuffix } from "./tool-label";
118
+
119
+ type ThemeChoice = "system" | "light" | "dark";
120
+ type UiStatus = "boot" | "idle" | "running" | "approval" | "picker";
121
+ type MainView = "chat" | "settings" | "integrations" | "skills";
122
+
123
+ interface PickerState {
124
+ title: string;
125
+ kind: SlashPickerKind;
126
+ items: PickerItem[];
127
+ index: number;
128
+ }
129
+
130
+ interface SessionMenuState {
131
+ id: string;
132
+ label: string;
133
+ x: number;
134
+ y: number;
135
+ }
136
+
137
+ interface PendingApproval {
138
+ callId: string;
139
+ toolName: string;
140
+ input: Record<string, unknown>;
141
+ }
142
+
143
+ function pickerSelectedId(kind: SlashPickerKind, current: DesktopState): string | undefined {
144
+ if (kind === "model") return current.modelId;
145
+ if (kind === "mode") return current.mode;
146
+ if (kind === "image") return current.imageModelId;
147
+ if (kind === "video") return current.videoModelId;
148
+ if (kind === "transcribe") return current.transcribeModelId;
149
+ return undefined;
150
+ }
151
+
152
+ function mainViewTitle(view: MainView): string {
153
+ if (view === "settings") return "Settings";
154
+ if (view === "integrations") return "Integrations";
155
+ if (view === "skills") return "Skills";
156
+ return "Chat";
157
+ }
158
+
159
+ function titleCase(value: string): string {
160
+ return value ? `${value[0]?.toUpperCase() ?? ""}${value.slice(1)}` : value;
161
+ }
162
+
163
+ interface MediaModelStatus {
164
+ kind: string;
165
+ label: string;
166
+ }
167
+
168
+ function composerMediaModels(current: DesktopState): MediaModelStatus[] {
169
+ return [
170
+ current.imageModelLabel ? { kind: "Image", label: current.imageModelLabel } : null,
171
+ current.videoModelLabel ? { kind: "Clip", label: current.videoModelLabel } : null,
172
+ current.transcribeModelLabel ? { kind: "Speech", label: current.transcribeModelLabel } : null,
173
+ ].filter((part): part is MediaModelStatus => Boolean(part));
174
+ }
175
+
176
+ function readTheme(): ThemeChoice {
177
+ const value = localStorage.getItem("harness-theme");
178
+ return value === "light" || value === "dark" ? value : "system";
179
+ }
180
+
181
+ function applyTheme(choice: ThemeChoice): void {
182
+ const root = document.documentElement;
183
+ if (choice === "system") delete root.dataset.theme;
184
+ else root.dataset.theme = choice;
185
+ localStorage.setItem("harness-theme", choice);
186
+ }
187
+
188
+ function readSidebar(): boolean {
189
+ return localStorage.getItem("harness-sidebar") !== "off";
190
+ }
191
+
192
+ function writeSidebar(open: boolean): void {
193
+ localStorage.setItem("harness-sidebar", open ? "on" : "off");
194
+ }
195
+
196
+ function readMediaMeta(): boolean {
197
+ return localStorage.getItem("harness-media-meta") === "on";
198
+ }
199
+
200
+ function writeMediaMeta(open: boolean): void {
201
+ localStorage.setItem("harness-media-meta", open ? "on" : "off");
202
+ }
203
+
204
+ function slashMenuKey(
205
+ key: string,
206
+ slashOpen: boolean,
207
+ count: number,
208
+ ): "down" | "up" | "tab" | undefined {
209
+ if (!slashOpen || count === 0) return undefined;
210
+ if (key === "ArrowDown") return "down";
211
+ if (key === "ArrowUp") return "up";
212
+ if (key === "Tab") return "tab";
213
+ return undefined;
214
+ }
215
+
216
+ function composerEscapeAction(
217
+ editing: boolean,
218
+ status: UiStatus,
219
+ ): "cancel-edit" | "stop" | undefined {
220
+ if (editing) return "cancel-edit";
221
+ if (status === "running" || status === "approval") return "stop";
222
+ return undefined;
223
+ }
224
+
225
+ function applySlashComposerKey(
226
+ slashKey: "down" | "up" | "tab" | undefined,
227
+ slashItems: SlashCommand[],
228
+ slashIndex: number,
229
+ setSlashIndex: Dispatch<SetStateAction<number>>,
230
+ setDraft: Dispatch<SetStateAction<string>>,
231
+ ): boolean {
232
+ if (slashKey === "down") {
233
+ setSlashIndex((index) => (index + 1) % slashItems.length);
234
+ return true;
235
+ }
236
+ if (slashKey === "up") {
237
+ setSlashIndex((index) => (index - 1 + slashItems.length) % slashItems.length);
238
+ return true;
239
+ }
240
+ if (slashKey !== "tab") return false;
241
+ const selected = slashItems[slashIndex] ?? slashItems[0];
242
+ if (selected) setDraft(selected.arg ? `/${selected.name} ` : `/${selected.name}`);
243
+ return true;
244
+ }
245
+
246
+ function desktopCommandView(cmd: string): "skills" | "integrations" | undefined {
247
+ if (cmd === "skills" || cmd === "skill find") return "skills";
248
+ if (cmd === "integrations" || cmd === "integration") return "integrations";
249
+ return undefined;
250
+ }
251
+
252
+ const SILENT_CAPTIONS = "data:text/vtt,WEBVTT";
253
+
254
+ function composePlaceholder(listening: boolean, status: UiStatus): string {
255
+ if (listening) return "Listening";
256
+ if (status === "running") return "Queue a follow-up";
257
+ return "Ask the project";
258
+ }
259
+
260
+ function pickerItemHint(applied: boolean, hint?: string): React.ReactNode {
261
+ if (applied) return <em>on</em>;
262
+ if (hint) return <em>{hint}</em>;
263
+ return null;
264
+ }
265
+
266
+ function richPartKey(part: ReturnType<typeof splitRichText>[number]): string {
267
+ if (part.type === "text") return `text:${part.text}`;
268
+ if (part.type === "link") return `link:${part.href}:${part.label}`;
269
+ if (part.type === "file") return `file:${part.path}:${part.label}`;
270
+ return `image:${part.src}:${part.alt}`;
271
+ }
272
+
273
+ function DeskSidePanel(
274
+ props: Readonly<{
275
+ view: MainView;
276
+ bridge: BridgeClient | null;
277
+ theme: ThemeChoice;
278
+ skillQuery: string;
279
+ onTheme: (theme: ThemeChoice) => void;
280
+ onSaved: (state: DesktopState) => void;
281
+ onNotice: (text: string) => void;
282
+ onSkillQuery: (value: string) => void;
283
+ }>,
284
+ ): React.ReactElement | null {
285
+ if (!props.bridge) return null;
286
+ if (props.view === "settings") {
287
+ return (
288
+ <SettingsPanel
289
+ bridge={props.bridge}
290
+ theme={props.theme}
291
+ onTheme={props.onTheme}
292
+ onSaved={props.onSaved}
293
+ onNotice={props.onNotice}
294
+ />
295
+ );
296
+ }
297
+ if (props.view === "integrations") {
298
+ return <IntegrationsPanel bridge={props.bridge} onNotice={props.onNotice} />;
299
+ }
300
+ if (props.view === "skills") {
301
+ return (
302
+ <SkillsPanel
303
+ bridge={props.bridge}
304
+ query={props.skillQuery}
305
+ onQuery={props.onSkillQuery}
306
+ onNotice={props.onNotice}
307
+ />
308
+ );
309
+ }
310
+ return null;
311
+ }
312
+
313
+ function ComposeMicControl(
314
+ props: Readonly<{
315
+ status: UiStatus;
316
+ listening: boolean;
317
+ onStop: () => void;
318
+ onStopDictation: () => void;
319
+ onStartDictation: () => void;
320
+ }>,
321
+ ): React.ReactElement {
322
+ if (props.status === "running" || props.status === "approval") {
323
+ return (
324
+ <button type="button" className="desk-compose-icon" aria-label="Stop" onClick={props.onStop}>
325
+ <SquareIcon size={16} weight="regular" />
326
+ </button>
327
+ );
328
+ }
329
+ if (props.listening) {
330
+ return (
331
+ <button
332
+ type="button"
333
+ className="desk-compose-icon is-on"
334
+ aria-label="Stop dictation"
335
+ aria-pressed
336
+ onClick={props.onStopDictation}
337
+ >
338
+ <MicrophoneIcon size={16} weight="regular" />
339
+ </button>
340
+ );
341
+ }
342
+ return (
343
+ <button
344
+ type="button"
345
+ className="desk-compose-icon"
346
+ aria-label="Dictate"
347
+ aria-pressed={false}
348
+ disabled={props.status !== "idle"}
349
+ onClick={props.onStartDictation}
350
+ >
351
+ <MicrophoneIcon size={16} weight="regular" />
352
+ </button>
353
+ );
354
+ }
355
+
356
+ function DeskBoot(props: Readonly<{ error?: string }>): React.ReactElement {
357
+ return (
358
+ <div className="desk desk--boot">
359
+ <header className="desk-bar">
360
+ <LogoMark size={20} />
361
+ <h1>Caelence</h1>
362
+ {props.error ? null : (
363
+ <span className="cel-chip cel-chip--run">
364
+ <span className="cel-chip__spin" aria-hidden="true" />
365
+ {"Starting"}
366
+ </span>
367
+ )}
368
+ </header>
369
+ <main className="desk-empty">
370
+ {props.error ? (
371
+ <>
372
+ <p>{props.error}</p>
373
+ <p>Open this UI from the Caelence agent window, not a browser tab.</p>
374
+ </>
375
+ ) : (
376
+ <p>Starting the local runtime</p>
377
+ )}
378
+ </main>
379
+ </div>
380
+ );
381
+ }
382
+
383
+ function applyDesktopTurnEvent(
384
+ event: AgentEvent,
385
+ setState: Dispatch<SetStateAction<DesktopState | null>>,
386
+ setPending: Dispatch<SetStateAction<PendingApproval | null>>,
387
+ setStatus: Dispatch<SetStateAction<UiStatus>>,
388
+ setLines: Dispatch<SetStateAction<StreamLine[]>>,
389
+ ): boolean {
390
+ if (event.kind === "session_meta") {
391
+ setState((s) => (s ? { ...s, title: event.title } : s));
392
+ }
393
+ if (event.kind === "approval_request") {
394
+ setPending({
395
+ callId: event.callId,
396
+ toolName: event.toolName,
397
+ input: event.input,
398
+ });
399
+ setStatus("approval");
400
+ }
401
+ setLines((prev) => applyEvent(prev, event));
402
+ return event.kind === "completion" || event.kind === "error";
403
+ }
404
+
405
+ function failRunningTools(prev: StreamLine[]): StreamLine[] {
406
+ return prev.map((line) =>
407
+ line.type === "tool" && line.status === "running"
408
+ ? {
409
+ ...line,
410
+ status: "fail" as const,
411
+ error: "Turn stopped before this tool finished.",
412
+ }
413
+ : line,
414
+ );
415
+ }
416
+
417
+ export function App(): React.ReactElement {
418
+ const [bridge, setBridge] = useState<BridgeClient | null>(null);
419
+ const [bootError, setBootError] = useState<string | null>(null);
420
+ const [state, setState] = useState<DesktopState | null>(null);
421
+ const [sessions, setSessions] = useState<PickerItem[]>([]);
422
+ const [lines, setLines] = useState<StreamLine[]>([]);
423
+ const [draft, setDraft] = useState("");
424
+ const [status, setStatus] = useState<UiStatus>("boot");
425
+ const [view, setView] = useState<MainView>("chat");
426
+ const [skillQuery, setSkillQuery] = useState("");
427
+ const [theme, setTheme] = useState<ThemeChoice>(readTheme);
428
+ const [sideOpen, setSideOpen] = useState(readSidebar);
429
+ const [mediaOpen, setMediaOpen] = useState(readMediaMeta);
430
+ const [slashItems, setSlashItems] = useState<SlashCommand[]>([]);
431
+ const [slashIndex, setSlashIndex] = useState(0);
432
+ const [picker, setPicker] = useState<PickerState | null>(null);
433
+ const [sessionMenu, setSessionMenu] = useState<SessionMenuState | null>(null);
434
+ const [renamingId, setRenamingId] = useState<string | null>(null);
435
+ const [renameDraft, setRenameDraft] = useState("");
436
+ const [pending, setPending] = useState<PendingApproval | null>(null);
437
+ const [listening, setListening] = useState(false);
438
+ const [queue, setQueue] = useState<QueuedMessage[]>([]);
439
+ const [editingUser, setEditingUser] = useState<{ index: number; text: string } | null>(null);
440
+ const [editingQueuedId, setEditingQueuedId] = useState<string | null>(null);
441
+ const [notice, setNotice] = useState<{ text: string; id: number } | null>(null);
442
+ const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);
443
+ const [fileDrag, setFileDrag] = useState(false);
444
+ const transcriptRef = useRef<HTMLDivElement>(null);
445
+ const inputRef = useRef<HTMLTextAreaElement>(null);
446
+ const fileInputRef = useRef<HTMLInputElement>(null);
447
+ const attachmentsRef = useRef<ComposerAttachment[]>([]);
448
+ const fileDragDepth = useRef(0);
449
+ const viewRef = useRef(view);
450
+ viewRef.current = view;
451
+ const pickerListRef = useRef<HTMLUListElement>(null);
452
+ const sessionMenuRef = useRef<HTMLDivElement>(null);
453
+ const renameInputRef = useRef<HTMLInputElement>(null);
454
+ const skipRenameBlurRef = useRef(false);
455
+ const recorderRef = useRef<MediaRecorder | null>(null);
456
+ const dictationModeRef = useRef<"web" | "native" | null>(null);
457
+ const queueRef = useRef<QueuedMessage[]>([]);
458
+ const sendingRef = useRef(false);
459
+ const skipDrainRef = useRef(false);
460
+ const pickerRequestRef = useRef(0);
461
+ attachmentsRef.current = attachments;
462
+
463
+ const slashOpen = view === "chat" && draft.startsWith("/") && !listening && status !== "picker";
464
+
465
+ useEffect(() => {
466
+ applyTheme(theme);
467
+ }, [theme]);
468
+
469
+ useEffect(() => {
470
+ writeSidebar(sideOpen);
471
+ }, [sideOpen]);
472
+
473
+ useEffect(() => {
474
+ writeMediaMeta(mediaOpen);
475
+ }, [mediaOpen]);
476
+
477
+ const refreshSessions = useCallback(async (client: BridgeClient) => {
478
+ const result = await getSessions(client);
479
+ setSessions(result.items);
480
+ }, []);
481
+
482
+ useEffect(() => {
483
+ let cancelled = false;
484
+ const timer = window.setTimeout(() => {
485
+ if (!cancelled) {
486
+ setBootError(
487
+ (current) =>
488
+ current ??
489
+ "Caelence agent is taking too long to start. Close the window and run it again.",
490
+ );
491
+ }
492
+ }, 12_000);
493
+ void (async () => {
494
+ try {
495
+ const client = await resolveBridge();
496
+ const next = await getState(client);
497
+ const listed = await getSessions(client);
498
+ if (cancelled) return;
499
+ setBridge(client);
500
+ setState(next);
501
+ setSessions(listed.items);
502
+ if (next.sessionId) {
503
+ const loaded = await postSession(client, { id: next.sessionId });
504
+ if (cancelled) return;
505
+ setState(loaded.state);
506
+ setLines(linesFromTranscript(loaded.messages ?? []));
507
+ }
508
+ setStatus("idle");
509
+ } catch (err) {
510
+ if (cancelled) return;
511
+ setBootError(
512
+ err instanceof Error ? err.message : "Caelence agent could not reach the local runtime.",
513
+ );
514
+ } finally {
515
+ window.clearTimeout(timer);
516
+ }
517
+ })();
518
+ return () => {
519
+ cancelled = true;
520
+ window.clearTimeout(timer);
521
+ };
522
+ }, []);
523
+
524
+ useEffect(() => {
525
+ const node = transcriptRef.current;
526
+ if (node) node.scrollTop = node.scrollHeight;
527
+ }, [lines, pending]);
528
+
529
+ useEffect(() => {
530
+ if (!bridge || !slashOpen) {
531
+ setSlashItems([]);
532
+ return;
533
+ }
534
+ let cancelled = false;
535
+ void getSlash(bridge, draft).then((result) => {
536
+ if (!cancelled) setSlashItems(result.items);
537
+ });
538
+ return () => {
539
+ cancelled = true;
540
+ };
541
+ }, [bridge, draft, slashOpen]);
542
+
543
+ useEffect(() => {
544
+ setSlashIndex(0);
545
+ }, [draft]);
546
+
547
+ const pushSystem = useCallback((text: string) => {
548
+ setLines((prev) => [
549
+ ...prev,
550
+ { key: `sys-${prev.length}-${Date.now()}`, type: "system", text },
551
+ ]);
552
+ }, []);
553
+
554
+ const dismissNotice = useCallback(() => setNotice(null), []);
555
+
556
+ const showNotice = useCallback((text: string) => {
557
+ const line = text.trim();
558
+ if (!line) return;
559
+ setNotice({ text: line, id: Date.now() });
560
+ }, []);
561
+
562
+ const noticeError = useCallback(
563
+ (err: unknown) => {
564
+ showNotice(errorMessage(err));
565
+ },
566
+ [showNotice],
567
+ );
568
+
569
+ const applyOutcome = useCallback(
570
+ async (outcome: SlashOutcome, nextState?: DesktopState) => {
571
+ if (nextState) setState(nextState);
572
+ if (outcome.kind === "applied" || outcome.kind === "hold") return;
573
+ if (outcome.kind === "incomplete") {
574
+ setDraft(outcome.draft);
575
+ return;
576
+ }
577
+ if (outcome.kind === "text") {
578
+ pushSystem(outcome.text);
579
+ return;
580
+ }
581
+ if (outcome.kind === "clear") {
582
+ setLines([]);
583
+ pushSystem("New session.");
584
+ if (bridge) await refreshSessions(bridge);
585
+ return;
586
+ }
587
+ if (outcome.kind === "session") {
588
+ if (!bridge) return;
589
+ const loaded = await postSession(bridge, { id: outcome.session.id });
590
+ setState(loaded.state);
591
+ setLines(linesFromTranscript(loaded.messages ?? []));
592
+ pushSystem(`Resumed ${loaded.state.title}`);
593
+ await refreshSessions(bridge);
594
+ return;
595
+ }
596
+ if (outcome.kind === "exit") {
597
+ const { getCurrentWindow } = await import("@tauri-apps/api/window");
598
+ await getCurrentWindow().close();
599
+ return;
600
+ }
601
+ if (outcome.kind === "media") {
602
+ setLines((prev) => [
603
+ ...prev,
604
+ {
605
+ key: `media-${prev.length}-${Date.now()}`,
606
+ type: "media",
607
+ kind: outcome.media.kind,
608
+ src: outcome.media.dataUrl,
609
+ caption: outcome.caption,
610
+ mimeType: outcome.media.mimeType,
611
+ },
612
+ ]);
613
+ return;
614
+ }
615
+ const currentId = nextState ? pickerSelectedId(outcome.picker, nextState) : undefined;
616
+ setPicker({
617
+ title: outcome.title,
618
+ kind: outcome.picker,
619
+ items: outcome.items,
620
+ index: pickerStartIndex(outcome.items, currentId),
621
+ });
622
+ setStatus("picker");
623
+ },
624
+ [bridge, pushSystem, refreshSessions],
625
+ );
626
+
627
+ const setQueueSync = useCallback((next: QueuedMessage[]) => {
628
+ queueRef.current = next;
629
+ setQueue(next);
630
+ }, []);
631
+
632
+ const addFiles = useCallback(
633
+ (files: File[]) => {
634
+ if (files.length === 0) return;
635
+ const next = mergeAttachments(attachmentsRef.current, files);
636
+ if (next.rejected.length > 0) {
637
+ showNotice(`Could not add ${next.rejected.join(", ")}.`);
638
+ }
639
+ if (next.attachments === attachmentsRef.current) return;
640
+ attachmentsRef.current = next.attachments;
641
+ setAttachments(next.attachments);
642
+ },
643
+ [showNotice],
644
+ );
645
+
646
+ const ingestDropped = useCallback(
647
+ async (transfer: DataTransfer | null, extraPaths: string[] = []) => {
648
+ if (viewRef.current !== "chat") return;
649
+ const html = filesFromTransfer(transfer);
650
+ const usable = html.filter((file) => file.size > 0);
651
+ if (usable.length > 0) {
652
+ addFiles(usable);
653
+ return;
654
+ }
655
+ const paths = [...new Set([...extraPaths, ...droppedPaths(transfer)])];
656
+ if (paths.length === 0) {
657
+ if (html.length > 0) addFiles(html);
658
+ return;
659
+ }
660
+ try {
661
+ const files = await filesFromDroppedPaths(paths);
662
+ addFiles(files.length > 0 ? files : html);
663
+ } catch (err) {
664
+ noticeError(err);
665
+ }
666
+ },
667
+ [addFiles, noticeError],
668
+ );
669
+
670
+ const takeAttachments = useCallback((): ComposerAttachment[] => {
671
+ const items = attachmentsRef.current;
672
+ attachmentsRef.current = [];
673
+ setAttachments([]);
674
+ return items;
675
+ }, []);
676
+
677
+ const removeAttachment = useCallback((index: number) => {
678
+ setAttachments((current) => {
679
+ const item = current[index];
680
+ if (item) releaseAttachment(item);
681
+ return current.filter((_, at) => at !== index);
682
+ });
683
+ }, []);
684
+
685
+ const onFileDragEnter = useCallback(
686
+ (event: React.DragEvent) => {
687
+ if (view !== "chat" || !transferHasFiles(event.dataTransfer)) return;
688
+ event.preventDefault();
689
+ fileDragDepth.current += 1;
690
+ setFileDrag(true);
691
+ },
692
+ [view],
693
+ );
694
+
695
+ const onFileDragOver = useCallback((event: React.DragEvent) => {
696
+ if (!transferHasFiles(event.dataTransfer)) return;
697
+ event.preventDefault();
698
+ event.dataTransfer.dropEffect = "copy";
699
+ }, []);
700
+
701
+ const onFileDragLeave = useCallback((event: React.DragEvent) => {
702
+ if (!transferHasFiles(event.dataTransfer)) return;
703
+ event.preventDefault();
704
+ fileDragDepth.current = Math.max(0, fileDragDepth.current - 1);
705
+ if (fileDragDepth.current === 0) setFileDrag(false);
706
+ }, []);
707
+
708
+ const onFileDrop = useCallback(
709
+ (event: React.DragEvent) => {
710
+ if (view !== "chat" || !transferHasFiles(event.dataTransfer)) return;
711
+ event.preventDefault();
712
+ event.stopPropagation();
713
+ fileDragDepth.current = 0;
714
+ setFileDrag(false);
715
+ void ingestDropped(event.dataTransfer);
716
+ },
717
+ [ingestDropped, view],
718
+ );
719
+
720
+ const sendTurn = useCallback(
721
+ async (message: string, editUserTurn?: number, files: ComposerAttachment[] = []) => {
722
+ if (!bridge) return;
723
+ sendingRef.current = true;
724
+ skipDrainRef.current = false;
725
+ try {
726
+ let current = message;
727
+ let edit = editUserTurn;
728
+ let pendingFiles = files;
729
+ while (true) {
730
+ const slash =
731
+ edit === undefined &&
732
+ (current.startsWith("/") ||
733
+ current === "help" ||
734
+ current === "--help" ||
735
+ current === "-h");
736
+ if (slash) {
737
+ const { cmd, arg } = parseSlashLine(current);
738
+ const viewForCmd = desktopCommandView(cmd);
739
+ if (viewForCmd) {
740
+ if (viewForCmd === "skills") setSkillQuery(cmd === "skill find" ? arg : "");
741
+ setView(viewForCmd);
742
+ setDraft("");
743
+ break;
744
+ }
745
+ if (arg || !PICKS_WHEN_EMPTY.has(cmd)) {
746
+ setStatus("running");
747
+ }
748
+ setView("chat");
749
+ try {
750
+ const result = await startTurn(bridge, current);
751
+ if (result?.outcome) await applyOutcome(result.outcome, result.state);
752
+ if (
753
+ result?.outcome?.kind === "picker" ||
754
+ result?.outcome?.kind === "exit" ||
755
+ result?.outcome?.kind === "hold" ||
756
+ result?.outcome?.kind === "incomplete"
757
+ ) {
758
+ break;
759
+ }
760
+ } catch (err) {
761
+ if (!isAbortError(err)) noticeError(err);
762
+ }
763
+ } else {
764
+ setView("chat");
765
+ const editIndex = edit;
766
+ const previews = toAttachmentPreviews(pendingFiles);
767
+ if (editIndex !== undefined) {
768
+ setLines((prev) => truncateAfterUserTurn(prev, editIndex, current));
769
+ } else {
770
+ setLines((prev) => [
771
+ ...prev,
772
+ {
773
+ key: `u-${Date.now()}`,
774
+ type: "user",
775
+ text: current,
776
+ userTurnIndex: nextUserTurnIndex(prev),
777
+ ...(previews.length > 0 ? { attachments: previews } : {}),
778
+ },
779
+ ]);
780
+ }
781
+ setStatus("running");
782
+ try {
783
+ let finished = false;
784
+ const payload =
785
+ pendingFiles.length > 0
786
+ ? await serializeComposerAttachments(pendingFiles)
787
+ : undefined;
788
+ await startTurn(
789
+ bridge,
790
+ current,
791
+ (event: AgentEvent) => {
792
+ if (applyDesktopTurnEvent(event, setState, setPending, setStatus, setLines)) {
793
+ finished = true;
794
+ }
795
+ },
796
+ undefined,
797
+ edit,
798
+ payload,
799
+ );
800
+ if (!finished) {
801
+ setLines(failRunningTools);
802
+ showNotice("The turn stopped before the model finished. Send the prompt again.");
803
+ }
804
+ const next = await getState(bridge);
805
+ setState(next);
806
+ await refreshSessions(bridge);
807
+ } catch (err) {
808
+ if (!isAbortError(err)) noticeError(err);
809
+ } finally {
810
+ setPending(null);
811
+ }
812
+ }
813
+ if (skipDrainRef.current) break;
814
+ const queued = queueRef.current[0];
815
+ if (!queued) break;
816
+ queueRef.current = queueRef.current.slice(1);
817
+ setQueue(queueRef.current);
818
+ current = queued.text;
819
+ pendingFiles = queued.attachments ?? [];
820
+ edit = undefined;
821
+ }
822
+ } finally {
823
+ sendingRef.current = false;
824
+ setPending(null);
825
+ setStatus((current) => (current === "picker" ? current : "idle"));
826
+ }
827
+ },
828
+ [applyOutcome, bridge, noticeError, refreshSessions, showNotice],
829
+ );
830
+
831
+ const openComposerPicker = useCallback(
832
+ async (kind: "model" | "mode") => {
833
+ if (
834
+ !bridge ||
835
+ listening ||
836
+ status === "boot" ||
837
+ status === "running" ||
838
+ status === "approval"
839
+ ) {
840
+ return;
841
+ }
842
+ if (sendingRef.current) return;
843
+ pickerRequestRef.current += 1;
844
+ const requestId = pickerRequestRef.current;
845
+ if (picker?.kind === kind) {
846
+ setPicker(null);
847
+ setStatus("idle");
848
+ return;
849
+ }
850
+ if (kind === "mode") {
851
+ const items = AGENT_MODES.map((id) => ({ id, label: id }));
852
+ setPicker({
853
+ title: "Mode",
854
+ kind: "mode",
855
+ items,
856
+ index: pickerStartIndex(items, state?.mode),
857
+ });
858
+ setStatus("picker");
859
+ return;
860
+ }
861
+ try {
862
+ const result = await getModels(bridge);
863
+ if (requestId !== pickerRequestRef.current) return;
864
+ setPicker({
865
+ title: "Model",
866
+ kind: "model",
867
+ items: result.items,
868
+ index: pickerStartIndex(result.items, state?.modelId),
869
+ });
870
+ setStatus("picker");
871
+ } catch (err) {
872
+ if (requestId !== pickerRequestRef.current) return;
873
+ noticeError(err);
874
+ }
875
+ },
876
+ [bridge, listening, noticeError, picker, state, status],
877
+ );
878
+
879
+ const submit = useCallback(async () => {
880
+ if (!bridge || listening || status === "picker" || status === "boot") return;
881
+ const message = draft.trim();
882
+ const files = attachmentsRef.current;
883
+ if (!message && files.length === 0) return;
884
+ const slash = message
885
+ ? resolveSlashSubmit(message, slashOpen ? slashItems[slashIndex] : undefined)
886
+ : undefined;
887
+ if (slash?.action === "hold") return;
888
+ if (slash?.action === "complete") {
889
+ setDraft(slash.line);
890
+ return;
891
+ }
892
+ const toSend = slash?.action === "send" ? slash.line : message;
893
+ const pendingFiles = slash ? [] : takeAttachments();
894
+ setDraft("");
895
+ setView("chat");
896
+ if (status === "running" || status === "approval" || sendingRef.current) {
897
+ setQueueSync(enqueueMessage(queueRef.current, toSend, `q-${Date.now()}`, pendingFiles));
898
+ return;
899
+ }
900
+ await sendTurn(toSend, undefined, pendingFiles);
901
+ }, [
902
+ bridge,
903
+ draft,
904
+ listening,
905
+ sendTurn,
906
+ setQueueSync,
907
+ slashIndex,
908
+ slashItems,
909
+ slashOpen,
910
+ status,
911
+ takeAttachments,
912
+ ]);
913
+
914
+ const stop = useCallback(async () => {
915
+ if (!bridge) return;
916
+ await abortTurn(bridge);
917
+ }, [bridge]);
918
+
919
+ const commitEdit = useCallback(async () => {
920
+ if (!bridge || !editingUser) return;
921
+ const text = editingUser.text.trim();
922
+ if (!text) return;
923
+ const index = editingUser.index;
924
+ setEditingUser(null);
925
+ skipDrainRef.current = true;
926
+ if (status === "running" || status === "approval" || sendingRef.current) {
927
+ await abortTurn(bridge);
928
+ for (let i = 0; i < 50 && sendingRef.current; i++) {
929
+ await new Promise((resolve) => setTimeout(resolve, 20));
930
+ }
931
+ }
932
+ skipDrainRef.current = false;
933
+ await sendTurn(text, index);
934
+ }, [bridge, editingUser, sendTurn, status]);
935
+
936
+ const choosePicker = useCallback(
937
+ async (item: PickerItem) => {
938
+ if (!bridge || !picker) return;
939
+ const kind = picker.kind;
940
+ setPicker(null);
941
+ setStatus("idle");
942
+ const result = await postPicker(bridge, kind, item.id);
943
+ setState(result.state);
944
+ if (result.messages) {
945
+ setLines(linesFromTranscript(result.messages));
946
+ pushSystem(`Resumed ${result.state.title}`);
947
+ } else if (result.text) {
948
+ pushSystem(result.text);
949
+ }
950
+ const nextDraft = draftAfterPicker(kind);
951
+ if (nextDraft) {
952
+ setDraft(nextDraft);
953
+ requestAnimationFrame(() => inputRef.current?.focus());
954
+ }
955
+ await refreshSessions(bridge);
956
+ },
957
+ [bridge, picker, pushSystem, refreshSessions],
958
+ );
959
+
960
+ const cancelPicker = useCallback(() => {
961
+ if (!picker) return;
962
+ pickerRequestRef.current += 1;
963
+ const next = draftAfterPicker(picker.kind);
964
+ setPicker(null);
965
+ setStatus("idle");
966
+ if (next) setDraft(next);
967
+ requestAnimationFrame(() => inputRef.current?.focus());
968
+ }, [picker]);
969
+
970
+ useEffect(() => {
971
+ if (!picker) return;
972
+ const onKey = (event: KeyboardEvent) => {
973
+ const action = pickerKeyAction(event.key, event.shiftKey);
974
+ if (!action) return;
975
+ event.preventDefault();
976
+ event.stopPropagation();
977
+ if (action.type === "move") {
978
+ setPicker((current) =>
979
+ current
980
+ ? { ...current, index: stepIndex(current.index, current.items.length, action.delta) }
981
+ : current,
982
+ );
983
+ return;
984
+ }
985
+ if (action.type === "confirm") {
986
+ const item = picker.items[picker.index];
987
+ if (item) void choosePicker(item);
988
+ return;
989
+ }
990
+ if (action.type === "cancel") cancelPicker();
991
+ };
992
+ window.addEventListener("keydown", onKey, true);
993
+ return () => window.removeEventListener("keydown", onKey, true);
994
+ }, [cancelPicker, choosePicker, picker]);
995
+
996
+ useEffect(() => {
997
+ if (!picker) return;
998
+ const node = pickerListRef.current?.querySelector(`[data-picker-index="${picker.index}"]`);
999
+ if (node instanceof HTMLElement) node.scrollIntoView({ block: "nearest" });
1000
+ }, [picker]);
1001
+
1002
+ const releaseLinePreviews = useCallback((next: StreamLine[]) => {
1003
+ setLines((prev) => {
1004
+ for (const line of prev) {
1005
+ if (line.type !== "user") continue;
1006
+ for (const item of line.attachments ?? []) releaseAttachment(item);
1007
+ }
1008
+ return next;
1009
+ });
1010
+ }, []);
1011
+
1012
+ const openSession = useCallback(
1013
+ async (id: string) => {
1014
+ if (!bridge || status !== "idle") return;
1015
+ setView("chat");
1016
+ setQueueSync([]);
1017
+ setEditingUser(null);
1018
+ setRenamingId(null);
1019
+ setSessionMenu(null);
1020
+ const loaded = await postSession(bridge, { id });
1021
+ setState(loaded.state);
1022
+ releaseLinePreviews(linesFromTranscript(loaded.messages ?? []));
1023
+ },
1024
+ [bridge, releaseLinePreviews, setQueueSync, status],
1025
+ );
1026
+
1027
+ const newChat = useCallback(async () => {
1028
+ if (!bridge || status !== "idle") return;
1029
+ setView("chat");
1030
+ setQueueSync([]);
1031
+ setEditingUser(null);
1032
+ setRenamingId(null);
1033
+ setSessionMenu(null);
1034
+ const next = await postSession(bridge, { clear: true });
1035
+ setState(next.state);
1036
+ releaseLinePreviews([]);
1037
+ }, [bridge, releaseLinePreviews, setQueueSync, status]);
1038
+
1039
+ const commitRename = useCallback(async () => {
1040
+ if (!bridge || !renamingId) return;
1041
+ const id = renamingId;
1042
+ const nextTitle = renameDraft.trim();
1043
+ setRenamingId(null);
1044
+ if (!nextTitle) return;
1045
+ try {
1046
+ const result = await renameSession(bridge, id, nextTitle);
1047
+ setState(result.state);
1048
+ await refreshSessions(bridge);
1049
+ } catch (err) {
1050
+ noticeError(err);
1051
+ }
1052
+ }, [bridge, noticeError, refreshSessions, renameDraft, renamingId]);
1053
+
1054
+ const removeChat = useCallback(
1055
+ async (id: string) => {
1056
+ if (!bridge) return;
1057
+ setSessionMenu(null);
1058
+ try {
1059
+ const result = await deleteSession(bridge, id);
1060
+ setState(result.state);
1061
+ if (result.cleared) {
1062
+ releaseLinePreviews([]);
1063
+ setQueueSync([]);
1064
+ setEditingUser(null);
1065
+ }
1066
+ await refreshSessions(bridge);
1067
+ } catch (err) {
1068
+ noticeError(err);
1069
+ }
1070
+ },
1071
+ [bridge, noticeError, refreshSessions, releaseLinePreviews, setQueueSync],
1072
+ );
1073
+
1074
+ useLayoutEffect(() => {
1075
+ if (!sessionMenu) return;
1076
+ const node = sessionMenuRef.current;
1077
+ if (!node) return;
1078
+ const next = clampMenuPosition(
1079
+ sessionMenu.x,
1080
+ sessionMenu.y,
1081
+ { width: node.offsetWidth, height: node.offsetHeight },
1082
+ { width: window.innerWidth, height: window.innerHeight },
1083
+ );
1084
+ node.style.left = `${next.x}px`;
1085
+ node.style.top = `${next.y}px`;
1086
+ node.querySelector("button")?.focus();
1087
+ }, [sessionMenu]);
1088
+
1089
+ useEffect(() => {
1090
+ if (!sessionMenu) return;
1091
+ const onPointer = (event: Event) => {
1092
+ const node = event.target;
1093
+ if (node instanceof Node && sessionMenuRef.current?.contains(node)) return;
1094
+ setSessionMenu(null);
1095
+ };
1096
+ window.addEventListener("mousedown", onPointer);
1097
+ return () => window.removeEventListener("mousedown", onPointer);
1098
+ }, [sessionMenu]);
1099
+
1100
+ useEffect(() => {
1101
+ if (renamingId) renameInputRef.current?.focus();
1102
+ }, [renamingId]);
1103
+
1104
+ useEffect(() => {
1105
+ if (!sessionMenu && !renamingId) return;
1106
+ const onKey = (event: KeyboardEvent) => {
1107
+ if (event.key !== "Escape") return;
1108
+ event.preventDefault();
1109
+ setSessionMenu(null);
1110
+ if (renamingId) {
1111
+ skipRenameBlurRef.current = true;
1112
+ setRenamingId(null);
1113
+ }
1114
+ };
1115
+ window.addEventListener("keydown", onKey);
1116
+ return () => window.removeEventListener("keydown", onKey);
1117
+ }, [renamingId, sessionMenu]);
1118
+
1119
+ const decide = useCallback(
1120
+ async (decision: "yes" | "no" | "always") => {
1121
+ if (!bridge || !pending) return;
1122
+ await approve(bridge, {
1123
+ callId: pending.callId,
1124
+ decision,
1125
+ toolName: pending.toolName,
1126
+ });
1127
+ setPending(null);
1128
+ setStatus("running");
1129
+ },
1130
+ [bridge, pending],
1131
+ );
1132
+
1133
+ const applySpoken = useCallback(
1134
+ async (data: string, format: string) => {
1135
+ if (!bridge) return;
1136
+ try {
1137
+ const result = await transcribe(bridge, { data, format });
1138
+ const spoken = result.text.trim();
1139
+ if (!spoken) {
1140
+ showNotice("Transcription returned no text.");
1141
+ return;
1142
+ }
1143
+ setDraft((current) => (current.trim() ? `${current.trim()} ${spoken}` : spoken));
1144
+ inputRef.current?.focus();
1145
+ } catch (err) {
1146
+ noticeError(err);
1147
+ }
1148
+ },
1149
+ [bridge, noticeError, showNotice],
1150
+ );
1151
+
1152
+ const stopDictation = useCallback(() => {
1153
+ const mode = dictationModeRef.current;
1154
+ if (mode === "native") {
1155
+ dictationModeRef.current = null;
1156
+ setListening(false);
1157
+ void (async () => {
1158
+ try {
1159
+ const clip = await micStop();
1160
+ await applySpoken(clip.data, clip.format);
1161
+ } catch (err) {
1162
+ noticeError(err);
1163
+ }
1164
+ })();
1165
+ return;
1166
+ }
1167
+ const recorder = recorderRef.current;
1168
+ if (!recorder) {
1169
+ setListening(false);
1170
+ return;
1171
+ }
1172
+ if (recorder.state !== "inactive") recorder.stop();
1173
+ }, [applySpoken, noticeError]);
1174
+
1175
+ const startDictation = useCallback(async () => {
1176
+ if (!bridge || status !== "idle" || listening) return;
1177
+ const startWeb = async () => {
1178
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
1179
+ const mime = pickRecorderMime();
1180
+ const recorder = mime
1181
+ ? new MediaRecorder(stream, { mimeType: mime })
1182
+ : new MediaRecorder(stream);
1183
+ const chunks: Blob[] = [];
1184
+ recorder.ondataavailable = (event) => {
1185
+ if (event.data.size > 0) chunks.push(event.data);
1186
+ };
1187
+ recorder.onstop = () => {
1188
+ for (const track of stream.getTracks()) track.stop();
1189
+ recorderRef.current = null;
1190
+ dictationModeRef.current = null;
1191
+ setListening(false);
1192
+ const blob = new Blob(chunks, { type: recorder.mimeType || "audio/webm" });
1193
+ if (blob.size === 0) return;
1194
+ void blobToBase64(blob).then((data) => applySpoken(data, audioFormatFromMime(blob.type)));
1195
+ };
1196
+ recorderRef.current = recorder;
1197
+ dictationModeRef.current = "web";
1198
+ recorder.start(250);
1199
+ setListening(true);
1200
+ };
1201
+ if (canUseWebMic()) {
1202
+ try {
1203
+ await startWeb();
1204
+ return;
1205
+ } catch (err) {
1206
+ if (isMicPermissionDenied(err)) {
1207
+ showNotice(dictationErrorMessage(err));
1208
+ return;
1209
+ }
1210
+ }
1211
+ }
1212
+ try {
1213
+ await micStart();
1214
+ dictationModeRef.current = "native";
1215
+ setListening(true);
1216
+ } catch (err) {
1217
+ showNotice(dictationErrorMessage(err));
1218
+ }
1219
+ }, [applySpoken, bridge, listening, showNotice, status]);
1220
+
1221
+ useEffect(() => {
1222
+ const onOver = (event: DragEvent) => {
1223
+ if (!transferHasFiles(event.dataTransfer)) return;
1224
+ event.preventDefault();
1225
+ };
1226
+ const onDrop = (event: DragEvent) => {
1227
+ if (!transferHasFiles(event.dataTransfer)) return;
1228
+ event.preventDefault();
1229
+ fileDragDepth.current = 0;
1230
+ setFileDrag(false);
1231
+ void ingestDropped(event.dataTransfer);
1232
+ };
1233
+ window.addEventListener("dragover", onOver);
1234
+ window.addEventListener("drop", onDrop);
1235
+ return () => {
1236
+ window.removeEventListener("dragover", onOver);
1237
+ window.removeEventListener("drop", onDrop);
1238
+ const recorder = recorderRef.current;
1239
+ if (recorder && recorder.state !== "inactive") recorder.stop();
1240
+ if (dictationModeRef.current === "native") {
1241
+ void micStop().catch(() => undefined);
1242
+ dictationModeRef.current = null;
1243
+ }
1244
+ for (const item of attachmentsRef.current) releaseAttachment(item);
1245
+ };
1246
+ }, [ingestDropped]);
1247
+
1248
+ useEffect(() => {
1249
+ let cancelled = false;
1250
+ let stop: (() => void) | undefined;
1251
+ void (async () => {
1252
+ try {
1253
+ const { getCurrentWebview } = await import("@tauri-apps/api/webview");
1254
+ const unlisten = await getCurrentWebview().onDragDropEvent((event) => {
1255
+ if (viewRef.current !== "chat") return;
1256
+ if (event.payload.type === "enter" || event.payload.type === "over") {
1257
+ setFileDrag(true);
1258
+ return;
1259
+ }
1260
+ if (event.payload.type === "leave") {
1261
+ setFileDrag(false);
1262
+ return;
1263
+ }
1264
+ if (event.payload.type === "drop") {
1265
+ setFileDrag(false);
1266
+ void ingestDropped(null, event.payload.paths);
1267
+ }
1268
+ });
1269
+ if (cancelled) unlisten();
1270
+ else stop = unlisten;
1271
+ } catch {
1272
+ // Browser preview has no Tauri webview.
1273
+ }
1274
+ })();
1275
+ return () => {
1276
+ cancelled = true;
1277
+ stop?.();
1278
+ };
1279
+ }, [ingestDropped]);
1280
+
1281
+ const onKeyDown = useCallback(
1282
+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
1283
+ if (picker) {
1284
+ event.preventDefault();
1285
+ return;
1286
+ }
1287
+ if (event.key === "Escape") {
1288
+ const action = composerEscapeAction(Boolean(editingUser), status);
1289
+ if (action === "cancel-edit") {
1290
+ event.preventDefault();
1291
+ setEditingUser(null);
1292
+ return;
1293
+ }
1294
+ if (action === "stop") {
1295
+ event.preventDefault();
1296
+ void stop();
1297
+ return;
1298
+ }
1299
+ }
1300
+ const slashKey = slashMenuKey(event.key, slashOpen, slashItems.length);
1301
+ if (applySlashComposerKey(slashKey, slashItems, slashIndex, setSlashIndex, setDraft)) {
1302
+ event.preventDefault();
1303
+ return;
1304
+ }
1305
+ if (event.key === "Enter" && !event.shiftKey) {
1306
+ event.preventDefault();
1307
+ void submit();
1308
+ }
1309
+ },
1310
+ [editingUser, picker, slashIndex, slashItems, slashOpen, status, stop, submit],
1311
+ );
1312
+
1313
+ const mediaModels = state ? composerMediaModels(state) : [];
1314
+
1315
+ if (bootError) return <DeskBoot error={bootError} />;
1316
+ if (!state) return <DeskBoot />;
1317
+
1318
+ const approvalPreview = pending ? previewInput(pending.input) : "";
1319
+ const turnRunning = status === "running" || status === "approval";
1320
+ const transcriptBlocks = groupTranscriptLines(lines);
1321
+ const lastLine = lines.at(-1);
1322
+ const thoughtPending = turnRunning && (!lastLine || lastLine.type === "user");
1323
+ const warmupSeed = lastLine?.type === "user" ? lastLine.userTurnIndex : 0;
1324
+
1325
+ return (
1326
+ <div className={`desk${sideOpen ? "" : " is-side-off"}`}>
1327
+ <aside className="desk-side">
1328
+ <div className="desk-brand">
1329
+ <LogoMark size={20} />
1330
+ <div className="desk-brand-copy">
1331
+ <p className="desk-wordmark">Caelence</p>
1332
+ <p className="desk-product">agent</p>
1333
+ </div>
1334
+ <button
1335
+ type="button"
1336
+ className="desk-side-toggle"
1337
+ aria-pressed={sideOpen}
1338
+ aria-label={sideOpen ? "Hide sidebar" : "Show sidebar"}
1339
+ onClick={() => setSideOpen((open) => !open)}
1340
+ >
1341
+ <SidebarSimpleIcon size={16} weight="regular" />
1342
+ </button>
1343
+ </div>
1344
+ <button
1345
+ type="button"
1346
+ className="desk-settings-btn desk-new"
1347
+ disabled={status !== "idle"}
1348
+ aria-label="New chat"
1349
+ onClick={() => void newChat()}
1350
+ >
1351
+ <PlusIcon size={16} weight="regular" />
1352
+ <span>New chat</span>
1353
+ </button>
1354
+ <section className="desk-sessions" aria-label="Sessions">
1355
+ <h2>Sessions</h2>
1356
+ {sessions.length === 0 ? (
1357
+ <p className="desk-side-empty">No saved sessions</p>
1358
+ ) : (
1359
+ <ul>
1360
+ {sessions.map((item) => (
1361
+ <li
1362
+ key={item.id}
1363
+ onContextMenu={(event) => {
1364
+ event.preventDefault();
1365
+ setPicker(null);
1366
+ setStatus((current) => (current === "picker" ? "idle" : current));
1367
+ setRenamingId(null);
1368
+ setSessionMenu({
1369
+ id: item.id,
1370
+ label: item.label,
1371
+ x: event.clientX,
1372
+ y: event.clientY,
1373
+ });
1374
+ }}
1375
+ >
1376
+ {renamingId === item.id ? (
1377
+ <input
1378
+ ref={renameInputRef}
1379
+ className="cel-input desk-rename"
1380
+ value={renameDraft}
1381
+ aria-label="Chat name"
1382
+ onChange={(event) => setRenameDraft(event.target.value)}
1383
+ onKeyDown={(event) => {
1384
+ if (event.key === "Enter") {
1385
+ event.preventDefault();
1386
+ event.stopPropagation();
1387
+ skipRenameBlurRef.current = true;
1388
+ void commitRename();
1389
+ }
1390
+ if (event.key === "Escape") {
1391
+ event.preventDefault();
1392
+ event.stopPropagation();
1393
+ skipRenameBlurRef.current = true;
1394
+ setRenamingId(null);
1395
+ }
1396
+ }}
1397
+ onBlur={() => {
1398
+ if (skipRenameBlurRef.current) {
1399
+ skipRenameBlurRef.current = false;
1400
+ return;
1401
+ }
1402
+ void commitRename();
1403
+ }}
1404
+ />
1405
+ ) : (
1406
+ <button
1407
+ type="button"
1408
+ className={item.id === state.sessionId ? "is-on" : undefined}
1409
+ disabled={status !== "idle"}
1410
+ onClick={() => void openSession(item.id)}
1411
+ >
1412
+ <span>{item.label}</span>
1413
+ {item.hint ? <em>{item.hint}</em> : null}
1414
+ </button>
1415
+ )}
1416
+ </li>
1417
+ ))}
1418
+ </ul>
1419
+ )}
1420
+ </section>
1421
+ <button
1422
+ type="button"
1423
+ className={`desk-settings-btn ${view === "skills" ? "is-on" : ""}`}
1424
+ aria-label="Skills"
1425
+ onClick={() => {
1426
+ setView((current) => (current === "skills" ? "chat" : "skills"));
1427
+ setSkillQuery("");
1428
+ }}
1429
+ >
1430
+ <PuzzlePieceIcon size={16} weight="regular" />
1431
+ <span>Skills</span>
1432
+ </button>
1433
+ <button
1434
+ type="button"
1435
+ className={`desk-settings-btn ${view === "integrations" ? "is-on" : ""}`}
1436
+ aria-label="Integrations"
1437
+ onClick={() =>
1438
+ setView((current) => (current === "integrations" ? "chat" : "integrations"))
1439
+ }
1440
+ >
1441
+ <PlugsIcon size={16} weight="regular" />
1442
+ <span>Integrations</span>
1443
+ </button>
1444
+ <button
1445
+ type="button"
1446
+ className={`desk-settings-btn ${view === "settings" ? "is-on" : ""}`}
1447
+ aria-label="Settings"
1448
+ onClick={() => setView((current) => (current === "settings" ? "chat" : "settings"))}
1449
+ >
1450
+ <GearIcon size={16} weight="regular" />
1451
+ <span>Settings</span>
1452
+ </button>
1453
+ </aside>
1454
+
1455
+ <section
1456
+ className={`desk-main${fileDrag && view === "chat" ? " is-file-drag" : ""}`}
1457
+ aria-label="Chat"
1458
+ onDragEnter={onFileDragEnter}
1459
+ onDragOver={onFileDragOver}
1460
+ onDragLeave={onFileDragLeave}
1461
+ onDrop={onFileDrop}
1462
+ >
1463
+ <header className="desk-bar">
1464
+ <div className="desk-id">
1465
+ <h1>{mainViewTitle(view)}</h1>
1466
+ {view === "chat" && state.spend ? <p>{state.spend}</p> : null}
1467
+ </div>
1468
+ </header>
1469
+
1470
+ <div className="desk-stage">
1471
+ {view !== "chat" ? (
1472
+ <DeskSidePanel
1473
+ view={view}
1474
+ bridge={bridge}
1475
+ theme={theme}
1476
+ skillQuery={skillQuery}
1477
+ onTheme={setTheme}
1478
+ onSaved={(next) => setState(next)}
1479
+ onNotice={showNotice}
1480
+ onSkillQuery={setSkillQuery}
1481
+ />
1482
+ ) : (
1483
+ <div className="desk-transcript" ref={transcriptRef}>
1484
+ {lines.length === 0 && !thoughtPending ? (
1485
+ <p className="desk-hint">Type a message, drop files, or / for commands</p>
1486
+ ) : (
1487
+ <>
1488
+ {transcriptBlocks.map((block, index) => {
1489
+ if (block.type === "thought") {
1490
+ const tools = thoughtTools(block.entries);
1491
+ return (
1492
+ <ThoughtFold
1493
+ key={tools[0]?.key ?? `thought-${index}`}
1494
+ entries={block.entries}
1495
+ live={turnRunning && block.live}
1496
+ />
1497
+ );
1498
+ }
1499
+ const line = block.line;
1500
+ return (
1501
+ <TranscriptLine
1502
+ key={line.key}
1503
+ line={line}
1504
+ bridge={bridge}
1505
+ editing={
1506
+ line.type === "user" && editingUser?.index === line.userTurnIndex
1507
+ ? editingUser.text
1508
+ : null
1509
+ }
1510
+ onStartEdit={
1511
+ line.type === "user"
1512
+ ? () => setEditingUser({ index: line.userTurnIndex, text: line.text })
1513
+ : undefined
1514
+ }
1515
+ onEditChange={(text) =>
1516
+ setEditingUser((current) => (current ? { ...current, text } : current))
1517
+ }
1518
+ onEditSave={() => void commitEdit()}
1519
+ onEditCancel={() => setEditingUser(null)}
1520
+ onOpenUrl={(url) => {
1521
+ void openExternal(url, bridge).catch((err: unknown) => {
1522
+ noticeError(err);
1523
+ });
1524
+ }}
1525
+ onOpenFile={(path, reveal) => {
1526
+ void openLocalFile(path, reveal, bridge).catch((err: unknown) => {
1527
+ noticeError(err);
1528
+ });
1529
+ }}
1530
+ />
1531
+ );
1532
+ })}
1533
+ {thoughtPending ? (
1534
+ <ThoughtFold key="thinking" entries={[]} live warmupSeed={warmupSeed} />
1535
+ ) : null}
1536
+ </>
1537
+ )}
1538
+ </div>
1539
+ )}
1540
+
1541
+ {view === "chat" && pending ? (
1542
+ <section className="desk-approve" aria-label="Approval needed">
1543
+ <p>Approval needed · {pending.toolName}</p>
1544
+ <pre className="cel-code">{approvalPreview}</pre>
1545
+ <div className="desk-approve-actions">
1546
+ <button
1547
+ type="button"
1548
+ className="cel-btn cel-btn--secondary cel-btn--compact"
1549
+ onClick={() => void decide("yes")}
1550
+ >
1551
+ Approve
1552
+ </button>
1553
+ <button
1554
+ type="button"
1555
+ className="cel-btn cel-btn--secondary cel-btn--compact"
1556
+ onClick={() => void decide("no")}
1557
+ >
1558
+ Deny
1559
+ </button>
1560
+ <button
1561
+ type="button"
1562
+ className="cel-btn cel-btn--tertiary cel-btn--compact"
1563
+ onClick={() => void decide("always")}
1564
+ >
1565
+ Always this session
1566
+ </button>
1567
+ </div>
1568
+ </section>
1569
+ ) : null}
1570
+
1571
+ {view === "chat" ? (
1572
+ <footer className="desk-composer">
1573
+ {fileDrag ? <p className="desk-composer__drop">Drop files to attach</p> : null}
1574
+ {queue.length > 0 ? (
1575
+ <ul className="desk-queue" aria-label="Queued messages">
1576
+ {queue.map((item) => (
1577
+ <li key={item.id} className="desk-queue-item">
1578
+ {editingQueuedId === item.id ? (
1579
+ <textarea
1580
+ className="cel-input desk-compose-input"
1581
+ rows={2}
1582
+ value={item.text}
1583
+ aria-label="Edit queued message"
1584
+ onChange={(event) =>
1585
+ setQueueSync(
1586
+ setQueuedText(queueRef.current, item.id, event.target.value),
1587
+ )
1588
+ }
1589
+ onKeyDown={(event) => {
1590
+ if (event.key === "Enter" && !event.shiftKey) {
1591
+ event.preventDefault();
1592
+ setQueueSync(updateQueued(queueRef.current, item.id, item.text));
1593
+ setEditingQueuedId(null);
1594
+ }
1595
+ if (event.key === "Escape") {
1596
+ event.preventDefault();
1597
+ setEditingQueuedId(null);
1598
+ }
1599
+ }}
1600
+ onBlur={() => {
1601
+ setQueueSync(updateQueued(queueRef.current, item.id, item.text));
1602
+ setEditingQueuedId(null);
1603
+ }}
1604
+ />
1605
+ ) : (
1606
+ <div className="desk-queue-copy">
1607
+ <AttachmentThumbs items={item.attachments ?? []} />
1608
+ {item.text ? (
1609
+ <button
1610
+ type="button"
1611
+ className="desk-queue-text"
1612
+ onClick={() => setEditingQueuedId(item.id)}
1613
+ >
1614
+ {item.text}
1615
+ </button>
1616
+ ) : null}
1617
+ </div>
1618
+ )}
1619
+ <button
1620
+ type="button"
1621
+ className="cel-btn cel-btn--quiet cel-btn--compact"
1622
+ aria-label="Remove from queue"
1623
+ onClick={() => {
1624
+ if (editingQueuedId === item.id) setEditingQueuedId(null);
1625
+ setQueueSync(removeQueued(queueRef.current, item.id));
1626
+ }}
1627
+ >
1628
+ <XIcon size={16} weight="regular" />
1629
+ </button>
1630
+ </li>
1631
+ ))}
1632
+ </ul>
1633
+ ) : null}
1634
+ {mediaModels.length > 0 && mediaOpen ? (
1635
+ <section className="desk-composer__meta">
1636
+ <h2 className="visually-hidden">Active media models</h2>
1637
+ <p>
1638
+ {mediaModels.map((item, index) => (
1639
+ <span key={item.kind} className="desk-composer__meta-item">
1640
+ {index > 0 ? (
1641
+ <span className="desk-composer__meta-sep" aria-hidden="true">
1642
+ ·
1643
+ </span>
1644
+ ) : null}
1645
+ <span className="desk-composer__meta-kind">{item.kind}</span>
1646
+ <span className="desk-composer__meta-name">{item.label}</span>
1647
+ </span>
1648
+ ))}
1649
+ </p>
1650
+ <button
1651
+ type="button"
1652
+ className="desk-composer__meta-toggle"
1653
+ aria-expanded
1654
+ aria-label="Hide media models"
1655
+ onClick={() => setMediaOpen(false)}
1656
+ >
1657
+ <XIcon size={14} weight="regular" />
1658
+ </button>
1659
+ </section>
1660
+ ) : null}
1661
+ <div className="desk-composer__row">
1662
+ <input
1663
+ ref={fileInputRef}
1664
+ className="visually-hidden"
1665
+ type="file"
1666
+ multiple
1667
+ onChange={(event) => {
1668
+ addFiles(Array.from(event.target.files ?? []));
1669
+ event.target.value = "";
1670
+ }}
1671
+ />
1672
+ {mediaModels.length > 0 && !mediaOpen ? (
1673
+ <button
1674
+ type="button"
1675
+ className="desk-composer__meta-toggle desk-composer__meta-toggle--peek"
1676
+ aria-expanded={false}
1677
+ aria-label="Show media models"
1678
+ onClick={() => setMediaOpen(true)}
1679
+ >
1680
+ <CaretDownIcon size={14} weight="bold" />
1681
+ </button>
1682
+ ) : null}
1683
+ <fieldset
1684
+ className={`desk-field desk-compose-box${attachments.length > 0 ? " has-files" : ""}`}
1685
+ onDragEnter={onFileDragEnter}
1686
+ onDragOver={onFileDragOver}
1687
+ onDragLeave={onFileDragLeave}
1688
+ onDrop={onFileDrop}
1689
+ >
1690
+ <legend className="visually-hidden">Message composer</legend>
1691
+ {slashOpen && slashItems.length > 0 ? (
1692
+ <div className="desk-slash cel-float">
1693
+ {slashItems.map((item, index) => (
1694
+ <button
1695
+ key={item.name}
1696
+ type="button"
1697
+ className={index === slashIndex ? "is-on" : undefined}
1698
+ onClick={() => setDraft(item.arg ? `/${item.name} ` : `/${item.name}`)}
1699
+ >
1700
+ <span>
1701
+ /{item.name}
1702
+ {item.slot ? ` ${item.slot}` : ""}
1703
+ </span>
1704
+ <em>· {item.hint}</em>
1705
+ </button>
1706
+ ))}
1707
+ </div>
1708
+ ) : null}
1709
+ {picker ? (
1710
+ <div className="desk-float cel-float" role="listbox" aria-label={picker.title}>
1711
+ <p>{picker.title}</p>
1712
+ <ul ref={pickerListRef}>
1713
+ {picker.items.map((item, index) => (
1714
+ <li key={item.id}>
1715
+ <button
1716
+ type="button"
1717
+ role="option"
1718
+ aria-selected={index === picker.index}
1719
+ data-picker-index={index}
1720
+ className={index === picker.index ? "is-on" : undefined}
1721
+ onClick={() => void choosePicker(item)}
1722
+ >
1723
+ <span>{item.label}</span>
1724
+ {pickerItemHint(
1725
+ Boolean(state && item.id === pickerSelectedId(picker.kind, state)),
1726
+ item.hint,
1727
+ )}
1728
+ </button>
1729
+ </li>
1730
+ ))}
1731
+ </ul>
1732
+ <button
1733
+ type="button"
1734
+ className="cel-btn cel-btn--quiet cel-btn--compact"
1735
+ onClick={() => cancelPicker()}
1736
+ >
1737
+ Cancel
1738
+ </button>
1739
+ </div>
1740
+ ) : null}
1741
+ <AttachmentThumbs items={attachments} onRemove={removeAttachment} />
1742
+ <textarea
1743
+ ref={inputRef}
1744
+ className="cel-input desk-compose-input"
1745
+ rows={1}
1746
+ aria-label="Message"
1747
+ value={draft}
1748
+ placeholder={composePlaceholder(listening, status)}
1749
+ disabled={listening}
1750
+ onChange={(event) => setDraft(event.target.value)}
1751
+ onKeyDown={onKeyDown}
1752
+ />
1753
+ <div className="desk-compose-bar">
1754
+ <button
1755
+ type="button"
1756
+ className="desk-compose-icon"
1757
+ aria-label="Add files"
1758
+ onClick={() => fileInputRef.current?.click()}
1759
+ >
1760
+ <PlusIcon size={16} weight="regular" />
1761
+ </button>
1762
+ <div className="desk-compose-bar__end">
1763
+ <button
1764
+ type="button"
1765
+ className="desk-compose-model"
1766
+ aria-label="Choose model"
1767
+ disabled={status !== "idle" && status !== "picker"}
1768
+ onClick={() => void openComposerPicker("model")}
1769
+ >
1770
+ <span>{state.modelTarget ?? state.modelLabel}</span>
1771
+ <CaretDownIcon size={12} weight="bold" />
1772
+ </button>
1773
+ <button
1774
+ type="button"
1775
+ className="desk-compose-mode"
1776
+ aria-label="Choose mode"
1777
+ disabled={status !== "idle" && status !== "picker"}
1778
+ onClick={() => void openComposerPicker("mode")}
1779
+ >
1780
+ <span className="desk-compose-mode__dot" aria-hidden="true" />
1781
+ {titleCase(state.mode)}
1782
+ </button>
1783
+ <ComposeMicControl
1784
+ status={status}
1785
+ listening={listening}
1786
+ onStop={() => void stop()}
1787
+ onStopDictation={() => stopDictation()}
1788
+ onStartDictation={() => void startDictation()}
1789
+ />
1790
+ <button
1791
+ type="button"
1792
+ className={`desk-compose-send${draft.trim() || attachments.length > 0 ? " is-on" : ""}`}
1793
+ disabled={listening || (!draft.trim() && attachments.length === 0)}
1794
+ onClick={() => void submit()}
1795
+ aria-label={
1796
+ status === "running" || status === "approval" ? "Queue" : "Send"
1797
+ }
1798
+ >
1799
+ <PaperPlaneTiltIcon size={16} weight="regular" />
1800
+ </button>
1801
+ </div>
1802
+ </div>
1803
+ </fieldset>
1804
+ </div>
1805
+ </footer>
1806
+ ) : null}
1807
+ </div>
1808
+ {notice ? (
1809
+ <div className="desk-notice-host">
1810
+ <FloatNotice key={notice.id} text={notice.text} onDismiss={dismissNotice} />
1811
+ </div>
1812
+ ) : null}
1813
+ </section>
1814
+ {sessionMenu ? (
1815
+ <div
1816
+ ref={sessionMenuRef}
1817
+ className="desk-menu cel-float"
1818
+ role="menu"
1819
+ aria-label="Chat"
1820
+ style={{ left: sessionMenu.x, top: sessionMenu.y }}
1821
+ >
1822
+ <button
1823
+ type="button"
1824
+ role="menuitem"
1825
+ onClick={() => {
1826
+ setRenameDraft(sessionMenu.label);
1827
+ setRenamingId(sessionMenu.id);
1828
+ setSessionMenu(null);
1829
+ }}
1830
+ >
1831
+ <PencilSimpleIcon size={16} weight="regular" />
1832
+ Rename
1833
+ </button>
1834
+ <button
1835
+ type="button"
1836
+ role="menuitem"
1837
+ className="is-danger"
1838
+ onClick={() => void removeChat(sessionMenu.id)}
1839
+ >
1840
+ <TrashIcon size={16} weight="regular" />
1841
+ Delete
1842
+ </button>
1843
+ </div>
1844
+ ) : null}
1845
+ </div>
1846
+ );
1847
+ }
1848
+
1849
+ function IntegrationActions(
1850
+ props: Readonly<{
1851
+ pending: boolean;
1852
+ connected: boolean;
1853
+ onConnect: () => void;
1854
+ onDisconnect: () => void;
1855
+ }>,
1856
+ ): React.ReactElement {
1857
+ if (props.pending) {
1858
+ return (
1859
+ <span className="desk-integration-ok">
1860
+ <span className="cel-chip__spin" aria-hidden="true" />
1861
+ {props.connected ? "Disconnecting" : "Connecting"}
1862
+ </span>
1863
+ );
1864
+ }
1865
+ if (props.connected) {
1866
+ return (
1867
+ <>
1868
+ <span className="desk-integration-ok">
1869
+ <CheckIcon size={16} weight="regular" aria-hidden="true" />
1870
+ Connected
1871
+ </span>
1872
+ <button
1873
+ type="button"
1874
+ className="cel-btn cel-btn--quiet cel-btn--compact"
1875
+ onClick={props.onDisconnect}
1876
+ >
1877
+ Disconnect
1878
+ </button>
1879
+ </>
1880
+ );
1881
+ }
1882
+ return (
1883
+ <button
1884
+ type="button"
1885
+ className="cel-btn cel-btn--secondary cel-btn--compact"
1886
+ onClick={props.onConnect}
1887
+ >
1888
+ Connect
1889
+ </button>
1890
+ );
1891
+ }
1892
+
1893
+ function IntegrationMark(props: Readonly<{ item: PublicIntegration }>): React.ReactElement {
1894
+ const [failed, setFailed] = useState(false);
1895
+ if (failed) {
1896
+ return <span className="desk-integration-glyph desk-integration-mark">{props.item.glyph}</span>;
1897
+ }
1898
+ return (
1899
+ <span className="desk-integration-mark">
1900
+ <img src={props.item.logoUrl} alt="" width={20} height={20} onError={() => setFailed(true)} />
1901
+ </span>
1902
+ );
1903
+ }
1904
+
1905
+ function IntegrationRow(
1906
+ props: Readonly<{
1907
+ item: PublicIntegration;
1908
+ pending: boolean;
1909
+ onConnect: () => void;
1910
+ onDisconnect: () => void;
1911
+ }>,
1912
+ ): React.ReactElement {
1913
+ const { item } = props;
1914
+ return (
1915
+ <li>
1916
+ <IntegrationMark item={item} />
1917
+ <div>
1918
+ <p>{item.label}</p>
1919
+ <em>{item.description}</em>
1920
+ </div>
1921
+ <div className="desk-integration-actions">
1922
+ <IntegrationActions
1923
+ pending={props.pending}
1924
+ connected={item.connected}
1925
+ onConnect={props.onConnect}
1926
+ onDisconnect={props.onDisconnect}
1927
+ />
1928
+ </div>
1929
+ </li>
1930
+ );
1931
+ }
1932
+
1933
+ function IntegrationsPanel(
1934
+ props: Readonly<{
1935
+ bridge: BridgeClient;
1936
+ onNotice: (text: string) => void;
1937
+ }>,
1938
+ ): React.ReactElement {
1939
+ const [items, setItems] = useState<PublicIntegration[] | null>(null);
1940
+ const [query, setQuery] = useState("");
1941
+ const [loadFailed, setLoadFailed] = useState(false);
1942
+ const [pendingId, setPendingId] = useState<string | null>(null);
1943
+
1944
+ useEffect(() => {
1945
+ let alive = true;
1946
+ void getIntegrations(props.bridge)
1947
+ .then((result) => {
1948
+ if (alive) setItems(result.items);
1949
+ })
1950
+ .catch((err: unknown) => {
1951
+ if (!alive) return;
1952
+ setLoadFailed(true);
1953
+ props.onNotice(errorMessage(err));
1954
+ });
1955
+ return () => {
1956
+ alive = false;
1957
+ };
1958
+ }, [props.bridge, props.onNotice]);
1959
+
1960
+ const visible = (items ?? []).filter((item) => integrationMatches(item.label, query));
1961
+ const ready = visible.filter(
1962
+ (item) => item.auth !== "google" && item.auth !== "microsoft" && item.auth !== "desktop",
1963
+ );
1964
+ const desktop = visible.filter((item) => item.auth === "desktop");
1965
+ const setup = visible.filter((item) => item.auth === "google" || item.auth === "microsoft");
1966
+
1967
+ const run = async (id: string, action: "connect" | "disconnect"): Promise<void> => {
1968
+ setPendingId(id);
1969
+ try {
1970
+ const result =
1971
+ action === "connect"
1972
+ ? await connectIntegration(props.bridge, id)
1973
+ : await disconnectIntegration(props.bridge, id);
1974
+ setItems(result.items);
1975
+ } catch (err) {
1976
+ props.onNotice(errorMessage(err));
1977
+ } finally {
1978
+ setPendingId(null);
1979
+ }
1980
+ };
1981
+
1982
+ if (!items && !loadFailed) {
1983
+ return (
1984
+ <div className="desk-integrations">
1985
+ <p>Loading integrations</p>
1986
+ </div>
1987
+ );
1988
+ }
1989
+
1990
+ if (!items && loadFailed) {
1991
+ return (
1992
+ <div className="desk-integrations">
1993
+ <p className="desk-side-empty">Integrations could not be loaded</p>
1994
+ </div>
1995
+ );
1996
+ }
1997
+
1998
+ return (
1999
+ <div className="desk-integrations">
2000
+ <p className="desk-integrations-lead">
2001
+ Hosted MCP servers the agent can call. App connectors for published sites stay in the
2002
+ builder.
2003
+ </p>
2004
+ <label className="desk-field">
2005
+ <span className="visually-hidden">Search integrations</span>
2006
+ <input
2007
+ className="cel-input"
2008
+ value={query}
2009
+ placeholder="Search"
2010
+ onChange={(event) => setQuery(event.target.value)}
2011
+ />
2012
+ </label>
2013
+ {visible.length === 0 ? (
2014
+ <p className="desk-side-empty">No integrations match</p>
2015
+ ) : (
2016
+ <>
2017
+ {ready.length > 0 ? (
2018
+ <ul className="desk-integration-list">
2019
+ {ready.map((item) => (
2020
+ <IntegrationRow
2021
+ key={item.id}
2022
+ item={item}
2023
+ pending={pendingId === item.id}
2024
+ onConnect={() => void run(item.id, "connect")}
2025
+ onDisconnect={() => void run(item.id, "disconnect")}
2026
+ />
2027
+ ))}
2028
+ </ul>
2029
+ ) : null}
2030
+ {desktop.length > 0 ? (
2031
+ <>
2032
+ <div className="desk-integration-split">
2033
+ <p>Figma desktop required</p>
2034
+ <em>
2035
+ Remote Figma MCP only allows approved clients. Enable the Dev Mode MCP server in
2036
+ Figma desktop, then Connect.
2037
+ </em>
2038
+ </div>
2039
+ <ul className="desk-integration-list">
2040
+ {desktop.map((item) => (
2041
+ <IntegrationRow
2042
+ key={item.id}
2043
+ item={item}
2044
+ pending={pendingId === item.id}
2045
+ onConnect={() => void run(item.id, "connect")}
2046
+ onDisconnect={() => void run(item.id, "disconnect")}
2047
+ />
2048
+ ))}
2049
+ </ul>
2050
+ </>
2051
+ ) : null}
2052
+ {setup.length > 0 ? (
2053
+ <>
2054
+ <div className="desk-integration-split">
2055
+ <p>OAuth client required</p>
2056
+ <em>
2057
+ Google Workspace and Microsoft 365 have no dynamic client registration. Add a
2058
+ client id in Settings, then Connect.
2059
+ </em>
2060
+ </div>
2061
+ <ul className="desk-integration-list">
2062
+ {setup.map((item) => (
2063
+ <IntegrationRow
2064
+ key={item.id}
2065
+ item={item}
2066
+ pending={pendingId === item.id}
2067
+ onConnect={() => void run(item.id, "connect")}
2068
+ onDisconnect={() => void run(item.id, "disconnect")}
2069
+ />
2070
+ ))}
2071
+ </ul>
2072
+ </>
2073
+ ) : null}
2074
+ </>
2075
+ )}
2076
+ </div>
2077
+ );
2078
+ }
2079
+
2080
+ function SettingsPanel(
2081
+ props: Readonly<{
2082
+ bridge: BridgeClient;
2083
+ theme: ThemeChoice;
2084
+ onTheme: (theme: ThemeChoice) => void;
2085
+ onSaved: (state: DesktopState) => void;
2086
+ onNotice: (text: string) => void;
2087
+ }>,
2088
+ ): React.ReactElement {
2089
+ const [settings, setSettings] = useState<DesktopSettings | null>(null);
2090
+ const [apiKey, setApiKey] = useState("");
2091
+ const [googleClientId, setGoogleClientId] = useState("");
2092
+ const [microsoftClientId, setMicrosoftClientId] = useState("");
2093
+ const [microsoftClientSecret, setMicrosoftClientSecret] = useState("");
2094
+ const [saved, setSaved] = useState(false);
2095
+
2096
+ useEffect(() => {
2097
+ void getSettings(props.bridge).then(setSettings);
2098
+ }, [props.bridge]);
2099
+
2100
+ if (!settings) {
2101
+ return (
2102
+ <div className="desk-settings">
2103
+ <p>Loading settings</p>
2104
+ </div>
2105
+ );
2106
+ }
2107
+
2108
+ return (
2109
+ <form
2110
+ className="desk-settings"
2111
+ onSubmit={(event) => {
2112
+ event.preventDefault();
2113
+ setSaved(false);
2114
+ void (async () => {
2115
+ try {
2116
+ const result = await saveSettings(props.bridge, {
2117
+ mode: settings.mode,
2118
+ modelId: settings.modelId,
2119
+ ...(apiKey.trim() ? { apiKey: apiKey.trim() } : {}),
2120
+ ...(googleClientId.trim() ? { googleClientId: googleClientId.trim() } : {}),
2121
+ ...(microsoftClientId.trim() ? { microsoftClientId: microsoftClientId.trim() } : {}),
2122
+ ...(microsoftClientSecret.trim()
2123
+ ? { microsoftClientSecret: microsoftClientSecret.trim() }
2124
+ : {}),
2125
+ });
2126
+ setSettings({
2127
+ ...settings,
2128
+ hasApiKey: result.hasApiKey,
2129
+ apiKeyHint: result.apiKeyHint,
2130
+ hasGoogleOAuth: result.hasGoogleOAuth,
2131
+ googleOAuthHint: result.googleOAuthHint,
2132
+ hasMicrosoftOAuth: result.hasMicrosoftOAuth,
2133
+ microsoftOAuthHint: result.microsoftOAuthHint,
2134
+ });
2135
+ setApiKey("");
2136
+ setGoogleClientId("");
2137
+ setMicrosoftClientId("");
2138
+ setMicrosoftClientSecret("");
2139
+ props.onSaved(result.state);
2140
+ setSaved(true);
2141
+ } catch (err) {
2142
+ props.onNotice(errorMessage(err));
2143
+ }
2144
+ })();
2145
+ }}
2146
+ >
2147
+ <label>
2148
+ <span>OpenRouter API key</span>
2149
+ <input
2150
+ className="cel-input"
2151
+ type="password"
2152
+ autoComplete="off"
2153
+ spellCheck={false}
2154
+ value={apiKey}
2155
+ placeholder={settings.hasApiKey ? settings.apiKeyHint : "sk-or-…"}
2156
+ onChange={(event) => setApiKey(event.target.value)}
2157
+ />
2158
+ <em>
2159
+ {settings.hasApiKey
2160
+ ? `Key on this machine · ${settings.apiKeyHint}`
2161
+ : "Stored in ~/.harness on this machine"}
2162
+ </em>
2163
+ </label>
2164
+ <label>
2165
+ <span>Google OAuth client id</span>
2166
+ <input
2167
+ className="cel-input"
2168
+ type="text"
2169
+ autoComplete="off"
2170
+ spellCheck={false}
2171
+ value={googleClientId}
2172
+ placeholder={settings.hasGoogleOAuth ? settings.googleOAuthHint : ""}
2173
+ onChange={(event) => setGoogleClientId(event.target.value)}
2174
+ />
2175
+ <em>
2176
+ Google Workspace MCP has no dynamic client registration. Register a Desktop app in Google
2177
+ Cloud. Loopback redirect and PKCE. No client secret.
2178
+ </em>
2179
+ </label>
2180
+ <label>
2181
+ <span>Microsoft Entra client id</span>
2182
+ <input
2183
+ className="cel-input"
2184
+ type="text"
2185
+ autoComplete="off"
2186
+ spellCheck={false}
2187
+ value={microsoftClientId}
2188
+ placeholder={settings.hasMicrosoftOAuth ? settings.microsoftOAuthHint : ""}
2189
+ onChange={(event) => setMicrosoftClientId(event.target.value)}
2190
+ />
2191
+ </label>
2192
+ <label>
2193
+ <span>Microsoft Entra client secret</span>
2194
+ <input
2195
+ className="cel-input"
2196
+ type="password"
2197
+ autoComplete="off"
2198
+ spellCheck={false}
2199
+ value={microsoftClientSecret}
2200
+ placeholder={settings.hasMicrosoftOAuth ? "••••" : ""}
2201
+ onChange={(event) => setMicrosoftClientSecret(event.target.value)}
2202
+ />
2203
+ <em>
2204
+ Required for Microsoft 365 directory MCP. Register a public client in Entra. Dynamic
2205
+ client registration is not supported. This server is users and groups, not Excel or
2206
+ Outlook.
2207
+ </em>
2208
+ </label>
2209
+ <label>
2210
+ <span>Theme</span>
2211
+ <span className="desk-select-wrap">
2212
+ <select
2213
+ className="cel-input desk-select"
2214
+ value={props.theme}
2215
+ onChange={(event) => props.onTheme(event.target.value as ThemeChoice)}
2216
+ >
2217
+ <option value="system">System</option>
2218
+ <option value="light">Light</option>
2219
+ <option value="dark">Dark</option>
2220
+ </select>
2221
+ </span>
2222
+ <em>System follows the OS</em>
2223
+ </label>
2224
+ <label>
2225
+ <span>Mode</span>
2226
+ <span className="desk-select-wrap">
2227
+ <select
2228
+ className="cel-input desk-select"
2229
+ value={settings.mode}
2230
+ onChange={(event) => setSettings({ ...settings, mode: event.target.value })}
2231
+ >
2232
+ <option value="ask">Ask</option>
2233
+ <option value="plan">Plan</option>
2234
+ <option value="agent">Agent</option>
2235
+ </select>
2236
+ </span>
2237
+ </label>
2238
+ {saved ? <p className="desk-saved">Saved</p> : null}
2239
+ <button type="submit" className="cel-btn cel-btn--secondary cel-btn--compact">
2240
+ Save
2241
+ </button>
2242
+ </form>
2243
+ );
2244
+ }
2245
+
2246
+ function ThoughtFold(
2247
+ props: Readonly<{
2248
+ entries: FoldEntry[];
2249
+ live: boolean;
2250
+ warmupSeed?: number;
2251
+ }>,
2252
+ ): React.ReactElement {
2253
+ const { entries, live, warmupSeed } = props;
2254
+ const tools = thoughtTools(entries);
2255
+ const summary = thoughtSummary(tools, live, {
2256
+ warmup: entries.length === 0,
2257
+ seed: warmupSeed ?? 0,
2258
+ });
2259
+ const hasBody = entries.some((entry) =>
2260
+ entry.type === "note" ? entry.text.trim().length > 0 : true,
2261
+ );
2262
+ if (!hasBody) {
2263
+ return (
2264
+ <p className="desk-thought desk-thought--plain">
2265
+ <span className="desk-thought__headline">{summary.headline}</span>
2266
+ </p>
2267
+ );
2268
+ }
2269
+ return (
2270
+ <details className="desk-thought">
2271
+ <summary>
2272
+ <span className="desk-thought__copy">
2273
+ <span className="desk-thought__headline">{summary.headline}</span>
2274
+ {live && summary.activity ? (
2275
+ <span className="desk-thought__activity">{summary.activity}</span>
2276
+ ) : null}
2277
+ </span>
2278
+ </summary>
2279
+ <div className="desk-thought__body">
2280
+ {entries.map((entry) => {
2281
+ if (entry.type === "note") {
2282
+ const text = entry.text.trim();
2283
+ if (!text) return null;
2284
+ return (
2285
+ <p key={`note-${text}`} className="desk-thought__reasoning">
2286
+ {text}
2287
+ </p>
2288
+ );
2289
+ }
2290
+ return <ToolEventRow key={entry.tool.key} line={entry.tool} />;
2291
+ })}
2292
+ </div>
2293
+ </details>
2294
+ );
2295
+ }
2296
+
2297
+ function ToolEventRow(props: Readonly<{ line: ToolLine }>): React.ReactElement {
2298
+ const { line } = props;
2299
+ const count = eventCountSuffix(line.count);
2300
+ return (
2301
+ <article className={`desk-line desk-line--event is-${line.status}`}>
2302
+ <p>
2303
+ {line.status === "running" ? (
2304
+ <span className="desk-event__spin" aria-hidden="true" />
2305
+ ) : (
2306
+ <GearIcon size={16} weight="regular" aria-hidden="true" />
2307
+ )}
2308
+ <span>
2309
+ {line.label}
2310
+ {count}
2311
+ </span>
2312
+ </p>
2313
+ {line.status === "fail" && line.error ? (
2314
+ <p className="desk-event__err">{line.error}</p>
2315
+ ) : null}
2316
+ </article>
2317
+ );
2318
+ }
2319
+
2320
+ function UserTranscriptLine(
2321
+ props: Readonly<{
2322
+ line: Extract<StreamLine, { type: "user" }>;
2323
+ editing?: string | null;
2324
+ onStartEdit?: () => void;
2325
+ onEditChange?: (text: string) => void;
2326
+ onEditSave?: () => void;
2327
+ onEditCancel?: () => void;
2328
+ }>,
2329
+ ): React.ReactElement {
2330
+ const editing = props.editing != null;
2331
+ return (
2332
+ <article className={`desk-line desk-line--user${editing ? " is-editing" : ""}`}>
2333
+ <p className="desk-line__who">
2334
+ {!editing && props.onStartEdit ? (
2335
+ <button
2336
+ type="button"
2337
+ className="cel-btn cel-btn--quiet cel-btn--compact desk-line__edit-btn"
2338
+ onClick={props.onStartEdit}
2339
+ >
2340
+ <PencilSimpleIcon size={16} weight="regular" />
2341
+ Edit
2342
+ </button>
2343
+ ) : null}
2344
+ <span>You</span>
2345
+ </p>
2346
+ <div className="desk-line__body">
2347
+ {editing ? (
2348
+ <>
2349
+ <textarea
2350
+ className="cel-input desk-compose-input"
2351
+ rows={3}
2352
+ value={props.editing ?? ""}
2353
+ aria-label="Edit message"
2354
+ onChange={(event) => props.onEditChange?.(event.target.value)}
2355
+ onKeyDown={(event) => {
2356
+ if (event.key === "Enter" && !event.shiftKey) {
2357
+ event.preventDefault();
2358
+ props.onEditSave?.();
2359
+ }
2360
+ if (event.key === "Escape") {
2361
+ event.preventDefault();
2362
+ props.onEditCancel?.();
2363
+ }
2364
+ }}
2365
+ />
2366
+ <div className="desk-line__edit-actions">
2367
+ <button
2368
+ type="button"
2369
+ className="cel-btn cel-btn--secondary cel-btn--compact"
2370
+ onClick={props.onEditSave}
2371
+ >
2372
+ Save
2373
+ </button>
2374
+ <button
2375
+ type="button"
2376
+ className="cel-btn cel-btn--quiet cel-btn--compact"
2377
+ onClick={props.onEditCancel}
2378
+ >
2379
+ Cancel
2380
+ </button>
2381
+ </div>
2382
+ </>
2383
+ ) : (
2384
+ <>
2385
+ <AttachmentThumbs items={props.line.attachments ?? []} variant="chat" />
2386
+ {props.line.text ? <p>{props.line.text}</p> : null}
2387
+ </>
2388
+ )}
2389
+ </div>
2390
+ </article>
2391
+ );
2392
+ }
2393
+
2394
+ function TranscriptLine(
2395
+ props: Readonly<{
2396
+ line: StreamLine;
2397
+ bridge: BridgeClient | null;
2398
+ editing?: string | null;
2399
+ onStartEdit?: () => void;
2400
+ onEditChange?: (text: string) => void;
2401
+ onEditSave?: () => void;
2402
+ onEditCancel?: () => void;
2403
+ onOpenUrl?: (url: string) => void;
2404
+ onOpenFile?: (path: string, reveal: boolean) => void;
2405
+ }>,
2406
+ ): React.ReactElement {
2407
+ const { line, bridge, onOpenUrl, onOpenFile } = props;
2408
+ if (line.type === "user") {
2409
+ return (
2410
+ <UserTranscriptLine
2411
+ line={line}
2412
+ editing={props.editing}
2413
+ onStartEdit={props.onStartEdit}
2414
+ onEditChange={props.onEditChange}
2415
+ onEditSave={props.onEditSave}
2416
+ onEditCancel={props.onEditCancel}
2417
+ />
2418
+ );
2419
+ }
2420
+ if (line.type === "assistant") {
2421
+ return (
2422
+ <article className="desk-line desk-line--assistant">
2423
+ <p className="desk-line__who">Agent</p>
2424
+ <div className="desk-line__body">
2425
+ <RichBody
2426
+ text={line.text}
2427
+ bridge={bridge}
2428
+ onOpenUrl={onOpenUrl}
2429
+ onOpenFile={onOpenFile}
2430
+ />
2431
+ </div>
2432
+ </article>
2433
+ );
2434
+ }
2435
+ if (line.type === "tool") {
2436
+ const count = eventCountSuffix(line.count);
2437
+ return (
2438
+ <article className={`desk-line desk-line--event is-${line.status}`}>
2439
+ <p>
2440
+ {line.status === "running" ? (
2441
+ <span className="desk-event__spin" aria-hidden="true" />
2442
+ ) : (
2443
+ <GearIcon size={16} weight="regular" aria-hidden="true" />
2444
+ )}
2445
+ <span>
2446
+ {line.label}
2447
+ {count}
2448
+ </span>
2449
+ </p>
2450
+ {line.status === "fail" && line.error ? (
2451
+ <p className="desk-event__err">{line.error}</p>
2452
+ ) : null}
2453
+ </article>
2454
+ );
2455
+ }
2456
+ if (line.type === "error") {
2457
+ return (
2458
+ <article className="desk-line desk-line--error">
2459
+ <p>{line.text}</p>
2460
+ </article>
2461
+ );
2462
+ }
2463
+ if (line.type === "media") {
2464
+ return (
2465
+ <article className="desk-line desk-line--assistant">
2466
+ <p className="desk-line__who">Agent</p>
2467
+ <div className="desk-line__body">
2468
+ {line.kind === "video" ? (
2469
+ <video className="desk-preview desk-preview--img" controls src={line.src}>
2470
+ <track kind="captions" srcLang="en" label="Captions" src={SILENT_CAPTIONS} />
2471
+ </video>
2472
+ ) : (
2473
+ <img className="desk-preview desk-preview--img" src={line.src} alt={line.caption} />
2474
+ )}
2475
+ <p className="desk-line__caption">{line.caption}</p>
2476
+ </div>
2477
+ </article>
2478
+ );
2479
+ }
2480
+ return (
2481
+ <article className="desk-line desk-line--system">
2482
+ <p>{line.text}</p>
2483
+ </article>
2484
+ );
2485
+ }
2486
+
2487
+ function RichBody(
2488
+ props: Readonly<{
2489
+ text: string;
2490
+ bridge: BridgeClient | null;
2491
+ onOpenUrl?: (url: string) => void;
2492
+ onOpenFile?: (path: string, reveal: boolean) => void;
2493
+ }>,
2494
+ ): React.ReactElement {
2495
+ const parts = splitRichText(props.text);
2496
+ return (
2497
+ <div className="desk-rich">
2498
+ {parts.map((part, index) => {
2499
+ if (part.type === "text") {
2500
+ const next = parts.at(index + 1);
2501
+ if (next?.type === "image" && /^\s*Preview:?\s*$/i.test(part.text)) return null;
2502
+ return <span key={richPartKey(part)}>{part.text}</span>;
2503
+ }
2504
+ if (part.type === "file") {
2505
+ return (
2506
+ <FileLink
2507
+ key={richPartKey(part)}
2508
+ path={part.path}
2509
+ label={part.label}
2510
+ onOpenFile={props.onOpenFile}
2511
+ />
2512
+ );
2513
+ }
2514
+ if (part.type === "image") {
2515
+ const viewHref = [...parts]
2516
+ .reverse()
2517
+ .find(
2518
+ (item): item is Extract<typeof item, { type: "link" }> =>
2519
+ item.type === "link" && item.href.includes("canva.com/d/"),
2520
+ )?.href;
2521
+ return (
2522
+ <PreviewFrame
2523
+ key={richPartKey(part)}
2524
+ src={part.src}
2525
+ title={part.alt}
2526
+ viewHref={viewHref}
2527
+ bridge={props.bridge}
2528
+ onOpenUrl={props.onOpenUrl}
2529
+ />
2530
+ );
2531
+ }
2532
+ return (
2533
+ <ExternalLink
2534
+ key={richPartKey(part)}
2535
+ href={part.href}
2536
+ label={part.label}
2537
+ onOpenUrl={props.onOpenUrl}
2538
+ />
2539
+ );
2540
+ })}
2541
+ </div>
2542
+ );
2543
+ }
2544
+
2545
+ function FileLink(
2546
+ props: Readonly<{
2547
+ path: string;
2548
+ label: string;
2549
+ onOpenFile?: (path: string, reveal: boolean) => void;
2550
+ }>,
2551
+ ): React.ReactElement {
2552
+ return (
2553
+ <span className="desk-file">
2554
+ <button
2555
+ type="button"
2556
+ className="desk-link"
2557
+ onClick={() => props.onOpenFile?.(props.path, false)}
2558
+ >
2559
+ {props.label}
2560
+ </button>
2561
+ <button
2562
+ type="button"
2563
+ className="desk-link desk-link--icon"
2564
+ aria-label={`Show ${props.label} in folder`}
2565
+ onClick={() => props.onOpenFile?.(props.path, true)}
2566
+ >
2567
+ <FolderSimpleIcon size={16} weight="regular" aria-hidden="true" />
2568
+ </button>
2569
+ </span>
2570
+ );
2571
+ }
2572
+
2573
+ function ExternalLink(
2574
+ props: Readonly<{
2575
+ href: string;
2576
+ label: string;
2577
+ onOpenUrl?: (url: string) => void;
2578
+ }>,
2579
+ ): React.ReactElement {
2580
+ return (
2581
+ <button type="button" className="desk-link" onClick={() => props.onOpenUrl?.(props.href)}>
2582
+ <span>{props.label}</span>
2583
+ <ArrowUpRightIcon size={16} weight="regular" aria-hidden="true" />
2584
+ </button>
2585
+ );
2586
+ }
2587
+
2588
+ function PreviewFrame(
2589
+ props: Readonly<{
2590
+ src: string;
2591
+ title: string;
2592
+ viewHref?: string;
2593
+ bridge: BridgeClient | null;
2594
+ onOpenUrl?: (url: string) => void;
2595
+ }>,
2596
+ ): React.ReactElement {
2597
+ const [blobSrc, setBlobSrc] = useState<string | null>(null);
2598
+ const [mode, setMode] = useState<"load" | "frame" | "expired">("load");
2599
+ const openHref = props.viewHref ?? canvaViewUrl(props.src) ?? props.src;
2600
+
2601
+ useEffect(() => {
2602
+ let objectUrl: string | undefined;
2603
+ let cancelled = false;
2604
+ setMode("load");
2605
+ setBlobSrc(null);
2606
+ void (async () => {
2607
+ try {
2608
+ if (!props.bridge) {
2609
+ if (!cancelled) setMode("expired");
2610
+ return;
2611
+ }
2612
+ const blob = await embedPreview(props.bridge, props.src);
2613
+ if (cancelled) return;
2614
+ objectUrl = URL.createObjectURL(blob);
2615
+ if (cancelled) {
2616
+ URL.revokeObjectURL(objectUrl);
2617
+ return;
2618
+ }
2619
+ setBlobSrc(objectUrl);
2620
+ setMode("frame");
2621
+ } catch {
2622
+ if (!cancelled) setMode("expired");
2623
+ }
2624
+ })();
2625
+ return () => {
2626
+ cancelled = true;
2627
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
2628
+ };
2629
+ }, [props.bridge, props.src]);
2630
+
2631
+ if (mode === "expired") {
2632
+ return (
2633
+ <div className="desk-preview desk-preview--empty">
2634
+ <p>Preview expired</p>
2635
+ <p>The thumbnail link is no longer valid.</p>
2636
+ <button
2637
+ type="button"
2638
+ className="cel-btn cel-btn--tertiary cel-btn--compact"
2639
+ onClick={() => props.onOpenUrl?.(openHref)}
2640
+ >
2641
+ Open in Canva
2642
+ </button>
2643
+ </div>
2644
+ );
2645
+ }
2646
+ if (mode === "frame" && blobSrc) {
2647
+ return <img className="desk-preview desk-preview--img" src={blobSrc} alt={props.title} />;
2648
+ }
2649
+ return (
2650
+ <div className="desk-preview desk-preview--empty" aria-busy="true">
2651
+ <span className="cel-chip cel-chip--run">
2652
+ <span className="cel-chip__spin" aria-hidden="true" />
2653
+ {"Preview"}
2654
+ </span>
2655
+ </div>
2656
+ );
2657
+ }