Repository navigation
Expand file tree
/
Copy pathplugin.client.js
More file actions
4371 lines (4182 loc) · 211 KB
/
Copy pathplugin.client.js
File metadata and controls
4371 lines (4182 loc) · 211 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-tree-view — 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, i18n namespace and storage keys all moved off the upstream
// `message-tree` spelling (`/tree-view`, `dsh-tree-view:*`) so this fork and
// dsh-plugin-message-edit can be installed together without their routes,
// locales or persisted UI state colliding. The durable event type keeps the
// upstream name on purpose — see the note in lib/index.js.
const ROUTE = '/tree-view';
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;
}
/* ------------------------------------------------------------ diagnostics -- */
// Client diagnostics ride back to the host over the same route as every other
// action, so a report never has to be transcribed from a DevTools console. The
// renderer's console is not persisted anywhere the host can read, and most of
// what matters for a "the tree did the wrong thing" report happens in the
// renderer — including errors the app's own sidebar logs. Lines still reach the
// local console too, for whoever has it open.
//
// The queue is deliberately lossy and fire-and-forget: a dropped line is fine, a
// canvas that waits on a network round trip is not.
const nativeLog = typeof console !== 'undefined' && console.log ? console.log.bind(console) : function () {};
const nativeWarn = typeof console !== 'undefined' && console.warn ? console.warn.bind(console) : function () {};
const nativeError = typeof console !== 'undefined' && console.error ? console.error.bind(console) : function () {};
const logQueue = [];
let logFlushTimer = 0;
function remoteLog(level, message, meta) {
(level === 'error' ? nativeError : level === 'warn' ? nativeWarn : nativeLog)('[dsh-tree-view] ' + message, meta === undefined ? '' : meta);
const g = realGlobal();
if (!g || typeof g.fetch !== 'function') return;
logQueue.push({ level: level, message: message, meta: meta === undefined ? undefined : meta });
if (logQueue.length > 300) logQueue.shift();
if (logFlushTimer) return;
logFlushTimer = setTimeout(function () {
logFlushTimer = 0;
const batch = logQueue.splice(0, logQueue.length);
if (batch.length === 0) return;
const now = realGlobal();
if (!now || typeof now.fetch !== 'function') return;
now.fetch(ROUTE, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ action: 'log', entries: batch }),
}).catch(function () {});
}, 250);
}
// Forward renderer errors that are not ours — the app's own races included — so
// the next "it jumps back" report carries the actual failure without a DevTools
// paste. Uncaught errors and rejections go through the window handlers; the
// console.error wrapper is what catches the app's "Sidebar Session opening
// failed" style diagnostics, which are logged, not thrown.
let errorForwardingInstalled = false;
const ERROR_HOOK_MARK = '__dshTreeViewErrorHooked';
function installErrorForwarding() {
if (errorForwardingInstalled) return;
errorForwardingInstalled = true;
const g = realGlobal();
if (!g) return;
try {
// Marked on the shared console object so a re-mounted bundle never stacks a
// second wrapper on top of the first (the tests remount the client per case).
if (typeof console !== 'undefined' && typeof console.error === 'function' && !console[ERROR_HOOK_MARK]) {
console[ERROR_HOOK_MARK] = true;
const original = console.error;
console.error = function () {
try { original.apply(console, arguments); } catch (e) {}
const text = Array.prototype.map.call(arguments, function (a) {
return a && a.stack ? String(a.stack) : typeof a === 'string' ? a : (function () { try { return JSON.stringify(a); } catch (e) { return String(a); } })();
}).join(' ').slice(0, 2000);
if (text) remoteLog('error', 'console.error: ' + text);
};
}
} catch (e) {}
try {
if (g.addEventListener) {
g.addEventListener('error', function (event) {
const message = event && (event.message || (event.error && event.error.message));
if (message) remoteLog('error', 'uncaught: ' + message);
});
g.addEventListener('unhandledrejection', function (event) {
const reason = event && event.reason;
const message = reason && (reason.message || String(reason));
if (message) remoteLog('error', 'unhandledrejection: ' + message);
});
}
} catch (e) {}
}
/* ------------------------------------------------------------- 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-tree-view: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-tree-view: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();
// The session rendered just before the current one. Landing on a family root
// from inside that same family is a deliberate move — the sidebar entry points
// at the root, and that entry is how you leave a branch — while landing from
// anywhere else is exactly what the restore is for.
let lastViewedSessionId;
/* --------------------------------------------------------------- prefs -- */
// Behaviour toggles, persisted next to the style choice. `v` is the schema
// version, and it exists for one migration: `rememberPath` shipped on, and it
// navigated the app away from the conversation you had just clicked. Reading a
// conversation must not move you somewhere else, so it now defaults to off.
const PREFS_VERSION = 2;
const PREFS_KEY = 'dsh-tree-view:prefs';
const PREFS_DEFAULTS = {
// Jump back to the branch you last had open when you come back to its family.
// Off by default: a click on a conversation opens that conversation. On, it
// still refuses to fire on a page load, on a move inside the same family, or
// for a branch the sidebar is not listing — see the restore in UserMessageView.
rememberPath: false,
// Cancel a still-running turn before an edit forks the conversation.
stopOnEdit: true,
// Hide forks that copied the conversation and never added a turn of their own.
// On by default, because a photocopy drawn as a branch doubles the canvas; the
// switch in the Tree panel is there for when you want to see them anyway.
dropEmptyForks: true,
// Hide subagent conversations from the tree. Off by default: the label already
// tells a reader that a card is a subagent, and erasing it is a different
// promise from marking it. When hiding would leave nothing to draw — the
// reader is inside a subagent conversation — the filter is skipped rather than
// handing back an empty canvas.
hideSubagents: false,
// Straight stretches longer than this fold into a single node (0 = never
// fold). That covers the shared history above the first fork and the
// unbranched run any one branch continues on. A fold node unfolds again, and
// the toolbar can fold any stretch by hand.
foldSharedAt: 8,
};
// The preferences that hold a number rather than a switch.
const PREFS_NUMBERS = { foldSharedAt: true };
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) {}
// A preference object written before this schema carries `rememberPath:
// true` — either because that was the default or because it was turned on
// — and the two cannot be told apart. That one stored value is dropped so
// the new default takes effect; every other toggle survives, and turning
// this one on again writes the current version and is honoured from then
// on. (Only `rememberPath` changed meaning: a stored preference is
// otherwise never taken away from the user.)
const current = !!parsed && parsed.v === PREFS_VERSION;
const out = {};
for (const k in PREFS_DEFAULTS) {
const kindOk = !!parsed
&& (PREFS_NUMBERS[k] ? typeof parsed[k] === 'number' : typeof parsed[k] === 'boolean');
const usable = kindOk && (current || k !== 'rememberPath');
out[k] = usable ? parsed[k] : PREFS_DEFAULTS[k];
}
this.value = out;
}
return this.value;
},
set(patch) {
const next = Object.assign({}, this.get(), patch, { v: PREFS_VERSION });
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);
};
},
};
// How long straight stretches are drawn, per family: 'auto' follows the
// threshold in Settings, 'expanded' keeps them all open, 'folded' closes them by
// hand. Kept for the page rather than for one mount, so switching tabs or views
// does not undo a choice the reader just made.
const foldModes = new Map();
// What the fold threshold can be. 0 means "never fold on its own"; the toolbar
// button folds by hand either way.
const FOLD_CHOICES = [0, 5, 8, 12, 20];
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;
// The host builds a tree payload by reading and parsing every version's log, which
// on this conversation's family measured 3.7-5.2 seconds — and a client that has
// never loaded that family sits on an empty canvas for exactly that long. So the
// last payload is kept in storage and painted at once, then replaced by the fresh
// one when it arrives. A second of a stale archive flag or `current` mark is a fair
// price for not staring at nothing; the refresh follows immediately.
const TREE_CACHE_KEY = 'dsh-tree-view:tree:';
const TREE_CACHE_INDEX = 'dsh-tree-view:tree:index';
const TREE_CACHE_LIMIT = 6;
const TREE_CACHE_MAX_CHARS = 500000;
// How long a painted tree is trusted before it is refreshed in the background. The
// host's rebuild is expensive (see above), and anything the reader would notice —
// a new version, a collected branch — invalidates this cache instead.
const TREE_REVALIDATE_MS = 60000;
function rememberTree(sessionId, versions, archiveSupport) {
const g = realGlobal();
if (!g || !g.localStorage || !sessionId) return;
try {
const body = JSON.stringify({ at: Date.now(), versions: versions, archiveSupport: archiveSupport ?? null });
if (body.length > TREE_CACHE_MAX_CHARS) return;
g.localStorage.setItem(TREE_CACHE_KEY + sessionId, body);
const raw = g.localStorage.getItem(TREE_CACHE_INDEX);
const index = raw ? JSON.parse(raw) : [];
const keep = [sessionId].concat(index.filter(function (id) { return id !== sessionId; })).slice(0, TREE_CACHE_LIMIT);
for (const id of index) {
if (keep.indexOf(id) === -1) g.localStorage.removeItem(TREE_CACHE_KEY + id);
}
g.localStorage.setItem(TREE_CACHE_INDEX, JSON.stringify(keep));
} catch (e) {
// A full or blocked store costs us the head start, never the tree.
}
}
function recallTree(sessionId) {
const g = realGlobal();
if (!g || !g.localStorage || !sessionId) return null;
try {
const raw = g.localStorage.getItem(TREE_CACHE_KEY + sessionId);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!parsed || !Array.isArray(parsed.versions)) return null;
return parsed;
} catch (e) {
return null;
}
}
// 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, archiveSupport) {
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,
// The host's capability report travels with the payload: the panel uses
// it to disable what cannot work.
archiveSupport: archiveSupport ?? (existingRoot && existingRoot.archiveSupport) ?? null,
};
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();
// Remembered so the next cold open of this family paints at once (see the
// cache note above); the host's fresher answer replaces it moments later.
rememberTree(sessionId, versions, entry.archiveSupport);
this.notify();
},
/**
* Patch one version inside the cached family.
*
* The host answers a move immediately, but the refetch that follows is a
* round trip; without this the menu would still offer "collect into the tree"
* right after doing exactly that. The refetch then reconciles whatever the
* host actually settled on.
*/
patchVersion(sessionId, versionSessionId, patch) {
const entry = this.bySession.get(sessionId);
if (!entry || !Array.isArray(entry.versions)) return;
const versions = entry.versions.map(function (v) {
return v && v.sessionId === versionSessionId ? Object.assign({}, v, patch) : v;
});
this.setTree(sessionId, versions, entry.updatedAt || Date.now());
},
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 });
}
// Nothing to show and the host needs seconds to answer: paint what this family
// looked like last time. Its own timestamp is used so the answer on its way
// still counts as newer and replaces this.
if (!existing || !existing.versions) {
const remembered = recallTree(sessionId);
if (remembered) {
this.setTree(sessionId, remembered.versions, remembered.at, remembered.archiveSupport);
}
}
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, data.archiveSupport);
} 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,
archiveSupport: prev ? prev.archiveSupport : null,
});
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) > TREE_REVALIDATE_MS && !entry.loading) {
// Background revalidation. This is deliberately unhurried: the host rebuilds
// the whole payload (3.7-5.2 seconds on a large family), so asking every few
// seconds burned host CPU for nothing — the canvas is already painted, and a
// new version arrives through a session-list change, which invalidates this
// cache outright rather than waiting for the interval.
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(sessions, v) {
if (!v || v.deleted || !sessions) return;
remoteLog('info', 'open: ' + v.sessionId + ' archived=' + v.archived + (sessions.unarchive ? ' (workspace unarchive available)' : ''));
if (v.archived) {
// Bringing a collected version back out is a *client* operation on 0.1.7
// (`uiWorkspace.unarchiveSession`), and that is the whole difference: our own
// host route writes the archive registry behind the client's back, so the
// client catalogue never learns the session and `openSession` keeps refusing
// it — which is precisely how the way back to a collected version ended up on
// the session you were leaving. The host route stays as the fallback for hosts
// whose workspace has no unarchive of its own.
let unarchived = false;
if (typeof sessions.unarchive === 'function') {
try {
unarchived = await sessions.unarchive(v.sessionId);
} catch (e) {
remoteLog('warn', 'could not bring the version back out:', e && e.message ? e.message : e);
}
}
if (!unarchived) {
try {
await mutate({ action: 'activate', sessionId: v.sessionId });
} catch (e) {
// Swallowing this used to hide a click that could never work.
remoteLog('warn', 'could not unarchive the version through the host either:', e && e.message ? e.message : e);
}
}
treeStore.invalidate();
}
openWhenListed(sessions, v.sessionId);
}
function collectLeftVersion(sessions, left, target, versions) {
if (!left || left === target) return;
const list = versions || [];
const entry = list.find(function (v) { return v.sessionId === left; });
// An archived version has nothing left to collect, and one that is still
// generating a reply is left alone: archiving mid-turn would hide work that is
// still arriving.
if (!entry || entry.archived || entry.deleted || entry.running === true) return;
// Only ever inside one family: leaving a conversation for another one is not a
// version switch.
if (rootOf(list, left) !== rootOf(list, target)) return;
mutate({ action: 'demote', sessionId: left })
.then(function () { treeStore.load(target); })
.catch(function (error) {
// Nothing to recover from: the version simply stays where it is.
remoteLog('warn', 'could not collect the version you left:', error && error.message);
});
}
/**
* Put the version you leave away — but only once the app is really showing the
* version you asked for.
*
* The order is the whole point, and issuing the collect in the click's own tick was
* wrong: the session on screen was archived while the reveal of the target was
* still in flight, the workspace re-revealed its own fallback, and the reader ended
* up on the session they had just left. That is what made clicking a second node
* look like it jumped to the new session.
*
* The signal is the host's, not the component's: the session list marks the
* sessions the main view is retaining, and opening the target retains it. Watching
* that survives the view being remounted on the switch — a pending intent kept in a
* React ref died with the old component, which is how the collect went missing
* altogether. If retention is never reported (older hosts keep no such field), a
* bounded wait collects anyway rather than never.
*/
function collectAfterSwitch(sessions, left, target, versions) {
if (!left || left === target) return;
const collect = function () { collectLeftVersion(sessions, left, target, versions); };
const retained = function () {
const list = sessions && typeof sessions.list === 'function' ? sessions.list() : null;
if (!list || typeof list.getSnapshot !== 'function') return true;
const snapshot = list.getSnapshot();
const entry = snapshot && snapshot.byId ? snapshot.byId[target] : null;
return !!(entry && entry.retainedBy);
};
if (retained()) { collect(); return; }
const list = sessions && typeof sessions.list === 'function' ? sessions.list() : null;
let done = false;
let stop = function () {};
const finish = function () {
if (done) return;
done = true;
clearTimeout(timer);
stop();
collect();
};
if (list && typeof list.subscribe === 'function') {
stop = list.subscribe(function () { if (retained()) finish(); });
}
// A host that never reports retention still has to collect: waiting forever is
// how the collect went missing in the first place.
const timer = setTimeout(finish, 2000);
}
/**
* Session navigation, looked up instead of declared.
*
* "Show this session in the main view" has moved between DSH versions: 0.1.5 and
* 0.1.6 keep it on the session controller (`sessions.open`), and 0.1.7 moved it
* to the workspace service (`uiWorkspace.openSession`). Declaring either as a
* hard `inject` is what breaks the other — a service the host never provides
* leaves the plugin parked forever, and DSH Desktop deselects a client plugin
* whose boot does not finish. So both are looked up lazily, at click time, and a
* host that offers neither leaves the tree readable instead of refusing to boot.
*/
function sessionNavigator(ctx) {
// Every navigation takes a token; a newer one invalidates the retries of an older
// one, so a stale attempt can never drag the reader back to a version they left.
let navigationToken = 0;
function service(name) {
return ctx && typeof ctx.get === 'function' ? ctx.get(name) : undefined;
}
/**
* The session the main view is really showing, or null when this host's list
* snapshot carries no retention information.
*/
function mainSessionId() {
const sessions = service('sessions');
const list = sessions && sessions.list;
if (!list || typeof list.getSnapshot !== 'function') return null;
const snapshot = list.getSnapshot();
const byId = snapshot && snapshot.byId;
if (!byId) return null;
let seen = false;
let first = null;
for (const id in byId) {
const entry = byId[id];
if (!entry || entry.retainedBy === undefined) continue;
seen = true;
if (entry.retainedBy && entry.retainedBy.length > 0 && first === null) first = id;
}
return seen ? first : null;
}
return {
list: function () {
const sessions = service('sessions');
return sessions && sessions.list;
},
mainSession: mainSessionId,
/**
* Run `callback` once the main view really shows `sessionId`.
*
* Clicking a node also opens the Chat tab, and flipping to it in the click's own
* tick showed the session you were leaving for a moment — the report "it flashes
* the new conversation and then jumps to the target". A host that does not
* report retention cannot be asked, so it keeps the immediate behaviour rather
* than guessing; the callback always runs, at the latest after three seconds.
*/
whenMain: function (sessionId, callback) {
const current = mainSessionId();
if (current === null || current === sessionId) { callback(); return; }
let tries = 0;
const poll = function () {
tries += 1;
if (mainSessionId() === sessionId || tries >= 25) { callback(); return; }
setTimeout(poll, 120);
};
setTimeout(poll, 120);
},
/**
* Bring a collected version back out of the tree, through the client.
*
* The app owns this in 0.1.7 (`uiWorkspace.unarchiveSession`) and it also
* refreshes the client's own catalogue; our host route, by contrast, changes the
* registry without telling the client, which then keeps refusing to open a
* session it believes is still archived. Returns false when this host has no such
* method, so the caller can fall back to the route.
*/
unarchive: async function (sessionId) {
const workspace = service('uiWorkspace');
if (workspace && typeof workspace.unarchiveSession === 'function') {
await workspace.unarchiveSession(sessionId);
return true;
}
return false;
},
/**
* Show a session, retrying while the client's session manager catches up.
*
* 0.1.7's `uiWorkspace.openSession` throws when the manager does not know the
* target yet: `resolveTarget` refuses an id that is neither loaded nor in the
* catalogue. That is precisely the state a version comes out of the tree in —
* it was archived, the host has just unarchived it, and the client catalogue is
* still a step behind — and the throw used to escape silently, so the click did
* nothing at all and the reader stayed on the session they were on. Retrying is
* the whole fix; giving up loudly is the floor.
*
* Only the newest navigation may retry. Click two nodes quickly and the first
* one's pending retries would otherwise land after the second click and drag the
* reader back to the version they had already left — which is exactly what
* "fast clicking still jumps to the new conversation" was.
*/
open: function (sessionId) {
const token = ++navigationToken;
const reinforce = function () {
// One idempotent re-issue after the dust settles. 0.1.7's right sidebar
// re-syncs its retained session views when the main session changes, and a
// stale sync can prune the freshly-created view while it is still opening
// — the console reports "Sidebar Session opening failed: … is released" and
// the main view never lands on the target. openSession to the same target is
// harmless, so a second call after the race re-establishes it. A newer click
// bumps the token and cancels this.
if (token !== navigationToken) return;
const workspace = service('uiWorkspace');
if (workspace && typeof workspace.openSession === 'function') {
try { workspace.openSession(sessionId); }
catch (e) { remoteLog('warn', 'reinforce failed for ' + sessionId + ': ' + (e && e.message ? e.message : e)); }
}
};
const attempt = function (left) {
// Superseded by a later click: this navigation is stale, drop it.
if (token !== navigationToken) return false;
const workspace = service('uiWorkspace');
if (workspace && typeof workspace.openSession === 'function') {
try {
workspace.openSession(sessionId);
setTimeout(reinforce, 400);
return true;
} catch (e) {
if (left > 0) { setTimeout(function () { attempt(left - 1); }, 150); return false; }
remoteLog('warn', 'could not open ' + sessionId + ': ' + (e && e.message ? e.message : e));
return false;
}
}
const sessions = service('sessions');
if (sessions && typeof sessions.open === 'function') {
try {
sessions.open(sessionId);
setTimeout(reinforce, 400);
return true;
} catch (e) {
if (left > 0) { setTimeout(function () { attempt(left - 1); }, 150); return false; }
remoteLog('warn', 'could not open ' + sessionId + ': ' + (e && e.message ? e.message : e));
return false;
}
}
remoteLog('warn', 'This DSH build exposes no session navigation service; the tree stays readable, switching versions does not.');
return false;
};
// 20 tries over three seconds: long enough for an unarchive to reach the
// catalogue, short enough that a real refusal is reported rather than hidden.
return attempt(20);
},
};
}
function openWhenListed(sessions, sessionId) {
const list = sessions.list ? sessions.list() : null;
if (!list || typeof list.getSnapshot !== 'function') { sessions.open(sessionId); return; }
if (list.getSnapshot().byId[sessionId] !== undefined) { sessions.open(sessionId); return; }
const stop = list.subscribe(function () {
if (list.getSnapshot().byId[sessionId] !== undefined) {
stop();
sessions.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) {
// The body rides on the error: a refusal carries the list of busy sessions,
// which is exactly what the panel has to ask about.
const failure = new Error(body.error || ('HTTP ' + res.status));
failure.body = body;
throw failure;
}
return body;
}
/**
* The last view position of each conversation, for the lifetime of the page.
*
* The host unmounts this view whenever the reader leaves the Tree tab, and coming back
* used to re-frame the whole tree from scratch — so a reader who had panned to one branch
* lost it every time they looked at the conversation. This is a position, not data: it
* lives in memory and is dropped with the page.
*/
const viewMemory = new Map();
/* ---------------------------------------------------------------- utils -- */
/**
* Split a user message into the shape the host's user-content renderer takes.
*
* This mirrors the host's own `contentParts` on purpose: the message body is
* only half of what a user message carries, and the part that turns `@file`
* and session references into clickable chips lives downstream of the host
* renderer, not in the text. Anything this function cannot account for is
* handed back as an extra block instead of being dropped.
*/
function contentParts(content) {
const texts = [];
const attachments = [];
const rest = [];
if (Array.isArray(content)) {
for (let i = 0; i < content.length; i++) {
const block = content[i];
if (!block || typeof block !== 'object') { rest.push(block); continue; }
if (block.type === 'text' && typeof block.text === 'string') {
texts.push(block.text);
} else if (block.type === 'image' && block.attachment !== undefined) {
attachments.push({ type: 'image', image: { attachment: block.attachment } });
} else if (block.type === 'file' && block.attachment !== undefined) {
attachments.push({ type: 'file', file: block.attachment });
} else {
rest.push(block);
}
}
}
// Text blocks concatenate, they do not gain a separator: that is what the
// host does, and the chat is not ours to re-punctuate.
return { text: texts.join(''), attachments, rest };
}
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 imageParts(content) {
if (!Array.isArray(content)) return [];
const out = [];
for (let i = 0; i < content.length; i++) {
const block = content[i];
if (block && block.type === 'image' && block.attachment) out.push({ attachment: block.attachment });
}
return out;
}
/**
* Draw a user message through the host's own user-content factory.
*
* This view replaces the host row, so it inherits the host row's duties. The
* text is the smallest of them: `@file` and session references only become
* chips, and only become clickable, inside the host renderer — it parses the
* text against its reference rules and wires each chip to its own open action.
* A renderer that draws the joined string instead shows the same characters
* with none of that, which reads as "the style broke".
*
* Returns null when this host has no such factory (older hosts), so the caller
* can keep the plain bubble rather than fail to render the message at all.
*
* @param props - the Chat node renderer's props, which carry the factory seat.