-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.client.js
More file actions
1666 lines (1551 loc) · 70.6 KB
/
Copy pathplugin.client.js
File metadata and controls
1666 lines (1551 loc) · 70.6 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();
/* --------------------------------------------------------------- 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';
const PREFS_DEFAULTS = {
// Restore the last-viewed branch when reopening a conversation.
rememberPath: true,
// Cancel a still-running turn before an edit forks the conversation.
stopOnEdit: 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) {}
const out = {};
for (const k in PREFS_DEFAULTS) {
out[k] = 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(sessions, v) {
if (!v || v.deleted || !sessions) return;
if (v.archived) {
try {
await mutate({ action: 'activate', sessionId: v.sessionId });
treeStore.invalidate();
} catch (e) {}
}
openWhenListed(sessions, v.sessionId);
}
function openWhenListed(sessions, sessionId) {
const list = sessions.list;
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) throw new Error(body.error || ('HTTP ' + res.status));
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 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;
}
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; }));
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].parentId && !allIds.has(nodes[i].parentId)) {
nodes[i].parentId = rootNodeId;
}
}
const activePathIds = new Set();
let latestNode = null;
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
if (n.sessionId === currentSessionId) {
if (!latestNode || (n.turn || 0) >= (latestNode.turn || 0)) {
latestNode = n;
}
}
}
let pathCursor = latestNode || nodes[0];
const seenPath = new Set();
while (pathCursor && !seenPath.has(pathCursor.id)) {
seenPath.add(pathCursor.id);
activePathIds.add(pathCursor.id);
pathCursor = pathCursor.parentId ? nodeMap.get(pathCursor.parentId) : null;
}
activePathIds.add(rootNodeId);
for (let i = 0; i < nodes.length; i++) {
nodes[i].onCurrentPath = activePathIds.has(nodes[i].id);
}
return nodes;
}
/**
* Tidy tree layout for turn nodes: leaves claim successive horizontal slots,
* parents center over their children, siblings ordered by creation time.
*/
function layoutTurnTree(nodes) {
const byId = new Map(nodes.map(function (n) { return [n.id, n]; }));
const children = new Map();
const roots = [];
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
if (n.parentId && byId.has(n.parentId)) {
if (!children.has(n.parentId)) children.set(n.parentId, []);
children.get(n.parentId).push(n);
} else {
roots.push(n);
}
}
children.forEach(function (list) {
list.sort(function (a, b) { return (a.time || 0) - (b.time || 0) || String(a.id).localeCompare(String(b.id)); });
});
roots.sort(function (a, b) { return (a.time || 0) - (b.time || 0) || String(a.id).localeCompare(String(b.id)); });
const pos = new Map();
let cursor = 0;
function walk(n, depth) {
const kids = children.get(n.id) || [];
if (kids.length === 0) {
pos.set(n.id, { x: cursor * SLOT_X, y: depth * SLOT_Y });
cursor += 1;
return;
}
let lo = Infinity, hi = -Infinity;
for (let i = 0; i < kids.length; i++) {
walk(kids[i], depth + 1);
const p = pos.get(kids[i].id);
if (p.x < lo) lo = p.x;
if (p.x > hi) hi = p.x;
}
pos.set(n.id, { x: (lo + hi) / 2, y: depth * SLOT_Y });
}
for (let i = 0; i < roots.length; i++) walk(roots[i], 0);
const edges = [];
children.forEach(function (kids, parentId) {
for (let i = 0; i < kids.length; i++) {
edges.push({ from: parentId, to: kids[i].id, onPath: !!kids[i].onCurrentPath });
}
});
return { pos: pos, edges: edges, byId: byId, nodes: nodes };
}
function edgePath(x1, y1, x2, y2) {
const dy = Math.max(26, (y2 - y1) * 0.5);
return 'M' + x1 + ' ' + y1 + ' C' + x1 + ' ' + (y1 + dy) + ', ' + x2 + ' ' + (y2 - dy) + ', ' + x2 + ' ' + y2;
}
/** Bring the Chat view forward; the first conversation tab is always Chat. */
function showChat() {
const g = realGlobal();
if (!g || !g.document) return;
const tab = g.document.querySelector('[role=tab]');
if (tab && tab.getAttribute('aria-selected') !== 'true') tab.click();
}
/**
* After a graph click lands in a session, glide the chat to the version's own
* message and flash it. Polls because the session view mounts asynchronously.
*/
function flashTurn(sessionId, turn, tries) {
const g = realGlobal();
if (!g || !g.document) return;
const el = g.document.querySelector(
'.mtx-row[data-session="' + sessionId + '"][data-turn="' + String(turn) + '"]');
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
el.classList.remove('mtx-flash');
void el.offsetWidth;
el.classList.add('mtx-flash');
return;
}
if (tries > 0) setTimeout(function () { flashTurn(sessionId, turn, tries - 1); }, 160);
}
/* ------------------------------------------------------------------ css -- */
const CSS = [
// User bubble replica: right-aligned rounded panel like the host's, with a
// hover-revealed edit control to its left, ChatGPT-style.
'.mtx-row{display:flex;flex-direction:column;align-items:flex-end;gap:6px}',
'.mtx-line{display:flex;align-items:flex-start;gap:8px;max-width:min(85%,720px)}',
'.mtx-edit-btn{flex:none;margin-top:8px;width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;border-radius:8px;border:0;background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer;opacity:0;transition:opacity 120ms ease,background 120ms ease}',
'.mtx-row:hover .mtx-edit-btn{opacity:1}',
'.mtx-edit-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
'.mtx-bubble{background:var(--dsw-alias-interactive-bg-hover,rgba(140,140,150,.14));border-radius:16px;padding:10px 16px;font-size:15px;line-height:26px;color:var(--dsw-alias-label-primary);white-space:pre-wrap;overflow-wrap:anywhere}',
'.mtx-img{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}',
// Inline editor, ChatGPT-style: the bubble grows into an editing surface
// with Cancel / Send below-right.
'.mtx-editor{width:min(85%,720px);background:var(--dsw-alias-interactive-bg-hover,rgba(140,140,150,.14));border-radius:16px;padding:12px 16px;display:flex;flex-direction:column;gap:10px}',
'.mtx-textarea{width:100%;min-height:72px;resize:vertical;border:0;outline:none;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:15px;line-height:26px}',
'.mtx-editor-actions{display:flex;justify-content:flex-end;gap:8px}',
'.mtx-btn{padding:6px 16px;border-radius:999px;border:1px solid var(--dsw-alias-border-secondary,rgba(128,128,128,.3));background:transparent;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}',
'.mtx-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}',
'.mtx-btn[data-primary]{background:var(--dsw-alias-accent-primary,#4b8dff);border-color:transparent;color:#fff}',
'.mtx-btn[data-primary]:hover{filter:brightness(1.08)}',
'.mtx-btn[disabled]{opacity:.5;cursor:default}',
'.mtx-error{font-size:12px;color:var(--dsw-alias-status-error,#e5484d)}',
// Version ring, under the bubble: ‹ 2/3 ›.
'.mtx-ring{display:flex;align-items:center;gap:2px;font-size:12px;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums}',
'.mtx-ring button{width:22px;height:22px;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:6px;background:transparent;color:inherit;cursor:pointer;font-size:14px}',
'.mtx-ring button:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
'.mtx-ring button[disabled]{opacity:.35;cursor:default}',
// Versions graph: a pannable canvas with spring-arranged cards and bezier
// edges. Cursor communicates state: grab on canvas, pointer on cards.
'.mtx-graph{position:relative;height:100%;overflow:hidden;cursor:grab;background-image:radial-gradient(color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 22%,transparent) 1px,transparent 1px);background-size:26px 26px;touch-action:none;user-select:none}',
'.mtx-graph[data-panning]{cursor:grabbing}',
'.mtx-world{position:absolute;left:0;top:0;will-change:transform}',
'.mtx-edges{position:absolute;left:0;top:0;overflow:visible;pointer-events:none}',
'.mtx-edge{fill:none;stroke:color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 45%,transparent);stroke-width:1.5}',
'.mtx-edge[data-path]{stroke:var(--dsw-alias-accent-primary,#4b8dff);stroke-width:2}',
'.mtx-card{position:absolute;left:0;top:0;width:176px;box-sizing:border-box;display:flex;align-items:flex-start;gap:8px;padding:10px 12px;border-radius:13px;border:1px solid color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 30%,transparent);background:color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 10%,var(--dsw-alias-bg-primary,rgba(30,30,34,.9)));box-shadow:0 2px 10px rgba(0,0,0,.14);cursor:pointer;will-change:transform;transition:box-shadow 180ms ease,border-color 180ms ease}',
'.mtx-card:hover{box-shadow:0 6px 22px rgba(0,0,0,.24);border-color:color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 55%,transparent)}',
'.mtx-card[data-current]{border-color:var(--dsw-alias-accent-primary,#4b8dff);box-shadow:0 0 0 1px var(--dsw-alias-accent-primary,#4b8dff),0 6px 24px color-mix(in srgb,var(--dsw-alias-accent-primary,#4b8dff) 30%,transparent)}',
'.mtx-card[data-dragging]{cursor:grabbing;box-shadow:0 14px 34px rgba(0,0,0,.3);z-index:3}',
'.mtx-card[data-deleted]{opacity:.55;border-style:dashed;cursor:default}',
'.mtx-card[data-archived]{opacity:.72}',
'.mtx-card[data-deleted]:hover{box-shadow:0 2px 10px rgba(0,0,0,.14);border-color:color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 30%,transparent)}',
'.mtx-card-icon{flex:none;width:24px;height:24px;display:flex;align-items:center;justify-content:center;border-radius:8px;font-size:12px;background:color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 18%,transparent);color:var(--dsw-alias-label-secondary,#bbb)}',
'.mtx-card[data-path] .mtx-card-icon{background:color-mix(in srgb,var(--dsw-alias-accent-primary,#4b8dff) 20%,transparent);color:var(--dsw-alias-accent-primary,#4b8dff)}',
'.mtx-card-main{min-width:0;flex:1}',
'.mtx-card-title{font-size:12.5px;font-weight:600;line-height:17px;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.mtx-card-sub{font-size:11px;line-height:15px;margin-top:2px;color:var(--dsw-alias-label-tertiary);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}',
'.mtx-graph-tools{position:absolute;top:12px;right:14px;display:flex;gap:6px;z-index:4}',
'.mtx-tool{width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border-radius:9px;border:1px solid color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 30%,transparent);background:var(--dsw-alias-bg-primary,rgba(30,30,34,.85));color:var(--dsw-alias-label-secondary,#bbb);cursor:pointer;font-size:14px}',
'.mtx-tool:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}',
'.mtx-empty{position:absolute;left:0;right:0;bottom:26px;text-align:center;color:var(--dsw-alias-label-tertiary);font-size:12.5px;pointer-events:none}',
'.mtx-graph .mtx-link{position:absolute;right:14px;bottom:10px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-decoration:none;z-index:4}',
'.mtx-link:hover{color:var(--dsw-alias-label-primary)}',
'.mtx-error{font-size:12px;color:var(--dsw-alias-status-error,#e5484d)}',
'.mtx-graph .mtx-error{position:absolute;left:14px;top:16px;z-index:4}',
// Flash highlight when a graph click lands on its message.
'@keyframes mtx-flash-kf{0%,55%{background:color-mix(in srgb,var(--dsw-alias-accent-primary,#4b8dff) 22%,transparent)}100%{background:transparent}}',
'.mtx-flash .mtx-bubble{animation:mtx-flash-kf 1.4s ease-out}',
/* ---- action row, below the bubble ------------------------------------ */
// All three references put the message controls BELOW the bubble, not
// beside it. What differs is which controls exist and whether they are
// always visible or revealed on hover.
'.mtx-actions{display:flex;align-items:center;gap:2px;margin-top:1px}',
'.mtx-act{width:26px;height:26px;padding:0;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}',
'.mtx-act:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
'.mtx-act[disabled]{opacity:.4;cursor:default}',
// ChatGPT and Claude reveal the controls on hover; DeepSeek keeps them out,
// which is also how DSH itself behaves.
'html[data-mtx-style=chatgpt] .mtx-actions,html[data-mtx-style=claude] .mtx-actions{opacity:0;transition:opacity 120ms ease}',
'html[data-mtx-style=chatgpt] .mtx-row:hover .mtx-actions,html[data-mtx-style=chatgpt] .mtx-row:focus-within .mtx-actions,',
'html[data-mtx-style=claude] .mtx-row:hover .mtx-actions,html[data-mtx-style=claude] .mtx-row:focus-within .mtx-actions{opacity:1}',
// Only Claude offers a retry control on the user message.
'.mtx-act[data-act=retry]{display:none}',
'html[data-mtx-style=claude] .mtx-act[data-act=retry]{display:inline-flex}',
/* ---- editor button placement ----------------------------------------- */
// ChatGPT and DeepSeek keep Cancel/Send INSIDE the editor box. Claude puts
// them OUTSIDE, below it, and names the primary action Save.
'.mtx-editor-outside{display:none;justify-content:flex-end;align-items:center;gap:8px;margin-top:8px;width:min(85%,720px)}',
'html[data-mtx-style=claude] .mtx-editor-actions{display:none}',
'html[data-mtx-style=claude] .mtx-editor-outside{display:flex}',
/* ---- settings section ------------------------------------------------ */
'.mtx-set{display:flex;flex-direction:column;gap:12px;max-width:560px;font-size:14px;color:var(--dsw-alias-label-primary)}',
'.mtx-set-row{display:flex;align-items:center;justify-content:space-between;gap:12px}',
'.mtx-set-label{font-size:13px}',
'.mtx-select{border-radius:9px;border:1px solid color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 34%,transparent);background:var(--dsw-alias-bg-primary,rgba(30,30,34,.6));color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;padding:6px 10px;outline:none;cursor:pointer}',
'.mtx-set-hint{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}',
'.mtx-preview{margin-top:2px;padding:18px 16px 16px;border-radius:12px;background:color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 7%,transparent);border:1px solid color-mix(in srgb,var(--dsw-alias-label-tertiary,#888) 16%,transparent);pointer-events:none}',
'.mtx-preview .mtx-editor{margin-top:12px}',
'.mtx-preview .mtx-textarea{min-height:auto}',
'.mtx-preview .mtx-actions{opacity:1!important}',
'.mtx-set-link{align-self:flex-end;font-size:12px;color:var(--dsw-alias-label-tertiary);text-decoration:none;pointer-events:auto}',
'.mtx-set-link:hover{color:var(--dsw-alias-label-primary)}',
].join('');
return {
// Module dependencies load code; Cordis injection waits for its services.
// The session controller becomes ready asynchronously after connection.
inject: ['slots', 'sessions', 'locale'],
apply(ctx) {
const slots = ctx.get('slots');
if (slots === undefined) {
throw new Error('[dsh-plugin-message-edit] Missing DSH slots service. Check dsh.client.inject and restart DSH.');
}
ctx.effect(function () { return styles.insert(CSS); });
// Reflect the chosen edit style onto <html> now and on every change.
ctx.effect(function () { syncStyleAttribute(); return styleStore.subscribe(syncStyleAttribute); });
const sessions = ctx.get('sessions');
if (!sessions || typeof sessions.open !== 'function') {
throw new Error('[dsh-plugin-message-edit] Missing DSH session navigation service. Check client dependencies and restart DSH.');
}
ctx.effect(function () {
if (sessions && sessions.list && typeof sessions.list.subscribe === 'function') {
return sessions.list.subscribe(function () { treeStore.invalidate(); });
}
});
// Session-list state straight from the service, so this works no matter
// what props the host chooses to pass slot components.
function useSessionList() {
const [, force] = React.useReducer(function (x) { return x + 1; }, 0);
React.useEffect(function () {
if (!sessions || !sessions.list || typeof sessions.list.subscribe !== 'function') return undefined;
return sessions.list.subscribe(force);
}, []);
return sessions && sessions.list && typeof sessions.list.getSnapshot === 'function'
? sessions.list.getSnapshot()
: { byId: {} };
}
const I18N_NS = 'dsh-plugin-message-tree';
const I18N = {
en: {
view: 'Versions',
edit: 'Edit message',
cancel: 'Cancel',
send: 'Send',
save: 'Save',
copy: 'Copy',
copied: 'Copied',
retry: 'Retry this turn',
regen: 'Regenerate from here',
original: 'Original conversation',
turn: 'Turn {turn}',
edited: 'Edited turn {turn}',
retried: 'Regenerated turn {turn}',
branch: 'Branch',
refresh: 'Refresh',
fit: 'Center view',
empty: 'No versions yet — edit any of your messages to branch this conversation. Drag to pan, scroll to zoom.',
images: '{count} image(s) kept as-is',
nav: 'Message Edit',
styleLabel: 'Edit interface style',
styleHint: 'Where the message controls sit and which ones appear. Changes apply live.',
style_chatgpt: 'ChatGPT',
style_deepseek: 'DeepSeek',
style_claude: 'Claude',
styleDesc_chatgpt: 'Copy and edit under the bubble, revealed on hover. Cancel and Send sit inside the editor.',
styleDesc_deepseek: 'Copy and edit under the bubble, always visible — closest to DSH itself. Cancel and Send sit inside the editor.',
styleDesc_claude: 'Retry, edit and copy under the bubble, revealed on hover. Cancel and Save sit below the editor.',
deletedVersion: 'Deleted version',
archivedTag: 'Archived',
rememberPathLabel: 'Remember the version I was viewing',
rememberPathHint: 'Reopening a conversation returns to the branch you last had open instead of the original. Off means it always opens the first version.',
stopOnEditLabel: 'Stop the running reply when I edit',
stopOnEditHint: 'Editing or retrying cancels every reply still being generated in this conversation before branching, including other versions, so no superseded answer keeps spending tokens. This also lets you edit mid-reply. Off leaves them running.',
previewUser: 'Rewrite this paragraph to be more concise.',
},
zh: {
view: '版本',
edit: '编辑消息',
cancel: '取消',
send: '发送',
save: '保存',
copy: '复制',
copied: '已复制',
retry: '重试本轮',
regen: '从这里重新生成',
original: '原始对话',
turn: '第 {turn} 轮',
edited: '编辑了第 {turn} 轮',
retried: '重新生成第 {turn} 轮',
branch: '分支',
refresh: '刷新',
fit: '居中显示',
empty: '还没有版本——编辑任意一条你的消息即可创建分支。拖动平移,滚轮缩放。',
images: '{count} 张图片将原样保留',
nav: '消息编辑',
styleLabel: '编辑界面风格',
styleHint: '消息操作按钮的位置与种类。修改即时生效。',
style_chatgpt: 'ChatGPT',
style_deepseek: 'DeepSeek',
style_claude: 'Claude',
styleDesc_chatgpt: '气泡下方为复制与编辑,悬停时显示;「取消 / 发送」位于编辑框内部。',
styleDesc_deepseek: '气泡下方为复制与编辑,始终显示——最接近 DSH 原生;「取消 / 发送」位于编辑框内部。',
styleDesc_claude: '气泡下方为重试、编辑与复制,悬停时显示;「取消 / 保存」位于编辑框下方。',
deletedVersion: '已删除的版本',
archivedTag: '已归档',
rememberPathLabel: '记住我正在查看的版本',
rememberPathHint: '重新打开会话时回到上次查看的分支,而不是最初那条。关闭后始终打开第一个版本。',
stopOnEditLabel: '编辑时中止正在生成的回复',
stopOnEditHint: '编辑或重试时,先取消该会话中所有仍在生成的回复(包括其它版本)再分支,避免被取代的回答继续消耗额度;同时允许在回复过程中直接编辑。关闭后它们会继续跑完。',
previewUser: '把这段话改写得更简洁一些。',
},
};
let t = function (key, params) {
let out = I18N.en[key] || key;
if (params) for (const k in params) out = out.replace('{' + k + '}', String(params[k]));
return out;
};
try {
const locale = ctx.get('locale');
if (locale && typeof locale.register === 'function' && typeof locale.bind === 'function') {
ctx.effect(function () { return locale.register(I18N_NS, I18N); });
t = locale.bind(I18N_NS);
}
} catch (e) {
console.warn('[dsh-plugin-message-edit] Failed to register translations; using English.', e);
}
function PencilIcon() {
return React.createElement('svg', { width: 15, height: 15, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true },
React.createElement('path', {
d: 'M11.1 2.4a1.6 1.6 0 012.3 2.3l-7.2 7.2-3 .8.8-3 7.1-7.3z',
stroke: 'currentColor', strokeWidth: 1.3, strokeLinejoin: 'round',
}));
}
function CopyIcon() {
return React.createElement('svg', { width: 15, height: 15, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true },
React.createElement('rect', {
x: 5.4, y: 5.4, width: 8.2, height: 8.2, rx: 2,
stroke: 'currentColor', strokeWidth: 1.3,
}),
React.createElement('path', {
d: 'M10.6 5.2V4.2a1.8 1.8 0 00-1.8-1.8H4.2a1.8 1.8 0 00-1.8 1.8v4.6a1.8 1.8 0 001.8 1.8h1',
stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round',
}));
}
function RetryIcon() {