@gemies/sdk 4.1.0 → 6.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.
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Realtime: the one socket a signed-in client holds to Gemies (`docs/realtime.mdx`). Mounted by
3
+ * `GemieRuntimeProvider`; a host listens with the hooks below for what is its own (credits, its
4
+ * lists, notifications), while the runtime's conversations, reactions, rooms and "typing…" are
5
+ * kept live by the SDK itself.
6
+ */
7
+
8
+ export {
9
+ GemieRealtimeProvider,
10
+ useGemieRealtime,
11
+ useRealtimeEvent,
12
+ useRealtimeReset,
13
+ useRealtimeTopic,
14
+ } from './react';
15
+ export {
16
+ useConversationActivity,
17
+ useRealtimeActivityStore,
18
+ type ActorActivityEntry,
19
+ } from './activity';
20
+ export type { RealtimeConnection, RealtimeListener } from './connection';
21
+ export {
22
+ REALTIME_DURABLE_TYPES,
23
+ REALTIME_SIGNAL_TYPES,
24
+ type ActivityState,
25
+ type RealtimeActivity,
26
+ type RealtimeConversationRow,
27
+ type RealtimeData,
28
+ type RealtimeDurableType,
29
+ type RealtimeFrame,
30
+ type RealtimeSignalType,
31
+ type RealtimeThreadTotal,
32
+ type RealtimeType,
33
+ } from './contract';
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The realtime connection in React (`docs/realtime.mdx`).
3
+ *
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
6
+ * in step with it. Everything else only listens: {@link useRealtimeEvent} for a type,
7
+ * {@link useRealtimeTopic} for an agent run, {@link useConversationActivity} for "typing…".
8
+ */
9
+
10
+ import { QueryClientContext } from '@tanstack/react-query';
11
+ import { useOxy } from '@oxy.so/services/ui/client';
12
+ import {
13
+ createContext,
14
+ type ReactNode,
15
+ useContext,
16
+ useEffect,
17
+ useMemo,
18
+ useRef,
19
+ useState,
20
+ } from 'react';
21
+ import { useRealtimeActivityStore } from './activity';
22
+ import { attachRealtimeCache } from './cache';
23
+ import { acquireRealtime, type RealtimeConnection, type RealtimeListener } from './connection';
24
+ import type { RealtimeActivity, RealtimeFrame, RealtimeType } from './contract';
25
+
26
+ interface RealtimeHold {
27
+ readonly apiUrl: string;
28
+ readonly connection: RealtimeConnection | null;
29
+ }
30
+
31
+ const RealtimeContext = createContext<RealtimeHold | null>(null);
32
+
33
+ /** Hold the signed-in account's connection to `apiUrl`; `null` while signed out. */
34
+ function useHeldConnection(apiUrl: string, enabled: boolean): RealtimeConnection | null {
35
+ const { oxyServices, user, canUsePrivateApi } = useOxy();
36
+ const account = enabled && canUsePrivateApi ? (user?.id ?? null) : null;
37
+ const [connection, setConnection] = useState<RealtimeConnection | null>(null);
38
+ // The connection is the account's: a new services object for the same account does not open
39
+ // another one (read when the connection is opened).
40
+ const servicesRef = useRef(oxyServices);
41
+ servicesRef.current = oxyServices;
42
+
43
+ useEffect(() => {
44
+ if (!account) {
45
+ setConnection(null);
46
+ return;
47
+ }
48
+ // The API's own token, refreshed by Oxy when it is due — never a captured one.
49
+ const linked = servicesRef.current.createLinkedClient({ baseURL: apiUrl });
50
+ const held = acquireRealtime(apiUrl, account, () => linked.getAccessToken(apiUrl));
51
+ setConnection(held.connection);
52
+ return () => {
53
+ held.release();
54
+ linked.dispose();
55
+ setConnection(null);
56
+ };
57
+ }, [apiUrl, account]);
58
+
59
+ return connection;
60
+ }
61
+
62
+ const activityHolders = new WeakMap<RealtimeConnection, { refs: number; detach: () => void }>();
63
+
64
+ /** Feed a connection's `activity` frames into the store, once per connection. */
65
+ function attachActivity(connection: RealtimeConnection): () => void {
66
+ const existing = activityHolders.get(connection);
67
+ if (existing) existing.refs++;
68
+ else {
69
+ const store = useRealtimeActivityStore.getState;
70
+ const offFrames = connection.on('activity', (frame) =>
71
+ store().apply(frame.data as RealtimeActivity),
72
+ );
73
+ // What happened while away is unknown: a stale "typing…" is worse than none.
74
+ const offStatus = connection.onStatus((connected) => {
75
+ if (!connected) store().clear();
76
+ });
77
+ activityHolders.set(connection, {
78
+ refs: 1,
79
+ detach: () => {
80
+ offFrames();
81
+ offStatus();
82
+ store().clear();
83
+ },
84
+ });
85
+ }
86
+ let released = false;
87
+ return () => {
88
+ if (released) return;
89
+ released = true;
90
+ const entry = activityHolders.get(connection);
91
+ if (!entry || --entry.refs > 0) return;
92
+ entry.detach();
93
+ activityHolders.delete(connection);
94
+ };
95
+ }
96
+
97
+ /**
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.
100
+ */
101
+ export function GemieRealtimeProvider({
102
+ apiUrl,
103
+ children,
104
+ }: {
105
+ apiUrl: string;
106
+ children: ReactNode;
107
+ }) {
108
+ const parent = useContext(RealtimeContext);
109
+ const inherited = parent !== null && parent.apiUrl === apiUrl;
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);
113
+ useEffect(() => {
114
+ if (inherited || !connection) return;
115
+ const detachCache = queryClient ? attachRealtimeCache(connection, queryClient) : undefined;
116
+ const detachActivity = attachActivity(connection);
117
+ return () => {
118
+ detachCache?.();
119
+ detachActivity();
120
+ };
121
+ }, [inherited, connection, queryClient]);
122
+ const value = useMemo<RealtimeHold>(
123
+ () => (inherited && parent ? parent : { apiUrl, connection }),
124
+ [inherited, parent, apiUrl, connection],
125
+ );
126
+ return <RealtimeContext.Provider value={value}>{children}</RealtimeContext.Provider>;
127
+ }
128
+
129
+ /** The account's realtime connection, or `null` while signed out or outside a runtime provider. */
130
+ export function useGemieRealtime(): RealtimeConnection | null {
131
+ return useContext(RealtimeContext)?.connection ?? null;
132
+ }
133
+
134
+ /** Call `handler` for every frame of `type` while mounted (the latest `handler`, without resubscribing). */
135
+ export function useRealtimeEvent<T extends RealtimeType | '*'>(
136
+ type: T,
137
+ handler: (frame: RealtimeFrame) => void,
138
+ ): void {
139
+ const connection = useGemieRealtime();
140
+ const ref = useRef(handler);
141
+ ref.current = handler;
142
+ useEffect(() => {
143
+ if (!connection) return;
144
+ const listener: RealtimeListener = (frame) => ref.current(frame);
145
+ return connection.on(type, listener);
146
+ }, [connection, type]);
147
+ }
148
+
149
+ /** Call `handler` when the client must reload what it shows (its cursor fell out of the log). */
150
+ export function useRealtimeReset(handler: () => void): void {
151
+ const connection = useGemieRealtime();
152
+ const ref = useRef(handler);
153
+ ref.current = handler;
154
+ useEffect(() => {
155
+ if (!connection) return;
156
+ return connection.onReset(() => ref.current());
157
+ }, [connection]);
158
+ }
159
+
160
+ /**
161
+ * Follow a topic (`agent:<id>`, `agent-session:<id>`) while mounted, and hear its frames. The
162
+ * server checks the person may; a refused topic simply never speaks.
163
+ */
164
+ export function useRealtimeTopic(
165
+ topic: string | null,
166
+ handler: (frame: RealtimeFrame) => void,
167
+ ): void {
168
+ const connection = useGemieRealtime();
169
+ const ref = useRef(handler);
170
+ ref.current = handler;
171
+ useEffect(() => {
172
+ if (!connection || !topic) return;
173
+ const release = connection.follow(topic);
174
+ const off = connection.on('agent.activity', (frame) => {
175
+ if (frame.topic === topic) ref.current(frame);
176
+ });
177
+ return () => {
178
+ off();
179
+ release();
180
+ };
181
+ }, [connection, topic]);
182
+ }
183
+
184
+ /**
185
+ * Hear the account's `activity` where no runtime provider holds the connection — an "Ask Alia"
186
+ * button an app draws on its own (`useGemieActivity`). Inside a provider it does nothing: the
187
+ * provider already feeds the store.
188
+ */
189
+ export function useRealtimeActivityFeed(apiUrl: string): void {
190
+ const inherited = useContext(RealtimeContext) !== null;
191
+ const connection = useHeldConnection(apiUrl, !inherited);
192
+ useEffect(() => {
193
+ if (!connection) return;
194
+ return attachActivity(connection);
195
+ }, [connection]);
196
+ }
@@ -1,8 +1,7 @@
1
- import type { MessageReactionUpdate } from './message-reactions';
2
1
  import { createContext, type ReactNode, useContext, useMemo } from 'react';
3
2
  import { GEMIES_API_URL } from '../lib/origins';
4
- import type { RoomEvent } from './room-events';
5
- import type { AgentRun, Message } from './types';
3
+ import type { AgentRun } from './types';
4
+ import { GemieRealtimeProvider } from '../realtime/react';
6
5
 
7
6
  /**
8
7
  * Where a signed-out session keeps its conversations, per account. The host
@@ -107,28 +106,6 @@ export interface GemieRuntimeHost {
107
106
  onAgentTurn?: (turn: AgentRun & { conversationId: string | null }) => void;
108
107
  /** The agent's row in the host's list, ahead of the server: your line, then her answer. */
109
108
  onTurnPreview?: (agentId: string | null | undefined, text: string) => void;
110
- /**
111
- * Messages an agent writes into the open conversation by itself (a result, a check-in).
112
- * Returns the unsubscribe.
113
- */
114
- subscribeConversationMessages?: (
115
- conversationId: string,
116
- listener: (message: Message) => void,
117
- ) => () => void;
118
- /** Authoritative reaction changes on existing messages, including another device. */
119
- subscribeConversationReactions?: (
120
- conversationId: string,
121
- listener: (update: MessageReactionUpdate) => void,
122
- ) => () => void;
123
- /**
124
- * Live actor responses (group turns or reactions in an agent chat): the host's `group:event` socket
125
- * event for this conversation. Returns the unsubscribe. Without it, what a group's members say
126
- * after the request ended appears on reload.
127
- */
128
- subscribeRoomEvents?: (
129
- conversationId: string,
130
- listener: (event: RoomEvent) => void,
131
- ) => () => void;
132
109
  /**
133
110
  * Show where the work of a turn is read — the host's right panel — now that the thread selected
134
111
  * one (`useThoughtStore`; the panel is `ThoughtPanel`). Return `false` to decline an
@@ -213,7 +190,12 @@ export function GemieRuntimeProvider({
213
190
  app: app ?? parent.app,
214
191
  };
215
192
  }, [apiUrl, offline, streamFetch, speech, host, app, parent]);
216
- return <GemieRuntimeContext.Provider value={value}>{children}</GemieRuntimeContext.Provider>;
193
+ return (
194
+ <GemieRuntimeContext.Provider value={value}>
195
+ {/* The account's one realtime connection, for everything below (`docs/realtime.mdx`). */}
196
+ <GemieRealtimeProvider apiUrl={value.apiUrl}>{children}</GemieRealtimeProvider>
197
+ </GemieRuntimeContext.Provider>
198
+ );
217
199
  }
218
200
 
219
201
  /** The runtime's configuration: the nearest provider's, or the defaults. */
@@ -1,5 +1,11 @@
1
1
  import { useOxy } from '@oxy.so/services/ui/client';
2
- import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
2
+ import {
3
+ keepPreviousData,
4
+ useInfiniteQuery,
5
+ useMutation,
6
+ useQuery,
7
+ useQueryClient,
8
+ } from '@tanstack/react-query';
3
9
  import * as WebBrowser from 'expo-web-browser';
4
10
  import { useCallback, useEffect, useRef } from 'react';
5
11
  import { Platform } from 'react-native';
@@ -13,9 +19,11 @@ import { useGemieRuntime } from './config';
13
19
  * (`mcp_notion__…`, `mcp_notion_2__…`) and its own grants to gemies, so which account a tool acts
14
20
  * on is always explicit.
15
21
  *
16
- * The store (`GemieConnectorsStore`) is where a person finds and connects one; Settings
17
- * (`GemieConnectedConnectors`) lists only what they connected. Both, and every logo
18
- * (`ConnectorLogo`), are the same in the Gemies and the Alia apps.
22
+ * The store (`GemieConnectorsStore`) is where a person finds and connects one: the providers'
23
+ * servers Gemies curates, and the remote servers synced from the official MCP Registry, each with
24
+ * its badge (`official`, `verified`, `community`). Settings (`GemieConnectedConnectors`) lists only
25
+ * what they connected. Both, and every logo (`ConnectorLogo`), are the same in the Gemies and the
26
+ * Alia apps.
19
27
  */
20
28
 
21
29
  /** The routes, on the Gemies API (credentialed, the Gemies and Alia origins). */
@@ -31,6 +39,7 @@ export const CONNECTOR_ROUTES = {
31
39
 
32
40
  export const connectorQueryKeys = {
33
41
  catalogue: ['gemie-connectors', 'catalogue'] as const,
42
+ store: (query: ConnectorStoreQuery) => ['gemie-connectors', 'catalogue', query] as const,
34
43
  connected: ['gemie-connectors', 'connected'] as const,
35
44
  };
36
45
 
@@ -39,21 +48,63 @@ export const CONNECTOR_CATEGORIES = [
39
48
  'development',
40
49
  'communication',
41
50
  'data',
51
+ 'design',
52
+ 'finance',
53
+ 'marketing',
54
+ 'commerce',
55
+ 'search',
56
+ 'other',
42
57
  ] as const;
43
58
  export type ConnectorCategory = (typeof CONNECTOR_CATEGORIES)[number];
44
59
 
45
- /** A connector of the catalogue: a provider's hosted MCP server this deployment can connect. */
60
+ /**
61
+ * Who stands behind a connector: `official` is the provider's own server (curated by Gemies, or
62
+ * published by a domain its publisher proved and reached on it), `verified` a proven domain's server
63
+ * reached elsewhere, `community` a server published by a GitHub account.
64
+ */
65
+ export const CONNECTOR_TRUST = ['official', 'verified', 'community'] as const;
66
+ export type ConnectorTrust = (typeof CONNECTOR_TRUST)[number];
67
+
68
+ export const CONNECTOR_SORTS = ['featured', 'name', 'recent'] as const;
69
+ export type ConnectorSort = (typeof CONNECTOR_SORTS)[number];
70
+
71
+ /** A connector of the store: a remote MCP server this deployment can connect. */
46
72
  export interface ConnectorEntry {
47
73
  id: string;
48
74
  name: string;
49
75
  description: string;
50
76
  category: ConnectorCategory;
51
77
  featured: boolean;
52
- docsUrl: string;
78
+ trust: ConnectorTrust;
79
+ /** `curated` by Gemies, or synced from the official MCP Registry. */
80
+ source: 'curated' | 'mcp_registry';
81
+ /** `oauth` opens the provider's sign-in; `none` connects at once. */
82
+ signIn: 'oauth' | 'none';
83
+ /** How many tools it offers, when known before connecting. */
84
+ toolCount: number | null;
85
+ /** Where to read about it; `null` when its publisher gave no page. */
86
+ docsUrl: string | null;
53
87
  /** On the API's origin; `null` draws a monogram. */
54
88
  logoUrl: string | null;
55
89
  }
56
90
 
91
+ /** What the store shows: a search, a category, badges, only what needs no sign-in, an order. */
92
+ export interface ConnectorStoreQuery {
93
+ q?: string;
94
+ category?: ConnectorCategory;
95
+ trust?: readonly ConnectorTrust[];
96
+ noSignIn?: boolean;
97
+ sort?: ConnectorSort;
98
+ }
99
+
100
+ /** One page of the store, and each category's count under the same search and filters. */
101
+ export interface ConnectorStorePage {
102
+ servers: ConnectorEntry[];
103
+ total: number;
104
+ nextOffset: number | null;
105
+ categories: { id: ConnectorCategory; count: number }[];
106
+ }
107
+
57
108
  export type ConnectionStatus = 'installed' | 'running' | 'error';
58
109
 
59
110
  /** One account a person connected. */
@@ -77,16 +128,46 @@ export interface Connection {
77
128
  usedBy: { id: string; name: string }[];
78
129
  }
79
130
 
80
- /** The catalogue, as this deployment can connect it. */
81
- export function useConnectorCatalogue() {
131
+ /** How many entries one page of the store asks for. */
132
+ export const CONNECTOR_STORE_PAGE_SIZE = 30;
133
+
134
+ /** The query string the store route reads (`GET /mcp/registry`). */
135
+ export function connectorStoreParams(
136
+ query: ConnectorStoreQuery,
137
+ offset: number,
138
+ limit = CONNECTOR_STORE_PAGE_SIZE,
139
+ ): Record<string, string | number> {
140
+ return {
141
+ ...(query.q?.trim() ? { q: query.q.trim() } : {}),
142
+ ...(query.category ? { category: query.category } : {}),
143
+ ...(query.trust?.length ? { trust: query.trust.join(',') } : {}),
144
+ ...(query.noSignIn ? { signIn: 'none' } : {}),
145
+ ...(query.sort ? { sort: query.sort } : {}),
146
+ offset,
147
+ limit,
148
+ };
149
+ }
150
+
151
+ /**
152
+ * The store, a page at a time: hundreds of connectors are searched, filtered and sorted by the API,
153
+ * and a new search keeps the previous results on screen until the next arrive.
154
+ */
155
+ export function useConnectorStore(query: ConnectorStoreQuery) {
82
156
  const api = useGemieApi();
83
157
  const { isAuthenticated } = useOxy();
84
- return useQuery({
85
- queryKey: connectorQueryKeys.catalogue,
86
- queryFn: async () =>
87
- (await api.get<{ servers: ConnectorEntry[] }>(CONNECTOR_ROUTES.catalogue)).data.servers,
158
+ return useInfiniteQuery({
159
+ queryKey: connectorQueryKeys.store(query),
160
+ initialPageParam: 0,
161
+ queryFn: async ({ pageParam }) =>
162
+ (
163
+ await api.get<ConnectorStorePage>(CONNECTOR_ROUTES.catalogue, {
164
+ params: connectorStoreParams(query, pageParam),
165
+ })
166
+ ).data,
167
+ getNextPageParam: (last) => last.nextOffset ?? undefined,
88
168
  enabled: isAuthenticated,
89
169
  staleTime: 5 * 60_000,
170
+ placeholderData: keepPreviousData,
90
171
  });
91
172
  }
92
173
 
@@ -179,13 +260,16 @@ export function useConnectorActions({ returnTo }: ConnectorActionsOptions) {
179
260
  return complete.mutateAsync(result);
180
261
  };
181
262
 
263
+ /** A new account: through the provider's sign-in, or at once for a server that needs none. */
182
264
  const connect = useMutation({
183
265
  mutationFn: async (registryId: string) => {
184
- const { data } = await api.post<{ authorizationUrl: string }>(CONNECTOR_ROUTES.connect, {
185
- registryId,
186
- returnTo,
187
- });
188
- return signIn(data.authorizationUrl);
266
+ const { data } = await api.post<{ authorizationUrl?: string; server?: Connection }>(
267
+ CONNECTOR_ROUTES.connect,
268
+ { registryId, returnTo },
269
+ );
270
+ if (data.authorizationUrl) return signIn(data.authorizationUrl);
271
+ await refresh();
272
+ return data.server ?? null;
189
273
  },
190
274
  });
191
275
 
@@ -18,6 +18,8 @@ import { gemieQueryKeys, type ConversationsFilter } from './query-keys';
18
18
  import { API_ROUTES } from './routes';
19
19
  import { createRandomUuid } from './random-uuid';
20
20
  import type { Conversation, ConversationsInfiniteData, ConversationsPage, Message } from './types';
21
+ import type { RealtimeConnection } from '../realtime/connection';
22
+ import { useGemieRealtime } from '../realtime/react';
21
23
 
22
24
  /** Conversation as returned by the API (timestamps are ISO strings, not Dates). */
23
25
  type ApiConversation = Omit<Conversation, 'createdAt' | 'updatedAt' | 'messages'> & {
@@ -106,6 +108,8 @@ export interface ConversationsClient {
106
108
  newChatTitle: string;
107
109
  /** The chat's app, which labels a conversation it creates (`GemieRuntimeConfig.app`). */
108
110
  app: string | undefined;
111
+ /** Told the account's realtime cursor each read carried, so no event is lost behind it. */
112
+ realtime: RealtimeConnection | null;
109
113
  }
110
114
 
111
115
  /** The runtime's conversation client for the nearest provider. */
@@ -113,9 +117,16 @@ function useConversationsClient(): ConversationsClient {
113
117
  const api = useGemieApi();
114
118
  const { offline, app } = useGemieRuntime();
115
119
  const { newChat } = useLabels();
120
+ const realtime = useGemieRealtime();
116
121
  return useMemo(
117
- () => ({ api, offline: new OfflineConversations(offline), newChatTitle: newChat, app }),
118
- [api, offline, newChat, app],
122
+ () => ({
123
+ api,
124
+ offline: new OfflineConversations(offline),
125
+ newChatTitle: newChat,
126
+ app,
127
+ realtime,
128
+ }),
129
+ [api, offline, newChat, app, realtime],
119
130
  );
120
131
  }
121
132
 
@@ -129,6 +140,7 @@ async function fetchConversationsPage(
129
140
  conversations: ApiConversation[];
130
141
  nextCursor: string | null;
131
142
  hasMore: boolean;
143
+ realtimeSeq?: number;
132
144
  }>(API_ROUTES.conversations.list, {
133
145
  signal,
134
146
  params: {
@@ -138,6 +150,7 @@ async function fetchConversationsPage(
138
150
  ...(app === undefined ? {} : { app }),
139
151
  },
140
152
  });
153
+ if (typeof data.realtimeSeq === 'number') client.realtime?.noteSnapshot(data.realtimeSeq);
141
154
  return {
142
155
  conversations: data.conversations.map((conv) => ({
143
156
  ...conv,
@@ -226,7 +239,10 @@ export function useConversations({ agentId, app }: ConversationsFilter = {}) {
226
239
 
227
240
  async function fetchConversation(client: ConversationsClient, id: string): Promise<Conversation> {
228
241
  try {
229
- const { data } = await client.api.get<ApiConversation>(API_ROUTES.conversations.get(id));
242
+ const { data } = await client.api.get<ApiConversation & { realtimeSeq?: number }>(
243
+ API_ROUTES.conversations.get(id),
244
+ );
245
+ if (typeof data.realtimeSeq === 'number') client.realtime?.noteSnapshot(data.realtimeSeq);
230
246
  return {
231
247
  ...data,
232
248
  createdAt: new Date(data.createdAt),
@@ -273,6 +289,42 @@ export function useConversation(id: string | undefined) {
273
289
  });
274
290
  }
275
291
 
292
+ /** Read one conversation afresh, as `useConversation` would (a rewritten thread, reloaded). */
293
+ export function useReadConversation(): (id: string) => Promise<Conversation> {
294
+ const client = useConversationsClient();
295
+ return useCallback((id) => fetchConversation(client, id), [client]);
296
+ }
297
+
298
+ /**
299
+ * The person has seen a conversation: its unread count goes to zero here at once and on every
300
+ * other surface through the server's `conversation` event. Sent only when there is something
301
+ * unread, so an open conversation costs nothing while nothing arrives.
302
+ */
303
+ export function useMarkConversationRead(): (id: string) => void {
304
+ const queryClient = useQueryClient();
305
+ const client = useConversationsClient();
306
+ return useCallback(
307
+ (id) => {
308
+ const update = (c: Conversation) => (c.id === id ? { ...c, unreadCount: 0 } : c);
309
+ queryClient.setQueriesData<ConversationsInfiniteData>(
310
+ { queryKey: gemieQueryKeys.conversations.all },
311
+ (old) =>
312
+ old?.pages
313
+ ? {
314
+ ...old,
315
+ pages: old.pages.map((page) => ({
316
+ ...page,
317
+ conversations: page.conversations.map(update),
318
+ })),
319
+ }
320
+ : old,
321
+ );
322
+ void client.api.post(API_ROUTES.conversations.read(id), {}).catch(() => undefined);
323
+ },
324
+ [queryClient, client],
325
+ );
326
+ }
327
+
276
328
  /** Prefetch a conversation's detail (call from the sidebar on press-in / hover). */
277
329
  export function usePrefetchConversation(): (id: string) => void {
278
330
  const queryClient = useQueryClient();
@@ -25,6 +25,13 @@ export type {
25
25
  } from './config';
26
26
  export type { RoomEvent } from './room-events';
27
27
  export type { MessageReactionUpdate } from './message-reactions';
28
+ export {
29
+ useGemieRealtime,
30
+ useRealtimeEvent,
31
+ useRealtimeReset,
32
+ useRealtimeTopic,
33
+ } from '../realtime/react';
34
+ export { useConversationActivity } from '../realtime/activity';
28
35
  export { GemieApiError, useGemieApi } from './api';
29
36
  export {
30
37
  GEMIE_FEATURES,
@@ -87,6 +94,7 @@ export {
87
94
  useConversations,
88
95
  useCreateConversation,
89
96
  useDeleteConversation,
97
+ useMarkConversationRead,
90
98
  usePrefetchConversation,
91
99
  useRenameConversation,
92
100
  useSaveConversation,
@@ -25,6 +25,8 @@ export const API_ROUTES = {
25
25
  * what is being deleted is the message collection and nothing else.
26
26
  */
27
27
  clearMessages: (id: string) => `/v1/conversations/${id}/messages`,
28
+ /** The person has seen it: its unread count goes to zero on every surface. */
29
+ read: (id: string) => `/v1/conversations/${id}/read`,
28
30
  vote: (id: string, messageId: string) => `/v1/conversations/${id}/messages/${messageId}/vote`,
29
31
  react: (id: string, messageId: string) =>
30
32
  `/v1/conversations/${id}/messages/${messageId}/reactions`,
@@ -117,6 +117,11 @@ export interface Conversation {
117
117
  threadId?: string | null;
118
118
  /** The app the conversation started in, by its slug, or `null` for Alia's own surfaces. */
119
119
  app?: string | null;
120
+ /**
121
+ * Messages the person has not seen: what arrived while nobody watched (a gemie writing on its
122
+ * own, a group member answering in the background). The sidebar's badge; zeroed by reading it.
123
+ */
124
+ unreadCount?: number;
120
125
  createdAt: Date;
121
126
  updatedAt: Date;
122
127
  messages: Message[];