@agent-native/toolkit 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/composer/AgentComposerFrame.d.ts +19 -0
- package/dist/composer/AgentComposerFrame.d.ts.map +1 -0
- package/dist/composer/AgentComposerFrame.js +14 -0
- package/dist/composer/AgentComposerFrame.js.map +1 -0
- package/dist/composer/ComposerPlusMenu.d.ts +17 -0
- package/dist/composer/ComposerPlusMenu.d.ts.map +1 -0
- package/dist/composer/ComposerPlusMenu.js +501 -0
- package/dist/composer/ComposerPlusMenu.js.map +1 -0
- package/dist/composer/MentionPopover.d.ts +29 -0
- package/dist/composer/MentionPopover.d.ts.map +1 -0
- package/dist/composer/MentionPopover.js +180 -0
- package/dist/composer/MentionPopover.js.map +1 -0
- package/dist/composer/PastedTextChip.d.ts +9 -0
- package/dist/composer/PastedTextChip.d.ts.map +1 -0
- package/dist/composer/PastedTextChip.js +47 -0
- package/dist/composer/PastedTextChip.js.map +1 -0
- package/dist/composer/PromptComposer.d.ts +114 -0
- package/dist/composer/PromptComposer.d.ts.map +1 -0
- package/dist/composer/PromptComposer.js +302 -0
- package/dist/composer/PromptComposer.js.map +1 -0
- package/dist/composer/PromptComposer.spec.d.ts +2 -0
- package/dist/composer/PromptComposer.spec.d.ts.map +1 -0
- package/dist/composer/PromptComposer.spec.js +64 -0
- package/dist/composer/PromptComposer.spec.js.map +1 -0
- package/dist/composer/RealtimeVoiceMode.d.ts +104 -0
- package/dist/composer/RealtimeVoiceMode.d.ts.map +1 -0
- package/dist/composer/RealtimeVoiceMode.js +245 -0
- package/dist/composer/RealtimeVoiceMode.js.map +1 -0
- package/dist/composer/RealtimeVoiceMode.spec.d.ts +2 -0
- package/dist/composer/RealtimeVoiceMode.spec.d.ts.map +1 -0
- package/dist/composer/RealtimeVoiceMode.spec.js +439 -0
- package/dist/composer/RealtimeVoiceMode.spec.js.map +1 -0
- package/dist/composer/TiptapComposer.d.ts +221 -0
- package/dist/composer/TiptapComposer.d.ts.map +1 -0
- package/dist/composer/TiptapComposer.js +1838 -0
- package/dist/composer/TiptapComposer.js.map +1 -0
- package/dist/composer/TiptapComposer.spec.d.ts +2 -0
- package/dist/composer/TiptapComposer.spec.d.ts.map +1 -0
- package/dist/composer/TiptapComposer.spec.js +277 -0
- package/dist/composer/TiptapComposer.spec.js.map +1 -0
- package/dist/composer/VoiceButton.d.ts +25 -0
- package/dist/composer/VoiceButton.d.ts.map +1 -0
- package/dist/composer/VoiceButton.js +100 -0
- package/dist/composer/VoiceButton.js.map +1 -0
- package/dist/composer/VoiceButton.spec.d.ts +2 -0
- package/dist/composer/VoiceButton.spec.d.ts.map +1 -0
- package/dist/composer/VoiceButton.spec.js +19 -0
- package/dist/composer/VoiceButton.spec.js.map +1 -0
- package/dist/composer/asset-picker-url.d.ts +16 -0
- package/dist/composer/asset-picker-url.d.ts.map +1 -0
- package/dist/composer/asset-picker-url.js +64 -0
- package/dist/composer/asset-picker-url.js.map +1 -0
- package/dist/composer/asset-picker-url.spec.d.ts +2 -0
- package/dist/composer/asset-picker-url.spec.d.ts.map +1 -0
- package/dist/composer/asset-picker-url.spec.js +23 -0
- package/dist/composer/asset-picker-url.spec.js.map +1 -0
- package/dist/composer/attachment-accept.d.ts +9 -0
- package/dist/composer/attachment-accept.d.ts.map +1 -0
- package/dist/composer/attachment-accept.js +65 -0
- package/dist/composer/attachment-accept.js.map +1 -0
- package/dist/composer/attachment-accept.spec.d.ts +2 -0
- package/dist/composer/attachment-accept.spec.d.ts.map +1 -0
- package/dist/composer/attachment-accept.spec.js +15 -0
- package/dist/composer/attachment-accept.spec.js.map +1 -0
- package/dist/composer/draft-key.d.ts +2 -0
- package/dist/composer/draft-key.d.ts.map +1 -0
- package/dist/composer/draft-key.js +8 -0
- package/dist/composer/draft-key.js.map +1 -0
- package/dist/composer/draft-key.spec.d.ts +2 -0
- package/dist/composer/draft-key.spec.d.ts.map +1 -0
- package/dist/composer/draft-key.spec.js +13 -0
- package/dist/composer/draft-key.spec.js.map +1 -0
- package/dist/composer/extensions/FileReference.d.ts +3 -0
- package/dist/composer/extensions/FileReference.d.ts.map +1 -0
- package/dist/composer/extensions/FileReference.js +36 -0
- package/dist/composer/extensions/FileReference.js.map +1 -0
- package/dist/composer/extensions/MentionReference.d.ts +3 -0
- package/dist/composer/extensions/MentionReference.d.ts.map +1 -0
- package/dist/composer/extensions/MentionReference.js +66 -0
- package/dist/composer/extensions/MentionReference.js.map +1 -0
- package/dist/composer/extensions/SkillReference.d.ts +3 -0
- package/dist/composer/extensions/SkillReference.d.ts.map +1 -0
- package/dist/composer/extensions/SkillReference.js +40 -0
- package/dist/composer/extensions/SkillReference.js.map +1 -0
- package/dist/composer/index.d.ts +14 -0
- package/dist/composer/index.d.ts.map +1 -0
- package/dist/composer/index.js +13 -0
- package/dist/composer/index.js.map +1 -0
- package/dist/composer/pasted-text.d.ts +31 -0
- package/dist/composer/pasted-text.d.ts.map +1 -0
- package/dist/composer/pasted-text.js +130 -0
- package/dist/composer/pasted-text.js.map +1 -0
- package/dist/composer/pasted-text.spec.d.ts +2 -0
- package/dist/composer/pasted-text.spec.d.ts.map +1 -0
- package/dist/composer/pasted-text.spec.js +107 -0
- package/dist/composer/pasted-text.spec.js.map +1 -0
- package/dist/composer/prompt-attachments.d.ts +18 -0
- package/dist/composer/prompt-attachments.d.ts.map +1 -0
- package/dist/composer/prompt-attachments.js +65 -0
- package/dist/composer/prompt-attachments.js.map +1 -0
- package/dist/composer/prompt-attachments.spec.d.ts +2 -0
- package/dist/composer/prompt-attachments.spec.d.ts.map +1 -0
- package/dist/composer/prompt-attachments.spec.js +63 -0
- package/dist/composer/prompt-attachments.spec.js.map +1 -0
- package/dist/composer/realtime-voice-audio-level.d.ts +14 -0
- package/dist/composer/realtime-voice-audio-level.d.ts.map +1 -0
- package/dist/composer/realtime-voice-audio-level.js +47 -0
- package/dist/composer/realtime-voice-audio-level.js.map +1 -0
- package/dist/composer/realtime-voice-audio-level.spec.d.ts +2 -0
- package/dist/composer/realtime-voice-audio-level.spec.d.ts.map +1 -0
- package/dist/composer/realtime-voice-audio-level.spec.js +25 -0
- package/dist/composer/realtime-voice-audio-level.spec.js.map +1 -0
- package/dist/composer/realtime-voice-transcript.d.ts +26 -0
- package/dist/composer/realtime-voice-transcript.d.ts.map +1 -0
- package/dist/composer/realtime-voice-transcript.js +103 -0
- package/dist/composer/realtime-voice-transcript.js.map +1 -0
- package/dist/composer/realtime-voice-transcript.spec.d.ts +2 -0
- package/dist/composer/realtime-voice-transcript.spec.d.ts.map +1 -0
- package/dist/composer/realtime-voice-transcript.spec.js +76 -0
- package/dist/composer/realtime-voice-transcript.spec.js.map +1 -0
- package/dist/composer/runtime-adapters.d.ts +163 -0
- package/dist/composer/runtime-adapters.d.ts.map +1 -0
- package/dist/composer/runtime-adapters.js +130 -0
- package/dist/composer/runtime-adapters.js.map +1 -0
- package/dist/composer/types.d.ts +60 -0
- package/dist/composer/types.d.ts.map +1 -0
- package/dist/composer/types.js +2 -0
- package/dist/composer/types.js.map +1 -0
- package/dist/composer/use-file-search.d.ts +6 -0
- package/dist/composer/use-file-search.d.ts.map +1 -0
- package/dist/composer/use-file-search.js +53 -0
- package/dist/composer/use-file-search.js.map +1 -0
- package/dist/composer/use-mention-search.d.ts +6 -0
- package/dist/composer/use-mention-search.d.ts.map +1 -0
- package/dist/composer/use-mention-search.js +75 -0
- package/dist/composer/use-mention-search.js.map +1 -0
- package/dist/composer/use-skills.d.ts +7 -0
- package/dist/composer/use-skills.d.ts.map +1 -0
- package/dist/composer/use-skills.js +40 -0
- package/dist/composer/use-skills.js.map +1 -0
- package/dist/composer/useRealtimeVoiceMode.d.ts +179 -0
- package/dist/composer/useRealtimeVoiceMode.d.ts.map +1 -0
- package/dist/composer/useRealtimeVoiceMode.js +1657 -0
- package/dist/composer/useRealtimeVoiceMode.js.map +1 -0
- package/dist/composer/useRealtimeVoiceMode.spec.d.ts +2 -0
- package/dist/composer/useRealtimeVoiceMode.spec.d.ts.map +1 -0
- package/dist/composer/useRealtimeVoiceMode.spec.js +618 -0
- package/dist/composer/useRealtimeVoiceMode.spec.js.map +1 -0
- package/dist/composer/useVoiceDictation.d.ts +57 -0
- package/dist/composer/useVoiceDictation.d.ts.map +1 -0
- package/dist/composer/useVoiceDictation.js +1004 -0
- package/dist/composer/useVoiceDictation.js.map +1 -0
- package/dist/composer/useVoiceDictation.spec.d.ts +2 -0
- package/dist/composer/useVoiceDictation.spec.d.ts.map +1 -0
- package/dist/composer/useVoiceDictation.spec.js +32 -0
- package/dist/composer/useVoiceDictation.spec.js.map +1 -0
- package/dist/editor/RegistryBlockContext.d.ts +68 -0
- package/dist/editor/RegistryBlockContext.d.ts.map +1 -0
- package/dist/editor/RegistryBlockContext.js +10 -0
- package/dist/editor/RegistryBlockContext.js.map +1 -0
- package/dist/editor/RegistryBlockNode.d.ts +66 -0
- package/dist/editor/RegistryBlockNode.d.ts.map +1 -0
- package/dist/editor/RegistryBlockNode.js +406 -0
- package/dist/editor/RegistryBlockNode.js.map +1 -0
- package/dist/editor/RegistryBlockNode.spec.d.ts +2 -0
- package/dist/editor/RegistryBlockNode.spec.d.ts.map +1 -0
- package/dist/editor/RegistryBlockNode.spec.js +215 -0
- package/dist/editor/RegistryBlockNode.spec.js.map +1 -0
- package/dist/editor/index.d.ts +2 -0
- package/dist/editor/index.d.ts.map +1 -1
- package/dist/editor/index.js +2 -0
- package/dist/editor/index.js.map +1 -1
- package/dist/editor/registrySlashCommands.d.ts +68 -0
- package/dist/editor/registrySlashCommands.d.ts.map +1 -0
- package/dist/editor/registrySlashCommands.js +51 -0
- package/dist/editor/registrySlashCommands.js.map +1 -0
- package/package.json +16 -1
|
@@ -0,0 +1,1838 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { Skeleton } from "@agent-native/toolkit/ui/skeleton";
|
|
3
|
+
import { useComposer, useComposerRuntime } from "@assistant-ui/react";
|
|
4
|
+
import { IconArrowUp, IconCheck, IconChevronDown, IconChevronRight, IconBulb, IconClock, IconBolt, IconTool, IconX, IconClipboardList, IconKey, IconPencil, IconPlugConnected, } from "@tabler/icons-react";
|
|
5
|
+
import Placeholder from "@tiptap/extension-placeholder";
|
|
6
|
+
import { useEditor, EditorContent } from "@tiptap/react";
|
|
7
|
+
import StarterKit from "@tiptap/starter-kit";
|
|
8
|
+
import { useState, useRef, useEffect, useCallback, useImperativeHandle, useMemo, } from "react";
|
|
9
|
+
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover.js";
|
|
10
|
+
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip.js";
|
|
11
|
+
import { ComposerPlusMenu } from "./ComposerPlusMenu.js";
|
|
12
|
+
import { getComposerDraftKey } from "./draft-key.js";
|
|
13
|
+
import { FileReference } from "./extensions/FileReference.js";
|
|
14
|
+
import { MentionReference } from "./extensions/MentionReference.js";
|
|
15
|
+
import { SkillReference } from "./extensions/SkillReference.js";
|
|
16
|
+
import { MentionPopover } from "./MentionPopover.js";
|
|
17
|
+
import { createPastedAttachmentFile, readClipboardPaste, shouldConvertClipboardToAttachment, } from "./pasted-text.js";
|
|
18
|
+
import { AGENT_CHAT_INSERT_REFERENCE_EVENT, AGENT_CHAT_INSERT_REFERENCE_MESSAGE_TYPE, DEFAULT_REASONING_EFFORT, formatPromptContextItems, getReasoningEffortOptionsForModel, reasoningEffortLabel, resolveReasoningEffortSelection, useComposerRuntimeAdapters, } from "./runtime-adapters.js";
|
|
19
|
+
import { useMentionSearch } from "./use-mention-search.js";
|
|
20
|
+
import { useSkills } from "./use-skills.js";
|
|
21
|
+
import { RealtimeVoiceModeBoundary } from "./useRealtimeVoiceMode.js";
|
|
22
|
+
import { useVoiceDictation } from "./useVoiceDictation.js";
|
|
23
|
+
import { VoiceButton, VoiceRecordingOverlay } from "./VoiceButton.js";
|
|
24
|
+
export const DEFAULT_VOICE_DICTATION_ENABLED = false;
|
|
25
|
+
export function canSubmitComposerContent(options) {
|
|
26
|
+
return (!options.disabled &&
|
|
27
|
+
(options.hasEditorContent || options.attachmentCount > 0));
|
|
28
|
+
}
|
|
29
|
+
const VOICE_TERMINAL_PUNCTUATION = /[.!?…。!?:;](?:["'”’»)\]}]*)$/;
|
|
30
|
+
export function formatVoiceTranscriptForComposer(text) {
|
|
31
|
+
const trimmed = text.trim();
|
|
32
|
+
if (!trimmed)
|
|
33
|
+
return "";
|
|
34
|
+
return `${trimmed}${VOICE_TERMINAL_PUNCTUATION.test(trimmed) ? "" : "."} `;
|
|
35
|
+
}
|
|
36
|
+
export function canRemoveVoicePreview(options) {
|
|
37
|
+
if (!options.previewText)
|
|
38
|
+
return false;
|
|
39
|
+
if (options.anchor < 1)
|
|
40
|
+
return false;
|
|
41
|
+
if (options.anchor + options.previewText.length > options.documentSize) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
return options.currentText === options.previewText;
|
|
45
|
+
}
|
|
46
|
+
export function resolveComposerPrimaryAction(options) {
|
|
47
|
+
return !options.canSubmit && options.hasStopButton ? "stop" : "send";
|
|
48
|
+
}
|
|
49
|
+
export function resolveContextChipBackspaceAction(options) {
|
|
50
|
+
if (!options.cursorAtStart || options.contextItemKeys.length === 0) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
if (options.selectedKey &&
|
|
54
|
+
options.contextItemKeys.includes(options.selectedKey)) {
|
|
55
|
+
return { type: "remove", key: options.selectedKey };
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
type: "select",
|
|
59
|
+
key: options.contextItemKeys[options.contextItemKeys.length - 1],
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const MAX_DOCUMENT_ATTACHMENT_BYTES = 4 * 1024 * 1024;
|
|
63
|
+
function composerReferenceFromMentionItem(item) {
|
|
64
|
+
return {
|
|
65
|
+
label: item.label,
|
|
66
|
+
icon: item.icon || "file",
|
|
67
|
+
source: item.source,
|
|
68
|
+
refType: item.refType,
|
|
69
|
+
refId: item.refId || null,
|
|
70
|
+
refPath: item.refPath || null,
|
|
71
|
+
slotKey: item.slotKey,
|
|
72
|
+
slotLabel: item.slotLabel,
|
|
73
|
+
metadata: item.metadata,
|
|
74
|
+
clearsSlots: item.clearsSlots,
|
|
75
|
+
relatedReferences: item.relatedReferences,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function mentionReferenceAttrs(ref) {
|
|
79
|
+
return {
|
|
80
|
+
label: ref.label,
|
|
81
|
+
icon: ref.icon || "file",
|
|
82
|
+
source: ref.source,
|
|
83
|
+
refType: ref.refType,
|
|
84
|
+
refId: ref.refId || null,
|
|
85
|
+
refPath: ref.refPath || null,
|
|
86
|
+
slotKey: ref.slotKey || null,
|
|
87
|
+
slotLabel: ref.slotLabel || null,
|
|
88
|
+
metadata: ref.metadata || null,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function referenceFromComposerReference(ref) {
|
|
92
|
+
return {
|
|
93
|
+
type: ref.refType === "file"
|
|
94
|
+
? "file"
|
|
95
|
+
: ref.refType === "agent"
|
|
96
|
+
? "agent"
|
|
97
|
+
: ref.refType === "custom-agent"
|
|
98
|
+
? "custom-agent"
|
|
99
|
+
: "mention",
|
|
100
|
+
path: ref.refPath || "",
|
|
101
|
+
name: ref.label,
|
|
102
|
+
source: ref.source || "",
|
|
103
|
+
refType: ref.refType,
|
|
104
|
+
refId: ref.refId || undefined,
|
|
105
|
+
slotKey: ref.slotKey,
|
|
106
|
+
slotLabel: ref.slotLabel,
|
|
107
|
+
metadata: ref.metadata,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function applySlotReferenceChanges(current, references) {
|
|
111
|
+
let next = current;
|
|
112
|
+
const applyOne = (ref) => {
|
|
113
|
+
for (const related of ref.relatedReferences ?? []) {
|
|
114
|
+
applyOne(related);
|
|
115
|
+
}
|
|
116
|
+
if (!ref.slotKey)
|
|
117
|
+
return;
|
|
118
|
+
const cleared = new Set([ref.slotKey, ...(ref.clearsSlots ?? [])]);
|
|
119
|
+
next = next.filter((existing) => !cleared.has(existing.slotKey ?? ""));
|
|
120
|
+
next = [...next, ref];
|
|
121
|
+
};
|
|
122
|
+
for (const ref of references) {
|
|
123
|
+
applyOne(ref);
|
|
124
|
+
}
|
|
125
|
+
return next;
|
|
126
|
+
}
|
|
127
|
+
function removeSlotReference(current, ref) {
|
|
128
|
+
const removed = new Set([ref.slotKey, ...(ref.clearsSlots ?? [])]);
|
|
129
|
+
return current.filter((existing) => !removed.has(existing.slotKey ?? ""));
|
|
130
|
+
}
|
|
131
|
+
function slotReferenceTitle(ref) {
|
|
132
|
+
return ref.slotLabel ? `${ref.slotLabel}: ${ref.label}` : ref.label;
|
|
133
|
+
}
|
|
134
|
+
function metadataString(metadata, key) {
|
|
135
|
+
const value = metadata?.[key];
|
|
136
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
137
|
+
}
|
|
138
|
+
function trimVoiceContextValue(value, maxChars) {
|
|
139
|
+
const trimmed = value.replace(/\0/g, "").trim();
|
|
140
|
+
if (!trimmed)
|
|
141
|
+
return null;
|
|
142
|
+
if (trimmed.length <= maxChars)
|
|
143
|
+
return trimmed;
|
|
144
|
+
return `${trimmed.slice(0, maxChars).trimEnd()}\n[truncated]`;
|
|
145
|
+
}
|
|
146
|
+
function filterMentionItemsForSlots(items, slotReferences) {
|
|
147
|
+
return items.filter((item) => {
|
|
148
|
+
const requiredSlotKey = metadataString(item.metadata, "requiredSlotKey");
|
|
149
|
+
const requiredRefId = metadataString(item.metadata, "requiredRefId");
|
|
150
|
+
if (!requiredSlotKey || !requiredRefId)
|
|
151
|
+
return true;
|
|
152
|
+
const selected = slotReferences.find((ref) => ref.slotKey === requiredSlotKey);
|
|
153
|
+
if (!selected?.refId)
|
|
154
|
+
return true;
|
|
155
|
+
return selected.refId === requiredRefId;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function isDocumentAttachment(value) {
|
|
159
|
+
if (value.type === "document")
|
|
160
|
+
return true;
|
|
161
|
+
const contentType = String(value.contentType ?? "").toLowerCase();
|
|
162
|
+
const name = String(value.name ?? "").toLowerCase();
|
|
163
|
+
return contentType === "application/pdf" || name.endsWith(".pdf");
|
|
164
|
+
}
|
|
165
|
+
export function getOversizedDocumentAttachmentError(attachments) {
|
|
166
|
+
for (const attachment of attachments) {
|
|
167
|
+
if (!attachment || typeof attachment !== "object")
|
|
168
|
+
continue;
|
|
169
|
+
const candidate = attachment;
|
|
170
|
+
if (!isDocumentAttachment(candidate))
|
|
171
|
+
continue;
|
|
172
|
+
const file = candidate.file;
|
|
173
|
+
if (!(file instanceof File))
|
|
174
|
+
continue;
|
|
175
|
+
if (file.size <= MAX_DOCUMENT_ATTACHMENT_BYTES)
|
|
176
|
+
continue;
|
|
177
|
+
const name = typeof candidate.name === "string" && candidate.name.trim()
|
|
178
|
+
? candidate.name
|
|
179
|
+
: file.name;
|
|
180
|
+
const mb = (file.size / 1024 / 1024).toFixed(1);
|
|
181
|
+
const maxMb = (MAX_DOCUMENT_ATTACHMENT_BYTES / 1024 / 1024).toFixed(0);
|
|
182
|
+
return `"${name}" is ${mb} MB — PDFs are capped at ${maxMb} MB to stay within message limits. Please reduce the file size or split it into smaller parts.`;
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
export function getComposerSubmitIntentForEnterKey(event, isMac) {
|
|
187
|
+
if (event.key !== "Enter" || event.shiftKey)
|
|
188
|
+
return null;
|
|
189
|
+
const queuedModifierPressed = isMac ? event.metaKey : event.ctrlKey;
|
|
190
|
+
if (queuedModifierPressed)
|
|
191
|
+
return "queued";
|
|
192
|
+
if (!event.metaKey && !event.ctrlKey)
|
|
193
|
+
return "immediate";
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
export function insertComposerHardBreakAndScrollIntoView(view) {
|
|
197
|
+
const hardBreak = view.state.schema.nodes.hardBreak;
|
|
198
|
+
if (!hardBreak)
|
|
199
|
+
return false;
|
|
200
|
+
view.dispatch(view.state.tr.replaceSelectionWith(hardBreak.create()).scrollIntoView());
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
export function getComposerPopoverPosition(view, pos) {
|
|
204
|
+
try {
|
|
205
|
+
const coords = view.coordsAtPos(pos);
|
|
206
|
+
if (!Number.isFinite(coords.top) || !Number.isFinite(coords.left)) {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
return { top: coords.top, left: coords.left };
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
export function displayableComposerModeMessage(options) {
|
|
216
|
+
const modePrompt = options.trimmedText ||
|
|
217
|
+
(options.attachmentCount > 0 ? "Use the attached context." : "");
|
|
218
|
+
return `${options.messagePrefix}${modePrompt}`;
|
|
219
|
+
}
|
|
220
|
+
function uniquifyComposerImageFile(file) {
|
|
221
|
+
if (!file.type.startsWith("image/"))
|
|
222
|
+
return file;
|
|
223
|
+
const uniqueName = `${Date.now()}-${Math.random().toString(36).slice(2)}-${file.name}`;
|
|
224
|
+
return new File([file], uniqueName, { type: file.type });
|
|
225
|
+
}
|
|
226
|
+
function composerDocumentHasContent(doc) {
|
|
227
|
+
if (doc.textContent.trim().length > 0)
|
|
228
|
+
return true;
|
|
229
|
+
let hasContent = false;
|
|
230
|
+
doc.descendants((node) => {
|
|
231
|
+
if (node.type.name === "mentionReference" ||
|
|
232
|
+
node.type.name === "fileReference" ||
|
|
233
|
+
node.type.name === "skillReference") {
|
|
234
|
+
hasContent = true;
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
return true;
|
|
238
|
+
});
|
|
239
|
+
return hasContent;
|
|
240
|
+
}
|
|
241
|
+
export function handleComposerFileDrop(options) {
|
|
242
|
+
const droppedFiles = Array.from(options.event.dataTransfer?.files ?? []);
|
|
243
|
+
if (droppedFiles.length === 0)
|
|
244
|
+
return false;
|
|
245
|
+
options.event.preventDefault();
|
|
246
|
+
options.event.stopPropagation();
|
|
247
|
+
const attachments = droppedFiles.map(uniquifyComposerImageFile);
|
|
248
|
+
void Promise.all(attachments.map((file) => options.addAttachment(file))).catch((error) => {
|
|
249
|
+
options.onError?.(error);
|
|
250
|
+
});
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
const BUILT_IN_COMMANDS = [
|
|
254
|
+
{ name: "clear", description: "Start a new chat", icon: "clear" },
|
|
255
|
+
{ name: "new", description: "Start a new chat", icon: "new" },
|
|
256
|
+
{ name: "history", description: "Browse all chats", icon: "history" },
|
|
257
|
+
{ name: "plan", description: "Switch to read-only planning", icon: "plan" },
|
|
258
|
+
{ name: "act", description: "Switch back to acting", icon: "act" },
|
|
259
|
+
{ name: "help", description: "Show available commands", icon: "help" },
|
|
260
|
+
];
|
|
261
|
+
function normalizeSlashCommandName(name) {
|
|
262
|
+
return name.replace(/^\/+/, "").trim().toLowerCase();
|
|
263
|
+
}
|
|
264
|
+
function mergeSlashCommands(commands) {
|
|
265
|
+
const seen = new Set();
|
|
266
|
+
const merged = [];
|
|
267
|
+
for (const command of commands) {
|
|
268
|
+
const name = normalizeSlashCommandName(command.name);
|
|
269
|
+
if (!name || seen.has(name))
|
|
270
|
+
continue;
|
|
271
|
+
seen.add(name);
|
|
272
|
+
merged.push({ ...command, name });
|
|
273
|
+
}
|
|
274
|
+
return merged;
|
|
275
|
+
}
|
|
276
|
+
function mergeSlashSkills(skills) {
|
|
277
|
+
const seen = new Set();
|
|
278
|
+
const merged = [];
|
|
279
|
+
for (const skill of skills) {
|
|
280
|
+
const key = `${skill.source ?? ""}:${skill.path ?? ""}:${skill.name}`;
|
|
281
|
+
if (!skill.name || seen.has(key))
|
|
282
|
+
continue;
|
|
283
|
+
seen.add(key);
|
|
284
|
+
merged.push(skill);
|
|
285
|
+
}
|
|
286
|
+
return merged;
|
|
287
|
+
}
|
|
288
|
+
const COMPOSER_MODE_CONFIGS = {
|
|
289
|
+
skill: {
|
|
290
|
+
label: "Create Skill",
|
|
291
|
+
icon: IconBulb,
|
|
292
|
+
placeholder: "Describe the skill you want to create...",
|
|
293
|
+
messagePrefix: "Create a skill: ",
|
|
294
|
+
getContext: (prompt) => `The user wants to create an agent skill. Their description: "${prompt}"
|
|
295
|
+
|
|
296
|
+
Follow the create-skill pattern to build this. Before writing:
|
|
297
|
+
|
|
298
|
+
1. **Determine the skill name** — derive a hyphen-case name from the description (e.g. "code review" → "code-review")
|
|
299
|
+
2. **Determine the skill type** — Pattern (architectural rule), Workflow (step-by-step), or Generator (scaffolding)
|
|
300
|
+
3. **Write the skill** as a personal resource at path "skills/<name>/SKILL.md" using the \`resources\` tool with \`action: "write"\`
|
|
301
|
+
|
|
302
|
+
The skill file MUST have YAML frontmatter with name and description (under 40 words), then markdown with:
|
|
303
|
+
- Clear rule/purpose statement
|
|
304
|
+
- Why this skill exists
|
|
305
|
+
- How to follow it (with code examples where helpful)
|
|
306
|
+
- Common violations to avoid
|
|
307
|
+
- Related skills
|
|
308
|
+
|
|
309
|
+
After creating, update the shared AGENTS.md resource to reference the new skill in its skills table.
|
|
310
|
+
|
|
311
|
+
Keep the skill concise (under 500 lines) and actionable.`,
|
|
312
|
+
},
|
|
313
|
+
job: {
|
|
314
|
+
label: "Schedule Task",
|
|
315
|
+
icon: IconClock,
|
|
316
|
+
placeholder: "Describe what should happen and when...",
|
|
317
|
+
messagePrefix: "Create a recurring job: ",
|
|
318
|
+
getContext: (prompt) => `The user wants to create a recurring job. Their description: "${prompt}"
|
|
319
|
+
|
|
320
|
+
Use the manage-jobs tool with action "create" to create this. You need to:
|
|
321
|
+
1. Derive a hyphen-case name from the description
|
|
322
|
+
2. Convert the schedule to a cron expression (e.g., "every weekday at 9am" → "0 9 * * 1-5")
|
|
323
|
+
3. Write clear, self-contained instructions for what the agent should do each time the job runs
|
|
324
|
+
4. Create it in personal scope
|
|
325
|
+
|
|
326
|
+
The job will run automatically on the schedule. Make the instructions specific — include which actions to call and what to do with results.`,
|
|
327
|
+
},
|
|
328
|
+
automation: {
|
|
329
|
+
label: "Create Automation",
|
|
330
|
+
icon: IconBolt,
|
|
331
|
+
placeholder: "Describe what you want to automate...",
|
|
332
|
+
messagePrefix: "Create an automation: ",
|
|
333
|
+
beforeSend: () => {
|
|
334
|
+
window.dispatchEvent(new CustomEvent("agent-panel:set-mode", {
|
|
335
|
+
detail: { mode: "chat" },
|
|
336
|
+
}));
|
|
337
|
+
},
|
|
338
|
+
getContext: (prompt) => `The user wants to create a new automation. Scope: personal. Their description: "${prompt}"
|
|
339
|
+
|
|
340
|
+
Use manage-automations with action=define to create it. Ask clarifying questions if needed about what event to trigger on, conditions, and what actions to take.`,
|
|
341
|
+
},
|
|
342
|
+
extension: {
|
|
343
|
+
label: "Create Extension",
|
|
344
|
+
icon: IconTool,
|
|
345
|
+
placeholder: "Describe the interactive extension you want to build...",
|
|
346
|
+
messagePrefix: "Create an extension: ",
|
|
347
|
+
getContext: (prompt) => `The user wants to create an interactive extension (sandboxed mini-app). Their description: "${prompt}"
|
|
348
|
+
|
|
349
|
+
Use the create-extension action with Alpine.js HTML content. The extension runs as a sandboxed iframe with Tailwind CSS and modest default canvas padding. For edge-to-edge layouts, put data-extension-layout="full-bleed" on the outermost element.
|
|
350
|
+
|
|
351
|
+
After creating the extension, navigate the user to it with the path returned by create-extension; extension URLs may include a friendly "/extensions/<id>/<slug>" suffix.
|
|
352
|
+
|
|
353
|
+
Make the extension functional and visually polished. Extensions can use extensionFetch() for external API calls, appAction()/appFetch() for app operations and app data writes, extensionData for per-extension persistence, and dbQuery() only for read-only inspection of existing app tables.
|
|
354
|
+
|
|
355
|
+
Prefer appAction()/appFetch() for app data. Some actions return JSON strings for CLI compatibility, so parse string results before counting rows or reading arrays. Do not guess raw SQL table names or columns for app data; use dbQuery() only when the table is known to exist in the current schema.`,
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
function ComposerModeChip({ mode, onRemove, }) {
|
|
359
|
+
const config = COMPOSER_MODE_CONFIGS[mode];
|
|
360
|
+
const Icon = config.icon;
|
|
361
|
+
return (_jsxs("span", { className: "inline-flex items-center gap-1 rounded-md border border-border bg-muted/50 px-1.5 py-0.5 text-xs font-medium text-foreground", children: [_jsx(Icon, { className: "h-3 w-3 text-muted-foreground" }), config.label, _jsx("button", { type: "button", onClick: onRemove, className: "ms-0.5 rounded-sm text-muted-foreground hover:text-foreground cursor-pointer", children: _jsx(IconX, { className: "h-3 w-3" }) })] }));
|
|
362
|
+
}
|
|
363
|
+
function plainTextToDoc(text) {
|
|
364
|
+
const lines = text.length > 0 ? text.split(/\r?\n/) : [""];
|
|
365
|
+
return {
|
|
366
|
+
type: "doc",
|
|
367
|
+
content: lines.map((line) => ({
|
|
368
|
+
type: "paragraph",
|
|
369
|
+
content: line ? [{ type: "text", text: line }] : [],
|
|
370
|
+
})),
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** Tiptap keeps the Editor object truthy after destroy but clears commandManager. */
|
|
374
|
+
export function isComposerEditorUsable(editor) {
|
|
375
|
+
return Boolean(editor && editor.isDestroyed !== true);
|
|
376
|
+
}
|
|
377
|
+
export function createTiptapComposerExtensions(getPlaceholder) {
|
|
378
|
+
return [
|
|
379
|
+
StarterKit.configure({
|
|
380
|
+
heading: false,
|
|
381
|
+
horizontalRule: false,
|
|
382
|
+
bulletList: false,
|
|
383
|
+
orderedList: false,
|
|
384
|
+
listItem: false,
|
|
385
|
+
listKeymap: false,
|
|
386
|
+
blockquote: false,
|
|
387
|
+
codeBlock: false,
|
|
388
|
+
strike: false,
|
|
389
|
+
italic: false,
|
|
390
|
+
bold: false,
|
|
391
|
+
code: false,
|
|
392
|
+
dropcursor: false,
|
|
393
|
+
gapcursor: false,
|
|
394
|
+
link: false,
|
|
395
|
+
trailingNode: false,
|
|
396
|
+
underline: false,
|
|
397
|
+
}),
|
|
398
|
+
Placeholder.configure({
|
|
399
|
+
placeholder: () => getPlaceholder() ?? "",
|
|
400
|
+
emptyEditorClass: "is-editor-empty",
|
|
401
|
+
showOnlyCurrent: false,
|
|
402
|
+
}),
|
|
403
|
+
FileReference,
|
|
404
|
+
SkillReference,
|
|
405
|
+
MentionReference,
|
|
406
|
+
];
|
|
407
|
+
}
|
|
408
|
+
function ModeSelector({ mode, onChange, planModeDisabled = false, planModeDisabledReason = "Open Agent Native Desktop to use Plan mode.", }) {
|
|
409
|
+
const [open, setOpen] = useState(false);
|
|
410
|
+
return (_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("button", { type: "button", "aria-label": mode === "build" ? "Act mode" : "Plan mode", "data-agent-composer-slot": "mode-button", className: "agent-composer-mode-button shrink-0 flex items-center gap-1 rounded-md px-2 py-1 text-[12px] font-medium text-muted-foreground hover:bg-accent/50 hover:text-foreground", children: [mode === "build" ? "Act" : "Plan", _jsx(IconChevronDown, { className: "h-3 w-3 opacity-60" })] }) }), _jsxs(PopoverContent, { side: "top", align: "end", sideOffset: 6, collisionPadding: 8, "data-agent-native-composer-popover": "true", className: "z-[260] w-60 rounded-lg border-border p-0 py-1 shadow-lg", style: { fontSize: 13 }, children: [_jsxs("button", { type: "button", onClick: () => {
|
|
411
|
+
onChange("build");
|
|
412
|
+
setOpen(false);
|
|
413
|
+
}, className: "flex w-full items-center gap-3 px-3 py-2 hover:bg-accent/50 text-start", children: [_jsx(IconPencil, { className: "h-4 w-4 shrink-0 text-muted-foreground" }), _jsxs("div", { className: "flex-1 min-w-0", children: [_jsx("span", { className: "font-medium text-foreground text-[13px]", children: "Act" }), _jsx("p", { className: "text-[11px] text-muted-foreground mt-0.5", children: "Use tools and make approved changes" })] }), mode === "build" && (_jsx(IconCheck, { className: "h-3.5 w-3.5 shrink-0 text-blue-500" }))] }), _jsxs("button", { type: "button", disabled: planModeDisabled, title: planModeDisabled ? planModeDisabledReason : undefined, onClick: () => {
|
|
414
|
+
if (planModeDisabled)
|
|
415
|
+
return;
|
|
416
|
+
onChange("plan");
|
|
417
|
+
setOpen(false);
|
|
418
|
+
}, className: `flex w-full items-center gap-3 px-3 py-2 text-start ${planModeDisabled
|
|
419
|
+
? "cursor-not-allowed opacity-60"
|
|
420
|
+
: "hover:bg-accent/50"}`, children: [_jsx(IconClipboardList, { className: "h-4 w-4 shrink-0 text-muted-foreground" }), _jsxs("div", { className: "flex-1 min-w-0", children: [_jsx("span", { className: "font-medium text-foreground text-[13px]", children: "Plan" }), _jsx("p", { className: "text-[11px] text-muted-foreground mt-0.5", children: planModeDisabled
|
|
421
|
+
? planModeDisabledReason
|
|
422
|
+
: "Read-only research and approval first" })] }), mode === "plan" && !planModeDisabled && (_jsx(IconCheck, { className: "h-3.5 w-3.5 shrink-0 text-blue-500" }))] })] })] }));
|
|
423
|
+
}
|
|
424
|
+
const FRIENDLY_MODEL_NAMES = {
|
|
425
|
+
auto: "Default model",
|
|
426
|
+
"codex-cli": "ChatGPT subscription",
|
|
427
|
+
"claude-fable-5": "Fable 5",
|
|
428
|
+
"kimi-k2-5": "Kimi K2.5",
|
|
429
|
+
"deepseek-v3-1": "DeepSeek v3.1",
|
|
430
|
+
"z-ai/glm-5.2": "GLM 5.2",
|
|
431
|
+
};
|
|
432
|
+
export const MODEL_SELECTOR_POPOVER_STYLE = {
|
|
433
|
+
fontSize: 13,
|
|
434
|
+
maxHeight: "min(500px, var(--radix-popover-content-available-height, 500px))",
|
|
435
|
+
};
|
|
436
|
+
export function shouldShowModelSelectorSkeleton(isLoading, engineCount) {
|
|
437
|
+
return isLoading && engineCount === 0;
|
|
438
|
+
}
|
|
439
|
+
function friendlyModelName(model) {
|
|
440
|
+
if (FRIENDLY_MODEL_NAMES[model])
|
|
441
|
+
return FRIENDLY_MODEL_NAMES[model];
|
|
442
|
+
// Claude: claude-{tier}-{major}[-minor][-dateYYYYMMDD] → Tier Major[.Minor]
|
|
443
|
+
const claude = model.match(/^claude-(opus|sonnet|haiku)-(\d+)(?:-(\d+))?(?:-\d{8,})?$/);
|
|
444
|
+
if (claude) {
|
|
445
|
+
const tier = claude[1][0].toUpperCase() + claude[1].slice(1);
|
|
446
|
+
return `${tier} ${claude[2]}${claude[3] ? `.${claude[3]}` : ""}`;
|
|
447
|
+
}
|
|
448
|
+
// GPT: gpt-{major}-{minor}[-suffix] or gpt-{major}.{minor}[-suffix]
|
|
449
|
+
if (model.startsWith("gpt-")) {
|
|
450
|
+
const rest = model.slice(4);
|
|
451
|
+
const gpt = rest.match(/^(\d+)[.-](\d+)(?:[.-](.+))?$/);
|
|
452
|
+
if (gpt) {
|
|
453
|
+
const suffix = gpt[3]
|
|
454
|
+
? " " +
|
|
455
|
+
gpt[3]
|
|
456
|
+
.split("-")
|
|
457
|
+
.map((s) => s[0].toUpperCase() + s.slice(1))
|
|
458
|
+
.join(" ")
|
|
459
|
+
: "";
|
|
460
|
+
return `GPT-${gpt[1]}.${gpt[2]}${suffix}`;
|
|
461
|
+
}
|
|
462
|
+
return `GPT-${rest}`;
|
|
463
|
+
}
|
|
464
|
+
if (/^o\d/.test(model))
|
|
465
|
+
return model;
|
|
466
|
+
// Gemini: gemini-{major}-{minor}-{variant}[-preview] → Gemini Major.Minor Variant
|
|
467
|
+
const geminiVersioned = model.match(/^gemini-(\d+)-(\d+)-(.+?)(?:-preview)?$/);
|
|
468
|
+
if (geminiVersioned) {
|
|
469
|
+
const variant = geminiVersioned[3]
|
|
470
|
+
.split("-")
|
|
471
|
+
.map((s) => s[0].toUpperCase() + s.slice(1))
|
|
472
|
+
.join(" ");
|
|
473
|
+
return `Gemini ${geminiVersioned[1]}.${geminiVersioned[2]} ${variant}`;
|
|
474
|
+
}
|
|
475
|
+
// Gemini: gemini-{version.parts}[-preview] → Gemini Version Parts
|
|
476
|
+
const gemini = model.match(/^gemini-(.+?)(?:-preview)?$/);
|
|
477
|
+
if (gemini) {
|
|
478
|
+
const parts = gemini[1]
|
|
479
|
+
.split("-")
|
|
480
|
+
.map((s) => s[0].toUpperCase() + s.slice(1))
|
|
481
|
+
.join(" ");
|
|
482
|
+
return `Gemini ${parts}`;
|
|
483
|
+
}
|
|
484
|
+
return model;
|
|
485
|
+
}
|
|
486
|
+
export function compactComposerModelName(model) {
|
|
487
|
+
const gpt56Variant = model.match(/^(?:openai\/)?gpt-5[.-]6[.-](sol|terra|luna)$/i)?.[1];
|
|
488
|
+
if (gpt56Variant) {
|
|
489
|
+
return gpt56Variant[0].toUpperCase() + gpt56Variant.slice(1).toLowerCase();
|
|
490
|
+
}
|
|
491
|
+
return friendlyModelName(model);
|
|
492
|
+
}
|
|
493
|
+
export function compactComposerReasoningEffortLabel(effort) {
|
|
494
|
+
if (effort === "medium" || effort === "auto")
|
|
495
|
+
return "Med";
|
|
496
|
+
if (effort === "minimal")
|
|
497
|
+
return "Min";
|
|
498
|
+
if (effort === "xhigh")
|
|
499
|
+
return "XHigh";
|
|
500
|
+
return reasoningEffortLabel(effort);
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Deduplicate models to only the latest version per family.
|
|
504
|
+
* e.g. [opus-4-7, opus-4-6, opus-4-5] → [opus-4-7]
|
|
505
|
+
*/
|
|
506
|
+
function latestModelsOnly(models) {
|
|
507
|
+
const seen = new Set();
|
|
508
|
+
return models.filter((m) => {
|
|
509
|
+
// Claude: family = tier (opus/sonnet/haiku)
|
|
510
|
+
const claude = m.match(/^claude-(opus|sonnet|haiku)-/);
|
|
511
|
+
if (claude) {
|
|
512
|
+
if (seen.has(claude[1]))
|
|
513
|
+
return false;
|
|
514
|
+
seen.add(claude[1]);
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
// GPT: family = gpt-{major} (e.g. gpt-5.6-sol and gpt-5.6-luna are different)
|
|
518
|
+
// OpenAI reasoning: each is its own family
|
|
519
|
+
// Gemini: family = gemini-{major} + variant
|
|
520
|
+
const gemini = m.match(/^gemini-(\d+(?:\.\d+)?)-(.+?)(?:-preview)?$/);
|
|
521
|
+
if (gemini) {
|
|
522
|
+
const family = gemini[2]; // flash, pro, etc.
|
|
523
|
+
if (seen.has(`gemini-${family}`))
|
|
524
|
+
return false;
|
|
525
|
+
seen.add(`gemini-${family}`);
|
|
526
|
+
return true;
|
|
527
|
+
}
|
|
528
|
+
return true;
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
export function getComposerReasoningEffortOptions(model) {
|
|
532
|
+
return model === "auto"
|
|
533
|
+
? ["low", "medium", "high", "xhigh", "max"]
|
|
534
|
+
: getReasoningEffortOptionsForModel(model);
|
|
535
|
+
}
|
|
536
|
+
function ModelSelector({ model, effort, engines, modelListLoading = false, onChange, onEffortChange, providerConnectStatusEnabled = true, onConnectProvider, onConnectLocalRuntime, imageModel, }) {
|
|
537
|
+
const adapters = useComposerRuntimeAdapters();
|
|
538
|
+
const t = adapters.translate;
|
|
539
|
+
const reasoning = adapters.models?.reasoning;
|
|
540
|
+
const defaultEffort = reasoning?.defaultEffort ?? DEFAULT_REASONING_EFFORT;
|
|
541
|
+
const [open, setOpen] = useState(false);
|
|
542
|
+
const autoModelGroup = engines.find((group) => group.models.includes("auto"));
|
|
543
|
+
const providerGroups = useMemo(() => engines
|
|
544
|
+
.map((group) => ({
|
|
545
|
+
...group,
|
|
546
|
+
models: group.models.filter((candidate) => candidate !== "auto"),
|
|
547
|
+
}))
|
|
548
|
+
.filter((group) => group.models.length > 0), [engines]);
|
|
549
|
+
const effortOptions = reasoning?.getOptionsForModel?.(model) ??
|
|
550
|
+
getComposerReasoningEffortOptions(model);
|
|
551
|
+
const selectedEffort = reasoning?.resolve?.(model, effort) ??
|
|
552
|
+
resolveReasoningEffortSelection(model, effort ?? defaultEffort);
|
|
553
|
+
const effortLabel = reasoning?.label ?? reasoningEffortLabel;
|
|
554
|
+
// Collapse non-selected families by default. The family containing the
|
|
555
|
+
// currently-selected model stays expanded so the user sees their pick at
|
|
556
|
+
// a glance; clicking another family's header expands it inline.
|
|
557
|
+
const selectedGroupKey = useMemo(() => {
|
|
558
|
+
const found = providerGroups.find((g) => g.models.includes(model));
|
|
559
|
+
return found ? `${found.engine}:${found.label}` : null;
|
|
560
|
+
}, [model, providerGroups]);
|
|
561
|
+
const [expandedGroups, setExpandedGroups] = useState(() => new Set(selectedGroupKey ? [selectedGroupKey] : []));
|
|
562
|
+
// Reset expansion when the popover re-opens so the picker always lands
|
|
563
|
+
// on the "selected family expanded, others collapsed" view.
|
|
564
|
+
useEffect(() => {
|
|
565
|
+
if (open) {
|
|
566
|
+
setExpandedGroups(new Set(selectedGroupKey ? [selectedGroupKey] : []));
|
|
567
|
+
}
|
|
568
|
+
}, [open, selectedGroupKey]);
|
|
569
|
+
const toggleGroup = useCallback((key) => {
|
|
570
|
+
setExpandedGroups((prev) => {
|
|
571
|
+
const next = new Set(prev);
|
|
572
|
+
if (next.has(key))
|
|
573
|
+
next.delete(key);
|
|
574
|
+
else
|
|
575
|
+
next.add(key);
|
|
576
|
+
return next;
|
|
577
|
+
});
|
|
578
|
+
}, []);
|
|
579
|
+
// The reasoning effort list is collapsed by default — it's a secondary
|
|
580
|
+
// control most users don't touch, so it stays tucked behind a header that
|
|
581
|
+
// reveals the current effort at a glance. Reset to collapsed on each open.
|
|
582
|
+
const [reasoningExpanded, setReasoningExpanded] = useState(false);
|
|
583
|
+
useEffect(() => {
|
|
584
|
+
if (open)
|
|
585
|
+
setReasoningExpanded(false);
|
|
586
|
+
}, [open]);
|
|
587
|
+
// The optional image-model section follows the same collapsed-by-default
|
|
588
|
+
// pattern; the current selection shows next to the header.
|
|
589
|
+
const [imageExpanded, setImageExpanded] = useState(false);
|
|
590
|
+
useEffect(() => {
|
|
591
|
+
if (open)
|
|
592
|
+
setImageExpanded(false);
|
|
593
|
+
}, [open]);
|
|
594
|
+
const imageModelLabel = imageModel?.options.find((option) => option.value === imageModel.value)
|
|
595
|
+
?.label ?? imageModel?.value;
|
|
596
|
+
const showModelListSkeleton = shouldShowModelSelectorSkeleton(modelListLoading, engines.length);
|
|
597
|
+
// When Builder.io isn't connected, surface a one-click connect path —
|
|
598
|
+
// it unlocks every model family (Claude, OpenAI, Gemini) without the
|
|
599
|
+
// user having to paste individual API keys.
|
|
600
|
+
const builderFlow = adapters.builder.useConnectFlow({
|
|
601
|
+
enabled: providerConnectStatusEnabled,
|
|
602
|
+
trackingSource: "composer_builder_cta",
|
|
603
|
+
});
|
|
604
|
+
const hasConfiguredBuilderModels = providerGroups.some((group) => group.engine === "builder" && group.configured);
|
|
605
|
+
const showBuilderCta = (builderFlow.hasFetchedStatus ||
|
|
606
|
+
(!providerConnectStatusEnabled && !!onConnectProvider)) &&
|
|
607
|
+
!builderFlow.configured &&
|
|
608
|
+
!builderFlow.envManaged &&
|
|
609
|
+
!hasConfiguredBuilderModels;
|
|
610
|
+
const openLlmSettings = useCallback(() => {
|
|
611
|
+
try {
|
|
612
|
+
window.location.hash = "llm";
|
|
613
|
+
}
|
|
614
|
+
catch { }
|
|
615
|
+
window.dispatchEvent(new CustomEvent("agent-panel:open-settings"));
|
|
616
|
+
setOpen(false);
|
|
617
|
+
}, []);
|
|
618
|
+
const connectLocalRuntime = useCallback((engine) => {
|
|
619
|
+
onConnectLocalRuntime?.(engine);
|
|
620
|
+
setOpen(false);
|
|
621
|
+
}, [onConnectLocalRuntime]);
|
|
622
|
+
return (_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("button", { type: "button", "data-agent-composer-slot": "model-button", "aria-label": `Model: ${friendlyModelName(model)}${effortOptions.length > 0
|
|
623
|
+
? `. Reasoning: ${effortLabel(selectedEffort)}`
|
|
624
|
+
: ""}`, className: "agent-composer-model-button flex min-w-0 max-w-[10.5rem] shrink items-center gap-1 rounded-md px-2 py-1 text-[12px] font-medium text-muted-foreground hover:bg-accent/50 hover:text-foreground", children: [_jsx("span", { className: "min-w-0 truncate", children: compactComposerModelName(model) }), effortOptions.length > 0 && (_jsxs("span", { className: "agent-composer-model-effort min-w-0 shrink truncate text-muted-foreground/70", children: ["\u00B7 ", compactComposerReasoningEffortLabel(selectedEffort)] })), _jsx(IconChevronDown, { className: "h-3 w-3 shrink-0 opacity-60" })] }) }), _jsxs(PopoverContent, { side: "top", align: "end", sideOffset: 6, collisionPadding: 8, "data-agent-native-composer-popover": "true", className: "z-[260] box-border w-72 overflow-y-auto rounded-lg border-border p-0 py-1 shadow-lg", style: MODEL_SELECTOR_POPOVER_STYLE, children: [showBuilderCta && (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", onClick: () => {
|
|
625
|
+
if (onConnectProvider) {
|
|
626
|
+
onConnectProvider();
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
builderFlow.start();
|
|
630
|
+
}
|
|
631
|
+
}, disabled: !onConnectProvider && builderFlow.connecting, className: "flex w-full items-start gap-2 px-3 py-2 text-start hover:bg-accent/50 disabled:opacity-60", children: [_jsx(IconPlugConnected, { className: "h-4 w-4 shrink-0 mt-0.5 text-blue-500" }), _jsxs("span", { className: "flex-1 min-w-0", children: [_jsx("span", { className: "block text-[12px] font-medium text-foreground", children: !onConnectProvider && builderFlow.connecting
|
|
632
|
+
? t("agentPanel.connectingBuilder", {
|
|
633
|
+
defaultValue: "Connecting Builder.io…",
|
|
634
|
+
})
|
|
635
|
+
: t("agentPanel.connectBuilderIo", {
|
|
636
|
+
defaultValue: "Connect Builder.io",
|
|
637
|
+
}) }), _jsx("span", { className: "block text-[11px] text-muted-foreground", children: t("agentPanel.builderModelCredits", {
|
|
638
|
+
defaultValue: "Free credits for Claude, OpenAI & Gemini",
|
|
639
|
+
}) })] })] }), _jsxs("button", { type: "button", onClick: openLlmSettings, className: "flex w-full items-start gap-2 px-3 py-2 text-start hover:bg-accent/50", children: [_jsx(IconKey, { className: "mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block text-[12px] font-medium text-foreground", children: t("agentPanel.addOwnKeys", {
|
|
640
|
+
defaultValue: "Add your own keys",
|
|
641
|
+
}) }), _jsx("span", { className: "block text-[11px] text-muted-foreground", children: t("agentPanel.configureProviderKeys", {
|
|
642
|
+
defaultValue: "Configure Anthropic, OpenAI, or another provider",
|
|
643
|
+
}) })] })] }), _jsx("div", { className: "my-1 border-t border-border" })] })), imageModel && imageModel.options.length > 0 && (_jsxs(_Fragment, { children: [_jsx("div", { className: "flex items-center hover:bg-accent/30", children: _jsxs("button", { type: "button", "aria-expanded": imageExpanded, onClick: () => setImageExpanded((prev) => !prev), className: "flex flex-1 min-w-0 items-center gap-1.5 px-2 py-1.5 cursor-pointer text-start", children: [imageExpanded ? (_jsx(IconChevronDown, { className: "h-3 w-3 shrink-0 text-muted-foreground" })) : (_jsx(IconChevronRight, { className: "h-3 w-3 shrink-0 text-muted-foreground rtl:-scale-x-100" })), _jsx("span", { className: "text-[11px] font-medium text-muted-foreground uppercase tracking-wide shrink-0", children: imageModel.label ?? "Image model" }), !imageExpanded && imageModelLabel && (_jsx("span", { className: "text-[11px] text-muted-foreground/80 truncate", children: imageModelLabel }))] }) }), imageExpanded &&
|
|
644
|
+
imageModel.options.map((option) => (_jsxs("button", { type: "button", onClick: () => {
|
|
645
|
+
imageModel.onChange(option.value);
|
|
646
|
+
setImageExpanded(false);
|
|
647
|
+
}, className: "flex w-full items-center gap-3 ps-7 pe-3 py-1.5 text-start hover:bg-accent/50", children: [_jsx("span", { className: "flex-1 min-w-0 text-[13px] text-foreground truncate", children: option.label }), option.value === imageModel.value && (_jsx(IconCheck, { className: "h-3.5 w-3.5 shrink-0 text-blue-500" }))] }, option.value))), _jsx("div", { className: "my-1 border-t border-border" })] })), showModelListSkeleton && _jsx(ModelSelectorSkeleton, {}), autoModelGroup && (_jsxs("button", { type: "button", onClick: () => {
|
|
648
|
+
onChange("auto", autoModelGroup.engine);
|
|
649
|
+
setOpen(false);
|
|
650
|
+
}, className: "flex w-full items-center gap-3 px-3 py-1.5 text-start hover:bg-accent/50", children: [_jsx("span", { className: "flex-1 min-w-0 text-[13px] text-foreground truncate", children: "Auto" }), model === "auto" && (_jsx(IconCheck, { className: "h-3.5 w-3.5 shrink-0 text-blue-500" }))] })), autoModelGroup && providerGroups.length > 0 && (_jsx("div", { className: "my-1 border-t border-border" })), providerGroups.map((group) => {
|
|
651
|
+
const models = latestModelsOnly(group.models);
|
|
652
|
+
const groupKey = `${group.engine}:${group.label}`;
|
|
653
|
+
const isExpanded = expandedGroups.has(groupKey);
|
|
654
|
+
const ChevronIcon = isExpanded ? IconChevronDown : IconChevronRight;
|
|
655
|
+
return (_jsxs("div", { children: [_jsxs("div", { className: "flex items-center hover:bg-accent/30", children: [_jsxs("button", { type: "button", "aria-expanded": isExpanded, onClick: () => toggleGroup(groupKey), className: "flex flex-1 min-w-0 items-center gap-1.5 px-2 py-1.5 cursor-pointer text-start", children: [_jsx(ChevronIcon, { className: "h-3 w-3 shrink-0 text-muted-foreground rtl:-scale-x-100" }), _jsx("span", { className: "text-[11px] font-medium text-muted-foreground uppercase tracking-wide shrink-0", children: group.label }), !isExpanded && groupKey === selectedGroupKey && (_jsx("span", { className: "text-[11px] text-muted-foreground/80 truncate", children: friendlyModelName(model) }))] }), !group.configured && (_jsx("button", { type: "button", className: "text-[10px] text-muted-foreground/60 hover:text-foreground cursor-pointer pe-3 py-1.5", onClick: () => group.engine === "codex-cli" && onConnectLocalRuntime
|
|
656
|
+
? connectLocalRuntime(group.engine)
|
|
657
|
+
: openLlmSettings(), children: group.engine === "codex-cli" && onConnectLocalRuntime
|
|
658
|
+
? "sign in"
|
|
659
|
+
: "needs API key" }))] }), isExpanded &&
|
|
660
|
+
models.map((m) => (_jsxs("button", { type: "button", onClick: () => {
|
|
661
|
+
if (!group.configured) {
|
|
662
|
+
if (group.engine === "codex-cli" &&
|
|
663
|
+
onConnectLocalRuntime) {
|
|
664
|
+
connectLocalRuntime(group.engine);
|
|
665
|
+
}
|
|
666
|
+
else {
|
|
667
|
+
openLlmSettings();
|
|
668
|
+
}
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
onChange(m, group.engine);
|
|
672
|
+
const nextOptions = getReasoningEffortOptionsForModel(m);
|
|
673
|
+
if (nextOptions.length > 0 &&
|
|
674
|
+
!nextOptions.includes(selectedEffort)) {
|
|
675
|
+
onEffortChange?.(defaultEffort);
|
|
676
|
+
}
|
|
677
|
+
setOpen(false);
|
|
678
|
+
}, className: `flex w-full items-center gap-3 ps-7 pe-3 py-1.5 text-start ${group.configured
|
|
679
|
+
? "hover:bg-accent/50"
|
|
680
|
+
: "opacity-40 cursor-default"}`, children: [_jsx("span", { className: "flex-1 min-w-0 text-[13px] text-foreground truncate", children: friendlyModelName(m) }), m === model && group.configured && (_jsx(IconCheck, { className: "h-3.5 w-3.5 shrink-0 text-blue-500" }))] }, m)))] }, groupKey));
|
|
681
|
+
}), !showModelListSkeleton && effortOptions.length > 0 && (_jsxs(_Fragment, { children: [_jsx("div", { className: "my-1 border-t border-border" }), _jsx("div", { className: "flex items-center hover:bg-accent/30", children: _jsxs("button", { type: "button", "aria-expanded": reasoningExpanded, onClick: () => setReasoningExpanded((prev) => !prev), className: "flex flex-1 min-w-0 items-center gap-1.5 px-2 py-1.5 cursor-pointer text-start", children: [reasoningExpanded ? (_jsx(IconChevronDown, { className: "h-3 w-3 shrink-0 text-muted-foreground" })) : (_jsx(IconChevronRight, { className: "h-3 w-3 shrink-0 text-muted-foreground rtl:-scale-x-100" })), _jsx("span", { className: "text-[11px] font-medium text-muted-foreground uppercase tracking-wide shrink-0", children: "Reasoning" }), !reasoningExpanded && (_jsx("span", { className: "text-[11px] text-muted-foreground/80 truncate", children: effortLabel(selectedEffort) }))] }) }), reasoningExpanded &&
|
|
682
|
+
effortOptions.map((option) => (_jsxs("button", { type: "button", onClick: () => onEffortChange?.(option), className: "flex w-full items-center gap-3 ps-7 pe-3 py-1.5 text-start hover:bg-accent/50", children: [_jsx("span", { className: "flex-1 min-w-0 text-[13px] text-foreground truncate", children: effortLabel(option) }), option === selectedEffort && (_jsx(IconCheck, { className: "h-3.5 w-3.5 shrink-0 text-blue-500" }))] }, option)))] }))] })] }));
|
|
683
|
+
}
|
|
684
|
+
function ModelSelectorSkeleton() {
|
|
685
|
+
return (_jsxs("div", { className: "space-y-1 px-2 py-2", role: "status", "aria-label": "Loading models", children: [_jsx("span", { className: "sr-only", children: "Loading models\u2026" }), ["w-24", "w-32", "w-20", "w-28"].map((width, index) => (_jsxs("div", { className: "flex items-center gap-1.5 px-1 py-1.5", children: [_jsx(Skeleton, { className: "size-3 rounded-sm" }), _jsx(Skeleton, { className: `h-3 ${width}` })] }, index)))] }));
|
|
686
|
+
}
|
|
687
|
+
export function TiptapComposer({ placeholder = "Message agent...", disabled = false, focusRef, initialText, initialTextKey, onSubmit, onBeforeSubmit, clearOnSubmit = true, onTextChange, actionButton, extraActionButton, stopButton, attachButton, modeControl, toolbarSlot, layoutVariant = "default", slashCommands = [], slashSkills = [], includeDefaultSlashCommands = true, includeDefaultSlashSkills = true, onSlashCommand, execMode, onExecModeChange, planModeDisabled = false, planModeDisabledReason, voiceEnabled = DEFAULT_VOICE_DICTATION_ENABLED, selectedModel, selectedEffort, availableModels, modelListLoading, onModelChange, onEffortChange, providerConnectStatusEnabled, onConnectProvider, onConnectLocalRuntime, imageModelMenu, draftScope, contextItems = [], onRemoveContextItem, plusMenuMode = "full", interceptBuildRequestsForBuilder = false, onAttachmentError, }) {
|
|
688
|
+
const adapters = useComposerRuntimeAdapters();
|
|
689
|
+
const t = adapters.translate;
|
|
690
|
+
const [popover, setPopover] = useState(null);
|
|
691
|
+
const popoverRef = useRef(null);
|
|
692
|
+
const composerRuntime = useComposerRuntime();
|
|
693
|
+
const lastComposerRuntimeSyncRef = useRef(null);
|
|
694
|
+
const submitInFlightRef = useRef(false);
|
|
695
|
+
const [editorHasText, setEditorHasText] = useState(false);
|
|
696
|
+
const [slotReferences, setSlotReferences] = useState([]);
|
|
697
|
+
const [selectedContextItemKey, setSelectedContextItemKey] = useState(null);
|
|
698
|
+
const composerText = useComposer((state) => state.text);
|
|
699
|
+
const composerAttachments = useComposer((state) => state.attachments);
|
|
700
|
+
const canSend = canSubmitComposerContent({
|
|
701
|
+
hasEditorContent: editorHasText || slotReferences.length > 0,
|
|
702
|
+
attachmentCount: composerAttachments.length,
|
|
703
|
+
disabled,
|
|
704
|
+
});
|
|
705
|
+
const primaryAction = resolveComposerPrimaryAction({
|
|
706
|
+
canSubmit: canSend,
|
|
707
|
+
hasStopButton: Boolean(stopButton),
|
|
708
|
+
});
|
|
709
|
+
const hasContextRows = contextItems.length > 0 || slotReferences.length > 0;
|
|
710
|
+
const [composerMode, setComposerMode] = useState(null);
|
|
711
|
+
const composerModeRef = useRef(null);
|
|
712
|
+
const isMac = typeof navigator !== "undefined" &&
|
|
713
|
+
/Mac|iPhone|iPad/.test(navigator.userAgent);
|
|
714
|
+
// Refs for values accessed in handleKeyDown (ProseMirror doesn't re-bind)
|
|
715
|
+
const popoverStateRef = useRef(null);
|
|
716
|
+
const onAttachmentErrorRef = useRef(onAttachmentError);
|
|
717
|
+
onAttachmentErrorRef.current = onAttachmentError;
|
|
718
|
+
const execModeRef = useRef(execMode);
|
|
719
|
+
execModeRef.current = execMode;
|
|
720
|
+
const onExecModeChangeRef = useRef(onExecModeChange);
|
|
721
|
+
onExecModeChangeRef.current = onExecModeChange;
|
|
722
|
+
const planModeDisabledRef = useRef(planModeDisabled);
|
|
723
|
+
planModeDisabledRef.current = planModeDisabled;
|
|
724
|
+
const { items: mentionItems, isLoading: mentionsLoading } = useMentionSearch(popover?.type === "@" ? popover.query : "", popover?.type === "@");
|
|
725
|
+
const filteredMentionItems = useMemo(() => filterMentionItemsForSlots(mentionItems, slotReferences), [mentionItems, slotReferences]);
|
|
726
|
+
const { skills, hint, isLoading: skillsLoading, } = useSkills(includeDefaultSlashSkills && popover?.type === "/");
|
|
727
|
+
const allSlashCommands = useMemo(() => mergeSlashCommands([
|
|
728
|
+
...(includeDefaultSlashCommands ? BUILT_IN_COMMANDS : []),
|
|
729
|
+
...slashCommands,
|
|
730
|
+
]), [includeDefaultSlashCommands, slashCommands]);
|
|
731
|
+
const allSlashSkills = useMemo(() => mergeSlashSkills([
|
|
732
|
+
...(includeDefaultSlashSkills ? skills : []),
|
|
733
|
+
...slashSkills,
|
|
734
|
+
]), [includeDefaultSlashSkills, skills, slashSkills]);
|
|
735
|
+
const filteredCommands = useMemo(() => {
|
|
736
|
+
if (!popover || popover.type !== "/")
|
|
737
|
+
return allSlashCommands;
|
|
738
|
+
const q = popover.query.toLowerCase();
|
|
739
|
+
if (!q)
|
|
740
|
+
return allSlashCommands;
|
|
741
|
+
return allSlashCommands.filter((c) => c.name.toLowerCase().includes(q) ||
|
|
742
|
+
c.description.toLowerCase().includes(q));
|
|
743
|
+
}, [allSlashCommands, popover]);
|
|
744
|
+
const filteredSkills = useMemo(() => {
|
|
745
|
+
if (!popover || popover.type !== "/")
|
|
746
|
+
return allSlashSkills;
|
|
747
|
+
const q = popover.query.toLowerCase();
|
|
748
|
+
if (!q)
|
|
749
|
+
return allSlashSkills;
|
|
750
|
+
return allSlashSkills.filter((s) => s.name.toLowerCase().includes(q) ||
|
|
751
|
+
s.description?.toLowerCase().includes(q));
|
|
752
|
+
}, [allSlashSkills, popover]);
|
|
753
|
+
// Keep refs in sync with state
|
|
754
|
+
const mentionItemsRef = useRef(filteredMentionItems);
|
|
755
|
+
mentionItemsRef.current = filteredMentionItems;
|
|
756
|
+
const filteredCommandsRef = useRef(filteredCommands);
|
|
757
|
+
filteredCommandsRef.current = filteredCommands;
|
|
758
|
+
const filteredSkillsRef = useRef(filteredSkills);
|
|
759
|
+
filteredSkillsRef.current = filteredSkills;
|
|
760
|
+
const onSlashCommandRef = useRef(onSlashCommand);
|
|
761
|
+
onSlashCommandRef.current = onSlashCommand;
|
|
762
|
+
const onTextChangeRef = useRef(onTextChange);
|
|
763
|
+
onTextChangeRef.current = onTextChange;
|
|
764
|
+
const contextItemsRef = useRef(contextItems);
|
|
765
|
+
contextItemsRef.current = contextItems;
|
|
766
|
+
const onRemoveContextItemRef = useRef(onRemoveContextItem);
|
|
767
|
+
onRemoveContextItemRef.current = onRemoveContextItem;
|
|
768
|
+
const selectedContextItemKeyRef = useRef(null);
|
|
769
|
+
selectedContextItemKeyRef.current = selectedContextItemKey;
|
|
770
|
+
const initialTextKeyRef = useRef(undefined);
|
|
771
|
+
const seenReferenceInsertIdsRef = useRef(new Set());
|
|
772
|
+
useEffect(() => {
|
|
773
|
+
if (selectedContextItemKey &&
|
|
774
|
+
!contextItems.some((item) => item.key === selectedContextItemKey)) {
|
|
775
|
+
selectedContextItemKeyRef.current = null;
|
|
776
|
+
setSelectedContextItemKey(null);
|
|
777
|
+
}
|
|
778
|
+
}, [contextItems, selectedContextItemKey]);
|
|
779
|
+
const closePopover = useCallback(() => {
|
|
780
|
+
setPopover(null);
|
|
781
|
+
popoverStateRef.current = null;
|
|
782
|
+
}, []);
|
|
783
|
+
// Persist draft to localStorage so hot-reloads don't lose the prompt
|
|
784
|
+
const draftKey = getComposerDraftKey(draftScope);
|
|
785
|
+
const draftTimerRef = useRef(undefined);
|
|
786
|
+
useEffect(() => {
|
|
787
|
+
return () => {
|
|
788
|
+
clearTimeout(draftTimerRef.current);
|
|
789
|
+
};
|
|
790
|
+
}, []);
|
|
791
|
+
useEffect(() => {
|
|
792
|
+
lastComposerRuntimeSyncRef.current = null;
|
|
793
|
+
}, [composerRuntime]);
|
|
794
|
+
// Tiptap reads extension config once at init; ref keeps runtime prop
|
|
795
|
+
// changes visible to Placeholder's function form.
|
|
796
|
+
const placeholderRef = useRef(placeholder);
|
|
797
|
+
useEffect(() => {
|
|
798
|
+
placeholderRef.current = composerMode
|
|
799
|
+
? COMPOSER_MODE_CONFIGS[composerMode].placeholder
|
|
800
|
+
: placeholder;
|
|
801
|
+
}, [placeholder, composerMode]);
|
|
802
|
+
const editor = useEditor({
|
|
803
|
+
extensions: createTiptapComposerExtensions(() => placeholderRef.current),
|
|
804
|
+
editable: !disabled,
|
|
805
|
+
onCreate: ({ editor: ed }) => {
|
|
806
|
+
// Restore draft on mount
|
|
807
|
+
try {
|
|
808
|
+
if (initialText !== undefined) {
|
|
809
|
+
ed.commands.setContent(plainTextToDoc(initialText));
|
|
810
|
+
ed.commands.focus("end");
|
|
811
|
+
setEditorHasText(composerDocumentHasContent(ed.state.doc));
|
|
812
|
+
initialTextKeyRef.current = initialTextKey ?? initialText;
|
|
813
|
+
}
|
|
814
|
+
else {
|
|
815
|
+
const saved = localStorage.getItem(draftKey);
|
|
816
|
+
if (saved) {
|
|
817
|
+
ed.commands.setContent(saved);
|
|
818
|
+
ed.commands.focus("end");
|
|
819
|
+
setEditorHasText(composerDocumentHasContent(ed.state.doc));
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
onTextChangeRef.current?.(ed.state.doc.textContent.trim());
|
|
823
|
+
}
|
|
824
|
+
catch { }
|
|
825
|
+
},
|
|
826
|
+
onUpdate: ({ editor: ed }) => {
|
|
827
|
+
// Drive the send button's enabled state from the actual editor contents;
|
|
828
|
+
// the composer runtime is only synced on submit, so its isEmpty lags.
|
|
829
|
+
setEditorHasText(composerDocumentHasContent(ed.state.doc));
|
|
830
|
+
onTextChangeRef.current?.(ed.state.doc.textContent.trim());
|
|
831
|
+
// Debounce-save draft to localStorage
|
|
832
|
+
clearTimeout(draftTimerRef.current);
|
|
833
|
+
draftTimerRef.current = setTimeout(() => {
|
|
834
|
+
try {
|
|
835
|
+
const html = ed.getHTML();
|
|
836
|
+
const isEmpty = !composerDocumentHasContent(ed.state.doc);
|
|
837
|
+
if (isEmpty) {
|
|
838
|
+
localStorage.removeItem(draftKey);
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
localStorage.setItem(draftKey, html);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
catch { }
|
|
845
|
+
}, 300);
|
|
846
|
+
},
|
|
847
|
+
onSelectionUpdate: ({ editor: ed }) => {
|
|
848
|
+
const { from, to } = ed.state.selection;
|
|
849
|
+
if (selectedContextItemKeyRef.current && (from !== to || from > 1)) {
|
|
850
|
+
selectedContextItemKeyRef.current = null;
|
|
851
|
+
setSelectedContextItemKey(null);
|
|
852
|
+
}
|
|
853
|
+
},
|
|
854
|
+
editorProps: {
|
|
855
|
+
attributes: {
|
|
856
|
+
"data-agent-composer-variant": layoutVariant,
|
|
857
|
+
"data-agent-composer-slot": "editor-input",
|
|
858
|
+
class: "agent-composer-prosemirror flex-1 resize-none bg-transparent text-sm text-foreground outline-none leading-[1.625rem] min-h-[3.25rem] max-h-[10rem] overflow-y-auto",
|
|
859
|
+
},
|
|
860
|
+
handlePaste: (_view, event) => {
|
|
861
|
+
const paste = readClipboardPaste(event.clipboardData);
|
|
862
|
+
const pastedText = paste.text;
|
|
863
|
+
const files = Array.from(event.clipboardData?.files ?? []).filter((file) => file.type.startsWith("image/"));
|
|
864
|
+
if (files.length > 0) {
|
|
865
|
+
event.preventDefault();
|
|
866
|
+
const attachments = files.map((file) => {
|
|
867
|
+
// SimpleImageAttachmentAdapter uses file.name as the attachment id.
|
|
868
|
+
// Clipboard images (e.g. screenshots) are typically all named
|
|
869
|
+
// "image.png", so a second paste would replace the first instead of
|
|
870
|
+
// appending. Prepend a unique token so each paste gets a distinct id.
|
|
871
|
+
const uniqueName = `${Date.now()}-${Math.random().toString(36).slice(2)}-${file.name}`;
|
|
872
|
+
return new File([file], uniqueName, { type: file.type });
|
|
873
|
+
});
|
|
874
|
+
// Google Docs rich clipboard payloads can contain both embedded
|
|
875
|
+
// image files and the document text. Since handling files means we
|
|
876
|
+
// prevent Tiptap's default paste, preserve any text as its own chip
|
|
877
|
+
// instead of silently dropping the source material.
|
|
878
|
+
if (pastedText.trim()) {
|
|
879
|
+
attachments.push(createPastedAttachmentFile(paste));
|
|
880
|
+
}
|
|
881
|
+
void Promise.all(attachments.map((file) => composerRuntime.addAttachment(file))).catch((error) => {
|
|
882
|
+
const msg = error instanceof Error
|
|
883
|
+
? error.message
|
|
884
|
+
: "Could not attach the pasted image. Try a different format.";
|
|
885
|
+
onAttachmentErrorRef.current?.(msg);
|
|
886
|
+
});
|
|
887
|
+
return true;
|
|
888
|
+
}
|
|
889
|
+
// Page-sized pastes turn into a `Pasted text` attachment chip so the
|
|
890
|
+
// prompt stays readable while normal paragraphs and lists stay inline.
|
|
891
|
+
// When the paste is HTML (e.g. an Alpine.js extension or a document the
|
|
892
|
+
// user wants hosted), it's stored as a real .html attachment so it
|
|
893
|
+
// travels the same rail as uploading that file — the agent reads it
|
|
894
|
+
// verbatim via contentFromAttachment instead of retyping it inline,
|
|
895
|
+
// which cuts off mid-stream on large files and triggers a spin.
|
|
896
|
+
if (shouldConvertClipboardToAttachment(paste)) {
|
|
897
|
+
event.preventDefault();
|
|
898
|
+
void composerRuntime
|
|
899
|
+
.addAttachment(createPastedAttachmentFile(paste))
|
|
900
|
+
.catch((error) => {
|
|
901
|
+
const msg = error instanceof Error
|
|
902
|
+
? error.message
|
|
903
|
+
: "Could not attach the pasted text.";
|
|
904
|
+
onAttachmentErrorRef.current?.(msg);
|
|
905
|
+
});
|
|
906
|
+
return true;
|
|
907
|
+
}
|
|
908
|
+
return false;
|
|
909
|
+
},
|
|
910
|
+
handleDrop: (_view, event) => {
|
|
911
|
+
// Drag-and-drop files (decks, images, PDFs, etc.) into the composer.
|
|
912
|
+
// Mark handled drops as consumed so the chat-wide drop target does not
|
|
913
|
+
// add the same file a second time.
|
|
914
|
+
return handleComposerFileDrop({
|
|
915
|
+
event: event,
|
|
916
|
+
addAttachment: (file) => composerRuntime.addAttachment(file),
|
|
917
|
+
onError: (error) => {
|
|
918
|
+
const msg = error instanceof Error
|
|
919
|
+
? error.message
|
|
920
|
+
: "Could not attach the dropped file. Try a different format.";
|
|
921
|
+
onAttachmentErrorRef.current?.(msg);
|
|
922
|
+
},
|
|
923
|
+
});
|
|
924
|
+
},
|
|
925
|
+
handleKeyDown: (view, event) => {
|
|
926
|
+
const pop = popoverStateRef.current;
|
|
927
|
+
// Handle popover keyboard nav
|
|
928
|
+
if (pop) {
|
|
929
|
+
if (event.key === "ArrowUp") {
|
|
930
|
+
event.preventDefault();
|
|
931
|
+
popoverRef.current?.moveUp();
|
|
932
|
+
return true;
|
|
933
|
+
}
|
|
934
|
+
if (event.key === "ArrowDown") {
|
|
935
|
+
event.preventDefault();
|
|
936
|
+
popoverRef.current?.moveDown();
|
|
937
|
+
return true;
|
|
938
|
+
}
|
|
939
|
+
if (event.key === "Enter") {
|
|
940
|
+
event.preventDefault();
|
|
941
|
+
const idx = popoverRef.current?.getSelectedIndex() ?? 0;
|
|
942
|
+
const currentCommands = filteredCommandsRef.current;
|
|
943
|
+
const currentSkills = filteredSkillsRef.current;
|
|
944
|
+
if (pop.type === "@") {
|
|
945
|
+
const item = popoverRef.current?.getSelectedMention();
|
|
946
|
+
if (item)
|
|
947
|
+
selectMention(view, pop, item);
|
|
948
|
+
}
|
|
949
|
+
else if (pop.type === "/") {
|
|
950
|
+
const cmd = popoverRef.current?.getSelectedCommand();
|
|
951
|
+
if (cmd) {
|
|
952
|
+
executeCommand(view, pop, cmd);
|
|
953
|
+
}
|
|
954
|
+
else {
|
|
955
|
+
const skillIdx = idx - currentCommands.length;
|
|
956
|
+
if (currentSkills[skillIdx]) {
|
|
957
|
+
selectSkill(view, pop, currentSkills[skillIdx]);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
return true;
|
|
962
|
+
}
|
|
963
|
+
if (event.key === "Escape") {
|
|
964
|
+
event.preventDefault();
|
|
965
|
+
popoverStateRef.current = null;
|
|
966
|
+
setPopover(null);
|
|
967
|
+
return true;
|
|
968
|
+
}
|
|
969
|
+
if (event.key === " " && pop.query === "") {
|
|
970
|
+
popoverStateRef.current = null;
|
|
971
|
+
setPopover(null);
|
|
972
|
+
return false;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
const { from, to } = view.state.selection;
|
|
976
|
+
const cursorAtStart = from === to && from <= 1;
|
|
977
|
+
if (event.key === "Backspace" && onRemoveContextItemRef.current) {
|
|
978
|
+
const chipAction = resolveContextChipBackspaceAction({
|
|
979
|
+
contextItemKeys: contextItemsRef.current.map((item) => item.key),
|
|
980
|
+
selectedKey: selectedContextItemKeyRef.current,
|
|
981
|
+
cursorAtStart,
|
|
982
|
+
});
|
|
983
|
+
if (chipAction) {
|
|
984
|
+
event.preventDefault();
|
|
985
|
+
if (chipAction.type === "select") {
|
|
986
|
+
selectedContextItemKeyRef.current = chipAction.key;
|
|
987
|
+
setSelectedContextItemKey(chipAction.key);
|
|
988
|
+
}
|
|
989
|
+
else {
|
|
990
|
+
selectedContextItemKeyRef.current = null;
|
|
991
|
+
setSelectedContextItemKey(null);
|
|
992
|
+
contextItemsRef.current = contextItemsRef.current.filter((item) => item.key !== chipAction.key);
|
|
993
|
+
onRemoveContextItemRef.current?.(chipAction.key);
|
|
994
|
+
}
|
|
995
|
+
return true;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (selectedContextItemKeyRef.current) {
|
|
999
|
+
selectedContextItemKeyRef.current = null;
|
|
1000
|
+
setSelectedContextItemKey(null);
|
|
1001
|
+
}
|
|
1002
|
+
// Backspace removes composer mode chip when editor is empty
|
|
1003
|
+
if (event.key === "Backspace" && composerModeRef.current) {
|
|
1004
|
+
if (view.state.doc.textContent.trim() === "" &&
|
|
1005
|
+
from === to &&
|
|
1006
|
+
from <= 1) {
|
|
1007
|
+
setComposerMode(null);
|
|
1008
|
+
composerModeRef.current = null;
|
|
1009
|
+
return true;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
// Keyboard shortcut toggles Act/Plan mode from inside the editor.
|
|
1013
|
+
if (event.key === "Tab" && event.shiftKey) {
|
|
1014
|
+
event.preventDefault();
|
|
1015
|
+
const current = execModeRef.current;
|
|
1016
|
+
const cb = onExecModeChangeRef.current;
|
|
1017
|
+
if (current && cb) {
|
|
1018
|
+
const next = current === "build" ? "plan" : "build";
|
|
1019
|
+
if (next !== "plan" || !planModeDisabledRef.current) {
|
|
1020
|
+
cb(next);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
return true;
|
|
1024
|
+
}
|
|
1025
|
+
// Submit on Enter. Shift+Enter inserts a newline and keeps the
|
|
1026
|
+
// composer scrolled to the caret.
|
|
1027
|
+
// Cmd+Enter on macOS / Ctrl+Enter elsewhere marks the submit queued.
|
|
1028
|
+
if (event.key === "Enter" && event.shiftKey) {
|
|
1029
|
+
event.preventDefault();
|
|
1030
|
+
return insertComposerHardBreakAndScrollIntoView(view);
|
|
1031
|
+
}
|
|
1032
|
+
const submitIntent = getComposerSubmitIntentForEnterKey(event, isMac);
|
|
1033
|
+
if (submitIntent) {
|
|
1034
|
+
event.preventDefault();
|
|
1035
|
+
void submitComposer(submitIntent);
|
|
1036
|
+
return true;
|
|
1037
|
+
}
|
|
1038
|
+
// Detect @ trigger — only when preceded by start-of-text, space, or newline
|
|
1039
|
+
// (not after alphanumeric chars, which would indicate an email address)
|
|
1040
|
+
if (event.key === "@") {
|
|
1041
|
+
const { from } = view.state.selection;
|
|
1042
|
+
const textBefore = view.state.doc.textBetween(Math.max(0, from - 1), from);
|
|
1043
|
+
if (from === 1 || textBefore === "" || /\s/.test(textBefore)) {
|
|
1044
|
+
const position = getComposerPopoverPosition(view, from);
|
|
1045
|
+
if (!position)
|
|
1046
|
+
return false;
|
|
1047
|
+
setTimeout(() => {
|
|
1048
|
+
const state = {
|
|
1049
|
+
type: "@",
|
|
1050
|
+
position,
|
|
1051
|
+
startPos: view.state.selection.from,
|
|
1052
|
+
query: "",
|
|
1053
|
+
};
|
|
1054
|
+
popoverStateRef.current = state;
|
|
1055
|
+
setPopover(state);
|
|
1056
|
+
}, 0);
|
|
1057
|
+
}
|
|
1058
|
+
return false;
|
|
1059
|
+
}
|
|
1060
|
+
// Detect / trigger (only at start of line or after whitespace)
|
|
1061
|
+
if (event.key === "/") {
|
|
1062
|
+
const { from } = view.state.selection;
|
|
1063
|
+
const textBefore = view.state.doc.textBetween(Math.max(0, from - 1), from);
|
|
1064
|
+
if (from === 1 || textBefore === "" || /\s/.test(textBefore)) {
|
|
1065
|
+
const position = getComposerPopoverPosition(view, from);
|
|
1066
|
+
if (!position)
|
|
1067
|
+
return false;
|
|
1068
|
+
setTimeout(() => {
|
|
1069
|
+
const state = {
|
|
1070
|
+
type: "/",
|
|
1071
|
+
position,
|
|
1072
|
+
startPos: view.state.selection.from,
|
|
1073
|
+
query: "",
|
|
1074
|
+
};
|
|
1075
|
+
popoverStateRef.current = state;
|
|
1076
|
+
setPopover(state);
|
|
1077
|
+
}, 0);
|
|
1078
|
+
}
|
|
1079
|
+
return false;
|
|
1080
|
+
}
|
|
1081
|
+
return false;
|
|
1082
|
+
},
|
|
1083
|
+
},
|
|
1084
|
+
});
|
|
1085
|
+
// A tab can stay mounted while becoming the active composer later. Publish
|
|
1086
|
+
// its existing draft when the host starts observing it so contextual UI is
|
|
1087
|
+
// correct immediately after a tab switch, not only after the next keystroke.
|
|
1088
|
+
useEffect(() => {
|
|
1089
|
+
if (!isComposerEditorUsable(editor) || !onTextChange)
|
|
1090
|
+
return;
|
|
1091
|
+
onTextChange(editor.state.doc.textContent.trim());
|
|
1092
|
+
}, [editor, onTextChange]);
|
|
1093
|
+
const insertReference = useCallback((ref) => {
|
|
1094
|
+
const normalized = adapters.agentChat.normalizeReference(ref);
|
|
1095
|
+
const ed = editor;
|
|
1096
|
+
if (!normalized || !isComposerEditorUsable(ed))
|
|
1097
|
+
return;
|
|
1098
|
+
if (normalized.slotKey) {
|
|
1099
|
+
setSlotReferences((current) => applySlotReferenceChanges(current, [normalized]));
|
|
1100
|
+
ed.commands.focus("end");
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
if (normalized.relatedReferences?.some((item) => item.slotKey)) {
|
|
1104
|
+
setSlotReferences((current) => applySlotReferenceChanges(current, normalized.relatedReferences ?? []));
|
|
1105
|
+
}
|
|
1106
|
+
ed.chain()
|
|
1107
|
+
.focus()
|
|
1108
|
+
.insertContent({
|
|
1109
|
+
type: "mentionReference",
|
|
1110
|
+
attrs: mentionReferenceAttrs(normalized),
|
|
1111
|
+
})
|
|
1112
|
+
.insertContent(" ")
|
|
1113
|
+
.run();
|
|
1114
|
+
setEditorHasText(true);
|
|
1115
|
+
}, [editor]);
|
|
1116
|
+
const insertReferenceIfEmpty = useCallback((payload) => {
|
|
1117
|
+
const insertMessageId = typeof payload.insertMessageId === "string"
|
|
1118
|
+
? payload.insertMessageId
|
|
1119
|
+
: "";
|
|
1120
|
+
if (insertMessageId) {
|
|
1121
|
+
if (seenReferenceInsertIdsRef.current.has(insertMessageId))
|
|
1122
|
+
return;
|
|
1123
|
+
seenReferenceInsertIdsRef.current.add(insertMessageId);
|
|
1124
|
+
}
|
|
1125
|
+
const ed = editor;
|
|
1126
|
+
if (!isComposerEditorUsable(ed) || disabled || composerModeRef.current)
|
|
1127
|
+
return;
|
|
1128
|
+
const normalized = adapters.agentChat.normalizeReference(payload);
|
|
1129
|
+
if (normalized?.slotKey) {
|
|
1130
|
+
insertReference(normalized);
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
if (composerAttachments.length > 0)
|
|
1134
|
+
return;
|
|
1135
|
+
if (composerDocumentHasContent(ed.state.doc))
|
|
1136
|
+
return;
|
|
1137
|
+
insertReference(payload);
|
|
1138
|
+
}, [composerAttachments.length, disabled, editor, insertReference]);
|
|
1139
|
+
useEffect(() => {
|
|
1140
|
+
if (typeof window === "undefined")
|
|
1141
|
+
return;
|
|
1142
|
+
const handleEvent = (event) => {
|
|
1143
|
+
const payload = event.detail;
|
|
1144
|
+
const normalized = adapters.agentChat.normalizeReference(payload);
|
|
1145
|
+
if (!normalized)
|
|
1146
|
+
return;
|
|
1147
|
+
insertReferenceIfEmpty({
|
|
1148
|
+
...normalized,
|
|
1149
|
+
insertMessageId: typeof payload?.insertMessageId === "string"
|
|
1150
|
+
? payload.insertMessageId
|
|
1151
|
+
: "",
|
|
1152
|
+
});
|
|
1153
|
+
};
|
|
1154
|
+
const handleMessage = (event) => {
|
|
1155
|
+
if (!adapters.builder.isTrustedFrameMessage(event) &&
|
|
1156
|
+
!adapters.builder.isTrustedBuilderMessage(event)) {
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
if (event.data?.type !== AGENT_CHAT_INSERT_REFERENCE_MESSAGE_TYPE) {
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
const payload = event.data.data;
|
|
1163
|
+
const normalized = adapters.agentChat.normalizeReference(payload);
|
|
1164
|
+
if (!normalized)
|
|
1165
|
+
return;
|
|
1166
|
+
insertReferenceIfEmpty({
|
|
1167
|
+
...normalized,
|
|
1168
|
+
insertMessageId: typeof payload?.insertMessageId === "string"
|
|
1169
|
+
? payload.insertMessageId
|
|
1170
|
+
: "",
|
|
1171
|
+
});
|
|
1172
|
+
};
|
|
1173
|
+
window.addEventListener(AGENT_CHAT_INSERT_REFERENCE_EVENT, handleEvent);
|
|
1174
|
+
window.addEventListener("message", handleMessage);
|
|
1175
|
+
return () => {
|
|
1176
|
+
window.removeEventListener(AGENT_CHAT_INSERT_REFERENCE_EVENT, handleEvent);
|
|
1177
|
+
window.removeEventListener("message", handleMessage);
|
|
1178
|
+
};
|
|
1179
|
+
}, [adapters, insertReferenceIfEmpty]);
|
|
1180
|
+
useImperativeHandle(focusRef, () => ({
|
|
1181
|
+
focus() {
|
|
1182
|
+
if (isComposerEditorUsable(editor))
|
|
1183
|
+
editor.commands.focus("end");
|
|
1184
|
+
},
|
|
1185
|
+
setText(text) {
|
|
1186
|
+
if (!isComposerEditorUsable(editor))
|
|
1187
|
+
return;
|
|
1188
|
+
editor.commands.setContent(plainTextToDoc(text));
|
|
1189
|
+
editor.commands.focus("end");
|
|
1190
|
+
const trimmed = editor.state.doc.textContent.trim();
|
|
1191
|
+
setEditorHasText(trimmed.length > 0);
|
|
1192
|
+
setSlotReferences([]);
|
|
1193
|
+
composerRuntime.setText(trimmed);
|
|
1194
|
+
onTextChangeRef.current?.(trimmed);
|
|
1195
|
+
try {
|
|
1196
|
+
if (trimmed) {
|
|
1197
|
+
localStorage.setItem(draftKey, editor.getHTML());
|
|
1198
|
+
}
|
|
1199
|
+
else {
|
|
1200
|
+
localStorage.removeItem(draftKey);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
catch { }
|
|
1204
|
+
},
|
|
1205
|
+
insertReference,
|
|
1206
|
+
}));
|
|
1207
|
+
const handleSelectMode = useCallback((mode) => {
|
|
1208
|
+
setComposerMode(mode);
|
|
1209
|
+
composerModeRef.current = mode;
|
|
1210
|
+
setTimeout(() => {
|
|
1211
|
+
if (isComposerEditorUsable(editor))
|
|
1212
|
+
editor.commands.focus("end");
|
|
1213
|
+
}, 50);
|
|
1214
|
+
}, [editor]);
|
|
1215
|
+
// --- Live voice transcription: text appears in the editor as the user speaks ---
|
|
1216
|
+
const voiceAnchorRef = useRef(null);
|
|
1217
|
+
const prevVoiceInsertRef = useRef("");
|
|
1218
|
+
const handleLiveUpdate = useCallback((finalText, interimText) => {
|
|
1219
|
+
const ed = editor;
|
|
1220
|
+
if (!isComposerEditorUsable(ed))
|
|
1221
|
+
return;
|
|
1222
|
+
if (voiceAnchorRef.current == null) {
|
|
1223
|
+
const { from } = ed.state.selection;
|
|
1224
|
+
const prevChar = from > 1 ? ed.state.doc.textBetween(from - 1, from) : "";
|
|
1225
|
+
if (prevChar && !/\s/.test(prevChar)) {
|
|
1226
|
+
ed.chain().insertContent(" ").run();
|
|
1227
|
+
}
|
|
1228
|
+
voiceAnchorRef.current = ed.state.selection.from;
|
|
1229
|
+
prevVoiceInsertRef.current = "";
|
|
1230
|
+
}
|
|
1231
|
+
const anchor = voiceAnchorRef.current;
|
|
1232
|
+
const prevLen = prevVoiceInsertRef.current.length;
|
|
1233
|
+
const newText = finalText + interimText;
|
|
1234
|
+
if (newText === prevVoiceInsertRef.current)
|
|
1235
|
+
return;
|
|
1236
|
+
ed.chain()
|
|
1237
|
+
.deleteRange({ from: anchor, to: anchor + prevLen })
|
|
1238
|
+
.insertContentAt(anchor, newText)
|
|
1239
|
+
.run();
|
|
1240
|
+
prevVoiceInsertRef.current = newText;
|
|
1241
|
+
}, [editor]);
|
|
1242
|
+
const insertTranscript = useCallback((text) => {
|
|
1243
|
+
const ed = editor;
|
|
1244
|
+
if (!isComposerEditorUsable(ed))
|
|
1245
|
+
return;
|
|
1246
|
+
const formattedText = formatVoiceTranscriptForComposer(text);
|
|
1247
|
+
const anchor = voiceAnchorRef.current;
|
|
1248
|
+
if (anchor != null) {
|
|
1249
|
+
const prevLen = prevVoiceInsertRef.current.length;
|
|
1250
|
+
if (formattedText) {
|
|
1251
|
+
ed.chain()
|
|
1252
|
+
.focus()
|
|
1253
|
+
.deleteRange({ from: anchor, to: anchor + prevLen })
|
|
1254
|
+
.insertContentAt(anchor, formattedText)
|
|
1255
|
+
.run();
|
|
1256
|
+
}
|
|
1257
|
+
else if (prevLen > 0) {
|
|
1258
|
+
ed.chain()
|
|
1259
|
+
.deleteRange({ from: anchor, to: anchor + prevLen })
|
|
1260
|
+
.run();
|
|
1261
|
+
}
|
|
1262
|
+
voiceAnchorRef.current = null;
|
|
1263
|
+
prevVoiceInsertRef.current = "";
|
|
1264
|
+
}
|
|
1265
|
+
else if (formattedText) {
|
|
1266
|
+
const { from } = ed.state.selection;
|
|
1267
|
+
const prevChar = from > 1 ? ed.state.doc.textBetween(from - 1, from) : "";
|
|
1268
|
+
const needsLead = prevChar && !/\s/.test(prevChar);
|
|
1269
|
+
ed.chain()
|
|
1270
|
+
.focus()
|
|
1271
|
+
.insertContent((needsLead ? " " : "") + formattedText)
|
|
1272
|
+
.run();
|
|
1273
|
+
}
|
|
1274
|
+
}, [editor]);
|
|
1275
|
+
const buildVoiceContextPack = useCallback(() => {
|
|
1276
|
+
const snippets = [];
|
|
1277
|
+
const activeContext = trimVoiceContextValue(adapters.agentChat.formatContextItems(contextItems) ||
|
|
1278
|
+
formatPromptContextItems(contextItems), 3200);
|
|
1279
|
+
if (activeContext) {
|
|
1280
|
+
snippets.push({ label: "Active app context", value: activeContext });
|
|
1281
|
+
}
|
|
1282
|
+
const selectedReferences = trimVoiceContextValue(slotReferences.map((ref) => slotReferenceTitle(ref)).join(", "), 1200);
|
|
1283
|
+
if (selectedReferences) {
|
|
1284
|
+
snippets.push({
|
|
1285
|
+
label: "Selected references",
|
|
1286
|
+
value: selectedReferences,
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
const draft = isComposerEditorUsable(editor)
|
|
1290
|
+
? trimVoiceContextValue(editor.state.doc.textContent, 1200)
|
|
1291
|
+
: null;
|
|
1292
|
+
if (draft)
|
|
1293
|
+
snippets.push({ label: "Current draft", value: draft });
|
|
1294
|
+
if (typeof document !== "undefined") {
|
|
1295
|
+
const title = trimVoiceContextValue(document.title, 160);
|
|
1296
|
+
if (title)
|
|
1297
|
+
snippets.push({ label: "Page title", value: title });
|
|
1298
|
+
}
|
|
1299
|
+
if (typeof window !== "undefined") {
|
|
1300
|
+
const route = trimVoiceContextValue(window.location.pathname, 240);
|
|
1301
|
+
if (route)
|
|
1302
|
+
snippets.push({ label: "Route", value: route });
|
|
1303
|
+
}
|
|
1304
|
+
if (snippets.length === 0)
|
|
1305
|
+
return undefined;
|
|
1306
|
+
return {
|
|
1307
|
+
surface: "agent-composer",
|
|
1308
|
+
mode: "dictation",
|
|
1309
|
+
snippets,
|
|
1310
|
+
};
|
|
1311
|
+
}, [adapters, contextItems, editor, slotReferences]);
|
|
1312
|
+
const voice = useVoiceDictation({
|
|
1313
|
+
onTranscript: insertTranscript,
|
|
1314
|
+
onLiveUpdate: handleLiveUpdate,
|
|
1315
|
+
contextPack: buildVoiceContextPack,
|
|
1316
|
+
});
|
|
1317
|
+
// Clean up live text if voice session ends without a final transcript (cancel/error)
|
|
1318
|
+
useEffect(() => {
|
|
1319
|
+
if (voice.state === "idle" && voiceAnchorRef.current != null) {
|
|
1320
|
+
const anchor = voiceAnchorRef.current;
|
|
1321
|
+
const prevLen = prevVoiceInsertRef.current.length;
|
|
1322
|
+
if (isComposerEditorUsable(editor) && prevLen > 0) {
|
|
1323
|
+
const documentSize = editor.state.doc.content.size;
|
|
1324
|
+
const currentText = anchor >= 1 && anchor + prevLen <= documentSize
|
|
1325
|
+
? editor.state.doc.textBetween(anchor, anchor + prevLen, "", "\n")
|
|
1326
|
+
: "";
|
|
1327
|
+
if (canRemoveVoicePreview({
|
|
1328
|
+
documentSize,
|
|
1329
|
+
anchor,
|
|
1330
|
+
previewText: prevVoiceInsertRef.current,
|
|
1331
|
+
currentText,
|
|
1332
|
+
})) {
|
|
1333
|
+
editor
|
|
1334
|
+
.chain()
|
|
1335
|
+
.deleteRange({ from: anchor, to: anchor + prevLen })
|
|
1336
|
+
.run();
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
voiceAnchorRef.current = null;
|
|
1340
|
+
prevVoiceInsertRef.current = "";
|
|
1341
|
+
}
|
|
1342
|
+
}, [voice.state, editor]);
|
|
1343
|
+
// Global shortcut: Cmd/Ctrl + Shift + M toggles dictation. Escape cancels
|
|
1344
|
+
// while recording. Scoped to avoid firing when focus is outside the app.
|
|
1345
|
+
useEffect(() => {
|
|
1346
|
+
if (!voiceEnabled || !voice.supported)
|
|
1347
|
+
return;
|
|
1348
|
+
const handler = (e) => {
|
|
1349
|
+
// e.key can be undefined on some trusted keydown events (autofill/IME
|
|
1350
|
+
// quirks) — seen crashing in production (AGENT-NATIVE-BROWSER-S).
|
|
1351
|
+
const isToggleCombo = typeof e.key === "string" &&
|
|
1352
|
+
e.key.toLowerCase() === "m" &&
|
|
1353
|
+
e.shiftKey &&
|
|
1354
|
+
(e.metaKey || e.ctrlKey) &&
|
|
1355
|
+
!e.altKey;
|
|
1356
|
+
if (isToggleCombo) {
|
|
1357
|
+
e.preventDefault();
|
|
1358
|
+
if (voice.state === "recording" || voice.state === "starting") {
|
|
1359
|
+
voice.stop();
|
|
1360
|
+
}
|
|
1361
|
+
else if (voice.state !== "transcribing") {
|
|
1362
|
+
void voice.start();
|
|
1363
|
+
}
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
if (e.key === "Escape" &&
|
|
1367
|
+
(voice.state === "recording" || voice.state === "starting")) {
|
|
1368
|
+
e.preventDefault();
|
|
1369
|
+
voice.cancel();
|
|
1370
|
+
}
|
|
1371
|
+
};
|
|
1372
|
+
window.addEventListener("keydown", handler);
|
|
1373
|
+
return () => window.removeEventListener("keydown", handler);
|
|
1374
|
+
}, [voiceEnabled, voice]);
|
|
1375
|
+
const extractComposerPayload = useCallback(() => {
|
|
1376
|
+
const ed = editor;
|
|
1377
|
+
if (!isComposerEditorUsable(ed)) {
|
|
1378
|
+
return {
|
|
1379
|
+
text: slotReferences.map((ref) => slotReferenceTitle(ref)).join(", "),
|
|
1380
|
+
references: slotReferences.map(referenceFromComposerReference),
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
const references = slotReferences.map(referenceFromComposerReference);
|
|
1384
|
+
// Build text that preserves @mentions (getText() strips them).
|
|
1385
|
+
// Walk the document and reconstruct with @name for mention/file/skill nodes.
|
|
1386
|
+
const textParts = [];
|
|
1387
|
+
ed.state.doc.descendants((node) => {
|
|
1388
|
+
if (node.isText) {
|
|
1389
|
+
textParts.push(node.text);
|
|
1390
|
+
}
|
|
1391
|
+
else if (node.type.name === "mentionReference") {
|
|
1392
|
+
textParts.push(`@[${node.attrs.label}|${node.attrs.icon || "file"}]`);
|
|
1393
|
+
}
|
|
1394
|
+
else if (node.type.name === "fileReference") {
|
|
1395
|
+
const label = node.attrs.path?.split("/").pop() || node.attrs.path;
|
|
1396
|
+
textParts.push(`@[${label}|file]`);
|
|
1397
|
+
}
|
|
1398
|
+
else if (node.type.name === "skillReference") {
|
|
1399
|
+
textParts.push(`/${node.attrs.name}`);
|
|
1400
|
+
}
|
|
1401
|
+
else if (node.type.name === "hardBreak") {
|
|
1402
|
+
textParts.push("\n");
|
|
1403
|
+
}
|
|
1404
|
+
else if (node.type.name === "paragraph" &&
|
|
1405
|
+
textParts.length > 0 &&
|
|
1406
|
+
textParts[textParts.length - 1] !== "\n") {
|
|
1407
|
+
textParts.push("\n");
|
|
1408
|
+
}
|
|
1409
|
+
});
|
|
1410
|
+
const rawText = textParts.join("").trim();
|
|
1411
|
+
const text = rawText ||
|
|
1412
|
+
slotReferences.map((ref) => slotReferenceTitle(ref)).join(", ");
|
|
1413
|
+
ed.state.doc.descendants((node) => {
|
|
1414
|
+
if (node.type.name === "fileReference") {
|
|
1415
|
+
// Legacy support
|
|
1416
|
+
references.push({
|
|
1417
|
+
type: "file",
|
|
1418
|
+
path: node.attrs.path,
|
|
1419
|
+
name: node.attrs.path?.split("/").pop() || node.attrs.path,
|
|
1420
|
+
source: node.attrs.source || "codebase",
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
else if (node.type.name === "mentionReference") {
|
|
1424
|
+
const refType = node.attrs.refType;
|
|
1425
|
+
references.push({
|
|
1426
|
+
type: refType === "file"
|
|
1427
|
+
? "file"
|
|
1428
|
+
: refType === "agent"
|
|
1429
|
+
? "agent"
|
|
1430
|
+
: refType === "custom-agent"
|
|
1431
|
+
? "custom-agent"
|
|
1432
|
+
: "mention",
|
|
1433
|
+
path: node.attrs.refPath || "",
|
|
1434
|
+
name: node.attrs.label,
|
|
1435
|
+
source: node.attrs.source,
|
|
1436
|
+
refType: node.attrs.refType,
|
|
1437
|
+
refId: node.attrs.refId,
|
|
1438
|
+
slotKey: node.attrs.slotKey,
|
|
1439
|
+
slotLabel: node.attrs.slotLabel,
|
|
1440
|
+
metadata: node.attrs.metadata,
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
else if (node.type.name === "skillReference") {
|
|
1444
|
+
references.push({
|
|
1445
|
+
type: "skill",
|
|
1446
|
+
path: node.attrs.path,
|
|
1447
|
+
name: node.attrs.name,
|
|
1448
|
+
source: node.attrs.source || "codebase",
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
});
|
|
1452
|
+
return { text, references };
|
|
1453
|
+
}, [editor, slotReferences]);
|
|
1454
|
+
const syncComposerRuntimeState = useCallback((text, references) => {
|
|
1455
|
+
const requestMode = execMode === "plan" ? "plan" : execMode === "build" ? "act" : undefined;
|
|
1456
|
+
const custom = {};
|
|
1457
|
+
if (references.length > 0) {
|
|
1458
|
+
custom.references = references;
|
|
1459
|
+
}
|
|
1460
|
+
if (requestMode) {
|
|
1461
|
+
custom.requestMode = requestMode;
|
|
1462
|
+
}
|
|
1463
|
+
const runConfig = Object.keys(custom).length > 0 ? { custom } : {};
|
|
1464
|
+
const runConfigSignature = JSON.stringify(runConfig);
|
|
1465
|
+
const last = lastComposerRuntimeSyncRef.current;
|
|
1466
|
+
if (last?.text === text &&
|
|
1467
|
+
last.runConfigSignature === runConfigSignature) {
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
composerRuntime.setText(text);
|
|
1471
|
+
composerRuntime.setRunConfig(runConfig);
|
|
1472
|
+
lastComposerRuntimeSyncRef.current = { text, runConfigSignature };
|
|
1473
|
+
}, [composerRuntime, execMode]);
|
|
1474
|
+
const resetComposerRuntimeState = useCallback(() => {
|
|
1475
|
+
const runConfigSignature = "{}";
|
|
1476
|
+
const last = lastComposerRuntimeSyncRef.current;
|
|
1477
|
+
if (last?.text === "" && last.runConfigSignature === runConfigSignature) {
|
|
1478
|
+
return;
|
|
1479
|
+
}
|
|
1480
|
+
composerRuntime.setText("");
|
|
1481
|
+
composerRuntime.setRunConfig({});
|
|
1482
|
+
lastComposerRuntimeSyncRef.current = { text: "", runConfigSignature };
|
|
1483
|
+
}, [composerRuntime]);
|
|
1484
|
+
const syncComposerState = useCallback(() => {
|
|
1485
|
+
const { text, references } = extractComposerPayload();
|
|
1486
|
+
syncComposerRuntimeState(text, references);
|
|
1487
|
+
return { text, references };
|
|
1488
|
+
}, [extractComposerPayload, syncComposerRuntimeState]);
|
|
1489
|
+
const clearEditorAfterSubmit = useCallback(() => {
|
|
1490
|
+
const ed = editor;
|
|
1491
|
+
if (!isComposerEditorUsable(ed))
|
|
1492
|
+
return;
|
|
1493
|
+
ed.commands.clearContent();
|
|
1494
|
+
setEditorHasText(false);
|
|
1495
|
+
setSlotReferences([]);
|
|
1496
|
+
resetComposerRuntimeState();
|
|
1497
|
+
try {
|
|
1498
|
+
localStorage.removeItem(draftKey);
|
|
1499
|
+
}
|
|
1500
|
+
catch { }
|
|
1501
|
+
closePopover();
|
|
1502
|
+
}, [closePopover, draftKey, editor, resetComposerRuntimeState]);
|
|
1503
|
+
const submitComposer = useCallback(async (intent = "immediate") => {
|
|
1504
|
+
const ed = editor;
|
|
1505
|
+
if (!isComposerEditorUsable(ed))
|
|
1506
|
+
return;
|
|
1507
|
+
if (submitInFlightRef.current)
|
|
1508
|
+
return;
|
|
1509
|
+
const { text, references } = syncComposerState();
|
|
1510
|
+
const attachments = composerRuntime.getState().attachments;
|
|
1511
|
+
if (!text.trim() && references.length === 0 && attachments.length === 0)
|
|
1512
|
+
return;
|
|
1513
|
+
const oversizedDocumentError = getOversizedDocumentAttachmentError(attachments);
|
|
1514
|
+
if (oversizedDocumentError) {
|
|
1515
|
+
onAttachmentErrorRef.current?.(oversizedDocumentError);
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
const cancelActiveVoice = () => {
|
|
1519
|
+
if (voice.state === "recording" ||
|
|
1520
|
+
voice.state === "starting" ||
|
|
1521
|
+
voice.state === "transcribing") {
|
|
1522
|
+
voice.cancel();
|
|
1523
|
+
}
|
|
1524
|
+
};
|
|
1525
|
+
// Intercept slash commands typed directly (e.g. "/clear" + Enter)
|
|
1526
|
+
const trimmed = text.trim();
|
|
1527
|
+
if (trimmed.startsWith("/") && references.length === 0) {
|
|
1528
|
+
const cmdName = normalizeSlashCommandName(trimmed);
|
|
1529
|
+
const matched = allSlashCommands.find((c) => c.name === cmdName);
|
|
1530
|
+
if (matched) {
|
|
1531
|
+
clearEditorAfterSubmit();
|
|
1532
|
+
onSlashCommandRef.current?.(matched.name);
|
|
1533
|
+
return;
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
// Builder iframe delegation: when this app is mounted inside the
|
|
1537
|
+
// Builder.io webview and the user typed a "build me an app/agent"
|
|
1538
|
+
// prompt, hand it up to the parent Builder chat instead of sending
|
|
1539
|
+
// it to this app's domain agent. Builder is the code-writing agent;
|
|
1540
|
+
// the local agent (dispatch, mail, etc.) cannot scaffold workspace
|
|
1541
|
+
// apps from inside its own iframe.
|
|
1542
|
+
if (!composerMode &&
|
|
1543
|
+
interceptBuildRequestsForBuilder &&
|
|
1544
|
+
adapters.builder.tryDelegateBuildRequest(trimmed)) {
|
|
1545
|
+
cancelActiveVoice();
|
|
1546
|
+
clearEditorAfterSubmit();
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1549
|
+
if (onBeforeSubmit) {
|
|
1550
|
+
submitInFlightRef.current = true;
|
|
1551
|
+
try {
|
|
1552
|
+
const shouldSubmit = await onBeforeSubmit();
|
|
1553
|
+
if (!shouldSubmit)
|
|
1554
|
+
return;
|
|
1555
|
+
}
|
|
1556
|
+
finally {
|
|
1557
|
+
submitInFlightRef.current = false;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
if (!isComposerEditorUsable(ed))
|
|
1561
|
+
return;
|
|
1562
|
+
// Composer mode: send with context via agent chat bridge
|
|
1563
|
+
if (composerMode) {
|
|
1564
|
+
const config = COMPOSER_MODE_CONFIGS[composerMode];
|
|
1565
|
+
config.beforeSend?.();
|
|
1566
|
+
const message = displayableComposerModeMessage({
|
|
1567
|
+
messagePrefix: config.messagePrefix,
|
|
1568
|
+
trimmedText: trimmed,
|
|
1569
|
+
attachmentCount: attachments.length,
|
|
1570
|
+
});
|
|
1571
|
+
const modePrompt = trimmed ||
|
|
1572
|
+
(attachments.length > 0 ? "Use the attached context." : "");
|
|
1573
|
+
if (attachments.length > 0) {
|
|
1574
|
+
composerRuntime.setText(`${message}\n\n<context>\n${config.getContext(modePrompt)}\n</context>`);
|
|
1575
|
+
composerRuntime.send();
|
|
1576
|
+
}
|
|
1577
|
+
else {
|
|
1578
|
+
adapters.agentChat.sendToAgentChat({
|
|
1579
|
+
message,
|
|
1580
|
+
context: config.getContext(modePrompt),
|
|
1581
|
+
mode: execMode === "plan"
|
|
1582
|
+
? "plan"
|
|
1583
|
+
: execMode === "build"
|
|
1584
|
+
? "act"
|
|
1585
|
+
: undefined,
|
|
1586
|
+
submit: true,
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
cancelActiveVoice();
|
|
1590
|
+
if (isComposerEditorUsable(ed))
|
|
1591
|
+
ed.commands.clearContent();
|
|
1592
|
+
setEditorHasText(false);
|
|
1593
|
+
setSlotReferences([]);
|
|
1594
|
+
setComposerMode(null);
|
|
1595
|
+
composerModeRef.current = null;
|
|
1596
|
+
try {
|
|
1597
|
+
localStorage.removeItem(draftKey);
|
|
1598
|
+
}
|
|
1599
|
+
catch { }
|
|
1600
|
+
closePopover();
|
|
1601
|
+
return;
|
|
1602
|
+
}
|
|
1603
|
+
if (onSubmit) {
|
|
1604
|
+
onSubmit(text, references, attachments, { intent });
|
|
1605
|
+
// Clear any pending attachments now that the host has them.
|
|
1606
|
+
void composerRuntime.clearAttachments().catch(() => { });
|
|
1607
|
+
if (!clearOnSubmit) {
|
|
1608
|
+
closePopover();
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
cancelActiveVoice();
|
|
1612
|
+
clearEditorAfterSubmit();
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
else {
|
|
1616
|
+
composerRuntime.send();
|
|
1617
|
+
}
|
|
1618
|
+
cancelActiveVoice();
|
|
1619
|
+
if (isComposerEditorUsable(ed))
|
|
1620
|
+
ed.commands.clearContent();
|
|
1621
|
+
setEditorHasText(false);
|
|
1622
|
+
setSlotReferences([]);
|
|
1623
|
+
try {
|
|
1624
|
+
localStorage.removeItem(draftKey);
|
|
1625
|
+
}
|
|
1626
|
+
catch { }
|
|
1627
|
+
closePopover();
|
|
1628
|
+
}, [
|
|
1629
|
+
closePopover,
|
|
1630
|
+
clearEditorAfterSubmit,
|
|
1631
|
+
composerMode,
|
|
1632
|
+
composerRuntime,
|
|
1633
|
+
draftKey,
|
|
1634
|
+
editor,
|
|
1635
|
+
interceptBuildRequestsForBuilder,
|
|
1636
|
+
clearOnSubmit,
|
|
1637
|
+
onBeforeSubmit,
|
|
1638
|
+
onSubmit,
|
|
1639
|
+
syncComposerState,
|
|
1640
|
+
voice,
|
|
1641
|
+
allSlashCommands,
|
|
1642
|
+
]);
|
|
1643
|
+
// Helper functions that operate on the editor view directly
|
|
1644
|
+
// These are called from handleKeyDown which can't use React state
|
|
1645
|
+
function selectMention(_view, pop, item) {
|
|
1646
|
+
const ed = editor;
|
|
1647
|
+
if (!isComposerEditorUsable(ed))
|
|
1648
|
+
return;
|
|
1649
|
+
const currentPos = ed.state.selection.from;
|
|
1650
|
+
// startPos is after the trigger char, so -1 to include the @ or /
|
|
1651
|
+
const deleteFrom = Math.max(0, pop.startPos - 1);
|
|
1652
|
+
ed.chain().focus().deleteRange({ from: deleteFrom, to: currentPos }).run();
|
|
1653
|
+
insertReference(composerReferenceFromMentionItem(item));
|
|
1654
|
+
popoverStateRef.current = null;
|
|
1655
|
+
setPopover(null);
|
|
1656
|
+
}
|
|
1657
|
+
function executeCommand(_view, pop, command) {
|
|
1658
|
+
const ed = editor;
|
|
1659
|
+
if (!isComposerEditorUsable(ed))
|
|
1660
|
+
return;
|
|
1661
|
+
const currentPos = ed.state.selection.from;
|
|
1662
|
+
const deleteFrom = Math.max(0, pop.startPos - 1);
|
|
1663
|
+
ed.chain().focus().deleteRange({ from: deleteFrom, to: currentPos }).run();
|
|
1664
|
+
popoverStateRef.current = null;
|
|
1665
|
+
setPopover(null);
|
|
1666
|
+
onSlashCommandRef.current?.(command.name);
|
|
1667
|
+
}
|
|
1668
|
+
function selectSkill(_view, pop, skill) {
|
|
1669
|
+
const ed = editor;
|
|
1670
|
+
if (!isComposerEditorUsable(ed))
|
|
1671
|
+
return;
|
|
1672
|
+
const currentPos = ed.state.selection.from;
|
|
1673
|
+
const deleteFrom = Math.max(0, pop.startPos - 1);
|
|
1674
|
+
ed.chain()
|
|
1675
|
+
.focus()
|
|
1676
|
+
.deleteRange({ from: deleteFrom, to: currentPos })
|
|
1677
|
+
.insertContent({
|
|
1678
|
+
type: "skillReference",
|
|
1679
|
+
attrs: { name: skill.name, path: skill.path, source: skill.source },
|
|
1680
|
+
})
|
|
1681
|
+
.insertContent(" ")
|
|
1682
|
+
.run();
|
|
1683
|
+
popoverStateRef.current = null;
|
|
1684
|
+
setPopover(null);
|
|
1685
|
+
}
|
|
1686
|
+
// Popover select handlers for click-based selection (from MentionPopover)
|
|
1687
|
+
const handleSelectMention = useCallback((item) => {
|
|
1688
|
+
if (!isComposerEditorUsable(editor) || !popover)
|
|
1689
|
+
return;
|
|
1690
|
+
const currentPos = editor.state.selection.from;
|
|
1691
|
+
const deleteFrom = Math.max(0, popover.startPos - 1);
|
|
1692
|
+
editor
|
|
1693
|
+
.chain()
|
|
1694
|
+
.focus()
|
|
1695
|
+
.deleteRange({ from: deleteFrom, to: currentPos })
|
|
1696
|
+
.run();
|
|
1697
|
+
insertReference(composerReferenceFromMentionItem(item));
|
|
1698
|
+
closePopover();
|
|
1699
|
+
}, [editor, popover, closePopover, insertReference]);
|
|
1700
|
+
const handleSelectCommand = useCallback((command) => {
|
|
1701
|
+
if (!isComposerEditorUsable(editor) || !popover)
|
|
1702
|
+
return;
|
|
1703
|
+
const currentPos = editor.state.selection.from;
|
|
1704
|
+
const deleteFrom = Math.max(0, popover.startPos - 1);
|
|
1705
|
+
editor
|
|
1706
|
+
.chain()
|
|
1707
|
+
.focus()
|
|
1708
|
+
.deleteRange({ from: deleteFrom, to: currentPos })
|
|
1709
|
+
.run();
|
|
1710
|
+
closePopover();
|
|
1711
|
+
onSlashCommand?.(command.name);
|
|
1712
|
+
}, [editor, popover, closePopover, onSlashCommand]);
|
|
1713
|
+
const handleSelectSkill = useCallback((skill) => {
|
|
1714
|
+
if (!isComposerEditorUsable(editor) || !popover)
|
|
1715
|
+
return;
|
|
1716
|
+
const currentPos = editor.state.selection.from;
|
|
1717
|
+
const deleteFrom = Math.max(0, popover.startPos - 1);
|
|
1718
|
+
editor
|
|
1719
|
+
.chain()
|
|
1720
|
+
.focus()
|
|
1721
|
+
.deleteRange({ from: deleteFrom, to: currentPos })
|
|
1722
|
+
.insertContent({
|
|
1723
|
+
type: "skillReference",
|
|
1724
|
+
attrs: { name: skill.name, path: skill.path, source: skill.source },
|
|
1725
|
+
})
|
|
1726
|
+
.insertContent(" ")
|
|
1727
|
+
.run();
|
|
1728
|
+
closePopover();
|
|
1729
|
+
}, [editor, popover, closePopover]);
|
|
1730
|
+
// Track query text as user types after trigger
|
|
1731
|
+
useEffect(() => {
|
|
1732
|
+
if (!isComposerEditorUsable(editor) || !popover)
|
|
1733
|
+
return;
|
|
1734
|
+
const updateHandler = () => {
|
|
1735
|
+
const pop = popoverStateRef.current;
|
|
1736
|
+
if (!pop)
|
|
1737
|
+
return;
|
|
1738
|
+
const { from } = editor.state.selection;
|
|
1739
|
+
const { startPos, type } = pop;
|
|
1740
|
+
if (from < startPos) {
|
|
1741
|
+
closePopover();
|
|
1742
|
+
return;
|
|
1743
|
+
}
|
|
1744
|
+
const text = editor.state.doc.textBetween(startPos, from);
|
|
1745
|
+
// Verify the trigger character is still there
|
|
1746
|
+
if (startPos > 0) {
|
|
1747
|
+
const triggerChar = editor.state.doc.textBetween(startPos - 1, startPos);
|
|
1748
|
+
if ((type === "@" && triggerChar !== "@") ||
|
|
1749
|
+
(type === "/" && triggerChar !== "/")) {
|
|
1750
|
+
closePopover();
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
if (pop.query === text)
|
|
1755
|
+
return;
|
|
1756
|
+
const updated = { ...pop, query: text };
|
|
1757
|
+
popoverStateRef.current = updated;
|
|
1758
|
+
setPopover(updated);
|
|
1759
|
+
};
|
|
1760
|
+
editor.on("update", updateHandler);
|
|
1761
|
+
editor.on("selectionUpdate", updateHandler);
|
|
1762
|
+
return () => {
|
|
1763
|
+
if (isComposerEditorUsable(editor)) {
|
|
1764
|
+
editor.off("update", updateHandler);
|
|
1765
|
+
editor.off("selectionUpdate", updateHandler);
|
|
1766
|
+
}
|
|
1767
|
+
};
|
|
1768
|
+
}, [editor, popover, closePopover]);
|
|
1769
|
+
useEffect(() => {
|
|
1770
|
+
if (!isComposerEditorUsable(editor))
|
|
1771
|
+
return;
|
|
1772
|
+
if (composerText !== "")
|
|
1773
|
+
return;
|
|
1774
|
+
if (editor.isEmpty)
|
|
1775
|
+
return;
|
|
1776
|
+
editor.commands.clearContent();
|
|
1777
|
+
}, [composerText, editor]);
|
|
1778
|
+
useEffect(() => {
|
|
1779
|
+
if (!isComposerEditorUsable(editor) || initialText === undefined)
|
|
1780
|
+
return;
|
|
1781
|
+
const key = initialTextKey ?? initialText;
|
|
1782
|
+
if (initialTextKeyRef.current === key)
|
|
1783
|
+
return;
|
|
1784
|
+
initialTextKeyRef.current = key;
|
|
1785
|
+
editor.commands.setContent(plainTextToDoc(initialText));
|
|
1786
|
+
editor.commands.focus("end");
|
|
1787
|
+
const trimmed = editor.state.doc.textContent.trim();
|
|
1788
|
+
setEditorHasText(trimmed.length > 0);
|
|
1789
|
+
composerRuntime.setText(trimmed);
|
|
1790
|
+
onTextChangeRef.current?.(trimmed);
|
|
1791
|
+
try {
|
|
1792
|
+
if (trimmed) {
|
|
1793
|
+
localStorage.setItem(draftKey, editor.getHTML());
|
|
1794
|
+
}
|
|
1795
|
+
else {
|
|
1796
|
+
localStorage.removeItem(draftKey);
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
catch { }
|
|
1800
|
+
}, [composerRuntime, draftKey, editor, initialText, initialTextKey]);
|
|
1801
|
+
// Tiptap only reads `editable` at init; prop changes need setEditable.
|
|
1802
|
+
useEffect(() => {
|
|
1803
|
+
if (!isComposerEditorUsable(editor))
|
|
1804
|
+
return;
|
|
1805
|
+
editor.setEditable(!disabled);
|
|
1806
|
+
if (disabled)
|
|
1807
|
+
editor.commands.blur();
|
|
1808
|
+
}, [editor, disabled]);
|
|
1809
|
+
return (_jsxs(RealtimeVoiceModeBoundary, { children: [_jsx("style", { children: `
|
|
1810
|
+
.aui-composer .ProseMirror p.is-editor-empty:first-child::before {
|
|
1811
|
+
content: attr(data-placeholder);
|
|
1812
|
+
color: var(--color-muted-foreground);
|
|
1813
|
+
opacity: 0.5;
|
|
1814
|
+
float: left;
|
|
1815
|
+
height: 0;
|
|
1816
|
+
pointer-events: none;
|
|
1817
|
+
}
|
|
1818
|
+
` }), composerMode && (_jsx("div", { "data-agent-composer-variant": layoutVariant, "data-agent-composer-slot": "mode-row", className: "agent-composer-mode-row px-2.5 pt-2 pb-0", children: _jsx(ComposerModeChip, { mode: composerMode, onRemove: () => {
|
|
1819
|
+
setComposerMode(null);
|
|
1820
|
+
composerModeRef.current = null;
|
|
1821
|
+
if (isComposerEditorUsable(editor)) {
|
|
1822
|
+
editor.commands.focus("end");
|
|
1823
|
+
}
|
|
1824
|
+
} }) })), hasContextRows && (_jsxs("div", { "data-agent-composer-variant": layoutVariant, "data-agent-composer-slot": "context-row", className: "agent-composer-context-row flex flex-wrap gap-1.5 px-2.5 pt-2 pb-0", children: [slotReferences.map((ref) => (_jsxs("span", { className: "inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-background px-2 py-1 text-[11px] font-medium text-foreground shadow-sm", children: [_jsx(IconClipboardList, { className: "h-3 w-3 shrink-0 text-muted-foreground" }), ref.slotLabel && (_jsx("span", { className: "shrink-0 text-muted-foreground", children: ref.slotLabel })), _jsx("span", { className: "min-w-0 truncate", children: ref.label }), _jsx("button", { type: "button", onClick: () => {
|
|
1825
|
+
setSlotReferences((current) => removeSlotReference(current, ref));
|
|
1826
|
+
if (isComposerEditorUsable(editor)) {
|
|
1827
|
+
editor.commands.focus("end");
|
|
1828
|
+
}
|
|
1829
|
+
}, "aria-label": `Remove ${slotReferenceTitle(ref)} reference`, className: "ms-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground", children: _jsx(IconX, { className: "h-3 w-3" }) })] }, ref.slotKey))), contextItems.map((item) => (_jsxs("span", { "data-state": selectedContextItemKey === item.key ? "selected" : undefined, className: `inline-flex max-w-full items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-medium text-foreground ${selectedContextItemKey === item.key
|
|
1830
|
+
? "border-ring bg-accent ring-2 ring-ring/40"
|
|
1831
|
+
: "border-border bg-muted/50"}`, children: [_jsx(IconClipboardList, { className: "h-3 w-3 shrink-0 text-muted-foreground" }), _jsx("span", { className: "min-w-0 truncate", children: item.title }), _jsx("button", { type: "button", onClick: () => {
|
|
1832
|
+
selectedContextItemKeyRef.current = null;
|
|
1833
|
+
setSelectedContextItemKey(null);
|
|
1834
|
+
onRemoveContextItem?.(item.key);
|
|
1835
|
+
}, "aria-label": `Remove ${item.title} context`, className: "ms-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground", children: _jsx(IconX, { className: "h-3 w-3" }) })] }, item.key)))] })), _jsx("div", { "data-agent-composer-variant": layoutVariant, "data-agent-composer-slot": "editor-wrap", className: `agent-composer-editor-wrap ${composerMode || hasContextRows ? "px-2 pt-1 pb-1" : "px-2 pt-2 pb-1"}`, children: _jsx(EditorContent, { editor: editor, "data-agent-composer-variant": layoutVariant, "data-agent-composer-slot": "editor", className: "agent-composer-editor aui-composer flex-1 min-w-0 [&_.ProseMirror]:outline-none [&_.ProseMirror_p]:m-0 px-0.5" }) }), voiceEnabled && _jsx(VoiceRecordingOverlay, { voice: voice }), _jsxs("div", { "data-agent-composer-variant": layoutVariant, "data-agent-composer-slot": "toolbar", className: "agent-composer-toolbar flex items-center gap-1 px-2 py-1.5", children: [attachButton ??
|
|
1836
|
+
(plusMenuMode === "hidden" ? null : (_jsx(ComposerPlusMenu, { onSelectMode: handleSelectMode, mode: plusMenuMode, onAttachmentError: onAttachmentError }))), toolbarSlot ?? modeControl, _jsx("div", { "data-agent-composer-slot": "toolbar-spacer", className: "flex-1" }), selectedModel && availableModels && onModelChange && (_jsx(ModelSelector, { model: selectedModel, effort: selectedEffort, engines: availableModels, modelListLoading: modelListLoading, onChange: onModelChange, onEffortChange: onEffortChange, providerConnectStatusEnabled: providerConnectStatusEnabled, onConnectProvider: onConnectProvider, onConnectLocalRuntime: onConnectLocalRuntime, imageModel: imageModelMenu })), execMode && onExecModeChange && (_jsx(ModeSelector, { mode: execMode, onChange: onExecModeChange, planModeDisabled: planModeDisabled, planModeDisabledReason: planModeDisabledReason })), actionButton ?? (_jsxs(_Fragment, { children: [extraActionButton, voiceEnabled && (_jsx(VoiceButton, { voice: voice, isMac: isMac, disabled: disabled })), primaryAction === "stop" ? (stopButton) : (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", onClick: () => void submitComposer("immediate"), disabled: !canSend, "data-agent-composer-slot": "send-button", className: "agent-composer-send-button shrink-0 flex h-7 w-7 items-center justify-center rounded-md bg-primary text-primary-foreground hover:opacity-90 transition-[opacity,transform] duration-150 active:scale-[0.97] disabled:opacity-30 disabled:cursor-not-allowed", children: _jsx(IconArrowUp, { className: "h-3.5 w-3.5" }) }) }), _jsx(TooltipContent, { children: "Send message" })] }))] }))] }), _jsx(MentionPopover, { ref: popoverRef, type: popover?.type ?? "@", position: popover?.position ?? null, mentionItems: filteredMentionItems, skills: filteredSkills, commands: filteredCommands, hint: hint, isLoading: popover?.type === "@" ? mentionsLoading : skillsLoading, query: popover?.query ?? "", onSelectMention: handleSelectMention, onSelectSkill: handleSelectSkill, onSelectCommand: handleSelectCommand, onClose: closePopover })] }));
|
|
1837
|
+
}
|
|
1838
|
+
//# sourceMappingURL=TiptapComposer.js.map
|