queue-prompt-input.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. * Derived from vercel/ai-elements (skills/ai-elements/scripts/queue-prompt-input.tsx).
  3. * Copyright 2023 Vercel, Inc. Licensed under Apache-2.0.
  4. * Modified by ZCode: local integration, formatting and adaptations.
  5. * See THIRD-PARTY-NOTICES.md in the repository root for license and provenance.
  6. */
  7. "use client";
  8. import {
  9. Attachment,
  10. AttachmentPreview,
  11. AttachmentRemove,
  12. Attachments,
  13. } from "@/components/ai-elements/attachments";
  14. import {
  15. ModelSelector,
  16. ModelSelectorContent,
  17. ModelSelectorEmpty,
  18. ModelSelectorGroup,
  19. ModelSelectorInput,
  20. ModelSelectorItem,
  21. ModelSelectorList,
  22. ModelSelectorLogo,
  23. ModelSelectorLogoGroup,
  24. ModelSelectorName,
  25. ModelSelectorTrigger,
  26. } from "@/components/ai-elements/model-selector";
  27. import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
  28. import {
  29. PromptInput,
  30. PromptInputActionAddAttachments,
  31. PromptInputActionMenu,
  32. PromptInputActionMenuContent,
  33. PromptInputActionMenuTrigger,
  34. PromptInputBody,
  35. PromptInputButton,
  36. PromptInputFooter,
  37. PromptInputHeader,
  38. PromptInputSubmit,
  39. PromptInputTextarea,
  40. PromptInputTools,
  41. usePromptInputAttachments,
  42. } from "@/components/ai-elements/prompt-input";
  43. import type { QueueTodo } from "@/components/ai-elements/queue";
  44. import {
  45. Queue,
  46. QueueItem,
  47. QueueItemAction,
  48. QueueItemActions,
  49. QueueItemContent,
  50. QueueItemDescription,
  51. QueueItemIndicator,
  52. QueueSection,
  53. QueueSectionContent,
  54. } from "@/components/ai-elements/queue";
  55. import { CheckIcon, GlobeIcon, Trash2 } from "lucide-react";
  56. import { memo, useCallback, useRef, useState } from "react";
  57. const models = [
  58. {
  59. chef: "OpenAI",
  60. chefSlug: "openai",
  61. id: "gpt-4o",
  62. name: "GPT-4o",
  63. providers: ["openai", "azure"],
  64. },
  65. {
  66. chef: "OpenAI",
  67. chefSlug: "openai",
  68. id: "gpt-4o-mini",
  69. name: "GPT-4o Mini",
  70. providers: ["openai", "azure"],
  71. },
  72. {
  73. chef: "Anthropic",
  74. chefSlug: "anthropic",
  75. id: "claude-opus-4-20250514",
  76. name: "Claude 4 Opus",
  77. providers: ["anthropic", "azure", "google", "amazon-bedrock"],
  78. },
  79. {
  80. chef: "Anthropic",
  81. chefSlug: "anthropic",
  82. id: "claude-sonnet-4-20250514",
  83. name: "Claude 4 Sonnet",
  84. providers: ["anthropic", "azure", "google", "amazon-bedrock"],
  85. },
  86. {
  87. chef: "Google",
  88. chefSlug: "google",
  89. id: "gemini-2.0-flash-exp",
  90. name: "Gemini 2.0 Flash",
  91. providers: ["google"],
  92. },
  93. ];
  94. const SUBMITTING_TIMEOUT = 200;
  95. const STREAMING_TIMEOUT = 2000;
  96. interface AttachmentItemProps {
  97. attachment: {
  98. id: string;
  99. type: "file";
  100. filename?: string;
  101. mediaType?: string;
  102. url: string;
  103. };
  104. onRemove: (id: string) => void;
  105. }
  106. const AttachmentItem = memo(({ attachment, onRemove }: AttachmentItemProps) => {
  107. const handleRemove = useCallback(() => onRemove(attachment.id), [onRemove, attachment.id]);
  108. return (
  109. <Attachment data={attachment} key={attachment.id} onRemove={handleRemove}>
  110. <AttachmentPreview />
  111. <AttachmentRemove />
  112. </Attachment>
  113. );
  114. });
  115. AttachmentItem.displayName = "AttachmentItem";
  116. interface TodoItemProps {
  117. todo: QueueTodo;
  118. onRemove: (id: string) => void;
  119. }
  120. const TodoItem = memo(({ todo, onRemove }: TodoItemProps) => {
  121. const isCompleted = todo.status === "completed";
  122. const handleRemove = useCallback(() => onRemove(todo.id), [onRemove, todo.id]);
  123. return (
  124. <QueueItem key={todo.id}>
  125. <div className="flex items-center gap-2">
  126. <QueueItemIndicator completed={isCompleted} />
  127. <QueueItemContent completed={isCompleted}>{todo.title}</QueueItemContent>
  128. <QueueItemActions>
  129. <QueueItemAction aria-label="Remove todo" onClick={handleRemove}>
  130. <Trash2 size={12} />
  131. </QueueItemAction>
  132. </QueueItemActions>
  133. </div>
  134. {todo.description && (
  135. <QueueItemDescription completed={isCompleted}>{todo.description}</QueueItemDescription>
  136. )}
  137. </QueueItem>
  138. );
  139. });
  140. TodoItem.displayName = "TodoItem";
  141. interface ModelItemProps {
  142. m: (typeof models)[0];
  143. selectedModel: string;
  144. onSelect: (id: string) => void;
  145. }
  146. const ModelItem = memo(({ m, selectedModel, onSelect }: ModelItemProps) => {
  147. const handleSelect = useCallback(() => onSelect(m.id), [onSelect, m.id]);
  148. return (
  149. <ModelSelectorItem key={m.id} onSelect={handleSelect} value={m.id}>
  150. <ModelSelectorLogo provider={m.chefSlug} />
  151. <ModelSelectorName>{m.name}</ModelSelectorName>
  152. <ModelSelectorLogoGroup>
  153. {m.providers.map((provider) => (
  154. <ModelSelectorLogo key={provider} provider={provider} />
  155. ))}
  156. </ModelSelectorLogoGroup>
  157. {selectedModel === m.id ? (
  158. <CheckIcon className="ml-auto size-4" />
  159. ) : (
  160. <div className="ml-auto size-4" />
  161. )}
  162. </ModelSelectorItem>
  163. );
  164. });
  165. ModelItem.displayName = "ModelItem";
  166. const sampleTodos: QueueTodo[] = [
  167. {
  168. description: "Complete the README and API docs",
  169. id: "todo-1",
  170. status: "completed",
  171. title: "Write project documentation",
  172. },
  173. {
  174. id: "todo-2",
  175. status: "pending",
  176. title: "Implement authentication",
  177. },
  178. {
  179. description: "Resolve crash on settings page",
  180. id: "todo-3",
  181. status: "pending",
  182. title: "Fix bug #42",
  183. },
  184. {
  185. description: "Unify queue and todo state management",
  186. id: "todo-4",
  187. status: "pending",
  188. title: "Refactor queue logic",
  189. },
  190. {
  191. description: "Increase test coverage for hooks",
  192. id: "todo-5",
  193. status: "pending",
  194. title: "Add unit tests",
  195. },
  196. ];
  197. const PromptInputAttachmentsDisplay = () => {
  198. const attachments = usePromptInputAttachments();
  199. const handleRemove = useCallback((id: string) => attachments.remove(id), [attachments]);
  200. if (attachments.files.length === 0) {
  201. return null;
  202. }
  203. return (
  204. <Attachments variant="inline">
  205. {attachments.files.map((attachment) => (
  206. <AttachmentItem attachment={attachment} key={attachment.id} onRemove={handleRemove} />
  207. ))}
  208. </Attachments>
  209. );
  210. };
  211. const Example = () => {
  212. const [todos, setTodos] = useState(sampleTodos);
  213. const handleRemoveTodo = useCallback((id: string) => {
  214. setTodos((prev) => prev.filter((todo) => todo.id !== id));
  215. }, []);
  216. const [text, setText] = useState<string>("");
  217. const [model, setModel] = useState<string>(models[0].id);
  218. const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
  219. const [status, setStatus] = useState<"submitted" | "streaming" | "ready" | "error">("ready");
  220. const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  221. const handleTextChange = useCallback(
  222. (e: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value),
  223. [],
  224. );
  225. const handleModelSelect = useCallback((id: string) => {
  226. setModel(id);
  227. setModelSelectorOpen(false);
  228. }, []);
  229. const selectedModelData = models.find((m) => m.id === model);
  230. const stop = () => {
  231. console.log("Stopping request...");
  232. // Clear any pending timeouts
  233. if (timeoutRef.current) {
  234. clearTimeout(timeoutRef.current);
  235. timeoutRef.current = null;
  236. }
  237. setStatus("ready");
  238. };
  239. const handleSubmit = useCallback(
  240. (message: PromptInputMessage) => {
  241. // If currently streaming or submitted, stop instead of submitting
  242. if (status === "streaming" || status === "submitted") {
  243. stop();
  244. return;
  245. }
  246. const hasText = Boolean(message.text);
  247. const hasAttachments = Boolean(message.files?.length);
  248. if (!(hasText || hasAttachments)) {
  249. return;
  250. }
  251. setStatus("submitted");
  252. console.log("Submitting message:", message);
  253. setTimeout(() => {
  254. setStatus("streaming");
  255. }, SUBMITTING_TIMEOUT);
  256. timeoutRef.current = setTimeout(() => {
  257. setStatus("ready");
  258. timeoutRef.current = null;
  259. }, STREAMING_TIMEOUT);
  260. },
  261. [status],
  262. );
  263. return (
  264. <div className="flex size-full flex-col justify-end">
  265. <Queue className="mx-auto max-h-[150px] w-[95%] overflow-y-auto rounded-b-none border-input border-b-0">
  266. {todos.length > 0 && (
  267. <QueueSection>
  268. <QueueSectionContent>
  269. <div>
  270. {todos.map((todo) => (
  271. <TodoItem key={todo.id} onRemove={handleRemoveTodo} todo={todo} />
  272. ))}
  273. </div>
  274. </QueueSectionContent>
  275. </QueueSection>
  276. )}
  277. </Queue>
  278. <PromptInput globalDrop multiple onSubmit={handleSubmit}>
  279. <PromptInputHeader>
  280. <PromptInputAttachmentsDisplay />
  281. </PromptInputHeader>
  282. <PromptInputBody>
  283. <PromptInputTextarea onChange={handleTextChange} value={text} />
  284. </PromptInputBody>
  285. <PromptInputFooter>
  286. <PromptInputTools>
  287. <PromptInputActionMenu>
  288. <PromptInputActionMenuTrigger />
  289. <PromptInputActionMenuContent>
  290. <PromptInputActionAddAttachments />
  291. </PromptInputActionMenuContent>
  292. </PromptInputActionMenu>
  293. <PromptInputButton>
  294. <GlobeIcon size={16} />
  295. <span>Search</span>
  296. </PromptInputButton>
  297. <ModelSelector onOpenChange={setModelSelectorOpen} open={modelSelectorOpen}>
  298. <ModelSelectorTrigger asChild>
  299. <PromptInputButton>
  300. {selectedModelData?.chefSlug && (
  301. <ModelSelectorLogo provider={selectedModelData.chefSlug} />
  302. )}
  303. {selectedModelData?.name && (
  304. <ModelSelectorName>{selectedModelData.name}</ModelSelectorName>
  305. )}
  306. </PromptInputButton>
  307. </ModelSelectorTrigger>
  308. <ModelSelectorContent>
  309. <ModelSelectorInput placeholder="Search models..." />
  310. <ModelSelectorList>
  311. <ModelSelectorEmpty>No models found.</ModelSelectorEmpty>
  312. {["OpenAI", "Anthropic", "Google"].map((chef) => (
  313. <ModelSelectorGroup heading={chef} key={chef}>
  314. {models
  315. .filter((m) => m.chef === chef)
  316. .map((m) => (
  317. <ModelItem
  318. key={m.id}
  319. m={m}
  320. onSelect={handleModelSelect}
  321. selectedModel={model}
  322. />
  323. ))}
  324. </ModelSelectorGroup>
  325. ))}
  326. </ModelSelectorList>
  327. </ModelSelectorContent>
  328. </ModelSelector>
  329. </PromptInputTools>
  330. <PromptInputSubmit status={status} />
  331. </PromptInputFooter>
  332. </PromptInput>
  333. </div>
  334. );
  335. };
  336. export default Example;