Repository navigation
Expand file tree
/
Copy pathsession-store.ts
More file actions
1637 lines (1524 loc) · 70.5 KB
/
Copy pathsession-store.ts
File metadata and controls
1637 lines (1524 loc) · 70.5 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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { resilientLocalStorage } from '@/lib/stores/resilient-local-storage';
import type { Node, Edge } from 'reactflow';
import type { GenerateOutput, GenerateInput } from '../ai/schemas/generate';
import type { AttackOutput, AttackInput } from '../ai/schemas/attack';
import type { BrainstormOutput, BrainstormInput } from '../ai/schemas/brainstorm';
import type { FactoidsOutput, FactoidsInput } from '../ai/schemas/factoids';
import type { AskOutput } from '../ai/schemas/ask';
import { supabase } from '@/lib/supabase/client';
import { restoredSessionsBlocked } from '@/lib/supabase/session-expiry';
import { currentUserId } from '@/lib/supabase/current-user';
import i18n from '@/i18n';
import { findSavedPage, normalizeSourceUrl, savedSourceUrl } from '@/lib/source-url';
import { activeDebateId, useDebateStore, type DebateSide } from './debate-store';
interface Message {
id: string;
role: 'user' | 'assistant';
content: string;
timestamp: number;
output?: AskOutput | GenerateOutput | AttackOutput | BrainstormOutput | FactoidsOutput;
}
interface StreamingAskMessage {
id: string;
role: 'assistant';
content: string;
timestamp: number;
isStreaming: true;
}
/** Auditable provenance for sources captured from AI research or imports. */
export interface SourceSemanticMetadata {
relevance: number;
importance: 0 | 1 | 2 | 3;
strength: 0 | 1 | 2 | 3;
evaluatedAt: string;
useCount: number;
caseUseCount: number;
lastUsedAt?: string;
lastUsedInCase?: boolean;
}
export interface SourceProvenance {
url?: string;
sourceType?: string;
qualityScore?: number;
qualityLabel?: 'strong' | 'moderate' | 'weak';
query?: string;
/** Which flow captured this source, e.g. 'generate' | 'brainstorm' | 'ask' | 'factoids'. */
capturedVia?: string;
semantic?: SourceSemanticMetadata;
}
export interface SourceAssessmentUpdate {
key: string;
id?: string;
relevance: number;
importance: 0 | 1 | 2 | 3;
strength: 0 | 1 | 2 | 3;
evaluatedAt: string;
retained: boolean;
usedInCase?: boolean;
}
export interface Source {
id: string;
title: string;
content: string;
type: 'url' | 'file' | 'text';
origin?: string;
folder?: string;
metadata?: SourceProvenance;
/** The one debate this source belongs to; null only for unsorted legacy sources. */
debateId?: string | null;
createdAt: number;
isActive: boolean;
}
export interface SavedItem<T> {
id: string;
data: T;
createdAt: number;
title: string;
/** Null for one-off work and unsorted legacy material. */
debateId?: string | null;
side?: DebateSide | null;
}
/** Tool results that DebateLab records automatically inside a debate. */
export type ResultKind = 'case' | 'attack' | 'brainstorm' | 'factoids' | 'crossfire';
/** Everything that can later be attached from one-off or Unsorted into a debate. */
export type AttachKind = ResultKind | 'chat' | 'flowchart' | 'source';
const RESULT_TABLES = {
case: 'cases',
attack: 'attacks',
brainstorm: 'brainstorms',
factoids: 'factoids',
crossfire: 'crossfires',
} as const;
const RESULT_LISTS = {
case: 'savedCases',
attack: 'savedAttacks',
brainstorm: 'savedBrainstorms',
factoids: 'savedFactoids',
crossfire: 'savedCrossfires',
} as const;
const ATTACH_LISTS = { ...RESULT_LISTS, chat: 'savedChats', flowchart: 'savedFlowcharts', source: 'sourceLibrary' } as const;
export interface RecordResultInput {
title: string;
input: unknown;
output: unknown;
debateId: string;
side: DebateSide;
}
export interface FlowchartData {
nodes: Node[]; // Keeping any for now to avoid ReactFlow dependency here, but could be stricter
edges: Edge[];
}
export interface SessionState {
/** Account these persisted drafts belong to. Null until sign-in binds them. */
ownerUserId: string | null;
generateResult: GenerateOutput | null;
generateLoading: boolean;
/** The Generate section being regenerated; kept here so it survives leaving the page. */
generateRegeneratingSection: string | null;
attackResult: AttackOutput | null;
attackLoading: boolean;
brainstormResult: BrainstormOutput | null;
brainstormLoading: boolean;
factoidsResult: FactoidsOutput | null;
factoidsLoading: boolean;
askMessages: Message[];
askLoading: boolean;
askStreamingAssistant: StreamingAskMessage | null;
/** Server chat that the current Ask conversation is being recorded into. */
askChatId: string | null;
/** Debate that `askChatId` belongs to; null for an unsorted chat. */
askChatDebateId: string | null;
askPersistedCount: number;
savedCases: SavedItem<GenerateOutput>[];
savedAttacks: SavedItem<AttackOutput>[];
savedBrainstorms: SavedItem<BrainstormOutput>[];
savedFactoids: SavedItem<FactoidsOutput>[];
savedChats: SavedItem<Message[]>[];
savedFlowcharts: SavedItem<FlowchartData>[];
savedCrossfires: SavedItem<unknown>[];
autosavedCases: SavedItem<GenerateOutput>[];
autosavedAttacks: SavedItem<AttackOutput>[];
autosavedBrainstorms: SavedItem<BrainstormOutput>[];
autosavedFactoids: SavedItem<FactoidsOutput>[];
sourceFolders: string[];
sourceLibrary: Source[];
// Persisted Form State
generateForm: Partial<GenerateInput>;
attackForm: Partial<AttackInput>;
brainstormForm: Partial<BrainstormInput>;
factoidsForm: Partial<FactoidsInput>;
setGenerateForm: (data: Partial<GenerateInput>) => void;
setAttackForm: (data: Partial<AttackInput>) => void;
setBrainstormForm: (data: Partial<BrainstormInput>) => void;
setFactoidsForm: (data: Partial<FactoidsInput>) => void;
setGenerateResult: (result: GenerateOutput | null) => void;
/**
* Debate the current Generate result belongs to. Null is one-off work.
* Undefined means a result restored before this was recorded.
*/
generateResultDebateId: string | null | undefined;
setGenerateResultDebateId: (debateId: string | null) => void;
setGenerateLoading: (loading: boolean) => void;
setGenerateRegeneratingSection: (section: string | null) => void;
saveCurrentCase: (title: string) => Promise<void>;
deleteSavedCase: (id: string) => Promise<void>;
loadSavedCase: (id: string) => void;
setAttackResult: (result: AttackOutput | null) => void;
setAttackLoading: (loading: boolean) => void;
saveCurrentAttack: (title: string) => Promise<void>;
loadSavedAttack: (id: string) => void;
setBrainstormResult: (result: BrainstormOutput | null) => void;
setBrainstormLoading: (loading: boolean) => void;
saveCurrentBrainstorm: (title: string) => Promise<void>;
loadSavedBrainstorm: (id: string) => void;
setFactoidsResult: (result: FactoidsOutput | null) => void;
setFactoidsLoading: (loading: boolean) => void;
saveCurrentFactoids: (title: string) => Promise<void>;
loadSavedFactoids: (id: string) => void;
/** Pass the streaming bubble's id so the stored reply keeps its identity and doesn't remount. */
addAskMessage: (message: Omit<Message, 'id' | 'timestamp'> & { id?: string }) => void;
setAskLoading: (loading: boolean) => void;
setAskStreamingAssistant: (message: StreamingAskMessage | null) => void;
appendAskStreamingDelta: (text: string) => void;
clearAskMessages: () => void;
saveCurrentChat: (title: string) => Promise<void>;
loadSavedChat: (id: string) => void;
saveFlowchart: (title: string, data: FlowchartData, debateId?: string | null) => Promise<void>;
recordResult: (kind: ResultKind, input: RecordResultInput) => Promise<string>;
updateRecordedResult: (kind: ResultKind, id: string, output: unknown) => Promise<void>;
deleteRecordedResult: (kind: ResultKind, id: string) => Promise<void>;
attachItem: (kind: AttachKind, id: string, debateId: string, side?: DebateSide) => Promise<void>;
/** Records new Ask messages: into the loaded chat, or a new chat in `debateId`. */
syncAskChat: (debateId: string | null) => Promise<void>;
deleteSavedFlowchart: (id: string) => Promise<void>;
/**
* Shows the source at once and saves it. `id` and `createdAt` are only for
* Undo, which puts a deleted source back exactly. Throws DuplicateSourceError
* when the debate already holds the same web page.
*/
addSource: (source: Omit<Source, 'id' | 'createdAt' | 'isActive'> & { isActive?: boolean; id?: string; createdAt?: number }) => Promise<void>;
createSourceFolder: (folder: string) => Promise<void>;
updateSource: (id: string, patch: Partial<Omit<Source, 'id' | 'createdAt'>>) => Promise<void>;
applySourceAssessments: (assessments: SourceAssessmentUpdate[]) => Promise<void>;
renameSourceFolder: (oldName: string, newName: string) => Promise<void>;
deleteSourceFolder: (name: string, mode: 'empty-only' | 'move-to-general') => Promise<void>;
setFolderActive: (folder: string, isActive: boolean) => Promise<void>;
removeSource: (id: string) => Promise<void>;
toggleSource: (id: string) => Promise<void>;
clearLibrary: () => Promise<void>;
hydrateFromServer: () => Promise<void>;
/**
* This page load's server hydration: `partial` when a saved-result list
* failed to load and may be missing results. Not persisted.
*/
serverHydration: 'pending' | 'partial' | 'complete';
clearAllData: () => Promise<void>;
resetLocalData: () => void;
/**
* Binds persisted drafts to the signed-in account. A different account, or
* drafts saved before accounts were recorded, is cleared first so one
* browser cannot show the previous person's work.
*/
prepareForUser: (userId: string) => void;
clearSession: () => void;
pendingFlowchartData: FlowchartData | null;
setPendingFlowchartData: (data: FlowchartData | null) => void;
}
const generateId = () => Math.random().toString(36).substring(2, 9);
const toTimestamp = (value: string | number) => {
if (typeof value === 'number') return value;
return new Date(value).getTime();
};
function mergeFormState<T extends Record<string, unknown>>(current: Partial<T>, partial: Partial<T>): Partial<T> {
const next: Record<string, unknown> = { ...current };
for (const [key, value] of Object.entries(partial)) {
const currentValue = next[key];
if (
value &&
typeof value === 'object' &&
!Array.isArray(value) &&
currentValue &&
typeof currentValue === 'object' &&
!Array.isArray(currentValue)
) {
next[key] = { ...currentValue, ...value };
} else {
next[key] = value;
}
}
return next as Partial<T>;
}
function settledData<T>(label: string, result: PromiseSettledResult<{ data?: T | null; error?: { message?: string } | null }>): T | null {
if (result.status === 'rejected') {
console.warn(`[SessionStore] Failed to hydrate ${label}:`, result.reason);
return null;
}
if (result.value.error) {
console.warn(`[SessionStore] Failed to hydrate ${label}:`, result.value.error.message || result.value.error);
return null;
}
return result.value.data ?? null;
}
function normalizeFolder(folder?: string | null) {
const trimmed = folder?.trim();
return trimmed || 'General';
}
/** Device-only work that must not cross accounts. Server lists reload after this. */
function sessionWorkForAccount(ownerUserId: string | null): Partial<SessionState> {
return {
ownerUserId,
serverHydration: 'pending',
savedCases: [],
savedAttacks: [],
savedBrainstorms: [],
savedFactoids: [],
savedChats: [],
savedFlowcharts: [],
savedCrossfires: [],
autosavedCases: [],
autosavedAttacks: [],
autosavedBrainstorms: [],
autosavedFactoids: [],
askChatId: null,
askChatDebateId: null,
askPersistedCount: 0,
sourceFolders: ['General'],
sourceLibrary: [],
generateResult: null,
attackResult: null,
brainstormResult: null,
factoidsResult: null,
askMessages: [],
askStreamingAssistant: null,
pendingFlowchartData: null,
generateForm: {},
generateResultDebateId: undefined,
attackForm: {},
brainstormForm: {},
factoidsForm: {},
};
}
/**
* Keeps a rehydrate that finishes after sign-in from putting another account's
* snapshot back. Drafts with no owner are kept only while nobody is bound yet;
* binding then clears them.
*/
export function mergePersistedSessionState(persistedState: unknown, currentState: SessionState): SessionState {
const saved = persistedState && typeof persistedState === 'object' ? persistedState as Partial<SessionState> : {};
const savedOwner = typeof saved.ownerUserId === 'string' ? saved.ownerUserId : null;
if (currentState.ownerUserId && savedOwner !== currentState.ownerUserId) return currentState;
return { ...currentState, ...saved, ownerUserId: savedOwner ?? currentState.ownerUserId };
}
function mergeSourceFolders(currentFolders: string[], sources: Source[] = []) {
return Array.from(new Set([
'General',
...currentFolders.map(normalizeFolder),
...sources.map((source) => normalizeFolder(source.folder)),
])).sort((a, b) => a.localeCompare(b));
}
async function getUserId() {
return await currentUserId();
}
function signInRequired(action: string): Error {
return new Error(`Sign in to ${action}`);
}
type EqQuery = {
eq: (column: string, value: unknown) => unknown;
};
async function applyUserScopedIdFilter(query: EqQuery, userId: string | null, id: string): Promise<unknown> {
if (userId) {
const scoped = query.eq('user_id', userId);
if (scoped && typeof (scoped as EqQuery).eq === 'function') {
return (scoped as EqQuery).eq('id', id);
}
}
return query.eq('id', id);
}
async function applyUserScopedColumnFilter(query: EqQuery, userId: string | null, column: string, value: string): Promise<unknown> {
if (userId) {
const scoped = query.eq('user_id', userId);
if (scoped && typeof (scoped as EqQuery).eq === 'function') {
return (scoped as EqQuery).eq(column, value);
}
}
return query.eq(column, value);
}
function throwOnWriteError(result: unknown, action: string): void {
if (!result || typeof result !== 'object' || !('error' in result)) return;
const error = (result as { error?: { message?: string } | null }).error;
if (error) throw new Error(`[SessionStore] Failed to ${action}: ${error.message || 'Unknown error'}`);
}
interface DebateColumns {
debate_id?: string | null;
side?: DebateSide | null;
}
interface SupabaseSavedRow<T> extends DebateColumns {
id: string;
title: string;
output: T;
created_at: string;
}
interface SupabaseFlowchartRow extends DebateColumns {
id: string;
title: string;
nodes: Node[];
edges: Edge[];
created_at: string;
}
interface SupabaseChatRow extends DebateColumns {
id: string;
title: string;
created_at: string;
}
interface SupabaseMessageRow {
id: string;
chat_id: string;
role: 'user' | 'assistant';
content: string;
output: AskOutput | GenerateOutput | AttackOutput | BrainstormOutput | FactoidsOutput | null;
created_at: string;
}
interface SupabaseSourceRow {
id: string;
title: string;
content: string;
type: 'url' | 'file' | 'text';
origin: string | null;
folder?: string | null;
is_active: boolean;
metadata?: unknown | null;
debate_id?: string | null;
created_at: string;
}
interface SupabaseSourceFolderRow {
id: string;
name: string;
created_at: string;
}
/** Thrown when a source would be saved without a debate to belong to. */
export class DebateRequiredError extends Error {
constructor() {
super('Select or create a debate before adding sources');
this.name = 'DebateRequiredError';
}
}
/** Thrown when the debate already has a source for the same web page. */
export class DuplicateSourceError extends Error {
constructor(readonly existingId: string) {
super('This page is already in the debate\'s Library');
this.name = 'DuplicateSourceError';
}
}
const PENDING_SOURCE_PREFIX = 'pending-';
/** Counts source switch writes, so a server reload can tell which ones it predates. */
let sourceWriteSeq = 0;
/** Writes to a source's switch still running, and the last value the server accepted. */
const sourceToggles = new Map<string, { latest: number; confirmed: boolean; chain: Promise<void> }>();
/** The newest switch value per source, kept so a reload that started earlier does not undo it. */
const lastSourceToggle = new Map<string, { value: boolean; seq: number }>();
interface SourceActiveWrite {
seq: number;
value: boolean;
entries: Array<[string, { latest: number; confirmed: boolean; chain: Promise<void> }]>;
done: Promise<void>;
}
/**
* Every write that changes whether sources are on (the switch, a folder's
* Activate or Deactivate, the editor's Save) joins each source's queue, so the
* server applies them in the order the student made them. Call it before
* showing the new value; finishSourceActiveWrite then decides what shows.
*/
function beginSourceActiveWrite(ids: string[], value: boolean, write: () => Promise<void>): SourceActiveWrite {
const seq = ++sourceWriteSeq;
const shown = useSessionStore.getState().sourceLibrary;
const entries = ids.map((id): SourceActiveWrite['entries'][number] => {
const entry = sourceToggles.get(id) ?? {
latest: 0,
confirmed: shown.find((source) => source.id === id)?.isActive ?? value,
chain: Promise.resolve(),
};
entry.latest = seq;
sourceToggles.set(id, entry);
lastSourceToggle.set(id, { value, seq });
return [id, entry];
});
const done = Promise.all(entries.map(([, entry]) => entry.chain)).then(write);
for (const [, entry] of entries) entry.chain = done.catch((): void => undefined);
return { seq, value, entries, done };
}
/**
* Shows the newest write's value once it lands, or the last value the server
* took if it fails. With `quietWhenReplaced`, a failure is not reported when a
* newer write already owns every source: that write's outcome is what shows.
*/
async function finishSourceActiveWrite({ seq, value, entries, done }: SourceActiveWrite, quietWhenReplaced = false): Promise<void> {
const show = (values: Map<string, boolean>) => {
if (values.size === 0) return;
useSessionStore.setState((state) => ({
sourceLibrary: state.sourceLibrary.map((source) => values.has(source.id) ? { ...source, isActive: values.get(source.id)! } : source),
}));
};
try {
await done;
} catch (error) {
const fallback = new Map<string, boolean>();
for (const [id, entry] of entries) {
if (entry.latest !== seq) continue;
sourceToggles.delete(id);
lastSourceToggle.set(id, { value: entry.confirmed, seq });
fallback.set(id, entry.confirmed);
}
show(fallback);
if (quietWhenReplaced && fallback.size === 0) return;
throw error;
}
const settled = new Map<string, boolean>();
for (const [id, entry] of entries) {
entry.confirmed = value;
// A server reload while this ran may have put back the old value.
if (entry.latest !== seq) continue;
sourceToggles.delete(id);
settled.set(id, value);
}
show(settled);
}
/** A source shown before its row is saved; it has no server id to change yet. */
export function isPendingSource(source: Pick<Source, 'id'>): boolean {
return source.id.startsWith(PENDING_SOURCE_PREFIX);
}
function savedFromRow<T>(row: SupabaseSavedRow<T>): SavedItem<T> {
return {
id: row.id,
data: row.output,
createdAt: toTimestamp(row.created_at),
title: row.title,
debateId: row.debate_id ?? null,
side: row.side ?? null,
};
}
function markDebateActivity(debateId: string | null | undefined) {
if (debateId) useDebateStore.getState().markActivity(debateId);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function parseSourceProvenance(value: unknown): SourceProvenance | undefined {
if (!isRecord(value)) return undefined;
const provenance: SourceProvenance = {};
if (typeof value.url === 'string') provenance.url = value.url;
if (typeof value.sourceType === 'string') provenance.sourceType = value.sourceType;
if (typeof value.qualityScore === 'number' && Number.isFinite(value.qualityScore)) {
provenance.qualityScore = value.qualityScore;
}
if (value.qualityLabel === 'strong' || value.qualityLabel === 'moderate' || value.qualityLabel === 'weak') {
provenance.qualityLabel = value.qualityLabel;
}
if (typeof value.query === 'string') provenance.query = value.query;
if (typeof value.capturedVia === 'string') provenance.capturedVia = value.capturedVia;
if (isRecord(value.semantic)) {
const semantic = value.semantic;
const relevance = semantic.relevance;
const importance = semantic.importance;
const strength = semantic.strength;
const evaluatedAt = semantic.evaluatedAt;
const useCount = semantic.useCount;
const caseUseCount = semantic.caseUseCount;
if (
typeof relevance === 'number' && Number.isFinite(relevance) && relevance >= 0 && relevance <= 1 &&
Number.isInteger(importance) && typeof importance === 'number' && importance >= 0 && importance <= 3 &&
Number.isInteger(strength) && typeof strength === 'number' && strength >= 0 && strength <= 3 &&
typeof evaluatedAt === 'string' && Number.isFinite(Date.parse(evaluatedAt)) &&
Number.isInteger(useCount) && typeof useCount === 'number' && useCount >= 0 &&
Number.isInteger(caseUseCount) && typeof caseUseCount === 'number' && caseUseCount >= 0 &&
(semantic.lastUsedAt === undefined || typeof semantic.lastUsedAt === 'string') &&
(semantic.lastUsedInCase === undefined || typeof semantic.lastUsedInCase === 'boolean')
) {
provenance.semantic = {
relevance,
importance: importance as 0 | 1 | 2 | 3,
strength: strength as 0 | 1 | 2 | 3,
evaluatedAt,
useCount,
caseUseCount,
...(typeof semantic.lastUsedAt === 'string' ? { lastUsedAt: semantic.lastUsedAt } : {}),
...(typeof semantic.lastUsedInCase === 'boolean' ? { lastUsedInCase: semantic.lastUsedInCase } : {}),
};
}
}
return Object.keys(provenance).length > 0 ? provenance : undefined;
}
export const useSessionStore = create<SessionState>()(
persist(
(set, get) => ({
ownerUserId: null as string | null,
generateResult: null as GenerateOutput | null,
generateLoading: false,
generateRegeneratingSection: null as string | null,
attackResult: null as AttackOutput | null,
attackLoading: false,
brainstormResult: null as BrainstormOutput | null,
brainstormLoading: false,
factoidsResult: null as FactoidsOutput | null,
factoidsLoading: false,
askMessages: [] as Message[],
askLoading: false,
askStreamingAssistant: null as StreamingAskMessage | null,
askChatId: null as string | null,
askChatDebateId: null as string | null,
askPersistedCount: 0,
savedCases: [] as SavedItem<GenerateOutput>[],
savedAttacks: [] as SavedItem<AttackOutput>[],
savedBrainstorms: [] as SavedItem<BrainstormOutput>[],
savedFactoids: [] as SavedItem<FactoidsOutput>[],
savedChats: [] as SavedItem<Message[]>[],
savedFlowcharts: [] as SavedItem<FlowchartData>[],
savedCrossfires: [] as SavedItem<unknown>[],
autosavedCases: [] as SavedItem<GenerateOutput>[],
autosavedAttacks: [] as SavedItem<AttackOutput>[],
autosavedBrainstorms: [] as SavedItem<BrainstormOutput>[],
autosavedFactoids: [] as SavedItem<FactoidsOutput>[],
sourceFolders: ['General'] as string[],
sourceLibrary: [] as Source[],
generateForm: {},
generateResultDebateId: undefined as string | null | undefined,
attackForm: {},
brainstormForm: {},
factoidsForm: {},
setGenerateForm: (data) => set((state) => ({ generateForm: mergeFormState(state.generateForm, data) })),
setGenerateResultDebateId: (debateId) => set({ generateResultDebateId: debateId }),
setAttackForm: (data) => set((state) => ({ attackForm: mergeFormState(state.attackForm, data) })),
setBrainstormForm: (data) => set((state) => ({ brainstormForm: mergeFormState(state.brainstormForm, data) })),
setFactoidsForm: (data) => set((state) => ({ factoidsForm: mergeFormState(state.factoidsForm, data) })),
pendingFlowchartData: null as FlowchartData | null,
serverHydration: 'pending',
setPendingFlowchartData: (data) => set({ pendingFlowchartData: data }),
addSource: async ({ id: restoredId, createdAt: restoredAt, ...source }) => {
const folder = normalizeFolder(source.folder);
const isActive = source.isActive ?? true;
// An omitted debate means the tool's scope, which is none in one-off mode.
const debateId = source.debateId !== undefined ? source.debateId : activeDebateId();
if (!debateId) throw new DebateRequiredError();
// One row per web page per debate. Undo puts back a row that was just deleted.
const url = source.metadata?.url ?? source.origin;
if (!restoredId) {
const known = findSavedPage(get().sourceLibrary, debateId, url);
if (known) throw new DuplicateSourceError(known.id);
}
// Other actions copy rows as they change them, so the shown row is found
// again by its id. A restored row is pending too until its insert lands.
const localId = `${PENDING_SOURCE_PREFIX}${restoredId ?? generateId()}`;
const localItem: Source = { ...source, folder, debateId, isActive, id: localId, createdAt: restoredAt ?? Date.now() };
// The library is newest first; a restored source goes back to its old place.
const place = (list: Source[], item: Source) =>
restoredId ? [...list, item].sort((x, y) => y.createdAt - x.createdAt) : [item, ...list];
// The row shows while it saves, and leaves again if the save fails.
set((state) => ({ sourceLibrary: place(state.sourceLibrary, localItem) }));
const withoutLocal = () => set((state) => ({ sourceLibrary: state.sourceLibrary.filter((item) => item.id !== localId) }));
let savedSource: Source;
try {
const userId = await getUserId();
if (!userId) throw signInRequired('save this source');
const key = !restoredId && url ? normalizeSourceUrl(url) : null;
if (key) {
// Another tab, or a list that failed to load, may hold the page already.
const { data: rows, error: lookupError } = await supabase
.from('sources')
.select('id,origin,metadata')
.eq('user_id', userId)
.eq('debate_id', debateId);
throwOnWriteError({ error: lookupError }, 'check for a saved copy of this page');
const match = (rows ?? []).find((row) => savedSourceUrl({
origin: row.origin ?? undefined,
metadata: parseSourceProvenance(row.metadata),
}) === key);
if (match) throw new DuplicateSourceError(match.id);
}
const folderResult = await supabase
.from('source_folders')
.upsert({ user_id: userId, name: folder }, { onConflict: 'user_id,name' });
throwOnWriteError(folderResult, 'save source folder');
const { data, error } = await supabase
.from('sources')
.insert({
...(restoredId ? { id: restoredId, created_at: new Date(localItem.createdAt).toISOString() } : {}),
user_id: userId,
debate_id: debateId,
title: source.title,
content: source.content,
type: source.type,
origin: source.origin || null,
folder,
is_active: isActive,
metadata: source.metadata ?? null,
})
.select('*')
.single();
throwOnWriteError({ error }, 'save source');
if (!data) throw new Error('[SessionStore] Failed to save source: No record returned');
savedSource = {
id: data.id,
title: data.title,
content: data.content,
type: data.type,
origin: data.origin || undefined,
folder: normalizeFolder(data.folder || localItem.folder),
metadata: parseSourceProvenance(data.metadata),
debateId: data.debate_id ?? debateId,
isActive: data.is_active,
createdAt: toTimestamp(data.created_at),
};
} catch (error) {
withoutLocal();
throw error;
}
set((state) => {
const shown = state.sourceLibrary.some((item) => item.id === localId);
// A reload from the server while this saved may already list the row.
const listed = state.sourceLibrary.some((item) => item.id === savedSource.id);
// A debate deleted meanwhile took its sources with it.
const debateGone = !useDebateStore.getState().debates.some((debate) => debate.id === debateId);
const sourceLibrary = shown
? listed
? state.sourceLibrary.filter((item) => item.id !== localId)
: state.sourceLibrary.map((item) => item.id === localId ? savedSource : item)
: listed || debateGone
? state.sourceLibrary
: place(state.sourceLibrary, savedSource);
return { sourceFolders: mergeSourceFolders(state.sourceFolders, [savedSource]), sourceLibrary };
});
markDebateActivity(debateId);
},
createSourceFolder: async (folder) => {
const normalized = normalizeFolder(folder);
const userId = await getUserId();
if (!userId) throw signInRequired('save this folder');
throwOnWriteError(
await supabase
.from('source_folders')
.upsert({ user_id: userId, name: normalized }, { onConflict: 'user_id,name' }),
'save source folder',
);
set((state) => ({
sourceFolders: mergeSourceFolders([...state.sourceFolders, normalized], state.sourceLibrary),
}));
},
updateSource: async (id, patch) => {
const current = get().sourceLibrary.find((s) => s.id === id);
// A row still saving has nothing on the server to update yet.
if (!current || isPendingSource(current)) return;
const normalizedPatch: Partial<Omit<Source, 'id' | 'createdAt'>> = { ...patch };
if (patch.folder !== undefined) {
normalizedPatch.folder = normalizeFolder(patch.folder);
}
if (patch.origin !== undefined) {
normalizedPatch.origin = patch.origin.trim() || undefined;
}
if (patch.title !== undefined) normalizedPatch.title = patch.title.trim() || current.title;
if (patch.content !== undefined) normalizedPatch.content = patch.content.trim() || current.content;
// Only what this edit changes is written. The switch is left alone unless
// the edit changes it, so a refresh of research metadata cannot save a
// switch value whose own write is still running or about to fail.
const changesActive = patch.isActive !== undefined && patch.isActive !== current.isActive;
delete normalizedPatch.isActive;
const row: Record<string, unknown> = {};
if (normalizedPatch.title !== undefined) row.title = normalizedPatch.title;
if (normalizedPatch.content !== undefined) row.content = normalizedPatch.content;
if (normalizedPatch.type !== undefined) row.type = normalizedPatch.type;
if ('origin' in normalizedPatch) row.origin = normalizedPatch.origin || null;
if (normalizedPatch.folder !== undefined) row.folder = normalizedPatch.folder;
if ('metadata' in normalizedPatch) row.metadata = normalizedPatch.metadata ?? null;
if (changesActive) row.is_active = patch.isActive;
if (Object.keys(row).length === 0) return;
const write = async () => {
const userId = await getUserId();
if (!userId) throw signInRequired('save this source');
if (normalizedPatch.folder) {
const folderResult = await supabase
.from('source_folders')
.upsert({ user_id: userId, name: normalizedPatch.folder }, { onConflict: 'user_id,name' });
throwOnWriteError(folderResult, 'save source folder');
}
throwOnWriteError(await applyUserScopedIdFilter(supabase.from('sources').update(row), userId, id), 'update source');
};
const activeWrite = changesActive ? beginSourceActiveWrite([id], patch.isActive!, write) : null;
const previousFolders = get().sourceFolders;
// A failed save undoes only the fields it changed.
const undo: Partial<Source> = {};
for (const key of Object.keys(normalizedPatch) as Array<keyof typeof normalizedPatch>) {
(undo as Record<string, unknown>)[key] = current[key];
}
set((state) => ({
sourceFolders: normalizedPatch.folder ? mergeSourceFolders(state.sourceFolders, [{ ...current, folder: normalizedPatch.folder }]) : state.sourceFolders,
sourceLibrary: state.sourceLibrary.map((source) => source.id === id
? { ...source, ...normalizedPatch, ...(changesActive ? { isActive: patch.isActive! } : {}) }
: source),
}));
try {
if (activeWrite) await finishSourceActiveWrite(activeWrite);
else await write();
} catch (error) {
set((state) => ({
sourceFolders: normalizedPatch.folder ? previousFolders : state.sourceFolders,
sourceLibrary: state.sourceLibrary.map((source) => source.id === id ? { ...source, ...undo } : source),
}));
throw error;
}
},
applySourceAssessments: async (assessments) => {
if (assessments.length === 0) return;
const previous = get().sourceLibrary;
const debateId = activeDebateId();
if (!debateId) return;
// A URL can be saved in several debates; only this debate's copy was used.
const candidates = previous.filter((source) => source.debateId === debateId);
const updates = new Map<string, Source>();
for (const assessment of assessments.slice(0, 10)) {
const source = candidates.find((candidate) => candidate.id === assessment.id || candidate.id === assessment.key || candidate.origin === assessment.key || candidate.metadata?.url === assessment.key);
if (!source) continue;
const prior = source.metadata?.semantic;
const usedInCase = assessment.usedInCase;
updates.set(source.id, {
...source,
metadata: {
...source.metadata,
semantic: {
relevance: assessment.relevance,
importance: assessment.importance,
strength: assessment.strength,
evaluatedAt: assessment.evaluatedAt,
useCount: (prior?.useCount ?? 0) + 1,
caseUseCount: (prior?.caseUseCount ?? 0) + (usedInCase === true ? 1 : 0),
lastUsedAt: assessment.evaluatedAt,
...(usedInCase !== undefined
? { lastUsedInCase: usedInCase }
: prior?.lastUsedInCase !== undefined ? { lastUsedInCase: prior.lastUsedInCase } : {}),
},
},
});
}
if (updates.size === 0) return;
set((state) => ({ sourceLibrary: state.sourceLibrary.map((source) => updates.get(source.id) ?? source) }));
try {
const userId = await getUserId();
if (!userId) throw signInRequired('save this source');
await Promise.all(Array.from(updates.values()).map(async (source) => {
const result = await applyUserScopedIdFilter(
supabase.from('sources').update({ metadata: source.metadata ?? null }),
userId,
source.id,
);
throwOnWriteError(result, 'update source assessment');
}));
} catch (error) {
set({ sourceLibrary: previous });
throw error;
}
},
// Folders are per account, but renaming or deleting one only moves the
// Current Debate's sources. The folder name survives while another debate uses it.
renameSourceFolder: async (oldName, newName) => {
const from = normalizeFolder(oldName);
const to = normalizeFolder(newName);
if (from === 'General' || from === to) return;
const debateId = useDebateStore.getState().currentDebateId;
if (!debateId) throw new DebateRequiredError();
const inThisDebate = (source: Source) => source.debateId === debateId && normalizeFolder(source.folder) === from;
const usedElsewhere = get().sourceLibrary.some((source) => source.debateId !== debateId && normalizeFolder(source.folder) === from);
const applyRename = (): void => {
set((state) => {
const renamedSources = state.sourceLibrary.map((source) => inThisDebate(source) ? { ...source, folder: to } : source);
const folders = usedElsewhere
? [...state.sourceFolders, to]
: state.sourceFolders.map((folder) => normalizeFolder(folder) === from ? to : folder);
return { sourceFolders: mergeSourceFolders(folders, renamedSources), sourceLibrary: renamedSources };
});
};
const userId = await getUserId();
if (!userId) throw signInRequired('rename this folder');
const folderResult = await supabase
.from('source_folders')
.upsert({ user_id: userId, name: to }, { onConflict: 'user_id,name' });
throwOnWriteError(folderResult, 'create renamed source folder');
throwOnWriteError(
await supabase.from('sources').update({ folder: to }).eq('user_id', userId).eq('debate_id', debateId).eq('folder', from),
'move sources to renamed folder',
);
if (!usedElsewhere) {
throwOnWriteError(
await applyUserScopedColumnFilter(supabase.from('source_folders').delete(), userId, 'name', from),
'delete renamed source folder',
);
}
applyRename();
},
deleteSourceFolder: async (name, mode) => {
const folder = normalizeFolder(name);
if (folder === 'General') return;
const debateId = useDebateStore.getState().currentDebateId;
if (!debateId) throw new DebateRequiredError();
const inThisDebate = (source: Source) => source.debateId === debateId && normalizeFolder(source.folder) === folder;
const affected = get().sourceLibrary.filter(inThisDebate);
const usedElsewhere = get().sourceLibrary.some((source) => source.debateId !== debateId && normalizeFolder(source.folder) === folder);
if (affected.length > 0 && mode === 'empty-only') {
throw new Error('Folder is not empty');
}
const applyDelete = (): void => {
set((state) => {
const movedSources = state.sourceLibrary.map((source) => inThisDebate(source) ? { ...source, folder: 'General' } : source);
const folders = mergeSourceFolders(state.sourceFolders, movedSources);
return {
sourceFolders: usedElsewhere ? folders : folders.filter((existing) => normalizeFolder(existing) !== folder),
sourceLibrary: movedSources,
};
});
};
const userId = await getUserId();
if (!userId) throw signInRequired('delete this folder');
if (affected.length > 0) {
throwOnWriteError(
await supabase.from('sources').update({ folder: 'General' }).eq('user_id', userId).eq('debate_id', debateId).eq('folder', folder),
'move sources from deleted folder',
);
}
if (!usedElsewhere) {
throwOnWriteError(
await applyUserScopedColumnFilter(supabase.from('source_folders').delete(), userId, 'name', folder),
'delete source folder',
);
}
applyDelete();
},
setFolderActive: async (folder, isActive) => {
const normalized = normalizeFolder(folder);
const debateId = useDebateStore.getState().currentDebateId;
if (!debateId) throw new DebateRequiredError();
// Rows still saving are not on the server yet; they keep the value they are saved with.
const ids = get().sourceLibrary
.filter((source) => source.debateId === debateId && normalizeFolder(source.folder) === normalized && !isPendingSource(source))
.map((source) => source.id);
if (ids.length === 0) return;
// Only the rows on screen: a row still saving could otherwise commit first
// and take the folder's value on the server but not in the Library.
const activeWrite = beginSourceActiveWrite(ids, isActive, async () => {
const userId = await getUserId();
if (!userId) throw signInRequired('update this folder');
throwOnWriteError(
await supabase.from('sources').update({ is_active: isActive })
.eq('user_id', userId).eq('debate_id', debateId).in('id', ids),
'update source folder activity',
);
});
await finishSourceActiveWrite(activeWrite);
},
removeSource: async (id) => {
if (isPendingSource({ id })) throw new Error('[SessionStore] This source is still saving');
const userId = await getUserId();