@conscience-technology/ovenn 0.7.3 → 0.7.5

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 (150) hide show
  1. package/assets/components/AIMessage/AIMessage.module.css +10 -0
  2. package/assets/components/AIMessage/AIMessage.tsx +6 -2
  3. package/assets/components/Breadcrumb/Breadcrumb.module.css +82 -23
  4. package/assets/components/Breadcrumb/Breadcrumb.tsx +44 -26
  5. package/assets/components/Breadcrumb/index.ts +1 -0
  6. package/assets/components/Button/Button.module.css +2 -4
  7. package/assets/components/Callout/Callout.module.css +44 -18
  8. package/assets/components/Callout/Callout.tsx +9 -4
  9. package/assets/components/Callout/index.ts +1 -1
  10. package/assets/components/Canvas/Canvas.module.css +13 -0
  11. package/assets/components/Canvas/Canvas.tsx +378 -94
  12. package/assets/components/Canvas/clipboard.ts +5 -1
  13. package/assets/components/Canvas/collision.ts +5 -1
  14. package/assets/components/Canvas/graph.ts +14 -5
  15. package/assets/components/Canvas/history.ts +11 -4
  16. package/assets/components/Canvas/index.ts +2 -1
  17. package/assets/components/Canvas/types.ts +36 -1
  18. package/assets/components/CanvasEdge/tokens.css +14 -1
  19. package/assets/components/CanvasNode/tokens.css +13 -10
  20. package/assets/components/ChatInput/ChatInput.tsx +1 -1
  21. package/assets/components/ColorField/ColorField.module.css +6 -1
  22. package/assets/components/ColorPicker/ColorPicker.module.css +3 -0
  23. package/assets/components/CommandPalette/CommandPalette.module.css +115 -1
  24. package/assets/components/CommandPalette/CommandPalette.tsx +206 -21
  25. package/assets/components/CommandPalette/index.ts +1 -0
  26. package/assets/components/DatePicker/DatePicker.module.css +3 -2
  27. package/assets/components/Drawer/Drawer.module.css +30 -0
  28. package/assets/components/Drawer/Drawer.tsx +75 -16
  29. package/assets/components/Drawer/index.ts +1 -0
  30. package/assets/components/Icon/Icon.tsx +3 -0
  31. package/assets/components/Input/Input.module.css +4 -4
  32. package/assets/components/Select/Select.module.css +6 -2
  33. package/assets/components/SocialLoginButton/SocialLoginButton.module.css +198 -0
  34. package/assets/components/SocialLoginButton/SocialLoginButton.tsx +86 -0
  35. package/assets/components/SocialLoginButton/assets/amazon.svg +1 -0
  36. package/assets/components/SocialLoginButton/assets/apple.svg +3 -0
  37. package/assets/components/SocialLoginButton/assets/discord.svg +3 -0
  38. package/assets/components/SocialLoginButton/assets/facebook-white.png +0 -0
  39. package/assets/components/SocialLoginButton/assets/facebook.png +0 -0
  40. package/assets/components/SocialLoginButton/assets/github.svg +3 -0
  41. package/assets/components/SocialLoginButton/assets/google-mark.png +0 -0
  42. package/assets/components/SocialLoginButton/assets/kakao.svg +3 -0
  43. package/assets/components/SocialLoginButton/assets/line-icon.png +0 -0
  44. package/assets/components/SocialLoginButton/assets/line-white.png +0 -0
  45. package/assets/components/SocialLoginButton/assets/linkedin-white.png +0 -0
  46. package/assets/components/SocialLoginButton/assets/linkedin.png +0 -0
  47. package/assets/components/SocialLoginButton/assets/microsoft.svg +6 -0
  48. package/assets/components/SocialLoginButton/assets/naver.png +0 -0
  49. package/assets/components/SocialLoginButton/assets/slack.svg +17 -0
  50. package/assets/components/SocialLoginButton/assets/spotify.svg +3 -0
  51. package/assets/components/SocialLoginButton/assets/twitch.svg +21 -0
  52. package/assets/components/SocialLoginButton/assets/wechat.png +0 -0
  53. package/assets/components/SocialLoginButton/assets/x.svg +3 -0
  54. package/assets/components/SocialLoginButton/index.ts +2 -0
  55. package/assets/components/SocialLoginButton/provider-tokens.css +30 -0
  56. package/assets/components/SocialLoginButton/providers.ts +23 -0
  57. package/assets/components/TimePicker/TimePicker.module.css +3 -2
  58. package/assets/components/_data.ts +1 -1
  59. package/assets/components/_utils.css +2 -2
  60. package/assets/components/component-registry.json +30 -1
  61. package/assets/components/index.ts +1 -0
  62. package/assets/components/tokens.css +14 -15
  63. package/assets/prompts/ASSEMBLY.md +2 -0
  64. package/assets/prompts/CATALOG.md +1 -0
  65. package/assets/prompts/PRINCIPLES.md +1 -1
  66. package/assets/prompts/RULES.md +31 -0
  67. package/assets/prompts/axes/material.md +4 -4
  68. package/assets/prompts/axes/palette.md +1 -1
  69. package/assets/prompts/axes/shape.md +2 -2
  70. package/assets/prompts/axes/voice.md +2 -2
  71. package/assets/prompts/components/_variants.md +3 -3
  72. package/assets/prompts/components/accordion.md +1 -1
  73. package/assets/prompts/components/ai-message.md +6 -2
  74. package/assets/prompts/components/app-frame.md +2 -2
  75. package/assets/prompts/components/avatar.md +2 -2
  76. package/assets/prompts/components/badge.md +1 -1
  77. package/assets/prompts/components/breadcrumb.md +11 -5
  78. package/assets/prompts/components/button.md +2 -2
  79. package/assets/prompts/components/calendar.md +1 -1
  80. package/assets/prompts/components/callout.md +8 -4
  81. package/assets/prompts/components/canvas-edge.md +1 -1
  82. package/assets/prompts/components/canvas-node.md +2 -2
  83. package/assets/prompts/components/canvas.md +24 -8
  84. package/assets/prompts/components/chart-radial.md +1 -1
  85. package/assets/prompts/components/chart.md +1 -1
  86. package/assets/prompts/components/chat-reactions.md +1 -1
  87. package/assets/prompts/components/checkbox-card.md +3 -3
  88. package/assets/prompts/components/checkbox.md +1 -1
  89. package/assets/prompts/components/chip.md +4 -4
  90. package/assets/prompts/components/code-block.md +1 -1
  91. package/assets/prompts/components/combobox.md +3 -3
  92. package/assets/prompts/components/command-palette.md +52 -44
  93. package/assets/prompts/components/comment.md +2 -2
  94. package/assets/prompts/components/control-group.md +1 -1
  95. package/assets/prompts/components/data-table.md +1 -1
  96. package/assets/prompts/components/disclosure.md +1 -1
  97. package/assets/prompts/components/drawer.md +15 -1
  98. package/assets/prompts/components/dropdown-menu.md +1 -1
  99. package/assets/prompts/components/event-chip.md +2 -2
  100. package/assets/prompts/components/file-icon.md +1 -1
  101. package/assets/prompts/components/file-upload.md +1 -1
  102. package/assets/prompts/components/icon-button.md +1 -1
  103. package/assets/prompts/components/input.md +3 -3
  104. package/assets/prompts/components/list-item.md +1 -1
  105. package/assets/prompts/components/menu-item.md +2 -2
  106. package/assets/prompts/components/metric-card.md +1 -1
  107. package/assets/prompts/components/mini-calendar.md +1 -1
  108. package/assets/prompts/components/page-header.md +1 -1
  109. package/assets/prompts/components/segmented-chart.md +1 -1
  110. package/assets/prompts/components/sidebar.md +3 -3
  111. package/assets/prompts/components/skeleton.md +3 -3
  112. package/assets/prompts/components/social-login-button.md +117 -0
  113. package/assets/prompts/components/tab-strip.md +1 -1
  114. package/assets/prompts/components/table-cell.md +1 -1
  115. package/assets/prompts/components/table-header.md +1 -1
  116. package/assets/prompts/components/table-row-edit.md +3 -3
  117. package/assets/prompts/components/table-row.md +1 -1
  118. package/assets/prompts/components/table-toolbar.md +1 -1
  119. package/assets/prompts/components/timeline-view.md +2 -2
  120. package/assets/prompts/components/toast.md +1 -1
  121. package/assets/prompts/components/tooltip.md +3 -3
  122. package/assets/prompts/components/tree-nav.md +2 -2
  123. package/assets/prompts/design-examples/ai-chat-full-page.png +0 -0
  124. package/assets/prompts/design-examples/catalog.json +9 -9
  125. package/assets/prompts/design-examples/sources/ai-chat-full-page/ChatExperience.module.css +37 -1
  126. package/assets/prompts/design-examples/sources/ai-chat-full-page/ChatExperience.tsx +113 -18
  127. package/assets/prompts/design-examples/sources/ai-chat-full-page/FullPageChat.tsx +2 -2
  128. package/assets/prompts/design-examples/sources/ai-chat-full-page/REFERENCE.md +3 -1
  129. package/assets/prompts/design-examples/sources/ai-chat-full-page/useChatDemo.ts +99 -51
  130. package/assets/prompts/primitives/scroll.md +1 -1
  131. package/assets/prompts/tokens/color.md +4 -5
  132. package/assets/prompts/tokens/material.md +5 -2
  133. package/assets/prompts/tokens/radius.md +1 -1
  134. package/assets/prompts/use-cases/chat-chat-input.md +382 -74
  135. package/assets/prompts/use-cases/data-list-item.md +38 -431
  136. package/assets/prompts/use-cases/feedback-drawer.md +112 -33
  137. package/assets/prompts/use-cases/overlay-command-palette.md +2004 -0
  138. package/assets/prompts/use-cases/structure-canvas.md +1016 -0
  139. package/assets/skills/ovenn-validate/SKILL.md +1 -1
  140. package/assets/skills/ovenn-validate/scripts/lib/component-usage.js +27 -5
  141. package/assets/skills/ovenn-validate/scripts/rules/hard-rules.mjs +174 -0
  142. package/assets/skills/ovenn-validate/scripts/rules/hard-rules.test.mjs +57 -0
  143. package/assets/skills/ovenn-validate/scripts/validate.mjs +2 -0
  144. package/package.json +1 -1
  145. package/src/commands/info.js +5 -4
  146. package/src/commands/update.js +5 -1
  147. package/src/utils/agents.js +28 -17
  148. package/src/utils/client-bridges.js +4 -2
  149. package/src/utils/component-usage.js +27 -5
  150. package/src/utils/patch.js +2 -1
@@ -78,6 +78,8 @@ type Strings = {
78
78
  desc: ReactNode;
79
79
  };
80
80
 
81
+ tokenWarning: { heading: string; desc: string; message: string; viewUsage: string; hideUsage: string; usage: string; placeholder: string; label: string };
82
+
81
83
  useCases: { heading: string; card: string; previewNote: string };
82
84
 
83
85
  api: {
@@ -175,7 +177,18 @@ const en: Strings = {
175
177
  useCases: {
176
178
  heading: "Use Cases",
177
179
  card: "AI chat card",
178
- previewNote: "Local demo. Suggested questions send immediately. Replies stream character by character and can be stopped; use the header menu to switch conversations.",
180
+ previewNote: "Local demo. Suggested questions send immediately. Replies stream character by character and can be stopped; use the header menu to switch conversations. Send /fail to try the error and retry flow.",
181
+ },
182
+
183
+ tokenWarning: {
184
+ heading: "Low token budget",
185
+ desc: "Warn above the composer when tokens run low. View usage opens the example budget.",
186
+ message: "You’ve used 90% of your token limit.",
187
+ viewUsage: "View usage",
188
+ hideUsage: "Hide usage",
189
+ usage: "9,000 of 10,000 tokens used. 1,000 left.",
190
+ placeholder: "Enter a message",
191
+ label: "Write a message",
179
192
  },
180
193
 
181
194
  api: {
@@ -273,7 +286,18 @@ const ko: Strings = {
273
286
  useCases: {
274
287
  heading: "사용사례",
275
288
  card: "AI 채팅 카드",
276
- previewNote: "실제 AI 연결 없이 동작하는 데모예요. 추천 질문을 누르면 바로 보내요. 응답은 한 글자씩 나타나고 중지할 수 있어요. 상단 메뉴에서 대화를 바꿔 보세요.",
289
+ previewNote: "실제 AI 연결 없이 동작하는 데모예요. 추천 질문을 누르면 바로 보내요. 응답은 한 글자씩 나타나고 중지할 수 있어요. 상단 메뉴에서 대화를 바꿀 수 있어요. /fail을 보내면 응답 실패와 재시도를 확인할 수 있어요.",
290
+ },
291
+
292
+ tokenWarning: {
293
+ heading: "토큰 잔량 경고",
294
+ desc: "토큰이 얼마 남지 않으면 입력창 위에서 알려줘요. 사용량 보기에서 예시 사용량을 확인할 수 있어요.",
295
+ message: "토큰 한도의 90%를 사용했어요.",
296
+ viewUsage: "사용량 보기",
297
+ hideUsage: "사용량 닫기",
298
+ usage: "10,000 토큰 중 9,000개를 사용했어요. 1,000개 남았어요.",
299
+ placeholder: "메시지를 입력하세요",
300
+ label: "메시지 작성",
277
301
  },
278
302
 
279
303
  api: {
@@ -322,6 +346,29 @@ export type { Strings };
322
346
  width: 100%;
323
347
  }
324
348
 
349
+ .inputWithNotice {
350
+ display: flex;
351
+ flex-direction: column;
352
+ gap: var(--space-2);
353
+ width: 100%;
354
+ }
355
+
356
+ .tokenNotice.tokenNotice {
357
+ box-shadow: none;
358
+ }
359
+
360
+ .noticeComposer.noticeComposer,
361
+ .noticeComposer.noticeComposer:focus-within {
362
+ box-shadow: none;
363
+ }
364
+
365
+ .tokenUsage {
366
+ margin: 0;
367
+ padding-inline: var(--space-4);
368
+ color: var(--fg-muted);
369
+ font-size: var(--text-sm);
370
+ }
371
+
325
372
  .shellWrap {
326
373
  background: var(--bg-subtle);
327
374
  corner-shape: var(--corner-shape);
@@ -346,7 +393,7 @@ export type { Strings };
346
393
  ````tsx
347
394
  "use client";
348
395
 
349
- import { useState } from "react";
396
+ import { useRef, useState } from "react";
350
397
  import { usePathname } from "next/navigation";
351
398
  import {
352
399
  AIChatInput,
@@ -358,6 +405,8 @@ import {
358
405
  type ChatInputSendIcon,
359
406
  } from "@/components/ChatInput";
360
407
  import { ChatUseCases } from "@/examples/ai-chat/ChatUseCases";
408
+ import { Button } from "@/components/Button";
409
+ import { Callout } from "@/components/Callout";
361
410
  import { Code } from "@/components/Code";
362
411
  import { Icon } from "@/components/Icon";
363
412
  import { ExampleBlock } from "../../../../_components/ExampleBlock";
@@ -405,6 +454,9 @@ type LocalProps = {
405
454
  attachments?: ChatAttachment[];
406
455
  quotation?: string;
407
456
  streaming?: boolean;
457
+ placeholder?: string;
458
+ label?: string;
459
+ className?: string;
408
460
  };
409
461
 
410
462
  function LocalChatInput(props: LocalProps) {
@@ -416,6 +468,7 @@ function LocalChatInput(props: LocalProps) {
416
468
 
417
469
  return (
418
470
  <AIChatInput
471
+ className={props.className}
419
472
  shape={props.shape ?? "multi"}
420
473
  variant={props.variant ?? "framed"}
421
474
  appearance={props.appearance}
@@ -423,6 +476,8 @@ function LocalChatInput(props: LocalProps) {
423
476
  sendVariant={props.sendVariant}
424
477
  sendIcon={props.sendIcon}
425
478
  value={v}
479
+ placeholder={props.placeholder}
480
+ inputProps={props.label ? { "aria-label": props.label } : undefined}
426
481
  onChange={setV}
427
482
  onSend={() => {
428
483
  setV("");
@@ -459,6 +514,10 @@ function LocalChatInput(props: LocalProps) {
459
514
  export default function ChatInputPage() {
460
515
  const pathname = usePathname() ?? "/";
461
516
  const t = strings[localeFromPathname(pathname)];
517
+ const [showTokenUsage, setShowTokenUsage] = useState(false);
518
+ const [tokenNoticeDismissed, setTokenNoticeDismissed] = useState(false);
519
+ const tokenPreviewRef = useRef<HTMLDivElement>(null);
520
+ const dismissTokenLabel = localeFromPathname(pathname) === "ko" ? "토큰 경고 닫기" : "Dismiss token warning";
462
521
 
463
522
  const [pgShape, setPgShape] = useState<ChatInputShape>("multi");
464
523
  const [pgAppearance, setPgAppearance] = useState<ChatInputAppearance>("outline");
@@ -692,7 +751,77 @@ const [value, setValue] = useState("");
692
751
  align="column"
693
752
  code={`<AIChatInput isStreaming onStop={cancel} ... />`}
694
753
  >
695
- <LocalChatInput shape="multi" initialValue="..." streaming />
754
+ <div className={styles.stage}>
755
+ <LocalChatInput shape="multi" initialValue="..." streaming />
756
+ </div>
757
+ </ExampleBlock>
758
+ </section>
759
+
760
+ <section id="token-warning">
761
+ <h2>{t.tokenWarning.heading}</h2>
762
+ <p className="desc">{t.tokenWarning.desc}</p>
763
+ <ExampleBlock
764
+ align="column"
765
+ code={`<div className={styles.inputWithNotice}>
766
+ {!tokenNoticeDismissed && <Callout
767
+ layout="inline"
768
+ size="sm"
769
+ variant="outline"
770
+ tone="warning"
771
+ className={styles.tokenNotice}
772
+ title="${t.tokenWarning.message}"
773
+ dismissible
774
+ dismissLabel="${dismissTokenLabel}"
775
+ onDismiss={() => setTokenNoticeDismissed(true)}
776
+ actions={
777
+ <Button size="xs" variant="ghost" aria-expanded={showTokenUsage}
778
+ aria-controls="token-usage-details" onClick={() => setShowTokenUsage(!showTokenUsage)}>
779
+ {showTokenUsage ? "${t.tokenWarning.hideUsage}" : "${t.tokenWarning.viewUsage}"}
780
+ </Button>
781
+ }
782
+ />}
783
+ <p id="token-usage-details" hidden={tokenNoticeDismissed || !showTokenUsage} className={styles.tokenUsage}>
784
+ ${t.tokenWarning.usage}
785
+ </p>
786
+ <AIChatInput className={styles.noticeComposer} value={value} onChange={setValue} onSend={send} />
787
+ </div>`}
788
+ >
789
+ <div className={styles.inputWithNotice} ref={tokenPreviewRef}>
790
+ {!tokenNoticeDismissed && <Callout
791
+ layout="inline"
792
+ size="sm"
793
+ variant="outline"
794
+ tone="warning"
795
+ className={styles.tokenNotice}
796
+ title={t.tokenWarning.message}
797
+ dismissible
798
+ dismissLabel={dismissTokenLabel}
799
+ onDismiss={() => {
800
+ tokenPreviewRef.current?.querySelector("textarea")?.focus({ preventScroll: true });
801
+ setTokenNoticeDismissed(true);
802
+ }}
803
+ actions={
804
+ <Button
805
+ size="xs"
806
+ variant="ghost"
807
+ aria-expanded={showTokenUsage}
808
+ aria-controls="token-usage-details"
809
+ onClick={() => setShowTokenUsage((open) => !open)}
810
+ >
811
+ {showTokenUsage ? t.tokenWarning.hideUsage : t.tokenWarning.viewUsage}
812
+ </Button>
813
+ }
814
+ />}
815
+ <p id="token-usage-details" hidden={tokenNoticeDismissed || !showTokenUsage} className={styles.tokenUsage}>
816
+ {t.tokenWarning.usage}
817
+ </p>
818
+ <LocalChatInput
819
+ className={styles.noticeComposer}
820
+ shape="multi"
821
+ placeholder={t.tokenWarning.placeholder}
822
+ label={t.tokenWarning.label}
823
+ />
824
+ </div>
696
825
  </ExampleBlock>
697
826
  </section>
698
827
 
@@ -924,6 +1053,33 @@ const [value, setValue] = useState("");
924
1053
  overflow-wrap: anywhere;
925
1054
  }
926
1055
 
1056
+ .sentAttachments {
1057
+ display: flex;
1058
+ flex-wrap: wrap;
1059
+ justify-content: flex-end;
1060
+ gap: var(--space-2);
1061
+ min-width: 0;
1062
+ }
1063
+
1064
+ .sentAttachments > * {
1065
+ max-width: 100%;
1066
+ }
1067
+
1068
+ .attachmentOnly > [data-user-message-body] {
1069
+ display: none;
1070
+ }
1071
+
1072
+ .composer [data-slot="chat-input-attachments"] {
1073
+ max-block-size: var(--size-24);
1074
+ overflow: auto;
1075
+ overscroll-behavior: contain;
1076
+ }
1077
+
1078
+ .composer [data-slot="chat-input-attachments"] > *,
1079
+ .composer [data-slot="chat-input-attachments"] > * > * {
1080
+ max-inline-size: 100%;
1081
+ }
1082
+
927
1083
  .assistant.assistant [data-ai-message-body] {
928
1084
  font-size: var(--text-base);
929
1085
  line-height: var(--lh-base);
@@ -1063,13 +1219,22 @@ const [value, setValue] = useState("");
1063
1219
 
1064
1220
  .fullPage .bottom {
1065
1221
  width: 100%;
1222
+ gap: var(--space-2);
1066
1223
  max-width: var(--chat-page-width);
1067
1224
  margin-inline: auto;
1068
1225
  padding-bottom: max(var(--space-6), env(safe-area-inset-bottom));
1069
1226
  }
1070
1227
 
1228
+ .tokenNotice {
1229
+ margin-inline: var(--chat-content-inset);
1230
+ }
1231
+
1232
+ .tokenNoticeIcon {
1233
+ color: var(--warning);
1234
+ }
1235
+
1071
1236
  .fullPage .composer.composer {
1072
- --chat-input-padding-y: var(--space-4);
1237
+ --chat-input-padding-y: var(--space-3);
1073
1238
  }
1074
1239
 
1075
1240
 
@@ -1199,7 +1364,10 @@ import { IconButton } from "@/components/IconButton";
1199
1364
  import { Modal } from "@/components/Modal";
1200
1365
  import { UserMessage } from "@/components/UserMessage";
1201
1366
  import { AIMessage } from "@/components/AIMessage";
1202
- import { useChatDemo } from "./useChatDemo";
1367
+ import { AttachmentItem } from "@/components/AttachmentItem";
1368
+ import { AttachmentThumb } from "@/components/AttachmentThumb";
1369
+ import { Callout } from "@/components/Callout";
1370
+ import { useChatDemo, type ChatDemoMessage } from "./useChatDemo";
1203
1371
  import { Card } from "@/components/Card";
1204
1372
  import { AppFrame } from "@/components/AppFrame";
1205
1373
  import { Topbar } from "@/components/Topbar";
@@ -1222,6 +1390,26 @@ const content = {
1222
1390
  switchThread: "Switch thread",
1223
1391
  createThread: "New chat",
1224
1392
  messagesLabel: "Conversation",
1393
+ composerLabel: "Write a message",
1394
+ tokenWarning: "You’ve used 90% of your token limit.",
1395
+ viewUsage: "View usage",
1396
+ hideUsage: "Hide usage",
1397
+ usage: "Example budget: 9,000 of 10,000 tokens used. 1,000 left.",
1398
+ sample: [
1399
+ "Can you organize the launch meeting notes?",
1400
+ "Send the notes and I’ll separate the decisions, owners, and open questions.",
1401
+ "The release is next Thursday. Design will finish the empty screens on Monday. Engineering needs the final copy by Tuesday. Support wants a checklist for common questions.",
1402
+ "Decision: release next Thursday.\n\nDesign: finish empty screens on Monday.\nEngineering: confirm final copy on Tuesday.\nSupport: draft a checklist for common questions.\n\nThe checklist still needs an owner and a due date.",
1403
+ "What should we cover in the review?",
1404
+ "Open the empty screens with a fresh account and check that each screen explains the next step. Read the copy alongside the screens so the team can spot inconsistencies.\n\nWalk through one support question from start to finish. Bring unresolved issues to the review with the person who can decide what to do next.",
1405
+ "Jin owns the checklist. Add a short review on Wednesday and write a message I can send to the team.",
1406
+ "We’re planning to release next Thursday. Design will finish the empty screens on Monday, and Engineering needs the final copy by Tuesday.\n\nJin will prepare the support checklist. We’ll review the copy, empty screens, and checklist together on Wednesday.\n\nPlease flag anything that could move the release date before the review.",
1407
+ ],
1408
+ failed: "Couldn’t generate a response.",
1409
+ stopped: "Response stopped.",
1410
+ retry: "Try again",
1411
+ attachmentReply: "I received your attachments. Paste the part you want to work on and tell me what you need.",
1412
+ retryReply: "The demo response is working again. Tell me what you’d like help with.",
1225
1413
  threadTitles: ["Meeting notes", "Follow-up email", "Document summary"],
1226
1414
  replies: [
1227
1415
  "Share your meeting notes and I’ll organize them into decisions and action items.\n\nFor each action, include the task, owner, and due date when available.",
@@ -1245,6 +1433,26 @@ const content = {
1245
1433
  switchThread: "대화 전환",
1246
1434
  createThread: "새 대화",
1247
1435
  messagesLabel: "대화 내용",
1436
+ composerLabel: "메시지 작성",
1437
+ tokenWarning: "토큰 한도의 90%를 사용했어요.",
1438
+ viewUsage: "사용량 보기",
1439
+ hideUsage: "사용량 닫기",
1440
+ usage: "예시 사용량은 10,000 토큰 중 9,000개예요. 1,000개 남았어요.",
1441
+ sample: [
1442
+ "출시 회의 메모를 정리해 주세요.",
1443
+ "메모를 보내주시면 결정 사항과 담당자, 아직 확인할 내용을 나눠 정리할게요.",
1444
+ "다음 주 목요일에 출시해요. 디자인은 월요일까지 빈 화면을 마무리하고, 개발은 화요일까지 최종 문구가 필요해요. 고객지원팀은 자주 묻는 질문을 체크리스트로 정리하기로 했어요.",
1445
+ "다음 주 목요일에 출시하기로 했어요.\n\n디자인팀은 월요일까지 빈 화면을 마무리해요.\n개발팀은 화요일까지 최종 문구를 확인해요.\n고객지원팀은 자주 묻는 질문을 정리해요.\n\n체크리스트 담당자와 마감일을 정하면 돼요.",
1446
+ "검토할 때는 뭘 보면 좋을까요?",
1447
+ "새 계정으로 빈 화면을 열고, 다음에 할 일이 분명한지 확인해요. 화면에 들어갈 문구도 같이 읽으면서 용어가 일관적인지 살펴보면 좋아요.\n\n고객 문의 하나를 골라 체크리스트를 처음부터 따라가 보세요. 결정이 필요한 항목은 담당자와 함께 수요일 검토에 가져오면 돼요.",
1448
+ "체크리스트는 진이 맡기로 했어요. 수요일에 같이 검토하기로 한 내용도 넣어서 팀에 보낼 메시지를 써 주세요.",
1449
+ "다음 주 목요일에 출시할 예정이에요. 디자인팀은 월요일까지 빈 화면을 마무리하고, 개발팀은 화요일까지 최종 문구를 확인해 주세요.\n\n진은 고객지원 체크리스트를 준비해 주세요. 수요일에는 문구, 빈 화면, 체크리스트를 함께 검토할게요.\n\n출시 일정에 영향을 줄 일이 있으면 수요일 검토 전에 알려주세요.",
1450
+ ],
1451
+ failed: "응답을 생성하지 못했어요.",
1452
+ stopped: "응답 생성을 중지했어요.",
1453
+ retry: "다시 시도",
1454
+ attachmentReply: "첨부를 받았어요. 작업할 내용을 붙여 넣고 어떤 도움이 필요한지 알려주세요.",
1455
+ retryReply: "데모 응답이 다시 작동해요. 어떤 일이 필요한지 알려주세요.",
1248
1456
  threadTitles: ["회의 메모 정리", "후속 메일 초안", "문서 요약"],
1249
1457
  replies: [
1250
1458
  "정리할 회의 메모를 보내주세요. 결정 사항과 실행 항목을 구분해 정리할게요.\n\n실행 항목마다 할 일, 담당자, 기한이 있다면 함께 알려주세요.",
@@ -1260,7 +1468,7 @@ const content = {
1260
1468
  },
1261
1469
  };
1262
1470
 
1263
- export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "ko"; presentation?: "card" | "page" }) {
1471
+ export function ChatExperience({ lang, presentation = "card", material }: { lang: "en" | "ko"; presentation?: "card" | "page"; material?: "glass" | "solid" }) {
1264
1472
  const isPage = presentation === "page";
1265
1473
  const t = content[lang];
1266
1474
  const [threadMenuOpen, setThreadMenuOpen] = useState(false);
@@ -1288,9 +1496,19 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1288
1496
  focusConversation.current = false;
1289
1497
  }
1290
1498
  }, [isMobile, mobileView]);
1291
- const getReply = (text: string) => t.replies[t.questions.indexOf(text)] ?? t.fallbackReply;
1499
+ const getReply = (text: string, hasAttachments: boolean) => {
1500
+ if (text === "/fail") return t.retryReply;
1501
+ if (hasAttachments) return t.attachmentReply;
1502
+ return t.replies[t.questions.indexOf(text)] ?? t.fallbackReply;
1503
+ };
1292
1504
  const getTitle = (text: string) => t.threadTitles[t.questions.indexOf(text)] ?? Array.from(text).slice(0, 18).join("");
1293
- const { threads, activeThread, setActiveId, createThread, renameThread, deleteThread, setDraft, send, stop, edit, regenerate, isStreaming } = useChatDemo(getReply, getTitle);
1505
+ const initialMessages = useRef<ChatDemoMessage[]>(isPage ? t.sample.map((text, index) => ({
1506
+ id: `sample-${index}`, role: index % 2 === 0 ? "user" : "assistant", text,
1507
+ })) : []);
1508
+ const { threads, activeThread, setActiveId, createThread, renameThread, deleteThread, setDraft, attach, removeAttachment, send, stop, edit, regenerate, retry, isStreaming } = useChatDemo(getReply, getTitle, initialMessages.current);
1509
+ const [noticeDismissed, setNoticeDismissed] = useState(false);
1510
+ const showNotice = isPage && activeThread.id === "chat-0" && !noticeDismissed;
1511
+ const [showUsage, setShowUsage] = useState(false);
1294
1512
  const viewportRef = useRef<HTMLDivElement>(null);
1295
1513
  const pageRef = useRef<HTMLDivElement>(null);
1296
1514
  useLayoutEffect(() => {
@@ -1338,18 +1556,18 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1338
1556
  composerRef.current?.querySelector("textarea")?.focus({ preventScroll: true });
1339
1557
  focusAfterSend.current = false;
1340
1558
  }
1341
- }, [activeThread.id, activeThread.messages, isPage, isMobile, mobileView]);
1559
+ }, [activeThread.id, activeThread.messages, activeThread.attachments, isPage, isMobile, mobileView]);
1342
1560
 
1343
1561
  const saveScroll = () => {
1344
1562
  newMessageIds.current.clear();
1345
1563
  if (viewportRef.current && !(isPage && isMobile && mobileView === "threads")) scrollPositions.current.set(activeThread.id, viewportRef.current.scrollTop);
1346
1564
  };
1347
- const sendPrompt = (text: string, focusInput = true) => {
1348
- if (!text.trim() || isStreaming) return;
1565
+ const sendPrompt = (text: string, focusInput = true, useDraft = true) => {
1566
+ if ((!text.trim() && !(useDraft && activeThread.attachments.length)) || isStreaming) return;
1349
1567
  followLatest.current = true;
1350
1568
  focusAfterSend.current = focusInput;
1351
1569
  newMessageIds.current.add(`${activeThread.id}-${activeThread.messages.length}-user`);
1352
- send(text);
1570
+ send(text, useDraft);
1353
1571
  };
1354
1572
 
1355
1573
  const toggleHistory = () => {
@@ -1364,8 +1582,13 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1364
1582
  setMobileView("chat");
1365
1583
  };
1366
1584
  const normalizedSearch = threadSearch.trim().toLocaleLowerCase();
1367
- const historyThreads = [...threads].reverse().filter((thread) => thread.title || thread.messages.length > 0 || thread.draft.trim());
1368
- const visibleThreads = historyThreads.filter((thread) => [thread.title, thread.draft, ...thread.messages.map((message) => message.text)].join(" ").toLocaleLowerCase().includes(normalizedSearch));
1585
+ const historyThreads = [...threads].reverse().filter((thread) => thread.title || thread.messages.length || thread.draft.trim() || thread.attachments.length);
1586
+ const attachmentName = (item: (typeof activeThread.attachments)[number]) => item.kind === "file" ? item.filename : item.alt;
1587
+ const threadLabel = (thread: typeof activeThread) => thread.title || getTitle(thread.draft.trim() || thread.attachments.map(attachmentName).find(Boolean) || t.title);
1588
+ const visibleThreads = historyThreads.filter((thread) => [
1589
+ thread.title, thread.draft, ...thread.attachments.map(attachmentName),
1590
+ ...thread.messages.flatMap((message) => [message.text, ...(message.attachments ?? []).map(attachmentName)]),
1591
+ ].join(" ").toLocaleLowerCase().includes(normalizedSearch));
1369
1592
 
1370
1593
  const header = (
1371
1594
  <div className={styles.header}>
@@ -1388,18 +1611,16 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1388
1611
  >
1389
1612
  {t.createThread}
1390
1613
  </DropdownMenu.Item>
1391
- {threads.some((thread) => thread.messages.length > 0 || thread.draft.trim()) && (
1614
+ {historyThreads.length > 0 && (
1392
1615
  <>
1393
1616
  <DropdownMenu.Separator />
1394
1617
  <DropdownMenu.Group>
1395
- {[...threads].reverse()
1396
- .filter((thread) => thread.messages.length > 0 || thread.draft.trim())
1397
- .map((thread) => (
1618
+ {historyThreads.map((thread) => (
1398
1619
  <DropdownMenu.Item
1399
1620
  key={thread.id}
1400
1621
  onSelect={() => { saveScroll(); setActiveId(thread.id); setThreadMenuOpen(false); }}
1401
1622
  >
1402
- {thread.title || Array.from(thread.draft.trim()).slice(0, 18).join("")}
1623
+ {threadLabel(thread)}
1403
1624
  </DropdownMenu.Item>
1404
1625
  ))}
1405
1626
  </DropdownMenu.Group>
@@ -1427,9 +1648,28 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1427
1648
  <div className={styles.messages} role="log" aria-live="polite" aria-relevant="additions text" aria-label={t.messagesLabel}>
1428
1649
  {activeThread.messages.map((message) => message.role === "user" ? (
1429
1650
  <UserMessage key={message.id} actionsVisibility="hover" textValue={message.text}
1651
+ actions={message.text ? undefined : []}
1652
+ className={message.text ? undefined : styles.attachmentOnly}
1653
+ before={message.attachments?.length ? (
1654
+ <div className={styles.sentAttachments}>
1655
+ {message.attachments.map((item) => item.kind === "file" ? (
1656
+ <AttachmentItem key={item.id} filename={item.filename} />
1657
+ ) : (
1658
+ <AttachmentThumb key={item.id} src={item.src} alt={item.alt} size="lg" />
1659
+ ))}
1660
+ </div>
1661
+ ) : undefined}
1430
1662
  onEdit={(text) => edit(message.id, text)} animate={newMessageIds.current.has(message.id)}>
1431
1663
  <span className={styles.messageText}>{message.text}</span>
1432
1664
  </UserMessage>
1665
+ ) : message.interruption ? (
1666
+ <Callout key={message.id} layout="inline"
1667
+ tone={message.interruption === "failed" ? "destructive" : "neutral"}
1668
+ title={t[message.interruption]}
1669
+ actions={<Button size="sm" variant="ghost" disabled={isStreaming} onClick={() => {
1670
+ viewportRef.current?.focus({ preventScroll: true });
1671
+ retry(message.id);
1672
+ }}>{t.retry}</Button>} />
1433
1673
  ) : (
1434
1674
  <AIMessage key={message.id} actionsVisibility="hover" actions={[
1435
1675
  { kind: "copy", onClick: () => navigator.clipboard.writeText(message.text), successLabel: lang === "ko" ? "복사됨" : "Copied", errorLabel: lang === "ko" ? "복사 실패" : "Copy failed" },
@@ -1449,13 +1689,29 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1449
1689
  );
1450
1690
  const bottom = (
1451
1691
  <div className={styles.bottom}>
1692
+ {showNotice && (
1693
+ <Callout layout="inline" size="sm" variant="fill" tone="neutral"
1694
+ icon={<Icon name="warning-circle" className={styles.tokenNoticeIcon} />} title={t.tokenWarning} className={styles.tokenNotice}
1695
+ dismissible
1696
+ dismissLabel={lang === "ko" ? "토큰 경고 닫기" : "Dismiss token warning"}
1697
+ onDismiss={() => {
1698
+ composerRef.current?.querySelector("textarea")?.focus({ preventScroll: true });
1699
+ setNoticeDismissed(true);
1700
+ }}
1701
+ actions={<Button size="xs" variant="ghost" aria-expanded={showUsage} aria-controls="page-token-usage"
1702
+ onClick={() => setShowUsage((open) => !open)}>
1703
+ {showUsage ? t.hideUsage : t.viewUsage}
1704
+ </Button>}>
1705
+ <span id="page-token-usage" hidden={!showUsage}><br />{t.usage}</span>
1706
+ </Callout>
1707
+ )}
1452
1708
  {!isPage && !hasMessages && (
1453
1709
  <div className={styles.questions} role="group" aria-label={t.suggestionsLabel}>
1454
1710
  {t.questions.map((question) => (
1455
1711
  <RadioCard
1456
1712
  key={question}
1457
1713
  mode="button"
1458
- onClick={(event) => sendPrompt(question, event.detail === 0)}
1714
+ onClick={(event) => sendPrompt(question, event.detail === 0, false)}
1459
1715
  onFocus={(event) => event.currentTarget.scrollIntoView({ block: "nearest", inline: "nearest" })}
1460
1716
  align="start"
1461
1717
  size="md"
@@ -1472,18 +1728,22 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1472
1728
  separateSend={!isPage}
1473
1729
  value={activeThread.draft}
1474
1730
  onChange={setDraft}
1731
+ attachments={activeThread.attachments}
1732
+ onAttach={attach}
1733
+ onRemoveAttachment={removeAttachment}
1475
1734
  onSend={() => sendPrompt(activeThread.draft)}
1476
1735
  isStreaming={isStreaming}
1477
1736
  onStop={stop}
1478
1737
  sendVariant="solid"
1479
1738
  placeholder={t.placeholder}
1739
+ inputProps={{ "aria-label": t.composerLabel }}
1480
1740
  className={styles.composer}
1481
1741
  />
1482
1742
  </div>
1483
1743
  );
1484
1744
 
1485
1745
  if (isPage) return (
1486
- <AppFrame ref={pageRef} variant="flat" layout="sidebar-first" className={styles.fullPage} data-ai-chat-page data-chat-thread={activeThread.id} data-mobile-view={mobileView} lang={lang}>
1746
+ <AppFrame ref={pageRef} variant="flat" layout="sidebar-first" className={styles.fullPage} data-ai-chat-page data-chat-thread={activeThread.id} data-mobile-view={mobileView} data-material={material} lang={lang}>
1487
1747
  <AppFrame.Topbar>
1488
1748
  <Topbar size="sm">
1489
1749
  <Topbar.Leading className={styles.threadHeading}>
@@ -1545,7 +1805,7 @@ export function ChatExperience({ lang, presentation = "card" }: { lang: "en" | "
1545
1805
  setActiveId(thread.id);
1546
1806
  focusConversation.current = isMobile;
1547
1807
  setMobileView("chat");
1548
- }}>{thread.title || Array.from(thread.draft.trim()).slice(0, 18).join("")}</MenuItem>
1808
+ }}>{threadLabel(thread)}</MenuItem>
1549
1809
  ))}
1550
1810
  </MenuItem.Section>
1551
1811
  {visibleThreads.length === 0 && <EmptyState className={styles.historyEmpty} size="sm" icon={normalizedSearch ? "search" : "chat-circle"} title={normalizedSearch ? t.noResults : t.noChats} role="status" />}
@@ -1591,23 +1851,32 @@ export function ChatUseCases({ lang }: { lang: "en" | "ko" }) {
1591
1851
  ````tsx
1592
1852
  "use client";
1593
1853
 
1594
- import { useRef, useState } from "react";
1854
+ import { useEffect, useRef, useState } from "react";
1855
+ import type { ChatAttachment } from "@/components/ChatInput";
1595
1856
  import { useDemoTextStream } from "./useDemoTextStream";
1596
1857
 
1597
- export type ChatDemoMessage = { id: string; role: "user" | "assistant"; text: string; isStreaming?: boolean };
1858
+ export type ChatDemoMessage = {
1859
+ id: string;
1860
+ role: "user" | "assistant";
1861
+ text: string;
1862
+ isStreaming?: boolean;
1863
+ interruption?: "failed" | "stopped";
1864
+ attachments?: ChatAttachment[];
1865
+ };
1598
1866
  export type ChatDemoThread = {
1599
1867
  id: string;
1600
1868
  title: string;
1601
1869
  draft: string;
1870
+ attachments: ChatAttachment[];
1602
1871
  messages: ChatDemoMessage[];
1603
1872
  };
1604
1873
 
1605
- export function useChatDemo(getReply: (text: string) => string, getTitle: (text: string) => string) {
1874
+ export function useChatDemo(getReply: (text: string, hasAttachments: boolean) => string, getTitle: (text: string) => string, initialMessages: ChatDemoMessage[] = []) {
1606
1875
  const sequence = useRef(1);
1607
1876
  const delivery = useDemoTextStream();
1608
1877
  const pendingThreads = useRef(new Set<string>());
1609
1878
  const [threads, setThreads] = useState<ChatDemoThread[]>([
1610
- { id: "chat-0", title: "", draft: "", messages: [] },
1879
+ { id: "chat-0", title: initialMessages.length ? getTitle(initialMessages[0].text) : "", draft: "", attachments: [], messages: initialMessages },
1611
1880
  ]);
1612
1881
  const [activeId, setActiveId] = useState("chat-0");
1613
1882
  const activeThread = threads.find((thread) => thread.id === activeId) ?? threads[0];
@@ -1616,41 +1885,87 @@ export function useChatDemo(getReply: (text: string) => string, getTitle: (text:
1616
1885
  setThreads((previous) => previous.map((thread) => thread.id === activeId ? { ...thread, draft } : thread));
1617
1886
  };
1618
1887
 
1619
- const send = (text: string) => {
1620
- const value = text.trim();
1621
- if (!value || pendingThreads.current.has(activeId)) return;
1622
- const targetId = activeId;
1623
- const baseMessages = activeThread.messages;
1624
- const messageId = `${targetId}-${baseMessages.length}`;
1625
- const assistantId = `${messageId}-assistant`;
1626
- pendingThreads.current.add(targetId);
1627
- setThreads((previous) => previous.map((thread) => {
1628
- if (thread.id !== activeId) return thread;
1629
- return {
1630
- ...thread,
1631
- title: thread.title || getTitle(value),
1632
- draft: "",
1633
- messages: [
1634
- ...baseMessages,
1635
- { id: `${messageId}-user`, role: "user", text: value },
1636
- { id: `${messageId}-assistant`, role: "assistant", text: "", isStreaming: true },
1637
- ],
1638
- };
1639
- }));
1640
- delivery.start(targetId, getReply(value), (reply, isStreaming) => {
1641
- if (!isStreaming) pendingThreads.current.delete(targetId);
1642
- setThreads((previous) => previous.map((thread) => thread.id === targetId ? {
1888
+ const imageUrls = useRef(new Set<string>());
1889
+ useEffect(() => {
1890
+ const used = new Set<string>();
1891
+ for (const thread of threads) {
1892
+ for (const attachment of [...thread.attachments, ...thread.messages.flatMap((message) => message.attachments ?? [])]) {
1893
+ if (attachment.kind === "image" && attachment.src) used.add(attachment.src);
1894
+ }
1895
+ }
1896
+ for (const url of imageUrls.current) {
1897
+ if (used.has(url)) continue;
1898
+ URL.revokeObjectURL(url);
1899
+ imageUrls.current.delete(url);
1900
+ }
1901
+ }, [threads]);
1902
+ useEffect(() => {
1903
+ const urls = imageUrls.current;
1904
+ return () => { urls.forEach((url) => URL.revokeObjectURL(url)); urls.clear(); };
1905
+ }, []);
1906
+
1907
+ const attach = (files: File[]) => {
1908
+ const attachments = files.map((file): ChatAttachment => {
1909
+ const id = `attachment-${sequence.current++}`;
1910
+ if (!file.type.startsWith("image/")) return { id, kind: "file", filename: file.name };
1911
+ const src = URL.createObjectURL(file);
1912
+ imageUrls.current.add(src);
1913
+ return { id, kind: "image", src, alt: file.name };
1914
+ });
1915
+ setThreads((previous) => previous.map((thread) => thread.id === activeId ? {
1916
+ ...thread, attachments: [...thread.attachments, ...attachments],
1917
+ } : thread));
1918
+ };
1919
+
1920
+ const removeAttachment = (id: string) => {
1921
+ setThreads((previous) => previous.map((thread) => thread.id === activeId ? {
1922
+ ...thread, attachments: thread.attachments.filter((attachment) => attachment.id !== id),
1923
+ } : thread));
1924
+ };
1925
+
1926
+ const streamReply = (threadId: string, assistantId: string, prompt: ChatDemoMessage) => {
1927
+ pendingThreads.current.add(threadId);
1928
+ delivery.start(threadId, getReply(prompt.text, !!prompt.attachments?.length), (text, isStreaming) => {
1929
+ if (!isStreaming) pendingThreads.current.delete(threadId);
1930
+ setThreads((previous) => previous.map((thread) => thread.id === threadId ? {
1643
1931
  ...thread,
1644
- messages: thread.messages.map((message) => message.id === assistantId ? { ...message, text: reply, isStreaming } : message),
1932
+ messages: thread.messages.map((message) => message.id === assistantId ? {
1933
+ ...message, text, isStreaming, interruption: undefined,
1934
+ } : message),
1645
1935
  } : thread));
1646
1936
  });
1647
1937
  };
1648
1938
 
1939
+ const send = (text: string, useDraft = true) => {
1940
+ const value = text.trim();
1941
+ const attachments = useDraft ? activeThread.attachments : [];
1942
+ if ((!value && !attachments.length) || pendingThreads.current.has(activeId)) return;
1943
+ const messageId = `${activeId}-${activeThread.messages.length}`;
1944
+ const assistantId = `${messageId}-assistant`;
1945
+ const prompt: ChatDemoMessage = { id: `${messageId}-user`, role: "user", text: value, attachments };
1946
+ const failed = value === "/fail";
1947
+ const firstFile = attachments[0];
1948
+ const title = value || (firstFile?.kind === "file" ? firstFile.filename : firstFile?.alt) || "";
1949
+ setThreads((previous) => previous.map((thread) => thread.id === activeId ? {
1950
+ ...thread,
1951
+ title: thread.title || getTitle(title),
1952
+ draft: useDraft ? "" : thread.draft,
1953
+ attachments: useDraft ? [] : thread.attachments,
1954
+ messages: [...thread.messages, prompt, {
1955
+ id: assistantId, role: "assistant", text: "",
1956
+ interruption: failed ? "failed" : undefined, isStreaming: !failed,
1957
+ }],
1958
+ } : thread));
1959
+ if (!failed) streamReply(activeId, assistantId, prompt);
1960
+ };
1961
+
1649
1962
  const stop = () => {
1650
1963
  delivery.stop(activeId);
1651
1964
  pendingThreads.current.delete(activeId);
1652
1965
  setThreads((previous) => previous.map((thread) => thread.id === activeId ? {
1653
- ...thread, messages: thread.messages.map((message) => message.isStreaming ? { ...message, isStreaming: false } : message),
1966
+ ...thread, messages: thread.messages.map((message) => message.isStreaming ? {
1967
+ ...message, isStreaming: false, interruption: message.text ? undefined : "stopped",
1968
+ } : message),
1654
1969
  } : thread));
1655
1970
  };
1656
1971
 
@@ -1661,22 +1976,22 @@ export function useChatDemo(getReply: (text: string) => string, getTitle: (text:
1661
1976
  const targetId = activeId;
1662
1977
  const assistantId = `${targetId}-${index}-assistant`;
1663
1978
  delivery.stop(targetId);
1664
- pendingThreads.current.add(targetId);
1665
1979
  setThreads((previous) => previous.map((thread) => thread.id === targetId ? {
1666
1980
  ...thread,
1667
1981
  messages: [
1668
1982
  ...thread.messages.slice(0, index),
1669
- { id: messageId, role: "user", text: value },
1983
+ { ...thread.messages[index], text: value },
1670
1984
  { id: assistantId, role: "assistant", text: "", isStreaming: true },
1671
1985
  ],
1672
1986
  } : thread));
1673
- delivery.start(targetId, getReply(value), (reply, streaming) => {
1674
- if (!streaming) pendingThreads.current.delete(targetId);
1675
- setThreads((previous) => previous.map((thread) => thread.id === targetId ? {
1676
- ...thread,
1677
- messages: thread.messages.map((message) => message.id === assistantId ? { ...message, text: reply, isStreaming: streaming } : message),
1678
- } : thread));
1679
- });
1987
+ streamReply(targetId, assistantId, { ...activeThread.messages[index], text: value });
1988
+ };
1989
+
1990
+ const retry = (messageId: string) => {
1991
+ if (pendingThreads.current.has(activeId)) return;
1992
+ const index = activeThread.messages.findIndex((message) => message.id === messageId && message.interruption);
1993
+ const prompt = activeThread.messages[index - 1];
1994
+ if (prompt?.role === "user") streamReply(activeId, messageId, prompt);
1680
1995
  };
1681
1996
 
1682
1997
  const regenerate = (messageId: string) => {
@@ -1685,28 +2000,21 @@ export function useChatDemo(getReply: (text: string) => string, getTitle: (text:
1685
2000
  const prompt = activeThread.messages[index - 1];
1686
2001
  if (index < 1 || prompt?.role !== "user") return;
1687
2002
  const targetId = activeId;
1688
- pendingThreads.current.add(targetId);
1689
2003
  setThreads((previous) => previous.map((thread) => thread.id === targetId ? {
1690
2004
  ...thread,
1691
2005
  messages: [...thread.messages.slice(0, index), { id: messageId, role: "assistant", text: "", isStreaming: true }],
1692
2006
  } : thread));
1693
- delivery.start(targetId, getReply(prompt.text), (text, streaming) => {
1694
- if (!streaming) pendingThreads.current.delete(targetId);
1695
- setThreads((previous) => previous.map((thread) => thread.id === targetId ? {
1696
- ...thread,
1697
- messages: thread.messages.map((message) => message.id === messageId ? { ...message, text, isStreaming: streaming } : message),
1698
- } : thread));
1699
- });
2007
+ streamReply(targetId, messageId, prompt);
1700
2008
  };
1701
2009
 
1702
2010
  const createThread = () => {
1703
- const empty = threads.find((thread) => thread.messages.length === 0 && !thread.draft && !thread.title);
2011
+ const empty = threads.find((thread) => thread.messages.length === 0 && !thread.draft.trim() && !thread.title && !thread.attachments.length);
1704
2012
  if (empty) {
1705
2013
  setActiveId(empty.id);
1706
2014
  return;
1707
2015
  }
1708
2016
  const id = `chat-${sequence.current++}`;
1709
- setThreads((previous) => [...previous, { id, title: "", draft: "", messages: [] }]);
2017
+ setThreads((previous) => [...previous, { id, title: "", draft: "", attachments: [], messages: [] }]);
1710
2018
  setActiveId(id);
1711
2019
  };
1712
2020
 
@@ -1720,13 +2028,13 @@ export function useChatDemo(getReply: (text: string) => string, getTitle: (text:
1720
2028
  pendingThreads.current.delete(id);
1721
2029
  const remaining = threads.filter((thread) => thread.id !== id);
1722
2030
  if (!remaining.length) {
1723
- remaining.push({ id: `chat-${sequence.current++}`, title: "", draft: "", messages: [] });
2031
+ remaining.push({ id: `chat-${sequence.current++}`, title: "", draft: "", attachments: [], messages: [] });
1724
2032
  }
1725
2033
  setThreads(remaining);
1726
2034
  if (activeId === id) setActiveId(remaining[remaining.length - 1].id);
1727
2035
  };
1728
2036
 
1729
- return { threads, activeThread, setActiveId, createThread, renameThread, deleteThread, setDraft, send, stop, edit, regenerate, isStreaming: activeThread.messages.some((message) => message.isStreaming) };
2037
+ return { threads, activeThread, setActiveId, createThread, renameThread, deleteThread, setDraft, attach, removeAttachment, send, stop, edit, regenerate, retry, isStreaming: activeThread.messages.some((message) => message.isStreaming) };
1730
2038
  }
1731
2039
  ````
1732
2040