@gemies/sdk 9.1.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +9 -6
  3. package/package.json +4 -11
  4. package/src/accounts.ts +7 -1
  5. package/src/ask-eager.ts +0 -2
  6. package/src/ask-text.ts +0 -1
  7. package/src/ask.ts +0 -1
  8. package/src/components/AmbientField.tsx +13 -2
  9. package/src/components/ComposerDropZone.tsx +20 -4
  10. package/src/components/ComposerSuggestions.tsx +9 -2
  11. package/src/components/GemieActivityLine.tsx +11 -5
  12. package/src/components/GemieBetweenGemies.tsx +23 -10
  13. package/src/components/GemieChatContent.tsx +65 -23
  14. package/src/components/GemieChatScreen.tsx +7 -4
  15. package/src/components/GemieChatSheet.tsx +6 -2
  16. package/src/components/GemieComposer.tsx +17 -7
  17. package/src/components/GemieGroupWelcome.tsx +16 -2
  18. package/src/components/GemieRecentConversations.tsx +13 -10
  19. package/src/components/GemieSharedConversation.tsx +38 -6
  20. package/src/components/GemieWelcomeMessage.tsx +23 -7
  21. package/src/components/IdentityMark.tsx +6 -12
  22. package/src/components/PlanPreviewCard.tsx +18 -7
  23. package/src/components/QuestionCard.tsx +6 -2
  24. package/src/components/ReplyMarkdown.tsx +32 -6
  25. package/src/components/RichBlocks.tsx +20 -15
  26. package/src/components/accounts/GemieAccountGrants.tsx +27 -10
  27. package/src/components/accounts/GemieConnectedAccounts.tsx +87 -51
  28. package/src/components/canvas/CanvasComponent.tsx +6 -2
  29. package/src/components/canvas/DashboardRenderer.tsx +25 -8
  30. package/src/components/canvas/DeckRenderer.tsx +23 -6
  31. package/src/components/canvas/FormRenderer.tsx +8 -3
  32. package/src/components/connectors/ConnectorLogo.tsx +15 -9
  33. package/src/components/connectors/GemieConnectedConnectors.tsx +51 -25
  34. package/src/components/connectors/GemieConnectorsStore.tsx +99 -41
  35. package/src/components/connectors/GrantSwitchRow.tsx +18 -5
  36. package/src/components/thought/ThoughtPanel.tsx +26 -12
  37. package/src/components/thought/ToolStep.tsx +14 -6
  38. package/src/components/thread/AgentResultCard.tsx +10 -4
  39. package/src/components/thread/AgentTaskCard.tsx +8 -3
  40. package/src/components/thread/ApprovalCard.tsx +118 -0
  41. package/src/components/thread/ChatBubble.tsx +66 -25
  42. package/src/components/thread/GemieThread.tsx +36 -8
  43. package/src/components/thread/ThreadRow.tsx +20 -15
  44. package/src/components/thread/ThreadSearch.tsx +27 -10
  45. package/src/components/thread/ThreadSkeleton.tsx +12 -6
  46. package/src/components/thread/ToolResultCard.tsx +10 -4
  47. package/src/components/thread/TurnAttachments.tsx +17 -8
  48. package/src/components/voice/VoiceControls.tsx +9 -6
  49. package/src/connectors.ts +15 -2
  50. package/src/hooks/useChatVoice.ts +2 -10
  51. package/src/hooks/useMessageReactions.ts +5 -5
  52. package/src/hooks/useThoughtScope.ts +9 -8
  53. package/src/index.ts +2 -3
  54. package/src/lib/copy-en.ts +7 -0
  55. package/src/lib/copy-es.ts +7 -0
  56. package/src/lib/tool-call-status.ts +1 -1
  57. package/src/lib/utils.ts +1 -8
  58. package/src/realtime/react.tsx +9 -9
  59. package/src/realtime/reread.ts +28 -0
  60. package/src/realtime/store.ts +123 -0
  61. package/src/runtime/agents.ts +46 -27
  62. package/src/runtime/approvals.ts +99 -0
  63. package/src/runtime/collections.ts +35 -136
  64. package/src/runtime/config.tsx +10 -0
  65. package/src/runtime/connected-accounts.ts +175 -88
  66. package/src/runtime/connectors.ts +244 -127
  67. package/src/runtime/conversations.ts +181 -607
  68. package/src/runtime/data/answer.ts +76 -0
  69. package/src/runtime/data/collections.ts +168 -0
  70. package/src/runtime/data/conversations.ts +626 -0
  71. package/src/runtime/data/reactions.ts +29 -0
  72. package/src/runtime/data/read.ts +37 -0
  73. package/src/runtime/data/threads.ts +149 -0
  74. package/src/runtime/index.ts +74 -8
  75. package/src/runtime/model.ts +0 -2
  76. package/src/runtime/routes.ts +2 -2
  77. package/src/runtime/sharing.ts +69 -56
  78. package/src/runtime/types.ts +8 -16
  79. package/src/runtime/use-bound-action.ts +27 -0
  80. package/src/runtime/use-conversation-stream.ts +47 -31
  81. package/src/runtime/use-conversation-thread.ts +44 -51
  82. package/src/runtime/use-gemie-thread.ts +32 -43
  83. package/src/runtime/use-start-conversation.ts +14 -15
  84. package/src/runtime/use-thread-history.ts +26 -36
  85. package/src/runtime/use-thread-search.ts +29 -76
  86. package/src/text.ts +0 -1
  87. package/src/voice.ts +0 -1
  88. package/src/components/Image.tsx +0 -12
  89. package/src/realtime/cache.ts +0 -257
  90. package/src/runtime/conversation-dates.ts +0 -31
  91. package/src/runtime/query-keys.ts +0 -66
  92. package/src/runtime/reaction-cache.ts +0 -45
@@ -1,7 +1,7 @@
1
1
  import type { ComposerLoaderPhase } from '@oxy.so/bloom/composer-loader';
2
2
  import { ASK_USER_QUESTION_TOOL } from '../tools';
3
3
  import { useOxy } from '@oxy.so/services/ui/client';
4
- import { useQueryClient } from '@tanstack/react-query';
4
+ import { useStore, withStore } from '@oxy.so/bloom-data';
5
5
  import { useCallback, useEffect, useRef, useState } from 'react';
6
6
  import { canvasResultOf } from '../lib/canvas-result';
7
7
  import { useLabels } from '../lib/labels';
@@ -16,7 +16,7 @@ import {
16
16
  readErrorResponseBody,
17
17
  } from './error-utils';
18
18
  import { memberDraftId, buildOutboundMessages, isMemberDraftOf } from './message-history';
19
- import { gemieQueryKeys } from './query-keys';
19
+ import { Conversations } from './data/conversations';
20
20
  import {
21
21
  applyRoomEvent,
22
22
  claimMemberTurn,
@@ -28,6 +28,15 @@ import {
28
28
  import { createRandomUuid } from './random-uuid';
29
29
  import { createChatTurnControl } from './chat-turn-control';
30
30
  import { awaitTurnPreparation } from './turn-preparation';
31
+ import {
32
+ type ApprovalEntry,
33
+ type ApprovalOutcome,
34
+ parseApprovalRequest,
35
+ parseApprovalResolved,
36
+ stillPending,
37
+ withApprovalOutcome,
38
+ withApprovalRequest,
39
+ } from './approvals';
31
40
  import { type GemieHostTools, HostOutcomeQueue, hostRequest } from './host-tools';
32
41
  import { API_ROUTES } from './routes';
33
42
  import { createSseFrameReader } from './sse-frame-reader';
@@ -39,14 +48,7 @@ import {
39
48
  } from './stream-events';
40
49
  import { hasUsableStreamOutput, type StreamOutputEvidence } from './stream-outcome';
41
50
  import { failureDetail, readGemieMeta, type FailedTurn } from './turn-failure';
42
- import type {
43
- AgentRun,
44
- Conversation,
45
- ConversationsInfiniteData,
46
- Message,
47
- SendOptions,
48
- ToolInvocation,
49
- } from './types';
51
+ import type { AgentRun, Message, SendOptions, ToolInvocation } from './types';
50
52
  import { UsageLimitError } from './usage-limit-error';
51
53
  import { useGemieRealtime } from '../realtime/react';
52
54
 
@@ -243,6 +245,11 @@ export function useConversationStream({
243
245
  * was.
244
246
  */
245
247
  const [suggestedNewConversation, setSuggestedNewConversation] = useState<string | null>(null);
248
+ /**
249
+ * A coding CLI's questions to its own user, this turn's and any still waiting (`approvals.ts`).
250
+ * Held beside the messages, not in them: a question is not part of what was said.
251
+ */
252
+ const [approvals, setApprovals] = useState<ApprovalEntry[]>([]);
246
253
  /** The run a delegated agent started for this conversation (`alia.agent_turn`), or `null`. */
247
254
  const [agentRun, setAgentRun] = useState<AgentRun | null>(null);
248
255
  /**
@@ -267,7 +274,7 @@ export function useConversationStream({
267
274
  const turnOptionsRef = useRef(new Map<string, Pick<SendOptions, 'mcpServerId' | 'skillNames'>>());
268
275
  const { oxyServices, user } = useOxy();
269
276
  const appAssertionHeaders = useAppAssertionHeaders();
270
- const queryClient = useQueryClient();
277
+ const store = useStore();
271
278
  const abortControllerRef = useRef<AbortController | null>(null);
272
279
  const turnControlRef = useRef<ReturnType<typeof createChatTurnControl> | null>(null);
273
280
  // A Stop acknowledgement can outlive its stream, thread, or the next send.
@@ -375,6 +382,7 @@ export function useConversationStream({
375
382
  const conversationRef = useRef(conversationId);
376
383
  useEffect(() => {
377
384
  setFailedTurn(null);
385
+ setApprovals([]);
378
386
  retryRef.current = null;
379
387
  turnOptionsRef.current.clear();
380
388
  // Outcomes answer this conversation's calls. The first turn of a new chat gives it its id,
@@ -424,6 +432,7 @@ export function useConversationStream({
424
432
  setConversationTitle(null);
425
433
  setSuggestedNewConversation(null);
426
434
  setAgentRun(null);
435
+ setApprovals([]);
427
436
  setFailedTurn(null);
428
437
  retryRef.current = null;
429
438
  turnOptionsRef.current.clear();
@@ -438,6 +447,8 @@ export function useConversationStream({
438
447
  // A new send answers the old failure, whether it is the retry or a fresh
439
448
  // message: either way the card comes down.
440
449
  setFailedTurn(null);
450
+ // The last turn's answered questions are history; one still waiting stays.
451
+ setApprovals(stillPending);
441
452
  retryRef.current = null;
442
453
 
443
454
  // Everything the send is about to change, so a turn that produces no real
@@ -1112,25 +1123,9 @@ export function useConversationStream({
1112
1123
  }
1113
1124
  case 'alia.title': {
1114
1125
  if (parsed.title && parsed.conversationId) {
1115
- queryClient.setQueryData(
1116
- gemieQueryKeys.conversations.detail(parsed.conversationId),
1117
- (old: Conversation | undefined) =>
1118
- old ? { ...old, title: parsed.title } : old,
1119
- );
1120
- queryClient.setQueriesData(
1121
- { queryKey: gemieQueryKeys.conversations.all },
1122
- (old: ConversationsInfiniteData | undefined) => {
1123
- if (!old?.pages) return old;
1124
- return {
1125
- ...old,
1126
- pages: old.pages.map((page) => ({
1127
- ...page,
1128
- conversations: page.conversations.map((c) =>
1129
- c.id === parsed.conversationId ? { ...c, title: parsed.title } : c,
1130
- ),
1131
- })),
1132
- };
1133
- },
1126
+ // One record: the thread, the sidebar and every list show the new title.
1127
+ withStore(store, () =>
1128
+ Conversations.merge(parsed.conversationId, { title: parsed.title }),
1134
1129
  );
1135
1130
  setConversationTitle(parsed.title);
1136
1131
  }
@@ -1204,6 +1199,20 @@ export function useConversationStream({
1204
1199
  );
1205
1200
  continue;
1206
1201
  }
1202
+ case 'alia.cli_permission_request': {
1203
+ const request = parseApprovalRequest(parsed);
1204
+ if (request) setApprovals((prev) => withApprovalRequest(prev, request));
1205
+ continue;
1206
+ }
1207
+ case 'alia.cli_permission_resolved': {
1208
+ const resolved = parseApprovalResolved(parsed);
1209
+ if (resolved) {
1210
+ setApprovals((prev) =>
1211
+ withApprovalOutcome(prev, resolved.requestId, resolved.outcome),
1212
+ );
1213
+ }
1214
+ continue;
1215
+ }
1207
1216
  case 'alia.agent_turn': {
1208
1217
  if (parsed.turnId) {
1209
1218
  const run = {
@@ -1592,7 +1601,7 @@ export function useConversationStream({
1592
1601
  labels,
1593
1602
  oxyServices,
1594
1603
  appAssertionHeaders,
1595
- queryClient,
1604
+ store,
1596
1605
  conversationId,
1597
1606
  model,
1598
1607
  agentId,
@@ -1675,6 +1684,11 @@ export function useConversationStream({
1675
1684
  if (!isLoading) setComposerPhase('idle');
1676
1685
  }, [isLoading, setComposerPhase]);
1677
1686
 
1687
+ /** The person's own answer, shown at once; the stream's `alia.cli_permission_resolved` repeats it. */
1688
+ const settleApproval = useCallback((requestId: string, outcome: ApprovalOutcome) => {
1689
+ setApprovals((prev) => withApprovalOutcome(prev, requestId, outcome));
1690
+ }, []);
1691
+
1678
1692
  /** Put the offer away. It wrote nothing, so there is nothing else to undo. */
1679
1693
  const dismissSuggestedNewConversation = useCallback(() => {
1680
1694
  setSuggestedNewConversation(null);
@@ -1700,6 +1714,8 @@ export function useConversationStream({
1700
1714
  suggestedNewConversation,
1701
1715
  dismissSuggestedNewConversation,
1702
1716
  agentRun,
1717
+ approvals,
1718
+ settleApproval,
1703
1719
  failedTurn,
1704
1720
  retryFailedTurn,
1705
1721
  clearFailedTurn,
@@ -1,6 +1,6 @@
1
1
  import { toast } from '@oxy.so/bloom/toast';
2
2
  import { useOxy } from '@oxy.so/services/ui/client';
3
- import { useQueryClient } from '@tanstack/react-query';
3
+ import { useStore, withStore } from '@oxy.so/bloom-data';
4
4
  import { useCallback, useEffect, useId, useMemo, useRef } from 'react';
5
5
  import { useGemieActivityStore } from '../lib/activity-store';
6
6
  import { turnActivityState } from '../lib/turn-state';
@@ -14,22 +14,24 @@ import { useGemieRuntime } from './config';
14
14
  import { releaseAttachments, useComposerDraftStore } from './composer-draft-store';
15
15
  import { useConversationStore } from './conversation-store';
16
16
  import {
17
- ConversationNotFoundError,
18
17
  useClearConversation,
19
18
  useConversation,
20
19
  useCreateConversation,
21
20
  useDeleteConversation,
22
21
  useMarkConversationRead,
23
- useReadConversation,
24
22
  } from './conversations';
25
- import { gemieQueryKeys } from './query-keys';
23
+ import {
24
+ bumpConversation,
25
+ ConversationNotFoundError,
26
+ forgetConversation,
27
+ mergeMessages,
28
+ } from './data/conversations';
26
29
  import { reportDroppedAttachments, useStartConversation } from './use-start-conversation';
27
30
  import { createRoomLedger } from './room-events';
28
31
  import { applyMessageReaction, type MessageReactionSnapshot } from './message-reactions';
29
32
  import { useConversationStream } from './use-conversation-stream';
30
33
  import { useRoomEvents } from './use-room-events';
31
34
  import { useGemieRealtime } from '../realtime/react';
32
- import { bumpConversation, mergeMessages } from '../realtime/cache';
33
35
  import type { RealtimeData } from '../realtime/contract';
34
36
  import { normalizeConversationMessages } from './message-history';
35
37
  import type { Message, SendOptions } from './types';
@@ -102,7 +104,7 @@ export function useConversationThread({
102
104
  clientContext,
103
105
  hostTools,
104
106
  }: UseConversationThreadOptions = {}) {
105
- const queryClient = useQueryClient();
107
+ const store = useStore();
106
108
  const labels = useLabels();
107
109
  const { host } = useGemieRuntime();
108
110
  const { user } = useOxy();
@@ -114,27 +116,31 @@ export function useConversationThread({
114
116
  const wasLoadingRef = useRef(false);
115
117
 
116
118
  const pendingInitialMessage = useConversationStore((state) => state.pendingInitialMessage);
119
+ // A rewritten thread (an edit or a regenerate on another device) is read again and replaces
120
+ // the screen's, unless a turn of this device is writing it now.
121
+ const loadingRef = useRef(false);
117
122
  const {
118
- data: conversation,
123
+ value: conversation,
119
124
  error: conversationQueryError,
120
125
  isLoading: conversationQueryLoading,
121
126
  isFetching: conversationFetching,
122
- } = useConversation(conversationId || '');
123
- const createConversationMutation = useCreateConversation();
124
- const { mutateAsync: deleteConversation } = useDeleteConversation();
125
- const { mutateAsync: clearMessages } = useClearConversation();
127
+ } = useConversation(conversationId || undefined, {
128
+ onReload: (fresh) => {
129
+ if (!loadingRef.current) setMessages(fresh.messages ?? []);
130
+ },
131
+ });
132
+ const { run: createConversation } = useCreateConversation();
133
+ const { run: deleteConversation } = useDeleteConversation();
134
+ const { run: clearMessages } = useClearConversation();
126
135
 
127
136
  // A missing row is not a transient loading failure and the URL cannot become
128
- // useful by staying open. Remove its cached detail/list state and return to a
129
- // valid composer; the query itself has retries disabled, so this happens once.
137
+ // useful by staying open. Drop it from the account's store (its record and every
138
+ // list) and return to a valid composer; its read is never retried, so this happens once.
130
139
  useEffect(() => {
131
140
  if (!(conversationQueryError instanceof ConversationNotFoundError)) return;
132
- queryClient.removeQueries({
133
- queryKey: gemieQueryKeys.conversations.detail(conversationQueryError.conversationId),
134
- });
135
- void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
141
+ withStore(store, () => forgetConversation(conversationQueryError.conversationId));
136
142
  host.closeConversation?.();
137
- }, [conversationQueryError, queryClient, host]);
143
+ }, [conversationQueryError, store, host]);
138
144
 
139
145
  // One per open conversation: which speaking turn each message draws (the request's and the room's).
140
146
  // biome-ignore lint/correctness/useExhaustiveDependencies: a new conversation is a new ledger
@@ -157,6 +163,8 @@ export function useConversationThread({
157
163
  suggestedNewConversation,
158
164
  dismissSuggestedNewConversation,
159
165
  agentRun,
166
+ approvals,
167
+ settleApproval,
160
168
  failedTurn,
161
169
  retryFailedTurn: retry,
162
170
  clearFailedTurn,
@@ -218,8 +226,10 @@ export function useConversationThread({
218
226
  useEffect(() => {
219
227
  if (wasLoadingRef.current === isLoading) return;
220
228
  wasLoadingRef.current = isLoading;
221
- if (isLoading && conversationId) bumpConversation(queryClient, conversationId, lastUserText);
222
- }, [isLoading, conversationId, queryClient, lastUserText]);
229
+ if (isLoading && conversationId) {
230
+ withStore(store, () => bumpConversation(conversationId, lastUserText));
231
+ }
232
+ }, [isLoading, conversationId, store, lastUserText]);
223
233
 
224
234
  // Sync chatId and load messages when conversation changes or when
225
235
  // seeded cache data upgrades to full data (messages go from empty to populated).
@@ -249,17 +259,14 @@ export function useConversationThread({
249
259
 
250
260
  // What this conversation gained elsewhere — a gemie writing on its own, a group member, another
251
261
  // device — arrives as the `conversation` event: merged by id, so the copy this device drew under
252
- // the same id is replaced, never doubled. A rewritten thread (an edit or a regenerate on another
253
- // device) is read again, unless a turn of this device is writing it now.
262
+ // the same id is replaced, never doubled.
254
263
  const realtime = useGemieRealtime();
255
- const readConversation = useReadConversation();
256
264
  const markRead = useMarkConversationRead();
257
265
  // Opening a conversation with something unread reads it.
258
266
  const openUnread = (conversation?.unreadCount ?? 0) > 0;
259
267
  useEffect(() => {
260
268
  if (conversationId && openUnread) markRead(conversationId);
261
269
  }, [conversationId, openUnread, markRead]);
262
- const loadingRef = useRef(isLoading);
263
270
  loadingRef.current = isLoading;
264
271
  useEffect(() => {
265
272
  if (!conversationId || !realtime) return;
@@ -272,20 +279,8 @@ export function useConversationThread({
272
279
  const incoming = normalizeConversationMessages(data.appended);
273
280
  setMessages((prev) => mergeMessages(prev, incoming));
274
281
  }
275
- if (data.reload && !loadingRef.current) {
276
- void queryClient
277
- .fetchQuery({
278
- queryKey: gemieQueryKeys.conversations.detail(conversationId),
279
- queryFn: () => readConversation(conversationId),
280
- staleTime: 0,
281
- })
282
- .then((fresh) => {
283
- if (!loadingRef.current) setMessages(fresh.messages);
284
- })
285
- .catch(() => undefined);
286
- }
287
282
  });
288
- }, [conversationId, realtime, setMessages, queryClient, readConversation, markRead]);
283
+ }, [conversationId, realtime, setMessages, markRead]);
289
284
 
290
285
  // Send pending initial message for new conversations
291
286
  useEffect(() => {
@@ -395,15 +390,11 @@ export function useConversationThread({
395
390
  */
396
391
  const ensureConversation = useCallback(async (): Promise<string | undefined> => {
397
392
  if (conversationId) return conversationId;
398
- try {
399
- const created = await createConversationMutation.mutateAsync({ agentId });
400
- host.openConversation?.(created.id);
401
- return created.id;
402
- } catch {
403
- // useCreateConversation.onError already told the person.
404
- return undefined;
405
- }
406
- }, [conversationId, createConversationMutation, agentId, host]);
393
+ // A refusal was already told (useCreateConversation's toast).
394
+ const created = await createConversation({ agentId }).catch(() => undefined);
395
+ if (created) host.openConversation?.(created.id);
396
+ return created?.id;
397
+ }, [conversationId, createConversation, agentId, host]);
407
398
 
408
399
  /** Leave this thread for an empty one. Nothing is deleted: the conversation stays in the list. */
409
400
  const startOver = useCallback(() => {
@@ -548,9 +539,9 @@ export function useConversationThread({
548
539
  * and nothing else, and the sync effect above, seeing a cached history and
549
540
  * no messages, read that as a data upgrade and hydrated it straight back
550
541
  * under a dialog that had just promised the action could not be undone.
551
- * `useClearConversation` empties the cache in its `onSuccess`, which has run
552
- * by the time `mutateAsync` resolves, so the local reset that follows has
553
- * nothing left to be undone by.
542
+ * `useClearConversation` empties the conversation's record, settled by the
543
+ * time `run` resolves, so the local reset that follows has nothing left to be
544
+ * undone by.
554
545
  *
555
546
  * A turn still streaming is stopped first rather than refused: the person
556
547
  * has just confirmed they want the thread empty, and an answer that kept
@@ -562,8 +553,8 @@ export function useConversationThread({
562
553
  * finished and stored, so the clear removes it — and the clear that follows
563
554
  * is of a thread nothing is writing to.
564
555
  *
565
- * A refusal keeps everything: the screen is not reset, the cache is not
566
- * touched, and the error is surfaced — a cleared view whose history returns
556
+ * A refusal keeps everything: the screen is not reset, the record is put
557
+ * back as it was, and the error is surfaced — a cleared view whose history returns
567
558
  * on the next fetch is exactly the state this exists to end. A turn that
568
559
  * could not be stopped is such a refusal.
569
560
  *
@@ -624,6 +615,8 @@ export function useConversationThread({
624
615
  suggestedNewConversation,
625
616
  dismissSuggestedNewConversation,
626
617
  agentRun,
618
+ approvals,
619
+ settleApproval,
627
620
  failedTurn,
628
621
  retryFailedTurn,
629
622
  };
@@ -1,54 +1,43 @@
1
- import { useQuery } from '@tanstack/react-query';
1
+ import { type RecordView, skip, useStore, withStore } from '@oxy.so/bloom-data';
2
+ import { useCallback } from 'react';
2
3
  import { useGemieApi } from './api';
3
- import { gemieQueryKeys } from './query-keys';
4
- import { AGENT_ROUTES, threadKey } from './routes';
5
- import { retryThreadRead } from './use-thread-history';
4
+ import { useAnswer } from './data/answer';
5
+ import { gemieThread, type GemieThreadInfo, threadHistory } from './data/threads';
6
+ import type { GemieThreadAddress } from './routes';
6
7
 
7
- /** A gemie's thread with the signed-in person, as `GET /agents/:id/thread` answers it. */
8
- export interface GemieThreadInfo {
9
- /** Who the thread is with. `name`, `handle` and `color` come from Oxy and may be `null` (Alia's do, until her account exists). */
10
- readonly agent: {
11
- readonly _id: string;
12
- readonly name: string | null;
13
- readonly handle: string | null;
14
- readonly character: unknown;
15
- readonly tagline: string;
16
- readonly description: string;
17
- };
18
- /** The active stretch: `GemieChatContent`'s `conversationId`, where the next turn goes. */
19
- readonly conversationId: string;
20
- /**
21
- * The thread row, for a gemie whose chats are loose (Alia): her thread is apart from them, and its
22
- * next stretch is `useCreateConversation({ threadId })`. `null` for any other gemie, whose thread is
23
- * every conversation the two hold.
24
- */
25
- readonly threadId: string | null;
26
- }
27
-
28
- /** How long the open thread is good: it changes when the person starts a stretch, which invalidates it. */
29
- const THREAD_STALE_MS = 5 * 60 * 1000;
8
+ export type { GemieThreadInfo } from './data/threads';
30
9
 
31
10
  /**
32
- * Open the person's thread with a gemie by its id — Alia's thread mode, since she has no handle
11
+ * Open the person's thread with a gemie by its id: Alia's thread mode, since she has no handle
33
12
  * (ADR 0034). The first open CREATES the thread and its first stretch, so ask only when the person
34
13
  * opens it, never to prefetch one nobody started.
35
14
  *
36
15
  * Render the chat with what it answers: `<GemieChatContent conversationId={thread.conversationId}
37
- * gemieThread={{ gemieId, threadId: thread.threadId }} />`. Keyed under `gemieQueryKeys.threads.all`,
38
- * so starting the next stretch from the chat moves this onto it.
16
+ * gemieThread={{ gemieId, threadId: thread.threadId }} />`. A message that may have started a new
17
+ * stretch (a realtime `conversation` event with appended messages) makes it stale, and starting the
18
+ * next stretch from the chat reads it again (`useRefreshGemieThread`).
19
+ */
20
+ export function useGemieThread(gemieId: string | undefined): RecordView<GemieThreadInfo> {
21
+ const api = useGemieApi();
22
+ return useAnswer(
23
+ gemieThread,
24
+ ...((gemieId?.length ?? 0) > 0 ? [api, { gemieId: gemieId as string }] : [skip]),
25
+ );
26
+ }
27
+
28
+ /**
29
+ * Read a thread again, with its history: after its next stretch started, the one that was live is
30
+ * history, and the pages held were read before its last turns existed.
39
31
  */
40
- export function useGemieThread(gemieId: string | undefined) {
32
+ export function useRefreshGemieThread(): (thread: GemieThreadAddress) => void {
41
33
  const api = useGemieApi();
42
- const address = { gemieId: gemieId ?? '' };
43
- return useQuery({
44
- queryKey: gemieQueryKeys.threads.all(threadKey(address)),
45
- queryFn: async (): Promise<GemieThreadInfo> => {
46
- const { data } = await api.get<GemieThreadInfo>(AGENT_ROUTES.thread(address));
47
- return data;
48
- },
49
- enabled: (gemieId?.length ?? 0) > 0,
50
- staleTime: THREAD_STALE_MS,
51
- // A 404 is an answer: the gemie does not exist or this person cannot open it.
52
- retry: retryThreadRead,
53
- });
34
+ const store = useStore();
35
+ return useCallback(
36
+ (thread) =>
37
+ withStore(store, () => {
38
+ void gemieThread.refresh(api, thread);
39
+ void threadHistory.refresh(api, thread);
40
+ }),
41
+ [api, store],
42
+ );
54
43
  }
@@ -63,7 +63,7 @@ export interface StartConversationOptions {
63
63
  export function useStartConversation({ agentId }: { agentId?: string } = {}) {
64
64
  const labels = useLabels();
65
65
  const { host } = useGemieRuntime();
66
- const { mutateAsync: createConversation } = useCreateConversation();
66
+ const { run: createConversation } = useCreateConversation();
67
67
  const upload = useDocumentUpload();
68
68
 
69
69
  return useCallback(
@@ -79,20 +79,9 @@ export function useStartConversation({ agentId }: { agentId?: string } = {}) {
79
79
  const built =
80
80
  attachments.length > 0 ? await buildMessageContent(text, attachments, upload) : null;
81
81
  reportDroppedAttachments(built?.dropped, labels);
82
- try {
83
- const conversation = await createConversation({ agentId });
84
- useConversationStore.getState().setPendingInitialMessage({
85
- conversationId: conversation.id,
86
- content: built ? built.content : text,
87
- text,
88
- attachments,
89
- mcpServerId: options?.mcpServerId ?? null,
90
- skillNames: options?.skillNames ?? [],
91
- });
92
- host.openConversation?.(conversation.id);
93
- return true;
94
- } catch {
95
- // useCreateConversation.onError already shows the toast.
82
+ // A refusal was already told (useCreateConversation's toast): the draft comes back.
83
+ const conversation = await createConversation({ agentId }).catch(() => undefined);
84
+ if (conversation === undefined) {
96
85
  useComposerDraftStore.getState().restore(draft, {
97
86
  text,
98
87
  attachments,
@@ -101,6 +90,16 @@ export function useStartConversation({ agentId }: { agentId?: string } = {}) {
101
90
  });
102
91
  return false;
103
92
  }
93
+ useConversationStore.getState().setPendingInitialMessage({
94
+ conversationId: conversation.id,
95
+ content: built ? built.content : text,
96
+ text,
97
+ attachments,
98
+ mcpServerId: options?.mcpServerId ?? null,
99
+ skillNames: options?.skillNames ?? [],
100
+ });
101
+ host.openConversation?.(conversation.id);
102
+ return true;
104
103
  },
105
104
  [labels, host, createConversation, agentId, upload],
106
105
  );
@@ -1,17 +1,16 @@
1
- import { useInfiniteQuery } from '@tanstack/react-query';
1
+ import { skip, useEntities, useList } from '@oxy.so/bloom-data';
2
2
  import { useMemo } from 'react';
3
3
  import { useGemieApi } from './api';
4
- import { errorStatus } from './error-utils';
5
- import { gemieQueryKeys } from './query-keys';
6
- import { AGENT_ROUTES, type GemieThreadAddress, threadKey } from './routes';
7
- import { type ThreadPage, threadHistory } from './thread/thread-history';
4
+ import { ThreadMessages, threadHistory as historySource } from './data/threads';
5
+ import type { GemieThreadAddress } from './routes';
6
+ import { type ThreadMessage, type WireThreadMessage, threadHistory } from './thread/thread-history';
8
7
 
9
8
  /**
10
9
  * Everything said in this thread before the conversation on screen, a page at a time, going back.
11
10
  *
12
11
  * The screen streams into the most recent conversation of the thread and knows nothing older;
13
12
  * the thread's messages route is what crosses the seams into the stretches before it. Pages are
14
- * pulled as the reader approaches the top, never eagerly — a thread has no end going backwards,
13
+ * pulled as the reader approaches the top, never eagerly: a thread has no end going backwards,
15
14
  * and the first page is already everything a reader who does not scroll will see.
16
15
  *
17
16
  * `nextCursor` is what says whether anything older remains, and it is the server's answer rather
@@ -20,9 +19,6 @@ import { type ThreadPage, threadHistory } from './thread/thread-history';
20
19
  * is long.
21
20
  */
22
21
 
23
- /** How many messages a page carries. The server clamps its own maximum. */
24
- const PAGE_SIZE = 50;
25
-
26
22
  /** Whether there is a thread to ask about: an address with a non-empty handle or gemie id. */
27
23
  export function isThreadAddress(
28
24
  thread: GemieThreadAddress | undefined,
@@ -31,9 +27,18 @@ export function isThreadAddress(
31
27
  return ('handle' in thread ? thread.handle : thread.gemieId).length > 0;
32
28
  }
33
29
 
34
- /** A 404 is the answer — the agent does not exist or is not the person's, and asking again does not change it. */
35
- export function retryThreadRead(failureCount: number, error: unknown): boolean {
36
- return errorStatus(error) !== 404 && failureCount < 2;
30
+ /** A thread list's messages (held newest first) in reading order, the active stretch left out. */
31
+ export function useHeldThreadMessages(
32
+ ids: readonly string[],
33
+ activeConversationId: string,
34
+ ): ThreadMessage[] {
35
+ const records = useEntities(ThreadMessages, ids);
36
+ return useMemo(() => {
37
+ const oldestFirst = records
38
+ .filter((message): message is WireThreadMessage => message !== undefined)
39
+ .reverse();
40
+ return threadHistory([{ messages: oldestFirst, nextCursor: null }], activeConversationId);
41
+ }, [records, activeConversationId]);
37
42
  }
38
43
 
39
44
  export function useThreadHistory(
@@ -41,33 +46,18 @@ export function useThreadHistory(
41
46
  activeConversationId: string | undefined,
42
47
  ) {
43
48
  const api = useGemieApi();
44
- const query = useInfiniteQuery({
45
- queryKey: gemieQueryKeys.threads.messages(thread === undefined ? '' : threadKey(thread)),
46
- queryFn: async ({ pageParam }): Promise<ThreadPage> => {
47
- if (thread === undefined) throw new Error('No thread to read');
48
- const { data } = await api.get<ThreadPage>(AGENT_ROUTES.threadMessages(thread), {
49
- params: { limit: PAGE_SIZE, before: pageParam },
50
- });
51
- return data;
52
- },
53
- initialPageParam: undefined as string | undefined,
54
- getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
55
- // Nothing to page through until the thread has answered which conversation is the live one:
56
- // without it every message would be history, including the ones already on screen.
57
- enabled: isThreadAddress(thread) && activeConversationId !== undefined,
58
- retry: retryThreadRead,
59
- });
60
-
61
- const messages = useMemo(
62
- () => threadHistory(query.data?.pages ?? [], activeConversationId ?? ''),
63
- [query.data?.pages, activeConversationId],
49
+ // Nothing to page through until the thread has answered which conversation is the live one:
50
+ // without it every message would be history, including the ones already on screen.
51
+ const view = useList(
52
+ historySource,
53
+ ...(isThreadAddress(thread) && activeConversationId !== undefined ? [api, thread] : [skip]),
64
54
  );
65
-
55
+ const messages = useHeldThreadMessages(view.ids, activeConversationId ?? '');
66
56
  return {
67
57
  messages,
68
58
  /** Whether a page older than the ones held remains to be asked for. */
69
- hasMore: query.hasNextPage,
70
- isLoadingMore: query.isFetchingNextPage,
71
- loadMore: query.fetchNextPage,
59
+ hasMore: view.hasMore,
60
+ isLoadingMore: view.isFetching && view.list !== undefined,
61
+ loadMore: view.more,
72
62
  };
73
63
  }