@gemies/sdk 9.1.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 +65 -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 +118 -0
- package/src/components/thread/ChatBubble.tsx +66 -25
- package/src/components/thread/GemieThread.tsx +36 -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/copy-en.ts +7 -0
- package/src/lib/copy-es.ts +7 -0
- 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/approvals.ts +99 -0
- package/src/runtime/collections.ts +35 -136
- package/src/runtime/config.tsx +10 -0
- 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 +74 -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 +47 -31
- package/src/runtime/use-conversation-thread.ts +44 -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
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A coding CLI asking its own user for permission, in the conversation (Gemies ADR 0043 §5).
|
|
3
|
+
*
|
|
4
|
+
* During a turn with an external agent (Claude Code on the person's computer), the CLI may stop and
|
|
5
|
+
* ask whether it can run something there. The turn waits; the stream carries two named events:
|
|
6
|
+
*
|
|
7
|
+
* `alia.cli_permission_request` the CLI asks: which tool, on what.
|
|
8
|
+
* `alia.cli_permission_resolved` the answer was given, or the time ran out.
|
|
9
|
+
*
|
|
10
|
+
* This is the third-party CLI's prompt to the person who runs it, on their own machine. It is not
|
|
11
|
+
* an Oxy grant: nothing here reaches Oxy, and the SDK does not know the endpoint that carries the
|
|
12
|
+
* answer — the host does (`GemieRuntimeHost.onApprovalDecision`).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export type ApprovalDecision = 'allow' | 'deny';
|
|
16
|
+
export type ApprovalOutcome = ApprovalDecision | 'expired';
|
|
17
|
+
|
|
18
|
+
export interface ApprovalRequest {
|
|
19
|
+
readonly requestId: string;
|
|
20
|
+
readonly agentId: string;
|
|
21
|
+
/** The CLI's tool: `Bash`, `Edit`, … */
|
|
22
|
+
readonly tool: string;
|
|
23
|
+
/** What it would act on (a command, a path), as the daemon reported it. */
|
|
24
|
+
readonly summary?: string;
|
|
25
|
+
/** ISO time after which the CLI is told no. */
|
|
26
|
+
readonly expiresAt: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A request and where it stands: waiting for the person, or how it ended. */
|
|
30
|
+
export interface ApprovalEntry extends ApprovalRequest {
|
|
31
|
+
readonly outcome: 'pending' | ApprovalOutcome;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const text = (value: unknown, max: number): string | undefined =>
|
|
35
|
+
typeof value === 'string' && value !== '' ? value.slice(0, max) : undefined;
|
|
36
|
+
|
|
37
|
+
/** The request in an `alia.cli_permission_request` frame, or `null` when the frame is not one. */
|
|
38
|
+
export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
|
|
39
|
+
if (data === null || typeof data !== 'object') return null;
|
|
40
|
+
const d = data as Record<string, unknown>;
|
|
41
|
+
const requestId = text(d.requestId, 100);
|
|
42
|
+
const agentId = text(d.agentId, 100);
|
|
43
|
+
const tool = text(d.tool, 80);
|
|
44
|
+
const expiresAt = text(d.expiresAt, 40);
|
|
45
|
+
if (!requestId || !agentId || !tool || !expiresAt || Number.isNaN(Date.parse(expiresAt))) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const summary = text(d.summary, 200);
|
|
49
|
+
return { requestId, agentId, tool, ...(summary ? { summary } : {}), expiresAt };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The answer in an `alia.cli_permission_resolved` frame, or `null` when the frame is not one. */
|
|
53
|
+
export function parseApprovalResolved(
|
|
54
|
+
data: unknown,
|
|
55
|
+
): { requestId: string; outcome: ApprovalOutcome } | null {
|
|
56
|
+
if (data === null || typeof data !== 'object') return null;
|
|
57
|
+
const d = data as Record<string, unknown>;
|
|
58
|
+
const requestId = text(d.requestId, 100);
|
|
59
|
+
if (!requestId) return null;
|
|
60
|
+
const decision = d.decision;
|
|
61
|
+
if (decision !== 'allow' && decision !== 'deny' && decision !== 'expired') return null;
|
|
62
|
+
return { requestId, outcome: decision };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A request arrived: waiting, once. A repeat of one already here changes nothing. */
|
|
66
|
+
export function withApprovalRequest(
|
|
67
|
+
list: readonly ApprovalEntry[],
|
|
68
|
+
request: ApprovalRequest,
|
|
69
|
+
): ApprovalEntry[] {
|
|
70
|
+
if (list.some((entry) => entry.requestId === request.requestId)) return [...list];
|
|
71
|
+
return [...list, { ...request, outcome: 'pending' }];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A request was answered. The first answer stands; an unknown request is ignored. */
|
|
75
|
+
export function withApprovalOutcome(
|
|
76
|
+
list: readonly ApprovalEntry[],
|
|
77
|
+
requestId: string,
|
|
78
|
+
outcome: ApprovalOutcome,
|
|
79
|
+
): ApprovalEntry[] {
|
|
80
|
+
return list.map((entry) =>
|
|
81
|
+
entry.requestId === requestId && entry.outcome === 'pending' ? { ...entry, outcome } : entry,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* What a host's `onApprovalDecision` rejects with when the question is no longer open (answered
|
|
87
|
+
* elsewhere, or its time ran out): the card then reads "Timed out" instead of offering a retry.
|
|
88
|
+
*/
|
|
89
|
+
export class ApprovalExpiredError extends Error {
|
|
90
|
+
constructor() {
|
|
91
|
+
super('The approval request is no longer open');
|
|
92
|
+
this.name = 'ApprovalExpiredError';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** What a new turn keeps of the last one's approvals: the ones still waiting. */
|
|
97
|
+
export function stillPending(list: readonly ApprovalEntry[]): ApprovalEntry[] {
|
|
98
|
+
return list.filter((entry) => entry.outcome === 'pending');
|
|
99
|
+
}
|
|
@@ -1,25 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* How a person files their conversations
|
|
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 {
|
|
7
|
+
import { skip, useStore, withStore } from '@oxy.so/bloom-data';
|
|
11
8
|
import { useOxy } from '@oxy.so/services/ui/client';
|
|
12
|
-
import {
|
|
13
|
-
import type
|
|
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
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
|
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
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
-
|
|
164
|
-
|
|
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
|
-
|
|
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,
|
|
83
|
+
}, [api, store]);
|
|
185
84
|
}
|
package/src/runtime/config.tsx
CHANGED
|
@@ -104,6 +104,16 @@ export interface GemieRuntimeHost {
|
|
|
104
104
|
onFeatureLocked?: (key: string) => void;
|
|
105
105
|
/** A delegated agent started a run of its own for this turn. */
|
|
106
106
|
onAgentTurn?: (turn: AgentRun & { conversationId: string | null }) => void;
|
|
107
|
+
/**
|
|
108
|
+
* The person answered a coding CLI that asked for permission to run something on their own
|
|
109
|
+
* computer (`alia.cli_permission_request`, ADR 0043). The host carries the answer to Gemies; the
|
|
110
|
+
* promise rejects when it could not be sent. Omitted, the request is shown with no way to answer.
|
|
111
|
+
*/
|
|
112
|
+
onApprovalDecision?: (
|
|
113
|
+
requestId: string,
|
|
114
|
+
agentId: string,
|
|
115
|
+
decision: 'allow' | 'deny',
|
|
116
|
+
) => Promise<void>;
|
|
107
117
|
/** The agent's row in the host's list, ahead of the server: your line, then her answer. */
|
|
108
118
|
onTurnPreview?: (agentId: string | null | undefined, text: string) => void;
|
|
109
119
|
/**
|
|
@@ -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 {
|
|
3
|
-
import {
|
|
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
|
|
92
|
-
return
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
|
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(
|
|
171
|
+
export function useConnectedAccountQr(
|
|
172
|
+
link: GemieAccountLink | null,
|
|
173
|
+
): RecordView<{ status: GemieAccountStatus; qr: string | null }> {
|
|
109
174
|
const api = useGemieApi();
|
|
110
|
-
const
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
|
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
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
}
|