@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,1669 @@
1
+ import type { ComposerLoaderPhase } from '@oxy.so/bloom/composer-loader';
2
+ import { ASK_USER_QUESTION_TOOL } from '../tools';
3
+ import { useOxy } from '@oxy.so/services/ui/client';
4
+ import { useQueryClient } from '@tanstack/react-query';
5
+ import { useCallback, useEffect, useRef, useState } from 'react';
6
+ import { useLabels } from '../lib/labels';
7
+ import { useGemieApi } from './api';
8
+ import { useAppAssertionHeaders } from './app-assertion';
9
+ import { type GemieArtifact, useGemieRuntime } from './config';
10
+ import {
11
+ errorCode,
12
+ errorMessage as getErrorMessage,
13
+ errorName,
14
+ errorStatus,
15
+ readErrorResponseBody,
16
+ } from './error-utils';
17
+ import { agentMessageId, buildOutboundMessages, isAgentMessageOf } from './message-history';
18
+ import { gemieQueryKeys } from './query-keys';
19
+ import {
20
+ applyRoomEvent,
21
+ claimConsult,
22
+ createRoomLedger,
23
+ isRoomOwned,
24
+ releaseConsult,
25
+ type RoomLedger,
26
+ } from './room-events';
27
+ import { createRandomUuid } from './random-uuid';
28
+ import { createChatTurnControl } from './chat-turn-control';
29
+ import { awaitTurnPreparation } from './turn-preparation';
30
+ import { type GemieHostTools, HostOutcomeQueue, hostRequest } from './host-tools';
31
+ import { API_ROUTES } from './routes';
32
+ import { createSseFrameReader } from './sse-frame-reader';
33
+ import {
34
+ type ConsultEvent,
35
+ lockedFeatureOf,
36
+ parseConsultEvent,
37
+ parseHostAction,
38
+ } from './stream-events';
39
+ import { hasUsableStreamOutput, type StreamOutputEvidence } from './stream-outcome';
40
+ import { failureDetail, readGemieMeta, type FailedTurn } from './turn-failure';
41
+ import type {
42
+ AgentRun,
43
+ Conversation,
44
+ ConversationsInfiniteData,
45
+ Message,
46
+ SendOptions,
47
+ ToolInvocation,
48
+ } from './types';
49
+ import { UsageLimitError } from './usage-limit-error';
50
+
51
+ export type { ToolInvocation };
52
+ export type { FailedTurn };
53
+
54
+ /**
55
+ * How a send ended.
56
+ *
57
+ * - `sent`: the turn got an answer, or at least real output. It may STILL
58
+ * carry a `failedTurn` — a stream that produced output and then a
59
+ * synthetic tail keeps the output and shows the tail as an error.
60
+ * - `errored`: no answer, and the person's turn is KEPT in the thread with
61
+ * `failedTurn` attached, retry and all. The caller has nothing to restore.
62
+ * - `failed`: the turn was rolled back to what the list was before the send,
63
+ * so the caller hands the text back to the composer. Only the usage-limit
64
+ * errors end this way now: they open a dialog of their own, and a retry
65
+ * would be the wrong offer next to "upgrade" or "wait".
66
+ * - `aborted`: the person stopped it; partial output is theirs to keep.
67
+ */
68
+ export type SendOutcome = 'sent' | 'errored' | 'failed' | 'aborted';
69
+
70
+ /** Shape of an error body thrown by the streaming fetch (rate-limit / credit info). */
71
+ interface ThrownErrorBody {
72
+ code?: string;
73
+ message?: string;
74
+ retryable?: boolean;
75
+ retryAfter?: number;
76
+ /** Alia's run id, on a turn that failed after the stream began. */
77
+ reference?: string;
78
+ suggestedAction?: 'wait' | 'upgrade';
79
+ }
80
+
81
+ /** Structured `error` object the server may embed in a non-OK response / SSE error event. */
82
+ interface StreamErrorObject {
83
+ code?: string;
84
+ message?: string;
85
+ retryable?: boolean;
86
+ retryAfter?: number;
87
+ suggestedAction?: 'wait' | 'upgrade';
88
+ type?: string;
89
+ /** Alia's run id, on a turn that failed (before any output or part-way). */
90
+ reference?: string;
91
+ details?: {
92
+ limitType?: string;
93
+ current?: number;
94
+ limit?: number;
95
+ tier?: string;
96
+ };
97
+ }
98
+
99
+ /** Non-OK response body read from the stream before the SSE loop starts. */
100
+ interface StreamErrorResponse {
101
+ error?: StreamErrorObject | string;
102
+ details?: unknown;
103
+ }
104
+
105
+ /**
106
+ * The artifact a tool result carries, if it carries one: a generated file, or
107
+ * an `artifact` object a tool returned for its own panel.
108
+ */
109
+ function artifactOf(
110
+ toolCallId: string,
111
+ name: string | undefined,
112
+ output: unknown,
113
+ ): GemieArtifact | null {
114
+ if (output === null || typeof output !== 'object') return null;
115
+ // Structural per-tool output, read the way the tools write it.
116
+ const result = output as Record<string, any>;
117
+ if (name === 'generateFile') {
118
+ const type = result.language ? 'code' : 'markdown';
119
+ return {
120
+ id: toolCallId,
121
+ type,
122
+ content:
123
+ type === 'code'
124
+ ? { language: result.language, code: result.content }
125
+ : { content: result.content },
126
+ title: result.filename || result.title || 'Generated file',
127
+ timestamp: Date.now(),
128
+ };
129
+ }
130
+ if (result.artifact) {
131
+ const a = result.artifact;
132
+ return {
133
+ id: toolCallId,
134
+ type: a.type || 'markdown',
135
+ content: a.data || a.content || a,
136
+ title: a.title || name || 'Artifact',
137
+ timestamp: Date.now(),
138
+ };
139
+ }
140
+ return null;
141
+ }
142
+
143
+ export interface UseConversationStreamOptions {
144
+ /** The conversation the turns belong to; omitted, the server makes the turn's own. */
145
+ conversationId?: string;
146
+ /** The power level (or a device model) every turn is sent with. */
147
+ model?: string;
148
+ /** The agent this conversation is with — its lead — when it is not Alia. */
149
+ agentId?: string | null;
150
+ /**
151
+ * The UI effects the host's client performs (`docs/agent-embedding.md` §2): declared with every
152
+ * request, performed once when the stream asks, and their outcomes sent with the next request.
153
+ */
154
+ hostTools?: GemieHostTools;
155
+ /**
156
+ * What the host app is, for Alia to know where the person is ("Notes — viewing note #42").
157
+ * Sent as the request's leading system message, which the server reads as client context.
158
+ */
159
+ clientContext?: string;
160
+ /**
161
+ * Which consultation each message draws, shared with the room's socket events (`use-room-events.ts`)
162
+ * so a member's reply that both the request and the socket carry is drawn once.
163
+ */
164
+ room?: RoomLedger;
165
+ }
166
+
167
+ /** The typed end the chat request gives a member still speaking when it closes (ADR 0025). */
168
+ const ROOM_CONTINUES = 'room_continues';
169
+
170
+ /** The words a message holds, as text: a consulted agent's reply is plain text as it streams. */
171
+ function messageWords(message: Message): string {
172
+ return typeof message.content === 'string' ? message.content : '';
173
+ }
174
+
175
+ export function useConversationStream({
176
+ conversationId,
177
+ model,
178
+ agentId,
179
+ clientContext,
180
+ hostTools,
181
+ room,
182
+ }: UseConversationStreamOptions = {}) {
183
+ const { apiUrl, streamFetch, host, app } = useGemieRuntime();
184
+ /** Where an awaited host action's answer goes: the same account and app assertion as the turn. */
185
+ const api = useGemieApi();
186
+ /** Read at send time and when an action arrives: the host's declaration may change between turns. */
187
+ const hostToolsRef = useRef(hostTools);
188
+ hostToolsRef.current = hostTools;
189
+ const appRef = useRef(app);
190
+ appRef.current = app;
191
+ const ownRoomRef = useRef<RoomLedger | null>(null);
192
+ ownRoomRef.current ??= createRoomLedger();
193
+ const roomRef = useRef<RoomLedger>(ownRoomRef.current);
194
+ roomRef.current = room ?? ownRoomRef.current;
195
+ /** This conversation's host actions: performed once, their outcomes held until a request carries them. */
196
+ const hostOutcomesRef = useRef(new HostOutcomeQueue());
197
+ const labels = useLabels();
198
+ const [messages, setMessages] = useState<Message[]>([]);
199
+ const [isLoading, setIsLoading] = useState(false);
200
+ const [composerPhase, setComposerPhaseState] = useState<ComposerLoaderPhase>('idle');
201
+ const composerPhaseRef = useRef<ComposerLoaderPhase>('idle');
202
+ const setComposerPhase = useCallback((phase: ComposerLoaderPhase) => {
203
+ composerPhaseRef.current = phase;
204
+ setComposerPhaseState(phase);
205
+ }, []);
206
+ const [error, setError] = useState<Error | null>(null);
207
+ const [conversationTitle, setConversationTitle] = useState<string | null>(null);
208
+ /**
209
+ * The agent proposing that the next stretch of the thread start fresh, or
210
+ * `null` for none.
211
+ *
212
+ * The `reason` is the model's own sentence, in the model's own words. It is
213
+ * carried through untouched so the offer can say WHY instead of appearing as
214
+ * a button with no context.
215
+ *
216
+ * At most one is ever in flight: the server bounds it to one per turn and a
217
+ * later one replaces an unanswered earlier one, so there is nothing to
218
+ * collapse here. And nothing has been written when it arrives — the tool that
219
+ * emits it creates nothing — so ignoring it leaves the thread exactly as it
220
+ * was.
221
+ */
222
+ const [suggestedNewConversation, setSuggestedNewConversation] = useState<string | null>(null);
223
+ /** The run a delegated agent started for this conversation (`alia.agent_turn`), or `null`. */
224
+ const [agentRun, setAgentRun] = useState<AgentRun | null>(null);
225
+ /**
226
+ * The turn that got no answer, drawn in the thread with an error and a
227
+ * retry — or `null`. See `turn-failure.ts` for why a
228
+ * failure is kept rather than rolled back, and what the server persisted
229
+ * (nothing) that makes a plain re-send safe.
230
+ */
231
+ const [failedTurn, setFailedTurn] = useState<FailedTurn | null>(null);
232
+ /** What a retry re-sends: the same content and attachments, the same options. */
233
+ const retryRef = useRef<{
234
+ message: Omit<Message, 'id'>;
235
+ options?: SendOptions;
236
+ userMessageId: string;
237
+ } | null>(null);
238
+ /**
239
+ * The connector and skills each user turn was sent with, by its id, so an
240
+ * edit or a regenerate sends it the way it was sent (#608 §6). A message
241
+ * does not carry them and the server does not return them, so this is only
242
+ * known for turns sent while this screen was open.
243
+ */
244
+ const turnOptionsRef = useRef(new Map<string, Pick<SendOptions, 'mcpServerId' | 'skillNames'>>());
245
+ const { oxyServices, user } = useOxy();
246
+ const appAssertionHeaders = useAppAssertionHeaders();
247
+ const queryClient = useQueryClient();
248
+ const abortControllerRef = useRef<AbortController | null>(null);
249
+ const turnControlRef = useRef<ReturnType<typeof createChatTurnControl> | null>(null);
250
+ // A Stop acknowledgement can outlive its stream, thread, or the next send.
251
+ const turnGenerationRef = useRef(0);
252
+
253
+ // Batching refs: accumulate streaming text and flush at ~20fps instead of per-chunk
254
+ const pendingContentRef = useRef('');
255
+ const pendingReasoningRef = useRef('');
256
+ /** A consulted agent's streamed words, by the id of the message they belong to. */
257
+ const pendingAgentContentRef = useRef(new Map<string, string>());
258
+ const flushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
259
+
260
+ const flushPendingUpdates = useCallback(() => {
261
+ const content = pendingContentRef.current;
262
+ const reasoning = pendingReasoningRef.current;
263
+ const agentContent = pendingAgentContentRef.current;
264
+ if (!content && !reasoning && agentContent.size === 0) return;
265
+
266
+ pendingContentRef.current = '';
267
+ pendingReasoningRef.current = '';
268
+ pendingAgentContentRef.current = new Map();
269
+
270
+ setMessages((prev) => {
271
+ const updated = prev.map((message) => {
272
+ const words = agentContent.get(message.id);
273
+ return words === undefined
274
+ ? message
275
+ : { ...message, content: messageWords(message) + words };
276
+ });
277
+ const lastMessage = updated[updated.length - 1];
278
+ if (lastMessage?.role === 'assistant' && (content || reasoning)) {
279
+ const changes: Partial<Message> = {};
280
+ if (content) changes.content = lastMessage.content + content;
281
+ if (reasoning) changes.thinking = (lastMessage.thinking || '') + reasoning;
282
+ updated[updated.length - 1] = { ...lastMessage, ...changes };
283
+ }
284
+ return updated;
285
+ });
286
+ }, []);
287
+
288
+ /** Drop everything still batched: the turn it belonged to is being undone. */
289
+ const dropPendingUpdates = useCallback(() => {
290
+ pendingContentRef.current = '';
291
+ pendingReasoningRef.current = '';
292
+ pendingAgentContentRef.current = new Map();
293
+ if (flushTimerRef.current) {
294
+ clearTimeout(flushTimerRef.current);
295
+ flushTimerRef.current = null;
296
+ }
297
+ }, []);
298
+
299
+ const scheduleFlush = useCallback(() => {
300
+ if (flushTimerRef.current) return;
301
+ flushTimerRef.current = setTimeout(() => {
302
+ flushTimerRef.current = null;
303
+ flushPendingUpdates();
304
+ }, 50);
305
+ }, [flushPendingUpdates]);
306
+
307
+ /** Whether this thread is on screen: a turn that outlives it ends without `onTurnEnd`. */
308
+ const mountedRef = useRef(false);
309
+
310
+ // Mounted, a turn that ends is announced (`onTurnEnd`); unmounting flushes and clears the timer.
311
+ useEffect(() => {
312
+ mountedRef.current = true;
313
+ return () => {
314
+ mountedRef.current = false;
315
+ turnGenerationRef.current++;
316
+ turnControlRef.current = null;
317
+ flushPendingUpdates();
318
+ if (flushTimerRef.current) {
319
+ clearTimeout(flushTimerRef.current);
320
+ flushTimerRef.current = null;
321
+ }
322
+ };
323
+ }, [flushPendingUpdates]);
324
+
325
+ // Ref to avoid messages in append's dep array (avoids recreation every 50ms during streaming)
326
+ // Synced both via useEffect (for streaming updates) and eagerly in setMessagesAndRef
327
+ // so that setMessages + append in the same tick see the correct history.
328
+ const messagesRef = useRef<Message[]>([]);
329
+ useEffect(() => {
330
+ messagesRef.current = messages;
331
+ }, [messages]);
332
+
333
+ // Wrapper that eagerly syncs messagesRef before React re-renders,
334
+ // so append() called in the same tick reads truncated history (e.g. editMessage).
335
+ const setMessagesAndRef = useCallback((update: Message[] | ((prev: Message[]) => Message[])) => {
336
+ if (typeof update === 'function') {
337
+ setMessages((prev) => {
338
+ const next = update(prev);
339
+ messagesRef.current = next;
340
+ return next;
341
+ });
342
+ } else {
343
+ messagesRef.current = update;
344
+ setMessages(update);
345
+ }
346
+ }, []);
347
+
348
+ /**
349
+ * A different conversation is a different thread: a failure from the last
350
+ * one must not be drawn under a message in this one.
351
+ */
352
+ const conversationRef = useRef(conversationId);
353
+ useEffect(() => {
354
+ setFailedTurn(null);
355
+ retryRef.current = null;
356
+ turnOptionsRef.current.clear();
357
+ // Outcomes answer this conversation's calls. The first turn of a new chat gives it its id,
358
+ // which is the same conversation; any other change is a different one.
359
+ const was = conversationRef.current;
360
+ conversationRef.current = conversationId;
361
+ if (was !== undefined && was !== conversationId) {
362
+ turnGenerationRef.current++;
363
+ turnControlRef.current = null;
364
+ hostOutcomesRef.current.clear();
365
+ // The reply still streaming belongs to the thread that was left: cut it, drop what it had
366
+ // batched (it would land on this thread's last message) and let the screen be idle.
367
+ abortControllerRef.current?.abort();
368
+ abortControllerRef.current = null;
369
+ dropPendingUpdates();
370
+ setIsLoading(false);
371
+ setComposerPhase('idle');
372
+ }
373
+ }, [conversationId, dropPendingUpdates, setComposerPhase]);
374
+
375
+ /**
376
+ * A different account is a different person: the thread on screen is not
377
+ * theirs.
378
+ *
379
+ * The new-chat screen stays mounted across a sign-out or a switch, and in
380
+ * ghost mode its thread exists nowhere but here — so without this the next
381
+ * person to sit down saw the previous one's conversation, and a reply still
382
+ * streaming kept writing into it. The stream is cut and the thread emptied.
383
+ * Signing IN from signed-out keeps what is there: nobody else owned it.
384
+ */
385
+ const accountId = user?.id ?? null;
386
+ const accountRef = useRef(accountId);
387
+ useEffect(() => {
388
+ const was = accountRef.current;
389
+ accountRef.current = accountId;
390
+ if (was === null || was === accountId) return;
391
+ turnGenerationRef.current++;
392
+ turnControlRef.current = null;
393
+ abortControllerRef.current?.abort();
394
+ abortControllerRef.current = null;
395
+ dropPendingUpdates();
396
+ hostOutcomesRef.current.clear();
397
+ setMessagesAndRef([]);
398
+ setIsLoading(false);
399
+ setComposerPhase('idle');
400
+ setError(null);
401
+ setConversationTitle(null);
402
+ setSuggestedNewConversation(null);
403
+ setAgentRun(null);
404
+ setFailedTurn(null);
405
+ retryRef.current = null;
406
+ turnOptionsRef.current.clear();
407
+ }, [accountId, setMessagesAndRef, dropPendingUpdates, setComposerPhase]);
408
+
409
+ const append = useCallback(
410
+ async (message: Omit<Message, 'id'>, options?: SendOptions): Promise<SendOutcome> => {
411
+ const turnGeneration = ++turnGenerationRef.current;
412
+ setIsLoading(true);
413
+ setComposerPhase('submitting');
414
+ setError(null);
415
+ // A new send answers the old failure, whether it is the retry or a fresh
416
+ // message: either way the card comes down.
417
+ setFailedTurn(null);
418
+ retryRef.current = null;
419
+
420
+ // Everything the send is about to change, so a turn that produces no real
421
+ // output can be undone in one step: the user message, the assistant
422
+ // placeholder, and any history editMessage truncated just before this call.
423
+ const snapshot = messagesRef.current;
424
+
425
+ // Only content the model actually produced counts. The server answers a
426
+ // dead provider, a mid-stream break or a global timeout with HTTP 200 and a
427
+ // stand-in message flagged `alia_meta.synthetic` — that is a failed send
428
+ // wearing a reply's clothes.
429
+ const outputEvidence: StreamOutputEvidence = {
430
+ realOutputChars: 0,
431
+ agentOutputChars: 0,
432
+ durableArtifactCount: 0,
433
+ toolInvocationCount: 0,
434
+ };
435
+
436
+ const rollback = (): SendOutcome => {
437
+ // Drop anything still batched first: flushPendingUpdates appends to
438
+ // whichever message is last, so a buffered fragment surviving the restore
439
+ // would land on the previous turn's reply.
440
+ dropPendingUpdates();
441
+ setMessagesAndRef(snapshot);
442
+ return 'failed';
443
+ };
444
+
445
+ /** Keep a half-streamed turn — destroying real output is worse than showing the error. */
446
+ const settleError = (): SendOutcome => {
447
+ // A room stores the person's message before selecting or running a member.
448
+ // A later credit/gate refusal cannot roll that stored question back locally.
449
+ if (isGroupTurn) return keepFailedTurn(false);
450
+ if (!hasUsableStreamOutput(outputEvidence)) return rollback();
451
+ settleAssistant('failed');
452
+ return 'sent';
453
+ };
454
+
455
+ /**
456
+ * The server's stand-in for an answer it could not get, if one arrived.
457
+ *
458
+ * Its content is NEVER appended: "all models are busy" rendered under
459
+ * Alia's mark is Alia declining, and it is the one thing this must not
460
+ * read as. The flag is remembered here and answered when the stream ends.
461
+ */
462
+ let syntheticTail: { retryable: boolean; detail?: string } | null = null;
463
+ /** The reply's text as the model produced it: what the host previews when the turn settles. */
464
+ let replyText = '';
465
+ // A room can deliberately remain quiet. Only its server frame establishes this,
466
+ // never a lack of output or an agent's prose.
467
+ let isGroupTurn = false;
468
+
469
+ /**
470
+ * Keep the person's turn, and hang the failure on it.
471
+ *
472
+ * With no real output the empty assistant placeholder comes out — an
473
+ * empty bubble under a thinking indicator would say an answer is still
474
+ * coming — and the user message stays where it was sent, with the error
475
+ * drawn under it. With real output, everything stays and the error is
476
+ * drawn under the answer as its tail. Either way what a retry needs is
477
+ * parked in `retryRef`, and the whole thing is one state update.
478
+ */
479
+ const keepFailedTurn = (retryable: boolean, detail?: string): SendOutcome => {
480
+ setComposerPhase('error');
481
+ const partial = hasUsableStreamOutput(outputEvidence);
482
+ if (partial) {
483
+ // The output is kept, so what is still batched is part of it: an
484
+ // in-stream error frame can land inside one flush window, and dropping
485
+ // the buffer drew the "interrupted" card under an empty bubble.
486
+ flushPendingUpdates();
487
+ } else {
488
+ dropPendingUpdates();
489
+ }
490
+ if (!partial) {
491
+ // The updater form, on purpose: the user row and the placeholder went
492
+ // in through plain `setMessages` calls that may not have rendered yet
493
+ // when a very fast failure lands, so `messagesRef` can still hold the
494
+ // pre-send snapshot here. `prev` is always the queue's own truth.
495
+ setMessagesAndRef((prev) => prev.filter((m) => m.id !== assistantMessage.id));
496
+ }
497
+ settleAssistant('failed');
498
+ retryRef.current = { message, options, userMessageId: userMessage.id };
499
+ setFailedTurn({
500
+ userMessageId: userMessage.id,
501
+ anchorMessageId: partial && !isGroupTurn ? assistantMessage.id : userMessage.id,
502
+ retryable,
503
+ partial,
504
+ detail,
505
+ });
506
+ return partial ? 'sent' : 'errored';
507
+ };
508
+
509
+ /**
510
+ * Stamped here, not on the way back: a thread left open across midnight has
511
+ * to draw its date line as the turn happens, and the server's own stamp only
512
+ * arrives with the next full load. `POST /conversations` already accepts a
513
+ * client `createdAt`, so this is the value that persists too.
514
+ */
515
+ const userMessage: Message = {
516
+ ...message,
517
+ id: createRandomUuid(),
518
+ createdAt: new Date().toISOString(),
519
+ unsaved: true,
520
+ };
521
+ if (options !== undefined) {
522
+ turnOptionsRef.current.set(userMessage.id, {
523
+ mcpServerId: options.mcpServerId,
524
+ skillNames: options.skillNames,
525
+ });
526
+ }
527
+ // Build from the pre-send snapshot before any await. The optimistic user
528
+ // row and assistant placeholder may reach messagesRef while device info is
529
+ // collected; reading the ref afterwards used to send both plus userMessage
530
+ // again, persisting user -> empty assistant -> duplicate user.
531
+ const history = buildOutboundMessages(snapshot, userMessage);
532
+ const messagesToSend = clientContext
533
+ ? [{ id: 'client-context', role: 'system', content: clientContext }, ...history]
534
+ : history;
535
+ setMessages((prev) => [...prev, userMessage]);
536
+ // The sidebar's row for this agent, immediately — this is the half that
537
+ // makes sending feel like a chat list rather than a form.
538
+ host.onTurnPreview?.(agentId, typeof message.content === 'string' ? message.content : '');
539
+
540
+ // Create assistant message placeholder. `isStreaming` is the turn's own
541
+ // lifecycle stamp: the thought panel reads "still running" from it rather
542
+ // than from whether the message has text yet, and `settleAssistant` below
543
+ // clears it however the stream ends.
544
+ const assistantMessage: Message = {
545
+ id: createRandomUuid(),
546
+ role: 'assistant',
547
+ content: '',
548
+ toolInvocations: [],
549
+ createdAt: new Date().toISOString(),
550
+ isStreaming: true,
551
+ unsaved: true,
552
+ };
553
+ setMessages((prev) => [...prev, assistantMessage]);
554
+ /** How many agents the lead has consulted in this turn: the next one's `agentMessageId` index. */
555
+ let agentAnswers = 0;
556
+ const nextAgentMessageId = (): string => agentMessageId(assistantMessage.id, agentAnswers++);
557
+ /** Each consultation of this turn, by `consultId`: the message its agent writes into. */
558
+ const consults = new Map<string, string>();
559
+ /** Whether `id` names a message this turn wrote: the question, the reply, an agent's answer. */
560
+ const isThisTurn = (id: string): boolean =>
561
+ id === userMessage.id ||
562
+ id === assistantMessage.id ||
563
+ isAgentMessageOf(id, assistantMessage.id) ||
564
+ (isGroupTurn && [...consults.values()].includes(id));
565
+
566
+ /**
567
+ * End the assistant message's turn, once.
568
+ *
569
+ * Only a message still marked streaming is touched: the error paths settle
570
+ * it as `failed` before returning, and the `finally` that runs after them
571
+ * must not re-settle it as completed or cancelled. Through the updater,
572
+ * so it lands after every batched content flush queued before it.
573
+ */
574
+ let settled = false;
575
+ const settleAssistant = (outcome: NonNullable<Message['turnOutcome']>): void => {
576
+ if (settled) return;
577
+ settled = true;
578
+ setMessages((prev) => {
579
+ if (
580
+ !isGroupTurn &&
581
+ prev.find((m) => m.id === assistantMessage.id)?.isStreaming !== true
582
+ ) {
583
+ return prev;
584
+ }
585
+ // A turn that completed is one the server has stored, under these ids.
586
+ const stored = outcome === 'completed';
587
+ return prev.map((m) => {
588
+ // A consultation still open when the turn ends ends with it.
589
+ const settles =
590
+ m.id === assistantMessage.id ||
591
+ (m.isStreaming === true && isThisTurn(m.id) && !isRoomOwned(roomRef.current, m.id));
592
+ let next = settles ? { ...m, isStreaming: false, turnOutcome: outcome } : m;
593
+ if (stored && next.unsaved === true && isThisTurn(next.id)) {
594
+ const { unsaved: _unsaved, ...rest } = next;
595
+ next = rest;
596
+ }
597
+ return next;
598
+ });
599
+ });
600
+ };
601
+
602
+ /** What a consult frame does to the thread: the agent's own message, from start to end. */
603
+ const applyConsult = (event: ConsultEvent): void => {
604
+ if (event.type === 'start') {
605
+ if (consults.has(event.consultId) || roomRef.current.discarded.has(event.consultId))
606
+ return;
607
+ const id = nextAgentMessageId();
608
+ consults.set(event.consultId, id);
609
+ // The room's socket may have drawn this member typing already: that is its message.
610
+ const adopted = claimConsult(roomRef.current, event.consultId, id);
611
+ if (adopted !== null) {
612
+ consults.set(event.consultId, adopted);
613
+ if (!roomRef.current.ended.has(event.consultId)) {
614
+ setMessages((prev) =>
615
+ prev.map((m) => (m.id === adopted ? { ...m, content: '' } : m)),
616
+ );
617
+ }
618
+ return;
619
+ }
620
+ const agentMessage: Message = {
621
+ id,
622
+ unsaved: true,
623
+ role: 'assistant',
624
+ content: '',
625
+ toolInvocations: [],
626
+ createdAt: new Date().toISOString(),
627
+ isStreaming: true,
628
+ agentInfo: { ...event.agent },
629
+ };
630
+ // Above the lead's own reply, which is still being written under it.
631
+ setMessages((prev) => {
632
+ const at = prev.findIndex((m) => m.id === assistantMessage.id);
633
+ return at < 0
634
+ ? [...prev, agentMessage]
635
+ : [...prev.slice(0, at), agentMessage, ...prev.slice(at)];
636
+ });
637
+ return;
638
+ }
639
+ const id = consults.get(event.consultId);
640
+ if (id === undefined || roomRef.current.discarded.has(event.consultId)) return;
641
+ if (
642
+ roomRef.current.ended.has(event.consultId) &&
643
+ !(event.type === 'end' && event.status === 'completed' && event.messageId !== undefined)
644
+ )
645
+ return;
646
+ if (event.type === 'delta') {
647
+ if (event.content === '') return;
648
+ outputEvidence.agentOutputChars += event.content.length;
649
+ const map = pendingAgentContentRef.current;
650
+ map.set(id, (map.get(id) ?? '') + event.content);
651
+ scheduleFlush();
652
+ return;
653
+ }
654
+ if (event.type === 'tool') {
655
+ if (event.phase === 'call') outputEvidence.toolInvocationCount += 1;
656
+ setMessages((prev) =>
657
+ prev.map((m) => {
658
+ if (m.id !== id) return m;
659
+ const invocations = [...(m.toolInvocations ?? [])];
660
+ const at = invocations.findIndex((call) => call.toolCallId === event.toolCallId);
661
+ const previous = at < 0 ? undefined : invocations[at];
662
+ const invocation: ToolInvocation = {
663
+ toolCallId: event.toolCallId,
664
+ toolName: event.name,
665
+ state: event.phase,
666
+ args: event.input ?? previous?.args,
667
+ ...(event.phase === 'result' ? { result: event.output } : {}),
668
+ };
669
+ if (at < 0) invocations.push(invocation);
670
+ else invocations[at] = invocation;
671
+ return { ...m, toolInvocations: invocations };
672
+ }),
673
+ );
674
+ return;
675
+ }
676
+ // The end: what was streamed lands first, then the agent's final words, if it sent them.
677
+ flushPendingUpdates();
678
+ if (event.errorCode === ROOM_CONTINUES) {
679
+ // The request is over but the member is still speaking: the room's socket carries it on.
680
+ // With no socket to carry it, it stops here, unfinished but not failed.
681
+ if (host.subscribeRoomEvents) releaseConsult(roomRef.current, event.consultId);
682
+ else {
683
+ setMessages((prev) =>
684
+ prev.map((m) => (m.id === id ? { ...m, isStreaming: false } : m)),
685
+ );
686
+ }
687
+ return;
688
+ }
689
+ if (isGroupTurn && event.errorCode === 'agent_declined') {
690
+ // A superseded room reply was never stored. Drop its provisional text
691
+ // across both transports instead of presenting it as a failed saved reply.
692
+ roomRef.current.ended.add(event.consultId);
693
+ roomRef.current.discarded.add(event.consultId);
694
+ setMessages((prev) => prev.filter((m) => m.id !== id));
695
+ return;
696
+ }
697
+ if (event.content !== undefined) outputEvidence.agentOutputChars += event.content.length;
698
+ if (isGroupTurn && event.status === 'completed' && event.messageId !== undefined) {
699
+ roomRef.current.ended.add(event.consultId);
700
+ consults.set(event.consultId, event.messageId);
701
+ setMessages((prev) =>
702
+ applyRoomEvent(prev, roomRef.current, conversationId ?? '', {
703
+ conversationId: conversationId ?? '',
704
+ event: 'alia.agent_end',
705
+ data: {
706
+ consultId: event.consultId,
707
+ status: event.status,
708
+ content: event.content,
709
+ messageId: event.messageId,
710
+ },
711
+ }),
712
+ );
713
+ return;
714
+ }
715
+ if (isGroupTurn) roomRef.current.ended.add(event.consultId);
716
+ setMessages((prev) =>
717
+ prev.map((m) =>
718
+ m.id !== id
719
+ ? m
720
+ : {
721
+ ...m,
722
+ ...(event.content === undefined ? {} : { content: event.content }),
723
+ isStreaming: false,
724
+ turnOutcome: event.status === 'completed' ? 'completed' : 'failed',
725
+ },
726
+ ),
727
+ );
728
+ };
729
+
730
+ /** The request's own controller: `finally` asks it whether the person stopped the turn. */
731
+ let controller: AbortController | null = null;
732
+ let linked: ReturnType<typeof oxyServices.createLinkedClient> | null = null;
733
+ let turnControl: ReturnType<typeof createChatTurnControl> | null = null;
734
+ /** Cut THIS turn's stream. Never the ref's: by now it may hold a later turn's controller. */
735
+ const abortThisTurn = (): void => {
736
+ controller?.abort();
737
+ if (abortControllerRef.current === controller) abortControllerRef.current = null;
738
+ };
739
+
740
+ try {
741
+ // Create the abort controller before the first await, so `stop()` and an account or
742
+ // conversation change reach a turn that is still collecting device info.
743
+ controller = new AbortController();
744
+ abortControllerRef.current = controller;
745
+ linked = oxyServices.createLinkedClient({ baseURL: apiUrl });
746
+ const assertion = appAssertionHeaders();
747
+ turnControl = createChatTurnControl(linked, assertion, conversationId, controller);
748
+ turnControlRef.current = turnControl;
749
+
750
+ // Attach both rejection handlers immediately; a slow host must not leave
751
+ // an already rejected surface assertion unobserved or defeat detachment.
752
+ const [appAssertion, deviceInfo] = await awaitTurnPreparation(
753
+ Promise.all([assertion, host.deviceInfo ? host.deviceInfo() : undefined]),
754
+ controller.signal,
755
+ );
756
+ if (controller.signal.aborted) return 'aborted';
757
+
758
+ /**
759
+ * Read at send time rather than closed over: the capability switches
760
+ * live in a menu that stays open across a send, and a value captured
761
+ * when the callback was built would send the state the composer had
762
+ * before the person touched it.
763
+ */
764
+ const { deepResearch: deepResearchMode, personalization } = host.turnRequest?.() ?? {};
765
+
766
+ // The host's tools, and the outcomes of the actions it performed since the last request.
767
+ const outcomes = hostOutcomesRef.current.pending();
768
+ const hostMember = hostRequest(appRef.current, hostToolsRef.current, outcomes);
769
+
770
+ // Authentication, the preflight refresh and the single 401 replay belong
771
+ // to the linked Oxy client; this layer never reads or writes a bearer.
772
+ // Which Oxy app this turn is in (ADR 0021): an agent Oxy confines to an app opens only there.
773
+ if (controller.signal.aborted) return 'aborted';
774
+ const response = await linked.client.requestAuthenticatedResponse({
775
+ method: 'POST',
776
+ url: API_ROUTES.chat,
777
+ headers: {
778
+ ...appAssertion,
779
+ Accept: 'text/event-stream',
780
+ 'Content-Type': 'application/json',
781
+ ...(deviceInfo === undefined ? {} : { 'X-Device-Info': JSON.stringify(deviceInfo) }),
782
+ },
783
+ body: JSON.stringify({
784
+ turnId: turnControl.id,
785
+ messages: messagesToSend,
786
+ // The reply is stored under the id it is drawn under here, so a vote
787
+ // or a read-aloud on it needs no reload to find it.
788
+ assistantMessageId: assistantMessage.id,
789
+ stream: true,
790
+ ...(conversationId && { conversationId }),
791
+ // Only sent when OFF: absent is the server's default.
792
+ ...(personalization === false && { personalization: false }),
793
+ // The power level (or a device model). Oxy picks the model of that
794
+ // level; the client never names a hosted model.
795
+ ...(model && { model }),
796
+ ...(options?.skillNames?.length ? { skillIds: options.skillNames } : {}),
797
+ ...(agentId && { agentId }),
798
+ ...(deepResearchMode && { deepResearch: true }),
799
+ ...(options?.mcpServerId === undefined ? {} : { mcpServerId: options.mcpServerId }),
800
+ ...(hostMember === undefined ? {} : { host: hostMember }),
801
+ }),
802
+ signal: controller.signal,
803
+ ...(streamFetch ? { fetch: streamFetch } : {}),
804
+ });
805
+
806
+ if (!response.ok) {
807
+ const errorData = (await readErrorResponseBody(response)) as StreamErrorResponse | null;
808
+
809
+ // An agent's feature gate refused the turn: the host shows its own upsell, and the
810
+ // person's words go back to the composer for after.
811
+ const lockedFeature = lockedFeatureOf(
812
+ errorData?.error && typeof errorData.error === 'object' ? errorData.error : null,
813
+ );
814
+ if (errorCode(errorData?.error) === 'turn_cancelled') {
815
+ flushPendingUpdates();
816
+ settleAssistant('cancelled');
817
+ abortThisTurn();
818
+ return 'aborted';
819
+ }
820
+ if (lockedFeature !== null) {
821
+ host.onFeatureLocked?.(lockedFeature);
822
+ return rollback();
823
+ }
824
+
825
+ // Detect usage limit errors (429 rate limit, 402 insufficient credits, 403 model access)
826
+ if (response.status === 429 || response.status === 402 || response.status === 403) {
827
+ const errObj =
828
+ errorData?.error && typeof errorData.error === 'object' ? errorData.error : null;
829
+ const isModelAccess = response.status === 403 && errObj?.code === 'MODEL_NOT_IN_PLAN';
830
+ const isCredits = response.status === 402 || errObj?.code === 'INSUFFICIENT_CREDITS';
831
+
832
+ if (isModelAccess || isCredits || response.status === 429) {
833
+ throw new UsageLimitError({
834
+ type: isModelAccess ? 'model_access' : isCredits ? 'credits' : 'rate_limit',
835
+ code:
836
+ errObj?.code ||
837
+ (isModelAccess
838
+ ? 'MODEL_NOT_IN_PLAN'
839
+ : isCredits
840
+ ? 'INSUFFICIENT_CREDITS'
841
+ : 'RATE_LIMIT_EXCEEDED'),
842
+ message:
843
+ errObj?.message ||
844
+ (isModelAccess
845
+ ? 'Upgrade your plan to use this model.'
846
+ : isCredits
847
+ ? "You've run out of credits."
848
+ : "You've sent too many messages."),
849
+ retryable: errObj?.retryable ?? (!isCredits && !isModelAccess),
850
+ retryAfterSeconds: errObj?.retryAfter,
851
+ suggestedAction:
852
+ errObj?.suggestedAction || (isCredits || isModelAccess ? 'upgrade' : 'wait'),
853
+ limitType: errObj?.details?.limitType,
854
+ current: errObj?.details?.current,
855
+ limit: errObj?.details?.limit,
856
+ tier: errObj?.details?.tier,
857
+ });
858
+ }
859
+ }
860
+
861
+ // Session expired or signed out mid-request: friendly sign-in prompt
862
+ // instead of the raw server error string.
863
+ if (response.status === 401) {
864
+ throw new Error(labels.signInRequired);
865
+ }
866
+
867
+ // A turn that failed before any output, answered before the stream
868
+ // opened (Alia's 503/500 with `code`, `retryable` and `reference`):
869
+ // the same failed-turn card as the in-stream error frame — the app's
870
+ // own line, with code and reference — never the server's English.
871
+ const failed =
872
+ errorData?.error && typeof errorData.error === 'object' ? errorData.error : null;
873
+ if (
874
+ failed &&
875
+ (typeof failed.reference === 'string' ||
876
+ (response.status >= 500 && typeof failed.code === 'string'))
877
+ ) {
878
+ setError(new Error(getErrorMessage(failed) || `Server error (${response.status})`));
879
+ setIsLoading(false);
880
+ return keepFailedTurn(
881
+ failed.retryable !== false,
882
+ failureDetail({
883
+ code: typeof failed.code === 'string' ? failed.code : undefined,
884
+ reference: typeof failed.reference === 'string' ? failed.reference : undefined,
885
+ }),
886
+ );
887
+ }
888
+
889
+ // Generic error fallback
890
+ let errorMessage = `Server error (${response.status})`;
891
+ if (errorData) {
892
+ const err = errorData.error;
893
+ if (typeof err === 'string') {
894
+ errorMessage = err;
895
+ } else if (getErrorMessage(err)) {
896
+ errorMessage = getErrorMessage(err);
897
+ } else if (typeof errorData.details === 'string') {
898
+ errorMessage = errorData.details;
899
+ }
900
+ } else {
901
+ errorMessage = response.statusText || errorMessage;
902
+ }
903
+ throw new Error(errorMessage);
904
+ }
905
+
906
+ if (!response.body) {
907
+ throw new Error('No response received from server');
908
+ }
909
+ setComposerPhase('streaming');
910
+ // The server has the outcomes this request carried: they are its calls' results now.
911
+ hostOutcomesRef.current.delivered(outcomes);
912
+
913
+ const reader = response.body.getReader();
914
+ const decoder = new TextDecoder();
915
+ /**
916
+ * Frame reassembly lives in `sse-frame-reader.ts`.
917
+ *
918
+ * It used to be loose variables here, and that is how the bug happened:
919
+ * `buffer` was declared outside the read loop and survived a chunk
920
+ * boundary, but the current event name was declared INSIDE it and reset
921
+ * on every `reader.read()`. A frame is `event: X\ndata: {…}\n\n`, so any
922
+ * frame split between those two lines lost its name, fell through to the
923
+ * OpenAI-shaped branch below, found no `choices[0]`, and was dropped in
924
+ * silence — most often for the largest payloads, which are the ones that
925
+ * do not fit in one read: `alia.title`, `alia.tool_result`,
926
+ * `alia.plan_preview`, `alia.agent_start`, `alia.host_action`.
927
+ *
928
+ * Two pieces of state that must both outlive a chunk are fields of one
929
+ * object now, and its test feeds a stream split at every byte offset —
930
+ * which is not something a test of this hook could do.
931
+ */
932
+ const sse = createSseFrameReader();
933
+ let lastOutputAt = 0;
934
+ /** The server closed the turn: `[DONE]`, or a chunk that carries a finish reason. */
935
+ let sawTerminal = false;
936
+
937
+ while (true) {
938
+ const { done, value } = await reader.read();
939
+
940
+ if (done) {
941
+ // Flush any remaining batched content before checking
942
+ flushPendingUpdates();
943
+
944
+ // The server answered with a stand-in, or with nothing usable at
945
+ // all: the turn stays, with the error under it. (With real output
946
+ // AND a synthetic tail, this keeps the output and marks the tail.)
947
+ if (syntheticTail !== null) {
948
+ return keepFailedTurn(syntheticTail.retryable, syntheticTail.detail);
949
+ }
950
+ if (!hasUsableStreamOutput(outputEvidence) && !(isGroupTurn && sawTerminal)) {
951
+ setError(new Error('No response received from AI'));
952
+ return keepFailedTurn(true);
953
+ }
954
+ // The connection closed before the server said the turn was over:
955
+ // what is on screen is a cut-off answer, not a finished one. Kept
956
+ // as an interrupted tail with Retry, never settled as complete.
957
+ if (!sawTerminal) {
958
+ setError(new Error('The response ended before it was complete'));
959
+ return keepFailedTurn(true);
960
+ }
961
+ break;
962
+ }
963
+
964
+ // `{ stream: true }`: a multi-byte character split across two reads
965
+ // decodes to U+FFFD without it.
966
+ const chunk = decoder.decode(value, { stream: true });
967
+
968
+ for (const frame of sse.push(chunk)) {
969
+ const data = frame.data;
970
+ const currentEventType = frame.event;
971
+
972
+ // Skip [DONE] marker
973
+ if (data === '[DONE]') {
974
+ sawTerminal = true;
975
+ continue;
976
+ }
977
+
978
+ try {
979
+ const parsed = JSON.parse(data);
980
+
981
+ // ── Named SSE events (Alia extensions) ──
982
+ if (currentEventType) {
983
+ switch (currentEventType) {
984
+ case 'alia.group_turn': {
985
+ if (
986
+ parsed.eventVersion !== 1 ||
987
+ typeof parsed.conversationId !== 'string' ||
988
+ (conversationId !== undefined && parsed.conversationId !== conversationId) ||
989
+ !Array.isArray(parsed.agentIds) ||
990
+ !parsed.agentIds.every((id: unknown) => typeof id === 'string')
991
+ ) {
992
+ continue;
993
+ }
994
+ isGroupTurn = true;
995
+ // The room has no lead assistant. Only a selected member's start
996
+ // creates a reply; a quiet decision leaves just the person's message.
997
+ setMessages((prev) => prev.filter((m) => m.id !== assistantMessage.id));
998
+ continue;
999
+ }
1000
+ case 'alia.reasoning': {
1001
+ const content = parsed.content;
1002
+ if (content) {
1003
+ pendingReasoningRef.current += content;
1004
+ scheduleFlush();
1005
+ }
1006
+ continue;
1007
+ }
1008
+ case 'alia.tool_result': {
1009
+ const { tool_call_id, name, output } = parsed;
1010
+ if (tool_call_id) {
1011
+ setMessages((prev) => {
1012
+ const updated = [...prev];
1013
+ const lastMessage = updated[updated.length - 1];
1014
+ if (lastMessage?.role === 'assistant') {
1015
+ const invocations = [...(lastMessage.toolInvocations || [])];
1016
+ const idx = invocations.findIndex((t) => t.toolCallId === tool_call_id);
1017
+ if (idx >= 0) {
1018
+ invocations[idx] = {
1019
+ ...(invocations[idx] as ToolInvocation),
1020
+ state: 'result',
1021
+ result: output,
1022
+ };
1023
+ } else {
1024
+ invocations.push({
1025
+ toolCallId: tool_call_id,
1026
+ toolName: name || 'unknown',
1027
+ state: 'result',
1028
+ result: output,
1029
+ });
1030
+ }
1031
+ updated[updated.length - 1] = {
1032
+ ...lastMessage,
1033
+ toolInvocations: invocations,
1034
+ };
1035
+ }
1036
+ return updated;
1037
+ });
1038
+ // The host hears of every finished tool (the memory document
1039
+ // may have been rewritten) and of the artifact it produced.
1040
+ host.onToolResult?.({ toolCallId: tool_call_id, name, output });
1041
+ const artifact = artifactOf(tool_call_id, name, output);
1042
+ if (artifact) {
1043
+ outputEvidence.durableArtifactCount += 1;
1044
+ host.onArtifact?.(artifact);
1045
+ }
1046
+ }
1047
+ continue;
1048
+ }
1049
+ case 'alia.agent_start':
1050
+ case 'alia.agent_delta':
1051
+ case 'alia.agent_tool':
1052
+ case 'alia.agent_end': {
1053
+ const consult = parseConsultEvent(currentEventType, parsed);
1054
+ if (consult !== null) applyConsult(consult);
1055
+ continue;
1056
+ }
1057
+ case 'alia.host_action': {
1058
+ // Performed here, by the client that declared it, once; its outcome rides
1059
+ // the next request. The stream does not wait for it.
1060
+ const action = parseHostAction(parsed);
1061
+ if (action === null) continue;
1062
+ if (action.awaitsResult && action.turnId !== undefined) {
1063
+ // The turn waits for this one: its answer goes back at once, through the
1064
+ // same authenticated API (and app assertion) the turn's account uses.
1065
+ const turnSignal = controller.signal;
1066
+ const route = API_ROUTES.hostResults(action.turnId);
1067
+ void hostOutcomesRef.current.answer(
1068
+ action,
1069
+ hostToolsRef.current,
1070
+ appRef.current,
1071
+ async (answer) => {
1072
+ if (turnSignal.aborted) throw new Error('The turn ended');
1073
+ await api.post(route, answer, { signal: turnSignal });
1074
+ },
1075
+ );
1076
+ continue;
1077
+ }
1078
+ void hostOutcomesRef.current.dispatch(
1079
+ action,
1080
+ hostToolsRef.current,
1081
+ appRef.current,
1082
+ );
1083
+ continue;
1084
+ }
1085
+ case 'alia.title': {
1086
+ if (parsed.title && parsed.conversationId) {
1087
+ queryClient.setQueryData(
1088
+ gemieQueryKeys.conversations.detail(parsed.conversationId),
1089
+ (old: Conversation | undefined) =>
1090
+ old ? { ...old, title: parsed.title } : old,
1091
+ );
1092
+ queryClient.setQueriesData(
1093
+ { queryKey: gemieQueryKeys.conversations.all },
1094
+ (old: ConversationsInfiniteData | undefined) => {
1095
+ if (!old?.pages) return old;
1096
+ return {
1097
+ ...old,
1098
+ pages: old.pages.map((page) => ({
1099
+ ...page,
1100
+ conversations: page.conversations.map((c) =>
1101
+ c.id === parsed.conversationId ? { ...c, title: parsed.title } : c,
1102
+ ),
1103
+ })),
1104
+ };
1105
+ },
1106
+ );
1107
+ setConversationTitle(parsed.title);
1108
+ }
1109
+ continue;
1110
+ }
1111
+ case 'alia.research_progress': {
1112
+ setMessages((prev) => {
1113
+ const updated = [...prev];
1114
+ const lastMessage = updated[updated.length - 1];
1115
+ if (lastMessage?.role === 'assistant') {
1116
+ updated[updated.length - 1] = {
1117
+ ...lastMessage,
1118
+ researchProgress: {
1119
+ phase: parsed.phase,
1120
+ message: parsed.message,
1121
+ subQuestions:
1122
+ parsed.subQuestions || lastMessage.researchProgress?.subQuestions,
1123
+ sourcesFound: parsed.sourcesFound,
1124
+ currentQuery: parsed.currentQuery,
1125
+ iteration: parsed.iteration,
1126
+ isComplete: parsed.phase === 'complete',
1127
+ // The final event carries the sources; every earlier
1128
+ // one carries none, and a progress event after the
1129
+ // final one must not erase them.
1130
+ sources: parsed.sources ?? lastMessage.researchProgress?.sources,
1131
+ totalSearches:
1132
+ parsed.totalSearches ?? lastMessage.researchProgress?.totalSearches,
1133
+ },
1134
+ };
1135
+ }
1136
+ return updated;
1137
+ });
1138
+ continue;
1139
+ }
1140
+ case 'alia.plan_preview': {
1141
+ setMessages((prev) => {
1142
+ const updated = [...prev];
1143
+ const lastMessage = updated[updated.length - 1];
1144
+ if (lastMessage?.role === 'assistant') {
1145
+ updated[updated.length - 1] = {
1146
+ ...lastMessage,
1147
+ plan: {
1148
+ planId: parsed.planId,
1149
+ steps: parsed.steps || [],
1150
+ },
1151
+ };
1152
+ }
1153
+ return updated;
1154
+ });
1155
+ continue;
1156
+ }
1157
+ case 'alia.context': {
1158
+ // What this turn put in the context window, for the usage card.
1159
+ host.onContext?.(
1160
+ typeof parsed.conversationId === 'string'
1161
+ ? parsed.conversationId
1162
+ : (conversationId ?? null),
1163
+ parsed,
1164
+ );
1165
+ continue;
1166
+ }
1167
+ case 'alia.suggest_new_conversation': {
1168
+ // A missing or blank reason degrades to an offer without
1169
+ // one rather than to an invented one: the sentence belongs
1170
+ // to the model, and a plausible substitute would be worse
1171
+ // than none.
1172
+ setSuggestedNewConversation(
1173
+ typeof parsed.reason === 'string' && parsed.reason.trim() !== ''
1174
+ ? parsed.reason.trim()
1175
+ : '',
1176
+ );
1177
+ continue;
1178
+ }
1179
+ case 'alia.agent_turn': {
1180
+ if (parsed.turnId) {
1181
+ const run = {
1182
+ turnId: String(parsed.turnId),
1183
+ agentId: String(parsed.agentId ?? agentId ?? ''),
1184
+ };
1185
+ setAgentRun(run);
1186
+ host.onAgentTurn?.({ ...run, conversationId: conversationId ?? null });
1187
+ }
1188
+ continue;
1189
+ }
1190
+ default:
1191
+ // Unknown named event — skip
1192
+ continue;
1193
+ }
1194
+ }
1195
+
1196
+ // ── Standard OpenAI data events ──
1197
+
1198
+ // Handle structured error events sent via SSE
1199
+ if (parsed.error) {
1200
+ const err = parsed.error;
1201
+ if (errorCode(err) === 'turn_cancelled') {
1202
+ flushPendingUpdates();
1203
+ settleAssistant('cancelled');
1204
+ abortThisTurn();
1205
+ reader.cancel().catch(() => {});
1206
+ return 'aborted';
1207
+ }
1208
+ // An agent's feature gate refused the turn before anything was spent: the host
1209
+ // shows its own upsell, and the person's words go back to the composer.
1210
+ const lockedFeature = lockedFeatureOf(err);
1211
+ if (lockedFeature !== null) {
1212
+ setIsLoading(false);
1213
+ abortThisTurn();
1214
+ reader.cancel().catch(() => {});
1215
+ host.onFeatureLocked?.(lockedFeature);
1216
+ return settleError();
1217
+ }
1218
+ // Check for usage limit errors (rate limit, credits, model access)
1219
+ if (
1220
+ errorCode(err) === 'MODEL_NOT_IN_PLAN' ||
1221
+ errorCode(err) === 'INSUFFICIENT_CREDITS' ||
1222
+ err.type === 'rate_limit_error'
1223
+ ) {
1224
+ const isRateLimit = err.type === 'rate_limit_error';
1225
+ throw new UsageLimitError({
1226
+ type:
1227
+ errorCode(err) === 'MODEL_NOT_IN_PLAN'
1228
+ ? 'model_access'
1229
+ : errorCode(err) === 'INSUFFICIENT_CREDITS'
1230
+ ? 'credits'
1231
+ : 'rate_limit',
1232
+ code: String(errorCode(err) ?? ''),
1233
+ message: getErrorMessage(err),
1234
+ retryable: isRateLimit,
1235
+ // A limit to wait out (the plan's usage window, the request
1236
+ // rate) carries when to retry, which drives the dialog's
1237
+ // countdown; running out of credits or a model's plan is an
1238
+ // upgrade.
1239
+ retryAfterSeconds:
1240
+ isRateLimit && typeof err.retryAfter === 'number'
1241
+ ? err.retryAfter
1242
+ : undefined,
1243
+ suggestedAction: isRateLimit ? 'wait' : 'upgrade',
1244
+ limitType:
1245
+ typeof err.details?.limitType === 'string'
1246
+ ? err.details.limitType
1247
+ : undefined,
1248
+ current:
1249
+ typeof err.details?.current === 'number' ? err.details.current : undefined,
1250
+ limit: typeof err.details?.limit === 'number' ? err.details.limit : undefined,
1251
+ });
1252
+ }
1253
+
1254
+ // Generic SSE error — stop, and report it IN the thread: the
1255
+ // turn stays with the error under it, so nothing needs a toast.
1256
+ const msg = getErrorMessage(err) || 'Something went wrong. Please try again.';
1257
+ setError(new Error(msg));
1258
+ setIsLoading(false);
1259
+ abortThisTurn();
1260
+ reader.cancel().catch(() => {});
1261
+ // A turn that failed after it started carries a run reference:
1262
+ // its card says code and reference, never the server's English
1263
+ // prose. A refusal without one (a gate, a bad request) keeps its
1264
+ // message, which is the only thing that says what to change.
1265
+ const detail =
1266
+ typeof err.reference === 'string'
1267
+ ? failureDetail({
1268
+ code: typeof err.code === 'string' ? err.code : undefined,
1269
+ reference: err.reference,
1270
+ })
1271
+ : getErrorMessage(err) || undefined;
1272
+ return keepFailedTurn(err.retryable !== false, detail);
1273
+ }
1274
+
1275
+ // Handle usage/credits info (comes at the end of stream).
1276
+ // New format: alia_usage (separate from OpenAI usage), fallback to legacy usage.
1277
+ //
1278
+ // Read BEFORE the choice guard: the server writes it on a chunk
1279
+ // with `choices: []`, which the guard skips — so it was never
1280
+ // read, and neither the balance nor the spending warning reached
1281
+ // the screen.
1282
+ const gemieUsage = parsed.alia_usage || parsed.usage;
1283
+ if (gemieUsage && gemieUsage.credits_remaining !== undefined) {
1284
+ host.onUsage?.(gemieUsage);
1285
+ }
1286
+
1287
+ // Handle OpenAI-compatible format
1288
+ const choice = parsed.choices?.[0];
1289
+ if (!choice) continue;
1290
+ if (choice.finish_reason) sawTerminal = true;
1291
+
1292
+ const delta = choice.delta;
1293
+ if (!delta) continue;
1294
+
1295
+ // Handle reasoning/thinking content (batched for performance)
1296
+ if (delta.reasoning) {
1297
+ pendingReasoningRef.current += delta.reasoning;
1298
+ scheduleFlush();
1299
+ }
1300
+
1301
+ // Handle text content (batched for performance)
1302
+ if (delta.content) {
1303
+ const meta = readGemieMeta(parsed);
1304
+ if (meta.synthetic) {
1305
+ // Remembered, never rendered — see `syntheticTail`. The
1306
+ // server sends a stop chunk and [DONE] right after, and the
1307
+ // `done` branch turns this into the error under the turn.
1308
+ const detail = failureDetail(meta);
1309
+ syntheticTail = {
1310
+ retryable: meta.retryable,
1311
+ ...(detail === undefined ? {} : { detail }),
1312
+ };
1313
+ } else {
1314
+ outputEvidence.realOutputChars += delta.content.length;
1315
+
1316
+ // A tick for the host (a haptic), throttled by time — per-character
1317
+ // counting fired dozens of native bridge calls per second on
1318
+ // fast streams.
1319
+ const now = Date.now();
1320
+ if (now - lastOutputAt >= 150) {
1321
+ lastOutputAt = now;
1322
+ host.onOutput?.();
1323
+ }
1324
+
1325
+ replyText += delta.content;
1326
+ pendingContentRef.current += delta.content;
1327
+ scheduleFlush();
1328
+ }
1329
+ }
1330
+
1331
+ // Handle tool calls (OpenAI format: delta.tool_calls)
1332
+ if (delta.tool_calls && Array.isArray(delta.tool_calls)) {
1333
+ for (const tc of delta.tool_calls) {
1334
+ const toolCallId = tc.id;
1335
+ const toolName = tc.function?.name;
1336
+ if (!toolCallId || !toolName) continue;
1337
+ outputEvidence.toolInvocationCount += 1;
1338
+ // A question card is the turn's output, even with no sentence before it.
1339
+ if (toolName === ASK_USER_QUESTION_TOOL) outputEvidence.durableArtifactCount += 1;
1340
+
1341
+ let args: Record<string, unknown> | undefined;
1342
+ if (tc.function?.arguments) {
1343
+ try {
1344
+ args = JSON.parse(tc.function.arguments);
1345
+ } catch {
1346
+ args = { _raw: tc.function.arguments };
1347
+ }
1348
+ }
1349
+
1350
+ setMessages((prev) => {
1351
+ const updated = [...prev];
1352
+ const lastMessage = updated[updated.length - 1];
1353
+ if (lastMessage?.role === 'assistant') {
1354
+ const invocations = [...(lastMessage.toolInvocations || [])];
1355
+ const idx = invocations.findIndex((t) => t.toolCallId === toolCallId);
1356
+ const invocation: ToolInvocation = {
1357
+ toolCallId,
1358
+ toolName,
1359
+ state: 'call',
1360
+ args,
1361
+ };
1362
+
1363
+ if (idx >= 0) {
1364
+ invocations[idx] = invocation;
1365
+ } else {
1366
+ invocations.push(invocation);
1367
+ }
1368
+
1369
+ updated[updated.length - 1] = {
1370
+ ...lastMessage,
1371
+ toolInvocations: invocations,
1372
+ };
1373
+ }
1374
+ return updated;
1375
+ });
1376
+ }
1377
+ }
1378
+
1379
+ // Handle tool results (custom extension: delta.tool_result)
1380
+ if (delta.tool_result) {
1381
+ const { tool_call_id, name, output } = delta.tool_result;
1382
+ if (tool_call_id) {
1383
+ setMessages((prev) => {
1384
+ const updated = [...prev];
1385
+ const lastMessage = updated[updated.length - 1];
1386
+ if (lastMessage?.role === 'assistant') {
1387
+ const invocations = [...(lastMessage.toolInvocations || [])];
1388
+ const idx = invocations.findIndex((t) => t.toolCallId === tool_call_id);
1389
+
1390
+ if (idx >= 0) {
1391
+ invocations[idx] = {
1392
+ ...(invocations[idx] as ToolInvocation),
1393
+ state: 'result',
1394
+ result: output,
1395
+ };
1396
+ } else {
1397
+ invocations.push({
1398
+ toolCallId: tool_call_id,
1399
+ toolName: name || 'unknown',
1400
+ state: 'result',
1401
+ result: output,
1402
+ });
1403
+ }
1404
+
1405
+ updated[updated.length - 1] = {
1406
+ ...lastMessage,
1407
+ toolInvocations: invocations,
1408
+ };
1409
+ }
1410
+ return updated;
1411
+ });
1412
+
1413
+ host.onToolResult?.({ toolCallId: tool_call_id, name, output });
1414
+ const artifact = artifactOf(tool_call_id, name, output);
1415
+ if (artifact) {
1416
+ outputEvidence.durableArtifactCount += 1;
1417
+ host.onArtifact?.(artifact);
1418
+ }
1419
+ }
1420
+ }
1421
+
1422
+ // Handle error events from server
1423
+ if (parsed.type === 'error') {
1424
+ const errMsg =
1425
+ typeof parsed.error === 'string'
1426
+ ? parsed.error
1427
+ : parsed.error?.message || JSON.stringify(parsed.error);
1428
+ setError(new Error(errMsg));
1429
+ setIsLoading(false);
1430
+
1431
+ // Abort the stream
1432
+ abortThisTurn();
1433
+
1434
+ // Break out of the streaming loop
1435
+ reader.cancel().catch(() => {});
1436
+ return keepFailedTurn(true, errMsg);
1437
+ }
1438
+ } catch (frameError: unknown) {
1439
+ /**
1440
+ * Malformed SSE fragments are expected mid-stream; the next
1441
+ * complete event supersedes them.
1442
+ *
1443
+ * A `UsageLimitError` is NOT one of those. It is thrown
1444
+ * deliberately from the `parsed.error` branch above so the outer
1445
+ * handler can show the upgrade dialog — and it was thrown from
1446
+ * inside this same `try`, so this `catch` ate it. An in-stream
1447
+ * `INSUFFICIENT_CREDITS`, `MODEL_NOT_IN_PLAN` or
1448
+ * `rate_limit_error` therefore did nothing at all: the loop kept
1449
+ * reading, the stream ended, and the user saw a reply that
1450
+ * simply stopped with no error and no way to act on it. (The
1451
+ * generic-error branch beside it escaped only because it uses
1452
+ * `return` rather than `throw`.)
1453
+ */
1454
+ // `instanceof` AND the name, matching the outer handler: Hermes
1455
+ // can break `instanceof` for Error subclasses, and a rethrow that
1456
+ // misses is the same silent swallow this fixes.
1457
+ if (
1458
+ frameError instanceof UsageLimitError ||
1459
+ errorName(frameError) === 'UsageLimitError'
1460
+ ) {
1461
+ throw frameError;
1462
+ }
1463
+ }
1464
+ }
1465
+ }
1466
+
1467
+ return 'sent';
1468
+ } catch (e: unknown) {
1469
+ // Ignore abort errors (user cancelled) — partial output is theirs to keep.
1470
+ if (e instanceof Error && errorName(e) === 'AbortError') {
1471
+ return 'aborted';
1472
+ }
1473
+
1474
+ // UsageLimitError thrown from the 429/402 handler above
1475
+ // Check both instanceof AND name — Hermes can break instanceof for Error subclasses
1476
+ if (e instanceof UsageLimitError || errorName(e) === 'UsageLimitError') {
1477
+ setError(e instanceof Error ? e : new Error(getErrorMessage(e)));
1478
+ setComposerPhase('error');
1479
+ return settleError();
1480
+ }
1481
+
1482
+ // A streaming fetch may throw a non-Error object (e.g. the response body)
1483
+ // Try to detect rate limit / credit errors from the thrown object
1484
+ if (e && typeof e === 'object' && !(e instanceof Error)) {
1485
+ const thrown = e as {
1486
+ status?: number;
1487
+ error?: ThrownErrorBody;
1488
+ body?: { error?: ThrownErrorBody };
1489
+ };
1490
+ const status = thrown.status || errorStatus(e);
1491
+ const errBody: ThrownErrorBody | undefined =
1492
+ thrown.error || thrown.body?.error || (thrown as ThrownErrorBody);
1493
+ if (
1494
+ status === 429 ||
1495
+ status === 402 ||
1496
+ errBody?.code === 'RATE_LIMIT_EXCEEDED' ||
1497
+ errBody?.code === 'INSUFFICIENT_CREDITS'
1498
+ ) {
1499
+ const isCredits = status === 402 || errBody?.code === 'INSUFFICIENT_CREDITS';
1500
+ const usageError = new UsageLimitError({
1501
+ type: isCredits ? 'credits' : 'rate_limit',
1502
+ code: errBody?.code || (isCredits ? 'INSUFFICIENT_CREDITS' : 'RATE_LIMIT_EXCEEDED'),
1503
+ message:
1504
+ errBody?.message ||
1505
+ (isCredits ? "You've run out of credits." : "You've sent too many messages."),
1506
+ retryable: errBody?.retryable ?? !isCredits,
1507
+ retryAfterSeconds: errBody?.retryAfter,
1508
+ suggestedAction: errBody?.suggestedAction || (isCredits ? 'upgrade' : 'wait'),
1509
+ });
1510
+ setError(usageError);
1511
+ setComposerPhase('error');
1512
+ return settleError();
1513
+ }
1514
+ }
1515
+
1516
+ // Everything else — the network, a 5xx, a 401 — keeps the turn in the
1517
+ // thread with the error under it and a retry beside it. The message is
1518
+ // shown as the card's detail line, not as an answer.
1519
+ const finalError =
1520
+ e instanceof Error
1521
+ ? e
1522
+ : new Error(
1523
+ typeof e === 'string' ? e : getErrorMessage(e) || 'An unexpected error occurred',
1524
+ );
1525
+ setError(finalError);
1526
+ setComposerPhase('error');
1527
+ return keepFailedTurn(true, finalError.message);
1528
+ } finally {
1529
+ // Batches belong to the current turn. An older finally must not flush or clear
1530
+ // the next turn's shared timer, even when its controller ref has been cleared.
1531
+ if (turnGenerationRef.current === turnGeneration) {
1532
+ flushPendingUpdates();
1533
+ if (flushTimerRef.current) {
1534
+ clearTimeout(flushTimerRef.current);
1535
+ flushTimerRef.current = null;
1536
+ }
1537
+ }
1538
+ // Settle only this turn's message ids, including when a new send has already
1539
+ // started in the same conversation. Error paths may have settled them first.
1540
+ settleAssistant(controller?.signal.aborted === true ? 'cancelled' : 'completed');
1541
+ // Retain this control while its ACK drains so repeated Stop remains deduplicated.
1542
+ // Local transport cleanup is required even after the thread has been replaced.
1543
+ if (turnControl) await turnControl.finish();
1544
+ else linked?.dispose();
1545
+ if (abortControllerRef.current === controller) abortControllerRef.current = null;
1546
+ if (turnControlRef.current === turnControl) turnControlRef.current = null;
1547
+ // Recheck after the await: another turn, thread, account or mount may now own UI.
1548
+ if (mountedRef.current && turnGenerationRef.current === turnGeneration) {
1549
+ setIsLoading(false);
1550
+ if (composerPhaseRef.current !== 'error' && composerPhaseRef.current !== 'idle') {
1551
+ setComposerPhase('complete');
1552
+ }
1553
+ // The sidebar preview and completion notification belong to this visible turn.
1554
+ if (replyText !== '') host.onTurnPreview?.(agentId, replyText);
1555
+ host.onTurnEnd?.();
1556
+ }
1557
+ }
1558
+ },
1559
+ [
1560
+ api,
1561
+ apiUrl,
1562
+ streamFetch,
1563
+ host,
1564
+ labels,
1565
+ oxyServices,
1566
+ appAssertionHeaders,
1567
+ queryClient,
1568
+ conversationId,
1569
+ model,
1570
+ agentId,
1571
+ clientContext,
1572
+ scheduleFlush,
1573
+ flushPendingUpdates,
1574
+ dropPendingUpdates,
1575
+ setMessagesAndRef,
1576
+ setComposerPhase,
1577
+ ],
1578
+ );
1579
+
1580
+ const detach = useCallback(() => {
1581
+ if (abortControllerRef.current) {
1582
+ abortControllerRef.current.abort();
1583
+ abortControllerRef.current = null;
1584
+ }
1585
+ setIsLoading(false);
1586
+ setComposerPhase('idle');
1587
+ }, [setComposerPhase]);
1588
+
1589
+ const stop = useCallback(() => {
1590
+ const turn = turnControlRef.current;
1591
+ const turnGeneration = turnGenerationRef.current;
1592
+ if (!turn) return;
1593
+ setComposerPhase('stopping');
1594
+ void turn.stop().catch((error: unknown) => {
1595
+ if (
1596
+ turnControlRef.current === turn &&
1597
+ turnGenerationRef.current === turnGeneration &&
1598
+ mountedRef.current
1599
+ ) {
1600
+ setError(error instanceof Error ? error : new Error('Generation could not be stopped.'));
1601
+ setComposerPhase('streaming');
1602
+ }
1603
+ });
1604
+ }, [setComposerPhase]);
1605
+
1606
+ const clearError = useCallback(() => {
1607
+ setError(null);
1608
+ if (!isLoading) setComposerPhase('idle');
1609
+ }, [isLoading, setComposerPhase]);
1610
+
1611
+ /**
1612
+ * Send the failed turn again: the same content and attachments, the same
1613
+ * options, through the same `append`.
1614
+ *
1615
+ * The thread is cut back to just before the failed user message first —
1616
+ * the same truncation an edit does — so the re-sent turn lands where the
1617
+ * failed one was rather than after it, and the history the server receives
1618
+ * holds the message once. It was never persisted (see `turn-failure.ts`),
1619
+ * so there is no second row to avoid on that side either. Cut from
1620
+ * `messagesRef` directly and set as an array, not through an updater, so
1621
+ * `append`'s snapshot sees the cut regardless of when React runs it.
1622
+ */
1623
+ const retryFailedTurn = useCallback(async (): Promise<SendOutcome> => {
1624
+ const retry = retryRef.current;
1625
+ if (retry === null) return 'failed';
1626
+ const current = messagesRef.current;
1627
+ const idx = current.findIndex((m) => m.id === retry.userMessageId);
1628
+ if (idx >= 0) setMessagesAndRef(current.slice(0, idx));
1629
+ return append(retry.message, retry.options);
1630
+ }, [append, setMessagesAndRef]);
1631
+
1632
+ /** Take the error down without retrying — the thread was cleared, or the person moved on. */
1633
+ const clearFailedTurn = useCallback(() => {
1634
+ setFailedTurn(null);
1635
+ retryRef.current = null;
1636
+ if (!isLoading) setComposerPhase('idle');
1637
+ }, [isLoading, setComposerPhase]);
1638
+
1639
+ /** Put the offer away. It wrote nothing, so there is nothing else to undo. */
1640
+ const dismissSuggestedNewConversation = useCallback(() => {
1641
+ setSuggestedNewConversation(null);
1642
+ }, []);
1643
+
1644
+ /** The options a user turn was sent with, if it was sent from this screen. */
1645
+ const turnOptionsOf = useCallback(
1646
+ (userMessageId: string) => turnOptionsRef.current.get(userMessageId),
1647
+ [],
1648
+ );
1649
+
1650
+ return {
1651
+ messages,
1652
+ isLoading,
1653
+ composerPhase,
1654
+ error,
1655
+ append,
1656
+ stop,
1657
+ detach,
1658
+ setMessages: setMessagesAndRef,
1659
+ conversationTitle,
1660
+ clearError,
1661
+ suggestedNewConversation,
1662
+ dismissSuggestedNewConversation,
1663
+ agentRun,
1664
+ failedTurn,
1665
+ retryFailedTurn,
1666
+ clearFailedTurn,
1667
+ turnOptionsOf,
1668
+ };
1669
+ }