@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.
@@ -1,39 +1,44 @@
1
- import { useEffect } from 'react';
2
- import { useOxy } from '@oxy.so/services/ui/client';
3
1
  import type { GemieAvatarState } from '../components/GemieAvatar';
4
2
  import { selectGemieActivity, useGemieActivityStore } from '../lib/activity-store';
5
- import { acquireActivitySocket } from '../lib/activity-socket';
6
3
  import { GEMIES_API_URL } from '../lib/origins';
4
+ import type { ActorActivityEntry } from '../realtime/activity';
5
+ import { useRealtimeActivityStore } from '../realtime/activity';
6
+ import { useRealtimeActivityFeed } from '../realtime/react';
7
7
 
8
8
  export interface UseGemieActivityOptions {
9
- /** The API the activity socket connects to. Defaults to the runtime's `apiUrl`. */
9
+ /** The API to hear from when no `GemieRuntimeProvider` is mounted. Defaults to Gemies's. */
10
10
  apiUrl?: string;
11
11
  }
12
12
 
13
+ /** A tool in use is the avatar's `working`; the other states are its own. */
14
+ const AVATAR_STATE: Record<ActorActivityEntry['state'], GemieAvatarState> = {
15
+ thinking: 'thinking',
16
+ writing: 'writing',
17
+ tool: 'working',
18
+ };
19
+ const RANK: Record<GemieAvatarState, number> = { idle: 0, writing: 1, thinking: 2, working: 3 };
20
+
21
+ function busiestRemote(entries: Readonly<Record<string, ActorActivityEntry>>): GemieAvatarState {
22
+ let top: GemieAvatarState = 'idle';
23
+ for (const entry of Object.values(entries)) {
24
+ const state = AVATAR_STATE[entry.state];
25
+ if (RANK[state] > RANK[top]) top = state;
26
+ }
27
+ return top;
28
+ }
29
+
13
30
  /**
14
31
  * What Alia is doing right now, for any surface that wants to show it — an "Ask Alia" button's
15
32
  * avatar, a status dot. It is the busiest of:
16
33
  *
17
34
  * - a turn running in this app (`useConversationThread`, so every chat drives every button), and
18
- * - her runs for the signed-in person elsewhere, reported by the server over one shared socket
19
- * (background work, another device), connected only while someone is signed in AND using this.
35
+ * - what the signed-in person's gemies are doing elsewhere (background work, another device), heard
36
+ * as `activity` on the account's realtime connection: the runtime provider's, or one held here
37
+ * while signed in when the button is drawn outside any.
20
38
  */
21
39
  export function useGemieActivity(options: UseGemieActivityOptions = {}): GemieAvatarState {
22
- const { apiUrl = GEMIES_API_URL } = options;
23
- const { oxyServices, isAuthenticated } = useOxy();
24
-
25
- useEffect(() => {
26
- if (!isAuthenticated) return;
27
- // The API's own token, refreshed by core when it is due, as every other request gets it. The
28
- // session's base `accessToken` is not refreshed for this origin: once it expired, the server
29
- // refused every handshake and the socket retried forever.
30
- const linked = oxyServices.createLinkedClient({ baseURL: apiUrl });
31
- const release = acquireActivitySocket(apiUrl, () => linked.getAccessToken(apiUrl));
32
- return () => {
33
- release();
34
- linked.dispose();
35
- };
36
- }, [apiUrl, isAuthenticated, oxyServices]);
37
-
38
- return useGemieActivityStore(selectGemieActivity);
40
+ useRealtimeActivityFeed(options.apiUrl ?? GEMIES_API_URL);
41
+ const local = useGemieActivityStore(selectGemieActivity);
42
+ const remote = useRealtimeActivityStore((s) => busiestRemote(s.entries));
43
+ return RANK[remote] > RANK[local] ? remote : local;
39
44
  }
@@ -4,7 +4,6 @@ import { useQueryClient } from '@tanstack/react-query';
4
4
  import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react';
5
5
  import { useLabels } from '../lib/labels';
6
6
  import { useGemieApi } from '../runtime/api';
7
- import { useGemieRuntime } from '../runtime/config';
8
7
  import { GEMIES_API_ROUTES } from '../runtime/model';
9
8
  import {
10
9
  MessageReactionController,
@@ -13,6 +12,7 @@ import {
13
12
  type MessageReactionSnapshot,
14
13
  } from '../runtime/message-reactions';
15
14
  import { updateReactionCaches } from '../runtime/reaction-cache';
15
+ import { useGemieRealtime } from '../realtime/react';
16
16
 
17
17
  const NONE: readonly string[] = [];
18
18
 
@@ -28,7 +28,6 @@ export function useMessageReactions({
28
28
  } = {}) {
29
29
  const { t } = useLabels();
30
30
  const api = useGemieApi();
31
- const { host } = useGemieRuntime();
32
31
  const { user } = useOxy();
33
32
  const queryClient = useQueryClient();
34
33
  const [version, changed] = useReducer((value: number) => value + 1, 0);
@@ -68,21 +67,17 @@ export function useMessageReactions({
68
67
  return () => controller.dispose();
69
68
  }, [controller]);
70
69
 
70
+ // Reactions changed anywhere — another device, a gemie — arrive as `message.reaction`.
71
71
  const subscriptions = JSON.stringify([...new Set(conversationIds)].sort());
72
- const subscribe = host.subscribeConversationReactions;
72
+ const realtime = useGemieRealtime();
73
73
  useEffect(() => {
74
- if (!enabled || !subscribe) return;
75
- const ids: string[] = JSON.parse(subscriptions);
76
- const unsubscribers = ids.map((conversationId) =>
77
- subscribe(conversationId, (value) => {
78
- const update = readMessageReactionUpdate(value);
79
- if (update?.conversationId === conversationId) controller.receive(update);
80
- }),
81
- );
82
- return () => {
83
- for (const unsubscribe of unsubscribers) unsubscribe();
84
- };
85
- }, [controller, enabled, subscribe, subscriptions]);
74
+ if (!enabled || !realtime) return;
75
+ const ids = new Set<string>(JSON.parse(subscriptions));
76
+ return realtime.on('message.reaction', (frame) => {
77
+ const update = readMessageReactionUpdate(frame.data);
78
+ if (update && ids.has(update.conversationId)) controller.receive(update);
79
+ });
80
+ }, [controller, enabled, realtime, subscriptions]);
86
81
 
87
82
  // biome-ignore lint/correctness/useExhaustiveDependencies: each update refreshes memoized rows
88
83
  const reactionsOf = useCallback(
package/src/index.ts CHANGED
@@ -16,6 +16,12 @@ export type {
16
16
  UseParticipantsOptions,
17
17
  } from './components/GemieParticipants';
18
18
  export { GemieParticipantsHeader } from './components/GemieParticipantsHeader';
19
+ export {
20
+ GemieActivityLine,
21
+ activityText,
22
+ useConversationActivityText,
23
+ } from './components/GemieActivityLine';
24
+ export type { GemieActivityLineProps } from './components/GemieActivityLine';
19
25
  export type { GemieParticipantsHeaderProps } from './components/GemieParticipantsHeader';
20
26
  export { ALIA_GEMIE_ID } from './lib/alia-gemie';
21
27
  export { ALIA_LEAD, leadOf } from './lib/participants';
@@ -4,20 +4,14 @@ import type { GemieAvatarState } from '../components/GemieAvatar';
4
4
  type Sources = Readonly<Record<string, GemieAvatarState>>;
5
5
 
6
6
  /**
7
- * What Alia is doing, from every place that can know. Two sources feed it and neither owns it:
8
- *
9
- * - `local`: the turns running in THIS app, one entry per `useConversationThread` instance;
10
- * - `remote`: runs the server reports for the person, one entry per agent session, so a button
11
- * reacts to work that is not in any open chat.
12
- *
13
- * An idle source holds no entry, so neither map grows with use.
7
+ * The turns running in THIS app, one entry per `useConversationThread` instance, so every chat
8
+ * drives every "Ask Alia" button. What the person's gemies do elsewhere is the realtime activity
9
+ * store's (`realtime/activity.ts`); `useGemieActivity` shows the busier of the two. An idle source
10
+ * holds no entry, so the map does not grow with use.
14
11
  */
15
12
  interface GemieActivityStore {
16
13
  local: Sources;
17
- remote: Sources;
18
14
  setLocal(source: string, state: GemieAvatarState): void;
19
- setRemote(session: string, state: GemieAvatarState): void;
20
- clearRemote(): void;
21
15
  }
22
16
 
23
17
  function put(map: Sources, key: string, state: GemieAvatarState): Sources {
@@ -31,10 +25,7 @@ function put(map: Sources, key: string, state: GemieAvatarState): Sources {
31
25
 
32
26
  export const useGemieActivityStore = create<GemieActivityStore>((set) => ({
33
27
  local: {},
34
- remote: {},
35
28
  setLocal: (source, state) => set((s) => ({ local: put(s.local, source, state) })),
36
- setRemote: (session, state) => set((s) => ({ remote: put(s.remote, session, state) })),
37
- clearRemote: () => set((s) => (Object.keys(s.remote).length === 0 ? s : { remote: {} })),
38
29
  }));
39
30
 
40
31
  /** The most telling thing any source is doing: a tool call outranks thinking, thinking outranks writing. */
@@ -48,6 +39,5 @@ export function busiest(...maps: ReadonlyArray<Sources>): GemieAvatarState {
48
39
  return top;
49
40
  }
50
41
 
51
- /** A primitive, so a subscriber re-renders when the state changes and not when a session does. */
52
- export const selectGemieActivity = (s: GemieActivityStore): GemieAvatarState =>
53
- busiest(s.local, s.remote);
42
+ /** A primitive, so a subscriber re-renders when the state changes and not when a source does. */
43
+ export const selectGemieActivity = (s: GemieActivityStore): GemieAvatarState => busiest(s.local);
@@ -151,10 +151,16 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
151
151
  'faircoin.updated': 'Updated %{time}',
152
152
  'faircoin.volume': '24h volume',
153
153
  'gemie.connectors.cancel': 'Cancel',
154
+ 'gemie.connectors.category.commerce': 'Commerce',
154
155
  'gemie.connectors.category.communication': 'Communication',
155
156
  'gemie.connectors.category.data': 'Data',
157
+ 'gemie.connectors.category.design': 'Design',
156
158
  'gemie.connectors.category.development': 'Development',
159
+ 'gemie.connectors.category.finance': 'Finance',
160
+ 'gemie.connectors.category.marketing': 'Marketing',
161
+ 'gemie.connectors.category.other': 'Other',
157
162
  'gemie.connectors.category.productivity': 'Productivity',
163
+ 'gemie.connectors.category.search': 'Search and research',
158
164
  'gemie.connectors.connected.browse': 'Browse connectors',
159
165
  'gemie.connectors.connected.description':
160
166
  'The accounts you connected. Alia can use every one; other gemies only the ones you give them in their editor.',
@@ -200,6 +206,10 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
200
206
  'gemie.connectors.status.installed': 'Not connected yet',
201
207
  'gemie.connectors.status.running': 'Connected',
202
208
  'gemie.connectors.store.all': 'All',
209
+ 'gemie.connectors.store.allCount': {
210
+ one: 'All connectors · 1',
211
+ other: 'All connectors · {{count}}',
212
+ },
203
213
  'gemie.connectors.store.categories': 'Categories',
204
214
  'gemie.connectors.store.connect': 'Connect',
205
215
  'gemie.connectors.store.connectAnother': 'Add account',
@@ -208,16 +218,33 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
208
218
  other: '{{count}} accounts connected',
209
219
  },
210
220
  'gemie.connectors.store.description':
211
- 'Connect the apps you work with. Each is the provider’s own MCP server: you sign in with them, and Gemies never sees your password.',
221
+ 'Connect the apps you work with: the providers’ own MCP servers, and hundreds more from the official MCP Registry. Official means the provider publishes it; Community means a developer does. When one asks you to sign in, you sign in with them, and Gemies never sees your password.',
212
222
  'gemie.connectors.store.docs': 'About',
213
223
  'gemie.connectors.store.empty': 'No connector is available right now.',
214
224
  'gemie.connectors.store.featured': 'Featured',
225
+ 'gemie.connectors.store.filter.noSignIn': 'No sign-in',
226
+ 'gemie.connectors.store.filter.official': 'Official',
227
+ 'gemie.connectors.store.filter.verified': 'Verified',
228
+ 'gemie.connectors.store.filters': 'Filters',
215
229
  'gemie.connectors.store.loadFailed': 'Connectors could not be loaded.',
230
+ 'gemie.connectors.store.more': { one: 'Show 1 more', other: 'Show more ({{count}} left)' },
216
231
  'gemie.connectors.store.noResults': 'No connector matches “{{query}}”.',
232
+ 'gemie.connectors.store.results': {
233
+ zero: 'No results',
234
+ one: '1 result',
235
+ other: '{{count}} results',
236
+ },
217
237
  'gemie.connectors.store.retry': 'Retry',
218
238
  'gemie.connectors.store.search': 'Search connectors',
239
+ 'gemie.connectors.store.sort': 'Sort by',
240
+ 'gemie.connectors.store.sortBy.featured': 'Featured',
241
+ 'gemie.connectors.store.sortBy.name': 'Name',
242
+ 'gemie.connectors.store.sortBy.recent': 'Recently updated',
219
243
  'gemie.connectors.store.title': 'Connectors',
220
244
  'gemie.connectors.toolCount': { zero: 'No tools', one: '1 tool', other: '{{count}} tools' },
245
+ 'gemie.connectors.trust.community': 'Community',
246
+ 'gemie.connectors.trust.official': 'Official',
247
+ 'gemie.connectors.trust.verified': 'Verified',
221
248
  'gemie.connectors.usedBy': 'Used by {{names}}',
222
249
  'gemie.accounts.answerChat': 'Answer {{name}}',
223
250
  'gemie.accounts.answeringLabel': 'Answers on its own',
@@ -147,10 +147,16 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
147
147
  'faircoin.updated': 'Actualizado %{time}',
148
148
  'faircoin.volume': 'Volumen 24 h',
149
149
  'gemie.connectors.cancel': 'Cancelar',
150
+ 'gemie.connectors.category.commerce': 'Comercio',
150
151
  'gemie.connectors.category.communication': 'Comunicación',
151
152
  'gemie.connectors.category.data': 'Datos',
153
+ 'gemie.connectors.category.design': 'Diseño',
152
154
  'gemie.connectors.category.development': 'Desarrollo',
155
+ 'gemie.connectors.category.finance': 'Finanzas',
156
+ 'gemie.connectors.category.marketing': 'Marketing',
157
+ 'gemie.connectors.category.other': 'Otros',
153
158
  'gemie.connectors.category.productivity': 'Productividad',
159
+ 'gemie.connectors.category.search': 'Búsqueda e investigación',
154
160
  'gemie.connectors.connected.browse': 'Explorar conectores',
155
161
  'gemie.connectors.connected.description':
156
162
  'Las cuentas que conectaste. Alia puede usarlas todas; los demás gemies solo las que les des en su editor.',
@@ -196,6 +202,10 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
196
202
  'gemie.connectors.status.installed': 'Aún sin conectar',
197
203
  'gemie.connectors.status.running': 'Conectado',
198
204
  'gemie.connectors.store.all': 'Todos',
205
+ 'gemie.connectors.store.allCount': {
206
+ one: 'Todos los conectores · 1',
207
+ other: 'Todos los conectores · {{count}}',
208
+ },
199
209
  'gemie.connectors.store.categories': 'Categorías',
200
210
  'gemie.connectors.store.connect': 'Conectar',
201
211
  'gemie.connectors.store.connectAnother': 'Añadir cuenta',
@@ -204,20 +214,37 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
204
214
  other: '{{count}} cuentas conectadas',
205
215
  },
206
216
  'gemie.connectors.store.description':
207
- 'Conecta las apps con las que trabajas. Cada una es el servidor MCP del propio proveedor: inicias sesión con ellos y Gemies nunca ve tu contraseña.',
217
+ 'Conecta las apps con las que trabajas: los servidores MCP de los propios proveedores y cientos más del registro oficial de MCP. Oficial significa que lo publica el proveedor; Comunidad, que lo publica un desarrollador. Si alguno te pide iniciar sesión, la inicias con ellos y Gemies nunca ve tu contraseña.',
208
218
  'gemie.connectors.store.docs': 'Más información',
209
219
  'gemie.connectors.store.empty': 'Ahora mismo no hay conectores disponibles.',
210
220
  'gemie.connectors.store.featured': 'Destacados',
221
+ 'gemie.connectors.store.filter.noSignIn': 'Sin inicio de sesión',
222
+ 'gemie.connectors.store.filter.official': 'Oficiales',
223
+ 'gemie.connectors.store.filter.verified': 'Verificados',
224
+ 'gemie.connectors.store.filters': 'Filtros',
211
225
  'gemie.connectors.store.loadFailed': 'No se pudieron cargar los conectores.',
226
+ 'gemie.connectors.store.more': { one: 'Mostrar 1 más', other: 'Mostrar más (quedan {{count}})' },
212
227
  'gemie.connectors.store.noResults': 'Ningún conector coincide con «{{query}}».',
228
+ 'gemie.connectors.store.results': {
229
+ zero: 'Sin resultados',
230
+ one: '1 resultado',
231
+ other: '{{count}} resultados',
232
+ },
213
233
  'gemie.connectors.store.retry': 'Reintentar',
214
234
  'gemie.connectors.store.search': 'Buscar conectores',
235
+ 'gemie.connectors.store.sort': 'Ordenar por',
236
+ 'gemie.connectors.store.sortBy.featured': 'Destacados',
237
+ 'gemie.connectors.store.sortBy.name': 'Nombre',
238
+ 'gemie.connectors.store.sortBy.recent': 'Actualizados recientemente',
215
239
  'gemie.connectors.store.title': 'Conectores',
216
240
  'gemie.connectors.toolCount': {
217
241
  zero: 'Sin herramientas',
218
242
  one: '1 herramienta',
219
243
  other: '{{count}} herramientas',
220
244
  },
245
+ 'gemie.connectors.trust.community': 'Comunidad',
246
+ 'gemie.connectors.trust.official': 'Oficial',
247
+ 'gemie.connectors.trust.verified': 'Verificado',
221
248
  'gemie.connectors.usedBy': 'Lo usan {{names}}',
222
249
  'gemie.accounts.answerChat': 'Responder a {{name}}',
223
250
  'gemie.accounts.answeringLabel': 'Responde por su cuenta',
@@ -75,6 +75,16 @@ export const SPANISH_LABELS: GemieChatLabels = {
75
75
  reasoning: 'Razonamiento',
76
76
  locale: 'es',
77
77
  newChat: 'Nueva conversación',
78
+ activity: (name, state) => {
79
+ const verb =
80
+ state === 'writing'
81
+ ? 'está escribiendo'
82
+ : state === 'tool'
83
+ ? 'está trabajando'
84
+ : 'está pensando';
85
+ const bare = state === 'writing' ? 'Escribiendo' : state === 'tool' ? 'Trabajando' : 'Pensando';
86
+ return name ? `${name} ${verb}…` : `${bare}…`;
87
+ },
78
88
  recentConversations: 'Recientes',
79
89
  sendFailed:
80
90
  'No se pudo enviar el mensaje. Lo tienes de vuelta en el cuadro de texto, inténtalo otra vez.',
@@ -88,6 +88,11 @@ export interface GemieChatLabels {
88
88
  // Conversations (the runtime's own words: toasts and the errors it raises)
89
89
  /** A conversation's title until it has one. */
90
90
  newChat: string;
91
+ /**
92
+ * What a gemie is doing, live, as the header and a sidebar row say it ("Pepe is typing…"):
93
+ * `name` is the gemie's, `null` for one whose name the event did not carry.
94
+ */
95
+ activity: (name: string | null, state: 'thinking' | 'writing' | 'tool') => string;
91
96
  /** Over the sheet's recent conversations with its lead. */
92
97
  recentConversations: string;
93
98
  /** A turn could not be sent and the composer got its text back. */
@@ -168,6 +173,12 @@ export const DEFAULT_LABELS: GemieChatLabels = {
168
173
  t: englishCopy,
169
174
  locale: 'en',
170
175
  newChat: 'New chat',
176
+ activity: (name, state) => {
177
+ const verb =
178
+ state === 'writing' ? 'is typing' : state === 'tool' ? 'is working' : 'is thinking';
179
+ const bare = state === 'writing' ? 'Typing' : state === 'tool' ? 'Working' : 'Thinking';
180
+ return name ? `${name} ${verb}…` : `${bare}…`;
181
+ },
171
182
  recentConversations: 'Recent',
172
183
  sendFailed: "Your message couldn't be sent",
173
184
  signInRequired: 'Sign in to keep chatting',
@@ -30,6 +30,11 @@ export interface GemieChatParticipants {
30
30
  lead: GemieLead;
31
31
  /** The consulted agents that have joined the header, in the order they joined. */
32
32
  joined: GemieParticipant[];
33
+ /**
34
+ * The conversation they are in, so the header can say live what one of them is doing
35
+ * ("Pepe is typing…") in place of their names. Absent before the first turn creates one.
36
+ */
37
+ conversationId?: string;
33
38
  }
34
39
 
35
40
  /**
@@ -0,0 +1,23 @@
1
+ import { useLabels } from '../lib/labels';
2
+ import { type ActorActivityEntry, useConversationActivity } from './activity';
3
+
4
+ /** The words for what the busiest actor is doing, or `null` when nobody is doing anything. */
5
+ export function useConversationActivityText(
6
+ conversationId: string | null | undefined,
7
+ ): string | null {
8
+ const activity = useConversationActivity(conversationId);
9
+ const labels = useLabels();
10
+ return activityText(activity, labels.activity);
11
+ }
12
+
13
+ const RANK: Record<ActorActivityEntry['state'], number> = { thinking: 1, writing: 2, tool: 3 };
14
+
15
+ /** The busiest entry, said once: "Pepe is typing…" (one), "Pepe is typing…" for the first of several. */
16
+ export function activityText(
17
+ activity: readonly ActorActivityEntry[],
18
+ say: (name: string | null, state: ActorActivityEntry['state']) => string,
19
+ ): string | null {
20
+ let top: ActorActivityEntry | undefined;
21
+ for (const entry of activity) if (!top || RANK[entry.state] > RANK[top.state]) top = entry;
22
+ return top ? say(top.name, top.state) : null;
23
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Who is doing what, live: WhatsApp's "typing…" for gemies (`activity` frames, `docs/realtime.mdx`).
3
+ *
4
+ * One entry per actor per place (a conversation, or an agent session with none). An entry lives
5
+ * for the `ttlMs` its frame states and is renewed by the server's heartbeat; `idle` removes it at
6
+ * once, and so does a lost connection — a stale "typing…" is worse than none, and a reconnect hears
7
+ * the truth within one heartbeat.
8
+ */
9
+
10
+ import { create } from 'zustand';
11
+ import { useShallow } from 'zustand/react/shallow';
12
+ import type { ActivityState, RealtimeActivity } from './contract';
13
+
14
+ export interface ActorActivityEntry {
15
+ readonly conversationId: string | null;
16
+ readonly sessionId: string | null;
17
+ readonly agentId: string | null;
18
+ readonly name: string | null;
19
+ readonly state: Exclude<ActivityState, 'idle'>;
20
+ readonly tool: string | null;
21
+ }
22
+
23
+ interface RealtimeActivityStore {
24
+ readonly entries: Readonly<Record<string, ActorActivityEntry>>;
25
+ apply(activity: RealtimeActivity): void;
26
+ clear(): void;
27
+ }
28
+
29
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
30
+
31
+ function keyOf(activity: RealtimeActivity): string {
32
+ const place = activity.conversationId ?? `session:${activity.sessionId ?? ''}`;
33
+ return `${place}|${activity.actor.agentId ?? 'alia'}`;
34
+ }
35
+
36
+ function without(
37
+ entries: Readonly<Record<string, ActorActivityEntry>>,
38
+ key: string,
39
+ ): Readonly<Record<string, ActorActivityEntry>> {
40
+ if (!(key in entries)) return entries;
41
+ const { [key]: _gone, ...rest } = entries;
42
+ return rest;
43
+ }
44
+
45
+ export const useRealtimeActivityStore = create<RealtimeActivityStore>((set) => ({
46
+ entries: {},
47
+ apply(activity) {
48
+ const key = keyOf(activity);
49
+ const pending = timers.get(key);
50
+ if (pending !== undefined) clearTimeout(pending);
51
+ timers.delete(key);
52
+ if (activity.state === 'idle') {
53
+ set((s) => ({ entries: without(s.entries, key) }));
54
+ return;
55
+ }
56
+ const entry: ActorActivityEntry = {
57
+ conversationId: activity.conversationId,
58
+ sessionId: activity.sessionId ?? null,
59
+ agentId: activity.actor.agentId,
60
+ name: activity.actor.name ?? null,
61
+ state: activity.state,
62
+ tool: activity.tool ?? null,
63
+ };
64
+ set((s) => ({ entries: { ...s.entries, [key]: entry } }));
65
+ timers.set(
66
+ key,
67
+ setTimeout(
68
+ () => {
69
+ timers.delete(key);
70
+ set((s) => ({ entries: without(s.entries, key) }));
71
+ },
72
+ Math.max(1_000, activity.ttlMs),
73
+ ),
74
+ );
75
+ },
76
+ clear() {
77
+ for (const timer of timers.values()) clearTimeout(timer);
78
+ timers.clear();
79
+ set((s) => (Object.keys(s.entries).length === 0 ? s : { entries: {} }));
80
+ },
81
+ }));
82
+
83
+ /** Who is active in one conversation. Use with `useShallow`, so it re-renders on a change only. */
84
+ export function selectConversationActivity(conversationId: string | null | undefined) {
85
+ return (s: RealtimeActivityStore): ActorActivityEntry[] =>
86
+ conversationId
87
+ ? Object.values(s.entries).filter((entry) => entry.conversationId === conversationId)
88
+ : [];
89
+ }
90
+
91
+ /** Who is doing what in one conversation right now: "Pepe is typing…", "Alia is thinking…". */
92
+ export function useConversationActivity(
93
+ conversationId: string | null | undefined,
94
+ ): readonly ActorActivityEntry[] {
95
+ return useRealtimeActivityStore(useShallow(selectConversationActivity(conversationId)));
96
+ }