@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,900 @@
1
+ /**
2
+ * The conversation: header, thread and composer, with its voice call. The one screen of the
3
+ * bottom sheet, `GemieChatScreen` and the Alia app — they are frames around this.
4
+ *
5
+ * It is the top of three layers, each depending only on the one before it: the runtime
6
+ * (`useConversationThread`, the stream, the cache), the hooks that turn it into what a person does
7
+ * (`useChatComposer`, `useChatVoice`, `useThreadView`), and this, which draws it — the thread
8
+ * (`GemieThread`) and the agent's history behind it, the composer with its levels, suggestions and
9
+ * questions, and the voice call: the button that opens it, the bar that replaces the composer, the
10
+ * notices and the transcript in the thread. The call itself is not imported here: the entry that
11
+ * bundles it hands it down (`VoiceCallContext`, `withVoiceCall`), so the text-only entries
12
+ * (`@gemies/sdk/text`, `@gemies/sdk/ask/text`) never reach its modules.
13
+ *
14
+ * What a host brings is data and places: the conversation to show, the chrome around it
15
+ * (`chrome`), its rows in the add menu, its words (`labels`), where the thought panel and a
16
+ * scheduled task open (`runtime`), and a few gates (`voice`, `onSignInRequired`,
17
+ * `renderUsageLimit`).
18
+ */
19
+
20
+ import { getAccountDisplayName } from '@oxy.so/core';
21
+ import { useOxy } from '@oxy.so/services/ui/client';
22
+ import { AiChatContainer, type AiChatThreadHandle } from '@oxy.so/bloom/ai-chat';
23
+ import {
24
+ AvatarFlightLayer,
25
+ type AvatarFlights,
26
+ useAvatarFlights,
27
+ } from '@oxy.so/bloom/avatar-flight';
28
+ import { Button } from '@oxy.so/bloom/button';
29
+ import { ScrollToBottomButton } from '@oxy.so/bloom/chat-screen';
30
+ import { RiEditLine } from '@oxy.so/bloom/icons/RiEditLine';
31
+ import { toast } from '@oxy.so/bloom/toast';
32
+ import { Text } from '@oxy.so/bloom/typography';
33
+ import { useQueryClient } from '@tanstack/react-query';
34
+ import {
35
+ type ReactNode,
36
+ useCallback,
37
+ useContext,
38
+ useEffect,
39
+ useMemo,
40
+ useRef,
41
+ useState,
42
+ } from 'react';
43
+ import { View } from 'react-native';
44
+ import type { SharedValue } from 'react-native-reanimated';
45
+ import { useAmbientWave } from '../hooks/useAmbientWave';
46
+ import { useAtBottom } from '../hooks/useAtBottom';
47
+ import { type GemieTurn, useChatComposer } from '../hooks/useChatComposer';
48
+ import { type GemieVoiceOptions, useChatVoice } from '../hooks/useChatVoice';
49
+ import { useAttachMenu } from '../hooks/useAttachMenu';
50
+ import { usePendingQuestions } from '../hooks/usePendingQuestions';
51
+ import { useThreadView } from '../hooks/useThreadView';
52
+ import { useTTS } from '../hooks/useTTS';
53
+ import { BubblesProvider } from '../lib/bubbles';
54
+ import type { GemieAddMenu } from '../lib/add-menu';
55
+ import { GemieFlightsProvider } from '../lib/flights';
56
+ import {
57
+ type GemieChatParticipants,
58
+ type GemieParticipant,
59
+ groupParticipants,
60
+ leadOf,
61
+ } from '../lib/participants';
62
+ import { type GemieToolRenderers, GemieToolRenderersProvider } from '../lib/tool-renderers';
63
+ import { KeyboardSafeAreaFloor } from '../lib/keyboard';
64
+ import { type GemieChatLabels, GemieChatLabelsProvider, useLabels } from '../lib/labels';
65
+ import { type DeviceModel, buildPowerLevelOptions } from '../lib/power-level-options';
66
+ import { GEMIE_FEATURES, featureOffer, useAgentFeatures, useAgentProfile } from '../runtime/agents';
67
+ import { type GemieRuntimeHost, GemieRuntimeProvider, useGemieRuntime } from '../runtime/config';
68
+ import { type GemieHostTools, APP_SLUG } from '../runtime/host-tools';
69
+ import { useCreateConversation } from '../runtime/conversations';
70
+ import { gemieQueryKeys } from '../runtime/query-keys';
71
+ import { type GemieThreadAddress, threadKey } from '../runtime/routes';
72
+ import type { AgentExchange } from '../runtime/thread/agent-exchange';
73
+ import type { Message } from '../runtime/types';
74
+ import { useAgentActivity } from '../runtime/use-agent-activity';
75
+ import { useConversationThread } from '../runtime/use-conversation-thread';
76
+ import { UsageLimitError } from '../runtime/usage-limit-error';
77
+ import type { GemieSuggestion } from '../types';
78
+ import type { GemieAvatarState } from './GemieAvatar';
79
+ import { GemieComposer } from './GemieComposer';
80
+ import { useParticipants } from './GemieParticipants';
81
+ import { GemieGroupWelcome } from './GemieGroupWelcome';
82
+ import { GemieWelcomeMessage } from './GemieWelcomeMessage';
83
+ import { AmbientField } from './AmbientField';
84
+ import { InertWhen } from './InertWhen';
85
+ import { AgentExchangeView } from './thread/AgentExchangeView';
86
+ import { GemieThread } from './thread/GemieThread';
87
+ import { ThreadSearch } from './thread/ThreadSearch';
88
+ import { VoiceModeIcon } from './VoiceModeIcon';
89
+ import { VoiceCallContext } from './voice/VoiceCallContext';
90
+
91
+ /** The agent a chat is opened on: its lead instead of Alia. */
92
+ export interface GemieChatAgentRef {
93
+ id: string;
94
+ }
95
+
96
+ /** What the chat tells its chrome: whether there is a conversation to act on, who takes part, what the lead is doing. */
97
+ export interface GemieChatState {
98
+ /** The conversation open, or `undefined` before the first turn creates one. */
99
+ conversationId: string | undefined;
100
+ hasMessages: boolean;
101
+ /** Begin a new conversation. Nothing is deleted: the old one stays in the list. */
102
+ startOver: () => void;
103
+ /** Empty the open conversation, on the server and on screen. */
104
+ clearMessages: () => Promise<unknown>;
105
+ /** What the lead is doing; the header's avatar shows it. */
106
+ markState: GemieAvatarState;
107
+ /**
108
+ * Who is in the conversation — the lead, and the agents it consulted once they have joined.
109
+ * Draw it with `GemieParticipants` wherever the chrome puts the conversation's title.
110
+ */
111
+ participants: GemieChatParticipants;
112
+ /** Search what was said in the agent's thread. Present only on a thread (`threadHandle`, `gemieThread`). */
113
+ openSearch: (() => void) | undefined;
114
+ /** The conversation as it stands now, for an export. Read when called, not when rendered. */
115
+ getMessages: () => readonly Message[];
116
+ }
117
+
118
+ /** What the container draws around the thread. */
119
+ export interface GemieChatChrome {
120
+ /** The top bar. */
121
+ header?: ReactNode;
122
+ /** The crumb of the container's breadcrumb row. */
123
+ title?: string;
124
+ /** The project the chat is filed under, in the breadcrumb. */
125
+ project?: string;
126
+ /** The chat's own actions, at the end of the breadcrumb row. */
127
+ actions?: ReactNode;
128
+ }
129
+
130
+ export interface GemieChatContentProps {
131
+ // ── Which conversation ──
132
+ /**
133
+ * The conversation to show. Given, the host owns which one is open (a route) and learns of a new
134
+ * one through `onConversationChange`; omitted, the chat keeps its own — unless the host
135
+ * navigates (`runtime.openConversation`), which then decides: the chat starts empty and
136
+ * creates its conversation with the first turn, or the first call.
137
+ */
138
+ conversationId?: string;
139
+ /**
140
+ * The agent this chat is with, any agent the person can reach: it leads the conversation — its
141
+ * greeting, name, character and starters, and the header's first avatar. Omitted, Alia.
142
+ */
143
+ agent?: GemieChatAgentRef;
144
+ /**
145
+ * The handle of the agent's permanent thread, when this conversation is the active stretch of
146
+ * one: the conversations behind it are paged in above, and the thread can be searched. Omitted,
147
+ * the chat is one conversation with nothing behind it.
148
+ */
149
+ threadHandle?: string;
150
+ /**
151
+ * The same, for a thread addressed by its gemie's id — Alia's, whose account has no handle yet
152
+ * (ADR 0034): what `useGemieThread` answers. `threadId` is her thread row, so the next stretch the
153
+ * chat offers stays in the thread instead of becoming a loose chat. Give one of `threadHandle` and
154
+ * `gemieThread`; the handle wins if both are given.
155
+ */
156
+ gemieThread?: { readonly gemieId: string; readonly threadId: string | null };
157
+ /** The chat opened a conversation (a new one, from a first turn or a call) or left it (`undefined`). */
158
+ onConversationChange?: (conversationId: string | undefined) => void;
159
+ /** The host's side of the conversation runtime: navigation, artifacts, credits… */
160
+ runtime?: GemieRuntimeHost;
161
+ /**
162
+ * Nothing is stored: the first turn is sent without creating a conversation, so the whole chat
163
+ * lives on this screen (ghost mode).
164
+ */
165
+ ephemeral?: boolean;
166
+ apiUrl?: string;
167
+ /**
168
+ * The Oxy app this chat is embedded in, by its slug (`homiio`, `mercaria`). A conversation the
169
+ * chat starts is labelled with it, so the app can list only its own
170
+ * (`useConversations({ app })`), and its `hostTools` are this app's. Omitted, the chat is
171
+ * Alia's own (`docs/agent-embedding.md` §6).
172
+ */
173
+ app?: string;
174
+ /** App context injected into the system prompt. */
175
+ clientContext?: string;
176
+ /**
177
+ * The UI effects this app's client performs for the lead (`docs/agent-embedding.md` §2). Declared
178
+ * with every turn under the chat's `app`, which a chat with host tools must name; an action the
179
+ * stream asks for is performed once, by `execute`, and its outcome reaches the model with the
180
+ * next turn.
181
+ */
182
+ hostTools?: GemieHostTools;
183
+ /** The app's own drawing of a catalogue tool's result, keyed `<app>:<tool>`, before the generic card. */
184
+ toolRenderers?: GemieToolRenderers;
185
+ /**
186
+ * The lead's feature gate refused something (`attachments.documents`…): the host shows its own
187
+ * upsell. Also called for a locked row of the attach menu.
188
+ */
189
+ onFeatureLocked?: (key: string) => void;
190
+ // ── The power level ──
191
+ /**
192
+ * The power level (`auto`, `instant`, `medium`, `high`, `xhigh`, `pro`, `ultra`) or exact
193
+ * `publisher/model` every turn is sent with; omitted, the server's default.
194
+ */
195
+ model?: string;
196
+ /** Makes the level selectable in the composer: the person picked `model`. Omitted, no selector. */
197
+ onModelChange?: (model: string) => void;
198
+ /** Models on the person's own devices, offered after the levels in the selector. */
199
+ deviceModels?: readonly DeviceModel[];
200
+ // ── Words ──
201
+ /** Overrides for the chat's own copy; anything omitted is English. */
202
+ labels?: Partial<GemieChatLabels>;
203
+ /** The empty chat's greeting; omitted, the agent's own, or Alia greets the signed-in person by name (`labels`). */
204
+ welcomeGreeting?: string;
205
+ welcomeSubtitle?: string;
206
+ /** The lines offered over the composer on an empty chat; omitted, the agent's starters. */
207
+ welcomeSuggestions?: GemieSuggestion[];
208
+ /** Drawn under the empty chat's greeting — the sheet's recent conversations with its lead. */
209
+ welcomeAccessory?: ReactNode;
210
+ /** What the host found for the typed text (see `onSuggestionQuery`). */
211
+ suggestionMatches?: GemieSuggestion[];
212
+ /** The typed text, once typing has settled, for the host to search suggestions with. */
213
+ onSuggestionQuery?: (query: string) => void;
214
+ /** A suggestion was picked (before it is sent, or put in the composer if it is a template). */
215
+ onSuggestionPicked?: (suggestion: GemieSuggestion) => void;
216
+ // ── The frame ──
217
+ /**
218
+ * What the container draws around the thread, from what the chat knows (who took part, whether
219
+ * there is anything to clear, whether it is a searchable thread).
220
+ */
221
+ chrome?: (state: GemieChatState) => GemieChatChrome;
222
+ /**
223
+ * Draw the turns as chat bubbles, as an agent's thread does: the person's in the theme's primary (the agent's colour),
224
+ * the replies in a neutral one. Off, a thread keeps its ordinary look (Alia's own chat).
225
+ */
226
+ bubbles?: boolean;
227
+ /**
228
+ * The conversation is a GROUP: its members, in the order they answer (two or more). Nobody leads
229
+ * it, so the header lists them all, the empty chat shows them together, and every reply is a
230
+ * bubble under its author's name. The host reads them from the conversation's `memberAgentIds`.
231
+ */
232
+ group?: readonly GemieParticipant[];
233
+ /**
234
+ * The host is still resolving WHICH conversation this is (an agent's thread is looked up by its
235
+ * handle before its conversation is known). The chat is drawn at once, with the thread's
236
+ * skeleton where the turns will be, and cannot send until the host says what it is talking to.
237
+ */
238
+ loading?: boolean;
239
+ /** Dark-mode flag — forwarded to the ambient wave overlay. */
240
+ isDarkMode?: boolean;
241
+ /** The ambient field's shape: the whole `screen` (default) or a `sheet`'s smaller one. */
242
+ layout?: 'screen' | 'sheet';
243
+ /**
244
+ * Whether the screen holding the chat is the one on show. A screen kept mounted under another
245
+ * pauses its ambient field, and a live call ends when it is not. Default `true`.
246
+ */
247
+ isFocused?: boolean;
248
+ /**
249
+ * Space the composer keeps clear at the bottom edge, in px — the home indicator, when the chat
250
+ * is flush with the screen. It gives way to the keyboard. The ambient background still runs
251
+ * behind it.
252
+ */
253
+ bottomInset?: number;
254
+ // ── The composer ──
255
+ /** The host's rows in the add menu. Omitted, the menu offers photos and files, as the lead takes them. */
256
+ addMenu?: GemieAddMenu;
257
+ /** The tab on the composer's top edge (the project the chat is filed under). Replaced by the edit strip while a question is rewritten. */
258
+ composerStatus?: ReactNode;
259
+ /** Error handler (e.g. toast) */
260
+ onError?: (message: string) => void;
261
+ /**
262
+ * The person is signed out and sent a turn: the host asks them to sign in. The draft stays in
263
+ * the composer. Omitted, the turn is sent and the server's refusal is told.
264
+ */
265
+ onSignInRequired?: () => void;
266
+ /**
267
+ * The turn was refused for the person's usage limit: the composer is closed until `dismiss`,
268
+ * and this draws what the host says about it (a dialog).
269
+ */
270
+ renderUsageLimit?: (limit: { error: UsageLimitError; dismiss: () => void }) => ReactNode;
271
+ /**
272
+ * The chat's voice call. On by default where the call is bundled (the root entry and
273
+ * `@gemies/sdk/ask`); the text-only entries have none. `false` makes the chat text-only. An object brings
274
+ * what only the host knows: the gate before a call (`canStartVoice`, `onVoiceBlocked`), what
275
+ * to refresh when one ends (`onCallEnded`), where its notices go (`onNotice`), the sounds it
276
+ * plays. The call always lives in the chat's conversation, made when it starts if the chat has
277
+ * none.
278
+ */
279
+ voice?: false | GemieVoiceOptions;
280
+ // ── The sheet's ──
281
+ /**
282
+ * Hands the first turn of an empty chat to the host instead of sending it here — a sheet opens
283
+ * the conversation in a new sheet over this one. Omitted, the chat sends it itself.
284
+ */
285
+ onStart?: (turn: GemieTurn) => void;
286
+ /**
287
+ * The avatar flights this chat takes part in, when a sheet shares them across its chats (the
288
+ * greeting's avatar flies into a header in another sheet). Omitted, the chat has its own.
289
+ */
290
+ flights?: AvatarFlights;
291
+ /** A turn sent once as this chat mounts: the conversation a sheet was opened for. */
292
+ initialTurn?: GemieTurn;
293
+ /**
294
+ * The `animatedProgress` of the Bloom sheet this chat is in. The composer takes focus (and on
295
+ * native opens the keyboard) once it reads `1`, so the person can type as soon as the sheet is
296
+ * up. Omitted, the chat is not in a sheet and focus is left alone.
297
+ */
298
+ presentedProgress?: SharedValue<number>;
299
+ /** Internal sheet lifecycle bridge: receives the live request canceller. */
300
+ onStopReady?: (stop: (() => void) | null) => void;
301
+ /** Detach a closed view while its durable answer continues. Never invokes explicit Stop. */
302
+ onDetachReady?: (detach: (() => void) | null) => void;
303
+ }
304
+
305
+ /** No live conversation while the thread looks at a moment of its past, as ONE array. */
306
+ const NO_MESSAGES: Message[] = [];
307
+
308
+ /** A host without renderers, as ONE object, so the thread's rows do not re-render for a new `{}`. */
309
+ const NO_RENDERERS: GemieToolRenderers = {};
310
+
311
+ /** The conversation view: everything of `GemieChatContentProps` that is not about which conversation is open. */
312
+ type ConversationViewProps = Omit<
313
+ GemieChatContentProps,
314
+ | 'labels'
315
+ | 'onConversationChange'
316
+ | 'runtime'
317
+ | 'conversationId'
318
+ | 'apiUrl'
319
+ | 'toolRenderers'
320
+ | 'onFeatureLocked'
321
+ > & { conversationId: string | undefined };
322
+
323
+ function GemieConversationView({
324
+ clientContext,
325
+ model,
326
+ onModelChange,
327
+ deviceModels,
328
+ conversationId,
329
+ agent,
330
+ hostTools,
331
+ threadHandle,
332
+ gemieThread,
333
+ ephemeral = false,
334
+ onError,
335
+ welcomeGreeting,
336
+ welcomeSubtitle,
337
+ welcomeSuggestions,
338
+ welcomeAccessory,
339
+ suggestionMatches,
340
+ onSuggestionQuery,
341
+ onSuggestionPicked,
342
+ chrome,
343
+ bubbles = false,
344
+ group,
345
+ loading = false,
346
+ isDarkMode,
347
+ layout = 'screen',
348
+ isFocused = true,
349
+ bottomInset = 0,
350
+ addMenu,
351
+ composerStatus,
352
+ onSignInRequired,
353
+ renderUsageLimit,
354
+ voice: voiceOptions,
355
+ onStart,
356
+ flights: sharedFlights,
357
+ initialTurn,
358
+ presentedProgress,
359
+ onStopReady,
360
+ onDetachReady,
361
+ }: ConversationViewProps) {
362
+ const ownFlights = useAvatarFlights();
363
+ const flights = sharedFlights ?? ownFlights;
364
+ const labels = useLabels();
365
+ const { t } = labels;
366
+ const runtime = useGemieRuntime();
367
+ const queryClient = useQueryClient();
368
+ const { user, isAuthenticated } = useOxy();
369
+ const agentId = agent?.id;
370
+
371
+ // ── Who leads: the agent the chat was opened on, or Alia ──
372
+ const { data: profile, isLoading: profileLoading } = useAgentProfile(agentId);
373
+ const lead = useMemo(
374
+ () => (group === undefined ? leadOf(profile) : groupParticipants(group).lead),
375
+ [group, profile],
376
+ );
377
+ const { data: features } = useAgentFeatures(agentId);
378
+
379
+ // A failure reaches the host's handler when it has one, and Bloom's toast otherwise.
380
+ const reportError = useCallback(
381
+ (message: string, title?: string) => {
382
+ if (onError) onError(title ? `${title}: ${message}` : message);
383
+ else toast.error(title ?? message, title ? { description: message } : undefined);
384
+ },
385
+ [onError],
386
+ );
387
+
388
+ // ── The conversation ──
389
+ const thread = useConversationThread({
390
+ conversationId,
391
+ agentId,
392
+ model,
393
+ clientContext,
394
+ hostTools,
395
+ });
396
+ const {
397
+ messages,
398
+ setMessages,
399
+ isLoading,
400
+ composerPhase,
401
+ conversationLoading,
402
+ error,
403
+ clearError,
404
+ stopGeneration: stop,
405
+ detachGeneration: detach,
406
+ startOver,
407
+ clearConversation,
408
+ suggestedNewConversation,
409
+ dismissSuggestedNewConversation,
410
+ agentRun,
411
+ failedTurn,
412
+ retryFailedTurn,
413
+ } = thread;
414
+ const consulted = useParticipants({ lead, messages, flights });
415
+ // The direct agent is a member too. Use the requested id before its profile loads: an
416
+ // attributed follow-up is still its own reply, never a consultation with itself.
417
+ const memberIds = useMemo(
418
+ () =>
419
+ new Set(group === undefined ? (agentId ? [agentId] : []) : group.map((member) => member.id)),
420
+ [agentId, group],
421
+ );
422
+ const participants = useMemo(
423
+ () => (group === undefined ? consulted : groupParticipants(group)),
424
+ [group, consulted],
425
+ );
426
+ const asked = usePendingQuestions(messages, isLoading);
427
+ const gemieId = gemieThread?.gemieId;
428
+ const threadAddress = useMemo<GemieThreadAddress | undefined>(
429
+ () =>
430
+ threadHandle !== undefined
431
+ ? { handle: threadHandle }
432
+ : gemieId !== undefined
433
+ ? { gemieId }
434
+ : undefined,
435
+ [threadHandle, gemieId],
436
+ );
437
+ const view = useThreadView(threadAddress, conversationId);
438
+ // The internal conversation of a consulted agent, read-only, drawn over the chat (which stays
439
+ // mounted under it, so its scroll and the draft are exactly as they were on the way back).
440
+ const [exchange, setExchange] = useState<AgentExchange | null>(null);
441
+ const closeExchange = useCallback(() => setExchange(null), []);
442
+ const agentActivity = useAgentActivity(agentRun?.turnId ?? null, agentRun?.agentId);
443
+
444
+ // The turn was refused for the usage limit: the composer is closed until the host's dialog is
445
+ // dismissed. Name as well as class — Hermes can break `instanceof` for Error subclasses.
446
+ const usageLimit =
447
+ error instanceof UsageLimitError || error?.name === 'UsageLimitError'
448
+ ? (error as UsageLimitError)
449
+ : null;
450
+ const closed = usageLimit !== null;
451
+
452
+ useEffect(() => {
453
+ onStopReady?.(stop);
454
+ return () => onStopReady?.(null);
455
+ }, [onStopReady, stop]);
456
+ useEffect(() => {
457
+ onDetachReady?.(detach);
458
+ return () => onDetachReady?.(null);
459
+ }, [onDetachReady, detach]);
460
+
461
+ // ── What the person does: write, send, rewrite, call ──
462
+ // An agent's starters are its welcome suggestions, unless the host brought its own.
463
+ const starters = useMemo<GemieSuggestion[] | undefined>(
464
+ () =>
465
+ lead.starters.length === 0
466
+ ? undefined
467
+ : lead.starters.map((starter, index) => ({
468
+ id: `starter-${index}`,
469
+ text: starter.prompt,
470
+ })),
471
+ [lead.starters],
472
+ );
473
+ const composer = useChatComposer({
474
+ conversationId,
475
+ thread,
476
+ ephemeral,
477
+ closed,
478
+ onWrite: view.backToLatest,
479
+ onStart,
480
+ flights,
481
+ group,
482
+ lead,
483
+ initialTurn,
484
+ onSignInRequired,
485
+ reportError,
486
+ welcomeSuggestions: welcomeSuggestions ?? starters,
487
+ suggestionMatches,
488
+ onSuggestionQuery,
489
+ onSuggestionPicked,
490
+ presentedProgress,
491
+ });
492
+
493
+ /**
494
+ * A bubble's reply button: the turn's words, quoted, ahead of what is already typed. Each line is
495
+ * prefixed `> `, so a model reads it as a quotation and a person as a reply.
496
+ */
497
+ const quoteIntoComposer = useCallback(
498
+ (words: string) => {
499
+ const quoted = words
500
+ .split('\n')
501
+ .map((line) => `> ${line}`)
502
+ .join('\n');
503
+ composer.setText(`${quoted}\n\n${composer.text}`);
504
+ },
505
+ [composer],
506
+ );
507
+ // Without a call handed down (a text-only entry), the chat is text-only whatever `voice` says.
508
+ const VoiceCall = useContext(VoiceCallContext);
509
+ const voice = useChatVoice({
510
+ options: VoiceCall === null ? false : voiceOptions,
511
+ conversationId,
512
+ agentId,
513
+ isFocused,
514
+ ensureConversation: thread.ensureConversation,
515
+ messages,
516
+ setMessages,
517
+ storedMessages: thread.conversation?.messages,
518
+ isLoading,
519
+ });
520
+ // The default menu offers what the lead takes: Alia every attachment; an agent what its feature
521
+ // answer lists, nothing until it has answered.
522
+ const offers = useMemo(() => {
523
+ const states = agentId === undefined ? undefined : (features ?? []);
524
+ return {
525
+ images: featureOffer(states, GEMIE_FEATURES.images),
526
+ documents: featureOffer(states, GEMIE_FEATURES.documents),
527
+ };
528
+ }, [agentId, features]);
529
+ const attachMenu = useAttachMenu(composer.address, offers, runtime.host.onFeatureLocked);
530
+ const menu = addMenu ?? attachMenu;
531
+ const modes = useMemo(
532
+ () => (onModelChange ? buildPowerLevelOptions(t, deviceModels ?? []) : undefined),
533
+ [onModelChange, t, deviceModels],
534
+ );
535
+
536
+ // ── The way back to the newest turn ──
537
+ const threadRef = useRef<AiChatThreadHandle | null>(null);
538
+ const { isAtBottom, onScroll } = useAtBottom();
539
+ const jumpToEnd = useCallback(() => threadRef.current?.scrollToEnd({ animated: false }), []);
540
+
541
+ // ── The ambient wave — one persistent overlay across idle, voice, read-aloud and dictation ──
542
+ const tts = useTTS({ apiUrl: runtime.apiUrl, ...runtime.speech });
543
+ const { state: voiceState } = voice;
544
+ const wave = useAmbientWave({
545
+ voice: voiceState
546
+ ? {
547
+ isActive: voice.isActive,
548
+ isConnected: voiceState.isConnected,
549
+ agentState: voiceState.agentState,
550
+ waveAmplitude: voiceState.waveAmplitude,
551
+ }
552
+ : undefined,
553
+ isTTSPlaying: tts.playbackState === 'playing',
554
+ ttsWaveAmplitude: tts.ttsWaveAmplitude,
555
+ isGenerating: isLoading,
556
+ });
557
+ // The welcome and a call are the field's moments, so they get the intro's full strength; a
558
+ // conversation being read keeps the hook's subtle one, so the text stays easy to read.
559
+ const ambientIntensity = voice.isActive || composer.firstTurn ? 1 : wave.intensity;
560
+ const background = useMemo(
561
+ () => (
562
+ <AmbientField
563
+ layout={layout}
564
+ waveAmplitude={wave.waveAmplitude}
565
+ agentState={wave.agentState}
566
+ intensity={ambientIntensity}
567
+ isDarkMode={isDarkMode}
568
+ // A screen kept mounted under another does not keep animating back there.
569
+ paused={!isFocused}
570
+ />
571
+ ),
572
+ [layout, wave.waveAmplitude, wave.agentState, ambientIntensity, isDarkMode, isFocused],
573
+ );
574
+
575
+ // ── The greeting of an empty chat ──
576
+ const greeting =
577
+ welcomeGreeting ??
578
+ lead.greeting ??
579
+ (isAuthenticated && user
580
+ ? labels.greetingNamed(getAccountDisplayName(user, labels.locale))
581
+ : labels.greeting);
582
+ // An agent's chat greets as the agent: nothing, rather than Alia, until its profile is read.
583
+ const welcome = useMemo(
584
+ () =>
585
+ profileLoading ? null : (
586
+ <View className="items-center gap-8">
587
+ {group === undefined ? (
588
+ <GemieWelcomeMessage greeting={greeting} subtitle={welcomeSubtitle} lead={lead} />
589
+ ) : (
590
+ <GemieGroupWelcome members={group} />
591
+ )}
592
+ {welcomeAccessory}
593
+ </View>
594
+ ),
595
+ [profileLoading, greeting, welcomeSubtitle, lead, group, welcomeAccessory],
596
+ );
597
+
598
+ // ── The agent's offer to start the next stretch fresh ──
599
+ const createConversation = useCreateConversation();
600
+ /**
601
+ * Take the agent up on its offer: start the next stretch of this thread.
602
+ *
603
+ * The agent cannot do this — its tool emits one frame and writes nothing — so the act is the
604
+ * person's, here. A new conversation with the same agent becomes the most recent, which is the
605
+ * one the thread calls active, so re-reading the thread is what moves the screen onto it. On a
606
+ * chat that is not a thread there is nothing to continue: the offer empties the chat, which is
607
+ * "start a new conversation" on a screen that has no thread.
608
+ *
609
+ * A thread with a row of its own (Alia's: `gemieThread.threadId`) is continued by that row, since
610
+ * a conversation with her that names only her gemie is a loose chat, not her thread's.
611
+ */
612
+ const threadRowId = gemieThread?.threadId ?? null;
613
+ const acceptNewConversation = useCallback(() => {
614
+ dismissSuggestedNewConversation();
615
+ const next =
616
+ threadRowId !== null ? { threadId: threadRowId } : agentId !== undefined ? { agentId } : null;
617
+ if (threadAddress === undefined || next === null) {
618
+ void startOver();
619
+ return;
620
+ }
621
+ const key = threadKey(threadAddress);
622
+ createConversation.mutate(next, {
623
+ onSuccess: () => {
624
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.threads.all(key) });
625
+ // And the history with it: the stretch that was live becomes history the moment a new
626
+ // one is active, and the pages held were fetched before its last turns existed.
627
+ void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.threads.messages(key) });
628
+ },
629
+ });
630
+ }, [
631
+ agentId,
632
+ threadAddress,
633
+ threadRowId,
634
+ createConversation,
635
+ queryClient,
636
+ dismissSuggestedNewConversation,
637
+ startOver,
638
+ ]);
639
+ const newConversationOffer = useMemo(
640
+ () =>
641
+ suggestedNewConversation === null
642
+ ? undefined
643
+ : {
644
+ reason: suggestedNewConversation,
645
+ onAccept: acceptNewConversation,
646
+ onDismiss: dismissSuggestedNewConversation,
647
+ },
648
+ [suggestedNewConversation, acceptNewConversation, dismissSuggestedNewConversation],
649
+ );
650
+
651
+ // ── The chrome ──
652
+ const latestMessages = useRef(messages);
653
+ latestMessages.current = messages;
654
+ const hasMessages = messages.length > 0;
655
+ const state = useMemo<GemieChatState>(
656
+ () => ({
657
+ conversationId,
658
+ hasMessages,
659
+ startOver,
660
+ clearMessages: clearConversation,
661
+ markState: voice.markState,
662
+ participants,
663
+ openSearch: threadAddress === undefined ? undefined : view.openSearch,
664
+ getMessages: () => latestMessages.current,
665
+ }),
666
+ [
667
+ conversationId,
668
+ hasMessages,
669
+ startOver,
670
+ clearConversation,
671
+ voice.markState,
672
+ participants,
673
+ threadAddress,
674
+ view.openSearch,
675
+ ],
676
+ );
677
+ const frame = useMemo(() => chrome?.(state) ?? {}, [chrome, state]);
678
+
679
+ // ── The composer ──
680
+ const { editing, edit } = composer;
681
+ const voiceButton = voice.enabled ? (
682
+ <Button
683
+ iconOnly
684
+ tone="action"
685
+ size="md"
686
+ accessibilityLabel={labels.startVoice}
687
+ onPress={voice.activate}
688
+ leadingIcon={VoiceModeIcon}
689
+ />
690
+ ) : undefined;
691
+ const status: ReactNode =
692
+ editing !== undefined ? (
693
+ // What is happening while a question is rewritten, and the way out of it. Drawn as the
694
+ // status tab it replaces: the thread scrolls behind the composer, and a strip without the
695
+ // tab's surface printed its words over the transcript's.
696
+ <View className="mx-7 h-[34px] flex-row items-center gap-2 rounded-t-2xl bg-background-tertiary-default px-2 py-1">
697
+ <RiEditLine size="sm" />
698
+ <Text className="flex-1 text-xs text-muted-foreground" numberOfLines={1}>
699
+ {t('composer.editingMessage')}
700
+ </Text>
701
+ <Button appearance="subtle" tone="accent" size="xs" onPress={edit.cancel}>
702
+ {t('composer.cancelEdit')}
703
+ </Button>
704
+ </View>
705
+ ) : (
706
+ composerStatus
707
+ );
708
+
709
+ const composerNode = (
710
+ <>
711
+ {VoiceCall !== null && voice.enabled && voice.isActive ? (
712
+ <VoiceCall {...voice.launcher.sessionProps} />
713
+ ) : (
714
+ <GemieComposer
715
+ // A different account is a different composer: reads in flight for the last one are
716
+ // aborted rather than landing here.
717
+ key={composer.address.account ?? ''}
718
+ apiUrl={runtime.apiUrl}
719
+ speechLanguage={runtime.speech.language}
720
+ inputRef={composer.inputRef}
721
+ disableKeyboardAvoidance
722
+ onKeyPress={composer.onKeyPress}
723
+ suggestions={composer.suggestions}
724
+ // Asked beside the field, not in the thread: the card docks above the composer.
725
+ questions={{
726
+ items: asked.questions,
727
+ onSubmit: (message) => void composer.sendTurn(message, undefined, composer.turnOptions),
728
+ onDismiss: asked.dismiss,
729
+ }}
730
+ value={composer.text}
731
+ onValueChange={composer.setText}
732
+ onSubmit={() => void composer.submit(composer.text)}
733
+ busy={isLoading}
734
+ loaderPhase={composerPhase}
735
+ disabled={closed || loading}
736
+ onStop={stop}
737
+ emptyAction={voiceButton}
738
+ accessory={
739
+ <ScrollToBottomButton
740
+ visible={!isAtBottom}
741
+ onPress={jumpToEnd}
742
+ accessibilityLabel={t('chat.bloom.scrollToLatest')}
743
+ />
744
+ }
745
+ placeholder={
746
+ closed
747
+ ? t('usageLimit.inputDisabledPlaceholder')
748
+ : editing !== undefined
749
+ ? t('composer.editPlaceholder')
750
+ : group === undefined
751
+ ? labels.placeholder(lead.name)
752
+ : t('chat.groupPlaceholder')
753
+ }
754
+ status={status}
755
+ // The mode selector is the power level: how much power this turn gets.
756
+ {...(modes === undefined
757
+ ? {}
758
+ : { modes, mode: model ?? 'auto', onModeChange: onModelChange })}
759
+ addMenu={menu.groups}
760
+ onAddMenuSelect={menu.onSelect}
761
+ attachments={composer.photos}
762
+ onAddAttachment={composer.addAttachment}
763
+ onRemoveAttachment={composer.removeAttachment}
764
+ attachmentKinds={addMenu === undefined ? attachMenu.kinds : undefined}
765
+ onError={onError}
766
+ />
767
+ )}
768
+ {bottomInset > 0 ? <KeyboardSafeAreaFloor inset={bottomInset} /> : null}
769
+ </>
770
+ );
771
+
772
+ const showsPast = view.jumped;
773
+ return (
774
+ <GemieFlightsProvider value={flights}>
775
+ <InertWhen inert={exchange !== null}>
776
+ <AiChatContainer
777
+ header={frame.header}
778
+ title={frame.title}
779
+ project={frame.project}
780
+ actions={frame.actions}
781
+ composer={composerNode}
782
+ // The thread scrolls behind the header and the composer, which fade in over it. The wave
783
+ // is the container's background layer, between its surface and the turns.
784
+ floatingChrome
785
+ // The wave is a translucent layer over the frame's own fill, so the container paints no surface
786
+ // of its own: the frame's fill shows through, and the composer's fade lands on that same fill
787
+ // rather than on a band of its own (Bloom: `surface={false}` beside a translucent `background`).
788
+ surface={false}
789
+ background={background}
790
+ >
791
+ <BubblesProvider value={bubbles || group !== undefined}>
792
+ <GemieThread
793
+ // Nothing live under a window: it is a view of the past, and the conversation being
794
+ // streamed into is not below it in the thread.
795
+ messages={showsPast ? NO_MESSAGES : messages}
796
+ conversationId={conversationId}
797
+ isLoading={isLoading}
798
+ conversationLoading={conversationLoading || loading}
799
+ memberIds={memberIds}
800
+ history={view.history}
801
+ focusCursor={view.focusCursor}
802
+ failedTurn={failedTurn}
803
+ onRetryTurn={retryFailedTurn}
804
+ onRegenerate={composer.regenerate}
805
+ onStartEdit={edit.start}
806
+ newConversationOffer={newConversationOffer}
807
+ agentActivity={agentRun === null ? null : agentActivity}
808
+ call={voice.isActive ? { agentState: voice.agentState } : undefined}
809
+ empty={welcome}
810
+ threadRef={threadRef}
811
+ onScroll={onScroll}
812
+ onReply={quoteIntoComposer}
813
+ onReactionChange={thread.applyReaction}
814
+ onOpenAgentChat={setExchange}
815
+ />
816
+ </BubblesProvider>
817
+ {!showsPast ? null : (
818
+ <View className="absolute inset-x-0 top-16 z-10 items-center" pointerEvents="box-none">
819
+ <Button appearance="outline" tone="neutral" size="sm" onPress={view.backToLatest}>
820
+ {t('chat.backToLatest')}
821
+ </Button>
822
+ </View>
823
+ )}
824
+ {!view.searchOpen || threadAddress === undefined ? null : (
825
+ <ThreadSearch thread={threadAddress} onJump={view.jump} onClose={view.closeSearch} />
826
+ )}
827
+ </AiChatContainer>
828
+ </InertWhen>
829
+ {exchange === null ? null : (
830
+ <AgentExchangeView exchange={exchange} lead={lead} onBack={closeExchange} />
831
+ )}
832
+ {usageLimit === null ? null : renderUsageLimit?.({ error: usageLimit, dismiss: clearError })}
833
+ {sharedFlights ? null : <AvatarFlightLayer flights={ownFlights} />}
834
+ </GemieFlightsProvider>
835
+ );
836
+ }
837
+
838
+ /**
839
+ * The chat: header, thread and composer, with the host's labels in reach of all of it.
840
+ *
841
+ * It is a conversation view over the shared runtime. The conversation open in it is the host's
842
+ * when `conversationId` is given, and its own otherwise.
843
+ */
844
+ export function GemieChatContent({
845
+ labels,
846
+ conversationId: controlledId,
847
+ onConversationChange,
848
+ runtime,
849
+ apiUrl,
850
+ app,
851
+ toolRenderers,
852
+ onFeatureLocked,
853
+ ...props
854
+ }: GemieChatContentProps) {
855
+ const [ownId, setOwnId] = useState<string | undefined>(undefined);
856
+ const parent = useGemieRuntime();
857
+ const chatApp = app ?? parent.app;
858
+ if (chatApp !== undefined && !APP_SLUG.test(chatApp)) {
859
+ throw new Error(
860
+ `GemieChatContent: app "${chatApp}" is not an app slug (^[a-z][a-z0-9-]{0,31}$)`,
861
+ );
862
+ }
863
+ if (props.hostTools !== undefined && chatApp === undefined) {
864
+ throw new Error(
865
+ "GemieChatContent: hostTools are an app's, so a chat with hostTools names its app",
866
+ );
867
+ }
868
+ // Who decides which conversation is open: a host that navigates (a route) does; with none, the
869
+ // chat does (the sheet). Either way the host hears of it first, then `onConversationChange`.
870
+ const hostOpens = runtime?.openConversation ?? parent.host.openConversation;
871
+ const hostCloses = runtime?.closeConversation ?? parent.host.closeConversation;
872
+ const hostNavigates = hostOpens !== undefined;
873
+ const host = useMemo<GemieRuntimeHost>(
874
+ () => ({
875
+ ...runtime,
876
+ ...(onFeatureLocked === undefined ? {} : { onFeatureLocked }),
877
+ openConversation: (id) => {
878
+ hostOpens?.(id);
879
+ if (!hostNavigates) setOwnId(id);
880
+ onConversationChange?.(id);
881
+ },
882
+ closeConversation: () => {
883
+ hostCloses?.();
884
+ if (!hostNavigates) setOwnId(undefined);
885
+ onConversationChange?.(undefined);
886
+ },
887
+ }),
888
+ [runtime, onFeatureLocked, hostOpens, hostCloses, hostNavigates, onConversationChange],
889
+ );
890
+
891
+ return (
892
+ <GemieChatLabelsProvider labels={labels}>
893
+ <GemieRuntimeProvider apiUrl={apiUrl ?? parent.apiUrl} host={host} app={chatApp}>
894
+ <GemieToolRenderersProvider value={toolRenderers ?? NO_RENDERERS}>
895
+ <GemieConversationView {...props} conversationId={controlledId ?? ownId} />
896
+ </GemieToolRenderersProvider>
897
+ </GemieRuntimeProvider>
898
+ </GemieChatLabelsProvider>
899
+ );
900
+ }