@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-11

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,3791 @@
1
+ /**
2
+ * DSH增强 — browser half.
3
+ *
4
+ * Registers four contributions:
5
+ * - one row in a session's "..." menu (delete),
6
+ * - one footer action beside Settings (session recovery),
7
+ * - two frame-wide overlay entries (search panel, dialogs + toast),
8
+ * - one settings section (switches and limits).
9
+ *
10
+ * All host work goes through a single exact Connection fetch route, which is
11
+ * authenticated by the page's own browser session; this module never touches
12
+ * session files or the workspace registry itself.
13
+ */
14
+ window.__ModuleLoader__.load({
15
+ id: '@xsok/dsh-enhanced',
16
+ factory(require) {
17
+ const React = require('react');
18
+ const h = React.createElement;
19
+ const NS = 'dshEnhanced';
20
+
21
+ let primitives = null;
22
+ try {
23
+ primitives = require('@deepseek-ai/dsh-client-ui-primitives');
24
+ } catch (error) {
25
+ console.warn('[dsh-enhanced] ui primitives are unavailable; using fallbacks', error);
26
+ primitives = null;
27
+ }
28
+
29
+ /** Render into <body> so dialogs cannot cover our panels; optional. */
30
+ let createPortal = null;
31
+ try {
32
+ const ReactDOM = require('react-dom');
33
+ if (typeof ReactDOM?.createPortal === 'function') createPortal = ReactDOM.createPortal;
34
+ } catch {
35
+ createPortal = null;
36
+ }
37
+
38
+ const DEFAULTS = Object.freeze({
39
+ version: 1,
40
+ deleteEnabled: true,
41
+ trashEnabled: true,
42
+ searchEnabled: true,
43
+ moveEnabled: true,
44
+ autoLoadEnabled: true,
45
+ syncEnabled: false,
46
+ syncDir: '',
47
+ syncScript: '',
48
+ syncMachineId: '',
49
+ syncSkipAttachments: false,
50
+ syncIntervalMinutes: 0,
51
+ syncDailyAt: '',
52
+ syncOnIdle: true,
53
+ syncCooldownMinutes: 5,
54
+ syncMode: 'local',
55
+ webdavUrl: '',
56
+ webdavUser: '',
57
+ webdavPassword: '',
58
+ webdavRoot: '',
59
+ webdavAutoCreate: true,
60
+ mirrorDir: '',
61
+ matchTitle: true,
62
+ matchBody: true,
63
+ matchTools: false,
64
+ retentionDays: 60,
65
+ });
66
+
67
+ const DICT = {
68
+ en: {
69
+ 'nav.title': 'DSH Enhanced',
70
+ 'env.button': 'Environment check',
71
+ 'restart.button': 'Restart app',
72
+ 'restart.hint': 'Ctrl+Shift+Alt+R',
73
+ 'restart.desc': 'Restart the desktop app now?',
74
+ 'restart.confirm': 'Restart',
75
+ 'restart.busy': 'A turn is still running. Stop it, then restart.',
76
+ 'restart.auto': '{reason} · restarting in {seconds}s',
77
+ 'restart.reason.sync': 'Sync done',
78
+ 'restart.reason.move': 'Session moved',
79
+ 'restart.reason.restore': 'Cloud applied',
80
+ 'overwrite.cloud': 'Overwrite cloud',
81
+ 'overwrite.local': 'Overwrite this machine',
82
+ 'overwrite.awayCloud': 'Replaces the cloud with this machine\'s data. Nothing is merged.',
83
+ 'overwrite.awayLocal': 'Replaces this machine with the cloud data. Nothing is merged.',
84
+ 'overwrite.confirm': 'Start overwrite',
85
+ 'overwrite.running': 'Working…',
86
+ 'overwrite.cloudDone': 'Cloud replaced; {n} file(s) uploaded.',
87
+ 'overwrite.localDone': 'This machine replaced; {n} area(s) copied.',
88
+ 'env.busy': 'Checking…',
89
+ 'env.title': 'DSH Enhanced · Environment check',
90
+ 'env.ok': 'No problems found',
91
+ 'env.risk': '{n} risk(s) found. Export a report?',
92
+ 'env.report': 'Export report',
93
+ 'env.reported': 'Report saved to {path}',
94
+ 'env.versionLine': 'App {app} · plugin V{plugin}',
95
+ 'env.update.title': 'DSH Enhanced · host updated',
96
+ 'env.update.desc': 'The host application changed ({last} → {app}). Run the environment check to make sure the plugin still works?',
97
+ 'env.update.yes': 'Yes',
98
+ 'env.update.no': 'No',
99
+ 'pause.title': 'DSH Enhanced · automatic sync paused',
100
+ 'pause.desc': 'Automatic sync stopped after {n} consecutive failures.',
101
+ 'pause.last': 'Last failure: {summary}. {hint}',
102
+ 'pause.resume': 'Resume automatic sync',
103
+ 'pause.resumed': 'Automatic sync resumed',
104
+ 'section.title': 'DSH Enhanced',
105
+ 'section.desc': 'Session delete and restore, cross-workspace move, full-corpus search, quoting, auto-load history, and multi-device sync.',
106
+ 'section.reading': 'Reading and actions',
107
+ 'section.sessions': 'Session management',
108
+ 'section.search': 'Content search',
109
+ 'section.sync': 'Session sync',
110
+ 'sync.interval': 'Interval (minutes)',
111
+ 'sync.interval.hint': '0 turns interval sync off.',
112
+ 'sync.daily': 'Daily at',
113
+ 'sync.daily.hint': 'HH:MM in 24-hour form; empty turns it off.',
114
+ 'sync.idle': 'Sync when idle',
115
+ 'sync.idle.desc': 'Runs once the first time every session stops working.',
116
+ 'sync.cooldown': 'Minimum gap (minutes)',
117
+ 'sync.mode': 'Sync target',
118
+ 'sync.mode.local': 'Local folder',
119
+ 'sync.mode.webdav': 'WebDAV',
120
+ 'sync.webdav.url': 'WebDAV address',
121
+ 'sync.webdav.presets': 'Saved setups',
122
+ 'sync.webdav.presets.hint': 'One click fills the four fields above. Up to three.',
123
+ 'sync.webdav.presets.save': 'Save current setup',
124
+ 'sync.webdav.presets.modify': 'Edit setup',
125
+ 'sync.webdav.presets.commitModify': 'Save changes',
126
+ 'sync.webdav.presets.updated': 'Updated "{name}".',
127
+ 'sync.webdav.presets.replaced': 'Setup replaced.',
128
+ 'sync.webdav.presets.replaceTitle': 'Replace which setup?',
129
+ 'sync.webdav.presets.replaceDesc': 'Three setups are already saved. Pick the one this replaces.',
130
+ 'sync.webdav.presets.saved': 'Saved "{name}".',
131
+ 'sync.webdav.presets.rename': 'Rename',
132
+ 'sync.webdav.presets.name': 'Setup name',
133
+ 'sync.webdav.presets.confirm': 'Apply the name',
134
+ 'sync.webdav.presets.default': 'Default (current fields)',
135
+ 'sync.webdav.presets.remove': 'Delete',
136
+ 'sync.webdav.presets.unsaved': '(current fields, not saved)',
137
+ 'sync.webdav.presets.full': 'Three saved setups are the limit. Remove one first.',
138
+ 'sync.webdav.presets.empty': 'Fill in the address first.',
139
+ 'sync.webdav.user': 'Account',
140
+ 'sync.webdav.password': 'App password',
141
+ 'sync.webdav.password.hint': 'Jianguoyun requires an application password from its security page, not the login password.',
142
+ 'sync.webdav.root': 'Remote root',
143
+ 'sync.webdav.root.hint': 'Full path, e.g. https://dav.jianguoyun.com/dav/我的坚果云/DSH-Sync',
144
+ 'sync.webdav.mirror': 'Local mirror folder',
145
+ 'sync.webdav.mirror.usage': 'Currently using {size} ({files} files)',
146
+ 'sync.webdav.autoCreate': 'Create the remote folder',
147
+ 'sync.webdav.autoCreate.desc': 'When the remote path is missing, create it level by level before testing.',
148
+ 'sync.webdav.test': 'Test connection',
149
+ 'sync.webdav.testing': 'Connecting…',
150
+ 'sync.webdav.ok': 'Connected: {message}',
151
+ 'sync.webdav.fail': 'Connection failed: {message}',
152
+ 'sync.pull': 'Pull once',
153
+ 'sync.push': 'Push once',
154
+ 'sync.pull.confirm': 'Download from the cloud into the local mirror folder? Nothing is uploaded or deleted remotely.',
155
+ 'sync.push.confirm': 'Upload the mirror folder to the cloud? Existing remote files are overwritten only when they differ, never deleted.',
156
+ 'sync.pulled': 'Pulled {n} files ({bytes}), skipped {skipped}.',
157
+ 'sync.pushed': 'Pushed {n} files ({bytes}), skipped {skipped}.',
158
+ 'sync.directionFailed': '{n} files failed',
159
+ 'sync.noFailure': 'no failures',
160
+ 'switch.delete': 'Delete sessions',
161
+ 'switch.delete.desc': 'Adds "Delete session" to the session menu. A running session cannot be deleted.',
162
+ 'switch.move': 'Move between workspaces',
163
+ 'switch.move.desc': 'Adds "Move to workspace" to the session menu. Moving copies the session and permanently deletes the original.',
164
+ 'switch.autoLoad': 'Auto-load earlier messages',
165
+ 'switch.autoLoad.desc': 'Scrolling to the top of a conversation loads the next older page automatically, without clicking "Load earlier".',
166
+ 'sync.title': 'Session and config sync',
167
+ 'sync.desc': 'Runs the bundled sync engine to copy sessions, config and attachments into a shared folder.',
168
+ 'sync.needDir': 'Fill in the shared folder before syncing.',
169
+ 'sync.needMirror': 'Fill in the local mirror folder before syncing.',
170
+ 'sync.enable': 'Automatic sync',
171
+ 'sync.enable.hint': 'Idle, interval and daily triggers only; Sync now ignores this switch.',
172
+ 'sync.dir': 'Shared folder',
173
+ 'sync.machine': 'Machine id',
174
+ 'sync.machine.hint': 'Empty uses the Windows user name; a collision with an existing id refuses the sync.',
175
+ 'sync.machine.placeholder': 'System default: {id}',
176
+ 'sync.attachments': 'Sync attachments',
177
+ 'sync.probe': 'Check',
178
+ 'sync.run': 'Sync now',
179
+ 'sync.run.hint': 'Ctrl+Alt+Shift+T',
180
+ 'sync.running': 'Syncing…',
181
+ 'sync.done': 'Sessions synced',
182
+ 'sync.never': 'Not run yet.',
183
+ 'sync.last': 'Last run: {time} · {result} · {ms} ms',
184
+ 'sync.result.ok': 'ok',
185
+ 'sync.result.fail': 'failed',
186
+ 'sync.purged': 'trash pruned {n}',
187
+ 'sync.paths': 'dirs created {created}, failed {failed}',
188
+ 'sync.failed': '{n} files failed',
189
+ 'sync.counts': '↑ {up} · ↓ {down} · 🗑 {del}',
190
+ 'sync.transport': 'transport: {down} down, {up} up',
191
+ 'sync.transportDel': 'transport: {down} down, {up} up, {del} deleted',
192
+ 'sync.dirMissing': 'Shared folder not found: {path}',
193
+ 'sync.log': 'Show log',
194
+ 'sync.logToggle': 'Click to show or hide the run history',
195
+ 'sync.more': 'Show more',
196
+ 'sync.historyCount': '{n} runs recorded',
197
+ 'sync.logHide': 'Hide log',
198
+ 'sync.failed': 'Sync failed: {message}',
199
+ 'switch.trash': 'Session recovery',
200
+ 'switch.trash.desc': 'Shows the recovery entry in the session menu and on this page. Deleted sessions stay in the local recycle bin.',
201
+ 'switch.search': 'Content search',
202
+ 'switch.search.desc': 'Opens the search panel over any screen and matches titles and messages.',
203
+ 'switch.matchTitle': 'Match session titles',
204
+ 'switch.matchBody': 'Match user and assistant messages',
205
+ 'switch.matchTools': 'Match tool output',
206
+ 'switch.limits': 'Search scope',
207
+ 'field.retention': 'Keep deleted sessions for (days)',
208
+ 'field.retention.hint': '0 keeps them until you remove them by hand.',
209
+ 'trash.usage': '{count} sessions, {size}',
210
+ 'trash.clear': 'Empty recycle bin',
211
+ 'trash.cleared': 'Recycle bin emptied.',
212
+ 'delete.label': 'Delete session',
213
+ 'delete.running': 'Delete session (running)',
214
+ 'delete.title': 'Delete this session?',
215
+ 'delete.desc': 'The local session directory, its projection cache shard, and its workspace reference are removed. The session stays recoverable until the retention period ends.',
216
+ 'delete.confirm': 'Delete',
217
+ 'delete.done': '"{title}" was deleted.',
218
+ 'delete.failed': 'Delete failed: {message}',
219
+ 'delete.blocked': 'A running session cannot be deleted.',
220
+ 'move.label': 'Move to workspace…',
221
+ 'hover.sessionId': 'Session ID: ',
222
+ 'hover.copy.title': 'Session name',
223
+ 'hover.copy.id': 'Session ID',
224
+ 'hover.copy.path': 'Workspace path',
225
+ 'hover.copy.done': 'Copied: {label}',
226
+ 'hover.copy.failed': 'Copy failed: {label}',
227
+ 'move.running': 'Move to workspace (running)',
228
+ 'move.title': 'Move to workspace',
229
+ 'move.desc': 'Moves the session into the target workspace in place: the session itself is unchanged and only its working directory becomes the target. Later tool calls run there. The new grouping appears after the app restarts.',
230
+ 'move.session': 'Session: {title}',
231
+ 'move.restarting': 'Moved. Restarting so the new grouping takes effect…',
232
+ 'move.current': 'Current workspace: {title}',
233
+ 'move.target': 'Target workspace',
234
+ 'move.empty': 'No other workspace is available.',
235
+ 'move.loading': 'Reading workspaces…',
236
+ 'move.busy': 'Copying the session…',
237
+ 'move.confirm': 'Move',
238
+ 'move.done': 'Moved to "{title}".',
239
+ 'move.failed': 'Move failed: {message}',
240
+ 'trash.title': 'Session deletions',
241
+ 'trash.untitled': 'Untitled',
242
+ 'trash.menu': 'Recover sessions in this workspace',
243
+ 'trash.desc': 'Sessions deleted in this workspace. Restore one, or remove it permanently.',
244
+ 'trash.empty': 'No deleted sessions.',
245
+ 'trash.restore': 'Restore',
246
+ 'trash.purge': 'Delete permanently',
247
+ 'trash.purge.confirm': 'Delete for good?',
248
+ 'trash.clear': 'Empty recycle bin',
249
+ 'trash.clear.confirm': 'Empty for good?',
250
+ 'trash.clearWorkspace': 'Empty workspace',
251
+ 'trash.clearWorkspace.confirm': 'Empty for good?',
252
+ 'trash.restored': '"{title}" was restored.',
253
+ 'trash.purged': '"{title}" was deleted permanently.',
254
+ 'trash.loading': 'Loading…',
255
+ 'search.placeholder': 'Search session titles and content',
256
+ 'search.empty': 'No matches.',
257
+ 'search.hint': 'Type to search every session. Enter opens the highlighted result.',
258
+ 'search.loading': 'Searching…',
259
+ 'search.error': 'Search failed: {message}',
260
+ 'search.meta': '{count} sessions, {matches} matches',
261
+ 'search.notLocated': 'Opened the session, but the match is not loaded yet. Click "Load earlier" and try again.',
262
+ 'search.close': 'Close search',
263
+ 'role.user': 'You',
264
+ 'role.assistant': 'Assistant',
265
+ 'role.tool': 'Tool',
266
+ 'role.title': 'Title',
267
+ 'common.close': 'Close',
268
+ 'common.cancel': 'Cancel',
269
+ 'common.retry': 'Retry',
270
+ },
271
+ zh: {
272
+ 'nav.title': 'DSH增强',
273
+ 'env.button': '环境检测',
274
+ 'restart.button': '重启应用',
275
+ 'restart.hint': 'Ctrl+Shift+Alt+R',
276
+ 'restart.desc': '立即重启桌面应用?',
277
+ 'restart.confirm': '重启',
278
+ 'restart.busy': '有任务正在运行,结束或停止后再重启。',
279
+ 'restart.auto': '{reason} · 即将自动重启 {seconds}s',
280
+ 'restart.reason.sync': '同步完成',
281
+ 'restart.reason.move': '会话已移动',
282
+ 'restart.reason.restore': '已应用云端',
283
+ 'overwrite.cloud': '覆盖云端',
284
+ 'overwrite.local': '覆盖本机',
285
+ 'overwrite.awayCloud': '将以本机数据完全替换云端,不做合并。',
286
+ 'overwrite.awayLocal': '将以云端数据完全替换本机,不做合并。',
287
+ 'overwrite.confirm': '开始覆盖',
288
+ 'overwrite.running': '处理中…',
289
+ 'overwrite.cloudDone': '云端已覆盖;上传 {n} 个文件。',
290
+ 'overwrite.localDone': '本机已覆盖;复制 {n} 个区域。',
291
+ 'env.busy': '正在检测…',
292
+ 'env.title': 'DSH增强 · 环境检测',
293
+ 'env.ok': '环境无异常',
294
+ 'env.risk': '发现 {n} 项风险点,是否输出风险报告?',
295
+ 'env.report': '输出风险报告',
296
+ 'env.reported': '风险报告已保存到 {path}',
297
+ 'env.versionLine': '主程序 {app} · 插件 V{plugin}',
298
+ 'env.update.title': 'DSH增强 · 主程序已更新',
299
+ 'env.update.desc': '发现主程序更新({last} → {app}),请运行“环境检测”确保插件可正确运行,是否立即检测?',
300
+ 'env.update.yes': '是',
301
+ 'env.update.no': '否',
302
+ 'pause.title': 'DSH增强 · 自动同步已暂停',
303
+ 'pause.desc': '连续 {n} 次同步失败,自动同步已暂停。',
304
+ 'pause.last': '最近一次失败:{summary}。{hint}',
305
+ 'pause.resume': '恢复自动同步',
306
+ 'pause.resumed': '自动同步已恢复',
307
+ 'section.title': 'DSH增强',
308
+ 'section.desc': '会话删除与找回、跨工作区移动、全库搜索、文字引用、自动加载历史,以及多设备同步。',
309
+ 'section.reading': '阅读与操作',
310
+ 'section.sessions': '会话管理',
311
+ 'section.search': '内容搜索',
312
+ 'section.sync': '会话同步',
313
+ 'sync.interval': '间隔同步(分钟)',
314
+ 'sync.interval.hint': '填0表示关闭间隔同步。',
315
+ 'sync.daily': '每日定时',
316
+ 'sync.daily.hint': '24小时制 HH:MM,留空表示关闭。',
317
+ 'sync.idle': '对话空闲后同步',
318
+ 'sync.idle.desc': '所有会话第一次全部进入空闲时自动同步一次。',
319
+ 'sync.cooldown': '最小间隔(分钟)',
320
+ 'sync.mode': '同步方式',
321
+ 'sync.mode.local': '本地目录',
322
+ 'sync.mode.webdav': 'WebDAV',
323
+ 'sync.webdav.url': 'WebDAV 地址',
324
+ 'sync.webdav.presets': '配置组',
325
+ 'sync.webdav.presets.hint': '点一下即填入上面四项;最多保存三组。',
326
+ 'sync.webdav.presets.save': '保存当前配置',
327
+ 'sync.webdav.presets.modify': '修改配置',
328
+ 'sync.webdav.presets.commitModify': '保存配置',
329
+ 'sync.webdav.presets.updated': '已更新“{name}”。',
330
+ 'sync.webdav.presets.replaced': '配置已替换。',
331
+ 'sync.webdav.presets.replaceTitle': '替换哪一组配置?',
332
+ 'sync.webdav.presets.replaceDesc': '已保存三组配置,请选择要被替换的一组。',
333
+ 'sync.webdav.presets.saved': '已保存“{name}”。',
334
+ 'sync.webdav.presets.rename': '重命名',
335
+ 'sync.webdav.presets.name': '配置名称',
336
+ 'sync.webdav.presets.confirm': '保存名称',
337
+ 'sync.webdav.presets.default': '默认配置',
338
+ 'sync.webdav.presets.remove': '删除',
339
+ 'sync.webdav.presets.unsaved': '(当前填写,未保存)',
340
+ 'sync.webdav.presets.full': '最多保存三组,请先删除一组。',
341
+ 'sync.webdav.presets.empty': '请先填写地址。',
342
+ 'sync.webdav.user': '账号',
343
+ 'sync.webdav.password': '应用密码',
344
+ 'sync.webdav.password.hint': '坚果云请到网页版“安全选项”生成应用密码,不要填登录密码。',
345
+ 'sync.webdav.root': '远程根目录',
346
+ 'sync.webdav.root.hint': '填完整路径,例如 https://dav.jianguoyun.com/dav/我的坚果云/DSH-Sync',
347
+ 'sync.webdav.mirror': '本地镜像目录',
348
+ 'sync.webdav.mirror.usage': '当前占用 {size}({files} 个文件)',
349
+ 'sync.webdav.autoCreate': '自动创建远程目录',
350
+ 'sync.webdav.autoCreate.desc': '远程路径不存在时,测试连接前会逐级创建。',
351
+ 'sync.webdav.test': '测试连接',
352
+ 'sync.webdav.testing': '正在连接…',
353
+ 'sync.webdav.ok': '连接成功:{message}',
354
+ 'sync.webdav.fail': '连接失败:{message}',
355
+ 'sync.pull': '拉取一次',
356
+ 'sync.push': '推送一次',
357
+ 'sync.pull.confirm': '从云端拉取到本地镜像目录?只下载,不会上传或删除云端文件。',
358
+ 'sync.push.confirm': '把本地镜像目录推送到云端?只有内容不同时才覆盖,不会删除云端已有文件。',
359
+ 'sync.pulled': '已拉取 {n} 个文件({bytes}),跳过 {skipped} 个。',
360
+ 'sync.pushed': '已推送 {n} 个文件({bytes}),跳过 {skipped} 个。',
361
+ 'sync.directionFailed': '{n} 个文件失败',
362
+ 'sync.noFailure': '无失败',
363
+ 'switch.delete': '会话删除',
364
+ 'switch.delete.desc': '在会话菜单中加入“删除会话”。运行中的会话不可删除。',
365
+ 'switch.move': '会话移动',
366
+ 'switch.move.desc': '在会话菜单中加入“移动到工作区”。移动会复制成新会话并永久删除原会话。',
367
+ 'switch.autoLoad': '自动加载更早消息',
368
+ 'switch.autoLoad.desc': '对话滚动到顶部时自动加载上一页历史,不需要再点“加载更早”。',
369
+ 'sync.title': '会话与配置同步',
370
+ 'sync.desc': '调用插件自带的同步引擎,把会话、配置与附件同步到共享目录。',
371
+ 'sync.needDir': '请先填写共享目录。',
372
+ 'sync.needMirror': '请先填写本地镜像目录。',
373
+ 'sync.enable': '自动同步',
374
+ 'sync.enable.hint': '只控制空闲、间隔、定时三种自动触发;“立即同步”不受此开关限制。',
375
+ 'sync.dir': '共享目录',
376
+ 'sync.machine': '机器标识',
377
+ 'sync.machine.hint': '留空则使用系统用户名;若与共享中已有标识冲突,同步会被拒绝。',
378
+ 'sync.machine.placeholder': '当前系统默认用户名:{id}',
379
+ 'sync.attachments': '同步附件',
380
+ 'sync.probe': '检查',
381
+ 'sync.run': '立即同步',
382
+ 'sync.run.hint': 'Ctrl+Alt+Shift+T',
383
+ 'sync.running': '正在同步…',
384
+ 'sync.done': '会话同步完成',
385
+ 'sync.never': '尚未运行。',
386
+ 'sync.last': '上次同步:{time} · {result} · {ms} ms',
387
+ 'sync.result.ok': '成功',
388
+ 'sync.result.fail': '失败',
389
+ 'sync.purged': '清理回收站 {n}',
390
+ 'sync.paths': '目录创建 {created}、失败 {failed}',
391
+ 'sync.failed': '{n} 个文件失败',
392
+ 'sync.counts': '↑ {up} · ↓ {down} · 🗑 {del}',
393
+ 'sync.transport': '传输:下载 {down}、上传 {up}',
394
+ 'sync.transportDel': '传输:下载 {down}、上传 {up}、删除 {del}',
395
+ 'sync.dirMissing': '共享目录不存在:{path}',
396
+ 'sync.log': '查看日志',
397
+ 'sync.logToggle': '点击展开或收起同步记录',
398
+ 'sync.more': '查看更多',
399
+ 'sync.historyCount': '共 {n} 次同步记录',
400
+ 'sync.logHide': '收起日志',
401
+ 'sync.failed': '同步失败:{message}',
402
+ 'switch.trash': '会话找回',
403
+ 'switch.trash.desc': '在会话菜单和本页显示会话找回入口,已删除会话保留在本机回收站。',
404
+ 'switch.search': '内容搜索',
405
+ 'switch.search.desc': '按 Ctrl+F 打开搜索面板,匹配标题与消息正文。',
406
+ 'switch.matchTitle': '匹配会话标题',
407
+ 'switch.matchBody': '匹配用户与助手消息',
408
+ 'switch.matchTools': '匹配工具输出',
409
+ 'switch.limits': '搜索范围',
410
+ 'field.retention': '已删除会话保留天数',
411
+ 'field.retention.hint': '填0表示一直保留,直到手动永久删除。',
412
+ 'trash.usage': '{count}个会话,占用{size}',
413
+ 'trash.clear': '清空回收站',
414
+ 'trash.cleared': '回收站已清空。',
415
+ 'delete.label': '删除会话',
416
+ 'delete.running': '删除会话(运行中)',
417
+ 'delete.title': '删除这个会话?',
418
+ 'delete.desc': '将删除本机会话目录、会话缓存分片,以及工作区中的引用。会话会保留在回收站,直到超过保留期。',
419
+ 'delete.confirm': '删除',
420
+ 'delete.done': '“{title}”已删除。',
421
+ 'delete.failed': '删除失败:{message}',
422
+ 'delete.blocked': '运行中的会话不可删除。',
423
+ 'move.label': '移动到工作区…',
424
+ 'hover.sessionId': '会话ID:',
425
+ 'hover.copy.title': '会话名称',
426
+ 'hover.copy.id': '会话ID',
427
+ 'hover.copy.path': '工作区路径',
428
+ 'hover.copy.done': '已复制:{label}',
429
+ 'hover.copy.failed': '复制失败:{label}',
430
+ 'move.running': '移动到工作区(运行中)',
431
+ 'move.title': '移动到工作区',
432
+ 'move.desc': '将该会话整体移入目标工作区:会话本身不变,只是工作目录改到目标目录,之后的工具调用会在那里执行。分组变化需要重启应用后完全生效。',
433
+ 'move.session': '会话:{title}',
434
+ 'move.restarting': '已移动,正在重启以应用新分组…',
435
+ 'move.current': '当前工作区:{title}',
436
+ 'move.target': '目标工作区',
437
+ 'move.empty': '没有其他工作区可移动。',
438
+ 'move.loading': '正在读取工作区…',
439
+ 'move.busy': '正在复制会话…',
440
+ 'move.confirm': '移动',
441
+ 'move.done': '已移动到“{title}”。',
442
+ 'move.failed': '移动失败:{message}',
443
+ 'trash.title': '删除会话管理',
444
+ 'trash.untitled': '未命名',
445
+ 'trash.menu': '本工作区会话找回',
446
+ 'trash.desc': '本工作区中已删除的会话,可恢复或永久删除。',
447
+ 'trash.empty': '暂无已删除的会话。',
448
+ 'trash.restore': '恢复',
449
+ 'trash.purge': '永久删除',
450
+ 'trash.purge.confirm': '确认永久删除?',
451
+ 'trash.clear': '清空回收站',
452
+ 'trash.clear.confirm': '确认清空?',
453
+ 'trash.clearWorkspace': '清空该工作区',
454
+ 'trash.clearWorkspace.confirm': '确认清空?',
455
+ 'trash.restored': '“{title}”已恢复。',
456
+ 'trash.purged': '“{title}”已永久删除。',
457
+ 'trash.loading': '正在读取…',
458
+ 'search.placeholder': '搜索会话标题与内容',
459
+ 'search.empty': '没有匹配结果。',
460
+ 'search.hint': '输入关键词搜索全部会话,回车打开选中结果。',
461
+ 'search.loading': '正在搜索…',
462
+ 'search.error': '搜索失败:{message}',
463
+ 'search.meta': '{count}个会话,{matches}处匹配',
464
+ 'search.notLocated': '已打开会话,但该处尚未加载。可点击“加载更早”后再试。',
465
+ 'search.close': '关闭搜索',
466
+ 'role.user': '你',
467
+ 'role.assistant': '助手',
468
+ 'role.tool': '工具',
469
+ 'role.title': '标题',
470
+ 'common.close': '关闭',
471
+ 'common.cancel': '取消',
472
+ 'common.retry': '重试',
473
+ },
474
+ };
475
+
476
+ const STYLES = `
477
+ .dshe-overlay{position:fixed;inset:0;z-index:2000;display:flex;justify-content:center;align-items:flex-start;pointer-events:none}
478
+ .dshe-overlay-top{z-index:2147482000}
479
+ .dshe-backdrop{position:absolute;inset:0;background:rgba(15,18,26,.42);pointer-events:auto}
480
+ .dshe-search{position:relative;pointer-events:auto;margin-top:6vh;width:min(720px,92vw);max-height:calc(100vh - 90px);display:flex;flex-direction:column;
481
+ background:var(--dsw-alias-bg-overlay,#fff);color:var(--dsw-alias-label-primary,#1b1d22);border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.12));
482
+ border-radius:14px;box-shadow:0 24px 60px rgba(0,0,0,.28);overflow:hidden;font-size:13px}
483
+ .dshe-search-head{display:flex;align-items:center;gap:8px;padding:12px 14px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.1))}
484
+ .dshe-search-icon{display:inline-flex;color:var(--dsw-alias-label-secondary,#6b7280)}
485
+ .dshe-search-input{flex:1;min-width:0;border:0;outline:0;background:transparent;color:inherit;font-size:14px;line-height:20px;font-family:inherit}
486
+ .dshe-search-input::placeholder{color:var(--dsw-alias-label-secondary,#9aa1ad)}
487
+ .dshe-results{overflow:auto;padding:6px 6px 10px;min-height:64px;max-height:calc(100vh - 220px)}
488
+ .dshe-status{padding:14px;color:var(--dsw-alias-label-secondary,#6b7280);font-size:12px}
489
+ .dshe-error{color:var(--dsw-alias-state-error-primary,#c0392b)}
490
+ .dshe-group{padding:4px 0 8px}
491
+ .dshe-group-title{display:block;width:100%;text-align:left;border:0;background:transparent;color:var(--dsw-alias-label-primary,#1b1d22);
492
+ font:inherit;font-weight:600;padding:6px 10px;border-radius:8px;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
493
+ .dshe-group-title:hover{background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.05))}
494
+ .dshe-group-meta{color:var(--dsw-alias-label-secondary,#8a919c);font-weight:400;font-size:11px;margin-left:8px}
495
+ .dshe-match{display:flex;gap:6px;width:100%;text-align:left;border:0;background:transparent;color:var(--dsw-alias-label-secondary,#4b5563);
496
+ font:inherit;padding:5px 10px 5px 18px;border-radius:8px;cursor:pointer;line-height:18px}
497
+ .dshe-match:hover,.dshe-match[data-active="true"]{background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.06))}
498
+ .dshe-role{flex:none;font-size:11px;padding:0 6px;border-radius:6px;background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.05));
499
+ color:var(--dsw-alias-label-secondary,#6b7280);height:18px;line-height:18px}
500
+ .dshe-snippet{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-primary,#2b2f36)}
501
+ .dshe-group-title{display:flex;align-items:center;gap:6px}
502
+ .dshe-group-caret{flex:none;width:12px;color:var(--dsw-alias-label-secondary,#8a919c);font-size:11px}
503
+ .dshe-group-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
504
+ .dshe-group-meta{flex:none;margin-left:0}
505
+ .dshe-match-time{flex:none;min-width:0;color:var(--dsw-alias-label-secondary,#8a919c);font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap}
506
+ .dshe-mark{background:color-mix(in srgb,var(--dsw-alias-brand-primary,#3b6ef5) 26%,transparent);color:inherit;border-radius:3px;padding:0 1px}
507
+ .dshe-section{display:flex;flex-direction:column;gap:14px;width:100%;font-size:13px}
508
+ .dshe-match-time[data-tier="1"]{min-width:52px}
509
+ .dshe-match-time[data-tier="2"]{min-width:60px}
510
+ .dshe-match-time[data-tier="3"]{min-width:88px}
511
+ .dshe-preview{position:fixed;z-index:2147482000;max-width:min(560px,46vw);max-height:46vh;overflow:auto;
512
+ background:var(--dsw-alias-bg-overlay,#fff);color:var(--dsw-alias-label-primary,#1b1d22);
513
+ border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.12));border-radius:10px;padding:10px 12px;
514
+ font-size:12px;line-height:1.6;white-space:pre-wrap;word-break:break-word;box-shadow:0 12px 32px rgba(0,0,0,.18)}
515
+ .dshe-mark-current{background:#ffd76a;color:#1b1d22;border-radius:3px;box-shadow:0 0 0 2px rgba(255,193,7,.5)}
516
+ ::highlight(dshe-flash){background-color:#ffe27a;color:#1b1d22;border-radius:3px}
517
+ .dshe-section-title{margin:0;font-size:15px;font-weight:600;color:var(--dsw-alias-label-primary,#1b1d22)}
518
+ .dshe-subsection-title{margin:4px 0 0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,#1b1d22);
519
+ padding-top:10px;border-top:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))}
520
+ .dshe-section-desc{margin:0;color:var(--dsw-alias-label-secondary,#6b7280);font-size:12px;line-height:18px}
521
+ .dshe-card{border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.1));border-radius:10px;overflow:hidden}
522
+ .dshe-row{display:flex;align-items:center;gap:12px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))}
523
+ .dshe-row:last-child{border-bottom:0}
524
+ .dshe-row-main{flex:1;min-width:0}
525
+ .dshe-row-title{font-size:13px;color:var(--dsw-alias-label-primary,#1b1d22)}
526
+ .dshe-row-desc{font-size:11px;color:var(--dsw-alias-label-secondary,#8a919c);margin-top:2px;line-height:16px}
527
+ .dshe-switch{flex:none;width:36px;height:20px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.2));
528
+ background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.08));position:relative;cursor:pointer;padding:0}
529
+ .dshe-switch[aria-checked="true"]{background:var(--dsw-alias-brand-primary,#3b6ef5);border-color:transparent}
530
+ .dshe-switch span{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:var(--dsw-alias-label-primary,#1b1d22);transition:transform .12s ease,background .12s ease}
531
+ .dshe-switch[aria-checked="true"] span{transform:translateX(16px);background:#fff}
532
+ .dshe-number{flex:none;width:72px;padding:4px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.2));
533
+ background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary,#1b1d22);font:inherit;font-size:12px}
534
+ .dshe-text{flex:none;width:240px;max-width:46vw;padding:4px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.2));
535
+ background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary,#1b1d22);font:inherit;font-size:12px}
536
+ .dshe-sync-log{max-height:220px;overflow:auto;margin:0;padding:8px 10px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.05));
537
+ color:var(--dsw-alias-label-secondary,#4b5563);font-size:11px;line-height:16px;white-space:pre-wrap;word-break:break-all;font-family:var(--ds-font-family-code,monospace)}
538
+ font-family:var(--ds-font-family-code,monospace);font-size:11px;line-height:18px;color:var(--dsw-alias-label-secondary,#4b5563);word-break:break-all}
539
+ .dshe-counts{display:inline-flex;align-items:center;gap:1px}
540
+ .dshe-log-body{display:block;white-space:normal}
541
+ .dshe-log-line{display:flex;align-items:baseline;line-height:18px}
542
+ .dshe-log-label{flex:0 0 5em;text-align:justify;text-align-last:justify;text-justify:inter-character;white-space:nowrap}
543
+ .dshe-log-colon{flex:0 0 auto;margin:0 1px}
544
+ .dshe-log-text{flex:1 1 auto;white-space:pre-wrap;word-break:break-all}
545
+ .dshe-log-line-plain{display:block;padding-left:0.6em;color:var(--dsw-alias-label-secondary,#6b7280)}
546
+ .dshe-log-line-more{cursor:pointer}
547
+ .dshe-log-line-more:hover .dshe-log-text{color:var(--dsw-alias-label-primary,#1b1d22)}
548
+ .dshe-log-more{margin-left:4px;opacity:.55;font-size:10px}
549
+ .dshe-log-files{margin:2px 0 4px 5.6em;padding-left:6px;border-left:2px solid var(--dsw-alias-border-l1,rgba(0,0,0,.12))}
550
+ .dshe-log-file{font-family:var(--ds-font-family-code,monospace);font-size:10px;line-height:15px;color:var(--dsw-alias-label-secondary,#6b7280);word-break:break-all}
551
+ .dshe-log-line-sub .dshe-log-label{text-align:right;text-align-last:auto;color:var(--dsw-alias-label-secondary,#6b7280)}
552
+ .dshe-log-list{display:flex;flex-direction:column;gap:4px;align-items:stretch}
553
+ .dshe-log-scroll{max-height:42vh;overflow-y:auto;overflow-x:hidden;padding-right:2px;flex:0 0 auto}
554
+ .dshe-log-toggle{background:none;border:0;padding:0;margin:0;text-align:left;cursor:pointer;font:inherit;color:inherit;display:block;width:100%}
555
+ .dshe-log-toggle:hover{color:var(--dsw-alias-label-primary,#1b1d22)}
556
+ .dshe-log-item{border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08));border-radius:8px;overflow:hidden;flex:0 0 auto}
557
+ .dshe-log-row{display:flex;align-items:center;justify-content:space-between;gap:8px;width:100%;padding:6px 10px;
558
+ background:transparent;border:0;cursor:pointer;text-align:left;font-size:11px;line-height:16px;
559
+ color:var(--dsw-alias-label-secondary,#4b5563);font-family:var(--ds-font-family-code,monospace)}
560
+ .dshe-log-row:hover{background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.04))}
561
+ .dshe-log-row-open{color:var(--dsw-alias-label-primary,#1b1d22)}
562
+ .dshe-log-caret{opacity:.6}
563
+ .dshe-log-item .dshe-sync-log{border-radius:0;margin:0}
564
+ .dshe-hint{font-size:11px;color:var(--dsw-alias-label-secondary,#8a919c);padding:0 12px 10px}
565
+ .dshe-trash-body{max-height:46vh;overflow:auto;display:flex;flex-direction:column;gap:12px;min-height:80px}
566
+ .dshe-trash-group-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:2px 0 6px}
567
+ .dshe-trash-group-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#6b7280);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
568
+ .dshe-trash-group-actions{display:inline-flex;gap:6px;flex:none}
569
+ .dshe-link-danger{border:0;background:transparent;padding:0;font:inherit;font-size:11px;color:var(--dsw-alias-state-error-primary,#c0392b);cursor:pointer;flex:none}
570
+ .dshe-link-danger:hover{text-decoration:underline}
571
+ .dshe-link-danger[disabled]{opacity:.5;cursor:default;text-decoration:none}
572
+ background:var(--dsw-alias-bg-overlay,#fff);border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.12));
573
+ box-shadow:0 10px 30px rgba(0,0,0,.18);display:flex;flex-direction:column;gap:2px}
574
+ font:inherit;font-size:12px;padding:7px 10px;border-radius:6px;cursor:pointer}
575
+ .dshe-move-list{display:flex;flex-direction:column;gap:6px;max-height:40vh;overflow:auto}
576
+ .dshe-move-item{display:flex;align-items:flex-start;gap:8px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.1));border-radius:8px;cursor:pointer}
577
+ .dshe-move-item[data-active="true"]{border-color:var(--dsw-alias-brand-primary,#3b6ef5);background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.04))}
578
+ .dshe-move-item input{margin-top:2px;flex:none}
579
+ .dshe-move-main{display:flex;flex-direction:column;gap:2px;min-width:0}
580
+ .dshe-move-title{font-size:13px;color:var(--dsw-alias-label-primary,#1b1d22);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
581
+ .dshe-move-meta{font-size:11px;color:var(--dsw-alias-label-secondary,#8a919c);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
582
+ .dshe-trash-row{display:flex;align-items:center;gap:10px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.1));border-radius:8px}
583
+ .dshe-trash-main{flex:1;min-width:0}
584
+ .dshe-trash-title{font-size:13px;color:var(--dsw-alias-label-primary,#1b1d22);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
585
+ .dshe-trash-id{font-family:var(--ds-font-family-code,monospace);font-size:10px;line-height:14px;color:var(--dsw-alias-label-secondary,#8a919c);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
586
+ .dshe-trash-meta{font-size:11px;color:var(--dsw-alias-label-secondary,#8a919c);margin-top:2px}
587
+ .dshe-action{border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.2));background:transparent;color:var(--dsw-alias-label-primary,#1b1d22);
588
+ font:inherit;font-size:12px;padding:4px 10px;border-radius:8px;cursor:pointer}
589
+ .dshe-action:hover{background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.06))}
590
+ .dshe-action-active:hover,.dshe-action-active:focus-visible{background:var(--dsw-alias-brand-primary,#3b6ef5);color:#fff;filter:brightness(1.1)}
591
+ .dshe-action-danger:hover,.dshe-action-danger:focus-visible{background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#c0392b) 12%,transparent)}
592
+ .dshe-action[disabled]{opacity:.5;cursor:default}
593
+ .dshe-presets{display:flex;flex-direction:column;gap:6px;padding:6px 0 2px}
594
+ .dshe-presets-head{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary,#1b1d22)}
595
+ .dshe-presets-chips{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
596
+ .dshe-select{border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.2));background:var(--dsw-alias-bg-overlay,#fff);
597
+ color:var(--dsw-alias-label-primary,#1b1d22);font:inherit;font-size:12px;padding:4px 8px;border-radius:8px;min-width:160px}
598
+ .dshe-preset-chip{display:inline-flex;align-items:center;gap:4px}
599
+ .dshe-action-active{background:var(--dsw-alias-brand-primary,#3b6ef5);color:#fff;border-color:transparent}
600
+ .dshe-action-danger{color:var(--dsw-alias-state-error-primary,#c0392b);border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary,#c0392b) 45%,transparent)}
601
+ .dshe-toast{position:static;pointer-events:auto;z-index:2010;
602
+ background:rgba(24,26,30,.96);color:#fff;border:1px solid rgba(255,255,255,.18);
603
+ border-radius:14px;padding:10px 18px;font-size:13px;line-height:1.5;
604
+ box-shadow:0 18px 40px rgba(0,0,0,.38);max-width:70vw;user-select:none}
605
+ .dshe-toast[data-kind="error"]{color:#ff4600}
606
+ .dshe-toast-spinner{display:inline-block;width:14px;height:14px;margin-left:8px;vertical-align:-2px;
607
+ animation:dshe-toast-spin .8s linear infinite}
608
+ @keyframes dshe-toast-spin{to{transform:rotate(360deg)}}
609
+ `;
610
+
611
+ // ── store ────────────────────────────────────────────────────────────────
612
+
613
+ function createStore() {
614
+ let state = {
615
+ ready: false,
616
+ settings: { ...DEFAULTS },
617
+ toast: null,
618
+ search: { open: false, query: '', status: 'idle', groups: [], error: null, tookMs: 0, truncated: false, scanned: 0 },
619
+ trash: { open: false, loading: false, groups: [], error: null, busy: null, confirmPurge: null, confirmClear: false, confirmWorkspace: null, count: 0, size: 0, scopeSession: null, scopeWorkspace: null },
620
+ pendingDelete: null,
621
+ deleteBusy: false,
622
+ deleteError: null,
623
+ move: { open: false, sessionId: null, title: '', loading: false, current: null, workspaces: [], targetId: null, error: null, busy: false },
624
+ sync: { loading: false, busy: false, target: null, state: null, error: null, showLog: false, webdav: null, webdavBusy: false, history: [], historyOpen: null, historyLimit: 20, auto: null },
625
+ overwrite: { open: false, direction: 'cloud', busy: false, preview: null, error: null },
626
+ restartConfirm: false,
627
+ syncLive: false,
628
+ syncDone: false,
629
+ restartCountdown: null,
630
+ presetEdit: null,
631
+ presetReplace: null,
632
+ pauseOpen: false,
633
+ pauseShownAt: null,
634
+ envCheck: { busy: false, open: false, result: null, reportPath: null },
635
+ updatePrompt: { open: false, appVersion: null, lastAppVersion: null },
636
+ };
637
+ const listeners = new Set();
638
+ let toastTimer = null;
639
+ let searchTimer = null;
640
+ let searchController = null;
641
+ let searchSeq = 0;
642
+
643
+ /** Saved setups match only when all four connection fields agree. */
644
+ function matchesPreset(item, settings) {
645
+ const trim = (value) => String(value ?? '').trim().replace(/[\\/]+$/u, '');
646
+ return trim(item.url) === trim(settings.webdavUrl)
647
+ && String(item.user ?? '').trim() === String(settings.webdavUser ?? '').trim()
648
+ && String(item.password ?? '') === String(settings.webdavPassword ?? '')
649
+ && trim(item.root) === trim(settings.webdavRoot);
650
+ }
651
+
652
+ let restartCountdownTimer = null;
653
+
654
+ const store = {
655
+ get: () => state,
656
+ subscribe(listener) {
657
+ listeners.add(listener);
658
+ return () => listeners.delete(listener);
659
+ },
660
+ set(patch) {
661
+ state = { ...state, ...patch };
662
+ for (const listener of listeners) listener();
663
+ },
664
+ patchSearch(patch) {
665
+ store.set({ search: { ...state.search, ...patch } });
666
+ },
667
+ patchTrash(patch) {
668
+ store.set({ trash: { ...state.trash, ...patch } });
669
+ },
670
+ patchTrashState(patch) {
671
+ store.patchTrash(patch);
672
+ },
673
+ toast(kind, text) {
674
+ if (toastTimer !== null) clearTimeout(toastTimer);
675
+ toastTimer = null;
676
+ store.set({ toast: { kind, text, id: Date.now() } });
677
+ toastTimer = setTimeout(() => store.set({ toast: null }), kind === 'error' ? 5000 : 3000);
678
+ },
679
+ /** A notice that stays until the work finishes; the spinner shows progress. */
680
+ toastBusy(text) {
681
+ if (toastTimer !== null) {
682
+ clearTimeout(toastTimer);
683
+ toastTimer = null;
684
+ }
685
+ store.set({ toast: { kind: 'info', text, spinner: true, id: Date.now() } });
686
+ },
687
+ /** Remove the sticky notice once the work has an answer of its own. */
688
+ clearToast() {
689
+ if (toastTimer !== null) {
690
+ clearTimeout(toastTimer);
691
+ toastTimer = null;
692
+ }
693
+ store.set({ toast: null });
694
+ },
695
+ async init() {
696
+ try {
697
+ const data = await runtime.rpc('state');
698
+ store.set({
699
+ ready: true,
700
+ settings: { ...DEFAULTS, ...data.settings },
701
+ trash: { ...state.trash, count: Number(data.count) || 0, size: Number(data.size) || 0 },
702
+ });
703
+ } catch (error) {
704
+ store.set({ ready: true });
705
+ console.warn('[dsh-enhanced] initial state failed:', error);
706
+ }
707
+ // Launch-time catch-up: runs regardless of the automatic sync switch.
708
+ window.setTimeout(() => { void store.startupSync(); }, 2000);
709
+ // Follow the automatic sync only; the manual one has its own notice.
710
+ // The call waits until the run flips, so there is no polling timer.
711
+ void store.watchSyncState();
712
+ },
713
+ /**
714
+ * Sync once shortly after launch, reusing the normal run path.
715
+ *
716
+ * Doing it here (instead of on the host) means a restart that follows can
717
+ * show its countdown in the UI first.
718
+ */
719
+ async startupSync() {
720
+ // Launch-time catch-up: unconditional on the sync switch, but it must not
721
+ // run while a turn is in progress.
722
+ if (store.get().sync.busy === true) return;
723
+ // The composer status line follows the launch run just like a manual one.
724
+ store.set({ sync: { ...store.get().sync, busy: true, error: null }, syncDone: false });
725
+ try {
726
+ const data = await runtime.rpc('sync.run', { quiet: true });
727
+ if (data?.skipped === 'busy') {
728
+ store.set({ sync: { ...store.get().sync, busy: false } });
729
+ return;
730
+ }
731
+ store.set({
732
+ sync: { ...store.get().sync, busy: false, state: data, error: null },
733
+ syncDone: data?.ok !== false,
734
+ });
735
+ await store.loadSync();
736
+ const pulled = Number(data?.summary?.sessions?.pulled) || Number(data?.summary?.sessions?.created) || 0;
737
+ const repaired = Number(data?.summary?.blankGuard?.repaired) || 0;
738
+ const archiveChanged = Number(data?.summary?.archive?.changed) || 0;
739
+ if (pulled > 0 || repaired > 0 || archiveChanged > 0) store.restartSoon('restart.reason.sync');
740
+ } catch (error) {
741
+ store.set({ sync: { ...store.get().sync, busy: false } });
742
+ console.warn('[dsh-enhanced] startup sync failed:', error);
743
+ }
744
+ },
745
+ async refreshCount() {
746
+ try {
747
+ const data = await runtime.rpc('state');
748
+ store.patchTrash({ count: Number(data.count) || 0, size: Number(data.size) || 0 });
749
+ store.set({ settings: { ...DEFAULTS, ...data.settings } });
750
+ } catch {
751
+ // The badge is decorative; a failed refresh changes nothing.
752
+ }
753
+ },
754
+ async saveSettings(rawPatch) {
755
+ // Master/sub switch coupling:
756
+ // master off + any sub turned on -> master on
757
+ // master turned off -> every sub off
758
+ // master turned on -> subs keep their state
759
+ const patch = { ...rawPatch };
760
+ if (Object.prototype.hasOwnProperty.call(patch, 'syncEnabled')) {
761
+ if (patch.syncEnabled !== true) {
762
+ patch.syncOnIdle = false;
763
+ patch.syncIntervalMinutes = 0;
764
+ patch.syncDailyAt = '';
765
+ }
766
+ } else {
767
+ const merged = { ...state.settings, ...patch };
768
+ const anySub = merged.syncOnIdle === true
769
+ || Number(merged.syncIntervalMinutes) > 0
770
+ || (typeof merged.syncDailyAt === 'string' && merged.syncDailyAt.trim() !== '');
771
+ if (anySub && merged.syncEnabled !== true) patch.syncEnabled = true;
772
+ }
773
+ const next = { ...state.settings, ...patch };
774
+ store.set({ settings: next });
775
+ try {
776
+ const data = await runtime.rpc('settings.set', { patch });
777
+ store.set({ settings: { ...DEFAULTS, ...data.settings } });
778
+ } catch (error) {
779
+ store.toast('error', String(error?.message ?? error));
780
+ await store.init();
781
+ }
782
+ },
783
+ openSearch() {
784
+ store.patchSearch({ open: true });
785
+ const query = state.search.query;
786
+ if (query.trim() !== '' && state.search.status === 'idle') store.runSearch(query);
787
+ },
788
+ closeSearch() {
789
+ if (searchTimer !== null) clearTimeout(searchTimer);
790
+ searchTimer = null;
791
+ if (searchController !== null) searchController.abort();
792
+ searchController = null;
793
+ store.patchSearch({ open: false, status: 'idle' });
794
+ },
795
+ setQuery(query) {
796
+ store.patchSearch({ query });
797
+ if (searchTimer !== null) clearTimeout(searchTimer);
798
+ if (query.trim() === '') {
799
+ if (searchController !== null) searchController.abort();
800
+ searchController = null;
801
+ store.patchSearch({ status: 'idle', groups: [], error: null, scanned: 0 });
802
+ return;
803
+ }
804
+ searchTimer = setTimeout(() => {
805
+ searchTimer = null;
806
+ store.runSearch(query);
807
+ }, 220);
808
+ },
809
+ async runSearch(query) {
810
+ const seq = ++searchSeq;
811
+ if (searchController !== null) searchController.abort();
812
+ const controller = new AbortController();
813
+ searchController = controller;
814
+ store.patchSearch({ status: 'loading', error: null });
815
+ try {
816
+ const data = await runtime.rpc('search', { query }, controller.signal);
817
+ if (seq !== searchSeq) return;
818
+ store.patchSearch({
819
+ status: 'done',
820
+ groups: Array.isArray(data.groups) ? data.groups : [],
821
+ error: null,
822
+ tookMs: Number(data.tookMs) || 0,
823
+ truncated: data.truncated === true,
824
+ scanned: Number(data.scanned) || 0,
825
+ });
826
+ } catch (error) {
827
+ if (seq !== searchSeq || controller.signal.aborted) return;
828
+ store.patchSearch({ status: 'error', error: String(error?.message ?? error), groups: [] });
829
+ } finally {
830
+ if (searchController === controller) searchController = null;
831
+ }
832
+ },
833
+ requestDelete(sessionId, title, running) {
834
+ store.set({ pendingDelete: { sessionId, title, running: running === true }, deleteError: null, deleteBusy: false });
835
+ },
836
+ cancelDelete() {
837
+ if (state.deleteBusy) return;
838
+ store.set({ pendingDelete: null, deleteError: null });
839
+ },
840
+ async confirmDelete() {
841
+ const pending = state.pendingDelete;
842
+ if (pending === null) return;
843
+ store.set({ deleteBusy: true, deleteError: null });
844
+ try {
845
+ const data = await runtime.rpc('session.delete', { sessionId: pending.sessionId });
846
+ store.set({ pendingDelete: null, deleteBusy: false });
847
+ store.toast('success', runtime.t('delete.done', { title: data?.title ?? pending.title }));
848
+ await store.refreshCount();
849
+ store.restartApp();
850
+ } catch (error) {
851
+ store.set({ deleteBusy: false, deleteError: String(error?.message ?? error) });
852
+ }
853
+ },
854
+ async openTrash() {
855
+ store.patchTrash({ open: true, loading: true, error: null, scopeSession: null, scopeWorkspace: null, confirmPurge: null, confirmClear: false, confirmWorkspace: null });
856
+ await store.loadTrash();
857
+ },
858
+ async openTrashForSession(sessionId) {
859
+ store.patchTrash({ open: true, loading: true, error: null, scopeSession: sessionId, scopeWorkspace: null, confirmPurge: null, confirmClear: false, confirmWorkspace: null });
860
+ await store.loadTrash();
861
+ },
862
+ closeTrash() {
863
+ if (state.trash.busy !== null) return;
864
+ store.patchTrash({ open: false, confirmPurge: null, confirmClear: false, confirmWorkspace: null, scopeSession: null, scopeWorkspace: null });
865
+ },
866
+ async loadTrash() {
867
+ store.patchTrash({ loading: true, error: null });
868
+ try {
869
+ const scope = { sessionId: state.trash.scopeSession, workspaceId: state.trash.scopeWorkspace };
870
+ const data = await runtime.rpc('trash.list', scope);
871
+ store.patchTrash({
872
+ loading: false,
873
+ groups: Array.isArray(data.groups) ? data.groups : [],
874
+ count: Number(data.count) || 0,
875
+ size: Number(data.size) || 0,
876
+ });
877
+ } catch (error) {
878
+ store.patchTrash({ loading: false, error: String(error?.message ?? error) });
879
+ }
880
+ },
881
+ requestPurge(sessionId) {
882
+ store.patchTrash({ confirmPurge: sessionId, confirmClear: false, confirmWorkspace: null });
883
+ },
884
+ async restore(sessionId, title) {
885
+ store.patchTrash({ busy: sessionId });
886
+ try {
887
+ const data = await runtime.rpc('trash.restore', { sessionId });
888
+ await store.loadTrash();
889
+ const warning = typeof data?.warning === 'string' && data.warning !== '' ? data.warning : null;
890
+ store.toast(warning === null ? 'success' : 'info', warning ?? runtime.t('trash.restored', { title }));
891
+ store.patchTrash({ open: false, confirmPurge: null, confirmClear: false });
892
+ if (typeof data?.workspaceId === 'string' && data.workspaceId !== '') {
893
+ await runtime.refreshWorkspace(data.workspaceId);
894
+ }
895
+ store.restartApp();
896
+ } catch (error) {
897
+ store.toast('error', String(error?.message ?? error));
898
+ } finally {
899
+ store.patchTrash({ busy: null });
900
+ }
901
+ },
902
+ async purge(sessionId, title) {
903
+ store.patchTrash({ busy: sessionId, confirmPurge: null });
904
+ try {
905
+ await runtime.rpc('trash.purge', { sessionId });
906
+ await store.loadTrash();
907
+ store.toast('success', runtime.t('trash.purged', { title }));
908
+ } catch (error) {
909
+ store.toast('error', String(error?.message ?? error));
910
+ } finally {
911
+ store.patchTrash({ busy: null });
912
+ }
913
+ },
914
+ requestClear() {
915
+ store.patchTrash({ confirmClear: true, confirmPurge: null, confirmWorkspace: null });
916
+ },
917
+ async clearTrash() {
918
+ store.patchTrash({ busy: '*', confirmClear: false });
919
+ try {
920
+ await runtime.rpc('trash.clear');
921
+ await store.loadTrash();
922
+ store.toast('success', runtime.t('trash.cleared'));
923
+ } catch (error) {
924
+ store.toast('error', String(error?.message ?? error));
925
+ } finally {
926
+ store.patchTrash({ busy: null });
927
+ }
928
+ },
929
+ requestClearWorkspace(workspaceId) {
930
+ store.patchTrash({ confirmWorkspace: workspaceId, confirmClear: false, confirmPurge: null });
931
+ }, async clearWorkspace(workspaceId) {
932
+ store.patchTrash({ busy: workspaceId, confirmWorkspace: null });
933
+ try {
934
+ const data = await runtime.rpc('trash.clear', { workspaceId });
935
+ await store.loadTrash();
936
+ store.toast('success', `${runtime.t('trash.clearWorkspace')} · ${String(Number(data?.removed) || 0)}`);
937
+ } catch (error) {
938
+ store.toast('error', String(error?.message ?? error));
939
+ } finally {
940
+ store.patchTrash({ busy: null });
941
+ }
942
+ },
943
+ async openMove(sessionId, title) {
944
+ store.set({
945
+ move: {
946
+ open: true,
947
+ sessionId,
948
+ title: title === '' ? '未命名会话' : title,
949
+ loading: true,
950
+ current: null,
951
+ workspaces: [],
952
+ targetId: null,
953
+ error: null,
954
+ busy: false,
955
+ },
956
+ });
957
+ try {
958
+ const data = await runtime.rpc('workspace.candidates', { sessionId });
959
+ const workspaces = Array.isArray(data.workspaces) ? data.workspaces : [];
960
+ store.set({
961
+ move: { ...state.move, loading: false, current: data.current ?? null, workspaces, targetId: workspaces[0]?.id ?? null },
962
+ });
963
+ } catch (error) {
964
+ store.set({ move: { ...state.move, loading: false, error: String(error?.message ?? error) } });
965
+ }
966
+ },
967
+ closeMove() {
968
+ if (state.move.busy) return;
969
+ store.set({ move: { ...state.move, open: false } });
970
+ },
971
+ setMoveTarget(targetId) {
972
+ store.set({ move: { ...state.move, targetId } });
973
+ },
974
+ async confirmMove() {
975
+ const move = state.move;
976
+ if (move.busy || move.targetId === null) return;
977
+ store.set({ move: { ...move, busy: true, error: null } });
978
+ try {
979
+ const data = await runtime.rpc('session.move', { sessionId: move.sessionId, workspaceId: move.targetId });
980
+ const target = move.workspaces.find((workspace) => workspace.id === move.targetId);
981
+ store.set({ move: { ...state.move, open: false, busy: false } });
982
+ const warning = typeof data?.warning === 'string' && data.warning !== '' ? data.warning : null;
983
+ store.toast(warning === null ? 'success' : 'info', warning ?? runtime.t('move.done', { title: target?.title ?? '' }));
984
+ await store.refreshCount();
985
+ if (data?.needsRestart === true) store.restartSoon('restart.reason.move');
986
+ } catch (error) {
987
+ store.set({ move: { ...state.move, busy: false, error: String(error?.message ?? error) } });
988
+ }
989
+ },
990
+ async loadSync() {
991
+ try {
992
+ const data = await runtime.rpc('sync.state');
993
+ const auto = data?.auto ?? null;
994
+ if (auto?.paused === true && auto.pausedAt !== null && auto.pausedAt !== state.pauseShownAt) {
995
+ store.set({ pauseOpen: true, pauseShownAt: auto.pausedAt });
996
+ }
997
+ store.set({
998
+ sync: {
999
+ ...state.sync,
1000
+ loading: false,
1001
+ error: null,
1002
+ target: data?.target ?? null,
1003
+ state: data?.state ?? null,
1004
+ auto,
1005
+ history: Array.isArray(data?.history) ? data.history : [],
1006
+ },
1007
+ });
1008
+ } catch (error) {
1009
+ store.set({ sync: { ...state.sync, loading: false, error: String(error?.message ?? error) } });
1010
+ }
1011
+ },
1012
+ /**
1013
+ * Wait for the AUTOMATIC sync to start or stop, then wait again.
1014
+ *
1015
+ * The host resolves the call when the run flips (or after 25 s), so the
1016
+ * badge updates at once and the idle cost is one open request.
1017
+ */
1018
+ async watchSyncState() {
1019
+ let lastUserSeq = null;
1020
+ for (;;) {
1021
+ try {
1022
+ const data = await runtime.rpc('sync.watch');
1023
+ // A new user message (in any session) is the send signal the host sees.
1024
+ if (Number.isFinite(data?.userSeq)) {
1025
+ if (lastUserSeq === null) lastUserSeq = data.userSeq;
1026
+ else if (data.userSeq > lastUserSeq) {
1027
+ lastUserSeq = data.userSeq;
1028
+ if (store.get().syncDone === true) store.set({ syncDone: false });
1029
+ }
1030
+ }
1031
+ const running = data?.auto?.running === true;
1032
+ const wasRunning = store.get().syncLive === true;
1033
+ if (running) {
1034
+ store.set({ syncLive: true, syncDone: false });
1035
+ } else if (wasRunning) {
1036
+ // The run just finished: keep a short "done" line until a click.
1037
+ store.set({ syncLive: false, syncDone: true });
1038
+ } else {
1039
+ store.set({ syncLive: false });
1040
+ }
1041
+ } catch {
1042
+ // A dropped connection only means a short pause before retrying.
1043
+ await new Promise((resolve) => { window.setTimeout(resolve, 3000); });
1044
+ }
1045
+ }
1046
+ },
1047
+ async probeSync() {
1048
+ if (state.sync.busy) return;
1049
+ store.set({ sync: { ...state.sync, busy: true, error: null } });
1050
+ try {
1051
+ const data = await runtime.rpc('sync.probe');
1052
+ store.set({
1053
+ sync: { ...state.sync, busy: false, state: data, error: data?.ok === false ? String(data?.summary?.error ?? runtime.t('sync.result.fail')) : null },
1054
+ });
1055
+ } catch (error) {
1056
+ store.set({ sync: { ...state.sync, busy: false, error: String(error?.message ?? error) } });
1057
+ }
1058
+ },
1059
+ async runSyncNow() {
1060
+ if (state.sync.busy) return;
1061
+ store.set({ sync: { ...state.sync, busy: true, error: null }, syncDone: false });
1062
+ store.toastBusy(runtime.t('sync.running'));
1063
+ try {
1064
+ const data = await runtime.rpc('sync.run');
1065
+ store.clearToast();
1066
+ store.set({
1067
+ sync: { ...state.sync, busy: false, state: data, error: null },
1068
+ syncDone: data?.ok !== false,
1069
+ });
1070
+ store.toast(
1071
+ data?.ok === false ? 'error' : 'success',
1072
+ data?.ok === false
1073
+ ? runtime.t('sync.failed', { message: String(data?.summary?.error ?? data?.exitCode ?? '?') })
1074
+ : runtime.t('sync.result.ok'),
1075
+ );
1076
+ await store.loadSync();
1077
+ const pulled = Number(data?.summary?.sessions?.pulled) || Number(data?.summary?.sessions?.created) || 0;
1078
+ const repaired = Number(data?.summary?.blankGuard?.repaired) || 0;
1079
+ const archiveChanged = Number(data?.summary?.archive?.changed) || 0;
1080
+ if (pulled > 0 || repaired > 0 || archiveChanged > 0) {
1081
+ store.restartSoon('restart.reason.sync');
1082
+ }
1083
+ } catch (error) {
1084
+ store.clearToast();
1085
+ store.set({ sync: { ...state.sync, busy: false, error: String(error?.message ?? error) } });
1086
+ store.toast('error', String(error?.message ?? error));
1087
+ await store.loadSync();
1088
+ }
1089
+ },
1090
+ /**
1091
+ * Announce an automatic restart, counting down from three, then restart.
1092
+ */
1093
+ restartSoon(reasonKey) {
1094
+ if (restartCountdownTimer !== null) return;
1095
+ const reason = runtime.t(reasonKey);
1096
+ let left = 3;
1097
+ const tick = () => {
1098
+ store.toast('info', runtime.t('restart.auto', { reason, seconds: String(left) }));
1099
+ if (left === 0) {
1100
+ window.clearInterval(restartCountdownTimer);
1101
+ restartCountdownTimer = null;
1102
+ store.set({ restartCountdown: null });
1103
+ store.restartApp();
1104
+ return;
1105
+ }
1106
+ store.set({ restartCountdown: left });
1107
+ left -= 1;
1108
+ };
1109
+ tick();
1110
+ restartCountdownTimer = window.setInterval(tick, 1000);
1111
+ },
1112
+ /** Restart the app so a structural change becomes visible. */
1113
+ restartApp() {
1114
+ window.setTimeout(() => {
1115
+ void runtime.rpc('app.restart').catch((error) => {
1116
+ const message = String(error?.message ?? error);
1117
+ // The host refuses while a turn is running; say so instead of
1118
+ // looking like the button did nothing.
1119
+ store.toast('error', message.includes('restart-busy')
1120
+ ? runtime.t('restart.busy')
1121
+ : message);
1122
+ });
1123
+ }, 400);
1124
+ },
1125
+ openRestart() {
1126
+ store.set({ restartConfirm: true });
1127
+ },
1128
+ startPresetRename() {
1129
+ const settings = state.settings ?? {};
1130
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1131
+ const active = presets.find((item) => matchesPreset(item, settings)) ?? null;
1132
+ if (active === null) return;
1133
+ store.set({ presetEdit: { mode: 'rename', id: active.id, name: active.name } });
1134
+ },
1135
+ startPresetSave() {
1136
+ const settings = state.settings ?? {};
1137
+ const url = String(settings.webdavUrl ?? '').trim();
1138
+ if (url === '') return;
1139
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1140
+ if (presets.length >= 3) {
1141
+ store.set({ presetReplace: { open: true } });
1142
+ return;
1143
+ }
1144
+ store.set({ presetEdit: { mode: 'save', id: null, name: '' } });
1145
+ },
1146
+ startPresetModify() {
1147
+ const settings = state.settings ?? {};
1148
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1149
+ const active = presets.find((item) => matchesPreset(item, settings)) ?? null;
1150
+ if (active === null) return;
1151
+ store.set({ presetEdit: { mode: 'modify', id: active.id, name: active.name } });
1152
+ },
1153
+ commitPresetModify() {
1154
+ const current = state.presetEdit;
1155
+ if (current === null) return;
1156
+ const settings = state.settings ?? {};
1157
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1158
+ const list = presets.map((item) => (item.id === current.id
1159
+ ? {
1160
+ ...item,
1161
+ url: settings.webdavUrl ?? '',
1162
+ user: settings.webdavUser ?? '',
1163
+ password: settings.webdavPassword ?? '',
1164
+ root: settings.webdavRoot ?? '',
1165
+ }
1166
+ : item));
1167
+ store.set({ presetEdit: null });
1168
+ void runtime.store.saveSettings({ webdavProfiles: list })
1169
+ .then(() => runtime.store.toast('success', runtime.t('sync.webdav.presets.updated', { name: current.name })))
1170
+ .catch((error) => runtime.store.toast('error', String(error?.message ?? error)));
1171
+ },
1172
+ closePresetReplace() {
1173
+ store.set({ presetReplace: null });
1174
+ },
1175
+ confirmPresetReplace(id) {
1176
+ const settings = state.settings ?? {};
1177
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1178
+ const list = presets.map((item) => (item.id === id
1179
+ ? {
1180
+ ...item,
1181
+ url: settings.webdavUrl ?? '',
1182
+ user: settings.webdavUser ?? '',
1183
+ password: settings.webdavPassword ?? '',
1184
+ root: settings.webdavRoot ?? '',
1185
+ custom: true,
1186
+ }
1187
+ : item));
1188
+ store.set({ presetReplace: null });
1189
+ void runtime.store.saveSettings({ webdavProfiles: list })
1190
+ .then(() => runtime.store.toast('success', runtime.t('sync.webdav.presets.replaced')))
1191
+ .catch((error) => runtime.store.toast('error', String(error?.message ?? error)));
1192
+ },
1193
+ setPresetName(name) {
1194
+ const current = state.presetEdit;
1195
+ if (current === null) return;
1196
+ store.set({ presetEdit: { ...current, name } });
1197
+ },
1198
+ cancelPresetEdit() {
1199
+ store.set({ presetEdit: null });
1200
+ },
1201
+ dropActivePreset() {
1202
+ const settings = state.settings ?? {};
1203
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1204
+ const active = presets.find((item) => matchesPreset(item, settings)) ?? null;
1205
+ if (active === null) return;
1206
+ const rest = presets.filter((item) => item.id !== active.id);
1207
+ const next = rest[0];
1208
+ void runtime.store.saveSettings(next === undefined
1209
+ ? { webdavProfiles: rest }
1210
+ : { webdavProfiles: rest, webdavUrl: next.url, webdavUser: next.user, webdavPassword: next.password, webdavRoot: next.root });
1211
+ },
1212
+ commitPresetEdit() {
1213
+ const current = state.presetEdit;
1214
+ if (current === null) return;
1215
+ let name = String(current.name ?? '').trim();
1216
+ if (name === '') {
1217
+ const url = String(state.settings?.webdavUrl ?? '').trim();
1218
+ let host = 'WebDAV';
1219
+ try { host = new URL(url).host; } catch { host = url.replace(/^https?:\/\//u, '').split('/')[0] || 'WebDAV'; }
1220
+ const root = String(state.settings?.webdavRoot ?? '').trim();
1221
+ name = root === '' || root === '/' ? host : `${host} · ${root}`;
1222
+ }
1223
+ const settings = state.settings ?? {};
1224
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
1225
+ if (current.mode === 'rename') {
1226
+ const list = presets.map((item) => (item.id === current.id ? { ...item, name, custom: true } : item));
1227
+ store.set({ presetEdit: null });
1228
+ void runtime.store.saveSettings({ webdavProfiles: list });
1229
+ return;
1230
+ }
1231
+ const entry = {
1232
+ id: `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`,
1233
+ name,
1234
+ url: settings.webdavUrl ?? '',
1235
+ user: settings.webdavUser ?? '',
1236
+ password: settings.webdavPassword ?? '',
1237
+ root: settings.webdavRoot ?? '',
1238
+ custom: true,
1239
+ };
1240
+ if (presets.length >= 3) {
1241
+ runtime.store.toast('error', runtime.t('sync.webdav.presets.full'));
1242
+ return;
1243
+ }
1244
+ store.set({ presetEdit: null });
1245
+ void runtime.store.saveSettings({ webdavProfiles: [...presets, entry] })
1246
+ .then(() => runtime.store.toast('success', runtime.t('sync.webdav.presets.saved', { name })))
1247
+ .catch((error) => runtime.store.toast('error', String(error?.message ?? error)));
1248
+ },
1249
+ closeRestart() {
1250
+ store.set({ restartConfirm: false });
1251
+ },
1252
+ confirmRestart() {
1253
+ store.set({ restartConfirm: false });
1254
+ store.restartApp();
1255
+ },
1256
+ openOverwrite(direction) {
1257
+ store.set({ overwrite: { open: true, direction, busy: false, preview: null, error: null } });
1258
+ },
1259
+ closeOverwrite() {
1260
+ if (state.overwrite.busy === true) return;
1261
+ store.set({ overwrite: { ...state.overwrite, open: false } });
1262
+ },
1263
+ async confirmOverwrite() {
1264
+ const direction = state.overwrite.direction;
1265
+ store.set({ overwrite: { ...state.overwrite, busy: true, error: null } });
1266
+ try {
1267
+ const result = await runtime.rpc('sync.overwrite', { direction, apply: true });
1268
+ store.set({ overwrite: { ...state.overwrite, open: false, busy: false } });
1269
+ store.toast('success', direction === 'cloud'
1270
+ ? runtime.t('overwrite.cloudDone', { n: String(result?.uploaded ?? 0) })
1271
+ : runtime.t('overwrite.localDone', { n: String(result?.copied ?? 0) }));
1272
+ await store.loadSync();
1273
+ // Replacing this machine wholesale only takes effect after a restart.
1274
+ if (direction === 'local') store.restartSoon('restart.reason.restore');
1275
+ } catch (error) {
1276
+ store.set({ overwrite: { ...state.overwrite, busy: false, error: String(error?.message ?? error) } });
1277
+ }
1278
+ },
1279
+ dismissPauseNotice() {
1280
+ store.set({ pauseOpen: false });
1281
+ },
1282
+ async resumeAutoSync() {
1283
+ try {
1284
+ const data = await runtime.rpc('sync.resume');
1285
+ store.set({ pauseOpen: false, sync: { ...state.sync, auto: data?.auto ?? null } });
1286
+ store.toast('success', runtime.t('pause.resumed'));
1287
+ } catch (error) {
1288
+ store.toast('error', String(error?.message ?? error));
1289
+ }
1290
+ },
1291
+ async runEnvCheck() {
1292
+ store.set({ envCheck: { ...state.envCheck, busy: true, open: true, result: null, reportPath: null } });
1293
+ try {
1294
+ const result = await runtime.rpc('env.check');
1295
+ store.set({ envCheck: { ...state.envCheck, busy: false, open: true, result } });
1296
+ // A deliberate check counts as "I have seen this version".
1297
+ void runtime.rpc('env.ack').catch(() => {});
1298
+ } catch (error) {
1299
+ store.set({ envCheck: { ...state.envCheck, busy: false, open: true, result: { ok: false, failedCount: 1, checks: [{ label: '检测失败', ok: false, detail: String(error?.message ?? error), severity: 'high' }] } } });
1300
+ }
1301
+ },
1302
+ closeEnvCheck() {
1303
+ store.set({ envCheck: { ...state.envCheck, open: false } });
1304
+ },
1305
+ async writeEnvReport() {
1306
+ try {
1307
+ const written = await runtime.rpc('env.report');
1308
+ store.set({ envCheck: { ...state.envCheck, open: false, reportPath: written?.path ?? null } });
1309
+ store.toast('success', runtime.t('env.reported', { path: written?.path ?? '' }));
1310
+ } catch (error) {
1311
+ store.toast('error', String(error?.message ?? error));
1312
+ }
1313
+ },
1314
+ async checkAppVersion() {
1315
+ try {
1316
+ const info = await runtime.rpc('env.version');
1317
+ if (info?.changed === true) {
1318
+ store.set({ updatePrompt: { open: true, appVersion: info.appVersion, lastAppVersion: info.lastAppVersion } });
1319
+ return;
1320
+ }
1321
+ if (info?.appVersion !== null && info?.appVersion !== undefined) {
1322
+ await runtime.rpc('env.ack');
1323
+ }
1324
+ } catch {
1325
+ // Version probing is advisory only.
1326
+ }
1327
+ },
1328
+ async acceptUpdatePrompt() {
1329
+ store.set({ updatePrompt: { ...state.updatePrompt, open: false } });
1330
+ await store.runEnvCheck();
1331
+ },
1332
+ dismissUpdatePrompt() {
1333
+ // No ack: the reminder returns on the next start until a check runs.
1334
+ store.set({ updatePrompt: { ...state.updatePrompt, open: false } });
1335
+ },
1336
+ toggleSyncLog() {
1337
+ const open = state.sync.showLog !== true;
1338
+ store.set({ sync: { ...state.sync, showLog: open, historyOpen: open ? 0 : null, historyLimit: 20 } });
1339
+ },
1340
+ showMoreHistory() {
1341
+ store.set({ sync: { ...state.sync, historyLimit: (Number(state.sync.historyLimit) || 20) + 50 } });
1342
+ },
1343
+ openHistory(index) {
1344
+ const next = state.sync.historyOpen === index ? null : index;
1345
+ store.set({ sync: { ...state.sync, historyOpen: next } });
1346
+ },
1347
+ async testWebdav() {
1348
+ if (state.sync.webdavBusy === true) return;
1349
+ store.set({ sync: { ...state.sync, webdavBusy: true, webdav: null } });
1350
+ try {
1351
+ const data = await runtime.rpc('sync.webdavTest');
1352
+ store.set({ sync: { ...state.sync, webdavBusy: false, webdav: data } });
1353
+ } catch (error) {
1354
+ store.set({ sync: { ...state.sync, webdavBusy: false, webdav: { ok: false, message: String(error?.message ?? error) } } });
1355
+ }
1356
+ },
1357
+ };
1358
+ return store;
1359
+ }
1360
+
1361
+ const runtime = {
1362
+ store: null,
1363
+ t: (key) => key,
1364
+ rpc: async () => {
1365
+ throw new Error('DSH增强尚未初始化。');
1366
+ },
1367
+ openSession: () => {},
1368
+ jumpToAnchor: () => {},
1369
+ focusMatch: () => {},
1370
+ composer: null,
1371
+ composerDraft: '',
1372
+ };
1373
+
1374
+ function useStore() {
1375
+ const store = runtime.store;
1376
+ return React.useSyncExternalStore(store.subscribe, store.get, store.get);
1377
+ }
1378
+
1379
+ // ── shared pieces ────────────────────────────────────────────────────────
1380
+
1381
+ function icon(name, props) {
1382
+ const Component = primitives?.[name];
1383
+ if (Component === undefined) return null;
1384
+ return h(Component, props ?? {});
1385
+ }
1386
+
1387
+ function MenuRow(props) {
1388
+ const { danger, disabled, separatorBefore, iconName, onSelect, children } = props;
1389
+ if (primitives?.MenuItemButton !== undefined) {
1390
+ return h(primitives.MenuItemButton, {
1391
+ danger,
1392
+ disabled,
1393
+ separatorBefore,
1394
+ icon: icon(iconName ?? 'IconTrashOutlineRegular', { size: 14 }),
1395
+ onSelect,
1396
+ }, children);
1397
+ }
1398
+ return h('button', {
1399
+ type: 'button',
1400
+ role: 'menuitem',
1401
+ disabled,
1402
+ className: `dshe-match${danger === true ? ' dshe-action-danger' : ''}`,
1403
+ onClick: onSelect,
1404
+ }, children);
1405
+ }
1406
+
1407
+ function Switch(props) {
1408
+ return h('button', {
1409
+ type: 'button',
1410
+ role: 'switch',
1411
+ className: 'dshe-switch',
1412
+ 'aria-checked': props.checked === true,
1413
+ 'aria-label': props.label,
1414
+ disabled: props.disabled === true,
1415
+ onClick: () => props.onChange(!(props.checked === true)),
1416
+ }, h('span', {}));
1417
+ }
1418
+
1419
+ /**
1420
+ * Compact stamp for one search hit: 今日 10:11 / 昨日 10:11 / 周三 12:11 /
1421
+ * 11-02 11:12 / 2025-12-31 08:44.
1422
+ */
1423
+ function formatMatchTime(value) {
1424
+ const ms = Number(value);
1425
+ if (!Number.isFinite(ms) || ms <= 0) return '';
1426
+ const date = new Date(ms);
1427
+ const now = new Date();
1428
+ const pad = (n) => String(n).padStart(2, '0');
1429
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
1430
+ const dayStart = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
1431
+ const days = Math.round((dayStart(now) - dayStart(date)) / 86400000);
1432
+ if (days === 0) return `今日 ${clock}`;
1433
+ if (days === 1) return `昨日 ${clock}`;
1434
+ const monday = (d) => {
1435
+ const start = new Date(d.getFullYear(), d.getMonth(), d.getDate());
1436
+ start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
1437
+ return start.getTime();
1438
+ };
1439
+ if (monday(date) === monday(now)) {
1440
+ const names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
1441
+ return `${names[(date.getDay() + 6) % 7]} ${clock}`;
1442
+ }
1443
+ if (date.getFullYear() === now.getFullYear()) {
1444
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
1445
+ }
1446
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
1447
+ }
1448
+
1449
+ /** Width class for a match stamp: 1 = 今日/昨日/周X, 2 = MM-DD, 3 = YYYY-MM-DD. */
1450
+ function timeTier(text) {
1451
+ if (typeof text !== 'string' || text === '') return 1;
1452
+ if (/^(今日|昨日|周[一二三四五六日])/u.test(text)) return 1;
1453
+ if (/^\d{2}-\d{2} /u.test(text)) return 2;
1454
+ return 3;
1455
+ }
1456
+
1457
+ function formatSize(bytes) {
1458
+ const value = Number(bytes) || 0;
1459
+ if (value < 1024) return `${String(value)} B`;
1460
+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
1461
+ return `${(value / (1024 * 1024)).toFixed(1)} MB`;
1462
+ }
1463
+
1464
+ function formatWhen(iso) {
1465
+ const time = typeof iso === 'string' ? Date.parse(iso) : Number.NaN;
1466
+ if (!Number.isFinite(time)) return '';
1467
+ return new Date(time).toLocaleString();
1468
+ }
1469
+
1470
+ /** Highlight every hit; the one at focusIndex also gets the current style. */
1471
+ function highlightFocus(text, query, focusIndex) {
1472
+ const needle = typeof query === 'string' ? query.trim() : '';
1473
+ if (needle === '') return text;
1474
+ const lower = text.toLowerCase();
1475
+ const target = needle.toLowerCase();
1476
+ const parts = [];
1477
+ let from = 0;
1478
+ let key = 0;
1479
+ let index = lower.indexOf(target);
1480
+ while (index >= 0) {
1481
+ if (index > from) parts.push(text.slice(from, index));
1482
+ const current = Number(focusIndex) === index;
1483
+ parts.push(h('mark', { className: current ? 'dshe-mark dshe-mark-current' : 'dshe-mark', key: `f${String(key)}` }, text.slice(index, index + target.length)));
1484
+ key += 1;
1485
+ from = index + target.length;
1486
+ index = lower.indexOf(target, from);
1487
+ }
1488
+ if (from < text.length) parts.push(text.slice(from));
1489
+ return parts;
1490
+ }
1491
+
1492
+ function highlight(text, query) {
1493
+ const needle = typeof query === 'string' ? query.trim() : '';
1494
+ if (needle === '') return text;
1495
+ const lower = text.toLowerCase();
1496
+ const target = needle.toLowerCase();
1497
+ const parts = [];
1498
+ let from = 0;
1499
+ let index = lower.indexOf(target);
1500
+ let key = 0;
1501
+ while (index >= 0) {
1502
+ if (index > from) parts.push(text.slice(from, index));
1503
+ parts.push(h('mark', { className: 'dshe-mark', key: `m${String(key)}` }, text.slice(index, index + target.length)));
1504
+ key += 1;
1505
+ from = index + target.length;
1506
+ index = lower.indexOf(target, from);
1507
+ }
1508
+ if (from < text.length) parts.push(text.slice(from));
1509
+ return parts;
1510
+ }
1511
+
1512
+ // ── session menu row ─────────────────────────────────────────────────────
1513
+
1514
+ function SessionTrashRow(props) {
1515
+ const state = useStore();
1516
+ const { sessionId, useMenuOpenState } = props;
1517
+ const closeMenu = typeof useMenuOpenState === 'function' ? useMenuOpenState()[1] : null;
1518
+ if (state.settings.trashEnabled !== true) return null;
1519
+ return h(MenuRow, {
1520
+ disabled: false,
1521
+ separatorBefore: false,
1522
+ iconName: 'IconArchiveOutlineRegular',
1523
+ onSelect: () => {
1524
+ if (typeof closeMenu === 'function') closeMenu(false);
1525
+ runtime.store.openTrashForSession(sessionId);
1526
+ },
1527
+ }, runtime.t('trash.menu'));
1528
+ }
1529
+
1530
+ function SessionMoveRow(props) {
1531
+ const state = useStore();
1532
+ const { sessionId, displayTitle, useMenuOpenState } = props;
1533
+ const closeMenu = typeof useMenuOpenState === 'function' ? useMenuOpenState()[1] : null;
1534
+ const statuses = typeof props.useSessionStatus === 'function' ? props.useSessionStatus((value) => value) : null;
1535
+ let running = false;
1536
+ try {
1537
+ running = statuses?.get?.(sessionId)?.running === true;
1538
+ } catch {
1539
+ running = false;
1540
+ }
1541
+ if (state.settings.moveEnabled !== true) return null;
1542
+ return h(MenuRow, {
1543
+ disabled: running,
1544
+ separatorBefore: false,
1545
+ iconName: 'IconFolderOpenRegular',
1546
+ onSelect: () => {
1547
+ if (typeof closeMenu === 'function') closeMenu(false);
1548
+ runtime.store.openMove(sessionId, displayTitle);
1549
+ },
1550
+ }, running ? runtime.t('move.running') : runtime.t('move.label'));
1551
+ }
1552
+
1553
+ function SessionDeleteRow(props) { const state = useStore();
1554
+ const { sessionId, displayTitle, useMenuOpenState } = props;
1555
+ const closeMenu = typeof useMenuOpenState === 'function' ? useMenuOpenState()[1] : null;
1556
+ const statuses = typeof props.useSessionStatus === 'function' ? props.useSessionStatus((value) => value) : null;
1557
+ let running = false;
1558
+ try {
1559
+ running = statuses?.get?.(sessionId)?.running === true;
1560
+ } catch {
1561
+ running = false;
1562
+ }
1563
+ if (state.settings.deleteEnabled !== true) return null;
1564
+ return h(MenuRow, {
1565
+ danger: true,
1566
+ disabled: running,
1567
+ separatorBefore: true,
1568
+ onSelect: () => {
1569
+ if (typeof closeMenu === 'function') closeMenu(false);
1570
+ runtime.store.requestDelete(sessionId, displayTitle, running);
1571
+ },
1572
+ }, running ? runtime.t('delete.running') : runtime.t('delete.label'));
1573
+ }
1574
+
1575
+ /**
1576
+ * Dismiss on a double click anywhere in the window.
1577
+ *
1578
+ * A single click stays harmless, so a stray click does not hide a notice the
1579
+ * reader is still reading. The listener lives on the document, so a double
1580
+ * click on the notice, on the chat, or in the sidebar all count.
1581
+ */
1582
+ function armQuickClose(node, close) {
1583
+ let done = false;
1584
+ const onDouble = () => {
1585
+ if (done) return;
1586
+ done = true;
1587
+ document.removeEventListener('dblclick', onDouble, true);
1588
+ close();
1589
+ };
1590
+ const onSingle = (event) => event.stopPropagation();
1591
+ node.addEventListener('click', onSingle);
1592
+ document.addEventListener('dblclick', onDouble, true);
1593
+ return () => {
1594
+ done = true;
1595
+ document.removeEventListener('dblclick', onDouble, true);
1596
+ node.removeEventListener('click', onSingle);
1597
+ };
1598
+ }
1599
+
1600
+ /**
1601
+ * Put one string on the clipboard, then say what happened.
1602
+ *
1603
+ * The async Clipboard API needs a secure context; the textarea fallback keeps
1604
+ * the action working when the page is served from elsewhere.
1605
+ */
1606
+ async function copyWithNotice(value, labelKey) {
1607
+ const label = runtime.t(labelKey);
1608
+ const done = () => runtime.store.toast('success', runtime.t('hover.copy.done', { label }));
1609
+ const failed = () => runtime.store.toast('error', runtime.t('hover.copy.failed', { label }));
1610
+ try {
1611
+ await navigator.clipboard.writeText(value);
1612
+ done();
1613
+ return;
1614
+ } catch {
1615
+ // fall through to the legacy path
1616
+ }
1617
+ try {
1618
+ const area = document.createElement('textarea');
1619
+ area.value = value;
1620
+ area.setAttribute('readonly', '');
1621
+ area.style.cssText = 'position:fixed;top:-1000px;opacity:0';
1622
+ document.body.appendChild(area);
1623
+ area.select();
1624
+ const ok = document.execCommand('copy');
1625
+ area.remove();
1626
+ if (ok) done();
1627
+ else failed();
1628
+ } catch {
1629
+ failed();
1630
+ }
1631
+ }
1632
+
1633
+ /**
1634
+ * Session id line inside the row's hover card.
1635
+ *
1636
+ * The hover slot sits below the relative time, but the id reads better right
1637
+ * under the title, so the slot only carries the session identity: the line
1638
+ * itself is created imperatively and parked after the title element, which
1639
+ * keeps React's own layout untouched. Any structural surprise means no line.
1640
+ */
1641
+ function SessionIdRow(props) {
1642
+ const id = typeof props?.sessionId === 'string' ? props.sessionId : '';
1643
+ const markerRef = React.useRef(null);
1644
+
1645
+ React.useEffect(() => {
1646
+ const marker = markerRef.current;
1647
+ if (marker === null || id === '') return undefined;
1648
+ try {
1649
+ const host = marker.closest('[data-slot="sidebar.session.row.hover"]');
1650
+ const content = host === null ? null : host.parentElement;
1651
+ const title = content === null ? null : content.firstElementChild;
1652
+ if (title === null) return undefined;
1653
+
1654
+ const children = Array.from(content.children);
1655
+ const candidatePath = children.length > 1 ? children[1] : null;
1656
+ // The path line is the one carrying a separator; a reshaped card just
1657
+ // leaves this field unbound.
1658
+ const pathText = candidatePath === null ? '' : (candidatePath.textContent ?? '').trim();
1659
+ const pathLine = /[\\/:]/.test(pathText) ? candidatePath : null;
1660
+
1661
+ // The card's own click copies the session id; each field now copies its
1662
+ // own text instead, so a mis-click still produces something useful.
1663
+ const bindings = [];
1664
+ const bind = (element, value, labelKey) => {
1665
+ if (element === null || typeof value !== 'string' || value.trim() === '') return;
1666
+ const handler = (event) => {
1667
+ event.preventDefault();
1668
+ event.stopPropagation();
1669
+ void copyWithNotice(value.trim(), labelKey);
1670
+ };
1671
+ element.addEventListener('click', handler);
1672
+ element.style.cursor = 'pointer';
1673
+ bindings.push({ element, handler });
1674
+ };
1675
+
1676
+ bind(title, title.textContent ?? '', 'hover.copy.title');
1677
+ bind(pathLine, pathLine === null ? '' : pathLine.textContent ?? '', 'hover.copy.path');
1678
+
1679
+ const line = document.createElement('div');
1680
+ line.className = 'dshe-session-id';
1681
+ line.title = id;
1682
+ line.dataset.sessionId = id;
1683
+ line.style.cssText = [
1684
+ 'margin-top:2px',
1685
+ 'color:var(--dsw-alias-hovercard-label-secondary, currentColor)',
1686
+ 'font-size:12px',
1687
+ 'line-height:16px',
1688
+ 'overflow-wrap:anywhere',
1689
+ 'word-break:break-all',
1690
+ 'user-select:text',
1691
+ 'cursor:pointer',
1692
+ ].join(';');
1693
+ line.textContent = runtime.t('hover.sessionId') + id;
1694
+ line.addEventListener('click', (event) => {
1695
+ event.preventDefault();
1696
+ event.stopPropagation();
1697
+ void copyWithNotice(id, 'hover.copy.id');
1698
+ });
1699
+ title.insertAdjacentElement('afterend', line);
1700
+
1701
+ // The slot's own wrapper also forwards clicks to the card; keep it quiet.
1702
+ const markerClick = (event) => event.stopPropagation();
1703
+ marker.addEventListener('click', markerClick);
1704
+
1705
+ return () => {
1706
+ for (const binding of bindings) {
1707
+ binding.element.removeEventListener('click', binding.handler);
1708
+ binding.element.style.cursor = '';
1709
+ }
1710
+ marker.removeEventListener('click', markerClick);
1711
+ line.remove();
1712
+ };
1713
+ } catch {
1714
+ // A layout change without a line is better than a broken card.
1715
+ return undefined;
1716
+ }
1717
+ }, [id]);
1718
+
1719
+ if (id === '') return null;
1720
+ return h('span', { ref: markerRef, style: { display: 'none' } });
1721
+ }
1722
+
1723
+ // ── delete confirmation ──────────────────────────────────────────────────
1724
+
1725
+ const displayName = (value) => {
1726
+ const text = typeof value === 'string' ? value.trim() : '';
1727
+ if (text === '' || /^session-[0-9a-f-]{8,}$/iu.test(text)) return runtime.t('trash.untitled');
1728
+ return text;
1729
+ };
1730
+
1731
+ function DeleteDialog() {
1732
+ const state = useStore();
1733
+ const pending = state.pendingDelete;
1734
+ if (pending === null) return null;
1735
+ const body = h('div', { className: 'dshe-section' },
1736
+ h('div', { className: 'dshe-card' },
1737
+ h('div', { className: 'dshe-row' },
1738
+ h('div', { className: 'dshe-row-main' },
1739
+ h('div', { className: 'dshe-row-title' }, displayName(pending.title)),
1740
+ h('div', { className: 'dshe-row-desc' }, runtime.t('delete.desc')),
1741
+ ),
1742
+ ),
1743
+ ),
1744
+ state.deleteError === null ? null : h('div', { className: 'dshe-status dshe-error', role: 'alert' }, state.deleteError),
1745
+ state.deleteBusy === true ? h('div', { className: 'dshe-status', role: 'status' }, `${runtime.t('delete.confirm')}…`) : null,
1746
+ );
1747
+ const footer = h(React.Fragment, {},
1748
+ h('button', { type: 'button', className: 'dshe-action', disabled: state.deleteBusy, onClick: () => runtime.store.cancelDelete() }, runtime.t('common.cancel')),
1749
+ h('button', {
1750
+ type: 'button',
1751
+ className: 'dshe-action dshe-action-danger',
1752
+ disabled: state.deleteBusy,
1753
+ onClick: () => runtime.store.confirmDelete(),
1754
+ }, runtime.t('delete.confirm')),
1755
+ );
1756
+ if (primitives?.Modal === undefined) return null;
1757
+ return h(primitives.Modal, {
1758
+ open: true,
1759
+ onClose: () => runtime.store.cancelDelete(),
1760
+ closeLabel: runtime.t('common.close'),
1761
+ title: runtime.t('delete.title'),
1762
+ footer,
1763
+ }, body);
1764
+ }
1765
+
1766
+ // ── composer bridge ──────────────────────────────────────────────────────
1767
+
1768
+ function ComposerBridge(props) {
1769
+ const { inputActions, useInput } = props;
1770
+ const input = typeof useInput === 'function' ? useInput((value) => value) : undefined;
1771
+ const draft = typeof input?.draft === 'string' ? input.draft : '';
1772
+ React.useEffect(() => {
1773
+ runtime.composer = inputActions ?? null;
1774
+ runtime.composerDraft = draft;
1775
+ return () => {
1776
+ if (runtime.composer === inputActions) runtime.composer = null;
1777
+ };
1778
+ }, [inputActions, draft]);
1779
+ return null;
1780
+ }
1781
+
1782
+ // ── move dialog ──────────────────────────────────────────────────────────
1783
+
1784
+ function MoveDialog() {
1785
+ const state = useStore();
1786
+ const move = state.move;
1787
+ if (move.open !== true) return null;
1788
+ if (primitives?.Modal === undefined) return null;
1789
+ const body = h('div', { className: 'dshe-section' },
1790
+ h('div', { className: 'dshe-row-desc' }, runtime.t('move.session', { title: move.title })),
1791
+ move.current === null ? null : h('div', { className: 'dshe-row-desc' }, runtime.t('move.current', { title: move.current.title })),
1792
+ move.loading === true
1793
+ ? h('div', { className: 'dshe-status', role: 'status' }, runtime.t('move.loading'))
1794
+ : move.error !== null
1795
+ ? h('div', { className: 'dshe-status dshe-error', role: 'alert' }, runtime.t('move.failed', { message: move.error }))
1796
+ : move.workspaces.length === 0
1797
+ ? h('div', { className: 'dshe-status' }, runtime.t('move.empty'))
1798
+ : h('div', { className: 'dshe-move-list', role: 'radiogroup', 'aria-label': runtime.t('move.target') },
1799
+ move.workspaces.map((workspace) => h('label', {
1800
+ className: 'dshe-move-item',
1801
+ key: workspace.id,
1802
+ 'data-active': move.targetId === workspace.id ? 'true' : 'false',
1803
+ },
1804
+ h('input', {
1805
+ type: 'radio',
1806
+ name: 'dshe-move-target',
1807
+ checked: move.targetId === workspace.id,
1808
+ disabled: move.busy === true,
1809
+ onChange: () => runtime.store.setMoveTarget(workspace.id),
1810
+ }),
1811
+ h('span', { className: 'dshe-move-main' },
1812
+ h('span', { className: 'dshe-move-title' }, workspace.title),
1813
+ h('span', { className: 'dshe-move-meta' }, `${workspace.path} · ${String(workspace.sessionCount)}`),
1814
+ ),
1815
+ )),
1816
+ ),
1817
+ move.busy === true ? h('div', { className: 'dshe-status', role: 'status' }, runtime.t('move.busy')) : null,
1818
+ );
1819
+ const footer = h(React.Fragment, {},
1820
+ h('button', {
1821
+ type: 'button',
1822
+ className: 'dshe-action',
1823
+ disabled: move.busy === true,
1824
+ onClick: () => runtime.store.closeMove(),
1825
+ }, runtime.t('common.cancel')),
1826
+ h('button', {
1827
+ type: 'button',
1828
+ className: 'dshe-action dshe-action-danger',
1829
+ disabled: move.busy === true || move.loading === true || move.targetId === null,
1830
+ onClick: () => runtime.store.confirmMove(),
1831
+ }, runtime.t('move.confirm')),
1832
+ );
1833
+ return h(primitives.Modal, {
1834
+ open: true,
1835
+ onClose: () => runtime.store.closeMove(),
1836
+ closeLabel: runtime.t('common.close'),
1837
+ title: runtime.t('move.title'),
1838
+ footer,
1839
+ }, body);
1840
+ }
1841
+
1842
+ // ── trash dialog ─────────────────────────────────────────────────────────
1843
+
1844
+ function TrashDialog() {
1845
+ const state = useStore();
1846
+ const trash = state.trash;
1847
+ if (trash.open !== true) return null;
1848
+ if (primitives?.Modal === undefined) return null;
1849
+ const groups = trash.groups ?? [];
1850
+ const body = h('div', { className: 'dshe-section' },
1851
+ h('p', { className: 'dshe-section-desc' }, runtime.t('trash.desc')),
1852
+ trash.loading === true
1853
+ ? h('div', { className: 'dshe-status', role: 'status' }, runtime.t('trash.loading'))
1854
+ : trash.error !== null
1855
+ ? h('div', { className: 'dshe-status dshe-error', role: 'alert' }, trash.error)
1856
+ : groups.length === 0
1857
+ ? h('div', { className: 'dshe-status' }, runtime.t('trash.empty'))
1858
+ : h('div', { className: 'dshe-trash-body' }, groups.map((group) => h('div', { key: group.workspaceId },
1859
+ h('div', { className: 'dshe-trash-group-head' },
1860
+ h('span', { className: 'dshe-trash-group-title' }, group.workspaceTitle === '' || group.workspaceTitle === undefined ? '未分组' : group.workspaceTitle),
1861
+ trash.confirmWorkspace === group.workspaceId
1862
+ ? h('span', { className: 'dshe-trash-group-actions' },
1863
+ h('button', {
1864
+ type: 'button',
1865
+ className: 'dshe-action',
1866
+ disabled: trash.busy !== null,
1867
+ onClick: () => runtime.store.patchTrashState({ confirmWorkspace: null }),
1868
+ }, runtime.t('common.cancel')),
1869
+ h('button', {
1870
+ type: 'button',
1871
+ className: 'dshe-action dshe-action-danger',
1872
+ disabled: trash.busy !== null,
1873
+ onClick: () => runtime.store.clearWorkspace(group.workspaceId),
1874
+ }, runtime.t('trash.clearWorkspace.confirm')),
1875
+ )
1876
+ : group.workspaceId === '_ungrouped'
1877
+ ? null
1878
+ : h('button', {
1879
+ type: 'button',
1880
+ className: 'dshe-link-danger',
1881
+ disabled: trash.busy !== null,
1882
+ onClick: () => runtime.store.requestClearWorkspace(group.workspaceId),
1883
+ }, runtime.t('trash.clearWorkspace')),
1884
+ ),
1885
+ (group.items ?? []).map((item) => {
1886
+ const confirming = trash.confirmPurge === item.sessionId;
1887
+ return h('div', { className: 'dshe-trash-row', key: item.sessionId },
1888
+ h('div', { className: 'dshe-trash-main' },
1889
+ h('div', { className: 'dshe-trash-title', title: displayName(item.title) }, displayName(item.title)),
1890
+ h('div', { className: 'dshe-trash-id', title: item.sessionId }, item.sessionId),
1891
+ h('div', { className: 'dshe-trash-meta' }, `${formatWhen(item.deletedAt)} · ${formatSize(item.sizeBytes)}`),
1892
+ ),
1893
+ confirming
1894
+ ? h(React.Fragment, {},
1895
+ h('button', {
1896
+ type: 'button',
1897
+ className: 'dshe-action',
1898
+ disabled: trash.busy !== null,
1899
+ onClick: () => runtime.store.patchTrashState({ confirmPurge: null }),
1900
+ }, runtime.t('common.cancel')),
1901
+ h('button', {
1902
+ type: 'button',
1903
+ className: 'dshe-action dshe-action-danger',
1904
+ disabled: trash.busy !== null,
1905
+ onClick: () => runtime.store.purge(item.sessionId, item.title),
1906
+ }, runtime.t('trash.purge.confirm')),
1907
+ )
1908
+ : h(React.Fragment, {},
1909
+ h('button', {
1910
+ type: 'button',
1911
+ className: 'dshe-action',
1912
+ disabled: trash.busy !== null,
1913
+ onClick: () => runtime.store.restore(item.sessionId, item.title),
1914
+ }, runtime.t('trash.restore')),
1915
+ h('button', {
1916
+ type: 'button',
1917
+ className: 'dshe-action dshe-action-danger',
1918
+ disabled: trash.busy !== null,
1919
+ onClick: () => runtime.store.requestPurge(item.sessionId),
1920
+ }, runtime.t('trash.purge')),
1921
+ ),
1922
+ );
1923
+ }),
1924
+ ))),
1925
+ );
1926
+ const footer = h(React.Fragment, {},
1927
+ trash.confirmClear === true
1928
+ ? h(React.Fragment, {},
1929
+ h('button', {
1930
+ type: 'button',
1931
+ className: 'dshe-action',
1932
+ disabled: trash.busy !== null,
1933
+ onClick: () => runtime.store.patchTrashState({ confirmClear: false }),
1934
+ }, runtime.t('common.cancel')),
1935
+ h('button', {
1936
+ type: 'button',
1937
+ className: 'dshe-action dshe-action-danger',
1938
+ disabled: trash.busy !== null,
1939
+ onClick: () => runtime.store.clearTrash(),
1940
+ }, runtime.t('trash.clear.confirm')),
1941
+ )
1942
+ : h('button', {
1943
+ type: 'button',
1944
+ className: 'dshe-action dshe-action-danger',
1945
+ disabled: trash.busy !== null || trash.count === 0 || trash.scopeSession !== null,
1946
+ onClick: () => runtime.store.requestClear(),
1947
+ style: trash.scopeSession === null ? undefined : { display: 'none' },
1948
+ }, runtime.t('trash.clear')),
1949
+ h('button', {
1950
+ type: 'button',
1951
+ className: 'dshe-action',
1952
+ disabled: trash.busy !== null,
1953
+ onClick: () => runtime.store.closeTrash(),
1954
+ }, runtime.t('common.close')),
1955
+ );
1956
+ return h(primitives.Modal, {
1957
+ open: true,
1958
+ onClose: () => runtime.store.closeTrash(),
1959
+ closeLabel: runtime.t('common.close'),
1960
+ title: runtime.t('trash.title'),
1961
+ footer,
1962
+ }, body);
1963
+ }
1964
+
1965
+ // ── search overlay ───────────────────────────────────────────────────────
1966
+
1967
+ /** Height of the shell's caption strip, which the page must not cover. */
1968
+ function captionHeight() {
1969
+ let bottom = 0;
1970
+ let nodes = [];
1971
+ try {
1972
+ nodes = Array.from(document.querySelectorAll('*'));
1973
+ } catch {
1974
+ return 0;
1975
+ }
1976
+ for (const node of nodes) {
1977
+ let style;
1978
+ try {
1979
+ style = window.getComputedStyle(node);
1980
+ } catch {
1981
+ continue;
1982
+ }
1983
+ if (style.webkitAppRegion !== 'drag') continue;
1984
+ const rect = node.getBoundingClientRect();
1985
+ if (rect.top > 80) continue;
1986
+ if (rect.bottom > bottom) bottom = rect.bottom;
1987
+ }
1988
+ return Math.max(0, Math.round(bottom));
1989
+ }
1990
+
1991
+
1992
+
1993
+ function SearchOverlay() {
1994
+ const state = useStore();
1995
+ const search = state.search;
1996
+ const inputRef = React.useRef(null);
1997
+ const resultsRef = React.useRef(null);
1998
+ const [active, setActive] = React.useState(0);
1999
+ const [expanded, setExpanded] = React.useState(null);
2000
+ const [preview, setPreview] = React.useState(null);
2001
+
2002
+ // The card lives on document.body: inside the dialog an animated ancestor would
2003
+ // turn position:fixed into a local coordinate system and clip it.
2004
+ React.useEffect(() => {
2005
+ const existing = document.getElementById('dshe-preview-el');
2006
+ if (existing !== null) existing.remove();
2007
+ if (preview === null) return;
2008
+
2009
+ const node = document.createElement('div');
2010
+ node.id = 'dshe-preview-el';
2011
+ node.className = 'dshe-preview';
2012
+ node.style.cssText = [
2013
+ 'position:fixed',
2014
+ 'z-index:2147482000',
2015
+ 'box-sizing:border-box',
2016
+ 'overflow:auto',
2017
+ 'width:' + String(preview.width) + 'px',
2018
+ 'left:' + String(preview.left) + 'px',
2019
+ 'max-height:' + String(preview.maxHeight ?? 320) + 'px',
2020
+ preview.bottom !== null && preview.bottom !== undefined
2021
+ ? 'bottom:' + String(preview.bottom) + 'px'
2022
+ : 'top:' + String(Math.max(12, preview.top ?? 12)) + 'px',
2023
+ ].join(';');
2024
+
2025
+ const needle = search.query.trim().toLowerCase();
2026
+ const text = String(preview.text ?? '');
2027
+ if (needle === '') {
2028
+ node.textContent = text;
2029
+ } else {
2030
+ let from = 0;
2031
+ let at = text.toLowerCase().indexOf(needle);
2032
+ while (at >= 0) {
2033
+ if (at > from) node.appendChild(document.createTextNode(text.slice(from, at)));
2034
+ const mark = document.createElement('mark');
2035
+ mark.className = at === preview.hit ? 'dshe-mark dshe-mark-current' : 'dshe-mark';
2036
+ mark.textContent = text.slice(at, at + needle.length);
2037
+ node.appendChild(mark);
2038
+ from = at + needle.length;
2039
+ at = text.toLowerCase().indexOf(needle, from);
2040
+ }
2041
+ if (from < text.length) node.appendChild(document.createTextNode(text.slice(from)));
2042
+ }
2043
+
2044
+ node.addEventListener('mouseenter', () => {
2045
+ if (previewTimer.current !== null) window.clearTimeout(previewTimer.current);
2046
+ });
2047
+ node.addEventListener('mouseleave', () => {
2048
+ if (previewTimer.current !== null) window.clearTimeout(previewTimer.current);
2049
+ previewTimer.current = window.setTimeout(() => setPreview(null), 160);
2050
+ });
2051
+ document.body.appendChild(node);
2052
+
2053
+ // Keep it inside the window, then centre the focused hit.
2054
+ const rect = node.getBoundingClientRect();
2055
+ if (rect.bottom > window.innerHeight - 12) {
2056
+ node.style.top = 'auto';
2057
+ node.style.bottom = String(Math.max(12, Math.round(window.innerHeight - rect.top - (window.innerHeight - 24 - rect.height)))) + 'px';
2058
+ }
2059
+ const mark = node.querySelector('.dshe-mark-current');
2060
+ if (mark !== null) {
2061
+ const box = node.getBoundingClientRect();
2062
+ const markRect = mark.getBoundingClientRect();
2063
+ node.scrollTop += markRect.top - box.top - node.clientHeight / 2 + markRect.height / 2;
2064
+ }
2065
+ return () => { node.remove(); };
2066
+ }, [preview, search.query]);
2067
+
2068
+ const previewRef = React.useRef(null);
2069
+ const previewTimer = React.useRef(null);
2070
+ const previewGate = React.useRef(true);
2071
+ const previewHover = React.useRef(null);
2072
+ const previewPointer = React.useRef({ x: 0, y: 0 });
2073
+ const previewEpoch = React.useRef(0);
2074
+
2075
+ React.useEffect(() => {
2076
+ // Typing hides the preview; it may only reappear after the pointer moves.
2077
+ previewGate.current = true;
2078
+ if (previewHover.current !== null) {
2079
+ window.clearTimeout(previewHover.current);
2080
+ previewHover.current = null;
2081
+ }
2082
+ setPreview(null);
2083
+ }, [search.query]);
2084
+
2085
+ React.useEffect(() => {
2086
+ const onMove = (event) => {
2087
+ previewGate.current = false;
2088
+ previewPointer.current = { x: event.clientX, y: event.clientY };
2089
+ };
2090
+ window.addEventListener('mousemove', onMove, { passive: true });
2091
+ return () => window.removeEventListener('mousemove', onMove);
2092
+ }, []);
2093
+
2094
+ React.useEffect(() => {
2095
+ if (search.open !== true) return undefined;
2096
+ const focus = () => {
2097
+ const node = inputRef.current;
2098
+ if (node !== null) {
2099
+ node.focus();
2100
+ node.select();
2101
+ }
2102
+ };
2103
+ focus();
2104
+ const timer = setTimeout(focus, 0);
2105
+ return () => clearTimeout(timer);
2106
+ }, [search.open]);
2107
+
2108
+ React.useEffect(() => {
2109
+ if (search.open !== true) return undefined;
2110
+ const onKeyDown = (event) => {
2111
+ if (event.key !== 'Escape') return;
2112
+ event.preventDefault();
2113
+ event.stopPropagation();
2114
+ runtime.store.closeSearch();
2115
+ };
2116
+ window.addEventListener('keydown', onKeyDown, true);
2117
+ return () => window.removeEventListener('keydown', onKeyDown, true);
2118
+ }, [search.open]);
2119
+
2120
+ const flat = React.useMemo(() => {
2121
+ const groups = search.groups ?? [];
2122
+ const target = expanded === null ? groups[0] : groups.find((group) => group.sessionId === expanded);
2123
+ return (target?.matches ?? []).map((match) => ({ group: target, match }));
2124
+ }, [search.groups, expanded]);
2125
+
2126
+ const groups = search.groups ?? [];
2127
+ const totalMatches = React.useMemo(
2128
+ () => groups.reduce((sum, group) => sum + (group.matches ?? []).length, 0),
2129
+ [search.groups],
2130
+ );
2131
+
2132
+ React.useEffect(() => {
2133
+ setExpanded((groups[0]?.sessionId) ?? null);
2134
+ }, [search.groups]);
2135
+
2136
+ React.useEffect(() => {
2137
+ setActive(0);
2138
+ }, [expanded]);
2139
+
2140
+ React.useEffect(() => {
2141
+ previewEpoch.current += 1;
2142
+ if (previewHover.current !== null) {
2143
+ window.clearTimeout(previewHover.current);
2144
+ previewHover.current = null;
2145
+ }
2146
+ setPreview(null);
2147
+ }, [search.open, search.groups]);
2148
+
2149
+
2150
+ React.useEffect(() => {
2151
+ if (active >= flat.length) setActive(flat.length === 0 ? 0 : flat.length - 1);
2152
+ }, [flat.length, active]);
2153
+
2154
+ React.useEffect(() => {
2155
+ const node = resultsRef.current?.querySelector('.dshe-match[data-active="true"]');
2156
+ if (node !== null && node !== undefined && typeof node.scrollIntoView === 'function') {
2157
+ node.scrollIntoView({ block: 'nearest' });
2158
+ }
2159
+ }, [active, search.groups]);
2160
+
2161
+ if (search.open !== true) return null;
2162
+
2163
+ const open = (sessionId, match) => {
2164
+ const query = search.query;
2165
+ runtime.store.closeSearch();
2166
+ runtime.openSession(sessionId);
2167
+ runtime.focusMatch(sessionId, match, query);
2168
+ };
2169
+
2170
+ const onKeyDown = (event) => {
2171
+ if (event.key === 'Escape') {
2172
+ event.preventDefault();
2173
+ runtime.store.closeSearch();
2174
+ return;
2175
+ }
2176
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
2177
+ if (flat.length === 0) return;
2178
+ event.preventDefault();
2179
+ const delta = event.key === 'ArrowDown' ? 1 : -1;
2180
+ setActive((current) => (current + delta + flat.length) % flat.length);
2181
+ return;
2182
+ }
2183
+ if (event.key === 'Enter') {
2184
+ const row = flat[active];
2185
+ if (row === undefined) return;
2186
+ event.preventDefault();
2187
+ open(row.group.sessionId, row.match);
2188
+ }
2189
+ };
2190
+
2191
+ const meta = search.status === 'done'
2192
+ ? runtime.t('search.meta', { count: (search.groups ?? []).length, matches: totalMatches })
2193
+ : '';
2194
+
2195
+
2196
+ const panel = h('div', { className: 'dshe-overlay dshe-overlay-top', role: 'presentation', style: { top: `${String(captionHeight())}px` } },
2197
+ h('div', { className: 'dshe-backdrop', 'aria-hidden': 'true', onClick: () => runtime.store.closeSearch() }),
2198
+ h('div', {
2199
+ className: 'dshe-search',
2200
+ role: 'dialog',
2201
+ 'aria-modal': 'true',
2202
+ 'aria-label': runtime.t('search.placeholder'),
2203
+ onKeyDown,
2204
+ },
2205
+ h('div', { className: 'dshe-search-head' },
2206
+ h('span', { className: 'dshe-search-icon' }, icon('IconSearchOutlineRegular', { size: 16 })),
2207
+ h('input', {
2208
+ ref: inputRef,
2209
+ className: 'dshe-search-input',
2210
+ type: 'text',
2211
+ value: search.query,
2212
+ placeholder: runtime.t('search.placeholder'),
2213
+ 'aria-label': runtime.t('search.placeholder'),
2214
+ onChange: (event) => runtime.store.setQuery(event.target.value),
2215
+ }),
2216
+ h('span', { className: 'dshe-group-meta' }, meta),
2217
+ h('button', {
2218
+ type: 'button',
2219
+ className: 'dshe-action',
2220
+ onClick: () => runtime.store.closeSearch(),
2221
+ }, runtime.t('common.close')),
2222
+ ),
2223
+ h('div', { className: 'dshe-results', ref: resultsRef },
2224
+ search.status === 'loading' ? h('div', { className: 'dshe-status', role: 'status' }, runtime.t('search.loading')) : null,
2225
+ search.status === 'error' ? h('div', { className: 'dshe-status dshe-error', role: 'alert' }, runtime.t('search.error', { message: search.error })) : null,
2226
+ search.status === 'idle' ? h('div', { className: 'dshe-status' }, runtime.t('search.hint')) : null,
2227
+ search.status === 'done' && totalMatches === 0 ? h('div', { className: 'dshe-status' }, runtime.t('search.empty')) : null,
2228
+ search.status === 'done'
2229
+ ? groups.map((group) => {
2230
+ const isOpen = group.sessionId === expanded;
2231
+ return h('div', { className: 'dshe-group', key: group.sessionId },
2232
+ h('button', {
2233
+ type: 'button',
2234
+ className: 'dshe-group-title',
2235
+ title: group.title,
2236
+ 'aria-expanded': isOpen ? 'true' : 'false',
2237
+ onClick: () => setExpanded(isOpen ? null : group.sessionId),
2238
+ },
2239
+ h('span', { className: 'dshe-group-caret' }, isOpen ? '▾' : '▸'),
2240
+ h('span', { className: 'dshe-group-name' }, group.title),
2241
+ h('span', { className: 'dshe-group-meta' }, (group.matches ?? []).length + '')),
2242
+ isOpen
2243
+ ? (group.matches ?? []).map((match, index) => h('button', {
2244
+ type: 'button',
2245
+ className: 'dshe-match',
2246
+ onMouseEnter: (event) => {
2247
+ if (previewHover.current !== null) window.clearTimeout(previewHover.current);
2248
+ if (previewGate.current === true) return;
2249
+ const row = event.currentTarget;
2250
+ if (event.clientX !== undefined) previewPointer.current = { x: event.clientX, y: event.clientY };
2251
+ const epoch = previewEpoch.current;
2252
+ previewHover.current = window.setTimeout(() => {
2253
+ if (previewEpoch.current !== epoch) return;
2254
+ previewHover.current = null;
2255
+ const rect = row.getBoundingClientRect();
2256
+ const dialog = row.closest('.dshe-search');
2257
+ const box = dialog === null ? null : dialog.getBoundingClientRect();
2258
+ const base = box !== null && box.width > 200 ? box.width : window.innerWidth;
2259
+ const width = Math.max(280, Math.min(460, Math.round(base * 0.62)));
2260
+ const pointer = previewPointer.current;
2261
+ const left = Math.max(12, Math.min(Math.round(pointer.x + 16), window.innerWidth - width - 12));
2262
+ const spaceBelow = Math.round(window.innerHeight - rect.bottom - 12);
2263
+ const spaceAbove = Math.round(rect.top - 12);
2264
+ // Pick whichever side has more room, so a row near the bottom opens upwards.
2265
+ const goAbove = spaceAbove > spaceBelow;
2266
+ if (goAbove) {
2267
+ const bottom = Math.max(12, Math.round(window.innerHeight - (rect.top - 6)));
2268
+ const maxHeight = Math.max(160, Math.min(Math.round(window.innerHeight * 0.7), spaceAbove - 6));
2269
+ setPreview({ text: match.preview || match.snippet || '', hit: match.previewHit ?? -1, left, width, maxHeight, top: null, bottom });
2270
+ } else {
2271
+ const top = Math.round(rect.bottom + 6);
2272
+ const maxHeight = Math.max(160, Math.min(Math.round(window.innerHeight * 0.7), spaceBelow - 6));
2273
+ setPreview({ text: match.preview || match.snippet || '', hit: match.previewHit ?? -1, left, width, maxHeight, top, bottom: null });
2274
+ }
2275
+ }, 1000);
2276
+ },
2277
+ onMouseLeave: () => {
2278
+ if (previewHover.current !== null) {
2279
+ window.clearTimeout(previewHover.current);
2280
+ previewHover.current = null;
2281
+ }
2282
+ if (previewTimer.current !== null) window.clearTimeout(previewTimer.current);
2283
+ previewTimer.current = window.setTimeout(() => setPreview(null), 160);
2284
+ },
2285
+ key: `${group.sessionId}-${String(match.seq ?? 'title')}-${String(index)}`,
2286
+ 'data-active': index === active ? 'true' : 'false',
2287
+ onClick: () => {
2288
+ previewEpoch.current += 1;
2289
+ if (previewHover.current !== null) {
2290
+ window.clearTimeout(previewHover.current);
2291
+ previewHover.current = null;
2292
+ }
2293
+ if (previewTimer.current !== null) window.clearTimeout(previewTimer.current);
2294
+ setPreview(null);
2295
+ open(group.sessionId, match);
2296
+ },
2297
+ },
2298
+ h('span', { className: 'dshe-match-time', 'data-tier': String(timeTier(formatMatchTime(match.time))) }, formatMatchTime(match.time)),
2299
+ h('span', { className: 'dshe-role' }, runtime.t(`role.${match.role ?? 'body'}`)),
2300
+ h('span', { className: 'dshe-snippet' }, highlight(match.snippet ?? '', search.query)),
2301
+ ))
2302
+ : null,
2303
+ );
2304
+ })
2305
+ : null,
2306
+ ),
2307
+ ),
2308
+ );
2309
+ return panel;
2310
+ }
2311
+
2312
+ // ── settings section ─────────────────────────────────────────────────────
2313
+
2314
+ function NumberField(props) {
2315
+ const [draft, setDraft] = React.useState(String(props.value));
2316
+ React.useEffect(() => setDraft(String(props.value)), [props.value]);
2317
+ const commit = () => {
2318
+ const parsed = Number.parseInt(draft, 10);
2319
+ if (!Number.isFinite(parsed)) {
2320
+ setDraft(String(props.value));
2321
+ return;
2322
+ }
2323
+ const clamped = Math.min(props.max, Math.max(props.min, parsed));
2324
+ setDraft(String(clamped));
2325
+ if (clamped !== props.value) props.onChange(clamped);
2326
+ };
2327
+ return h('input', {
2328
+ className: 'dshe-number',
2329
+ type: 'number',
2330
+ min: props.min,
2331
+ max: props.max,
2332
+ value: draft,
2333
+ 'aria-label': props.label,
2334
+ onChange: (event) => setDraft(event.target.value),
2335
+ onBlur: commit,
2336
+ onKeyDown: (event) => {
2337
+ if (event.key === 'Enter') {
2338
+ event.preventDefault();
2339
+ commit();
2340
+ }
2341
+ },
2342
+ });
2343
+ }
2344
+
2345
+ function TextField(props) {
2346
+ const [draft, setDraft] = React.useState(props.value ?? '');
2347
+ React.useEffect(() => setDraft(props.value ?? ''), [props.value]);
2348
+ const commit = () => {
2349
+ const next = draft.trim();
2350
+ if (next !== (props.value ?? '')) props.onChange(next);
2351
+ };
2352
+ return h('input', {
2353
+ className: 'dshe-text',
2354
+ type: props.type ?? 'text',
2355
+ value: draft,
2356
+ placeholder: props.placeholder ?? '',
2357
+ 'aria-label': props.label ?? props.title,
2358
+ onChange: (event) => setDraft(event.target.value),
2359
+ onBlur: commit,
2360
+ onKeyDown: (event) => {
2361
+ if (event.key === 'Enter') {
2362
+ event.preventDefault();
2363
+ commit();
2364
+ }
2365
+ },
2366
+ });
2367
+ }
2368
+
2369
+ function Row(props) {
2370
+ return h('div', { className: 'dshe-row' },
2371
+ h('div', { className: 'dshe-row-main' },
2372
+ h('div', { className: 'dshe-row-title' }, props.title),
2373
+ props.desc === undefined ? null : h('div', { className: 'dshe-row-desc' }, props.desc),
2374
+ ),
2375
+ props.control,
2376
+ );
2377
+ }
2378
+
2379
+ function SettingsSection() {
2380
+ const state = useStore();
2381
+ const settings = state.settings;
2382
+ const set = (patch) => runtime.store.saveSettings(patch);
2383
+ const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
2384
+ const trimTail = (value) => String(value ?? '').trim().replace(/[\\/]+$/u, '');
2385
+ const currentFields = {
2386
+ url: settings.webdavUrl ?? '',
2387
+ user: settings.webdavUser ?? '',
2388
+ password: settings.webdavPassword ?? '',
2389
+ root: settings.webdavRoot ?? '',
2390
+ };
2391
+ const sameFields = (a, b) => trimTail(a.url) === trimTail(b.url)
2392
+ && String(a.user ?? '').trim() === String(b.user ?? '').trim()
2393
+ && String(a.password ?? '') === String(b.password ?? '')
2394
+ && trimTail(a.root) === trimTail(b.root);
2395
+ const activePreset = presets.find((item) => sameFields(item, currentFields)) ?? null;
2396
+ const canSavePreset = trimTail(currentFields.url) !== ''
2397
+ && presets.every((item) => sameFields(item, currentFields) === false);
2398
+ const applyPreset = (item) => {
2399
+ runtime.store.cancelPresetEdit();
2400
+ set({ webdavUrl: item.url, webdavUser: item.user, webdavPassword: item.password, webdavRoot: item.root });
2401
+ };
2402
+ const syncDirValue = typeof settings.syncDir === 'string' ? settings.syncDir : '';
2403
+ const webdavUrlValue = typeof settings.webdavUrl === 'string' ? settings.webdavUrl : '';
2404
+ const effectiveDir = settings.syncMode === 'webdav'
2405
+ ? (typeof settings.mirrorDir === 'string' ? settings.mirrorDir : '')
2406
+ : syncDirValue;
2407
+ React.useEffect(() => {
2408
+ runtime.store.refreshCount();
2409
+ runtime.store.loadSync();
2410
+ }, []);
2411
+ return h('div', { className: 'dshe-section' },
2412
+ h('h2', { className: 'dshe-section-title' }, runtime.t('section.title')),
2413
+ h('p', { className: 'dshe-section-desc' }, runtime.t('section.desc')),
2414
+
2415
+ h('h3', { className: 'dshe-subsection-title' }, runtime.t('section.reading')),
2416
+ h('div', { className: 'dshe-card' },
2417
+ h(Row, {
2418
+ title: runtime.t('switch.autoLoad'),
2419
+ desc: runtime.t('switch.autoLoad.desc'),
2420
+ control: h(Switch, { label: runtime.t('switch.autoLoad'), checked: settings.autoLoadEnabled, onChange: (value) => set({ autoLoadEnabled: value }) }),
2421
+ }),
2422
+ h(Row, {
2423
+ title: runtime.t('switch.move'),
2424
+ desc: runtime.t('switch.move.desc'),
2425
+ control: h(Switch, { label: runtime.t('switch.move'), checked: settings.moveEnabled, onChange: (value) => set({ moveEnabled: value }) }),
2426
+ }),
2427
+ ),
2428
+
2429
+ h('h3', { className: 'dshe-subsection-title' }, runtime.t('section.sessions')),
2430
+ h('div', { className: 'dshe-card' },
2431
+ h(Row, {
2432
+ title: runtime.t('switch.delete'),
2433
+ desc: runtime.t('switch.delete.desc'),
2434
+ control: h(Switch, { label: runtime.t('switch.delete'), checked: settings.deleteEnabled, onChange: (value) => set({ deleteEnabled: value }) }),
2435
+ }),
2436
+ h(Row, {
2437
+ title: runtime.t('switch.trash'),
2438
+ desc: runtime.t('switch.trash.desc'),
2439
+ control: h(Switch, { label: runtime.t('switch.trash'), checked: settings.trashEnabled, onChange: (value) => set({ trashEnabled: value }) }),
2440
+ }),
2441
+ ),
2442
+ h('div', { className: 'dshe-card' },
2443
+ h(Row, {
2444
+ title: runtime.t('field.retention'),
2445
+ desc: runtime.t('field.retention.hint'),
2446
+ control: h(NumberField, { label: runtime.t('field.retention'), value: settings.retentionDays, min: 0, max: 3650, onChange: (value) => set({ retentionDays: value }) }),
2447
+ }),
2448
+ ),
2449
+ h('div', { className: 'dshe-section' },
2450
+ settings.trashEnabled === true
2451
+ ? h('button', {
2452
+ type: 'button',
2453
+ className: 'dshe-action',
2454
+ onClick: () => runtime.store.openTrash(),
2455
+ }, h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
2456
+ icon('IconArchiveOutlineRegular', { size: 14 }),
2457
+ runtime.t('trash.title'),
2458
+ ))
2459
+ : null,
2460
+ h('div', { className: 'dshe-row-desc' }, runtime.t('trash.usage', { count: state.trash.count, size: formatSize(state.trash.size) })),
2461
+ ),
2462
+
2463
+ h('h3', { className: 'dshe-subsection-title' }, runtime.t('section.search')),
2464
+ h('div', { className: 'dshe-card' },
2465
+ h(Row, {
2466
+ title: runtime.t('switch.search'),
2467
+ desc: runtime.t('switch.search.desc'),
2468
+ control: h(Switch, { label: runtime.t('switch.search'), checked: settings.searchEnabled, onChange: (value) => set({ searchEnabled: value }) }),
2469
+ }),
2470
+ ),
2471
+ h('div', { className: 'dshe-card' },
2472
+ h(Row, {
2473
+ title: runtime.t('switch.matchTitle'),
2474
+ control: h(Switch, { label: runtime.t('switch.matchTitle'), checked: settings.matchTitle, onChange: (value) => set({ matchTitle: value }) }),
2475
+ }),
2476
+ h(Row, {
2477
+ title: runtime.t('switch.matchBody'),
2478
+ control: h(Switch, { label: runtime.t('switch.matchBody'), checked: settings.matchBody, onChange: (value) => set({ matchBody: value }) }),
2479
+ }),
2480
+ h(Row, {
2481
+ title: runtime.t('switch.matchTools'),
2482
+ control: h(Switch, { label: runtime.t('switch.matchTools'), checked: settings.matchTools, onChange: (value) => set({ matchTools: value }) }),
2483
+ }),
2484
+
2485
+ ),
2486
+
2487
+ h('h3', { className: 'dshe-subsection-title' }, runtime.t('section.sync')),
2488
+ h('div', { className: 'dshe-card' },
2489
+ h(Row, {
2490
+ title: runtime.t('sync.enable'),
2491
+ desc: runtime.t('sync.enable.hint'),
2492
+ control: h(Switch, { label: runtime.t('sync.enable'), checked: settings.syncEnabled, onChange: (value) => set({ syncEnabled: value }) }),
2493
+ }),
2494
+ h(Row, {
2495
+ title: runtime.t('sync.mode'),
2496
+ control: h('span', { style: { display: 'inline-flex', gap: '6px' } },
2497
+ h('button', {
2498
+ type: 'button',
2499
+ className: `dshe-action${settings.syncMode === 'webdav' ? ' dshe-action-active' : ''}`,
2500
+ onClick: () => set({ syncMode: 'webdav' }),
2501
+ }, runtime.t('sync.mode.webdav')),
2502
+ h('button', {
2503
+ type: 'button',
2504
+ className: `dshe-action${settings.syncMode === 'webdav' ? '' : ' dshe-action-active'}`,
2505
+ onClick: () => set({ syncMode: 'local' }),
2506
+ }, runtime.t('sync.mode.local')),
2507
+ ),
2508
+ }),
2509
+ settings.syncMode === 'webdav'
2510
+ ? h(React.Fragment, {},
2511
+ h('div', { className: 'dshe-presets' },
2512
+ h('div', { className: 'dshe-presets-head' }, runtime.t('sync.webdav.presets')),
2513
+ h('div', { className: 'dshe-presets-chips' },
2514
+ h('select', {
2515
+ className: 'dshe-select',
2516
+ value: activePreset === null ? '' : activePreset.id,
2517
+ onChange: (event) => {
2518
+ const picked = presets.find((item) => item.id === event.target.value);
2519
+ if (picked !== undefined) applyPreset(picked);
2520
+ },
2521
+ },
2522
+ activePreset === null ? h('option', { value: '' }, runtime.t('sync.webdav.presets.default')) : null,
2523
+ presets.map((item) => h('option', { key: item.id, value: item.id }, item.name)),
2524
+ ),
2525
+ state.presetEdit !== null && state.presetEdit.mode === 'modify'
2526
+ ? h(React.Fragment, null,
2527
+ h('button', { key: 'commit', type: 'button', className: 'dshe-action dshe-action-active', onClick: () => runtime.store.commitPresetModify() }, runtime.t('sync.webdav.presets.commitModify')),
2528
+ h('button', { key: 'cancel', type: 'button', className: 'dshe-action', onClick: () => runtime.store.cancelPresetEdit() }, runtime.t('common.cancel')),
2529
+ )
2530
+ : state.presetEdit === null
2531
+ ? h(React.Fragment, null,
2532
+ h('button', { key: 'rename', type: 'button', className: 'dshe-action', disabled: activePreset === null, onClick: () => runtime.store.startPresetRename() }, runtime.t('sync.webdav.presets.rename')),
2533
+ h('button', { key: 'modify', type: 'button', className: 'dshe-action', disabled: activePreset === null, onClick: () => runtime.store.startPresetModify() }, runtime.t('sync.webdav.presets.modify')),
2534
+ h('button', { key: 'remove', type: 'button', className: 'dshe-action dshe-action-danger', disabled: activePreset === null, onClick: () => runtime.store.dropActivePreset() }, runtime.t('sync.webdav.presets.remove')),
2535
+ h('button', { key: 'save', type: 'button', className: 'dshe-action dshe-action-active', disabled: canSavePreset === false, onClick: () => runtime.store.startPresetSave() }, runtime.t('sync.webdav.presets.save')),
2536
+ )
2537
+ : h(React.Fragment, null,
2538
+ h(TextField, { key: 'name', title: runtime.t('sync.webdav.presets.name'), value: state.presetEdit.name, onChange: (value) => runtime.store.setPresetName(value) }),
2539
+ h('button', { key: 'ok', type: 'button', className: 'dshe-action dshe-action-active', onClick: () => runtime.store.commitPresetEdit() }, '✓'),
2540
+ h('button', { key: 'cancel', type: 'button', className: 'dshe-action', onClick: () => runtime.store.cancelPresetEdit() }, '×'),
2541
+ ),
2542
+ ),
2543
+ ),
2544
+ h(Row, {
2545
+ title: runtime.t('sync.webdav.url'),
2546
+ control: h(TextField, { title: runtime.t('sync.webdav.url'), value: webdavUrlValue, placeholder: 'https://dav.jianguoyun.com/dav/', onChange: (value) => set({ webdavUrl: value }) }),
2547
+ }),
2548
+ h(Row, {
2549
+ title: runtime.t('sync.webdav.user'),
2550
+ control: h(TextField, { title: runtime.t('sync.webdav.user'), value: settings.webdavUser, placeholder: 'user@example.com', onChange: (value) => set({ webdavUser: value }) }),
2551
+ }),
2552
+ h(Row, {
2553
+ title: runtime.t('sync.webdav.password'),
2554
+ desc: runtime.t('sync.webdav.password.hint'),
2555
+ control: h(TextField, { title: runtime.t('sync.webdav.password'), type: 'password', value: settings.webdavPassword, onChange: (value) => set({ webdavPassword: value }) }),
2556
+ }),
2557
+ h(Row, {
2558
+ title: runtime.t('sync.webdav.root'),
2559
+ desc: runtime.t('sync.webdav.root.hint'),
2560
+ control: h(TextField, { title: runtime.t('sync.webdav.root'), value: settings.webdavRoot, placeholder: '/我的坚果云/DSH-Sync', onChange: (value) => set({ webdavRoot: value }) }),
2561
+ }),
2562
+ h(Row, {
2563
+ title: runtime.t('sync.webdav.mirror'),
2564
+ desc: state.sync.target !== null && state.sync.target.usage !== null && state.sync.target.usage !== undefined
2565
+ ? runtime.t('sync.webdav.mirror.usage', { size: formatSize(state.sync.target.usage.bytes), files: state.sync.target.usage.files })
2566
+ : undefined,
2567
+ control: h(TextField, { title: runtime.t('sync.webdav.mirror'), value: settings.mirrorDir, onChange: (value) => set({ mirrorDir: value }) }),
2568
+ }),
2569
+ h(Row, {
2570
+ title: runtime.t('sync.webdav.autoCreate'),
2571
+ desc: runtime.t('sync.webdav.autoCreate.desc'),
2572
+ control: h(Switch, { label: runtime.t('sync.webdav.autoCreate'), checked: settings.webdavAutoCreate, onChange: (value) => set({ webdavAutoCreate: value }) }),
2573
+ }),
2574
+ h(Row, {
2575
+ title: runtime.t('sync.webdav.test'),
2576
+ desc: state.sync.webdav === null
2577
+ ? undefined
2578
+ : (state.sync.webdav.ok === true
2579
+ ? runtime.t('sync.webdav.ok', { message: state.sync.webdav.message })
2580
+ : runtime.t('sync.webdav.fail', { message: state.sync.webdav.message })),
2581
+ control: h('button', {
2582
+ type: 'button',
2583
+ className: 'dshe-action',
2584
+ disabled: state.sync.webdavBusy === true,
2585
+ onClick: () => runtime.store.testWebdav(),
2586
+ }, state.sync.webdavBusy === true ? runtime.t('sync.webdav.testing') : runtime.t('sync.webdav.test')),
2587
+ }),
2588
+ )
2589
+ : h(Row, {
2590
+ title: runtime.t('sync.dir'),
2591
+ control: h(TextField, { title: runtime.t('sync.dir'), value: syncDirValue, placeholder: 'D:\\Synced\\DSH', onChange: (value) => set({ syncDir: value }) }),
2592
+ }),
2593
+ h(Row, {
2594
+ title: runtime.t('sync.machine'),
2595
+ desc: runtime.t('sync.machine.hint'),
2596
+ control: h(TextField, {
2597
+ title: runtime.t('sync.machine'),
2598
+ value: settings.syncMachineId,
2599
+ placeholder: state.sync.target === null || state.sync.target.machineId === undefined
2600
+ ? ''
2601
+ : runtime.t('sync.machine.placeholder', { id: state.sync.target.machineId }),
2602
+ onChange: (value) => set({ syncMachineId: value }),
2603
+ }),
2604
+ }),
2605
+ h(Row, {
2606
+ title: runtime.t('sync.attachments'),
2607
+ control: h(Switch, { label: runtime.t('sync.attachments'), checked: settings.syncSkipAttachments !== true, onChange: (value) => set({ syncSkipAttachments: !value }) }),
2608
+ }),
2609
+ h(Row, {
2610
+ title: runtime.t('sync.idle'),
2611
+ desc: runtime.t('sync.idle.desc'),
2612
+ control: h(Switch, { label: runtime.t('sync.idle'), checked: settings.syncOnIdle, onChange: (value) => set({ syncOnIdle: value }) }),
2613
+ }),
2614
+ h(Row, {
2615
+ title: runtime.t('sync.interval'),
2616
+ desc: runtime.t('sync.interval.hint'),
2617
+ control: h(NumberField, { label: runtime.t('sync.interval'), value: settings.syncIntervalMinutes, min: 0, max: 1440, onChange: (value) => set({ syncIntervalMinutes: value }) }),
2618
+ }),
2619
+ h(Row, {
2620
+ title: runtime.t('sync.daily'),
2621
+ desc: runtime.t('sync.daily.hint'),
2622
+ control: h(TextField, { title: runtime.t('sync.daily'), value: settings.syncDailyAt, placeholder: 'HH:MM', onChange: (value) => set({ syncDailyAt: value }) }),
2623
+ }),
2624
+ h(Row, {
2625
+ title: runtime.t('sync.cooldown'),
2626
+ control: h(NumberField, { label: runtime.t('sync.cooldown'), value: settings.syncCooldownMinutes, min: 1, max: 240, onChange: (value) => set({ syncCooldownMinutes: value }) }),
2627
+ }),
2628
+ ),
2629
+ h('div', { className: 'dshe-section' },
2630
+ h('div', { style: { display: 'flex', gap: '8px', flexWrap: 'wrap' } },
2631
+ h('button', {
2632
+ type: 'button',
2633
+ className: 'dshe-action',
2634
+ title: runtime.t('sync.run.hint'),
2635
+ disabled: state.sync.busy === true,
2636
+ onClick: () => runtime.store.runSyncNow(),
2637
+ }, runtime.t('sync.run')),
2638
+ h('button', {
2639
+ type: 'button',
2640
+ className: 'dshe-action',
2641
+ disabled: state.sync.busy === true,
2642
+ onClick: () => runtime.store.openOverwrite('cloud'),
2643
+ }, runtime.t('overwrite.cloud')),
2644
+ h('button', {
2645
+ type: 'button',
2646
+ className: 'dshe-action',
2647
+ disabled: state.sync.busy === true,
2648
+ onClick: () => runtime.store.openOverwrite('local'),
2649
+ }, runtime.t('overwrite.local')),
2650
+ h('button', {
2651
+ type: 'button',
2652
+ className: 'dshe-action',
2653
+ onClick: () => runtime.store.toggleSyncLog(),
2654
+ }, state.sync.showLog === true ? runtime.t('sync.logHide') : runtime.t('sync.log')),
2655
+ h('button', {
2656
+ type: 'button',
2657
+ className: 'dshe-action',
2658
+ disabled: state.envCheck.busy === true,
2659
+ onClick: () => runtime.store.runEnvCheck(),
2660
+ }, state.envCheck.busy === true ? runtime.t('env.busy') : runtime.t('env.button')),
2661
+ h('button', {
2662
+ type: 'button',
2663
+ className: 'dshe-action',
2664
+ title: runtime.t('restart.hint'),
2665
+ onClick: () => runtime.store.openRestart(),
2666
+ }, runtime.t('restart.button')),
2667
+ ),
2668
+ state.sync.showLog === true ? null : h('button', {
2669
+ type: 'button',
2670
+ className: 'dshe-row-desc dshe-log-toggle',
2671
+ title: runtime.t('sync.logToggle'),
2672
+ onClick: () => runtime.store.toggleSyncLog(),
2673
+ }, syncStatusLine(state, settings)),
2674
+ effectiveDir === ''
2675
+ ? h('div', { className: 'dshe-row-desc dshe-error' }, runtime.t(settings.syncMode === 'webdav' ? 'sync.needMirror' : 'sync.needDir'))
2676
+ : null,
2677
+ state.sync.target !== null
2678
+ && settings.syncMode !== 'webdav'
2679
+ && state.sync.target.syncDirConfigured === true
2680
+ && state.sync.target.syncDirExists === false
2681
+ ? h('div', { className: 'dshe-row-desc dshe-error' }, runtime.t('sync.dirMissing', { path: state.sync.target.syncDir }))
2682
+ : null,
2683
+ state.sync.error === null
2684
+ ? null
2685
+ : h('div', { className: 'dshe-row-desc dshe-error', role: 'alert' }, String(state.sync.error)),
2686
+ state.sync.showLog === true
2687
+ ? h('div', {},
2688
+ h('div', { className: 'dshe-row-desc' }, runtime.t('sync.historyCount', { n: logEntries(state).length })),
2689
+ h('div', { className: 'dshe-log-list dshe-log-scroll' },
2690
+ logEntries(state).slice(0, Number(state.sync.historyLimit) || 20).map((item, index) => {
2691
+ const open = state.sync.historyOpen === index;
2692
+ return h('div', { key: item.at ?? String(index), className: 'dshe-log-item' },
2693
+ h('button', {
2694
+ type: 'button',
2695
+ className: `dshe-log-row${open ? ' dshe-log-row-open' : ''}`,
2696
+ onClick: () => runtime.store.openHistory(index),
2697
+ },
2698
+ h('span', {}, historyLine(item.entry)),
2699
+ h('span', { className: 'dshe-log-caret' }, open ? '▾' : '▸')),
2700
+ open ? h('div', { className: 'dshe-sync-log dshe-log-body' }, (item.log ?? []).map((line, lineIndex) => h(LogLine, { key: lineIndex, line, files: item.details?.[lineIndex] ?? [] }))) : null);
2701
+ }),
2702
+ ),
2703
+ logEntries(state).length > (Number(state.sync.historyLimit) || 20)
2704
+ ? h('button', { type: 'button', className: 'dshe-action', onClick: () => runtime.store.showMoreHistory() }, runtime.t('sync.more'))
2705
+ : null,
2706
+ )
2707
+ : null,
2708
+ ),
2709
+ );
2710
+ }
2711
+
2712
+ /** One log line: label column justified, rest flows normally. */
2713
+ function LogLine(props) {
2714
+ const [open, setOpen] = React.useState(false);
2715
+ const files = Array.isArray(props.files) ? props.files : [];
2716
+ const raw = String(props.line ?? '');
2717
+ const indent = raw.length - raw.trimStart().length;
2718
+ const text = raw.trimStart();
2719
+ const cut = text.indexOf(':');
2720
+ if (cut <= 0) {
2721
+ return h('div', { key: props.key, className: 'dshe-log-line dshe-log-line-plain' }, text);
2722
+ }
2723
+ const sub = indent > 0;
2724
+ const detail = files.length === 0
2725
+ ? null
2726
+ : h('div', { className: 'dshe-log-files' }, files.slice(0, 200).map((file, index) => h('div', { key: index, className: 'dshe-log-file' }, file)));
2727
+ return h('div', { key: props.key, className: 'dshe-log-entry' },
2728
+ h('div', {
2729
+ className: `dshe-log-line${sub ? ' dshe-log-line-sub' : ''}${files.length > 0 ? ' dshe-log-line-more' : ''}`,
2730
+ title: files.length === 0 ? undefined : files.slice(0, 15).join('\n') + (files.length > 15 ? `\n…共 ${String(files.length)} 项` : ''),
2731
+ onClick: files.length === 0 ? undefined : () => setOpen((value) => !value),
2732
+ },
2733
+ h('span', { className: 'dshe-log-label' }, text.slice(0, cut)),
2734
+ h('span', { className: 'dshe-log-colon' }, ':'),
2735
+ h('span', { className: 'dshe-log-text' }, text.slice(cut + 1)),
2736
+ files.length === 0 ? null : h('span', { className: 'dshe-log-more' }, open ? '▾' : '▸')),
2737
+ open && detail !== null ? detail : null);
2738
+ }
2739
+
2740
+ /** Outline trash glyph used in the counter line (inherits text colour). */
2741
+ function TrashIcon() {
2742
+ return h('svg', {
2743
+ width: 12,
2744
+ height: 12,
2745
+ viewBox: '0 0 24 24',
2746
+ fill: 'none',
2747
+ stroke: 'currentColor',
2748
+ strokeWidth: 2,
2749
+ strokeLinecap: 'round',
2750
+ strokeLinejoin: 'round',
2751
+ 'aria-hidden': 'true',
2752
+ style: { verticalAlign: '-2px', margin: '0 1px' },
2753
+ },
2754
+ h('path', { d: 'M4 7h16' }),
2755
+ h('path', { d: 'M9 7V5h6v2' }),
2756
+ h('path', { d: 'M18 7l-1 13H7L6 7' }),
2757
+ h('path', { d: 'M10 11v6' }),
2758
+ h('path', { d: 'M14 11v6' }));
2759
+ }
2760
+
2761
+ /** ↑ pushed · ↓ pulled · 🗑 deleted, with the icon drawn as SVG. */
2762
+ function countsNode(up, down, deleted, details) {
2763
+ const tip = (list, label) => {
2764
+ if (!Array.isArray(list) || list.length === 0) return undefined;
2765
+ const head = list.slice(0, 15).join('\n');
2766
+ return list.length > 15 ? `${label}\n${head}\n…共 ${String(list.length)} 项` : `${label}\n${head}`;
2767
+ };
2768
+ return h('span', { className: 'dshe-counts' },
2769
+ h('span', { title: tip(details?.up, '上传') }, `⬆ ${String(Number(up) || 0)}`),
2770
+ ' · ',
2771
+ h('span', { title: tip(details?.down, '下载') }, `⬇ ${String(Number(down) || 0)}`),
2772
+ ' · ',
2773
+ h(TrashIcon, {}),
2774
+ h('span', { title: tip(details?.del, '删除') }, ` ${String(Number(deleted) || 0)}`));
2775
+ }
2776
+
2777
+ /** Latest run first, then the stored history, each with its own log slice. */
2778
+ function logEntries(state) {
2779
+ const list = [];
2780
+ const current = state.sync.state;
2781
+ const history = Array.isArray(state.sync.history) ? state.sync.history : [];
2782
+ const detailOf = (...candidates) => {
2783
+ for (const candidate of candidates) {
2784
+ if (Array.isArray(candidate?.details)) return candidate.details;
2785
+ }
2786
+ return [];
2787
+ };
2788
+ if (current !== null && current !== undefined) {
2789
+ const same = history[0] !== undefined && history[0].at === current.at;
2790
+ list.push({
2791
+ at: current.at,
2792
+ entry: same ? { ...current, ...history[0] } : current,
2793
+ log: Array.isArray(current.log) ? current.log : [],
2794
+ details: detailOf(current, history[0]),
2795
+ });
2796
+ }
2797
+ for (const item of history) {
2798
+ if (list.length > 0 && item.at === list[0].at) continue;
2799
+ list.push({ at: item.at, entry: item, log: Array.isArray(item.log) ? item.log : [], details: detailOf(item) });
2800
+ }
2801
+ return list;
2802
+ }
2803
+
2804
+ /** One compact line for one stored run. */
2805
+ function historyLine(item) {
2806
+ const when = typeof item.at === 'string' ? new Date(item.at).toLocaleString() : '';
2807
+ const result = item.ok === true ? runtime.t('sync.result.ok') : runtime.t('sync.result.fail');
2808
+ const up = Number(item.counts?.up ?? item.pushed ?? item.uploaded ?? 0) || 0;
2809
+ const down = Number(item.counts?.down ?? item.pulled ?? item.downloaded ?? 0) || 0;
2810
+ const del = Number(item.counts?.del ?? item.deleted ?? 0) || 0;
2811
+ const failed = Number(item.failed) > 0 ? ` · ✗${String(item.failed)}` : '';
2812
+ const label = typeof item.targetLabel === 'string' && item.targetLabel !== '' ? `${item.targetLabel} · ` : '';
2813
+ return h('span', {}, `${when} · ${result} · ${label}${String(Number(item.durationMs) || 0)} ms · `, countsNode(up, down, del, item.countDetails), failed);
2814
+ }
2815
+
2816
+
2817
+ /** Width of the settings panel this page is rendered in, for relative sizing. */
2818
+ function measureSettingsPanel() {
2819
+ let node = document.querySelector('.dshe-section');
2820
+ while (node !== null && node !== document.body) {
2821
+ const width = node.getBoundingClientRect().width;
2822
+ if (width > 600) return Math.round(width);
2823
+ node = node.parentElement;
2824
+ }
2825
+ return 0;
2826
+ }
2827
+
2828
+
2829
+ function syncStatusLine(state, settings) {
2830
+ const record = state.sync.state;
2831
+ if (record === null || record === undefined) return runtime.t('sync.never');
2832
+ const when = typeof record.at === 'string' ? new Date(record.at).toLocaleString() : '';
2833
+ const base = runtime.t('sync.last', {
2834
+ time: when,
2835
+ result: record.ok === true ? runtime.t('sync.result.ok') : runtime.t('sync.result.fail'),
2836
+ ms: Number(record.durationMs) || 0,
2837
+ });
2838
+ // One shape everywhere: ↑ pushed · ↓ pulled · 🗑 deleted.
2839
+ const pushed = record.counts?.up ?? record.summary?.sessions?.pushed ?? record.transport?.pushed?.uploaded ?? 0;
2840
+ const pulled = record.counts?.down ?? record.summary?.sessions?.pulled ?? record.transport?.pulled?.downloaded ?? 0;
2841
+ const removed = record.counts?.del ?? record.transport?.pushed?.deleted ?? record.summary?.prune?.sharedDeleted ?? 0;
2842
+
2843
+ const transport = record.transport;
2844
+ const extras = [];
2845
+ if (Number(record.trashPurged) > 0) extras.push(runtime.t('sync.purged', { n: Number(record.trashPurged) }));
2846
+ const paths = record.summary?.paths;
2847
+ if (paths !== null && paths !== undefined && (Number(paths.created) > 0 || Number(paths.failed) > 0)) {
2848
+ extras.push(runtime.t('sync.paths', { created: Number(paths.created) || 0, failed: Number(paths.failed) || 0 }));
2849
+ }
2850
+ const failures = (record.transport?.pushed?.failed?.length ?? 0) + (record.transport?.pulled?.failed?.length ?? 0);
2851
+ if (failures > 0) extras.push(runtime.t('sync.failed', { n: failures }));
2852
+ const tail = extras.length === 0 ? '' : ` · ${extras.join(' · ')}`;
2853
+ const skipped = transport?.pushed?.deleteSkipped;
2854
+ const note = typeof skipped === 'string' && skipped !== '' ? ` · ${skipped}` : '';
2855
+ return h('span', {}, `${base} · 传输:`, countsNode(pushed, pulled, removed, record.countDetails), `${tail}${note}`);
2856
+ }
2857
+
2858
+ // ── toast ────────────────────────────────────────────────────────────────
2859
+
2860
+ /**
2861
+ * Writes the toast straight into <body>.
2862
+ *
2863
+ * The overlay slot sits inside the settings dialog's stacking context, so a
2864
+ * fixed child still renders under that dialog. Appending to body escapes it.
2865
+ */
2866
+ function Toasts() {
2867
+ const state = useStore();
2868
+ const toast = state.toast;
2869
+ React.useEffect(() => {
2870
+ let host = document.getElementById('dshe-toast-host');
2871
+ if (host === null) {
2872
+ host = document.createElement('div');
2873
+ host.id = 'dshe-toast-host';
2874
+ document.body.appendChild(host);
2875
+ }
2876
+ // A full-window flex box keeps every toast dead centre; rewriting it each
2877
+ // time also repairs a host left behind by an older build.
2878
+ host.style.cssText = 'position:fixed;top:33vh;left:0;right:0;display:flex;justify-content:center;pointer-events:none;z-index:2147483000';
2879
+ host.textContent = '';
2880
+ if (toast === null || toast === undefined) return;
2881
+ const node = document.createElement('div');
2882
+ node.className = 'dshe-toast';
2883
+ node.dataset.kind = String(toast.kind ?? 'info');
2884
+ node.setAttribute('role', toast.kind === 'error' ? 'alert' : 'status');
2885
+ node.style.position = 'static';
2886
+ node.style.transform = 'none';
2887
+ node.style.left = 'auto';
2888
+ node.style.bottom = 'auto';
2889
+ node.textContent = String(toast.text ?? '');
2890
+ if (toast.spinner === true) {
2891
+ const spinner = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2892
+ spinner.setAttribute('class', 'dshe-toast-spinner');
2893
+ spinner.setAttribute('viewBox', '0 0 16 16');
2894
+ spinner.setAttribute('aria-hidden', 'true');
2895
+ const track = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
2896
+ track.setAttribute('cx', '8');
2897
+ track.setAttribute('cy', '8');
2898
+ track.setAttribute('r', '6');
2899
+ track.setAttribute('fill', 'none');
2900
+ track.setAttribute('stroke', 'rgba(255,255,255,.28)');
2901
+ track.setAttribute('stroke-width', '2');
2902
+ const arc = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
2903
+ arc.setAttribute('cx', '8');
2904
+ arc.setAttribute('cy', '8');
2905
+ arc.setAttribute('r', '6');
2906
+ arc.setAttribute('fill', 'none');
2907
+ arc.setAttribute('stroke', '#fff');
2908
+ arc.setAttribute('stroke-width', '2');
2909
+ arc.setAttribute('stroke-linecap', 'round');
2910
+ arc.setAttribute('stroke-dasharray', '26 12');
2911
+ spinner.appendChild(track);
2912
+ spinner.appendChild(arc);
2913
+ node.appendChild(spinner);
2914
+ }
2915
+ const release = armQuickClose(node, () => { node.remove(); });
2916
+ host.appendChild(node);
2917
+ return () => {
2918
+ release();
2919
+ node.remove();
2920
+ };
2921
+ }, [toast]);
2922
+ return null;
2923
+ }
2924
+
2925
+ /**
2926
+ * The automatic-sync hint, parked on the composer status row.
2927
+ *
2928
+ * The dock entry itself renders nothing: it only marks where the row is. The
2929
+ * visible node lives on document.body and is aligned to the row's own measured
2930
+ * rectangle on every layout change, so it keeps that row's baseline and right
2931
+ * edge without hard-coded offsets.
2932
+ */
2933
+ function SyncRunningBadge() {
2934
+ const state = useStore();
2935
+ // Manual runs own their centred toast, but the status line follows them too.
2936
+ const live = state.syncLive === true || state.sync.busy === true;
2937
+ const done = state.syncDone === true;
2938
+ const show = live || done;
2939
+ const markerRef = React.useRef(null);
2940
+
2941
+ React.useEffect(() => {
2942
+ if (!show) return undefined;
2943
+ const holder = markerRef.current;
2944
+ if (holder === null) return undefined;
2945
+ const ownRow = holder.parentElement;
2946
+ const dock = ownRow === null ? null : ownRow.parentElement;
2947
+ if (dock === null) return undefined;
2948
+
2949
+ const node = document.createElement('div');
2950
+ node.className = 'dshe-sync-inline';
2951
+ node.style.cssText = [
2952
+ 'position:fixed',
2953
+ 'z-index:2147483001',
2954
+ 'pointer-events:none',
2955
+ 'display:inline-flex',
2956
+ 'align-items:center',
2957
+ 'gap:6px',
2958
+ 'font-size:12px',
2959
+ 'line-height:16px',
2960
+ 'color:var(--dsw-alias-label-secondary, currentColor)',
2961
+ 'white-space:nowrap',
2962
+ ].join(';');
2963
+ const label = document.createElement('span');
2964
+ label.textContent = runtime.t(live ? 'sync.running' : 'sync.done');
2965
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2966
+ svg.setAttribute('class', live ? 'dshe-toast-spinner' : 'dshe-sync-done');
2967
+ svg.setAttribute('viewBox', '0 0 16 16');
2968
+ svg.setAttribute('width', '12');
2969
+ svg.setAttribute('height', '12');
2970
+ svg.setAttribute('aria-hidden', 'true');
2971
+ svg.style.flex = 'none';
2972
+ if (live) {
2973
+ const track = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
2974
+ track.setAttribute('cx', '8');
2975
+ track.setAttribute('cy', '8');
2976
+ track.setAttribute('r', '6');
2977
+ track.setAttribute('fill', 'none');
2978
+ track.setAttribute('stroke', 'currentColor');
2979
+ track.setAttribute('stroke-opacity', '0.25');
2980
+ track.setAttribute('stroke-width', '2');
2981
+ const arc = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
2982
+ arc.setAttribute('cx', '8');
2983
+ arc.setAttribute('cy', '8');
2984
+ arc.setAttribute('r', '6');
2985
+ arc.setAttribute('fill', 'none');
2986
+ arc.setAttribute('stroke', 'currentColor');
2987
+ arc.setAttribute('stroke-width', '2');
2988
+ arc.setAttribute('stroke-linecap', 'round');
2989
+ arc.setAttribute('stroke-dasharray', '26 12');
2990
+ svg.appendChild(track);
2991
+ svg.appendChild(arc);
2992
+ } else {
2993
+ // Finished: a quiet tick instead of the turning ring.
2994
+ const tick = document.createElementNS('http://www.w3.org/2000/svg', 'path');
2995
+ tick.setAttribute('d', 'M3.5 8.5 L6.5 11.5 L12.5 4.5');
2996
+ tick.setAttribute('fill', 'none');
2997
+ tick.setAttribute('stroke', 'currentColor');
2998
+ tick.setAttribute('stroke-width', '1.8');
2999
+ tick.setAttribute('stroke-linecap', 'round');
3000
+ tick.setAttribute('stroke-linejoin', 'round');
3001
+ svg.appendChild(tick);
3002
+ }
3003
+ node.appendChild(label);
3004
+ node.appendChild(svg);
3005
+ document.body.appendChild(node);
3006
+
3007
+ // The last foreign row of the dock is the status line; our own row keeps
3008
+ // its normal place, so the shipped text never moves.
3009
+ const measure = () => {
3010
+ if (!node.isConnected) return;
3011
+ const rows = Array.from(dock.children).filter((child) => child !== ownRow);
3012
+ const anchor = rows.length > 0 ? rows[rows.length - 1] : dock;
3013
+ const rect = anchor.getBoundingClientRect();
3014
+ if (rect.width === 0 || rect.height === 0) return;
3015
+ const width = node.offsetWidth;
3016
+ const height = node.offsetHeight;
3017
+ const right = Math.max(12, window.innerWidth - 16);
3018
+ const left = Math.max(12, right - width);
3019
+ const top = Math.max(0, rect.top + (rect.height - height) / 2);
3020
+ node.style.left = Math.round(left) + 'px';
3021
+ node.style.top = Math.round(top) + 'px';
3022
+ };
3023
+
3024
+ measure();
3025
+ const frame = window.requestAnimationFrame(measure);
3026
+ // One late pass covers fonts and row heights that settle after the frame.
3027
+ const settle = window.setTimeout(measure, 300);
3028
+ window.addEventListener('resize', measure);
3029
+ // The row only moves when its container changes size, so observing the dock
3030
+ // is enough; no timer keeps running while the line just sits there.
3031
+ let observer = null;
3032
+ if (typeof ResizeObserver === 'function') {
3033
+ observer = new ResizeObserver(() => { measure(); });
3034
+ observer.observe(dock);
3035
+ }
3036
+ return () => {
3037
+ window.cancelAnimationFrame(frame);
3038
+ window.clearTimeout(settle);
3039
+ window.removeEventListener('resize', measure);
3040
+ if (observer !== null) observer.disconnect();
3041
+ node.remove();
3042
+ };
3043
+ }, [show, live]);
3044
+
3045
+ if (!show) return null;
3046
+ return h('span', { ref: markerRef, style: { display: 'none' } });
3047
+ }
3048
+
3049
+ /** Environment check result, including the "export report" path. */
3050
+ function EnvDialog() {
3051
+ const state = useStore();
3052
+ if (state.envCheck.open !== true) return null;
3053
+ if (primitives?.Modal === undefined) return null;
3054
+ const result = state.envCheck.result;
3055
+ const busy = state.envCheck.busy === true;
3056
+ const close = () => runtime.store.closeEnvCheck();
3057
+ if (busy) {
3058
+ return h(primitives.Modal, { open: true, onClose: close, closeLabel: runtime.t('common.close'), title: runtime.t('env.title') },
3059
+ h('p', { className: 'dshe-section-desc' }, runtime.t('env.busy')));
3060
+ }
3061
+ if (result?.ok === true) {
3062
+ return h(primitives.Modal, { open: true, onClose: close, closeLabel: runtime.t('common.close'), title: runtime.t('env.title') },
3063
+ h('p', { className: 'dshe-section-desc' }, runtime.t('env.ok')),
3064
+ h('div', { className: 'dshe-row-desc' }, runtime.t('env.versionLine', { app: result.appVersion ?? '未知', plugin: result.pluginVersion })));
3065
+ }
3066
+ const rows = (result?.checks ?? []).filter((item) => item.ok !== true);
3067
+ return h(primitives.Modal, {
3068
+ open: true,
3069
+ onClose: close,
3070
+ closeLabel: runtime.t('common.close'),
3071
+ title: runtime.t('env.title'),
3072
+ footer: h(React.Fragment, {},
3073
+ h('button', { type: 'button', className: 'dshe-action', onClick: close }, runtime.t('common.cancel')),
3074
+ h('button', { type: 'button', className: 'dshe-action dshe-action-danger', onClick: () => runtime.store.writeEnvReport() }, runtime.t('env.report'))),
3075
+ },
3076
+ h('p', { className: 'dshe-section-desc' }, runtime.t('env.risk', { n: Number(result?.failedCount) || rows.length })),
3077
+ h('div', { className: 'dshe-log-body' }, rows.slice(0, 12).map((item, index) => h('div', { key: index, className: 'dshe-log-line' },
3078
+ h('span', { className: 'dshe-log-label' }, item.label),
3079
+ h('span', { className: 'dshe-log-colon' }, ':'),
3080
+ h('span', { className: 'dshe-log-text' }, String(item.detail ?? ''))))));
3081
+ }
3082
+
3083
+ /** Confirm an application restart (a running turn would be interrupted). */
3084
+ function RestartDialog() {
3085
+ const state = useStore();
3086
+ if (state.restartConfirm !== true) return null;
3087
+ if (primitives?.Modal === undefined) return null;
3088
+ return h(primitives.Modal, {
3089
+ open: true,
3090
+ onClose: () => runtime.store.closeRestart(),
3091
+ closeLabel: runtime.t('common.close'),
3092
+ title: runtime.t('restart.button'),
3093
+ footer: h(React.Fragment, {},
3094
+ h('button', { type: 'button', className: 'dshe-action', onClick: () => runtime.store.closeRestart() }, runtime.t('common.cancel')),
3095
+ h('button', { type: 'button', className: 'dshe-action dshe-action-danger', onClick: () => runtime.store.confirmRestart() }, runtime.t('restart.confirm'))),
3096
+ },
3097
+ h('p', { className: 'dshe-section-desc' }, runtime.t('restart.desc')));
3098
+ }
3099
+
3100
+ /** Pick which saved setup a new one replaces when all three slots are taken. */
3101
+ function PresetReplaceDialog() {
3102
+ const state = useStore();
3103
+ if (state.presetReplace === null || state.presetReplace.open !== true) return null;
3104
+ if (primitives?.Modal === undefined) return null;
3105
+ const presets = Array.isArray(state.settings.webdavProfiles) ? state.settings.webdavProfiles : [];
3106
+ return h(primitives.Modal, {
3107
+ open: true,
3108
+ onClose: () => runtime.store.closePresetReplace(),
3109
+ closeLabel: runtime.t('common.close'),
3110
+ title: runtime.t('sync.webdav.presets.replaceTitle'),
3111
+ footer: h(React.Fragment, {},
3112
+ h('button', { type: 'button', className: 'dshe-action', onClick: () => runtime.store.closePresetReplace() }, runtime.t('common.cancel'))),
3113
+ },
3114
+ h('p', { className: 'dshe-section-desc' }, runtime.t('sync.webdav.presets.replaceDesc')),
3115
+ h('div', { className: 'dshe-presets-chips' },
3116
+ presets.map((item) => h('button', {
3117
+ key: item.id,
3118
+ type: 'button',
3119
+ className: 'dshe-action dshe-action-danger',
3120
+ onClick: () => runtime.store.confirmPresetReplace(item.id),
3121
+ }, item.name))));
3122
+ }
3123
+
3124
+ /** Confirm a one-way overwrite of the cloud or of this machine. */
3125
+ function OverwriteDialog() {
3126
+ const state = useStore();
3127
+ const overwrite = state.overwrite;
3128
+ if (overwrite.open !== true) return null;
3129
+ if (primitives?.Modal === undefined) return null;
3130
+ const toCloud = overwrite.direction === 'cloud';
3131
+ const away = toCloud ? runtime.t('overwrite.awayCloud') : runtime.t('overwrite.awayLocal');
3132
+ return h(primitives.Modal, {
3133
+ open: true,
3134
+ onClose: () => runtime.store.closeOverwrite(),
3135
+ closeLabel: runtime.t('common.close'),
3136
+ title: toCloud ? runtime.t('overwrite.cloud') : runtime.t('overwrite.local'),
3137
+ footer: h(React.Fragment, {},
3138
+ h('button', { type: 'button', className: 'dshe-action', onClick: () => runtime.store.closeOverwrite() }, runtime.t('common.cancel')),
3139
+ h('button', {
3140
+ type: 'button',
3141
+ className: 'dshe-action dshe-action-danger',
3142
+ disabled: overwrite.busy === true,
3143
+ onClick: () => runtime.store.confirmOverwrite(),
3144
+ }, overwrite.busy === true ? runtime.t('overwrite.running') : runtime.t('overwrite.confirm'))),
3145
+ },
3146
+ h('p', { className: 'dshe-section-desc' }, away),
3147
+ overwrite.error === null
3148
+ ? null
3149
+ : h('div', { className: 'dshe-row-desc dshe-error', role: 'alert' }, overwrite.error));
3150
+ }
3151
+
3152
+ /** Shown when automatic sync paused after repeated failures. */
3153
+ function PauseDialog() {
3154
+ const state = useStore();
3155
+ if (state.pauseOpen !== true) return null;
3156
+ if (primitives?.Modal === undefined) return null;
3157
+ const auto = state.sync.auto;
3158
+ const last = state.sync.state?.diagnosis;
3159
+ return h(primitives.Modal, {
3160
+ open: true,
3161
+ onClose: () => runtime.store.dismissPauseNotice(),
3162
+ closeLabel: runtime.t('common.close'),
3163
+ title: runtime.t('pause.title'),
3164
+ footer: h(React.Fragment, {},
3165
+ h('button', { type: 'button', className: 'dshe-action', onClick: () => runtime.store.dismissPauseNotice() }, runtime.t('common.close')),
3166
+ h('button', { type: 'button', className: 'dshe-action dshe-action-active', onClick: () => runtime.store.resumeAutoSync() }, runtime.t('pause.resume'))),
3167
+ },
3168
+ h('p', { className: 'dshe-section-desc' }, runtime.t('pause.desc', { n: Number(auto?.failures) || 0 })),
3169
+ last === null || last === undefined
3170
+ ? null
3171
+ : h('div', { className: 'dshe-row-desc' }, runtime.t('pause.last', { summary: last.summary, hint: last.hint })));
3172
+ }
3173
+
3174
+ /** Shown once when the host application version changed since the last run. */
3175
+ function UpdateDialog() {
3176
+ const state = useStore();
3177
+ if (state.updatePrompt.open !== true) return null;
3178
+ if (primitives?.Modal === undefined) return null;
3179
+ return h(primitives.Modal, {
3180
+ open: true,
3181
+ onClose: () => runtime.store.dismissUpdatePrompt(),
3182
+ closeLabel: runtime.t('common.close'),
3183
+ title: runtime.t('env.update.title'),
3184
+ footer: h(React.Fragment, {},
3185
+ h('button', { type: 'button', className: 'dshe-action', onClick: () => runtime.store.dismissUpdatePrompt() }, runtime.t('env.update.no')),
3186
+ h('button', { type: 'button', className: 'dshe-action dshe-action-active', onClick: () => runtime.store.acceptUpdatePrompt() }, runtime.t('env.update.yes'))),
3187
+ },
3188
+ h('p', { className: 'dshe-section-desc' }, runtime.t('env.update.desc', {
3189
+ app: state.updatePrompt.appVersion ?? '',
3190
+ last: state.updatePrompt.lastAppVersion ?? '',
3191
+ })));
3192
+ }
3193
+
3194
+ function OverlayStack() {
3195
+ return h(React.Fragment, {}, h(DeleteDialog, {}), h(MoveDialog, {}), h(TrashDialog, {}), h(EnvDialog, {}), h(UpdateDialog, {}), h(PauseDialog, {}), h(OverwriteDialog, {}), h(RestartDialog, {}), h(PresetReplaceDialog, {}), h(Toasts, {}));
3196
+ }
3197
+
3198
+ // ── plugin ───────────────────────────────────────────────────────────────
3199
+
3200
+ return {
3201
+ inject: ['slots', 'locale', 'uiWorkspace'],
3202
+ apply(ctx) {
3203
+ const store = createStore();
3204
+ runtime.store = store;
3205
+ const t = ctx.locale.bind(NS);
3206
+ runtime.t = t;
3207
+ runtime.openSession = (sessionId) => {
3208
+ try {
3209
+ ctx.uiWorkspace.openSession(sessionId);
3210
+ } catch (error) {
3211
+ console.warn('[dsh-enhanced] opening the session failed:', error);
3212
+ }
3213
+ };
3214
+ /**
3215
+ * Reconnect a workspace so its session list is rebuilt by the host.
3216
+ * Reloading the page cannot be used here: a reload right after a data
3217
+ * change makes the next boot fail to import this plugin's entry.
3218
+ */
3219
+ runtime.refreshWorkspace = async (workspaceId) => {
3220
+ if (typeof workspaceId !== 'string' || workspaceId === '') return;
3221
+ try {
3222
+ await ctx.uiWorkspace.openWorkspace(workspaceId);
3223
+ } catch (error) {
3224
+ console.warn('[dsh-enhanced] refreshing the workspace failed:', error);
3225
+ }
3226
+ };
3227
+ /**
3228
+ * Scroll to the start of one turn.
3229
+ *
3230
+ * Text-level precision inside a turn is not reliable: the same sentence can
3231
+ * appear in the prompt and in the reply, and markdown rendering shifts the
3232
+ * offsets. Landing on the turn boundary is predictable.
3233
+ */
3234
+ /** Normalise for a loose containment check: markdown noise and spaces out. */
3235
+ const looseText = (value) => String(value ?? '').replace(/[\s`*_#>~\[\]()…⋯]/gu, '').toLowerCase();
3236
+
3237
+ /** Keep only letters and digits: markdown markers differ between log and UI. */
3238
+ const bareText = (value) => String(value ?? '').replace(/[^\p{L}\p{N}]/gu, '').toLowerCase();
3239
+
3240
+ /** Wrap every occurrence of the query inside the given nodes, then undo it later. */
3241
+ /**
3242
+ * Highlight every occurrence inside the given nodes with the CSS Highlight API.
3243
+ *
3244
+ * Ranges leave the DOM untouched, so a later render cannot break the markup,
3245
+ * and the ten-second timer starts only after the target page is on screen.
3246
+ */
3247
+ let releaseFlash = null;
3248
+ const highlightMatches = (nodes, query) => {
3249
+ if (releaseFlash !== null) {
3250
+ releaseFlash();
3251
+ releaseFlash = null;
3252
+ }
3253
+ const needle = typeof query === 'string' ? query.trim() : '';
3254
+ if (needle === '' || nodes.length === 0) return;
3255
+ if (typeof CSS === 'undefined' || CSS.highlights === undefined || typeof Highlight === 'undefined') return;
3256
+ const lowerNeedle = needle.toLowerCase();
3257
+ const ranges = [];
3258
+ for (const node of nodes.slice(0, 8)) {
3259
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, {
3260
+ acceptNode: (textNode) => (textNode.nodeValue ?? '').toLowerCase().includes(lowerNeedle)
3261
+ ? NodeFilter.FILTER_ACCEPT
3262
+ : NodeFilter.FILTER_SKIP,
3263
+ });
3264
+ while (walker.nextNode() !== null) {
3265
+ const textNode = walker.currentNode;
3266
+ const value = textNode.nodeValue ?? '';
3267
+ const lower = value.toLowerCase();
3268
+ let from = 0;
3269
+ let at = lower.indexOf(lowerNeedle);
3270
+ while (at >= 0) {
3271
+ const range = document.createRange();
3272
+ range.setStart(textNode, at);
3273
+ range.setEnd(textNode, at + needle.length);
3274
+ ranges.push(range);
3275
+ from = at + needle.length;
3276
+ at = lower.indexOf(lowerNeedle, from);
3277
+ }
3278
+ }
3279
+ }
3280
+ if (ranges.length === 0) return;
3281
+ CSS.highlights.set('dshe-flash', new Highlight(...ranges));
3282
+ const timer = window.setTimeout(() => {
3283
+ CSS.highlights.delete('dshe-flash');
3284
+ releaseFlash = null;
3285
+ }, 10_000);
3286
+ releaseFlash = () => {
3287
+ window.clearTimeout(timer);
3288
+ CSS.highlights.delete('dshe-flash');
3289
+ };
3290
+ };
3291
+
3292
+
3293
+ /**
3294
+ * Scroll to the turn a hit belongs to and flash the matched text for ten seconds.
3295
+ *
3296
+ * The event seq keys the rendered node ("13:input-message…"), so that is the
3297
+ * primary anchor. Assistant nodes are keyed by turn instead, and the stored
3298
+ * turn can be off by one across the host/UI numbering, so neighbouring turns
3299
+ * are tried and the one whose own text contains the hit wins.
3300
+ */
3301
+ /**
3302
+ * Fixed-position banner for jump feedback.
3303
+ *
3304
+ * It does not depend on React or the toast store and always lands at a
3305
+ * constant place in the window, so nothing can push it off-screen.
3306
+ */
3307
+ const showJumpNotice = (text, ms) => {
3308
+ try {
3309
+ const existing = document.getElementById('dshe-jump-notice');
3310
+ if (existing !== null) existing.remove();
3311
+ const node = document.createElement('div');
3312
+ node.id = 'dshe-jump-notice';
3313
+ node.textContent = String(text ?? '');
3314
+ node.style.cssText = [
3315
+ 'position:fixed',
3316
+ 'z-index:2147483002',
3317
+ 'top:33vh',
3318
+ 'left:50%',
3319
+ 'transform:translateX(-50%)',
3320
+ 'pointer-events:auto',
3321
+ 'background:rgba(24,26,30,.96)',
3322
+ 'color:#fff',
3323
+ 'border:1px solid rgba(255,255,255,.18)',
3324
+ 'border-radius:14px',
3325
+ 'padding:16px 26px',
3326
+ 'font-size:16px',
3327
+ 'font-weight:500',
3328
+ 'line-height:1.55',
3329
+ 'box-shadow:0 24px 60px rgba(0,0,0,.38)',
3330
+ 'max-width:70vw',
3331
+ 'text-align:center',
3332
+ 'cursor:pointer',
3333
+ 'user-select:none',
3334
+ ].join(';');
3335
+ let release = () => {};
3336
+ const closeNotice = () => {
3337
+ release();
3338
+ node.remove();
3339
+ };
3340
+ release = armQuickClose(node, closeNotice);
3341
+ document.body.appendChild(node);
3342
+ window.setTimeout(closeNotice, typeof ms === 'number' ? ms : 5000);
3343
+ } catch (error) {
3344
+ console.warn('[dsh-enhanced] notice failed:', error);
3345
+ }
3346
+ };
3347
+
3348
+ /**
3349
+ * Locate one hit inside the mounted transcript.
3350
+ *
3351
+ * Only rendered rows can be found: a hit that lives in older history is
3352
+ * reported instead of being searched for where it cannot exist.
3353
+ */
3354
+ runtime.jumpToAnchor = (options) => {
3355
+ const query = typeof options?.query === 'string' ? options.query : '';
3356
+ const previewText = typeof options?.preview === 'string' ? options.preview : '';
3357
+ const previewHit = Number.isInteger(options?.previewHit) ? options.previewHit : -1;
3358
+ const probe = bareText(options?.snippet ?? '').slice(0, 40);
3359
+ const anchorText = previewText !== '' && previewHit >= 0
3360
+ ? bareText(previewText.slice(Math.max(0, previewHit - 60), previewHit + 60))
3361
+ : '';
3362
+ const kinds = options?.role === 'user'
3363
+ ? ['user', 'steering']
3364
+ : (options?.role === 'assistant'
3365
+ ? ['assistant-step', 'turn-tail']
3366
+ : (options?.role === 'tool' ? ['tool-call'] : null));
3367
+
3368
+ let settled = false;
3369
+ let tries = 0;
3370
+
3371
+ const finish = (row) => {
3372
+ settled = true;
3373
+ scrollToKeyword(row, query);
3374
+ highlightMatches([row], query);
3375
+ showJumpNotice('已定位到匹配位置', 2000);
3376
+ };
3377
+
3378
+ /** Scroll the transcript so one occurrence of the keyword is centred. */
3379
+ const scrollToKeyword = (row, queryText) => {
3380
+ const needle = String(queryText ?? '').trim().toLowerCase();
3381
+ if (needle === '') {
3382
+ row.scrollIntoView({ block: 'center', behavior: 'smooth' });
3383
+ return;
3384
+ }
3385
+ let scroller = row.parentElement;
3386
+ while (scroller !== null && scroller !== document.body) {
3387
+ const style = window.getComputedStyle(scroller);
3388
+ if ((style.overflowY === 'auto' || style.overflowY === 'scroll') && scroller.scrollHeight > scroller.clientHeight) break;
3389
+ scroller = scroller.parentElement;
3390
+ }
3391
+ const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT, {
3392
+ acceptNode: (textNode) => (textNode.nodeValue ?? '').toLowerCase().includes(needle)
3393
+ ? NodeFilter.FILTER_ACCEPT
3394
+ : NodeFilter.FILTER_SKIP,
3395
+ });
3396
+ while (walker.nextNode() !== null) {
3397
+ const textNode = walker.currentNode;
3398
+ const value = textNode.nodeValue ?? '';
3399
+ const at = value.toLowerCase().indexOf(needle);
3400
+ if (at < 0) continue;
3401
+ if (scroller === null) break;
3402
+ const range = document.createRange();
3403
+ range.setStart(textNode, at);
3404
+ range.setEnd(textNode, at + needle.length);
3405
+ const rect = range.getBoundingClientRect();
3406
+ const box = scroller.getBoundingClientRect();
3407
+ if (rect.height > 0) {
3408
+ scroller.scrollTop += rect.top - box.top - box.height / 2 + rect.height / 2;
3409
+ return;
3410
+ }
3411
+ }
3412
+ row.scrollIntoView({ block: 'center', behavior: 'smooth' });
3413
+ };
3414
+
3415
+ /** Row that carries most of the excerpt, or null. */
3416
+ const pickRow = (rows) => {
3417
+ const chunks = anchorText === ''
3418
+ ? []
3419
+ : (() => {
3420
+ const size = Math.max(10, Math.floor(anchorText.length / 3));
3421
+ const parts = [];
3422
+ for (let i = 0; i + size <= anchorText.length; i += size) parts.push(anchorText.slice(i, i + size));
3423
+ return parts;
3424
+ })();
3425
+ const needed = Math.max(2, Math.ceil(chunks.length * 0.6));
3426
+ for (const row of rows) {
3427
+ const text = bareText(row.textContent);
3428
+ if (query !== '' && !text.includes(bareText(query))) continue;
3429
+ if (chunks.length > 0 && chunks.filter((part) => text.includes(part)).length >= needed) return row;
3430
+ if (probe.length >= 24 && text.includes(probe)) return row;
3431
+ }
3432
+ return null;
3433
+ };
3434
+
3435
+ const attempt = () => {
3436
+ if (settled === true) return;
3437
+ tries += 1;
3438
+ try {
3439
+ const flows = Array.from(document.querySelectorAll('[data-chat-flow]'))
3440
+ .filter((node) => node.querySelector('[data-chat-flow-key]') !== null);
3441
+ for (const flow of flows) {
3442
+ let rows = Array.from(flow.querySelectorAll('[data-chat-flow-key]'));
3443
+ if (kinds !== null) {
3444
+ const byKind = rows.filter((row) => kinds.includes(row.getAttribute('data-chat-flow-kind') ?? ''));
3445
+ if (byKind.length > 0) rows = byKind;
3446
+ }
3447
+ const hit = pickRow(rows);
3448
+ if (hit !== null) {
3449
+ finish(hit);
3450
+ return;
3451
+ }
3452
+ }
3453
+ } catch (error) {
3454
+ console.warn('[dsh-enhanced] locate failed:', error);
3455
+ }
3456
+ if (tries >= 8) {
3457
+ settled = true;
3458
+ showJumpNotice('该命中在更早的会话中,已打开会话但未自动定位', 5000);
3459
+ return;
3460
+ }
3461
+ window.setTimeout(attempt, 350);
3462
+ };
3463
+ attempt();
3464
+ };
3465
+
3466
+ runtime.focusMatch = (sessionId, match, query) => {
3467
+ // The hit already names its session, and only mounted rows can be located,
3468
+ // so the click navigates by text alone.
3469
+ runtime.jumpToAnchor({
3470
+ role: match?.role,
3471
+ snippet: match?.snippet,
3472
+ preview: match?.preview,
3473
+ previewHit: match?.previewHit,
3474
+ query,
3475
+ });
3476
+ };
3477
+ runtime.rpc = async (action, payload, signal) => {
3478
+ const url = new URL('api/dsh-enhanced/rpc', document.baseURI);
3479
+ const response = await fetch(url, {
3480
+ method: 'POST',
3481
+ headers: { 'content-type': 'application/json' },
3482
+ credentials: 'same-origin',
3483
+ signal,
3484
+ body: JSON.stringify({ action, ...(payload ?? {}) }),
3485
+ });
3486
+ if (!response.ok) throw new Error(`请求失败(HTTP ${String(response.status)})`);
3487
+ const body = await response.json();
3488
+ if (body === null || typeof body !== 'object' || body.ok !== true) {
3489
+ throw new Error(body?.error?.message ?? '请求失败');
3490
+ }
3491
+ return body.data;
3492
+ };
3493
+
3494
+ ctx.effect(() => ctx.locale.register(NS, DICT), 'dsh-enhanced: dictionaries');
3495
+
3496
+ ctx.effect(() => {
3497
+ const id = '@xsok/dsh-enhanced/styles';
3498
+ if (document.querySelector(`style[data-plugin-css="${id}"]`) !== null) return () => {};
3499
+ const tag = document.createElement('style');
3500
+ tag.dataset.plugin = '@xsok/dsh-enhanced';
3501
+ tag.dataset.pluginCss = id;
3502
+ tag.textContent = STYLES;
3503
+ document.head.appendChild(tag);
3504
+ return () => tag.remove();
3505
+ }, 'dsh-enhanced: styles');
3506
+
3507
+ // Ctrl+Alt+Shift+T starts one immediate sync while this window has focus.
3508
+ ctx.effect(() => {
3509
+ const onKeyDown = (event) => {
3510
+ if (!event.ctrlKey || !event.altKey || !event.shiftKey) return;
3511
+ if (event.code !== 'KeyT' && (event.key ?? '').toLowerCase() !== 't') return;
3512
+ if (event.repeat) return;
3513
+ event.preventDefault();
3514
+ event.stopPropagation();
3515
+ void runtime.store.runSyncNow();
3516
+ };
3517
+ window.addEventListener('keydown', onKeyDown, true);
3518
+ return () => window.removeEventListener('keydown', onKeyDown, true);
3519
+ }, 'dsh-enhanced: sync hotkey');
3520
+
3521
+ ctx.effect(() => {
3522
+ const onKeyDown = (event) => {
3523
+ if (!(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey) return;
3524
+ if (event.key !== 'f' && event.key !== 'F') return;
3525
+ if (runtime.store.get().settings.searchEnabled !== true) return;
3526
+ event.preventDefault();
3527
+ event.stopPropagation();
3528
+ runtime.store.openSearch();
3529
+ };
3530
+ window.addEventListener('keydown', onKeyDown, true);
3531
+ return () => window.removeEventListener('keydown', onKeyDown, true);
3532
+ }, 'dsh-enhanced: ctrl+f');
3533
+
3534
+
3535
+ ctx.effect(() => {
3536
+ const onKeyDown = (event) => {
3537
+ if (event.ctrlKey !== true || event.shiftKey !== true || event.altKey !== true) return;
3538
+ if (String(event.key).toLowerCase() !== 'r') return;
3539
+ event.preventDefault();
3540
+ event.stopPropagation();
3541
+ if (runtime.store.get().restartConfirm !== true) runtime.store.openRestart();
3542
+ };
3543
+ window.addEventListener('keydown', onKeyDown, true);
3544
+ return () => window.removeEventListener('keydown', onKeyDown, true);
3545
+ }, 'dsh-enhanced: restart shortcut');
3546
+
3547
+
3548
+
3549
+ ctx.effect(() => {
3550
+ // Prefetch distance from the top of the loaded history, in pixels.
3551
+ const PREFETCH_PX = 600;
3552
+ // Do not stack requests closer than this, so one flick loads one page.
3553
+ const MIN_GAP_MS = 600;
3554
+ let cachedScroller = null;
3555
+ let loading = null;
3556
+ let scheduled = null;
3557
+ let lastStartAt = 0;
3558
+
3559
+ const flowNode = () => document.querySelector('[data-chat-flow]');
3560
+
3561
+ const followingTail = () => document.querySelector('[data-chat-following-tail]') !== null;
3562
+
3563
+ const scrollerFor = () => {
3564
+ if (cachedScroller !== null && cachedScroller.isConnected === true) return cachedScroller;
3565
+ cachedScroller = null;
3566
+ const node = flowNode();
3567
+ if (node !== null) {
3568
+ let current = node.parentElement;
3569
+ while (current !== null && current !== document.body) {
3570
+ const style = window.getComputedStyle(current);
3571
+ if ((style.overflowY === 'auto' || style.overflowY === 'scroll') && current.scrollHeight > current.clientHeight + 4) {
3572
+ cachedScroller = current;
3573
+ return current;
3574
+ }
3575
+ current = current.parentElement;
3576
+ }
3577
+ }
3578
+ const doc = document.scrollingElement;
3579
+ if (doc instanceof Element) cachedScroller = doc;
3580
+ return cachedScroller;
3581
+ };
3582
+
3583
+ const findOlderButton = () => {
3584
+ const candidates = Array.from(document.querySelectorAll('button, [role="button"], a, [data-load-older]'));
3585
+ for (const node of candidates) {
3586
+ const label = (node.textContent ?? '').trim();
3587
+ if (label === 'Load earlier' || label.startsWith('加载更早')) return node;
3588
+ if (node.hasAttribute('data-load-older')) return node;
3589
+ const className = [String(node.className ?? ''), String(node.parentElement?.className ?? '')].join(' ');
3590
+ if (/(?:^|[_\s-])older(?:[_\s-]|$)/iu.test(className)) return node;
3591
+ }
3592
+ return null;
3593
+ };
3594
+
3595
+ const scrollHeightOf = (scroller) => (scroller === null ? 0 : scroller.scrollHeight);
3596
+
3597
+ /**
3598
+ * Load one page without moving the viewport.
3599
+ *
3600
+ * The click inserts content above; the reader keeps the same messages on
3601
+ * screen because scrollTop grows by exactly the height that was added.
3602
+ */
3603
+ const loadPage = () => {
3604
+ if (loading !== null) return;
3605
+ if (Date.now() - lastStartAt < MIN_GAP_MS) return;
3606
+ if (runtime.store.get().settings.autoLoadEnabled !== true) return;
3607
+ if (followingTail()) return;
3608
+ const button = findOlderButton();
3609
+ if (button === null || button.disabled === true) return;
3610
+
3611
+ const scroller = scrollerFor();
3612
+ if (scroller === null) return;
3613
+ const before = { height: scroller.scrollHeight, top: scroller.scrollTop };
3614
+
3615
+ loading = { height: before.height, top: before.top, at: Date.now() };
3616
+ lastStartAt = Date.now();
3617
+ try {
3618
+ button.blur();
3619
+ } catch {
3620
+ // A button without focus support is fine.
3621
+ }
3622
+ button.click();
3623
+
3624
+ const settle = () => {
3625
+ if (loading === null) return;
3626
+ const heightNow = scroller.scrollHeight;
3627
+ const grown = heightNow - before.height;
3628
+ const elapsed = Date.now() - loading.at;
3629
+ if (grown <= 0 && elapsed < 8000) {
3630
+ window.setTimeout(settle, 100);
3631
+ return;
3632
+ }
3633
+ // The browser may already have anchored the view; only correct when it
3634
+ // did not, or the two compensations would add up into a jump.
3635
+ const moved = Math.abs(scroller.scrollTop - before.top) > 4;
3636
+ if (grown > 0 && !moved) scroller.scrollTop = before.top + grown;
3637
+ loading = null;
3638
+ // Chain straight into the next page while the reader is still near the top.
3639
+ schedule(400);
3640
+ };
3641
+ window.setTimeout(settle, 100);
3642
+ };
3643
+
3644
+ const schedule = (delay) => {
3645
+ if (scheduled !== null) window.clearTimeout(scheduled);
3646
+ scheduled = window.setTimeout(() => {
3647
+ scheduled = null;
3648
+ const scroller = scrollerFor();
3649
+ if (scroller === null) return;
3650
+ if (scroller.scrollTop > PREFETCH_PX) return;
3651
+ loadPage();
3652
+ }, delay);
3653
+ };
3654
+
3655
+ let framePending = false;
3656
+ let lastTop = null;
3657
+ const onScroll = () => {
3658
+ if (framePending) return;
3659
+ framePending = true;
3660
+ window.requestAnimationFrame(() => {
3661
+ framePending = false;
3662
+ if (runtime.store.get().settings.autoLoadEnabled !== true) return;
3663
+ if (followingTail()) return;
3664
+ const scroller = scrollerFor();
3665
+ if (scroller === null) return;
3666
+ const top = scroller.scrollTop;
3667
+ const goingUp = lastTop !== null && top < lastTop - 2;
3668
+ lastTop = top;
3669
+ if (!goingUp) return;
3670
+ if (top > PREFETCH_PX) return;
3671
+ loadPage();
3672
+ });
3673
+ };
3674
+
3675
+ const onWheel = (event) => {
3676
+ if (event.deltaY >= 0) return;
3677
+ const scroller = scrollerFor();
3678
+ if (scroller === null) return;
3679
+ if (scroller.scrollTop > PREFETCH_PX) return;
3680
+ schedule(0);
3681
+ };
3682
+
3683
+ window.addEventListener('scroll', onScroll, { capture: true, passive: true });
3684
+ window.addEventListener('wheel', onWheel, { capture: true, passive: true });
3685
+ return () => {
3686
+ window.removeEventListener('scroll', onScroll, true);
3687
+ window.removeEventListener('wheel', onWheel, true);
3688
+ if (scheduled !== null) window.clearTimeout(scheduled);
3689
+ };
3690
+ }, 'dsh-enhanced: auto load earlier');
3691
+
3692
+ ctx.effect(() => {
3693
+ let pending = null;
3694
+ try {
3695
+ pending = window.sessionStorage.getItem('dsh-enhanced.pendingOpen');
3696
+ if (pending !== null) window.sessionStorage.removeItem('dsh-enhanced.pendingOpen');
3697
+ } catch {
3698
+ pending = null;
3699
+ }
3700
+ if (pending === null || pending === '') return () => {};
3701
+ const openWhenReady = (attempt) => {
3702
+ try {
3703
+ runtime.openSession(pending);
3704
+ } catch {
3705
+ if (attempt < 4) window.setTimeout(() => openWhenReady(attempt + 1), 500);
3706
+ }
3707
+ };
3708
+ const timer = window.setTimeout(() => openWhenReady(0), 800);
3709
+ return () => window.clearTimeout(timer);
3710
+ }, 'dsh-enhanced: open session after reload');
3711
+
3712
+
3713
+ ctx.effect(() => {
3714
+ runtime.store.init();
3715
+ return () => {};
3716
+ }, 'dsh-enhanced: initial state');
3717
+
3718
+ ctx.effect(() => {
3719
+ const timer = setTimeout(() => { void runtime.store.checkAppVersion(); }, 1500);
3720
+ return () => clearTimeout(timer);
3721
+ }, 'dsh-enhanced: app version probe');
3722
+
3723
+ ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({
3724
+ name: 'sidebar.workspaces.session.menu.item',
3725
+ id: 'dsh-enhanced.delete-session',
3726
+ order: 500,
3727
+ locale: NS,
3728
+ }, SessionDeleteRow));
3729
+
3730
+ ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({
3731
+ name: 'sidebar.workspaces.session.menu.item',
3732
+ id: 'dsh-enhanced.trash-for-session',
3733
+ order: 510,
3734
+ locale: NS,
3735
+ }, SessionTrashRow));
3736
+
3737
+ ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({
3738
+ name: 'sidebar.workspaces.session.menu.item',
3739
+ id: 'dsh-enhanced.move-session',
3740
+ order: 520,
3741
+ locale: NS,
3742
+ }, SessionMoveRow));
3743
+
3744
+ // Session id inside the row's hover card, between time and status.
3745
+ ctx.slots.inject('sidebar.session.row.hover', () => ctx.slots.register({
3746
+ name: 'sidebar.session.row.hover',
3747
+ id: 'dsh-enhanced.session-id',
3748
+ order: 20,
3749
+ locale: NS,
3750
+ }, SessionIdRow));
3751
+
3752
+
3753
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
3754
+ name: 'shell.overlay',
3755
+ id: 'dsh-enhanced.search',
3756
+ order: 900,
3757
+ locale: NS,
3758
+ }, SearchOverlay));
3759
+
3760
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
3761
+ name: 'shell.overlay',
3762
+ id: 'dsh-enhanced.dialogs',
3763
+ order: 910,
3764
+ locale: NS,
3765
+ }, OverlayStack));
3766
+
3767
+ ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
3768
+ name: 'conversation.composer.dock',
3769
+ id: 'dsh-enhanced.sync-running',
3770
+ order: 40,
3771
+ locale: NS,
3772
+ }, SyncRunningBadge));
3773
+
3774
+ ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
3775
+ name: 'conversation.input.left',
3776
+ id: 'dsh-enhanced.composer-bridge',
3777
+ order: 1000,
3778
+ locale: NS,
3779
+ }, ComposerBridge));
3780
+
3781
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
3782
+ name: 'settings.section',
3783
+ id: 'dsh-enhanced',
3784
+ order: 30,
3785
+ label: () => runtime.t('nav.title'),
3786
+ locale: NS,
3787
+ }, SettingsSection));
3788
+ },
3789
+ };
3790
+ },
3791
+ });