-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
1604 lines (1526 loc) · 50.7 KB
/
Copy pathplugin.js
File metadata and controls
1604 lines (1526 loc) · 50.7 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
/**
* harness-progress — Hermes Desktop trajectory pane
*
* Session keys: gateway events use RUNTIME id; the pane title uses STORED id
* (20260819_…). Those two must alias or the bar stays empty.
*
* i18n: ctx.i18n.register + nested keys (en / zh / zh-hant / ja / ar).
* 8 colors. History stays after a turn ends. One bucket per bot + chat.
*/
import {
atom,
cn,
host,
PALETTE_AREA,
SegmentedControl,
STATUSBAR_AREAS,
Tip,
usePluginI18n,
useValue
} from '@hermes/plugin-sdk'
import { useEffect, useRef, useState } from 'react'
import { jsx, jsxs } from 'react/jsx-runtime'
const ID = 'harness-progress'
const VERSION = '0.0.2'
const MAX_EVENTS = 240
const LANE_H = 24
const SPAN_H = 11
const SPAN_W = 16
const LANE_LABEL_W = 44
const TIMELINE_H = 88
const VIEWS = ['table', 'list', 'board', 'time']
const LANE_KEYS = ['input', 'model', 'tools']
const POOL = ['user', 'context', 'thinking', 'message', 'tool', 'subagent', 'approval', 'error', 'todo', 'goal', 'background', 'compact']
const DEFAULT_LANES = [
['user', 'context'],
['thinking', 'message'],
['tool', 'subagent', 'approval', 'error']
]
const store = { api: null }
const $buckets = atom({})
const $aliases = atom({})
const $viewKey = atom('')
const $selected = atom(null)
const $mode = atom('table')
const $layouts = atom({})
const $edit = atom(null)
const DEFAULT = {
user: '#4b5cc4',
context: '#789262',
thinking: '#801dae',
message: '#d6ecf0',
tool: '#ff8936',
subagent: '#30dff3',
approval: '#d9b611',
error: '#c3272b',
todo: '#38bdf8',
goal: '#c084fc',
background: '#94a3b8',
compact: '#14b8a6'
}
const KIND = {
user: 1,
context: 1,
thinking: 1,
message: 1,
tool: 1,
subagent: 1,
approval: 1,
error: 1,
todo: 1,
goal: 1,
background: 1,
compact: 1
}
const KIND_ALIAS = {
system: 'context',
compacted: 'compact',
subtool: 'tool',
result: 'tool'
}
const LOCALES = {
en: {
title: 'Trajectory',
chip: 'Trajectory',
emptyTitle: 'No steps yet',
emptyBody: 'Send a message. Colors stay after the turn. Switching chat or bot keeps histories apart.',
idle: 'Idle',
steps: (n) => `${n} steps`,
running: (tags) => `Live ${tags}`,
clear: 'Clear this chat',
view: { board: 'Board', list: 'List', table: 'Table', time: 'Time' },
when: { today: 'Today' },
col: { time: 'Time', lane: 'Lane', kind: 'Kind', text: 'What', dur: 'Dur' },
help: 'Help: Trajectory',
helpBody: 'Right-hand column. Scroll the color bar. One history per chat and bot.',
none: 'No trajectory',
lane: { input: 'Prompt', model: 'Model', tools: 'Tools' },
kind: {
user: 'PROMPT',
context: 'CTX',
thinking: 'THINK',
message: 'REPLY',
tool: 'TOOL',
subagent: 'TASK',
approval: 'WAIT',
error: 'ERR',
todo: 'TODO',
goal: 'GOAL',
background: 'BG',
compact: 'PACK'
},
legend: {
user: 'Prompt',
context: 'Context',
thinking: 'Think',
message: 'Reply',
tool: 'Tool',
subagent: 'Subtask',
approval: 'Confirm',
error: 'Error',
todo: 'Todo',
goal: 'Goal',
background: 'Background',
compact: 'Compact'
},
edit: { add: 'Add', done: 'Done' },
evt: {
round: (n) => `Turn ${n}`,
thinking: 'Thinking',
writing: 'Writing',
todo: 'Update todos',
tool: (name) => name || 'Tool',
result: (name) => (name ? `${name} returned` : 'Tool result'),
toolFailed: (name) => (name ? `${name} failed` : 'Tool failed'),
subagent: (name) => name || 'Subagent',
subtool: (name) => name || 'Subagent tool',
clarify: 'Needs a question',
approve: 'Waiting for approval',
compact: 'Context compacted',
context: 'Context update',
error: (msg) => msg || 'Error'
}
},
zh: {
title: '轨迹',
chip: '轨迹',
emptyTitle: '这场还没有轨迹',
emptyBody: '发一条消息就会按颜色留下每一步。换对话或换 bot 不会混。',
idle: '空闲',
steps: (n) => `${n} 步`,
running: (tags) => `进行中 ${tags}`,
clear: '清空本场',
view: { board: '看板', list: '列表', table: '表格', time: '时间' },
when: { today: '今天' },
col: { time: '时间', lane: '列', kind: '种类', text: '内容', dur: '耗时' },
help: '轨迹说明',
helpBody: '右边单独一列。色轴可左右滑。换会话或换 bot 各看各的。',
none: '还没有轨迹',
lane: { input: '提问', model: '模型', tools: '工具' },
kind: {
user: '提问',
context: '上下文',
thinking: '思考',
message: '回答',
tool: '工具',
subagent: '子任务',
approval: '待确认',
error: '出错',
todo: '任务',
goal: '目标',
background: '后台',
compact: '压缩'
},
legend: {
user: '提问',
context: '上下文',
thinking: '思考',
message: '回答',
tool: '工具',
subagent: '子任务',
approval: '待确认',
error: '出错',
todo: '任务',
goal: '目标',
background: '后台',
compact: '压缩'
},
edit: { add: '添加', done: '完成' },
evt: {
round: (n) => `第 ${n} 轮`,
thinking: '思考',
writing: '生成回复',
todo: '更新任务',
tool: (name) => name || '工具',
result: (name) => (name ? `${name} 返回` : '工具返回'),
toolFailed: (name) => (name ? `${name} 失败` : '工具失败'),
subagent: (name) => name || '子代理',
subtool: (name) => name || '子代理工具',
clarify: '需要澄清',
approve: '等待批准',
compact: '压缩上下文',
context: '上下文更新',
error: (msg) => msg || '出错'
}
},
'zh-hant': {
title: '軌跡',
chip: '軌跡',
emptyTitle: '這場還沒有軌跡',
emptyBody: '送出訊息後依顏色留下每一步。切對話或切 bot 不會混在一起。',
idle: '閒置',
steps: (n) => `${n} 步`,
running: (tags) => `進行中 ${tags}`,
clear: '清空本場',
view: { board: '看板', list: '列表', table: '表格', time: '時間' },
when: { today: '今天' },
col: { time: '時間', lane: '欄', kind: '種類', text: '內容', dur: '耗時' },
help: '軌跡說明',
helpBody: '右邊獨立一欄。色軸可左右滑。切會話或切 bot 各自獨立。',
none: '還沒有軌跡',
lane: { input: '提問', model: '模型', tools: '工具' },
kind: {
user: '提問',
context: '上下文',
thinking: '思考',
message: '回答',
tool: '工具',
subagent: '子任務',
approval: '待確認',
error: '出錯',
todo: '任務',
goal: '目標',
background: '後台',
compact: '壓縮'
},
legend: {
user: '提問',
context: '上下文',
thinking: '思考',
message: '回答',
tool: '工具',
subagent: '子任務',
approval: '待確認',
error: '出錯',
todo: '任務',
goal: '目標',
background: '後台',
compact: '壓縮'
},
edit: { add: '新增', done: '完成' },
evt: {
round: (n) => `第 ${n} 輪`,
thinking: '思考',
writing: '產生回覆',
todo: '更新任務',
tool: (name) => name || '工具',
result: (name) => (name ? `${name} 返回` : '工具返回'),
toolFailed: (name) => (name ? `${name} 失敗` : '工具失敗'),
subagent: (name) => name || '子代理',
subtool: (name) => name || '子代理工具',
clarify: '需要澄清',
approve: '等待核准',
compact: '壓縮上下文',
context: '上下文更新',
error: (msg) => msg || '出錯'
}
},
ja: {
title: '軌跡',
chip: '軌跡',
emptyTitle: 'まだ軌跡がありません',
emptyBody: '送信すると色で手順が残ります。会話や bot を切り替えても混ざりません。',
idle: '待機',
steps: (n) => `${n} ステップ`,
running: (tags) => `実行中 ${tags}`,
clear: 'この会話を消去',
view: { board: 'ボード', list: 'リスト', table: '表', time: '時間' },
when: { today: '今日' },
col: { time: '時刻', lane: '列', kind: '種類', text: '内容', dur: '時間' },
help: '軌跡の説明',
helpBody: '右側の独立列。カラーバーは横に送れます。会話・bot ごとに分かれます。',
none: '軌跡なし',
lane: { input: '質問', model: 'モデル', tools: 'ツール' },
kind: {
user: '質問',
context: '文脈',
thinking: '思考',
message: '回答',
tool: 'ツール',
subagent: '子任務',
approval: '確認',
error: 'エラー',
todo: 'ToDo',
goal: '目標',
background: '裏',
compact: '圧縮'
},
legend: {
user: '質問',
context: '文脈',
thinking: '思考',
message: '回答',
tool: 'ツール',
subagent: '子任務',
approval: '確認',
error: 'エラー',
todo: 'ToDo',
goal: '目標',
background: 'バックグラウンド',
compact: '圧縮'
},
edit: { add: '追加', done: '完了' },
evt: {
round: (n) => `ターン ${n}`,
thinking: '思考中',
writing: '応答を生成',
todo: 'ToDo を更新',
tool: (name) => name || 'ツール',
result: (name) => (name ? `${name} が返却` : 'ツール結果'),
toolFailed: (name) => (name ? `${name} が失敗` : 'ツール失敗'),
subagent: (name) => name || '子エージェント',
subtool: (name) => name || '子ツール',
clarify: '確認が必要',
approve: '承認待ち',
compact: '文脈を圧縮',
context: '文脈更新',
error: (msg) => msg || 'エラー'
}
},
ar: {
title: 'المسار',
chip: 'المسار',
emptyTitle: 'لا مسار بعد',
emptyBody: 'أرسل رسالة. الألوان تعلّم كل خطوة. تبديل المحادثة أو البوت لا يخلط السجلات.',
idle: 'خامل',
steps: (n) => `${n} خطوة`,
running: (tags) => `جارٍ ${tags}`,
clear: 'مسح هذه المحادثة',
view: { board: 'لوحة', list: 'قائمة', table: 'جدول', time: 'زمن' },
when: { today: 'اليوم' },
col: { time: 'وقت', lane: 'مسار', kind: 'نوع', text: 'ماذا', dur: 'مدة' },
help: 'شرح المسار',
helpBody: 'عمود مستقل على اليمين. حرّك شريط الألوان. لكل محادثة وبوت سجله.',
none: 'لا مسار',
lane: { input: 'سؤال', model: 'نموذج', tools: 'أدوات' },
kind: {
user: 'سؤال',
context: 'سياق',
thinking: 'فكر',
message: 'رد',
tool: 'أداة',
subagent: 'مهمة',
approval: 'انتظار',
error: 'خطأ',
todo: 'مهام',
goal: 'هدف',
background: 'خلفية',
compact: 'ضغط'
},
legend: {
user: 'سؤال',
context: 'سياق',
thinking: 'تفكير',
message: 'رد',
tool: 'أداة',
subagent: 'مهمة فرعية',
approval: 'انتظار',
error: 'خطأ',
todo: 'مهام',
goal: 'هدف',
background: 'خلفية',
compact: 'ضغط'
},
edit: { add: 'أضف', done: 'تم' },
evt: {
round: (n) => `الدورة ${n}`,
thinking: 'يفكر',
writing: 'يكتب الرد',
todo: 'تحديث المهام',
tool: (name) => name || 'أداة',
result: (name) => (name ? `${name} عاد` : 'نتيجة الأداة'),
toolFailed: (name) => (name ? `${name} فشل` : 'فشل الأداة'),
subagent: (name) => name || 'وكيل فرعي',
subtool: (name) => name || 'أداة فرعية',
clarify: 'يحتاج توضيحاً',
approve: 'بانتظار الموافقة',
compact: 'ضغط السياق',
context: 'تحديث السياق',
error: (msg) => msg || 'خطأ'
}
}
}
function visualKind(name) {
return KIND_ALIAS[name] || (KIND[name] ? name : 'context')
}
function emptyLayout() {
return { lanes: DEFAULT_LANES.map((row) => row.slice()), diy: null }
}
function layoutOf(key) {
return $layouts.get()[key || liveKey()] || emptyLayout()
}
function writeLayout(key, next) {
$layouts.set({ ...$layouts.get(), [key]: next })
persist()
}
function liveLanes() {
return layoutOf($viewKey.get()).lanes
}
function laneOf(kind) {
const k = visualKind(kind)
const lanes = liveLanes()
for (let i = 0; i < 3; i += 1) {
if (lanes[i] && lanes[i].includes(k)) return i
}
return -1
}
function kindMeta(name) {
return { lane: laneOf(name) }
}
function liveColors() {
return { ...DEFAULT, ...(layoutOf($viewKey.get()).diy || {}) }
}
function colorOf(kind, error) {
const bag = liveColors()
if (error || kind === 'error') return bag.error
return bag[visualKind(kind)] || bag.context
}
function lockTo(id) {
$selected.set(id)
if (id == null) return
const run = () => {
document.querySelectorAll(`[data-eid="${id}"]`).forEach((el) => {
try {
el.scrollIntoView({ block: 'nearest', inline: 'center' })
} catch {
/* ignore */
}
})
}
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(run)
else run()
}
function pad2(n) {
return String(n).padStart(2, '0')
}
function when(ts, nowTs) {
const d = new Date(ts)
const n = new Date(nowTs || Date.now())
const hm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
if (d.getFullYear() !== n.getFullYear()) {
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${hm}`
}
if (d.getMonth() !== n.getMonth() || d.getDate() !== n.getDate()) {
return `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${hm}`
}
return hm
}
function dayStamp(ts) {
const d = new Date(ts)
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
}
function dayLabel(ts, nowTs, t) {
const d = new Date(ts)
const n = new Date(nowTs || Date.now())
if (d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate()) {
return tx(t, 'when.today', '今天')
}
if (d.getFullYear() !== n.getFullYear()) return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
return `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
}
function tx(t, key, fallback, ...args) {
const got = t(key, ...args)
if (!got || got === key) return typeof fallback === 'function' ? fallback(...args) : fallback || key
return got
}
function eventText(t, ev) {
if (ev.textKey) return tx(t, ev.textKey, ev.label, ...(ev.args || []))
return ev.label || '—'
}
function profileName(event) {
return String((event && event.profile) || host.state.profile.get() || 'default')
}
function storedSid() {
return host.state.focusedStoredSessionId.get() || ''
}
function runtimeSid() {
return host.state.focusedSessionId.get() || host.state.activeSessionId.get() || ''
}
function scopeKey(profile, sid) {
return `${profile || 'default'}::${sid || 'draft'}`
}
function liveKey() {
return scopeKey(profileName(), storedSid() || runtimeSid() || 'draft')
}
function rememberAlias(runtime, stored) {
if (!runtime || !stored || runtime === stored) return
const cur = $aliases.get()
if (cur[runtime] === stored) return
$aliases.set({ ...cur, [runtime]: stored })
persist()
}
function canonicalSid(event) {
const evSid = String((event && (event.session_id || event.sessionId)) || '')
return evSid || runtimeSid() || storedSid() || 'draft'
}
function canonicalKey(event) {
return scopeKey(profileName(event), canonicalSid(event))
}
function relatedKeys(canonical) {
const [prof, sid] = (canonical || liveKey()).split('::')
const keys = new Set([canonical, scopeKey(prof, sid)])
const runtime = runtimeSid()
const stored = storedSid()
if (runtime) keys.add(scopeKey(prof, runtime))
if (stored) keys.add(scopeKey(prof, stored))
for (const [rt, st] of Object.entries($aliases.get())) {
if (st === sid || rt === sid || st === stored || rt === runtime) {
keys.add(scopeKey(prof, rt))
keys.add(scopeKey(prof, st))
}
}
return [...keys]
}
function emptyBucket() {
return { seq: 0, events: [] }
}
function bucketOf(key) {
return $buckets.get()[key] || emptyBucket()
}
function persist() {
try {
store.api &&
store.api.set('traj-v3', {
buckets: $buckets.get(),
aliases: $aliases.get(),
layouts: $layouts.get(),
mode: $mode.get()
})
} catch {
/* ignore */
}
}
function normalizeBucket(bucket) {
if (!bucket || typeof bucket !== 'object' || Array.isArray(bucket)) return emptyBucket()
const seq = Number.isFinite(bucket.seq) ? Math.max(0, Math.floor(bucket.seq)) : 0
const events = Array.isArray(bucket.events)
? bucket.events
.filter((event) => event && typeof event === 'object')
.map((event, index) => ({
id: Number.isFinite(event.id) ? event.id : index + 1,
kind: visualKind(event.kind),
at: Number.isFinite(event.at) ? event.at : Date.now(),
running: Boolean(event.running),
error: Boolean(event.error),
ms: Number.isFinite(event.ms) ? event.ms : undefined,
textKey: typeof event.textKey === 'string' ? event.textKey : undefined,
label: typeof event.label === 'string' ? event.label : undefined,
args: Array.isArray(event.args) ? event.args.filter((arg) => arg != null).map(String) : undefined
}))
.slice(-MAX_EVENTS)
: []
return { seq: Math.max(seq, events.length), events }
}
function normalizeLayout(layout) {
if (!layout || typeof layout !== 'object' || Array.isArray(layout)) return emptyLayout()
const lanes = Array.isArray(layout.lanes) && layout.lanes.length === LANE_KEYS.length
? layout.lanes.map((row, laneIndex) =>
Array.isArray(row)
? [...new Set(row.filter((kind) => POOL.includes(kind)).map(visualKind))]
: DEFAULT_LANES[laneIndex].slice()
)
: DEFAULT_LANES.map((row) => row.slice())
const diy = layout.diy && typeof layout.diy === 'object' && !Array.isArray(layout.diy)
? Object.fromEntries(
Object.entries(layout.diy).filter(([kind, color]) => POOL.includes(kind) && typeof color === 'string')
)
: null
return { lanes, diy: diy && Object.keys(diy).length ? diy : null }
}
function pruneStorage() {
const buckets = $buckets.get()
const aliases = $aliases.get()
const layouts = $layouts.get()
const nextBuckets = {}
for (const [key, bucket] of Object.entries(buckets)) {
if (key.includes('::')) nextBuckets[key] = normalizeBucket(bucket)
}
const nextLayouts = {}
for (const [key, layout] of Object.entries(layouts)) {
if (key.includes('::')) nextLayouts[key] = normalizeLayout(layout)
}
const nextAliases = {}
for (const [runtime, stored] of Object.entries(aliases)) {
if (runtime && stored && runtime !== stored) nextAliases[runtime] = String(stored)
}
$buckets.set(nextBuckets)
$aliases.set(nextAliases)
$layouts.set(nextLayouts)
}
function setMode(id) {
if (!VIEWS.includes(id)) return
$mode.set(id)
persist()
}
function setDiyColor(kind, hex) {
const key = $viewKey.get()
const cur = layoutOf(key)
if (!POOL.includes(kind) || typeof hex !== 'string') return
writeLayout(key, { ...cur, diy: { ...(cur.diy || {}), [kind]: hex } })
}
function dropKind(lane, kind) {
const key = $viewKey.get()
const cur = layoutOf(key)
if (!Number.isInteger(lane) || lane < 0 || lane >= LANE_KEYS.length || !POOL.includes(kind)) return
const lanes = cur.lanes.map((row, i) => (i === lane ? row.filter((k) => k !== kind) : row.slice()))
writeLayout(key, { ...cur, lanes })
}
function addKind(lane, kind) {
const key = $viewKey.get()
const cur = layoutOf(key)
if (!Number.isInteger(lane) || lane < 0 || lane >= LANE_KEYS.length || !POOL.includes(kind)) return
const lanes = cur.lanes.map((row) => row.filter((k) => k !== kind))
if (!lanes[lane].includes(kind)) lanes[lane] = [...lanes[lane], kind]
writeLayout(key, { ...cur, lanes })
}
function writeBucket(key, next) {
$buckets.set({ ...$buckets.get(), [key]: normalizeBucket(next) })
persist()
}
function pushEvent(key, kind, extra) {
const canonicalKind = visualKind(kind)
if (!POOL.includes(canonicalKind)) return null
const b = bucketOf(key)
const seq = b.seq + 1
const id = seq
const item = {
id,
kind: canonicalKind,
at: Date.now(),
running: false,
error: false,
...extra
}
item.id = id
item.kind = visualKind(item.kind)
const events =
b.events.length >= MAX_EVENTS ? [...b.events.slice(b.events.length - MAX_EVENTS + 1), item] : [...b.events, item]
writeBucket(key, { seq, events })
return item.id
}
function patchEvent(key, id, patch) {
const b = bucketOf(key)
let changed = false
const events = b.events.map((event) => {
if (event.id !== id) return event
changed = true
return normalizeBucket({ events: [{ ...event, ...patch }] }).events[0]
})
if (!changed) return
writeBucket(key, { seq: b.seq, events })
}
function lastOf(key, kind, runningOnly) {
const canonicalKind = visualKind(kind)
const list = bucketOf(key).events
for (let i = list.length - 1; i >= 0; i -= 1) {
if (list[i].kind !== canonicalKind) continue
if (runningOnly && !list[i].running) continue
return list[i]
}
return null
}
function mergedEvents(canonical) {
const seen = new Set()
const out = []
for (const key of new Set([canonical, ...relatedKeys(canonical)])) {
for (const ev of bucketOf(key).events) {
const stamp = `${key}:${ev.at}:${ev.kind}:${ev.textKey || ev.label || ''}:${ev.id}`
if (seen.has(stamp)) continue
seen.add(stamp)
out.push(ev)
}
}
out.sort((a, b) => a.at - b.at || a.id - b.id)
return out
}
function formatElapsed(ms) {
if (!ms || ms < 0) return ''
const s = Math.floor(ms / 1000)
if (s < 60) return `${s}s`
return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
}
function eventDuration(event, now) {
return event.running ? formatElapsed(now - event.at) : event.ms != null ? formatElapsed(event.ms) : ''
}
function useNow(active) {
const [now, setNow] = useState(() => Date.now())
useEffect(() => {
if (!active) return undefined
const timer = setInterval(() => setNow(Date.now()), 500)
return () => clearInterval(timer)
}, [active])
return now
}
function useViewEvents() {
useValue($buckets)
useValue($aliases)
useValue($layouts)
const key = useValue($viewKey)
return mergedEvents(key).filter((ev) => laneOf(ev.kind) >= 0)
}
function Timeline({ t }) {
useValue($layouts)
const events = useViewEvents()
const selected = useValue($selected)
const scroller = useRef(null)
const follow = useRef(true)
const width = Math.max(events.length * SPAN_W, 80)
useEffect(() => {
const el = scroller.current
if (!el || !follow.current) return
el.scrollLeft = el.scrollWidth
}, [events.length, selected])
return jsx('div', {
style: {
flex: 'none',
borderBottom: '1px solid var(--ui-stroke-secondary)',
background: 'var(--ui-bg-secondary, transparent)'
},
children: jsxs('div', {
style: { display: 'grid', gridTemplateColumns: `${LANE_LABEL_W}px minmax(0, 1fr)`, height: TIMELINE_H },
children: [
jsx('div', {
style: {
position: 'relative',
borderRight: '1px solid var(--ui-stroke-secondary)',
color: 'var(--ui-text-tertiary)',
fontSize: 11,
fontWeight: 600
},
children: liveLanes().map((kinds, id) =>
jsx(
'button',
{
type: 'button',
onClick: () => $edit.set($edit.get() === id ? null : id),
style: {
position: 'absolute',
left: 4,
right: 4,
top: 8 + id * LANE_H,
height: SPAN_H + 6,
display: 'flex',
alignItems: 'center',
whiteSpace: 'nowrap',
overflow: 'hidden',
border: 'none',
padding: 0,
background: 'transparent',
color: 'inherit',
font: 'inherit',
fontWeight: 600,
cursor: 'pointer'
},
children: tx(t, `lane.${LANE_KEYS[id]}`, LANE_KEYS[id])
},
LANE_KEYS[id]
)
)
}),
jsx('div', {
ref: scroller,
onWheel: (e) => {
const el = scroller.current
if (!el) return
const dx = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY
if (!dx) return
e.preventDefault()
e.stopPropagation()
el.scrollLeft += dx
follow.current = el.scrollLeft + el.clientWidth >= el.scrollWidth - 8
},
onScroll: () => {
const el = scroller.current
if (!el) return
follow.current = el.scrollLeft + el.clientWidth >= el.scrollWidth - 8
},
style: { position: 'relative', overflowX: 'auto', overflowY: 'hidden', cursor: 'ew-resize' },
children: jsx('div', {
style: { position: 'relative', width, height: TIMELINE_H, minWidth: '100%' },
children: [
...liveLanes().map((kinds, id) =>
jsx(
'div',
{
style: {
position: 'absolute',
left: 0,
right: 0,
top: 8 + id * LANE_H + SPAN_H + 4,
height: 1,
background: 'var(--ui-stroke-secondary)',
opacity: 0.45
}
},
`rule-${LANE_KEYS[id]}`
)
),
events.length === 0
? jsx('div', {
style: {
position: 'absolute',
inset: 0,
display: 'grid',
placeItems: 'center',
color: 'var(--ui-text-quaternary)',
fontSize: 11
},
children: tx(t, 'none', '—')
})
: events.map((ev, i) => {
const meta = kindMeta(ev.kind)
return jsx(
'button',
{
type: 'button',
title: `${tx(t, `kind.${visualKind(ev.kind)}`, ev.kind)} ${eventText(t, ev)}`,
'data-eid': String(ev.id),
onClick: () => lockTo(ev.id),
style: {
position: 'absolute',
top: 8 + meta.lane * LANE_H,
left: i * SPAN_W + 1,
width: SPAN_W - 3,
height: SPAN_H,
border: 'none',
borderRadius: 2,
padding: 0,
cursor: 'pointer',
background: colorOf(ev.kind, ev.error),
opacity: selected && selected !== ev.id ? 0.22 : ev.running ? 1 : 0.92,
boxShadow: selected === ev.id ? '0 0 0 1px var(--ui-accent)' : 'none'
}
},
`${ev.at}-${ev.id}`
)
})
]
})
})
]
})
})
}
function Legend({ t }) {
useValue($layouts)
const lanes = liveLanes()
return jsx('div', {
style: {
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gap: 8,
padding: '8px 10px',
borderBottom: '1px solid var(--ui-stroke-secondary)',
fontSize: 11,
color: 'var(--ui-text-tertiary)'
},
children: lanes.map((kinds, id) =>
jsxs(
'div',
{
style: {
display: 'flex',
flexDirection: 'column',
gap: 5,
minWidth: 0,
paddingRight: 6,
borderRight: id < 2 ? '1px solid var(--ui-stroke-secondary)' : 'none'
},
children: [
jsx('button', {
type: 'button',
onClick: () => $edit.set($edit.get() === id ? null : id),
style: {
fontWeight: 600,
color: 'var(--ui-text-secondary)',
marginBottom: 1,
border: 'none',
background: 'transparent',
padding: 0,
textAlign: 'left',
cursor: 'pointer'
},
children: tx(t, `lane.${LANE_KEYS[id]}`, LANE_KEYS[id])
}),
...kinds.map((kind) =>
jsxs(
'label',
{
style: { display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer' },
children: [
jsx('input', {
type: 'color',
value: colorOf(kind, kind === 'error'),
onChange: (e) => setDiyColor(kind, e.target.value),
style: {
width: 14,
height: 14,
padding: 0,
border: 'none',
background: 'transparent',
cursor: 'pointer'
}
}),
tx(t, `legend.${kind}`, kind)
]
},
kind
)
)
]
},
LANE_KEYS[id]
)
)
})
}
function LaneEditor({ t }) {
const edit = useValue($edit)
useValue($layouts)
if (edit == null) return null
const used = new Set(liveLanes().flat())
const mine = liveLanes()[edit] || []
const extra = POOL.filter((k) => !used.has(k))
return jsxs('div', {
style: {
padding: '8px 10px',
borderBottom: '1px solid var(--ui-stroke-secondary)',
fontSize: 11
},
children: [
jsxs('div', {