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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +8 -5
  2. package/desktop/README.md +26 -0
  3. package/desktop/bun.lock +321 -0
  4. package/desktop/index.html +20 -0
  5. package/desktop/package.json +28 -0
  6. package/desktop/scripts/make-icons.ts +105 -0
  7. package/desktop/scripts/run-tauri.ts +40 -0
  8. package/desktop/src/App.tsx +2657 -0
  9. package/desktop/src/ComposerAttach.tsx +111 -0
  10. package/desktop/src/FloatNotice.test.ts +23 -0
  11. package/desktop/src/FloatNotice.tsx +30 -0
  12. package/desktop/src/LogoMark.tsx +37 -0
  13. package/desktop/src/SkillsPanel.tsx +409 -0
  14. package/desktop/src/api.ts +503 -0
  15. package/desktop/src/app.css +1749 -0
  16. package/desktop/src/composer-files.test.ts +46 -0
  17. package/desktop/src/composer-files.ts +135 -0
  18. package/desktop/src/dictation.test.ts +22 -0
  19. package/desktop/src/dictation.ts +59 -0
  20. package/desktop/src/integration-search.test.ts +13 -0
  21. package/desktop/src/integration-search.ts +8 -0
  22. package/desktop/src/main.tsx +43 -0
  23. package/desktop/src/picker-nav.test.ts +27 -0
  24. package/desktop/src/picker-nav.ts +26 -0
  25. package/desktop/src/queue.test.ts +37 -0
  26. package/desktop/src/queue.ts +40 -0
  27. package/desktop/src/rich-text.test.ts +85 -0
  28. package/desktop/src/rich-text.ts +193 -0
  29. package/desktop/src/session-menu.test.ts +19 -0
  30. package/desktop/src/session-menu.ts +12 -0
  31. package/desktop/src/skill-search.test.ts +37 -0
  32. package/desktop/src/skill-search.ts +25 -0
  33. package/desktop/src/stream.test.ts +93 -0
  34. package/desktop/src/stream.ts +197 -0
  35. package/desktop/src/styles/fonts/chivo-mono-latin-ext-wght-normal.woff2 +0 -0
  36. package/desktop/src/styles/fonts/chivo-mono-latin-wght-normal.ttf +0 -0
  37. package/desktop/src/styles/fonts/chivo-mono-latin-wght-normal.woff2 +0 -0
  38. package/desktop/src/styles/fonts/instrument-sans-latin-ext-wght-normal.woff2 +0 -0
  39. package/desktop/src/styles/fonts/instrument-sans-latin-wght-normal.ttf +0 -0
  40. package/desktop/src/styles/fonts/instrument-sans-latin-wght-normal.woff2 +0 -0
  41. package/desktop/src/styles/fonts.css +53 -0
  42. package/desktop/src/styles/primitives.css +600 -0
  43. package/desktop/src/styles/tokens-matte.css +354 -0
  44. package/desktop/src/thought.test.ts +96 -0
  45. package/desktop/src/thought.ts +87 -0
  46. package/desktop/src/tool-label.test.ts +17 -0
  47. package/desktop/src/tool-label.ts +70 -0
  48. package/desktop/src/vite-env.d.ts +15 -0
  49. package/desktop/src-tauri/Cargo.lock +4791 -0
  50. package/desktop/src-tauri/Cargo.toml +21 -0
  51. package/desktop/src-tauri/Entitlements.plist +8 -0
  52. package/desktop/src-tauri/Info.plist +12 -0
  53. package/desktop/src-tauri/build.rs +16 -0
  54. package/desktop/src-tauri/capabilities/default.json +15 -0
  55. package/desktop/src-tauri/icons/128x128.png +0 -0
  56. package/desktop/src-tauri/icons/16x16.png +0 -0
  57. package/desktop/src-tauri/icons/32x32.png +0 -0
  58. package/desktop/src-tauri/icons/henry.w@example.net +0 -0
  59. package/desktop/src-tauri/icons/icon.icns +0 -0
  60. package/desktop/src-tauri/icons/icon.ico +0 -0
  61. package/desktop/src-tauri/icons/icon.png +0 -0
  62. package/desktop/src-tauri/icons/icon.svg +7 -0
  63. package/desktop/src-tauri/permissions/bridge.toml +24 -0
  64. package/desktop/src-tauri/src/main.rs +312 -0
  65. package/desktop/src-tauri/src/mic.rs +216 -0
  66. package/desktop/src-tauri/tauri.conf.json +46 -0
  67. package/desktop/tsconfig.json +21 -0
  68. package/desktop/vite.config.ts +18 -0
  69. package/package.json +5 -4
  70. package/src/cli/main.test.ts +6 -0
  71. package/src/cli/main.ts +5 -2
@@ -0,0 +1,46 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ attachmentKind,
4
+ droppedPaths,
5
+ fileExtension,
6
+ filesFromTransfer,
7
+ mergeAttachments,
8
+ transferHasFiles,
9
+ } from "./composer-files.ts";
10
+
11
+ describe("composer files", () => {
12
+ test("classifies images, video, and other files", () => {
13
+ expect(attachmentKind("shot.PNG", "")).toBe("image");
14
+ expect(attachmentKind("clip.mp4", "video/mp4")).toBe("video");
15
+ expect(attachmentKind("notes.md", "text/markdown")).toBe("file");
16
+ });
17
+
18
+ test("reads a short extension label", () => {
19
+ expect(fileExtension("Brief.PDF")).toBe("PDF");
20
+ expect(fileExtension("noext")).toBe("FILE");
21
+ });
22
+
23
+ test("detects a file drag payload", () => {
24
+ expect(transferHasFiles({ types: ["Files"] } as DataTransfer)).toBe(true);
25
+ expect(transferHasFiles({ types: ["text/plain"] } as DataTransfer)).toBe(false);
26
+ expect(transferHasFiles(null)).toBe(false);
27
+ });
28
+
29
+ test("reads files and native paths from a drop", () => {
30
+ const file = new File(["hi"], "a.txt", { type: "text/plain" });
31
+ Object.assign(file, { path: "/tmp/a.txt" });
32
+ const transfer = { files: [file] } as unknown as DataTransfer;
33
+ expect(filesFromTransfer(transfer).map((item) => item.name)).toEqual(["a.txt"]);
34
+ expect(droppedPaths(transfer)).toEqual(["/tmp/a.txt"]);
35
+ });
36
+
37
+ test("merges unique files and rejects oversized extras", () => {
38
+ const first = new File(["hello"], "a.txt", { type: "text/plain", lastModified: 1 });
39
+ const same = new File(["hello"], "a.txt", { type: "text/plain", lastModified: 1 });
40
+ const extra = new File(["world"], "b.txt", { type: "text/plain", lastModified: 2 });
41
+ const huge = new File([new Uint8Array(11 * 1024 * 1024)], "big.bin", { lastModified: 3 });
42
+ const merged = mergeAttachments([], [first, same, extra, huge]);
43
+ expect(merged.attachments.map((item) => item.name)).toEqual(["a.txt", "b.txt"]);
44
+ expect(merged.rejected).toEqual(["big.bin"]);
45
+ });
46
+ });
@@ -0,0 +1,135 @@
1
+ import { blobToBase64 } from "./dictation.ts";
2
+
3
+ export const MAX_COMPOSER_FILES = 8;
4
+ export const MAX_COMPOSER_FILE_BYTES = 10 * 1024 * 1024;
5
+
6
+ export type ComposerFileKind = "image" | "video" | "file";
7
+
8
+ export interface ComposerAttachment {
9
+ id: string;
10
+ name: string;
11
+ mime: string;
12
+ size: number;
13
+ kind: ComposerFileKind;
14
+ previewUrl?: string;
15
+ file: File;
16
+ }
17
+
18
+ export interface TurnAttachmentPayload {
19
+ name: string;
20
+ mime: string;
21
+ data: string;
22
+ }
23
+
24
+ export interface AttachmentPreview {
25
+ name: string;
26
+ mime: string;
27
+ kind: ComposerFileKind;
28
+ previewUrl?: string;
29
+ }
30
+
31
+ export function attachmentKind(name: string, mime: string): ComposerFileKind {
32
+ const type = mime.split(";")[0]?.trim().toLowerCase() ?? "";
33
+ if (type.startsWith("image/")) return "image";
34
+ if (type.startsWith("video/")) return "video";
35
+ if (/\.(png|jpe?g|gif|webp|bmp|svg|avif|heic)$/i.test(name)) return "image";
36
+ if (/\.(mp4|webm|mov|m4v)$/i.test(name)) return "video";
37
+ return "file";
38
+ }
39
+
40
+ export function fileExtension(name: string): string {
41
+ const match = /\.([a-z0-9]{1,8})$/i.exec(name.trim());
42
+ return match?.[1]?.toUpperCase() ?? "FILE";
43
+ }
44
+
45
+ export function transferHasFiles(transfer: DataTransfer | null): boolean {
46
+ if (!transfer) return false;
47
+ return Array.from(transfer.types).includes("Files");
48
+ }
49
+
50
+ export function filesFromTransfer(transfer: DataTransfer | null): File[] {
51
+ if (!transfer) return [];
52
+ return Array.from(transfer.files ?? []);
53
+ }
54
+
55
+ export function droppedPaths(transfer: DataTransfer | null): string[] {
56
+ if (!transfer) return [];
57
+ const paths: string[] = [];
58
+ for (const file of Array.from(transfer.files ?? [])) {
59
+ const path = (file as File & { path?: string }).path?.trim();
60
+ if (path) paths.push(path);
61
+ }
62
+ return paths;
63
+ }
64
+
65
+ export function createAttachment(file: File): ComposerAttachment {
66
+ const mime = file.type || "application/octet-stream";
67
+ const kind = attachmentKind(file.name, mime);
68
+ const previewUrl =
69
+ file.size > 0 &&
70
+ kind !== "file" &&
71
+ typeof URL !== "undefined" &&
72
+ typeof URL.createObjectURL === "function"
73
+ ? URL.createObjectURL(file)
74
+ : undefined;
75
+ return {
76
+ id: `${file.name}-${file.size}-${file.lastModified}-${Math.random().toString(36).slice(2, 8)}`,
77
+ name: file.name || "file",
78
+ mime,
79
+ size: file.size,
80
+ kind,
81
+ ...(previewUrl ? { previewUrl } : {}),
82
+ file,
83
+ };
84
+ }
85
+
86
+ export function releaseAttachment(item: ComposerAttachment | AttachmentPreview): void {
87
+ if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
88
+ }
89
+
90
+ export function isSameFile(item: ComposerAttachment, file: File): boolean {
91
+ return (
92
+ item.name === file.name &&
93
+ item.size === file.size &&
94
+ item.file.lastModified === file.lastModified
95
+ );
96
+ }
97
+
98
+ export function mergeAttachments(
99
+ current: ComposerAttachment[],
100
+ files: File[],
101
+ ): { attachments: ComposerAttachment[]; rejected: string[] } {
102
+ const attachments = [...current];
103
+ const rejected: string[] = [];
104
+ for (const file of files) {
105
+ if (!file.name && file.size <= 0) continue;
106
+ if (attachments.some((item) => isSameFile(item, file))) continue;
107
+ if (attachments.length >= MAX_COMPOSER_FILES || file.size > MAX_COMPOSER_FILE_BYTES) {
108
+ rejected.push(file.name || "file");
109
+ continue;
110
+ }
111
+ attachments.push(createAttachment(file));
112
+ }
113
+ return { attachments, rejected };
114
+ }
115
+
116
+ export function toAttachmentPreviews(items: ComposerAttachment[]): AttachmentPreview[] {
117
+ return items.map((item) => ({
118
+ name: item.name,
119
+ mime: item.mime,
120
+ kind: item.kind,
121
+ ...(item.previewUrl ? { previewUrl: item.previewUrl } : {}),
122
+ }));
123
+ }
124
+
125
+ export async function serializeComposerAttachments(
126
+ items: ComposerAttachment[],
127
+ ): Promise<TurnAttachmentPayload[]> {
128
+ return Promise.all(
129
+ items.map(async (item) => ({
130
+ name: item.name,
131
+ mime: item.mime,
132
+ data: await blobToBase64(item.file),
133
+ })),
134
+ );
135
+ }
@@ -0,0 +1,22 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { audioFormatFromMime, canUseWebMic, dictationErrorMessage } from "./dictation.ts";
3
+
4
+ describe("dictation helpers", () => {
5
+ test("maps recorder mime types to OpenRouter formats", () => {
6
+ expect(audioFormatFromMime("audio/webm;codecs=opus")).toBe("webm");
7
+ expect(audioFormatFromMime("audio/mp4")).toBe("mp4");
8
+ expect(audioFormatFromMime("audio/wav")).toBe("wav");
9
+ });
10
+
11
+ test("names a blocked microphone", () => {
12
+ expect(dictationErrorMessage({ name: "NotAllowedError" })).toBe(
13
+ "Microphone is blocked. Allow it for Caelence agent, then try again.",
14
+ );
15
+ });
16
+
17
+ test("treats a missing webview mic as unavailable, not a hard stop", () => {
18
+ expect(canUseWebMic()).toBe(
19
+ typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia),
20
+ );
21
+ });
22
+ });
@@ -0,0 +1,59 @@
1
+ export function audioFormatFromMime(mime: string): string {
2
+ const type = mime.split(";")[0]?.trim().toLowerCase() ?? "";
3
+ if (type.includes("wav")) return "wav";
4
+ if (type.includes("mpeg") || type.includes("mp3")) return "mp3";
5
+ if (type.includes("mp4") || type.includes("m4a") || type.includes("aac")) return "mp4";
6
+ if (type.includes("ogg")) return "ogg";
7
+ return "webm";
8
+ }
9
+
10
+ export function blobToBase64(blob: Blob): Promise<string> {
11
+ return new Promise((resolve, reject) => {
12
+ const reader = new FileReader();
13
+ reader.onload = () => {
14
+ const dataUrl = String(reader.result ?? "");
15
+ const comma = dataUrl.indexOf(",");
16
+ if (comma < 0) {
17
+ reject(new Error("Recording was empty."));
18
+ return;
19
+ }
20
+ resolve(dataUrl.slice(comma + 1));
21
+ };
22
+ reader.onerror = () => reject(reader.error ?? new Error("Could not read the recording."));
23
+ reader.readAsDataURL(blob);
24
+ });
25
+ }
26
+
27
+ export function canUseWebMic(): boolean {
28
+ return (
29
+ typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getUserMedia === "function"
30
+ );
31
+ }
32
+
33
+ export function isMicPermissionDenied(err: unknown): boolean {
34
+ const name =
35
+ err && typeof err === "object" && "name" in err ? String((err as { name: string }).name) : "";
36
+ return name === "NotAllowedError" || name === "PermissionDeniedError";
37
+ }
38
+
39
+ export function dictationErrorMessage(err: unknown): string {
40
+ const name =
41
+ err && typeof err === "object" && "name" in err ? String((err as { name: string }).name) : "";
42
+ if (isMicPermissionDenied(err)) {
43
+ return "Microphone is blocked. Allow it for Caelence agent, then try again.";
44
+ }
45
+ if (name === "NotFoundError") {
46
+ return "No microphone is available.";
47
+ }
48
+ return err instanceof Error ? err.message : "Could not start the microphone.";
49
+ }
50
+
51
+ export function pickRecorderMime(): string | undefined {
52
+ if (typeof MediaRecorder === "undefined" || typeof MediaRecorder.isTypeSupported !== "function") {
53
+ return undefined;
54
+ }
55
+ for (const type of ["audio/webm", "audio/mp4", "audio/ogg"]) {
56
+ if (MediaRecorder.isTypeSupported(type)) return type;
57
+ }
58
+ return undefined;
59
+ }
@@ -0,0 +1,13 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { integrationMatches } from "./integration-search.ts";
3
+
4
+ describe("integrationMatches", () => {
5
+ test("matches a name prefix and ignores description copy", () => {
6
+ expect(integrationMatches("Canva", "ca")).toBe(true);
7
+ expect(integrationMatches("Google Calendar", "ca")).toBe(true);
8
+ expect(integrationMatches("Google Sheets", "ca")).toBe(false);
9
+ expect(integrationMatches("Replicate", "ca")).toBe(false);
10
+ expect(integrationMatches("Google Sheets", "google")).toBe(true);
11
+ expect(integrationMatches("Google Sheets", "sheet")).toBe(true);
12
+ });
13
+ });
@@ -0,0 +1,8 @@
1
+ /** Match the integration name, not the description. Short queries are word prefixes. */
2
+ export function integrationMatches(label: string, query: string): boolean {
3
+ const q = query.trim().toLowerCase();
4
+ if (!q) return true;
5
+ const hay = label.toLowerCase();
6
+ if (hay.startsWith(q)) return true;
7
+ return hay.split(/\s+/).some((word) => word.startsWith(q));
8
+ }
@@ -0,0 +1,43 @@
1
+ import { Component, type ErrorInfo, type ReactNode, StrictMode } from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import { App } from "./App";
4
+ import "./styles/tokens-matte.css";
5
+ import "./styles/fonts.css";
6
+ import "./styles/primitives.css";
7
+ import "./app.css";
8
+
9
+ class RootErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null }> {
10
+ state: { error: Error | null } = { error: null };
11
+
12
+ static getDerivedStateFromError(error: Error): { error: Error } {
13
+ return { error };
14
+ }
15
+
16
+ componentDidCatch(error: Error, info: ErrorInfo): void {
17
+ console.error(error, info.componentStack);
18
+ }
19
+
20
+ render(): ReactNode {
21
+ if (this.state.error) {
22
+ return (
23
+ <div className="desk desk--boot">
24
+ <main className="desk-empty">
25
+ <p>Caelence agent failed to load.</p>
26
+ <pre className="cel-code">{this.state.error.message}</pre>
27
+ </main>
28
+ </div>
29
+ );
30
+ }
31
+ return this.props.children;
32
+ }
33
+ }
34
+
35
+ const root = document.getElementById("root");
36
+ if (!root) throw new Error("Missing #root");
37
+ createRoot(root).render(
38
+ <StrictMode>
39
+ <RootErrorBoundary>
40
+ <App />
41
+ </RootErrorBoundary>
42
+ </StrictMode>,
43
+ );
@@ -0,0 +1,27 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { pickerKeyAction, pickerStartIndex, stepIndex } from "./picker-nav";
3
+
4
+ describe("picker navigation", () => {
5
+ test("wraps arrow steps around the list", () => {
6
+ expect(stepIndex(0, 3, -1)).toBe(2);
7
+ expect(stepIndex(2, 3, 1)).toBe(0);
8
+ expect(stepIndex(1, 3, 1)).toBe(2);
9
+ });
10
+
11
+ test("maps list keys away from the composer", () => {
12
+ expect(pickerKeyAction("ArrowDown")).toEqual({ type: "move", delta: 1 });
13
+ expect(pickerKeyAction("ArrowUp")).toEqual({ type: "move", delta: -1 });
14
+ expect(pickerKeyAction("Tab")).toEqual({ type: "move", delta: 1 });
15
+ expect(pickerKeyAction("Tab", true)).toEqual({ type: "move", delta: -1 });
16
+ expect(pickerKeyAction("Enter")).toEqual({ type: "confirm" });
17
+ expect(pickerKeyAction("Escape")).toEqual({ type: "cancel" });
18
+ expect(pickerKeyAction("a")).toEqual({ type: "block" });
19
+ expect(pickerKeyAction("Shift")).toBeNull();
20
+ });
21
+
22
+ test("starts on the current value", () => {
23
+ const items = [{ id: "ask" }, { id: "plan" }, { id: "agent" }];
24
+ expect(pickerStartIndex(items, "agent")).toBe(2);
25
+ expect(pickerStartIndex(items, "missing")).toBe(0);
26
+ });
27
+ });
@@ -0,0 +1,26 @@
1
+ export function stepIndex(index: number, count: number, delta: number): number {
2
+ if (count <= 0) return 0;
3
+ return (index + delta + count) % count;
4
+ }
5
+
6
+ export type PickerKeyAction =
7
+ | { type: "move"; delta: number }
8
+ | { type: "confirm" }
9
+ | { type: "cancel" }
10
+ | { type: "block" };
11
+
12
+ /** Keys that belong to an open command list, not the composer. */
13
+ export function pickerKeyAction(key: string, shiftKey = false): PickerKeyAction | null {
14
+ if (key === "ArrowDown" || (key === "Tab" && !shiftKey)) return { type: "move", delta: 1 };
15
+ if (key === "ArrowUp" || (key === "Tab" && shiftKey)) return { type: "move", delta: -1 };
16
+ if (key === "Enter") return { type: "confirm" };
17
+ if (key === "Escape") return { type: "cancel" };
18
+ if (key.length === 1 || key === "Backspace" || key === "Delete") return { type: "block" };
19
+ return null;
20
+ }
21
+
22
+ export function pickerStartIndex(items: Array<{ id: string }>, currentId?: string): number {
23
+ if (!currentId) return 0;
24
+ const index = items.findIndex((item) => item.id === currentId);
25
+ return index >= 0 ? index : 0;
26
+ }
@@ -0,0 +1,37 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { enqueueMessage, removeQueued, setQueuedText, shiftQueue, updateQueued } from "./queue.ts";
3
+
4
+ describe("message queue", () => {
5
+ test("enqueues trimmed text and drops empty", () => {
6
+ expect(enqueueMessage([], " ", "q-1")).toEqual([]);
7
+ expect(enqueueMessage([], " later ", "q-1")).toEqual([{ id: "q-1", text: "later" }]);
8
+ });
9
+
10
+ test("enqueues attachments without text", () => {
11
+ const file = new File(["hi"], "a.txt", { type: "text/plain" });
12
+ const attachment = {
13
+ id: "a1",
14
+ name: "a.txt",
15
+ mime: "text/plain",
16
+ size: 2,
17
+ kind: "file" as const,
18
+ file,
19
+ };
20
+ expect(enqueueMessage([], " ", "q-1", [attachment])).toEqual([
21
+ { id: "q-1", text: "", attachments: [attachment] },
22
+ ]);
23
+ });
24
+
25
+ test("updates, removes, and shifts in order", () => {
26
+ let queue = enqueueMessage([], "one", "q-1");
27
+ queue = enqueueMessage(queue, "two", "q-2");
28
+ queue = updateQueued(queue, "q-1", "one edited");
29
+ expect(queue.map((item) => item.text)).toEqual(["one edited", "two"]);
30
+ queue = setQueuedText(queue, "q-2", "two ");
31
+ expect(queue[1]?.text).toBe("two ");
32
+ queue = removeQueued(queue, "q-2");
33
+ const shifted = shiftQueue(queue);
34
+ expect(shifted.next?.text).toBe("one edited");
35
+ expect(shifted.rest).toEqual([]);
36
+ });
37
+ });
@@ -0,0 +1,40 @@
1
+ import type { ComposerAttachment } from "./composer-files.ts";
2
+
3
+ export interface QueuedMessage {
4
+ id: string;
5
+ text: string;
6
+ attachments?: ComposerAttachment[];
7
+ }
8
+
9
+ export function enqueueMessage(
10
+ queue: QueuedMessage[],
11
+ text: string,
12
+ id: string,
13
+ attachments: ComposerAttachment[] = [],
14
+ ): QueuedMessage[] {
15
+ const trimmed = text.trim();
16
+ if (!trimmed && attachments.length === 0) return queue;
17
+ return [...queue, { id, text: trimmed, ...(attachments.length > 0 ? { attachments } : {}) }];
18
+ }
19
+
20
+ export function removeQueued(queue: QueuedMessage[], id: string): QueuedMessage[] {
21
+ return queue.filter((item) => item.id !== id);
22
+ }
23
+
24
+ export function setQueuedText(queue: QueuedMessage[], id: string, text: string): QueuedMessage[] {
25
+ return queue.map((item) => (item.id === id ? { ...item, text } : item));
26
+ }
27
+
28
+ export function updateQueued(queue: QueuedMessage[], id: string, text: string): QueuedMessage[] {
29
+ const trimmed = text.trim();
30
+ if (!trimmed) return removeQueued(queue, id);
31
+ return queue.map((item) => (item.id === id ? { ...item, text: trimmed } : item));
32
+ }
33
+
34
+ export function shiftQueue(queue: QueuedMessage[]): {
35
+ next?: QueuedMessage;
36
+ rest: QueuedMessage[];
37
+ } {
38
+ const [next, ...rest] = queue;
39
+ return next ? { next, rest } : { rest };
40
+ }
@@ -0,0 +1,85 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { canvaViewUrl, isImageUrl, linkLabel, splitRichText } from "./rich-text.ts";
3
+
4
+ describe("splitRichText", () => {
5
+ test("turns a Canva document-image URL into a preview", () => {
6
+ const src =
7
+ "https://media.canva.com/v2/document-image/hash:2114610722/height:532/id:DAHTOpj1Mso/type:B/width:376?brand=x";
8
+ const parts = splitRichText(`Preview:\n${src}`);
9
+ expect(parts[0]).toEqual({ type: "text", text: "Preview:\n" });
10
+ expect(parts[1]).toEqual({ type: "image", src, alt: "Preview" });
11
+ expect(isImageUrl(src)).toBe(true);
12
+ });
13
+
14
+ test("decodes HTML-escaped query ampersands in Canva URLs", () => {
15
+ const parts = splitRichText(
16
+ "Preview:\nhttps://media.canva.com/v2/document-image/id:abc?sig=one&amp;exp=two",
17
+ );
18
+ expect(parts[1]).toMatchObject({
19
+ type: "image",
20
+ src: "https://media.canva.com/v2/document-image/id:abc?sig=one&exp=two",
21
+ });
22
+ });
23
+
24
+ test("turns Edit and View Canva URLs into clickable links", () => {
25
+ const parts = splitRichText(
26
+ "Edit: https://www.canva.com/d/K4tAORuznFyHJOx\nView: https://www.canva.com/d/zB----6zs2unkjaV",
27
+ );
28
+ const links = parts.filter((part) => part.type === "link");
29
+ expect(links).toHaveLength(2);
30
+ expect(links[0]).toMatchObject({
31
+ type: "link",
32
+ href: "https://www.canva.com/d/K4tAORuznFyHJOx",
33
+ label: "www.canva.com/d/K4tAORuznFyHJOx",
34
+ });
35
+ expect(linkLabel("https://www.canva.com/d/K4tAORuznFyHJOx")).toBe(
36
+ "www.canva.com/d/K4tAORuznFyHJOx",
37
+ );
38
+ });
39
+
40
+ test("builds a Canva view URL from a document-image or /d/ link", () => {
41
+ expect(canvaViewUrl("https://www.canva.com/d/zB----6zs2unkjaV")).toBe(
42
+ "https://www.canva.com/d/zB----6zs2unkjaV",
43
+ );
44
+ expect(
45
+ canvaViewUrl("https://media.canva.com/v2/document-image/hash:1/id:DAHTOpj1Mso/type:B?sig=x"),
46
+ ).toBe("https://www.canva.com/design/DAHTOpj1Mso/view");
47
+ });
48
+
49
+ test("keeps markdown links and surrounding copy", () => {
50
+ const parts = splitRichText("See [the file](https://www.canva.com/d/abc) next.");
51
+ expect(parts).toEqual([
52
+ { type: "text", text: "See " },
53
+ { type: "link", href: "https://www.canva.com/d/abc", label: "the file" },
54
+ { type: "text", text: " next." },
55
+ ]);
56
+ });
57
+
58
+ test("turns listed local files into openable paths", () => {
59
+ const parts = splitRichText(
60
+ "Latest files in ~/Downloads (newest first):\n\n1. Figma.dmg — Sep 15, 14:34\n2. favicon-agent-bg-32.svg — Sep 15, 09:05\n6. CV_Mads_Hærup_14-09-2026.pdf — Sep 14, 15:17",
61
+ );
62
+ const files = parts.filter((part) => part.type === "file");
63
+ expect(files).toEqual([
64
+ { type: "file", path: "~/Downloads", label: "~/Downloads" },
65
+ { type: "file", path: "~/Downloads/Figma.dmg", label: "Figma.dmg" },
66
+ {
67
+ type: "file",
68
+ path: "~/Downloads/favicon-agent-bg-32.svg",
69
+ label: "favicon-agent-bg-32.svg",
70
+ },
71
+ {
72
+ type: "file",
73
+ path: "~/Downloads/CV_Mads_Hærup_14-09-2026.pdf",
74
+ label: "CV_Mads_Hærup_14-09-2026.pdf",
75
+ },
76
+ ]);
77
+ });
78
+
79
+ test("keeps an explicit home path clickable", () => {
80
+ const parts = splitRichText("Open ~/Documents/brief.md when you can.");
81
+ expect(parts.some((part) => part.type === "file" && part.path === "~/Documents/brief.md")).toBe(
82
+ true,
83
+ );
84
+ });
85
+ });