@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.
- package/CHANGELOG.md +43 -0
- package/README.md +19 -0
- package/package.json +2 -1
- package/src/components/GemieActivityLine.tsx +28 -0
- package/src/components/GemieChatContent.tsx +5 -2
- package/src/components/GemieParticipants.tsx +4 -0
- package/src/components/connectors/GemieConnectorsStore.tsx +208 -78
- package/src/connectors.ts +14 -5
- package/src/hooks/useGemieActivity.ts +28 -23
- package/src/hooks/useMessageReactions.ts +10 -15
- package/src/index.ts +6 -0
- package/src/lib/activity-store.ts +6 -16
- package/src/lib/copy-en.ts +28 -1
- package/src/lib/copy-es.ts +28 -1
- package/src/lib/labels-es.ts +10 -0
- package/src/lib/labels.tsx +11 -0
- package/src/lib/participants.ts +5 -0
- package/src/realtime/activity-text.ts +23 -0
- package/src/realtime/activity.ts +96 -0
- package/src/realtime/cache.ts +244 -0
- package/src/realtime/connection.ts +317 -0
- package/src/realtime/contract.ts +148 -0
- package/src/realtime/index.ts +33 -0
- package/src/realtime/react.tsx +196 -0
- package/src/runtime/config.tsx +8 -26
- package/src/runtime/connectors.ts +101 -17
- package/src/runtime/conversations.ts +55 -3
- package/src/runtime/index.ts +8 -0
- package/src/runtime/routes.ts +2 -0
- package/src/runtime/types.ts +5 -0
- package/src/runtime/use-agent-activity.ts +18 -45
- package/src/runtime/use-conversation-stream.ts +7 -2
- package/src/runtime/use-conversation-thread.ts +61 -26
- package/src/runtime/use-room-events.ts +10 -9
- package/src/lib/activity-socket.ts +0 -137
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { useOxy } from '@oxy.so/services/ui/client';
|
|
2
1
|
import { useCallback, useEffect, useState } from 'react';
|
|
3
|
-
import {
|
|
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:
|
|
21
|
-
*
|
|
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
|
|
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
|
-
//
|
|
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,
|
|
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 (
|
|
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
|
-
//
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
244
|
-
//
|
|
245
|
-
//
|
|
246
|
-
//
|
|
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
|
|
250
|
-
|
|
251
|
-
|
|
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,
|
|
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 {
|
|
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 (`
|
|
13
|
-
* Group turns and reaction-triggered agent replies share this lifecycle.
|
|
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
|
|
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 || !
|
|
35
|
+
if (!conversationId || !realtime) return;
|
|
37
36
|
let lastEventAt = Date.now();
|
|
38
37
|
const failedChains = new Set<string>();
|
|
39
|
-
const unsubscribe =
|
|
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,
|
|
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
|
-
}
|