@gemies/sdk 5.0.0 → 6.1.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 +34 -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/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/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 +252 -0
- package/src/realtime/connection.ts +317 -0
- package/src/realtime/contract.ts +169 -0
- package/src/realtime/index.ts +33 -0
- package/src/realtime/react.tsx +196 -0
- package/src/runtime/collections-model.ts +66 -0
- package/src/runtime/collections.ts +185 -0
- package/src/runtime/config.tsx +8 -26
- package/src/runtime/conversations.ts +55 -3
- package/src/runtime/index.ts +21 -0
- package/src/runtime/query-keys.ts +2 -0
- package/src/runtime/routes.ts +13 -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,169 @@
|
|
|
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
|
+
'collections',
|
|
30
|
+
] as const;
|
|
31
|
+
|
|
32
|
+
/** Signals: only true while they happen, never replayed. */
|
|
33
|
+
export const REALTIME_SIGNAL_TYPES = [
|
|
34
|
+
'activity',
|
|
35
|
+
'room',
|
|
36
|
+
'presence',
|
|
37
|
+
'runtimes',
|
|
38
|
+
'show.progress',
|
|
39
|
+
'agent.activity',
|
|
40
|
+
] as const;
|
|
41
|
+
|
|
42
|
+
export type RealtimeDurableType = (typeof REALTIME_DURABLE_TYPES)[number];
|
|
43
|
+
export type RealtimeSignalType = (typeof REALTIME_SIGNAL_TYPES)[number];
|
|
44
|
+
export type RealtimeType = RealtimeDurableType | RealtimeSignalType;
|
|
45
|
+
|
|
46
|
+
export interface RealtimeFrame<T extends RealtimeType = RealtimeType> {
|
|
47
|
+
readonly v: 1;
|
|
48
|
+
readonly type: T;
|
|
49
|
+
readonly data: RealtimeData[T];
|
|
50
|
+
readonly seq?: number;
|
|
51
|
+
readonly topic?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface RealtimeSyncReply {
|
|
55
|
+
readonly head: number;
|
|
56
|
+
readonly events?: readonly RealtimeFrame[];
|
|
57
|
+
readonly reset?: true;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A conversation as a list shows it (the API's `ConversationSummary`), dates as ISO strings. */
|
|
61
|
+
export interface RealtimeConversationRow {
|
|
62
|
+
readonly id: string;
|
|
63
|
+
readonly title: string;
|
|
64
|
+
readonly lastMessage: string | null;
|
|
65
|
+
readonly source: string;
|
|
66
|
+
readonly agentId: string | null;
|
|
67
|
+
readonly threadId: string | null;
|
|
68
|
+
readonly memberAgentIds: string[];
|
|
69
|
+
readonly spaceId: string | null;
|
|
70
|
+
readonly app: string | null;
|
|
71
|
+
readonly unreadCount: number;
|
|
72
|
+
readonly createdAt: string;
|
|
73
|
+
readonly updatedAt: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A gemie's whole thread with the person (many conversations): its sidebar row's badge. */
|
|
77
|
+
export interface RealtimeThreadTotal {
|
|
78
|
+
readonly agentId: string | null;
|
|
79
|
+
readonly unreadCount: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type ActivityState = 'thinking' | 'writing' | 'tool' | 'idle';
|
|
83
|
+
|
|
84
|
+
export interface RealtimeActivity {
|
|
85
|
+
readonly conversationId: string | null;
|
|
86
|
+
readonly sessionId?: string;
|
|
87
|
+
readonly actor: { readonly agentId: string | null; readonly name?: string | null };
|
|
88
|
+
readonly state: ActivityState;
|
|
89
|
+
readonly tool?: string;
|
|
90
|
+
readonly ttlMs: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A person's folders, projects, pins and favourites, as the API answers and publishes them. */
|
|
94
|
+
export interface CollectionsSnapshotWire {
|
|
95
|
+
readonly collections: ReadonlyArray<{
|
|
96
|
+
readonly id: string;
|
|
97
|
+
readonly kind: 'folder' | 'project';
|
|
98
|
+
readonly name: string;
|
|
99
|
+
readonly description: string | null;
|
|
100
|
+
readonly icon: string | null;
|
|
101
|
+
readonly color: string | null;
|
|
102
|
+
readonly isFavorite: boolean;
|
|
103
|
+
readonly isExpanded: boolean;
|
|
104
|
+
readonly conversationIds: string[];
|
|
105
|
+
readonly createdAt: string;
|
|
106
|
+
readonly updatedAt: string;
|
|
107
|
+
}>;
|
|
108
|
+
readonly pinned: string[];
|
|
109
|
+
readonly favorites: string[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface RealtimeData {
|
|
113
|
+
conversation: {
|
|
114
|
+
readonly conversation: RealtimeConversationRow;
|
|
115
|
+
readonly thread: RealtimeThreadTotal;
|
|
116
|
+
/** Messages the conversation gained, as `GET /conversations/:id` returns them. */
|
|
117
|
+
readonly appended?: Message[];
|
|
118
|
+
/** The thread was rewritten: read it again. */
|
|
119
|
+
readonly reload?: true;
|
|
120
|
+
};
|
|
121
|
+
'conversation.deleted': {
|
|
122
|
+
readonly conversationId: string;
|
|
123
|
+
readonly thread?: RealtimeThreadTotal;
|
|
124
|
+
};
|
|
125
|
+
'message.reaction': {
|
|
126
|
+
readonly conversationId: string;
|
|
127
|
+
readonly messageId: string;
|
|
128
|
+
readonly reactions: readonly string[];
|
|
129
|
+
readonly revision: number;
|
|
130
|
+
readonly mutationId: string;
|
|
131
|
+
};
|
|
132
|
+
gemies: { readonly agentId: string | null; readonly change: 'created' | 'updated' | 'deleted' };
|
|
133
|
+
credits: { readonly credits?: number };
|
|
134
|
+
notification: { readonly notification: Record<string, unknown> & { readonly id: string } };
|
|
135
|
+
connections: Record<string, never>;
|
|
136
|
+
collections: CollectionsSnapshotWire;
|
|
137
|
+
activity: RealtimeActivity;
|
|
138
|
+
room: {
|
|
139
|
+
readonly conversationId: string;
|
|
140
|
+
readonly chainId: string;
|
|
141
|
+
readonly event: string;
|
|
142
|
+
readonly data: unknown;
|
|
143
|
+
};
|
|
144
|
+
presence: { readonly agentId: string; readonly online: boolean };
|
|
145
|
+
runtimes: Record<string, never>;
|
|
146
|
+
'show.progress': Record<string, unknown> & { readonly episodeId: string };
|
|
147
|
+
'agent.activity': Record<string, unknown> & {
|
|
148
|
+
readonly sessionId: string;
|
|
149
|
+
readonly agentId: string;
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const TYPES: ReadonlySet<string> = new Set<string>([
|
|
154
|
+
...REALTIME_DURABLE_TYPES,
|
|
155
|
+
...REALTIME_SIGNAL_TYPES,
|
|
156
|
+
]);
|
|
157
|
+
|
|
158
|
+
/** A frame this client understands, or `null`: an unknown type from a newer server is skipped. */
|
|
159
|
+
export function readFrame(value: unknown): RealtimeFrame | null {
|
|
160
|
+
if (typeof value !== 'object' || value === null) return null;
|
|
161
|
+
const frame = value as Partial<RealtimeFrame>;
|
|
162
|
+
if (frame.v !== 1 || typeof frame.type !== 'string' || !TYPES.has(frame.type)) return null;
|
|
163
|
+
if (
|
|
164
|
+
frame.seq !== undefined &&
|
|
165
|
+
(typeof frame.seq !== 'number' || !Number.isSafeInteger(frame.seq))
|
|
166
|
+
)
|
|
167
|
+
return null;
|
|
168
|
+
return frame as RealtimeFrame;
|
|
169
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Realtime: the one socket a signed-in client holds to Gemies (`docs/realtime.mdx`). Mounted by
|
|
3
|
+
* `GemieRuntimeProvider`; a host listens with the hooks below for what is its own (credits, its
|
|
4
|
+
* lists, notifications), while the runtime's conversations, reactions, rooms and "typing…" are
|
|
5
|
+
* kept live by the SDK itself.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
GemieRealtimeProvider,
|
|
10
|
+
useGemieRealtime,
|
|
11
|
+
useRealtimeEvent,
|
|
12
|
+
useRealtimeReset,
|
|
13
|
+
useRealtimeTopic,
|
|
14
|
+
} from './react';
|
|
15
|
+
export {
|
|
16
|
+
useConversationActivity,
|
|
17
|
+
useRealtimeActivityStore,
|
|
18
|
+
type ActorActivityEntry,
|
|
19
|
+
} from './activity';
|
|
20
|
+
export type { RealtimeConnection, RealtimeListener } from './connection';
|
|
21
|
+
export {
|
|
22
|
+
REALTIME_DURABLE_TYPES,
|
|
23
|
+
REALTIME_SIGNAL_TYPES,
|
|
24
|
+
type ActivityState,
|
|
25
|
+
type RealtimeActivity,
|
|
26
|
+
type RealtimeConversationRow,
|
|
27
|
+
type RealtimeData,
|
|
28
|
+
type RealtimeDurableType,
|
|
29
|
+
type RealtimeFrame,
|
|
30
|
+
type RealtimeSignalType,
|
|
31
|
+
type RealtimeThreadTotal,
|
|
32
|
+
type RealtimeType,
|
|
33
|
+
} from './contract';
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The realtime connection in React (`docs/realtime.mdx`).
|
|
3
|
+
*
|
|
4
|
+
* {@link GemieRealtimeProvider} is mounted by `GemieRuntimeProvider`: it holds the signed-in
|
|
5
|
+
* account's connection to the runtime's API and keeps the runtime's caches and the activity store
|
|
6
|
+
* in step with it. Everything else only listens: {@link useRealtimeEvent} for a type,
|
|
7
|
+
* {@link useRealtimeTopic} for an agent run, {@link useConversationActivity} for "typing…".
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { QueryClientContext } from '@tanstack/react-query';
|
|
11
|
+
import { useOxy } from '@oxy.so/services/ui/client';
|
|
12
|
+
import {
|
|
13
|
+
createContext,
|
|
14
|
+
type ReactNode,
|
|
15
|
+
useContext,
|
|
16
|
+
useEffect,
|
|
17
|
+
useMemo,
|
|
18
|
+
useRef,
|
|
19
|
+
useState,
|
|
20
|
+
} from 'react';
|
|
21
|
+
import { useRealtimeActivityStore } from './activity';
|
|
22
|
+
import { attachRealtimeCache } from './cache';
|
|
23
|
+
import { acquireRealtime, type RealtimeConnection, type RealtimeListener } from './connection';
|
|
24
|
+
import type { RealtimeActivity, RealtimeFrame, RealtimeType } from './contract';
|
|
25
|
+
|
|
26
|
+
interface RealtimeHold {
|
|
27
|
+
readonly apiUrl: string;
|
|
28
|
+
readonly connection: RealtimeConnection | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const RealtimeContext = createContext<RealtimeHold | null>(null);
|
|
32
|
+
|
|
33
|
+
/** Hold the signed-in account's connection to `apiUrl`; `null` while signed out. */
|
|
34
|
+
function useHeldConnection(apiUrl: string, enabled: boolean): RealtimeConnection | null {
|
|
35
|
+
const { oxyServices, user, canUsePrivateApi } = useOxy();
|
|
36
|
+
const account = enabled && canUsePrivateApi ? (user?.id ?? null) : null;
|
|
37
|
+
const [connection, setConnection] = useState<RealtimeConnection | null>(null);
|
|
38
|
+
// The connection is the account's: a new services object for the same account does not open
|
|
39
|
+
// another one (read when the connection is opened).
|
|
40
|
+
const servicesRef = useRef(oxyServices);
|
|
41
|
+
servicesRef.current = oxyServices;
|
|
42
|
+
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
if (!account) {
|
|
45
|
+
setConnection(null);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
// The API's own token, refreshed by Oxy when it is due — never a captured one.
|
|
49
|
+
const linked = servicesRef.current.createLinkedClient({ baseURL: apiUrl });
|
|
50
|
+
const held = acquireRealtime(apiUrl, account, () => linked.getAccessToken(apiUrl));
|
|
51
|
+
setConnection(held.connection);
|
|
52
|
+
return () => {
|
|
53
|
+
held.release();
|
|
54
|
+
linked.dispose();
|
|
55
|
+
setConnection(null);
|
|
56
|
+
};
|
|
57
|
+
}, [apiUrl, account]);
|
|
58
|
+
|
|
59
|
+
return connection;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const activityHolders = new WeakMap<RealtimeConnection, { refs: number; detach: () => void }>();
|
|
63
|
+
|
|
64
|
+
/** Feed a connection's `activity` frames into the store, once per connection. */
|
|
65
|
+
function attachActivity(connection: RealtimeConnection): () => void {
|
|
66
|
+
const existing = activityHolders.get(connection);
|
|
67
|
+
if (existing) existing.refs++;
|
|
68
|
+
else {
|
|
69
|
+
const store = useRealtimeActivityStore.getState;
|
|
70
|
+
const offFrames = connection.on('activity', (frame) =>
|
|
71
|
+
store().apply(frame.data as RealtimeActivity),
|
|
72
|
+
);
|
|
73
|
+
// What happened while away is unknown: a stale "typing…" is worse than none.
|
|
74
|
+
const offStatus = connection.onStatus((connected) => {
|
|
75
|
+
if (!connected) store().clear();
|
|
76
|
+
});
|
|
77
|
+
activityHolders.set(connection, {
|
|
78
|
+
refs: 1,
|
|
79
|
+
detach: () => {
|
|
80
|
+
offFrames();
|
|
81
|
+
offStatus();
|
|
82
|
+
store().clear();
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
let released = false;
|
|
87
|
+
return () => {
|
|
88
|
+
if (released) return;
|
|
89
|
+
released = true;
|
|
90
|
+
const entry = activityHolders.get(connection);
|
|
91
|
+
if (!entry || --entry.refs > 0) return;
|
|
92
|
+
entry.detach();
|
|
93
|
+
activityHolders.delete(connection);
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Mounted by `GemieRuntimeProvider`: the account's connection for everything below, wired into the
|
|
99
|
+
* runtime's caches and the activity store. A nested provider on the same API shares its parent's.
|
|
100
|
+
*/
|
|
101
|
+
export function GemieRealtimeProvider({
|
|
102
|
+
apiUrl,
|
|
103
|
+
children,
|
|
104
|
+
}: {
|
|
105
|
+
apiUrl: string;
|
|
106
|
+
children: ReactNode;
|
|
107
|
+
}) {
|
|
108
|
+
const parent = useContext(RealtimeContext);
|
|
109
|
+
const inherited = parent !== null && parent.apiUrl === apiUrl;
|
|
110
|
+
const connection = useHeldConnection(apiUrl, !inherited);
|
|
111
|
+
// A host without React Query has no runtime caches to keep; it still hears activity.
|
|
112
|
+
const queryClient = useContext(QueryClientContext);
|
|
113
|
+
useEffect(() => {
|
|
114
|
+
if (inherited || !connection) return;
|
|
115
|
+
const detachCache = queryClient ? attachRealtimeCache(connection, queryClient) : undefined;
|
|
116
|
+
const detachActivity = attachActivity(connection);
|
|
117
|
+
return () => {
|
|
118
|
+
detachCache?.();
|
|
119
|
+
detachActivity();
|
|
120
|
+
};
|
|
121
|
+
}, [inherited, connection, queryClient]);
|
|
122
|
+
const value = useMemo<RealtimeHold>(
|
|
123
|
+
() => (inherited && parent ? parent : { apiUrl, connection }),
|
|
124
|
+
[inherited, parent, apiUrl, connection],
|
|
125
|
+
);
|
|
126
|
+
return <RealtimeContext.Provider value={value}>{children}</RealtimeContext.Provider>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The account's realtime connection, or `null` while signed out or outside a runtime provider. */
|
|
130
|
+
export function useGemieRealtime(): RealtimeConnection | null {
|
|
131
|
+
return useContext(RealtimeContext)?.connection ?? null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Call `handler` for every frame of `type` while mounted (the latest `handler`, without resubscribing). */
|
|
135
|
+
export function useRealtimeEvent<T extends RealtimeType | '*'>(
|
|
136
|
+
type: T,
|
|
137
|
+
handler: (frame: RealtimeFrame) => void,
|
|
138
|
+
): void {
|
|
139
|
+
const connection = useGemieRealtime();
|
|
140
|
+
const ref = useRef(handler);
|
|
141
|
+
ref.current = handler;
|
|
142
|
+
useEffect(() => {
|
|
143
|
+
if (!connection) return;
|
|
144
|
+
const listener: RealtimeListener = (frame) => ref.current(frame);
|
|
145
|
+
return connection.on(type, listener);
|
|
146
|
+
}, [connection, type]);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Call `handler` when the client must reload what it shows (its cursor fell out of the log). */
|
|
150
|
+
export function useRealtimeReset(handler: () => void): void {
|
|
151
|
+
const connection = useGemieRealtime();
|
|
152
|
+
const ref = useRef(handler);
|
|
153
|
+
ref.current = handler;
|
|
154
|
+
useEffect(() => {
|
|
155
|
+
if (!connection) return;
|
|
156
|
+
return connection.onReset(() => ref.current());
|
|
157
|
+
}, [connection]);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Follow a topic (`agent:<id>`, `agent-session:<id>`) while mounted, and hear its frames. The
|
|
162
|
+
* server checks the person may; a refused topic simply never speaks.
|
|
163
|
+
*/
|
|
164
|
+
export function useRealtimeTopic(
|
|
165
|
+
topic: string | null,
|
|
166
|
+
handler: (frame: RealtimeFrame) => void,
|
|
167
|
+
): void {
|
|
168
|
+
const connection = useGemieRealtime();
|
|
169
|
+
const ref = useRef(handler);
|
|
170
|
+
ref.current = handler;
|
|
171
|
+
useEffect(() => {
|
|
172
|
+
if (!connection || !topic) return;
|
|
173
|
+
const release = connection.follow(topic);
|
|
174
|
+
const off = connection.on('agent.activity', (frame) => {
|
|
175
|
+
if (frame.topic === topic) ref.current(frame);
|
|
176
|
+
});
|
|
177
|
+
return () => {
|
|
178
|
+
off();
|
|
179
|
+
release();
|
|
180
|
+
};
|
|
181
|
+
}, [connection, topic]);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Hear the account's `activity` where no runtime provider holds the connection — an "Ask Alia"
|
|
186
|
+
* button an app draws on its own (`useGemieActivity`). Inside a provider it does nothing: the
|
|
187
|
+
* provider already feeds the store.
|
|
188
|
+
*/
|
|
189
|
+
export function useRealtimeActivityFeed(apiUrl: string): void {
|
|
190
|
+
const inherited = useContext(RealtimeContext) !== null;
|
|
191
|
+
const connection = useHeldConnection(apiUrl, !inherited);
|
|
192
|
+
useEffect(() => {
|
|
193
|
+
if (!connection) return;
|
|
194
|
+
return attachActivity(connection);
|
|
195
|
+
}, [connection]);
|
|
196
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The data of a person's collections, without React (`runtime/collections.ts` has the hooks), so the
|
|
3
|
+
* realtime cache can read a `collections` frame without loading the UI client.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { CollectionsSnapshotWire } from '../realtime/contract';
|
|
7
|
+
|
|
8
|
+
export type ConversationCollectionKind = 'folder' | 'project';
|
|
9
|
+
|
|
10
|
+
export interface ConversationCollection {
|
|
11
|
+
id: string;
|
|
12
|
+
kind: ConversationCollectionKind;
|
|
13
|
+
name: string;
|
|
14
|
+
description: string | null;
|
|
15
|
+
icon: string | null;
|
|
16
|
+
color: string | null;
|
|
17
|
+
isFavorite: boolean;
|
|
18
|
+
isExpanded: boolean;
|
|
19
|
+
conversationIds: string[];
|
|
20
|
+
/** ISO 8601: the snapshot is persisted as JSON by hosts that keep their cache. */
|
|
21
|
+
createdAt: string;
|
|
22
|
+
updatedAt: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ConversationCollections {
|
|
26
|
+
collections: ConversationCollection[];
|
|
27
|
+
/** Pinned conversations, oldest pin first. */
|
|
28
|
+
pinned: string[];
|
|
29
|
+
favorites: string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What a collection may be created or edited with. */
|
|
33
|
+
export interface CollectionFields {
|
|
34
|
+
name?: string;
|
|
35
|
+
description?: string | null;
|
|
36
|
+
icon?: string | null;
|
|
37
|
+
color?: string | null;
|
|
38
|
+
isFavorite?: boolean;
|
|
39
|
+
isExpanded?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What a device filed before collections were the account's (`importCollections`). */
|
|
43
|
+
export interface LocalCollections {
|
|
44
|
+
pinned: string[];
|
|
45
|
+
favorites: string[];
|
|
46
|
+
folders: Array<CollectionFields & { name: string; conversationIds: string[] }>;
|
|
47
|
+
projects: Array<CollectionFields & { name: string; conversationIds: string[] }>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const EMPTY_COLLECTIONS: ConversationCollections = {
|
|
51
|
+
collections: [],
|
|
52
|
+
pinned: [],
|
|
53
|
+
favorites: [],
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** The wire snapshot as the runtime keeps it (a copy: the cache never shares a frame's arrays). */
|
|
57
|
+
export function readCollectionsSnapshot(wire: CollectionsSnapshotWire): ConversationCollections {
|
|
58
|
+
return {
|
|
59
|
+
collections: wire.collections.map((c) => ({
|
|
60
|
+
...c,
|
|
61
|
+
conversationIds: [...c.conversationIds],
|
|
62
|
+
})),
|
|
63
|
+
pinned: [...wire.pinned],
|
|
64
|
+
favorites: [...wire.favorites],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a person files their conversations — folders, projects, pins, favourites — on their account,
|
|
3
|
+
* so every device shows the same (Gemies `docs/realtime.mdx`, "Collections").
|
|
4
|
+
*
|
|
5
|
+
* One query holds the whole snapshot (`GET /v1/conversations/collections`). Every change is drawn
|
|
6
|
+
* at once (optimistic), sent, and replaced by the snapshot the server answers; the other devices
|
|
7
|
+
* receive the same snapshot as the realtime `collections` event. Nothing is stored on the device.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
11
|
+
import { useOxy } from '@oxy.so/services/ui/client';
|
|
12
|
+
import { useCallback, useMemo } from 'react';
|
|
13
|
+
import type { CollectionsSnapshotWire } from '../realtime/contract';
|
|
14
|
+
import {
|
|
15
|
+
type CollectionFields,
|
|
16
|
+
type ConversationCollection,
|
|
17
|
+
type ConversationCollectionKind,
|
|
18
|
+
type ConversationCollections,
|
|
19
|
+
EMPTY_COLLECTIONS,
|
|
20
|
+
type LocalCollections,
|
|
21
|
+
readCollectionsSnapshot,
|
|
22
|
+
} from './collections-model';
|
|
23
|
+
|
|
24
|
+
export type {
|
|
25
|
+
CollectionFields,
|
|
26
|
+
ConversationCollection,
|
|
27
|
+
ConversationCollectionKind,
|
|
28
|
+
ConversationCollections,
|
|
29
|
+
LocalCollections,
|
|
30
|
+
} from './collections-model';
|
|
31
|
+
export { readCollectionsSnapshot } from './collections-model';
|
|
32
|
+
import { type GemieApi, useGemieApi } from './api';
|
|
33
|
+
import { gemieQueryKeys } from './query-keys';
|
|
34
|
+
import { API_ROUTES } from './routes';
|
|
35
|
+
|
|
36
|
+
/** The person's folders, projects, pins and favourites. Kept current by the realtime connection. */
|
|
37
|
+
export function useConversationCollections(): ConversationCollections {
|
|
38
|
+
const api = useGemieApi();
|
|
39
|
+
const { canUsePrivateApi, isAccountCacheReady } = useOxy();
|
|
40
|
+
const query = useQuery({
|
|
41
|
+
queryKey: gemieQueryKeys.collections,
|
|
42
|
+
queryFn: async () =>
|
|
43
|
+
readCollectionsSnapshot(
|
|
44
|
+
(await api.get<CollectionsSnapshotWire>(API_ROUTES.collections.list)).data,
|
|
45
|
+
),
|
|
46
|
+
enabled: canUsePrivateApi && isAccountCacheReady,
|
|
47
|
+
// No timer and no refocus: the `collections` event keeps it, and a reset reads it again.
|
|
48
|
+
staleTime: Number.POSITIVE_INFINITY,
|
|
49
|
+
refetchOnWindowFocus: false,
|
|
50
|
+
});
|
|
51
|
+
return query.data ?? EMPTY_COLLECTIONS;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Bring what this device filed before collections were the account's into the account (the
|
|
56
|
+
* server merges by name, so every device may bring its own). Resolves with the account's snapshot.
|
|
57
|
+
*/
|
|
58
|
+
export async function importCollections(
|
|
59
|
+
api: GemieApi,
|
|
60
|
+
local: LocalCollections,
|
|
61
|
+
): Promise<ConversationCollections> {
|
|
62
|
+
const { data } = await api.post<CollectionsSnapshotWire>(API_ROUTES.collections.import, local);
|
|
63
|
+
return readCollectionsSnapshot(data);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface CollectionActions {
|
|
67
|
+
createCollection(
|
|
68
|
+
kind: ConversationCollectionKind,
|
|
69
|
+
fields: CollectionFields & { name: string },
|
|
70
|
+
): Promise<void>;
|
|
71
|
+
updateCollection(id: string, fields: CollectionFields): Promise<void>;
|
|
72
|
+
deleteCollection(id: string): Promise<void>;
|
|
73
|
+
addToCollection(id: string, conversationId: string): Promise<void>;
|
|
74
|
+
removeFromCollection(id: string, conversationId: string): Promise<void>;
|
|
75
|
+
setPinned(conversationId: string, pinned: boolean): Promise<void>;
|
|
76
|
+
setFavorite(conversationId: string, favorite: boolean): Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Change how the person files their conversations. Each change is drawn at once and then replaced
|
|
81
|
+
* by what the server answers; a refused change puts the server's state back.
|
|
82
|
+
*/
|
|
83
|
+
export function useCollectionActions(): CollectionActions {
|
|
84
|
+
const api = useGemieApi();
|
|
85
|
+
const queryClient = useQueryClient();
|
|
86
|
+
|
|
87
|
+
const run = useCallback(
|
|
88
|
+
async (
|
|
89
|
+
draw: (current: ConversationCollections) => ConversationCollections,
|
|
90
|
+
send: () => Promise<{ data: CollectionsSnapshotWire }>,
|
|
91
|
+
) => {
|
|
92
|
+
await queryClient.cancelQueries({ queryKey: gemieQueryKeys.collections });
|
|
93
|
+
queryClient.setQueryData<ConversationCollections>(gemieQueryKeys.collections, (current) =>
|
|
94
|
+
draw(current ?? EMPTY_COLLECTIONS),
|
|
95
|
+
);
|
|
96
|
+
try {
|
|
97
|
+
const { data } = await send();
|
|
98
|
+
queryClient.setQueryData(gemieQueryKeys.collections, readCollectionsSnapshot(data));
|
|
99
|
+
} catch (error) {
|
|
100
|
+
void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.collections });
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
[queryClient],
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
return useMemo<CollectionActions>(() => {
|
|
108
|
+
const R = API_ROUTES.collections;
|
|
109
|
+
const edit =
|
|
110
|
+
(id: string, change: (c: ConversationCollection) => ConversationCollection) =>
|
|
111
|
+
(current: ConversationCollections) => ({
|
|
112
|
+
...current,
|
|
113
|
+
collections: current.collections.map((c) => (c.id === id ? change(c) : c)),
|
|
114
|
+
});
|
|
115
|
+
const toggle = (list: string[], id: string, on: boolean) =>
|
|
116
|
+
on ? (list.includes(id) ? list : [...list, id]) : list.filter((x) => x !== id);
|
|
117
|
+
return {
|
|
118
|
+
createCollection: (kind, fields) =>
|
|
119
|
+
run(
|
|
120
|
+
(current) => ({
|
|
121
|
+
...current,
|
|
122
|
+
collections: [
|
|
123
|
+
...current.collections,
|
|
124
|
+
{
|
|
125
|
+
id: `pending-${Date.now()}`,
|
|
126
|
+
kind,
|
|
127
|
+
name: fields.name,
|
|
128
|
+
description: fields.description ?? null,
|
|
129
|
+
icon: fields.icon ?? null,
|
|
130
|
+
color: fields.color ?? null,
|
|
131
|
+
isFavorite: false,
|
|
132
|
+
isExpanded: true,
|
|
133
|
+
conversationIds: [],
|
|
134
|
+
createdAt: new Date().toISOString(),
|
|
135
|
+
updatedAt: new Date().toISOString(),
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
}),
|
|
139
|
+
() => api.post(R.create, { kind, ...fields }),
|
|
140
|
+
),
|
|
141
|
+
updateCollection: (id, fields) =>
|
|
142
|
+
run(
|
|
143
|
+
edit(id, (c) => ({ ...c, ...fields, name: fields.name ?? c.name })),
|
|
144
|
+
() => api.patch(R.one(id), fields),
|
|
145
|
+
),
|
|
146
|
+
deleteCollection: (id) =>
|
|
147
|
+
run(
|
|
148
|
+
(current) => ({
|
|
149
|
+
...current,
|
|
150
|
+
collections: current.collections.filter((c) => c.id !== id),
|
|
151
|
+
}),
|
|
152
|
+
() => api.delete(R.one(id)),
|
|
153
|
+
),
|
|
154
|
+
addToCollection: (id, conversationId) =>
|
|
155
|
+
run(
|
|
156
|
+
edit(id, (c) => ({
|
|
157
|
+
...c,
|
|
158
|
+
conversationIds: toggle(c.conversationIds, conversationId, true),
|
|
159
|
+
})),
|
|
160
|
+
() => api.put(R.member(id, conversationId)),
|
|
161
|
+
),
|
|
162
|
+
removeFromCollection: (id, conversationId) =>
|
|
163
|
+
run(
|
|
164
|
+
edit(id, (c) => ({
|
|
165
|
+
...c,
|
|
166
|
+
conversationIds: toggle(c.conversationIds, conversationId, false),
|
|
167
|
+
})),
|
|
168
|
+
() => api.delete(R.member(id, conversationId)),
|
|
169
|
+
),
|
|
170
|
+
setPinned: (conversationId, pinned) =>
|
|
171
|
+
run(
|
|
172
|
+
(current) => ({ ...current, pinned: toggle(current.pinned, conversationId, pinned) }),
|
|
173
|
+
() => api.patch(API_ROUTES.conversations.marks(conversationId), { pinned }),
|
|
174
|
+
),
|
|
175
|
+
setFavorite: (conversationId, favorite) =>
|
|
176
|
+
run(
|
|
177
|
+
(current) => ({
|
|
178
|
+
...current,
|
|
179
|
+
favorites: toggle(current.favorites, conversationId, favorite),
|
|
180
|
+
}),
|
|
181
|
+
() => api.patch(API_ROUTES.conversations.marks(conversationId), { favorite }),
|
|
182
|
+
),
|
|
183
|
+
};
|
|
184
|
+
}, [api, run]);
|
|
185
|
+
}
|