@gemies/sdk 0.0.0-stage → 1.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 (246) hide show
  1. package/CHANGELOG.md +1678 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +15 -0
  4. package/README.md +516 -2
  5. package/package.json +105 -4
  6. package/src/accounts.ts +29 -0
  7. package/src/animations.ts +5 -0
  8. package/src/ask-eager.ts +8 -0
  9. package/src/ask-text.ts +11 -0
  10. package/src/ask.ts +12 -0
  11. package/src/avatar.ts +13 -0
  12. package/src/character.ts +1 -0
  13. package/src/components/AmbientField.tsx +580 -0
  14. package/src/components/ComposerDropZone.tsx +235 -0
  15. package/src/components/ComposerSuggestions.tsx +45 -0
  16. package/src/components/GemieAccounts.tsx +433 -0
  17. package/src/components/GemieAskCore.tsx +184 -0
  18. package/src/components/GemieAskProvider.tsx +18 -0
  19. package/src/components/GemieAskProviderLazy.tsx +27 -0
  20. package/src/components/GemieAskProviderText.tsx +25 -0
  21. package/src/components/GemieAskSheet.tsx +51 -0
  22. package/src/components/GemieAskSheetWithVoice.tsx +10 -0
  23. package/src/components/GemieAvatar.tsx +57 -0
  24. package/src/components/GemieAvatarIcon.tsx +35 -0
  25. package/src/components/GemieChatContent.tsx +900 -0
  26. package/src/components/GemieChatHeader.tsx +123 -0
  27. package/src/components/GemieChatScreen.tsx +170 -0
  28. package/src/components/GemieChatSheet.tsx +368 -0
  29. package/src/components/GemieChatWithVoice.tsx +13 -0
  30. package/src/components/GemieComposer.tsx +388 -0
  31. package/src/components/GemieGroupWelcome.tsx +37 -0
  32. package/src/components/GemieParticipants.tsx +133 -0
  33. package/src/components/GemieParticipantsHeader.tsx +27 -0
  34. package/src/components/GemieRecentConversations.tsx +65 -0
  35. package/src/components/GemieSharedConversation.tsx +87 -0
  36. package/src/components/GemieWelcomeMessage.tsx +58 -0
  37. package/src/components/IdentityMark.tsx +225 -0
  38. package/src/components/Image.tsx +12 -0
  39. package/src/components/InertWhen.tsx +48 -0
  40. package/src/components/PlanPreviewCard.tsx +53 -0
  41. package/src/components/QuestionCard.tsx +64 -0
  42. package/src/components/ReplyMarkdown.tsx +373 -0
  43. package/src/components/RichBlocks.tsx +195 -0
  44. package/src/components/VoiceModeIcon.tsx +18 -0
  45. package/src/components/canvas/CanvasComponent.tsx +65 -0
  46. package/src/components/canvas/ChartRenderer.tsx +73 -0
  47. package/src/components/canvas/CodeRenderer.tsx +20 -0
  48. package/src/components/canvas/DashboardRenderer.tsx +70 -0
  49. package/src/components/canvas/DeckRenderer.tsx +43 -0
  50. package/src/components/canvas/FormRenderer.tsx +101 -0
  51. package/src/components/canvas/MarkdownRenderer.tsx +14 -0
  52. package/src/components/canvas/TableRenderer.tsx +47 -0
  53. package/src/components/icons/RiEmojiPicker.tsx +39 -0
  54. package/src/components/icons/RiMoreDots.tsx +32 -0
  55. package/src/components/icons/RiReplyLine.tsx +25 -0
  56. package/src/components/thought/FilesAndSources.tsx +120 -0
  57. package/src/components/thought/ThoughtPanel.tsx +426 -0
  58. package/src/components/thought/ToolStep.tsx +134 -0
  59. package/src/components/thread/AgentExchangeView.tsx +112 -0
  60. package/src/components/thread/AgentResultCard.tsx +125 -0
  61. package/src/components/thread/AgentTaskCard.tsx +127 -0
  62. package/src/components/thread/ChatBubble.tsx +256 -0
  63. package/src/components/thread/GemieThread.tsx +455 -0
  64. package/src/components/thread/MessageBlockBoundary.tsx +78 -0
  65. package/src/components/thread/NewConversationOffer.tsx +54 -0
  66. package/src/components/thread/ThreadRow.tsx +598 -0
  67. package/src/components/thread/ThreadSearch.tsx +130 -0
  68. package/src/components/thread/ThreadSkeleton.tsx +30 -0
  69. package/src/components/thread/ToolResultCard.tsx +254 -0
  70. package/src/components/thread/TurnMenu.tsx +54 -0
  71. package/src/components/thread/TurnStatusLine.tsx +34 -0
  72. package/src/components/voice/GemieVoiceCall.tsx +21 -0
  73. package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
  74. package/src/components/voice/VoiceCallContext.ts +13 -0
  75. package/src/components/voice/VoiceControls.tsx +106 -0
  76. package/src/components/voice/VoiceSession.tsx +120 -0
  77. package/src/components/voice/withVoiceCall.tsx +25 -0
  78. package/src/csp.ts +50 -0
  79. package/src/dictation.ts +40 -0
  80. package/src/hooks/useAmbientWave.ts +184 -0
  81. package/src/hooks/useAtBottom.ts +51 -0
  82. package/src/hooks/useAttachMenu.ts +93 -0
  83. package/src/hooks/useAttachmentIntake.ts +401 -0
  84. package/src/hooks/useAudioLevelMonitor.ts +46 -0
  85. package/src/hooks/useAudioLevels.ts +51 -0
  86. package/src/hooks/useChatComposer.ts +309 -0
  87. package/src/hooks/useChatVoice.ts +129 -0
  88. package/src/hooks/useComposerSuggestions.ts +84 -0
  89. package/src/hooks/useDictation.ts +292 -0
  90. package/src/hooks/useDocumentPicker.ts +11 -0
  91. package/src/hooks/useFailedTurnToast.ts +43 -0
  92. package/src/hooks/useFocusWhenPresented.ts +41 -0
  93. package/src/hooks/useGemieActivity.ts +31 -0
  94. package/src/hooks/useImagePicker.ts +38 -0
  95. package/src/hooks/useMessageReactions.ts +119 -0
  96. package/src/hooks/useMessageVote.ts +50 -0
  97. package/src/hooks/useOpenThought.ts +79 -0
  98. package/src/hooks/usePendingQuestions.ts +19 -0
  99. package/src/hooks/useReadAloud.ts +92 -0
  100. package/src/hooks/useShareHandler.ts +24 -0
  101. package/src/hooks/useSoundEffects.ts +137 -0
  102. package/src/hooks/useTTS.ts +303 -0
  103. package/src/hooks/useThoughtScope.ts +59 -0
  104. package/src/hooks/useThreadRows.ts +157 -0
  105. package/src/hooks/useThreadView.ts +67 -0
  106. package/src/hooks/useTimelineWindow.ts +256 -0
  107. package/src/hooks/useVoiceLauncher.ts +180 -0
  108. package/src/hooks/useVoiceRoom.ts +212 -0
  109. package/src/index.ts +141 -0
  110. package/src/lib/activity-socket.ts +102 -0
  111. package/src/lib/activity-store.ts +53 -0
  112. package/src/lib/add-menu.ts +7 -0
  113. package/src/lib/agent-character.ts +28 -0
  114. package/src/lib/alia-character.ts +14 -0
  115. package/src/lib/alia-gemie.ts +6 -0
  116. package/src/lib/attachment-intake.ts +154 -0
  117. package/src/lib/attachment-tiles.ts +74 -0
  118. package/src/lib/audio-level.ts +130 -0
  119. package/src/lib/audio-request-auth.ts +4 -0
  120. package/src/lib/audio-session-binding.ts +27 -0
  121. package/src/lib/bubbles.tsx +16 -0
  122. package/src/lib/call-thread.ts +33 -0
  123. package/src/lib/canvas-result.ts +21 -0
  124. package/src/lib/catalogue-tool.ts +22 -0
  125. package/src/lib/citations.ts +192 -0
  126. package/src/lib/clipboard.ts +23 -0
  127. package/src/lib/content-utils.ts +46 -0
  128. package/src/lib/copy-en.ts +333 -0
  129. package/src/lib/copy-es.ts +330 -0
  130. package/src/lib/copy.ts +38 -0
  131. package/src/lib/deferred/document-picker.ts +2 -0
  132. package/src/lib/deferred/document-picker.web.ts +12 -0
  133. package/src/lib/deferred/expo-audio.ts +2 -0
  134. package/src/lib/deferred/expo-audio.web.ts +12 -0
  135. package/src/lib/deferred/image-data-url.ts +5 -0
  136. package/src/lib/deferred/image-data-url.web.ts +12 -0
  137. package/src/lib/dictation-protocol.ts +142 -0
  138. package/src/lib/dictation-recorder-types.ts +37 -0
  139. package/src/lib/dictation-recorder.native.ts +90 -0
  140. package/src/lib/dictation-recorder.ts +131 -0
  141. package/src/lib/dictation-stream.ts +238 -0
  142. package/src/lib/dictation.ts +216 -0
  143. package/src/lib/document-picker.ts +31 -0
  144. package/src/lib/domain.ts +12 -0
  145. package/src/lib/flights.ts +33 -0
  146. package/src/lib/focus-return.ts +66 -0
  147. package/src/lib/greeting.ts +15 -0
  148. package/src/lib/image-data-url.ts +35 -0
  149. package/src/lib/keyboard.native.tsx +25 -0
  150. package/src/lib/keyboard.tsx +55 -0
  151. package/src/lib/labels-es.ts +113 -0
  152. package/src/lib/labels.tsx +207 -0
  153. package/src/lib/origins.ts +28 -0
  154. package/src/lib/participants.ts +97 -0
  155. package/src/lib/pcm.ts +57 -0
  156. package/src/lib/power-level-options.ts +66 -0
  157. package/src/lib/questions.ts +92 -0
  158. package/src/lib/speech-language.ts +20 -0
  159. package/src/lib/speech-messages.ts +54 -0
  160. package/src/lib/speech-synthesis.ts +156 -0
  161. package/src/lib/suggestions.ts +53 -0
  162. package/src/lib/task-labels.ts +35 -0
  163. package/src/lib/text-input.ts +10 -0
  164. package/src/lib/tool-call-status.ts +28 -0
  165. package/src/lib/tool-icons.ts +36 -0
  166. package/src/lib/tool-registry.ts +71 -0
  167. package/src/lib/tool-renderers.tsx +32 -0
  168. package/src/lib/turn-state.ts +15 -0
  169. package/src/lib/utils.ts +35 -0
  170. package/src/lib/voice-audio-engine-types.ts +59 -0
  171. package/src/lib/voice-audio-engine.native.ts +232 -0
  172. package/src/lib/voice-audio-engine.ts +206 -0
  173. package/src/lib/voice-call-request.ts +49 -0
  174. package/src/lib/voice-call.ts +627 -0
  175. package/src/lib/voice-controls-labels.ts +31 -0
  176. package/src/lib/voice-levels.ts +64 -0
  177. package/src/lib/voice-protocol.ts +328 -0
  178. package/src/lib/voice-worklets.ts +19 -0
  179. package/src/lib/work-log.ts +370 -0
  180. package/src/metro/chart-importers.json +18 -0
  181. package/src/metro/granular-charts.js +3 -0
  182. package/src/metro/index.cjs +227 -0
  183. package/src/metro/index.d.cts +5 -0
  184. package/src/runtime/agents.ts +151 -0
  185. package/src/runtime/api.ts +144 -0
  186. package/src/runtime/app-assertion.ts +51 -0
  187. package/src/runtime/attachment-utils.ts +97 -0
  188. package/src/runtime/chat-turn-control.ts +74 -0
  189. package/src/runtime/composer-draft-store.ts +270 -0
  190. package/src/runtime/config.tsx +222 -0
  191. package/src/runtime/conversation-dates.ts +31 -0
  192. package/src/runtime/conversation-store.ts +49 -0
  193. package/src/runtime/conversations.ts +633 -0
  194. package/src/runtime/error-utils.ts +144 -0
  195. package/src/runtime/gemie-accounts.ts +182 -0
  196. package/src/runtime/host-tools.ts +290 -0
  197. package/src/runtime/index.ts +137 -0
  198. package/src/runtime/message-history.ts +124 -0
  199. package/src/runtime/message-reactions.ts +214 -0
  200. package/src/runtime/model.ts +39 -0
  201. package/src/runtime/oxy-files.ts +37 -0
  202. package/src/runtime/power-levels.ts +66 -0
  203. package/src/runtime/query-keys.ts +60 -0
  204. package/src/runtime/random-uuid.ts +25 -0
  205. package/src/runtime/reaction-cache.ts +45 -0
  206. package/src/runtime/room-events.ts +333 -0
  207. package/src/runtime/routes.ts +85 -0
  208. package/src/runtime/sharing.ts +217 -0
  209. package/src/runtime/sse-frame-reader.ts +88 -0
  210. package/src/runtime/stream-events.ts +154 -0
  211. package/src/runtime/stream-outcome.ts +21 -0
  212. package/src/runtime/thought-store.ts +103 -0
  213. package/src/runtime/thread/agent-activity.ts +261 -0
  214. package/src/runtime/thread/agent-exchange.ts +94 -0
  215. package/src/runtime/thread/automation-labels.ts +79 -0
  216. package/src/runtime/thread/conversation-export.ts +135 -0
  217. package/src/runtime/thread/message-days.ts +120 -0
  218. package/src/runtime/thread/message-processor.ts +93 -0
  219. package/src/runtime/thread/speaker-changes.ts +66 -0
  220. package/src/runtime/thread/task-utils.ts +11 -0
  221. package/src/runtime/thread/thought-utils.ts +750 -0
  222. package/src/runtime/thread/thread-history.ts +139 -0
  223. package/src/runtime/thread/timeline.ts +202 -0
  224. package/src/runtime/thread/title-tags.ts +8 -0
  225. package/src/runtime/thread/tool-cards.ts +387 -0
  226. package/src/runtime/turn-failure.ts +108 -0
  227. package/src/runtime/turn-preparation.ts +21 -0
  228. package/src/runtime/types.ts +172 -0
  229. package/src/runtime/usage-limit-error.ts +44 -0
  230. package/src/runtime/use-agent-activity.ts +80 -0
  231. package/src/runtime/use-conversation-stream.ts +1669 -0
  232. package/src/runtime/use-conversation-thread.ts +590 -0
  233. package/src/runtime/use-gemie-thread.ts +54 -0
  234. package/src/runtime/use-room-events.ts +75 -0
  235. package/src/runtime/use-start-conversation.ts +107 -0
  236. package/src/runtime/use-thread-history.ts +73 -0
  237. package/src/runtime/use-thread-search.ts +100 -0
  238. package/src/runtime/use-turn-edit.ts +99 -0
  239. package/src/text.ts +19 -0
  240. package/src/theme.ts +16 -0
  241. package/src/tools.ts +27 -0
  242. package/src/types.ts +161 -0
  243. package/src/voice-messages.ts +2 -0
  244. package/src/voice.ts +67 -0
  245. package/tsconfig.json +17 -0
  246. package/worklets/voice-processors.js +152 -0
@@ -0,0 +1,590 @@
1
+ import { toast } from '@oxy.so/bloom/toast';
2
+ import { useOxy } from '@oxy.so/services/ui/client';
3
+ import { useQueryClient } from '@tanstack/react-query';
4
+ import { useCallback, useEffect, useId, useMemo, useRef } from 'react';
5
+ import { useGemieActivityStore } from '../lib/activity-store';
6
+ import { turnActivityState } from '../lib/turn-state';
7
+ import { useLabels } from '../lib/labels';
8
+ import { getTextFromContent } from '../lib/content-utils';
9
+ import type { GemieAttachment } from '../types';
10
+ import { buildMessageContent } from './attachment-utils';
11
+ import type { GemieHostTools } from './host-tools';
12
+ import { useDocumentUpload } from './oxy-files';
13
+ import { useGemieRuntime } from './config';
14
+ import { releaseAttachments, useComposerDraftStore } from './composer-draft-store';
15
+ import { useConversationStore } from './conversation-store';
16
+ import {
17
+ ConversationNotFoundError,
18
+ useClearConversation,
19
+ useConversation,
20
+ useCreateConversation,
21
+ useDeleteConversation,
22
+ } from './conversations';
23
+ import { gemieQueryKeys } from './query-keys';
24
+ import { reportDroppedAttachments, useStartConversation } from './use-start-conversation';
25
+ import { createRoomLedger } from './room-events';
26
+ import { applyMessageReaction, type MessageReactionSnapshot } from './message-reactions';
27
+ import { useConversationStream } from './use-conversation-stream';
28
+ import { useRoomEvents } from './use-room-events';
29
+ import type { Message, SendOptions } from './types';
30
+
31
+ export interface UseConversationThreadOptions {
32
+ conversationId?: string;
33
+ /** The power level (or device model) every turn is sent with. */
34
+ model?: string;
35
+ agentId?: string;
36
+ /** What the host app is; see `useConversationStream`. */
37
+ clientContext?: string;
38
+ /** The UI effects the host performs; see `useConversationStream`. */
39
+ hostTools?: GemieHostTools;
40
+ }
41
+
42
+ type MessageContent = Message['content'];
43
+
44
+ /**
45
+ * What an edit sends in place of the original user turn.
46
+ *
47
+ * A STRING is the composer's edit: it replaces the text of the turn and keeps
48
+ * every non-text part (`image_url`, files) the turn already carried, because
49
+ * the composer only ever shows the text for editing and a person rewording a
50
+ * question about a picture has not asked for the picture to go. A full parts
51
+ * ARRAY is sent verbatim — that is how regenerate replays a turn unchanged, and
52
+ * how a caller that has deliberately removed an attachment says so.
53
+ */
54
+ export type EditedContent = string | MessageContent;
55
+
56
+ /**
57
+ * Merge an edit into the original turn's content, per the `EditedContent` rule.
58
+ * The replacement text lands where the original's first text part was, so a
59
+ * turn built as `[text, image]` stays `[text, image]` rather than reordering
60
+ * the picture ahead of the question; an original with no text part (image-only)
61
+ * gets the new text appended after its attachments.
62
+ */
63
+ export function mergeEditedContent(
64
+ original: MessageContent | undefined,
65
+ edit: EditedContent,
66
+ ): MessageContent {
67
+ if (typeof edit !== 'string') return edit;
68
+ if (!Array.isArray(original)) return edit;
69
+ const attachments = original.filter((part) => part.type !== 'text');
70
+ if (attachments.length === 0) return edit;
71
+ if (!edit.trim()) return attachments;
72
+ const textPart = { type: 'text', text: edit };
73
+ const firstTextIndex = original.findIndex((part) => part.type === 'text');
74
+ if (firstTextIndex < 0) return [...attachments, textPart];
75
+ const before = original.slice(0, firstTextIndex).filter((part) => part.type !== 'text');
76
+ const after = original.slice(firstTextIndex + 1).filter((part) => part.type !== 'text');
77
+ return [...before, textPart, ...after];
78
+ }
79
+
80
+ /** True when there is nothing to send: no text and no attachment part. */
81
+ function isEmptyContent(content: MessageContent | undefined): boolean {
82
+ if (content === undefined || content === null) return true;
83
+ if (typeof content === 'string') return !content.trim();
84
+ return content.length === 0;
85
+ }
86
+
87
+ export function useConversationThread({
88
+ conversationId,
89
+ model,
90
+ agentId,
91
+ clientContext,
92
+ hostTools,
93
+ }: UseConversationThreadOptions = {}) {
94
+ const queryClient = useQueryClient();
95
+ const labels = useLabels();
96
+ const { host } = useGemieRuntime();
97
+ const { user } = useOxy();
98
+ const bindDraftAccount = useComposerDraftStore((state) => state.bindAccount);
99
+ // The drafts are this account's: a different person starts with none.
100
+ useEffect(() => bindDraftAccount(user?.id ?? null), [bindDraftAccount, user?.id]);
101
+ const hasSentPendingMessage = useRef(false);
102
+ const lastConversationId = useRef<string | null>(null);
103
+ const wasLoadingRef = useRef(false);
104
+
105
+ const pendingInitialMessage = useConversationStore((state) => state.pendingInitialMessage);
106
+ const {
107
+ data: conversation,
108
+ error: conversationQueryError,
109
+ isLoading: conversationQueryLoading,
110
+ isFetching: conversationFetching,
111
+ } = useConversation(conversationId || '');
112
+ const createConversationMutation = useCreateConversation();
113
+ const { mutateAsync: deleteConversation } = useDeleteConversation();
114
+ const { mutateAsync: clearMessages } = useClearConversation();
115
+
116
+ // A missing row is not a transient loading failure and the URL cannot become
117
+ // useful by staying open. Remove its cached detail/list state and return to a
118
+ // valid composer; the query itself has retries disabled, so this happens once.
119
+ useEffect(() => {
120
+ if (!(conversationQueryError instanceof ConversationNotFoundError)) return;
121
+ queryClient.removeQueries({
122
+ queryKey: gemieQueryKeys.conversations.detail(conversationQueryError.conversationId),
123
+ });
124
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
125
+ host.closeConversation?.();
126
+ }, [conversationQueryError, queryClient, host]);
127
+
128
+ // One per open conversation: which consultation each message draws (the request's and the room's).
129
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a new conversation is a new ledger
130
+ const room = useMemo(() => createRoomLedger(), [conversationId]);
131
+
132
+ /**
133
+ * Turns go to `/v1/chat/completions`, the Gemies product API: the same handler `/alia/chat` mounts,
134
+ * on the one surface that answers a browser from any Oxy app's origin (see `routes.ts`).
135
+ */
136
+ const {
137
+ messages,
138
+ append,
139
+ isLoading,
140
+ composerPhase,
141
+ error,
142
+ clearError,
143
+ setMessages,
144
+ stop,
145
+ detach,
146
+ suggestedNewConversation,
147
+ dismissSuggestedNewConversation,
148
+ agentRun,
149
+ failedTurn,
150
+ retryFailedTurn: retry,
151
+ clearFailedTurn,
152
+ turnOptionsOf,
153
+ } = useConversationStream({
154
+ conversationId,
155
+ model,
156
+ agentId,
157
+ clientContext,
158
+ hostTools,
159
+ room,
160
+ });
161
+ // A group's members keep talking after the request: their room's events join the thread.
162
+ useRoomEvents(conversationId, room, setMessages, () => {
163
+ // While HTTP owns the turn its typed failure supplies the error card. Later
164
+ // selector failures have no agent bubble or matching client message ID.
165
+ if (!isLoading && failedTurn === null) toast.error(labels.sendFailed);
166
+ });
167
+ const applyReaction = useCallback(
168
+ (update: MessageReactionSnapshot) => {
169
+ if (update.conversationId === conversationId) {
170
+ setMessages((previous) => applyMessageReaction(previous, update));
171
+ }
172
+ },
173
+ [conversationId, setMessages],
174
+ );
175
+ const upload = useDocumentUpload();
176
+
177
+ // The turn's lifecycle, published for every "Ask Alia" button (`useGemieActivity`).
178
+ const activitySource = useId();
179
+ const activity = turnActivityState(messages, isLoading);
180
+ useEffect(() => {
181
+ const { setLocal } = useGemieActivityStore.getState();
182
+ setLocal(activitySource, activity);
183
+ return () => setLocal(activitySource, 'idle');
184
+ }, [activitySource, activity]);
185
+
186
+ // Expose streaming state globally so sidebar can show a spinner
187
+ const setStreamingConversationId = useConversationStore((s) => s.setStreamingConversationId);
188
+ useEffect(() => {
189
+ setStreamingConversationId(isLoading && conversationId ? conversationId : null);
190
+ return () => {
191
+ if (useConversationStore.getState().streamingConversationId === conversationId) {
192
+ setStreamingConversationId(null);
193
+ }
194
+ };
195
+ }, [isLoading, conversationId, setStreamingConversationId]);
196
+
197
+ // Refresh sidebar when streaming finishes (backend auto-saves with AI-generated title)
198
+ useEffect(() => {
199
+ if (wasLoadingRef.current && !isLoading && conversationId) {
200
+ // Immediate refetch (gets saved conversation data)
201
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
202
+ void queryClient.invalidateQueries({
203
+ queryKey: gemieQueryKeys.conversations.detail(conversationId),
204
+ });
205
+ // Delayed fallback for async title generation. Only the list needs it —
206
+ // re-fetching the whole message detail 5s after every exchange just for
207
+ // a possible title was a second full refetch per message.
208
+ const timer = setTimeout(() => {
209
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
210
+ }, 5000);
211
+ wasLoadingRef.current = isLoading;
212
+ return () => clearTimeout(timer);
213
+ }
214
+ wasLoadingRef.current = isLoading;
215
+ }, [isLoading, conversationId, queryClient]);
216
+
217
+ // Sync chatId and load messages when conversation changes or when
218
+ // seeded cache data upgrades to full data (messages go from empty to populated).
219
+ useEffect(() => {
220
+ if (!conversationId || conversationQueryLoading) return;
221
+
222
+ const incomingMessages = conversation?.messages || [];
223
+ const isNewConversation = lastConversationId.current !== conversationId;
224
+ const isDataUpgrade =
225
+ !isNewConversation && incomingMessages.length > 0 && messages.length === 0;
226
+
227
+ if (!isNewConversation && !isDataUpgrade) return;
228
+
229
+ if (isNewConversation) {
230
+ lastConversationId.current = conversationId;
231
+ hasSentPendingMessage.current = false;
232
+ }
233
+
234
+ const validMessages = incomingMessages
235
+ .filter((msg) => msg?.role && msg?.content !== undefined)
236
+ .map((msg, index) => ({
237
+ ...msg,
238
+ id: msg.id || `db-${conversationId}-${index}`,
239
+ }));
240
+ setMessages(validMessages);
241
+ }, [conversationId, conversation, conversationQueryLoading, setMessages, messages.length]);
242
+
243
+ // An agent wrote into THIS conversation on its own (a result, a check-in).
244
+ // Appended to what is on screen: the detail refetch alone would not reach an
245
+ // open chat, whose local messages are only replaced when the id changes. The
246
+ // server keeps it even if the next turn is sent before this arrives.
247
+ useEffect(() => {
248
+ if (!conversationId) return;
249
+ return host.subscribeConversationMessages?.(conversationId, (incoming) => {
250
+ if (!incoming?.id) return;
251
+ setMessages((prev) => (prev.some((m) => m.id === incoming.id) ? prev : [...prev, incoming]));
252
+ });
253
+ }, [conversationId, setMessages, host]);
254
+
255
+ // Send pending initial message for new conversations
256
+ useEffect(() => {
257
+ if (!conversationId || !pendingInitialMessage || isLoading) return;
258
+ // Addressed to the conversation it was made for: a second open thread must not take it.
259
+ if (pendingInitialMessage.conversationId !== conversationId) return;
260
+ if (hasSentPendingMessage.current) return;
261
+ if (messages.length > 0) return; // Only send if no messages yet
262
+
263
+ const pending = pendingInitialMessage;
264
+ // Taken now: a failure is handed back to the account that sent it, never
265
+ // to one signed in while the request was out.
266
+ const newChatDraft = useComposerDraftStore.getState().address(null);
267
+ hasSentPendingMessage.current = true;
268
+ host.onTurnStart?.();
269
+ useConversationStore.getState().clearPendingInitialMessage();
270
+
271
+ void append(
272
+ { role: 'user', content: pending.content },
273
+ { mcpServerId: pending.mcpServerId, skillNames: pending.skillNames },
274
+ ).then(async (outcome) => {
275
+ // The request carries the bytes inline now; the temporary URLs behind
276
+ // the tiles have nothing left to show.
277
+ if (outcome !== 'failed') {
278
+ releaseAttachments(pending.attachments);
279
+ return;
280
+ }
281
+
282
+ // The conversation was created by POST /conversations/new before the model
283
+ // was ever reached, and this guard ran on messages.length === 0, so the row
284
+ // is provably empty. Undo it rather than leave a blank chat in the sidebar.
285
+ // A failed delete still leaves the user whole — it only leaves the row.
286
+ await deleteConversation(conversationId).catch(() => {});
287
+ useComposerDraftStore.getState().restore(newChatDraft, {
288
+ text: pending.text,
289
+ attachments: pending.attachments,
290
+ mcpServerId: pending.mcpServerId,
291
+ skillNames: pending.skillNames,
292
+ });
293
+ host.closeConversation?.();
294
+ toast.error(labels.sendFailed);
295
+ });
296
+ }, [
297
+ conversationId,
298
+ pendingInitialMessage,
299
+ isLoading,
300
+ messages.length,
301
+ append,
302
+ deleteConversation,
303
+ host,
304
+ labels,
305
+ ]);
306
+
307
+ // Actions
308
+ const sendMessage = useCallback(
309
+ async (
310
+ content: string,
311
+ attachments?: GemieAttachment[],
312
+ options?: SendOptions,
313
+ ): Promise<boolean> => {
314
+ if ((!content.trim() && !attachments?.length) || isLoading) return false;
315
+ const draft = useComposerDraftStore.getState().address(conversationId ?? null);
316
+
317
+ host.onTurnStart?.();
318
+
319
+ const built = attachments?.length
320
+ ? await buildMessageContent(content, attachments, upload)
321
+ : null;
322
+ const messageContent = built ? built.content : content;
323
+ reportDroppedAttachments(built?.dropped, labels);
324
+
325
+ const outcome = await append({ role: 'user', content: messageContent }, options);
326
+
327
+ // Nothing was persisted server-side (a turn without an assistant response is
328
+ // never saved), so returning the composer to its pre-send state is the whole
329
+ // rollback. Only the usage-limit errors end here now; every other failure
330
+ // is `errored` — the turn stays in the thread with its error and a retry,
331
+ // and the composer stays clear because the text is already on screen.
332
+ if (outcome === 'failed') {
333
+ useComposerDraftStore.getState().restore(draft, {
334
+ text: content,
335
+ attachments: attachments ?? [],
336
+ mcpServerId: options?.mcpServerId ?? null,
337
+ skillNames: options?.skillNames ?? [],
338
+ });
339
+ toast.error(labels.sendFailed);
340
+ return false;
341
+ }
342
+ // A retry re-sends the built content, whose bytes are inline.
343
+ releaseAttachments(attachments ?? []);
344
+ return true;
345
+ },
346
+ [isLoading, append, conversationId, host, labels, upload],
347
+ );
348
+
349
+ const startConversation = useStartConversation({ agentId });
350
+ const createNewConversation = useCallback(
351
+ (text: string, attachments?: GemieAttachment[], options?: SendOptions) =>
352
+ startConversation(text, { attachments, options }),
353
+ [startConversation],
354
+ );
355
+
356
+ /**
357
+ * The conversation a voice call lives in: the open one, or — on a new-chat
358
+ * screen — a new one, created now and shown, so the transcript has a home
359
+ * the moment the call starts. `undefined` when it could not be created.
360
+ */
361
+ const ensureConversation = useCallback(async (): Promise<string | undefined> => {
362
+ if (conversationId) return conversationId;
363
+ try {
364
+ const created = await createConversationMutation.mutateAsync({ agentId });
365
+ host.openConversation?.(created.id);
366
+ return created.id;
367
+ } catch {
368
+ // useCreateConversation.onError already told the person.
369
+ return undefined;
370
+ }
371
+ }, [conversationId, createConversationMutation, agentId, host]);
372
+
373
+ /** Leave this thread for an empty one. Nothing is deleted: the conversation stays in the list. */
374
+ const startOver = useCallback(() => {
375
+ stop();
376
+ setMessages([]);
377
+ clearFailedTurn();
378
+ host.closeConversation?.();
379
+ }, [stop, setMessages, clearFailedTurn, host]);
380
+
381
+ /**
382
+ * Rewrite a user turn: cut the thread back to it and send the new version.
383
+ *
384
+ * `attachments` are the ones added in the composer while editing. They go
385
+ * AFTER whatever the turn already carried — a string edit keeps those, see
386
+ * `EditedContent` — so rewording a question and adding a second picture is
387
+ * one edit, not a lost picture.
388
+ */
389
+ const editMessage = useCallback(
390
+ async (
391
+ messageId: string,
392
+ newContent: EditedContent,
393
+ options?: SendOptions,
394
+ attachments?: GemieAttachment[],
395
+ ): Promise<boolean> => {
396
+ // Truncate to messages before the edited one, then re-send.
397
+ // setMessages eagerly syncs messagesRef so append reads truncated history.
398
+ const beforeEdit = messages;
399
+ const draft = useComposerDraftStore.getState().address(conversationId ?? null);
400
+ const original = messages.find((msg) => msg.id === messageId);
401
+ if (original === undefined) return false;
402
+ // Like a send: while a reply streams, truncating the thread under it would let the old
403
+ // stream keep writing into the new turn. The composer gets the words back.
404
+ if (isLoading) return false;
405
+ // A string edit keeps the original turn's attachments; only a full parts
406
+ // array replaces them. See `EditedContent`.
407
+ let content = mergeEditedContent(original.content, newContent);
408
+ if (attachments?.length && typeof newContent === 'string') {
409
+ const built = await buildMessageContent(newContent, attachments, upload);
410
+ reportDroppedAttachments(built.dropped, labels);
411
+ const added =
412
+ typeof built.content === 'string'
413
+ ? []
414
+ : built.content.filter((part) => part.type !== 'text');
415
+ if (added.length > 0) {
416
+ content = [
417
+ ...(typeof content === 'string' ? [{ type: 'text', text: content }] : content),
418
+ ...added,
419
+ ];
420
+ }
421
+ }
422
+ if (isEmptyContent(content)) return false;
423
+
424
+ // An edit sends a new turn (so does a regenerate, through here).
425
+ host.onTurnStart?.();
426
+
427
+ setMessages((prev) => {
428
+ const idx = prev.findIndex((msg) => msg.id === messageId);
429
+ return idx < 0 ? prev : prev.slice(0, idx);
430
+ });
431
+
432
+ const outcome = await append({ role: 'user', content }, options);
433
+
434
+ // append rolls back to the truncated list; only this scope still knows what
435
+ // was cut, so it restores the rest and returns the edit to the composer.
436
+ // The original turn — attachments included — comes back with the rest, so
437
+ // nothing the person attached is orphaned by a send that never happened;
438
+ // the composer gets the text, and the attachments added while editing.
439
+ if (outcome === 'failed') {
440
+ setMessages(beforeEdit);
441
+ useComposerDraftStore.getState().restore(draft, {
442
+ text: typeof newContent === 'string' ? newContent : getTextFromContent(content),
443
+ attachments: attachments ?? [],
444
+ mcpServerId: options?.mcpServerId ?? null,
445
+ skillNames: options?.skillNames ?? [],
446
+ });
447
+ toast.error(labels.sendFailed);
448
+ return false;
449
+ }
450
+ releaseAttachments(attachments ?? []);
451
+ return true;
452
+ },
453
+ [setMessages, append, messages, conversationId, host, labels, upload, isLoading],
454
+ );
455
+
456
+ /** The user turn a reply answers: the nearest one before it, or `undefined`. */
457
+ const promptOf = useCallback(
458
+ (assistantMessageId: string): Message | undefined => {
459
+ const idx = messages.findIndex((msg) => msg.id === assistantMessageId);
460
+ for (let i = idx - 1; i >= 0; i--) {
461
+ const earlier = messages[i];
462
+ if (earlier?.role === 'user') return earlier;
463
+ }
464
+ return undefined;
465
+ },
466
+ [messages],
467
+ );
468
+
469
+ /**
470
+ * Ask for this reply again, with the options its prompt was sent with.
471
+ *
472
+ * `fallback` is for a prompt this screen did not send (the conversation was
473
+ * reloaded since): nothing records what it carried, so the caller's current
474
+ * choice — the composer's — is the best there is.
475
+ */
476
+ const regenerateMessage = useCallback(
477
+ async (assistantMessageId: string, fallback?: SendOptions): Promise<boolean> => {
478
+ // Regenerating IS re-sending the prompt that produced this answer. Walk back
479
+ // to the user turn before it and replay that — editMessage already truncates
480
+ // the history and re-appends, so there is no second path to keep in step.
481
+ //
482
+ // The turn goes through WHOLE: a string stays a string and a parts array
483
+ // keeps its `image_url`/file parts. Reducing it to its text first is what
484
+ // used to regenerate "what is in this picture" without the picture, and
485
+ // refuse outright on a prompt that was only a picture.
486
+ const prompt = promptOf(assistantMessageId);
487
+ if (prompt === undefined || isEmptyContent(prompt.content)) return false;
488
+ return editMessage(prompt.id, prompt.content, turnOptionsOf(prompt.id) ?? fallback);
489
+ },
490
+ [promptOf, editMessage, turnOptionsOf],
491
+ );
492
+
493
+ const stopGeneration = useCallback(() => {
494
+ stop();
495
+ }, [stop]);
496
+
497
+ /**
498
+ * Send the failed turn again. Guarded on `isLoading` like `sendMessage`:
499
+ * the card is gone the moment a send starts, but a double tap can land
500
+ * before that render.
501
+ */
502
+ const retryFailedTurn = useCallback(async (): Promise<boolean> => {
503
+ if (isLoading) return false;
504
+ host.onTurnStart?.();
505
+ const outcome = await retry();
506
+ return outcome !== 'failed';
507
+ }, [isLoading, retry, host]);
508
+
509
+ /**
510
+ * Empty the thread — on the server first, then on screen.
511
+ *
512
+ * The order is the fix for #553. `setMessages([])` alone cleared the screen
513
+ * and nothing else, and the sync effect above, seeing a cached history and
514
+ * no messages, read that as a data upgrade and hydrated it straight back
515
+ * under a dialog that had just promised the action could not be undone.
516
+ * `useClearConversation` empties the cache in its `onSuccess`, which has run
517
+ * by the time `mutateAsync` resolves, so the local reset that follows has
518
+ * nothing left to be undone by.
519
+ *
520
+ * A turn still streaming is stopped first rather than refused: the person
521
+ * has just confirmed they want the thread empty, and an answer that kept
522
+ * arriving into it would be the next thing to clear. Stopping settles the
523
+ * assistant placeholder as `cancelled` and lets the server close the turn,
524
+ * so the clear that follows is of a thread nothing is writing to.
525
+ *
526
+ * A refusal keeps everything: the screen is not reset, the cache is not
527
+ * touched, and the error is surfaced — a cleared view whose history returns
528
+ * on the next fetch is exactly the state this exists to end.
529
+ *
530
+ * With no conversation id there is nothing persisted to clear, so the
531
+ * screen's own list is all there is and the local reset is the whole job.
532
+ */
533
+ const clearConversation = useCallback(async (): Promise<boolean> => {
534
+ if (isLoading) stop();
535
+
536
+ if (conversationId) {
537
+ try {
538
+ await clearMessages(conversationId);
539
+ } catch {
540
+ toast.error(labels.conversationClearFailed);
541
+ return false;
542
+ }
543
+ }
544
+
545
+ setMessages([]);
546
+ // The message the error hung under is gone with the rest.
547
+ clearFailedTurn();
548
+ return true;
549
+ }, [isLoading, stop, conversationId, clearMessages, setMessages, clearFailedTurn, labels]);
550
+
551
+ // True while loading conversation messages (initial fetch or seeded→full upgrade)
552
+ const conversationLoading =
553
+ conversationQueryLoading ||
554
+ (conversationFetching && (!conversation?.messages || conversation.messages.length === 0));
555
+
556
+ return {
557
+ // State
558
+ conversationId,
559
+ conversation,
560
+ messages,
561
+ isLoading,
562
+ composerPhase,
563
+ conversationLoading,
564
+ error,
565
+
566
+ // Actions
567
+ sendMessage,
568
+ createNewConversation,
569
+ ensureConversation,
570
+ startOver,
571
+ editMessage,
572
+ regenerateMessage,
573
+ promptOf,
574
+ turnOptionsOf,
575
+ stopGeneration,
576
+ detachGeneration: detach,
577
+ clearConversation,
578
+ clearError,
579
+ setMessages,
580
+ applyReaction,
581
+ suggestedNewConversation,
582
+ dismissSuggestedNewConversation,
583
+ agentRun,
584
+ failedTurn,
585
+ retryFailedTurn,
586
+ };
587
+ }
588
+
589
+ /** What `useConversationThread` hands back: the open conversation and everything that can be done to it. */
590
+ export type ConversationThread = ReturnType<typeof useConversationThread>;
@@ -0,0 +1,54 @@
1
+ import { useQuery } from '@tanstack/react-query';
2
+ import { useGemieApi } from './api';
3
+ import { gemieQueryKeys } from './query-keys';
4
+ import { AGENT_ROUTES, threadKey } from './routes';
5
+ import { retryThreadRead } from './use-thread-history';
6
+
7
+ /** A gemie's thread with the signed-in person, as `GET /agents/:id/thread` answers it. */
8
+ export interface GemieThreadInfo {
9
+ /** Who the thread is with. `name`, `handle` and `color` come from Oxy and may be `null` (Alia's do, until her account exists). */
10
+ readonly agent: {
11
+ readonly _id: string;
12
+ readonly name: string | null;
13
+ readonly handle: string | null;
14
+ readonly character: unknown;
15
+ readonly tagline: string;
16
+ readonly description: string;
17
+ };
18
+ /** The active stretch: `GemieChatContent`'s `conversationId`, where the next turn goes. */
19
+ readonly conversationId: string;
20
+ /**
21
+ * The thread row, for a gemie whose chats are loose (Alia): her thread is apart from them, and its
22
+ * next stretch is `useCreateConversation({ threadId })`. `null` for any other gemie, whose thread is
23
+ * every conversation the two hold.
24
+ */
25
+ readonly threadId: string | null;
26
+ }
27
+
28
+ /** How long the open thread is good: it changes when the person starts a stretch, which invalidates it. */
29
+ const THREAD_STALE_MS = 5 * 60 * 1000;
30
+
31
+ /**
32
+ * Open the person's thread with a gemie by its id — Alia's thread mode, since she has no handle
33
+ * (ADR 0034). The first open CREATES the thread and its first stretch, so ask only when the person
34
+ * opens it, never to prefetch one nobody started.
35
+ *
36
+ * Render the chat with what it answers: `<GemieChatContent conversationId={thread.conversationId}
37
+ * gemieThread={{ gemieId, threadId: thread.threadId }} />`. Keyed under `gemieQueryKeys.threads.all`,
38
+ * so starting the next stretch from the chat moves this onto it.
39
+ */
40
+ export function useGemieThread(gemieId: string | undefined) {
41
+ const api = useGemieApi();
42
+ const address = { gemieId: gemieId ?? '' };
43
+ return useQuery({
44
+ queryKey: gemieQueryKeys.threads.all(threadKey(address)),
45
+ queryFn: async (): Promise<GemieThreadInfo> => {
46
+ const { data } = await api.get<GemieThreadInfo>(AGENT_ROUTES.thread(address));
47
+ return data;
48
+ },
49
+ enabled: (gemieId?.length ?? 0) > 0,
50
+ staleTime: THREAD_STALE_MS,
51
+ // A 404 is an answer: the gemie does not exist or this person cannot open it.
52
+ retry: retryThreadRead,
53
+ });
54
+ }