@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,79 @@
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+ import { rememberOpener } from '../lib/focus-return';
3
+ import { useGemieRuntime } from '../runtime/config';
4
+ import { type ThoughtScope, type ThoughtTab, useThoughtStore } from '../runtime/thought-store';
5
+ import type { ThreadMessage } from '../runtime/thread/thread-history';
6
+
7
+ /** Open the thought panel on a turn; `opener` is the control pressed, to give focus back to. */
8
+ export type OpenThought = (messageId: string, tab?: ThoughtTab, opener?: unknown) => void;
9
+
10
+ /**
11
+ * The scope a press on a row hands the thought panel: the conversation the row belongs to, which
12
+ * is not always the one being streamed into.
13
+ *
14
+ * A live row belongs to the conversation on screen. A history row belongs to an earlier stretch
15
+ * of the thread — persisted and complete — so its scope is that stretch's messages and nothing
16
+ * about the live turn. Keyed by conversation and message: the panel never shows one
17
+ * conversation's turn under another's.
18
+ */
19
+ export function thoughtScopeFor(
20
+ messageId: string,
21
+ live: ThoughtScope,
22
+ history: readonly ThreadMessage[],
23
+ ): ThoughtScope {
24
+ if (live.messages.some((m) => m.id === messageId)) return live;
25
+ const past = history.find((m) => m.id === messageId);
26
+ if (past === undefined) return live;
27
+ return {
28
+ conversationId: past.conversationId,
29
+ messages: history.filter((m) => m.conversationId === past.conversationId),
30
+ status: 'ready',
31
+ isLoading: false,
32
+ failedTurn: null,
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Open the thought panel on any turn — the one in flight or one long past — or `undefined` when
38
+ * the host has no panel to show it in (`GemieRuntimeHost.showThought`): the row then draws its
39
+ * "worked for" line as plain text.
40
+ *
41
+ * `runningTurnId` is the turn in flight once it has begun using tools. The first tool of a turn
42
+ * opens the panel on it unless the host declines (something else is open), once per turn: a
43
+ * reader who closes it keeps it closed.
44
+ *
45
+ * The returned function is stable: it is a prop of every memoised row, while the live scope
46
+ * changes per streamed token, so the scopes are read at press time through a ref.
47
+ */
48
+ export function useOpenThought(
49
+ live: ThoughtScope,
50
+ history: readonly ThreadMessage[],
51
+ runningTurnId: string | null,
52
+ ): OpenThought | undefined {
53
+ const { showThought } = useGemieRuntime().host;
54
+ const select = useThoughtStore((s) => s.open);
55
+ const latest = useRef({ live, history, showThought });
56
+ useEffect(() => {
57
+ latest.current = { live, history, showThought };
58
+ });
59
+
60
+ const open = useCallback<OpenThought>(
61
+ (messageId, tab, opener) => {
62
+ const { live: scope, history: past, showThought: show } = latest.current;
63
+ rememberOpener(opener);
64
+ select(messageId, thoughtScopeFor(messageId, scope, past), tab);
65
+ show?.('pressed');
66
+ },
67
+ [select],
68
+ );
69
+
70
+ const autoOpened = useRef<string | null>(null);
71
+ useEffect(() => {
72
+ if (runningTurnId === null || autoOpened.current === runningTurnId) return;
73
+ autoOpened.current = runningTurnId;
74
+ const { live: scope, showThought: show } = latest.current;
75
+ if (show?.('automatic') === true) select(runningTurnId, scope);
76
+ }, [runningTurnId, select]);
77
+
78
+ return showThought === undefined ? undefined : open;
79
+ }
@@ -0,0 +1,19 @@
1
+ import { useCallback, useMemo, useState } from 'react';
2
+ import { type AskedQuestion, pendingQuestions } from '../lib/questions';
3
+ import type { Message } from '../runtime/types';
4
+
5
+ /**
6
+ * What Alia asked in her last turn and the person has not answered: asked above the composer,
7
+ * not in the thread. Any later message, typed or sent from the card, is the answer; `dismiss`
8
+ * puts the card away until she asks again.
9
+ */
10
+ export function usePendingQuestions(
11
+ messages: readonly Pick<Message, 'id' | 'role' | 'toolInvocations'>[],
12
+ isStreaming: boolean,
13
+ ): { questions: AskedQuestion[]; dismiss: () => void } {
14
+ const asked = useMemo(() => pendingQuestions(messages, isStreaming), [messages, isStreaming]);
15
+ const lastMessageId = messages.at(-1)?.id ?? null;
16
+ const [dismissedOf, setDismissedOf] = useState<string | null>(null);
17
+ const dismiss = useCallback(() => setDismissedOf(lastMessageId), [lastMessageId]);
18
+ return { questions: dismissedOf === lastMessageId ? [] : asked, dismiss };
19
+ }
@@ -0,0 +1,92 @@
1
+ import { toast } from '@oxy.so/bloom/toast';
2
+ import { useCallback, useEffect, useRef } from 'react';
3
+ import { useLabels } from '../lib/labels';
4
+ import { useGemieRuntime } from '../runtime/config';
5
+ import { useDictationStore } from './useDictation';
6
+ import { useTTS } from './useTTS';
7
+
8
+ export type ReadAloudState = 'idle' | 'loading' | 'playing' | 'paused' | 'error';
9
+
10
+ /**
11
+ * The screen whose player is sounding, if any.
12
+ *
13
+ * `useTTS` keeps its player PER HOOK INSTANCE while the playback state is one shared store — and
14
+ * a host can keep every visited chat mounted, each with its own thread and so its own instance.
15
+ * Starting a reply in one chat must stop a reply still playing in another, and only the instance
16
+ * that owns a player can stop it. So the owner registers its `stop` here, and anyone may call it.
17
+ */
18
+ let owner: { stop: () => void } | null = null;
19
+
20
+ /** Silence whatever a thread is reading aloud, on any mounted screen. */
21
+ function stopReadingAloud(): void {
22
+ const current = owner;
23
+ owner = null;
24
+ current?.stop();
25
+ }
26
+
27
+ /**
28
+ * Read one reply aloud, as a toggle.
29
+ *
30
+ * - A press starts it; a second press on the same reply stops it — not `useTTS`'s pause, which
31
+ * would leave a half-read reply parked with nothing on screen saying so.
32
+ * - `blocked` is a call or a dictation holding the audio: the button is disabled, and anything
33
+ * already being read stops when either starts. Two voices at once, or the microphone recording
34
+ * Alia's own voice into the draft, is the thing this prevents.
35
+ * - A failure is a toast, and the button goes back to idle.
36
+ *
37
+ * It speaks with the runtime's `apiUrl` and the host's `speech` preferences.
38
+ */
39
+ export function useReadAloud(blocked: boolean) {
40
+ const { t } = useLabels();
41
+ const { apiUrl, speech } = useGemieRuntime();
42
+ const { readAloud, stop, activeMessageId, playbackState } = useTTS({ apiUrl, ...speech });
43
+ const self = useRef<{ stop: () => void }>({ stop });
44
+ self.current.stop = stop;
45
+ const owns = owner === self.current && activeMessageId !== null;
46
+
47
+ // A call or a dictation began: whatever is being read stops, wherever.
48
+ const dictating = useDictationStore((s) => s.isRecording);
49
+ const busy = blocked || dictating;
50
+ useEffect(() => {
51
+ if (busy) stopReadingAloud();
52
+ }, [busy]);
53
+
54
+ useEffect(() => {
55
+ if (!owns || playbackState !== 'error') return;
56
+ toast.error(t('chat.readAloudFailed'));
57
+ stopReadingAloud();
58
+ }, [owns, playbackState, t]);
59
+
60
+ // Leaving takes the player with it (`useTTS` releases it); the shared state has to go too, or
61
+ // every other screen would show a reply still playing.
62
+ useEffect(() => {
63
+ const me = self.current;
64
+ return () => {
65
+ if (owner === me) stopReadingAloud();
66
+ };
67
+ }, []);
68
+
69
+ const active = useRef(activeMessageId);
70
+ active.current = activeMessageId;
71
+ const toggle = useCallback(
72
+ (messageId: string, text: string, conversationId?: string) => {
73
+ const wasThis = active.current === messageId;
74
+ stopReadingAloud();
75
+ if (wasThis) return;
76
+ owner = self.current;
77
+ // The route makes a clip once and answers every later press — here or after a reload — from
78
+ // storage. `conversationId` files it under the conversation, so deleting that deletes it;
79
+ // the caller passes it only for a message the server holds (`Message.unsaved`): for one it
80
+ // does not, the route answers 404 and nothing would be read.
81
+ void readAloud(messageId, text, conversationId);
82
+ },
83
+ [readAloud],
84
+ );
85
+
86
+ const stateOf = useCallback(
87
+ (messageId: string): ReadAloudState => (activeMessageId === messageId ? playbackState : 'idle'),
88
+ [activeMessageId, playbackState],
89
+ );
90
+
91
+ return { toggle, stateOf, blocked: busy };
92
+ }
@@ -0,0 +1,24 @@
1
+ import { toast } from '@oxy.so/bloom/toast';
2
+ import { useCallback } from 'react';
3
+ import { useLabels } from '../lib/labels';
4
+ import { type GemieConversationShare, useShareConversation } from '../runtime/sharing';
5
+
6
+ /**
7
+ * What the header's share button does: mint the conversation's read-only link, then hand it to
8
+ * the host, which builds its own URL and shows its own share sheet. `undefined` without a host
9
+ * `onShare`, so there is no button.
10
+ */
11
+ export function useShareHandler(
12
+ onShare: ((share: GemieConversationShare) => void) | undefined,
13
+ ): ((conversationId: string | undefined) => void) | undefined {
14
+ const { share } = useShareConversation();
15
+ const { t } = useLabels();
16
+ const handle = useCallback(
17
+ (conversationId: string | undefined) => {
18
+ if (conversationId === undefined || onShare === undefined) return;
19
+ void share(conversationId).then(onShare, () => toast.error(t('chat.shareFailed')));
20
+ },
21
+ [share, onShare, t],
22
+ );
23
+ return onShare === undefined ? undefined : handle;
24
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Sound effects hook for voice mode.
3
+ * Plays short audio cues when the AI is thinking, using tools,
4
+ * or when voice connection state changes.
5
+ *
6
+ * Sounds are provided via options instead of hardcoded require() calls,
7
+ * making this hook portable across different bundlers and apps.
8
+ */
9
+
10
+ import { useEffect, useRef, useCallback } from 'react';
11
+ import type { AudioPlayer, AudioSource } from 'expo-audio';
12
+ import { loadExpoAudio } from '../lib/deferred/expo-audio';
13
+ import type { AgentState } from '../types';
14
+
15
+ export type SoundName = 'thinking' | 'toolCall' | 'voiceConnect' | 'voiceDisconnect';
16
+
17
+ export interface SoundSources {
18
+ thinking?: AudioSource;
19
+ toolCall?: AudioSource;
20
+ voiceConnect?: AudioSource;
21
+ voiceDisconnect?: AudioSource;
22
+ }
23
+
24
+ const SOUND_NAMES: SoundName[] = ['thinking', 'toolCall', 'voiceConnect', 'voiceDisconnect'];
25
+
26
+ export function useSoundEffects(enabled: boolean = false, sounds: SoundSources = {}) {
27
+ const playersRef = useRef<Map<SoundName, AudioPlayer>>(new Map());
28
+ const loadedRef = useRef(false);
29
+
30
+ useEffect(() => {
31
+ if (!enabled || loadedRef.current) return;
32
+
33
+ // Only load sounds that were actually provided
34
+ const hasAnySounds = SOUND_NAMES.some((name) => sounds[name] != null);
35
+ if (!hasAnySounds) return;
36
+
37
+ let mounted = true;
38
+
39
+ (async () => {
40
+ try {
41
+ const { createAudioPlayer } = await loadExpoAudio();
42
+ if (!mounted) return;
43
+
44
+ for (const name of SOUND_NAMES) {
45
+ const source = sounds[name];
46
+ if (source == null) continue;
47
+ try {
48
+ const player = createAudioPlayer(source);
49
+ playersRef.current.set(name, player);
50
+ } catch {
51
+ // Individual sound failed to load — skip it
52
+ }
53
+ }
54
+ loadedRef.current = true;
55
+ } catch {
56
+ // expo-audio not available — degrade silently
57
+ }
58
+ })();
59
+
60
+ return () => {
61
+ mounted = false;
62
+ for (const player of playersRef.current.values()) {
63
+ try {
64
+ player.release();
65
+ } catch {
66
+ // Best-effort cleanup — a player already released/unloaded is safe to ignore.
67
+ }
68
+ }
69
+ playersRef.current.clear();
70
+ loadedRef.current = false;
71
+ };
72
+ }, [enabled, sounds]);
73
+
74
+ const play = useCallback(
75
+ (sound: SoundName) => {
76
+ if (!enabled) return;
77
+ const player = playersRef.current.get(sound);
78
+ if (player) {
79
+ try {
80
+ player.seekTo(0);
81
+ player.play();
82
+ } catch {
83
+ // Playback failed — ignore
84
+ }
85
+ }
86
+ },
87
+ [enabled],
88
+ );
89
+
90
+ return { play };
91
+ }
92
+
93
+ /**
94
+ * Hook that automatically triggers sound effects based on voice state changes.
95
+ * Wire this into the conversation page from the launcher's state (`useVoiceLauncher`).
96
+ */
97
+ export function useVoiceSoundEffects({
98
+ isVoiceActive,
99
+ agentState,
100
+ isConnected,
101
+ sounds = {},
102
+ }: {
103
+ isVoiceActive: boolean;
104
+ agentState: AgentState;
105
+ isConnected: boolean;
106
+ sounds?: SoundSources;
107
+ }) {
108
+ const { play } = useSoundEffects(isVoiceActive, sounds);
109
+ const prevAgentStateRef = useRef<AgentState>('idle');
110
+ const prevConnectedRef = useRef(false);
111
+
112
+ // Play sound on agent state transitions
113
+ useEffect(() => {
114
+ if (!isVoiceActive) return;
115
+
116
+ const prev = prevAgentStateRef.current;
117
+ prevAgentStateRef.current = agentState;
118
+
119
+ if (agentState === 'thinking' && prev !== 'thinking') {
120
+ play('thinking');
121
+ }
122
+ }, [agentState, isVoiceActive, play]);
123
+
124
+ // Play sound on connection state changes
125
+ useEffect(() => {
126
+ if (!isVoiceActive) return;
127
+
128
+ const wasConnected = prevConnectedRef.current;
129
+ prevConnectedRef.current = isConnected;
130
+
131
+ if (isConnected && !wasConnected) {
132
+ play('voiceConnect');
133
+ } else if (!isConnected && wasConnected) {
134
+ play('voiceDisconnect');
135
+ }
136
+ }, [isConnected, isVoiceActive, play]);
137
+ }
@@ -0,0 +1,303 @@
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+ import type { AudioPlayer, AudioSample, AudioStatus } from 'expo-audio';
3
+ import { makeMutable, withTiming } from 'react-native-reanimated';
4
+ import { useOxy } from '@oxy.so/services/ui/client';
5
+ import { errorMessage } from '../lib/utils';
6
+ import { create } from 'zustand';
7
+ import { createAudioLevelMeter } from '../lib/audio-level';
8
+ import { loadExpoAudio } from '../lib/deferred/expo-audio';
9
+ import { requestSpeechClip } from '../lib/speech-synthesis';
10
+ import { GEMIES_API_URL } from '../lib/origins';
11
+ import { bindAudioSession } from '../lib/audio-session-binding';
12
+
13
+ // ============== OPTIONS ==============
14
+
15
+ export interface UseTTSOptions {
16
+ apiUrl?: string;
17
+ accessToken?: string;
18
+ voice?: 'male' | 'female';
19
+ tone?: 'brief' | 'chill' | 'default';
20
+ /**
21
+ * Speech model. Omitted, the request carries no `model` and the server's
22
+ * own speech model answers.
23
+ */
24
+ model?: string;
25
+ }
26
+
27
+ // ============== INLINE TTS STORE ==============
28
+
29
+ type PlaybackState = 'idle' | 'loading' | 'playing' | 'paused' | 'error';
30
+
31
+ interface TTSStore {
32
+ activeMessageId: string | null;
33
+ playbackState: PlaybackState;
34
+ error: string | null;
35
+ setActiveMessage: (id: string | null) => void;
36
+ setPlaybackState: (state: PlaybackState) => void;
37
+ setError: (error: string | null) => void;
38
+ reset: () => void;
39
+ }
40
+
41
+ const useTTSStore = create<TTSStore>((set) => ({
42
+ activeMessageId: null,
43
+ playbackState: 'idle',
44
+ error: null,
45
+ setActiveMessage: (id) => set({ activeMessageId: id }),
46
+ setPlaybackState: (playbackState) => set({ playbackState }),
47
+ setError: (error) => set({ error, playbackState: error ? 'error' : 'idle' }),
48
+ reset: () => set({ activeMessageId: null, playbackState: 'idle', error: null }),
49
+ }));
50
+
51
+ // ============== PLAYBACK LEVEL ==============
52
+
53
+ /** How long the level takes to reach silence once a clip stops sounding. */
54
+ const SILENCE_FADE_MS = 300;
55
+
56
+ /**
57
+ * The live playback level, 0..1, shared by every consumer.
58
+ *
59
+ * At module scope rather than inside the hook because the two ends of it live
60
+ * in different components: the message list calls `readAloud` and therefore
61
+ * owns the player, while the ambient field behind the conversation is rendered
62
+ * somewhere else entirely. Each `useTTS()` call is its own React instance, so a
63
+ * per-instance `useSharedValue` leaves the field reading a value that nothing
64
+ * writes — which is why the animation it replaces had to be driven off the
65
+ * shared playback STATE instead of off the audio. One player, one store, one
66
+ * level.
67
+ */
68
+ const ttsWaveAmplitude = makeMutable(0);
69
+
70
+ /**
71
+ * Silence is a projection of playback state, not an animation of its own.
72
+ *
73
+ * Every platform stops delivering buffers the instant a clip pauses, ends or
74
+ * fails, so nothing would write the level down again and the field would freeze
75
+ * swollen wherever the last syllable left it. Subscribed once, beside the store
76
+ * that owns the transitions, so a transition added later cannot forget it.
77
+ */
78
+ useTTSStore.subscribe((state, previous) => {
79
+ if (state.playbackState === 'playing') return;
80
+ if (previous.playbackState !== 'playing') return;
81
+ ttsWaveAmplitude.value = withTiming(0, { duration: SILENCE_FADE_MS });
82
+ });
83
+
84
+ // ============== HOOK ==============
85
+
86
+ export function useTTS(options: UseTTSOptions = {}) {
87
+ const apiUrl = options.apiUrl || GEMIES_API_URL;
88
+ const voicePref = options.voice ?? 'female';
89
+ const voiceModel = options.model;
90
+ const tonePref = options.tone ?? 'default';
91
+
92
+ const { oxyServices } = useOxy();
93
+ // Per-field selectors: subscribing to the whole store re-renders every
94
+ // consumer on any playback transition. Actions are static store refs, so
95
+ // selecting them individually never triggers a re-render.
96
+ const activeMessageId = useTTSStore((s) => s.activeMessageId);
97
+ const playbackState = useTTSStore((s) => s.playbackState);
98
+ const error = useTTSStore((s) => s.error);
99
+ const setActiveMessage = useTTSStore((s) => s.setActiveMessage);
100
+ const setPlaybackState = useTTSStore((s) => s.setPlaybackState);
101
+ const setError = useTTSStore((s) => s.setError);
102
+ const reset = useTTSStore((s) => s.reset);
103
+
104
+ const playerRef = useRef<AudioPlayer | null>(null);
105
+ const requestRef = useRef<AbortController | null>(null);
106
+
107
+ const getTTSVoice = useCallback(() => {
108
+ return voicePref === 'male' ? 'male' : 'female';
109
+ }, [voicePref]);
110
+
111
+ const getTTSSpeed = useCallback(() => {
112
+ if (tonePref === 'brief') return 1.15;
113
+ if (tonePref === 'chill') return 0.9;
114
+ return 1.0;
115
+ }, [tonePref]);
116
+
117
+ const releasePlayer = useCallback(() => {
118
+ try {
119
+ playerRef.current?.remove();
120
+ } catch {
121
+ // Best-effort teardown — the player may already be removed.
122
+ }
123
+ playerRef.current = null;
124
+ }, []);
125
+
126
+ const stop = useCallback(() => {
127
+ requestRef.current?.abort();
128
+ requestRef.current = null;
129
+ releasePlayer();
130
+ reset();
131
+ }, [reset, releasePlayer]);
132
+
133
+ /** Play the clip the route answered with. A clip that will not play is a failure, reported. */
134
+ const playFromUrl = useCallback(
135
+ (audioUrl: string, signal: AbortSignal) => {
136
+ releasePlayer();
137
+
138
+ (async () => {
139
+ try {
140
+ const { createAudioPlayer } = await loadExpoAudio();
141
+ if (signal.aborted) return;
142
+ /**
143
+ * `crossOrigin` is web-only and ignored elsewhere, and it is what makes
144
+ * the waveform readable there: a browser will not let an `AnalyserNode`
145
+ * see a cross-origin media element loaded without CORS, so without this
146
+ * `setAudioSamplingEnabled` below silently declines and the field never
147
+ * moves. Clips are served by `GET /media` on the API host, which is a
148
+ * different origin from the app on every deployment.
149
+ *
150
+ * It costs the clip its CORS headers if the app's origin is not on the
151
+ * API's allowlist — but such an origin cannot load a conversation to
152
+ * read aloud in the first place, since `/media` and `/conversations`
153
+ * share that allowlist. Measured against production 2026-08-26: an allowed
154
+ * `Origin` is echoed back in `access-control-allow-origin`, with `Vary: Origin`.
155
+ */
156
+ const player = createAudioPlayer({ uri: audioUrl }, { crossOrigin: 'anonymous' });
157
+ playerRef.current = player;
158
+
159
+ /**
160
+ * The real waveform, which is what the ambient field behind the
161
+ * conversation moves to. Enabled BEFORE `play()`: on web this is what
162
+ * builds the analyser, and the sampling loop only starts if the player
163
+ * is already playing or starts afterwards.
164
+ *
165
+ * It can decline, and declining is not an error. Android routes
166
+ * playback sampling through `android.media.audiofx.Visualizer`, which
167
+ * needs `RECORD_AUDIO` already granted — and asking a person for the
168
+ * microphone so that a background can move would be a worse trade than
169
+ * the background not moving. Where it declines no buffer ever arrives,
170
+ * the level stays at zero and the field simply rests. That is the
171
+ * honest reading of "we cannot hear this", and it is deliberately not
172
+ * papered over with motion that does not come from the audio.
173
+ */
174
+ player.setAudioSamplingEnabled(true);
175
+ const meter = createAudioLevelMeter();
176
+ player.addListener('audioSampleUpdate', (sample: AudioSample) => {
177
+ const frames = sample.channels[0]?.frames;
178
+ if (frames === undefined) return;
179
+ ttsWaveAmplitude.value = meter.push(frames, Date.now());
180
+ });
181
+
182
+ player.addListener('playbackStatusUpdate', (status: AudioStatus) => {
183
+ if (signal.aborted || playerRef.current !== player) return;
184
+ if (status.error) {
185
+ releasePlayer();
186
+ setError(status.error);
187
+ return;
188
+ }
189
+ if (status.didJustFinish) {
190
+ releasePlayer();
191
+ reset();
192
+ }
193
+ });
194
+
195
+ player.play();
196
+ setPlaybackState('playing');
197
+ } catch {
198
+ if (signal.aborted) return;
199
+ setError('Audio playback not available');
200
+ }
201
+ })();
202
+ },
203
+ [releasePlayer, reset, setPlaybackState, setError],
204
+ );
205
+
206
+ const readAloud = useCallback(
207
+ async (messageId: string, text: string, conversationId?: string) => {
208
+ // Read volatile playback state at call time (not via closure) so this
209
+ // callback's identity survives every playback transition. It is passed to
210
+ // memoized message rows — an unstable identity re-renders all of them.
211
+ const { activeMessageId, playbackState } = useTTSStore.getState();
212
+
213
+ // If same message is playing, toggle pause/play
214
+ if (activeMessageId === messageId) {
215
+ if (playbackState === 'playing') {
216
+ playerRef.current?.pause();
217
+ setPlaybackState('paused');
218
+ return;
219
+ }
220
+ if (playbackState === 'paused') {
221
+ playerRef.current?.play();
222
+ setPlaybackState('playing');
223
+ return;
224
+ }
225
+ }
226
+
227
+ // Stop any current playback
228
+ if (activeMessageId) {
229
+ stop();
230
+ }
231
+
232
+ const controller = new AbortController();
233
+ requestRef.current = controller;
234
+ const linked = options.accessToken
235
+ ? null
236
+ : bindAudioSession(oxyServices, apiUrl, () => controller.abort());
237
+ try {
238
+ setActiveMessage(messageId);
239
+ setPlaybackState('loading');
240
+
241
+ /**
242
+ * Always ask the route: it answers a clip this person already had made —
243
+ * same text, voice, speed and model — from storage, without
244
+ * synthesizing it again, and makes it only when there is none. So a
245
+ * second press, here or after a reload, costs nothing and plays at once.
246
+ * `conversationId` (with the message id) files the clip under that
247
+ * conversation, so deleting the conversation deletes it.
248
+ */
249
+ const audioUrl = await requestSpeechClip({
250
+ apiUrl,
251
+ ...(linked ? { transport: linked } : { token: options.accessToken ?? '' }),
252
+ model: voiceModel,
253
+ input: text,
254
+ voice: getTTSVoice(),
255
+ speed: getTTSSpeed(),
256
+ conversationId,
257
+ messageId,
258
+ signal: controller.signal,
259
+ });
260
+ playFromUrl(audioUrl, controller.signal);
261
+ } catch (e: unknown) {
262
+ if (controller.signal.aborted) return;
263
+ console.error('[TTS] Error:', e);
264
+ setError(errorMessage(e, 'Failed to read aloud'));
265
+ } finally {
266
+ linked?.dispose();
267
+ }
268
+ },
269
+ [
270
+ options.accessToken,
271
+ oxyServices,
272
+ apiUrl,
273
+ voiceModel,
274
+ getTTSVoice,
275
+ getTTSSpeed,
276
+ stop,
277
+ playFromUrl,
278
+ setActiveMessage,
279
+ setPlaybackState,
280
+ setError,
281
+ ],
282
+ );
283
+
284
+ // Cleanup on unmount
285
+ useEffect(() => {
286
+ return () => {
287
+ requestRef.current?.abort();
288
+ releasePlayer();
289
+ };
290
+ }, []);
291
+
292
+ return {
293
+ readAloud,
294
+ stop,
295
+ activeMessageId,
296
+ playbackState,
297
+ error,
298
+ ttsWaveAmplitude,
299
+ isPlaying: playbackState === 'playing',
300
+ isPaused: playbackState === 'paused',
301
+ isLoading: playbackState === 'loading',
302
+ };
303
+ }