work-agent 0.1.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.
Files changed (245) hide show
  1. package/README.md +234 -0
  2. package/app/(admin)/approvals/page.tsx +16 -0
  3. package/app/(admin)/audit/page.tsx +18 -0
  4. package/app/(admin)/layout.tsx +47 -0
  5. package/app/(admin)/scheduled-tasks/page.tsx +17 -0
  6. package/app/(admin)/settings/page.tsx +46 -0
  7. package/app/(admin)/skills/[name]/page.tsx +378 -0
  8. package/app/(admin)/skills/page.tsx +406 -0
  9. package/app/(admin)/statistics/page.tsx +416 -0
  10. package/app/(admin)/tickets/[id]/page.tsx +348 -0
  11. package/app/(admin)/tickets/new/page.tsx +309 -0
  12. package/app/(admin)/tickets/page.tsx +27 -0
  13. package/app/api/audit/route.ts +30 -0
  14. package/app/api/auth/feishu/callback/route.ts +72 -0
  15. package/app/api/auth/feishu/login/route.ts +17 -0
  16. package/app/api/auth/feishu/sso/route.ts +78 -0
  17. package/app/api/auth/login/route.ts +85 -0
  18. package/app/api/auth/oauth/route.ts +168 -0
  19. package/app/api/config/providers/route.ts +105 -0
  20. package/app/api/config/route.ts +115 -0
  21. package/app/api/config/status/route.ts +56 -0
  22. package/app/api/config/test/route.ts +212 -0
  23. package/app/api/documents/[id]/route.ts +88 -0
  24. package/app/api/documents/route.ts +53 -0
  25. package/app/api/health/route.ts +32 -0
  26. package/app/api/knowledge/[id]/route.ts +152 -0
  27. package/app/api/knowledge/from-session/route.ts +27 -0
  28. package/app/api/knowledge/route.ts +100 -0
  29. package/app/api/market/knowledge/[id]/route.ts +92 -0
  30. package/app/api/market/knowledge/route.ts +130 -0
  31. package/app/api/marketplace/skills/[id]/approve/route.ts +68 -0
  32. package/app/api/marketplace/skills/[id]/certify/route.ts +54 -0
  33. package/app/api/marketplace/skills/[id]/install/route.ts +180 -0
  34. package/app/api/marketplace/skills/[id]/promote-to-system/route.ts +219 -0
  35. package/app/api/marketplace/skills/[id]/rate/route.ts +90 -0
  36. package/app/api/marketplace/skills/[id]/ratings/route.ts +55 -0
  37. package/app/api/marketplace/skills/[id]/reject/route.ts +68 -0
  38. package/app/api/marketplace/skills/[id]/route.ts +177 -0
  39. package/app/api/marketplace/skills/route.ts +235 -0
  40. package/app/api/memory/route.ts +40 -0
  41. package/app/api/my/files/[id]/route.ts +52 -0
  42. package/app/api/my/files/route.ts +230 -0
  43. package/app/api/my/knowledge/route.ts +36 -0
  44. package/app/api/pi-chat/route.ts +443 -0
  45. package/app/api/recommend/route.ts +38 -0
  46. package/app/api/scheduled-tasks/[id]/execute/route.ts +132 -0
  47. package/app/api/scheduled-tasks/[id]/route.ts +165 -0
  48. package/app/api/scheduled-tasks/[id]/toggle/route.ts +53 -0
  49. package/app/api/scheduled-tasks/route.ts +101 -0
  50. package/app/api/sessions/[id]/messages/route.ts +212 -0
  51. package/app/api/sessions/route.ts +101 -0
  52. package/app/api/share/file/[id]/route.ts +37 -0
  53. package/app/api/skills/[name]/execute/route.ts +121 -0
  54. package/app/api/skills/[name]/route.ts +167 -0
  55. package/app/api/skills/create/route.ts +65 -0
  56. package/app/api/skills/generate/route.ts +405 -0
  57. package/app/api/skills/installed/route.ts +151 -0
  58. package/app/api/skills/route.ts +174 -0
  59. package/app/api/skills/translate/route.ts +40 -0
  60. package/app/api/skills/user/[name]/route.ts +159 -0
  61. package/app/api/skills/user/route.ts +90 -0
  62. package/app/api/statistics/route.ts +94 -0
  63. package/app/api/task-executions/[id]/route.ts +34 -0
  64. package/app/api/task-executions/route.ts +29 -0
  65. package/app/api/tickets/[id]/approve/route.ts +129 -0
  66. package/app/api/tickets/[id]/execute/route.ts +201 -0
  67. package/app/api/tickets/[id]/route.ts +127 -0
  68. package/app/api/tickets/route.ts +103 -0
  69. package/app/api/user/skills/route.ts +175 -0
  70. package/app/api/users/route.ts +80 -0
  71. package/app/chat/page.tsx +5 -0
  72. package/app/globals.css +84 -0
  73. package/app/h5/layout.tsx +5 -0
  74. package/app/h5/mobile-approvals-page.tsx +167 -0
  75. package/app/h5/mobile-chat-page.tsx +951 -0
  76. package/app/h5/mobile-profile-page.tsx +147 -0
  77. package/app/h5/mobile-tickets-page.tsx +121 -0
  78. package/app/h5/page.tsx +23 -0
  79. package/app/h5/ticket-action-buttons.tsx +80 -0
  80. package/app/layout.tsx +26 -0
  81. package/app/login/page.tsx +318 -0
  82. package/app/market/knowledge/[id]/page.tsx +77 -0
  83. package/app/market/knowledge/page.tsx +358 -0
  84. package/app/market/layout.tsx +29 -0
  85. package/app/market/page.tsx +18 -0
  86. package/app/market/skills/page.tsx +397 -0
  87. package/app/my/files/page.tsx +511 -0
  88. package/app/my/knowledge/[id]/page.tsx +271 -0
  89. package/app/my/knowledge/new/page.tsx +234 -0
  90. package/app/my/knowledge/page.tsx +248 -0
  91. package/app/my/layout.tsx +32 -0
  92. package/app/my/memory/page.tsx +164 -0
  93. package/app/my/page.tsx +18 -0
  94. package/app/my/scheduled-tasks/[id]/edit/page.tsx +290 -0
  95. package/app/my/scheduled-tasks/[id]/executions/page.tsx +275 -0
  96. package/app/my/scheduled-tasks/[id]/page.tsx +284 -0
  97. package/app/my/scheduled-tasks/new/page.tsx +230 -0
  98. package/app/my/scheduled-tasks/page.tsx +27 -0
  99. package/app/my/skills/[name]/page.tsx +320 -0
  100. package/app/my/skills/new/page.tsx +394 -0
  101. package/app/my/skills/page.tsx +303 -0
  102. package/app/page.tsx +2288 -0
  103. package/app/share/[sessionId]/page.tsx +226 -0
  104. package/app/share/file/[id]/page.tsx +140 -0
  105. package/bin/README.md +63 -0
  106. package/bin/generate-api-system +300 -0
  107. package/bin/postinstall.js +95 -0
  108. package/bin/work-agent.js +173 -0
  109. package/components/ai-elements/agent.tsx +142 -0
  110. package/components/ai-elements/artifact.tsx +149 -0
  111. package/components/ai-elements/attachments.tsx +427 -0
  112. package/components/ai-elements/audio-player.tsx +232 -0
  113. package/components/ai-elements/canvas.tsx +26 -0
  114. package/components/ai-elements/chain-of-thought.tsx +223 -0
  115. package/components/ai-elements/checkpoint.tsx +72 -0
  116. package/components/ai-elements/code-block.tsx +555 -0
  117. package/components/ai-elements/commit.tsx +449 -0
  118. package/components/ai-elements/confirmation.tsx +173 -0
  119. package/components/ai-elements/connection.tsx +28 -0
  120. package/components/ai-elements/context.tsx +410 -0
  121. package/components/ai-elements/controls.tsx +19 -0
  122. package/components/ai-elements/conversation.tsx +167 -0
  123. package/components/ai-elements/edge.tsx +144 -0
  124. package/components/ai-elements/environment-variables.tsx +325 -0
  125. package/components/ai-elements/file-tree.tsx +298 -0
  126. package/components/ai-elements/image.tsx +25 -0
  127. package/components/ai-elements/inline-citation.tsx +294 -0
  128. package/components/ai-elements/jsx-preview.tsx +250 -0
  129. package/components/ai-elements/message.tsx +367 -0
  130. package/components/ai-elements/mic-selector.tsx +372 -0
  131. package/components/ai-elements/model-selector.tsx +214 -0
  132. package/components/ai-elements/node.tsx +72 -0
  133. package/components/ai-elements/open-in-chat.tsx +367 -0
  134. package/components/ai-elements/package-info.tsx +235 -0
  135. package/components/ai-elements/panel.tsx +16 -0
  136. package/components/ai-elements/persona.tsx +280 -0
  137. package/components/ai-elements/plan.tsx +144 -0
  138. package/components/ai-elements/prompt-input.tsx +1341 -0
  139. package/components/ai-elements/queue.tsx +275 -0
  140. package/components/ai-elements/reasoning.tsx +355 -0
  141. package/components/ai-elements/sandbox.tsx +133 -0
  142. package/components/ai-elements/schema-display.tsx +473 -0
  143. package/components/ai-elements/shimmer.tsx +78 -0
  144. package/components/ai-elements/snippet.tsx +141 -0
  145. package/components/ai-elements/sources.tsx +78 -0
  146. package/components/ai-elements/speech-input.tsx +324 -0
  147. package/components/ai-elements/stack-trace.tsx +531 -0
  148. package/components/ai-elements/suggestion.tsx +58 -0
  149. package/components/ai-elements/task.tsx +88 -0
  150. package/components/ai-elements/terminal.tsx +277 -0
  151. package/components/ai-elements/test-results.tsx +497 -0
  152. package/components/ai-elements/tool.tsx +174 -0
  153. package/components/ai-elements/toolbar.tsx +17 -0
  154. package/components/ai-elements/transcription.tsx +126 -0
  155. package/components/ai-elements/voice-selector.tsx +525 -0
  156. package/components/ai-elements/web-preview.tsx +282 -0
  157. package/components/audit-log-list.tsx +114 -0
  158. package/components/chat/EmptyPreviewState.tsx +12 -0
  159. package/components/chat/KnowledgePickerDialog.tsx +464 -0
  160. package/components/chat/KnowledgePreview.tsx +70 -0
  161. package/components/chat/KnowledgePreviewPanel.tsx +86 -0
  162. package/components/chat/MentionInput.tsx +309 -0
  163. package/components/chat/OrganizeDialog.tsx +258 -0
  164. package/components/chat/RecommendationBanner.tsx +94 -0
  165. package/components/chat/SaveToKnowledgeDialog.tsx +193 -0
  166. package/components/chat/SkillSelector.tsx +305 -0
  167. package/components/chat/SkillSwitcher.tsx +163 -0
  168. package/components/client-layout.tsx +15 -0
  169. package/components/knowledge/KnowledgeMetadataPanel.tsx +293 -0
  170. package/components/layout-wrapper.tsx +18 -0
  171. package/components/mobile-layout.tsx +62 -0
  172. package/components/scheduled-task-list.tsx +356 -0
  173. package/components/setup-guide.tsx +484 -0
  174. package/components/sub-nav.tsx +54 -0
  175. package/components/ticket-detail-content.tsx +383 -0
  176. package/components/ticket-list.tsx +366 -0
  177. package/components/top-nav.tsx +132 -0
  178. package/components/ui/accordion.tsx +58 -0
  179. package/components/ui/alert.tsx +59 -0
  180. package/components/ui/avatar.tsx +50 -0
  181. package/components/ui/badge.tsx +36 -0
  182. package/components/ui/button-group.tsx +83 -0
  183. package/components/ui/button.tsx +57 -0
  184. package/components/ui/card.tsx +91 -0
  185. package/components/ui/carousel.tsx +262 -0
  186. package/components/ui/collapsible.tsx +11 -0
  187. package/components/ui/command.tsx +153 -0
  188. package/components/ui/dialog.tsx +122 -0
  189. package/components/ui/dropdown-menu.tsx +200 -0
  190. package/components/ui/hover-card.tsx +29 -0
  191. package/components/ui/input-group.tsx +170 -0
  192. package/components/ui/input.tsx +22 -0
  193. package/components/ui/label.tsx +26 -0
  194. package/components/ui/popover.tsx +31 -0
  195. package/components/ui/progress.tsx +28 -0
  196. package/components/ui/scroll-area.tsx +48 -0
  197. package/components/ui/select.tsx +174 -0
  198. package/components/ui/separator.tsx +31 -0
  199. package/components/ui/spinner.tsx +16 -0
  200. package/components/ui/switch.tsx +29 -0
  201. package/components/ui/table.tsx +120 -0
  202. package/components/ui/tabs.tsx +55 -0
  203. package/components/ui/textarea.tsx +22 -0
  204. package/components/ui/tooltip.tsx +30 -0
  205. package/components/welcome-guide.tsx +182 -0
  206. package/components.json +24 -0
  207. package/lib/command-parser.ts +331 -0
  208. package/lib/dangerous-commands.ts +672 -0
  209. package/lib/db.ts +2250 -0
  210. package/lib/feishu-auth.ts +135 -0
  211. package/lib/file-storage.ts +306 -0
  212. package/lib/file-tool.ts +583 -0
  213. package/lib/knowledge-tool.ts +152 -0
  214. package/lib/knowledge-types.ts +66 -0
  215. package/lib/market-client.ts +313 -0
  216. package/lib/market-db.ts +736 -0
  217. package/lib/market-types.ts +51 -0
  218. package/lib/memory-tool.ts +211 -0
  219. package/lib/memory.ts +197 -0
  220. package/lib/pi-config.ts +436 -0
  221. package/lib/pi-session.ts +799 -0
  222. package/lib/pinyin.ts +13 -0
  223. package/lib/recommendation.ts +227 -0
  224. package/lib/risk-estimator.ts +350 -0
  225. package/lib/scheduled-task-tool.ts +184 -0
  226. package/lib/scheduler-init.ts +43 -0
  227. package/lib/scheduler.ts +416 -0
  228. package/lib/secure-bash-tool.ts +413 -0
  229. package/lib/skill-engine.ts +396 -0
  230. package/lib/skill-generator.ts +269 -0
  231. package/lib/skill-loader.ts +234 -0
  232. package/lib/skill-tool.ts +188 -0
  233. package/lib/skill-types.ts +82 -0
  234. package/lib/skills-init.ts +58 -0
  235. package/lib/ticket-tool.ts +246 -0
  236. package/lib/user-skill-types.ts +30 -0
  237. package/lib/user-skills.ts +362 -0
  238. package/lib/utils.ts +6 -0
  239. package/lib/workflow.ts +154 -0
  240. package/lib/zip-tool.ts +191 -0
  241. package/next.config.js +8 -0
  242. package/package.json +106 -0
  243. package/public/.gitkeep +1 -0
  244. package/public/icon.svg +1 -0
  245. package/tsconfig.json +42 -0
@@ -0,0 +1,1341 @@
1
+ "use client";
2
+
3
+ import type { ChatStatus, FileUIPart, SourceDocumentUIPart } from "ai";
4
+ import type {
5
+ ChangeEvent,
6
+ ChangeEventHandler,
7
+ ClipboardEventHandler,
8
+ ComponentProps,
9
+ FormEvent,
10
+ FormEventHandler,
11
+ HTMLAttributes,
12
+ KeyboardEventHandler,
13
+ PropsWithChildren,
14
+ ReactNode,
15
+ RefObject,
16
+ } from "react";
17
+
18
+ import {
19
+ Command,
20
+ CommandEmpty,
21
+ CommandGroup,
22
+ CommandInput,
23
+ CommandItem,
24
+ CommandList,
25
+ CommandSeparator,
26
+ } from "@/components/ui/command";
27
+ import {
28
+ DropdownMenu,
29
+ DropdownMenuContent,
30
+ DropdownMenuItem,
31
+ DropdownMenuTrigger,
32
+ } from "@/components/ui/dropdown-menu";
33
+ import {
34
+ HoverCard,
35
+ HoverCardContent,
36
+ HoverCardTrigger,
37
+ } from "@/components/ui/hover-card";
38
+ import {
39
+ InputGroup,
40
+ InputGroupAddon,
41
+ InputGroupButton,
42
+ InputGroupTextarea,
43
+ } from "@/components/ui/input-group";
44
+ import {
45
+ Select,
46
+ SelectContent,
47
+ SelectItem,
48
+ SelectTrigger,
49
+ SelectValue,
50
+ } from "@/components/ui/select";
51
+ import { Spinner } from "@/components/ui/spinner";
52
+ import {
53
+ Tooltip,
54
+ TooltipContent,
55
+ TooltipTrigger,
56
+ } from "@/components/ui/tooltip";
57
+ import { cn } from "@/lib/utils";
58
+ import {
59
+ CornerDownLeftIcon,
60
+ ImageIcon,
61
+ PlusIcon,
62
+ SquareIcon,
63
+ XIcon,
64
+ } from "lucide-react";
65
+ import { nanoid } from "nanoid";
66
+ import {
67
+ Children,
68
+ createContext,
69
+ useCallback,
70
+ useContext,
71
+ useEffect,
72
+ useMemo,
73
+ useRef,
74
+ useState,
75
+ } from "react";
76
+
77
+ // ============================================================================
78
+ // Helpers
79
+ // ============================================================================
80
+
81
+ const convertBlobUrlToDataUrl = async (url: string): Promise<string | null> => {
82
+ try {
83
+ const response = await fetch(url);
84
+ const blob = await response.blob();
85
+ // FileReader uses callback-based API, wrapping in Promise is necessary
86
+ // oxlint-disable-next-line eslint-plugin-promise(avoid-new)
87
+ return new Promise((resolve) => {
88
+ const reader = new FileReader();
89
+ // oxlint-disable-next-line eslint-plugin-unicorn(prefer-add-event-listener)
90
+ reader.onloadend = () => resolve(reader.result as string);
91
+ // oxlint-disable-next-line eslint-plugin-unicorn(prefer-add-event-listener)
92
+ reader.onerror = () => resolve(null);
93
+ reader.readAsDataURL(blob);
94
+ });
95
+ } catch {
96
+ return null;
97
+ }
98
+ };
99
+
100
+ // ============================================================================
101
+ // Provider Context & Types
102
+ // ============================================================================
103
+
104
+ export interface AttachmentsContext {
105
+ files: (FileUIPart & { id: string })[];
106
+ add: (files: File[] | FileList) => void;
107
+ remove: (id: string) => void;
108
+ clear: () => void;
109
+ openFileDialog: () => void;
110
+ fileInputRef: RefObject<HTMLInputElement | null>;
111
+ }
112
+
113
+ export interface TextInputContext {
114
+ value: string;
115
+ setInput: (v: string) => void;
116
+ clear: () => void;
117
+ }
118
+
119
+ export interface PromptInputControllerProps {
120
+ textInput: TextInputContext;
121
+ attachments: AttachmentsContext;
122
+ /** INTERNAL: Allows PromptInput to register its file textInput + "open" callback */
123
+ __registerFileInput: (
124
+ ref: RefObject<HTMLInputElement | null>,
125
+ open: () => void
126
+ ) => void;
127
+ }
128
+
129
+ const PromptInputController = createContext<PromptInputControllerProps | null>(
130
+ null
131
+ );
132
+ const ProviderAttachmentsContext = createContext<AttachmentsContext | null>(
133
+ null
134
+ );
135
+
136
+ export const usePromptInputController = () => {
137
+ const ctx = useContext(PromptInputController);
138
+ if (!ctx) {
139
+ throw new Error(
140
+ "Wrap your component inside <PromptInputProvider> to use usePromptInputController()."
141
+ );
142
+ }
143
+ return ctx;
144
+ };
145
+
146
+ // Optional variants (do NOT throw). Useful for dual-mode components.
147
+ const useOptionalPromptInputController = () =>
148
+ useContext(PromptInputController);
149
+
150
+ export const useProviderAttachments = () => {
151
+ const ctx = useContext(ProviderAttachmentsContext);
152
+ if (!ctx) {
153
+ throw new Error(
154
+ "Wrap your component inside <PromptInputProvider> to use useProviderAttachments()."
155
+ );
156
+ }
157
+ return ctx;
158
+ };
159
+
160
+ const useOptionalProviderAttachments = () =>
161
+ useContext(ProviderAttachmentsContext);
162
+
163
+ export type PromptInputProviderProps = PropsWithChildren<{
164
+ initialInput?: string;
165
+ }>;
166
+
167
+ /**
168
+ * Optional global provider that lifts PromptInput state outside of PromptInput.
169
+ * If you don't use it, PromptInput stays fully self-managed.
170
+ */
171
+ export const PromptInputProvider = ({
172
+ initialInput: initialTextInput = "",
173
+ children,
174
+ }: PromptInputProviderProps) => {
175
+ // ----- textInput state
176
+ const [textInput, setTextInput] = useState(initialTextInput);
177
+ const clearInput = useCallback(() => setTextInput(""), []);
178
+
179
+ // ----- attachments state (global when wrapped)
180
+ const [attachmentFiles, setAttachmentFiles] = useState<
181
+ (FileUIPart & { id: string })[]
182
+ >([]);
183
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
184
+ // oxlint-disable-next-line eslint(no-empty-function)
185
+ const openRef = useRef<() => void>(() => {});
186
+
187
+ const add = useCallback((files: File[] | FileList) => {
188
+ const incoming = [...files];
189
+ if (incoming.length === 0) {
190
+ return;
191
+ }
192
+
193
+ setAttachmentFiles((prev) => [
194
+ ...prev,
195
+ ...incoming.map((file) => ({
196
+ filename: file.name,
197
+ id: nanoid(),
198
+ mediaType: file.type,
199
+ type: "file" as const,
200
+ url: URL.createObjectURL(file),
201
+ })),
202
+ ]);
203
+ }, []);
204
+
205
+ const remove = useCallback((id: string) => {
206
+ setAttachmentFiles((prev) => {
207
+ const found = prev.find((f) => f.id === id);
208
+ if (found?.url) {
209
+ URL.revokeObjectURL(found.url);
210
+ }
211
+ return prev.filter((f) => f.id !== id);
212
+ });
213
+ }, []);
214
+
215
+ const clear = useCallback(() => {
216
+ setAttachmentFiles((prev) => {
217
+ for (const f of prev) {
218
+ if (f.url) {
219
+ URL.revokeObjectURL(f.url);
220
+ }
221
+ }
222
+ return [];
223
+ });
224
+ }, []);
225
+
226
+ // Keep a ref to attachments for cleanup on unmount (avoids stale closure)
227
+ const attachmentsRef = useRef(attachmentFiles);
228
+
229
+ useEffect(() => {
230
+ attachmentsRef.current = attachmentFiles;
231
+ }, [attachmentFiles]);
232
+
233
+ // Cleanup blob URLs on unmount to prevent memory leaks
234
+ useEffect(
235
+ () => () => {
236
+ for (const f of attachmentsRef.current) {
237
+ if (f.url) {
238
+ URL.revokeObjectURL(f.url);
239
+ }
240
+ }
241
+ },
242
+ []
243
+ );
244
+
245
+ const openFileDialog = useCallback(() => {
246
+ openRef.current?.();
247
+ }, []);
248
+
249
+ const attachments = useMemo<AttachmentsContext>(
250
+ () => ({
251
+ add,
252
+ clear,
253
+ fileInputRef,
254
+ files: attachmentFiles,
255
+ openFileDialog,
256
+ remove,
257
+ }),
258
+ [attachmentFiles, add, remove, clear, openFileDialog]
259
+ );
260
+
261
+ const __registerFileInput = useCallback(
262
+ (ref: RefObject<HTMLInputElement | null>, open: () => void) => {
263
+ fileInputRef.current = ref.current;
264
+ openRef.current = open;
265
+ },
266
+ []
267
+ );
268
+
269
+ const controller = useMemo<PromptInputControllerProps>(
270
+ () => ({
271
+ __registerFileInput,
272
+ attachments,
273
+ textInput: {
274
+ clear: clearInput,
275
+ setInput: setTextInput,
276
+ value: textInput,
277
+ },
278
+ }),
279
+ [textInput, clearInput, attachments, __registerFileInput]
280
+ );
281
+
282
+ return (
283
+ <PromptInputController.Provider value={controller}>
284
+ <ProviderAttachmentsContext.Provider value={attachments}>
285
+ {children}
286
+ </ProviderAttachmentsContext.Provider>
287
+ </PromptInputController.Provider>
288
+ );
289
+ };
290
+
291
+ // ============================================================================
292
+ // Component Context & Hooks
293
+ // ============================================================================
294
+
295
+ const LocalAttachmentsContext = createContext<AttachmentsContext | null>(null);
296
+
297
+ export const usePromptInputAttachments = () => {
298
+ // Prefer local context (inside PromptInput) as it has validation, fall back to provider
299
+ const provider = useOptionalProviderAttachments();
300
+ const local = useContext(LocalAttachmentsContext);
301
+ const context = local ?? provider;
302
+ if (!context) {
303
+ throw new Error(
304
+ "usePromptInputAttachments must be used within a PromptInput or PromptInputProvider"
305
+ );
306
+ }
307
+ return context;
308
+ };
309
+
310
+ // ============================================================================
311
+ // Referenced Sources (Local to PromptInput)
312
+ // ============================================================================
313
+
314
+ export interface ReferencedSourcesContext {
315
+ sources: (SourceDocumentUIPart & { id: string })[];
316
+ add: (sources: SourceDocumentUIPart[] | SourceDocumentUIPart) => void;
317
+ remove: (id: string) => void;
318
+ clear: () => void;
319
+ }
320
+
321
+ export const LocalReferencedSourcesContext =
322
+ createContext<ReferencedSourcesContext | null>(null);
323
+
324
+ export const usePromptInputReferencedSources = () => {
325
+ const ctx = useContext(LocalReferencedSourcesContext);
326
+ if (!ctx) {
327
+ throw new Error(
328
+ "usePromptInputReferencedSources must be used within a LocalReferencedSourcesContext.Provider"
329
+ );
330
+ }
331
+ return ctx;
332
+ };
333
+
334
+ export type PromptInputActionAddAttachmentsProps = ComponentProps<
335
+ typeof DropdownMenuItem
336
+ > & {
337
+ label?: string;
338
+ };
339
+
340
+ export const PromptInputActionAddAttachments = ({
341
+ label = "Add photos or files",
342
+ ...props
343
+ }: PromptInputActionAddAttachmentsProps) => {
344
+ const attachments = usePromptInputAttachments();
345
+
346
+ const handleSelect = useCallback(
347
+ (e: Event) => {
348
+ e.preventDefault();
349
+ attachments.openFileDialog();
350
+ },
351
+ [attachments]
352
+ );
353
+
354
+ return (
355
+ <DropdownMenuItem {...props} onSelect={handleSelect}>
356
+ <ImageIcon className="mr-2 size-4" /> {label}
357
+ </DropdownMenuItem>
358
+ );
359
+ };
360
+
361
+ export interface PromptInputMessage {
362
+ text: string;
363
+ files: FileUIPart[];
364
+ }
365
+
366
+ export type PromptInputProps = Omit<
367
+ HTMLAttributes<HTMLFormElement>,
368
+ "onSubmit" | "onError"
369
+ > & {
370
+ // e.g., "image/*" or leave undefined for any
371
+ accept?: string;
372
+ multiple?: boolean;
373
+ // When true, accepts drops anywhere on document. Default false (opt-in).
374
+ globalDrop?: boolean;
375
+ // Render a hidden input with given name and keep it in sync for native form posts. Default false.
376
+ syncHiddenInput?: boolean;
377
+ // Minimal constraints
378
+ maxFiles?: number;
379
+ // bytes
380
+ maxFileSize?: number;
381
+ onError?: (err: {
382
+ code: "max_files" | "max_file_size" | "accept";
383
+ message: string;
384
+ }) => void;
385
+ onSubmit: (
386
+ message: PromptInputMessage,
387
+ event: FormEvent<HTMLFormElement>
388
+ ) => void | Promise<void>;
389
+ };
390
+
391
+ export const PromptInput = ({
392
+ className,
393
+ accept,
394
+ multiple,
395
+ globalDrop,
396
+ syncHiddenInput,
397
+ maxFiles,
398
+ maxFileSize,
399
+ onError,
400
+ onSubmit,
401
+ children,
402
+ ...props
403
+ }: PromptInputProps) => {
404
+ // Try to use a provider controller if present
405
+ const controller = useOptionalPromptInputController();
406
+ const usingProvider = !!controller;
407
+
408
+ // Refs
409
+ const inputRef = useRef<HTMLInputElement | null>(null);
410
+ const formRef = useRef<HTMLFormElement | null>(null);
411
+
412
+ // ----- Local attachments (only used when no provider)
413
+ const [items, setItems] = useState<(FileUIPart & { id: string })[]>([]);
414
+ const files = usingProvider ? controller.attachments.files : items;
415
+
416
+ // ----- Local referenced sources (always local to PromptInput)
417
+ const [referencedSources, setReferencedSources] = useState<
418
+ (SourceDocumentUIPart & { id: string })[]
419
+ >([]);
420
+
421
+ // Keep a ref to files for cleanup on unmount (avoids stale closure)
422
+ const filesRef = useRef(files);
423
+
424
+ useEffect(() => {
425
+ filesRef.current = files;
426
+ }, [files]);
427
+
428
+ const openFileDialogLocal = useCallback(() => {
429
+ inputRef.current?.click();
430
+ }, []);
431
+
432
+ const matchesAccept = useCallback(
433
+ (f: File) => {
434
+ if (!accept || accept.trim() === "") {
435
+ return true;
436
+ }
437
+
438
+ const patterns = accept
439
+ .split(",")
440
+ .map((s) => s.trim())
441
+ .filter(Boolean);
442
+
443
+ return patterns.some((pattern) => {
444
+ if (pattern.endsWith("/*")) {
445
+ // e.g: image/* -> image/
446
+ const prefix = pattern.slice(0, -1);
447
+ return f.type.startsWith(prefix);
448
+ }
449
+ return f.type === pattern;
450
+ });
451
+ },
452
+ [accept]
453
+ );
454
+
455
+ const addLocal = useCallback(
456
+ (fileList: File[] | FileList) => {
457
+ const incoming = [...fileList];
458
+ const accepted = incoming.filter((f) => matchesAccept(f));
459
+ if (incoming.length && accepted.length === 0) {
460
+ onError?.({
461
+ code: "accept",
462
+ message: "No files match the accepted types.",
463
+ });
464
+ return;
465
+ }
466
+ const withinSize = (f: File) =>
467
+ maxFileSize ? f.size <= maxFileSize : true;
468
+ const sized = accepted.filter(withinSize);
469
+ if (accepted.length > 0 && sized.length === 0) {
470
+ onError?.({
471
+ code: "max_file_size",
472
+ message: "All files exceed the maximum size.",
473
+ });
474
+ return;
475
+ }
476
+
477
+ setItems((prev) => {
478
+ const capacity =
479
+ typeof maxFiles === "number"
480
+ ? Math.max(0, maxFiles - prev.length)
481
+ : undefined;
482
+ const capped =
483
+ typeof capacity === "number" ? sized.slice(0, capacity) : sized;
484
+ if (typeof capacity === "number" && sized.length > capacity) {
485
+ onError?.({
486
+ code: "max_files",
487
+ message: "Too many files. Some were not added.",
488
+ });
489
+ }
490
+ const next: (FileUIPart & { id: string })[] = [];
491
+ for (const file of capped) {
492
+ next.push({
493
+ filename: file.name,
494
+ id: nanoid(),
495
+ mediaType: file.type,
496
+ type: "file",
497
+ url: URL.createObjectURL(file),
498
+ });
499
+ }
500
+ return [...prev, ...next];
501
+ });
502
+ },
503
+ [matchesAccept, maxFiles, maxFileSize, onError]
504
+ );
505
+
506
+ const removeLocal = useCallback(
507
+ (id: string) =>
508
+ setItems((prev) => {
509
+ const found = prev.find((file) => file.id === id);
510
+ if (found?.url) {
511
+ URL.revokeObjectURL(found.url);
512
+ }
513
+ return prev.filter((file) => file.id !== id);
514
+ }),
515
+ []
516
+ );
517
+
518
+ // Wrapper that validates files before calling provider's add
519
+ const addWithProviderValidation = useCallback(
520
+ (fileList: File[] | FileList) => {
521
+ const incoming = [...fileList];
522
+ const accepted = incoming.filter((f) => matchesAccept(f));
523
+ if (incoming.length && accepted.length === 0) {
524
+ onError?.({
525
+ code: "accept",
526
+ message: "No files match the accepted types.",
527
+ });
528
+ return;
529
+ }
530
+ const withinSize = (f: File) =>
531
+ maxFileSize ? f.size <= maxFileSize : true;
532
+ const sized = accepted.filter(withinSize);
533
+ if (accepted.length > 0 && sized.length === 0) {
534
+ onError?.({
535
+ code: "max_file_size",
536
+ message: "All files exceed the maximum size.",
537
+ });
538
+ return;
539
+ }
540
+
541
+ const currentCount = files.length;
542
+ const capacity =
543
+ typeof maxFiles === "number"
544
+ ? Math.max(0, maxFiles - currentCount)
545
+ : undefined;
546
+ const capped =
547
+ typeof capacity === "number" ? sized.slice(0, capacity) : sized;
548
+ if (typeof capacity === "number" && sized.length > capacity) {
549
+ onError?.({
550
+ code: "max_files",
551
+ message: "Too many files. Some were not added.",
552
+ });
553
+ }
554
+
555
+ if (capped.length > 0) {
556
+ controller?.attachments.add(capped);
557
+ }
558
+ },
559
+ [matchesAccept, maxFileSize, maxFiles, onError, files.length, controller]
560
+ );
561
+
562
+ const clearAttachments = useCallback(
563
+ () =>
564
+ usingProvider
565
+ ? controller?.attachments.clear()
566
+ : setItems((prev) => {
567
+ for (const file of prev) {
568
+ if (file.url) {
569
+ URL.revokeObjectURL(file.url);
570
+ }
571
+ }
572
+ return [];
573
+ }),
574
+ [usingProvider, controller]
575
+ );
576
+
577
+ const clearReferencedSources = useCallback(
578
+ () => setReferencedSources([]),
579
+ []
580
+ );
581
+
582
+ const add = usingProvider ? addWithProviderValidation : addLocal;
583
+ const remove = usingProvider ? controller.attachments.remove : removeLocal;
584
+ const openFileDialog = usingProvider
585
+ ? controller.attachments.openFileDialog
586
+ : openFileDialogLocal;
587
+
588
+ const clear = useCallback(() => {
589
+ clearAttachments();
590
+ clearReferencedSources();
591
+ }, [clearAttachments, clearReferencedSources]);
592
+
593
+ // Let provider know about our hidden file input so external menus can call openFileDialog()
594
+ useEffect(() => {
595
+ if (!usingProvider) {
596
+ return;
597
+ }
598
+ controller.__registerFileInput(inputRef, () => inputRef.current?.click());
599
+ }, [usingProvider, controller]);
600
+
601
+ // Note: File input cannot be programmatically set for security reasons
602
+ // The syncHiddenInput prop is no longer functional
603
+ useEffect(() => {
604
+ if (syncHiddenInput && inputRef.current && files.length === 0) {
605
+ inputRef.current.value = "";
606
+ }
607
+ }, [files, syncHiddenInput]);
608
+
609
+ // Attach drop handlers on nearest form and document (opt-in)
610
+ useEffect(() => {
611
+ const form = formRef.current;
612
+ if (!form) {
613
+ return;
614
+ }
615
+ if (globalDrop) {
616
+ // when global drop is on, let the document-level handler own drops
617
+ return;
618
+ }
619
+
620
+ const onDragOver = (e: DragEvent) => {
621
+ if (e.dataTransfer?.types?.includes("Files")) {
622
+ e.preventDefault();
623
+ }
624
+ };
625
+ const onDrop = (e: DragEvent) => {
626
+ if (e.dataTransfer?.types?.includes("Files")) {
627
+ e.preventDefault();
628
+ }
629
+ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
630
+ add(e.dataTransfer.files);
631
+ }
632
+ };
633
+ form.addEventListener("dragover", onDragOver);
634
+ form.addEventListener("drop", onDrop);
635
+ return () => {
636
+ form.removeEventListener("dragover", onDragOver);
637
+ form.removeEventListener("drop", onDrop);
638
+ };
639
+ }, [add, globalDrop]);
640
+
641
+ useEffect(() => {
642
+ if (!globalDrop) {
643
+ return;
644
+ }
645
+
646
+ const onDragOver = (e: DragEvent) => {
647
+ if (e.dataTransfer?.types?.includes("Files")) {
648
+ e.preventDefault();
649
+ }
650
+ };
651
+ const onDrop = (e: DragEvent) => {
652
+ if (e.dataTransfer?.types?.includes("Files")) {
653
+ e.preventDefault();
654
+ }
655
+ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
656
+ add(e.dataTransfer.files);
657
+ }
658
+ };
659
+ document.addEventListener("dragover", onDragOver);
660
+ document.addEventListener("drop", onDrop);
661
+ return () => {
662
+ document.removeEventListener("dragover", onDragOver);
663
+ document.removeEventListener("drop", onDrop);
664
+ };
665
+ }, [add, globalDrop]);
666
+
667
+ useEffect(
668
+ () => () => {
669
+ if (!usingProvider) {
670
+ for (const f of filesRef.current) {
671
+ if (f.url) {
672
+ URL.revokeObjectURL(f.url);
673
+ }
674
+ }
675
+ }
676
+ },
677
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- cleanup only on unmount; filesRef always current
678
+ [usingProvider]
679
+ );
680
+
681
+ const handleChange: ChangeEventHandler<HTMLInputElement> = useCallback(
682
+ (event) => {
683
+ if (event.currentTarget.files) {
684
+ add(event.currentTarget.files);
685
+ }
686
+ // Reset input value to allow selecting files that were previously removed
687
+ event.currentTarget.value = "";
688
+ },
689
+ [add]
690
+ );
691
+
692
+ const attachmentsCtx = useMemo<AttachmentsContext>(
693
+ () => ({
694
+ add,
695
+ clear: clearAttachments,
696
+ fileInputRef: inputRef,
697
+ files: files.map((item) => ({ ...item, id: item.id })),
698
+ openFileDialog,
699
+ remove,
700
+ }),
701
+ [files, add, remove, clearAttachments, openFileDialog]
702
+ );
703
+
704
+ const refsCtx = useMemo<ReferencedSourcesContext>(
705
+ () => ({
706
+ add: (incoming: SourceDocumentUIPart[] | SourceDocumentUIPart) => {
707
+ const array = Array.isArray(incoming) ? incoming : [incoming];
708
+ setReferencedSources((prev) => [
709
+ ...prev,
710
+ ...array.map((s) => ({ ...s, id: nanoid() })),
711
+ ]);
712
+ },
713
+ clear: clearReferencedSources,
714
+ remove: (id: string) => {
715
+ setReferencedSources((prev) => prev.filter((s) => s.id !== id));
716
+ },
717
+ sources: referencedSources,
718
+ }),
719
+ [referencedSources, clearReferencedSources]
720
+ );
721
+
722
+ const handleSubmit: FormEventHandler<HTMLFormElement> = useCallback(
723
+ async (event) => {
724
+ event.preventDefault();
725
+
726
+ const form = event.currentTarget;
727
+ const text = usingProvider
728
+ ? controller.textInput.value
729
+ : (() => {
730
+ const formData = new FormData(form);
731
+ return (formData.get("message") as string) || "";
732
+ })();
733
+
734
+ // Reset form immediately after capturing text to avoid race condition
735
+ // where user input during async blob conversion would be lost
736
+ if (!usingProvider) {
737
+ form.reset();
738
+ }
739
+
740
+ try {
741
+ // Convert blob URLs to data URLs asynchronously
742
+ const convertedFiles: FileUIPart[] = await Promise.all(
743
+ files.map(async ({ id: _id, ...item }) => {
744
+ if (item.url?.startsWith("blob:")) {
745
+ const dataUrl = await convertBlobUrlToDataUrl(item.url);
746
+ // If conversion failed, keep the original blob URL
747
+ return {
748
+ ...item,
749
+ url: dataUrl ?? item.url,
750
+ };
751
+ }
752
+ return item;
753
+ })
754
+ );
755
+
756
+ const result = onSubmit({ files: convertedFiles, text }, event);
757
+
758
+ // Handle both sync and async onSubmit
759
+ if (result instanceof Promise) {
760
+ try {
761
+ await result;
762
+ clear();
763
+ if (usingProvider) {
764
+ controller.textInput.clear();
765
+ }
766
+ } catch {
767
+ // Don't clear on error - user may want to retry
768
+ }
769
+ } else {
770
+ // Sync function completed without throwing, clear inputs
771
+ clear();
772
+ if (usingProvider) {
773
+ controller.textInput.clear();
774
+ }
775
+ }
776
+ } catch {
777
+ // Don't clear on error - user may want to retry
778
+ }
779
+ },
780
+ [usingProvider, controller, files, onSubmit, clear]
781
+ );
782
+
783
+ // Render with or without local provider
784
+ const inner = (
785
+ <>
786
+ <input
787
+ accept={accept}
788
+ aria-label="Upload files"
789
+ className="hidden"
790
+ multiple={multiple}
791
+ onChange={handleChange}
792
+ ref={inputRef}
793
+ title="Upload files"
794
+ type="file"
795
+ />
796
+ <form
797
+ className={cn("w-full", className)}
798
+ onSubmit={handleSubmit}
799
+ ref={formRef}
800
+ {...props}
801
+ >
802
+ <InputGroup className="overflow-hidden">{children}</InputGroup>
803
+ </form>
804
+ </>
805
+ );
806
+
807
+ const withReferencedSources = (
808
+ <LocalReferencedSourcesContext.Provider value={refsCtx}>
809
+ {inner}
810
+ </LocalReferencedSourcesContext.Provider>
811
+ );
812
+
813
+ // Always provide LocalAttachmentsContext so children get validated add function
814
+ return (
815
+ <LocalAttachmentsContext.Provider value={attachmentsCtx}>
816
+ {withReferencedSources}
817
+ </LocalAttachmentsContext.Provider>
818
+ );
819
+ };
820
+
821
+ export type PromptInputBodyProps = HTMLAttributes<HTMLDivElement>;
822
+
823
+ export const PromptInputBody = ({
824
+ className,
825
+ ...props
826
+ }: PromptInputBodyProps) => (
827
+ <div className={cn("contents", className)} {...props} />
828
+ );
829
+
830
+ export type PromptInputTextareaProps = ComponentProps<
831
+ typeof InputGroupTextarea
832
+ >;
833
+
834
+ export const PromptInputTextarea = ({
835
+ onChange,
836
+ onKeyDown,
837
+ className,
838
+ placeholder = "What would you like to know?",
839
+ ...props
840
+ }: PromptInputTextareaProps) => {
841
+ const controller = useOptionalPromptInputController();
842
+ const attachments = usePromptInputAttachments();
843
+ const [isComposing, setIsComposing] = useState(false);
844
+
845
+ const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = useCallback(
846
+ (e) => {
847
+ // Call the external onKeyDown handler first
848
+ onKeyDown?.(e);
849
+
850
+ // If the external handler prevented default, don't run internal logic
851
+ if (e.defaultPrevented) {
852
+ return;
853
+ }
854
+
855
+ if (e.key === "Enter") {
856
+ if (isComposing || e.nativeEvent.isComposing) {
857
+ return;
858
+ }
859
+ if (e.shiftKey) {
860
+ return;
861
+ }
862
+ e.preventDefault();
863
+
864
+ // Check if the submit button is disabled before submitting
865
+ const { form } = e.currentTarget;
866
+ const submitButton = form?.querySelector(
867
+ 'button[type="submit"]'
868
+ ) as HTMLButtonElement | null;
869
+ if (submitButton?.disabled) {
870
+ return;
871
+ }
872
+
873
+ form?.requestSubmit();
874
+ }
875
+
876
+ // Remove last attachment when Backspace is pressed and textarea is empty
877
+ if (
878
+ e.key === "Backspace" &&
879
+ e.currentTarget.value === "" &&
880
+ attachments.files.length > 0
881
+ ) {
882
+ e.preventDefault();
883
+ const lastAttachment = attachments.files.at(-1);
884
+ if (lastAttachment) {
885
+ attachments.remove(lastAttachment.id);
886
+ }
887
+ }
888
+ },
889
+ [onKeyDown, isComposing, attachments]
890
+ );
891
+
892
+ const handlePaste: ClipboardEventHandler<HTMLTextAreaElement> = useCallback(
893
+ (event) => {
894
+ const items = event.clipboardData?.items;
895
+
896
+ if (!items) {
897
+ return;
898
+ }
899
+
900
+ const files: File[] = [];
901
+
902
+ for (const item of items) {
903
+ if (item.kind === "file") {
904
+ const file = item.getAsFile();
905
+ if (file) {
906
+ files.push(file);
907
+ }
908
+ }
909
+ }
910
+
911
+ if (files.length > 0) {
912
+ event.preventDefault();
913
+ attachments.add(files);
914
+ }
915
+ },
916
+ [attachments]
917
+ );
918
+
919
+ const handleCompositionEnd = useCallback(() => setIsComposing(false), []);
920
+ const handleCompositionStart = useCallback(() => setIsComposing(true), []);
921
+
922
+ const controlledProps = controller
923
+ ? {
924
+ onChange: (e: ChangeEvent<HTMLTextAreaElement>) => {
925
+ controller.textInput.setInput(e.currentTarget.value);
926
+ onChange?.(e);
927
+ },
928
+ value: controller.textInput.value,
929
+ }
930
+ : {
931
+ onChange,
932
+ };
933
+
934
+ return (
935
+ <InputGroupTextarea
936
+ className={cn("field-sizing-content max-h-48 min-h-16", className)}
937
+ name="message"
938
+ onCompositionEnd={handleCompositionEnd}
939
+ onCompositionStart={handleCompositionStart}
940
+ onKeyDown={handleKeyDown}
941
+ onPaste={handlePaste}
942
+ placeholder={placeholder}
943
+ {...props}
944
+ {...controlledProps}
945
+ />
946
+ );
947
+ };
948
+
949
+ export type PromptInputHeaderProps = Omit<
950
+ ComponentProps<typeof InputGroupAddon>,
951
+ "align"
952
+ >;
953
+
954
+ export const PromptInputHeader = ({
955
+ className,
956
+ ...props
957
+ }: PromptInputHeaderProps) => (
958
+ <InputGroupAddon
959
+ align="block-end"
960
+ className={cn("order-first flex-wrap gap-1", className)}
961
+ {...props}
962
+ />
963
+ );
964
+
965
+ export type PromptInputFooterProps = Omit<
966
+ ComponentProps<typeof InputGroupAddon>,
967
+ "align"
968
+ >;
969
+
970
+ export const PromptInputFooter = ({
971
+ className,
972
+ ...props
973
+ }: PromptInputFooterProps) => (
974
+ <InputGroupAddon
975
+ align="block-end"
976
+ className={cn("justify-between gap-1", className)}
977
+ {...props}
978
+ />
979
+ );
980
+
981
+ export type PromptInputToolsProps = HTMLAttributes<HTMLDivElement>;
982
+
983
+ export const PromptInputTools = ({
984
+ className,
985
+ ...props
986
+ }: PromptInputToolsProps) => (
987
+ <div
988
+ className={cn("flex min-w-0 items-center gap-1", className)}
989
+ {...props}
990
+ />
991
+ );
992
+
993
+ export type PromptInputButtonTooltip =
994
+ | string
995
+ | {
996
+ content: ReactNode;
997
+ shortcut?: string;
998
+ side?: ComponentProps<typeof TooltipContent>["side"];
999
+ };
1000
+
1001
+ export type PromptInputButtonProps = ComponentProps<typeof InputGroupButton> & {
1002
+ tooltip?: PromptInputButtonTooltip;
1003
+ };
1004
+
1005
+ export const PromptInputButton = ({
1006
+ variant = "ghost",
1007
+ className,
1008
+ size,
1009
+ tooltip,
1010
+ ...props
1011
+ }: PromptInputButtonProps) => {
1012
+ const newSize =
1013
+ size ?? (Children.count(props.children) > 1 ? "sm" : "icon-sm");
1014
+
1015
+ const button = (
1016
+ <InputGroupButton
1017
+ className={cn(className)}
1018
+ size={newSize}
1019
+ type="button"
1020
+ variant={variant}
1021
+ {...props}
1022
+ />
1023
+ );
1024
+
1025
+ if (!tooltip) {
1026
+ return button;
1027
+ }
1028
+
1029
+ const tooltipContent =
1030
+ typeof tooltip === "string" ? tooltip : tooltip.content;
1031
+ const shortcut = typeof tooltip === "string" ? undefined : tooltip.shortcut;
1032
+ const side = typeof tooltip === "string" ? "top" : (tooltip.side ?? "top");
1033
+
1034
+ return (
1035
+ <Tooltip>
1036
+ <TooltipTrigger asChild>{button}</TooltipTrigger>
1037
+ <TooltipContent side={side}>
1038
+ {tooltipContent}
1039
+ {shortcut && (
1040
+ <span className="ml-2 text-muted-foreground">{shortcut}</span>
1041
+ )}
1042
+ </TooltipContent>
1043
+ </Tooltip>
1044
+ );
1045
+ };
1046
+
1047
+ export type PromptInputActionMenuProps = ComponentProps<typeof DropdownMenu>;
1048
+ export const PromptInputActionMenu = (props: PromptInputActionMenuProps) => (
1049
+ <DropdownMenu {...props} />
1050
+ );
1051
+
1052
+ export type PromptInputActionMenuTriggerProps = PromptInputButtonProps;
1053
+
1054
+ export const PromptInputActionMenuTrigger = ({
1055
+ className,
1056
+ children,
1057
+ ...props
1058
+ }: PromptInputActionMenuTriggerProps) => (
1059
+ <DropdownMenuTrigger asChild>
1060
+ <PromptInputButton className={className} {...props}>
1061
+ {children ?? <PlusIcon className="size-4" />}
1062
+ </PromptInputButton>
1063
+ </DropdownMenuTrigger>
1064
+ );
1065
+
1066
+ export type PromptInputActionMenuContentProps = ComponentProps<
1067
+ typeof DropdownMenuContent
1068
+ >;
1069
+ export const PromptInputActionMenuContent = ({
1070
+ className,
1071
+ ...props
1072
+ }: PromptInputActionMenuContentProps) => (
1073
+ <DropdownMenuContent align="start" className={cn(className)} {...props} />
1074
+ );
1075
+
1076
+ export type PromptInputActionMenuItemProps = ComponentProps<
1077
+ typeof DropdownMenuItem
1078
+ >;
1079
+ export const PromptInputActionMenuItem = ({
1080
+ className,
1081
+ ...props
1082
+ }: PromptInputActionMenuItemProps) => (
1083
+ <DropdownMenuItem className={cn(className)} {...props} />
1084
+ );
1085
+
1086
+ // Note: Actions that perform side-effects (like opening a file dialog)
1087
+ // are provided in opt-in modules (e.g., prompt-input-attachments).
1088
+
1089
+ export type PromptInputSubmitProps = ComponentProps<typeof InputGroupButton> & {
1090
+ status?: ChatStatus;
1091
+ onStop?: () => void;
1092
+ };
1093
+
1094
+ export const PromptInputSubmit = ({
1095
+ className,
1096
+ variant = "default",
1097
+ size = "icon-sm",
1098
+ status,
1099
+ onStop,
1100
+ onClick,
1101
+ children,
1102
+ ...props
1103
+ }: PromptInputSubmitProps) => {
1104
+ const isGenerating = status === "submitted" || status === "streaming";
1105
+
1106
+ let Icon = <CornerDownLeftIcon className="size-4" />;
1107
+
1108
+ if (status === "submitted") {
1109
+ Icon = <Spinner />;
1110
+ } else if (status === "streaming") {
1111
+ Icon = <SquareIcon className="size-4" />;
1112
+ } else if (status === "error") {
1113
+ Icon = <XIcon className="size-4" />;
1114
+ }
1115
+
1116
+ const handleClick = useCallback(
1117
+ (e: React.MouseEvent<HTMLButtonElement>) => {
1118
+ if (isGenerating && onStop) {
1119
+ e.preventDefault();
1120
+ onStop();
1121
+ return;
1122
+ }
1123
+ onClick?.(e);
1124
+ },
1125
+ [isGenerating, onStop, onClick]
1126
+ );
1127
+
1128
+ return (
1129
+ <InputGroupButton
1130
+ aria-label={isGenerating ? "Stop" : "Submit"}
1131
+ className={cn(className)}
1132
+ onClick={handleClick}
1133
+ size={size}
1134
+ type={isGenerating && onStop ? "button" : "submit"}
1135
+ variant={variant}
1136
+ {...props}
1137
+ >
1138
+ {children ?? Icon}
1139
+ </InputGroupButton>
1140
+ );
1141
+ };
1142
+
1143
+ export type PromptInputSelectProps = ComponentProps<typeof Select>;
1144
+
1145
+ export const PromptInputSelect = (props: PromptInputSelectProps) => (
1146
+ <Select {...props} />
1147
+ );
1148
+
1149
+ export type PromptInputSelectTriggerProps = ComponentProps<
1150
+ typeof SelectTrigger
1151
+ >;
1152
+
1153
+ export const PromptInputSelectTrigger = ({
1154
+ className,
1155
+ ...props
1156
+ }: PromptInputSelectTriggerProps) => (
1157
+ <SelectTrigger
1158
+ className={cn(
1159
+ "border-none bg-transparent font-medium text-muted-foreground shadow-none transition-colors",
1160
+ "hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground",
1161
+ className
1162
+ )}
1163
+ {...props}
1164
+ />
1165
+ );
1166
+
1167
+ export type PromptInputSelectContentProps = ComponentProps<
1168
+ typeof SelectContent
1169
+ >;
1170
+
1171
+ export const PromptInputSelectContent = ({
1172
+ className,
1173
+ ...props
1174
+ }: PromptInputSelectContentProps) => (
1175
+ <SelectContent className={cn(className)} {...props} />
1176
+ );
1177
+
1178
+ export type PromptInputSelectItemProps = ComponentProps<typeof SelectItem>;
1179
+
1180
+ export const PromptInputSelectItem = ({
1181
+ className,
1182
+ ...props
1183
+ }: PromptInputSelectItemProps) => (
1184
+ <SelectItem className={cn(className)} {...props} />
1185
+ );
1186
+
1187
+ export type PromptInputSelectValueProps = ComponentProps<typeof SelectValue>;
1188
+
1189
+ export const PromptInputSelectValue = ({
1190
+ className,
1191
+ ...props
1192
+ }: PromptInputSelectValueProps) => (
1193
+ <SelectValue className={cn(className)} {...props} />
1194
+ );
1195
+
1196
+ export type PromptInputHoverCardProps = ComponentProps<typeof HoverCard>;
1197
+
1198
+ export const PromptInputHoverCard = ({
1199
+ openDelay = 0,
1200
+ closeDelay = 0,
1201
+ ...props
1202
+ }: PromptInputHoverCardProps) => (
1203
+ <HoverCard closeDelay={closeDelay} openDelay={openDelay} {...props} />
1204
+ );
1205
+
1206
+ export type PromptInputHoverCardTriggerProps = ComponentProps<
1207
+ typeof HoverCardTrigger
1208
+ >;
1209
+
1210
+ export const PromptInputHoverCardTrigger = (
1211
+ props: PromptInputHoverCardTriggerProps
1212
+ ) => <HoverCardTrigger {...props} />;
1213
+
1214
+ export type PromptInputHoverCardContentProps = ComponentProps<
1215
+ typeof HoverCardContent
1216
+ >;
1217
+
1218
+ export const PromptInputHoverCardContent = ({
1219
+ align = "start",
1220
+ ...props
1221
+ }: PromptInputHoverCardContentProps) => (
1222
+ <HoverCardContent align={align} {...props} />
1223
+ );
1224
+
1225
+ export type PromptInputTabsListProps = HTMLAttributes<HTMLDivElement>;
1226
+
1227
+ export const PromptInputTabsList = ({
1228
+ className,
1229
+ ...props
1230
+ }: PromptInputTabsListProps) => <div className={cn(className)} {...props} />;
1231
+
1232
+ export type PromptInputTabProps = HTMLAttributes<HTMLDivElement>;
1233
+
1234
+ export const PromptInputTab = ({
1235
+ className,
1236
+ ...props
1237
+ }: PromptInputTabProps) => <div className={cn(className)} {...props} />;
1238
+
1239
+ export type PromptInputTabLabelProps = HTMLAttributes<HTMLHeadingElement>;
1240
+
1241
+ export const PromptInputTabLabel = ({
1242
+ className,
1243
+ ...props
1244
+ }: PromptInputTabLabelProps) => (
1245
+ // Content provided via children in props
1246
+ // oxlint-disable-next-line eslint-plugin-jsx-a11y(heading-has-content)
1247
+ <h3
1248
+ className={cn(
1249
+ "mb-2 px-3 font-medium text-muted-foreground text-xs",
1250
+ className
1251
+ )}
1252
+ {...props}
1253
+ />
1254
+ );
1255
+
1256
+ export type PromptInputTabBodyProps = HTMLAttributes<HTMLDivElement>;
1257
+
1258
+ export const PromptInputTabBody = ({
1259
+ className,
1260
+ ...props
1261
+ }: PromptInputTabBodyProps) => (
1262
+ <div className={cn("space-y-1", className)} {...props} />
1263
+ );
1264
+
1265
+ export type PromptInputTabItemProps = HTMLAttributes<HTMLDivElement>;
1266
+
1267
+ export const PromptInputTabItem = ({
1268
+ className,
1269
+ ...props
1270
+ }: PromptInputTabItemProps) => (
1271
+ <div
1272
+ className={cn(
1273
+ "flex items-center gap-2 px-3 py-2 text-xs hover:bg-accent",
1274
+ className
1275
+ )}
1276
+ {...props}
1277
+ />
1278
+ );
1279
+
1280
+ export type PromptInputCommandProps = ComponentProps<typeof Command>;
1281
+
1282
+ export const PromptInputCommand = ({
1283
+ className,
1284
+ ...props
1285
+ }: PromptInputCommandProps) => <Command className={cn(className)} {...props} />;
1286
+
1287
+ export type PromptInputCommandInputProps = ComponentProps<typeof CommandInput>;
1288
+
1289
+ export const PromptInputCommandInput = ({
1290
+ className,
1291
+ ...props
1292
+ }: PromptInputCommandInputProps) => (
1293
+ <CommandInput className={cn(className)} {...props} />
1294
+ );
1295
+
1296
+ export type PromptInputCommandListProps = ComponentProps<typeof CommandList>;
1297
+
1298
+ export const PromptInputCommandList = ({
1299
+ className,
1300
+ ...props
1301
+ }: PromptInputCommandListProps) => (
1302
+ <CommandList className={cn(className)} {...props} />
1303
+ );
1304
+
1305
+ export type PromptInputCommandEmptyProps = ComponentProps<typeof CommandEmpty>;
1306
+
1307
+ export const PromptInputCommandEmpty = ({
1308
+ className,
1309
+ ...props
1310
+ }: PromptInputCommandEmptyProps) => (
1311
+ <CommandEmpty className={cn(className)} {...props} />
1312
+ );
1313
+
1314
+ export type PromptInputCommandGroupProps = ComponentProps<typeof CommandGroup>;
1315
+
1316
+ export const PromptInputCommandGroup = ({
1317
+ className,
1318
+ ...props
1319
+ }: PromptInputCommandGroupProps) => (
1320
+ <CommandGroup className={cn(className)} {...props} />
1321
+ );
1322
+
1323
+ export type PromptInputCommandItemProps = ComponentProps<typeof CommandItem>;
1324
+
1325
+ export const PromptInputCommandItem = ({
1326
+ className,
1327
+ ...props
1328
+ }: PromptInputCommandItemProps) => (
1329
+ <CommandItem className={cn(className)} {...props} />
1330
+ );
1331
+
1332
+ export type PromptInputCommandSeparatorProps = ComponentProps<
1333
+ typeof CommandSeparator
1334
+ >;
1335
+
1336
+ export const PromptInputCommandSeparator = ({
1337
+ className,
1338
+ ...props
1339
+ }: PromptInputCommandSeparatorProps) => (
1340
+ <CommandSeparator className={cn(className)} {...props} />
1341
+ );