dsh-timeback 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,3044 @@
1
+ /**
2
+ * Timeback — browser half.
3
+ *
4
+ * Registers a right-sidebar tab that draws the conversation/checkpoint tree of
5
+ * the current Session, plus a conversation-header button that opens it. Every
6
+ * read and action goes through the Host route `/timeback/api/*`; the panel
7
+ * never folds Session events itself, so it stays correct across branches and
8
+ * cold Sessions.
9
+ */
10
+ window.__ModuleLoader__.load({
11
+ id: 'dsh-timeback',
12
+ factory(require) {
13
+ const React = require('react')
14
+ const h = React.createElement
15
+
16
+ const ID = 'dsh-timeback'
17
+ const KIND = 'timeback'
18
+ const BOARD_ID = 'dsh-timeback-board'
19
+ const BOARD_KIND = 'timeback-board'
20
+ const NS = 'timeback'
21
+ /** Document-relative on purpose: the GUI may be mounted under a path prefix. */
22
+ const API = 'timeback/api'
23
+ const REFRESH_MS = 3000
24
+ const MAX_ROWS = 240
25
+ /** Bump together with package.json so a stale browser bundle is obvious. */
26
+ const BUILD = '0.6.0+board'
27
+ /** Set by apply(): opens another Session in the main column. */
28
+ let openSessionBridge = null
29
+ /** Set by apply(): opens the Timeback tab in the right sidebar. */
30
+ let openPanelBridge = null
31
+ let openBoardBridge = null
32
+
33
+ const DICT = {
34
+ zh: {
35
+ 'type.title': '时间回溯',
36
+ 'guide.title': '时间回溯',
37
+ 'guide.description': '对话树 + 文件快照:回到任意一轮并恢复工作区文件',
38
+ 'header.open': '时间回溯:分支与文件回退',
39
+ 'pill.open': '时间回溯',
40
+ 'panel.title': '时间回溯',
41
+ 'panel.current': '当前',
42
+ 'panel.branch': '分支',
43
+ 'panel.running': '运行中',
44
+ 'panel.loading': '加载中…',
45
+ 'panel.empty': '还没有快照。发送一条消息后,timeback 会在回合边界记录对话位置与文件快照。',
46
+ 'panel.emptyWithError': '还没有快照,最近一次记录失败:',
47
+ 'panel.noSession': '请先选择一个会话',
48
+ 'panel.refresh': '刷新',
49
+ 'panel.checkpoint': '手动检查点',
50
+ 'panel.noGit': 'git 不可用:只能分支会话,无法保存或恢复文件',
51
+ 'panel.branchCount': '{sessions} 分支 · {checkpoints} 检查点',
52
+ 'panel.rewind': '回到这里',
53
+ 'panel.rewindFiles': '仅恢复文件',
54
+ 'panel.branchOnly': '仅分支',
55
+ 'panel.safety': '回退前安全快照',
56
+ 'panel.inherited': '分支起点',
57
+ 'panel.before': '开始前',
58
+ 'panel.after': '结束后',
59
+ 'panel.manual': '手动',
60
+ 'panel.warning': '回退会按快照覆盖工作区文件,并删除快照之后新增的文件;回退前会自动保存安全快照。',
61
+ 'panel.confirmRewind': '将创建新分支并恢复工作区到:{who}\n\n{warning}\n\n确定继续?',
62
+ 'panel.confirmFiles': '将把工作区文件恢复为:{who}\n\n{warning}\n\n确定继续?',
63
+ 'panel.confirmBranchOnly': '将在该检查点创建新分支,不修改工作区文件:{who}\n\n确定继续?',
64
+ 'panel.confirmCheckpoint': '将记录当前对话位置与工作区快照。确定继续?',
65
+ 'panel.deleteWarning': '快照之后新增的文件会被删除,之后修改的文件会被覆盖。回退前会自动保存安全快照,可用它撤销本次恢复。',
66
+ 'panel.acting': '执行中…',
67
+ 'panel.doneCheckpoint': '检查点已创建',
68
+ 'panel.doneRestore': '文件恢复完成:+{restored} / -{deleted}',
69
+ 'panel.doneBranch': '新分支已创建',
70
+ 'panel.openBranch': '打开新分支',
71
+ 'panel.safetySaved': '安全快照已保存,可用它撤销本次恢复',
72
+ 'panel.undoRestore': '用安全快照恢复',
73
+ 'panel.undoUnavailable': '该安全快照不在当前列表里,请先刷新',
74
+ 'panel.noSnapshot': '无文件快照',
75
+ 'panel.seq': 'seq',
76
+ 'panel.error': '操作失败',
77
+ 'panel.errorCode': '{error}({code})',
78
+ 'panel.captureError': '最近一次快照失败',
79
+ 'panel.failedPaths': '有 {count} 个路径未能恢复(原因见 README 的恢复限制)',
80
+ 'panel.keptFiles': '{count} 个新增文件被保留(restoreDeletesExtra=false)',
81
+ 'panel.rowTruncated': '仅显示最近 {count} 条检查点',
82
+ 'panel.noBranchHint': '这一行只能恢复文件;若要从此处分支,请用上一回合的「结束后」检查点。',
83
+ 'panel.filesCapped': '文件计数最多显示 100 条',
84
+ 'panel.reasonNotCurrent': '只能在当前打开的会话上操作',
85
+ 'panel.reasonRunning': '会话正在运行,请等本轮结束或先停止',
86
+ 'panel.reasonGit': 'git 不可用,无法恢复文件',
87
+ 'panel.reasonBusy': '正在执行其他操作',
88
+ 'panel.notes': '记录板',
89
+ 'panel.note': '卡片记录',
90
+ 'note.title': '卡片文字记录',
91
+ 'note.hint': 'Markdown 文本,显示在卡片上;只修改当前卡片。',
92
+ 'note.placeholder': '记录这一步的思路、结论、命令…(支持 Markdown)',
93
+ 'note.save': '保存',
94
+ 'note.delete': '删除记录',
95
+ 'note.cancel': '取消',
96
+ 'note.empty': '(暂无记录)',
97
+ 'note.saved': '卡片记录已保存',
98
+ 'note.removed': '卡片记录已删除',
99
+ 'board.title': '记录板',
100
+ 'board.subtitle': '全局 Markdown 记录板 · 回溯时一起恢复',
101
+ 'board.new': '新建记录',
102
+ 'board.edit': '编辑',
103
+ 'board.delete': '删除',
104
+ 'board.save': '保存',
105
+ 'board.cancel': '取消',
106
+ 'board.preview': '预览',
107
+ 'board.editMode': '编辑',
108
+ 'board.titlePlaceholder': '记录标题',
109
+ 'board.bodyPlaceholder': '用 Markdown 记录分析、决策、进展…',
110
+ 'board.empty': '还没有记录。可以点「新建记录」,或让会话调用 timeback_note 写入。',
111
+ 'board.sourceUser': '我',
112
+ 'board.sourceAgent': '会话',
113
+ 'board.deleteConfirm': '删除这条记录?',
114
+ 'board.refresh': '刷新',
115
+ 'board.saved': '记录已保存',
116
+ 'board.deleted': '记录已删除',
117
+ 'board.count': '{count} 条记录 · 版本 v{version}',
118
+ 'board.error': '记录板操作失败:{error}',
119
+ 'board.agentHint': '提示:让会话调用 timeback_note 工具即可把结论写进记录板;回溯时记录板会一起回退。',
120
+ 'guide.boardTitle': '记录板',
121
+ 'guide.boardDescription': '全局 Markdown 记录板:手动添加或让会话记录,回溯时一起回退。',
122
+ 'panel.recording': '记录设置',
123
+ 'panel.recordThis': '记录此工作区并保存文件快照',
124
+ 'panel.recordThisHint': '该开关按工作区目录生效(含子目录):父目录开启后子目录默认继承;在子目录取消勾选可单独关闭该子目录,不影响父目录。',
125
+ 'panel.recordOff': '未开启记录',
126
+ 'panel.recordOn': '记录中',
127
+ 'panel.recordAll': '插件配置 capture=all:所有工作区自动记录',
128
+ 'panel.recordFixedOff': '插件配置 capture=off:自动记录已关闭,仍可手动创建检查点',
129
+ 'panel.recordDisabledNoGit': 'git 不可用,无法记录文件快照',
130
+ 'panel.recordMissing': '当前会话没有可用工作目录,无法记录',
131
+ 'panel.enabledWorkspaces': '已开启记录的工作区',
132
+ 'panel.excludedWorkspaces': '已单独关闭记录的子目录',
133
+ 'panel.restoreThis': '恢复继承',
134
+ 'panel.disableThis': '关闭',
135
+ 'panel.workspaceEnabled': '已开启此工作区的自动记录',
136
+ 'panel.workspaceDisabled': '已关闭此工作区的自动记录',
137
+ 'panel.workspaceStillOn': '操作已提交,但该目录仍被其它记录设置覆盖;请在上方已开启列表里取消对应路径。',
138
+ 'panel.emptyNotRecording': '此工作区尚未开启记录。勾选上方的「记录此工作区并保存文件快照」后,之后的回合才会保存检查点。',
139
+ 'view.tree': '树视图',
140
+ 'view.list': '列表视图',
141
+ 'tree.legend.turn': '回合',
142
+ 'tree.legend.manual': '手动',
143
+ 'tree.legend.branch': '分支',
144
+ 'tree.legend.current': '当前路径',
145
+ 'tree.empty': '还没有可视化节点。发送消息或创建检查点后会出现在这里。',
146
+ 'tree.truncated': '树中仅显示前 {count} 个回合;完整记录请切换到列表视图。',
147
+ 'tree.hint': '点击节点查看该回合的检查点操作;连线表示分支从哪个回合分出。',
148
+ 'tree.branchStart': '起点',
149
+ 'tree.noPrompt': '(本轮没有提示词记录)',
150
+ 'tree.zoomIn': '放大',
151
+ 'tree.zoomOut': '缩小',
152
+ 'tree.resetZoom': '重置缩放',
153
+ 'tree.fit': '适应画布',
154
+ 'tree.fitShort': '适应',
155
+ 'tree.panHint': '拖动空白处平移,滚轮缩放;点击卡片查看详情',
156
+ 'tree.dragHint': '拖动卡片可自由摆放;双击卡片或车道名跳回对应的会话',
157
+ 'tree.openHint': '双击跳回该会话',
158
+ 'tree.branch': '分支',
159
+ 'tree.branchHint': '在此检查点创建一个新分支(不修改文件)',
160
+ 'tree.resetLayout': '复位',
161
+ 'tree.resetLayoutHint': '清除拖动过的卡片位置,恢复自动布局',
162
+ 'tree.prune': '删后续',
163
+ 'tree.pruneHint': '删除该节点之后的会话(创建截断分支并归档旧会话)',
164
+ 'tree.expandHint': '展开/收起画布高度',
165
+ 'tree.autoPanOn': '自动平移',
166
+ 'tree.autoPanOff': '自动平移(关)',
167
+ 'tree.autoPanHint': '拖动卡片到画布边缘时自动平移画布;可一键关闭',
168
+ 'tree.panSpeedSlow': '慢速',
169
+ 'tree.panSpeedNormal': '标准',
170
+ 'tree.panSpeedFast': '快速',
171
+ 'tree.panSpeedHint': '点击切换边缘自动平移速度(慢速 45 / 标准 90 / 快速 170 px/s)',
172
+ 'panel.confirmPrune': '删除「{who}」之后的所有会话内容?\n\n将创建到该节点为止的截断分支(沿用原会话名称)并恢复工作区文件,然后归档原会话及其之后的后续分支。DSH 会话日志只追加、无法物理删除,删除以「归档」实现(可在侧栏归档列表恢复旧会话)。\n\n如果该节点已经是分支的最后一个节点,操作会被拒绝。\n\n确定继续?',
173
+ 'panel.donePrune': '已删除该节点之后的会话',
174
+ 'panel.pruneOld': '删除旧会话之后的记录',
175
+ 'panel.pruneArchived': '已归档 {count} 个旧会话',
176
+ 'panel.pruneFailed': '{count} 个旧会话未能归档(可能正在运行)',
177
+ 'panel.staleBuild': '检测到插件已更新(页面运行 {client},服务端 {server})。请刷新页面以加载新版本。',
178
+ 'panel.reloadPage': '立即刷新页面',
179
+
180
+
181
+ 'detail.title': '检查点详情',
182
+ 'detail.empty': '点击树上的节点查看可执行的回退操作。',
183
+ 'detail.turn': '第 {turn} 回合',
184
+ 'detail.start': '分支起点',
185
+ 'detail.manual': '手动检查点',
186
+ 'detail.before': '回合开始前',
187
+ 'detail.after': '回合结束后',
188
+ 'detail.safety': '回退前安全快照',
189
+ 'detail.noSnapshot': '无文件快照',
190
+ 'detail.beforeHint': '“开始前”节点只支持恢复文件;如需分支请用同一回合的“结束后”节点。',
191
+ 'detail.notCurrent': '只能在当前打开的会话上操作',
192
+ 'detail.running': '会话正在运行,请等本轮结束',
193
+
194
+ 'menu.enable': '时间回溯:开启此工作区记录',
195
+ 'menu.disable': '时间回溯:关闭此工作区记录',
196
+ 'menu.stateOn': '时间回溯记录:已开启',
197
+ 'menu.stateOff': '时间回溯记录:未开启',
198
+ 'menu.notifyOn': '已开启此工作区的文件记录',
199
+ 'menu.notifyOff': '已关闭此工作区的文件记录',
200
+ 'menu.failure': '切换时间回溯记录失败',
201
+ 'menu.unavailable': '时间回溯状态暂不可用',
202
+ 'hero.record': '时间回溯记录',
203
+ 'hero.recordHint': '为该工作区保存文件快照(按工作区生效,所有会话共用)',
204
+ 'hero.recordAll': '插件配置已对所有工作区开启记录',
205
+ 'hero.recordOff': '插件配置已关闭自动记录',
206
+ 'hero.recordError': '记录状态读取失败:{error}',
207
+ },
208
+ en: {
209
+ 'type.title': 'Timeback',
210
+ 'guide.title': 'Timeback',
211
+ 'guide.description': 'Conversation tree with file snapshots: return to any turn and restore the workspace',
212
+ 'header.open': 'Timeback: branches and file rollback',
213
+ 'pill.open': 'Timeback',
214
+ 'panel.title': 'Timeback',
215
+ 'panel.current': 'current',
216
+ 'panel.branch': 'branch',
217
+ 'panel.running': 'running',
218
+ 'panel.loading': 'Loading…',
219
+ 'panel.empty': 'No snapshots yet. After you send a message, timeback records a checkpoint at each turn boundary.',
220
+ 'panel.emptyWithError': 'No snapshots yet; the latest record failed:',
221
+ 'panel.noSession': 'Select a session first',
222
+ 'panel.refresh': 'Refresh',
223
+ 'panel.checkpoint': 'Checkpoint now',
224
+ 'panel.noGit': 'git is unavailable: branching works, file snapshots do not',
225
+ 'panel.branchCount': '{sessions} branches · {checkpoints} checkpoints',
226
+ 'panel.rewind': 'Rewind here',
227
+ 'panel.rewindFiles': 'Restore files',
228
+ 'panel.branchOnly': 'Branch only',
229
+ 'panel.safety': 'Pre-rewind safety snapshot',
230
+ 'panel.inherited': 'Branch start',
231
+ 'panel.before': 'before',
232
+ 'panel.after': 'after',
233
+ 'panel.manual': 'manual',
234
+ 'panel.warning': 'Rewinding overwrites workspace files from the snapshot and deletes files created after it. A safety snapshot is taken first.',
235
+ 'panel.confirmRewind': 'Create a new branch and restore the workspace to: {who}\n\n{warning}\n\nContinue?',
236
+ 'panel.confirmFiles': 'Restore workspace files to: {who}\n\n{warning}\n\nContinue?',
237
+ 'panel.confirmBranchOnly': 'Create a new branch at this checkpoint without touching files: {who}\n\nContinue?',
238
+ 'panel.confirmCheckpoint': 'Record the current conversation position and a workspace snapshot?',
239
+ 'panel.deleteWarning': 'Files created after the snapshot are deleted and files changed later are overwritten. A safety snapshot is taken first; it can undo this restore.',
240
+ 'panel.acting': 'Working…',
241
+ 'panel.doneCheckpoint': 'Checkpoint created',
242
+ 'panel.doneRestore': 'Files restored: +{restored} / -{deleted}',
243
+ 'panel.doneBranch': 'Branch created',
244
+ 'panel.openBranch': 'Open new branch',
245
+ 'panel.safetySaved': 'Safety snapshot saved; it can undo this restore',
246
+ 'panel.undoRestore': 'Restore the safety snapshot',
247
+ 'panel.undoUnavailable': 'That safety snapshot is not in the current list; refresh first',
248
+ 'panel.noSnapshot': 'No file snapshot',
249
+ 'panel.seq': 'seq',
250
+ 'panel.error': 'Action failed',
251
+ 'panel.errorCode': '{error} ({code})',
252
+ 'panel.captureError': 'Latest snapshot failed',
253
+ 'panel.failedPaths': '{count} path(s) could not be restored (see the README restore limits)',
254
+ 'panel.keptFiles': '{count} new file(s) kept (restoreDeletesExtra=false)',
255
+ 'panel.rowTruncated': 'Showing the newest {count} checkpoints only',
256
+ 'panel.noBranchHint': 'This row can restore files only; to branch here, use the previous turn’s “after” checkpoint.',
257
+ 'panel.filesCapped': 'File counts show at most 100 entries',
258
+ 'panel.reasonNotCurrent': 'Only available on the session on screen',
259
+ 'panel.reasonRunning': 'The session is running; wait for this turn or stop it first',
260
+ 'panel.reasonGit': 'git is unavailable, so files cannot be restored',
261
+ 'panel.reasonBusy': 'Another action is running',
262
+ 'panel.notes': 'Notes board',
263
+ 'panel.note': 'Card note',
264
+ 'note.title': 'Card note',
265
+ 'note.hint': 'Markdown text shown on the card; only this card is changed.',
266
+ 'note.placeholder': 'Capture the reasoning, result or command of this step… (Markdown supported)',
267
+ 'note.save': 'Save',
268
+ 'note.delete': 'Delete note',
269
+ 'note.cancel': 'Cancel',
270
+ 'note.empty': '(no note)',
271
+ 'note.saved': 'Card note saved',
272
+ 'note.removed': 'Card note deleted',
273
+ 'board.title': 'Notes board',
274
+ 'board.subtitle': 'Global Markdown notes · rewinds restore them too',
275
+ 'board.new': 'New note',
276
+ 'board.edit': 'Edit',
277
+ 'board.delete': 'Delete',
278
+ 'board.save': 'Save',
279
+ 'board.cancel': 'Cancel',
280
+ 'board.preview': 'Preview',
281
+ 'board.editMode': 'Edit',
282
+ 'board.titlePlaceholder': 'Note title',
283
+ 'board.bodyPlaceholder': 'Write analysis, decisions and progress in Markdown…',
284
+ 'board.empty': 'No notes yet. Create one, or let the session call timeback_note.',
285
+ 'board.sourceUser': 'Me',
286
+ 'board.sourceAgent': 'Session',
287
+ 'board.deleteConfirm': 'Delete this note?',
288
+ 'board.refresh': 'Refresh',
289
+ 'board.saved': 'Note saved',
290
+ 'board.deleted': 'Note deleted',
291
+ 'board.count': '{count} notes · version v{version}',
292
+ 'board.error': 'Notes board failed: {error}',
293
+ 'board.agentHint': 'Tip: ask the session to use the timeback_note tool; rewinds roll the board back with the conversation.',
294
+ 'guide.boardTitle': 'Notes board',
295
+ 'guide.boardDescription': 'Global Markdown notes: write manually or from the session; rewinds roll them back too.',
296
+ 'panel.recording': 'Recording',
297
+ 'panel.recordThis': 'Record this workspace and keep file snapshots',
298
+ 'panel.recordThisHint': 'Applies to the workspace directory and its subdirectories: a parent opt-in is inherited; unchecking in a subdirectory opts that subdirectory out without affecting the parent.',
299
+ 'panel.recordOff': 'Not recording',
300
+ 'panel.recordOn': 'Recording',
301
+ 'panel.recordAll': 'Plugin config capture=all records every workspace automatically',
302
+ 'panel.recordFixedOff': 'Plugin config capture=off disables automatic capture; manual checkpoints still work',
303
+ 'panel.recordDisabledNoGit': 'git is unavailable, so file snapshots cannot be recorded',
304
+ 'panel.recordMissing': 'This session has no usable working directory',
305
+ 'panel.enabledWorkspaces': 'Workspaces with recording enabled',
306
+ 'panel.excludedWorkspaces': 'Subdirectories opted out of recording',
307
+ 'panel.restoreThis': 'Restore inherited',
308
+ 'panel.disableThis': 'Turn off',
309
+ 'panel.workspaceEnabled': 'Recording enabled for this workspace',
310
+ 'panel.workspaceDisabled': 'Recording disabled for this workspace',
311
+ 'panel.emptyNotRecording': 'Recording is off for this workspace. Check “Record this workspace and keep file snapshots” above to save checkpoints from later turns.',
312
+ 'view.tree': 'Tree',
313
+ 'view.list': 'List',
314
+ 'tree.legend.turn': 'turn',
315
+ 'tree.legend.manual': 'manual',
316
+ 'tree.legend.branch': 'branch',
317
+ 'tree.legend.current': 'current path',
318
+ 'tree.empty': 'No visual nodes yet. Send a message or create a checkpoint and it appears here.',
319
+ 'tree.truncated': 'The tree shows the first {count} turns; switch to List for the complete record.',
320
+ 'tree.hint': 'Click a node to see its checkpoint actions; lines show which turn a branch came from.',
321
+ 'tree.branchStart': 'start',
322
+ 'tree.noPrompt': '(no prompt recorded for this turn)',
323
+ 'tree.zoomIn': 'Zoom in',
324
+ 'tree.zoomOut': 'Zoom out',
325
+ 'tree.resetZoom': 'Reset zoom',
326
+ 'tree.fit': 'Fit to canvas',
327
+ 'tree.fitShort': 'Fit',
328
+ 'tree.panHint': 'Drag empty space to pan, wheel to zoom; click a card for details',
329
+ 'tree.dragHint': 'Drag cards to arrange them; double-click a card or lane name to jump to that conversation',
330
+ 'tree.openHint': 'Double-click to jump to this conversation',
331
+ 'tree.branch': 'Branch',
332
+ 'tree.branchHint': 'Create a new branch at this checkpoint (files untouched)',
333
+ 'tree.resetLayout': 'Reset',
334
+ 'tree.resetLayoutHint': 'Clear dragged card positions and restore the automatic layout',
335
+ 'tree.prune': 'Delete after',
336
+ 'tree.pruneHint': 'Delete the conversation after this node (truncated branch + archived old sessions)',
337
+ 'tree.expandHint': 'Expand/collapse the canvas height',
338
+ 'tree.autoPanOn': 'Edge pan',
339
+ 'tree.autoPanOff': 'Edge pan (off)',
340
+ 'tree.autoPanHint': 'Auto-pan the canvas while dragging a card near an edge; turn it off here',
341
+ 'tree.panSpeedSlow': 'Slow',
342
+ 'tree.panSpeedNormal': 'Normal',
343
+ 'tree.panSpeedFast': 'Fast',
344
+ 'tree.panSpeedHint': 'Click to cycle the edge auto-pan speed (slow 45 / normal 90 / fast 170 px/s)',
345
+ 'panel.confirmPrune': 'Delete every conversation turn after “{who}”?\n\nA truncated branch up to this node (keeping the original conversation name, files restored) replaces the session, then the old session and branches forked after it are archived. DSH session logs are append-only, so deletion is implemented as archival (recoverable from the sidebar archive list).\n\nIf this is already the last node of the branch the operation is refused.\n\nContinue?',
346
+ 'panel.donePrune': 'Deleted the conversation after this node',
347
+ 'panel.pruneOld': 'Delete the old session tail',
348
+ 'panel.pruneArchived': '{count} old session(s) archived',
349
+ 'panel.pruneFailed': '{count} old session(s) could not be archived (possibly running)',
350
+ 'panel.staleBuild': 'The plugin was updated (page runs {client}, server serves {server}). Refresh the page to load it.',
351
+ 'panel.reloadPage': 'Reload now',
352
+
353
+
354
+ 'detail.title': 'Checkpoint details',
355
+ 'detail.empty': 'Click a node in the tree to see its rewind actions.',
356
+ 'detail.turn': 'Turn {turn}',
357
+ 'detail.start': 'Branch start',
358
+ 'detail.manual': 'Manual checkpoint',
359
+ 'detail.before': 'Before turn',
360
+ 'detail.after': 'After turn',
361
+ 'detail.safety': 'Pre-rewind safety snapshot',
362
+ 'detail.noSnapshot': 'No file snapshot',
363
+ 'detail.beforeHint': 'A “before turn” node can restore files only; use the “after turn” node of the same turn to branch.',
364
+ 'detail.notCurrent': 'Only available on the session on screen',
365
+ 'detail.running': 'The session is running; wait for this turn',
366
+
367
+ 'menu.enable': 'Timeback: record this workspace',
368
+ 'menu.disable': 'Timeback: stop recording this workspace',
369
+ 'menu.stateOn': 'Timeback recording: on',
370
+ 'menu.stateOff': 'Timeback recording: off',
371
+ 'menu.notifyOn': 'File recording enabled for this workspace',
372
+ 'menu.notifyOff': 'File recording disabled for this workspace',
373
+ 'menu.failure': 'Could not change Timeback recording',
374
+ 'menu.unavailable': 'Timeback state unavailable',
375
+ 'hero.record': 'Timeback recording',
376
+ 'hero.recordHint': 'Keep file snapshots for this workspace (workspace-wide, shared by every session)',
377
+ 'hero.recordAll': 'Plugin config already records every workspace',
378
+ 'hero.recordOff': 'Plugin config disables automatic recording',
379
+ 'hero.recordError': 'Recording state unavailable: {error}',
380
+ },
381
+ }
382
+
383
+ /* ---------------------------------------------------------------- */
384
+ /* styles */
385
+ /* ---------------------------------------------------------------- */
386
+
387
+ const CSS = `
388
+ .tb-panel{display:flex;flex-direction:column;height:100%;min-height:100%;width:100%;font-size:12.5px;color:var(--dsw-alias-label-primary,#e6e6e6);background:var(--dsw-alias-bg-base,#16181d)}
389
+ .tb-head{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.1));flex-wrap:wrap}
390
+ .tb-title{font-weight:600;font-size:13.5px;white-space:nowrap}
391
+ .tb-muted{color:var(--dsw-alias-label-secondary,#9aa0a6)}
392
+ .tb-small{font-size:11px}
393
+ .tb-chip{display:inline-flex;align-items:center;gap:4px;padding:1px 7px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6);white-space:nowrap}
394
+ .tb-chip.ok{color:var(--dsw-alias-state-success-primary,#3ecf8e);border-color:var(--dsw-alias-state-success-primary,rgba(62,207,142,.45))}
395
+ .tb-chip.warn{color:var(--dsw-alias-state-warning-primary,#f0b23e);border-color:var(--dsw-alias-state-warning-primary,rgba(240,178,62,.45))}
396
+ .tb-chip.run{color:var(--dsw-alias-label-secondary,#9aa0a6);border-style:dashed}
397
+ .tb-btn{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.04));color:var(--dsw-alias-label-primary,#e6e6e6);border-radius:6px;padding:4px 9px;font-size:12px;cursor:pointer;line-height:1.4}
398
+ .tb-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.1))}
399
+ .tb-btn:disabled{opacity:.5;cursor:default}
400
+ .tb-btn.primary{border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#7aa2ff)}
401
+ .tb-btn.danger{border-color:var(--dsw-alias-state-warning-primary,rgba(240,178,62,.5));color:var(--dsw-alias-state-warning-primary,#f0b23e)}
402
+ .tb-body{flex:1;min-height:120px;overflow:auto;padding:10px 12px 28px;display:flex;flex-direction:column;gap:8px}
403
+ .tb-ws{border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:9px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.03));display:flex;flex-direction:column;gap:6px}
404
+ .tb-ws-row{display:flex;align-items:flex-start;gap:8px;cursor:pointer}
405
+ .tb-ws-row.disabled{cursor:default;opacity:.65}
406
+ .tb-ws-row input{margin:3px 0 0;flex:none;accent-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}
407
+ .tb-ws-text{display:flex;flex-direction:column;gap:2px;min-width:0}
408
+ .tb-ws-title{font-weight:600;font-size:12.5px}
409
+ .tb-ws-path{font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%}
410
+ .tb-ws-hint{font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6);line-height:1.5}
411
+ .tb-ws-list{display:flex;flex-direction:column;gap:4px;border-top:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.08));padding-top:6px}
412
+ .tb-ws-item{display:flex;align-items:center;gap:6px;font-size:11.5px}
413
+ .tb-ws-item .tb-ws-path{flex:1}
414
+ .tb-note{margin:0;padding:7px 9px;border-radius:7px;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.12));color:var(--dsw-alias-label-secondary,#9aa0a6);font-size:11px;line-height:1.5}
415
+ .tb-feedback{position:sticky;top:0;z-index:2;padding:7px 9px;border-radius:7px;font-size:11.5px;line-height:1.55;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));background:var(--dsw-alias-bg-layer-1,rgba(28,32,40,.96));display:flex;flex-direction:column;gap:6px}
416
+ .tb-feedback.ok{color:var(--dsw-alias-state-success-primary,#3ecf8e);border-color:var(--dsw-alias-state-success-primary,rgba(62,207,142,.4))}
417
+ .tb-feedback.warn{color:var(--dsw-alias-state-warning-primary,#f0b23e);border-color:var(--dsw-alias-state-warning-primary,rgba(240,178,62,.45))}
418
+ .tb-feedback.err{color:var(--dsw-alias-state-error-primary,#ff7a59);border-color:var(--dsw-alias-state-error-primary,rgba(255,122,89,.45))}
419
+ .tb-feedback .tb-actions{display:flex;gap:6px;flex-wrap:wrap}
420
+ .tb-session{border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.12));border-radius:9px;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.03));overflow:hidden}
421
+ .tb-session.current{border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);box-shadow:0 0 0 1px rgba(65,118,230,.2)}
422
+ .tb-session-head{display:flex;align-items:center;gap:6px;flex-wrap:wrap;padding:8px 10px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.08))}
423
+ .tb-session-title{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:240px}
424
+ .tb-turn{display:flex;flex-direction:column;gap:4px;padding:7px 10px;border-top:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.06))}
425
+ .tb-turn:first-child{border-top:0}
426
+ .tb-turn-head{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
427
+ .tb-turn-label{font-weight:600;font-size:12px;white-space:nowrap}
428
+ .tb-prompt{color:var(--dsw-alias-label-secondary,#9aa0a6);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%;font-size:11.5px}
429
+ .tb-delta{display:inline-flex;gap:5px;font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6);flex-wrap:wrap}
430
+ .tb-delta .add{color:var(--dsw-alias-state-success-primary,#3ecf8e)}.tb-delta .mod{color:var(--dsw-alias-state-warning-primary,#f0b23e)}.tb-delta .del{color:var(--dsw-alias-state-error-primary,#ff7a59)}
431
+ .tb-actions{display:flex;gap:6px;flex-wrap:wrap;margin-left:auto}
432
+ .tb-viewtabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}
433
+ .tb-viewtab{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6);border-radius:6px;padding:3px 8px;font-size:11.5px;cursor:pointer;line-height:1.4}
434
+ .tb-viewtab.on{background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.08));color:var(--dsw-alias-label-primary,#e6e6e6);border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}
435
+ .tb-canvas{position:relative;overflow:hidden;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.12));border-radius:12px;background:radial-gradient(circle at 1px 1px, var(--dsw-alias-border-l2,rgba(255,255,255,.10)) 1px, transparent 0) 0 0/22px 22px, var(--dsw-alias-bg-layer-1,rgba(255,255,255,.02));height:clamp(320px,66vh,720px);min-height:240px;cursor:grab;touch-action:none;user-select:none}
436
+ .tb-canvas.expanded{height:min(88vh,1100px);min-height:420px}
437
+ .tb-canvas:active{cursor:grabbing}
438
+ .tb-canvas-toolbar{position:absolute;top:8px;right:8px;z-index:3;display:flex;gap:4px;align-items:center;background:var(--dsw-alias-bg-layer-2,rgba(24,28,36,.85));border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:8px;padding:3px;backdrop-filter:blur(4px)}
439
+ .tb-canvas-btn{appearance:none;border:0;background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6);border-radius:6px;min-width:22px;height:22px;padding:0 6px;font-size:11.5px;cursor:pointer;line-height:1}
440
+ .tb-canvas-btn.off{opacity:.5}
441
+ .tb-canvas-btn.on{color:var(--dsw-alias-state-success-primary,#3ecf8e)}
442
+ .tb-canvas-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.1));color:var(--dsw-alias-label-primary,#e6e6e6)}
443
+ .tb-world{position:absolute;left:0;top:0;transform-origin:0 0}
444
+ .tb-world-links{position:absolute;left:0;top:0;pointer-events:none;overflow:visible}
445
+ .tb-link{fill:none;stroke-width:1.6;opacity:.55}
446
+ .tb-link.fork{stroke-width:2;opacity:.75}
447
+ .tb-link.current{stroke-width:2.6;opacity:1;filter:drop-shadow(0 0 3px currentColor)}
448
+ .tb-lane-label{position:absolute;transform:translateY(-50%);max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;line-height:16px;border:1px solid;border-radius:999px;padding:0 8px;background:var(--dsw-alias-bg-base,#16181d);color:var(--dsw-alias-label-secondary,#9aa0a6);opacity:.85}
449
+ .tb-lane-label.current{opacity:1;font-weight:600}
450
+ .tb-card{position:absolute;width:246px;height:116px;box-sizing:border-box;border-radius:12px;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));background:var(--dsw-alias-bg-layer-2,rgba(28,32,40,.96));box-shadow:0 2px 8px rgba(0,0,0,.18);padding:8px 10px;display:flex;flex-direction:column;gap:5px;cursor:pointer;overflow:hidden;transition:box-shadow .12s, border-color .12s, transform .12s}
451
+ .tb-card:before{content:"";position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--tb-color,#4d7cfe);opacity:.55;border-radius:12px 0 0 12px}
452
+ .tb-card:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(0,0,0,.26)}
453
+ .tb-card.onpath{border-color:color-mix(in srgb, var(--tb-color,#4d7cfe) 55%, transparent)}
454
+ .tb-card.current{border-color:var(--tb-color,#4d7cfe);box-shadow:0 0 0 2px color-mix(in srgb, var(--tb-color,#4d7cfe) 32%, transparent), 0 6px 16px rgba(0,0,0,.24)}
455
+ .tb-card.selected{border-color:var(--tb-color,#4d7cfe);box-shadow:0 0 0 3px color-mix(in srgb, var(--tb-color,#4d7cfe) 42%, transparent), 0 8px 20px rgba(0,0,0,.3)}
456
+ .tb-card-head{display:flex;align-items:center;gap:6px;min-height:18px}
457
+ .tb-card-branch{font-size:10.5px;color:var(--dsw-alias-label-secondary,#9aa0a6);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:96px;line-height:16px}
458
+ .tb-card-badge{font-size:10.5px;font-weight:700;line-height:16px;border-radius:999px;padding:0 7px;color:var(--tb-color,#4d7cfe);border:1px solid color-mix(in srgb, var(--tb-color,#4d7cfe) 55%, transparent);background:color-mix(in srgb, var(--tb-color,#4d7cfe) 12%, transparent);white-space:nowrap}
459
+ .tb-card-spacer{flex:1}
460
+ .tb-card-time{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a919c);white-space:nowrap}
461
+ .tb-card-dot{width:7px;height:7px;border-radius:50%;background:var(--tb-color,#4d7cfe);box-shadow:0 0 0 3px color-mix(in srgb, var(--tb-color,#4d7cfe) 25%, transparent)}
462
+ .tb-card-prompt{font-size:11.5px;line-height:1.45;color:var(--dsw-alias-label-secondary,#9aa0a6);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;flex:1;word-break:break-word}
463
+ .tb-card-foot{display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:10px;min-height:16px}
464
+ .tb-card-chip{border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:4px;padding:0 4px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a919c)}
465
+ .tb-card-chip.manual{border-style:dashed}
466
+ .tb-card-chip.warn{color:var(--dsw-alias-state-warning-primary,#f0b23e);border-color:currentColor}
467
+ .tb-card-action{margin-left:auto;appearance:none;border:1px solid color-mix(in srgb, var(--tb-color,#4d7cfe) 45%, transparent);background:color-mix(in srgb, var(--tb-color,#4d7cfe) 12%, transparent);color:var(--tb-color,#4d7cfe);border-radius:4px;padding:0 5px;line-height:15px;font-size:9.5px;cursor:pointer;white-space:nowrap}
468
+ .tb-card-action:hover{background:color-mix(in srgb, var(--tb-color,#4d7cfe) 24%, transparent)}
469
+ .tb-card-action.danger{border-color:color-mix(in srgb, var(--dsw-alias-state-error-primary,#ff7a59) 55%, transparent);background:color-mix(in srgb, var(--dsw-alias-state-error-primary,#ff7a59) 10%, transparent);color:var(--dsw-alias-state-error-primary,#ff7a59)}
470
+ .tb-card-action.danger:hover{background:color-mix(in srgb, var(--dsw-alias-state-error-primary,#ff7a59) 22%, transparent)}
471
+ .tb-card:active{cursor:grabbing}
472
+ .tb-card-note{font-size:10.5px;line-height:1.35;color:var(--dsw-alias-label-primary,#d7dbe2);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;word-break:break-word;border-left:2px solid color-mix(in srgb, var(--tb-color,#4d7cfe) 65%, transparent);padding-left:6px}
473
+ .tb-card-prompt.withnote{-webkit-line-clamp:1;font-size:11px}
474
+ .tb-card-editnote{margin-left:auto;appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.05));color:var(--dsw-alias-label-secondary,#9aa0a6);border-radius:4px;padding:0 5px;line-height:15px;font-size:9.5px;cursor:pointer;white-space:nowrap}
475
+ .tb-card-editnote:hover{color:var(--dsw-alias-label-primary,#e6e6e6)}
476
+ .tb-card-editnote.has{color:var(--tb-color,#4d7cfe);border-color:color-mix(in srgb, var(--tb-color,#4d7cfe) 50%, transparent)}
477
+ .tb-overlay{position:fixed;inset:0;z-index:60;background:rgba(0,0,0,.35);display:flex;justify-content:flex-end;align-items:stretch}
478
+ .tb-overlay.center{justify-content:center;align-items:center;padding:16px}
479
+ .tb-note-dialog{width:min(520px,92vw);height:100%;background:var(--dsw-alias-bg-base,#16181d);border-left:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));padding:12px;display:flex;flex-direction:column;gap:8px;overflow:auto;box-shadow:-8px 0 24px rgba(0,0,0,.28)}
480
+ .tb-note-dialog textarea,.tb-board-dialog textarea,.tb-board-dialog input{width:100%;box-sizing:border-box;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.04));color:var(--dsw-alias-label-primary,#e6e6e6);border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));border-radius:7px;padding:7px 9px;font-size:12px;line-height:1.5;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;resize:vertical}
481
+ .tb-note-dialog textarea{min-height:180px}
482
+ .tb-note-actions{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end;margin-top:auto}
483
+ .tb-board-dialog{width:100%;box-sizing:border-box;background:var(--dsw-alias-bg-layer-2,rgba(28,32,40,.98));border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:10px;padding:12px;display:flex;flex-direction:column;gap:8px;max-height:calc(100vh - 48px);overflow:auto}
484
+ .tb-board-dialog textarea{min-height:180px}
485
+ .tb-board-panel{display:flex;flex-direction:column;height:100%;min-height:100%;width:100%;font-size:12.5px;color:var(--dsw-alias-label-primary,#e6e6e6);background:var(--dsw-alias-bg-base,#16181d)}
486
+ .tb-board-head{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.1));flex-wrap:wrap}
487
+ .tb-board-title{font-weight:600;font-size:13.5px}
488
+ .tb-board-sub{font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6)}
489
+ .tb-board-body{flex:1;min-height:120px;overflow:auto;padding:10px 12px 28px;display:flex;flex-direction:column;gap:10px}
490
+ .tb-board-hint{margin:0;padding:7px 9px;border-radius:7px;border:1px dashed var(--dsw-alias-border-l2,rgba(255,255,255,.16));font-size:11px;line-height:1.55;color:var(--dsw-alias-label-secondary,#9aa0a6)}
491
+ .tb-board-empty{margin:0;padding:18px 10px;text-align:center;color:var(--dsw-alias-label-secondary,#9aa0a6);font-size:12px;line-height:1.6}
492
+ .tb-board-note{border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:9px;padding:9px 11px;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.03));display:flex;flex-direction:column;gap:6px}
493
+ .tb-board-note-head{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
494
+ .tb-board-note-title{font-weight:600;font-size:12.5px;word-break:break-word}
495
+ .tb-board-meta{font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8a919c);white-space:nowrap}
496
+ .tb-board-actions{margin-left:auto;display:flex;gap:4px;flex-wrap:wrap}
497
+ .tb-md{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-primary,#d7dbe2);word-break:break-word}
498
+ .tb-md>*:first-child{margin-top:0}
499
+ .tb-md>*:last-child{margin-bottom:0}
500
+ .tb-md h1,.tb-md h2,.tb-md h3,.tb-md h4,.tb-md h5,.tb-md h6{margin:8px 0 4px;font-size:13px;line-height:1.4}
501
+ .tb-md h1{font-size:15px}.tb-md h2{font-size:14px}
502
+ .tb-md p{margin:4px 0}
503
+ .tb-md ul,.tb-md ol{margin:4px 0;padding-left:20px}
504
+ .tb-md li{margin:2px 0}
505
+ .tb-md blockquote{margin:6px 0;padding:2px 10px;border-left:3px solid var(--dsw-alias-border-l2,rgba(255,255,255,.24));color:var(--dsw-alias-label-secondary,#9aa0a6)}
506
+ .tb-md code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.08));border-radius:4px;padding:1px 4px}
507
+ .tb-md pre{margin:6px 0;padding:8px 10px;border-radius:7px;background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.28));overflow:auto;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.1))}
508
+ .tb-md pre code{background:transparent;padding:0}
509
+ .tb-md a{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#7aa2ff)}
510
+ .tb-md hr{border:0;border-top:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));margin:8px 0}
511
+ .tb-md strong{font-weight:700}
512
+ .tb-lane-label{cursor:pointer}
513
+ .tb-canvas-hint{font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8a919c)}
514
+ .tb-tree-section{display:flex;flex-direction:column;gap:8px}
515
+ .tb-legend{display:flex;gap:10px;flex-wrap:wrap;align-items:center;font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8a919c)}
516
+ .tb-legend i{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-label-tertiary,#8a919c);margin-right:4px;vertical-align:-1px}
517
+ .tb-legend i.manual{background:transparent;border:1.5px dashed var(--dsw-alias-label-tertiary,#8a919c);border-radius:2px;transform:rotate(45deg)}
518
+ .tb-legend i.current{background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}
519
+ .tb-tree-wrap{position:relative;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.12));border-radius:9px;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.02));overflow:auto;max-height:min(52vh,460px);min-height:140px}
520
+ .tb-tree-canvas{position:relative}
521
+ .tb-tree-svg{position:absolute;left:0;top:0;pointer-events:none}
522
+ .tb-link{fill:none;stroke:var(--dsw-alias-border-l3,rgba(255,255,255,.22));stroke-width:1.4}
523
+ .tb-link.current{stroke:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);stroke-width:2.2}
524
+ .tb-band{position:absolute;border-radius:10px;border:1px solid transparent;background:transparent;pointer-events:none}
525
+ .tb-band.current{border-color:rgba(65,118,230,.35);background:rgba(65,118,230,.06)}
526
+ .tb-branch-pill{position:absolute;transform:translate(-50%,-50%);max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;color:var(--dsw-alias-label-secondary,#9aa0a6);border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:999px;padding:1px 8px;background:var(--dsw-alias-bg-layer-1,rgba(20,23,29,.9))}
527
+ .tb-branch-pill.current{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#7aa2ff);border-color:currentColor}
528
+ .tb-node{position:absolute;transform:translate(-50%,-50%);appearance:none;border-radius:999px;border:1px solid var(--dsw-alias-border-l3,rgba(255,255,255,.3));background:var(--dsw-alias-bg-layer-2,rgba(40,45,55,.95));color:var(--dsw-alias-label-secondary,#9aa0a6);font-size:10px;line-height:1;padding:4px 7px;cursor:pointer;white-space:nowrap;z-index:1}
529
+ .tb-node:hover{border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);color:var(--dsw-alias-label-primary,#e6e6e6)}
530
+ .tb-node.onpath{color:var(--dsw-alias-label-primary,#e6e6e6);border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}
531
+ .tb-node.current{box-shadow:0 0 0 2px rgba(65,118,230,.35)}
532
+ .tb-node.selected{background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);color:#fff;border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}
533
+ .tb-node.manual{border-style:dashed;border-radius:5px;transform:translate(-50%,-50%) rotate(45deg)}
534
+ .tb-node.manual span{display:inline-block;transform:rotate(-45deg)}
535
+ .tb-node.start{border-radius:4px}
536
+ .tb-detail{border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:9px;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.03));padding:8px 10px;display:flex;flex-direction:column;gap:6px}
537
+ .tb-detail-head{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
538
+ .tb-detail-title{font-weight:600;font-size:12.5px}
539
+ .tb-detail-prompt{color:var(--dsw-alias-label-secondary,#9aa0a6);font-size:11.5px;line-height:1.5;word-break:break-word}
540
+ .tb-cp-row{border-top:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.08));padding-top:6px;display:flex;flex-direction:column;gap:4px}
541
+ .tb-cp-row:first-of-type{border-top:0}
542
+ .tb-cp-head{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11.5px}
543
+ .tb-cp-phase{font-weight:600;color:var(--dsw-alias-label-primary,#e6e6e6)}
544
+ .tb-hero{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;color:var(--dsw-alias-label-secondary,#9aa0a6);cursor:pointer;white-space:nowrap;line-height:1.6}
545
+ .tb-hero:hover{color:var(--dsw-alias-label-primary,#e6e6e6)}
546
+ .tb-hero input{margin:0;flex:none;accent-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}
547
+ .tb-hero input:disabled{cursor:default}
548
+ .tb-hero-err{font-size:11px;color:var(--dsw-alias-state-error-primary,#e5484d);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px}
549
+ .tb-hero-name{max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-tertiary,#8a919c)}
550
+ .tb-pill{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.04));color:var(--dsw-alias-label-secondary,#9aa0a6);border-radius:999px;padding:2px 9px;font-size:11.5px;cursor:pointer;display:inline-flex;align-items:center;gap:5px;line-height:1.5;white-space:nowrap}
551
+ .tb-pill:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.1));color:var(--dsw-alias-label-primary,#e6e6e6)}
552
+ .tb-iconbtn{appearance:none;border:0;background:transparent;color:inherit;display:inline-flex;align-items:center;justify-content:center;padding:4px;border-radius:6px;cursor:pointer}
553
+ .tb-iconbtn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.1))}
554
+ .tb-empty{padding:16px 10px;color:var(--dsw-alias-label-secondary,#9aa0a6);line-height:1.6}
555
+ .tb-inline{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
556
+ `
557
+
558
+ /** One-time style installation owned by the plugin context. */
559
+ function installStyles() {
560
+ if (typeof document === 'undefined') return () => {}
561
+ const attribute = 'data-plugin-css'
562
+ const marker = `${ID}/panel.css`
563
+ if (document.querySelector(`style[${attribute}=${JSON.stringify(marker)}]`) !== null) return () => {}
564
+ const tag = document.createElement('style')
565
+ tag.dataset.plugin = ID
566
+ tag.setAttribute(attribute, marker)
567
+ tag.textContent = CSS
568
+ document.head.appendChild(tag)
569
+ return () => {
570
+ tag.remove()
571
+ }
572
+ }
573
+
574
+ /* ---------------------------------------------------------------- */
575
+ /* icons */
576
+ /* ---------------------------------------------------------------- */
577
+
578
+ function TimebackIcon(props) {
579
+ const size = (props && props.size) || 16
580
+ return h(
581
+ 'svg',
582
+ {
583
+ viewBox: '0 0 24 24',
584
+ width: size,
585
+ height: size,
586
+ 'aria-hidden': true,
587
+ fill: 'none',
588
+ stroke: 'currentColor',
589
+ strokeWidth: 1.7,
590
+ strokeLinecap: 'round',
591
+ strokeLinejoin: 'round',
592
+ },
593
+ h('circle', { cx: 12, cy: 12.5, r: 7.6 }),
594
+ h('path', { d: 'M12 8.2v4.4l2.8 1.7' }),
595
+ h('path', { d: 'M4.2 6.4v4.1h4.1' }),
596
+ h('path', { d: 'M4.6 10.4A8.4 8.4 0 0 1 9.6 4.6' }),
597
+ )
598
+ }
599
+
600
+ function GuideIcon(props) {
601
+ return TimebackIcon({ size: (props && props.size) || 18 })
602
+ }
603
+
604
+ /* ---------------------------------------------------------------- */
605
+ /* helpers */
606
+ /* ---------------------------------------------------------------- */
607
+
608
+ /** Replace `{name}` placeholders in one localized template. */
609
+ function format(template, values) {
610
+ return String(template).replace(/\{(\w+)\}/g, (_match, key) => (key in values ? String(values[key]) : `{${key}}`))
611
+ }
612
+
613
+ /** Last path component of an absolute directory, for compact labels. */
614
+ function baseName(value) {
615
+ const cleaned = String(value || '').replace(/[\\/]+$/, '')
616
+ const parts = cleaned.split(/[\\/]/)
617
+ return parts[parts.length - 1] || cleaned
618
+ }
619
+
620
+ /** Flatten Markdown into one plain-text line for compact card previews. */
621
+ function stripMarkdown(value) {
622
+ return String(value ?? '')
623
+ .replace(/```[\s\S]*?```/g, ' ')
624
+ .replace(/`([^`]*)`/g, '$1')
625
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
626
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
627
+ .replace(/^[ \t]*(?:#{1,6}|>|[-*+]|\d+[.)])\s+/gm, '')
628
+ .replace(/[*_~]{1,3}/g, '')
629
+ .replace(/\s+/g, ' ')
630
+ .trim()
631
+ }
632
+
633
+ /** Parse inline Markdown (bold/italic/code/link) into React children. */
634
+ function inlineMarkdown(text, keyPrefix) {
635
+ const nodes = []
636
+ const pattern = /(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*\n]+\*|_[^_\n]+_)/g
637
+ let last = 0
638
+ let match
639
+ let index = 0
640
+ while ((match = pattern.exec(text)) !== null) {
641
+ if (match.index > last) nodes.push(text.slice(last, match.index))
642
+ const token = match[0]
643
+ const key = `${keyPrefix}-i${index++}`
644
+ if (token.startsWith('`')) nodes.push(h('code', { key }, token.slice(1, -1)))
645
+ else if (token.startsWith('**') || token.startsWith('__')) nodes.push(h('strong', { key }, token.slice(2, -2)))
646
+ else if (token.startsWith('[')) {
647
+ const link = /^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(token)
648
+ nodes.push(h('a', { key, href: link[2], target: '_blank', rel: 'noreferrer noopener' }, link[1]))
649
+ } else nodes.push(h('em', { key }, token.slice(1, -1)))
650
+ last = match.index + token.length
651
+ }
652
+ if (last < text.length) nodes.push(text.slice(last))
653
+ return nodes
654
+ }
655
+
656
+ /** Render a line-oriented Markdown subset as React nodes (escaping by construction). */
657
+ function renderMarkdown(source, keyPrefix) {
658
+ const lines = String(source ?? '').replace(/\r\n?/g, '\n').split('\n')
659
+ const blocks = []
660
+ const prefix = keyPrefix ?? 'md'
661
+ let index = 0
662
+ const keyOf = () => `${prefix}-b${blocks.length}`
663
+ while (index < lines.length) {
664
+ const line = lines[index]
665
+ if (/^\s*$/.test(line)) {
666
+ index += 1
667
+ continue
668
+ }
669
+ if (/^```/.test(line)) {
670
+ const code = []
671
+ index += 1
672
+ while (index < lines.length && !/^```/.test(lines[index])) code.push(lines[index++])
673
+ index += 1
674
+ blocks.push(h('pre', { key: keyOf() }, h('code', null, code.join('\n'))))
675
+ continue
676
+ }
677
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line)
678
+ if (heading) {
679
+ const level = Math.min(6, heading[1].length)
680
+ blocks.push(h(`h${level}`, { key: keyOf() }, ...inlineMarkdown(heading[2], `${prefix}-h${blocks.length}`)))
681
+ index += 1
682
+ continue
683
+ }
684
+ if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
685
+ blocks.push(h('hr', { key: keyOf() }))
686
+ index += 1
687
+ continue
688
+ }
689
+ if (/^\s*>/.test(line)) {
690
+ const inner = []
691
+ while (index < lines.length && /^\s*>/.test(lines[index])) inner.push(lines[index++].replace(/^\s*>\s?/, ''))
692
+ blocks.push(h('blockquote', { key: keyOf() }, renderMarkdown(inner.join('\n'), `${prefix}-q${blocks.length}`)))
693
+ continue
694
+ }
695
+ if (/^\s*[-*+]\s+/.test(line)) {
696
+ const items = []
697
+ while (index < lines.length) {
698
+ const item = /^\s*[-*+]\s+(.*)$/.exec(lines[index])
699
+ if (!item) break
700
+ items.push(h('li', { key: `li${items.length}` }, ...inlineMarkdown(item[1], `${prefix}-l${blocks.length}-${items.length}`)))
701
+ index += 1
702
+ }
703
+ blocks.push(h('ul', { key: keyOf() }, ...items))
704
+ continue
705
+ }
706
+ if (/^\s*\d+[.)]\s+/.test(line)) {
707
+ const items = []
708
+ while (index < lines.length) {
709
+ const item = /^\s*\d+[.)]\s+(.*)$/.exec(lines[index])
710
+ if (!item) break
711
+ items.push(h('li', { key: `li${items.length}` }, ...inlineMarkdown(item[1], `${prefix}-o${blocks.length}-${items.length}`)))
712
+ index += 1
713
+ }
714
+ blocks.push(h('ol', { key: keyOf() }, ...items))
715
+ continue
716
+ }
717
+ const paragraph = [line]
718
+ index += 1
719
+ while (
720
+ index < lines.length &&
721
+ !/^\s*$/.test(lines[index]) &&
722
+ !/^```|^#{1,6}\s|^\s*>|^\s*[-*+]\s|^\s*\d+[.)]\s|^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(lines[index])
723
+ ) {
724
+ paragraph.push(lines[index++])
725
+ }
726
+ blocks.push(h('p', { key: keyOf() }, ...inlineMarkdown(paragraph.join(' '), `${prefix}-p${blocks.length}`)))
727
+ }
728
+ return blocks.length > 0 ? blocks : [h('p', { key: `${prefix}-empty` }, '')]
729
+ }
730
+
731
+ /** One bounded JSON request to the Host route. */
732
+ async function request(path, options) {
733
+ const response = await fetch(`${API}/${path}`, {
734
+ credentials: 'same-origin',
735
+ headers: { accept: 'application/json', ...(options?.body ? { 'content-type': 'application/json' } : {}) },
736
+ ...options,
737
+ ...(options?.body ? { body: JSON.stringify(options.body) } : {}),
738
+ })
739
+ let body
740
+ try {
741
+ body = await response.json()
742
+ } catch {
743
+ throw new Error(`HTTP ${response.status}`)
744
+ }
745
+ if (!response.ok || body?.ok === false) {
746
+ const error = new Error(body?.error || `HTTP ${response.status}`)
747
+ error.code = body?.code
748
+ throw error
749
+ }
750
+ return body
751
+ }
752
+
753
+ /** Format a checkpoint time; today keeps HH:MM, older adds the date. */
754
+ function clock(value) {
755
+ if (!Number.isFinite(value)) return ''
756
+ try {
757
+ const date = new Date(value)
758
+ const sameDay = date.toDateString() === new Date().toDateString()
759
+ return date.toLocaleString(undefined, sameDay ? { hour: '2-digit', minute: '2-digit' } : { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
760
+ } catch {
761
+ return ''
762
+ }
763
+ }
764
+
765
+ /** Localized phase label for one checkpoint. */
766
+ function phaseLabel(checkpoint, t) {
767
+ if (checkpoint.phase === 'before') return t('panel.before')
768
+ if (checkpoint.phase === 'after') return t('panel.after')
769
+ if (checkpoint.phase === 'manual') return checkpoint.label || t('panel.manual')
770
+ if (checkpoint.phase === 'inherited') return checkpoint.label || t('panel.inherited')
771
+ if (checkpoint.phase === 'safety') return checkpoint.label || t('panel.safety')
772
+ return checkpoint.label || checkpoint.phase
773
+ }
774
+
775
+ /** A checkpoint's user-facing identity: `T3 · 结束后`. */
776
+ function checkpointName(checkpoint, t) {
777
+ const phase = phaseLabel(checkpoint, t)
778
+ return checkpoint.turn === null || checkpoint.turn === undefined ? phase : `T${checkpoint.turn} · ${phase}`
779
+ }
780
+
781
+ /** Group one session's checkpoints into newest-first rows. */
782
+ function turnRows(checkpoints, t) {
783
+ const order = { after: 3, before: 1, manual: 4, inherited: 0, safety: 5 }
784
+ const rows = checkpoints.map((checkpoint) => ({ key: checkpoint.id, checkpoint }))
785
+ rows.sort((left, right) => {
786
+ const turnDelta = (left.checkpoint.turn ?? -1) - (right.checkpoint.turn ?? -1)
787
+ if (turnDelta !== 0) return -turnDelta
788
+ const phaseDelta = (order[left.checkpoint.phase] ?? 2) - (order[right.checkpoint.phase] ?? 2)
789
+ if (phaseDelta !== 0) return -phaseDelta
790
+ return (right.checkpoint.createdAt ?? 0) - (left.checkpoint.createdAt ?? 0)
791
+ })
792
+ return {
793
+ rows: rows.slice(0, MAX_ROWS),
794
+ total: rows.length,
795
+ truncated: rows.length > MAX_ROWS,
796
+ label: (checkpoint) => checkpointName(checkpoint, t),
797
+ }
798
+ }
799
+
800
+
801
+ /* ---------------------------------------------------------------- */
802
+ /* tree canvas: layout + rendering (card canvas, inspired by */
803
+ /* node-link conversation maps; original implementation) */
804
+ /* ---------------------------------------------------------------- */
805
+
806
+ /** Card dimensions and spacing of the conversation canvas. */
807
+ const CARD_WIDTH = 246
808
+ const CARD_HEIGHT = 116
809
+ const CARD_GAP_X = 54
810
+ const CARD_GAP_Y = 38
811
+ const CANVAS_PAD = 46
812
+ /** Maximum turns one canvas renders before pointing at list view. */
813
+ const MAX_TREE_TURNS = 120
814
+ /** Lane accents; one branch keeps one colour. */
815
+ const LANE_COLORS = ['#4d7cfe', '#3ecf8e', '#f0b23e', '#c084fc', '#f472b6', '#38bdf8']
816
+
817
+ /**
818
+ * The part of an element actually visible after every clipping scroll
819
+ * container above it. Edge auto-pan must use this instead of the element's
820
+ * geometric box: the canvas can extend below/right of the panel viewport,
821
+ * which made some edges unreachable and asymmetric.
822
+ * @param {Element} element - element to measure.
823
+ * @returns {{left:number,top:number,right:number,bottom:number}|null}
824
+ */
825
+ function visibleRect(element) {
826
+ try {
827
+ const box = element.getBoundingClientRect()
828
+ let rect = { left: box.left, top: box.top, right: box.right, bottom: box.bottom }
829
+ const view = element.ownerDocument?.defaultView ?? window
830
+ const doc = element.ownerDocument
831
+ let node = element.parentElement
832
+ while (node && node !== doc?.body && node !== doc?.documentElement) {
833
+ const style = view.getComputedStyle(node)
834
+ const overflow = `${style.overflow} ${style.overflowX} ${style.overflowY}`
835
+ if (/hidden|auto|scroll|clip/.test(overflow)) {
836
+ const parent = node.getBoundingClientRect()
837
+ rect = {
838
+ left: Math.max(rect.left, parent.left + node.clientLeft),
839
+ top: Math.max(rect.top, parent.top + node.clientTop),
840
+ right: Math.min(rect.right, parent.left + node.clientLeft + node.clientWidth),
841
+ bottom: Math.min(rect.bottom, parent.top + node.clientTop + node.clientHeight),
842
+ }
843
+ }
844
+ node = node.parentElement
845
+ }
846
+ rect = {
847
+ left: Math.max(rect.left, 0),
848
+ top: Math.max(rect.top, 0),
849
+ right: Math.min(rect.right, view.innerWidth ?? rect.right),
850
+ bottom: Math.min(rect.bottom, view.innerHeight ?? rect.bottom),
851
+ }
852
+ if (rect.right <= rect.left || rect.bottom <= rect.top) return null
853
+ return rect
854
+ } catch {
855
+ return null
856
+ }
857
+ }
858
+
859
+ /**
860
+ * Edge auto-pan intensity for one pointer position.
861
+ * @param {{x:number,y:number}} pointer - viewport-relative pointer.
862
+ * @param {{left:number,top:number,right:number,bottom:number}} bounds - viewport box.
863
+ * @param {number} band - edge band width in CSS px.
864
+ * @returns {{x:number,y:number}} -1..1 per axis, positive means reveal content
865
+ * beyond that edge (left/top positive camera movement).
866
+ */
867
+ function edgePanVector(pointer, bounds, band) {
868
+ const depth = (distanceInside) => (band - Math.min(band, Math.max(0, distanceInside))) / band
869
+ const leftDepth = pointer.x - bounds.left < band ? depth(pointer.x - bounds.left) : 0
870
+ const rightDepth = bounds.right - pointer.x < band ? depth(bounds.right - pointer.x) : 0
871
+ const topDepth = pointer.y - bounds.top < band ? depth(pointer.y - bounds.top) : 0
872
+ const bottomDepth = bounds.bottom - pointer.y < band ? depth(bounds.bottom - pointer.y) : 0
873
+ return { x: leftDepth - rightDepth, y: topDepth - bottomDepth }
874
+ }
875
+
876
+ /**
877
+ * Lay out branch cards left-to-right (turn chain) with one horizontal lane
878
+ * per branch Session, fork edges from the parent turn card to the child's
879
+ * first card, and the current root→Session path marked.
880
+ * @returns {{width:number,height:number,cards:object[],links:object[],lanes:object[],byId:Map,currentKey:string|null,truncated:boolean}}
881
+ */
882
+ function layoutTree(sessions, currentSessionId, overrides) {
883
+ const byId = new Map(sessions.map((session) => [session.sessionId, session]))
884
+ const laneOf = new Map()
885
+ for (const session of sessions) {
886
+ if (laneOf.has(session.sessionId)) continue
887
+ laneOf.set(session.sessionId, laneOf.size)
888
+ }
889
+ const currentPath = new Set()
890
+ let cursor = byId.get(currentSessionId)
891
+ const guard = new Set()
892
+ while (cursor && !guard.has(cursor.sessionId)) {
893
+ guard.add(cursor.sessionId)
894
+ currentPath.add(cursor.sessionId)
895
+ cursor = cursor.parentSessionId ? byId.get(cursor.parentSessionId) : undefined
896
+ }
897
+ const cardOverrides = overrides && typeof overrides === 'object' ? overrides : {}
898
+ const place = (key, natural) => {
899
+ const override = cardOverrides[key]
900
+ if (override && Number.isFinite(override.x) && Number.isFinite(override.y)) return { x: override.x, y: override.y }
901
+ return natural
902
+ }
903
+ const cards = []
904
+ const links = []
905
+ const lanes = []
906
+ const cardsBySession = new Map()
907
+ let truncated = false
908
+ const cardForTurn = (session, turn) => (cardsBySession.get(session.sessionId) ?? []).find((card) => card.turn === turn) ?? null
909
+ const lastCardOf = (sessionId) => {
910
+ const list = cardsBySession.get(sessionId) ?? []
911
+ return list[list.length - 1] ?? null
912
+ }
913
+ for (const session of sessions) {
914
+ const lane = laneOf.get(session.sessionId) ?? 0
915
+ const color = LANE_COLORS[lane % LANE_COLORS.length]
916
+ const y = CANVAS_PAD + lane * (CARD_HEIGHT + CARD_GAP_Y)
917
+ const onPath = currentPath.has(session.sessionId)
918
+ const parent = session.parentSessionId ? byId.get(session.parentSessionId) : null
919
+ let forkCard = null
920
+ if (parent) {
921
+ if (Number.isInteger(session.forkAtSeq)) {
922
+ forkCard =
923
+ (cardsBySession.get(parent.sessionId) ?? []).find((card) =>
924
+ card.checkpoints.some((checkpoint) => checkpoint.seq === session.forkAtSeq),
925
+ ) ?? null
926
+ }
927
+ forkCard = forkCard ?? lastCardOf(parent.sessionId)
928
+ }
929
+ let x = CANVAS_PAD
930
+ if (forkCard) x = forkCard.x + CARD_WIDTH + CARD_GAP_X
931
+ const groups = new Map()
932
+ const looseManuals = []
933
+ const startCheckpoints = []
934
+ for (const checkpoint of session.checkpoints ?? []) {
935
+ if (checkpoint.phase === 'inherited') {
936
+ startCheckpoints.push(checkpoint)
937
+ continue
938
+ }
939
+ if (!Number.isInteger(checkpoint.turn)) {
940
+ if (checkpoint.phase === 'manual') looseManuals.push(checkpoint)
941
+ continue
942
+ }
943
+ const group = groups.get(checkpoint.turn) ?? { turn: checkpoint.turn, manual: [] }
944
+ if (checkpoint.phase === 'before') group.before = checkpoint
945
+ else if (checkpoint.phase === 'after') group.after = checkpoint
946
+ else if (checkpoint.phase === 'manual') group.manual.push(checkpoint)
947
+ else if (checkpoint.phase === 'safety') group.safety = checkpoint
948
+ groups.set(checkpoint.turn, group)
949
+ }
950
+ const turns = [...groups.keys()].sort((left, right) => left - right)
951
+ const shown = []
952
+ for (const turn of turns) {
953
+ if (turn > MAX_TREE_TURNS) {
954
+ truncated = true
955
+ continue
956
+ }
957
+ shown.push(turn)
958
+ }
959
+ const sessionCards = []
960
+ const pushCard = (card) => {
961
+ const placed = place(card.key, { x: card.x, y: card.y })
962
+ card.x = placed.x
963
+ card.y = placed.y
964
+ sessionCards.push(card)
965
+ cards.push(card)
966
+ }
967
+ if (startCheckpoints.length > 0) {
968
+ const prompt = startCheckpoints.find((checkpoint) => checkpoint.prompt)?.prompt ?? null
969
+ pushCard({
970
+ key: `${session.sessionId}:start`,
971
+ kind: 'start',
972
+ sessionId: session.sessionId,
973
+ sessionTitle: session.title || `${session.sessionId.slice(0, 8)}…`,
974
+ lane,
975
+ color,
976
+ x,
977
+ y,
978
+ label: '起点',
979
+ title: `${session.title || session.sessionId.slice(0, 8)} · 分支起点`,
980
+ prompt,
981
+ note: session.note ?? null,
982
+ checkpoints: startCheckpoints,
983
+ onPath,
984
+ createdAt: startCheckpoints[0]?.createdAt ?? null,
985
+ })
986
+ x += CARD_WIDTH + CARD_GAP_X
987
+ }
988
+ for (const turn of shown) {
989
+ const group = groups.get(turn)
990
+ const list = []
991
+ if (group.before) list.push(group.before)
992
+ if (group.safety) list.push(group.safety)
993
+ if (group.after) list.push(group.after)
994
+ for (const manual of group.manual ?? []) list.push(manual)
995
+ const prompt = group.after?.prompt ?? group.before?.prompt ?? null
996
+ pushCard({
997
+ key: `${session.sessionId}:turn:${turn}`,
998
+ kind: 'turn',
999
+ sessionId: session.sessionId,
1000
+ sessionTitle: session.title || `${session.sessionId.slice(0, 8)}…`,
1001
+ lane,
1002
+ color,
1003
+ x,
1004
+ y,
1005
+ turn,
1006
+ label: `T${turn}`,
1007
+ title: `${session.title || session.sessionId.slice(0, 8)} · 第 ${turn} 回合${prompt ? ` · ${prompt}` : ''}`,
1008
+ prompt,
1009
+ note: [...list].reverse().find((checkpoint) => checkpoint.note)?.note ?? null,
1010
+ checkpoints: list,
1011
+ manualCount: group.manual?.length ?? 0,
1012
+ onPath,
1013
+ createdAt: group.after?.createdAt ?? group.before?.createdAt ?? null,
1014
+ })
1015
+ x += CARD_WIDTH + CARD_GAP_X
1016
+ }
1017
+ for (const manual of looseManuals) {
1018
+ pushCard({
1019
+ key: `${session.sessionId}:manual:${manual.id}`,
1020
+ kind: 'manual',
1021
+ sessionId: session.sessionId,
1022
+ sessionTitle: session.title || `${session.sessionId.slice(0, 8)}…`,
1023
+ lane,
1024
+ color,
1025
+ x,
1026
+ y,
1027
+ label: '手动',
1028
+ title: `${session.title || session.sessionId.slice(0, 8)} · 手动检查点`,
1029
+ prompt: manual.prompt ?? null,
1030
+ note: manual.note ?? null,
1031
+ checkpoints: [manual],
1032
+ onPath,
1033
+ createdAt: manual.createdAt ?? null,
1034
+ })
1035
+ x += CARD_WIDTH + CARD_GAP_X
1036
+ }
1037
+ cardsBySession.set(session.sessionId, sessionCards)
1038
+ for (let index = 1; index < sessionCards.length; index += 1) {
1039
+ const from = sessionCards[index - 1]
1040
+ const to = sessionCards[index]
1041
+ links.push({
1042
+ key: `${session.sessionId}:chain:${index}`,
1043
+ kind: 'chain',
1044
+ current: onPath,
1045
+ color,
1046
+ d: connectorPath(
1047
+ { x: from.x + CARD_WIDTH, y: from.y + CARD_HEIGHT / 2 },
1048
+ { x: to.x, y: to.y + CARD_HEIGHT / 2 },
1049
+ ),
1050
+ })
1051
+ }
1052
+ if (forkCard && sessionCards.length > 0) {
1053
+ const first = sessionCards[0]
1054
+ links.push({
1055
+ key: `${session.sessionId}:fork`,
1056
+ kind: 'fork',
1057
+ current: onPath && currentPath.has(session.parentSessionId),
1058
+ color,
1059
+ d: connectorPath(
1060
+ { x: forkCard.x + CARD_WIDTH, y: forkCard.y + CARD_HEIGHT / 2 },
1061
+ { x: first.x, y: first.y + CARD_HEIGHT / 2 },
1062
+ ),
1063
+ })
1064
+ }
1065
+ if (sessionCards.length > 0) {
1066
+ lanes.push({
1067
+ key: `${session.sessionId}:lane`,
1068
+ sessionId: session.sessionId,
1069
+ title: session.title || `${session.sessionId.slice(0, 10)}…`,
1070
+ x: sessionCards[0].x,
1071
+ y: y - 26,
1072
+ width: Math.max(CARD_WIDTH, x - CARD_GAP_X - sessionCards[0].x),
1073
+ current: session.sessionId === currentSessionId,
1074
+ onPath,
1075
+ color,
1076
+ })
1077
+ }
1078
+ }
1079
+ const currentCards = cardsBySession.get(currentSessionId) ?? []
1080
+ const currentKey = currentCards.length > 0 ? currentCards[currentCards.length - 1].key : cards.length > 0 ? cards[cards.length - 1].key : null
1081
+ for (const card of cards) card.isCurrentPosition = card.key === currentKey
1082
+ const minX = cards.length === 0 ? 0 : Math.min(...cards.map((card) => card.x))
1083
+ const minY = cards.length === 0 ? 0 : Math.min(...cards.map((card) => card.y))
1084
+ const maxX = cards.length === 0 ? 320 : Math.max(...cards.map((card) => card.x + CARD_WIDTH))
1085
+ const maxY = cards.length === 0 ? 220 : Math.max(...cards.map((card) => card.y + CARD_HEIGHT))
1086
+ // Cards may carry negative coordinates after a drag. The world layer keeps
1087
+ // a fixed origin (no per-frame offset feedback) so dragging behaves the
1088
+ // same in every direction; the camera translate reveals negative space.
1089
+ const width = maxX + CANVAS_PAD
1090
+ const height = maxY + CANVAS_PAD
1091
+ return { width, height, minX, minY, maxX, maxY, cards, links, lanes, byId, currentKey, truncated }
1092
+ }
1093
+
1094
+ /** A cubic connector from one card edge to another. */
1095
+ function connectorPath(from, to) {
1096
+ const bend = Math.min(110, Math.max(36, Math.abs(to.x - from.x) * 0.2))
1097
+ return `M ${from.x} ${from.y} C ${from.x + bend} ${from.y}, ${to.x - bend} ${to.y}, ${to.x} ${to.y}`
1098
+ }
1099
+
1100
+ /** One card of the conversation canvas. */
1101
+ function CanvasCard({ card, t, selectedKey, onSelect, onOpen, onBranch, onPrune, onNote, onDragStart, suppressClickRef }) {
1102
+ const files = (card.checkpoints ?? []).reduce(
1103
+ (total, checkpoint) => ({
1104
+ added: total.added + (checkpoint.files?.added ?? 0),
1105
+ modified: total.modified + (checkpoint.files?.modified ?? 0),
1106
+ deleted: total.deleted + (checkpoint.files?.deleted ?? 0),
1107
+ }),
1108
+ { added: 0, modified: 0, deleted: 0 },
1109
+ )
1110
+ const phaseChips = []
1111
+ for (const checkpoint of card.checkpoints ?? []) {
1112
+ if (checkpoint.phase === 'before') phaseChips.push('前')
1113
+ else if (checkpoint.phase === 'after') phaseChips.push('后')
1114
+ else if (checkpoint.phase === 'manual') phaseChips.push('手动')
1115
+ else if (checkpoint.phase === 'inherited') phaseChips.push('起点')
1116
+ else if (checkpoint.phase === 'safety') phaseChips.push('安全')
1117
+ }
1118
+ const hasSnapshot = (card.checkpoints ?? []).some((checkpoint) => checkpoint.hasSnapshot !== false && checkpoint.hasSnapshot)
1119
+ const branchTarget = [...(card.checkpoints ?? [])].reverse().find((checkpoint) => Number.isInteger(checkpoint.seq) && checkpoint.phase !== 'before')
1120
+ const consumeClick = () => {
1121
+ if (suppressClickRef?.current) {
1122
+ suppressClickRef.current = false
1123
+ return true
1124
+ }
1125
+ return false
1126
+ }
1127
+ return h(
1128
+ 'article',
1129
+ {
1130
+ key: card.key,
1131
+ className: `tb-card${card.onPath ? ' onpath' : ''}${card.isCurrentPosition ? ' current' : ''}${card.key === selectedKey ? ' selected' : ''}`,
1132
+ style: { left: card.x, top: card.y, '--tb-color': card.color },
1133
+ title: card.title,
1134
+ role: 'button',
1135
+ tabIndex: 0,
1136
+ 'aria-label': card.title,
1137
+ onClick: (event) => {
1138
+ event.stopPropagation()
1139
+ if (consumeClick()) return
1140
+ onSelect(card.key)
1141
+ },
1142
+ onDoubleClick: (event) => {
1143
+ event.stopPropagation()
1144
+ if (consumeClick()) return
1145
+ if (typeof onOpen === 'function') onOpen(card.sessionId)
1146
+ },
1147
+ onPointerDown: (event) => {
1148
+ if (typeof onDragStart === 'function') onDragStart(event, card)
1149
+ },
1150
+ onKeyDown: (event) => {
1151
+ if (event.key === 'Enter' || event.key === ' ') {
1152
+ event.preventDefault()
1153
+ onSelect(card.key)
1154
+ }
1155
+ },
1156
+ },
1157
+ h(
1158
+ 'div',
1159
+ { className: 'tb-card-head' },
1160
+ h('span', { className: 'tb-card-badge' }, card.label),
1161
+ h('span', { className: 'tb-card-branch', title: card.sessionTitle, style: { color: card.color } }, card.sessionTitle),
1162
+ h('span', { className: 'tb-card-spacer' }),
1163
+ typeof onNote === 'function'
1164
+ ? h(
1165
+ 'button',
1166
+ {
1167
+ type: 'button',
1168
+ className: `tb-card-editnote${card.note ? ' has' : ''}`,
1169
+ title: t('note.title'),
1170
+ 'aria-label': t('note.title'),
1171
+ onClick: (event) => {
1172
+ event.stopPropagation()
1173
+ onNote(card)
1174
+ },
1175
+ },
1176
+ '📝',
1177
+ )
1178
+ : null,
1179
+ card.createdAt ? h('span', { className: 'tb-card-time' }, clock(card.createdAt)) : null,
1180
+ card.isCurrentPosition ? h('span', { className: 'tb-card-dot', title: t('panel.current') }) : null,
1181
+ ),
1182
+ h('div', { className: `tb-card-prompt${card.note ? ' withnote' : ''}` }, card.prompt || t('tree.noPrompt')),
1183
+ card.note ? h('div', { className: 'tb-card-note', title: card.note }, stripMarkdown(card.note)) : null,
1184
+ h(
1185
+ 'div',
1186
+ { className: 'tb-card-foot' },
1187
+ ...phaseChips.map((chip, index) => h('span', { key: `phase-${index}`, className: 'tb-card-chip' }, chip)),
1188
+ files.added || files.modified || files.deleted
1189
+ ? h(
1190
+ 'span',
1191
+ { className: 'tb-delta' },
1192
+ files.added ? h('span', { className: 'add' }, `+${files.added}`) : null,
1193
+ files.modified ? h('span', { className: 'mod' }, `~${files.modified}`) : null,
1194
+ files.deleted ? h('span', { className: 'del' }, `-${files.deleted}`) : null,
1195
+ )
1196
+ : null,
1197
+ card.manualCount ? h('span', { className: 'tb-card-chip manual' }, `手动×${card.manualCount}`) : null,
1198
+ hasSnapshot ? null : h('span', { className: 'tb-card-chip warn' }, t('detail.noSnapshot')),
1199
+ branchTarget && typeof onBranch === 'function'
1200
+ ? h(
1201
+ 'button',
1202
+ {
1203
+ type: 'button',
1204
+ className: 'tb-card-action',
1205
+ title: t('tree.branchHint'),
1206
+ onClick: (event) => {
1207
+ event.stopPropagation()
1208
+ onBranch(card, branchTarget)
1209
+ },
1210
+ },
1211
+ `⑂ ${t('tree.branch')}`,
1212
+ )
1213
+ : null,
1214
+ branchTarget && typeof onPrune === 'function'
1215
+ ? h(
1216
+ 'button',
1217
+ {
1218
+ type: 'button',
1219
+ className: 'tb-card-action danger',
1220
+ title: t('tree.pruneHint'),
1221
+ onClick: (event) => {
1222
+ event.stopPropagation()
1223
+ onPrune(card, branchTarget)
1224
+ },
1225
+ },
1226
+ `✕ ${t('tree.prune')}`,
1227
+ )
1228
+ : null,
1229
+ ),
1230
+ )
1231
+ }
1232
+
1233
+ /** Render the pannable/zoomable conversation canvas. */
1234
+ function TreeCanvas({
1235
+ layout,
1236
+ t,
1237
+ selectedKey,
1238
+ onSelect,
1239
+ onOpen,
1240
+ onBranch,
1241
+ onNote,
1242
+ onDragStart,
1243
+ onResetLayout,
1244
+ autoPan,
1245
+ panSpeed,
1246
+ onToggleAutoPan,
1247
+ onCyclePanSpeed,
1248
+ expanded,
1249
+ onToggleExpand,
1250
+ onPrune,
1251
+ suppressClickRef,
1252
+ viewportRef,
1253
+ worldRef,
1254
+ onPointerDown,
1255
+ onZoomIn,
1256
+ onZoomOut,
1257
+ onFit,
1258
+ zoom,
1259
+ }) {
1260
+ if (!layout || layout.cards.length === 0) {
1261
+ return h('div', { className: 'tb-empty' }, t('tree.empty'))
1262
+ }
1263
+ return h(
1264
+ 'div',
1265
+ { className: `tb-canvas${expanded ? ' expanded' : ''}`, ref: viewportRef, onPointerDown },
1266
+ h(
1267
+ 'div',
1268
+ { className: 'tb-canvas-toolbar' },
1269
+ h('button', { type: 'button', className: 'tb-canvas-btn', title: t('tree.zoomOut'), onClick: onZoomOut }, '−'),
1270
+ h('button', { type: 'button', className: 'tb-canvas-btn', title: t('tree.resetZoom'), onClick: onFit }, `${Math.round(zoom * 100)}%`),
1271
+ h('button', { type: 'button', className: 'tb-canvas-btn', title: t('tree.zoomIn'), onClick: onZoomIn }, '+'),
1272
+ h('button', { type: 'button', className: 'tb-canvas-btn', title: t('tree.fit'), onClick: onFit }, t('tree.fitShort')),
1273
+ h(
1274
+ 'button',
1275
+ {
1276
+ type: 'button',
1277
+ className: `tb-canvas-btn${autoPan ? '' : ' off'}`,
1278
+ title: t('tree.autoPanHint'),
1279
+ 'aria-pressed': autoPan,
1280
+ onClick: onToggleAutoPan,
1281
+ },
1282
+ autoPan ? t('tree.autoPanOn') : t('tree.autoPanOff'),
1283
+ ),
1284
+ h(
1285
+ 'button',
1286
+ {
1287
+ type: 'button',
1288
+ className: `tb-canvas-btn${panSpeed === 'fast' ? ' on' : ''}`,
1289
+ title: t('tree.panSpeedHint'),
1290
+ onClick: onCyclePanSpeed,
1291
+ },
1292
+ panSpeed === 'slow' ? t('tree.panSpeedSlow') : panSpeed === 'fast' ? t('tree.panSpeedFast') : t('tree.panSpeedNormal'),
1293
+ ),
1294
+ h('button', { type: 'button', className: 'tb-canvas-btn', title: t('tree.resetLayoutHint'), onClick: onResetLayout }, t('tree.resetLayout')),
1295
+ h('button', { type: 'button', className: 'tb-canvas-btn', title: t('tree.expandHint'), onClick: onToggleExpand }, expanded ? '⤡' : '⤢'),
1296
+ ),
1297
+ h(
1298
+ 'div',
1299
+ {
1300
+ className: 'tb-world',
1301
+ ref: worldRef,
1302
+ style: { width: layout.width, height: layout.height },
1303
+ },
1304
+ h(
1305
+ 'svg',
1306
+ { className: 'tb-world-links', width: layout.width, height: layout.height, 'aria-hidden': true },
1307
+ ...layout.links.map((link) =>
1308
+ h('path', {
1309
+ key: link.key,
1310
+ className: `tb-link${link.current ? ' current' : ''}${link.kind === 'fork' ? ' fork' : ''}`,
1311
+ d: link.d,
1312
+ style: { stroke: link.color },
1313
+ }),
1314
+ ),
1315
+ ),
1316
+ ...layout.cards.map((card) =>
1317
+ CanvasCard({ card, t, selectedKey, onSelect, onOpen, onBranch, onPrune, onNote, onDragStart, suppressClickRef }),
1318
+ ),
1319
+ ),
1320
+ )
1321
+ }
1322
+
1323
+
1324
+ /** Checkpoint action rows for one canvas card. */
1325
+ function checkpointRows({ node, t, act, busy, gitOff, session, currentSessionId }) {
1326
+ const baseDisabled = busy !== '' || node.sessionId !== currentSessionId || session?.running === true
1327
+ const reason = busy !== ''
1328
+ ? t('panel.reasonBusy')
1329
+ : node.sessionId !== currentSessionId
1330
+ ? t('detail.notCurrent')
1331
+ : session?.running
1332
+ ? t('detail.running')
1333
+ : ''
1334
+ const rows = []
1335
+ for (const checkpoint of node.checkpoints ?? []) {
1336
+ const label =
1337
+ checkpoint.phase === 'before'
1338
+ ? t('detail.before')
1339
+ : checkpoint.phase === 'after'
1340
+ ? t('detail.after')
1341
+ : checkpoint.phase === 'safety'
1342
+ ? t('detail.safety')
1343
+ : checkpoint.phase === 'inherited'
1344
+ ? t('detail.start')
1345
+ : checkpoint.phase === 'manual'
1346
+ ? t('detail.manual')
1347
+ : checkpoint.phase
1348
+ const canFiles = checkpoint.hasSnapshot === true && !gitOff
1349
+ const canBranch = Number.isInteger(checkpoint.seq)
1350
+ const afterLike = checkpoint.phase !== 'before'
1351
+ const files = checkpoint.files
1352
+ const capped = files?.truncated ? '+' : ''
1353
+ rows.push(
1354
+ h(
1355
+ 'div',
1356
+ { key: checkpoint.id, className: 'tb-cp-row' },
1357
+ h(
1358
+ 'div',
1359
+ { className: 'tb-cp-head' },
1360
+ h('span', { className: 'tb-cp-phase' }, label),
1361
+ checkpoint.createdAt ? h('span', { className: 'tb-muted tb-small' }, clock(checkpoint.createdAt)) : null,
1362
+ checkpoint.hasSnapshot === false ? h('span', { className: 'tb-chip warn' }, t('detail.noSnapshot')) : null,
1363
+ files
1364
+ ? h(
1365
+ 'span',
1366
+ { className: 'tb-delta', title: t('panel.filesCapped') },
1367
+ files.added ? h('span', { className: 'add' }, `+${files.added}${capped}`) : null,
1368
+ files.modified ? h('span', { className: 'mod' }, `~${files.modified}${capped}`) : null,
1369
+ files.deleted ? h('span', { className: 'del' }, `-${files.deleted}${capped}`) : null,
1370
+ )
1371
+ : null,
1372
+ h(
1373
+ 'span',
1374
+ { className: 'tb-actions' },
1375
+ afterLike && canFiles && canBranch
1376
+ ? h(
1377
+ 'button',
1378
+ {
1379
+ type: 'button',
1380
+ className: 'tb-btn danger',
1381
+ disabled: baseDisabled,
1382
+ title: reason || t('panel.rewind'),
1383
+ onClick: () => act('rewind', checkpoint),
1384
+ },
1385
+ t('panel.rewind'),
1386
+ )
1387
+ : null,
1388
+ canFiles
1389
+ ? h(
1390
+ 'button',
1391
+ {
1392
+ type: 'button',
1393
+ className: 'tb-btn',
1394
+ disabled: baseDisabled,
1395
+ title: reason || t('panel.rewindFiles'),
1396
+ onClick: () => act('restore-files', checkpoint),
1397
+ },
1398
+ t('panel.rewindFiles'),
1399
+ )
1400
+ : null,
1401
+ afterLike && canBranch
1402
+ ? h(
1403
+ 'button',
1404
+ {
1405
+ type: 'button',
1406
+ className: 'tb-btn',
1407
+ disabled: baseDisabled,
1408
+ title: reason || t('panel.branchOnly'),
1409
+ onClick: () => act('rewind', checkpoint, 'branch-only'),
1410
+ },
1411
+ t('panel.branchOnly'),
1412
+ )
1413
+ : null,
1414
+ ),
1415
+ ),
1416
+ checkpoint.phase === 'before' ? h('div', { className: 'tb-ws-hint' }, t('detail.beforeHint')) : null,
1417
+ ),
1418
+ )
1419
+ }
1420
+ return rows
1421
+ }
1422
+
1423
+ /** Detail card for the selected canvas card. */
1424
+ function renderCheckpointDetail({ node, layout, t, act, busy, gitOff, currentSessionId, onNote }) {
1425
+ if (!node) return h('div', { className: 'tb-detail' }, h('div', { className: 'tb-ws-hint' }, t('detail.empty')))
1426
+ const session = layout?.byId?.get(node.sessionId)
1427
+ const title =
1428
+ node.kind === 'turn'
1429
+ ? format(t('detail.turn'), { turn: node.turn })
1430
+ : node.kind === 'start'
1431
+ ? t('detail.start')
1432
+ : t('detail.manual')
1433
+ return h(
1434
+ 'div',
1435
+ { className: 'tb-detail' },
1436
+ h(
1437
+ 'div',
1438
+ { className: 'tb-detail-head' },
1439
+ h('span', { className: 'tb-detail-title' }, `${session?.title || node.sessionId.slice(0, 10)} · ${title}`),
1440
+ node.onPath ? h('span', { className: 'tb-chip ok' }, t('panel.current')) : null,
1441
+ ),
1442
+ node.prompt ? h('div', { className: 'tb-detail-prompt' }, `“${node.prompt}”`) : null,
1443
+ node.note
1444
+ ? h(
1445
+ 'div',
1446
+ { className: 'tb-detail-note' },
1447
+ h('div', { className: 'tb-ws-hint' }, t('note.title')),
1448
+ h('div', { className: 'tb-md' }, ...renderMarkdown(node.note, 'detail-note')),
1449
+ )
1450
+ : null,
1451
+ h(
1452
+ 'button',
1453
+ { type: 'button', className: 'tb-btn', disabled: busy !== '', onClick: () => onNote?.(node) },
1454
+ node.note ? `${t('note.title')} ✎` : `+ ${t('panel.note')}`,
1455
+ ),
1456
+ ...checkpointRows({ node, t, act, busy, gitOff, session, currentSessionId }),
1457
+ )
1458
+ }
1459
+
1460
+ /* ---------------------------------------------------------------- */
1461
+ /* panel */
1462
+ /* ---------------------------------------------------------------- */
1463
+
1464
+ function TimebackPanel(props) {
1465
+ const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : ''
1466
+ const t = typeof props?.t === 'function' ? props.t : (key) => key
1467
+ const [state, setState] = React.useState({ loading: true, data: null, error: null })
1468
+ const [tick, setTick] = React.useState(0)
1469
+ const [busy, setBusy] = React.useState('')
1470
+ const [feedback, setFeedback] = React.useState(null)
1471
+ const [view, setView] = React.useState('tree')
1472
+ const [selectedKey, setSelectedKey] = React.useState(null)
1473
+ const [zoom, setZoom] = React.useState(1)
1474
+ const [canvasExpanded, setCanvasExpanded] = React.useState(false)
1475
+ const [autoPan, setAutoPan] = React.useState(() => {
1476
+ try {
1477
+ const raw = window.localStorage.getItem('dsh-timeback:auto-pan')
1478
+ return raw === null ? true : raw === '1'
1479
+ } catch {
1480
+ return true
1481
+ }
1482
+ })
1483
+ const autoPanRef = React.useRef(autoPan)
1484
+ autoPanRef.current = autoPan
1485
+ const [panSpeed, setPanSpeed] = React.useState(() => {
1486
+ try {
1487
+ const raw = window.localStorage.getItem('dsh-timeback:auto-pan-speed')
1488
+ return raw === 'slow' || raw === 'fast' ? raw : 'normal'
1489
+ } catch {
1490
+ return 'normal'
1491
+ }
1492
+ })
1493
+ const panSpeedRef = React.useRef(panSpeed)
1494
+ panSpeedRef.current = panSpeed
1495
+ const [noteEditor, setNoteEditor] = React.useState(null)
1496
+ const viewportRef = React.useRef(null)
1497
+ const worldRef = React.useRef(null)
1498
+ const cameraRef = React.useRef({ x: 0, y: 0, scale: 1 })
1499
+ const fittedRef = React.useRef('')
1500
+ const layoutRef = React.useRef(null)
1501
+ const applyCameraRef = React.useRef(() => {})
1502
+ const [positions, setPositions] = React.useState({})
1503
+ const positionsRef = React.useRef({})
1504
+ const suppressClickRef = React.useRef(false)
1505
+ const draggingRef = React.useRef(false)
1506
+ const busyRef = React.useRef('')
1507
+ const currentCardRef = React.useRef(null)
1508
+ const scrolledFor = React.useRef('')
1509
+
1510
+ React.useEffect(() => {
1511
+ setState({ loading: true, data: null, error: null })
1512
+ setFeedback(null)
1513
+ setBusy('')
1514
+ setSelectedKey(null)
1515
+ busyRef.current = ''
1516
+ cameraRef.current = { x: 0, y: 0, scale: 1 }
1517
+ fittedRef.current = ''
1518
+ }, [sessionId])
1519
+
1520
+ React.useEffect(() => {
1521
+ if (!sessionId) return undefined
1522
+ let disposed = false
1523
+ let controller = null
1524
+ const load = async (silent) => {
1525
+ if (busyRef.current !== '') return
1526
+ if (controller) controller.abort()
1527
+ controller = new AbortController()
1528
+ if (!silent) setState((previous) => ({ ...previous, loading: true }))
1529
+ try {
1530
+ const response = await fetch(`${API}/tree?session=${encodeURIComponent(sessionId)}`, {
1531
+ credentials: 'same-origin',
1532
+ headers: { accept: 'application/json' },
1533
+ signal: controller.signal,
1534
+ })
1535
+ const body = await response.json()
1536
+ if (disposed) return
1537
+ if (!response.ok || body?.ok === false) throw new Error(body?.error || `HTTP ${response.status}`)
1538
+ if (body.currentSessionId !== sessionId) return
1539
+ setState({ loading: false, data: body, error: null })
1540
+ if (scrolledFor.current !== sessionId) {
1541
+ scrolledFor.current = sessionId
1542
+ window.setTimeout(() => {
1543
+ try {
1544
+ currentCardRef.current?.scrollIntoView({ block: 'nearest' })
1545
+ } catch {
1546
+ // Scrolling is a convenience.
1547
+ }
1548
+ }, 30)
1549
+ }
1550
+ } catch (error) {
1551
+ if (disposed || error?.name === 'AbortError') return
1552
+ setState((previous) => ({ ...previous, loading: false, error: error?.message || String(error) }))
1553
+ }
1554
+ }
1555
+ load(false)
1556
+ const timer = setInterval(() => {
1557
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
1558
+ load(true)
1559
+ }, REFRESH_MS)
1560
+ const onVisible = () => {
1561
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') load(true)
1562
+ }
1563
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)
1564
+ return () => {
1565
+ disposed = true
1566
+ clearInterval(timer)
1567
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible)
1568
+ if (controller) controller.abort()
1569
+ }
1570
+ }, [sessionId, tick])
1571
+
1572
+ const disabledReason = (session) => {
1573
+ if (busy !== '') return t('panel.reasonBusy')
1574
+ if (session && !session.isCurrent) return t('panel.reasonNotCurrent')
1575
+ if (session?.running) return t('panel.reasonRunning')
1576
+ return ''
1577
+ }
1578
+
1579
+ const act = async (action, checkpoint, mode, targetSessionId, existingChildSessionId) => {
1580
+ const data = state.data
1581
+ if (!data || data.currentSessionId !== sessionId) return
1582
+ const actionSessionId = targetSessionId || sessionId
1583
+ const who = checkpoint ? checkpointName(checkpoint, t) : ''
1584
+ let message
1585
+ if (action === 'checkpoint') message = t('panel.confirmCheckpoint')
1586
+ else if (action === 'prune') message = format(t('panel.confirmPrune'), { who })
1587
+ else if (mode === 'branch-only') message = format(t('panel.confirmBranchOnly'), { who })
1588
+ else if (action === 'restore-files') message = format(t('panel.confirmFiles'), { who, warning: t('panel.deleteWarning') })
1589
+ else message = format(t('panel.confirmRewind'), { who, warning: t('panel.deleteWarning') })
1590
+ if (!window.confirm(message)) return
1591
+ const busyKey = checkpoint ? checkpoint.id : action
1592
+ setBusy(busyKey)
1593
+ busyRef.current = busyKey
1594
+ setFeedback(null)
1595
+ try {
1596
+ if (action === 'checkpoint') {
1597
+ await request('action', { method: 'POST', body: { action: 'checkpoint', sessionId } })
1598
+ setFeedback({ tone: 'ok', text: t('panel.doneCheckpoint') })
1599
+ } else {
1600
+ let body
1601
+ if (action === 'prune') {
1602
+ body = {
1603
+ action: 'prune',
1604
+ sessionId: actionSessionId,
1605
+ checkpointId: checkpoint.id,
1606
+ mode: mode === 'branch-only' ? 'branch-only' : 'branch-and-files',
1607
+ ...(existingChildSessionId ? { childSessionId: existingChildSessionId } : {}),
1608
+ }
1609
+ } else {
1610
+ const isFileAction = action === 'restore-files' || mode === 'files-only'
1611
+ body = { action: isFileAction ? 'restore-files' : 'rewind', sessionId: actionSessionId, checkpointId: checkpoint.id }
1612
+ if (mode) body.mode = mode
1613
+ }
1614
+ const result = await request('action', { method: 'POST', body })
1615
+ let tone = 'ok'
1616
+ const details = []
1617
+ if (result.restore) {
1618
+ details.push(format(t('panel.doneRestore'), { restored: result.restore.restored ?? 0, deleted: result.restore.deleted ?? 0 }))
1619
+ if (Array.isArray(result.restore.failed) && result.restore.failed.length > 0) {
1620
+ tone = 'warn'
1621
+ details.push(format(t('panel.failedPaths'), { count: result.restore.failed.length }))
1622
+ }
1623
+ if (result.restore.skipped > 0) {
1624
+ tone = 'warn'
1625
+ details.push(format(t('panel.keptFiles'), { count: result.restore.skipped }))
1626
+ }
1627
+ }
1628
+ if (action === 'prune') {
1629
+ const archived = Array.isArray(result.archived) ? result.archived.length : 0
1630
+ if (archived > 0) details.push(format(t('panel.pruneArchived'), { count: archived }))
1631
+ if (Array.isArray(result.failed) && result.failed.length > 0) {
1632
+ tone = 'warn'
1633
+ details.push(format(t('panel.pruneFailed'), { count: result.failed.length }))
1634
+ }
1635
+ details.push(t('panel.donePrune'))
1636
+ } else if (result.childSessionId) {
1637
+ details.push(t('panel.doneBranch'))
1638
+ }
1639
+ if (result.safetyCheckpointId) details.push(t('panel.safetySaved'))
1640
+ if (result.warning) details.push(result.warning)
1641
+ const pruneCandidate =
1642
+ action === 'rewind' && result.childSessionId ? { sessionId: actionSessionId, checkpoint } : null
1643
+ setFeedback({
1644
+ tone,
1645
+ text: details.join(' · '),
1646
+ childSessionId: result.childSessionId,
1647
+ safetyCheckpointId: result.safetyCheckpointId,
1648
+ pruneCandidate,
1649
+ })
1650
+ if (action === 'prune' && result.childSessionId) openChild(result.childSessionId)
1651
+ if (action === 'rewind') {
1652
+ try {
1653
+ window.dispatchEvent(new CustomEvent('dsh-timeback:board-changed'))
1654
+ } catch {
1655
+ // The board tab simply refreshes on its next open.
1656
+ }
1657
+ }
1658
+ }
1659
+ setTick((value) => value + 1)
1660
+ } catch (error) {
1661
+ setFeedback({ tone: 'err', text: t('panel.errorCode').replace('{error}', error?.message || String(error)).replace('{code}', error?.code || 'timeback/failed') })
1662
+ } finally {
1663
+ setBusy('')
1664
+ busyRef.current = ''
1665
+ }
1666
+ }
1667
+
1668
+ const toggleWorkspace = async (enabled, explicitCwd) => {
1669
+ if (busyRef.current !== '') return
1670
+ const data = state.data
1671
+ const targetCwd = explicitCwd ?? data?.workspace?.cwd
1672
+ setBusy('workspace')
1673
+ busyRef.current = 'workspace'
1674
+ setFeedback(null)
1675
+ try {
1676
+ const result = await request('action', {
1677
+ method: 'POST',
1678
+ body: {
1679
+ action: 'set-workspace',
1680
+ ...(explicitCwd ? { cwd: explicitCwd } : { sessionId }),
1681
+ enabled,
1682
+ },
1683
+ })
1684
+ const stillOn = result?.workspace?.enabled === true
1685
+ setFeedback(
1686
+ stillOn
1687
+ ? { tone: 'warn', text: t('panel.workspaceStillOn') }
1688
+ : { tone: 'ok', text: enabled ? t('panel.workspaceEnabled') : t('panel.workspaceDisabled') },
1689
+ )
1690
+ setTick((value) => value + 1)
1691
+ return result
1692
+ } catch (error) {
1693
+ setFeedback({ tone: 'err', text: t('panel.errorCode').replace('{error}', error?.message || String(error)).replace('{code}', error?.code || 'timeback/failed') })
1694
+ } finally {
1695
+ setBusy('')
1696
+ busyRef.current = ''
1697
+ }
1698
+ return null
1699
+ }
1700
+
1701
+ const openChild = (childSessionId) => {
1702
+ try {
1703
+ if (typeof openSessionBridge === 'function') openSessionBridge(childSessionId)
1704
+ } catch {
1705
+ // Navigation is a convenience; the branch already exists.
1706
+ }
1707
+ }
1708
+
1709
+ /** Apply the current camera to the world layer. */
1710
+ const applyCamera = (announceZoom) => {
1711
+ const world = worldRef.current
1712
+ if (world) {
1713
+ const camera = cameraRef.current
1714
+ world.style.transform = `translate(${camera.x}px, ${camera.y}px) scale(${camera.scale})`
1715
+ }
1716
+ if (announceZoom) setZoom(cameraRef.current.scale)
1717
+ }
1718
+ applyCameraRef.current = () => applyCamera(true)
1719
+
1720
+ /** Fit the layout into the viewport. */
1721
+ const fitCanvas = () => {
1722
+ const viewport = viewportRef.current
1723
+ const current = layoutRef.current
1724
+ if (!viewport || !current || current.cards.length === 0) return
1725
+ const width = viewport.clientWidth || 360
1726
+ const height = viewport.clientHeight || 320
1727
+ const spanX = Math.max(1, current.maxX - current.minX)
1728
+ const spanY = Math.max(1, current.maxY - current.minY)
1729
+ const scale = Math.min(1.15, Math.max(0.35, Math.min((width - 28) / spanX, (height - 28) / spanY)))
1730
+ cameraRef.current = {
1731
+ scale,
1732
+ x: (width - spanX * scale) / 2 - current.minX * scale,
1733
+ y: (height - spanY * scale) / 2 - current.minY * scale,
1734
+ }
1735
+ applyCamera(true)
1736
+ }
1737
+
1738
+ /** Zoom around one viewport point. */
1739
+ const zoomAtPoint = (px, py, factor) => {
1740
+ const camera = cameraRef.current
1741
+ const next = Math.min(1.9, Math.max(0.28, camera.scale * factor))
1742
+ const ratio = next / camera.scale
1743
+ cameraRef.current = { scale: next, x: px - (px - camera.x) * ratio, y: py - (py - camera.y) * ratio }
1744
+ applyCamera(true)
1745
+ }
1746
+
1747
+ /** Zoom around the viewport centre (toolbar buttons). */
1748
+ const zoomCanvas = (factor) => {
1749
+ const viewport = viewportRef.current
1750
+ if (!viewport) return
1751
+ zoomAtPoint((viewport.clientWidth || 360) / 2, (viewport.clientHeight || 320) / 2, factor)
1752
+ }
1753
+
1754
+ /** Pointer drag on empty canvas pans the world layer. */
1755
+ const onCanvasPointerDown = (event) => {
1756
+ if (event.button !== 0) return
1757
+ const target = event.target
1758
+ if (target?.closest?.('.tb-card') || target?.closest?.('.tb-canvas-toolbar')) return
1759
+ const viewport = viewportRef.current
1760
+ if (!viewport) return
1761
+ event.preventDefault()
1762
+ const startX = event.clientX
1763
+ const startY = event.clientY
1764
+ const startCamera = { ...cameraRef.current }
1765
+ let frame = 0
1766
+ let pending = null
1767
+ const move = (next) => {
1768
+ pending = { x: startCamera.x + next.clientX - startX, y: startCamera.y + next.clientY - startY }
1769
+ if (frame !== 0) return
1770
+ frame = window.requestAnimationFrame(() => {
1771
+ frame = 0
1772
+ if (pending === null) return
1773
+ cameraRef.current = { ...cameraRef.current, ...pending }
1774
+ applyCamera(false)
1775
+ })
1776
+ }
1777
+ const finish = () => {
1778
+ window.removeEventListener('pointermove', move)
1779
+ window.removeEventListener('pointerup', finish)
1780
+ window.removeEventListener('pointercancel', finish)
1781
+ if (frame !== 0) {
1782
+ window.cancelAnimationFrame(frame)
1783
+ frame = 0
1784
+ }
1785
+ if (pending !== null) {
1786
+ cameraRef.current = { ...cameraRef.current, ...pending }
1787
+ applyCamera(false)
1788
+ }
1789
+ }
1790
+ window.addEventListener('pointermove', move)
1791
+ window.addEventListener('pointerup', finish)
1792
+ window.addEventListener('pointercancel', finish)
1793
+ }
1794
+
1795
+ const undoRestore = (safetyCheckpointId) => {
1796
+ const data = state.data
1797
+ if (!data) return
1798
+ const checkpoint = data.sessions.flatMap((session) => session.checkpoints).find((entry) => entry.id === safetyCheckpointId)
1799
+ if (!checkpoint) {
1800
+ setFeedback({ tone: 'warn', text: t('panel.undoUnavailable') })
1801
+ return
1802
+ }
1803
+ act('restore-files', checkpoint)
1804
+ }
1805
+
1806
+ const data = state.data
1807
+ const sessions = data?.sessions ?? []
1808
+ const checkpointTotal = sessions.reduce((total, session) => total + (session.checkpointCount ?? session.checkpoints?.length ?? 0), 0)
1809
+ const gitOff = data?.git === false
1810
+ const layout = data ? layoutTree(sessions, data.currentSessionId, positions) : null
1811
+ layoutRef.current = layout
1812
+ const clientVersion = BUILD.split('+')[0]
1813
+ const serverVersion = typeof data?.serverVersion === 'string' ? data.serverVersion : null
1814
+ const staleBundle = Boolean(serverVersion && clientVersion !== serverVersion)
1815
+ const fallbackNode =
1816
+ layout?.cards.filter((card) => card.sessionId === data?.currentSessionId).slice(-1)[0] ?? layout?.cards.slice(-1)[0] ?? null
1817
+ const selectedNode = (selectedKey ? layout?.cards.find((card) => card.key === selectedKey) : null) ?? fallbackNode
1818
+ const effectiveSelectedKey = selectedNode?.key ?? null
1819
+
1820
+ // Fit the canvas the first time a layout (or Session) appears.
1821
+ React.useEffect(() => {
1822
+ if (view !== 'tree' || !data || !layout || layout.cards.length === 0) return
1823
+ if (draggingRef.current) return
1824
+ const key = `${data.currentSessionId}:${layout.width}x${layout.height}`
1825
+ if (fittedRef.current === key) return
1826
+ fittedRef.current = key
1827
+ window.requestAnimationFrame(() => fitCanvas())
1828
+ // fitCanvas only reads refs; it is intentionally excluded from deps.
1829
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1830
+ }, [view, data?.currentSessionId, layout?.width, layout?.height])
1831
+
1832
+ const positionsKey = data?.rootSessionId ? `dsh-timeback:card-positions:${data.rootSessionId}` : null
1833
+
1834
+ // Restore dragged card positions for this branch family.
1835
+ React.useEffect(() => {
1836
+ if (!positionsKey) return
1837
+ let saved = {}
1838
+ try {
1839
+ const raw = window.localStorage.getItem(positionsKey)
1840
+ if (raw) saved = JSON.parse(raw)
1841
+ } catch {
1842
+ saved = {}
1843
+ }
1844
+ if (saved === null || typeof saved !== 'object' || Array.isArray(saved)) saved = {}
1845
+ positionsRef.current = saved
1846
+ setPositions(saved)
1847
+ }, [positionsKey])
1848
+
1849
+ // Wheel zoom must be non-passive, so it is bound directly to the viewport.
1850
+ React.useEffect(() => {
1851
+ const viewport = viewportRef.current
1852
+ if (!viewport || view !== 'tree' || !data) return undefined
1853
+ const onWheel = (event) => {
1854
+ event.preventDefault()
1855
+ const bounds = viewport.getBoundingClientRect()
1856
+ zoomAtPoint(event.clientX - bounds.left, event.clientY - bounds.top, Math.exp(-event.deltaY * 0.0014))
1857
+ }
1858
+ viewport.addEventListener('wheel', onWheel, { passive: false })
1859
+ return () => viewport.removeEventListener('wheel', onWheel)
1860
+ }, [view, data?.currentSessionId, layout?.width, layout?.height])
1861
+
1862
+ if (!sessionId) {
1863
+ return h('div', { className: 'tb-panel' }, h('div', { className: 'tb-empty' }, t('panel.noSession')))
1864
+ }
1865
+
1866
+ /** Persist dragged card positions for this branch family. */
1867
+ const storePositions = (next, persist) => {
1868
+ positionsRef.current = next
1869
+ setPositions(next)
1870
+ if (persist !== true) return
1871
+ try {
1872
+ if (positionsKey) window.localStorage.setItem(positionsKey, JSON.stringify(next))
1873
+ } catch {
1874
+ // Storage can be disabled; dragging still works in memory.
1875
+ }
1876
+ }
1877
+
1878
+ /** Drag one card inside the world layer (screen delta ÷ zoom). */
1879
+ const onCardDragStart = (event, card) => {
1880
+ if (event.button !== 0) return
1881
+ if (event.target?.closest?.('button')) return
1882
+ event.preventDefault()
1883
+ event.stopPropagation()
1884
+ const viewport = viewportRef.current
1885
+ const rect = viewport?.getBoundingClientRect?.() ?? { left: 0, top: 0, right: 0, bottom: 0 }
1886
+ const startCard = { x: card.x, y: card.y }
1887
+ const startCamera = { ...cameraRef.current }
1888
+ const startLayout = layoutRef.current
1889
+ // Pointer position inside the card, in world units, so the card stays
1890
+ // anchored under the cursor even when the world offset changes.
1891
+ const grabX = (event.clientX - rect.left - startCamera.x) / startCamera.scale - startCard.x
1892
+ const grabY = (event.clientY - rect.top - startCamera.y) / startCamera.scale - startCard.y
1893
+ const pointer = { x: event.clientX, y: event.clientY }
1894
+ let moved = false
1895
+ let frame = 0
1896
+ let panFrame = 0
1897
+ let latest = null
1898
+ draggingRef.current = true
1899
+ /** World-space card position under the last pointer sample. */
1900
+ const rawPosition = () => {
1901
+ const camera = cameraRef.current
1902
+ const rawX = (pointer.x - rect.left - camera.x) / camera.scale - grabX
1903
+ const rawY = (pointer.y - rect.top - camera.y) / camera.scale - grabY
1904
+ if (!Number.isFinite(rawX) || !Number.isFinite(rawY)) return null
1905
+ return { x: Math.round(rawX), y: Math.round(rawY) }
1906
+ }
1907
+ const apply = () => {
1908
+ frame = 0
1909
+ if (latest === null) return
1910
+ storePositions({ ...positionsRef.current, [card.key]: latest }, false)
1911
+ }
1912
+ const scheduleApply = () => {
1913
+ latest = rawPosition()
1914
+ if (latest !== null && frame === 0) frame = window.requestAnimationFrame(apply)
1915
+ }
1916
+ // Damped edge auto-pan: about 0-3 CSS px per animation frame, scaled by
1917
+ // how deep the pointer is inside the edge band (56 px). This replaces the
1918
+ // old per-pointer-event jump that felt far too fast.
1919
+ const EDGE_BAND = 44
1920
+ const PAN_SPEEDS = { slow: 45, normal: 90, fast: 170 } // CSS px per second at the deepest edge
1921
+ let lastPanAt = 0
1922
+ const panTick = (time) => {
1923
+ panFrame = 0
1924
+ if (!draggingRef.current || !autoPanRef.current) return
1925
+ const now = typeof time === 'number' ? time : window.performance?.now?.() ?? Date.now()
1926
+ const delta = lastPanAt === 0 ? 16 : Math.min(50, Math.max(0, now - lastPanAt))
1927
+ lastPanAt = now
1928
+ const bounds = (viewport ? visibleRect(viewport) : null) ?? viewport?.getBoundingClientRect?.() ?? rect
1929
+ const { x: depthX, y: depthY } = edgePanVector(pointer, bounds, EDGE_BAND)
1930
+ if (depthX !== 0 || depthY !== 0) {
1931
+ const maxSpeed = PAN_SPEEDS[panSpeedRef.current] ?? PAN_SPEEDS.normal
1932
+ const step = (maxSpeed * delta) / 1000
1933
+ const camera = cameraRef.current
1934
+ cameraRef.current = {
1935
+ ...camera,
1936
+ x: camera.x + depthX * Math.abs(depthX) * step,
1937
+ y: camera.y + depthY * Math.abs(depthY) * step,
1938
+ }
1939
+ applyCamera(false)
1940
+ scheduleApply()
1941
+ }
1942
+ panFrame = window.requestAnimationFrame(panTick)
1943
+ }
1944
+ panFrame = window.requestAnimationFrame(panTick)
1945
+ const move = (next) => {
1946
+ pointer.x = next.clientX
1947
+ pointer.y = next.clientY
1948
+ if (!moved && Math.hypot(next.clientX - event.clientX, next.clientY - event.clientY) < 4) return
1949
+ moved = true
1950
+ suppressClickRef.current = true
1951
+ scheduleApply()
1952
+ }
1953
+ const finish = () => {
1954
+ window.removeEventListener('pointermove', move)
1955
+ window.removeEventListener('pointerup', finish)
1956
+ window.removeEventListener('pointercancel', finish)
1957
+ if (panFrame !== 0) {
1958
+ window.cancelAnimationFrame(panFrame)
1959
+ panFrame = 0
1960
+ }
1961
+ if (frame !== 0) {
1962
+ window.cancelAnimationFrame(frame)
1963
+ frame = 0
1964
+ if (latest !== null) apply()
1965
+ }
1966
+ draggingRef.current = false
1967
+ if (moved) {
1968
+ storePositions(positionsRef.current, true)
1969
+ window.setTimeout(() => { suppressClickRef.current = false }, 80)
1970
+ }
1971
+ }
1972
+ window.addEventListener('pointermove', move)
1973
+ window.addEventListener('pointerup', finish)
1974
+ window.addEventListener('pointercancel', finish)
1975
+ }
1976
+
1977
+ /** Double-clicking a card or its lane jumps to that conversation. */
1978
+ const openSessionByCard = (targetSessionId) => {
1979
+ if (typeof openSessionBridge === 'function') openSessionBridge(targetSessionId)
1980
+ }
1981
+
1982
+ /** Branch from one card without touching files. */
1983
+ const branchFromCard = (card, checkpoint) => {
1984
+ act('rewind', checkpoint, 'branch-only', card.sessionId)
1985
+ }
1986
+
1987
+ /** Delete the conversation after one card (truncated branch + archive). */
1988
+ const pruneFromCard = (card, checkpoint) => {
1989
+ act('prune', checkpoint, null, card.sessionId)
1990
+ }
1991
+
1992
+ /** Toggle edge auto-pan and remember the preference. */
1993
+ const toggleAutoPan = () => {
1994
+ setAutoPan((value) => {
1995
+ const next = !value
1996
+ try {
1997
+ window.localStorage.setItem('dsh-timeback:auto-pan', next ? '1' : '0')
1998
+ } catch {
1999
+ // Storage can be disabled.
2000
+ }
2001
+ return next
2002
+ })
2003
+ }
2004
+
2005
+ /** Cycle the edge auto-pan speed and persist it. */
2006
+ const cyclePanSpeed = () => {
2007
+ setPanSpeed((value) => {
2008
+ const next = value === 'slow' ? 'normal' : value === 'normal' ? 'fast' : 'slow'
2009
+ try {
2010
+ window.localStorage.setItem('dsh-timeback:auto-pan-speed', next)
2011
+ } catch {
2012
+ // Storage can be disabled.
2013
+ }
2014
+ return next
2015
+ })
2016
+ }
2017
+
2018
+ /** Open the card-note editor for one canvas card. */
2019
+ const openCardNote = (card) => {
2020
+ if (!card) return
2021
+ const checkpoints = card.checkpoints ?? []
2022
+ const target =
2023
+ [...checkpoints].reverse().find((checkpoint) => checkpoint.note) ?? checkpoints[checkpoints.length - 1] ?? null
2024
+ setNoteEditor({
2025
+ card,
2026
+ checkpointId: card.kind === 'start' ? '' : target?.id ?? '',
2027
+ text: card.note ?? '',
2028
+ busy: false,
2029
+ error: null,
2030
+ })
2031
+ }
2032
+
2033
+ /** Save (or clear) the note on the card being edited. */
2034
+ const saveCardNote = async (clear) => {
2035
+ const editor = noteEditor
2036
+ if (!editor || editor.busy) return
2037
+ setNoteEditor({ ...editor, busy: true, error: null })
2038
+ try {
2039
+ await request('action', {
2040
+ method: 'POST',
2041
+ body: {
2042
+ action: 'card-note',
2043
+ sessionId: editor.card.sessionId,
2044
+ ...(editor.checkpointId ? { checkpointId: editor.checkpointId } : {}),
2045
+ note: clear === true ? '' : editor.text,
2046
+ },
2047
+ })
2048
+ setFeedback({ tone: 'ok', text: clear === true ? t('note.removed') : t('note.saved') })
2049
+ setNoteEditor(null)
2050
+ setTick((value) => value + 1)
2051
+ } catch (error) {
2052
+ setNoteEditor({ ...editor, busy: false, error: error?.message || String(error) })
2053
+ }
2054
+ }
2055
+
2056
+ /** Clear dragged positions and return to the automatic layout. */
2057
+ const resetCardPositions = () => {
2058
+ try {
2059
+ if (positionsKey) window.localStorage.removeItem(positionsKey)
2060
+ } catch {
2061
+ // Storage can be disabled.
2062
+ }
2063
+ positionsRef.current = {}
2064
+ setPositions({})
2065
+ }
2066
+ return h(
2067
+ 'div',
2068
+ { className: 'tb-panel', 'aria-busy': busy !== '' },
2069
+ h(
2070
+ 'div',
2071
+ { className: 'tb-head' },
2072
+ h(TimebackIcon, { size: 16 }),
2073
+ h('span', { className: 'tb-title' }, t('panel.title')),
2074
+ busy !== '' ? h('span', { className: 'tb-chip warn' }, t('panel.acting')) : null,
2075
+ gitOff
2076
+ ? h('span', { className: 'tb-chip warn' }, t('panel.noGit'))
2077
+ : h(
2078
+ 'span',
2079
+ { className: `tb-chip ${data?.workspace?.enabled ? 'ok' : 'warn'}` },
2080
+ data?.workspace?.enabled ? t('panel.recordOn') : t('panel.recordOff'),
2081
+ ),
2082
+ h(
2083
+ 'span',
2084
+ { className: 'tb-muted tb-small', title: `timeback client ${BUILD}` },
2085
+ format(t('panel.branchCount'), { sessions: sessions.length, checkpoints: checkpointTotal }),
2086
+ ),
2087
+ h('span', { className: 'tb-muted tb-small', title: 'timeback client build' }, BUILD),
2088
+ h('span', { style: { flex: 1 } }),
2089
+ h(
2090
+ 'button',
2091
+ { type: 'button', className: 'tb-btn', title: t('board.subtitle'), onClick: () => openBoardBridge?.() },
2092
+ `📋 ${t('panel.notes')}`,
2093
+ ),
2094
+ h('button', { type: 'button', className: 'tb-btn', disabled: busy !== '', onClick: () => setTick((value) => value + 1) }, t('panel.refresh')),
2095
+ h(
2096
+ 'button',
2097
+ { type: 'button', className: 'tb-btn primary', disabled: busy !== '' || gitOff || !data, onClick: () => act('checkpoint', null) },
2098
+ t('panel.checkpoint'),
2099
+ ),
2100
+ ),
2101
+ h(
2102
+ 'div',
2103
+ { className: 'tb-body' },
2104
+ feedback
2105
+ ? h(
2106
+ 'div',
2107
+ { className: `tb-feedback ${feedback.tone ?? 'ok'}`, role: feedback.tone === 'err' ? 'alert' : 'status' },
2108
+ h('div', null, feedback.text),
2109
+ feedback.childSessionId || feedback.safetyCheckpointId
2110
+ ? h(
2111
+ 'div',
2112
+ { className: 'tb-actions' },
2113
+ feedback.childSessionId
2114
+ ? h('button', { type: 'button', className: 'tb-btn primary', onClick: () => openChild(feedback.childSessionId) }, t('panel.openBranch'))
2115
+ : null,
2116
+ feedback.safetyCheckpointId
2117
+ ? h('button', { type: 'button', className: 'tb-btn', onClick: () => undoRestore(feedback.safetyCheckpointId) }, t('panel.undoRestore'))
2118
+ : null,
2119
+ feedback.pruneCandidate
2120
+ ? h(
2121
+ 'button',
2122
+ {
2123
+ type: 'button',
2124
+ className: 'tb-btn danger',
2125
+ onClick: () =>
2126
+ act(
2127
+ 'prune',
2128
+ feedback.pruneCandidate.checkpoint,
2129
+ null,
2130
+ feedback.pruneCandidate.sessionId,
2131
+ feedback.childSessionId,
2132
+ ),
2133
+ },
2134
+ t('panel.pruneOld'),
2135
+ )
2136
+ : null,
2137
+ )
2138
+ : null,
2139
+ )
2140
+ : null,
2141
+ staleBundle
2142
+ ? h(
2143
+ 'div',
2144
+ { className: 'tb-feedback warn', role: 'alert' },
2145
+ h('div', null, format(t('panel.staleBuild'), { client: clientVersion, server: serverVersion })),
2146
+ h(
2147
+ 'div',
2148
+ { className: 'tb-actions' },
2149
+ h(
2150
+ 'button',
2151
+ {
2152
+ type: 'button',
2153
+ className: 'tb-btn danger',
2154
+ onClick: () => {
2155
+ try {
2156
+ window.location.reload()
2157
+ } catch {
2158
+ // Navigation is best-effort.
2159
+ }
2160
+ },
2161
+ },
2162
+ t('panel.reloadPage'),
2163
+ ),
2164
+ ),
2165
+ )
2166
+ : null,
2167
+ renderWorkspaceSection({ workspace: data?.workspace, gitOff, busy, t, toggleWorkspace }),
2168
+ gitOff ? h('p', { className: 'tb-note' }, t('panel.noGit')) : h('p', { className: 'tb-note' }, t('panel.warning')),
2169
+ state.error ? h('div', { className: 'tb-feedback err', role: 'alert' }, `${t('panel.error')}: ${state.error}`) : null,
2170
+ state.loading && !data ? h('div', { className: 'tb-empty' }, t('panel.loading')) : null,
2171
+ data
2172
+ ? h(
2173
+ 'div',
2174
+ { className: 'tb-viewtabs' },
2175
+ h(
2176
+ 'button',
2177
+ { type: 'button', className: `tb-viewtab${view === 'tree' ? ' on' : ''}`, onClick: () => setView('tree') },
2178
+ t('view.tree'),
2179
+ ),
2180
+ h(
2181
+ 'button',
2182
+ { type: 'button', className: `tb-viewtab${view === 'list' ? ' on' : ''}`, onClick: () => setView('list') },
2183
+ t('view.list'),
2184
+ ),
2185
+ h('span', { style: { flex: 1 } }),
2186
+ view === 'tree'
2187
+ ? h(
2188
+ 'span',
2189
+ { className: 'tb-legend' },
2190
+ h('span', null, h('i', null), t('tree.legend.turn')),
2191
+ h('span', null, h('i', { className: 'manual' }), t('tree.legend.manual')),
2192
+ h('span', null, h('i', { className: 'current' }), t('tree.legend.current')),
2193
+ )
2194
+ : null,
2195
+ )
2196
+ : null,
2197
+ data && sessions.length === 0 ? h('div', { className: 'tb-empty' }, t('panel.empty')) : null,
2198
+ data && sessions.length > 0 && view === 'tree'
2199
+ ? layout && layout.cards.length > 0
2200
+ ? h(
2201
+ 'div',
2202
+ { className: 'tb-tree-section' },
2203
+ TreeCanvas({
2204
+ layout,
2205
+ t,
2206
+ selectedKey: effectiveSelectedKey,
2207
+ onSelect: setSelectedKey,
2208
+ onOpen: openSessionByCard,
2209
+ onBranch: branchFromCard,
2210
+ onPrune: pruneFromCard,
2211
+ onNote: openCardNote,
2212
+ expanded: canvasExpanded,
2213
+ onToggleExpand: () => setCanvasExpanded((value) => !value),
2214
+ onDragStart: onCardDragStart,
2215
+ onResetLayout: resetCardPositions,
2216
+ autoPan,
2217
+ panSpeed,
2218
+ onToggleAutoPan: toggleAutoPan,
2219
+ onCyclePanSpeed: cyclePanSpeed,
2220
+ suppressClickRef,
2221
+ viewportRef,
2222
+ worldRef,
2223
+ onPointerDown: onCanvasPointerDown,
2224
+ onZoomIn: () => zoomCanvas(1.2),
2225
+ onZoomOut: () => zoomCanvas(1 / 1.2),
2226
+ onFit: fitCanvas,
2227
+ zoom,
2228
+ }),
2229
+ h('div', { className: 'tb-canvas-hint' }, t('tree.panHint')),
2230
+ h('div', { className: 'tb-canvas-hint' }, t('tree.dragHint')),
2231
+ layout.truncated ? h('div', { className: 'tb-ws-hint' }, format(t('tree.truncated'), { count: MAX_TREE_TURNS })) : null,
2232
+ renderCheckpointDetail({ node: selectedNode, layout, t, act, busy, gitOff, currentSessionId: data.currentSessionId, onNote: openCardNote }),
2233
+ )
2234
+ : h(
2235
+ 'div',
2236
+ { className: 'tb-empty' },
2237
+ data.workspace?.enabled === false ? t('panel.emptyNotRecording') : t('tree.empty'),
2238
+ )
2239
+ : null,
2240
+ data && view === 'list'
2241
+ ? sessions.map((session, index) =>
2242
+ renderSession({
2243
+ session,
2244
+ t,
2245
+ act,
2246
+ busy,
2247
+ disabledReason: disabledReason(session),
2248
+ gitOff,
2249
+ currentRef: session.isCurrent
2250
+ ? (node) => {
2251
+ currentCardRef.current = node
2252
+ }
2253
+ : undefined,
2254
+ style: { marginLeft: Math.min(session.depth ?? 0, 6) * 10, order: index },
2255
+ }),
2256
+ )
2257
+ : null,
2258
+ ),
2259
+ noteEditor
2260
+ ? h(
2261
+ 'div',
2262
+ { className: 'tb-overlay', onClick: () => { if (!noteEditor.busy) setNoteEditor(null) } },
2263
+ h(
2264
+ 'div',
2265
+ { className: 'tb-note-dialog', role: 'dialog', 'aria-modal': true, onClick: (event) => event.stopPropagation() },
2266
+ h(
2267
+ 'div',
2268
+ { className: 'tb-detail-head' },
2269
+ h('span', { className: 'tb-detail-title' }, `${t('note.title')} · ${noteEditor.card.label}`),
2270
+ h('span', { style: { flex: 1 } }),
2271
+ h('button', { type: 'button', className: 'tb-btn', disabled: noteEditor.busy, onClick: () => setNoteEditor(null) }, t('note.cancel')),
2272
+ ),
2273
+ h('div', { className: 'tb-ws-hint' }, t('note.hint')),
2274
+ h('textarea', {
2275
+ value: noteEditor.text,
2276
+ placeholder: t('note.placeholder'),
2277
+ disabled: noteEditor.busy,
2278
+ onChange: (event) => setNoteEditor({ ...noteEditor, text: event.target.value }),
2279
+ }),
2280
+ noteEditor.error ? h('div', { className: 'tb-feedback err' }, noteEditor.error) : null,
2281
+ h(
2282
+ 'div',
2283
+ { className: 'tb-note-actions' },
2284
+ noteEditor.text.trim() !== '' || noteEditor.card.note
2285
+ ? h('button', { type: 'button', className: 'tb-btn danger', disabled: noteEditor.busy, onClick: () => saveCardNote(true) }, t('note.delete'))
2286
+ : null,
2287
+ h('button', { type: 'button', className: 'tb-btn primary', disabled: noteEditor.busy, onClick: () => saveCardNote(false) }, t('note.save')),
2288
+ ),
2289
+ ),
2290
+ )
2291
+ : null,
2292
+ )
2293
+ }
2294
+
2295
+ /** Draw the per-workspace recording switch and the enabled-workspace list. */
2296
+ function renderWorkspaceSection({ workspace, gitOff, busy, t, toggleWorkspace }) {
2297
+ if (!workspace) return null
2298
+ const cwd = workspace.cwd
2299
+ const mode = workspace.mode
2300
+ const canToggle = mode === 'workspace' && !gitOff && Boolean(cwd) && workspace.exists !== false && busy === ''
2301
+ const checked = mode === 'all' || workspace.enabled === true
2302
+ const reason = gitOff
2303
+ ? t('panel.recordDisabledNoGit')
2304
+ : !cwd || workspace.exists === false
2305
+ ? t('panel.recordMissing')
2306
+ : mode === 'all'
2307
+ ? t('panel.recordAll')
2308
+ : mode === 'off'
2309
+ ? t('panel.recordFixedOff')
2310
+ : t('panel.recordThisHint')
2311
+ return h(
2312
+ 'div',
2313
+ { className: 'tb-ws' },
2314
+ h(
2315
+ 'label',
2316
+ { className: `tb-ws-row${canToggle ? '' : ' disabled'}`, title: reason },
2317
+ h('input', {
2318
+ type: 'checkbox',
2319
+ checked,
2320
+ disabled: !canToggle,
2321
+ 'aria-label': t('panel.recordThis'),
2322
+ onChange: (event) => {
2323
+ if (canToggle) toggleWorkspace(event.target.checked)
2324
+ },
2325
+ }),
2326
+ h(
2327
+ 'span',
2328
+ { className: 'tb-ws-text' },
2329
+ h('span', { className: 'tb-ws-title' }, t('panel.recordThis')),
2330
+ cwd ? h('span', { className: 'tb-ws-path', title: cwd }, cwd) : null,
2331
+ h('span', { className: 'tb-ws-hint' }, reason),
2332
+ ),
2333
+ ),
2334
+ mode === 'workspace' && workspace.enabledWorkspaces?.length > 0
2335
+ ? h(
2336
+ 'div',
2337
+ { className: 'tb-ws-list' },
2338
+ h('span', { className: 'tb-ws-hint' }, t('panel.enabledWorkspaces')),
2339
+ ...workspace.enabledWorkspaces.map((entry) =>
2340
+ h(
2341
+ 'div',
2342
+ { key: entry.path, className: 'tb-ws-item' },
2343
+ h('span', { className: 'tb-ws-path', title: entry.path }, entry.path),
2344
+ h(
2345
+ 'button',
2346
+ {
2347
+ type: 'button',
2348
+ className: 'tb-btn',
2349
+ disabled: busy !== '',
2350
+ onClick: () => toggleWorkspace(false, entry.path),
2351
+ },
2352
+ t('panel.disableThis'),
2353
+ ),
2354
+ ),
2355
+ ),
2356
+ )
2357
+ : null,
2358
+ mode === 'workspace' && workspace.excludedWorkspaces?.length > 0
2359
+ ? h(
2360
+ 'div',
2361
+ { className: 'tb-ws-list' },
2362
+ h('span', { className: 'tb-ws-hint' }, t('panel.excludedWorkspaces')),
2363
+ ...workspace.excludedWorkspaces.map((entry) =>
2364
+ h(
2365
+ 'div',
2366
+ { key: `x:${entry.path}`, className: 'tb-ws-item' },
2367
+ h('span', { className: 'tb-ws-path', title: entry.path }, entry.path),
2368
+ h(
2369
+ 'button',
2370
+ {
2371
+ type: 'button',
2372
+ className: 'tb-btn',
2373
+ disabled: busy !== '',
2374
+ onClick: () => toggleWorkspace(true, entry.path),
2375
+ },
2376
+ t('panel.restoreThis'),
2377
+ ),
2378
+ ),
2379
+ ),
2380
+ )
2381
+ : null,
2382
+ )
2383
+ }
2384
+
2385
+ /** Draw one branch node and its turn rows. */
2386
+ function renderSession({ session, t, act, busy, disabledReason, gitOff, currentRef, style }) {
2387
+ const grouped = turnRows(session.checkpoints ?? [], t)
2388
+ const rows = grouped.rows
2389
+ const reason = disabledReason
2390
+ return h(
2391
+ 'div',
2392
+ { key: session.sessionId, ref: currentRef, className: `tb-session${session.isCurrent ? ' current' : ''}`, style },
2393
+ h(
2394
+ 'div',
2395
+ { className: 'tb-session-head' },
2396
+ h(TimebackIcon, { size: 14 }),
2397
+ h('span', { className: 'tb-session-title', title: session.sessionId }, session.title || `${session.sessionId.slice(0, 10)}…`),
2398
+ session.isCurrent ? h('span', { className: 'tb-chip ok' }, t('panel.current')) : null,
2399
+ session.running ? h('span', { className: 'tb-chip run' }, t('panel.running')) : null,
2400
+ session.parentSessionId
2401
+ ? h('span', { className: 'tb-chip', title: session.parentSessionId }, `${t('panel.branch')} · ${t('panel.seq')} ${session.forkAtSeq ?? '?'}`)
2402
+ : null,
2403
+ session.cwd
2404
+ ? h(
2405
+ 'span',
2406
+ { className: 'tb-muted tb-small', title: session.cwd, style: { maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
2407
+ session.cwd,
2408
+ )
2409
+ : null,
2410
+ ),
2411
+ session.status?.error
2412
+ ? h('div', { className: 'tb-feedback warn', style: { margin: '6px 10px 0' } }, `${t('panel.captureError')}: ${session.status.error}`)
2413
+ : null,
2414
+ rows.length === 0
2415
+ ? h(
2416
+ 'div',
2417
+ { className: 'tb-empty tb-small' },
2418
+ session.status?.error
2419
+ ? `${t('panel.emptyWithError')} ${session.status.error}`
2420
+ : session.recording === false
2421
+ ? t('panel.emptyNotRecording')
2422
+ : t('panel.empty'),
2423
+ )
2424
+ : rows.map(({ key, checkpoint }) => {
2425
+ const canBranch = Number.isInteger(checkpoint.seq)
2426
+ const canFiles = checkpoint.hasSnapshot === true && !gitOff
2427
+ const files = checkpoint.files
2428
+ const capped = files?.truncated ? `+` : ''
2429
+ const buttonDisabled = busy !== '' || reason !== ''
2430
+ const reasonTitle = reason || ''
2431
+ return h(
2432
+ 'div',
2433
+ { key, className: 'tb-turn' },
2434
+ h(
2435
+ 'div',
2436
+ { className: 'tb-turn-head' },
2437
+ h('span', { className: 'tb-turn-label' }, checkpointName(checkpoint, t)),
2438
+ checkpoint.prompt ? h('span', { className: 'tb-prompt', title: checkpoint.prompt }, `“${checkpoint.prompt}”`) : null,
2439
+ checkpoint.createdAt ? h('span', { className: 'tb-muted tb-small' }, clock(checkpoint.createdAt)) : null,
2440
+ checkpoint.hasSnapshot === false ? h('span', { className: 'tb-chip warn' }, t('panel.noSnapshot')) : null,
2441
+ h(
2442
+ 'span',
2443
+ { className: 'tb-actions' },
2444
+ files
2445
+ ? h(
2446
+ 'span',
2447
+ { className: 'tb-delta', title: t('panel.filesCapped') },
2448
+ files.added ? h('span', { className: 'add' }, `+${files.added}${capped}`) : null,
2449
+ files.modified ? h('span', { className: 'mod' }, `~${files.modified}${capped}`) : null,
2450
+ files.deleted ? h('span', { className: 'del' }, `-${files.deleted}${capped}`) : null,
2451
+ )
2452
+ : null,
2453
+ canBranch && canFiles
2454
+ ? h(
2455
+ 'button',
2456
+ {
2457
+ type: 'button',
2458
+ className: 'tb-btn danger',
2459
+ disabled: buttonDisabled,
2460
+ title: reasonTitle || t('panel.rewind'),
2461
+ 'aria-label': `${checkpointName(checkpoint, t)} ${t('panel.rewind')}`,
2462
+ onClick: () => act('rewind', checkpoint),
2463
+ },
2464
+ t('panel.rewind'),
2465
+ )
2466
+ : null,
2467
+ canFiles
2468
+ ? h(
2469
+ 'button',
2470
+ {
2471
+ type: 'button',
2472
+ className: 'tb-btn',
2473
+ disabled: buttonDisabled,
2474
+ title: reasonTitle || t('panel.rewindFiles'),
2475
+ 'aria-label': `${checkpointName(checkpoint, t)} ${t('panel.rewindFiles')}`,
2476
+ onClick: () => act('restore-files', checkpoint),
2477
+ },
2478
+ t('panel.rewindFiles'),
2479
+ )
2480
+ : null,
2481
+ canBranch
2482
+ ? h(
2483
+ 'button',
2484
+ {
2485
+ type: 'button',
2486
+ className: 'tb-btn',
2487
+ disabled: buttonDisabled,
2488
+ title: reasonTitle || t('panel.branchOnly'),
2489
+ 'aria-label': `${checkpointName(checkpoint, t)} ${t('panel.branchOnly')}`,
2490
+ onClick: () => act('rewind', checkpoint, 'branch-only'),
2491
+ },
2492
+ t('panel.branchOnly'),
2493
+ )
2494
+ : null,
2495
+ !canBranch
2496
+ ? h('span', { className: 'tb-muted tb-small', title: t('panel.noBranchHint') }, 'ⓘ')
2497
+ : null,
2498
+ ),
2499
+ ),
2500
+ )
2501
+ }),
2502
+ grouped.truncated
2503
+ ? h('div', { className: 'tb-muted tb-small', style: { padding: '4px 10px 8px' } }, format(t('panel.rowTruncated'), { count: MAX_ROWS }))
2504
+ : null,
2505
+ )
2506
+ }
2507
+
2508
+ /**
2509
+ * The slot entry must never render as a silent black panel: a render crash
2510
+ * is caught here and shown with its message instead.
2511
+ */
2512
+ class PanelBoundary extends React.Component {
2513
+ constructor(props) {
2514
+ super(props)
2515
+ this.state = { error: null }
2516
+ }
2517
+
2518
+ static getDerivedStateFromError(error) {
2519
+ return { error }
2520
+ }
2521
+
2522
+ componentDidCatch(error, info) {
2523
+ console.error('[timeback] panel crashed', error, info)
2524
+ }
2525
+
2526
+ render() {
2527
+ if (this.state.error !== null) {
2528
+ const message = this.state.error?.message ? String(this.state.error.message) : String(this.state.error)
2529
+ return h(
2530
+ 'div',
2531
+ { className: 'tb-panel' },
2532
+ h(
2533
+ 'div',
2534
+ { className: 'tb-head' },
2535
+ h(TimebackIcon, { size: 16 }),
2536
+ h('span', { className: 'tb-title' }, '时间回溯 · Timeback'),
2537
+ h('span', { className: 'tb-muted tb-small' }, BUILD),
2538
+ ),
2539
+ h(
2540
+ 'div',
2541
+ { className: 'tb-body' },
2542
+ h('div', { className: 'tb-feedback err', role: 'alert' }, `面板渲染失败 / Panel render failed: ${message}`),
2543
+ h('p', { className: 'tb-ws-hint' }, '请按 F12 打开 Console 查看 [timeback] 报错,并把错误发给我。你可以先用 get_goal 之类的普通功能;文件快照与开关仍可通过 timeback_workspace 工具操作。'),
2544
+ ),
2545
+ )
2546
+ }
2547
+ return h(TimebackPanel, this.props)
2548
+ }
2549
+ }
2550
+
2551
+ /** Error boundary for the global board page (reuses the panel fallback). */
2552
+ class BoardBoundary extends PanelBoundary {
2553
+ render() {
2554
+ if (this.state.error !== null) return super.render()
2555
+ return h(BoardPanel, this.props)
2556
+ }
2557
+ }
2558
+
2559
+ /**
2560
+ * Workspace recording checkbox shown in the New Session row, i.e. right
2561
+ * after a Workspace is created. The flag belongs to the workspace
2562
+ * directory, so every Session in it shares it.
2563
+ */
2564
+ function HeroRecordingToggle(props) {
2565
+ const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : ''
2566
+ const t = typeof props?.t === 'function' ? props.t : (key) => key
2567
+ const [state, setState] = React.useState({ workspace: null, error: null })
2568
+ const [busy, setBusy] = React.useState(false)
2569
+
2570
+ React.useEffect(() => {
2571
+ if (!sessionId) return undefined
2572
+ let disposed = false
2573
+ const controller = new AbortController()
2574
+ const load = async () => {
2575
+ try {
2576
+ const response = await fetch(`${API}/tree?session=${encodeURIComponent(sessionId)}`, {
2577
+ credentials: 'same-origin',
2578
+ headers: { accept: 'application/json' },
2579
+ signal: controller.signal,
2580
+ })
2581
+ const body = await response.json()
2582
+ if (disposed) return
2583
+ if (!response.ok || body?.ok === false) throw new Error(body?.error || `HTTP ${response.status}`)
2584
+ setState({ workspace: body.workspace ?? null, error: null })
2585
+ } catch (error) {
2586
+ if (disposed || error?.name === 'AbortError') return
2587
+ setState({ workspace: null, error: error?.message || String(error) })
2588
+ }
2589
+ }
2590
+ load()
2591
+ return () => {
2592
+ disposed = true
2593
+ controller.abort()
2594
+ }
2595
+ }, [sessionId])
2596
+
2597
+ const toggle = async (enabled) => {
2598
+ if (busy) return
2599
+ setBusy(true)
2600
+ try {
2601
+ // A brand-new Session may not be persisted yet, so resolving its cwd by
2602
+ // session id can fail. The workspace path is already known from the tree
2603
+ // payload, and an explicit cwd always wins on the host side.
2604
+ const cwd = state.workspace?.cwd || ''
2605
+ const result = await request('action', {
2606
+ method: 'POST',
2607
+ body: { action: 'set-workspace', ...(cwd ? { cwd } : { sessionId }), enabled },
2608
+ })
2609
+ setState({ workspace: result.workspace ?? state.workspace, error: null })
2610
+ } catch (error) {
2611
+ setState({ workspace: state.workspace, error: error?.message || String(error) })
2612
+ } finally {
2613
+ setBusy(false)
2614
+ }
2615
+ }
2616
+
2617
+ const workspace = state.workspace
2618
+ if (!workspace || !workspace.cwd) return null
2619
+ const fixed = workspace.mode !== 'workspace'
2620
+ const disabled = fixed || busy || workspace.exists === false
2621
+ const hint = fixed
2622
+ ? workspace.mode === 'all'
2623
+ ? t('hero.recordAll')
2624
+ : t('hero.recordOff')
2625
+ : t('hero.recordHint')
2626
+ return h(
2627
+ 'label',
2628
+ { className: 'tb-hero', title: state.error ? format(t('hero.recordError'), { error: state.error }) : hint },
2629
+ h('input', {
2630
+ type: 'checkbox',
2631
+ checked: workspace.enabled === true,
2632
+ disabled,
2633
+ 'aria-label': t('hero.record'),
2634
+ onChange: (event) => toggle(event.target.checked),
2635
+ }),
2636
+ h('span', null, t('hero.record')),
2637
+ h('span', { className: 'tb-hero-name', title: workspace.cwd }, baseName(workspace.cwd)),
2638
+ state.error ? h('span', { className: 'tb-hero-err', title: state.error }, state.error) : null,
2639
+ )
2640
+ }
2641
+
2642
+ /* ---------------------------------------------------------------- */
2643
+ /* entry points */
2644
+ /* ---------------------------------------------------------------- */
2645
+
2646
+ function ComposerPill(props) {
2647
+ const t = typeof props?.t === 'function' ? props.t : (key) => key
2648
+ if (!props?.sessionId) return null
2649
+ return h(
2650
+ 'button',
2651
+ {
2652
+ type: 'button',
2653
+ className: 'tb-pill',
2654
+ title: t('header.open'),
2655
+ 'aria-label': t('header.open'),
2656
+ onClick: () => {
2657
+ if (typeof openPanelBridge === 'function') openPanelBridge()
2658
+ },
2659
+ },
2660
+ h(TimebackIcon, { size: 14 }),
2661
+ h('span', null, t('pill.open')),
2662
+ )
2663
+ }
2664
+
2665
+ /* ---------------------------------------------------------------- */
2666
+ /* header button */
2667
+ /* ---------------------------------------------------------------- */
2668
+
2669
+ function HeaderButton(props) {
2670
+ const t = typeof props?.t === 'function' ? props.t : (key) => key
2671
+ const open = props?.open
2672
+ if (!props?.sessionId) return null
2673
+ return h(
2674
+ 'button',
2675
+ {
2676
+ type: 'button',
2677
+ className: 'tb-iconbtn',
2678
+ title: t('header.open'),
2679
+ 'aria-label': t('header.open'),
2680
+ onClick: () => {
2681
+ if (typeof open === 'function') open()
2682
+ },
2683
+ },
2684
+ h(TimebackIcon, { size: 18 }),
2685
+ )
2686
+ }
2687
+
2688
+ /* ---------------------------------------------------------------- */
2689
+ /* global notes board page */
2690
+ /* ---------------------------------------------------------------- */
2691
+
2692
+ function BoardPanel(props) {
2693
+ const t = typeof props?.t === 'function' ? props.t : (key) => key
2694
+ const [state, setState] = React.useState({ loading: true, board: null, error: null })
2695
+ const [draft, setDraft] = React.useState(null)
2696
+ const [busy, setBusy] = React.useState('')
2697
+
2698
+ const refresh = React.useCallback(async () => {
2699
+ try {
2700
+ const body = await request('notes')
2701
+ setState({ loading: false, board: body.board ?? null, error: null })
2702
+ } catch (error) {
2703
+ setState((previous) => ({ ...previous, loading: false, error: error?.message || String(error) }))
2704
+ }
2705
+ }, [])
2706
+
2707
+ React.useEffect(() => {
2708
+ refresh()
2709
+ const handler = () => {
2710
+ refresh()
2711
+ }
2712
+ window.addEventListener('dsh-timeback:board-changed', handler)
2713
+ return () => window.removeEventListener('dsh-timeback:board-changed', handler)
2714
+ }, [refresh])
2715
+
2716
+ const entries = [...(state.board?.entries ?? [])].sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
2717
+ const boardVersion = state.board?.version ?? 0
2718
+ const startCreate = () => setDraft({ id: '', title: '', body: '', preview: false, busy: false, error: null })
2719
+ const startEdit = (entry) => setDraft({ id: entry.id, title: entry.title, body: entry.body, preview: false, busy: false, error: null })
2720
+ const closeDraft = () => {
2721
+ if (draft && !draft.busy) setDraft(null)
2722
+ }
2723
+ const saveDraft = async () => {
2724
+ if (!draft || draft.busy) return
2725
+ setDraft({ ...draft, busy: true, error: null })
2726
+ try {
2727
+ const body = await request('action', {
2728
+ method: 'POST',
2729
+ body: { action: 'note-save', ...(draft.id ? { id: draft.id } : {}), title: draft.title, body: draft.body },
2730
+ })
2731
+ setDraft(null)
2732
+ setState({ loading: false, board: body.board ?? state.board, error: null })
2733
+ } catch (error) {
2734
+ setDraft({ ...draft, busy: false, error: error?.message || String(error) })
2735
+ }
2736
+ }
2737
+ const removeEntry = async (id) => {
2738
+ if (!id || busy !== '') return
2739
+ let confirmed = true
2740
+ try {
2741
+ confirmed = typeof window.confirm === 'function' ? window.confirm(t('board.deleteConfirm')) : true
2742
+ } catch {
2743
+ confirmed = true
2744
+ }
2745
+ if (!confirmed) return
2746
+ setBusy(id)
2747
+ try {
2748
+ const body = await request('action', { method: 'POST', body: { action: 'note-delete', id } })
2749
+ setState({ loading: false, board: body.board ?? state.board, error: null })
2750
+ } catch (error) {
2751
+ setState((previous) => ({ ...previous, error: error?.message || String(error) }))
2752
+ } finally {
2753
+ setBusy('')
2754
+ }
2755
+ }
2756
+
2757
+ return h(
2758
+ 'div',
2759
+ { className: 'tb-board-panel' },
2760
+ h(
2761
+ 'div',
2762
+ { className: 'tb-board-head' },
2763
+ h('span', { className: 'tb-board-title' }, `📋 ${t('board.title')}`),
2764
+ h('span', { className: 'tb-board-sub' }, t('board.subtitle')),
2765
+ h('span', { style: { flex: 1 } }),
2766
+ h('span', { className: 'tb-muted tb-small' }, format(t('board.count'), { count: entries.length, version: boardVersion })),
2767
+ h('button', { type: 'button', className: 'tb-btn', disabled: state.loading, onClick: refresh }, t('board.refresh')),
2768
+ h('button', { type: 'button', className: 'tb-btn primary', onClick: startCreate }, `+ ${t('board.new')}`),
2769
+ ),
2770
+ h(
2771
+ 'div',
2772
+ { className: 'tb-board-body' },
2773
+ h('p', { className: 'tb-board-hint' }, t('board.agentHint')),
2774
+ state.error ? h('div', { className: 'tb-feedback err' }, format(t('board.error'), { error: state.error })) : null,
2775
+ state.loading && !state.board ? h('p', { className: 'tb-board-empty' }, t('panel.loading')) : null,
2776
+ !state.loading && entries.length === 0
2777
+ ? h('p', { className: 'tb-board-empty' }, t('board.empty'))
2778
+ : null,
2779
+ ...entries.map((entry) =>
2780
+ h(
2781
+ 'article',
2782
+ { key: entry.id, className: 'tb-board-note' },
2783
+ h(
2784
+ 'div',
2785
+ { className: 'tb-board-note-head' },
2786
+ h('span', { className: 'tb-board-note-title' }, entry.title || '未命名记录'),
2787
+ h(
2788
+ 'span',
2789
+ { className: `tb-chip ${entry.source === 'agent' ? 'ok' : ''}` },
2790
+ entry.source === 'agent' ? t('board.sourceAgent') : t('board.sourceUser'),
2791
+ ),
2792
+ h('span', { className: 'tb-board-meta' }, clock(entry.updatedAt)),
2793
+ h(
2794
+ 'div',
2795
+ { className: 'tb-board-actions' },
2796
+ h('button', { type: 'button', className: 'tb-btn', onClick: () => startEdit(entry) }, t('board.edit')),
2797
+ h(
2798
+ 'button',
2799
+ { type: 'button', className: 'tb-btn danger', disabled: busy !== '', onClick: () => removeEntry(entry.id) },
2800
+ busy === entry.id ? '…' : t('board.delete'),
2801
+ ),
2802
+ ),
2803
+ ),
2804
+ entry.body ? h('div', { className: 'tb-md' }, ...renderMarkdown(entry.body, `board-${entry.id}`)) : null,
2805
+ ),
2806
+ ),
2807
+ ),
2808
+ draft
2809
+ ? h(
2810
+ 'div',
2811
+ { className: 'tb-overlay center', onClick: closeDraft },
2812
+ h(
2813
+ 'div',
2814
+ { className: 'tb-board-dialog', role: 'dialog', 'aria-modal': true, onClick: (event) => event.stopPropagation() },
2815
+ h(
2816
+ 'div',
2817
+ { className: 'tb-detail-head' },
2818
+ h('span', { className: 'tb-detail-title' }, draft.id ? t('board.edit') : t('board.new')),
2819
+ h('span', { style: { flex: 1 } }),
2820
+ h(
2821
+ 'button',
2822
+ {
2823
+ type: 'button',
2824
+ className: `tb-viewtab${draft.preview ? ' on' : ''}`,
2825
+ onClick: () => setDraft({ ...draft, preview: !draft.preview }),
2826
+ },
2827
+ draft.preview ? t('board.editMode') : t('board.preview'),
2828
+ ),
2829
+ ),
2830
+ h('input', {
2831
+ value: draft.title,
2832
+ placeholder: t('board.titlePlaceholder'),
2833
+ disabled: draft.busy,
2834
+ onChange: (event) => setDraft({ ...draft, title: event.target.value }),
2835
+ }),
2836
+ draft.preview
2837
+ ? h('div', { className: 'tb-md' }, ...renderMarkdown(draft.body, 'board-draft'))
2838
+ : h('textarea', {
2839
+ value: draft.body,
2840
+ placeholder: t('board.bodyPlaceholder'),
2841
+ disabled: draft.busy,
2842
+ onChange: (event) => setDraft({ ...draft, body: event.target.value }),
2843
+ }),
2844
+ draft.error ? h('div', { className: 'tb-feedback err' }, format(t('board.error'), { error: draft.error })) : null,
2845
+ h(
2846
+ 'div',
2847
+ { className: 'tb-note-actions' },
2848
+ h('button', { type: 'button', className: 'tb-btn', disabled: draft.busy, onClick: closeDraft }, t('board.cancel')),
2849
+ h('button', { type: 'button', className: 'tb-btn primary', disabled: draft.busy, onClick: saveDraft }, t('board.save')),
2850
+ ),
2851
+ ),
2852
+ )
2853
+ : null,
2854
+ )
2855
+ }
2856
+
2857
+ if (typeof window !== 'undefined' && window.__TIMEBACK_TEST__) {
2858
+ window.__TIMEBACK_TEST__.edgePanVector = edgePanVector
2859
+ window.__TIMEBACK_TEST__.renderMarkdown = renderMarkdown
2860
+ window.__TIMEBACK_TEST__.stripMarkdown = stripMarkdown
2861
+ }
2862
+
2863
+ return {
2864
+ inject: ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs', 'uiWorkspace', 'uiSession', 'contextMenus'],
2865
+ apply(ctx) {
2866
+ const t = ctx.locale.bind(NS)
2867
+ console.log(`[timeback] client ${BUILD} loaded`)
2868
+ openSessionBridge = (sessionId) => {
2869
+ try {
2870
+ ctx.uiWorkspace.openSession(sessionId)
2871
+ } catch (error) {
2872
+ console.warn('[timeback] openSession failed', error)
2873
+ }
2874
+ }
2875
+ openPanelBridge = () => {
2876
+ try {
2877
+ ctx.sidebarRight.openTab(KIND)
2878
+ } catch (error) {
2879
+ console.warn('[timeback] openTab failed', error)
2880
+ }
2881
+ }
2882
+ openBoardBridge = () => {
2883
+ try {
2884
+ ctx.sidebarRight.openTab(BOARD_KIND)
2885
+ } catch (error) {
2886
+ console.warn('[timeback] open board tab failed', error)
2887
+ }
2888
+ }
2889
+ ctx.effect(() => ctx.locale.register(NS, DICT), 'timeback: dictionaries')
2890
+ ctx.effect(() => installStyles(), 'timeback: panel styles')
2891
+
2892
+ ctx.effect(
2893
+ () =>
2894
+ ctx.sidebarRightTabs.register({
2895
+ id: ID,
2896
+ kind: KIND,
2897
+ priority: 'extension',
2898
+ title: () => t('type.title'),
2899
+ keepMounted: true,
2900
+ guide: [
2901
+ {
2902
+ id: 'timeback-tree',
2903
+ order: 70,
2904
+ title: () => t('guide.title'),
2905
+ description: () => t('guide.description'),
2906
+ icon: GuideIcon,
2907
+ },
2908
+ ],
2909
+ }),
2910
+ 'timeback: tab type',
2911
+ )
2912
+
2913
+ ctx.effect(
2914
+ () =>
2915
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
2916
+ ctx.slots.register({ name: 'sidebar.right.pane.tab', key: ID, locale: NS }, PanelBoundary),
2917
+ ),
2918
+ 'timeback: panel body',
2919
+ )
2920
+
2921
+ ctx.effect(
2922
+ () =>
2923
+ ctx.sidebarRightTabs.register({
2924
+ id: BOARD_ID,
2925
+ kind: BOARD_KIND,
2926
+ priority: 'extension',
2927
+ title: () => t('board.title'),
2928
+ keepMounted: true,
2929
+ guide: [
2930
+ {
2931
+ id: 'timeback-board',
2932
+ order: 71,
2933
+ title: () => t('guide.boardTitle'),
2934
+ description: () => t('guide.boardDescription'),
2935
+ icon: GuideIcon,
2936
+ },
2937
+ ],
2938
+ }),
2939
+ 'timeback: board tab type',
2940
+ )
2941
+
2942
+ ctx.effect(
2943
+ () =>
2944
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
2945
+ ctx.slots.register({ name: 'sidebar.right.pane.tab', key: BOARD_ID, locale: NS }, BoardBoundary),
2946
+ ),
2947
+ 'timeback: board panel body',
2948
+ )
2949
+
2950
+ ctx.effect(
2951
+ () =>
2952
+ ctx.slots.inject('contextMenu.icon', () =>
2953
+ ctx.slots.register({ name: 'contextMenu.icon', key: 'timeback.workspace' }, GuideIcon),
2954
+ ),
2955
+ 'timeback: workspace menu icon',
2956
+ )
2957
+
2958
+ ctx.effect(
2959
+ () =>
2960
+ ctx.contextMenus.register({
2961
+ id: 'timeback.workspace',
2962
+ target: 'workspace',
2963
+ order: 40,
2964
+ resolve: async (target) => {
2965
+ let info
2966
+ try {
2967
+ info = await request('action', { method: 'POST', body: { action: 'workspaces', cwd: target.path } })
2968
+ } catch {
2969
+ return [{ id: 'timeback.workspace.unavailable', label: t('menu.unavailable'), disabled: true }]
2970
+ }
2971
+ const enabled = info?.workspace?.enabled === true
2972
+ const fixed = info?.mode !== 'workspace'
2973
+ return [
2974
+ {
2975
+ id: 'timeback.workspace.toggle',
2976
+ label: enabled ? t('menu.disable') : t('menu.enable'),
2977
+ icon: { key: 'timeback.workspace' },
2978
+ disabled: fixed,
2979
+ failureLabel: t('menu.failure'),
2980
+ run: async () => {
2981
+ await request('action', {
2982
+ method: 'POST',
2983
+ body: { action: 'set-workspace', cwd: target.path, enabled: !enabled },
2984
+ })
2985
+ ctx.contextMenus.notify(enabled ? t('menu.notifyOff') : t('menu.notifyOn'), true)
2986
+ },
2987
+ },
2988
+ { id: 'timeback.workspace.state', label: enabled ? t('menu.stateOn') : t('menu.stateOff'), disabled: true },
2989
+ ]
2990
+ },
2991
+ }),
2992
+ 'timeback: workspace menu',
2993
+ )
2994
+
2995
+ ctx.effect(
2996
+ () =>
2997
+ ctx.slots.inject('conversation.hero.options', () =>
2998
+ ctx.slots.register(
2999
+ { name: 'conversation.hero.options', id: 'timeback-recording', order: 20, locale: NS },
3000
+ HeroRecordingToggle,
3001
+ ),
3002
+ ),
3003
+ 'timeback: new-session recording option',
3004
+ )
3005
+
3006
+ ctx.effect(
3007
+ () =>
3008
+ ctx.slots.inject('conversation.composer.dock', () =>
3009
+ ctx.slots.register(
3010
+ { name: 'conversation.composer.dock', id: ID, order: 6, locale: NS },
3011
+ ComposerPill,
3012
+ ),
3013
+ ),
3014
+ 'timeback: composer entry',
3015
+ )
3016
+
3017
+ ctx.effect(
3018
+ () =>
3019
+ ctx.slots.inject('conversation.session.header.utilities', () =>
3020
+ ctx.slots.register(
3021
+ {
3022
+ name: 'conversation.session.header.utilities',
3023
+ id: ID,
3024
+ order: 32,
3025
+ locale: NS,
3026
+ inject: () => ({
3027
+ open: () => {
3028
+ try {
3029
+ ctx.sidebarRight.openTab(KIND)
3030
+ } catch (error) {
3031
+ console.warn('[timeback] openTab failed', error)
3032
+ }
3033
+ },
3034
+ }),
3035
+ },
3036
+ HeaderButton,
3037
+ ),
3038
+ ),
3039
+ 'timeback: header button',
3040
+ )
3041
+ },
3042
+ }
3043
+ },
3044
+ })