Repository navigation
Expand file tree
/
Copy pathplugin.client.js
More file actions
2223 lines (2091 loc) · 104 KB
/
Copy pathplugin.client.js
File metadata and controls
2223 lines (2091 loc) · 104 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
// dsh-plugin-message-tree — client half.
//
// Mimics ChatGPT's edit-message behavior: hover a past prompt to edit it,
// sending branches the conversation from that point (the host half performs
// the true rewind); ‹ 2/3 › switches between versions of the same message;
// a Versions view draws the whole tree.
// Route, CSS prefix and storage keys keep the `message-tree` spelling even
// though the package is dsh-plugin-message-edit: Moeblack's dsh-message-edit
// owns the `message-edit` names, and colliding would break both plugins when
// installed together. See lib/index.js for the full note.
const ROUTE = '/message-tree';
const VIEW_ORDER = 16;
function realGlobal() {
try { if (typeof window !== 'undefined' && window) return window; } catch (e) {}
try { if (typeof globalThis !== 'undefined' && globalThis) return globalThis; } catch (e) {}
return null;
}
/* ------------------------------------------------------------- edit style -- */
// Which provider's message-edit LAYOUT to follow. All three put the controls
// below the bubble; what differs is which controls exist (only Claude offers
// retry), whether they wait for hover (ChatGPT and Claude) or stay visible
// (DeepSeek, like DSH itself), and whether the editor's Cancel/confirm sit
// inside the box or below it. Colours stay native in every preset. The choice
// is one attribute on <html>, so the stylesheet keys off it and switching
// takes effect live.
const STYLE_KEY = 'dsh-plugin-message-tree:style';
const STYLES = ['chatgpt', 'deepseek', 'claude'];
const DEFAULT_STYLE = 'chatgpt';
const styleStore = {
value: null,
listeners: [],
get() {
if (this.value === null) {
const g = realGlobal();
let stored = null;
try { stored = g && g.localStorage && g.localStorage.getItem(STYLE_KEY); } catch (e) {}
this.value = STYLES.indexOf(stored) !== -1 ? stored : DEFAULT_STYLE;
}
return this.value;
},
set(next) {
this.value = STYLES.indexOf(next) !== -1 ? next : DEFAULT_STYLE;
const g = realGlobal();
try { if (g && g.localStorage) g.localStorage.setItem(STYLE_KEY, this.value); } catch (e) {}
syncStyleAttribute();
for (let i = 0; i < this.listeners.length; i++) {
try { this.listeners[i](); } catch (e) {}
}
},
subscribe(fn) {
const listeners = this.listeners;
listeners.push(fn);
return function () {
const at = listeners.indexOf(fn);
if (at !== -1) listeners.splice(at, 1);
};
},
};
function syncStyleAttribute() {
const g = realGlobal();
const root = g && g.document && g.document.documentElement;
if (root) root.setAttribute('data-mtx-style', styleStore.get());
}
/* ----------------------------------------------------------- active path -- */
// A version IS a whole session, so "which version am I looking at" is just
// "which session is open". Reopening a conversation lands on whichever session
// the sidebar points at — normally the family root — so a branch you had
// selected is silently dropped and the ring snaps back to 1/N.
//
// Remember the last session viewed for each family, keyed by the family's root,
// and restore it when you land back on that root. Recording happens for every
// family member you view, so walking the ring back to the root records the root
// and the restore then correctly does nothing (no ping-pong).
const PATH_KEY = 'dsh-plugin-message-tree:active-path';
const PATH_LIMIT = 200;
const activePathStore = {
map: null,
read() {
if (this.map === null) {
let parsed = null;
try {
const g = realGlobal();
const raw = g && g.localStorage && g.localStorage.getItem(PATH_KEY);
parsed = raw ? JSON.parse(raw) : null;
} catch (e) {}
this.map = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
}
return this.map;
},
get(rootId) {
if (!rootId) return undefined;
const v = this.read()[rootId];
return typeof v === 'string' ? v : undefined;
},
set(rootId, sessionId) {
if (!rootId || !sessionId) return;
const map = this.read();
if (map[rootId] === sessionId) return;
map[rootId] = sessionId;
// Bound the map so a long-lived profile cannot grow it without limit.
// Object key order is insertion order for string keys, so the oldest
// entries are at the front.
const keys = Object.keys(map);
if (keys.length > PATH_LIMIT) {
for (let i = 0; i < keys.length - PATH_LIMIT; i++) delete map[keys[i]];
}
try {
const g = realGlobal();
if (g && g.localStorage) g.localStorage.setItem(PATH_KEY, JSON.stringify(map));
} catch (e) {}
},
};
/** The family root for `sessionId`: walk parents until one has none. */
function rootOf(versions, sessionId) {
if (!versions || sessionId === undefined) return undefined;
const byId = new Map(versions.map(function (v) { return [v.sessionId, v]; }));
let cursor = byId.get(sessionId);
if (!cursor) return undefined;
const seen = new Set();
while (cursor.parentSessionId && !seen.has(cursor.sessionId)) {
seen.add(cursor.sessionId);
const parent = byId.get(cursor.parentSessionId);
if (!parent) break;
cursor = parent;
}
return cursor.sessionId;
}
// Families already restored in this page load. Without this the restore would
// re-fire on every re-render and fight a deliberate walk back to the root.
const restoredFamilies = new Set();
// Restores that have been triggered but whose navigation has not landed yet.
// While a root is in here we must not record it as the selection.
const pendingRestore = new Set();
// Subagent and Sidechat (`origin: 'side'`, DSH 0.2.3-alpha.3) sessions belong
// to the conversation that started them. DSH hides them from the sidebar; they
// are never versions, so they never join a family row or its activity.
function ownedRow(row) {
return !!row && typeof row.origin === 'string';
}
// Sidebar-only projection: the real catalog remains available to VersionsView.
function sidebarRoot(id, byId) {
const seen = new Set([id]);
let current = id;
while (byId[current] && !ownedRow(byId[current])) {
const parent = byId[current].parentId;
if (!parent || !byId[parent] || ownedRow(byId[parent]) || seen.has(parent)) break;
seen.add(parent);
current = parent;
}
return current;
}
function sidebarList(list) {
// Native subagent activity can use byId-only entries absent from list.ids.
// DSH selects the row of a subagent or side conversation in view by walking
// its parentId to the first listed ordinary session. A hidden version is not
// listed, so the walk is pointed at the row that stands for that version.
const byId = {};
for (const [id, row] of Object.entries(list.byId)) {
if (!ownedRow(row)) continue;
const parent = list.byId[row.parentId];
const parentId = parent && !ownedRow(parent) ? sidebarRoot(row.parentId, list.byId) : row.parentId;
byId[id] = parentId === row.parentId ? row : { ...row, parentId };
}
const ids = [];
const seen = new Set();
const catalogs = new Map();
for (const id of list.ids) {
const session = list.byId[id];
if (!session) continue;
const root = sidebarRoot(id, list.byId);
if (!seen.has(root)) {
// An owned row is its own root; keep its redirected parentId.
const base = byId[root] ?? list.byId[root];
byId[root] = { ...base, retainedBy: { ...base.retainedBy } };
ids.push(root);
seen.add(root);
}
const row = byId[root];
row.updatedAt = Math.max(row.updatedAt || 0, session.updatedAt || 0);
row.running = row.running || session.running;
if (id !== root) row.retainedBy.mainView = (row.retainedBy.mainView || 0) + (session.retainedBy?.mainView || 0);
// Native runningChildCount reads the owning session's projection, not its
// parentId links. Seeded versions can inherit the same catalog entries.
for (const child of list.projectionsBySession?.[id]?.values.subagentCatalog || []) {
if (!catalogs.has(root)) catalogs.set(root, new Map());
catalogs.get(root).set(child.id, child);
}
}
const projectionsBySession = list.projectionsBySession && { ...list.projectionsBySession };
for (const [root, children] of catalogs) {
const projection = projectionsBySession[root];
projectionsBySession[root] = { ...projection, values: { ...projection?.values, subagentCatalog: [...children.values()] } };
}
return { ...list, ids, byId, ...(projectionsBySession ? { projectionsBySession } : {}) };
}
// Only project actionable flags from ordinary, openable family members. Use
// the same candidates for display and navigation; native read/approval state
// belongs to each real session and is never acknowledged by this projection.
function sidebarAttention(statuses, list, workspaces) {
const attention = new Map();
if (!statuses) return attention;
const archived = new Set(workspaces.archivedSessionIds);
// Prefer the original within each priority, then native catalog order.
const ids = new Set([...list.ids.map(id => sidebarRoot(id, list.byId)), ...list.ids]);
for (const id of ids) {
const session = list.byId[id];
const root = sidebarRoot(id, list.byId);
if (!session || session.blank || ownedRow(session) || archived.has(id) || archived.has(root)) continue;
const status = statuses.get(id);
if (!status) continue;
const pending = ['approval', 'plan-review', 'question'].includes(status.pendingInteraction?.kind);
const completed = status.completionUnread === true && !(status.running ?? session.running);
if (!pending && !completed) continue;
if (!attention.has(root)) attention.set(root, {});
const row = attention.get(root);
if (pending && !row.pending) row.pending = { id, interaction: status.pendingInteraction };
if (completed && !row.completed) row.completed = id;
}
return attention;
}
function sidebarStatuses(statuses, list, attention, workspaces) {
if (!statuses) return statuses;
const grouped = new Map(statuses);
for (const [id, status] of statuses) {
const root = sidebarRoot(id, list.byId);
if (id === root) continue;
const row = grouped.get(root);
grouped.set(root, { ...row,
running: row?.running || status.running,
});
}
for (const root of new Set(list.ids.map(id => sidebarRoot(id, list.byId)))) {
if (ownedRow(list.byId[root]) || workspaces.archivedSessionIds.includes(root)) continue;
const flags = attention.get(root);
grouped.set(root, { ...grouped.get(root),
completionUnread: !!flags?.completed,
completionFailed: statuses.get(flags?.completed)?.completionFailed === true,
pendingInteraction: flags?.pending?.interaction,
});
}
return grouped;
}
function sidebarWorkspaces(state, list) {
// Menus still act on the original session. Keep its real workspace, pin and
// archive membership, including Ungrouped, rather than projecting a child's
// membership onto a row whose native actions would disagree with it.
const originals = ids => ids.filter(id => sidebarRoot(id, list.byId) === id);
return {
...state,
items: state.items.map(item => ({ ...item, sessionIds: originals(item.sessionIds) })),
pinnedSessionIds: originals(state.pinnedSessionIds),
archivedSessionIds: originals(state.archivedSessionIds),
};
}
function sidebarSearch(result, list, workspaces, archivedFilter, query = '', targets) {
if (!result?.items) return result;
// The native title/id search sees the projected originals only. Preserve
// those matches for hidden branches as well, even when full-text search is
// disabled by the host. Native result limits and hasMore still apply.
const q = query.trim().toLowerCase();
const archived = new Set(workspaces.archivedSessionIds);
const visible = id => {
const row = list.byId[id];
return row && !row.blank && !ownedRow(row)
&& (archivedFilter === 'show' || (archivedFilter === 'only' ? archived.has(id) : !archived.has(id)));
};
const titleOrIdMatches = id => q && ((list.byId[id]?.title || '').toLowerCase().includes(q) || id.toLowerCase().includes(q));
const rootMatches = id => {
const cwd = list.byId[id]?.cwd || '';
const label = workspaces.items.find(item => item.sessionIds.includes(id))?.title
?? (cwd.replace(/[/\\]+$/, '').split(/[/\\]/).pop() || cwd);
return q && (titleOrIdMatches(id) || label.toLowerCase().includes(q));
};
const local = q ? list.ids.filter(id => {
return visible(id) && sidebarRoot(id, list.byId) !== id && titleOrIdMatches(id);
}).map(sessionId => ({ sessionId })) : [];
const families = new Map();
for (const item of [...result.items, ...local]) {
const sessionId = sidebarRoot(item.sessionId, list.byId);
// Host search takes no archive filter. Filter real versions before merging,
// and keep the original's archive visibility for the grouped entry itself.
if (!visible(item.sessionId) || !visible(sessionId)) continue;
if (!families.has(sessionId)) families.set(sessionId, []);
families.get(sessionId).push(item);
}
return { ...result, items: [...families].map(([sessionId, matches]) => {
const ordinary = rootMatches(sessionId);
const live = matches.filter(item => !archived.has(item.sessionId));
// In Show archived, an archived hit must not block a matching live member
// (including a native local root match that is absent from Host results).
if (!live.length && ordinary && !archived.has(sessionId)) return { sessionId };
const candidates = live.length ? live : matches;
const item = candidates.find(item => item.snippet) || candidates[0];
// A shared title alone does not express a request to change versions.
// Any displayed content snippet selects its source, including the root.
// Without one, only a hidden-only match selects a particular version.
if (item.snippet || (item.sessionId !== sessionId && !ordinary)) targets.set(sessionId, item.sessionId);
return { ...item, sessionId };
}) };
}
function installSidebarGrouping(slots) {
if (typeof slots.entriesOfSlot !== 'function') return;
return slots.inject('sidebar.workspaces', function () {
const entry = slots.entriesOfSlot('sidebar.workspaces').find(row => row.component);
if (!entry) return;
const Original = entry.component;
function GroupedSidebar(props) {
const prefs = usePrefs();
const list = props.useSessions(state => state);
const searchRequest = React.useRef(null);
const workspaces = props.useWorkspaces(state => state);
const latestView = React.useRef(null);
const archivedFilter = props.useStore ? props.useStore(state => state.archivedFilter ?? 'default') : 'default';
const archiveKey = JSON.stringify([...workspaces.archivedSessionIds].sort());
const statuses = props.useSessionStatus ? props.useSessionStatus(state => state) : null;
const grouped = React.useMemo(() => sidebarList(list), [list]);
const groupedWorkspaces = React.useMemo(() => sidebarWorkspaces(workspaces, list), [workspaces, list]);
const attention = React.useMemo(() => sidebarAttention(statuses, list, workspaces), [statuses, list, workspaces]);
const groupedStatuses = React.useMemo(() => sidebarStatuses(statuses, list, attention, workspaces), [statuses, list, attention, workspaces]);
latestView.current = { list, workspaces, attention };
const active = list.ids.find(id => (list.byId[id]?.retainedBy?.mainView || 0) > 0);
React.useEffect(() => {
// A subagent or side conversation in view is not a version to reopen.
if (prefs.foldSidebar && active && !ownedRow(list.byId[active])) activePathStore.set(sidebarRoot(active, list.byId), active);
}, [active, list, prefs.foldSidebar]);
const useSessions = selector => props.useSessions(state => selector(state === list ? grouped : sidebarList(state)));
const useWorkspaces = selector => props.useWorkspaces(() => selector(groupedWorkspaces));
const useSessionStatus = selector => props.useSessionStatus(() => selector(groupedStatuses));
const open = id => {
// An older rendered handler must not use a cleared flag, removed
// version or newly archived destination after a newer snapshot arrived.
const { list, workspaces, attention } = latestView.current;
const request = searchRequest.current;
searchRequest.current = null;
if (workspaces.archivedSessionIds.includes(id)) {
props.notifyArchivedNotOpenable?.();
return;
}
// The row decides which version opens; the bubble must not decide again.
if (prefs.openVersion === 'recent') restoredFamilies.add(id);
// Native search keeps its AbortSignal alive through openSearchResult's
// synchronous open call, then aborts it when the query clears/changes.
// Keep root IDs for its local-title/content merge, but navigate to the
// version that supplied the displayed snippet. Never persist this map.
if (request && !request.signal?.aborted) {
const target = request.targets.get(id);
if (workspaces.archivedSessionIds.includes(target)) {
props.notifyArchivedNotOpenable?.();
return;
}
if (target && list.byId[target]) {
activePathStore.set(id, target);
props.open(target);
return;
}
}
const flags = attention.get(id);
const actionable = flags?.pending?.id || flags?.completed;
if (actionable) {
// Also pin a root destination so the bubble-level remembered-path
// restore cannot undo navigation to the original's pending work.
activePathStore.set(id, actionable);
props.open(actionable);
return;
}
const archived = new Set(workspaces.archivedSessionIds);
let target;
if (prefs.openVersion === 'last') {
const remembered = activePathStore.get(id);
if (remembered && list.byId[remembered] && !archived.has(remembered)) target = remembered;
} else if (prefs.openVersion === 'recent') {
target = recentVersion(familyMembers(id, list).filter(member => !archived.has(member)), list.byId);
}
props.open(target || id);
};
// Native search clears its results whenever this callback changes.
// Catalog/status updates must not restart an otherwise unchanged query;
// archive membership/filter changes must remove newly hidden snippets.
const searchSessions = React.useCallback(async (...args) => {
const request = { signal: args[1], targets: new Map() };
searchRequest.current = request;
const project = result => sidebarSearch(result, latestView.current.list, latestView.current.workspaces, archivedFilter, args[0], request.targets);
try { return project(await props.searchSessions(...args)); }
catch (error) {
if (args[1]?.aborted) throw error;
const local = project({ items: [], hasMore: false });
if (!local.items.length) throw error;
return local;
}
}, [props.searchSessions, archivedFilter, archiveKey]);
return React.createElement(Original, prefs.foldSidebar ? { ...props, useSessions, useWorkspaces,
...(props.useSessionStatus ? { useSessionStatus } : {}), open, searchSessions } : props);
}
// Reuse the native entry so its child slots, store and menus stay intact.
entry.component = GroupedSidebar;
return function () { if (entry.component === GroupedSidebar) entry.component = Original; };
});
}
// The rename dialog every entry point opens: a row double-click, the row and
// header menus, and the rename shortcut all commit through its renameSession.
const RENAME_DIALOG_ID = 'workspace.session-rename';
/** The sessions one grouped sidebar row stands for: the original and its versions. */
function familyMembers(sessionId, list) {
const byId = list.byId || {};
if (!byId[sessionId] || ownedRow(byId[sessionId])) return [sessionId];
const root = sidebarRoot(sessionId, byId);
return (list.ids || []).filter(id => byId[id] && !ownedRow(byId[id]) && sidebarRoot(id, byId) === root);
}
/**
* The member with the latest activity. DSH's updatedAt is already the later of
* creation and the last prompt; blank and unlisted sessions never qualify.
*/
function recentVersion(ids, byId) {
let best;
for (const id of ids) {
const row = byId[id];
if (!row || row.blank || ownedRow(row)) continue;
if (best === undefined || (row.updatedAt || 0) > (byId[best].updatedAt || 0)) best = id;
}
return best;
}
/**
* With grouping on, one sidebar row is one conversation, so a rename names the
* conversation: every member gets the title, whichever row, menu or shortcut
* asked. Otherwise the row and a version's header disagree, and the next
* version inherits a stale name. Grouping off keeps per-session renames.
*/
function installFamilyRename(slots, sessions) {
if (typeof slots.entriesOfSlot !== 'function') return;
return slots.inject('shell.overlay', function () {
const entry = slots.entriesOfSlot('shell.overlay')
.find(row => row.component && ((row.options && row.options.id) || row.id) === RENAME_DIALOG_ID);
if (!entry) return;
const Original = entry.component;
function FamilyRenameDialog(props) {
const prefs = usePrefs();
const native = props.renameSession;
const renameSession = React.useCallback(async (sessionId, title) => {
// The named session first: on any failure it behaves as natively.
await native(sessionId, title);
let failure;
for (const id of familyMembers(sessionId, sessions.list.getSnapshot())) {
if (id === sessionId) continue;
try { await native(id, title); } catch (error) { failure = failure || error; }
}
if (failure) throw failure;
}, [native]);
return React.createElement(Original, prefs.foldSidebar && typeof native === 'function' ? { ...props, renameSession } : props);
}
entry.component = FamilyRenameDialog;
return function () { if (entry.component === FamilyRenameDialog) entry.component = Original; };
});
}
/* --------------------------------------------------------------- prefs -- */
// Behaviour toggles, persisted next to the style choice. Both default to the
// behaviour the user asked for rather than the old one.
const PREFS_KEY = 'dsh-plugin-message-tree:prefs';
// Which version opening a conversation lands on.
const OPEN_VERSIONS = ['recent', 'last', 'root'];
const PREFS_DEFAULTS = {
// Opt in to one sidebar entry per conversation family.
foldSidebar: false,
// The most recently active version, like DeepSeek's newest branch.
openVersion: 'recent',
// Cancel a still-running turn before an edit forks the conversation.
stopOnEdit: true,
};
/** A stored choice, or the one the former on/off "remember" switch meant. */
function storedOpenVersion(parsed) {
if (parsed && OPEN_VERSIONS.indexOf(parsed.openVersion) !== -1) return parsed.openVersion;
if (parsed && typeof parsed.rememberPath === 'boolean') return parsed.rememberPath ? 'last' : 'root';
return PREFS_DEFAULTS.openVersion;
}
const prefsStore = {
value: null,
listeners: [],
get() {
if (this.value === null) {
let parsed = null;
try {
const g = realGlobal();
const raw = g && g.localStorage && g.localStorage.getItem(PREFS_KEY);
parsed = raw ? JSON.parse(raw) : null;
} catch (e) {}
const out = {};
for (const k in PREFS_DEFAULTS) {
out[k] = k === 'openVersion' ? storedOpenVersion(parsed)
: parsed && typeof parsed[k] === 'boolean' ? parsed[k] : PREFS_DEFAULTS[k];
}
this.value = out;
}
return this.value;
},
set(patch) {
const next = Object.assign({}, this.get(), patch);
this.value = next;
try {
const g = realGlobal();
if (g && g.localStorage) g.localStorage.setItem(PREFS_KEY, JSON.stringify(next));
} catch (e) {}
for (let i = 0; i < this.listeners.length; i++) {
try { this.listeners[i](); } catch (e) {}
}
},
subscribe(fn) {
const listeners = this.listeners;
listeners.push(fn);
return function () {
const at = listeners.indexOf(fn);
if (at !== -1) listeners.splice(at, 1);
};
},
};
function usePrefs() {
const [, force] = React.useReducer(function (x) { return x + 1; }, 0);
React.useEffect(function () { return prefsStore.subscribe(force); }, []);
return prefsStore.get();
}
function useStyle() {
const [, force] = React.useReducer(function (x) { return x + 1; }, 0);
React.useEffect(function () { return styleStore.subscribe(force); }, []);
return styleStore.get();
}
/* ------------------------------------------------------- timeline store -- */
const MAX_CACHED_SESSIONS = 500;
const MAX_CACHED_ROOTS = 50;
// High-performance family-aware tree cache with zero-flicker Stale-While-Revalidate.
const treeStore = {
bySession: new Map(),
byRoot: new Map(),
inflight: new Map(),
listeners: [],
get(sessionId) {
if (!sessionId) return null;
return this.bySession.get(sessionId) || null;
},
notify() {
for (let i = 0; i < this.listeners.length; i++) {
try { this.listeners[i](); } catch (e) {}
}
},
subscribe(fn) {
const listeners = this.listeners;
listeners.push(fn);
return function () {
const at = listeners.indexOf(fn);
if (at !== -1) listeners.splice(at, 1);
};
},
_prune() {
while (this.bySession.size > MAX_CACHED_SESSIONS) {
const oldestKey = this.bySession.keys().next().value;
this.bySession.delete(oldestKey);
}
while (this.byRoot.size > MAX_CACHED_ROOTS) {
const oldestKey = this.byRoot.keys().next().value;
this.byRoot.delete(oldestKey);
}
},
setTree(sessionId, versions, timestamp) {
if (!Array.isArray(versions)) versions = [];
const rootId = rootOf(versions, sessionId) || sessionId;
const updatedAt = typeof timestamp === 'number' ? timestamp : Date.now();
const existingRoot = this.byRoot.get(rootId);
if (existingRoot && (existingRoot.updatedAt || 0) > updatedAt) {
return;
}
const entry = { versions: versions, rootId: rootId, loading: false, error: null, updatedAt: updatedAt };
this.byRoot.set(rootId, entry);
for (let i = 0; i < versions.length; i++) {
const v = versions[i];
if (v && v.sessionId && !v.deleted) {
this.bySession.set(v.sessionId, entry);
}
}
this.bySession.set(sessionId, entry);
this._prune();
this.notify();
},
async load(sessionId) {
if (!sessionId) return;
const g = realGlobal();
if (!g || typeof g.fetch !== 'function') return;
if (this.inflight.has(sessionId)) return this.inflight.get(sessionId);
const existing = this.bySession.get(sessionId);
const reqTime = Date.now();
if (existing) {
this.bySession.set(sessionId, Object.assign({}, existing, { loading: true }));
} else {
this.bySession.set(sessionId, { versions: null, loading: true, error: null, updatedAt: 0 });
}
const self = this;
const promise = (async function () {
try {
const res = await g.fetch(ROUTE + '?sessionId=' + encodeURIComponent(sessionId), { cache: 'no-store' });
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
self.setTree(sessionId, data.versions, reqTime);
} catch (e) {
const errStr = String((e && e.message) || e);
const prev = self.bySession.get(sessionId);
self.bySession.set(sessionId, {
versions: prev ? prev.versions : null,
loading: false,
error: errStr,
updatedAt: prev ? prev.updatedAt : 0,
});
self.notify();
} finally {
self.inflight.delete(sessionId);
}
})();
this.inflight.set(sessionId, promise);
return promise;
},
ensure(sessionId) {
if (!sessionId) return;
const entry = this.bySession.get(sessionId);
if (!entry || !entry.versions) {
this.load(sessionId);
} else if (Date.now() - (entry.updatedAt || 0) > 8000 && !entry.loading) {
this.load(sessionId);
}
},
invalidate(sessionId) {
if (sessionId) {
const entry = this.bySession.get(sessionId);
if (entry && entry.rootId) {
const rootEntry = this.byRoot.get(entry.rootId);
if (rootEntry) rootEntry.updatedAt = 0;
}
this.load(sessionId);
} else {
this.bySession.forEach(function (e) { if (e) e.updatedAt = 0; });
this.byRoot.forEach(function (e) { if (e) e.updatedAt = 0; });
this.notify();
}
},
};
function useTree(sessionId) {
const [, force] = React.useReducer(function (x) { return x + 1; }, 0);
React.useEffect(function () { return treeStore.subscribe(force); }, []);
React.useEffect(function () { if (sessionId) treeStore.ensure(sessionId); }, [sessionId]);
return sessionId ? treeStore.get(sessionId) : null;
}
/**
* The ‹ › ring for the message at `turn` while viewing `sessionId`.
*
* Versions are whole sessions: an edit creates a child rewound to before the
* turn. Walking up from the current session, sessions whose edit targets a
* LATER turn still inherit this one, so they are skipped; landing on a
* session that targets exactly this turn means we are viewing one of its
* alternatives, whose original lives in that session's parent.
*/
function ringFor(versions, sessionId, turn) {
if (!versions) return null;
const byId = new Map(versions.map(function (v) { return [v.sessionId, v]; }));
let cursor = byId.get(sessionId);
if (!cursor) return null;
while (cursor.parentSessionId && typeof cursor.targetTurn === 'number' && cursor.targetTurn > turn) {
const parent = byId.get(cursor.parentSessionId);
if (!parent) break;
cursor = parent;
}
let fork = cursor;
while (fork.parentSessionId && typeof fork.targetTurn === 'number' && fork.targetTurn === turn) {
const parent = byId.get(fork.parentSessionId);
if (!parent) break;
fork = parent;
}
function walksToFork(start) {
let x = start;
const seen = new Set();
while (x && !seen.has(x.sessionId)) {
seen.add(x.sessionId);
if (x.sessionId === fork.sessionId) return true;
if (typeof x.targetTurn !== 'number' || x.targetTurn !== turn) return false;
x = x.parentSessionId ? byId.get(x.parentSessionId) : null;
}
return false;
}
// A deleted (ghost) version still anchors the fork and still bridges the
// parent walks above, but it cannot be opened, so it never appears among
// the alternatives: the ring renumbers over the survivors.
const alternatives = versions
.filter(function (v) {
return !v.deleted && (v.sessionId === fork.sessionId || (v.targetTurn === turn && walksToFork(v)));
})
.sort(function (a, b) {
return a.createdAt - b.createdAt || String(a.sessionId).localeCompare(String(b.sessionId));
});
if (alternatives.length < 2) return null;
let index = alternatives.findIndex(function (v) { return v.sessionId === cursor.sessionId; });
if (index === -1) index = alternatives.findIndex(function (v) { return v.sessionId === sessionId; });
if (index === -1) index = 0;
return { alternatives: alternatives, index: index };
}
/* ------------------------------------------------------------ mutations -- */
/**
* Open a version, unarchiving it first when needed. The app cannot navigate
* to an archived session (it bounces to the workspace picker), so an archived
* target is activated through the host route before opening. Ghosts (deleted
* versions) are never openable.
*/
async function openVersionTarget(navigation, v) {
if (!v || v.deleted || !navigation) return;
if (v.archived) {
try {
await mutate({ action: 'activate', sessionId: v.sessionId });
treeStore.invalidate();
} catch (e) {}
}
openWhenListed(navigation, v.sessionId);
}
/**
* Open a version the user picked in the ‹ › ring or the Versions tree. Landing
* on the original that way is a choice, so the open-a-conversation restore
* must not send them back to another version.
*/
function openChosenVersion(navigation, versions, v) {
const root = rootOf(versions, v && v.sessionId);
if (root) restoredFamilies.add(root);
return openVersionTarget(navigation, v);
}
function openWhenListed(navigation, sessionId) {
const list = navigation.list;
const open = navigation.openVersion;
if (!list || typeof list.getSnapshot !== 'function') { open(sessionId); return; }
if (list.getSnapshot().byId[sessionId] !== undefined) { open(sessionId); return; }
const stop = list.subscribe(function () {
if (list.getSnapshot().byId[sessionId] !== undefined) {
stop();
open(sessionId);
}
});
}
async function mutate(operation) {
const g = realGlobal();
const res = await g.fetch(ROUTE, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(operation),
});
const body = await res.json().catch(function () { return {}; });
if (!res.ok) {
const error = new Error(body.error || ('HTTP ' + res.status));
// Refusals the editor can explain in the user's language.
if (body.code === 'context-window') Object.assign(error, { code: body.code, tokens: body.tokens, window: body.window });
throw error;
}
return body;
}
/* ---------------------------------------------------------------- utils -- */
function contentText(content) {
if (!Array.isArray(content)) return '';
let out = '';
for (let i = 0; i < content.length; i++) {
const block = content[i];
if (block && block.type === 'text' && typeof block.text === 'string') {
out += (out ? '\n' : '') + block.text;
}
}
return out;
}
function firstTextBlockIndex(content) {
if (!Array.isArray(content)) return -1;
for (let i = 0; i < content.length; i++) {
if (content[i] && content[i].type === 'text') return i;
}
return -1;
}
function imageCount(content) {
if (!Array.isArray(content)) return 0;
let n = 0;
for (let i = 0; i < content.length; i++) {
if (content[i] && content[i].type === 'image') n += 1;
}
return n;
}
function attachmentParts(content) {
if (!Array.isArray(content)) return [];
const out = [];
for (let i = 0; i < content.length; i++) {
const block = content[i];
if (block && block.attachment) {
if (block.type === 'image') out.push({ type: 'image', image: { attachment: block.attachment } });
else if (block.type === 'file') out.push({ type: 'file', file: block.attachment });
}
}
return out;
}
function clip(text, max) {
const t = String(text).replace(/\s+/g, ' ').trim();
return t.length > max ? t.slice(0, max - 1) + '…' : t;
}
function timeLabel(ms) {
try {
const d = new Date(ms);
const p = function (n) { return n < 10 ? '0' + n : String(n); };
return p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
} catch (e) {
return '';
}
}
/* ---------------------------------------------------------- graph layout -- */
const CARD_W = 176;
const SLOT_X = 206;
const SLOT_Y = 132;
/**
* Project conversation family versions into a turn-level branching tree.
*/
function buildTurnTree(versions, currentSessionId) {
if (!versions || versions.length === 0) return [];
const byId = new Map(versions.map(function (v) { return [v.sessionId, v]; }));
let rootVersion = versions.find(function (v) { return !v.parentSessionId; });
if (!rootVersion) {
const rootId = rootOf(versions, currentSessionId) || (versions[0] && versions[0].sessionId);
rootVersion = (rootId && byId.get(rootId)) || versions[0];
}
const rootSessionId = rootVersion.sessionId;
const activeSessionPath = new Set();
let cursor = byId.get(currentSessionId);
const seenSessions = new Set();
while (cursor && !seenSessions.has(cursor.sessionId)) {
seenSessions.add(cursor.sessionId);
activeSessionPath.add(cursor.sessionId);
cursor = cursor.parentSessionId ? byId.get(cursor.parentSessionId) : null;
}
const nodes = [];
const rootNodeId = rootSessionId + '#root';
const nodeMap = new Map();
const rootNode = {
id: rootNodeId,
sessionId: rootSessionId,
turn: 0,
isRoot: true,
time: rootVersion.createdAt || 0,
current: currentSessionId === rootSessionId && (!rootVersion.turns || rootVersion.turns.length === 0),
onCurrentPath: true,
deleted: !!rootVersion.deleted,
archived: !!rootVersion.archived,
};
nodes.push(rootNode);
nodeMap.set(rootNodeId, rootNode);
function findParentTurnNodeId(v, turn) {
if (!v.parentSessionId) {
if (turn === 1) return rootNodeId;
return v.sessionId + '#t' + (turn - 1);
}
if (turn === v.targetTurn) {
if (v.targetTurn === 1) return rootNodeId;
return v.parentSessionId + '#t' + (v.targetTurn - 1);
}
return v.sessionId + '#t' + (turn - 1);
}
for (let i = 0; i < versions.length; i++) {
const v = versions[i];
const isCurrentSession = v.sessionId === currentSessionId;
const turns = Array.isArray(v.turns) && v.turns.length > 0 ? v.turns : [];
if (!v.parentSessionId) {
for (let j = 0; j < turns.length; j++) {
const t = turns[j];
const turnNum = t.turn;
const turnNodeId = v.sessionId + '#t' + turnNum;
const parentId = findParentTurnNodeId(v, turnNum);
const node = {
id: turnNodeId,
sessionId: v.sessionId,
turn: turnNum,
parentId: parentId,
time: t.time || v.createdAt,
text: t.text || '',
current: isCurrentSession,
onCurrentPath: false,
deleted: !!v.deleted,
archived: !!v.archived,
};
nodes.push(node);
nodeMap.set(turnNodeId, node);
}
} else {
const targetTurn = typeof v.targetTurn === 'number' ? v.targetTurn : 1;
const ownTurns = turns.filter(function (t) { return t.turn >= targetTurn; });
if (ownTurns.length === 0) {
const turnNodeId = v.sessionId + '#t' + targetTurn;
const parentId = findParentTurnNodeId(v, targetTurn);
const node = {
id: turnNodeId,
sessionId: v.sessionId,
turn: targetTurn,
parentId: parentId,
operation: v.operation || 'edit',
text: v.after || v.before || '',
time: v.createdAt || 0,
current: isCurrentSession,
onCurrentPath: false,
deleted: !!v.deleted,
archived: !!v.archived,
};
nodes.push(node);
nodeMap.set(turnNodeId, node);
} else {
for (let j = 0; j < ownTurns.length; j++) {
const t = ownTurns[j];
const turnNum = t.turn;
const turnNodeId = v.sessionId + '#t' + turnNum;
const parentId = findParentTurnNodeId(v, turnNum);
const isForkTurn = turnNum === targetTurn;
const node = {
id: turnNodeId,
sessionId: v.sessionId,
turn: turnNum,
parentId: parentId,
operation: isForkTurn ? v.operation : undefined,
text: t.text || (isForkTurn ? (v.after || v.before || '') : ''),
time: t.time || v.createdAt,
current: isCurrentSession,
onCurrentPath: false,
deleted: !!v.deleted,
archived: !!v.archived,
};
nodes.push(node);
nodeMap.set(turnNodeId, node);
}
}
}
}
const allIds = new Set(nodes.map(function (n) { return n.id; }));