-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAdminPanel.tsx
More file actions
558 lines (538 loc) · 16.3 KB
/
AdminPanel.tsx
File metadata and controls
558 lines (538 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
import React, { useState, useEffect, useMemo } from "react";
import {
Button,
Checkbox,
HTMLTable,
Alert,
Intent,
Label,
MenuItem,
Spinner,
Tab,
TabId,
Tabs,
} from "@blueprintjs/core";
import Description from "roamjs-components/components/Description";
import { Select } from "@blueprintjs/select";
import { setSetting } from "~/utils/extensionSettings";
import {
getFeatureFlag,
setFeatureFlag,
} from "~/components/settings/utils/accessors";
import {
getSupabaseContext,
getLoggedInClient,
SupabaseContext,
} from "~/utils/supabaseContext";
import {
getConcepts,
getSchemaConcepts,
nodeSchemaSignature,
type NodeSignature,
type PConceptFull,
} from "@repo/database/lib/queries";
import migrateRelations from "~/utils/migrateRelations";
import { countReifiedRelations } from "~/utils/createReifiedBlock";
import type { DGSupabaseClient } from "@repo/database/lib/client";
import internalError from "~/utils/internalError";
import SuggestiveModeSettings from "./SuggestiveModeSettings";
import discourseConfigRef from "~/utils/discourseConfigRef";
import refreshConfigTree from "~/utils/refreshConfigTree";
import createBlock from "roamjs-components/writes/createBlock";
import deleteBlock from "roamjs-components/writes/deleteBlock";
import { USE_REIFIED_RELATIONS } from "~/data/userSettings";
import posthog from "posthog-js";
import { FeatureFlagPanel } from "./components/BlockPropSettingPanels";
import getPageUidByPageTitle from "roamjs-components/queries/getPageUidByPageTitle";
import { getUidAndBooleanSetting } from "~/utils/getExportSettings";
import { DISCOURSE_CONFIG_PAGE_TITLE } from "~/data/constants";
const NodeRow = ({ node }: { node: PConceptFull }) => {
return (
<tr>
<td>{node.name}</td>
<td>{node.created}</td>
<td>{node.last_modified}</td>
<td>
<pre>{JSON.stringify({ ...node, Content: null }, null, 2)}</pre>
</td>
<td>
<pre>
{JSON.stringify({ ...node.Content, Document: null }, null, 2)}
</pre>
<span
data-link-title={node.Content?.text}
data-link-uid={node.Content?.source_local_id}
>
<span className="rm-page-ref__brackets">[[</span>
<span
className="rm-page-ref rm-page-ref--link"
onClick={(event) => {
void (async (event) => {
if (event.shiftKey) {
if (node.Content?.source_local_id) {
await window.roamAlphaAPI.ui.rightSidebar.addWindow({
window: {
// @ts-expect-error TODO: fix this
"block-uid": node.Content.source_local_id,
type: "outline",
},
});
}
} else if (node.Content?.Document?.source_local_id) {
await window.roamAlphaAPI.ui.mainWindow.openPage({
page: {
uid: node.Content.Document.source_local_id,
},
});
}
})(event);
}}
>
{node.Content?.text}
</span>
<span className="rm-page-ref__brackets">]]</span>
</span>
</td>
<td>
<pre>{JSON.stringify(node.Content?.Document, null, 2)}</pre>
</td>
</tr>
);
};
const NodeTable = ({ nodes }: { nodes: PConceptFull[] }) => {
return (
<HTMLTable>
<thead>
<tr>
<th>Name</th>
<th>Created</th>
<th>Last Modified</th>
<th>Concept</th>
<th>Content</th>
<th>Document</th>
</tr>
</thead>
<tbody>
{nodes.map((node: PConceptFull) => (
<NodeRow node={node} key={node.id} />
))}
</tbody>
</HTMLTable>
);
};
const NodeListTab = (): React.ReactElement => {
const [context, setContext] = useState<SupabaseContext | null>(null);
const [supabase, setSupabase] = useState<DGSupabaseClient | null>(null);
const [schemas, setSchemas] = useState<NodeSignature[]>([]);
const [showingSchema, setShowingSchema] =
useState<NodeSignature>(nodeSchemaSignature);
const [nodes, setNodes] = useState<PConceptFull[]>([]);
const [loading, setLoading] = useState(true);
const [loadingNodes, setLoadingNodes] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let ignore = false;
void (async () => {
try {
if (!ignore) {
setContext(await getSupabaseContext());
}
// Ask for logged-in client _after_ the context
if (!ignore) {
setSupabase(await getLoggedInClient());
}
} catch (e) {
setError((e as Error).message);
console.error("AdminPanel init failed", e);
} finally {
setLoading(false);
}
})();
return () => {
ignore = true;
};
}, []);
useEffect(() => {
let ignore = false;
void (async () => {
if (!ignore && supabase !== null && context !== null) {
try {
setSchemas(await getSchemaConcepts(supabase, context.spaceId));
} catch (e) {
setError((e as Error).message);
console.error("getSchemaConcepts failed", e);
} finally {
setLoading(false);
}
}
})();
return () => {
ignore = true;
};
}, [supabase, context]);
useEffect(() => {
let ignore = false;
void (async () => {
if (
!ignore &&
schemas !== null &&
supabase !== null &&
context !== null
) {
const spaceId = context.spaceId;
try {
setLoadingNodes(true);
setNodes(
await getConcepts({
supabase,
spaceId,
scope: {
schemas:
showingSchema.sourceLocalId ===
nodeSchemaSignature.sourceLocalId,
type: "nodes",
ofTypes: [showingSchema.sourceLocalId],
},
}),
);
} catch (e) {
setError((e as Error).message);
console.error("getConcepts failed", e);
} finally {
setLoadingNodes(false);
}
}
})();
return () => {
ignore = true;
};
}, [schemas, showingSchema, context, supabase]);
if (loading) {
return (
<div className="p-3">
<Spinner />
<span className="mx-2">Loading admin data…</span>
</div>
);
}
if (error) {
return <p className="text-red-700">{error}</p>;
}
return (
<>
<p>
Context:{" "}
<code>{JSON.stringify({ ...context, spacePassword: "****" })}</code>
</p>
{schemas.length > 0 ? (
<>
<Label>
Display:
<div className="mx-2 inline-block">
<Select
items={schemas}
onItemSelect={(choice) => {
setShowingSchema(choice);
}}
itemRenderer={(node, { handleClick, modifiers }) => (
<MenuItem
active={modifiers.active}
key={node.sourceLocalId}
label={node.name}
onClick={handleClick}
text={node.name}
/>
)}
>
<Button text={showingSchema.name} />
</Select>
</div>
</Label>
<div>{loadingNodes ? <Spinner /> : <NodeTable nodes={nodes} />}</div>
</>
) : (
<p>No node schemas found</p>
)}
</>
);
};
const MigrationTab = (): React.ReactElement => {
let initial = true;
const [useMigrationResults, setMigrationResults] = useState<string>("");
const [useOngoing, setOngoing] = useState<boolean>(false);
const [useDryRun, setDryRun] = useState<boolean>(false);
const enabled = getFeatureFlag("Reified relation triples");
const doMigrateRelations = async () => {
setOngoing(true);
try {
posthog.capture("Reified Relations: Migration Started", {
dryRun: useDryRun,
});
const before = await countReifiedRelations();
const numProcessed = await migrateRelations(useDryRun);
const after = await countReifiedRelations();
if (after - before < numProcessed)
setMigrationResults(
`${after - before} new relations created out of ${numProcessed} distinct relations processed`,
);
else setMigrationResults(`${numProcessed} new relations created`);
posthog.capture("Reified Relations: Migration Completed", {
dryRun: useDryRun,
processed: numProcessed,
before,
after,
created: after - before,
});
} catch (e) {
console.error("Relation migration failed", e);
setMigrationResults(
`Migration failed: ${(e as Error).message ?? "see console for details"}`,
);
posthog.capture("Reified Relations: Migration Failed", {
dryRun: useDryRun,
error: (e as Error).message ?? "unknown error",
});
} finally {
setOngoing(false);
}
};
useEffect(() => {
void (async () => {
if (initial) {
const numRelations = await countReifiedRelations();
setMigrationResults(
numRelations > 0
? `${numRelations} already migrated`
: "No migrated relations",
);
// eslint-disable-next-line react-hooks/exhaustive-deps
initial = false;
}
})();
return () => {
initial;
};
}, []);
return (
<>
<p>
<Button
className="p-4"
onClick={() => {
void doMigrateRelations();
}}
disabled={!enabled || useOngoing}
text="Migrate all relations"
></Button>
<Checkbox
className="left-6 inline-block"
defaultChecked={useDryRun}
onChange={(e) => {
const target = e.target as HTMLInputElement;
setDryRun(target.checked);
}}
labelElement={<>Dry run</>}
/>
</p>
{useOngoing ? (
<Spinner />
) : (
<p id="migrationResultsLabel">{useMigrationResults}</p>
)}
</>
);
};
const FeatureFlagsTab = (): React.ReactElement => {
const [useReifiedRelations, setUseReifiedRelations] = useState<boolean>(
getFeatureFlag("Reified relation triples"),
);
const legacySuggestiveModeMeta = useMemo(() => {
refreshConfigTree();
return {
settingsUid: getPageUidByPageTitle(DISCOURSE_CONFIG_PAGE_TITLE),
suggestiveModeEnabledUid: getUidAndBooleanSetting({
tree: discourseConfigRef.tree,
text: "(BETA) Suggestive Mode Enabled",
}).uid,
};
}, []);
const [suggestiveModeEnabled, setSuggestiveModeEnabled] = useState(
getFeatureFlag("Suggestive mode enabled"),
);
const [suggestiveModeUid, setSuggestiveModeUid] = useState(
legacySuggestiveModeMeta.suggestiveModeEnabledUid,
);
const [isAlertOpen, setIsAlertOpen] = useState(false);
const [isInstructionOpen, setIsInstructionOpen] = useState(false);
return (
<div className="flex flex-col gap-4 p-4">
<Checkbox
checked={suggestiveModeEnabled}
onChange={(e) => {
const checked = (e.target as HTMLInputElement).checked;
if (checked) {
setIsAlertOpen(true);
} else {
if (suggestiveModeUid) {
void deleteBlock(suggestiveModeUid);
setSuggestiveModeUid(undefined);
}
setSuggestiveModeEnabled(false);
setFeatureFlag("Suggestive mode enabled", false);
}
}}
labelElement={
<>
(BETA) Suggestive mode enabled
<Description
description={
"Whether or not to enable the suggestive mode, if this is first time enabling it, you will need to generate and upload all node embeddings to supabase. Go to Suggestive Mode -> Sync Config -> Click on 'Generate & Upload All Node Embeddings'"
}
/>
</>
}
/>
<Alert
isOpen={isAlertOpen}
onConfirm={() => {
void createBlock({
parentUid: legacySuggestiveModeMeta.settingsUid,
node: { text: "(BETA) Suggestive Mode Enabled" },
}).then((uid) => {
setSuggestiveModeUid(uid);
setSuggestiveModeEnabled(true);
setFeatureFlag("Suggestive mode enabled", true);
setIsAlertOpen(false);
setIsInstructionOpen(true);
});
}}
onCancel={() => setIsAlertOpen(false)}
canEscapeKeyCancel={true}
canOutsideClickCancel={true}
intent={Intent.PRIMARY}
confirmButtonText="Enable"
cancelButtonText="Cancel"
>
<p>
Enabling Suggestive Mode will send your data (nodes) to our servers
and OpenAI servers to generate embeddings and suggestions.
</p>
<p>Are you sure you want to proceed?</p>
</Alert>
{/* TODO(ENG-1484): Add pull watcher reactivity so toggling suggestive mode
starts/stops sync and shows the tab without requiring a reload. */}
<Alert
isOpen={isInstructionOpen}
onConfirm={() => window.location.reload()}
onCancel={() => setIsInstructionOpen(false)}
confirmButtonText="Reload Graph"
cancelButtonText="Later"
intent={Intent.PRIMARY}
>
<p>
If this is the first time enabling it, you will need to generate and
upload all node embeddings to supabase.
</p>
<p>
Please reload the graph to see the new 'Suggestive Mode'
tab.
</p>
<p>
Then go to Suggestive Mode{" "}
{"-> Sync Config -> Click on 'Generate & Upload All Node Embeddings'"}
</p>
</Alert>
<Checkbox
defaultChecked={useReifiedRelations}
onChange={(e) => {
const target = e.target as HTMLInputElement;
setUseReifiedRelations(target.checked);
void setSetting(USE_REIFIED_RELATIONS, target.checked).catch(
() => undefined,
);
setFeatureFlag("Reified relation triples", target.checked);
posthog.capture("Reified Relations: Toggled", {
enabled: target.checked,
});
}}
labelElement={
<>
Reified relation triples
<Description
description={
"When ON, relations are read/written as reifiedRelationUid in [[roam/js/discourse-graph/relations]]."
}
/>
</>
}
/>
<FeatureFlagPanel
title="Use new settings store"
description="When enabled, accessor getters read from block props instead of the old system. Surfaces dual-write gaps during development."
featureKey="Use new settings store"
/>
<Button
className="w-96"
icon="send-message"
onClick={() => {
console.log("sending error email");
internalError({
error: new Error("test"),
type: "Test",
sendEmail: true,
forceSendInDev: true,
});
}}
>
Send Error Email
</Button>
</div>
);
};
const AdminPanel = (): React.ReactElement => {
const [selectedTabId, setSelectedTabId] = useState<TabId>("admin");
return (
<Tabs
onChange={(id) => setSelectedTabId(id)}
selectedTabId={selectedTabId}
renderActiveTabPanelOnly={true}
>
<Tab
id="admin"
title="Admin"
panel={
<div className="flex flex-col gap-4 p-1">
<FeatureFlagsTab />
</div>
}
/>
<Tab
id="migration"
title="Migration"
panel={
<div className="flex flex-col gap-4 p-1">
<MigrationTab />
</div>
}
/>
<Tab
id="node-list"
title="Node list"
panel={
<div className="flex flex-col gap-4 p-1">
<NodeListTab />
</div>
}
/>
{getFeatureFlag("Suggestive mode enabled") && (
<Tab
id="suggestive-mode-settings"
title="Suggestive mode"
className="overflow-y-auto"
panel={<SuggestiveModeSettings />}
/>
)}
</Tabs>
);
};
export default AdminPanel;