@gemies/sdk 5.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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. */
@@ -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,11 +94,25 @@ export {
87
94
  useConversations,
88
95
  useCreateConversation,
89
96
  useDeleteConversation,
97
+ useMarkConversationRead,
90
98
  usePrefetchConversation,
91
99
  useRenameConversation,
92
100
  useSaveConversation,
93
101
  } from './conversations';
94
102
  export { useConversationThread, mergeEditedContent } from './use-conversation-thread';
103
+ export {
104
+ importCollections,
105
+ useCollectionActions,
106
+ useConversationCollections,
107
+ } from './collections';
108
+ export type {
109
+ CollectionActions,
110
+ CollectionFields,
111
+ ConversationCollection,
112
+ ConversationCollectionKind,
113
+ ConversationCollections,
114
+ LocalCollections,
115
+ } from './collections';
95
116
  export type {
96
117
  ConversationThread,
97
118
  EditedContent,
@@ -11,6 +11,8 @@ export interface ConversationsFilter {
11
11
  }
12
12
 
13
13
  export const gemieQueryKeys = {
14
+ /** The person's folders, projects, pins and favourites (`runtime/collections.ts`). */
15
+ collections: ['conversation-collections'] as const,
14
16
  conversations: {
15
17
  all: ['conversations'] as const,
16
18
  detail: (id: string) => ['conversation', id] as const,
@@ -13,6 +13,15 @@ export const API_ROUTES = {
13
13
  chat: '/v1/chat/completions',
14
14
  /** The answer to an awaited host action, read by the turn that is waiting for it. */
15
15
  hostResults: (turnId: string) => `/v1/chat/turns/${encodeURIComponent(turnId)}/host-results`,
16
+ /** The person's folders and projects (`runtime/collections.ts`). */
17
+ collections: {
18
+ list: '/v1/conversations/collections',
19
+ create: '/v1/conversations/collections',
20
+ import: '/v1/conversations/collections/import',
21
+ one: (id: string) => `/v1/conversations/collections/${encodeURIComponent(id)}`,
22
+ member: (id: string, conversationId: string) =>
23
+ `/v1/conversations/collections/${encodeURIComponent(id)}/conversations/${encodeURIComponent(conversationId)}`,
24
+ },
16
25
  conversations: {
17
26
  list: '/v1/conversations',
18
27
  save: '/v1/conversations',
@@ -25,6 +34,10 @@ export const API_ROUTES = {
25
34
  * what is being deleted is the message collection and nothing else.
26
35
  */
27
36
  clearMessages: (id: string) => `/v1/conversations/${id}/messages`,
37
+ /** The person has seen it: its unread count goes to zero on every surface. */
38
+ read: (id: string) => `/v1/conversations/${id}/read`,
39
+ /** Its own marks: `{ pinned?, favorite? }`. */
40
+ marks: (id: string) => `/v1/conversations/${id}`,
28
41
  vote: (id: string, messageId: string) => `/v1/conversations/${id}/messages/${messageId}/vote`,
29
42
  react: (id: string, messageId: string) =>
30
43
  `/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[];
@@ -1,8 +1,7 @@
1
- import { useOxy } from '@oxy.so/services/ui/client';
2
1
  import { useCallback, useEffect, useState } from 'react';
3
- import { io } from 'socket.io-client';
2
+ import { useRealtimeTopic } from '../realtime/react';
3
+ import type { RealtimeFrame } from '../realtime/contract';
4
4
  import { useGemieApi } from './api';
5
- import { useGemieRuntime } from './config';
6
5
  import { AGENT_ROUTES } from './routes';
7
6
  import {
8
7
  type AgentActivityEvent,
@@ -17,11 +16,12 @@ import {
17
16
  export type UseAgentActivityResult = AgentActivityState;
18
17
 
19
18
  /**
20
- * Follow one agent run live: the session's room over Socket.IO, seeded with what the run had
21
- * already done (`GET` on its status, best-effort — the socket still carries live progress).
19
+ * Follow one agent run live: its session's topic on the account's realtime connection
20
+ * (`agent-session:<id>`, `docs/realtime.mdx`), seeded with what the run had already done (`GET` on
21
+ * its status, best-effort — the topic still carries live progress).
22
22
  *
23
23
  * @param sessionId - The agent session to follow; `null` follows nothing.
24
- * @param agentId - The agent's own room too, for the runs that announce themselves there.
24
+ * @param agentId - The agent's own topic too, for the runs that announce themselves there.
25
25
  */
26
26
  export function useAgentActivity(
27
27
  sessionId: string | null,
@@ -29,60 +29,33 @@ export function useAgentActivity(
29
29
  ): UseAgentActivityResult {
30
30
  const [state, setState] = useState<AgentActivityState>(INITIAL_ACTIVITY);
31
31
  const api = useGemieApi();
32
- const { apiUrl } = useGemieRuntime();
33
- const { oxyServices } = useOxy();
34
-
35
- const handleEvent = useCallback((event: AgentActivityEvent) => {
36
- setState((prev) => applyActivityEvent(prev, event));
37
- }, []);
38
32
 
39
33
  useEffect(() => {
40
34
  if (!sessionId) return;
41
-
42
35
  setState(INITIAL_ACTIVITY);
43
36
  let cancelled = false;
44
-
45
37
  api
46
38
  .get<AgentSessionStatus>(AGENT_ROUTES.sessionStatus(sessionId))
47
39
  .then(({ data }) => {
48
40
  if (!cancelled) setState((prev) => hydrateActivity(prev, data, sessionId));
49
41
  })
50
42
  .catch(() => {
51
- // Socket updates still provide live progress; hydration is best-effort.
43
+ // The topic still provides live progress; hydration is best-effort.
52
44
  });
53
-
54
- // The API's own token, refreshed when due (the session's base token is not, for this origin).
55
- const linked = oxyServices.createLinkedClient({ baseURL: apiUrl });
56
- const socket = io(apiUrl, {
57
- transports: ['websocket'],
58
- // The function form asks for a token on every (re)connect, so it survives rotation.
59
- auth: (cb) => {
60
- linked.getAccessToken(apiUrl).then(
61
- (token) => cb({ token }),
62
- () => cb({}),
63
- );
64
- },
65
- reconnection: true,
66
- reconnectionAttempts: Infinity,
67
- reconnectionDelay: 1000,
68
- reconnectionDelayMax: 10000,
69
- });
70
-
71
- socket.on('connect', () => {
72
- socket.emit('subscribe-agent-session', sessionId);
73
- if (agentId) socket.emit('subscribe-agent', agentId);
74
- });
75
-
76
- socket.on('agent-activity', (event: AgentActivityEvent) => {
77
- if (event.sessionId === sessionId) handleEvent(event);
78
- });
79
-
80
45
  return () => {
81
46
  cancelled = true;
82
- socket.disconnect();
83
- linked.dispose();
84
47
  };
85
- }, [sessionId, agentId, handleEvent, api, apiUrl, oxyServices]);
48
+ }, [sessionId, api]);
49
+
50
+ const onFrame = useCallback(
51
+ (frame: RealtimeFrame) => {
52
+ const event = frame.data as AgentActivityEvent;
53
+ if (event?.sessionId === sessionId) setState((prev) => applyActivityEvent(prev, event));
54
+ },
55
+ [sessionId],
56
+ );
57
+ useRealtimeTopic(sessionId ? `agent-session:${sessionId}` : null, onFrame);
58
+ useRealtimeTopic(sessionId && agentId ? `agent:${agentId}` : null, onFrame);
86
59
 
87
60
  return state;
88
61
  }
@@ -47,6 +47,7 @@ import type {
47
47
  ToolInvocation,
48
48
  } from './types';
49
49
  import { UsageLimitError } from './usage-limit-error';
50
+ import { useGemieRealtime } from '../realtime/react';
50
51
 
51
52
  export type { ToolInvocation };
52
53
  export type { FailedTurn };
@@ -181,6 +182,10 @@ export function useConversationStream({
181
182
  room,
182
183
  }: UseConversationStreamOptions = {}) {
183
184
  const { apiUrl, streamFetch, host, app } = useGemieRuntime();
185
+ // Whether a member still speaking after the request can be followed live (`room` frames).
186
+ const realtime = useGemieRealtime();
187
+ const realtimeRef = useRef(realtime);
188
+ realtimeRef.current = realtime;
184
189
  /** Where an awaited host action's answer goes: the same account and app assertion as the turn. */
185
190
  const api = useGemieApi();
186
191
  /** Read at send time and when an action arrives: the host's declaration may change between turns. */
@@ -677,8 +682,8 @@ export function useConversationStream({
677
682
  flushPendingUpdates();
678
683
  if (event.errorCode === ROOM_CONTINUES) {
679
684
  // The request is over but the member is still speaking: the room's socket carries it on.
680
- // With no socket to carry it, it stops here, unfinished but not failed.
681
- if (host.subscribeRoomEvents) releaseConsult(roomRef.current, event.consultId);
685
+ // With no socket to carry it (signed out), it stops here, unfinished but not failed.
686
+ if (realtimeRef.current) releaseConsult(roomRef.current, event.consultId);
682
687
  else {
683
688
  setMessages((prev) =>
684
689
  prev.map((m) => (m.id === id ? { ...m, isStreaming: false } : m)),
@@ -19,6 +19,8 @@ import {
19
19
  useConversation,
20
20
  useCreateConversation,
21
21
  useDeleteConversation,
22
+ useMarkConversationRead,
23
+ useReadConversation,
22
24
  } from './conversations';
23
25
  import { gemieQueryKeys } from './query-keys';
24
26
  import { reportDroppedAttachments, useStartConversation } from './use-start-conversation';
@@ -26,6 +28,10 @@ import { createRoomLedger } from './room-events';
26
28
  import { applyMessageReaction, type MessageReactionSnapshot } from './message-reactions';
27
29
  import { useConversationStream } from './use-conversation-stream';
28
30
  import { useRoomEvents } from './use-room-events';
31
+ import { useGemieRealtime } from '../realtime/react';
32
+ import { bumpConversation, mergeMessages } from '../realtime/cache';
33
+ import type { RealtimeData } from '../realtime/contract';
34
+ import { normalizeConversationMessages } from './message-history';
29
35
  import type { Message, SendOptions } from './types';
30
36
 
31
37
  export interface UseConversationThreadOptions {
@@ -84,6 +90,11 @@ function isEmptyContent(content: MessageContent | undefined): boolean {
84
90
  return content.length === 0;
85
91
  }
86
92
 
93
+ /** Whether the screen is in front of the person: a hidden browser tab is not; a mounted native screen is. */
94
+ function inFront(): boolean {
95
+ return typeof document === 'undefined' || document.visibilityState !== 'hidden';
96
+ }
97
+
87
98
  export function useConversationThread({
88
99
  conversationId,
89
100
  model,
@@ -194,25 +205,21 @@ export function useConversationThread({
194
205
  };
195
206
  }, [isLoading, conversationId, setStreamingConversationId]);
196
207
 
197
- // Refresh sidebar when streaming finishes (backend auto-saves with AI-generated title)
198
- useEffect(() => {
199
- if (wasLoadingRef.current && !isLoading && conversationId) {
200
- // Immediate refetch (gets saved conversation data)
201
- void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
202
- void queryClient.invalidateQueries({
203
- queryKey: gemieQueryKeys.conversations.detail(conversationId),
204
- });
205
- // Delayed fallback for async title generation. Only the list needs it —
206
- // re-fetching the whole message detail 5s after every exchange just for
207
- // a possible title was a second full refetch per message.
208
- const timer = setTimeout(() => {
209
- void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
210
- }, 5000);
211
- wasLoadingRef.current = isLoading;
212
- return () => clearTimeout(timer);
208
+ // The sidebar row moves as soon as the person sends — WhatsApp's own row jumps on send — and
209
+ // the server's `conversation` event replaces this guess with what it stored. No refetch: the
210
+ // turn's saved row, its title and the other devices' copies all arrive as events.
211
+ const lastUserText = useMemo(() => {
212
+ for (let i = messages.length - 1; i >= 0; i--) {
213
+ const message = messages[i];
214
+ if (message?.role === 'user') return getTextFromContent(message.content);
213
215
  }
216
+ return '';
217
+ }, [messages]);
218
+ useEffect(() => {
219
+ if (wasLoadingRef.current === isLoading) return;
214
220
  wasLoadingRef.current = isLoading;
215
- }, [isLoading, conversationId, queryClient]);
221
+ if (isLoading && conversationId) bumpConversation(queryClient, conversationId, lastUserText);
222
+ }, [isLoading, conversationId, queryClient, lastUserText]);
216
223
 
217
224
  // Sync chatId and load messages when conversation changes or when
218
225
  // seeded cache data upgrades to full data (messages go from empty to populated).
@@ -240,17 +247,45 @@ export function useConversationThread({
240
247
  setMessages(validMessages);
241
248
  }, [conversationId, conversation, conversationQueryLoading, setMessages, messages.length]);
242
249
 
243
- // An agent wrote into THIS conversation on its own (a result, a check-in).
244
- // Appended to what is on screen: the detail refetch alone would not reach an
245
- // open chat, whose local messages are only replaced when the id changes. The
246
- // server keeps it even if the next turn is sent before this arrives.
250
+ // What this conversation gained elsewhere — a gemie writing on its own, a group member, another
251
+ // 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.
254
+ const realtime = useGemieRealtime();
255
+ const readConversation = useReadConversation();
256
+ const markRead = useMarkConversationRead();
257
+ // Opening a conversation with something unread reads it.
258
+ const openUnread = (conversation?.unreadCount ?? 0) > 0;
259
+ useEffect(() => {
260
+ if (conversationId && openUnread) markRead(conversationId);
261
+ }, [conversationId, openUnread, markRead]);
262
+ const loadingRef = useRef(isLoading);
263
+ loadingRef.current = isLoading;
247
264
  useEffect(() => {
248
- if (!conversationId) return;
249
- return host.subscribeConversationMessages?.(conversationId, (incoming) => {
250
- if (!incoming?.id) return;
251
- setMessages((prev) => (prev.some((m) => m.id === incoming.id) ? prev : [...prev, incoming]));
265
+ if (!conversationId || !realtime) return;
266
+ return realtime.on('conversation', (frame) => {
267
+ const data = frame.data as RealtimeData['conversation'];
268
+ if (data.conversation.id !== conversationId) return;
269
+ // Open and in front of the person: what arrived is read (every surface's badge clears).
270
+ if (data.conversation.unreadCount > 0 && inFront()) markRead(conversationId);
271
+ if (data.appended?.length) {
272
+ const incoming = normalizeConversationMessages(data.appended);
273
+ setMessages((prev) => mergeMessages(prev, incoming));
274
+ }
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
+ }
252
287
  });
253
- }, [conversationId, setMessages, host]);
288
+ }, [conversationId, realtime, setMessages, queryClient, readConversation, markRead]);
254
289
 
255
290
  // Send pending initial message for new conversations
256
291
  useEffect(() => {
@@ -1,17 +1,17 @@
1
1
  import { useEffect, useRef } from 'react';
2
- import { useGemieRuntime } from './config';
2
+ import { useGemieRealtime } from '../realtime/react';
3
3
  import {
4
4
  applyRoomEvent,
5
5
  roomFailureReason,
6
6
  type RoomFailureReason,
7
+ type RoomEvent,
7
8
  type RoomLedger,
8
9
  } from './room-events';
9
10
  import type { Message } from './types';
10
11
 
11
12
  /**
12
- * While a conversation is open, fold its room's events (`group:event`, ADR 0025) into the thread.
13
- * Group turns and reaction-triggered agent replies share this lifecycle. A host without
14
- * `subscribeRoomEvents` sees background replies on reload.
13
+ * While a conversation is open, fold its room's events (`room` frames on the realtime socket,
14
+ * ADR 0025) into the thread. Group turns and reaction-triggered agent replies share this lifecycle.
15
15
  */
16
16
  /**
17
17
  * How long a room may say nothing while a member still shows as typing before the thread stops
@@ -28,15 +28,16 @@ export function useRoomEvents(
28
28
  setMessages: (update: (prev: Message[]) => Message[]) => void,
29
29
  onFailure?: (failure: { chainId: string; reason: RoomFailureReason }) => void,
30
30
  ): void {
31
- const { host } = useGemieRuntime();
32
- const subscribe = host.subscribeRoomEvents;
31
+ const realtime = useGemieRealtime();
33
32
  const failureRef = useRef(onFailure);
34
33
  failureRef.current = onFailure;
35
34
  useEffect(() => {
36
- if (!conversationId || !subscribe) return;
35
+ if (!conversationId || !realtime) return;
37
36
  let lastEventAt = Date.now();
38
37
  const failedChains = new Set<string>();
39
- const unsubscribe = subscribe(conversationId, (event) => {
38
+ const unsubscribe = realtime.on('room', (frame) => {
39
+ const event = frame.data as RoomEvent;
40
+ if (event?.conversationId !== conversationId) return;
40
41
  lastEventAt = Date.now();
41
42
  setMessages((prev) => applyRoomEvent(prev, ledger, conversationId, event));
42
43
  const reason =
@@ -71,5 +72,5 @@ export function useRoomEvents(
71
72
  clearInterval(timer);
72
73
  unsubscribe();
73
74
  };
74
- }, [conversationId, ledger, subscribe, setMessages]);
75
+ }, [conversationId, ledger, realtime, setMessages]);
75
76
  }