@gemies/sdk 9.2.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 (88) 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 +46 -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 +6 -2
  41. package/src/components/thread/ChatBubble.tsx +66 -25
  42. package/src/components/thread/GemieThread.tsx +25 -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/tool-call-status.ts +1 -1
  55. package/src/lib/utils.ts +1 -8
  56. package/src/realtime/react.tsx +9 -9
  57. package/src/realtime/reread.ts +28 -0
  58. package/src/realtime/store.ts +123 -0
  59. package/src/runtime/agents.ts +46 -27
  60. package/src/runtime/collections.ts +35 -136
  61. package/src/runtime/connected-accounts.ts +175 -88
  62. package/src/runtime/connectors.ts +244 -127
  63. package/src/runtime/conversations.ts +181 -607
  64. package/src/runtime/data/answer.ts +76 -0
  65. package/src/runtime/data/collections.ts +168 -0
  66. package/src/runtime/data/conversations.ts +626 -0
  67. package/src/runtime/data/reactions.ts +29 -0
  68. package/src/runtime/data/read.ts +37 -0
  69. package/src/runtime/data/threads.ts +149 -0
  70. package/src/runtime/index.ts +72 -8
  71. package/src/runtime/model.ts +0 -2
  72. package/src/runtime/routes.ts +2 -2
  73. package/src/runtime/sharing.ts +69 -56
  74. package/src/runtime/types.ts +8 -16
  75. package/src/runtime/use-bound-action.ts +27 -0
  76. package/src/runtime/use-conversation-stream.ts +8 -31
  77. package/src/runtime/use-conversation-thread.ts +40 -51
  78. package/src/runtime/use-gemie-thread.ts +32 -43
  79. package/src/runtime/use-start-conversation.ts +14 -15
  80. package/src/runtime/use-thread-history.ts +26 -36
  81. package/src/runtime/use-thread-search.ts +29 -76
  82. package/src/text.ts +0 -1
  83. package/src/voice.ts +0 -1
  84. package/src/components/Image.tsx +0 -12
  85. package/src/realtime/cache.ts +0 -257
  86. package/src/runtime/conversation-dates.ts +0 -31
  87. package/src/runtime/query-keys.ts +0 -66
  88. package/src/runtime/reaction-cache.ts +0 -45
@@ -0,0 +1,626 @@
1
+ /**
2
+ * The person's conversations, held in the signed-in account's `@oxy.so/bloom-data` store (the one
3
+ * Services' `OxyProvider` opens with the session): one `Conversations` record per conversation,
4
+ * the lists that order them (`ConversationList`, one per filter) and the writes that change them.
5
+ *
6
+ * Each account has its own store, so a switch never shows the previous account's conversations,
7
+ * and an answer that lands for an account that was left goes to its closed store and is dropped.
8
+ * Records and lists are copied to the account's durable store, so the sidebar paints from the last
9
+ * session.
10
+ *
11
+ * A conversation is two records, JSON throughout: its row (`Conversations`: what a list, a realtime
12
+ * event and the sidebar carry) and, once the conversation itself was read, its messages
13
+ * (`ConversationMessages`, whose copy on disk is bounded). A row arriving later never touches the
14
+ * messages.
15
+ */
16
+ import { action, currentStore, entity, list, source } from '@oxy.so/bloom-data';
17
+ import type { RealtimeConnection } from '../../realtime/connection';
18
+ import type { GemieApi } from '../api';
19
+ import type { OfflineConversationStore } from '../config';
20
+ import { errorStatus } from '../error-utils';
21
+ import { normalizeConversationMessages } from '../message-history';
22
+ import { createRandomUuid } from '../random-uuid';
23
+ import { API_ROUTES } from '../routes';
24
+ import type { Conversation, Message } from '../types';
25
+ import { rereadOn } from '../../realtime/reread';
26
+ import { gemieRead } from './read';
27
+
28
+ const PAGE_SIZE = 20;
29
+ const FIVE_MINUTES = 5 * 60_000;
30
+
31
+ /** What a conversation list may be narrowed to (`GET /v1/conversations?agentId=&app=&kind=`). */
32
+ export interface ConversationsFilter {
33
+ /** Only the conversations with this agent. */
34
+ agentId?: string;
35
+ /** Only the conversations started in this app, by its slug (`docs/agent-embedding.md` §6). */
36
+ app?: string;
37
+ /**
38
+ * The conversations the person's gemies have with each other (`gemies`, ADR 0042) instead of the
39
+ * person's own, which are the default and never include them.
40
+ */
41
+ kind?: 'gemies';
42
+ }
43
+
44
+ /** The list key of a filter: `all` for the person's own, unnarrowed list. */
45
+ export function conversationsKey({ agentId, app, kind }: ConversationsFilter = {}): string {
46
+ if (agentId === undefined && app === undefined && kind === undefined) return 'all';
47
+ return JSON.stringify([agentId ?? null, app ?? null, kind ?? null]);
48
+ }
49
+
50
+ /** The filter a list key was made from. */
51
+ export function filterOfKey(key: string): ConversationsFilter {
52
+ if (key === 'all') return {};
53
+ const [agentId, app, kind] = JSON.parse(key) as [string | null, string | null, 'gemies' | null];
54
+ return {
55
+ ...(agentId === null ? {} : { agentId }),
56
+ ...(app === null ? {} : { app }),
57
+ ...(kind === null ? {} : { kind }),
58
+ };
59
+ }
60
+
61
+ /** Whether a conversation belongs in a list of `filter`. */
62
+ export function matchesFilter(filter: ConversationsFilter, row: Conversation): boolean {
63
+ // The person's own lists never hold a conversation between their gemies, and that list holds
64
+ // nothing else (ADR 0042).
65
+ if ((filter.kind ?? 'person') !== (row.kind ?? 'person')) return false;
66
+ if (filter.agentId !== undefined && row.agentId !== filter.agentId) return false;
67
+ if (filter.app !== undefined && row.app !== filter.app) return false;
68
+ return true;
69
+ }
70
+
71
+ /** A signal that a conversation no longer exists on the server. */
72
+ export class ConversationNotFoundError extends Error {
73
+ readonly conversationId: string;
74
+
75
+ constructor(conversationId: string) {
76
+ super('Conversation not found');
77
+ this.conversationId = conversationId;
78
+ this.name = 'ConversationNotFoundError';
79
+ }
80
+ }
81
+
82
+ /**
83
+ * The offline copy of the conversations: what a session whose token failed (a 401) reads and
84
+ * writes instead of the server. Without a store configured it holds nothing, and the 401 is the
85
+ * caller's to handle.
86
+ */
87
+ export class OfflineConversations {
88
+ private readonly store: OfflineConversationStore | null;
89
+
90
+ constructor(store: OfflineConversationStore | null) {
91
+ this.store = store;
92
+ }
93
+
94
+ get available(): boolean {
95
+ return this.store !== null;
96
+ }
97
+
98
+ async read(): Promise<Conversation[]> {
99
+ const stored = await this.store?.getItem();
100
+ return stored ? (JSON.parse(stored) as Conversation[]) : [];
101
+ }
102
+
103
+ async write(conversations: Conversation[]): Promise<void> {
104
+ await this.store?.setItem(JSON.stringify(conversations));
105
+ }
106
+
107
+ async remove(id: string): Promise<void> {
108
+ if (!this.store) return;
109
+ try {
110
+ const conversations = await this.read();
111
+ const remaining = conversations.filter((conversation) => conversation.id !== id);
112
+ if (remaining.length !== conversations.length) await this.write(remaining);
113
+ } catch {
114
+ // A malformed offline copy cannot make a valid server answer invalid.
115
+ }
116
+ }
117
+ }
118
+
119
+ /** What the conversation reads and writes need; the hooks pass the provider's (`useConversationsClient`). */
120
+ export interface ConversationsClient {
121
+ api: GemieApi;
122
+ offline: OfflineConversations;
123
+ /** The title of a chat created while the session is unavailable. */
124
+ newChatTitle: string;
125
+ /** The chat's app, which labels a conversation it creates (`GemieRuntimeConfig.app`). */
126
+ app: string | undefined;
127
+ /** Told the account's realtime cursor each read carried, so no event is lost behind it. */
128
+ realtime: RealtimeConnection | null;
129
+ }
130
+
131
+ /** A conversation as the API answers it, with its optional fields. */
132
+ type ApiConversation = Conversation & { realtimeSeq?: number };
133
+
134
+ /** A list row: the conversation without messages, so it never empties a held conversation. */
135
+ function rowOf({ messages: _messages, realtimeSeq: _seq, ...row }: ApiConversation): Conversation {
136
+ return row;
137
+ }
138
+
139
+ /** Message content is a string or parts; a preview needs the text either way. */
140
+ function messageText(message: Message | undefined): string {
141
+ const content = message?.content;
142
+ if (typeof content === 'string') return content;
143
+ if (!content) return '';
144
+ return content
145
+ .map((part) => (typeof part.text === 'string' ? part.text : ''))
146
+ .join(' ')
147
+ .trim();
148
+ }
149
+
150
+ // ── Records and lists ───────────────────────────────────────────────
151
+
152
+ /** A conversation's row: everything but its messages. */
153
+ export const Conversations = entity<Conversation>('gemies.conversation', {
154
+ id: (conversation) => conversation.id,
155
+ persist: { version: 1 },
156
+ });
157
+
158
+ /** A conversation's messages, with its row (a ref into `Conversations`). */
159
+ export interface ConversationMessagesRecord {
160
+ readonly id: string;
161
+ readonly conversation: Conversation;
162
+ readonly messages: Message[];
163
+ }
164
+
165
+ /** How many conversations' messages the durable copy keeps: the ones written last. */
166
+ export const MAX_PERSISTED_CONVERSATIONS = 20;
167
+ /** How many of a conversation's messages the durable copy keeps: the last ones. */
168
+ export const MAX_PERSISTED_MESSAGES = 40;
169
+ /** The most a conversation's stored messages may weigh, as JSON. */
170
+ export const MAX_PERSISTED_BYTES = 150_000;
171
+
172
+ /** A message's text parts alone. */
173
+ function textOnly(message: Message): Message {
174
+ if (typeof message.content === 'string') return message;
175
+ const text = message.content.filter((part) => part.type === 'text');
176
+ return text.length === message.content.length ? message : { ...message, content: text };
177
+ }
178
+
179
+ /**
180
+ * What survives a restart of a conversation's messages, so reopening one draws its latest at once
181
+ * (and reads them again behind) instead of a skeleton: its last {@link MAX_PERSISTED_MESSAGES},
182
+ * never a turn still streaming or not yet stored by the server (a restart must not show a
183
+ * half-written reply as if it were the answer), text only (an image part can be a data URL of
184
+ * megabytes or a signed URL expired by the next visit), and at most {@link MAX_PERSISTED_BYTES},
185
+ * dropping the oldest messages first. Memory keeps them all.
186
+ */
187
+ export function trimConversationMessages(
188
+ record: ConversationMessagesRecord,
189
+ ): ConversationMessagesRecord {
190
+ let messages = record.messages
191
+ .filter((message) => !message.isStreaming && !message.unsaved)
192
+ .slice(-MAX_PERSISTED_MESSAGES)
193
+ .map(textOnly);
194
+ let trimmed = { ...record, messages };
195
+ while (messages.length > 1 && JSON.stringify(trimmed).length > MAX_PERSISTED_BYTES) {
196
+ messages = messages.slice(Math.ceil(messages.length / 4));
197
+ trimmed = { ...record, messages };
198
+ }
199
+ return trimmed;
200
+ }
201
+
202
+ export const ConversationMessages = entity<ConversationMessagesRecord>(
203
+ 'gemies.conversation-messages',
204
+ {
205
+ id: (record) => record.id,
206
+ refs: { conversation: Conversations },
207
+ persist: { version: 1, keep: MAX_PERSISTED_CONVERSATIONS, trim: trimConversationMessages },
208
+ },
209
+ );
210
+
211
+ /** A read conversation as its two records: the row, and its messages. */
212
+ export function messagesRecord(conversation: Conversation): ConversationMessagesRecord {
213
+ const { messages = [], ...row } = conversation;
214
+ return { id: conversation.id, conversation: row, messages };
215
+ }
216
+
217
+ /** A held conversation as readers see it: its row, with its messages once they were read. */
218
+ export function heldConversation(id: string): Conversation | undefined {
219
+ const row = Conversations.get(id);
220
+ const messages = ConversationMessages.get(id)?.messages;
221
+ return row && messages ? { ...row, messages } : row;
222
+ }
223
+
224
+ /** Forgets a conversation: its row (out of every list) and its messages. */
225
+ export function forgetConversation(id: string): void {
226
+ currentStore().batch(() => {
227
+ ConversationMessages.remove(id);
228
+ Conversations.remove(id);
229
+ });
230
+ }
231
+
232
+ /** The person's conversations, newest first, one list per filter (`conversationsKey`). */
233
+ export const ConversationList = list('gemies.conversations', { of: Conversations, persist: true });
234
+
235
+ /**
236
+ * The list of `filter`, a page at a time. A 401 is the session's to resolve, not a read to repeat.
237
+ */
238
+ export const conversationList = source(ConversationList, {
239
+ ...gemieRead,
240
+ key: (_client: ConversationsClient, filter: ConversationsFilter) => conversationsKey(filter),
241
+ stale: FIVE_MINUTES,
242
+ retry: (failureCount, error) =>
243
+ errorStatus(error) !== 401 && gemieRead.retry(failureCount, error),
244
+ load: async ({ cursor, signal }, client, { agentId, app, kind }) => {
245
+ const { data } = await client.api.get<{
246
+ conversations: ApiConversation[];
247
+ nextCursor: string | null;
248
+ hasMore: boolean;
249
+ realtimeSeq?: number;
250
+ }>(API_ROUTES.conversations.list, {
251
+ signal,
252
+ params: {
253
+ limit: PAGE_SIZE,
254
+ ...(cursor === undefined ? {} : { cursor }),
255
+ ...(agentId === undefined ? {} : { agentId }),
256
+ ...(app === undefined ? {} : { app }),
257
+ ...(kind === undefined ? {} : { kind }),
258
+ },
259
+ });
260
+ if (typeof data.realtimeSeq === 'number') client.realtime?.noteSnapshot(data.realtimeSeq);
261
+ return {
262
+ items: data.conversations.map(rowOf),
263
+ next: data.nextCursor,
264
+ hasMore: data.hasMore,
265
+ };
266
+ },
267
+ });
268
+
269
+ /** Reads one conversation with its messages, falling back to the offline copy on a 401. */
270
+ export async function fetchConversation(
271
+ client: ConversationsClient,
272
+ id: string,
273
+ signal?: AbortSignal,
274
+ ): Promise<Conversation> {
275
+ try {
276
+ const { data } = await client.api.get<ApiConversation>(API_ROUTES.conversations.get(id), {
277
+ signal,
278
+ });
279
+ if (typeof data.realtimeSeq === 'number') client.realtime?.noteSnapshot(data.realtimeSeq);
280
+ const { realtimeSeq: _seq, ...conversation } = data;
281
+ return { ...conversation, messages: normalizeConversationMessages(data.messages ?? []) };
282
+ } catch (error: unknown) {
283
+ const status = errorStatus(error);
284
+ // A server-side 404 is authoritative for an authenticated request. Keeping an older offline
285
+ // copy here resurrects a deleted conversation and makes every later read and write hit the
286
+ // same missing id again.
287
+ if (status === 404) {
288
+ await client.offline.remove(id);
289
+ throw new ConversationNotFoundError(id);
290
+ }
291
+ // An unavailable authenticated session can still read its offline copy.
292
+ if (status === 401) {
293
+ const conversation = (await client.offline.read()).find((c) => c.id === id);
294
+ if (conversation) {
295
+ return {
296
+ ...conversation,
297
+ messages: normalizeConversationMessages(conversation.messages ?? []),
298
+ };
299
+ }
300
+ }
301
+ throw error;
302
+ }
303
+ }
304
+
305
+ /**
306
+ * One conversation with its messages (its row stored beside them). A missing conversation is
307
+ * deterministic: retrying only repeats the same 404, so it is never retried (nor is a prefetch,
308
+ * which a refusal answers).
309
+ */
310
+ export const conversation = source(ConversationMessages, {
311
+ ...gemieRead,
312
+ key: (_client: ConversationsClient, id: string) => id,
313
+ stale: FIVE_MINUTES,
314
+ retry: 0,
315
+ load: async ({ signal }, client, id) =>
316
+ messagesRecord(await fetchConversation(client, id, signal)),
317
+ });
318
+
319
+ // A client too far behind the account's log reads its lists and conversations again.
320
+ rereadOn('reset', conversationList, conversation);
321
+
322
+ // ── Placement ───────────────────────────────────────────────────────
323
+
324
+ const timeOf = (row: Conversation | undefined): number => (row ? Date.parse(row.updatedAt) : 0);
325
+
326
+ /**
327
+ * A conversation as the server says it is now, where the lists' order puts it: newest
328
+ * `updatedAt` first, in every held list it belongs to, and out of every one it does not. A copy
329
+ * already newer than this one is kept (an event replayed over a fresher read). A row older than
330
+ * everything a list holds, not in it already, belongs to a page not read yet. Idempotent.
331
+ */
332
+ export function placeConversation(row: Conversation): void {
333
+ const store = currentStore();
334
+ const held = Conversations.get(row.id);
335
+ if (held && timeOf(held) > timeOf(row)) return;
336
+ store.batch(() => {
337
+ Conversations.put(row);
338
+ const time = timeOf(row);
339
+ for (const key of ConversationList.keys()) {
340
+ ConversationList.set(key, (current) => {
341
+ if (!current) return current;
342
+ const others = current.ids.filter((id) => id !== row.id);
343
+ const present = others.length !== current.ids.length;
344
+ if (!matchesFilter(filterOfKey(key), row)) {
345
+ return present ? { ...current, ids: others } : current;
346
+ }
347
+ const at = others.findIndex((id) => timeOf(Conversations.get(id)) <= time);
348
+ if (at < 0 && !present && current.hasMore) return current;
349
+ const ids = [...others];
350
+ ids.splice(at < 0 ? ids.length : at, 0, row.id);
351
+ return { ...current, ids };
352
+ });
353
+ }
354
+ });
355
+ }
356
+
357
+ /**
358
+ * The person just sent in a conversation: its row goes to the top of every list that shows it,
359
+ * with their words, now. The server's `conversation` event replaces this with what it stored.
360
+ */
361
+ export function bumpConversation(id: string, preview: string): void {
362
+ if (!Conversations.has(id)) return;
363
+ currentStore().batch(() => {
364
+ Conversations.merge(id, {
365
+ ...(preview ? { lastMessage: preview.slice(0, 100) } : {}),
366
+ updatedAt: new Date().toISOString(),
367
+ });
368
+ for (const key of ConversationList.keys()) {
369
+ if (ConversationList.get(key)?.ids.includes(id)) ConversationList.move(key, id, 0);
370
+ }
371
+ });
372
+ }
373
+
374
+ /** Messages merged by id: a copy the client drew under the same id is replaced, never doubled. */
375
+ export function mergeMessages(
376
+ previous: readonly Message[],
377
+ incoming: readonly Message[],
378
+ ): Message[] {
379
+ if (incoming.length === 0) return [...previous];
380
+ const next = [...previous];
381
+ for (const message of incoming) {
382
+ if (!message?.id) continue;
383
+ const index = next.findIndex((m) => m.id === message.id);
384
+ if (index >= 0) next[index] = { ...next[index], ...message };
385
+ else next.push(message);
386
+ }
387
+ return next;
388
+ }
389
+
390
+ /** A new or saved conversation at the top of the person's own list (`all`), if it is held. */
391
+ function toTop(id: string, moveExisting: boolean): void {
392
+ const held = ConversationList.get('all');
393
+ if (!held) return;
394
+ if (!held.ids.includes(id)) ConversationList.insert('all', [id], 0);
395
+ else if (moveExisting) ConversationList.move('all', id, 0);
396
+ }
397
+
398
+ /** Stores what a write answered: merged into the held records (keeping what it does not carry). */
399
+ function upsert(saved: Conversation): void {
400
+ const { conversation: row, messages } = messagesRecord(saved);
401
+ currentStore().batch(() => {
402
+ if (!Conversations.merge(row.id, row)) Conversations.put(row);
403
+ if (saved.messages === undefined || ConversationMessages.merge(row.id, { messages })) return;
404
+ const held = Conversations.get(row.id) ?? row;
405
+ ConversationMessages.put({ id: row.id, conversation: held, messages });
406
+ });
407
+ }
408
+
409
+ /** The row without its preview: what a clear leaves (`lastMessage` is not sent). */
410
+ function withoutPreview({ lastMessage: _last, ...rest }: Conversation): Conversation {
411
+ return rest;
412
+ }
413
+
414
+ /** Every held list read again: what a write the server reshaped (a clear) leaves behind. */
415
+ export function refreshConversationLists(client: ConversationsClient): void {
416
+ for (const key of ConversationList.keys()) {
417
+ void conversationList.refresh(client, filterOfKey(key));
418
+ }
419
+ }
420
+
421
+ /** One retry, a second later: the rule the runtime's writes always had. */
422
+ async function retryOnce<T>(write: () => Promise<T>): Promise<T> {
423
+ try {
424
+ return await write();
425
+ } catch {
426
+ await new Promise((resolve) => setTimeout(resolve, 1000));
427
+ return write();
428
+ }
429
+ }
430
+
431
+ // ── Writes ──────────────────────────────────────────────────────────
432
+
433
+ /**
434
+ * The person has seen a conversation: its unread count is zero at once here, and on every other
435
+ * surface through the server's `conversation` event. A refusal puts the count back.
436
+ */
437
+ export const markConversationRead = action({
438
+ key: (_client: ConversationsClient, id: string) => `gemies.conversation.read:${id}`,
439
+ optimistic: (_client, id) => {
440
+ Conversations.merge(id, { unreadCount: 0 });
441
+ },
442
+ run: async (client, id) => {
443
+ await client.api.post(API_ROUTES.conversations.read(id), {});
444
+ },
445
+ });
446
+
447
+ export interface SaveConversationInput {
448
+ id: string;
449
+ messages: Message[];
450
+ title?: string;
451
+ }
452
+
453
+ async function postSave(
454
+ client: ConversationsClient,
455
+ { id, messages, title }: SaveConversationInput,
456
+ ): Promise<Conversation> {
457
+ try {
458
+ const { data } = await retryOnce(() =>
459
+ client.api.post<ApiConversation>(API_ROUTES.conversations.save, {
460
+ conversationId: id,
461
+ messages,
462
+ ...(title && { title }),
463
+ ...(client.app === undefined ? {} : { app: client.app }),
464
+ }),
465
+ );
466
+ return {
467
+ id: data.id,
468
+ title: data.title,
469
+ lastMessage: data.lastMessage,
470
+ source: data.source,
471
+ app: data.app,
472
+ createdAt: data.createdAt,
473
+ updatedAt: data.updatedAt,
474
+ messages,
475
+ };
476
+ } catch (error: unknown) {
477
+ if (errorStatus(error) !== 401) throw error;
478
+ // Unauthorized: the offline copy keeps it.
479
+ const conversations = await client.offline.read();
480
+ const existing = conversations.find((c) => c.id === id);
481
+ const now = new Date().toISOString();
482
+ const saved: Conversation = {
483
+ id,
484
+ title:
485
+ title ||
486
+ messageText(messages.find((m) => m.role === 'user')).slice(0, 50) ||
487
+ client.newChatTitle,
488
+ lastMessage: messageText(messages[messages.length - 1]).slice(0, 100) || undefined,
489
+ createdAt: existing?.createdAt ?? now,
490
+ updatedAt: now,
491
+ messages,
492
+ };
493
+ await client.offline.write([saved, ...conversations.filter((c) => c.id !== id)]);
494
+ return saved;
495
+ }
496
+ }
497
+
498
+ /** Saves a conversation's messages (and title): drawn at once, put back if refused. */
499
+ export const saveConversation = action({
500
+ optimistic: (_client: ConversationsClient, { id, messages, title }: SaveConversationInput) => {
501
+ if (title) Conversations.merge(id, { title });
502
+ ConversationMessages.merge(id, { messages });
503
+ },
504
+ run: (client, input) => postSave(client, input),
505
+ settle: (saved: Conversation) => {
506
+ upsert(saved);
507
+ toTop(saved.id, true);
508
+ },
509
+ });
510
+
511
+ /**
512
+ * Renames a conversation. The API has no title-only route: `POST /conversations` writes the title
513
+ * AND replaces the messages, so the whole thread is read fresh first and saved back with the new
514
+ * title (a row seeded from a list has no messages, and saving it would empty the thread).
515
+ */
516
+ export const renameConversation = action({
517
+ key: (_client: ConversationsClient, id: string, _title: string) =>
518
+ `gemies.conversation.rename:${id}`,
519
+ optimistic: (_client, id, title) => {
520
+ Conversations.merge(id, { title });
521
+ },
522
+ run: async (client, id, title) => {
523
+ const fresh = await fetchConversation(client, id);
524
+ return postSave(client, { id, messages: fresh.messages ?? [], title });
525
+ },
526
+ settle: (saved: Conversation) => {
527
+ upsert(saved);
528
+ toTop(saved.id, true);
529
+ },
530
+ });
531
+
532
+ /** Deletes a conversation: it leaves every list at once, and comes back if refused. */
533
+ export const deleteConversation = action({
534
+ key: (_client: ConversationsClient, id: string) => `gemies.conversation.delete:${id}`,
535
+ optimistic: (_client, id) => {
536
+ for (const key of ConversationList.keys()) ConversationList.remove(key, [id]);
537
+ },
538
+ run: async (client, id) => {
539
+ try {
540
+ await retryOnce(() => client.api.delete(API_ROUTES.conversations.remove(id)));
541
+ } catch (error: unknown) {
542
+ if (errorStatus(error) !== 401) throw error;
543
+ // Unauthorized: it leaves the offline copy.
544
+ await client.offline.write((await client.offline.read()).filter((c) => c.id !== id));
545
+ }
546
+ return id;
547
+ },
548
+ settle: (id: string) => forgetConversation(id),
549
+ });
550
+
551
+ /**
552
+ * Empties a conversation on the server, keeping the conversation. Its messages go at once and come
553
+ * back exactly as they were if the server refuses; once it accepts, the row loses its preview (the
554
+ * server dropped `lastMessage` in the same transaction) and the conversation and the lists are
555
+ * read again, so the server's own answer (the moved `updatedAt`) replaces the local guess.
556
+ */
557
+ export const clearConversation = action({
558
+ key: (_client: ConversationsClient, id: string) => `gemies.conversation.clear:${id}`,
559
+ optimistic: (_client, id) => {
560
+ ConversationMessages.merge(id, { messages: [] });
561
+ },
562
+ run: async (client, id) => {
563
+ try {
564
+ await retryOnce(() => client.api.delete(API_ROUTES.conversations.clearMessages(id)));
565
+ } catch (error: unknown) {
566
+ if (errorStatus(error) !== 401) throw error;
567
+ // Unauthorized: the offline copy is emptied instead.
568
+ const now = new Date().toISOString();
569
+ await client.offline.write(
570
+ (await client.offline.read()).map((c) =>
571
+ c.id === id ? { ...withoutPreview(c), messages: [], updatedAt: now } : c,
572
+ ),
573
+ );
574
+ }
575
+ return id;
576
+ },
577
+ settle: (id: string, client: ConversationsClient) => {
578
+ Conversations.update(id, withoutPreview);
579
+ ConversationMessages.merge(id, { messages: [] });
580
+ void conversation.refresh(client, id);
581
+ refreshConversationLists(client);
582
+ },
583
+ });
584
+
585
+ export interface CreateConversationInput {
586
+ agentId?: string;
587
+ /** Two to six agents: a group conversation, answered by each in turn. */
588
+ agentIds?: readonly string[];
589
+ /** The thread row whose next stretch this is (`GemieThreadInfo.threadId`). */
590
+ threadId?: string;
591
+ }
592
+
593
+ /**
594
+ * Creates a conversation (optionally the next stretch of an agent's thread): it goes to the top of
595
+ * the person's list when the server answers with its id.
596
+ */
597
+ export const createConversation = action({
598
+ run: async (client: ConversationsClient, input: CreateConversationInput = {}) => {
599
+ try {
600
+ const { data } = await client.api.post<ApiConversation>(API_ROUTES.conversations.create, {
601
+ ...(input.agentId && { agentId: input.agentId }),
602
+ ...(input.agentIds && { agentIds: input.agentIds }),
603
+ ...(input.threadId && { threadId: input.threadId }),
604
+ ...(client.app === undefined ? {} : { app: client.app }),
605
+ });
606
+ return { ...rowOf(data), messages: [] };
607
+ } catch (error: unknown) {
608
+ if (errorStatus(error) !== 401 || !client.offline.available) throw error;
609
+ // Unauthorized: it is created in the offline copy.
610
+ const now = new Date().toISOString();
611
+ const created: Conversation = {
612
+ id: createRandomUuid(),
613
+ title: client.newChatTitle,
614
+ createdAt: now,
615
+ updatedAt: now,
616
+ messages: [],
617
+ };
618
+ await client.offline.write([created, ...(await client.offline.read())]);
619
+ return created;
620
+ }
621
+ },
622
+ settle: (created: Conversation) => {
623
+ ConversationMessages.put(messagesRecord(created));
624
+ toTop(created.id, false);
625
+ },
626
+ });
@@ -0,0 +1,29 @@
1
+ import { currentStore } from '@oxy.so/bloom-data';
2
+ import { applyMessageReaction, type MessageReactionSnapshot } from '../message-reactions';
3
+ import { ConversationMessages } from './conversations';
4
+ import { ThreadMessages, threadMessageKey } from './threads';
5
+
6
+ /**
7
+ * A saved reaction, wherever its message is held: in its conversation's messages, and in a
8
+ * thread's history or window. A copy newer than the update (a higher revision) is kept.
9
+ */
10
+ export function storeReaction(update: MessageReactionSnapshot): void {
11
+ currentStore().batch(() => {
12
+ ConversationMessages.patch(update.conversationId, (held) => ({
13
+ messages: applyMessageReaction(held.messages, update),
14
+ }));
15
+ const cursor = ThreadMessages.lookup(
16
+ 'message',
17
+ threadMessageKey(update.conversationId, update.messageId),
18
+ );
19
+ if (cursor === undefined) return;
20
+ ThreadMessages.patch(cursor, (held) =>
21
+ update.revision !== undefined && (held.reactionRevision ?? 0) > update.revision
22
+ ? undefined
23
+ : {
24
+ reactions: update.reactions,
25
+ ...(update.revision === undefined ? {} : { reactionRevision: update.revision }),
26
+ },
27
+ );
28
+ });
29
+ }
@@ -0,0 +1,37 @@
1
+ import { retryAfterSecondsOf } from '@oxy.so/core';
2
+ import { errorStatus } from '../error-utils';
3
+
4
+ /**
5
+ * The read options every Gemies source shares: the ones the Oxy SDK's React Query client gave
6
+ * every query the runtime ran on it, before Services 15. Retry only what another attempt can
7
+ * change (no answer at all, 408, 425, 429, 5xx), at most twice, never past a long `Retry-After`;
8
+ * back off as the refusal asked, or exponentially; and do not read again when the app comes to the
9
+ * front (the realtime connection keeps what is on screen current).
10
+ *
11
+ * bloom-data counts the first failure as 1. `stale` and any stricter `retry` stay per source.
12
+ */
13
+
14
+ const MAX_RETRIES = 2;
15
+ /** The longest a read waits, silently, for a refusal's `Retry-After`. */
16
+ const MAX_RETRY_AFTER_MS = 30_000;
17
+
18
+ const retryAfterMs = (error: unknown): number => (retryAfterSecondsOf(error) ?? 0) * 1000;
19
+
20
+ /** Whether another attempt can change a failure: the shared rule, before any source's own. */
21
+ export function retriesRead(failureCount: number, error: unknown): boolean {
22
+ if (failureCount > MAX_RETRIES) return false;
23
+ if (retryAfterMs(error) > MAX_RETRY_AFTER_MS) return false;
24
+ const status = errorStatus(error);
25
+ if (status === undefined) return true;
26
+ return status === 408 || status === 425 || status === 429 || status >= 500;
27
+ }
28
+
29
+ export const gemieRead = {
30
+ retry: retriesRead,
31
+ retryDelay: (failureCount: number, error: unknown) =>
32
+ retryAfterMs(error) || Math.min(1000 * 2 ** (failureCount - 1), 30_000),
33
+ refetchOnFocus: false,
34
+ } as const;
35
+
36
+ /** The key of a read the account makes once (its collections, its connected accounts). */
37
+ export const ACCOUNT = 'account';