@gemies/sdk 3.3.1 → 4.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.
@@ -0,0 +1,57 @@
1
+ import { Switch } from '@oxy.so/bloom/switch';
2
+ import { Text } from '@oxy.so/bloom/typography';
3
+ import type { ReactNode } from 'react';
4
+ import { View } from 'react-native';
5
+
6
+ export interface GrantSwitchRowProps {
7
+ /** What the row grants, drawn before its name: a connector's logo, a platform's mark. */
8
+ leading?: ReactNode;
9
+ label: string;
10
+ /** A second line: which account it is, or what the grant means here. */
11
+ detail?: string | null;
12
+ checked: boolean;
13
+ disabled?: boolean;
14
+ accessibilityLabel: string;
15
+ onCheckedChange: (granted: boolean) => void;
16
+ /** The first row of a list draws no divider above it. */
17
+ first?: boolean;
18
+ }
19
+
20
+ /**
21
+ * One grant of a connected account to a gemie, as a switch: the row every grant list draws, so a
22
+ * connector granted in a gemie's editor and a WhatsApp granted in Settings read and behave the same.
23
+ */
24
+ export function GrantSwitchRow({
25
+ leading,
26
+ label,
27
+ detail,
28
+ checked,
29
+ disabled,
30
+ accessibilityLabel,
31
+ onCheckedChange,
32
+ first,
33
+ }: GrantSwitchRowProps) {
34
+ return (
35
+ <View
36
+ className={`flex-row items-center gap-2.5 py-2.5 pe-2.5 ${first ? '' : 'border-t border-border'}`}
37
+ >
38
+ {leading}
39
+ <View className="flex-1 gap-0.5">
40
+ <Text variant="body-2-regular" numberOfLines={1}>
41
+ {label}
42
+ </Text>
43
+ {detail ? (
44
+ <Text variant="body-2-regular" className="text-text-secondary" numberOfLines={1}>
45
+ {detail}
46
+ </Text>
47
+ ) : null}
48
+ </View>
49
+ <Switch
50
+ accessibilityLabel={accessibilityLabel}
51
+ checked={checked}
52
+ disabled={disabled}
53
+ onCheckedChange={onCheckedChange}
54
+ />
55
+ </View>
56
+ );
57
+ }
package/src/connectors.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  /**
3
3
  * The connectors leaf entry: the providers' own remote MCP servers a person connects (Notion,
4
4
  * Linear, Slack…) and their own MCP servers by URL. The store where they are found and connected,
5
- * the Settings list of what was connected, and the one logo every screen draws for a connector.
5
+ * the Settings list of what was connected, the one logo every screen draws for a connector, and
6
+ * the switch every list that grants a connected account to a gemie draws (`GrantSwitchRow`).
6
7
  * The Gemies and the Alia apps both draw these; neither keeps a copy.
7
8
  */
8
9
  export { ConnectorLogo } from './components/connectors/ConnectorLogo';
@@ -11,6 +12,8 @@ export { GemieConnectorsStore } from './components/connectors/GemieConnectorsSto
11
12
  export type { GemieConnectorsStoreProps } from './components/connectors/GemieConnectorsStore';
12
13
  export { GemieConnectedConnectors } from './components/connectors/GemieConnectedConnectors';
13
14
  export type { GemieConnectedConnectorsProps } from './components/connectors/GemieConnectedConnectors';
15
+ export { GrantSwitchRow } from './components/connectors/GrantSwitchRow';
16
+ export type { GrantSwitchRowProps } from './components/connectors/GrantSwitchRow';
14
17
  export {
15
18
  CONNECTOR_CATEGORIES,
16
19
  CONNECTOR_ROUTES,
@@ -220,26 +220,37 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
220
220
  'gemie.connectors.toolCount': { zero: 'No tools', one: '1 tool', other: '{{count}} tools' },
221
221
  'gemie.connectors.usedBy': 'Used by {{names}}',
222
222
  'gemie.accounts.answerChat': 'Answer {{name}}',
223
+ 'gemie.accounts.answeringLabel': 'Answers on its own',
224
+ 'gemie.accounts.answeringNobody': 'Nobody',
225
+ 'gemie.accounts.answeringNone':
226
+ 'No gemie replies on its own to what arrives here. The gemies above still read and send when you ask them.',
227
+ 'gemie.accounts.answersOnItsOwn': 'Answers on its own',
223
228
  'gemie.accounts.cancel': 'Cancel',
229
+ 'gemie.accounts.connect': 'Connect an account',
230
+ 'gemie.accounts.connectFailed': 'Could not connect {{platform}}: {{reason}}',
231
+ 'gemie.accounts.connectNamed': 'Connect a {{platform}} account',
232
+ 'gemie.accounts.connected': '{{platform}} is connected. Choose which of your gemies may use it.',
224
233
  'gemie.accounts.description':
225
- 'Link a WhatsApp or Telegram account and {{name}} answers the messages that arrive on it, as you choose below. Only {{name}} can read or send through it.',
234
+ 'Connect your WhatsApp or Telegram once, then choose which of your gemies may use each account. They read and send through it when you ask them, or when a task of yours needs it. One of them can also answer what arrives on it on its own.',
235
+ 'gemie.accounts.grantLabel': '{{gemie}} may use {{account}}',
236
+ 'gemie.accounts.grants.description':
237
+ '{{name}} reads and sends through these when you ask it, or when a task of yours needs it.',
238
+ 'gemie.accounts.grants.empty': 'You have not connected a WhatsApp or Telegram account yet.',
239
+ 'gemie.accounts.grants.manage': 'Connect or manage accounts',
240
+ 'gemie.accounts.grants.title': 'Accounts {{name}} can use',
226
241
  'gemie.accounts.groupChat': '{{name}} (group)',
227
242
  'gemie.accounts.groupReplies.mentions': 'Only when mentioned or replied to',
228
243
  'gemie.accounts.groupReplies.never': 'Never',
229
244
  'gemie.accounts.groupRepliesLabel': 'In groups',
230
245
  'gemie.accounts.lastMessage': 'Last message: {{when}}',
231
- 'gemie.accounts.link': 'Link an account',
232
246
  'gemie.accounts.linkExpired':
233
- 'The {{platform}} code expired before it was scanned. Link it again.',
234
- 'gemie.accounts.linkFailed': 'Could not link {{platform}}: {{reason}}',
235
- 'gemie.accounts.linkNamed': 'Link a {{platform}} account',
236
- 'gemie.accounts.linked': '{{platform}} is linked. {{name}} answers there now.',
247
+ 'The {{platform}} code expired before it was scanned. Connect it again.',
237
248
  'gemie.accounts.loadFailed': 'Could not load this. Try again.',
238
249
  'gemie.accounts.noChats': 'No chats yet. They appear here once messages arrive.',
239
250
  'gemie.accounts.noMessagesYet': 'No messages yet',
240
251
  'gemie.accounts.remove': 'Remove',
241
252
  'gemie.accounts.removeDescription':
242
- '{{name}} stops answering on this {{platform}} account and its synced chats are deleted. You can link it again by scanning a new code.',
253
+ 'Your gemies stop using this {{platform}} account and its synced chats are deleted. You can connect it again by scanning a new code.',
243
254
  'gemie.accounts.removeFailed': 'Could not remove it. Try again.',
244
255
  'gemie.accounts.removeNamed': 'Remove the {{platform}} account',
245
256
  'gemie.accounts.removeTitle': 'Remove {{platform}}',
@@ -255,9 +266,9 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
255
266
  'gemie.accounts.scanTitle': 'Scan with {{platform}}',
256
267
  'gemie.accounts.status.connected': 'Connected',
257
268
  'gemie.accounts.status.disconnected': 'Reconnecting',
258
- 'gemie.accounts.status.failed': 'Could not reconnect. Remove it and link it again.',
269
+ 'gemie.accounts.status.failed': 'Could not reconnect. Remove it and connect it again.',
270
+ 'gemie.accounts.status.logged-out': 'Unlinked from the phone. Remove it and connect it again.',
259
271
  'gemie.accounts.status.paused': 'Paused',
260
- 'gemie.accounts.status.logged-out': 'Unlinked from the phone. Remove it and link it again.',
261
272
  'gemie.accounts.status.qr-pending': 'Waiting for the scan',
262
273
  'gemie.accounts.telegram.cannotReply':
263
274
  'Telegram does not let {{name}} reply yet: allow "Reply to messages" for the bot in Telegram › Settings › Telegram Business › Chatbots.',
@@ -266,11 +277,11 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
266
277
  'Telegram Business needs Telegram Premium, and covers your private chats only (not groups or channels). It stays connected until you remove it in Telegram.',
267
278
  'gemie.accounts.telegram.open': 'Open Telegram',
268
279
  'gemie.accounts.telegram.removeDescription':
269
- '{{name}} stops answering on your Telegram and what it read there is deleted. To disconnect it in Telegram too, remove the bot in Telegram › Settings › Telegram Business › Chatbots.',
280
+ 'Your gemies stop using your Telegram and what they read there is deleted. To disconnect it in Telegram too, remove the bot in Telegram › Settings › Telegram Business › Chatbots.',
270
281
  'gemie.accounts.telegram.status.disconnected': 'Reconnecting',
271
282
  'gemie.accounts.telegram.status.failed': 'Telegram could not be reached. It retries on its own.',
272
283
  'gemie.accounts.telegram.status.logged-out':
273
- 'Revoked: this Telegram now answers through another gemie. Remove it, or link it again.',
284
+ 'Revoked: this Telegram was connected again as another account. Remove this one.',
274
285
  'gemie.accounts.telegram.status.paused':
275
286
  'Paused in Telegram. It resumes on its own when you turn the bot back on there.',
276
287
  'gemie.accounts.telegram.status.qr-pending': 'Waiting for you in Telegram',
@@ -282,7 +293,10 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
282
293
  'Telegram knows it is you. Now go to Telegram › Settings › Telegram Business › Chatbots and add the bot you just opened.',
283
294
  'gemie.accounts.title': 'Connected accounts',
284
295
  'gemie.accounts.tryAgain': 'try again in a moment.',
285
- 'gemie.accounts.unavailable': 'Linking WhatsApp or Telegram is not available right now.',
296
+ 'gemie.accounts.unavailable': 'Connecting WhatsApp or Telegram is not available right now.',
297
+ 'gemie.accounts.usedBy': 'Gemies that can use it',
298
+ 'gemie.accounts.usedByHint':
299
+ 'They read and send through it when you ask them, or when a task of yours needs it.',
286
300
  'market.dayHigh': 'Day high',
287
301
  'market.dayLow': 'Day low',
288
302
  'market.marketCap': 'Market cap',
@@ -220,26 +220,37 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
220
220
  },
221
221
  'gemie.connectors.usedBy': 'Lo usan {{names}}',
222
222
  'gemie.accounts.answerChat': 'Responder a {{name}}',
223
+ 'gemie.accounts.answeringLabel': 'Responde por su cuenta',
224
+ 'gemie.accounts.answeringNobody': 'Nadie',
225
+ 'gemie.accounts.answeringNone':
226
+ 'Ningún gemie responde por su cuenta a lo que llega aquí. Los gemies de arriba siguen leyendo y enviando cuando se lo pides.',
227
+ 'gemie.accounts.answersOnItsOwn': 'Responde por su cuenta',
223
228
  'gemie.accounts.cancel': 'Cancelar',
229
+ 'gemie.accounts.connect': 'Conectar una cuenta',
230
+ 'gemie.accounts.connectFailed': 'No se ha podido conectar {{platform}}: {{reason}}',
231
+ 'gemie.accounts.connectNamed': 'Conectar una cuenta de {{platform}}',
232
+ 'gemie.accounts.connected': '{{platform}} está conectado. Elige qué gemies pueden usarlo.',
224
233
  'gemie.accounts.description':
225
- 'Vincula una cuenta de WhatsApp o Telegram y {{name}} responderá los mensajes que lleguen a ella, como elijas abajo. Solo {{name}} puede leer o enviar por ella.',
234
+ 'Conecta tu WhatsApp o tu Telegram una vez y elige qué gemies pueden usar cada cuenta. Leen y envían por ella cuando se lo pides o cuando una tarea tuya lo necesita. Uno de ellos puede además responder por su cuenta a lo que llega.',
235
+ 'gemie.accounts.grantLabel': '{{gemie}} puede usar {{account}}',
236
+ 'gemie.accounts.grants.description':
237
+ '{{name}} lee y envía por estas cuentas cuando se lo pides o cuando una tarea tuya lo necesita.',
238
+ 'gemie.accounts.grants.empty': 'Aún no has conectado ninguna cuenta de WhatsApp ni de Telegram.',
239
+ 'gemie.accounts.grants.manage': 'Conectar o gestionar cuentas',
240
+ 'gemie.accounts.grants.title': 'Cuentas que puede usar {{name}}',
226
241
  'gemie.accounts.groupChat': '{{name}} (grupo)',
227
242
  'gemie.accounts.groupReplies.mentions': 'Solo cuando le mencionan o le responden',
228
243
  'gemie.accounts.groupReplies.never': 'Nunca',
229
244
  'gemie.accounts.groupRepliesLabel': 'En grupos',
230
245
  'gemie.accounts.lastMessage': 'Último mensaje: {{when}}',
231
- 'gemie.accounts.link': 'Vincular una cuenta',
232
246
  'gemie.accounts.linkExpired':
233
- 'El código de {{platform}} caducó antes de escanearlo. Vuelve a vincularlo.',
234
- 'gemie.accounts.linkFailed': 'No se ha podido vincular {{platform}}: {{reason}}',
235
- 'gemie.accounts.linkNamed': 'Vincular una cuenta de {{platform}}',
236
- 'gemie.accounts.linked': '{{platform}} está vinculado. {{name}} ya responde allí.',
247
+ 'El código de {{platform}} caducó antes de escanearlo. Vuelve a conectarlo.',
237
248
  'gemie.accounts.loadFailed': 'No se ha podido cargar. Inténtalo de nuevo.',
238
249
  'gemie.accounts.noChats': 'Aún no hay chats. Aparecen aquí cuando llegan mensajes.',
239
250
  'gemie.accounts.noMessagesYet': 'Aún no hay mensajes',
240
251
  'gemie.accounts.remove': 'Quitar',
241
252
  'gemie.accounts.removeDescription':
242
- '{{name}} dejará de responder en esta cuenta de {{platform}} y se borrarán sus chats sincronizados. Puedes volver a vincularla escaneando un código nuevo.',
253
+ 'Tus gemies dejarán de usar esta cuenta de {{platform}} y se borrarán sus chats sincronizados. Puedes volver a conectarla escaneando un código nuevo.',
243
254
  'gemie.accounts.removeFailed': 'No se ha podido quitar. Inténtalo de nuevo.',
244
255
  'gemie.accounts.removeNamed': 'Quitar la cuenta de {{platform}}',
245
256
  'gemie.accounts.removeTitle': 'Quitar {{platform}}',
@@ -255,10 +266,10 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
255
266
  'gemie.accounts.scanTitle': 'Escanea con {{platform}}',
256
267
  'gemie.accounts.status.connected': 'Conectada',
257
268
  'gemie.accounts.status.disconnected': 'Reconectando',
258
- 'gemie.accounts.status.failed': 'No se ha podido reconectar. Quítala y vuelve a vincularla.',
259
- 'gemie.accounts.status.paused': 'En pausa',
269
+ 'gemie.accounts.status.failed': 'No se ha podido reconectar. Quítala y vuelve a conectarla.',
260
270
  'gemie.accounts.status.logged-out':
261
- 'Desvinculada desde el teléfono. Quítala y vuelve a vincularla.',
271
+ 'Desvinculada desde el teléfono. Quítala y vuelve a conectarla.',
272
+ 'gemie.accounts.status.paused': 'En pausa',
262
273
  'gemie.accounts.status.qr-pending': 'Esperando el escaneo',
263
274
  'gemie.accounts.telegram.cannotReply':
264
275
  'Telegram aún no deja responder a {{name}}: permite «Responder a mensajes» al bot en Telegram › Ajustes › Telegram Business › Chatbots.',
@@ -267,12 +278,12 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
267
278
  'Telegram Business necesita Telegram Premium y solo cubre tus chats privados (no grupos ni canales). Sigue conectado hasta que lo quites en Telegram.',
268
279
  'gemie.accounts.telegram.open': 'Abrir Telegram',
269
280
  'gemie.accounts.telegram.removeDescription':
270
- '{{name}} deja de responder en tu Telegram y se borra lo que leyó allí. Para desconectarlo también en Telegram, quita el bot en Telegram › Ajustes › Telegram Business › Chatbots.',
281
+ 'Tus gemies dejarán de usar tu Telegram y se borrará lo que leyeron allí. Para desconectarlo también en Telegram, quita el bot en Telegram › Ajustes › Telegram Business › Chatbots.',
271
282
  'gemie.accounts.telegram.status.disconnected': 'Reconectando',
272
283
  'gemie.accounts.telegram.status.failed':
273
284
  'No se ha podido contactar con Telegram. Lo reintenta solo.',
274
285
  'gemie.accounts.telegram.status.logged-out':
275
- 'Revocado: este Telegram ahora responde a través de otro gemie. Quítalo o vuelve a vincularlo.',
286
+ 'Revocado: este Telegram se conectó de nuevo como otra cuenta. Quita esta.',
276
287
  'gemie.accounts.telegram.status.paused':
277
288
  'En pausa en Telegram. Se reanuda solo cuando vuelvas a activar el bot allí.',
278
289
  'gemie.accounts.telegram.status.qr-pending': 'Esperándote en Telegram',
@@ -284,7 +295,10 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
284
295
  'Telegram ya sabe que eres tú. Ahora ve a Telegram › Ajustes › Telegram Business › Chatbots y añade el bot que acabas de abrir.',
285
296
  'gemie.accounts.title': 'Cuentas conectadas',
286
297
  'gemie.accounts.tryAgain': 'inténtalo de nuevo en un momento.',
287
- 'gemie.accounts.unavailable': 'Ahora mismo no se puede vincular WhatsApp ni Telegram.',
298
+ 'gemie.accounts.unavailable': 'Ahora mismo no se puede conectar WhatsApp ni Telegram.',
299
+ 'gemie.accounts.usedBy': 'Gemies que pueden usarla',
300
+ 'gemie.accounts.usedByHint':
301
+ 'Leen y envían por ella cuando se lo pides o cuando una tarea tuya lo necesita.',
288
302
  'market.dayHigh': 'Máximo del día',
289
303
  'market.dayLow': 'Mínimo del día',
290
304
  'market.marketCap': 'Capitalización',
@@ -71,7 +71,7 @@ async function readBody(response: Response): Promise<unknown> {
71
71
 
72
72
  /** The structural slice of `OxyServices` the API layer needs. */
73
73
  export interface LinkableOxy {
74
- createLinkedClient(config: { baseURL: string }): {
74
+ createLinkedClient(config: { baseURL: string; receiverSendsNoStore?: boolean }): {
75
75
  client: {
76
76
  requestAuthenticatedResponse(config: {
77
77
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -102,7 +102,9 @@ export function createGemieApi(
102
102
  request: GemieApiRequest = {},
103
103
  ): Promise<GemieApiResult<T>> {
104
104
  const assertion = await appAssertionHeaders();
105
- const linked = oxyServices.createLinkedClient({ baseURL: apiUrl });
105
+ // The Gemies API sends `Cache-Control: no-store` on every response, so the browser may use its
106
+ // CORS preflight cache (`@oxy.so/core` >= 7.50; an older core ignores the flag).
107
+ const linked = oxyServices.createLinkedClient({ baseURL: apiUrl, receiverSendsNoStore: true });
106
108
  try {
107
109
  const headers = {
108
110
  ...assertion,
@@ -0,0 +1,218 @@
1
+ import { useOxy } from '@oxy.so/services/ui/client';
2
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
+ import { useGemieApi } from './api';
4
+ import { errorStatus } from './error-utils';
5
+ import { gemieQueryKeys } from './query-keys';
6
+ import { ACCOUNT_ROUTES } from './routes';
7
+
8
+ /**
9
+ * A person's connected accounts (ADR 0035 as amended): the WhatsApp and Telegram (Business,
10
+ * ADR 0037) accounts they connect ONCE, in Settings, and grant to the gemies that may use them.
11
+ * At most one granted gemie answers what arrives on an account, as its replies say; every granted
12
+ * gemie reads and sends through it when the person asks it or its tasks need it. Each is the
13
+ * caller's own; the API never lists another person's. The Gemies and the Alia apps both manage them
14
+ * through these hooks, `GemieConnectedAccounts` (Settings) and `GemieAccountGrants` (a gemie's
15
+ * editor), from `@gemies/sdk/accounts`.
16
+ */
17
+
18
+ export const GEMIE_ACCOUNT_PLATFORMS = ['whatsapp', 'telegram'] as const;
19
+ export type GemieAccountPlatform = (typeof GEMIE_ACCOUNT_PLATFORMS)[number];
20
+
21
+ /** Where an account's session is, as the API reports it (the gateway's own vocabulary). */
22
+ export const GEMIE_ACCOUNT_STATUSES = [
23
+ 'qr-pending',
24
+ 'connected',
25
+ 'disconnected',
26
+ 'paused',
27
+ 'logged-out',
28
+ 'failed',
29
+ ] as const;
30
+ export type GemieAccountStatus = (typeof GEMIE_ACCOUNT_STATUSES)[number];
31
+
32
+ /** Who the answering gemie answers: everybody who writes, only the chosen chats, or nobody. */
33
+ export const GEMIE_ACCOUNT_REPLIES = ['everyone', 'chosen', 'nobody'] as const;
34
+ export type GemieAccountReplies = (typeof GEMIE_ACCOUNT_REPLIES)[number];
35
+ /** In a group: only when the message mentions or replies to the account, or never. */
36
+ export const GEMIE_ACCOUNT_GROUP_REPLIES = ['mentions', 'never'] as const;
37
+ export type GemieAccountGroupReplies = (typeof GEMIE_ACCOUNT_GROUP_REPLIES)[number];
38
+
39
+ /** One account, as `GET /me/accounts` lists it. */
40
+ export interface ConnectedAccount {
41
+ _id: string;
42
+ platform: GemieAccountPlatform;
43
+ displayName: string | null;
44
+ phoneNumber: string | null;
45
+ status: GemieAccountStatus;
46
+ /** Whether the platform lets a gemie write from it (Telegram Business); `null` elsewhere. */
47
+ canReply: boolean | null;
48
+ oxyTaskState: 'active' | 'reauth_required';
49
+ /** The gemies that may use it. */
50
+ gemieIds: string[];
51
+ /** The one that answers what arrives on it, or `null` when none does. */
52
+ answeringGemieId: string | null;
53
+ replies: GemieAccountReplies;
54
+ replyChatIds: string[];
55
+ groupReplies: GemieAccountGroupReplies;
56
+ lastActiveAt: string | null;
57
+ }
58
+
59
+ /** A gemie an account can be granted to: Alia, and the person's own. */
60
+ export interface GrantableGemie {
61
+ id: string;
62
+ name: string;
63
+ }
64
+
65
+ /** One chat of an account, to choose which ones it answers. */
66
+ export interface GemieAccountChat {
67
+ chatId: string;
68
+ name: string;
69
+ kind: 'direct' | 'group';
70
+ }
71
+
72
+ /**
73
+ * A connection waiting to be finished: WhatsApp's code to scan, or Telegram's t.me link to open
74
+ * (or scan from another device).
75
+ */
76
+ export interface GemieAccountLink {
77
+ accountId: string;
78
+ qr: string | null;
79
+ }
80
+
81
+ export interface ConnectedAccountsAnswer {
82
+ accounts: ConnectedAccount[];
83
+ /** The gemies the person can grant an account to. */
84
+ gemies: GrantableGemie[];
85
+ /** The platforms this deployment can connect now: only those are offered. */
86
+ platforms: GemieAccountPlatform[];
87
+ }
88
+
89
+ /**
90
+ * The caller's accounts, each as its session is now with its grants, and what can be connected.
91
+ * An account whose answering gemie's Oxy task lapsed is renewed on the way (the provider link is
92
+ * kept; the person looking is the verified requester); a renewal that fails leaves it typed
93
+ * inactive for the next visit to retry. An account nobody answers holds no task to renew.
94
+ */
95
+ export function useConnectedAccounts() {
96
+ const api = useGemieApi();
97
+ const { isAuthenticated } = useOxy();
98
+ return useQuery({
99
+ queryKey: gemieQueryKeys.accounts.all,
100
+ queryFn: async (): Promise<ConnectedAccountsAnswer> => {
101
+ const { data } = await api.get<ConnectedAccountsAnswer>(ACCOUNT_ROUTES.all);
102
+ await Promise.all(
103
+ data.accounts
104
+ .filter(
105
+ (account) => account.answeringGemieId && account.oxyTaskState === 'reauth_required',
106
+ )
107
+ .map(async (account) => {
108
+ try {
109
+ await api.post(`${ACCOUNT_ROUTES.one(account._id)}/reauthorize`);
110
+ account.oxyTaskState = 'active';
111
+ } catch {
112
+ /* Remains typed inactive; the next verified visit may retry. */
113
+ }
114
+ }),
115
+ );
116
+ return data;
117
+ },
118
+ enabled: isAuthenticated,
119
+ });
120
+ }
121
+
122
+ /**
123
+ * The code of an account being connected, refreshed while it waits (WhatsApp rotates its code
124
+ * every few seconds; Telegram's link is renewed when it expires, and is gone once Telegram knows
125
+ * who the person is). It stops once the session leaves `qr-pending`, and the list is re-read then,
126
+ * so the account shows as it is.
127
+ */
128
+ export function useConnectedAccountQr(link: GemieAccountLink | null) {
129
+ const api = useGemieApi();
130
+ const queryClient = useQueryClient();
131
+ const accountId = link?.accountId ?? '';
132
+ return useQuery({
133
+ queryKey: gemieQueryKeys.accounts.qr(accountId),
134
+ queryFn: async (): Promise<{ status: GemieAccountStatus; qr: string | null }> => {
135
+ const { data } = await api.get<{ status: GemieAccountStatus; qr: string | null }>(
136
+ `${ACCOUNT_ROUTES.one(accountId)}/qr`,
137
+ );
138
+ if (data.status !== 'qr-pending') {
139
+ await queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
140
+ }
141
+ return data;
142
+ },
143
+ enabled: link !== null,
144
+ initialData: link ? { status: 'qr-pending' as const, qr: link.qr } : undefined,
145
+ initialDataUpdatedAt: 0,
146
+ refetchInterval: (query) => (query.state.data?.status === 'qr-pending' ? 4000 : false),
147
+ });
148
+ }
149
+
150
+ /** An account's recent chats, read while the person chooses which ones it answers. */
151
+ export function useConnectedAccountChats(accountId: string) {
152
+ const api = useGemieApi();
153
+ return useQuery({
154
+ queryKey: gemieQueryKeys.accounts.chats(accountId),
155
+ queryFn: async (): Promise<GemieAccountChat[]> => {
156
+ try {
157
+ const { data } = await api.get<{ chats: GemieAccountChat[] }>(
158
+ `${ACCOUNT_ROUTES.one(accountId)}/chats`,
159
+ );
160
+ return data.chats;
161
+ } catch (error) {
162
+ if (errorStatus(error) === 404) return [];
163
+ throw error;
164
+ }
165
+ },
166
+ });
167
+ }
168
+
169
+ /** What can be changed of an account: who answers it, and whom that gemie answers. */
170
+ export interface ConnectedAccountPatch {
171
+ /** The gemie that answers it (granted it on the way), or `null` for none. */
172
+ answeringGemieId?: string | null;
173
+ replies?: GemieAccountReplies;
174
+ replyChatIds?: string[];
175
+ groupReplies?: GemieAccountGroupReplies;
176
+ }
177
+
178
+ /**
179
+ * Connecting, granting, who answers, and removing (its session ends and its task is revoked).
180
+ * Every write re-reads the list, so each screen that shows an account shows it as it now is.
181
+ */
182
+ export function useConnectedAccountMutations() {
183
+ const api = useGemieApi();
184
+ const queryClient = useQueryClient();
185
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
186
+
187
+ const connect = useMutation({
188
+ mutationFn: async (platform: GemieAccountPlatform): Promise<GemieAccountLink> => {
189
+ const { data } = await api.post<GemieAccountLink>(ACCOUNT_ROUTES.all, { platform });
190
+ return data;
191
+ },
192
+ onSuccess: invalidate,
193
+ });
194
+
195
+ const update = useMutation({
196
+ mutationFn: async ({ accountId, ...patch }: ConnectedAccountPatch & { accountId: string }) => {
197
+ await api.patch(ACCOUNT_ROUTES.one(accountId), patch);
198
+ },
199
+ onSuccess: invalidate,
200
+ });
201
+
202
+ const grant = useMutation({
203
+ mutationFn: async (input: { accountId: string; gemieId: string; granted: boolean }) => {
204
+ const path = ACCOUNT_ROUTES.grant(input.accountId, input.gemieId);
205
+ await (input.granted ? api.put(path) : api.delete(path));
206
+ },
207
+ onSuccess: invalidate,
208
+ });
209
+
210
+ const remove = useMutation({
211
+ mutationFn: async (accountId: string) => {
212
+ await api.delete(ACCOUNT_ROUTES.one(accountId));
213
+ },
214
+ onSuccess: invalidate,
215
+ });
216
+
217
+ return { connect, update, grant, remove };
218
+ }
@@ -22,15 +22,14 @@ export const gemieQueryKeys = {
22
22
  ['conversations', { agentId: filter.agentId, app: filter.app }] as const,
23
23
  },
24
24
  /**
25
- * A gemie's connected accounts (ADR 0035): the caller's accounts on it, the code of one being
26
- * linked and an account's chats. Their own roots, never persisted: phone numbers and a live code
27
- * stay in memory.
25
+ * The person's connected accounts (ADR 0035 as amended): the list with its grants, the code of
26
+ * one being connected and an account's chats. Their own roots, never persisted: phone numbers and
27
+ * a live code stay in memory.
28
28
  */
29
29
  accounts: {
30
- all: (gemieId: string) => ['gemie-accounts', gemieId] as const,
31
- qr: (gemieId: string, accountId: string) => ['gemie-account-qr', gemieId, accountId] as const,
32
- chats: (gemieId: string, accountId: string) =>
33
- ['gemie-account-chats', gemieId, accountId] as const,
30
+ all: ['connected-accounts'] as const,
31
+ qr: (accountId: string) => ['connected-account-qr', accountId] as const,
32
+ chats: (accountId: string) => ['connected-account-chats', accountId] as const,
34
33
  },
35
34
  /** An agent the chat is opened on: its profile and the state of its feature gates. */
36
35
  agents: {
@@ -78,8 +78,18 @@ export const AGENT_ROUTES = {
78
78
  threadSearch: (thread: GemieThreadAddress) => `${threadPath(thread)}/search`,
79
79
  /** What a run of an agent has done so far, to hydrate the live feed. */
80
80
  sessionStatus: (sessionId: string) => `/agents/sessions/${sessionId}/status`,
81
- /** The caller's WhatsApp and Telegram accounts linked to a gemie (ADR 0035), and one of them. */
82
- accounts: (gemieId: string) => `/agents/${encodeURIComponent(gemieId)}/accounts`,
83
- account: (gemieId: string, accountId: string) =>
84
- `/agents/${encodeURIComponent(gemieId)}/accounts/${encodeURIComponent(accountId)}`,
81
+ } as const;
82
+
83
+ /**
84
+ * The caller's connected WhatsApp and Telegram accounts (ADR 0035 as amended): theirs, connected
85
+ * once, and granted to the gemies that may use them.
86
+ */
87
+ export const ACCOUNT_ROUTES = {
88
+ /** Every account, with its grants, the gemies to grant and the platforms; `POST` connects one. */
89
+ all: '/me/accounts',
90
+ /** One account: `PATCH` its answering gemie and replies, `DELETE` it. */
91
+ one: (accountId: string) => `/me/accounts/${encodeURIComponent(accountId)}`,
92
+ /** A gemie's grant of one account: `PUT` grants it, `DELETE` revokes it. */
93
+ grant: (accountId: string, gemieId: string) =>
94
+ `/me/accounts/${encodeURIComponent(accountId)}/gemies/${encodeURIComponent(gemieId)}`,
85
95
  } as const;