@gemies/sdk 9.2.0 → 10.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 +103 -0
- package/README.md +9 -6
- package/package.json +4 -11
- package/src/accounts.ts +7 -1
- package/src/ask-eager.ts +0 -2
- package/src/ask-text.ts +0 -1
- package/src/ask.ts +0 -1
- package/src/components/AmbientField.tsx +13 -2
- package/src/components/ComposerDropZone.tsx +20 -4
- package/src/components/ComposerSuggestions.tsx +9 -2
- package/src/components/GemieActivityLine.tsx +11 -5
- package/src/components/GemieBetweenGemies.tsx +23 -10
- package/src/components/GemieChatContent.tsx +46 -23
- package/src/components/GemieChatScreen.tsx +7 -4
- package/src/components/GemieChatSheet.tsx +6 -2
- package/src/components/GemieComposer.tsx +17 -7
- package/src/components/GemieGroupWelcome.tsx +16 -2
- package/src/components/GemieRecentConversations.tsx +13 -10
- package/src/components/GemieSharedConversation.tsx +38 -6
- package/src/components/GemieWelcomeMessage.tsx +23 -7
- package/src/components/IdentityMark.tsx +6 -12
- package/src/components/PlanPreviewCard.tsx +18 -7
- package/src/components/QuestionCard.tsx +6 -2
- package/src/components/ReplyMarkdown.tsx +32 -6
- package/src/components/RichBlocks.tsx +20 -15
- package/src/components/accounts/GemieAccountGrants.tsx +27 -10
- package/src/components/accounts/GemieConnectedAccounts.tsx +87 -51
- package/src/components/canvas/CanvasComponent.tsx +6 -2
- package/src/components/canvas/DashboardRenderer.tsx +25 -8
- package/src/components/canvas/DeckRenderer.tsx +23 -6
- package/src/components/canvas/FormRenderer.tsx +8 -3
- package/src/components/connectors/ConnectorLogo.tsx +15 -9
- package/src/components/connectors/GemieConnectedConnectors.tsx +51 -25
- package/src/components/connectors/GemieConnectorsStore.tsx +99 -41
- package/src/components/connectors/GrantSwitchRow.tsx +18 -5
- package/src/components/thought/ThoughtPanel.tsx +26 -12
- package/src/components/thought/ToolStep.tsx +14 -6
- package/src/components/thread/AgentResultCard.tsx +10 -4
- package/src/components/thread/AgentTaskCard.tsx +8 -3
- package/src/components/thread/ApprovalCard.tsx +6 -2
- package/src/components/thread/ChatBubble.tsx +66 -25
- package/src/components/thread/GemieThread.tsx +25 -8
- package/src/components/thread/ThreadRow.tsx +20 -15
- package/src/components/thread/ThreadSearch.tsx +27 -10
- package/src/components/thread/ThreadSkeleton.tsx +12 -6
- package/src/components/thread/ToolResultCard.tsx +10 -4
- package/src/components/thread/TurnAttachments.tsx +17 -8
- package/src/components/voice/VoiceControls.tsx +9 -6
- package/src/connectors.ts +15 -2
- package/src/hooks/useChatVoice.ts +2 -10
- package/src/hooks/useMessageReactions.ts +5 -5
- package/src/hooks/useThoughtScope.ts +9 -8
- package/src/index.ts +2 -3
- package/src/lib/tool-call-status.ts +1 -1
- package/src/lib/utils.ts +1 -8
- package/src/realtime/react.tsx +9 -9
- package/src/realtime/reread.ts +28 -0
- package/src/realtime/store.ts +123 -0
- package/src/runtime/agents.ts +46 -27
- package/src/runtime/collections.ts +35 -136
- package/src/runtime/connected-accounts.ts +175 -88
- package/src/runtime/connectors.ts +244 -127
- package/src/runtime/conversations.ts +181 -607
- package/src/runtime/data/answer.ts +76 -0
- package/src/runtime/data/collections.ts +168 -0
- package/src/runtime/data/conversations.ts +626 -0
- package/src/runtime/data/reactions.ts +29 -0
- package/src/runtime/data/read.ts +37 -0
- package/src/runtime/data/threads.ts +149 -0
- package/src/runtime/index.ts +72 -8
- package/src/runtime/model.ts +0 -2
- package/src/runtime/routes.ts +2 -2
- package/src/runtime/sharing.ts +69 -56
- package/src/runtime/types.ts +8 -16
- package/src/runtime/use-bound-action.ts +27 -0
- package/src/runtime/use-conversation-stream.ts +8 -31
- package/src/runtime/use-conversation-thread.ts +40 -51
- package/src/runtime/use-gemie-thread.ts +32 -43
- package/src/runtime/use-start-conversation.ts +14 -15
- package/src/runtime/use-thread-history.ts +26 -36
- package/src/runtime/use-thread-search.ts +29 -76
- package/src/text.ts +0 -1
- package/src/voice.ts +0 -1
- package/src/components/Image.tsx +0 -12
- package/src/realtime/cache.ts +0 -257
- package/src/runtime/conversation-dates.ts +0 -31
- package/src/runtime/query-keys.ts +0 -66
- package/src/runtime/reaction-cache.ts +0 -45
|
@@ -1,119 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation hooks: the person's conversations as their account's store holds them
|
|
3
|
+
* (`data/conversations.ts`), read and written in the store of the tree (`OxyProvider`'s, the
|
|
4
|
+
* signed-in account's).
|
|
5
|
+
*
|
|
6
|
+
* Reads wait for the private API (`canUsePrivateApi`): until then they observe nothing. Writes are
|
|
7
|
+
* the store's actions, each bound to the provider's client.
|
|
8
|
+
*/
|
|
1
9
|
import {
|
|
2
|
-
type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
10
|
+
type ActionView,
|
|
11
|
+
type ListView,
|
|
12
|
+
type RecordView,
|
|
13
|
+
skip,
|
|
14
|
+
useEntities,
|
|
15
|
+
useEntity,
|
|
16
|
+
useList,
|
|
17
|
+
useRecord,
|
|
18
|
+
useStore,
|
|
19
|
+
withStore,
|
|
20
|
+
} from '@oxy.so/bloom-data';
|
|
8
21
|
import { toast } from '@oxy.so/bloom/toast';
|
|
9
22
|
import { useOxy } from '@oxy.so/services/ui/client';
|
|
10
23
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
|
11
24
|
import { useLabels } from '../lib/labels';
|
|
12
|
-
import {
|
|
13
|
-
import
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// Message content is either a plain string or a parts array; previews (titles,
|
|
46
|
-
// lastMessage) need the flattened text either way.
|
|
47
|
-
function messageText(message: Message | undefined): string {
|
|
48
|
-
const content = message?.content;
|
|
49
|
-
if (typeof content === 'string') return content;
|
|
50
|
-
if (!content) return '';
|
|
51
|
-
return content
|
|
52
|
-
.map((part) => (typeof part.text === 'string' ? part.text : ''))
|
|
53
|
-
.join(' ')
|
|
54
|
-
.trim();
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* The offline copy of the conversations: what a session whose token failed
|
|
59
|
-
* (a 401) reads and writes instead of the server. Without a store configured
|
|
60
|
-
* it holds nothing, and the 401 is the caller's to handle.
|
|
61
|
-
*/
|
|
62
|
-
class OfflineConversations {
|
|
63
|
-
private readonly store: OfflineConversationStore | null;
|
|
64
|
-
|
|
65
|
-
constructor(store: OfflineConversationStore | null) {
|
|
66
|
-
this.store = store;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
get available(): boolean {
|
|
70
|
-
return this.store !== null;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
async read(): Promise<Conversation[]> {
|
|
74
|
-
const stored = await this.store?.getItem();
|
|
75
|
-
if (!stored) return [];
|
|
76
|
-
return (JSON.parse(stored) as Conversation[]).map((conv) => ({
|
|
77
|
-
...conv,
|
|
78
|
-
createdAt: new Date(conv.createdAt),
|
|
79
|
-
updatedAt: new Date(conv.updatedAt),
|
|
80
|
-
}));
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
async write(conversations: Conversation[]): Promise<void> {
|
|
84
|
-
await this.store?.setItem(JSON.stringify(conversations));
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
async remove(id: string): Promise<void> {
|
|
88
|
-
if (!this.store) return;
|
|
89
|
-
const stored = await this.store.getItem();
|
|
90
|
-
if (!stored) return;
|
|
91
|
-
try {
|
|
92
|
-
const conversations: Conversation[] = JSON.parse(stored);
|
|
93
|
-
const remaining = conversations.filter((conversation) => conversation.id !== id);
|
|
94
|
-
if (remaining.length !== conversations.length) {
|
|
95
|
-
await this.store.setItem(JSON.stringify(remaining));
|
|
96
|
-
}
|
|
97
|
-
} catch {
|
|
98
|
-
// A malformed offline cache cannot make a valid server response invalid.
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** What the conversation functions need: the API and the offline copy. */
|
|
104
|
-
export interface ConversationsClient {
|
|
105
|
-
api: GemieApi;
|
|
106
|
-
offline: OfflineConversations;
|
|
107
|
-
/** Read at call time: the title of a chat created while signed out. */
|
|
108
|
-
newChatTitle: string;
|
|
109
|
-
/** The chat's app, which labels a conversation it creates (`GemieRuntimeConfig.app`). */
|
|
110
|
-
app: string | undefined;
|
|
111
|
-
/** Told the account's realtime cursor each read carried, so no event is lost behind it. */
|
|
112
|
-
realtime: RealtimeConnection | null;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/** The runtime's conversation client for the nearest provider. */
|
|
116
|
-
function useConversationsClient(): ConversationsClient {
|
|
25
|
+
import { useGemieRealtime, useRealtimeEvent } from '../realtime/react';
|
|
26
|
+
import type { RealtimeData } from '../realtime/contract';
|
|
27
|
+
import { useGemieApi } from './api';
|
|
28
|
+
import { useGemieRuntime } from './config';
|
|
29
|
+
import {
|
|
30
|
+
type ConversationsClient,
|
|
31
|
+
type ConversationsFilter,
|
|
32
|
+
type CreateConversationInput,
|
|
33
|
+
type SaveConversationInput,
|
|
34
|
+
ConversationMessages,
|
|
35
|
+
Conversations,
|
|
36
|
+
clearConversation,
|
|
37
|
+
conversation,
|
|
38
|
+
conversationList,
|
|
39
|
+
conversationsKey,
|
|
40
|
+
createConversation,
|
|
41
|
+
deleteConversation,
|
|
42
|
+
heldConversation,
|
|
43
|
+
markConversationRead,
|
|
44
|
+
OfflineConversations,
|
|
45
|
+
refreshConversationLists,
|
|
46
|
+
renameConversation,
|
|
47
|
+
saveConversation,
|
|
48
|
+
} from './data/conversations';
|
|
49
|
+
import { errorMessage } from './error-utils';
|
|
50
|
+
import type { Conversation } from './types';
|
|
51
|
+
import { useBoundAction } from './use-bound-action';
|
|
52
|
+
|
|
53
|
+
/** The provider's conversation client: what every conversation read and write is given. */
|
|
54
|
+
export function useConversationsClient(): ConversationsClient {
|
|
117
55
|
const api = useGemieApi();
|
|
118
56
|
const { offline, app } = useGemieRuntime();
|
|
119
57
|
const { newChat } = useLabels();
|
|
@@ -130,566 +68,202 @@ function useConversationsClient(): ConversationsClient {
|
|
|
130
68
|
);
|
|
131
69
|
}
|
|
132
70
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
{ agentId, app, kind }: ConversationsFilter,
|
|
137
|
-
signal?: AbortSignal,
|
|
138
|
-
): Promise<ConversationsPage> {
|
|
139
|
-
const { data } = await client.api.get<{
|
|
140
|
-
conversations: ApiConversation[];
|
|
141
|
-
nextCursor: string | null;
|
|
142
|
-
hasMore: boolean;
|
|
143
|
-
realtimeSeq?: number;
|
|
144
|
-
}>(API_ROUTES.conversations.list, {
|
|
145
|
-
signal,
|
|
146
|
-
params: {
|
|
147
|
-
limit: PAGE_SIZE,
|
|
148
|
-
...(pageParam ? { cursor: pageParam } : {}),
|
|
149
|
-
...(agentId === undefined ? {} : { agentId }),
|
|
150
|
-
...(app === undefined ? {} : { app }),
|
|
151
|
-
...(kind === undefined ? {} : { kind }),
|
|
152
|
-
},
|
|
153
|
-
});
|
|
154
|
-
if (typeof data.realtimeSeq === 'number') client.realtime?.noteSnapshot(data.realtimeSeq);
|
|
155
|
-
return {
|
|
156
|
-
conversations: data.conversations.map((conv) => ({
|
|
157
|
-
...conv,
|
|
158
|
-
createdAt: new Date(conv.createdAt),
|
|
159
|
-
updatedAt: new Date(conv.updatedAt),
|
|
160
|
-
messages: [], // Don't include messages in list view
|
|
161
|
-
})),
|
|
162
|
-
nextCursor: data.nextCursor,
|
|
163
|
-
hasMore: data.hasMore,
|
|
164
|
-
};
|
|
71
|
+
/** A list of conversations as a screen reads it: the list's view and its rows, in order. */
|
|
72
|
+
export interface ConversationsView extends ListView<unknown> {
|
|
73
|
+
readonly conversations: readonly Conversation[];
|
|
165
74
|
}
|
|
166
75
|
|
|
167
76
|
/**
|
|
168
|
-
* The person's conversations, newest first, a page at a time. The sidebar and the
|
|
169
|
-
* Given `agentId`, only the conversations with that agent; given `app`, only the
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
* `
|
|
173
|
-
*
|
|
77
|
+
* The person's conversations, newest first, a page at a time (`more()`). The sidebar and the
|
|
78
|
+
* sheet read this. Given `agentId`, only the conversations with that agent; given `app`, only the
|
|
79
|
+
* ones started in that app (`GET /v1/conversations?agentId=&app=`); given `kind: 'gemies'`, the
|
|
80
|
+
* conversations the person's gemies have with each other (ADR 0042), each with both gemies in
|
|
81
|
+
* `members`. A realtime reset makes it stale: read again at once on screen, else when next shown.
|
|
82
|
+
*
|
|
83
|
+
* While the session is unavailable (a 401) the person's own list shows the offline copy, when the
|
|
84
|
+
* runtime has one; it is a display fallback, never a server answer.
|
|
174
85
|
*/
|
|
175
|
-
export function useConversations(
|
|
176
|
-
const { user, isAuthenticated, canUsePrivateApi
|
|
86
|
+
export function useConversations(filter: ConversationsFilter = {}): ConversationsView {
|
|
87
|
+
const { user, isAuthenticated, canUsePrivateApi } = useOxy();
|
|
177
88
|
const client = useConversationsClient();
|
|
178
|
-
const accountId = user?.id;
|
|
179
89
|
const { offline: offlineStore } = useGemieRuntime();
|
|
90
|
+
const { agentId, app, kind } = filter;
|
|
91
|
+
const key = conversationsKey(filter);
|
|
92
|
+
// biome-ignore lint/correctness/useExhaustiveDependencies: the key identifies the filter
|
|
93
|
+
const stableFilter = useMemo(() => ({ agentId, app, kind }), [key]);
|
|
94
|
+
const view = useList(conversationList, ...(canUsePrivateApi ? [client, stableFilter] : [skip]));
|
|
95
|
+
const rows = useEntities(Conversations, view.ids);
|
|
96
|
+
|
|
97
|
+
const accountId = user?.id;
|
|
180
98
|
const [offline, setOffline] = useState<{
|
|
181
99
|
accountId: string | undefined;
|
|
182
|
-
|
|
183
|
-
data: ConversationsInfiniteData;
|
|
100
|
+
rows: readonly Conversation[];
|
|
184
101
|
} | null>(null);
|
|
185
102
|
useEffect(() => {
|
|
186
|
-
if (
|
|
187
|
-
!isAuthenticated ||
|
|
188
|
-
!isAccountCacheReady ||
|
|
189
|
-
agentId !== undefined ||
|
|
190
|
-
app !== undefined ||
|
|
191
|
-
kind !== undefined
|
|
192
|
-
)
|
|
193
|
-
return;
|
|
103
|
+
if (!isAuthenticated || key !== 'all') return;
|
|
194
104
|
let current = true;
|
|
195
105
|
void new OfflineConversations(offlineStore ?? null)
|
|
196
106
|
.read()
|
|
197
|
-
.then((
|
|
198
|
-
if (current &&
|
|
199
|
-
setOffline({
|
|
200
|
-
|
|
201
|
-
store: offlineStore,
|
|
202
|
-
data: {
|
|
203
|
-
pages: [
|
|
204
|
-
{
|
|
205
|
-
conversations: rows.map((row) => ({ ...row, messages: [] })),
|
|
206
|
-
nextCursor: null,
|
|
207
|
-
hasMore: false,
|
|
208
|
-
},
|
|
209
|
-
],
|
|
210
|
-
pageParams: [undefined],
|
|
211
|
-
},
|
|
212
|
-
});
|
|
107
|
+
.then((stored) => {
|
|
108
|
+
if (current && stored.length) {
|
|
109
|
+
setOffline({ accountId, rows: stored.map(({ messages: _m, ...row }) => row) });
|
|
110
|
+
}
|
|
213
111
|
})
|
|
214
112
|
.catch(() => {
|
|
215
|
-
/* A damaged offline copy must not mask the server
|
|
113
|
+
/* A damaged offline copy must not mask the server's answer. */
|
|
216
114
|
});
|
|
217
115
|
return () => {
|
|
218
116
|
current = false;
|
|
219
117
|
};
|
|
220
|
-
}, [accountId, offlineStore, isAuthenticated,
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
fetchConversationsPage(client, pageParam, { agentId, app, kind }, signal),
|
|
229
|
-
initialPageParam: undefined as string | undefined,
|
|
230
|
-
getNextPageParam: (lastPage) => (lastPage.hasMore ? lastPage.nextCursor : undefined),
|
|
231
|
-
select: reviveConversationDates,
|
|
232
|
-
staleTime: FIVE_MINUTES,
|
|
233
|
-
retry: (count, error) => errorStatus(error) !== 401 && count < 2,
|
|
234
|
-
enabled: canUsePrivateApi && isAccountCacheReady,
|
|
235
|
-
});
|
|
236
|
-
// Offline content is a display fallback, never a fresh successful server answer.
|
|
237
|
-
const fallback =
|
|
238
|
-
isAuthenticated &&
|
|
239
|
-
isAccountCacheReady &&
|
|
240
|
-
agentId === undefined &&
|
|
241
|
-
app === undefined &&
|
|
242
|
-
kind === undefined &&
|
|
243
|
-
offline?.accountId === accountId &&
|
|
244
|
-
offline?.store === offlineStore
|
|
245
|
-
? offline.data
|
|
246
|
-
: undefined;
|
|
247
|
-
return { ...query, data: query.data ?? fallback };
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
async function fetchConversation(client: ConversationsClient, id: string): Promise<Conversation> {
|
|
251
|
-
try {
|
|
252
|
-
const { data } = await client.api.get<ApiConversation & { realtimeSeq?: number }>(
|
|
253
|
-
API_ROUTES.conversations.get(id),
|
|
254
|
-
);
|
|
255
|
-
if (typeof data.realtimeSeq === 'number') client.realtime?.noteSnapshot(data.realtimeSeq);
|
|
256
|
-
return {
|
|
257
|
-
...data,
|
|
258
|
-
createdAt: new Date(data.createdAt),
|
|
259
|
-
updatedAt: new Date(data.updatedAt),
|
|
260
|
-
messages: normalizeConversationMessages(data.messages || []),
|
|
261
|
-
};
|
|
262
|
-
} catch (error: unknown) {
|
|
263
|
-
const status = errorStatus(error);
|
|
264
|
-
// A server-side 404 is authoritative for an authenticated request. Keeping
|
|
265
|
-
// an older offline copy here resurrects a deleted conversation and makes
|
|
266
|
-
// every later read and write hit the same missing id again.
|
|
267
|
-
if (status === 404) {
|
|
268
|
-
await client.offline.remove(id);
|
|
269
|
-
throw new ConversationNotFoundError(id);
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
// An unavailable authenticated session can still read its offline copy.
|
|
273
|
-
if (status === 401) {
|
|
274
|
-
const conversation = (await client.offline.read()).find((c) => c.id === id);
|
|
275
|
-
if (conversation) {
|
|
276
|
-
return {
|
|
277
|
-
...conversation,
|
|
278
|
-
messages: normalizeConversationMessages(conversation.messages || []),
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
throw error;
|
|
283
|
-
}
|
|
118
|
+
}, [accountId, offlineStore, isAuthenticated, key]);
|
|
119
|
+
|
|
120
|
+
const conversations = useMemo(() => {
|
|
121
|
+
const held = rows.filter((row): row is Conversation => row !== undefined);
|
|
122
|
+
if (view.list || !isAuthenticated || offline?.accountId !== accountId) return held;
|
|
123
|
+
return offline?.rows ?? held;
|
|
124
|
+
}, [rows, view.list, isAuthenticated, offline, accountId]);
|
|
125
|
+
return { ...view, conversations };
|
|
284
126
|
}
|
|
285
127
|
|
|
286
|
-
/**
|
|
287
|
-
|
|
288
|
-
|
|
128
|
+
/**
|
|
129
|
+
* One conversation with its messages. A row the sidebar holds shows at once (without messages)
|
|
130
|
+
* while the conversation is read. A rewritten thread (a realtime `reload`, an edit or a
|
|
131
|
+
* regenerate on another device) is read again, and `onReload` hears it once it is read; a realtime
|
|
132
|
+
* reset makes it stale.
|
|
133
|
+
*/
|
|
134
|
+
export function useConversation(
|
|
135
|
+
id: string | undefined,
|
|
136
|
+
{ onReload }: { onReload?: (fresh: Conversation) => void } = {},
|
|
137
|
+
): RecordView<Conversation> {
|
|
138
|
+
const { canUsePrivateApi } = useOxy();
|
|
289
139
|
const client = useConversationsClient();
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
140
|
+
const store = useStore();
|
|
141
|
+
const view = useRecord(conversation, ...(canUsePrivateApi && id ? [client, id] : [skip]));
|
|
142
|
+
// Plain records, the same while unchanged: the row, and its messages once read.
|
|
143
|
+
const row = useEntity(Conversations, id, (held) => held);
|
|
144
|
+
const messages = useEntity(ConversationMessages, id, (held) => held?.messages);
|
|
145
|
+
const value = useMemo(() => (row && messages ? { ...row, messages } : row), [row, messages]);
|
|
146
|
+
useRealtimeEvent('conversation', (frame) => {
|
|
147
|
+
const data = frame.data as RealtimeData['conversation'];
|
|
148
|
+
if (!data.reload || id === undefined || data.conversation.id !== id) return;
|
|
149
|
+
void view.refresh().then(() => {
|
|
150
|
+
const read = withStore(store, () => ({
|
|
151
|
+
status: conversation.state(client, id).status,
|
|
152
|
+
fresh: heldConversation(id),
|
|
153
|
+
}));
|
|
154
|
+
if (read.status === 'success' && read.fresh) onReload?.(read.fresh);
|
|
155
|
+
});
|
|
299
156
|
});
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
return useCallback((id) => fetchConversation(client, id), [client]);
|
|
157
|
+
return {
|
|
158
|
+
...view,
|
|
159
|
+
value,
|
|
160
|
+
isLoading: view.isLoading && value === undefined,
|
|
161
|
+
};
|
|
306
162
|
}
|
|
307
163
|
|
|
308
164
|
/**
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
* unread, so an open conversation costs nothing while nothing arrives.
|
|
165
|
+
* Mark a conversation seen: its unread count goes to zero here at once and on every other surface
|
|
166
|
+
* through the server's `conversation` event. Send it only when there is something unread.
|
|
312
167
|
*/
|
|
313
168
|
export function useMarkConversationRead(): (id: string) => void {
|
|
314
|
-
const
|
|
169
|
+
const store = useStore();
|
|
315
170
|
const client = useConversationsClient();
|
|
316
171
|
return useCallback(
|
|
317
172
|
(id) => {
|
|
318
|
-
|
|
319
|
-
queryClient.setQueriesData<ConversationsInfiniteData>(
|
|
320
|
-
{ queryKey: gemieQueryKeys.conversations.all },
|
|
321
|
-
(old) =>
|
|
322
|
-
old?.pages
|
|
323
|
-
? {
|
|
324
|
-
...old,
|
|
325
|
-
pages: old.pages.map((page) => ({
|
|
326
|
-
...page,
|
|
327
|
-
conversations: page.conversations.map(update),
|
|
328
|
-
})),
|
|
329
|
-
}
|
|
330
|
-
: old,
|
|
331
|
-
);
|
|
332
|
-
void client.api.post(API_ROUTES.conversations.read(id), {}).catch(() => undefined);
|
|
173
|
+
void withStore(store, () => markConversationRead(client, id)).catch(() => undefined);
|
|
333
174
|
},
|
|
334
|
-
[
|
|
175
|
+
[store, client],
|
|
335
176
|
);
|
|
336
177
|
}
|
|
337
178
|
|
|
338
|
-
/**
|
|
179
|
+
/** Read a conversation ahead of its press (the sidebar's press-in or hover). Never retried. */
|
|
339
180
|
export function usePrefetchConversation(): (id: string) => void {
|
|
340
|
-
const
|
|
181
|
+
const store = useStore();
|
|
341
182
|
const client = useConversationsClient();
|
|
342
|
-
return useCallback(
|
|
183
|
+
return useCallback(
|
|
184
|
+
(id) => {
|
|
185
|
+
void withStore(store, () => conversation.fetch(client, id));
|
|
186
|
+
},
|
|
187
|
+
[store, client],
|
|
188
|
+
);
|
|
343
189
|
}
|
|
344
190
|
|
|
345
191
|
/**
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
* very budget that refused it, and a limiter that counts refused requests then never lets up.
|
|
192
|
+
* Read a conversation and the lists again: what changed it happened outside this client's reads
|
|
193
|
+
* (a voice call wrote its transcript on the server).
|
|
349
194
|
*/
|
|
350
|
-
export function
|
|
351
|
-
|
|
352
|
-
client
|
|
353
|
-
|
|
354
|
-
)
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
195
|
+
export function useRefreshConversation(): (id: string) => void {
|
|
196
|
+
const store = useStore();
|
|
197
|
+
const client = useConversationsClient();
|
|
198
|
+
return useCallback(
|
|
199
|
+
(id) =>
|
|
200
|
+
withStore(store, () => {
|
|
201
|
+
void conversation.refresh(client, id);
|
|
202
|
+
refreshConversationLists(client);
|
|
203
|
+
}),
|
|
204
|
+
[store, client],
|
|
205
|
+
);
|
|
361
206
|
}
|
|
362
207
|
|
|
363
|
-
/**
|
|
364
|
-
function
|
|
365
|
-
|
|
366
|
-
row: Conversation,
|
|
367
|
-
moveExisting: boolean,
|
|
368
|
-
): ConversationsInfiniteData {
|
|
369
|
-
if (!old?.pages) {
|
|
370
|
-
return {
|
|
371
|
-
pages: [{ conversations: [row], nextCursor: null, hasMore: false }],
|
|
372
|
-
pageParams: [undefined],
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
const pages = [...old.pages];
|
|
376
|
-
if (moveExisting) {
|
|
377
|
-
// Remove the conversation from its current position (if it is in any page)
|
|
378
|
-
for (let i = 0; i < pages.length; i++) {
|
|
379
|
-
const page = pages[i] as ConversationsPage;
|
|
380
|
-
const existingIndex = page.conversations.findIndex((c) => c.id === row.id);
|
|
381
|
-
if (existingIndex >= 0) {
|
|
382
|
-
pages[i] = {
|
|
383
|
-
...page,
|
|
384
|
-
conversations: [
|
|
385
|
-
...page.conversations.slice(0, existingIndex),
|
|
386
|
-
...page.conversations.slice(existingIndex + 1),
|
|
387
|
-
],
|
|
388
|
-
};
|
|
389
|
-
break;
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
} else if (pages[0]?.conversations.some((c) => c.id === row.id)) {
|
|
393
|
-
return { ...old, pages };
|
|
394
|
-
}
|
|
395
|
-
// Always add to top of first page (most recently updated first)
|
|
396
|
-
if (pages[0]) {
|
|
397
|
-
pages[0] = { ...pages[0], conversations: [row, ...pages[0].conversations] };
|
|
398
|
-
}
|
|
399
|
-
return { ...old, pages };
|
|
208
|
+
/** Tells the person a write failed, with the server's words when it sent some. */
|
|
209
|
+
function useFailureToast(fallback: string): (error: unknown) => void {
|
|
210
|
+
return useCallback((error) => toast.error(errorMessage(error, fallback)), [fallback]);
|
|
400
211
|
}
|
|
401
212
|
|
|
402
213
|
/** Save a conversation's messages (and title). */
|
|
403
|
-
export function useSaveConversation() {
|
|
404
|
-
const queryClient = useQueryClient();
|
|
405
|
-
const client = useConversationsClient();
|
|
214
|
+
export function useSaveConversation(): ActionView<[input: SaveConversationInput], Conversation> {
|
|
406
215
|
const labels = useLabels();
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
messages,
|
|
413
|
-
title,
|
|
414
|
-
}: {
|
|
415
|
-
id: string;
|
|
416
|
-
messages: Message[];
|
|
417
|
-
title?: string;
|
|
418
|
-
}): Promise<Conversation> => {
|
|
419
|
-
const lastMessage = messageText(messages[messages.length - 1]).slice(0, 100) || undefined;
|
|
420
|
-
|
|
421
|
-
try {
|
|
422
|
-
const { data } = await client.api.post<ApiConversation>(API_ROUTES.conversations.save, {
|
|
423
|
-
conversationId: id,
|
|
424
|
-
messages,
|
|
425
|
-
...(title && { title }),
|
|
426
|
-
...(client.app === undefined ? {} : { app: client.app }),
|
|
427
|
-
});
|
|
428
|
-
return {
|
|
429
|
-
id: data.id,
|
|
430
|
-
title: data.title,
|
|
431
|
-
lastMessage: data.lastMessage,
|
|
432
|
-
source: data.source,
|
|
433
|
-
app: data.app,
|
|
434
|
-
createdAt: new Date(data.createdAt),
|
|
435
|
-
updatedAt: new Date(data.updatedAt),
|
|
436
|
-
messages,
|
|
437
|
-
};
|
|
438
|
-
} catch (error: unknown) {
|
|
439
|
-
// If unauthorized, save to the offline copy
|
|
440
|
-
if (errorStatus(error) === 401) {
|
|
441
|
-
const conversations = await client.offline.read();
|
|
442
|
-
const existingIndex = conversations.findIndex((c) => c.id === id);
|
|
443
|
-
|
|
444
|
-
const offlineTitle =
|
|
445
|
-
title ||
|
|
446
|
-
messageText(messages.find((m) => m.role === 'user')).slice(0, 50) ||
|
|
447
|
-
client.newChatTitle;
|
|
448
|
-
const conversation: Conversation = {
|
|
449
|
-
id,
|
|
450
|
-
title: offlineTitle,
|
|
451
|
-
lastMessage,
|
|
452
|
-
createdAt:
|
|
453
|
-
existingIndex >= 0
|
|
454
|
-
? (conversations[existingIndex] as Conversation).createdAt
|
|
455
|
-
: new Date(),
|
|
456
|
-
updatedAt: new Date(),
|
|
457
|
-
messages,
|
|
458
|
-
};
|
|
459
|
-
|
|
460
|
-
const next = [...conversations];
|
|
461
|
-
if (existingIndex >= 0) next[existingIndex] = conversation;
|
|
462
|
-
else next.unshift(conversation);
|
|
463
|
-
|
|
464
|
-
await client.offline.write(next);
|
|
465
|
-
return conversation;
|
|
466
|
-
}
|
|
467
|
-
throw error;
|
|
468
|
-
}
|
|
469
|
-
},
|
|
470
|
-
onSuccess: (data) => {
|
|
471
|
-
queryClient.setQueryData(
|
|
472
|
-
gemieQueryKeys.conversations.all,
|
|
473
|
-
(old: ConversationsInfiniteData | undefined) =>
|
|
474
|
-
upsertOnTop(old, { ...data, messages: [] }, true),
|
|
475
|
-
);
|
|
476
|
-
// Update individual conversation cache with full data including messages
|
|
477
|
-
queryClient.setQueryData(gemieQueryKeys.conversations.detail(data.id), data);
|
|
478
|
-
},
|
|
479
|
-
onError: (error: unknown) => {
|
|
480
|
-
toast.error(getErrorMessage(error) || labels.conversationSaveFailed);
|
|
481
|
-
},
|
|
482
|
-
});
|
|
216
|
+
return useBoundAction(
|
|
217
|
+
saveConversation,
|
|
218
|
+
useConversationsClient(),
|
|
219
|
+
useFailureToast(labels.conversationSaveFailed),
|
|
220
|
+
);
|
|
483
221
|
}
|
|
484
222
|
|
|
485
|
-
/**
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
* The API has no title-only route: `POST /conversations` writes the title AND
|
|
489
|
-
* replaces the messages. So the full thread is read fresh first (`staleTime:
|
|
490
|
-
* 0` — the sidebar seeds the detail cache from the list with no messages, and
|
|
491
|
-
* saving that seed would empty the thread) and saved back with the new title.
|
|
492
|
-
*/
|
|
493
|
-
export function useRenameConversation() {
|
|
494
|
-
const queryClient = useQueryClient();
|
|
495
|
-
const client = useConversationsClient();
|
|
496
|
-
const save = useSaveConversation();
|
|
497
|
-
|
|
498
|
-
return useMutation({
|
|
499
|
-
mutationFn: async ({ id, title }: { id: string; title: string }) => {
|
|
500
|
-
const conversation = await queryClient.fetchQuery({
|
|
501
|
-
queryKey: gemieQueryKeys.conversations.detail(id),
|
|
502
|
-
queryFn: () => fetchConversation(client, id),
|
|
503
|
-
staleTime: 0,
|
|
504
|
-
});
|
|
505
|
-
return save.mutateAsync({ id, messages: conversation.messages, title });
|
|
506
|
-
},
|
|
507
|
-
});
|
|
223
|
+
/** Rename a conversation (`run(id, title)`); the whole thread is read fresh and saved back. */
|
|
224
|
+
export function useRenameConversation(): ActionView<[id: string, title: string], Conversation> {
|
|
225
|
+
return useBoundAction(renameConversation, useConversationsClient());
|
|
508
226
|
}
|
|
509
227
|
|
|
510
|
-
/** Delete a conversation. */
|
|
511
|
-
export function useDeleteConversation() {
|
|
512
|
-
const queryClient = useQueryClient();
|
|
513
|
-
const client = useConversationsClient();
|
|
228
|
+
/** Delete a conversation (`run(id)`). */
|
|
229
|
+
export function useDeleteConversation(): ActionView<[id: string], string> {
|
|
514
230
|
const labels = useLabels();
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
await client.api.delete(API_ROUTES.conversations.remove(id));
|
|
521
|
-
} catch (error: unknown) {
|
|
522
|
-
// If unauthorized, delete from the offline copy
|
|
523
|
-
if (errorStatus(error) === 401) {
|
|
524
|
-
const conversations = await client.offline.read();
|
|
525
|
-
await client.offline.write(conversations.filter((c) => c.id !== id));
|
|
526
|
-
} else {
|
|
527
|
-
throw error;
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
return id;
|
|
531
|
-
},
|
|
532
|
-
onSuccess: (id) => {
|
|
533
|
-
queryClient.setQueryData(
|
|
534
|
-
gemieQueryKeys.conversations.all,
|
|
535
|
-
(old: ConversationsInfiniteData | undefined) => {
|
|
536
|
-
if (!old?.pages) return old;
|
|
537
|
-
return {
|
|
538
|
-
...old,
|
|
539
|
-
pages: old.pages.map((page) => ({
|
|
540
|
-
...page,
|
|
541
|
-
conversations: page.conversations.filter((c) => c.id !== id),
|
|
542
|
-
})),
|
|
543
|
-
};
|
|
544
|
-
},
|
|
545
|
-
);
|
|
546
|
-
queryClient.removeQueries({ queryKey: gemieQueryKeys.conversations.detail(id) });
|
|
547
|
-
},
|
|
548
|
-
onError: (error: unknown) => {
|
|
549
|
-
toast.error(getErrorMessage(error) || labels.conversationDeleteFailed);
|
|
550
|
-
},
|
|
551
|
-
});
|
|
231
|
+
return useBoundAction(
|
|
232
|
+
deleteConversation,
|
|
233
|
+
useConversationsClient(),
|
|
234
|
+
useFailureToast(labels.conversationDeleteFailed),
|
|
235
|
+
);
|
|
552
236
|
}
|
|
553
237
|
|
|
554
238
|
/**
|
|
555
|
-
* Empty a conversation on the server, keeping the conversation.
|
|
239
|
+
* Empty a conversation on the server, keeping the conversation (`run(id)`).
|
|
556
240
|
*
|
|
557
|
-
* The persistent half of "Clear conversation" (#553). The local half
|
|
558
|
-
* `
|
|
559
|
-
*
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
* which point React Query has run this `onSuccess`, so there is no longer a
|
|
564
|
-
* history for the effect to restore. Nothing is touched optimistically: a
|
|
565
|
-
* clear the server refused must leave the thread exactly as it was, because
|
|
566
|
-
* the dialog that asked for it promised the opposite of "it will be back".
|
|
567
|
-
*
|
|
568
|
-
* The list entry keeps its place and loses its preview — the server dropped
|
|
569
|
-
* `lastMessage` in the same transaction — and both queries are then
|
|
570
|
-
* invalidated so whatever the server has (the moved `updatedAt`, a title it
|
|
571
|
-
* may have kept) replaces the local guess.
|
|
241
|
+
* The persistent half of "Clear conversation" (#553). The local half, `setMessages([])` in
|
|
242
|
+
* `useConversationThread`, is NOT enough on its own: the conversation's record still holds the
|
|
243
|
+
* history, and the thread's sync treats "record has messages, screen has none" as a data upgrade
|
|
244
|
+
* and hydrates them straight back. So the record is emptied here, and the caller resets its
|
|
245
|
+
* screen after `run` resolves, when there is no history left to restore. A refusal puts the
|
|
246
|
+
* messages back exactly as they were.
|
|
572
247
|
*/
|
|
573
|
-
export function useClearConversation() {
|
|
574
|
-
|
|
575
|
-
const client = useConversationsClient();
|
|
576
|
-
|
|
577
|
-
return useMutation({
|
|
578
|
-
retry: 1,
|
|
579
|
-
mutationFn: async (id: string) => {
|
|
580
|
-
try {
|
|
581
|
-
await client.api.delete(API_ROUTES.conversations.clearMessages(id));
|
|
582
|
-
} catch (error: unknown) {
|
|
583
|
-
// If unauthorized, clear the offline copy — the same branch a delete takes.
|
|
584
|
-
if (errorStatus(error) === 401) {
|
|
585
|
-
const conversations = await client.offline.read();
|
|
586
|
-
await client.offline.write(
|
|
587
|
-
conversations.map((c) =>
|
|
588
|
-
c.id === id
|
|
589
|
-
? { ...c, messages: [], lastMessage: undefined, updatedAt: new Date() }
|
|
590
|
-
: c,
|
|
591
|
-
),
|
|
592
|
-
);
|
|
593
|
-
} else {
|
|
594
|
-
throw error;
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
return id;
|
|
598
|
-
},
|
|
599
|
-
onSuccess: (id) => {
|
|
600
|
-
queryClient.setQueryData(
|
|
601
|
-
gemieQueryKeys.conversations.detail(id),
|
|
602
|
-
(old: Conversation | undefined) =>
|
|
603
|
-
old ? { ...old, messages: [], lastMessage: undefined } : old,
|
|
604
|
-
);
|
|
605
|
-
queryClient.setQueryData(
|
|
606
|
-
gemieQueryKeys.conversations.all,
|
|
607
|
-
(old: ConversationsInfiniteData | undefined) => {
|
|
608
|
-
if (!old?.pages) return old;
|
|
609
|
-
return {
|
|
610
|
-
...old,
|
|
611
|
-
pages: old.pages.map((page) => ({
|
|
612
|
-
...page,
|
|
613
|
-
conversations: page.conversations.map((c) =>
|
|
614
|
-
c.id === id ? { ...c, lastMessage: undefined } : c,
|
|
615
|
-
),
|
|
616
|
-
})),
|
|
617
|
-
};
|
|
618
|
-
},
|
|
619
|
-
);
|
|
620
|
-
void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.detail(id) });
|
|
621
|
-
void queryClient.invalidateQueries({ queryKey: gemieQueryKeys.conversations.all });
|
|
622
|
-
},
|
|
623
|
-
});
|
|
248
|
+
export function useClearConversation(): ActionView<[id: string], string> {
|
|
249
|
+
return useBoundAction(clearConversation, useConversationsClient());
|
|
624
250
|
}
|
|
625
251
|
|
|
626
252
|
/**
|
|
627
253
|
* Create a conversation (optionally the next stretch of an agent's thread).
|
|
628
254
|
*
|
|
629
255
|
* The next stretch of a thread whose open answered a `threadId` (Alia's: `useGemieThread`) is
|
|
630
|
-
* `{ threadId }`; `{ agentId }` alone would start one more loose chat with her. Of any other
|
|
256
|
+
* `run({ threadId })`; `{ agentId }` alone would start one more loose chat with her. Of any other
|
|
631
257
|
* gemie's thread it is `{ agentId }`.
|
|
632
258
|
*/
|
|
633
|
-
export function useCreateConversation()
|
|
634
|
-
|
|
635
|
-
|
|
259
|
+
export function useCreateConversation(): ActionView<
|
|
260
|
+
[input?: CreateConversationInput],
|
|
261
|
+
Conversation
|
|
262
|
+
> {
|
|
636
263
|
const labels = useLabels();
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
agentIds?: readonly string[];
|
|
643
|
-
/** The thread row whose next stretch this is (`GemieThreadInfo.threadId`). */
|
|
644
|
-
threadId?: string;
|
|
645
|
-
}): Promise<Conversation> => {
|
|
646
|
-
try {
|
|
647
|
-
const { data } = await client.api.post<ApiConversation>(API_ROUTES.conversations.create, {
|
|
648
|
-
...(params?.agentId && { agentId: params.agentId }),
|
|
649
|
-
...(params?.agentIds && { agentIds: params.agentIds }),
|
|
650
|
-
...(params?.threadId && { threadId: params.threadId }),
|
|
651
|
-
...(client.app === undefined ? {} : { app: client.app }),
|
|
652
|
-
});
|
|
653
|
-
return {
|
|
654
|
-
id: data.id,
|
|
655
|
-
title: data.title,
|
|
656
|
-
lastMessage: undefined,
|
|
657
|
-
source: data.source,
|
|
658
|
-
agentId: data.agentId,
|
|
659
|
-
memberAgentIds: data.memberAgentIds,
|
|
660
|
-
spaceId: data.spaceId,
|
|
661
|
-
threadId: data.threadId,
|
|
662
|
-
app: data.app,
|
|
663
|
-
createdAt: new Date(data.createdAt),
|
|
664
|
-
updatedAt: new Date(data.updatedAt),
|
|
665
|
-
messages: [],
|
|
666
|
-
};
|
|
667
|
-
} catch (error: unknown) {
|
|
668
|
-
// If unauthorized, create it in the offline copy
|
|
669
|
-
if (errorStatus(error) === 401 && client.offline.available) {
|
|
670
|
-
const conversation: Conversation = {
|
|
671
|
-
id: createRandomUuid(),
|
|
672
|
-
title: client.newChatTitle,
|
|
673
|
-
lastMessage: undefined,
|
|
674
|
-
createdAt: new Date(),
|
|
675
|
-
updatedAt: new Date(),
|
|
676
|
-
messages: [],
|
|
677
|
-
};
|
|
678
|
-
await client.offline.write([conversation, ...(await client.offline.read())]);
|
|
679
|
-
return conversation;
|
|
680
|
-
}
|
|
681
|
-
throw error;
|
|
682
|
-
}
|
|
683
|
-
},
|
|
684
|
-
onSuccess: (data) => {
|
|
685
|
-
queryClient.setQueryData(
|
|
686
|
-
gemieQueryKeys.conversations.all,
|
|
687
|
-
(old: ConversationsInfiniteData | undefined) => upsertOnTop(old, data, false),
|
|
688
|
-
);
|
|
689
|
-
queryClient.setQueryData(gemieQueryKeys.conversations.detail(data.id), data);
|
|
690
|
-
},
|
|
691
|
-
onError: (error: unknown) => {
|
|
692
|
-
toast.error(getErrorMessage(error) || labels.conversationCreateFailed);
|
|
693
|
-
},
|
|
694
|
-
});
|
|
264
|
+
return useBoundAction(
|
|
265
|
+
createConversation,
|
|
266
|
+
useConversationsClient(),
|
|
267
|
+
useFailureToast(labels.conversationCreateFailed),
|
|
268
|
+
);
|
|
695
269
|
}
|