@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.
Files changed (88) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +9 -6
  3. package/package.json +4 -11
  4. package/src/accounts.ts +7 -1
  5. package/src/ask-eager.ts +0 -2
  6. package/src/ask-text.ts +0 -1
  7. package/src/ask.ts +0 -1
  8. package/src/components/AmbientField.tsx +13 -2
  9. package/src/components/ComposerDropZone.tsx +20 -4
  10. package/src/components/ComposerSuggestions.tsx +9 -2
  11. package/src/components/GemieActivityLine.tsx +11 -5
  12. package/src/components/GemieBetweenGemies.tsx +23 -10
  13. package/src/components/GemieChatContent.tsx +46 -23
  14. package/src/components/GemieChatScreen.tsx +7 -4
  15. package/src/components/GemieChatSheet.tsx +6 -2
  16. package/src/components/GemieComposer.tsx +17 -7
  17. package/src/components/GemieGroupWelcome.tsx +16 -2
  18. package/src/components/GemieRecentConversations.tsx +13 -10
  19. package/src/components/GemieSharedConversation.tsx +38 -6
  20. package/src/components/GemieWelcomeMessage.tsx +23 -7
  21. package/src/components/IdentityMark.tsx +6 -12
  22. package/src/components/PlanPreviewCard.tsx +18 -7
  23. package/src/components/QuestionCard.tsx +6 -2
  24. package/src/components/ReplyMarkdown.tsx +32 -6
  25. package/src/components/RichBlocks.tsx +20 -15
  26. package/src/components/accounts/GemieAccountGrants.tsx +27 -10
  27. package/src/components/accounts/GemieConnectedAccounts.tsx +87 -51
  28. package/src/components/canvas/CanvasComponent.tsx +6 -2
  29. package/src/components/canvas/DashboardRenderer.tsx +25 -8
  30. package/src/components/canvas/DeckRenderer.tsx +23 -6
  31. package/src/components/canvas/FormRenderer.tsx +8 -3
  32. package/src/components/connectors/ConnectorLogo.tsx +15 -9
  33. package/src/components/connectors/GemieConnectedConnectors.tsx +51 -25
  34. package/src/components/connectors/GemieConnectorsStore.tsx +99 -41
  35. package/src/components/connectors/GrantSwitchRow.tsx +18 -5
  36. package/src/components/thought/ThoughtPanel.tsx +26 -12
  37. package/src/components/thought/ToolStep.tsx +14 -6
  38. package/src/components/thread/AgentResultCard.tsx +10 -4
  39. package/src/components/thread/AgentTaskCard.tsx +8 -3
  40. package/src/components/thread/ApprovalCard.tsx +6 -2
  41. package/src/components/thread/ChatBubble.tsx +66 -25
  42. package/src/components/thread/GemieThread.tsx +25 -8
  43. package/src/components/thread/ThreadRow.tsx +20 -15
  44. package/src/components/thread/ThreadSearch.tsx +27 -10
  45. package/src/components/thread/ThreadSkeleton.tsx +12 -6
  46. package/src/components/thread/ToolResultCard.tsx +10 -4
  47. package/src/components/thread/TurnAttachments.tsx +17 -8
  48. package/src/components/voice/VoiceControls.tsx +9 -6
  49. package/src/connectors.ts +15 -2
  50. package/src/hooks/useChatVoice.ts +2 -10
  51. package/src/hooks/useMessageReactions.ts +5 -5
  52. package/src/hooks/useThoughtScope.ts +9 -8
  53. package/src/index.ts +2 -3
  54. package/src/lib/tool-call-status.ts +1 -1
  55. package/src/lib/utils.ts +1 -8
  56. package/src/realtime/react.tsx +9 -9
  57. package/src/realtime/reread.ts +28 -0
  58. package/src/realtime/store.ts +123 -0
  59. package/src/runtime/agents.ts +46 -27
  60. package/src/runtime/collections.ts +35 -136
  61. package/src/runtime/connected-accounts.ts +175 -88
  62. package/src/runtime/connectors.ts +244 -127
  63. package/src/runtime/conversations.ts +181 -607
  64. package/src/runtime/data/answer.ts +76 -0
  65. package/src/runtime/data/collections.ts +168 -0
  66. package/src/runtime/data/conversations.ts +626 -0
  67. package/src/runtime/data/reactions.ts +29 -0
  68. package/src/runtime/data/read.ts +37 -0
  69. package/src/runtime/data/threads.ts +149 -0
  70. package/src/runtime/index.ts +72 -8
  71. package/src/runtime/model.ts +0 -2
  72. package/src/runtime/routes.ts +2 -2
  73. package/src/runtime/sharing.ts +69 -56
  74. package/src/runtime/types.ts +8 -16
  75. package/src/runtime/use-bound-action.ts +27 -0
  76. package/src/runtime/use-conversation-stream.ts +8 -31
  77. package/src/runtime/use-conversation-thread.ts +40 -51
  78. package/src/runtime/use-gemie-thread.ts +32 -43
  79. package/src/runtime/use-start-conversation.ts +14 -15
  80. package/src/runtime/use-thread-history.ts +26 -36
  81. package/src/runtime/use-thread-search.ts +29 -76
  82. package/src/text.ts +0 -1
  83. package/src/voice.ts +0 -1
  84. package/src/components/Image.tsx +0 -12
  85. package/src/realtime/cache.ts +0 -257
  86. package/src/runtime/conversation-dates.ts +0 -31
  87. package/src/runtime/query-keys.ts +0 -66
  88. package/src/runtime/reaction-cache.ts +0 -45
@@ -1,25 +1,29 @@
1
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.
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"). The snapshot is held
4
+ * in the account's store (`data/collections.ts`) and kept current by the realtime connection.
8
5
  */
9
6
 
10
- import { useQuery, useQueryClient } from '@tanstack/react-query';
7
+ import { skip, useStore, withStore } from '@oxy.so/bloom-data';
11
8
  import { useOxy } from '@oxy.so/services/ui/client';
12
- import { useCallback, useMemo } from 'react';
13
- import type { CollectionsSnapshotWire } from '../realtime/contract';
9
+ import { useMemo } from 'react';
10
+ import { type GemieApi, useGemieApi } from './api';
14
11
  import {
15
12
  type CollectionFields,
16
- type ConversationCollection,
17
13
  type ConversationCollectionKind,
18
14
  type ConversationCollections,
19
15
  EMPTY_COLLECTIONS,
20
- type LocalCollections,
21
- readCollectionsSnapshot,
22
16
  } from './collections-model';
17
+ import {
18
+ conversationCollections,
19
+ createCollection,
20
+ deleteCollection,
21
+ setCollectionMember,
22
+ setConversationFavorite,
23
+ setConversationPinned,
24
+ updateCollection,
25
+ } from './data/collections';
26
+ import { useAnswer } from './data/answer';
23
27
 
24
28
  export type {
25
29
  CollectionFields,
@@ -29,38 +33,15 @@ export type {
29
33
  LocalCollections,
30
34
  } from './collections-model';
31
35
  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
 
36
37
  /** The person's folders, projects, pins and favourites. Kept current by the realtime connection. */
37
38
  export function useConversationCollections(): ConversationCollections {
38
39
  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);
40
+ const { canUsePrivateApi } = useOxy();
41
+ return (
42
+ useAnswer(conversationCollections, ...(canUsePrivateApi ? [api] : [skip])).value ??
43
+ EMPTY_COLLECTIONS
44
+ );
64
45
  }
65
46
 
66
47
  export interface CollectionActions {
@@ -78,108 +59,26 @@ export interface CollectionActions {
78
59
 
79
60
  /**
80
61
  * 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.
62
+ * by what the server answers; a refused change puts the server's state back, and rejects.
82
63
  */
83
64
  export function useCollectionActions(): CollectionActions {
84
65
  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
-
66
+ const store = useStore();
107
67
  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);
68
+ const call = <A extends unknown[]>(
69
+ action: (api: GemieApi, ...args: A) => Promise<unknown>,
70
+ ...args: A
71
+ ) => withStore(store, () => action(api, ...args)).then(() => undefined);
117
72
  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
- ),
73
+ createCollection: (kind, fields) => call(createCollection, kind, fields),
74
+ updateCollection: (id, fields) => call(updateCollection, id, fields),
75
+ deleteCollection: (id) => call(deleteCollection, id),
76
+ addToCollection: (id, conversationId) => call(setCollectionMember, id, conversationId, true),
162
77
  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
- ),
78
+ call(setCollectionMember, id, conversationId, false),
79
+ setPinned: (conversationId, pinned) => call(setConversationPinned, conversationId, pinned),
175
80
  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
- ),
81
+ call(setConversationFavorite, conversationId, favorite),
183
82
  };
184
- }, [api, run]);
83
+ }, [api, store]);
185
84
  }
@@ -1,9 +1,20 @@
1
+ import {
2
+ action,
3
+ type ActionView,
4
+ type RecordView,
5
+ skip,
6
+ useStore,
7
+ withStore,
8
+ } from '@oxy.so/bloom-data';
1
9
  import { useOxy } from '@oxy.so/services/ui/client';
2
- import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
- import { useGemieApi } from './api';
10
+ import { useCallback, useEffect } from 'react';
11
+ import { rereadOn } from '../realtime/reread';
12
+ import { type GemieApi, useGemieApi } from './api';
13
+ import { answerSource, useAnswer } from './data/answer';
14
+ import { ACCOUNT, gemieRead } from './data/read';
4
15
  import { errorStatus } from './error-utils';
5
- import { gemieQueryKeys } from './query-keys';
6
16
  import { ACCOUNT_ROUTES } from './routes';
17
+ import { useBoundAction } from './use-bound-action';
7
18
 
8
19
  /**
9
20
  * A person's connected accounts (ADR 0035 as amended): the WhatsApp and Telegram (Business,
@@ -85,65 +96,105 @@ export interface ConnectedAccountsAnswer {
85
96
  platforms: GemieAccountPlatform[];
86
97
  }
87
98
 
99
+ /**
100
+ * The caller's accounts with their grants, and what can be connected: memory only (phone numbers
101
+ * and a live code never reach the disk). Read again when the realtime `connections` event says they
102
+ * changed, and after a reset.
103
+ */
104
+ export const connectedAccounts = answerSource('gemies.connected-accounts', {
105
+ ...gemieRead,
106
+ key: (_api: GemieApi) => ACCOUNT,
107
+ load: async ({ signal }, api) =>
108
+ (await api.get<ConnectedAccountsAnswer>(ACCOUNT_ROUTES.all, { signal })).data,
109
+ });
110
+
111
+ rereadOn('connections', connectedAccounts);
112
+ rereadOn('reset', connectedAccounts);
113
+
114
+ /** The code of an account being connected, as its session reports it now. */
115
+ export const connectedAccountQr = answerSource('gemies.connected-account-qr', {
116
+ ...gemieRead,
117
+ key: (_api: GemieApi, accountId: string) => accountId,
118
+ load: async ({ signal }, api, accountId) =>
119
+ (
120
+ await api.get<{ status: GemieAccountStatus; qr: string | null }>(
121
+ `${ACCOUNT_ROUTES.one(accountId)}/qr`,
122
+ { signal },
123
+ )
124
+ ).data,
125
+ });
126
+
127
+ /** An account's recent chats; one that has none to list (a 404) has none. */
128
+ export const connectedAccountChats = answerSource('gemies.connected-account-chats', {
129
+ ...gemieRead,
130
+ key: (_api: GemieApi, accountId: string) => accountId,
131
+ load: async ({ signal }, api, accountId) => {
132
+ try {
133
+ const { data } = await api.get<{ chats: GemieAccountChat[] }>(
134
+ `${ACCOUNT_ROUTES.one(accountId)}/chats`,
135
+ { signal },
136
+ );
137
+ return data.chats;
138
+ } catch (error) {
139
+ if (errorStatus(error) === 404) return [];
140
+ throw error;
141
+ }
142
+ },
143
+ });
144
+
88
145
  /** The caller's accounts, each as its session is now with its grants, and what can be connected. */
89
- export function useConnectedAccounts() {
146
+ export function useConnectedAccounts(): RecordView<ConnectedAccountsAnswer> {
147
+ const api = useGemieApi();
148
+ const { canUsePrivateApi } = useOxy();
149
+ return useAnswer(connectedAccounts, ...(canUsePrivateApi ? [api] : [skip]));
150
+ }
151
+
152
+ /** Reads the caller's accounts again, in the store of the tree. */
153
+ function useRefreshConnectedAccounts(): () => void {
90
154
  const api = useGemieApi();
91
- const { isAuthenticated } = useOxy();
92
- return useQuery({
93
- queryKey: gemieQueryKeys.accounts.all,
94
- queryFn: async (): Promise<ConnectedAccountsAnswer> => {
95
- const { data } = await api.get<ConnectedAccountsAnswer>(ACCOUNT_ROUTES.all);
96
- return data;
97
- },
98
- enabled: isAuthenticated,
99
- });
155
+ const store = useStore();
156
+ return useCallback(
157
+ () => void withStore(store, () => connectedAccounts.refresh(api)),
158
+ [api, store],
159
+ );
100
160
  }
101
161
 
162
+ /** How often a waiting code is read again: WhatsApp rotates its code every few seconds. */
163
+ const QR_REFRESH_MS = 4000;
164
+
102
165
  /**
103
166
  * The code of an account being connected, refreshed while it waits (WhatsApp rotates its code
104
167
  * every few seconds; Telegram's link is renewed when it expires, and is gone once Telegram knows
105
- * who the person is). It stops once the session leaves `qr-pending`, and the list is re-read then,
106
- * so the account shows as it is.
168
+ * who the person is). It stops once the session leaves `qr-pending`, and the list is read again
169
+ * then, so the account shows as it is. Until the first read, the code the connection answered.
107
170
  */
108
- export function useConnectedAccountQr(link: GemieAccountLink | null) {
171
+ export function useConnectedAccountQr(
172
+ link: GemieAccountLink | null,
173
+ ): RecordView<{ status: GemieAccountStatus; qr: string | null }> {
109
174
  const api = useGemieApi();
110
- const queryClient = useQueryClient();
111
- const accountId = link?.accountId ?? '';
112
- return useQuery({
113
- queryKey: gemieQueryKeys.accounts.qr(accountId),
114
- queryFn: async (): Promise<{ status: GemieAccountStatus; qr: string | null }> => {
115
- const { data } = await api.get<{ status: GemieAccountStatus; qr: string | null }>(
116
- `${ACCOUNT_ROUTES.one(accountId)}/qr`,
117
- );
118
- if (data.status !== 'qr-pending') {
119
- await queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
120
- }
121
- return data;
122
- },
123
- enabled: link !== null,
124
- initialData: link ? { status: 'qr-pending' as const, qr: link.qr } : undefined,
125
- initialDataUpdatedAt: 0,
126
- refetchInterval: (query) => (query.state.data?.status === 'qr-pending' ? 4000 : false),
127
- });
175
+ const view = useAnswer(connectedAccountQr, ...(link ? [api, link.accountId] : [skip]));
176
+ const refreshAccounts = useRefreshConnectedAccounts();
177
+ const status = view.value?.status;
178
+ const { refresh } = view;
179
+ const waiting = link !== null && (status === undefined || status === 'qr-pending');
180
+ useEffect(() => {
181
+ if (!waiting) return;
182
+ const timer = setInterval(() => void refresh(), QR_REFRESH_MS);
183
+ return () => clearInterval(timer);
184
+ }, [waiting, refresh]);
185
+ useEffect(() => {
186
+ if (status !== undefined && status !== 'qr-pending') refreshAccounts();
187
+ }, [status, refreshAccounts]);
188
+ return {
189
+ ...view,
190
+ value: view.value ?? (link ? { status: 'qr-pending', qr: link.qr } : undefined),
191
+ };
128
192
  }
129
193
 
130
194
  /** An account's recent chats, read while the person chooses which ones it answers. */
131
- export function useConnectedAccountChats(accountId: string) {
195
+ export function useConnectedAccountChats(accountId: string): RecordView<GemieAccountChat[]> {
132
196
  const api = useGemieApi();
133
- return useQuery({
134
- queryKey: gemieQueryKeys.accounts.chats(accountId),
135
- queryFn: async (): Promise<GemieAccountChat[]> => {
136
- try {
137
- const { data } = await api.get<{ chats: GemieAccountChat[] }>(
138
- `${ACCOUNT_ROUTES.one(accountId)}/chats`,
139
- );
140
- return data.chats;
141
- } catch (error) {
142
- if (errorStatus(error) === 404) return [];
143
- throw error;
144
- }
145
- },
146
- });
197
+ return useAnswer(connectedAccountChats, api, accountId);
147
198
  }
148
199
 
149
200
  /** What can be changed of an account: who answers it, and whom that gemie answers. */
@@ -155,44 +206,80 @@ export interface ConnectedAccountPatch {
155
206
  groupReplies?: GemieAccountGroupReplies;
156
207
  }
157
208
 
158
- /**
159
- * Connecting, granting, who answers, and removing (its session ends and its grants go).
160
- * Every write re-reads the list, so each screen that shows an account shows it as it now is.
161
- */
162
- export function useConnectedAccountMutations() {
209
+ /** Draws a change to the held accounts, as the calling action's layer. */
210
+ function drawAccounts(change: (accounts: ConnectedAccount[]) => ConnectedAccount[]): void {
211
+ connectedAccounts.entity.update(ACCOUNT, (held) => ({
212
+ ...held,
213
+ value: { ...held.value, accounts: change([...held.value.accounts]) },
214
+ }));
215
+ }
216
+
217
+ /** Every write ends with the list read again, so each screen shows the accounts as they now are. */
218
+ const rereadAccounts = (api: GemieApi) => void connectedAccounts.refresh(api);
219
+
220
+ /** Connects an account on a platform: the code (or link) that finishes it. */
221
+ export const connectAccount = action({
222
+ run: async (api: GemieApi, platform: GemieAccountPlatform) =>
223
+ (await api.post<GemieAccountLink>(ACCOUNT_ROUTES.all, { platform })).data,
224
+ settle: (_link, api) => rereadAccounts(api),
225
+ });
226
+
227
+ /** Changes who answers an account and whom: drawn at once, put back if refused. */
228
+ export const updateAccount = action({
229
+ optimistic: (_api: GemieApi, accountId: string, patch: ConnectedAccountPatch) =>
230
+ drawAccounts((accounts) =>
231
+ accounts.map((account) => (account._id === accountId ? { ...account, ...patch } : account)),
232
+ ),
233
+ run: async (api, accountId, patch) => {
234
+ await api.patch(ACCOUNT_ROUTES.one(accountId), patch);
235
+ },
236
+ settle: (_result, api) => rereadAccounts(api),
237
+ });
238
+
239
+ /** Grants an account to a gemie (`granted: true`) or revokes it: drawn at once, put back if refused. */
240
+ export const grantAccount = action({
241
+ optimistic: (_api: GemieApi, accountId: string, gemieId: string, granted: boolean) =>
242
+ drawAccounts((accounts) =>
243
+ accounts.map((account) =>
244
+ account._id !== accountId
245
+ ? account
246
+ : {
247
+ ...account,
248
+ gemieIds: granted
249
+ ? [...account.gemieIds.filter((id) => id !== gemieId), gemieId]
250
+ : account.gemieIds.filter((id) => id !== gemieId),
251
+ },
252
+ ),
253
+ ),
254
+ run: async (api, accountId, gemieId, granted) => {
255
+ const path = ACCOUNT_ROUTES.grant(accountId, gemieId);
256
+ await (granted ? api.put(path) : api.delete(path));
257
+ },
258
+ settle: (_result, api) => rereadAccounts(api),
259
+ });
260
+
261
+ /** Removes an account (its session ends and its grants go): gone at once, back if refused. */
262
+ export const removeAccount = action({
263
+ optimistic: (_api: GemieApi, accountId: string) =>
264
+ drawAccounts((accounts) => accounts.filter((account) => account._id !== accountId)),
265
+ run: async (api, accountId) => {
266
+ await api.delete(ACCOUNT_ROUTES.one(accountId));
267
+ },
268
+ settle: (_result, api) => rereadAccounts(api),
269
+ });
270
+
271
+ /** Connecting, granting, who answers, and removing, as a component calls them. */
272
+ export function useConnectedAccountMutations(): {
273
+ connect: ActionView<[platform: GemieAccountPlatform], GemieAccountLink>;
274
+ update: ActionView<[accountId: string, patch: ConnectedAccountPatch], void>;
275
+ grant: ActionView<[accountId: string, gemieId: string, granted: boolean], void>;
276
+ remove: ActionView<[accountId: string], void>;
277
+ } {
163
278
  const api = useGemieApi();
164
- const queryClient = useQueryClient();
165
- const invalidate = () => queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
166
-
167
- const connect = useMutation({
168
- mutationFn: async (platform: GemieAccountPlatform): Promise<GemieAccountLink> => {
169
- const { data } = await api.post<GemieAccountLink>(ACCOUNT_ROUTES.all, { platform });
170
- return data;
171
- },
172
- onSuccess: invalidate,
173
- });
174
-
175
- const update = useMutation({
176
- mutationFn: async ({ accountId, ...patch }: ConnectedAccountPatch & { accountId: string }) => {
177
- await api.patch(ACCOUNT_ROUTES.one(accountId), patch);
178
- },
179
- onSuccess: invalidate,
180
- });
181
-
182
- const grant = useMutation({
183
- mutationFn: async (input: { accountId: string; gemieId: string; granted: boolean }) => {
184
- const path = ACCOUNT_ROUTES.grant(input.accountId, input.gemieId);
185
- await (input.granted ? api.put(path) : api.delete(path));
186
- },
187
- onSuccess: invalidate,
188
- });
189
-
190
- const remove = useMutation({
191
- mutationFn: async (accountId: string) => {
192
- await api.delete(ACCOUNT_ROUTES.one(accountId));
193
- },
194
- onSuccess: invalidate,
195
- });
196
-
197
- return { connect, update, grant, remove };
279
+ return {
280
+ connect: useBoundAction(connectAccount, api),
281
+ update: useBoundAction(updateAccount, api),
282
+ grant: useBoundAction(grantAccount, api),
283
+ remove: useBoundAction(removeAccount, api),
284
+ };
198
285
  }