@gemies/sdk 9.2.0 → 10.0.1

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 (89) 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 +32 -10
  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/useAgentRunFailureToast.ts +34 -0
  51. package/src/hooks/useChatVoice.ts +2 -10
  52. package/src/hooks/useMessageReactions.ts +5 -5
  53. package/src/hooks/useThoughtScope.ts +9 -8
  54. package/src/index.ts +2 -3
  55. package/src/lib/tool-call-status.ts +1 -1
  56. package/src/lib/utils.ts +1 -8
  57. package/src/realtime/react.tsx +9 -9
  58. package/src/realtime/reread.ts +28 -0
  59. package/src/realtime/store.ts +123 -0
  60. package/src/runtime/agents.ts +46 -27
  61. package/src/runtime/collections.ts +35 -136
  62. package/src/runtime/connected-accounts.ts +175 -88
  63. package/src/runtime/connectors.ts +244 -127
  64. package/src/runtime/conversations.ts +181 -607
  65. package/src/runtime/data/answer.ts +76 -0
  66. package/src/runtime/data/collections.ts +168 -0
  67. package/src/runtime/data/conversations.ts +626 -0
  68. package/src/runtime/data/reactions.ts +29 -0
  69. package/src/runtime/data/read.ts +37 -0
  70. package/src/runtime/data/threads.ts +149 -0
  71. package/src/runtime/index.ts +72 -8
  72. package/src/runtime/model.ts +0 -2
  73. package/src/runtime/routes.ts +2 -2
  74. package/src/runtime/sharing.ts +69 -56
  75. package/src/runtime/types.ts +8 -16
  76. package/src/runtime/use-bound-action.ts +27 -0
  77. package/src/runtime/use-conversation-stream.ts +8 -31
  78. package/src/runtime/use-conversation-thread.ts +40 -51
  79. package/src/runtime/use-gemie-thread.ts +32 -43
  80. package/src/runtime/use-start-conversation.ts +14 -15
  81. package/src/runtime/use-thread-history.ts +26 -36
  82. package/src/runtime/use-thread-search.ts +29 -76
  83. package/src/text.ts +0 -1
  84. package/src/voice.ts +0 -1
  85. package/src/components/Image.tsx +0 -12
  86. package/src/realtime/cache.ts +0 -257
  87. package/src/runtime/conversation-dates.ts +0 -31
  88. package/src/runtime/query-keys.ts +0 -66
  89. package/src/runtime/reaction-cache.ts +0 -45
@@ -35,7 +35,7 @@ import {
35
35
  } from '@oxy.so/bloom/segmented-control';
36
36
  import { Muted, Text } from '@oxy.so/bloom/typography';
37
37
  import { useState } from 'react';
38
- import { View } from 'react-native';
38
+ import { View, StyleSheet } from 'react-native';
39
39
 
40
40
  /**
41
41
  * A tool result drawn inside the assistant turn, each card one block line of
@@ -170,9 +170,9 @@ function WeatherResult({ data }: { data: WeatherCardData }) {
170
170
  <AiChatMessageLine block>
171
171
  <Card>
172
172
  <CardHeader>
173
- <View className="flex-row items-center gap-3">
173
+ <View style={styles.weatherHeader}>
174
174
  <IconCircle icon={conditionIcon(data.current.condition)} size="lg" />
175
- <View className="min-w-0 flex-1">
175
+ <View style={styles.weatherText}>
176
176
  <Muted>{data.place}</Muted>
177
177
  <Text variant="title-1-medium">{degrees(data.current.temperature, unit)}</Text>
178
178
  <Muted>{t(`weather.condition.${data.current.condition}`)}</Muted>
@@ -230,7 +230,7 @@ function ScheduledTaskResult({ data }: { data: ScheduledTaskCardData }) {
230
230
  title={data.objective}
231
231
  subtitle={triggerLabel(data.trigger, t)}
232
232
  trailing={
233
- <View className="flex-row items-center gap-2">
233
+ <View style={styles.trailing}>
234
234
  <Badge
235
235
  variant="subtle"
236
236
  color={data.enabled ? 'success' : 'default'}
@@ -252,3 +252,9 @@ function ScheduledTaskResult({ data }: { data: ScheduledTaskCardData }) {
252
252
  </AiChatMessageLine>
253
253
  );
254
254
  }
255
+
256
+ const styles = StyleSheet.create({
257
+ weatherHeader: { flexDirection: 'row', alignItems: 'center', gap: 12 },
258
+ weatherText: { minWidth: 0, flexGrow: 1, flexShrink: 1, flexBasis: '0%' },
259
+ trailing: { flexDirection: 'row', alignItems: 'center', gap: 8 },
260
+ });
@@ -20,7 +20,7 @@ import {
20
20
  } from '@oxy.so/bloom/message-media';
21
21
  import { useFileDownloadUrl, useOxy } from '@oxy.so/services/ui/client';
22
22
  import { useEffect, useMemo, useRef, useState } from 'react';
23
- import { Linking, View } from 'react-native';
23
+ import { Linking, View, StyleSheet } from 'react-native';
24
24
  import { useLabels } from '../../lib/labels';
25
25
  import { loadExpoAudio } from '../../lib/deferred/expo-audio';
26
26
  import {
@@ -28,7 +28,7 @@ import {
28
28
  type MessageContent,
29
29
  type TurnAttachment,
30
30
  } from '../../lib/content-utils';
31
- import { Image } from '../Image';
31
+ import { Image } from 'expo-image';
32
32
 
33
33
  type Tone = 'incoming' | 'outgoing';
34
34
  /** The bubble's tone, and its own foreground when the app paints a custom bubble. */
@@ -67,7 +67,7 @@ function StoredImage({ file, tone, onColor }: { file: FileAttachment } & Paint)
67
67
  accessibilityLabel={file.description ?? t('chat.attachment.sticker')}
68
68
  />
69
69
  ) : (
70
- <View className="size-32 rounded-xl bg-surface-secondary" />
70
+ <View style={styles.imagePlaceholder} />
71
71
  );
72
72
  }
73
73
  return url ? (
@@ -81,7 +81,7 @@ function StoredImage({ file, tone, onColor }: { file: FileAttachment } & Paint)
81
81
  onPress={() => void Linking.openURL(url)}
82
82
  />
83
83
  ) : (
84
- <View className="h-40 w-60 rounded-2xl bg-surface-secondary" />
84
+ <View style={styles.videoPlaceholder} />
85
85
  );
86
86
  }
87
87
 
@@ -152,8 +152,8 @@ function StoredFile({ file, tone, onColor }: { file: FileAttachment } & Paint) {
152
152
  function Attachment({ item, tone, onColor }: { item: TurnAttachment } & Paint) {
153
153
  if (item.type === 'inline-image') {
154
154
  return (
155
- <View className="size-[120px] overflow-hidden rounded-xl">
156
- <Image source={{ uri: item.url }} className="h-full w-full" contentFit="cover" />
155
+ <View style={styles.imageFrame}>
156
+ <Image source={{ uri: item.url }} style={styles.image} contentFit="cover" />
157
157
  </View>
158
158
  );
159
159
  }
@@ -179,10 +179,10 @@ export function TurnAttachments({
179
179
  const runs = attachmentRuns(getAttachmentsFromContent(content));
180
180
  if (runs.length === 0) return null;
181
181
  return (
182
- <View className="gap-2">
182
+ <View style={styles.attachments}>
183
183
  {runs.map((run) =>
184
184
  Array.isArray(run) ? (
185
- <View key={`images:${run[0]?.url}`} className="flex-row flex-wrap gap-2">
185
+ <View key={`images:${run[0]?.url}`} style={styles.imageRow}>
186
186
  {run.map((item) => (
187
187
  <Attachment key={item.url} item={item} tone={tone} onColor={onColor} />
188
188
  ))}
@@ -216,3 +216,12 @@ function attachmentRuns(items: readonly TurnAttachment[]): Array<InlineImage[] |
216
216
  export function hasAttachments(content: MessageContent | null | undefined): boolean {
217
217
  return getAttachmentsFromContent(content).length > 0;
218
218
  }
219
+
220
+ const styles = StyleSheet.create({
221
+ imagePlaceholder: { width: 128, height: 128, borderRadius: 12 },
222
+ videoPlaceholder: { height: 160, width: 240, borderRadius: 16 },
223
+ imageFrame: { width: 120, height: 120, overflow: 'hidden', borderRadius: 12 },
224
+ image: { height: '100%', width: '100%' },
225
+ attachments: { gap: 8 },
226
+ imageRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
227
+ });
@@ -10,6 +10,7 @@ import { VoiceControls as BloomVoiceControls, type VoiceState } from '@oxy.so/bl
10
10
  import { View } from 'react-native';
11
11
  import { VOICE_CONTROLS_LABELS, type VoiceControlsLabels } from '../../lib/voice-controls-labels';
12
12
  import type { RoomState, AgentState, VoiceCallState } from '../../types';
13
+ import { createTokenStyles } from '@oxy.so/bloom/theme';
13
14
 
14
15
  export { VOICE_CONTROLS_LABELS, type VoiceControlsLabels };
15
16
 
@@ -70,17 +71,14 @@ export function VoiceControls({
70
71
  callState,
71
72
  labels: labelOverrides,
72
73
  }: VoiceControlsProps) {
74
+ const styles = useStyles();
73
75
  const labels = { ...VOICE_CONTROLS_LABELS, ...labelOverrides };
74
76
  const statusText = getStatusText(roomState, agentState, isMuted, notice, labels, callState);
75
77
 
76
78
  return (
77
- <View className="items-center gap-4 pb-6 pt-4">
79
+ <View style={styles.controls}>
78
80
  {statusText ? (
79
- <Text
80
- className="text-lg font-medium text-text-primary"
81
- accessibilityLiveRegion="polite"
82
- aria-live="polite"
83
- >
81
+ <Text style={styles.status} accessibilityLiveRegion="polite" aria-live="polite">
84
82
  {statusText}
85
83
  </Text>
86
84
  ) : null}
@@ -104,3 +102,8 @@ export function VoiceControls({
104
102
  </View>
105
103
  );
106
104
  }
105
+
106
+ const useStyles = createTokenStyles((t) => ({
107
+ controls: { alignItems: 'center', gap: 16, paddingTop: 16, paddingBottom: 24 },
108
+ status: { fontSize: 18, fontWeight: 500, color: t.foreground, lineHeight: 28 },
109
+ }));
package/src/connectors.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="nativewind/types" />
2
1
  /**
3
2
  * The connectors leaf entry: the remote MCP servers a person connects — the providers' own
4
3
  * (Notion, Linear, Slack…), the hundreds synced from the official MCP Registry — and their own MCP
@@ -22,10 +21,20 @@ export {
22
21
  CONNECTOR_STORE_PAGE_SIZE,
23
22
  CONNECTOR_TRUST,
24
23
  CONNECTORS_PATH,
24
+ addCustomConnector,
25
+ completeConnectorSignIn,
26
+ connectConnector,
25
27
  connectionOfTool,
26
- connectorQueryKeys,
28
+ connections,
29
+ ConnectorEntries,
27
30
  connectorReturnTo,
31
+ connectorStore,
32
+ connectorStoreKey,
33
+ ConnectorStoreList,
28
34
  connectorStoreParams,
35
+ disconnectConnector,
36
+ reconnectConnector,
37
+ renameConnector,
29
38
  signInResult,
30
39
  useConnectionOfTool,
31
40
  useConnections,
@@ -40,7 +49,11 @@ export type {
40
49
  ConnectorCategory,
41
50
  ConnectorEntry,
42
51
  ConnectorSort,
52
+ ConnectorClient,
53
+ ConnectorStoreExtra,
43
54
  ConnectorStorePage,
44
55
  ConnectorStoreQuery,
56
+ ConnectorStoreView,
57
+ CustomConnectorInput,
45
58
  ConnectorTrust,
46
59
  } from './runtime/connectors';
@@ -0,0 +1,34 @@
1
+ import { useLabels } from '../lib/labels';
2
+ import type { AgentActivityState } from '../runtime/thread/agent-activity';
3
+ import { toast } from '@oxy.so/bloom/toast';
4
+ import { useEffect } from 'react';
5
+
6
+ /** One toast for the run that failed, replaced by the next failure. */
7
+ export const AGENT_RUN_FAILURE_TOAST_ID = 'agent-run-failure';
8
+ const AGENT_RUN_FAILURE_TOAST_MS = 10_000;
9
+
10
+ /**
11
+ * A run that ended in error is told with a toast, never with a panel in the conversation: the
12
+ * thread keeps the person's words and the agent's, and a failure is not part of either. The words
13
+ * are the server's (why it failed), under the app's own line. A run that ended well still leaves its
14
+ * summary card (`AgentResultCard`); this is for the one that did not, unless the turn's own failure
15
+ * toast already told it.
16
+ */
17
+ export function useAgentRunFailureToast(
18
+ activity: AgentActivityState | null | undefined,
19
+ failedTurn?: unknown,
20
+ ) {
21
+ const { t } = useLabels();
22
+ // When the turn itself failed, its own toast already says so (`useFailedTurnToast`).
23
+ const failed = activity?.isComplete === true && activity.hasError && !failedTurn;
24
+ const detail = activity?.lastError ?? undefined;
25
+
26
+ useEffect(() => {
27
+ if (!failed) return;
28
+ toast.error(t('chat.agentRun.taskFailed'), {
29
+ id: AGENT_RUN_FAILURE_TOAST_ID,
30
+ description: detail,
31
+ duration: AGENT_RUN_FAILURE_TOAST_MS,
32
+ });
33
+ }, [failed, detail, t]);
34
+ }
@@ -1,11 +1,10 @@
1
1
  import { useOxy } from '@oxy.so/services/ui/client';
2
- import { useQueryClient } from '@tanstack/react-query';
3
2
  import { useCallback, useEffect, useMemo, useRef } from 'react';
4
3
  import type { GemieAvatarState } from '../components/GemieAvatar';
5
4
  import { callThread } from '../lib/call-thread';
6
5
  import { turnActivityState } from '../lib/turn-state';
7
6
  import { useGemieRuntime } from '../runtime/config';
8
- import { gemieQueryKeys } from '../runtime/query-keys';
7
+ import { useRefreshConversation } from '../runtime/conversations';
9
8
  import type { Message } from '../runtime/types';
10
9
  import { type SoundSources, useVoiceSoundEffects } from './useSoundEffects';
11
10
  import { type UseVoiceLauncherOptions, useVoiceLauncher } from './useVoiceLauncher';
@@ -58,19 +57,12 @@ export function useChatVoice({
58
57
  }: UseChatVoiceOptions) {
59
58
  const runtime = useGemieRuntime();
60
59
  const { user } = useOxy();
61
- const queryClient = useQueryClient();
62
60
  const enabled = options !== false;
63
61
  const { sounds, ...launcherOptions }: GemieVoiceOptions =
64
62
  options === false || options === undefined ? {} : options;
65
63
  const { onCallEnded } = launcherOptions;
66
64
 
67
- const refreshConversation = useCallback(
68
- (id: string) => {
69
- void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.detail(id) });
70
- void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
71
- },
72
- [queryClient],
73
- );
65
+ const refreshConversation = useRefreshConversation();
74
66
 
75
67
  const launcher = useVoiceLauncher({
76
68
  apiUrl: runtime.apiUrl,
@@ -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, useMemo, useReducer, useRef } from 'react';
5
5
  import { useLabels } from '../lib/labels';
6
6
  import { useGemieApi } from '../runtime/api';
@@ -11,7 +11,7 @@ import {
11
11
  readMessageReactionAcknowledgement,
12
12
  type MessageReactionSnapshot,
13
13
  } from '../runtime/message-reactions';
14
- import { updateReactionCaches } from '../runtime/reaction-cache';
14
+ import { storeReaction } from '../runtime/data/reactions';
15
15
  import { useGemieRealtime } from '../realtime/react';
16
16
 
17
17
  const NONE: readonly string[] = [];
@@ -29,7 +29,7 @@ export function useMessageReactions({
29
29
  const { t } = useLabels();
30
30
  const api = useGemieApi();
31
31
  const { user } = useOxy();
32
- const queryClient = useQueryClient();
32
+ const store = useStore();
33
33
  const [version, changed] = useReducer((value: number) => value + 1, 0);
34
34
  const callbacks = useRef({ onChange, t });
35
35
  callbacks.current = { onChange, t };
@@ -54,12 +54,12 @@ export function useMessageReactions({
54
54
  },
55
55
  changed,
56
56
  confirmed: (update) => {
57
- updateReactionCaches(queryClient, update);
57
+ withStore(store, () => storeReaction(update));
58
58
  callbacks.current.onChange?.(update);
59
59
  },
60
60
  failed: () => toast.error(callbacks.current.t('chat.reactionFailed')),
61
61
  }),
62
- [api, queryClient, accountId],
62
+ [api, store, accountId],
63
63
  );
64
64
 
65
65
  useEffect(() => {
@@ -1,6 +1,7 @@
1
- import { useQueryClient } from '@tanstack/react-query';
1
+ import { useStore, withStore } from '@oxy.so/bloom-data';
2
2
  import { useEffect, useMemo } from 'react';
3
- import { gemieQueryKeys } from '../runtime/query-keys';
3
+ import { useConversationsClient } from '../runtime/conversations';
4
+ import { conversation } from '../runtime/data/conversations';
4
5
  import { type ThoughtScope, useThoughtStore } from '../runtime/thought-store';
5
6
  import type { FailedTurn } from '../runtime/turn-failure';
6
7
  import type { Message } from '../runtime/types';
@@ -24,8 +25,8 @@ export interface UseThoughtScopeOptions {
24
25
  * this only while the open selection belongs to the same conversation, so a new-chat screen
25
26
  * mounted underneath cannot blank a panel opened here.
26
27
  *
27
- * A load that failed is read off the query cache at the moment the memo recomputes: the load's
28
- * end is what flips `conversationLoading`, so the read is fresh exactly when it matters.
28
+ * A load that failed is read off the conversation's read state at the moment the memo recomputes:
29
+ * the load's end is what flips `conversationLoading`, so the read is fresh exactly when it matters.
29
30
  */
30
31
  export function useThoughtScope({
31
32
  conversationId,
@@ -34,14 +35,14 @@ export function useThoughtScope({
34
35
  isLoading,
35
36
  failedTurn,
36
37
  }: UseThoughtScopeOptions): ThoughtScope {
37
- const queryClient = useQueryClient();
38
+ const store = useStore();
39
+ const client = useConversationsClient();
38
40
  const sync = useThoughtStore((s) => s.sync);
39
41
 
40
42
  const scope = useMemo<ThoughtScope>(() => {
41
43
  const loadFailed =
42
44
  conversationId !== undefined &&
43
- queryClient.getQueryState(gemieQueryKeys.conversations.detail(conversationId))?.status ===
44
- 'error';
45
+ withStore(store, () => conversation.state(client, conversationId)).status === 'error';
45
46
  return {
46
47
  conversationId: conversationId ?? null,
47
48
  messages,
@@ -49,7 +50,7 @@ export function useThoughtScope({
49
50
  isLoading,
50
51
  failedTurn,
51
52
  };
52
- }, [conversationId, messages, conversationLoading, isLoading, failedTurn, queryClient]);
53
+ }, [conversationId, messages, conversationLoading, isLoading, failedTurn, store, client]);
53
54
 
54
55
  useEffect(() => {
55
56
  sync(scope);
package/src/index.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="nativewind/types" />
2
1
  // @gemies/sdk — the Gemies SDK
3
2
  // Reusable chat UI, voice, and streaming components for Oxy apps
4
3
 
@@ -123,8 +122,8 @@ export { GemieVoiceCall } from './components/voice/GemieVoiceCall';
123
122
  export { useVoiceLauncher, toastNotice } from './hooks/useVoiceLauncher';
124
123
  export type { UseVoiceLauncherOptions, VoiceLauncher } from './hooks/useVoiceLauncher';
125
124
 
126
- // ── UI Primitives (NativeWind) ──
127
- export { cn, formatFileSize } from './lib/utils';
125
+ // ── Utilities ──
126
+ export { formatFileSize } from './lib/utils';
128
127
  export { getToolLabel, getToolActiveLabel, getResearchActiveLabel } from './lib/tool-registry';
129
128
  export { getTextFromContent, getImagesFromContent } from './lib/content-utils';
130
129
 
@@ -20,7 +20,7 @@ export function toolCallStatus(
20
20
  result !== null &&
21
21
  typeof result === 'object' &&
22
22
  'error' in result &&
23
- Boolean((result as { error?: unknown }).error)
23
+ (result as { error?: unknown }).error
24
24
  ) {
25
25
  return 'error';
26
26
  }
package/src/lib/utils.ts CHANGED
@@ -1,10 +1,3 @@
1
- import { clsx, type ClassValue } from 'clsx';
2
- import { twMerge } from 'tailwind-merge';
3
-
4
- export function cn(...inputs: ClassValue[]) {
5
- return twMerge(clsx(inputs));
6
- }
7
-
8
1
  /** Extract a human-readable message from an unknown caught error. */
9
2
  export function errorMessage(err: unknown, fallback = 'Something went wrong'): string {
10
3
  if (err instanceof Error) return err.message;
@@ -31,5 +24,5 @@ export function formatFileSize(bytes: number): string {
31
24
  * `Math.log` of them is `NaN`, and `sizes[NaN]` is undefined too.
32
25
  */
33
26
  const i = Math.min(sizes.length - 1, Math.max(0, Math.floor(Math.log(bytes) / Math.log(k))));
34
- return `${String(Math.round((bytes / Math.pow(k, i)) * 100) / 100)} ${sizes[i]}`;
27
+ return `${String(Math.round((bytes / k ** i) * 100) / 100)} ${sizes[i]}`;
35
28
  }
@@ -2,12 +2,12 @@
2
2
  * The realtime connection in React (`docs/realtime.mdx`).
3
3
  *
4
4
  * {@link GemieRealtimeProvider} is mounted by `GemieRuntimeProvider`: it holds the signed-in
5
- * account's connection to the runtime's API and keeps the runtime's caches and the activity store
5
+ * account's connection to the runtime's API and keeps the account's store and the activity store
6
6
  * in step with it. Everything else only listens: {@link useRealtimeEvent} for a type,
7
7
  * {@link useRealtimeTopic} for an agent run, {@link useConversationActivity} for "typing…".
8
8
  */
9
9
 
10
- import { QueryClientContext } from '@tanstack/react-query';
10
+ import { useStore } from '@oxy.so/bloom-data';
11
11
  import { useOxy } from '@oxy.so/services/ui/client';
12
12
  import {
13
13
  createContext,
@@ -19,7 +19,7 @@ import {
19
19
  useState,
20
20
  } from 'react';
21
21
  import { useRealtimeActivityStore } from './activity';
22
- import { attachRealtimeCache } from './cache';
22
+ import { attachRealtimeStore } from './store';
23
23
  import { acquireRealtime, type RealtimeConnection, type RealtimeListener } from './connection';
24
24
  import type { RealtimeActivity, RealtimeFrame, RealtimeType } from './contract';
25
25
 
@@ -96,7 +96,7 @@ function attachActivity(connection: RealtimeConnection): () => void {
96
96
 
97
97
  /**
98
98
  * Mounted by `GemieRuntimeProvider`: the account's connection for everything below, wired into the
99
- * runtime's caches and the activity store. A nested provider on the same API shares its parent's.
99
+ * account's store and the activity store. A nested provider on the same API shares its parent's.
100
100
  */
101
101
  export function GemieRealtimeProvider({
102
102
  apiUrl,
@@ -108,17 +108,17 @@ export function GemieRealtimeProvider({
108
108
  const parent = useContext(RealtimeContext);
109
109
  const inherited = parent !== null && parent.apiUrl === apiUrl;
110
110
  const connection = useHeldConnection(apiUrl, !inherited);
111
- // A host without React Query has no runtime caches to keep; it still hears activity.
112
- const queryClient = useContext(QueryClientContext);
111
+ // The store is the signed-in account's: a switch re-attaches the connection to the next one.
112
+ const store = useStore();
113
113
  useEffect(() => {
114
114
  if (inherited || !connection) return;
115
- const detachCache = queryClient ? attachRealtimeCache(connection, queryClient) : undefined;
115
+ const detachStore = attachRealtimeStore(connection, store);
116
116
  const detachActivity = attachActivity(connection);
117
117
  return () => {
118
- detachCache?.();
118
+ detachStore();
119
119
  detachActivity();
120
120
  };
121
- }, [inherited, connection, queryClient]);
121
+ }, [inherited, connection, store]);
122
122
  const value = useMemo<RealtimeHold>(
123
123
  () => (inherited && parent ? parent : { apiUrl, connection }),
124
124
  [inherited, parent, apiUrl, connection],
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The reads a realtime signal makes stale, declared by the modules that own them: after a `reset`
3
+ * (the client fell too far behind the account's event log) and on `connections` (the person's
4
+ * connected accounts or connectors changed). The store's connection (`store.ts`) invalidates them
5
+ * in the account's store: a read on screen is read again at once, any other when it is next shown,
6
+ * however fresh it was.
7
+ */
8
+
9
+ export type RereadSignal = 'reset' | 'connections';
10
+
11
+ interface Invalidates {
12
+ invalidateAll(): void;
13
+ }
14
+
15
+ const sources: Record<RereadSignal, Set<Invalidates>> = {
16
+ reset: new Set(),
17
+ connections: new Set(),
18
+ };
19
+
20
+ /** Declares that `signal` makes every key of these sources stale. */
21
+ export function rereadOn(signal: RereadSignal, ...owned: Invalidates[]): void {
22
+ for (const source of owned) sources[signal].add(source);
23
+ }
24
+
25
+ /** Marks every key of the sources `signal` names stale, in the store in scope. */
26
+ export function invalidateOn(signal: RereadSignal): void {
27
+ for (const source of sources[signal]) source.invalidateAll();
28
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Realtime events into the signed-in account's store (`docs/realtime.mdx`).
3
+ *
4
+ * Every write here is an idempotent upsert of what the server says now (the conversation by id,
5
+ * a message by its id, a reaction by its revision), so applying an event twice, or again over a
6
+ * read that predates it (`noteSnapshot`), converges on the same state. What must be read again is
7
+ * invalidated, never read here: the reads a reset or a `connections` event makes stale
8
+ * (`reread.ts`), and a thread a new message may have moved onto another stretch. A rewritten
9
+ * conversation (`reload`) is read again by `useConversation`, which hands it to the thread.
10
+ */
11
+ import { currentStore, type Store, withStore } from '@oxy.so/bloom-data';
12
+ import { readCollectionsSnapshot } from '../runtime/collections-model';
13
+ import { storeCollections } from '../runtime/data/collections';
14
+ import {
15
+ ConversationMessages,
16
+ forgetConversation,
17
+ mergeMessages,
18
+ placeConversation,
19
+ } from '../runtime/data/conversations';
20
+ import { storeReaction } from '../runtime/data/reactions';
21
+ import { gemieThread } from '../runtime/data/threads';
22
+ import { normalizeConversationMessages } from '../runtime/message-history';
23
+ import type { Conversation } from '../runtime/types';
24
+ import type { RealtimeConnection } from './connection';
25
+ import type { RealtimeConversationRow, RealtimeData, RealtimeFrame } from './contract';
26
+ import { invalidateOn } from './reread';
27
+
28
+ function toConversation(row: RealtimeConversationRow): Conversation {
29
+ return {
30
+ id: row.id,
31
+ title: row.title,
32
+ ...(row.lastMessage === null ? {} : { lastMessage: row.lastMessage }),
33
+ source: row.source,
34
+ agentId: row.agentId,
35
+ memberAgentIds: row.memberAgentIds,
36
+ spaceId: row.spaceId,
37
+ ...(row.kind === undefined ? {} : { kind: row.kind }),
38
+ ...(row.members === undefined ? {} : { members: row.members }),
39
+ threadId: row.threadId,
40
+ app: row.app,
41
+ unreadCount: row.unreadCount,
42
+ createdAt: row.createdAt,
43
+ updatedAt: row.updatedAt,
44
+ };
45
+ }
46
+
47
+ /** Applies one frame to the store in scope. Pure store writes: safe to apply twice. */
48
+ export function applyRealtimeFrame(frame: RealtimeFrame): void {
49
+ switch (frame.type) {
50
+ case 'conversation': {
51
+ const data = frame.data as RealtimeData['conversation'];
52
+ const appended = data.appended ? normalizeConversationMessages(data.appended) : [];
53
+ currentStore().batch(() => {
54
+ placeConversation(toConversation(data.conversation));
55
+ if (appended.length === 0) return;
56
+ ConversationMessages.patch(data.conversation.id, (held) => ({
57
+ messages: mergeMessages(held.messages, appended),
58
+ }));
59
+ // A gemie's thread reads which stretch is active; a message may have started a new one.
60
+ gemieThread.invalidateAll();
61
+ });
62
+ return;
63
+ }
64
+ case 'conversation.deleted':
65
+ forgetConversation((frame.data as RealtimeData['conversation.deleted']).conversationId);
66
+ return;
67
+ case 'message.reaction': {
68
+ const update = frame.data as RealtimeData['message.reaction'];
69
+ storeReaction({ ...update, reactions: [...update.reactions] });
70
+ return;
71
+ }
72
+ case 'collections':
73
+ storeCollections(readCollectionsSnapshot(frame.data as RealtimeData['collections']));
74
+ return;
75
+ case 'connections':
76
+ invalidateOn('connections');
77
+ return;
78
+ default:
79
+ }
80
+ }
81
+
82
+ const attached = new WeakMap<
83
+ Store,
84
+ Map<RealtimeConnection, { refs: number; detach: () => void }>
85
+ >();
86
+
87
+ /**
88
+ * Keeps a store in step with a connection. Providers on the same connection and store attach the
89
+ * pair more than once; it is wired once and released with its last holder. Frames that arrive
90
+ * after the store's account was left go to its closed store, which drops them.
91
+ */
92
+ export function attachRealtimeStore(connection: RealtimeConnection, store: Store): () => void {
93
+ let byConnection = attached.get(store);
94
+ if (!byConnection) {
95
+ byConnection = new Map();
96
+ attached.set(store, byConnection);
97
+ }
98
+ const existing = byConnection.get(connection);
99
+ if (existing) existing.refs++;
100
+ else {
101
+ const offFrames = connection.on('*', (frame) =>
102
+ withStore(store, () => applyRealtimeFrame(frame)),
103
+ );
104
+ // Too far behind the account's log: everything it reads is stale.
105
+ const offReset = connection.onReset(() => withStore(store, () => invalidateOn('reset')));
106
+ byConnection.set(connection, {
107
+ refs: 1,
108
+ detach: () => {
109
+ offFrames();
110
+ offReset();
111
+ },
112
+ });
113
+ }
114
+ let released = false;
115
+ return () => {
116
+ if (released) return;
117
+ released = true;
118
+ const entry = byConnection?.get(connection);
119
+ if (!entry || --entry.refs > 0) return;
120
+ entry.detach();
121
+ byConnection?.delete(connection);
122
+ };
123
+ }