@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
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Realtime events into the conversation runtime's React Query cache (`docs/realtime.mdx`).
|
|
3
|
+
*
|
|
4
|
+
* Every write here is an idempotent upsert of what the server says now — the sidebar row by
|
|
5
|
+
* conversation id, a message by its id, a reaction by its revision — so applying an event twice,
|
|
6
|
+
* or again over a snapshot that predates it (`noteSnapshot`), converges on the same state. Nothing
|
|
7
|
+
* here refetches on a timer: only `reload` (a rewritten thread) and `reset` (a client too far
|
|
8
|
+
* behind) read again, and only what they name.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { QueryClient } from '@tanstack/react-query';
|
|
12
|
+
import { normalizeConversationMessages } from '../runtime/message-history';
|
|
13
|
+
import { gemieQueryKeys, type ConversationsFilter } from '../runtime/query-keys';
|
|
14
|
+
import { updateReactionCaches } from '../runtime/reaction-cache';
|
|
15
|
+
import type { Conversation, ConversationsInfiniteData, Message } from '../runtime/types';
|
|
16
|
+
import type { RealtimeConnection } from './connection';
|
|
17
|
+
import type { RealtimeConversationRow, RealtimeData, RealtimeFrame } from './contract';
|
|
18
|
+
|
|
19
|
+
function toConversation(row: RealtimeConversationRow): Conversation {
|
|
20
|
+
return {
|
|
21
|
+
id: row.id,
|
|
22
|
+
title: row.title,
|
|
23
|
+
...(row.lastMessage === null ? {} : { lastMessage: row.lastMessage }),
|
|
24
|
+
source: row.source,
|
|
25
|
+
agentId: row.agentId,
|
|
26
|
+
memberAgentIds: row.memberAgentIds,
|
|
27
|
+
spaceId: row.spaceId,
|
|
28
|
+
threadId: row.threadId,
|
|
29
|
+
app: row.app,
|
|
30
|
+
unreadCount: row.unreadCount,
|
|
31
|
+
createdAt: new Date(row.createdAt),
|
|
32
|
+
updatedAt: new Date(row.updatedAt),
|
|
33
|
+
messages: [],
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function matches(filter: ConversationsFilter | undefined, row: Conversation): boolean {
|
|
38
|
+
if (!filter) return true;
|
|
39
|
+
if (filter.agentId !== undefined && row.agentId !== filter.agentId) return false;
|
|
40
|
+
if (filter.app !== undefined && row.app !== filter.app) return false;
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The row where the list's order puts it: newest `updatedAt` first, on the first page. A row whose
|
|
46
|
+
* copy is already newer than this one keeps that copy (an event replayed over a fresher snapshot).
|
|
47
|
+
*/
|
|
48
|
+
export function placeConversation(
|
|
49
|
+
data: ConversationsInfiniteData | undefined,
|
|
50
|
+
row: Conversation,
|
|
51
|
+
): ConversationsInfiniteData | undefined {
|
|
52
|
+
if (!data?.pages?.length) return data;
|
|
53
|
+
let existing: Conversation | undefined;
|
|
54
|
+
const pages = data.pages.map((page) => {
|
|
55
|
+
const index = page.conversations.findIndex((c) => c.id === row.id);
|
|
56
|
+
if (index < 0) return page;
|
|
57
|
+
existing = page.conversations[index];
|
|
58
|
+
return { ...page, conversations: page.conversations.filter((c) => c.id !== row.id) };
|
|
59
|
+
});
|
|
60
|
+
if (existing && new Date(existing.updatedAt).getTime() > row.updatedAt.getTime()) return data;
|
|
61
|
+
const [first, ...rest] = pages;
|
|
62
|
+
if (!first) return data;
|
|
63
|
+
const conversations = [...first.conversations];
|
|
64
|
+
const at = conversations.findIndex(
|
|
65
|
+
(c) => new Date(c.updatedAt).getTime() <= row.updatedAt.getTime(),
|
|
66
|
+
);
|
|
67
|
+
// Older than everything on the first page and not there already: it belongs to a later page,
|
|
68
|
+
// which a scroll will read.
|
|
69
|
+
if (at < 0 && !existing && first.hasMore) return { ...data, pages };
|
|
70
|
+
conversations.splice(at < 0 ? conversations.length : at, 0, row);
|
|
71
|
+
return { ...data, pages: [{ ...first, conversations }, ...rest] };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The person just sent in a conversation: its row goes to the top with their words, now. The
|
|
76
|
+
* server's `conversation` event replaces this with what it stored.
|
|
77
|
+
*/
|
|
78
|
+
export function bumpConversation(client: QueryClient, id: string, preview: string): void {
|
|
79
|
+
for (const query of client
|
|
80
|
+
.getQueryCache()
|
|
81
|
+
.findAll({ queryKey: gemieQueryKeys.conversations.all })) {
|
|
82
|
+
const current = query.state.data as ConversationsInfiniteData | undefined;
|
|
83
|
+
const existing = current?.pages?.flatMap((page) => page.conversations).find((c) => c.id === id);
|
|
84
|
+
if (!existing) continue;
|
|
85
|
+
const next = placeConversation(current, {
|
|
86
|
+
...existing,
|
|
87
|
+
...(preview ? { lastMessage: preview.slice(0, 100) } : {}),
|
|
88
|
+
updatedAt: new Date(),
|
|
89
|
+
});
|
|
90
|
+
if (next !== current) client.setQueryData(query.queryKey, next);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function removeConversation(
|
|
95
|
+
data: ConversationsInfiniteData | undefined,
|
|
96
|
+
id: string,
|
|
97
|
+
): ConversationsInfiniteData | undefined {
|
|
98
|
+
if (!data?.pages) return data;
|
|
99
|
+
return {
|
|
100
|
+
...data,
|
|
101
|
+
pages: data.pages.map((page) => ({
|
|
102
|
+
...page,
|
|
103
|
+
conversations: page.conversations.filter((c) => c.id !== id),
|
|
104
|
+
})),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Messages merged by id: a copy the client drew under the same id is replaced, never doubled. */
|
|
109
|
+
export function mergeMessages(
|
|
110
|
+
previous: readonly Message[],
|
|
111
|
+
incoming: readonly Message[],
|
|
112
|
+
): Message[] {
|
|
113
|
+
if (incoming.length === 0) return [...previous];
|
|
114
|
+
const next = [...previous];
|
|
115
|
+
for (const message of incoming) {
|
|
116
|
+
if (!message?.id) continue;
|
|
117
|
+
const index = next.findIndex((m) => m.id === message.id);
|
|
118
|
+
if (index >= 0) next[index] = { ...next[index], ...message };
|
|
119
|
+
else next.push(message);
|
|
120
|
+
}
|
|
121
|
+
return next;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function applyConversation(client: QueryClient, data: RealtimeData['conversation']): void {
|
|
125
|
+
const row = toConversation(data.conversation);
|
|
126
|
+
for (const query of client
|
|
127
|
+
.getQueryCache()
|
|
128
|
+
.findAll({ queryKey: gemieQueryKeys.conversations.all })) {
|
|
129
|
+
const filter = query.queryKey[1] as ConversationsFilter | undefined;
|
|
130
|
+
const current = query.state.data as ConversationsInfiniteData | undefined;
|
|
131
|
+
const next = matches(filter, row)
|
|
132
|
+
? placeConversation(current, row)
|
|
133
|
+
: removeConversation(current, row.id);
|
|
134
|
+
if (next !== current) client.setQueryData(query.queryKey, next);
|
|
135
|
+
}
|
|
136
|
+
const appended = data.appended ? normalizeConversationMessages(data.appended) : [];
|
|
137
|
+
client.setQueryData<Conversation>(gemieQueryKeys.conversations.detail(row.id), (previous) =>
|
|
138
|
+
previous
|
|
139
|
+
? {
|
|
140
|
+
...previous,
|
|
141
|
+
...row,
|
|
142
|
+
messages: mergeMessages(previous.messages ?? [], appended),
|
|
143
|
+
}
|
|
144
|
+
: previous,
|
|
145
|
+
);
|
|
146
|
+
// A gemie's thread view reads which stretch is active; a message may have started a new one.
|
|
147
|
+
if (appended.length > 0) void client.invalidateQueries({ queryKey: ['agent-thread'] });
|
|
148
|
+
if (data.reload) {
|
|
149
|
+
void client.invalidateQueries({
|
|
150
|
+
queryKey: gemieQueryKeys.conversations.detail(row.id),
|
|
151
|
+
exact: true,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function applyDeleted(client: QueryClient, data: RealtimeData['conversation.deleted']): void {
|
|
157
|
+
for (const query of client
|
|
158
|
+
.getQueryCache()
|
|
159
|
+
.findAll({ queryKey: gemieQueryKeys.conversations.all })) {
|
|
160
|
+
const current = query.state.data as ConversationsInfiniteData | undefined;
|
|
161
|
+
const next = removeConversation(current, data.conversationId);
|
|
162
|
+
if (next !== current) client.setQueryData(query.queryKey, next);
|
|
163
|
+
}
|
|
164
|
+
client.removeQueries({
|
|
165
|
+
queryKey: gemieQueryKeys.conversations.detail(data.conversationId),
|
|
166
|
+
exact: true,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Apply one frame to the runtime's own caches. Pure cache writes: safe to call twice. */
|
|
171
|
+
export function applyRealtimeToCache(client: QueryClient, frame: RealtimeFrame): void {
|
|
172
|
+
switch (frame.type) {
|
|
173
|
+
case 'conversation':
|
|
174
|
+
applyConversation(client, frame.data as RealtimeData['conversation']);
|
|
175
|
+
return;
|
|
176
|
+
case 'conversation.deleted':
|
|
177
|
+
applyDeleted(client, frame.data as RealtimeData['conversation.deleted']);
|
|
178
|
+
return;
|
|
179
|
+
case 'message.reaction':
|
|
180
|
+
{
|
|
181
|
+
const update = frame.data as RealtimeData['message.reaction'];
|
|
182
|
+
updateReactionCaches(client, { ...update, reactions: [...update.reactions] });
|
|
183
|
+
}
|
|
184
|
+
return;
|
|
185
|
+
case 'connections':
|
|
186
|
+
// The person's connected accounts and connectors: their lists are read again, once.
|
|
187
|
+
void client.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
|
|
188
|
+
void client.invalidateQueries({ queryKey: ['gemie-connectors', 'connected'] });
|
|
189
|
+
return;
|
|
190
|
+
default:
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** What a client too far behind reads again: the runtime's lists and the open conversations. */
|
|
195
|
+
export function resetRealtimeCache(client: QueryClient): void {
|
|
196
|
+
void client.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
|
|
197
|
+
void client.invalidateQueries({ queryKey: ['conversation'] });
|
|
198
|
+
void client.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
|
|
199
|
+
void client.invalidateQueries({ queryKey: ['gemie-connectors', 'connected'] });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const attached = new WeakMap<
|
|
203
|
+
QueryClient,
|
|
204
|
+
Map<RealtimeConnection, { refs: number; detach: () => void }>
|
|
205
|
+
>();
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Keep one QueryClient's runtime caches in step with a connection. Nested runtime providers attach
|
|
209
|
+
* the same pair more than once; it is wired once and released with its last holder.
|
|
210
|
+
*/
|
|
211
|
+
export function attachRealtimeCache(
|
|
212
|
+
connection: RealtimeConnection,
|
|
213
|
+
client: QueryClient,
|
|
214
|
+
): () => void {
|
|
215
|
+
let byConnection = attached.get(client);
|
|
216
|
+
if (!byConnection) {
|
|
217
|
+
byConnection = new Map();
|
|
218
|
+
attached.set(client, byConnection);
|
|
219
|
+
}
|
|
220
|
+
const existing = byConnection.get(connection);
|
|
221
|
+
if (existing) {
|
|
222
|
+
existing.refs++;
|
|
223
|
+
} else {
|
|
224
|
+
const offFrames = connection.on('*', (frame) => applyRealtimeToCache(client, frame));
|
|
225
|
+
const offReset = connection.onReset(() => resetRealtimeCache(client));
|
|
226
|
+
byConnection.set(connection, {
|
|
227
|
+
refs: 1,
|
|
228
|
+
detach: () => {
|
|
229
|
+
offFrames();
|
|
230
|
+
offReset();
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
let released = false;
|
|
235
|
+
return () => {
|
|
236
|
+
if (released) return;
|
|
237
|
+
released = true;
|
|
238
|
+
const entry = byConnection?.get(connection);
|
|
239
|
+
if (!entry) return;
|
|
240
|
+
if (--entry.refs > 0) return;
|
|
241
|
+
entry.detach();
|
|
242
|
+
byConnection?.delete(connection);
|
|
243
|
+
};
|
|
244
|
+
}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE realtime connection of one signed-in account to one Gemies API (`docs/realtime.mdx`).
|
|
3
|
+
*
|
|
4
|
+
* One Socket.IO connection per (API, account), however many screens listen: they share it through
|
|
5
|
+
* {@link acquireRealtime} and the last to release closes it. It:
|
|
6
|
+
*
|
|
7
|
+
* - authenticates every (re)connect with a fresh token of the API's own linked Oxy client;
|
|
8
|
+
* - reconnects with jittered backoff (Socket.IO's own), and after the server REFUSES a handshake —
|
|
9
|
+
* which Socket.IO does not retry — tries again on a doubling delay up to a minute;
|
|
10
|
+
* - keeps the account's event cursor, and on every connect asks `rt:sync` for what came after it:
|
|
11
|
+
* missed events are replayed in order, a client too far behind is told to reload (`reset`);
|
|
12
|
+
* - drops a durable frame it already applied, and treats a frame that skips a number as a gap to
|
|
13
|
+
* fill from `rt:sync`, so an event is applied once and in order;
|
|
14
|
+
* - re-subscribes the topics its holders follow after every reconnect.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { io, type Socket } from 'socket.io-client';
|
|
18
|
+
import {
|
|
19
|
+
REALTIME_EVENT,
|
|
20
|
+
REALTIME_SUBSCRIBE,
|
|
21
|
+
REALTIME_SYNC,
|
|
22
|
+
REALTIME_UNSUBSCRIBE,
|
|
23
|
+
readFrame,
|
|
24
|
+
type RealtimeFrame,
|
|
25
|
+
type RealtimeSyncReply,
|
|
26
|
+
type RealtimeType,
|
|
27
|
+
} from './contract';
|
|
28
|
+
|
|
29
|
+
/** A holder's way to the API's access token: asked on every (re)connect. */
|
|
30
|
+
export type RealtimeTokenSource = () => string | null | Promise<string | null>;
|
|
31
|
+
|
|
32
|
+
export type RealtimeListener = (frame: RealtimeFrame) => void;
|
|
33
|
+
|
|
34
|
+
/** After a refused handshake: the first wait, doubled up to the second. */
|
|
35
|
+
export const REFUSED_RETRY_MS = 5_000;
|
|
36
|
+
export const REFUSED_RETRY_MAX_MS = 60_000;
|
|
37
|
+
/** How many applied durable frames are kept to re-apply over a snapshot that predates them. */
|
|
38
|
+
const REPLAY_BUFFER = 256;
|
|
39
|
+
|
|
40
|
+
export interface RealtimeConnection {
|
|
41
|
+
/** Listen for one type, or every frame (`'*'`). Returns the unsubscribe. */
|
|
42
|
+
on(type: RealtimeType | '*', listener: RealtimeListener): () => void;
|
|
43
|
+
/** Called when the client must reload what it shows (its cursor fell out of the log). */
|
|
44
|
+
onReset(listener: () => void): () => void;
|
|
45
|
+
/** Called when the connection comes up or goes down. Returns the unsubscribe. */
|
|
46
|
+
onStatus(listener: (connected: boolean) => void): () => void;
|
|
47
|
+
/**
|
|
48
|
+
* A device's own protocol on the same connection, outside the `rt` frames: the local model
|
|
49
|
+
* runtime's offer (`subscribe-user-runtime`) and the requests the server sends it. Dropped while
|
|
50
|
+
* disconnected; a protocol re-sends what it must from `onStatus`.
|
|
51
|
+
*/
|
|
52
|
+
send(event: string, payload?: unknown): void;
|
|
53
|
+
/** Hear one of those protocol events. Returns the unsubscribe. */
|
|
54
|
+
listen(event: string, handler: (payload: unknown) => void): () => void;
|
|
55
|
+
/** Follow a topic while held; re-subscribed after every reconnect. Returns the release. */
|
|
56
|
+
follow(topic: string): () => void;
|
|
57
|
+
/**
|
|
58
|
+
* An HTTP read that carried the account's cursor (`realtimeSeq`). Events after it that this
|
|
59
|
+
* connection already applied are applied again, after the read's data is in the cache, so a
|
|
60
|
+
* response that left before an event arrived cannot put the older state back.
|
|
61
|
+
*/
|
|
62
|
+
noteSnapshot(seq: number): void;
|
|
63
|
+
readonly connected: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface Internal extends RealtimeConnection {
|
|
67
|
+
socket: Socket;
|
|
68
|
+
refs: number;
|
|
69
|
+
tokens: Map<symbol, RealtimeTokenSource>;
|
|
70
|
+
close(): void;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function open(url: string): Internal {
|
|
74
|
+
const tokens = new Map<symbol, RealtimeTokenSource>();
|
|
75
|
+
const listeners = new Map<string, Set<RealtimeListener>>();
|
|
76
|
+
const resetListeners = new Set<() => void>();
|
|
77
|
+
const statusListeners = new Set<(connected: boolean) => void>();
|
|
78
|
+
const status = (connected: boolean): void => {
|
|
79
|
+
for (const listener of [...statusListeners]) listener(connected);
|
|
80
|
+
};
|
|
81
|
+
const topics = new Map<string, number>();
|
|
82
|
+
/** The last durable number applied; `null` until the first sync answered. */
|
|
83
|
+
let cursor: number | null = null;
|
|
84
|
+
/** The lowest snapshot seen before the first sync: where catch-up starts. */
|
|
85
|
+
let floor: number | null = null;
|
|
86
|
+
let syncing = false;
|
|
87
|
+
let resyncWanted = false;
|
|
88
|
+
const queued: RealtimeFrame[] = [];
|
|
89
|
+
const applied: RealtimeFrame[] = [];
|
|
90
|
+
let retry: ReturnType<typeof setTimeout> | null = null;
|
|
91
|
+
let retryMs = REFUSED_RETRY_MS;
|
|
92
|
+
|
|
93
|
+
const socket = io(url, {
|
|
94
|
+
transports: ['websocket'],
|
|
95
|
+
auth: (cb) => {
|
|
96
|
+
const source = [...tokens.values()].at(-1);
|
|
97
|
+
// A source that throws is a handshake without a token, never a crash of the caller.
|
|
98
|
+
new Promise<string | null>((resolve) => resolve(source ? source() : null)).then(
|
|
99
|
+
(token) => cb(token ? { token } : {}),
|
|
100
|
+
() => cb({}),
|
|
101
|
+
);
|
|
102
|
+
},
|
|
103
|
+
reconnection: true,
|
|
104
|
+
reconnectionAttempts: Number.POSITIVE_INFINITY,
|
|
105
|
+
reconnectionDelay: 1_000,
|
|
106
|
+
reconnectionDelayMax: 30_000,
|
|
107
|
+
randomizationFactor: 0.5,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const dispatch = (frame: RealtimeFrame): void => {
|
|
111
|
+
for (const key of [frame.type, '*']) {
|
|
112
|
+
const set = listeners.get(key);
|
|
113
|
+
if (!set) continue;
|
|
114
|
+
for (const listener of [...set]) {
|
|
115
|
+
try {
|
|
116
|
+
listener(frame);
|
|
117
|
+
} catch {
|
|
118
|
+
// One listener's failure is its own; the others still hear the frame.
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const applyDurable = (frame: RealtimeFrame): void => {
|
|
125
|
+
const seq = frame.seq as number;
|
|
126
|
+
if (cursor !== null && seq <= cursor) return;
|
|
127
|
+
if (cursor !== null && seq > cursor + 1) {
|
|
128
|
+
// A number was skipped: fetch the gap, which replays this frame too, in order.
|
|
129
|
+
sync();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
cursor = seq;
|
|
133
|
+
applied.push(frame);
|
|
134
|
+
if (applied.length > REPLAY_BUFFER) applied.shift();
|
|
135
|
+
dispatch(frame);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const sync = (): void => {
|
|
139
|
+
if (!socket.connected) return;
|
|
140
|
+
if (syncing) {
|
|
141
|
+
resyncWanted = true;
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
syncing = true;
|
|
145
|
+
const since = cursor ?? floor;
|
|
146
|
+
socket.emit(REALTIME_SYNC, { since }, (reply: RealtimeSyncReply) => {
|
|
147
|
+
syncing = false;
|
|
148
|
+
if (reply && typeof reply.head === 'number' && reply.head >= 0) {
|
|
149
|
+
if (reply.reset) {
|
|
150
|
+
cursor = reply.head;
|
|
151
|
+
applied.length = 0;
|
|
152
|
+
for (const listener of [...resetListeners]) listener();
|
|
153
|
+
} else {
|
|
154
|
+
if (cursor === null) cursor = since ?? reply.head;
|
|
155
|
+
for (const event of reply.events ?? []) {
|
|
156
|
+
const frame = readFrame(event);
|
|
157
|
+
if (frame?.seq !== undefined) applyDurable(frame);
|
|
158
|
+
}
|
|
159
|
+
if (cursor < reply.head && (reply.events?.length ?? 0) === 0) cursor = reply.head;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const pending = queued.splice(0);
|
|
163
|
+
for (const frame of pending) applyDurable(frame);
|
|
164
|
+
if (resyncWanted) {
|
|
165
|
+
resyncWanted = false;
|
|
166
|
+
sync();
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
socket.on('connect', () => {
|
|
172
|
+
retryMs = REFUSED_RETRY_MS;
|
|
173
|
+
sync();
|
|
174
|
+
for (const topic of topics.keys()) socket.emit(REALTIME_SUBSCRIBE, { topic });
|
|
175
|
+
status(true);
|
|
176
|
+
});
|
|
177
|
+
socket.on('disconnect', () => status(false));
|
|
178
|
+
socket.on('connect_error', () => {
|
|
179
|
+
// A refused handshake (no token yet, an expired one) ends Socket.IO's own retrying.
|
|
180
|
+
if (socket.active || retry !== null) return;
|
|
181
|
+
const wait = retryMs;
|
|
182
|
+
retryMs = Math.min(retryMs * 2, REFUSED_RETRY_MAX_MS);
|
|
183
|
+
retry = setTimeout(() => {
|
|
184
|
+
retry = null;
|
|
185
|
+
socket.connect();
|
|
186
|
+
}, wait);
|
|
187
|
+
});
|
|
188
|
+
socket.on(REALTIME_EVENT, (value: unknown) => {
|
|
189
|
+
const frame = readFrame(value);
|
|
190
|
+
if (!frame) return;
|
|
191
|
+
if (frame.seq === undefined) {
|
|
192
|
+
dispatch(frame);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (cursor === null || syncing) {
|
|
196
|
+
queued.push(frame);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
applyDurable(frame);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
socket,
|
|
204
|
+
refs: 0,
|
|
205
|
+
tokens,
|
|
206
|
+
get connected() {
|
|
207
|
+
return socket.connected;
|
|
208
|
+
},
|
|
209
|
+
on(type, listener) {
|
|
210
|
+
let set = listeners.get(type);
|
|
211
|
+
if (!set) {
|
|
212
|
+
set = new Set();
|
|
213
|
+
listeners.set(type, set);
|
|
214
|
+
}
|
|
215
|
+
set.add(listener);
|
|
216
|
+
return () => {
|
|
217
|
+
listeners.get(type)?.delete(listener);
|
|
218
|
+
};
|
|
219
|
+
},
|
|
220
|
+
onReset(listener) {
|
|
221
|
+
resetListeners.add(listener);
|
|
222
|
+
return () => {
|
|
223
|
+
resetListeners.delete(listener);
|
|
224
|
+
};
|
|
225
|
+
},
|
|
226
|
+
onStatus(listener) {
|
|
227
|
+
statusListeners.add(listener);
|
|
228
|
+
return () => {
|
|
229
|
+
statusListeners.delete(listener);
|
|
230
|
+
};
|
|
231
|
+
},
|
|
232
|
+
send(event, payload) {
|
|
233
|
+
if (socket.connected) socket.emit(event, payload);
|
|
234
|
+
},
|
|
235
|
+
listen(event, handler) {
|
|
236
|
+
socket.on(event, handler);
|
|
237
|
+
return () => {
|
|
238
|
+
socket.off(event, handler);
|
|
239
|
+
};
|
|
240
|
+
},
|
|
241
|
+
follow(topic) {
|
|
242
|
+
const held = topics.get(topic) ?? 0;
|
|
243
|
+
topics.set(topic, held + 1);
|
|
244
|
+
if (held === 0 && socket.connected) socket.emit(REALTIME_SUBSCRIBE, { topic });
|
|
245
|
+
let released = false;
|
|
246
|
+
return () => {
|
|
247
|
+
if (released) return;
|
|
248
|
+
released = true;
|
|
249
|
+
const left = (topics.get(topic) ?? 1) - 1;
|
|
250
|
+
if (left > 0) {
|
|
251
|
+
topics.set(topic, left);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
topics.delete(topic);
|
|
255
|
+
if (socket.connected) socket.emit(REALTIME_UNSUBSCRIBE, { topic });
|
|
256
|
+
};
|
|
257
|
+
},
|
|
258
|
+
noteSnapshot(seq) {
|
|
259
|
+
if (!Number.isSafeInteger(seq) || seq < 0) return;
|
|
260
|
+
if (cursor === null) {
|
|
261
|
+
floor = floor === null ? seq : Math.min(floor, seq);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (seq >= cursor) return;
|
|
265
|
+
const newer = applied.filter((frame) => (frame.seq as number) > seq);
|
|
266
|
+
if (newer.length === 0) return;
|
|
267
|
+
// After the read's data has been written: re-apply what it predates.
|
|
268
|
+
setTimeout(() => {
|
|
269
|
+
for (const frame of newer) dispatch(frame);
|
|
270
|
+
}, 0);
|
|
271
|
+
},
|
|
272
|
+
close() {
|
|
273
|
+
if (retry !== null) clearTimeout(retry);
|
|
274
|
+
socket.removeAllListeners();
|
|
275
|
+
socket.disconnect();
|
|
276
|
+
listeners.clear();
|
|
277
|
+
resetListeners.clear();
|
|
278
|
+
statusListeners.clear();
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const connections = new Map<string, Internal>();
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Hold the realtime connection of `account` to `url`, opening it on the first hold. The token
|
|
287
|
+
* source is the holder's; the connection asks the latest one still held. Returns the connection and
|
|
288
|
+
* its release: the last release closes it.
|
|
289
|
+
*/
|
|
290
|
+
export function acquireRealtime(
|
|
291
|
+
url: string,
|
|
292
|
+
account: string,
|
|
293
|
+
token: RealtimeTokenSource,
|
|
294
|
+
): { connection: RealtimeConnection; release: () => void } {
|
|
295
|
+
const key = `${url}|${account}`;
|
|
296
|
+
let held = connections.get(key);
|
|
297
|
+
if (!held) {
|
|
298
|
+
held = open(url);
|
|
299
|
+
connections.set(key, held);
|
|
300
|
+
}
|
|
301
|
+
const connection = held;
|
|
302
|
+
const holder = Symbol('realtime-holder');
|
|
303
|
+
connection.tokens.set(holder, token);
|
|
304
|
+
connection.refs++;
|
|
305
|
+
let released = false;
|
|
306
|
+
return {
|
|
307
|
+
connection,
|
|
308
|
+
release: () => {
|
|
309
|
+
if (released) return;
|
|
310
|
+
released = true;
|
|
311
|
+
connection.tokens.delete(holder);
|
|
312
|
+
if (--connection.refs > 0) return;
|
|
313
|
+
connections.delete(key);
|
|
314
|
+
connection.close();
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The realtime wire contract, as clients read it (`docs/realtime.mdx`). The API's
|
|
3
|
+
* `lib/realtime/contract.ts` and `domain/account-events.ts` are the server's copy;
|
|
4
|
+
* `packages/api/src/__tests__/realtime-contract.test.ts` holds the two lists equal.
|
|
5
|
+
*
|
|
6
|
+
* Pure data: no React, no socket, so a test on either side can import it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Message } from '../runtime/types';
|
|
10
|
+
|
|
11
|
+
/** The one server → client event. */
|
|
12
|
+
export const REALTIME_EVENT = 'rt';
|
|
13
|
+
/** Client → server: catch up from a cursor. */
|
|
14
|
+
export const REALTIME_SYNC = 'rt:sync';
|
|
15
|
+
/** Client → server: follow a topic (`agent:<id>`, `agent-session:<id>`). */
|
|
16
|
+
export const REALTIME_SUBSCRIBE = 'rt:subscribe';
|
|
17
|
+
/** Client → server: stop following a topic. */
|
|
18
|
+
export const REALTIME_UNSUBSCRIBE = 'rt:unsubscribe';
|
|
19
|
+
|
|
20
|
+
/** Durable: numbered per account, replayed to a client that reconnects. */
|
|
21
|
+
export const REALTIME_DURABLE_TYPES = [
|
|
22
|
+
'conversation',
|
|
23
|
+
'conversation.deleted',
|
|
24
|
+
'message.reaction',
|
|
25
|
+
'gemies',
|
|
26
|
+
'credits',
|
|
27
|
+
'notification',
|
|
28
|
+
'connections',
|
|
29
|
+
] as const;
|
|
30
|
+
|
|
31
|
+
/** Signals: only true while they happen, never replayed. */
|
|
32
|
+
export const REALTIME_SIGNAL_TYPES = [
|
|
33
|
+
'activity',
|
|
34
|
+
'room',
|
|
35
|
+
'presence',
|
|
36
|
+
'runtimes',
|
|
37
|
+
'show.progress',
|
|
38
|
+
'agent.activity',
|
|
39
|
+
] as const;
|
|
40
|
+
|
|
41
|
+
export type RealtimeDurableType = (typeof REALTIME_DURABLE_TYPES)[number];
|
|
42
|
+
export type RealtimeSignalType = (typeof REALTIME_SIGNAL_TYPES)[number];
|
|
43
|
+
export type RealtimeType = RealtimeDurableType | RealtimeSignalType;
|
|
44
|
+
|
|
45
|
+
export interface RealtimeFrame<T extends RealtimeType = RealtimeType> {
|
|
46
|
+
readonly v: 1;
|
|
47
|
+
readonly type: T;
|
|
48
|
+
readonly data: RealtimeData[T];
|
|
49
|
+
readonly seq?: number;
|
|
50
|
+
readonly topic?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface RealtimeSyncReply {
|
|
54
|
+
readonly head: number;
|
|
55
|
+
readonly events?: readonly RealtimeFrame[];
|
|
56
|
+
readonly reset?: true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A conversation as a list shows it (the API's `ConversationSummary`), dates as ISO strings. */
|
|
60
|
+
export interface RealtimeConversationRow {
|
|
61
|
+
readonly id: string;
|
|
62
|
+
readonly title: string;
|
|
63
|
+
readonly lastMessage: string | null;
|
|
64
|
+
readonly source: string;
|
|
65
|
+
readonly agentId: string | null;
|
|
66
|
+
readonly threadId: string | null;
|
|
67
|
+
readonly memberAgentIds: string[];
|
|
68
|
+
readonly spaceId: string | null;
|
|
69
|
+
readonly app: string | null;
|
|
70
|
+
readonly unreadCount: number;
|
|
71
|
+
readonly createdAt: string;
|
|
72
|
+
readonly updatedAt: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A gemie's whole thread with the person (many conversations): its sidebar row's badge. */
|
|
76
|
+
export interface RealtimeThreadTotal {
|
|
77
|
+
readonly agentId: string | null;
|
|
78
|
+
readonly unreadCount: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type ActivityState = 'thinking' | 'writing' | 'tool' | 'idle';
|
|
82
|
+
|
|
83
|
+
export interface RealtimeActivity {
|
|
84
|
+
readonly conversationId: string | null;
|
|
85
|
+
readonly sessionId?: string;
|
|
86
|
+
readonly actor: { readonly agentId: string | null; readonly name?: string | null };
|
|
87
|
+
readonly state: ActivityState;
|
|
88
|
+
readonly tool?: string;
|
|
89
|
+
readonly ttlMs: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface RealtimeData {
|
|
93
|
+
conversation: {
|
|
94
|
+
readonly conversation: RealtimeConversationRow;
|
|
95
|
+
readonly thread: RealtimeThreadTotal;
|
|
96
|
+
/** Messages the conversation gained, as `GET /conversations/:id` returns them. */
|
|
97
|
+
readonly appended?: Message[];
|
|
98
|
+
/** The thread was rewritten: read it again. */
|
|
99
|
+
readonly reload?: true;
|
|
100
|
+
};
|
|
101
|
+
'conversation.deleted': {
|
|
102
|
+
readonly conversationId: string;
|
|
103
|
+
readonly thread?: RealtimeThreadTotal;
|
|
104
|
+
};
|
|
105
|
+
'message.reaction': {
|
|
106
|
+
readonly conversationId: string;
|
|
107
|
+
readonly messageId: string;
|
|
108
|
+
readonly reactions: readonly string[];
|
|
109
|
+
readonly revision: number;
|
|
110
|
+
readonly mutationId: string;
|
|
111
|
+
};
|
|
112
|
+
gemies: { readonly agentId: string | null; readonly change: 'created' | 'updated' | 'deleted' };
|
|
113
|
+
credits: { readonly credits?: number };
|
|
114
|
+
notification: { readonly notification: Record<string, unknown> & { readonly id: string } };
|
|
115
|
+
connections: Record<string, never>;
|
|
116
|
+
activity: RealtimeActivity;
|
|
117
|
+
room: {
|
|
118
|
+
readonly conversationId: string;
|
|
119
|
+
readonly chainId: string;
|
|
120
|
+
readonly event: string;
|
|
121
|
+
readonly data: unknown;
|
|
122
|
+
};
|
|
123
|
+
presence: { readonly agentId: string; readonly online: boolean };
|
|
124
|
+
runtimes: Record<string, never>;
|
|
125
|
+
'show.progress': Record<string, unknown> & { readonly episodeId: string };
|
|
126
|
+
'agent.activity': Record<string, unknown> & {
|
|
127
|
+
readonly sessionId: string;
|
|
128
|
+
readonly agentId: string;
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const TYPES: ReadonlySet<string> = new Set<string>([
|
|
133
|
+
...REALTIME_DURABLE_TYPES,
|
|
134
|
+
...REALTIME_SIGNAL_TYPES,
|
|
135
|
+
]);
|
|
136
|
+
|
|
137
|
+
/** A frame this client understands, or `null`: an unknown type from a newer server is skipped. */
|
|
138
|
+
export function readFrame(value: unknown): RealtimeFrame | null {
|
|
139
|
+
if (typeof value !== 'object' || value === null) return null;
|
|
140
|
+
const frame = value as Partial<RealtimeFrame>;
|
|
141
|
+
if (frame.v !== 1 || typeof frame.type !== 'string' || !TYPES.has(frame.type)) return null;
|
|
142
|
+
if (
|
|
143
|
+
frame.seq !== undefined &&
|
|
144
|
+
(typeof frame.seq !== 'number' || !Number.isSafeInteger(frame.seq))
|
|
145
|
+
)
|
|
146
|
+
return null;
|
|
147
|
+
return frame as RealtimeFrame;
|
|
148
|
+
}
|