@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.
- package/CHANGELOG.md +1678 -0
- package/LICENSE +202 -0
- package/NOTICE +15 -0
- package/README.md +516 -2
- package/package.json +105 -4
- package/src/accounts.ts +29 -0
- package/src/animations.ts +5 -0
- package/src/ask-eager.ts +8 -0
- package/src/ask-text.ts +11 -0
- package/src/ask.ts +12 -0
- package/src/avatar.ts +13 -0
- package/src/character.ts +1 -0
- package/src/components/AmbientField.tsx +580 -0
- package/src/components/ComposerDropZone.tsx +235 -0
- package/src/components/ComposerSuggestions.tsx +45 -0
- package/src/components/GemieAccounts.tsx +433 -0
- package/src/components/GemieAskCore.tsx +184 -0
- package/src/components/GemieAskProvider.tsx +18 -0
- package/src/components/GemieAskProviderLazy.tsx +27 -0
- package/src/components/GemieAskProviderText.tsx +25 -0
- package/src/components/GemieAskSheet.tsx +51 -0
- package/src/components/GemieAskSheetWithVoice.tsx +10 -0
- package/src/components/GemieAvatar.tsx +57 -0
- package/src/components/GemieAvatarIcon.tsx +35 -0
- package/src/components/GemieChatContent.tsx +900 -0
- package/src/components/GemieChatHeader.tsx +123 -0
- package/src/components/GemieChatScreen.tsx +170 -0
- package/src/components/GemieChatSheet.tsx +368 -0
- package/src/components/GemieChatWithVoice.tsx +13 -0
- package/src/components/GemieComposer.tsx +388 -0
- package/src/components/GemieGroupWelcome.tsx +37 -0
- package/src/components/GemieParticipants.tsx +133 -0
- package/src/components/GemieParticipantsHeader.tsx +27 -0
- package/src/components/GemieRecentConversations.tsx +65 -0
- package/src/components/GemieSharedConversation.tsx +87 -0
- package/src/components/GemieWelcomeMessage.tsx +58 -0
- package/src/components/IdentityMark.tsx +225 -0
- package/src/components/Image.tsx +12 -0
- package/src/components/InertWhen.tsx +48 -0
- package/src/components/PlanPreviewCard.tsx +53 -0
- package/src/components/QuestionCard.tsx +64 -0
- package/src/components/ReplyMarkdown.tsx +373 -0
- package/src/components/RichBlocks.tsx +195 -0
- package/src/components/VoiceModeIcon.tsx +18 -0
- package/src/components/canvas/CanvasComponent.tsx +65 -0
- package/src/components/canvas/ChartRenderer.tsx +73 -0
- package/src/components/canvas/CodeRenderer.tsx +20 -0
- package/src/components/canvas/DashboardRenderer.tsx +70 -0
- package/src/components/canvas/DeckRenderer.tsx +43 -0
- package/src/components/canvas/FormRenderer.tsx +101 -0
- package/src/components/canvas/MarkdownRenderer.tsx +14 -0
- package/src/components/canvas/TableRenderer.tsx +47 -0
- package/src/components/icons/RiEmojiPicker.tsx +39 -0
- package/src/components/icons/RiMoreDots.tsx +32 -0
- package/src/components/icons/RiReplyLine.tsx +25 -0
- package/src/components/thought/FilesAndSources.tsx +120 -0
- package/src/components/thought/ThoughtPanel.tsx +426 -0
- package/src/components/thought/ToolStep.tsx +134 -0
- package/src/components/thread/AgentExchangeView.tsx +112 -0
- package/src/components/thread/AgentResultCard.tsx +125 -0
- package/src/components/thread/AgentTaskCard.tsx +127 -0
- package/src/components/thread/ChatBubble.tsx +256 -0
- package/src/components/thread/GemieThread.tsx +455 -0
- package/src/components/thread/MessageBlockBoundary.tsx +78 -0
- package/src/components/thread/NewConversationOffer.tsx +54 -0
- package/src/components/thread/ThreadRow.tsx +598 -0
- package/src/components/thread/ThreadSearch.tsx +130 -0
- package/src/components/thread/ThreadSkeleton.tsx +30 -0
- package/src/components/thread/ToolResultCard.tsx +254 -0
- package/src/components/thread/TurnMenu.tsx +54 -0
- package/src/components/thread/TurnStatusLine.tsx +34 -0
- package/src/components/voice/GemieVoiceCall.tsx +21 -0
- package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
- package/src/components/voice/VoiceCallContext.ts +13 -0
- package/src/components/voice/VoiceControls.tsx +106 -0
- package/src/components/voice/VoiceSession.tsx +120 -0
- package/src/components/voice/withVoiceCall.tsx +25 -0
- package/src/csp.ts +50 -0
- package/src/dictation.ts +40 -0
- package/src/hooks/useAmbientWave.ts +184 -0
- package/src/hooks/useAtBottom.ts +51 -0
- package/src/hooks/useAttachMenu.ts +93 -0
- package/src/hooks/useAttachmentIntake.ts +401 -0
- package/src/hooks/useAudioLevelMonitor.ts +46 -0
- package/src/hooks/useAudioLevels.ts +51 -0
- package/src/hooks/useChatComposer.ts +309 -0
- package/src/hooks/useChatVoice.ts +129 -0
- package/src/hooks/useComposerSuggestions.ts +84 -0
- package/src/hooks/useDictation.ts +292 -0
- package/src/hooks/useDocumentPicker.ts +11 -0
- package/src/hooks/useFailedTurnToast.ts +43 -0
- package/src/hooks/useFocusWhenPresented.ts +41 -0
- package/src/hooks/useGemieActivity.ts +31 -0
- package/src/hooks/useImagePicker.ts +38 -0
- package/src/hooks/useMessageReactions.ts +119 -0
- package/src/hooks/useMessageVote.ts +50 -0
- package/src/hooks/useOpenThought.ts +79 -0
- package/src/hooks/usePendingQuestions.ts +19 -0
- package/src/hooks/useReadAloud.ts +92 -0
- package/src/hooks/useShareHandler.ts +24 -0
- package/src/hooks/useSoundEffects.ts +137 -0
- package/src/hooks/useTTS.ts +303 -0
- package/src/hooks/useThoughtScope.ts +59 -0
- package/src/hooks/useThreadRows.ts +157 -0
- package/src/hooks/useThreadView.ts +67 -0
- package/src/hooks/useTimelineWindow.ts +256 -0
- package/src/hooks/useVoiceLauncher.ts +180 -0
- package/src/hooks/useVoiceRoom.ts +212 -0
- package/src/index.ts +141 -0
- package/src/lib/activity-socket.ts +102 -0
- package/src/lib/activity-store.ts +53 -0
- package/src/lib/add-menu.ts +7 -0
- package/src/lib/agent-character.ts +28 -0
- package/src/lib/alia-character.ts +14 -0
- package/src/lib/alia-gemie.ts +6 -0
- package/src/lib/attachment-intake.ts +154 -0
- package/src/lib/attachment-tiles.ts +74 -0
- package/src/lib/audio-level.ts +130 -0
- package/src/lib/audio-request-auth.ts +4 -0
- package/src/lib/audio-session-binding.ts +27 -0
- package/src/lib/bubbles.tsx +16 -0
- package/src/lib/call-thread.ts +33 -0
- package/src/lib/canvas-result.ts +21 -0
- package/src/lib/catalogue-tool.ts +22 -0
- package/src/lib/citations.ts +192 -0
- package/src/lib/clipboard.ts +23 -0
- package/src/lib/content-utils.ts +46 -0
- package/src/lib/copy-en.ts +333 -0
- package/src/lib/copy-es.ts +330 -0
- package/src/lib/copy.ts +38 -0
- package/src/lib/deferred/document-picker.ts +2 -0
- package/src/lib/deferred/document-picker.web.ts +12 -0
- package/src/lib/deferred/expo-audio.ts +2 -0
- package/src/lib/deferred/expo-audio.web.ts +12 -0
- package/src/lib/deferred/image-data-url.ts +5 -0
- package/src/lib/deferred/image-data-url.web.ts +12 -0
- package/src/lib/dictation-protocol.ts +142 -0
- package/src/lib/dictation-recorder-types.ts +37 -0
- package/src/lib/dictation-recorder.native.ts +90 -0
- package/src/lib/dictation-recorder.ts +131 -0
- package/src/lib/dictation-stream.ts +238 -0
- package/src/lib/dictation.ts +216 -0
- package/src/lib/document-picker.ts +31 -0
- package/src/lib/domain.ts +12 -0
- package/src/lib/flights.ts +33 -0
- package/src/lib/focus-return.ts +66 -0
- package/src/lib/greeting.ts +15 -0
- package/src/lib/image-data-url.ts +35 -0
- package/src/lib/keyboard.native.tsx +25 -0
- package/src/lib/keyboard.tsx +55 -0
- package/src/lib/labels-es.ts +113 -0
- package/src/lib/labels.tsx +207 -0
- package/src/lib/origins.ts +28 -0
- package/src/lib/participants.ts +97 -0
- package/src/lib/pcm.ts +57 -0
- package/src/lib/power-level-options.ts +66 -0
- package/src/lib/questions.ts +92 -0
- package/src/lib/speech-language.ts +20 -0
- package/src/lib/speech-messages.ts +54 -0
- package/src/lib/speech-synthesis.ts +156 -0
- package/src/lib/suggestions.ts +53 -0
- package/src/lib/task-labels.ts +35 -0
- package/src/lib/text-input.ts +10 -0
- package/src/lib/tool-call-status.ts +28 -0
- package/src/lib/tool-icons.ts +36 -0
- package/src/lib/tool-registry.ts +71 -0
- package/src/lib/tool-renderers.tsx +32 -0
- package/src/lib/turn-state.ts +15 -0
- package/src/lib/utils.ts +35 -0
- package/src/lib/voice-audio-engine-types.ts +59 -0
- package/src/lib/voice-audio-engine.native.ts +232 -0
- package/src/lib/voice-audio-engine.ts +206 -0
- package/src/lib/voice-call-request.ts +49 -0
- package/src/lib/voice-call.ts +627 -0
- package/src/lib/voice-controls-labels.ts +31 -0
- package/src/lib/voice-levels.ts +64 -0
- package/src/lib/voice-protocol.ts +328 -0
- package/src/lib/voice-worklets.ts +19 -0
- package/src/lib/work-log.ts +370 -0
- package/src/metro/chart-importers.json +18 -0
- package/src/metro/granular-charts.js +3 -0
- package/src/metro/index.cjs +227 -0
- package/src/metro/index.d.cts +5 -0
- package/src/runtime/agents.ts +151 -0
- package/src/runtime/api.ts +144 -0
- package/src/runtime/app-assertion.ts +51 -0
- package/src/runtime/attachment-utils.ts +97 -0
- package/src/runtime/chat-turn-control.ts +74 -0
- package/src/runtime/composer-draft-store.ts +270 -0
- package/src/runtime/config.tsx +222 -0
- package/src/runtime/conversation-dates.ts +31 -0
- package/src/runtime/conversation-store.ts +49 -0
- package/src/runtime/conversations.ts +633 -0
- package/src/runtime/error-utils.ts +144 -0
- package/src/runtime/gemie-accounts.ts +182 -0
- package/src/runtime/host-tools.ts +290 -0
- package/src/runtime/index.ts +137 -0
- package/src/runtime/message-history.ts +124 -0
- package/src/runtime/message-reactions.ts +214 -0
- package/src/runtime/model.ts +39 -0
- package/src/runtime/oxy-files.ts +37 -0
- package/src/runtime/power-levels.ts +66 -0
- package/src/runtime/query-keys.ts +60 -0
- package/src/runtime/random-uuid.ts +25 -0
- package/src/runtime/reaction-cache.ts +45 -0
- package/src/runtime/room-events.ts +333 -0
- package/src/runtime/routes.ts +85 -0
- package/src/runtime/sharing.ts +217 -0
- package/src/runtime/sse-frame-reader.ts +88 -0
- package/src/runtime/stream-events.ts +154 -0
- package/src/runtime/stream-outcome.ts +21 -0
- package/src/runtime/thought-store.ts +103 -0
- package/src/runtime/thread/agent-activity.ts +261 -0
- package/src/runtime/thread/agent-exchange.ts +94 -0
- package/src/runtime/thread/automation-labels.ts +79 -0
- package/src/runtime/thread/conversation-export.ts +135 -0
- package/src/runtime/thread/message-days.ts +120 -0
- package/src/runtime/thread/message-processor.ts +93 -0
- package/src/runtime/thread/speaker-changes.ts +66 -0
- package/src/runtime/thread/task-utils.ts +11 -0
- package/src/runtime/thread/thought-utils.ts +750 -0
- package/src/runtime/thread/thread-history.ts +139 -0
- package/src/runtime/thread/timeline.ts +202 -0
- package/src/runtime/thread/title-tags.ts +8 -0
- package/src/runtime/thread/tool-cards.ts +387 -0
- package/src/runtime/turn-failure.ts +108 -0
- package/src/runtime/turn-preparation.ts +21 -0
- package/src/runtime/types.ts +172 -0
- package/src/runtime/usage-limit-error.ts +44 -0
- package/src/runtime/use-agent-activity.ts +80 -0
- package/src/runtime/use-conversation-stream.ts +1669 -0
- package/src/runtime/use-conversation-thread.ts +590 -0
- package/src/runtime/use-gemie-thread.ts +54 -0
- package/src/runtime/use-room-events.ts +75 -0
- package/src/runtime/use-start-conversation.ts +107 -0
- package/src/runtime/use-thread-history.ts +73 -0
- package/src/runtime/use-thread-search.ts +100 -0
- package/src/runtime/use-turn-edit.ts +99 -0
- package/src/text.ts +19 -0
- package/src/theme.ts +16 -0
- package/src/tools.ts +27 -0
- package/src/types.ts +161 -0
- package/src/voice-messages.ts +2 -0
- package/src/voice.ts +67 -0
- package/tsconfig.json +17 -0
- package/worklets/voice-processors.js +152 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host side of a voice call, shared by every surface that offers one.
|
|
3
|
+
*
|
|
4
|
+
* It owns whether a call is open, the state it reports back (for the ambient
|
|
5
|
+
* wave, the sound effects and the transcript), the gate before one opens (plan,
|
|
6
|
+
* credits, sign-in: the host answers, the SDK tells the person), and the end of
|
|
7
|
+
* a call that is no longer the screen's — another screen on show, another
|
|
8
|
+
* conversation, another account. `sessionProps` is everything `VoiceSession`
|
|
9
|
+
* needs; the sheet, `GemieChatScreen` and the Alia app all spread it.
|
|
10
|
+
*
|
|
11
|
+
* Nothing here imports the call or its audio engine.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
15
|
+
import { toast } from '@oxy.so/bloom/toast';
|
|
16
|
+
import { useLabels, type VoiceBlockReason } from '../lib/labels';
|
|
17
|
+
import { isRequestFor, useVoiceCallRequests } from '../lib/voice-call-request';
|
|
18
|
+
import type { VoiceNotice, VoiceSessionProps, VoiceSessionState } from '../types';
|
|
19
|
+
|
|
20
|
+
export interface UseVoiceLauncherOptions {
|
|
21
|
+
/** Gemies API base URL. */
|
|
22
|
+
apiUrl?: string;
|
|
23
|
+
/** The conversation open on this screen, which is where the call lives. */
|
|
24
|
+
conversationId?: string;
|
|
25
|
+
/**
|
|
26
|
+
* Called after the gate, when no conversation is open: creates (and shows) the one the call
|
|
27
|
+
* will live in and returns its id, or `undefined` when it could not be made (the call then
|
|
28
|
+
* does not open). Every call has a conversation, so its transcript has a home. The call opens
|
|
29
|
+
* on the screen that shows that conversation: this one, or the one the host navigates to.
|
|
30
|
+
*/
|
|
31
|
+
resolveConversation?: () => Promise<string | undefined>;
|
|
32
|
+
/** Whose call it would be. A live call ends when the account, or the open conversation, changes. */
|
|
33
|
+
accountId?: string | null;
|
|
34
|
+
/** The agent the call talks to; omitted, Alia. */
|
|
35
|
+
agentId?: string;
|
|
36
|
+
/** Language spoken (BCP-47); omitted, the platform's. */
|
|
37
|
+
locale?: string;
|
|
38
|
+
/** Which of the product's two voices answers. */
|
|
39
|
+
voice?: 'male' | 'female';
|
|
40
|
+
/** Alia stored messages of the call in the conversation: refresh the thread. */
|
|
41
|
+
onMessagesSaved?: VoiceSessionProps['onMessagesSaved'];
|
|
42
|
+
/**
|
|
43
|
+
* The gate before a call opens: why it may not (no account, no plan, no credits), or `null`.
|
|
44
|
+
* The person is told (`labels.voiceBlocked`); `onVoiceBlocked` adds what only the host can do.
|
|
45
|
+
*/
|
|
46
|
+
canStartVoice?: () => VoiceBlockReason | null;
|
|
47
|
+
/** The call was not opened for `reason`: sign the person in, open the plans… */
|
|
48
|
+
onVoiceBlocked?: (reason: VoiceBlockReason) => void;
|
|
49
|
+
/** Where the call's notices go; omitted, Bloom's toast. */
|
|
50
|
+
onNotice?: (notice: VoiceNotice) => void;
|
|
51
|
+
/** A call is over, however it ended: refresh credits, the thread… */
|
|
52
|
+
onCallEnded?: () => void;
|
|
53
|
+
/** Whether the screen holding the call is the one on show. A live call ends when it is not. */
|
|
54
|
+
isFocused?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface VoiceLauncher {
|
|
58
|
+
/** A call is open (or being opened). */
|
|
59
|
+
isActive: boolean;
|
|
60
|
+
/** What the call reports back; `null` until it is under way. */
|
|
61
|
+
state: VoiceSessionState | null;
|
|
62
|
+
/** Open a call, after the gate. Does nothing while one is open or the screen is not on show. */
|
|
63
|
+
start: () => Promise<void>;
|
|
64
|
+
/** End the call. */
|
|
65
|
+
end: () => void;
|
|
66
|
+
/** Spread onto `VoiceSession` (or `GemieVoiceCall`). */
|
|
67
|
+
sessionProps: VoiceSessionProps;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Bloom's toast, by kind: the default home of a call's notices. */
|
|
71
|
+
export function toastNotice({ kind, text }: VoiceNotice): void {
|
|
72
|
+
if (kind === 'error') toast.error(text);
|
|
73
|
+
else if (kind === 'warning') toast.warning(text);
|
|
74
|
+
else toast.info(text);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function useVoiceLauncher(options: UseVoiceLauncherOptions = {}): VoiceLauncher {
|
|
78
|
+
const labels = useLabels();
|
|
79
|
+
const {
|
|
80
|
+
apiUrl,
|
|
81
|
+
conversationId,
|
|
82
|
+
resolveConversation,
|
|
83
|
+
accountId = null,
|
|
84
|
+
agentId,
|
|
85
|
+
locale,
|
|
86
|
+
voice,
|
|
87
|
+
onMessagesSaved,
|
|
88
|
+
canStartVoice,
|
|
89
|
+
onVoiceBlocked,
|
|
90
|
+
onNotice,
|
|
91
|
+
onCallEnded,
|
|
92
|
+
isFocused = true,
|
|
93
|
+
} = options;
|
|
94
|
+
const [isActive, setIsActive] = useState(false);
|
|
95
|
+
const [state, setState] = useState<VoiceSessionState | null>(null);
|
|
96
|
+
const latest = useRef({
|
|
97
|
+
canStartVoice,
|
|
98
|
+
onVoiceBlocked,
|
|
99
|
+
onNotice,
|
|
100
|
+
onCallEnded,
|
|
101
|
+
resolveConversation,
|
|
102
|
+
labels,
|
|
103
|
+
});
|
|
104
|
+
latest.current = {
|
|
105
|
+
canStartVoice,
|
|
106
|
+
onVoiceBlocked,
|
|
107
|
+
onNotice,
|
|
108
|
+
onCallEnded,
|
|
109
|
+
resolveConversation,
|
|
110
|
+
labels,
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const notify = useCallback((notice: VoiceNotice) => {
|
|
114
|
+
(latest.current.onNotice ?? toastNotice)(notice);
|
|
115
|
+
}, []);
|
|
116
|
+
|
|
117
|
+
const end = useCallback(() => {
|
|
118
|
+
setIsActive(false);
|
|
119
|
+
setState(null);
|
|
120
|
+
latest.current.onCallEnded?.();
|
|
121
|
+
}, []);
|
|
122
|
+
|
|
123
|
+
const start = useCallback(async () => {
|
|
124
|
+
if (isActive || !isFocused) return;
|
|
125
|
+
const reason = latest.current.canStartVoice?.() ?? null;
|
|
126
|
+
if (reason !== null) {
|
|
127
|
+
notify({
|
|
128
|
+
kind: reason === 'credits-exhausted' ? 'error' : 'info',
|
|
129
|
+
text: latest.current.labels.voiceBlocked(reason),
|
|
130
|
+
});
|
|
131
|
+
latest.current.onVoiceBlocked?.(reason);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// The gate first: a call that may not open must not leave an empty conversation behind.
|
|
135
|
+
const home = conversationId ?? (await latest.current.resolveConversation?.());
|
|
136
|
+
if (home === undefined) return;
|
|
137
|
+
// The call opens where its conversation is shown (see `useVoiceCallRequests`): here, at once,
|
|
138
|
+
// when it already is; wherever the host takes the new conversation, when it was just made.
|
|
139
|
+
useVoiceCallRequests.getState().ask(home, accountId);
|
|
140
|
+
}, [isActive, isFocused, conversationId, accountId, notify]);
|
|
141
|
+
|
|
142
|
+
const request = useVoiceCallRequests((store) => store.request);
|
|
143
|
+
useEffect(() => {
|
|
144
|
+
if (isActive || !isFocused || !isRequestFor(request, conversationId, accountId)) return;
|
|
145
|
+
useVoiceCallRequests.getState().clear();
|
|
146
|
+
setIsActive(true);
|
|
147
|
+
}, [request, isActive, isFocused, conversationId, accountId]);
|
|
148
|
+
|
|
149
|
+
// A call belongs to one account and one conversation, on the screen that shows it: it ends when
|
|
150
|
+
// the screen goes out of focus, the account changes, or the screen moves to another conversation.
|
|
151
|
+
const openedIn = useRef<{ conversationId: string | undefined; accountId: string | null }>(
|
|
152
|
+
undefined,
|
|
153
|
+
);
|
|
154
|
+
useEffect(() => {
|
|
155
|
+
if (!isActive) {
|
|
156
|
+
openedIn.current = undefined;
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
openedIn.current ??= { conversationId, accountId };
|
|
160
|
+
const call = openedIn.current;
|
|
161
|
+
if (!isFocused || call.accountId !== accountId || call.conversationId !== conversationId) end();
|
|
162
|
+
}, [isActive, isFocused, accountId, conversationId, end]);
|
|
163
|
+
|
|
164
|
+
const sessionProps = useMemo<VoiceSessionProps>(
|
|
165
|
+
() => ({
|
|
166
|
+
...(apiUrl === undefined ? {} : { apiUrl }),
|
|
167
|
+
...(conversationId === undefined ? {} : { conversationId }),
|
|
168
|
+
...(agentId === undefined ? {} : { agentId }),
|
|
169
|
+
...(locale === undefined ? {} : { locale }),
|
|
170
|
+
...(voice === undefined ? {} : { voice }),
|
|
171
|
+
...(onMessagesSaved === undefined ? {} : { onMessagesSaved }),
|
|
172
|
+
onNotice: notify,
|
|
173
|
+
onStateChange: setState,
|
|
174
|
+
onEnd: end,
|
|
175
|
+
}),
|
|
176
|
+
[apiUrl, conversationId, agentId, locale, voice, onMessagesSaved, notify, end],
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
return { isActive, state, start, end, sessionProps };
|
|
180
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A voice call: speech to speech through Alia's `/v1/voice/session`
|
|
3
|
+
* (ADR 0017).
|
|
4
|
+
*
|
|
5
|
+
* Alia holds the realtime session with Kaana — instructions, memory, tools
|
|
6
|
+
* (run in Alia, never here), the transcript stored in the conversation, credits
|
|
7
|
+
* and typed errors. Turn detection and barge-in are the model's, on the server.
|
|
8
|
+
* This hook captures and plays PCM through the platform's audio engine
|
|
9
|
+
* (`lib/voice-audio-engine*`) and exposes a state it can prove (`callState`,
|
|
10
|
+
* see `VoiceCallState`), with `roomState` / `agentState` as the coarse
|
|
11
|
+
* projections the call bar, the ambient field and the sound effects read.
|
|
12
|
+
*
|
|
13
|
+
* Nothing is recognized on the device: there is no browser or OS speech
|
|
14
|
+
* recognizer anywhere in a call.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { bindAudioSession } from '../lib/audio-session-binding';
|
|
18
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
19
|
+
import { useOxy } from '@oxy.so/services/ui/client';
|
|
20
|
+
import type { AgentState, RoomState, VoiceCallState, VoiceMessage } from '../types';
|
|
21
|
+
import { VOICE_ERROR_MESSAGES, type VoiceErrorCode } from '../lib/speech-messages';
|
|
22
|
+
import { defaultSpeechLanguage } from '../lib/speech-language';
|
|
23
|
+
import { createVoiceAudioEngine } from '../lib/voice-audio-engine';
|
|
24
|
+
import type { VoiceAudioEngine } from '../lib/voice-audio-engine-types';
|
|
25
|
+
import { VoiceCall, type VoiceCallSnapshot, type VoiceSocketFactory } from '../lib/voice-call';
|
|
26
|
+
import { VoiceLevelChannel, type VoiceLevelSource } from '../lib/voice-levels';
|
|
27
|
+
import type { ProductVoice, VoiceCloseReason } from '../lib/voice-protocol';
|
|
28
|
+
import { GEMIES_API_URL } from '../lib/origins';
|
|
29
|
+
import { useAppAssertionToken } from '../runtime/app-assertion';
|
|
30
|
+
|
|
31
|
+
export interface UseVoiceRoomOptions {
|
|
32
|
+
apiUrl?: string;
|
|
33
|
+
/**
|
|
34
|
+
* The conversation the call is stored in. Omitted, every call starts a
|
|
35
|
+
* conversation of its own (a fresh id per `connect`).
|
|
36
|
+
*/
|
|
37
|
+
conversationId?: string;
|
|
38
|
+
/** The agent this call talks to; omitted, Alia. */
|
|
39
|
+
agentId?: string;
|
|
40
|
+
/** Which of the product's two voices answers. */
|
|
41
|
+
voicePreference?: ProductVoice;
|
|
42
|
+
/** Bearer for the call; defaults to the surrounding Oxy session's. */
|
|
43
|
+
accessToken?: string;
|
|
44
|
+
/** Language spoken (BCP-47). Defaults to the platform's. */
|
|
45
|
+
lang?: string;
|
|
46
|
+
/** Alia stored messages of the call: refresh the thread. */
|
|
47
|
+
onMessagesSaved?: (conversationId: string, messageIds: readonly string[]) => void;
|
|
48
|
+
/** Test seams: the device's audio and the socket. */
|
|
49
|
+
createAudioEngine?: () => VoiceAudioEngine;
|
|
50
|
+
openSocket?: VoiceSocketFactory;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const IDLE: VoiceCallSnapshot = {
|
|
54
|
+
state: { kind: 'idle' },
|
|
55
|
+
messages: [],
|
|
56
|
+
isMuted: false,
|
|
57
|
+
endingSoonMs: null,
|
|
58
|
+
model: null,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const openWebSocket: VoiceSocketFactory = (url) =>
|
|
62
|
+
new WebSocket(url) as unknown as ReturnType<VoiceSocketFactory>;
|
|
63
|
+
|
|
64
|
+
function newConversationId(): string {
|
|
65
|
+
const random = globalThis.crypto?.randomUUID?.();
|
|
66
|
+
return random ?? `voice-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The coarse connection state the bar and the wave read. */
|
|
70
|
+
export function roomStateOf(state: VoiceCallState): RoomState {
|
|
71
|
+
switch (state.kind) {
|
|
72
|
+
case 'idle':
|
|
73
|
+
case 'ended':
|
|
74
|
+
return 'disconnected';
|
|
75
|
+
case 'connecting':
|
|
76
|
+
return 'connecting';
|
|
77
|
+
case 'reconnecting':
|
|
78
|
+
return 'reconnecting';
|
|
79
|
+
case 'error':
|
|
80
|
+
return 'error';
|
|
81
|
+
default:
|
|
82
|
+
return 'connected';
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Who has the turn, coarsely. */
|
|
87
|
+
export function agentStateOf(state: VoiceCallState): AgentState {
|
|
88
|
+
switch (state.kind) {
|
|
89
|
+
case 'listening':
|
|
90
|
+
case 'user-speaking':
|
|
91
|
+
return 'listening';
|
|
92
|
+
case 'thinking':
|
|
93
|
+
case 'using-tool':
|
|
94
|
+
return 'thinking';
|
|
95
|
+
case 'speaking':
|
|
96
|
+
return 'speaking';
|
|
97
|
+
default:
|
|
98
|
+
return 'idle';
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function useVoiceRoom(options: UseVoiceRoomOptions = {}) {
|
|
103
|
+
const { oxyServices } = useOxy();
|
|
104
|
+
const getAppAssertion = useAppAssertionToken();
|
|
105
|
+
const levels = useMemo(() => new VoiceLevelChannel(), []);
|
|
106
|
+
const [snapshot, setSnapshot] = useState<VoiceCallSnapshot>(IDLE);
|
|
107
|
+
const callRef = useRef<VoiceCall | null>(null);
|
|
108
|
+
const sessionBindingRef = useRef<ReturnType<typeof bindAudioSession> | null>(null);
|
|
109
|
+
const mountedRef = useRef(true);
|
|
110
|
+
const optionsRef = useRef(options);
|
|
111
|
+
optionsRef.current = options;
|
|
112
|
+
|
|
113
|
+
const connect = useCallback(async () => {
|
|
114
|
+
const live = callRef.current?.snapshot().state.kind;
|
|
115
|
+
if (live !== undefined && live !== 'ended' && live !== 'error') return;
|
|
116
|
+
const current = optionsRef.current;
|
|
117
|
+
sessionBindingRef.current?.dispose();
|
|
118
|
+
const apiUrl = current.apiUrl || GEMIES_API_URL;
|
|
119
|
+
const binding = current.accessToken
|
|
120
|
+
? null
|
|
121
|
+
: bindAudioSession(oxyServices, apiUrl, () => callRef.current?.hangUp());
|
|
122
|
+
sessionBindingRef.current = binding;
|
|
123
|
+
const call = new VoiceCall({
|
|
124
|
+
apiUrl,
|
|
125
|
+
getToken: binding?.getToken ?? (() => optionsRef.current.accessToken ?? null),
|
|
126
|
+
getAppAssertion,
|
|
127
|
+
conversationId: current.conversationId ?? newConversationId(),
|
|
128
|
+
...(current.agentId === undefined ? {} : { agentId: current.agentId }),
|
|
129
|
+
voice: current.voicePreference ?? 'female',
|
|
130
|
+
locale: current.lang ?? defaultSpeechLanguage(),
|
|
131
|
+
createEngine: current.createAudioEngine ?? createVoiceAudioEngine,
|
|
132
|
+
openSocket: current.openSocket ?? openWebSocket,
|
|
133
|
+
levels,
|
|
134
|
+
onChange: (next) => {
|
|
135
|
+
if (callRef.current !== call) return;
|
|
136
|
+
if (next.state.kind === 'ended' || next.state.kind === 'error') binding?.dispose();
|
|
137
|
+
if (mountedRef.current) setSnapshot(next);
|
|
138
|
+
},
|
|
139
|
+
onMessagesSaved: (conversationId, ids) =>
|
|
140
|
+
optionsRef.current.onMessagesSaved?.(conversationId, ids),
|
|
141
|
+
});
|
|
142
|
+
callRef.current = call;
|
|
143
|
+
await call.start();
|
|
144
|
+
}, [oxyServices, getAppAssertion, levels]);
|
|
145
|
+
|
|
146
|
+
/** Hang up and forget the call: the room is back to `disconnected`. */
|
|
147
|
+
const disconnect = useCallback(() => {
|
|
148
|
+
const call = callRef.current;
|
|
149
|
+
callRef.current = null;
|
|
150
|
+
sessionBindingRef.current?.dispose();
|
|
151
|
+
sessionBindingRef.current = null;
|
|
152
|
+
call?.hangUp();
|
|
153
|
+
levels.reset();
|
|
154
|
+
if (mountedRef.current) setSnapshot(IDLE);
|
|
155
|
+
}, [levels]);
|
|
156
|
+
|
|
157
|
+
const toggleMute = useCallback(() => {
|
|
158
|
+
const call = callRef.current;
|
|
159
|
+
if (call === null) return;
|
|
160
|
+
call.setMuted(!call.snapshot().isMuted);
|
|
161
|
+
}, []);
|
|
162
|
+
|
|
163
|
+
useEffect(() => {
|
|
164
|
+
mountedRef.current = true;
|
|
165
|
+
return () => {
|
|
166
|
+
mountedRef.current = false;
|
|
167
|
+
const call = callRef.current;
|
|
168
|
+
callRef.current = null;
|
|
169
|
+
sessionBindingRef.current?.dispose();
|
|
170
|
+
sessionBindingRef.current = null;
|
|
171
|
+
call?.hangUp();
|
|
172
|
+
};
|
|
173
|
+
}, []);
|
|
174
|
+
|
|
175
|
+
const { state } = snapshot;
|
|
176
|
+
const roomState = roomStateOf(state);
|
|
177
|
+
const errorCode: VoiceErrorCode | null = state.kind === 'error' ? state.code : null;
|
|
178
|
+
const endedReason: VoiceCloseReason | null = state.kind === 'ended' ? state.reason : null;
|
|
179
|
+
const room: VoiceLevelSource = levels;
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
/** The call's live levels, for `useAudioLevelMonitor`. */
|
|
183
|
+
room,
|
|
184
|
+
/** The honest state machine (ADR 0017 §4). */
|
|
185
|
+
callState: state,
|
|
186
|
+
roomState,
|
|
187
|
+
agentState: agentStateOf(state),
|
|
188
|
+
isMuted: snapshot.isMuted,
|
|
189
|
+
/** Why the call failed, in English. */
|
|
190
|
+
error: errorCode === null ? null : VOICE_ERROR_MESSAGES[errorCode],
|
|
191
|
+
/** The same, as a code an app can translate. */
|
|
192
|
+
errorCode,
|
|
193
|
+
/** Why the call ended without failing; `call-moved-elsewhere` is one. */
|
|
194
|
+
endedReason,
|
|
195
|
+
/** Milliseconds left once the server warned the call is about to end. */
|
|
196
|
+
endingSoonMs: snapshot.endingSoonMs,
|
|
197
|
+
/** The model serving the call (its name may be shown; the operator never is). */
|
|
198
|
+
model: snapshot.model,
|
|
199
|
+
/** The live transcript, both sides. The stored one is the conversation's. */
|
|
200
|
+
messages: snapshot.messages as VoiceMessage[],
|
|
201
|
+
currentSpeaker:
|
|
202
|
+
state.kind === 'speaking'
|
|
203
|
+
? ('primary' as const)
|
|
204
|
+
: state.kind === 'user-speaking'
|
|
205
|
+
? ('user' as const)
|
|
206
|
+
: null,
|
|
207
|
+
connect,
|
|
208
|
+
disconnect,
|
|
209
|
+
toggleMute,
|
|
210
|
+
isConnected: roomState === 'connected',
|
|
211
|
+
};
|
|
212
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/// <reference types="nativewind/types" />
|
|
2
|
+
// @gemies/sdk — the Gemies SDK
|
|
3
|
+
// Reusable chat UI, voice, and streaming components for Oxy apps
|
|
4
|
+
|
|
5
|
+
// ── Main components ──
|
|
6
|
+
export { GemieChatContent } from './components/GemieChatWithVoice';
|
|
7
|
+
export type {
|
|
8
|
+
GemieChatAgentRef,
|
|
9
|
+
GemieChatChrome,
|
|
10
|
+
GemieChatContentProps,
|
|
11
|
+
GemieChatState,
|
|
12
|
+
} from './components/GemieChatContent';
|
|
13
|
+
export { GemieParticipants, useParticipants } from './components/GemieParticipants';
|
|
14
|
+
export type {
|
|
15
|
+
GemieParticipantsProps,
|
|
16
|
+
UseParticipantsOptions,
|
|
17
|
+
} from './components/GemieParticipants';
|
|
18
|
+
export { GemieParticipantsHeader } from './components/GemieParticipantsHeader';
|
|
19
|
+
export type { GemieParticipantsHeaderProps } from './components/GemieParticipantsHeader';
|
|
20
|
+
export { ALIA_GEMIE_ID } from './lib/alia-gemie';
|
|
21
|
+
export { ALIA_LEAD, leadOf } from './lib/participants';
|
|
22
|
+
export type { GemieChatParticipants, GemieLead, GemieParticipant } from './lib/participants';
|
|
23
|
+
export { ANCHORS, leadToProfile } from './lib/flights';
|
|
24
|
+
export { parseCatalogueTool, toolRendererKey } from './lib/catalogue-tool';
|
|
25
|
+
export type { GemieToolRenderers, GemieToolResult } from './lib/tool-renderers';
|
|
26
|
+
export { GemieAskProvider, useAskGemie } from './components/GemieAskProvider';
|
|
27
|
+
export type {
|
|
28
|
+
GemieAsk,
|
|
29
|
+
GemieAskAgents,
|
|
30
|
+
GemieAskProviderProps,
|
|
31
|
+
} from './components/GemieAskProvider';
|
|
32
|
+
export { GemieSharedConversation } from './components/GemieSharedConversation';
|
|
33
|
+
export type { GemieSharedConversationProps } from './components/GemieSharedConversation';
|
|
34
|
+
export type { GemieAddMenu } from './lib/add-menu';
|
|
35
|
+
export type { GemieVoiceOptions } from './hooks/useChatVoice';
|
|
36
|
+
export { GemieChatSheet } from './components/GemieChatWithVoice';
|
|
37
|
+
export type { GemieChatSheetProps, GemieChatSheetRef } from './components/GemieChatSheet';
|
|
38
|
+
export { GemieRecentConversations } from './components/GemieRecentConversations';
|
|
39
|
+
export type { GemieTurn } from './hooks/useChatComposer';
|
|
40
|
+
export { GemieChatScreen } from './components/GemieChatWithVoice';
|
|
41
|
+
export type { GemieChatScreenProps } from './components/GemieChatScreen';
|
|
42
|
+
|
|
43
|
+
// ── Chat UI components ──
|
|
44
|
+
export { DEFAULT_LABELS } from './lib/labels';
|
|
45
|
+
export { GemieChatLabelsProvider, useLabels } from './lib/labels';
|
|
46
|
+
export type { GemieChatLabels, VoiceBlockReason } from './lib/labels';
|
|
47
|
+
export { VoiceModeIcon } from './components/VoiceModeIcon';
|
|
48
|
+
export { AmbientField, PARALLAX_DURATION, PARALLAX_EASE } from './components/AmbientField';
|
|
49
|
+
export type { AmbientFieldProps } from './components/AmbientField';
|
|
50
|
+
export { ALIA_AVATAR, GemieAvatar } from './components/GemieAvatar';
|
|
51
|
+
export { DEFAULT_AGENT_CHARACTER, readAgentCharacter } from './lib/agent-character';
|
|
52
|
+
export type { GemieAvatarProps, GemieAvatarState } from './components/GemieAvatar';
|
|
53
|
+
export { GemieAvatarIcon } from './components/GemieAvatarIcon';
|
|
54
|
+
export { useGemieActivity } from './hooks/useGemieActivity';
|
|
55
|
+
export type { UseGemieActivityOptions } from './hooks/useGemieActivity';
|
|
56
|
+
export { IdentityMark } from './components/IdentityMark';
|
|
57
|
+
export type { IdentityMarkProps, IdentityMarkState } from './components/IdentityMark';
|
|
58
|
+
export { ReplyMarkdown } from './components/ReplyMarkdown';
|
|
59
|
+
export { GemieThread } from './components/thread/GemieThread';
|
|
60
|
+
export type { GemieThreadProps, NewConversationOfferProps } from './components/thread/GemieThread';
|
|
61
|
+
export { ThoughtPanel } from './components/thought/ThoughtPanel';
|
|
62
|
+
export type { ThoughtPanelProps } from './components/thought/ThoughtPanel';
|
|
63
|
+
export type { OutputActions } from './components/thought/FilesAndSources';
|
|
64
|
+
export { CanvasComponent } from './components/canvas/CanvasComponent';
|
|
65
|
+
export { restoreOpenerFocus } from './lib/focus-return';
|
|
66
|
+
export { buildPowerLevelOptions, POWER_LEVEL_ICONS } from './lib/power-level-options';
|
|
67
|
+
export type { DeviceModel } from './lib/power-level-options';
|
|
68
|
+
export { GemieWelcomeMessage } from './components/GemieWelcomeMessage';
|
|
69
|
+
export { PlanPreviewCard } from './components/PlanPreviewCard';
|
|
70
|
+
export { AskedQuestions, QuestionCard } from './components/QuestionCard';
|
|
71
|
+
export { GemieComposer } from './components/GemieComposer';
|
|
72
|
+
export type {
|
|
73
|
+
GemieComposerProps,
|
|
74
|
+
GemieComposerQuestions,
|
|
75
|
+
GemieComposerSuggestions,
|
|
76
|
+
} from './components/GemieComposer';
|
|
77
|
+
export { ComposerSuggestions } from './components/ComposerSuggestions';
|
|
78
|
+
export { usePendingQuestions } from './hooks/usePendingQuestions';
|
|
79
|
+
export { useComposerSuggestions, useSuggestionQuery } from './hooks/useComposerSuggestions';
|
|
80
|
+
export { composerCompletions } from './lib/suggestions';
|
|
81
|
+
export type { Completion } from './lib/suggestions';
|
|
82
|
+
export {
|
|
83
|
+
ASK_USER_QUESTION_TOOL,
|
|
84
|
+
askedQuestions,
|
|
85
|
+
formatAnswers,
|
|
86
|
+
isQuestionInvocation,
|
|
87
|
+
} from './lib/questions';
|
|
88
|
+
export type { AskedOption, AskedQuestion, QuestionAnswer } from './lib/questions';
|
|
89
|
+
|
|
90
|
+
// ── Conversation runtime: the one data layer under the sheet, the screen and the Alia app ──
|
|
91
|
+
export * from './runtime';
|
|
92
|
+
|
|
93
|
+
// ── Read aloud and dictation (no call, no audio engine) ──
|
|
94
|
+
export { useTTS } from './hooks/useTTS';
|
|
95
|
+
export type { UseTTSOptions } from './hooks/useTTS';
|
|
96
|
+
export { useDictation, useDictationStore } from './hooks/useDictation';
|
|
97
|
+
export type { UseDictationOptions, DictationState } from './hooks/useDictation';
|
|
98
|
+
export { DictationError, requestTranscription } from './lib/dictation';
|
|
99
|
+
export type { DictationErrorCode, TranscriptionResult } from './lib/dictation';
|
|
100
|
+
export { VOICE_ERROR_MESSAGES } from './lib/speech-messages';
|
|
101
|
+
export type { VoiceErrorCode } from './lib/speech-messages';
|
|
102
|
+
export { SpeechClipError } from './lib/speech-synthesis';
|
|
103
|
+
export type { SpeechClipErrorCode } from './lib/speech-synthesis';
|
|
104
|
+
|
|
105
|
+
// ── Types ──
|
|
106
|
+
export type {
|
|
107
|
+
GemieAttachment,
|
|
108
|
+
GemieSuggestion,
|
|
109
|
+
ResearchProgress,
|
|
110
|
+
ResearchSource,
|
|
111
|
+
MessagePlan,
|
|
112
|
+
PlanStep,
|
|
113
|
+
} from './types';
|
|
114
|
+
|
|
115
|
+
// ── Voice: part of the conversation screen; the host brings callbacks (see `GemieVoiceOptions`) ──
|
|
116
|
+
export type { VoiceNotice, VoiceSessionProps, VoiceSessionState } from './types';
|
|
117
|
+
export { GemieVoiceCall } from './components/voice/GemieVoiceCall';
|
|
118
|
+
export { useVoiceLauncher, toastNotice } from './hooks/useVoiceLauncher';
|
|
119
|
+
export type { UseVoiceLauncherOptions, VoiceLauncher } from './hooks/useVoiceLauncher';
|
|
120
|
+
|
|
121
|
+
// ── UI Primitives (NativeWind) ──
|
|
122
|
+
export { cn, formatFileSize } from './lib/utils';
|
|
123
|
+
export { getToolLabel, getToolActiveLabel, getResearchActiveLabel } from './lib/tool-registry';
|
|
124
|
+
export { getTextFromContent, getImagesFromContent } from './lib/content-utils';
|
|
125
|
+
|
|
126
|
+
// ── The turn's work log: tool calls as Bloom's `WebSearch` and `TaskList` ──
|
|
127
|
+
export { isWebInvocation, taskListLog, webSearchLog } from './lib/work-log';
|
|
128
|
+
export type { LiveResearch, TaskListLog, WebSearchLog, WorkLogOptions } from './lib/work-log';
|
|
129
|
+
// The pure parts (call status, citations, tool labels, `Translate`) are `@gemies/sdk/tools`.
|
|
130
|
+
|
|
131
|
+
// ── Picker hooks ──
|
|
132
|
+
export { useImagePicker } from './hooks/useImagePicker';
|
|
133
|
+
export type { ImagePickerAsset } from './hooks/useImagePicker';
|
|
134
|
+
export { useDocumentPicker } from './hooks/useDocumentPicker';
|
|
135
|
+
export type { DocumentPickerResult } from './hooks/useDocumentPicker';
|
|
136
|
+
|
|
137
|
+
// ── Keyboard ──
|
|
138
|
+
export { KeyboardAwareScrollView, KeyboardAvoidingView, KeyboardProvider } from './lib/keyboard';
|
|
139
|
+
|
|
140
|
+
// ── Theme ──
|
|
141
|
+
export type { GemieColors } from './theme';
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { io, type Socket } from 'socket.io-client';
|
|
2
|
+
import type { GemieAvatarState } from '../components/GemieAvatar';
|
|
3
|
+
import { useGemieActivityStore } from './activity-store';
|
|
4
|
+
|
|
5
|
+
/** A run that goes quiet this long is over: a crashed run never says `idle`. */
|
|
6
|
+
export const ACTIVITY_QUIET_MS = 90_000;
|
|
7
|
+
/** Between tries after the server refuses a handshake (socket.io does not retry those itself). */
|
|
8
|
+
const RETRY_MS = 5_000;
|
|
9
|
+
|
|
10
|
+
const STATES: ReadonlySet<string> = new Set<GemieAvatarState>([
|
|
11
|
+
'idle',
|
|
12
|
+
'thinking',
|
|
13
|
+
'working',
|
|
14
|
+
'writing',
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
interface Connection {
|
|
18
|
+
socket: Socket;
|
|
19
|
+
refs: number;
|
|
20
|
+
quiet: Map<string, ReturnType<typeof setTimeout>>;
|
|
21
|
+
retry: ReturnType<typeof setTimeout> | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** One connection per API origin, however many buttons ask for it. */
|
|
25
|
+
const connections = new Map<string, Connection>();
|
|
26
|
+
|
|
27
|
+
function open(url: string, getToken: () => string | null): Connection {
|
|
28
|
+
const socket = io(url, {
|
|
29
|
+
transports: ['websocket'],
|
|
30
|
+
// Read on every (re)connect, so a rotated access token is the one that goes out.
|
|
31
|
+
auth: (cb) => cb({ token: getToken() }),
|
|
32
|
+
reconnection: true,
|
|
33
|
+
reconnectionAttempts: Infinity,
|
|
34
|
+
reconnectionDelay: 1000,
|
|
35
|
+
reconnectionDelayMax: 10_000,
|
|
36
|
+
});
|
|
37
|
+
const connection: Connection = { socket, refs: 0, quiet: new Map(), retry: null };
|
|
38
|
+
const store = useGemieActivityStore.getState;
|
|
39
|
+
|
|
40
|
+
const reset = (): void => {
|
|
41
|
+
for (const timer of connection.quiet.values()) clearTimeout(timer);
|
|
42
|
+
connection.quiet.clear();
|
|
43
|
+
store().clearRemote();
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
socket.on('connect', () => socket.emit('subscribe-alia-activity'));
|
|
47
|
+
// What happened while disconnected is unknown; a stale "working" is worse than idle.
|
|
48
|
+
socket.on('disconnect', reset);
|
|
49
|
+
socket.on('connect_error', () => {
|
|
50
|
+
// A refused handshake (no token yet, an expired one) ends the socket's own retrying.
|
|
51
|
+
if (socket.active || connection.retry !== null) return;
|
|
52
|
+
connection.retry = setTimeout(() => {
|
|
53
|
+
connection.retry = null;
|
|
54
|
+
socket.connect();
|
|
55
|
+
}, RETRY_MS);
|
|
56
|
+
});
|
|
57
|
+
socket.on('alia:activity', (event: unknown) => {
|
|
58
|
+
if (typeof event !== 'object' || event === null) return;
|
|
59
|
+
const { state, sessionId } = event as { state?: unknown; sessionId?: unknown };
|
|
60
|
+
if (typeof sessionId !== 'string' || typeof state !== 'string' || !STATES.has(state)) return;
|
|
61
|
+
const pending = connection.quiet.get(sessionId);
|
|
62
|
+
if (pending !== undefined) clearTimeout(pending);
|
|
63
|
+
connection.quiet.delete(sessionId);
|
|
64
|
+
store().setRemote(sessionId, state as GemieAvatarState);
|
|
65
|
+
if (state !== 'idle') {
|
|
66
|
+
connection.quiet.set(
|
|
67
|
+
sessionId,
|
|
68
|
+
setTimeout(() => {
|
|
69
|
+
connection.quiet.delete(sessionId);
|
|
70
|
+
store().setRemote(sessionId, 'idle');
|
|
71
|
+
}, ACTIVITY_QUIET_MS),
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return connection;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Listen for Alia's activity on the person's behalf. Every caller shares the one connection for
|
|
80
|
+
* `url`; the last to release closes it. Returns the release.
|
|
81
|
+
*/
|
|
82
|
+
export function acquireActivitySocket(url: string, getToken: () => string | null): () => void {
|
|
83
|
+
let held = connections.get(url);
|
|
84
|
+
if (!held) {
|
|
85
|
+
held = open(url, getToken);
|
|
86
|
+
connections.set(url, held);
|
|
87
|
+
}
|
|
88
|
+
const connection = held;
|
|
89
|
+
connection.refs++;
|
|
90
|
+
let released = false;
|
|
91
|
+
return () => {
|
|
92
|
+
if (released) return;
|
|
93
|
+
released = true;
|
|
94
|
+
if (--connection.refs > 0) return;
|
|
95
|
+
connections.delete(url);
|
|
96
|
+
if (connection.retry !== null) clearTimeout(connection.retry);
|
|
97
|
+
connection.socket.removeAllListeners();
|
|
98
|
+
connection.socket.disconnect();
|
|
99
|
+
for (const timer of connection.quiet.values()) clearTimeout(timer);
|
|
100
|
+
useGemieActivityStore.getState().clearRemote();
|
|
101
|
+
};
|
|
102
|
+
}
|