@useavalon/caelence-agent 0.2.3-canary.0 → 0.2.3-canary.2

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