@gemies/sdk 0.0.0-stage → 1.0.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 (242) hide show
  1. package/CHANGELOG.md +1662 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +15 -0
  4. package/README.md +516 -2
  5. package/package.json +102 -4
  6. package/src/animations.ts +5 -0
  7. package/src/ask-eager.ts +8 -0
  8. package/src/ask-text.ts +11 -0
  9. package/src/ask.ts +12 -0
  10. package/src/avatar.ts +13 -0
  11. package/src/character.ts +1 -0
  12. package/src/components/AmbientField.tsx +580 -0
  13. package/src/components/ComposerDropZone.tsx +235 -0
  14. package/src/components/ComposerSuggestions.tsx +45 -0
  15. package/src/components/GemieAskCore.tsx +184 -0
  16. package/src/components/GemieAskProvider.tsx +18 -0
  17. package/src/components/GemieAskProviderLazy.tsx +27 -0
  18. package/src/components/GemieAskProviderText.tsx +25 -0
  19. package/src/components/GemieAskSheet.tsx +51 -0
  20. package/src/components/GemieAskSheetWithVoice.tsx +10 -0
  21. package/src/components/GemieAvatar.tsx +57 -0
  22. package/src/components/GemieAvatarIcon.tsx +35 -0
  23. package/src/components/GemieChatContent.tsx +900 -0
  24. package/src/components/GemieChatHeader.tsx +123 -0
  25. package/src/components/GemieChatScreen.tsx +170 -0
  26. package/src/components/GemieChatSheet.tsx +368 -0
  27. package/src/components/GemieChatWithVoice.tsx +13 -0
  28. package/src/components/GemieComposer.tsx +388 -0
  29. package/src/components/GemieGroupWelcome.tsx +37 -0
  30. package/src/components/GemieParticipants.tsx +133 -0
  31. package/src/components/GemieParticipantsHeader.tsx +27 -0
  32. package/src/components/GemieRecentConversations.tsx +65 -0
  33. package/src/components/GemieSharedConversation.tsx +87 -0
  34. package/src/components/GemieWelcomeMessage.tsx +58 -0
  35. package/src/components/IdentityMark.tsx +225 -0
  36. package/src/components/Image.tsx +12 -0
  37. package/src/components/InertWhen.tsx +48 -0
  38. package/src/components/PlanPreviewCard.tsx +53 -0
  39. package/src/components/QuestionCard.tsx +64 -0
  40. package/src/components/ReplyMarkdown.tsx +373 -0
  41. package/src/components/RichBlocks.tsx +195 -0
  42. package/src/components/VoiceModeIcon.tsx +18 -0
  43. package/src/components/canvas/CanvasComponent.tsx +65 -0
  44. package/src/components/canvas/ChartRenderer.tsx +73 -0
  45. package/src/components/canvas/CodeRenderer.tsx +20 -0
  46. package/src/components/canvas/DashboardRenderer.tsx +70 -0
  47. package/src/components/canvas/DeckRenderer.tsx +43 -0
  48. package/src/components/canvas/FormRenderer.tsx +101 -0
  49. package/src/components/canvas/MarkdownRenderer.tsx +14 -0
  50. package/src/components/canvas/TableRenderer.tsx +47 -0
  51. package/src/components/icons/RiEmojiPicker.tsx +39 -0
  52. package/src/components/icons/RiMoreDots.tsx +32 -0
  53. package/src/components/icons/RiReplyLine.tsx +25 -0
  54. package/src/components/thought/FilesAndSources.tsx +120 -0
  55. package/src/components/thought/ThoughtPanel.tsx +426 -0
  56. package/src/components/thought/ToolStep.tsx +134 -0
  57. package/src/components/thread/AgentExchangeView.tsx +112 -0
  58. package/src/components/thread/AgentResultCard.tsx +125 -0
  59. package/src/components/thread/AgentTaskCard.tsx +127 -0
  60. package/src/components/thread/ChatBubble.tsx +256 -0
  61. package/src/components/thread/GemieThread.tsx +455 -0
  62. package/src/components/thread/MessageBlockBoundary.tsx +78 -0
  63. package/src/components/thread/NewConversationOffer.tsx +54 -0
  64. package/src/components/thread/ThreadRow.tsx +598 -0
  65. package/src/components/thread/ThreadSearch.tsx +130 -0
  66. package/src/components/thread/ThreadSkeleton.tsx +30 -0
  67. package/src/components/thread/ToolResultCard.tsx +254 -0
  68. package/src/components/thread/TurnMenu.tsx +54 -0
  69. package/src/components/thread/TurnStatusLine.tsx +34 -0
  70. package/src/components/voice/GemieVoiceCall.tsx +21 -0
  71. package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
  72. package/src/components/voice/VoiceCallContext.ts +13 -0
  73. package/src/components/voice/VoiceControls.tsx +106 -0
  74. package/src/components/voice/VoiceSession.tsx +120 -0
  75. package/src/components/voice/withVoiceCall.tsx +25 -0
  76. package/src/csp.ts +50 -0
  77. package/src/dictation.ts +40 -0
  78. package/src/hooks/useAmbientWave.ts +184 -0
  79. package/src/hooks/useAtBottom.ts +51 -0
  80. package/src/hooks/useAttachMenu.ts +93 -0
  81. package/src/hooks/useAttachmentIntake.ts +401 -0
  82. package/src/hooks/useAudioLevelMonitor.ts +46 -0
  83. package/src/hooks/useAudioLevels.ts +51 -0
  84. package/src/hooks/useChatComposer.ts +309 -0
  85. package/src/hooks/useChatVoice.ts +129 -0
  86. package/src/hooks/useComposerSuggestions.ts +84 -0
  87. package/src/hooks/useDictation.ts +292 -0
  88. package/src/hooks/useDocumentPicker.ts +11 -0
  89. package/src/hooks/useFailedTurnToast.ts +43 -0
  90. package/src/hooks/useFocusWhenPresented.ts +41 -0
  91. package/src/hooks/useGemieActivity.ts +31 -0
  92. package/src/hooks/useImagePicker.ts +38 -0
  93. package/src/hooks/useMessageReactions.ts +119 -0
  94. package/src/hooks/useMessageVote.ts +50 -0
  95. package/src/hooks/useOpenThought.ts +79 -0
  96. package/src/hooks/usePendingQuestions.ts +19 -0
  97. package/src/hooks/useReadAloud.ts +92 -0
  98. package/src/hooks/useShareHandler.ts +24 -0
  99. package/src/hooks/useSoundEffects.ts +137 -0
  100. package/src/hooks/useTTS.ts +303 -0
  101. package/src/hooks/useThoughtScope.ts +59 -0
  102. package/src/hooks/useThreadRows.ts +157 -0
  103. package/src/hooks/useThreadView.ts +67 -0
  104. package/src/hooks/useTimelineWindow.ts +256 -0
  105. package/src/hooks/useVoiceLauncher.ts +180 -0
  106. package/src/hooks/useVoiceRoom.ts +212 -0
  107. package/src/index.ts +140 -0
  108. package/src/lib/activity-socket.ts +102 -0
  109. package/src/lib/activity-store.ts +53 -0
  110. package/src/lib/add-menu.ts +7 -0
  111. package/src/lib/agent-character.ts +28 -0
  112. package/src/lib/alia-character.ts +14 -0
  113. package/src/lib/attachment-intake.ts +154 -0
  114. package/src/lib/attachment-tiles.ts +74 -0
  115. package/src/lib/audio-level.ts +130 -0
  116. package/src/lib/audio-request-auth.ts +4 -0
  117. package/src/lib/audio-session-binding.ts +27 -0
  118. package/src/lib/bubbles.tsx +16 -0
  119. package/src/lib/call-thread.ts +33 -0
  120. package/src/lib/canvas-result.ts +21 -0
  121. package/src/lib/catalogue-tool.ts +22 -0
  122. package/src/lib/citations.ts +192 -0
  123. package/src/lib/clipboard.ts +23 -0
  124. package/src/lib/content-utils.ts +46 -0
  125. package/src/lib/copy-en.ts +291 -0
  126. package/src/lib/copy-es.ts +287 -0
  127. package/src/lib/copy.ts +38 -0
  128. package/src/lib/deferred/document-picker.ts +2 -0
  129. package/src/lib/deferred/document-picker.web.ts +12 -0
  130. package/src/lib/deferred/expo-audio.ts +2 -0
  131. package/src/lib/deferred/expo-audio.web.ts +12 -0
  132. package/src/lib/deferred/image-data-url.ts +5 -0
  133. package/src/lib/deferred/image-data-url.web.ts +12 -0
  134. package/src/lib/dictation-protocol.ts +142 -0
  135. package/src/lib/dictation-recorder-types.ts +37 -0
  136. package/src/lib/dictation-recorder.native.ts +90 -0
  137. package/src/lib/dictation-recorder.ts +131 -0
  138. package/src/lib/dictation-stream.ts +238 -0
  139. package/src/lib/dictation.ts +216 -0
  140. package/src/lib/document-picker.ts +31 -0
  141. package/src/lib/domain.ts +12 -0
  142. package/src/lib/flights.ts +33 -0
  143. package/src/lib/focus-return.ts +66 -0
  144. package/src/lib/greeting.ts +15 -0
  145. package/src/lib/image-data-url.ts +35 -0
  146. package/src/lib/keyboard.native.tsx +25 -0
  147. package/src/lib/keyboard.tsx +55 -0
  148. package/src/lib/labels-es.ts +113 -0
  149. package/src/lib/labels.tsx +207 -0
  150. package/src/lib/origins.ts +28 -0
  151. package/src/lib/participants.ts +97 -0
  152. package/src/lib/pcm.ts +57 -0
  153. package/src/lib/power-level-options.ts +66 -0
  154. package/src/lib/questions.ts +92 -0
  155. package/src/lib/speech-language.ts +20 -0
  156. package/src/lib/speech-messages.ts +54 -0
  157. package/src/lib/speech-synthesis.ts +156 -0
  158. package/src/lib/suggestions.ts +53 -0
  159. package/src/lib/task-labels.ts +35 -0
  160. package/src/lib/text-input.ts +10 -0
  161. package/src/lib/tool-call-status.ts +28 -0
  162. package/src/lib/tool-icons.ts +36 -0
  163. package/src/lib/tool-registry.ts +71 -0
  164. package/src/lib/tool-renderers.tsx +32 -0
  165. package/src/lib/turn-state.ts +15 -0
  166. package/src/lib/utils.ts +35 -0
  167. package/src/lib/voice-audio-engine-types.ts +59 -0
  168. package/src/lib/voice-audio-engine.native.ts +232 -0
  169. package/src/lib/voice-audio-engine.ts +206 -0
  170. package/src/lib/voice-call-request.ts +49 -0
  171. package/src/lib/voice-call.ts +627 -0
  172. package/src/lib/voice-controls-labels.ts +31 -0
  173. package/src/lib/voice-levels.ts +64 -0
  174. package/src/lib/voice-protocol.ts +328 -0
  175. package/src/lib/voice-worklets.ts +19 -0
  176. package/src/lib/work-log.ts +370 -0
  177. package/src/metro/chart-importers.json +18 -0
  178. package/src/metro/granular-charts.js +3 -0
  179. package/src/metro/index.cjs +227 -0
  180. package/src/metro/index.d.cts +5 -0
  181. package/src/runtime/agents.ts +151 -0
  182. package/src/runtime/api.ts +144 -0
  183. package/src/runtime/app-assertion.ts +51 -0
  184. package/src/runtime/attachment-utils.ts +97 -0
  185. package/src/runtime/chat-turn-control.ts +74 -0
  186. package/src/runtime/composer-draft-store.ts +270 -0
  187. package/src/runtime/config.tsx +222 -0
  188. package/src/runtime/conversation-dates.ts +31 -0
  189. package/src/runtime/conversation-store.ts +49 -0
  190. package/src/runtime/conversations.ts +633 -0
  191. package/src/runtime/error-utils.ts +144 -0
  192. package/src/runtime/host-tools.ts +290 -0
  193. package/src/runtime/index.ts +137 -0
  194. package/src/runtime/message-history.ts +124 -0
  195. package/src/runtime/message-reactions.ts +214 -0
  196. package/src/runtime/model.ts +39 -0
  197. package/src/runtime/oxy-files.ts +37 -0
  198. package/src/runtime/power-levels.ts +66 -0
  199. package/src/runtime/query-keys.ts +49 -0
  200. package/src/runtime/random-uuid.ts +25 -0
  201. package/src/runtime/reaction-cache.ts +45 -0
  202. package/src/runtime/room-events.ts +333 -0
  203. package/src/runtime/routes.ts +81 -0
  204. package/src/runtime/sharing.ts +217 -0
  205. package/src/runtime/sse-frame-reader.ts +88 -0
  206. package/src/runtime/stream-events.ts +154 -0
  207. package/src/runtime/stream-outcome.ts +21 -0
  208. package/src/runtime/thought-store.ts +103 -0
  209. package/src/runtime/thread/agent-activity.ts +261 -0
  210. package/src/runtime/thread/agent-exchange.ts +94 -0
  211. package/src/runtime/thread/automation-labels.ts +79 -0
  212. package/src/runtime/thread/conversation-export.ts +135 -0
  213. package/src/runtime/thread/message-days.ts +120 -0
  214. package/src/runtime/thread/message-processor.ts +93 -0
  215. package/src/runtime/thread/speaker-changes.ts +66 -0
  216. package/src/runtime/thread/task-utils.ts +11 -0
  217. package/src/runtime/thread/thought-utils.ts +750 -0
  218. package/src/runtime/thread/thread-history.ts +139 -0
  219. package/src/runtime/thread/timeline.ts +202 -0
  220. package/src/runtime/thread/title-tags.ts +8 -0
  221. package/src/runtime/thread/tool-cards.ts +387 -0
  222. package/src/runtime/turn-failure.ts +108 -0
  223. package/src/runtime/turn-preparation.ts +21 -0
  224. package/src/runtime/types.ts +172 -0
  225. package/src/runtime/usage-limit-error.ts +44 -0
  226. package/src/runtime/use-agent-activity.ts +80 -0
  227. package/src/runtime/use-conversation-stream.ts +1669 -0
  228. package/src/runtime/use-conversation-thread.ts +590 -0
  229. package/src/runtime/use-gemie-thread.ts +54 -0
  230. package/src/runtime/use-room-events.ts +75 -0
  231. package/src/runtime/use-start-conversation.ts +107 -0
  232. package/src/runtime/use-thread-history.ts +73 -0
  233. package/src/runtime/use-thread-search.ts +100 -0
  234. package/src/runtime/use-turn-edit.ts +99 -0
  235. package/src/text.ts +19 -0
  236. package/src/theme.ts +16 -0
  237. package/src/tools.ts +27 -0
  238. package/src/types.ts +161 -0
  239. package/src/voice-messages.ts +2 -0
  240. package/src/voice.ts +67 -0
  241. package/tsconfig.json +17 -0
  242. package/worklets/voice-processors.js +152 -0
@@ -0,0 +1,633 @@
1
+ import {
2
+ type QueryClient,
3
+ useInfiniteQuery,
4
+ useMutation,
5
+ useQuery,
6
+ useQueryClient,
7
+ } from '@tanstack/react-query';
8
+ import { toast } from '@oxy.so/bloom/toast';
9
+ import { useOxy } from '@oxy.so/services/ui/client';
10
+ import { useCallback, useEffect, useMemo, useState } from 'react';
11
+ import { useLabels } from '../lib/labels';
12
+ import { type GemieApi, useGemieApi } from './api';
13
+ import { type OfflineConversationStore, useGemieRuntime } from './config';
14
+ import { errorMessage as getErrorMessage, errorStatus } from './error-utils';
15
+ import { reviveConversationDates } from './conversation-dates';
16
+ import { normalizeConversationMessages } from './message-history';
17
+ import { gemieQueryKeys, type ConversationsFilter } from './query-keys';
18
+ import { API_ROUTES } from './routes';
19
+ import { createRandomUuid } from './random-uuid';
20
+ import type { Conversation, ConversationsInfiniteData, ConversationsPage, Message } from './types';
21
+
22
+ /** Conversation as returned by the API (timestamps are ISO strings, not Dates). */
23
+ type ApiConversation = Omit<Conversation, 'createdAt' | 'updatedAt' | 'messages'> & {
24
+ createdAt: string;
25
+ updatedAt: string;
26
+ messages?: Message[];
27
+ };
28
+
29
+ const PAGE_SIZE = 20;
30
+ const FIVE_MINUTES = 1000 * 60 * 5;
31
+
32
+ /** A stable signal for a URL whose server-side conversation no longer exists. */
33
+ export class ConversationNotFoundError extends Error {
34
+ readonly conversationId: string;
35
+
36
+ constructor(conversationId: string) {
37
+ super('Conversation not found');
38
+ this.conversationId = conversationId;
39
+ this.name = 'ConversationNotFoundError';
40
+ }
41
+ }
42
+
43
+ // Message content is either a plain string or a parts array; previews (titles,
44
+ // lastMessage) need the flattened text either way.
45
+ function messageText(message: Message | undefined): string {
46
+ const content = message?.content;
47
+ if (typeof content === 'string') return content;
48
+ if (!content) return '';
49
+ return content
50
+ .map((part) => (typeof part.text === 'string' ? part.text : ''))
51
+ .join(' ')
52
+ .trim();
53
+ }
54
+
55
+ /**
56
+ * The offline copy of the conversations: what a session whose token failed
57
+ * (a 401) reads and writes instead of the server. Without a store configured
58
+ * it holds nothing, and the 401 is the caller's to handle.
59
+ */
60
+ class OfflineConversations {
61
+ private readonly store: OfflineConversationStore | null;
62
+
63
+ constructor(store: OfflineConversationStore | null) {
64
+ this.store = store;
65
+ }
66
+
67
+ get available(): boolean {
68
+ return this.store !== null;
69
+ }
70
+
71
+ async read(): Promise<Conversation[]> {
72
+ const stored = await this.store?.getItem();
73
+ if (!stored) return [];
74
+ return (JSON.parse(stored) as Conversation[]).map((conv) => ({
75
+ ...conv,
76
+ createdAt: new Date(conv.createdAt),
77
+ updatedAt: new Date(conv.updatedAt),
78
+ }));
79
+ }
80
+
81
+ async write(conversations: Conversation[]): Promise<void> {
82
+ await this.store?.setItem(JSON.stringify(conversations));
83
+ }
84
+
85
+ async remove(id: string): Promise<void> {
86
+ if (!this.store) return;
87
+ const stored = await this.store.getItem();
88
+ if (!stored) return;
89
+ try {
90
+ const conversations: Conversation[] = JSON.parse(stored);
91
+ const remaining = conversations.filter((conversation) => conversation.id !== id);
92
+ if (remaining.length !== conversations.length) {
93
+ await this.store.setItem(JSON.stringify(remaining));
94
+ }
95
+ } catch {
96
+ // A malformed offline cache cannot make a valid server response invalid.
97
+ }
98
+ }
99
+ }
100
+
101
+ /** What the conversation functions need: the API and the offline copy. */
102
+ export interface ConversationsClient {
103
+ api: GemieApi;
104
+ offline: OfflineConversations;
105
+ /** Read at call time: the title of a chat created while signed out. */
106
+ newChatTitle: string;
107
+ /** The chat's app, which labels a conversation it creates (`GemieRuntimeConfig.app`). */
108
+ app: string | undefined;
109
+ }
110
+
111
+ /** The runtime's conversation client for the nearest provider. */
112
+ function useConversationsClient(): ConversationsClient {
113
+ const api = useGemieApi();
114
+ const { offline, app } = useGemieRuntime();
115
+ const { newChat } = useLabels();
116
+ return useMemo(
117
+ () => ({ api, offline: new OfflineConversations(offline), newChatTitle: newChat, app }),
118
+ [api, offline, newChat, app],
119
+ );
120
+ }
121
+
122
+ async function fetchConversationsPage(
123
+ client: ConversationsClient,
124
+ pageParam: string | undefined,
125
+ { agentId, app }: ConversationsFilter,
126
+ signal?: AbortSignal,
127
+ ): Promise<ConversationsPage> {
128
+ const { data } = await client.api.get<{
129
+ conversations: ApiConversation[];
130
+ nextCursor: string | null;
131
+ hasMore: boolean;
132
+ }>(API_ROUTES.conversations.list, {
133
+ signal,
134
+ params: {
135
+ limit: PAGE_SIZE,
136
+ ...(pageParam ? { cursor: pageParam } : {}),
137
+ ...(agentId === undefined ? {} : { agentId }),
138
+ ...(app === undefined ? {} : { app }),
139
+ },
140
+ });
141
+ return {
142
+ conversations: data.conversations.map((conv) => ({
143
+ ...conv,
144
+ createdAt: new Date(conv.createdAt),
145
+ updatedAt: new Date(conv.updatedAt),
146
+ messages: [], // Don't include messages in list view
147
+ })),
148
+ nextCursor: data.nextCursor,
149
+ hasMore: data.hasMore,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * The person's conversations, newest first, a page at a time. The sidebar and the sheet read this.
155
+ * Given `agentId`, only the conversations with that agent; given `app`, only the ones started in
156
+ * that app — an embedding app's own list (`GET /v1/conversations?agentId=&app=`). Neither is
157
+ * implied by the chat's `app`: the app that wants only its own says so here.
158
+ */
159
+ export function useConversations({ agentId, app }: ConversationsFilter = {}) {
160
+ const { user, isAuthenticated, canUsePrivateApi, isAccountCacheReady } = useOxy();
161
+ const client = useConversationsClient();
162
+ const accountId = user?.id;
163
+ const { offline: offlineStore } = useGemieRuntime();
164
+ const [offline, setOffline] = useState<{
165
+ accountId: string | undefined;
166
+ store: OfflineConversationStore | null | undefined;
167
+ data: ConversationsInfiniteData;
168
+ } | null>(null);
169
+ useEffect(() => {
170
+ if (!isAuthenticated || !isAccountCacheReady || agentId !== undefined || app !== undefined)
171
+ return;
172
+ let current = true;
173
+ void new OfflineConversations(offlineStore ?? null)
174
+ .read()
175
+ .then((rows) => {
176
+ if (current && rows.length)
177
+ setOffline({
178
+ accountId,
179
+ store: offlineStore,
180
+ data: {
181
+ pages: [
182
+ {
183
+ conversations: rows.map((row) => ({ ...row, messages: [] })),
184
+ nextCursor: null,
185
+ hasMore: false,
186
+ },
187
+ ],
188
+ pageParams: [undefined],
189
+ },
190
+ });
191
+ })
192
+ .catch(() => {
193
+ /* A damaged offline copy must not mask the server result. */
194
+ });
195
+ return () => {
196
+ current = false;
197
+ };
198
+ }, [accountId, offlineStore, isAuthenticated, isAccountCacheReady, agentId, app]);
199
+
200
+ const query = useInfiniteQuery({
201
+ queryKey:
202
+ agentId === undefined && app === undefined
203
+ ? gemieQueryKeys.conversations.all
204
+ : gemieQueryKeys.conversations.filtered({ agentId, app }),
205
+ queryFn: ({ pageParam, signal }) =>
206
+ fetchConversationsPage(client, pageParam, { agentId, app }, signal),
207
+ initialPageParam: undefined as string | undefined,
208
+ getNextPageParam: (lastPage) => (lastPage.hasMore ? lastPage.nextCursor : undefined),
209
+ select: reviveConversationDates,
210
+ staleTime: FIVE_MINUTES,
211
+ retry: (count, error) => errorStatus(error) !== 401 && count < 2,
212
+ enabled: canUsePrivateApi && isAccountCacheReady,
213
+ });
214
+ // Offline content is a display fallback, never a fresh successful server answer.
215
+ const fallback =
216
+ isAuthenticated &&
217
+ isAccountCacheReady &&
218
+ agentId === undefined &&
219
+ app === undefined &&
220
+ offline?.accountId === accountId &&
221
+ offline?.store === offlineStore
222
+ ? offline.data
223
+ : undefined;
224
+ return { ...query, data: query.data ?? fallback };
225
+ }
226
+
227
+ async function fetchConversation(client: ConversationsClient, id: string): Promise<Conversation> {
228
+ try {
229
+ const { data } = await client.api.get<ApiConversation>(API_ROUTES.conversations.get(id));
230
+ return {
231
+ ...data,
232
+ createdAt: new Date(data.createdAt),
233
+ updatedAt: new Date(data.updatedAt),
234
+ messages: normalizeConversationMessages(data.messages || []),
235
+ };
236
+ } catch (error: unknown) {
237
+ const status = errorStatus(error);
238
+ // A server-side 404 is authoritative for an authenticated request. Keeping
239
+ // an older offline copy here resurrects a deleted conversation and makes
240
+ // every later read and write hit the same missing id again.
241
+ if (status === 404) {
242
+ await client.offline.remove(id);
243
+ throw new ConversationNotFoundError(id);
244
+ }
245
+
246
+ // An unavailable authenticated session can still read its offline copy.
247
+ if (status === 401) {
248
+ const conversation = (await client.offline.read()).find((c) => c.id === id);
249
+ if (conversation) {
250
+ return {
251
+ ...conversation,
252
+ messages: normalizeConversationMessages(conversation.messages || []),
253
+ };
254
+ }
255
+ }
256
+ throw error;
257
+ }
258
+ }
259
+
260
+ /** One conversation with its messages. */
261
+ export function useConversation(id: string | undefined) {
262
+ const { isAuthenticated } = useOxy();
263
+ const client = useConversationsClient();
264
+
265
+ return useQuery({
266
+ queryKey: gemieQueryKeys.conversations.detail(id ?? ''),
267
+ queryFn: () => fetchConversation(client, id ?? ''),
268
+ enabled: isAuthenticated && !!id,
269
+ staleTime: FIVE_MINUTES,
270
+ // A missing conversation is deterministic. Retrying only repeats the same
271
+ // 404 and makes one stale local link look like an API outage in the console.
272
+ retry: false,
273
+ });
274
+ }
275
+
276
+ /** Prefetch a conversation's detail (call from the sidebar on press-in / hover). */
277
+ export function usePrefetchConversation(): (id: string) => void {
278
+ const queryClient = useQueryClient();
279
+ const client = useConversationsClient();
280
+ return useCallback((id) => prefetchConversation(queryClient, client, id), [queryClient, client]);
281
+ }
282
+
283
+ /**
284
+ * A prefetch is a favour to the press that may never come, so it never retries: a refusal (the
285
+ * rate limit's 429 above all) is answered by the press's own fetch, whereas retrying it spends the
286
+ * very budget that refused it, and a limiter that counts refused requests then never lets up.
287
+ */
288
+ export function prefetchConversation(
289
+ queryClient: QueryClient,
290
+ client: ConversationsClient,
291
+ id: string,
292
+ ): void {
293
+ void queryClient.prefetchQuery({
294
+ queryKey: gemieQueryKeys.conversations.detail(id),
295
+ queryFn: () => fetchConversation(client, id),
296
+ staleTime: FIVE_MINUTES,
297
+ retry: false,
298
+ });
299
+ }
300
+
301
+ /** Put a conversation's row at the top of the first page (or make the first page). */
302
+ function upsertOnTop(
303
+ old: ConversationsInfiniteData | undefined,
304
+ row: Conversation,
305
+ moveExisting: boolean,
306
+ ): ConversationsInfiniteData {
307
+ if (!old?.pages) {
308
+ return {
309
+ pages: [{ conversations: [row], nextCursor: null, hasMore: false }],
310
+ pageParams: [undefined],
311
+ };
312
+ }
313
+ const pages = [...old.pages];
314
+ if (moveExisting) {
315
+ // Remove the conversation from its current position (if it is in any page)
316
+ for (let i = 0; i < pages.length; i++) {
317
+ const page = pages[i] as ConversationsPage;
318
+ const existingIndex = page.conversations.findIndex((c) => c.id === row.id);
319
+ if (existingIndex >= 0) {
320
+ pages[i] = {
321
+ ...page,
322
+ conversations: [
323
+ ...page.conversations.slice(0, existingIndex),
324
+ ...page.conversations.slice(existingIndex + 1),
325
+ ],
326
+ };
327
+ break;
328
+ }
329
+ }
330
+ } else if (pages[0]?.conversations.some((c) => c.id === row.id)) {
331
+ return { ...old, pages };
332
+ }
333
+ // Always add to top of first page (most recently updated first)
334
+ if (pages[0]) {
335
+ pages[0] = { ...pages[0], conversations: [row, ...pages[0].conversations] };
336
+ }
337
+ return { ...old, pages };
338
+ }
339
+
340
+ /** Save a conversation's messages (and title). */
341
+ export function useSaveConversation() {
342
+ const queryClient = useQueryClient();
343
+ const client = useConversationsClient();
344
+ const labels = useLabels();
345
+
346
+ return useMutation({
347
+ retry: 1,
348
+ mutationFn: async ({
349
+ id,
350
+ messages,
351
+ title,
352
+ }: {
353
+ id: string;
354
+ messages: Message[];
355
+ title?: string;
356
+ }): Promise<Conversation> => {
357
+ const lastMessage = messageText(messages[messages.length - 1]).slice(0, 100) || undefined;
358
+
359
+ try {
360
+ const { data } = await client.api.post<ApiConversation>(API_ROUTES.conversations.save, {
361
+ conversationId: id,
362
+ messages,
363
+ ...(title && { title }),
364
+ ...(client.app === undefined ? {} : { app: client.app }),
365
+ });
366
+ return {
367
+ id: data.id,
368
+ title: data.title,
369
+ lastMessage: data.lastMessage,
370
+ source: data.source,
371
+ app: data.app,
372
+ createdAt: new Date(data.createdAt),
373
+ updatedAt: new Date(data.updatedAt),
374
+ messages,
375
+ };
376
+ } catch (error: unknown) {
377
+ // If unauthorized, save to the offline copy
378
+ if (errorStatus(error) === 401) {
379
+ const conversations = await client.offline.read();
380
+ const existingIndex = conversations.findIndex((c) => c.id === id);
381
+
382
+ const offlineTitle =
383
+ title ||
384
+ messageText(messages.find((m) => m.role === 'user')).slice(0, 50) ||
385
+ client.newChatTitle;
386
+ const conversation: Conversation = {
387
+ id,
388
+ title: offlineTitle,
389
+ lastMessage,
390
+ createdAt:
391
+ existingIndex >= 0
392
+ ? (conversations[existingIndex] as Conversation).createdAt
393
+ : new Date(),
394
+ updatedAt: new Date(),
395
+ messages,
396
+ };
397
+
398
+ const next = [...conversations];
399
+ if (existingIndex >= 0) next[existingIndex] = conversation;
400
+ else next.unshift(conversation);
401
+
402
+ await client.offline.write(next);
403
+ return conversation;
404
+ }
405
+ throw error;
406
+ }
407
+ },
408
+ onSuccess: (data) => {
409
+ queryClient.setQueryData(
410
+ gemieQueryKeys.conversations.all,
411
+ (old: ConversationsInfiniteData | undefined) =>
412
+ upsertOnTop(old, { ...data, messages: [] }, true),
413
+ );
414
+ // Update individual conversation cache with full data including messages
415
+ queryClient.setQueryData(gemieQueryKeys.conversations.detail(data.id), data);
416
+ },
417
+ onError: (error: unknown) => {
418
+ toast.error(getErrorMessage(error) || labels.conversationSaveFailed);
419
+ },
420
+ });
421
+ }
422
+
423
+ /**
424
+ * Rename a conversation.
425
+ *
426
+ * The API has no title-only route: `POST /conversations` writes the title AND
427
+ * replaces the messages. So the full thread is read fresh first (`staleTime:
428
+ * 0` — the sidebar seeds the detail cache from the list with no messages, and
429
+ * saving that seed would empty the thread) and saved back with the new title.
430
+ */
431
+ export function useRenameConversation() {
432
+ const queryClient = useQueryClient();
433
+ const client = useConversationsClient();
434
+ const save = useSaveConversation();
435
+
436
+ return useMutation({
437
+ mutationFn: async ({ id, title }: { id: string; title: string }) => {
438
+ const conversation = await queryClient.fetchQuery({
439
+ queryKey: gemieQueryKeys.conversations.detail(id),
440
+ queryFn: () => fetchConversation(client, id),
441
+ staleTime: 0,
442
+ });
443
+ return save.mutateAsync({ id, messages: conversation.messages, title });
444
+ },
445
+ });
446
+ }
447
+
448
+ /** Delete a conversation. */
449
+ export function useDeleteConversation() {
450
+ const queryClient = useQueryClient();
451
+ const client = useConversationsClient();
452
+ const labels = useLabels();
453
+
454
+ return useMutation({
455
+ retry: 1,
456
+ mutationFn: async (id: string) => {
457
+ try {
458
+ await client.api.delete(API_ROUTES.conversations.remove(id));
459
+ } catch (error: unknown) {
460
+ // If unauthorized, delete from the offline copy
461
+ if (errorStatus(error) === 401) {
462
+ const conversations = await client.offline.read();
463
+ await client.offline.write(conversations.filter((c) => c.id !== id));
464
+ } else {
465
+ throw error;
466
+ }
467
+ }
468
+ return id;
469
+ },
470
+ onSuccess: (id) => {
471
+ queryClient.setQueryData(
472
+ gemieQueryKeys.conversations.all,
473
+ (old: ConversationsInfiniteData | undefined) => {
474
+ if (!old?.pages) return old;
475
+ return {
476
+ ...old,
477
+ pages: old.pages.map((page) => ({
478
+ ...page,
479
+ conversations: page.conversations.filter((c) => c.id !== id),
480
+ })),
481
+ };
482
+ },
483
+ );
484
+ queryClient.removeQueries({ queryKey: gemieQueryKeys.conversations.detail(id) });
485
+ },
486
+ onError: (error: unknown) => {
487
+ toast.error(getErrorMessage(error) || labels.conversationDeleteFailed);
488
+ },
489
+ });
490
+ }
491
+
492
+ /**
493
+ * Empty a conversation on the server, keeping the conversation.
494
+ *
495
+ * The persistent half of "Clear conversation" (#553). The local half —
496
+ * `setMessages([])` in `useGemieConversation` — is NOT enough on its own: the
497
+ * detail query still holds the history, and the sync effect there treats
498
+ * "cache has messages, screen has none" as a data upgrade and hydrates them
499
+ * straight back, which is the bug. So the cache is emptied HERE, on success
500
+ * only, and the caller resets its screen after `mutateAsync` resolves — by
501
+ * which point React Query has run this `onSuccess`, so there is no longer a
502
+ * history for the effect to restore. Nothing is touched optimistically: a
503
+ * clear the server refused must leave the thread exactly as it was, because
504
+ * the dialog that asked for it promised the opposite of "it will be back".
505
+ *
506
+ * The list entry keeps its place and loses its preview — the server dropped
507
+ * `lastMessage` in the same transaction — and both queries are then
508
+ * invalidated so whatever the server has (the moved `updatedAt`, a title it
509
+ * may have kept) replaces the local guess.
510
+ */
511
+ export function useClearConversation() {
512
+ const queryClient = useQueryClient();
513
+ const client = useConversationsClient();
514
+
515
+ return useMutation({
516
+ retry: 1,
517
+ mutationFn: async (id: string) => {
518
+ try {
519
+ await client.api.delete(API_ROUTES.conversations.clearMessages(id));
520
+ } catch (error: unknown) {
521
+ // If unauthorized, clear the offline copy — the same branch a delete takes.
522
+ if (errorStatus(error) === 401) {
523
+ const conversations = await client.offline.read();
524
+ await client.offline.write(
525
+ conversations.map((c) =>
526
+ c.id === id
527
+ ? { ...c, messages: [], lastMessage: undefined, updatedAt: new Date() }
528
+ : c,
529
+ ),
530
+ );
531
+ } else {
532
+ throw error;
533
+ }
534
+ }
535
+ return id;
536
+ },
537
+ onSuccess: (id) => {
538
+ queryClient.setQueryData(
539
+ gemieQueryKeys.conversations.detail(id),
540
+ (old: Conversation | undefined) =>
541
+ old ? { ...old, messages: [], lastMessage: undefined } : old,
542
+ );
543
+ queryClient.setQueryData(
544
+ gemieQueryKeys.conversations.all,
545
+ (old: ConversationsInfiniteData | undefined) => {
546
+ if (!old?.pages) return old;
547
+ return {
548
+ ...old,
549
+ pages: old.pages.map((page) => ({
550
+ ...page,
551
+ conversations: page.conversations.map((c) =>
552
+ c.id === id ? { ...c, lastMessage: undefined } : c,
553
+ ),
554
+ })),
555
+ };
556
+ },
557
+ );
558
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.detail(id) });
559
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
560
+ },
561
+ });
562
+ }
563
+
564
+ /**
565
+ * Create a conversation (optionally the next stretch of an agent's thread).
566
+ *
567
+ * The next stretch of a thread whose open answered a `threadId` (Alia's: `useGemieThread`) is
568
+ * `{ threadId }`; `{ agentId }` alone would start one more loose chat with her. Of any other
569
+ * gemie's thread it is `{ agentId }`.
570
+ */
571
+ export function useCreateConversation() {
572
+ const queryClient = useQueryClient();
573
+ const client = useConversationsClient();
574
+ const labels = useLabels();
575
+
576
+ return useMutation({
577
+ mutationFn: async (params?: {
578
+ agentId?: string;
579
+ /** Two to six agents: a group conversation, answered by each in turn. */
580
+ agentIds?: readonly string[];
581
+ /** The thread row whose next stretch this is (`GemieThreadInfo.threadId`). */
582
+ threadId?: string;
583
+ }): Promise<Conversation> => {
584
+ try {
585
+ const { data } = await client.api.post<ApiConversation>(API_ROUTES.conversations.create, {
586
+ ...(params?.agentId && { agentId: params.agentId }),
587
+ ...(params?.agentIds && { agentIds: params.agentIds }),
588
+ ...(params?.threadId && { threadId: params.threadId }),
589
+ ...(client.app === undefined ? {} : { app: client.app }),
590
+ });
591
+ return {
592
+ id: data.id,
593
+ title: data.title,
594
+ lastMessage: undefined,
595
+ source: data.source,
596
+ agentId: data.agentId,
597
+ memberAgentIds: data.memberAgentIds,
598
+ spaceId: data.spaceId,
599
+ threadId: data.threadId,
600
+ app: data.app,
601
+ createdAt: new Date(data.createdAt),
602
+ updatedAt: new Date(data.updatedAt),
603
+ messages: [],
604
+ };
605
+ } catch (error: unknown) {
606
+ // If unauthorized, create it in the offline copy
607
+ if (errorStatus(error) === 401 && client.offline.available) {
608
+ const conversation: Conversation = {
609
+ id: createRandomUuid(),
610
+ title: client.newChatTitle,
611
+ lastMessage: undefined,
612
+ createdAt: new Date(),
613
+ updatedAt: new Date(),
614
+ messages: [],
615
+ };
616
+ await client.offline.write([conversation, ...(await client.offline.read())]);
617
+ return conversation;
618
+ }
619
+ throw error;
620
+ }
621
+ },
622
+ onSuccess: (data) => {
623
+ queryClient.setQueryData(
624
+ gemieQueryKeys.conversations.all,
625
+ (old: ConversationsInfiniteData | undefined) => upsertOnTop(old, data, false),
626
+ );
627
+ queryClient.setQueryData(gemieQueryKeys.conversations.detail(data.id), data);
628
+ },
629
+ onError: (error: unknown) => {
630
+ toast.error(getErrorMessage(error) || labels.conversationCreateFailed);
631
+ },
632
+ });
633
+ }