@gemies/sdk 3.2.0 → 3.3.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.
@@ -0,0 +1,444 @@
1
+ import {
2
+ Accordion,
3
+ AccordionContent,
4
+ AccordionItem,
5
+ AccordionTrigger,
6
+ } from '@oxy.so/bloom/accordion';
7
+ import { Button } from '@oxy.so/bloom/button';
8
+ import { Chip, ChipRow } from '@oxy.so/bloom/chip';
9
+ import { Dialog } from '@oxy.so/bloom/dialog';
10
+ import { RiAddLine } from '@oxy.so/bloom/icons/RiAddLine';
11
+ import { Search } from '@oxy.so/bloom/search';
12
+ import * as Skeleton from '@oxy.so/bloom/skeleton';
13
+ import { TextFieldInput, TextFieldLabel } from '@oxy.so/bloom/text-field';
14
+ import { toast } from '@oxy.so/bloom/toast';
15
+ import { Text } from '@oxy.so/bloom/typography';
16
+ import * as WebBrowser from 'expo-web-browser';
17
+ import { useMemo, useState } from 'react';
18
+ import { Pressable, View } from 'react-native';
19
+ import { englishCopy, type Translate } from '../../lib/copy';
20
+ import {
21
+ CONNECTOR_CATEGORIES,
22
+ type ConnectorCategory,
23
+ type ConnectorEntry,
24
+ useConnections,
25
+ useConnectorActions,
26
+ useConnectorCatalogue,
27
+ connectorReturnTo,
28
+ signInErrorKey,
29
+ useWebSignInReturn,
30
+ } from '../../runtime/connectors';
31
+ import { ConnectorLogo } from './ConnectorLogo';
32
+
33
+ /** This component's own strings. */
34
+ const K = 'gemie.connectors';
35
+
36
+ export interface GemieConnectorsStoreProps {
37
+ /**
38
+ * The native app's URL scheme (`gemies`, `alia`): a provider's sign-in returns to the store at
39
+ * `<scheme>://connectors`, and on the web to the store's page (`connectorReturnTo`).
40
+ */
41
+ nativeScheme: string;
42
+ /** The host's translator; English without one. */
43
+ t?: Translate;
44
+ /** Told when an account was connected here (a native sign-in finishes in place). */
45
+ onConnected?: () => void;
46
+ }
47
+
48
+ /**
49
+ * The connectors store: every connector this deployment can connect, with its real logo, what it
50
+ * does, its category and a Connect button, and a way to add one's own MCP server by URL. Connecting
51
+ * again adds another account of the same connector. What the person connected is managed in
52
+ * Settings (`GemieConnectedConnectors`), not here.
53
+ */
54
+ export function GemieConnectorsStore({
55
+ nativeScheme,
56
+ t = englishCopy,
57
+ onConnected,
58
+ }: GemieConnectorsStoreProps) {
59
+ const catalogue = useConnectorCatalogue();
60
+ const connections = useConnections();
61
+ const actions = useConnectorActions({ returnTo: connectorReturnTo(nativeScheme) });
62
+ useWebSignInReturn((outcome) => {
63
+ if (outcome.ok) {
64
+ toast.success(t(`${K}.signIn.connected`, { name: outcome.connection.displayName }));
65
+ } else {
66
+ toast.error(t(signInErrorKey(outcome.error)));
67
+ }
68
+ });
69
+ const [query, setQuery] = useState('');
70
+ const [category, setCategory] = useState<ConnectorCategory | null>(null);
71
+ const [pending, setPending] = useState<string | null>(null);
72
+ const [customOpen, setCustomOpen] = useState(false);
73
+
74
+ const accountsOf = useMemo(() => {
75
+ const counts = new Map<string, number>();
76
+ for (const connection of connections.data ?? []) {
77
+ if (connection.registryId) {
78
+ counts.set(connection.registryId, (counts.get(connection.registryId) ?? 0) + 1);
79
+ }
80
+ }
81
+ return counts;
82
+ }, [connections.data]);
83
+
84
+ const visible = useMemo(() => {
85
+ const words = query.trim().toLowerCase();
86
+ return (catalogue.data ?? []).filter(
87
+ (entry) =>
88
+ (category === null || entry.category === category) &&
89
+ (!words ||
90
+ entry.name.toLowerCase().includes(words) ||
91
+ entry.description.toLowerCase().includes(words)),
92
+ );
93
+ }, [catalogue.data, query, category]);
94
+
95
+ const browsing = !query.trim() && category === null;
96
+ const featured = browsing ? visible.filter((entry) => entry.featured) : [];
97
+ const rest = browsing ? visible.filter((entry) => !entry.featured) : visible;
98
+ const categories = CONNECTOR_CATEGORIES.filter((slug) =>
99
+ (catalogue.data ?? []).some((entry) => entry.category === slug),
100
+ );
101
+
102
+ const connect = async (entry: ConnectorEntry) => {
103
+ setPending(entry.id);
104
+ try {
105
+ const connection = await actions.connect.mutateAsync(entry.id);
106
+ if (connection) {
107
+ toast.success(t(`${K}.signIn.connected`, { name: entry.name }));
108
+ onConnected?.();
109
+ }
110
+ } catch {
111
+ toast.error(t(`${K}.signIn.failed`, { name: entry.name }));
112
+ } finally {
113
+ setPending(null);
114
+ }
115
+ };
116
+
117
+ return (
118
+ <View className="gap-4">
119
+ <Search
120
+ label={t(`${K}.store.search`)}
121
+ value={query}
122
+ onChangeText={setQuery}
123
+ onClearText={() => setQuery('')}
124
+ />
125
+ {categories.length > 1 ? (
126
+ <ChipRow role="radiogroup" accessibilityLabel={t(`${K}.store.categories`)}>
127
+ <Chip
128
+ size="sm"
129
+ role="radio"
130
+ selected={category === null}
131
+ onPress={() => setCategory(null)}
132
+ >
133
+ {t(`${K}.store.all`)}
134
+ </Chip>
135
+ {categories.map((slug) => (
136
+ <Chip
137
+ key={slug}
138
+ size="sm"
139
+ role="radio"
140
+ selected={category === slug}
141
+ onPress={() => setCategory(category === slug ? null : slug)}
142
+ >
143
+ {t(`${K}.category.${slug}`)}
144
+ </Chip>
145
+ ))}
146
+ </ChipRow>
147
+ ) : null}
148
+
149
+ {catalogue.isPending ? (
150
+ <StoreSkeleton />
151
+ ) : catalogue.isError ? (
152
+ <View className="items-start gap-2 py-4">
153
+ <Text variant="body-2-regular" className="text-text-secondary">
154
+ {t(`${K}.store.loadFailed`)}
155
+ </Text>
156
+ <Button size="sm" appearance="outline" tone="neutral" onPress={() => catalogue.refetch()}>
157
+ {t(`${K}.store.retry`)}
158
+ </Button>
159
+ </View>
160
+ ) : (
161
+ <>
162
+ {featured.length > 0 ? (
163
+ <StoreGroup title={t(`${K}.store.featured`)}>
164
+ {featured.map((entry) => (
165
+ <StoreCard
166
+ key={entry.id}
167
+ entry={entry}
168
+ accounts={accountsOf.get(entry.id) ?? 0}
169
+ pending={pending === entry.id}
170
+ onConnect={connect}
171
+ t={t}
172
+ />
173
+ ))}
174
+ </StoreGroup>
175
+ ) : null}
176
+ {rest.length > 0 ? (
177
+ <StoreGroup title={browsing && featured.length > 0 ? t(`${K}.store.all`) : undefined}>
178
+ {rest.map((entry) => (
179
+ <StoreCard
180
+ key={entry.id}
181
+ entry={entry}
182
+ accounts={accountsOf.get(entry.id) ?? 0}
183
+ pending={pending === entry.id}
184
+ onConnect={connect}
185
+ t={t}
186
+ />
187
+ ))}
188
+ </StoreGroup>
189
+ ) : null}
190
+ {visible.length === 0 ? (
191
+ <Text variant="body-2-regular" className="py-4 text-text-secondary">
192
+ {query.trim()
193
+ ? t(`${K}.store.noResults`, { query: query.trim() })
194
+ : t(`${K}.store.empty`)}
195
+ </Text>
196
+ ) : null}
197
+ </>
198
+ )}
199
+
200
+ <Pressable
201
+ accessibilityRole="button"
202
+ onPress={() => setCustomOpen(true)}
203
+ className="flex-row items-center gap-3 rounded-2xl border border-dashed border-border p-4"
204
+ >
205
+ <View className="h-10 w-10 items-center justify-center rounded-xl bg-background-tertiary-default">
206
+ <RiAddLine width={20} height={20} />
207
+ </View>
208
+ <View className="flex-1 gap-0.5">
209
+ <Text variant="body-2-semibold">{t(`${K}.custom.title`)}</Text>
210
+ <Text variant="body-2-regular" className="text-text-secondary">
211
+ {t(`${K}.custom.description`)}
212
+ </Text>
213
+ </View>
214
+ </Pressable>
215
+
216
+ <CustomServerDialog
217
+ open={customOpen}
218
+ onClose={() => setCustomOpen(false)}
219
+ onAdd={async (input) => {
220
+ await actions.addCustom.mutateAsync(input);
221
+ toast.success(t(`${K}.signIn.connected`, { name: input.name }));
222
+ onConnected?.();
223
+ }}
224
+ t={t}
225
+ />
226
+ </View>
227
+ );
228
+ }
229
+
230
+ function StoreGroup({ title, children }: { title?: string; children: React.ReactNode }) {
231
+ return (
232
+ <View className="gap-2">
233
+ {title ? <Text variant="headline-semibold">{title}</Text> : null}
234
+ <View className="flex-row flex-wrap gap-3">{children}</View>
235
+ </View>
236
+ );
237
+ }
238
+
239
+ function StoreCard({
240
+ entry,
241
+ accounts,
242
+ pending,
243
+ onConnect,
244
+ t,
245
+ }: {
246
+ entry: ConnectorEntry;
247
+ accounts: number;
248
+ pending: boolean;
249
+ onConnect: (entry: ConnectorEntry) => void;
250
+ t: Translate;
251
+ }) {
252
+ return (
253
+ <View className="min-w-[260px] flex-1 basis-[260px] gap-3 rounded-2xl border border-border p-4">
254
+ <View className="flex-row items-center gap-3">
255
+ <ConnectorLogo name={entry.name} logoUrl={entry.logoUrl} size={40} />
256
+ <View className="flex-1">
257
+ <Text variant="body-2-semibold" numberOfLines={1}>
258
+ {entry.name}
259
+ </Text>
260
+ <Text variant="body-2-regular" className="text-text-secondary" numberOfLines={1}>
261
+ {accounts > 0
262
+ ? t(`${K}.store.connectedCount`, { count: accounts })
263
+ : t(`${K}.category.${entry.category}`)}
264
+ </Text>
265
+ </View>
266
+ </View>
267
+ <Text variant="body-2-regular" className="text-text-secondary" numberOfLines={2}>
268
+ {entry.description}
269
+ </Text>
270
+ <View className="flex-row items-center gap-2">
271
+ <Button
272
+ size="sm"
273
+ appearance={accounts > 0 ? 'outline' : 'solid'}
274
+ tone={accounts > 0 ? 'neutral' : 'accent'}
275
+ loading={pending}
276
+ onPress={() => onConnect(entry)}
277
+ >
278
+ {accounts > 0 ? t(`${K}.store.connectAnother`) : t(`${K}.store.connect`)}
279
+ </Button>
280
+ <Button
281
+ size="sm"
282
+ appearance="plain"
283
+ tone="neutral"
284
+ onPress={() => void WebBrowser.openBrowserAsync(entry.docsUrl)}
285
+ >
286
+ {t(`${K}.store.docs`)}
287
+ </Button>
288
+ </View>
289
+ </View>
290
+ );
291
+ }
292
+
293
+ function CustomServerDialog({
294
+ open,
295
+ onClose,
296
+ onAdd,
297
+ t,
298
+ }: {
299
+ open: boolean;
300
+ onClose: () => void;
301
+ onAdd: (input: { name: string; url: string; headers?: Record<string, string> }) => Promise<void>;
302
+ t: Translate;
303
+ }) {
304
+ const [name, setName] = useState('');
305
+ const [url, setUrl] = useState('');
306
+ const [headerName, setHeaderName] = useState('');
307
+ const [headerValue, setHeaderValue] = useState('');
308
+ const [advanced, setAdvanced] = useState<string | undefined>(undefined);
309
+ const [adding, setAdding] = useState(false);
310
+
311
+ const reset = () => {
312
+ setName('');
313
+ setUrl('');
314
+ setHeaderName('');
315
+ setHeaderValue('');
316
+ setAdvanced(undefined);
317
+ onClose();
318
+ };
319
+
320
+ const add = async () => {
321
+ setAdding(true);
322
+ try {
323
+ await onAdd({
324
+ name: name.trim(),
325
+ url: url.trim(),
326
+ ...(headerName.trim() && headerValue
327
+ ? { headers: { [headerName.trim()]: headerValue } }
328
+ : {}),
329
+ });
330
+ reset();
331
+ } catch {
332
+ toast.error(t(`${K}.custom.failed`));
333
+ } finally {
334
+ setAdding(false);
335
+ }
336
+ };
337
+
338
+ return (
339
+ <Dialog
340
+ open={open}
341
+ onClose={reset}
342
+ placement={{ base: 'bottom', md: 'center' }}
343
+ maxWidth={420}
344
+ title={t(`${K}.custom.title`)}
345
+ description={t(`${K}.custom.description`)}
346
+ actions={[
347
+ { label: t(`${K}.custom.cancel`), color: 'cancel', disabled: adding },
348
+ {
349
+ label: adding ? t(`${K}.custom.adding`) : t(`${K}.custom.add`),
350
+ onPress: add,
351
+ disabled: adding || !name.trim() || !url.trim().startsWith('https://'),
352
+ shouldCloseOnPress: false,
353
+ },
354
+ ]}
355
+ >
356
+ <View className="gap-3">
357
+ <View>
358
+ <TextFieldLabel>{t(`${K}.custom.name`)}</TextFieldLabel>
359
+ <TextFieldInput
360
+ label={t(`${K}.custom.name`)}
361
+ placeholder={t(`${K}.custom.namePlaceholder`)}
362
+ value={name}
363
+ onChangeText={setName}
364
+ autoCapitalize="words"
365
+ />
366
+ </View>
367
+ <View>
368
+ <TextFieldLabel>{t(`${K}.custom.url`)}</TextFieldLabel>
369
+ <TextFieldInput
370
+ label={t(`${K}.custom.url`)}
371
+ placeholder="https://…/mcp"
372
+ value={url}
373
+ onChangeText={setUrl}
374
+ autoCapitalize="none"
375
+ autoCorrect={false}
376
+ keyboardType="url"
377
+ />
378
+ </View>
379
+ <Accordion
380
+ type="single"
381
+ value={advanced}
382
+ onValueChange={(next) => setAdvanced(typeof next === 'string' ? next : undefined)}
383
+ >
384
+ <AccordionItem value="advanced">
385
+ <AccordionTrigger>{t(`${K}.custom.advanced`)}</AccordionTrigger>
386
+ <AccordionContent>
387
+ <View className="gap-3">
388
+ <View>
389
+ <TextFieldLabel>{t(`${K}.custom.headerName`)}</TextFieldLabel>
390
+ <TextFieldInput
391
+ label={t(`${K}.custom.headerName`)}
392
+ placeholder="Authorization"
393
+ value={headerName}
394
+ onChangeText={setHeaderName}
395
+ autoCapitalize="none"
396
+ autoCorrect={false}
397
+ />
398
+ </View>
399
+ <View>
400
+ <TextFieldLabel>{t(`${K}.custom.headerValue`)}</TextFieldLabel>
401
+ <TextFieldInput
402
+ label={t(`${K}.custom.headerValue`)}
403
+ placeholder="Bearer …"
404
+ value={headerValue}
405
+ onChangeText={setHeaderValue}
406
+ autoCapitalize="none"
407
+ autoCorrect={false}
408
+ secureTextEntry
409
+ />
410
+ </View>
411
+ </View>
412
+ </AccordionContent>
413
+ </AccordionItem>
414
+ </Accordion>
415
+ </View>
416
+ </Dialog>
417
+ );
418
+ }
419
+
420
+ /** The store's shape while the catalogue is read: cards, never a spinner. */
421
+ function StoreSkeleton() {
422
+ return (
423
+ <Skeleton.Region>
424
+ <View className="flex-row flex-wrap gap-3">
425
+ {[0, 1, 2, 3].map((index) => (
426
+ <View
427
+ key={index}
428
+ className="min-w-[260px] flex-1 basis-[260px] gap-3 rounded-2xl border border-border p-4"
429
+ >
430
+ <View className="flex-row items-center gap-3">
431
+ <Skeleton.Box width={40} height={40} borderRadius={9} />
432
+ <View className="flex-1 gap-1.5">
433
+ <Skeleton.Box width={120} height={14} />
434
+ <Skeleton.Box width={80} height={12} />
435
+ </View>
436
+ </View>
437
+ <Skeleton.Box width={220} height={12} />
438
+ <Skeleton.Box width={88} height={32} borderRadius={16} />
439
+ </View>
440
+ ))}
441
+ </View>
442
+ </Skeleton.Region>
443
+ );
444
+ }
@@ -20,6 +20,8 @@ import {
20
20
  import { restoreOpenerFocus } from '../../lib/focus-return';
21
21
  import { useLabels } from '../../lib/labels';
22
22
  import { getToolIcon } from '../../lib/tool-icons';
23
+ import { useConnectionOfTool } from '../../runtime/connectors';
24
+ import { ConnectorLogo } from '../connectors/ConnectorLogo';
23
25
  import { type ThoughtTab, useThoughtStore } from '../../runtime/thought-store';
24
26
  import { FilesAndSources, type OutputActions } from './FilesAndSources';
25
27
  import { ToolStep } from './ToolStep';
@@ -156,7 +158,6 @@ function StepsTab({ steps, lifecycle }: { steps: ThoughtStep[]; lifecycle: TurnL
156
158
  }
157
159
  const inv = step.invocation;
158
160
  const key = inv?.toolCallId || `tool-${index}`;
159
- const ToolIcon = getToolIcon(step.toolName || '');
160
161
  const status =
161
162
  inv === undefined ? (live ? 'running' : 'done') : toolCallStatus(inv, live);
162
163
  return (
@@ -165,9 +166,8 @@ function StepsTab({ steps, lifecycle }: { steps: ThoughtStep[]; lifecycle: TurnL
165
166
  title={step.toolName === undefined ? step.label : toolLabel(step.toolName, t)}
166
167
  status={status}
167
168
  icon={
168
- <ToolIcon
169
- width={14}
170
- height={14}
169
+ <ToolGlyph
170
+ toolName={step.toolName}
171
171
  fill={status === 'error' ? colors.error : colors.text}
172
172
  />
173
173
  }
@@ -424,3 +424,16 @@ export function ThoughtPanel({ onClose, outputActions }: ThoughtPanelProps) {
424
424
  </View>
425
425
  );
426
426
  }
427
+
428
+ /**
429
+ * A step's glyph: a connector's tool (`mcp_<account>__<tool>`) shows that connector's logo, every
430
+ * other tool its own glyph.
431
+ */
432
+ function ToolGlyph({ toolName, fill }: { toolName: string | undefined; fill: string }) {
433
+ const connection = useConnectionOfTool(toolName);
434
+ if (connection) {
435
+ return <ConnectorLogo name={connection.displayName} logoUrl={connection.logoUrl} size={14} />;
436
+ }
437
+ const ToolIcon = getToolIcon(toolName || '');
438
+ return <ToolIcon width={14} height={14} fill={fill} />;
439
+ }
@@ -0,0 +1,34 @@
1
+ /// <reference types="nativewind/types" />
2
+ /**
3
+ * The connectors leaf entry: the providers' own remote MCP servers a person connects (Notion,
4
+ * Linear, Slack…) and their own MCP servers by URL. The store where they are found and connected,
5
+ * the Settings list of what was connected, and the one logo every screen draws for a connector.
6
+ * The Gemies and the Alia apps both draw these; neither keeps a copy.
7
+ */
8
+ export { ConnectorLogo } from './components/connectors/ConnectorLogo';
9
+ export type { ConnectorLogoProps } from './components/connectors/ConnectorLogo';
10
+ export { GemieConnectorsStore } from './components/connectors/GemieConnectorsStore';
11
+ export type { GemieConnectorsStoreProps } from './components/connectors/GemieConnectorsStore';
12
+ export { GemieConnectedConnectors } from './components/connectors/GemieConnectedConnectors';
13
+ export type { GemieConnectedConnectorsProps } from './components/connectors/GemieConnectedConnectors';
14
+ export {
15
+ CONNECTOR_CATEGORIES,
16
+ CONNECTOR_ROUTES,
17
+ CONNECTORS_PATH,
18
+ connectionOfTool,
19
+ connectorQueryKeys,
20
+ connectorReturnTo,
21
+ signInResult,
22
+ useConnectionOfTool,
23
+ useConnections,
24
+ useConnectorActions,
25
+ useConnectorCatalogue,
26
+ useConnectorLogoUrl,
27
+ useWebSignInReturn,
28
+ } from './runtime/connectors';
29
+ export type {
30
+ Connection,
31
+ ConnectionStatus,
32
+ ConnectorCategory,
33
+ ConnectorEntry,
34
+ } from './runtime/connectors';
@@ -24,7 +24,15 @@ export function useGemieActivity(options: UseGemieActivityOptions = {}): GemieAv
24
24
 
25
25
  useEffect(() => {
26
26
  if (!isAuthenticated) return;
27
- return acquireActivitySocket(apiUrl, () => oxyServices.session.accessToken);
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
+ };
28
36
  }, [apiUrl, isAuthenticated, oxyServices]);
29
37
 
30
38
  return useGemieActivityStore(selectGemieActivity);
@@ -4,8 +4,17 @@ import { useGemieActivityStore } from './activity-store';
4
4
 
5
5
  /** A run that goes quiet this long is over: a crashed run never says `idle`. */
6
6
  export const ACTIVITY_QUIET_MS = 90_000;
7
- /** Between tries after the server refuses a handshake (socket.io does not retry those itself). */
8
- const RETRY_MS = 5_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>;
9
18
 
10
19
  const STATES: ReadonlySet<string> = new Set<GemieAvatarState>([
11
20
  'idle',
@@ -19,22 +28,40 @@ interface Connection {
19
28
  refs: number;
20
29
  quiet: Map<string, ReturnType<typeof setTimeout>>;
21
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>;
22
34
  }
23
35
 
24
36
  /** One connection per API origin, however many buttons ask for it. */
25
37
  const connections = new Map<string, Connection>();
26
38
 
27
- function open(url: string, getToken: () => string | null): Connection {
39
+ function open(url: string): Connection {
40
+ const tokens = new Map<symbol, ActivityTokenSource>();
28
41
  const socket = io(url, {
29
42
  transports: ['websocket'],
30
- // Read on every (re)connect, so a rotated access token is the one that goes out.
31
- auth: (cb) => cb({ token: getToken() }),
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
+ },
32
52
  reconnection: true,
33
53
  reconnectionAttempts: Infinity,
34
54
  reconnectionDelay: 1000,
35
55
  reconnectionDelayMax: 10_000,
36
56
  });
37
- const connection: Connection = { socket, refs: 0, quiet: new Map(), retry: null };
57
+ const connection: Connection = {
58
+ socket,
59
+ refs: 0,
60
+ quiet: new Map(),
61
+ retry: null,
62
+ retryMs: RETRY_MS,
63
+ tokens,
64
+ };
38
65
  const store = useGemieActivityStore.getState;
39
66
 
40
67
  const reset = (): void => {
@@ -43,16 +70,21 @@ function open(url: string, getToken: () => string | null): Connection {
43
70
  store().clearRemote();
44
71
  };
45
72
 
46
- socket.on('connect', () => socket.emit('subscribe-alia-activity'));
73
+ socket.on('connect', () => {
74
+ connection.retryMs = RETRY_MS;
75
+ socket.emit('subscribe-alia-activity');
76
+ });
47
77
  // What happened while disconnected is unknown; a stale "working" is worse than idle.
48
78
  socket.on('disconnect', reset);
49
79
  socket.on('connect_error', () => {
50
80
  // A refused handshake (no token yet, an expired one) ends the socket's own retrying.
51
81
  if (socket.active || connection.retry !== null) return;
82
+ const wait = connection.retryMs;
83
+ connection.retryMs = Math.min(wait * 2, MAX_RETRY_MS);
52
84
  connection.retry = setTimeout(() => {
53
85
  connection.retry = null;
54
86
  socket.connect();
55
- }, RETRY_MS);
87
+ }, wait);
56
88
  });
57
89
  socket.on('alia:activity', (event: unknown) => {
58
90
  if (typeof event !== 'object' || event === null) return;
@@ -79,18 +111,21 @@ function open(url: string, getToken: () => string | null): Connection {
79
111
  * Listen for Alia's activity on the person's behalf. Every caller shares the one connection for
80
112
  * `url`; the last to release closes it. Returns the release.
81
113
  */
82
- export function acquireActivitySocket(url: string, getToken: () => string | null): () => void {
114
+ export function acquireActivitySocket(url: string, getToken: ActivityTokenSource): () => void {
83
115
  let held = connections.get(url);
84
116
  if (!held) {
85
- held = open(url, getToken);
117
+ held = open(url);
86
118
  connections.set(url, held);
87
119
  }
88
120
  const connection = held;
121
+ const holder = Symbol('activity-holder');
122
+ connection.tokens.set(holder, getToken);
89
123
  connection.refs++;
90
124
  let released = false;
91
125
  return () => {
92
126
  if (released) return;
93
127
  released = true;
128
+ connection.tokens.delete(holder);
94
129
  if (--connection.refs > 0) return;
95
130
  connections.delete(url);
96
131
  if (connection.retry !== null) clearTimeout(connection.retry);