@gemies/sdk 5.0.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.
@@ -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
  }
@@ -1,137 +0,0 @@
1
- import { io, type Socket } from 'socket.io-client';
2
- import type { GemieAvatarState } from '../components/GemieAvatar';
3
- import { useGemieActivityStore } from './activity-store';
4
-
5
- /** A run that goes quiet this long is over: a crashed run never says `idle`. */
6
- export const ACTIVITY_QUIET_MS = 90_000;
7
- /**
8
- * After the server refuses a handshake (socket.io does not retry those itself), wait this long,
9
- * doubling up to {@link MAX_RETRY_MS}. A fixed 5 s retry with a token that could never pass (the
10
- * session's base token after it expired) opened a websocket every few seconds for as long as the
11
- * tab stayed open: 51 upgrades in 12 minutes for one person, on top of their API budget.
12
- */
13
- export const RETRY_MS = 5_000;
14
- export const MAX_RETRY_MS = 60_000;
15
-
16
- /** A holder's way to the API's access token: fresh on every call (a linked client's). */
17
- export type ActivityTokenSource = () => string | null | Promise<string | null>;
18
-
19
- const STATES: ReadonlySet<string> = new Set<GemieAvatarState>([
20
- 'idle',
21
- 'thinking',
22
- 'working',
23
- 'writing',
24
- ]);
25
-
26
- interface Connection {
27
- socket: Socket;
28
- refs: number;
29
- quiet: Map<string, ReturnType<typeof setTimeout>>;
30
- retry: ReturnType<typeof setTimeout> | null;
31
- retryMs: number;
32
- /** Each holder's token source; the socket asks the latest one still held. */
33
- tokens: Map<symbol, ActivityTokenSource>;
34
- }
35
-
36
- /** One connection per API origin, however many buttons ask for it. */
37
- const connections = new Map<string, Connection>();
38
-
39
- function open(url: string): Connection {
40
- const tokens = new Map<symbol, ActivityTokenSource>();
41
- const socket = io(url, {
42
- transports: ['websocket'],
43
- // Asked on every (re)connect, of a holder still holding it, so the token that goes out is a
44
- // current one: never a captured one, never one whose holder has gone.
45
- auth: (cb) => {
46
- const source = [...tokens.values()].at(-1);
47
- Promise.resolve(source ? source() : null).then(
48
- (token) => cb({ token }),
49
- () => cb({}),
50
- );
51
- },
52
- reconnection: true,
53
- reconnectionAttempts: Infinity,
54
- reconnectionDelay: 1000,
55
- reconnectionDelayMax: 10_000,
56
- });
57
- const connection: Connection = {
58
- socket,
59
- refs: 0,
60
- quiet: new Map(),
61
- retry: null,
62
- retryMs: RETRY_MS,
63
- tokens,
64
- };
65
- const store = useGemieActivityStore.getState;
66
-
67
- const reset = (): void => {
68
- for (const timer of connection.quiet.values()) clearTimeout(timer);
69
- connection.quiet.clear();
70
- store().clearRemote();
71
- };
72
-
73
- socket.on('connect', () => {
74
- connection.retryMs = RETRY_MS;
75
- socket.emit('subscribe-alia-activity');
76
- });
77
- // What happened while disconnected is unknown; a stale "working" is worse than idle.
78
- socket.on('disconnect', reset);
79
- socket.on('connect_error', () => {
80
- // A refused handshake (no token yet, an expired one) ends the socket's own retrying.
81
- if (socket.active || connection.retry !== null) return;
82
- const wait = connection.retryMs;
83
- connection.retryMs = Math.min(wait * 2, MAX_RETRY_MS);
84
- connection.retry = setTimeout(() => {
85
- connection.retry = null;
86
- socket.connect();
87
- }, wait);
88
- });
89
- socket.on('alia:activity', (event: unknown) => {
90
- if (typeof event !== 'object' || event === null) return;
91
- const { state, sessionId } = event as { state?: unknown; sessionId?: unknown };
92
- if (typeof sessionId !== 'string' || typeof state !== 'string' || !STATES.has(state)) return;
93
- const pending = connection.quiet.get(sessionId);
94
- if (pending !== undefined) clearTimeout(pending);
95
- connection.quiet.delete(sessionId);
96
- store().setRemote(sessionId, state as GemieAvatarState);
97
- if (state !== 'idle') {
98
- connection.quiet.set(
99
- sessionId,
100
- setTimeout(() => {
101
- connection.quiet.delete(sessionId);
102
- store().setRemote(sessionId, 'idle');
103
- }, ACTIVITY_QUIET_MS),
104
- );
105
- }
106
- });
107
- return connection;
108
- }
109
-
110
- /**
111
- * Listen for Alia's activity on the person's behalf. Every caller shares the one connection for
112
- * `url`; the last to release closes it. Returns the release.
113
- */
114
- export function acquireActivitySocket(url: string, getToken: ActivityTokenSource): () => void {
115
- let held = connections.get(url);
116
- if (!held) {
117
- held = open(url);
118
- connections.set(url, held);
119
- }
120
- const connection = held;
121
- const holder = Symbol('activity-holder');
122
- connection.tokens.set(holder, getToken);
123
- connection.refs++;
124
- let released = false;
125
- return () => {
126
- if (released) return;
127
- released = true;
128
- connection.tokens.delete(holder);
129
- if (--connection.refs > 0) return;
130
- connections.delete(url);
131
- if (connection.retry !== null) clearTimeout(connection.retry);
132
- connection.socket.removeAllListeners();
133
- connection.socket.disconnect();
134
- for (const timer of connection.quiet.values()) clearTimeout(timer);
135
- useGemieActivityStore.getState().clearRemote();
136
- };
137
- }