dsh-timeback 0.0.0-stage → 0.6.1

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