dsh-lmw-plugin 0.0.0-stage → 1.0.4

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,2118 @@
1
+ /**
2
+ * Client half of the lmw-plugin bundle (display name: LMW-DSH 基础功能).
3
+ *
4
+ * One self-contained artifact for the browser module table:
5
+ * - a left-sidebar footer action ("会话分配检查") that opens the assignment
6
+ * check without touching the skills directory,
7
+ * - the dialog itself: clearly separated session-assignment and skills panels,
8
+ * a checkable "create skills directory" row, one "确认执行" action, a
9
+ * confirm/cancel prompt, and a combined result,
10
+ * - a renderless decorator that appends each Workspace's full directory path
11
+ * under its name in the sidebar.
12
+ *
13
+ * Visible text goes through the Client locale service. Styling uses the host's
14
+ * `--dsw-alias-*` tokens; the scrims use a fixed translucent black because no
15
+ * token describes a modal scrim.
16
+ *
17
+ * @module dsh-lmw-plugin/client
18
+ */
19
+
20
+ window.__ModuleLoader__.load({
21
+ id: 'dsh-lmw-plugin',
22
+ factory(require) {
23
+ 'use strict'
24
+ const React = require('react')
25
+ const h = React.createElement
26
+ const { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } = React
27
+
28
+ const NS = 'lmw'
29
+ const ROUTE = 'lmw-plugin'
30
+
31
+ /* ------------------------------------------------------------------ */
32
+ /* Dictionaries */
33
+ /* ------------------------------------------------------------------ */
34
+
35
+ const DICTIONARIES = {
36
+ en: {
37
+ 'footer.label': 'Check session assignment',
38
+ 'footer.aria': 'Check session assignment',
39
+ 'dialog.title': 'LMW-DSH basics',
40
+ 'dialog.description': 'Two basic features: session assignment (list sessions without a workspace by directory, then create or reuse a workspace and attach them) and the skills directory (check the default skills directory and create it when missing). Check what you want, then press "Confirm and run".',
41
+ 'dialog.titleAssign': 'Session assignment',
42
+ 'dialog.descriptionAssign': 'Session assignment only: list sessions without a workspace by their directory, then create or reuse a workspace and attach them.',
43
+ 'dialog.loading': 'Reading sessions…',
44
+ 'dialog.error': 'Reading failed: {message}',
45
+ 'dialog.refreshFailed': 'Refresh failed; showing the previous result: {message}',
46
+ 'dialog.retry': 'Retry',
47
+ 'dialog.close': 'Close',
48
+ 'toolbar.all': 'Select all',
49
+ 'toolbar.none': 'Select none',
50
+ 'panel.sessions': 'Session assignment',
51
+ 'panel.sessionsMeta': '{sessions} sessions / {dirs} directories',
52
+ 'panel.skill': 'Skills directory',
53
+ 'empty': 'No session is missing a workspace.',
54
+ 'group.aria': 'Select directory {path}',
55
+ 'group.count': '{n} sessions',
56
+ 'group.missing': 'Directory missing — cannot assign',
57
+ 'session.aria': 'Select session {title}',
58
+ 'session.untitled': 'Untitled session',
59
+ 'session.archived': 'Archived',
60
+ 'summary': 'Selected {sessions} sessions in {dirs} directories',
61
+ 'action.cancel': 'Cancel',
62
+ 'action.execute': 'Confirm and run',
63
+ 'confirm.title': 'Confirm execution',
64
+ 'confirm.text': 'This assigns {sessions} sessions in {dirs} directories. Continue?',
65
+ 'confirm.textSkill': 'This assigns {sessions} sessions in {dirs} directories and creates the skills directory. Continue?',
66
+ 'confirm.textSkillOnly': 'This creates the skills directory. Continue?',
67
+ 'confirm.textNothing': 'Nothing is selected.',
68
+ 'confirm.go': 'Confirm',
69
+ 'confirm.back': 'Cancel',
70
+ 'executing': 'Running…',
71
+ 'skill.exists': 'Present',
72
+ 'skill.create': 'Create the skills directory',
73
+ 'skill.createAria': 'Create the skills directory {path}',
74
+ 'result.title': 'Execution complete',
75
+ 'result.titlePartial': 'Execution finished with failures',
76
+ 'result.summary': 'Assigned {assigned} sessions across {workspaces} workspaces.',
77
+ 'result.created': 'created',
78
+ 'result.reused': 'reused',
79
+ 'result.skipped': '{n} sessions were already assigned and were skipped.',
80
+ 'result.failed': '{n} sessions could not be assigned:',
81
+ 'result.skillCreated': 'Skills directory created: {path}',
82
+ 'result.skillExists': 'Skills directory already present: {path}',
83
+ 'result.skillFailed': 'Skills directory creation failed: {message}',
84
+ 'result.assignmentFailed': 'Session assignment request failed: {message}',
85
+ 'result.rescan': 'Scan again',
86
+ 'result.close': 'Close',
87
+ 'unassignable': '{n} more sessions cannot be assigned (no cwd or outdated log format).',
88
+ 'unassignableEmpty': '{n} empty sessions (no conversation yet) are hidden.',
89
+ 'reload.action': 'Reload the page',
90
+ 'import.footer': 'Import sessions',
91
+ 'import.footerAria': 'Import sessions from a directory',
92
+ 'import.title': 'Import sessions',
93
+ 'import.subtitle': 'Copy DSH session files from another directory into the default sessions directory. Identical sessions are replaced, new sessions get a workspace automatically.',
94
+ 'import.pathLabel': 'Sessions directory',
95
+ 'import.pathPlaceholder': 'e.g. X:\\AI\\_Agent\\DSH\\session-pi',
96
+ 'import.browse': 'Browse…',
97
+ 'import.scan': 'Scan',
98
+ 'import.scanning': 'Scanning…',
99
+ 'import.empty': 'Enter a directory, then press Scan.',
100
+ 'import.summary': 'New {added} / replaceable {replace} / skipped {skipped} / blocked {blocked}',
101
+ 'import.status.new': 'New',
102
+ 'import.status.replace': 'Replace',
103
+ 'import.status.unchanged': 'Unchanged',
104
+ 'import.status.live': 'In use',
105
+ 'import.status.conflict': 'Conflict',
106
+ 'import.status.invalid': 'Invalid',
107
+ 'import.status.duplicate': 'Duplicate',
108
+ 'import.status.empty': 'Empty',
109
+ 'import.warning.largerOnly': 'File is larger, but its modification time is not newer',
110
+ 'import.warning.newerOnly': 'Modification time is newer, but the file is smaller',
111
+ 'import.entry.source': 'Source: {size} · {time}',
112
+ 'import.entry.existing': 'Current: {size} · {time}',
113
+ 'import.selected': 'Selected {sessions} sessions',
114
+ 'import.action': 'Add selected',
115
+ 'import.confirm.title': 'Confirm import',
116
+ 'import.confirm.text': 'This adds {added} new sessions, replaces {replaced} identical ones, and assigns workspaces to the new sessions. Continue?',
117
+ 'import.confirm.go': 'Add now',
118
+ 'import.confirm.back': 'Cancel',
119
+ 'import.applying': 'Importing…',
120
+ 'import.result.title': 'Import complete',
121
+ 'import.result.summary': 'Added {added}, replaced {replaced}, failed {failed}, skipped {skipped}.',
122
+ 'import.result.added': 'added',
123
+ 'import.result.replaced': 'replaced',
124
+ 'import.result.failed': 'failed',
125
+ 'import.result.skipped': 'skipped',
126
+ 'import.result.rescan': 'Scan again',
127
+ 'import.result.close': 'Close',
128
+ 'import.error.noPath': 'Enter a directory first',
129
+ 'import.error.scan': 'Scan failed: {message}',
130
+ 'import.error.apply': 'Import failed: {message}',
131
+ 'import.note.subagent': '{n} subagent sessions skipped',
132
+ 'import.note.large': '{n} oversized files skipped',
133
+ 'import.blocked.title': 'Not addable ({n})',
134
+ 'import.none': 'No addable sessions.',
135
+ 'import.count': '{n} sessions',
136
+ 'sort.footer': 'Sort workspaces',
137
+ 'sort.title': 'Sort workspaces',
138
+ 'sort.hint': 'Reorders the sidebar groups; the order is saved for this profile.',
139
+ 'sort.byPath': 'By path name',
140
+ 'sort.byName': 'By workspace name',
141
+ 'sort.byActivity': 'By session activity',
142
+ 'sort.applying': 'Reordering…',
143
+ 'sort.manual': 'Manual (no auto sort)',
144
+ 'offline.workspace': 'Workspace directory is missing (its drive may be unplugged)',
145
+ 'offline.session': 'The workspace directory of this session is missing (its drive may be unplugged)',
146
+ 'offline.input': 'This workspace directory is missing, so input is disabled',
147
+ },
148
+ zh: {
149
+ 'footer.label': '会话分配检查',
150
+ 'footer.aria': '检查会话分配',
151
+ 'dialog.title': 'LMW-DSH基础功能',
152
+ 'dialog.description': '本插件包含两项基础功能:会话分配——按会话目录列出未分配工作区的会话,勾选后创建或复用工作区并挂载会话;Skill 目录——检查默认 Skill 目录,缺失时可一并创建。勾选后点「确认执行」一次完成。',
153
+ 'dialog.titleAssign': '会话分配',
154
+ 'dialog.descriptionAssign': '仅运行会话分配功能:按会话目录列出未分配工作区的会话,勾选后创建或复用工作区并挂载会话。',
155
+ 'dialog.loading': '正在读取会话…',
156
+ 'dialog.error': '读取失败:{message}',
157
+ 'dialog.refreshFailed': '刷新失败,显示的是上次结果:{message}',
158
+ 'dialog.retry': '重试',
159
+ 'dialog.close': '关闭',
160
+ 'toolbar.all': '全选',
161
+ 'toolbar.none': '全不选',
162
+ 'panel.sessions': '会话分配',
163
+ 'panel.sessionsMeta': '{sessions} 个会话 / {dirs} 个目录',
164
+ 'panel.skill': 'Skill 目录',
165
+ 'empty': '没有未分配工作区的会话。',
166
+ 'group.aria': '选择目录 {path}',
167
+ 'group.count': '{n} 个会话',
168
+ 'group.missing': '目录不存在,无法分配',
169
+ 'session.aria': '选择会话 {title}',
170
+ 'session.untitled': '未命名会话',
171
+ 'session.archived': '已归档',
172
+ 'summary': '已选 {sessions} 个会话 / {dirs} 个目录',
173
+ 'action.cancel': '取消',
174
+ 'action.execute': '确认执行',
175
+ 'confirm.title': '确认执行',
176
+ 'confirm.text': '将分配 {sessions} 个会话({dirs} 个目录)。是否继续?',
177
+ 'confirm.textSkill': '将分配 {sessions} 个会话({dirs} 个目录),并创建 Skill 目录。是否继续?',
178
+ 'confirm.textSkillOnly': '将创建 Skill 目录。是否继续?',
179
+ 'confirm.textNothing': '没有勾选任何可执行项。',
180
+ 'confirm.go': '确认',
181
+ 'confirm.back': '取消',
182
+ 'executing': '正在执行…',
183
+ 'skill.exists': '已存在',
184
+ 'skill.create': '创建 Skill 目录',
185
+ 'skill.createAria': '勾选创建 Skill 目录 {path}',
186
+ 'result.title': '执行完成',
187
+ 'result.titlePartial': '执行完成,存在失败项',
188
+ 'result.summary': '成功分配 {assigned} 个会话,涉及 {workspaces} 个工作区。',
189
+ 'result.created': '新建',
190
+ 'result.reused': '复用',
191
+ 'result.skipped': '{n} 个会话原本已分配,已跳过。',
192
+ 'result.failed': '{n} 个会话未能分配:',
193
+ 'result.skillCreated': 'Skill 目录已创建:{path}',
194
+ 'result.skillExists': 'Skill 目录已存在:{path}',
195
+ 'result.skillFailed': 'Skill 目录创建失败:{message}',
196
+ 'result.assignmentFailed': '会话分配请求失败:{message}',
197
+ 'result.rescan': '重新扫描',
198
+ 'result.close': '关闭',
199
+ 'unassignable': '另有 {n} 个会话无法分配(无 cwd 或旧格式日志)。',
200
+ 'unassignableEmpty': '另有 {n} 个空会话(尚无对话内容)未列出。',
201
+ 'reload.action': '重新加载页面',
202
+ 'import.footer': '导入会话',
203
+ 'import.footerAria': '从目录导入会话',
204
+ 'import.title': '导入会话',
205
+ 'import.subtitle': '把其它目录中的 DSH 会话文件复制到本机默认会话目录:相同会话直接替换,新会话自动分配工作区。',
206
+ 'import.pathLabel': '会话目录',
207
+ 'import.pathPlaceholder': '例如 X:\\AI\\_Agent\\DSH\\session-pi',
208
+ 'import.browse': '浏览…',
209
+ 'import.scan': '识别',
210
+ 'import.scanning': '识别中…',
211
+ 'import.empty': '填写目录后点击「识别」。',
212
+ 'import.summary': '新增 {added} / 可替换 {replace} / 跳过 {skipped} / 阻止 {blocked}',
213
+ 'import.status.new': '新增',
214
+ 'import.status.replace': '替换',
215
+ 'import.status.unchanged': '不变',
216
+ 'import.status.live': '使用中',
217
+ 'import.status.conflict': '冲突',
218
+ 'import.status.invalid': '无效',
219
+ 'import.status.duplicate': '重复',
220
+ 'import.status.empty': '空会话',
221
+ 'import.warning.largerOnly': '文件更大,但修改时间不更新',
222
+ 'import.warning.newerOnly': '修改时间更新,但文件更小',
223
+ 'import.entry.source': '目录副本:{size} · {time}',
224
+ 'import.entry.existing': '现有:{size} · {time}',
225
+ 'import.selected': '已选 {sessions} 个会话',
226
+ 'import.action': '添加所选',
227
+ 'import.confirm.title': '确认添加',
228
+ 'import.confirm.text': '将添加 {added} 个新会话、替换 {replaced} 个相同会话,并为新会话自动分配工作区。是否继续?',
229
+ 'import.confirm.go': '确认添加',
230
+ 'import.confirm.back': '取消',
231
+ 'import.applying': '正在添加…',
232
+ 'import.result.title': '添加完成',
233
+ 'import.result.summary': '新增 {added} 个,替换 {replaced} 个,失败 {failed} 个,跳过 {skipped} 个。',
234
+ 'import.result.added': '新增',
235
+ 'import.result.replaced': '替换',
236
+ 'import.result.failed': '失败',
237
+ 'import.result.skipped': '跳过',
238
+ 'import.result.rescan': '重新识别',
239
+ 'import.result.close': '关闭',
240
+ 'import.error.noPath': '请填写目录',
241
+ 'import.error.scan': '识别失败:{message}',
242
+ 'import.error.apply': '添加失败:{message}',
243
+ 'import.note.subagent': '已跳过 {n} 个子代理会话',
244
+ 'import.note.large': '已跳过 {n} 个过大的文件',
245
+ 'import.blocked.title': '不可添加的会话({n})',
246
+ 'import.none': '没有可添加的会话。',
247
+ 'import.count': '{n} 个会话',
248
+ 'sort.footer': '工作区排序',
249
+ 'sort.title': '工作区排序',
250
+ 'sort.hint': '调整侧栏工作区分组的顺序,顺序会保存到当前 profile。',
251
+ 'sort.byPath': '按路径名',
252
+ 'sort.byName': '按工作区名',
253
+ 'sort.byActivity': '按会话活跃度',
254
+ 'sort.applying': '正在调整…',
255
+ 'sort.manual': '手动(不自动排序)',
256
+ 'offline.workspace': '工作区目录不存在(可能所在磁盘已拔出)',
257
+ 'offline.session': '该会话所属工作区目录不存在(可能所在磁盘已拔出)',
258
+ 'offline.input': '该会话所属工作区目录不存在,无法输入',
259
+ },
260
+ }
261
+
262
+ /** Fallback translate that never throws and always returns a string. */
263
+ function makeT(t) {
264
+ return (key, params) => {
265
+ if (typeof t !== 'function') return key
266
+ try {
267
+ return t(key, params)
268
+ } catch {
269
+ return key
270
+ }
271
+ }
272
+ }
273
+
274
+ function messageOf(error) {
275
+ return error instanceof Error ? error.message : String(error)
276
+ }
277
+
278
+ /* ------------------------------------------------------------------ */
279
+ /* Host transport */
280
+ /* ------------------------------------------------------------------ */
281
+
282
+ async function requestJson(method, path, body) {
283
+ const init = { method, credentials: 'same-origin' }
284
+ if (body !== undefined) {
285
+ init.headers = { 'content-type': 'application/json' }
286
+ init.body = JSON.stringify(body)
287
+ }
288
+ const response = await fetch(`${ROUTE}/${path}`, init)
289
+ const text = await response.text()
290
+ let payload = null
291
+ if (text.trim().length > 0) {
292
+ try {
293
+ payload = JSON.parse(text)
294
+ } catch {
295
+ payload = null
296
+ }
297
+ }
298
+ if (!response.ok) {
299
+ throw new Error(payload?.error?.message ?? `HTTP ${response.status}`)
300
+ }
301
+ return payload
302
+ }
303
+
304
+ /* ------------------------------------------------------------------ */
305
+ /* Store */
306
+ /* ------------------------------------------------------------------ */
307
+
308
+ function createStore(options = {}) {
309
+ const refreshSessions = typeof options.refreshSessions === 'function' ? options.refreshSessions : undefined
310
+ let snapshot = {
311
+ data: null,
312
+ error: null,
313
+ dialogOpen: false,
314
+ mode: 'assign',
315
+ executing: false,
316
+ result: null,
317
+ }
318
+ const listeners = new Set()
319
+ const publish = (patch) => {
320
+ snapshot = { ...snapshot, ...patch }
321
+ for (const listener of [...listeners]) {
322
+ try {
323
+ listener()
324
+ } catch (error) {
325
+ console.error('[lmw-plugin] listener failed:', error)
326
+ }
327
+ }
328
+ }
329
+ let loading = null
330
+ let autoOpened = false
331
+ let titleTimers = null
332
+
333
+ // The Host warms missing title-cache rows after answering the scan; the
334
+ // sidebar's session list only re-reads titles on a pull, so pull it a few
335
+ // times while the background warm settles.
336
+ const scheduleTitleRefresh = (pending) => {
337
+ if (pending <= 0 || refreshSessions === undefined || titleTimers !== null) return
338
+ const delays = [1500, 5000, 12000, 25000]
339
+ titleTimers = delays.map((delay, index) => window.setTimeout(() => {
340
+ void refreshSessions().catch((error) => {
341
+ console.error('[lmw-plugin] session list refresh failed:', error)
342
+ })
343
+ if (index === delays.length - 1) titleTimers = null
344
+ }, delay))
345
+ }
346
+
347
+ const refresh = async () => {
348
+ if (loading !== null) return loading
349
+ loading = (async () => {
350
+ if (snapshot.data === null) publish({ error: null })
351
+ try {
352
+ const data = await requestJson('GET', 'state')
353
+ publish({ data, error: null })
354
+ scheduleTitleRefresh(data?.titleWarm?.pending ?? 0)
355
+ return data
356
+ } catch (error) {
357
+ publish({ error: messageOf(error) })
358
+ return null
359
+ } finally {
360
+ loading = null
361
+ }
362
+ })()
363
+ return loading
364
+ }
365
+
366
+ const boot = async () => {
367
+ const data = await refresh()
368
+ if (data === null || autoOpened) return
369
+ const unassigned = data.counts?.unassignedSessions ?? 0
370
+ const skillMissing = data.skillDir?.exists === false
371
+ if (data.config?.autoOpenOnStartup !== false && (unassigned > 0 || skillMissing)) {
372
+ autoOpened = true
373
+ publish({ dialogOpen: true, mode: 'full', result: null })
374
+ }
375
+ }
376
+
377
+ const open = (mode = 'assign') => {
378
+ publish({ dialogOpen: true, mode, result: null })
379
+ void refresh()
380
+ }
381
+ const close = () => {
382
+ publish({ dialogOpen: false, result: null })
383
+ }
384
+ const toggle = () => {
385
+ if (snapshot.dialogOpen) close()
386
+ else open('assign')
387
+ }
388
+
389
+ const execute = async (request) => {
390
+ if (snapshot.executing) return snapshot.result
391
+ publish({ executing: true, result: null })
392
+ const failures = []
393
+ let assignment = null
394
+ let skill = null
395
+ if (request.sessionIds.length > 0) {
396
+ try {
397
+ assignment = await requestJson('POST', 'assign', { sessionIds: request.sessionIds })
398
+ } catch (error) {
399
+ failures.push({ part: 'assignment', message: messageOf(error) })
400
+ }
401
+ }
402
+ if (request.createSkillDir) {
403
+ try {
404
+ skill = await requestJson('POST', 'skills', { action: 'create' })
405
+ } catch (error) {
406
+ failures.push({ part: 'skill', message: messageOf(error) })
407
+ }
408
+ }
409
+ const result = { assignment, skill, failures }
410
+ publish({ executing: false, result })
411
+ void refresh()
412
+ return result
413
+ }
414
+
415
+ const dispose = () => {
416
+ if (titleTimers === null) return
417
+ for (const timer of titleTimers) window.clearTimeout(timer)
418
+ titleTimers = null
419
+ }
420
+
421
+ return {
422
+ getSnapshot: () => snapshot,
423
+ subscribe: (listener) => {
424
+ listeners.add(listener)
425
+ return () => {
426
+ listeners.delete(listener)
427
+ }
428
+ },
429
+ boot,
430
+ open,
431
+ close,
432
+ toggle,
433
+ refresh,
434
+ execute,
435
+ dispose,
436
+ }
437
+ }
438
+
439
+ /* ------------------------------------------------------------------ */
440
+ /* Shared helpers */
441
+ /* ------------------------------------------------------------------ */
442
+
443
+ function formatBytes(bytes) {
444
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '—'
445
+ if (bytes < 1024) return `${bytes} B`
446
+ const units = ['KB', 'MB', 'GB', 'TB']
447
+ let value = bytes / 1024
448
+ let index = 0
449
+ while (value >= 1024 && index < units.length - 1) {
450
+ value /= 1024
451
+ index += 1
452
+ }
453
+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[index]}`
454
+ }
455
+
456
+ function formatTime(ms) {
457
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return '—'
458
+ try {
459
+ return new Date(ms).toLocaleString()
460
+ } catch {
461
+ return '—'
462
+ }
463
+ }
464
+
465
+ /** Expand the given Workspace groups if the sidebar renders them folded. */
466
+ function expandWorkspaceRows(workspaceIds) {
467
+ const ids = (workspaceIds ?? []).map((id) => String(id)).filter((id) => id.length > 0)
468
+ if (ids.length === 0) return undefined
469
+ const expand = () => {
470
+ for (const id of ids) {
471
+ let row = null
472
+ try {
473
+ row = document.querySelector(`[data-row-key="workspace:${id}"]`)
474
+ } catch {
475
+ row = null
476
+ }
477
+ if (row instanceof HTMLElement && row.getAttribute('aria-expanded') === 'false') row.click()
478
+ }
479
+ }
480
+ const timers = [window.setTimeout(expand, 300), window.setTimeout(expand, 1200)]
481
+ return () => {
482
+ for (const timer of timers) window.clearTimeout(timer)
483
+ }
484
+ }
485
+
486
+ /* ------------------------------------------------------------------ */
487
+ /* Import store */
488
+ /* ------------------------------------------------------------------ */
489
+
490
+ function createImportStore(options = {}) {
491
+ const refreshSessions = typeof options.refreshSessions === 'function' ? options.refreshSessions : undefined
492
+ let snapshot = {
493
+ dialogOpen: false,
494
+ path: '',
495
+ scanning: false,
496
+ scan: null,
497
+ error: null,
498
+ applying: false,
499
+ result: null,
500
+ applyError: null,
501
+ }
502
+ const listeners = new Set()
503
+ const publish = (patch) => {
504
+ snapshot = { ...snapshot, ...patch }
505
+ for (const listener of [...listeners]) {
506
+ try {
507
+ listener()
508
+ } catch (error) {
509
+ console.error('[lmw-plugin] import listener failed:', error)
510
+ }
511
+ }
512
+ }
513
+
514
+ const open = () => publish({ dialogOpen: true })
515
+ const close = () => publish({ dialogOpen: false, result: null, applyError: null, error: null })
516
+ const toggle = () => {
517
+ if (snapshot.dialogOpen) close()
518
+ else open()
519
+ }
520
+ const setPath = (path) => publish({ path })
521
+ const reset = () => publish({ scan: null, result: null, error: null, applyError: null })
522
+
523
+ const scanNow = async () => {
524
+ const path = snapshot.path.trim()
525
+ if (path.length === 0) {
526
+ publish({ error: 'no-path' })
527
+ return null
528
+ }
529
+ publish({ scanning: true, error: null, scan: null, result: null, applyError: null })
530
+ try {
531
+ const data = await requestJson('POST', 'import/scan', { path })
532
+ publish({ scanning: false, scan: data })
533
+ return data
534
+ } catch (error) {
535
+ publish({ scanning: false, error: messageOf(error) })
536
+ return null
537
+ }
538
+ }
539
+
540
+ const apply = async (sessionIds) => {
541
+ if (snapshot.applying) return null
542
+ if (sessionIds.length === 0) return null
543
+ publish({ applying: true, result: null, applyError: null })
544
+ try {
545
+ const data = await requestJson('POST', 'import/apply', { path: snapshot.path.trim(), sessionIds })
546
+ publish({ applying: false, result: data })
547
+ const workspaceIds = (data?.results ?? [])
548
+ .map((entry) => entry?.workspace?.workspaceId)
549
+ .filter((id) => typeof id === 'string' && id.length > 0)
550
+ expandWorkspaceRows(workspaceIds)
551
+ if (typeof options.refreshAssignment === 'function') {
552
+ try {
553
+ options.refreshAssignment()
554
+ } catch (error) {
555
+ console.error('[lmw-plugin] refreshing the assignment scan failed:', error)
556
+ }
557
+ }
558
+ if (refreshSessions !== undefined) {
559
+ for (const delay of [1200, 4000]) {
560
+ window.setTimeout(() => {
561
+ void refreshSessions().catch((error) => {
562
+ console.error('[lmw-plugin] session list refresh failed:', error)
563
+ })
564
+ }, delay)
565
+ }
566
+ }
567
+ return data
568
+ } catch (error) {
569
+ publish({ applying: false, applyError: messageOf(error) })
570
+ return null
571
+ }
572
+ }
573
+
574
+ return {
575
+ getSnapshot: () => snapshot,
576
+ subscribe: (listener) => {
577
+ listeners.add(listener)
578
+ return () => {
579
+ listeners.delete(listener)
580
+ }
581
+ },
582
+ open,
583
+ close,
584
+ toggle,
585
+ setPath,
586
+ reset,
587
+ scanNow,
588
+ apply,
589
+ }
590
+ }
591
+
592
+ /* ------------------------------------------------------------------ */
593
+ /* Shared UI atoms */
594
+ /* ------------------------------------------------------------------ */
595
+
596
+ const GLYPH = h(
597
+ 'svg',
598
+ { width: 16, height: 16, viewBox: '0 0 36 36', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
599
+ h('path', {
600
+ d: 'M4.5 11.75A2.75 2.75 0 0 1 7.25 9h6.1c.73 0 1.43.29 1.94.8l1.6 1.6h10.36A2.75 2.75 0 0 1 30 14.15v11.1A2.75 2.75 0 0 1 27.25 28H7.25A2.75 2.75 0 0 1 4.5 25.25V11.75Z',
601
+ fill: 'currentColor',
602
+ opacity: 0.9,
603
+ }),
604
+ h('path', { d: 'M17.25 14.2v7.2', stroke: 'var(--dsw-alias-bg-base)', 'stroke-width': 2.4, 'stroke-linecap': 'round' }),
605
+ h('path', { d: 'm13.6 18.2 3.65 3.65L20.9 18.2', stroke: 'var(--dsw-alias-bg-base)', 'stroke-width': 2.4, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }),
606
+ )
607
+
608
+ const CHECK_GLYPH = h(
609
+ 'svg',
610
+ { width: 14, height: 14, viewBox: '0 0 14 14', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
611
+ h('circle', { cx: 7, cy: 7, r: 6.3, stroke: 'currentColor', 'stroke-width': 1.3 }),
612
+ h('path', {
613
+ d: 'M4.1 7.2l2 2 3.8-4',
614
+ stroke: 'currentColor',
615
+ 'stroke-width': 1.6,
616
+ 'stroke-linecap': 'round',
617
+ 'stroke-linejoin': 'round',
618
+ }),
619
+ )
620
+
621
+ function Checkbox({ checked, indeterminate, disabled, onChange, label }) {
622
+ const ref = useRef(null)
623
+ useEffect(() => {
624
+ if (ref.current !== null) ref.current.indeterminate = indeterminate === true
625
+ }, [indeterminate])
626
+ return h('input', {
627
+ ref,
628
+ type: 'checkbox',
629
+ className: 'lmw-check',
630
+ checked: checked === true,
631
+ disabled: disabled === true,
632
+ 'aria-label': label,
633
+ onChange: () => onChange(),
634
+ })
635
+ }
636
+
637
+ function shortId(id) {
638
+ const text = String(id)
639
+ return text.length > 15 ? `${text.slice(0, 12)}…` : text
640
+ }
641
+
642
+ /* ------------------------------------------------------------------ */
643
+ /* Assignment dialog */
644
+ /* ------------------------------------------------------------------ */
645
+
646
+ function AssignDialog(props) {
647
+ const { store, workspaces } = props
648
+ const tr = makeT(props.translate ?? props.t)
649
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
650
+ const dialogRef = useRef(null)
651
+ const [selected, setSelected] = useState(() => new Set())
652
+ const [createSkill, setCreateSkill] = useState(false)
653
+ const [confirming, setConfirming] = useState(false)
654
+
655
+ const open = snapshot.dialogOpen
656
+ const data = snapshot.data
657
+ const groups = data?.groups ?? []
658
+ const result = snapshot.result
659
+ const showSkill = snapshot.mode === 'full'
660
+ const skillDir = data?.skillDir
661
+ const skillExists = skillDir?.exists === true
662
+
663
+ const subscribeWorkspaces = useCallback((listener) => workspaces.list.subscribe(listener), [workspaces])
664
+ const readWorkspaces = useCallback(() => workspaces.list.getSnapshot(), [workspaces])
665
+ const workspaceSnapshot = useSyncExternalStore(subscribeWorkspaces, readWorkspaces)
666
+ const archived = useMemo(
667
+ () => new Set((workspaceSnapshot.archivedSessionIds ?? []).map((id) => String(id))),
668
+ [workspaceSnapshot.archivedSessionIds],
669
+ )
670
+
671
+ const assignableIds = useMemo(() => {
672
+ const ids = []
673
+ for (const group of groups) {
674
+ if (group.exists === false) continue
675
+ for (const session of group.sessions) ids.push(session.id)
676
+ }
677
+ return ids
678
+ }, [groups])
679
+
680
+ useEffect(() => {
681
+ if (!open) return
682
+ setSelected(new Set(assignableIds))
683
+ setCreateSkill(showSkill && data?.skillDir?.exists === false)
684
+ setConfirming(false)
685
+ }, [open, data?.generatedAt, showSkill])
686
+
687
+ useEffect(() => {
688
+ if (!open) return undefined
689
+ const timer = window.setTimeout(() => {
690
+ dialogRef.current?.querySelector('[data-lmw-autofocus]')?.focus()
691
+ }, 40)
692
+ return () => {
693
+ window.clearTimeout(timer)
694
+ try {
695
+ document.querySelector('[data-lmw-foot-button]')?.focus()
696
+ } catch {
697
+ // A detached trigger is not worth reporting.
698
+ }
699
+ }
700
+ }, [open])
701
+
702
+ useEffect(() => {
703
+ if (!open) return undefined
704
+ const onKeyDown = (event) => {
705
+ if (event.key !== 'Escape') return
706
+ event.stopPropagation()
707
+ if (confirming) setConfirming(false)
708
+ else store.close()
709
+ }
710
+ document.addEventListener('keydown', onKeyDown, true)
711
+ return () => {
712
+ document.removeEventListener('keydown', onKeyDown, true)
713
+ }
714
+ }, [open, confirming, store])
715
+
716
+ useEffect(() => {
717
+ if (!open || !confirming) return undefined
718
+ const timer = window.setTimeout(() => {
719
+ dialogRef.current?.querySelector('[data-lmw-confirm-go]')?.focus()
720
+ }, 30)
721
+ return () => {
722
+ window.clearTimeout(timer)
723
+ }
724
+ }, [open, confirming])
725
+
726
+ // While the confirm layer is up, the dialog content behind it must not
727
+ // take focus or clicks (inert also hides it from assistive technology).
728
+ useEffect(() => {
729
+ if (!open || !confirming) return undefined
730
+ const root = dialogRef.current
731
+ if (root === null) return undefined
732
+ const parts = [...root.querySelectorAll(':scope > .lmw-header, :scope > .lmw-body, :scope > .lmw-footbar')]
733
+ for (const part of parts) part.setAttribute('inert', '')
734
+ return () => {
735
+ for (const part of parts) part.removeAttribute('inert')
736
+ }
737
+ }, [open, confirming])
738
+
739
+ // DSH renders every Workspace group folded unless it was expanded
740
+ // before, so a freshly assigned Workspace would show its name with no
741
+ // visible sessions. Expand the groups this run touched so the result is
742
+ // visible immediately; the user can fold them again as usual.
743
+ useEffect(() => {
744
+ if (result === null) return undefined
745
+ return expandWorkspaceRows((result.assignment?.workspaces ?? []).map((workspace) => workspace.workspaceId))
746
+ }, [result])
747
+
748
+ const toggleSession = (id) => {
749
+ setSelected((current) => {
750
+ const next = new Set(current)
751
+ if (next.has(id)) next.delete(id)
752
+ else next.add(id)
753
+ return next
754
+ })
755
+ }
756
+
757
+ const toggleGroup = (group) => {
758
+ setSelected((current) => {
759
+ const next = new Set(current)
760
+ const ids = group.sessions.map((session) => session.id)
761
+ const all = ids.length > 0 && ids.every((id) => next.has(id))
762
+ for (const id of ids) {
763
+ if (all) next.delete(id)
764
+ else next.add(id)
765
+ }
766
+ return next
767
+ })
768
+ }
769
+
770
+ const selectedCount = selected.size
771
+ const selectedDirs = groups.filter(
772
+ (group) => group.exists !== false && group.sessions.some((session) => selected.has(session.id)),
773
+ ).length
774
+ const skillWillCreate = showSkill && !skillExists && createSkill
775
+ const actionable = selectedCount > 0 || skillWillCreate
776
+
777
+ const runExecute = async () => {
778
+ if (snapshot.executing || !actionable) return
779
+ setConfirming(false)
780
+ await store.execute({
781
+ sessionIds: [...selected],
782
+ createSkillDir: skillWillCreate,
783
+ })
784
+ }
785
+
786
+ if (!open) return null
787
+
788
+ const subtitle = () => tr(showSkill ? 'dialog.description' : 'dialog.descriptionAssign')
789
+
790
+ const header = h(
791
+ 'header',
792
+ { className: 'lmw-header' },
793
+ h(
794
+ 'div',
795
+ { className: 'lmw-header-text' },
796
+ h('div', { className: 'lmw-title' }, tr(showSkill ? 'dialog.title' : 'dialog.titleAssign')),
797
+ h('div', { className: 'lmw-subtitle' }, subtitle()),
798
+ ),
799
+ h(
800
+ 'button',
801
+ {
802
+ type: 'button',
803
+ className: 'lmw-close',
804
+ 'aria-label': tr('dialog.close'),
805
+ 'data-lmw-autofocus': '',
806
+ onClick: () => store.close(),
807
+ },
808
+ h('svg', { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': 'true' },
809
+ h('path', { d: 'M3 3l8 8M11 3l-8 8', stroke: 'currentColor', 'stroke-width': 1.6, 'stroke-linecap': 'round' })),
810
+ ),
811
+ )
812
+
813
+ const renderGroup = (group) => {
814
+ const ids = group.sessions.map((session) => session.id)
815
+ const chosen = ids.filter((id) => selected.has(id)).length
816
+ const all = ids.length > 0 && chosen === ids.length
817
+ const some = chosen > 0 && !all
818
+ const missing = group.exists === false
819
+ return h(
820
+ 'section',
821
+ { className: 'lmw-group', 'data-missing': missing ? '1' : undefined, key: group.cwd },
822
+ h(
823
+ 'label',
824
+ { className: 'lmw-group-head' },
825
+ h(Checkbox, {
826
+ checked: all,
827
+ indeterminate: some,
828
+ disabled: missing || snapshot.executing === true,
829
+ label: tr('group.aria', { path: group.cwd }),
830
+ onChange: () => toggleGroup(group),
831
+ }),
832
+ h('span', { className: 'lmw-group-path' }, group.cwd),
833
+ missing
834
+ ? h('span', { className: 'lmw-badge lmw-badge-warn' }, tr('group.missing'))
835
+ : h('span', { className: 'lmw-count' }, tr('group.count', { n: group.sessions.length })),
836
+ ),
837
+ h(
838
+ 'ul',
839
+ { className: 'lmw-sessions' },
840
+ group.sessions.map((session) => {
841
+ const isArchived = archived.has(session.id)
842
+ const title = session.title.length > 0 ? session.title : tr('session.untitled')
843
+ return h(
844
+ 'li',
845
+ { className: 'lmw-session', key: session.id },
846
+ h(
847
+ 'label',
848
+ { className: 'lmw-session-label' },
849
+ h(Checkbox, {
850
+ checked: selected.has(session.id),
851
+ disabled: missing || snapshot.executing === true,
852
+ label: tr('session.aria', { title }),
853
+ onChange: () => toggleSession(session.id),
854
+ }),
855
+ h('span', { className: 'lmw-session-title' }, title),
856
+ isArchived ? h('span', { className: 'lmw-badge' }, tr('session.archived')) : null,
857
+ h('span', { className: 'lmw-session-id' }, shortId(session.id)),
858
+ ),
859
+ )
860
+ }),
861
+ ),
862
+ )
863
+ }
864
+
865
+ const renderSkillPanel = () => {
866
+ if (!showSkill || !skillDir) return null
867
+ return h(
868
+ 'section',
869
+ { className: 'lmw-panel' },
870
+ h('div', { className: 'lmw-panel-head' },
871
+ h('span', { className: 'lmw-panel-title' }, tr('panel.skill'))),
872
+ skillExists
873
+ ? h('div', { className: 'lmw-skill-line' },
874
+ h('code', { className: 'lmw-path' }, skillDir.path),
875
+ h('span', { className: 'lmw-skill-state' }, tr('skill.exists')),
876
+ h('span', {
877
+ className: 'lmw-check-ok',
878
+ role: 'img',
879
+ 'aria-label': tr('skill.exists'),
880
+ }, CHECK_GLYPH))
881
+ : h('label', { className: 'lmw-skill-line lmw-skill-check' },
882
+ h(Checkbox, {
883
+ checked: createSkill,
884
+ disabled: snapshot.executing === true,
885
+ label: tr('skill.createAria', { path: skillDir.path }),
886
+ onChange: () => setCreateSkill((value) => !value),
887
+ }),
888
+ h('span', { className: 'lmw-skill-label' }, tr('skill.create')),
889
+ h('code', { className: 'lmw-path' }, skillDir.path)),
890
+ )
891
+ }
892
+
893
+ const renderResult = () => {
894
+ const assignment = result.assignment
895
+ const failed = assignment && Array.isArray(assignment.failed) ? assignment.failed : []
896
+ const skipped = assignment && Array.isArray(assignment.skipped) ? assignment.skipped : []
897
+ const workspacesTouched = assignment && Array.isArray(assignment.workspaces) ? assignment.workspaces : []
898
+ const skill = result.skill
899
+ const failures = Array.isArray(result.failures) ? result.failures : []
900
+ const hasFailure = failures.length > 0 || failed.length > 0
901
+ const items = []
902
+ if (assignment !== null) {
903
+ items.push(h('p', { className: 'lmw-result-text', key: 'summary' },
904
+ tr('result.summary', { assigned: assignment.assigned ?? 0, workspaces: workspacesTouched.length })))
905
+ if (workspacesTouched.length > 0) {
906
+ items.push(h('ul', { className: 'lmw-list', key: 'workspaces' },
907
+ workspacesTouched.map((workspace) => h('li', { key: workspace.workspaceId },
908
+ `${workspace.created ? tr('result.created') : tr('result.reused')} · ${workspace.path}`))))
909
+ }
910
+ if (skipped.length > 0) {
911
+ items.push(h('p', { className: 'lmw-result-text', key: 'skipped' }, tr('result.skipped', { n: skipped.length })))
912
+ }
913
+ if (failed.length > 0) {
914
+ items.push(h('div', { className: 'lmw-result-fail', key: 'failed' },
915
+ h('p', { className: 'lmw-error' }, tr('result.failed', { n: failed.length })),
916
+ h('ul', { className: 'lmw-list' }, failed.slice(0, 12).map((item, index) =>
917
+ h('li', { key: `${item.sessionId}:${index}` }, `${shortId(item.sessionId)} — ${item.code}: ${item.message}`)))))
918
+ }
919
+ }
920
+ if (skill !== null) {
921
+ items.push(h('p', {
922
+ className: skill.created ? 'lmw-result-text lmw-ok' : 'lmw-result-text',
923
+ key: 'skill',
924
+ }, tr(skill.created ? 'result.skillCreated' : 'result.skillExists', { path: skill.path })))
925
+ }
926
+ for (const failure of failures) {
927
+ items.push(h('p', { className: 'lmw-error', key: `failure:${failure.part}` },
928
+ tr(failure.part === 'skill' ? 'result.skillFailed' : 'result.assignmentFailed', { message: failure.message })))
929
+ }
930
+ return h(
931
+ 'div',
932
+ { className: 'lmw-result' },
933
+ h('div', { className: hasFailure ? 'lmw-result-title lmw-warn' : 'lmw-result-title lmw-ok' },
934
+ tr(hasFailure ? 'result.titlePartial' : 'result.title')),
935
+ ...items,
936
+ h('div', { className: 'lmw-result-actions' },
937
+ h('button', {
938
+ type: 'button',
939
+ className: 'lmw-button',
940
+ onClick: () => {
941
+ store.close()
942
+ store.open(snapshot.mode)
943
+ },
944
+ }, tr('result.rescan')),
945
+ h('button', { type: 'button', className: 'lmw-button lmw-primary', onClick: () => store.close() }, tr('result.close'))),
946
+ )
947
+ }
948
+
949
+ const body = () => {
950
+ if (result !== null) return renderResult()
951
+ if (snapshot.error !== null && data === null) {
952
+ return h('div', { className: 'lmw-state' },
953
+ h('p', { className: 'lmw-error' }, tr('dialog.error', { message: snapshot.error })),
954
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => { void store.refresh() } }, tr('dialog.retry')))
955
+ }
956
+ if (data === null) {
957
+ return h('div', { className: 'lmw-state' }, h('p', { className: 'lmw-note' }, tr('dialog.loading')))
958
+ }
959
+ const staleError = snapshot.error !== null && snapshot.error !== undefined
960
+ ? h('p', { className: 'lmw-error' }, tr('dialog.refreshFailed', { message: snapshot.error }))
961
+ : null
962
+ const extra = (data.unassignable?.noCwd ?? 0) + (data.unassignable?.legacyFormat ?? 0)
963
+ const extraNote = extra > 0 ? h('p', { className: 'lmw-note' }, tr('unassignable', { n: extra })) : null
964
+ const emptyCount = data.unassignable?.empty ?? 0
965
+ const emptyNote = emptyCount > 0
966
+ ? h('p', { className: 'lmw-note' }, tr('unassignableEmpty', { n: emptyCount }))
967
+ : null
968
+ const sessionsPanel = h('section', { className: 'lmw-panel' },
969
+ h('div', { className: 'lmw-panel-head' },
970
+ h('span', { className: 'lmw-panel-title' }, tr('panel.sessions')),
971
+ h('span', { className: 'lmw-panel-meta' },
972
+ tr('panel.sessionsMeta', {
973
+ sessions: groups.reduce((total, group) => total + group.sessions.length, 0),
974
+ dirs: groups.length,
975
+ }))),
976
+ groups.length === 0
977
+ ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('empty'))
978
+ : h('div', null,
979
+ h('div', { className: 'lmw-toolbar' },
980
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set(assignableIds)) }, tr('toolbar.all')),
981
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set()) }, tr('toolbar.none'))),
982
+ h('div', { className: 'lmw-groups' }, groups.map(renderGroup))),
983
+ extraNote,
984
+ emptyNote)
985
+ return h('div', { className: 'lmw-panels' },
986
+ staleError,
987
+ sessionsPanel,
988
+ renderSkillPanel())
989
+ }
990
+
991
+ const executeText = () => {
992
+ if (selectedCount === 0 && !skillWillCreate) return tr('confirm.textNothing')
993
+ if (selectedCount === 0) return tr('confirm.textSkillOnly')
994
+ if (skillWillCreate) return tr('confirm.textSkill', { sessions: selectedCount, dirs: selectedDirs })
995
+ return tr('confirm.text', { sessions: selectedCount, dirs: selectedDirs })
996
+ }
997
+
998
+ const footer = () => {
999
+ if (result !== null) return null
1000
+ return h('div', { className: 'lmw-footbar' },
1001
+ h('span', { className: 'lmw-summary' },
1002
+ actionable ? tr('summary', { sessions: selectedCount, dirs: selectedDirs }) : tr('confirm.textNothing')),
1003
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => store.close() }, tr('action.cancel')),
1004
+ h('button', {
1005
+ type: 'button',
1006
+ className: 'lmw-button lmw-primary',
1007
+ disabled: snapshot.executing === true || !actionable,
1008
+ onClick: () => setConfirming(true),
1009
+ }, snapshot.executing ? tr('executing') : tr('action.execute')))
1010
+ }
1011
+
1012
+ const confirmLayer = confirming
1013
+ ? h('div', { className: 'lmw-confirm-layer' },
1014
+ h('div', {
1015
+ className: 'lmw-confirm-card',
1016
+ role: 'alertdialog',
1017
+ 'aria-modal': 'true',
1018
+ 'aria-label': tr('confirm.title'),
1019
+ },
1020
+ h('div', { className: 'lmw-confirm-title' }, tr('confirm.title')),
1021
+ h('p', { className: 'lmw-confirm-text' }, executeText()),
1022
+ h('div', { className: 'lmw-confirm-actions' },
1023
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => setConfirming(false) }, tr('confirm.back')),
1024
+ h('button', {
1025
+ type: 'button',
1026
+ className: 'lmw-button lmw-primary',
1027
+ 'data-lmw-confirm-go': '',
1028
+ disabled: !actionable,
1029
+ onClick: () => { void runExecute() },
1030
+ }, tr('confirm.go')))))
1031
+ : null
1032
+
1033
+ return h('div', {
1034
+ className: 'lmw-backdrop',
1035
+ onMouseDown: (event) => {
1036
+ if (event.target === event.currentTarget) store.close()
1037
+ },
1038
+ },
1039
+ h('section', {
1040
+ ref: dialogRef,
1041
+ className: 'lmw-dialog',
1042
+ role: 'dialog',
1043
+ 'aria-modal': 'true',
1044
+ 'aria-label': tr(showSkill ? 'dialog.title' : 'dialog.titleAssign'),
1045
+ },
1046
+ header,
1047
+ h('div', { className: 'lmw-body' }, body()),
1048
+ footer(),
1049
+ confirmLayer,
1050
+ ),
1051
+ )
1052
+ }
1053
+
1054
+ /* ------------------------------------------------------------------ */
1055
+ /* Sidebar reload and import actions */
1056
+ /* ------------------------------------------------------------------ */
1057
+
1058
+ const RELOAD_GLYPH = h(
1059
+ 'svg',
1060
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
1061
+ h('path', { d: 'M13 8a5 5 0 1 1-1.46-3.54', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round' }),
1062
+ h('path', { d: 'M13 3.55v3.2h-3.2', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }),
1063
+ )
1064
+
1065
+ const IMPORT_GLYPH = h(
1066
+ 'svg',
1067
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
1068
+ h('path', { d: 'M8 3v6.1', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round' }),
1069
+ h('path', { d: 'M5.5 6.7 8 9.2l2.5-2.5', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }),
1070
+ h('path', { d: 'M3.2 10.5v1.3A1.2 1.2 0 0 0 4.4 13h7.2a1.2 1.2 0 0 0 1.2-1.2v-1.3', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round' }),
1071
+ )
1072
+
1073
+ function FootRow(props) {
1074
+ const { wide, glyph, label, aria, expanded, onClick, badge, badgeAlert } = props
1075
+ return h(
1076
+ 'div',
1077
+ { className: 'lmw-foot' },
1078
+ h(
1079
+ 'button',
1080
+ {
1081
+ type: 'button',
1082
+ className: 'lmw-foot-button',
1083
+ 'data-lmw-foot-button': '',
1084
+ 'data-wide': wide ? '1' : '0',
1085
+ 'aria-label': aria,
1086
+ 'aria-expanded': expanded === undefined ? undefined : (expanded ? 'true' : 'false'),
1087
+ title: aria,
1088
+ onClick,
1089
+ },
1090
+ h('span', { className: 'lmw-foot-glyph', 'aria-hidden': 'true' }, glyph),
1091
+ wide ? h('span', { className: 'lmw-foot-text' }, label) : null,
1092
+ badge !== undefined && badge.length > 0
1093
+ ? h('span', { className: 'lmw-foot-count', 'data-alert': badgeAlert === true ? '1' : undefined }, badge)
1094
+ : null,
1095
+ ),
1096
+ )
1097
+ }
1098
+
1099
+ /** One footer seat holding the three actions stacked, so labels stay readable. */
1100
+ function FooterActionsPanel(props) {
1101
+ const { wide, store, importStore, sortStore } = props
1102
+ const tr = makeT(props.translate ?? props.t)
1103
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
1104
+ const importSnapshot = useSyncExternalStore(importStore.subscribe, importStore.getSnapshot)
1105
+ const count = snapshot.data?.counts?.unassignedSessions ?? 0
1106
+ return h(
1107
+ 'div',
1108
+ { className: 'lmw-foot-stack' },
1109
+ h(FootRow, {
1110
+ wide,
1111
+ glyph: RELOAD_GLYPH,
1112
+ label: tr('reload.action'),
1113
+ aria: tr('reload.action'),
1114
+ onClick: () => {
1115
+ try {
1116
+ window.location.reload()
1117
+ } catch {
1118
+ // A context that cannot reload simply stays as it is.
1119
+ }
1120
+ },
1121
+ }),
1122
+ h(FootRow, {
1123
+ wide,
1124
+ glyph: GLYPH,
1125
+ label: tr('footer.label'),
1126
+ aria: tr('footer.aria'),
1127
+ expanded: snapshot.dialogOpen === true,
1128
+ badge: count > 0 ? String(count) : '',
1129
+ onClick: () => store.toggle(),
1130
+ }),
1131
+ h(FootRow, {
1132
+ wide,
1133
+ glyph: IMPORT_GLYPH,
1134
+ label: tr('import.footer'),
1135
+ aria: tr('import.footerAria'),
1136
+ expanded: importSnapshot.dialogOpen === true,
1137
+ onClick: () => importStore.toggle(),
1138
+ }),
1139
+ h(FootRow, {
1140
+ wide,
1141
+ glyph: SORT_GLYPH,
1142
+ label: tr('sort.footer'),
1143
+ aria: tr('sort.title'),
1144
+ onClick: () => sortStore.toggle(),
1145
+ }),
1146
+ )
1147
+ }
1148
+
1149
+ /* ------------------------------------------------------------------ */
1150
+ /* Import dialog */
1151
+ /* ------------------------------------------------------------------ */
1152
+
1153
+ function ImportDialog(props) {
1154
+ const { store, pickDirectory } = props
1155
+ const tr = makeT(props.translate ?? props.t)
1156
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
1157
+ const dialogRef = useRef(null)
1158
+ const [selected, setSelected] = useState(() => new Set())
1159
+ const [confirming, setConfirming] = useState(false)
1160
+ const [browsing, setBrowsing] = useState(false)
1161
+ const [showBlocked, setShowBlocked] = useState(false)
1162
+
1163
+ const open = snapshot.dialogOpen
1164
+ const scan = snapshot.scan
1165
+ const result = snapshot.result
1166
+ const entries = scan?.entries ?? []
1167
+ const addable = useMemo(
1168
+ () => entries.filter((entry) => entry.status === 'new' || entry.status === 'replace'),
1169
+ [entries],
1170
+ )
1171
+ const blockedEntries = useMemo(
1172
+ () => entries.filter((entry) => entry.status !== 'new' && entry.status !== 'replace'),
1173
+ [entries],
1174
+ )
1175
+ const addableIds = useMemo(() => addable.map((entry) => entry.id), [addable])
1176
+ const addableGroups = useMemo(() => {
1177
+ const map = new Map()
1178
+ for (const entry of addable) {
1179
+ const key = typeof entry.cwd === 'string' && entry.cwd.length > 0 ? entry.cwd : '—'
1180
+ let list = map.get(key)
1181
+ if (list === undefined) {
1182
+ list = []
1183
+ map.set(key, list)
1184
+ }
1185
+ list.push(entry)
1186
+ }
1187
+ return [...map.entries()]
1188
+ .map(([cwd, list]) => ({
1189
+ cwd,
1190
+ entries: list.sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0)),
1191
+ }))
1192
+ .sort((left, right) => left.cwd.localeCompare(right.cwd))
1193
+ }, [addable])
1194
+
1195
+ useEffect(() => {
1196
+ if (!open) return
1197
+ setSelected(new Set())
1198
+ setConfirming(false)
1199
+ setBrowsing(false)
1200
+ setShowBlocked(false)
1201
+ }, [open])
1202
+
1203
+ useEffect(() => {
1204
+ if (!open || scan === null) return
1205
+ setSelected(new Set(addableIds))
1206
+ setShowBlocked(false)
1207
+ }, [open, scan?.generatedAt])
1208
+
1209
+ useEffect(() => {
1210
+ if (!open) return undefined
1211
+ const timer = window.setTimeout(() => {
1212
+ dialogRef.current?.querySelector('[data-lmw-autofocus]')?.focus()
1213
+ }, 40)
1214
+ return () => {
1215
+ window.clearTimeout(timer)
1216
+ try {
1217
+ document.querySelector('[data-lmw-foot-button]')?.focus()
1218
+ } catch {
1219
+ // A detached trigger is not worth reporting.
1220
+ }
1221
+ }
1222
+ }, [open])
1223
+
1224
+ useEffect(() => {
1225
+ if (!open) return undefined
1226
+ const onKeyDown = (event) => {
1227
+ if (event.key !== 'Escape') return
1228
+ event.stopPropagation()
1229
+ if (confirming) setConfirming(false)
1230
+ else store.close()
1231
+ }
1232
+ document.addEventListener('keydown', onKeyDown, true)
1233
+ return () => {
1234
+ document.removeEventListener('keydown', onKeyDown, true)
1235
+ }
1236
+ }, [open, confirming, store])
1237
+
1238
+ useEffect(() => {
1239
+ if (!open || !confirming) return undefined
1240
+ const timer = window.setTimeout(() => {
1241
+ dialogRef.current?.querySelector('[data-lmw-confirm-go]')?.focus()
1242
+ }, 30)
1243
+ return () => {
1244
+ window.clearTimeout(timer)
1245
+ }
1246
+ }, [open, confirming])
1247
+
1248
+ const toggleEntry = (entry) => {
1249
+ if (entry.status !== 'new' && entry.status !== 'replace') return
1250
+ setSelected((current) => {
1251
+ const next = new Set(current)
1252
+ if (next.has(entry.id)) next.delete(entry.id)
1253
+ else next.add(entry.id)
1254
+ return next
1255
+ })
1256
+ }
1257
+
1258
+ const selectedEntries = addable.filter((entry) => selected.has(entry.id))
1259
+ const addedCount = selectedEntries.filter((entry) => entry.status === 'new').length
1260
+ const replacedCount = selectedEntries.filter((entry) => entry.status === 'replace').length
1261
+
1262
+ const runApply = async () => {
1263
+ if (snapshot.applying || selected.size === 0) return
1264
+ setConfirming(false)
1265
+ await store.apply([...selected])
1266
+ }
1267
+
1268
+ if (!open) return null
1269
+
1270
+ const statusBadge = (entry) => {
1271
+ const cls = entry.status === 'new'
1272
+ ? 'lmw-badge lmw-badge-new'
1273
+ : entry.status === 'replace'
1274
+ ? 'lmw-badge lmw-badge-replace'
1275
+ : entry.status === 'live' || entry.status === 'conflict'
1276
+ ? 'lmw-badge lmw-badge-block'
1277
+ : 'lmw-badge'
1278
+ return h('span', { className: cls }, tr(`import.status.${entry.status}`))
1279
+ }
1280
+
1281
+ const renderEntry = (entry) => {
1282
+ const checkable = entry.status === 'new' || entry.status === 'replace'
1283
+ return h(
1284
+ 'li',
1285
+ { className: 'lmw-entry', key: `${entry.id}:${entry.sourceFile}` },
1286
+ h(
1287
+ 'label',
1288
+ { className: 'lmw-entry-label' },
1289
+ h(Checkbox, {
1290
+ checked: checkable && selected.has(entry.id),
1291
+ disabled: !checkable || snapshot.applying === true,
1292
+ label: shortId(entry.id),
1293
+ onChange: () => toggleEntry(entry),
1294
+ }),
1295
+ h(
1296
+ 'div',
1297
+ { className: 'lmw-entry-main' },
1298
+ h('div', { className: 'lmw-entry-title' },
1299
+ h('span', { className: 'lmw-entry-id', title: entry.id }, shortId(entry.id)),
1300
+ ' ',
1301
+ statusBadge(entry)),
1302
+ h('div', { className: 'lmw-entry-meta' },
1303
+ tr('import.entry.source', {
1304
+ size: formatBytes(entry.sourceBytes),
1305
+ time: formatTime(entry.sourceMtime),
1306
+ })),
1307
+ checkable && entry.existingPath
1308
+ ? h('div', { className: 'lmw-entry-meta' },
1309
+ tr('import.entry.existing', {
1310
+ size: formatBytes(entry.existingBytes),
1311
+ time: formatTime(entry.existingMtime),
1312
+ }))
1313
+ : null,
1314
+ entry.warning !== null && entry.warning !== undefined
1315
+ ? h('div', { className: 'lmw-warn-text' },
1316
+ tr(entry.warning === 'larger-only' ? 'import.warning.largerOnly' : 'import.warning.newerOnly'))
1317
+ : null,
1318
+ !checkable && entry.reason !== undefined
1319
+ ? h('div', { className: 'lmw-entry-reason' }, entry.reason)
1320
+ : null,
1321
+ ),
1322
+ ),
1323
+ )
1324
+ }
1325
+
1326
+ const renderScanTop = () => {
1327
+ if (scan === null) return null
1328
+ const blocked = (scan.counts?.blocked ?? 0) + (scan.counts?.invalid ?? 0)
1329
+ return h(
1330
+ 'div',
1331
+ { className: 'lmw-import-top' },
1332
+ h('div', { className: 'lmw-import-summary' },
1333
+ tr('import.summary', {
1334
+ added: scan.counts?.new ?? 0,
1335
+ replace: scan.counts?.replace ?? 0,
1336
+ skipped: scan.counts?.unchanged ?? 0,
1337
+ blocked,
1338
+ })),
1339
+ (scan.counts?.skippedSubagent ?? 0) > 0
1340
+ ? h('p', { className: 'lmw-note lmw-note-flush' },
1341
+ tr('import.note.subagent', { n: scan.counts.skippedSubagent }))
1342
+ : null,
1343
+ (scan.counts?.skippedLarge ?? 0) > 0
1344
+ ? h('p', { className: 'lmw-note lmw-note-flush' },
1345
+ tr('import.note.large', { n: scan.counts.skippedLarge }))
1346
+ : null,
1347
+ h('div', { className: 'lmw-toolbar' },
1348
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set(addableIds)) }, tr('toolbar.all')),
1349
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set()) }, tr('toolbar.none'))),
1350
+ )
1351
+ }
1352
+
1353
+ const renderScanLists = () => {
1354
+ if (scan === null) return null
1355
+ const blocked = blockedEntries.length
1356
+ return h(
1357
+ 'div',
1358
+ { className: 'lmw-import-scroll' },
1359
+ addableGroups.length === 0
1360
+ ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('import.none'))
1361
+ : addableGroups.map((group) => h(
1362
+ 'section',
1363
+ { className: 'lmw-group', key: group.cwd },
1364
+ h('div', { className: 'lmw-group-head' },
1365
+ h('span', { className: 'lmw-group-path' }, group.cwd),
1366
+ h('span', { className: 'lmw-count' }, tr('import.count', { n: group.entries.length }))),
1367
+ h('ul', { className: 'lmw-import-entries' }, group.entries.map(renderEntry)),
1368
+ )),
1369
+ blocked > 0
1370
+ ? h(
1371
+ 'section',
1372
+ { className: 'lmw-import-blocked' },
1373
+ h(
1374
+ 'button',
1375
+ {
1376
+ type: 'button',
1377
+ className: 'lmw-import-blocked-head',
1378
+ 'aria-expanded': showBlocked ? 'true' : 'false',
1379
+ onClick: () => setShowBlocked((value) => !value),
1380
+ },
1381
+ h(
1382
+ 'svg',
1383
+ {
1384
+ width: 10,
1385
+ height: 10,
1386
+ viewBox: '0 0 10 10',
1387
+ 'aria-hidden': 'true',
1388
+ className: showBlocked ? 'lmw-chev lmw-chev-open' : 'lmw-chev',
1389
+ },
1390
+ h('path', {
1391
+ d: 'M3 1.5 6.5 5 3 8.5',
1392
+ fill: 'none',
1393
+ stroke: 'currentColor',
1394
+ 'stroke-width': 1.4,
1395
+ 'stroke-linecap': 'round',
1396
+ 'stroke-linejoin': 'round',
1397
+ }),
1398
+ ),
1399
+ h('span', null, tr('import.blocked.title', { n: blocked })),
1400
+ ),
1401
+ showBlocked
1402
+ ? h('ul', { className: 'lmw-import-entries' }, blockedEntries.map(renderEntry))
1403
+ : null,
1404
+ )
1405
+ : null,
1406
+ )
1407
+ }
1408
+
1409
+ const renderResult = () => {
1410
+ const counts = result?.counts ?? {}
1411
+ const list = Array.isArray(result?.results) ? result.results : []
1412
+ return h(
1413
+ 'div',
1414
+ { className: 'lmw-result' },
1415
+ h('div', { className: 'lmw-result-title lmw-ok' }, tr('import.result.title')),
1416
+ h('p', { className: 'lmw-result-text' },
1417
+ tr('import.result.summary', {
1418
+ added: counts.added ?? 0,
1419
+ replaced: counts.replaced ?? 0,
1420
+ failed: counts.failed ?? 0,
1421
+ skipped: counts.skipped ?? 0,
1422
+ })),
1423
+ list.length > 0
1424
+ ? h('ul', { className: 'lmw-list' }, list.map((entry, index) => h(
1425
+ 'li',
1426
+ { key: `${entry.sessionId}:${index}` },
1427
+ `${shortId(entry.sessionId)} — ${tr(`import.result.${entry.action}`)}`
1428
+ + (entry.workspace === undefined ? '' : ` · ${entry.workspace.path}`)
1429
+ + (entry.message === undefined ? '' : ` · ${entry.message}`),
1430
+ )))
1431
+ : null,
1432
+ h('div', { className: 'lmw-result-actions' },
1433
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => { void store.scanNow() } }, tr('import.result.rescan')),
1434
+ h('button', { type: 'button', className: 'lmw-button lmw-primary', onClick: () => store.close() }, tr('import.result.close'))),
1435
+ )
1436
+ }
1437
+
1438
+ const header = h(
1439
+ 'header',
1440
+ { className: 'lmw-header' },
1441
+ h(
1442
+ 'div',
1443
+ { className: 'lmw-header-text' },
1444
+ h('div', { className: 'lmw-title' }, tr('import.title')),
1445
+ h('div', { className: 'lmw-subtitle' }, tr('import.subtitle')),
1446
+ ),
1447
+ h(
1448
+ 'button',
1449
+ {
1450
+ type: 'button',
1451
+ className: 'lmw-close',
1452
+ 'aria-label': tr('dialog.close'),
1453
+ 'data-lmw-autofocus': '',
1454
+ onClick: () => store.close(),
1455
+ },
1456
+ h('svg', { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': 'true' },
1457
+ h('path', { d: 'M3 3l8 8M11 3l-8 8', stroke: 'currentColor', 'stroke-width': 1.6, 'stroke-linecap': 'round' })),
1458
+ ),
1459
+ )
1460
+
1461
+ const body = () => {
1462
+ if (result !== null) return h('div', { className: 'lmw-import-scroll' }, renderResult())
1463
+ return h(
1464
+ 'div',
1465
+ { className: 'lmw-import-body' },
1466
+ h(
1467
+ 'div',
1468
+ { className: 'lmw-import-top' },
1469
+ h(
1470
+ 'div',
1471
+ { className: 'lmw-import-path' },
1472
+ h('label', { className: 'lmw-import-label' }, tr('import.pathLabel')),
1473
+ h('input', {
1474
+ className: 'lmw-input',
1475
+ type: 'text',
1476
+ spellCheck: false,
1477
+ value: snapshot.path,
1478
+ placeholder: tr('import.pathPlaceholder'),
1479
+ onChange: (event) => store.setPath(event.target.value),
1480
+ onKeyDown: (event) => {
1481
+ if (event.key !== 'Enter' || snapshot.scanning) return
1482
+ event.preventDefault()
1483
+ void store.scanNow()
1484
+ },
1485
+ }),
1486
+ h('button', {
1487
+ type: 'button',
1488
+ className: 'lmw-button',
1489
+ disabled: browsing || typeof pickDirectory !== 'function',
1490
+ onClick: async () => {
1491
+ setBrowsing(true)
1492
+ try {
1493
+ const picked = await pickDirectory()
1494
+ if (typeof picked === 'string' && picked.length > 0) store.setPath(picked)
1495
+ } catch {
1496
+ // A cancelled or unavailable chooser leaves the field as it is.
1497
+ } finally {
1498
+ setBrowsing(false)
1499
+ }
1500
+ },
1501
+ }, browsing ? tr('import.scanning') : tr('import.browse')),
1502
+ h('button', {
1503
+ type: 'button',
1504
+ className: 'lmw-button lmw-primary',
1505
+ disabled: snapshot.scanning === true,
1506
+ onClick: () => { void store.scanNow() },
1507
+ }, snapshot.scanning ? tr('import.scanning') : tr('import.scan')),
1508
+ ),
1509
+ snapshot.error === 'no-path'
1510
+ ? h('p', { className: 'lmw-error' }, tr('import.error.noPath'))
1511
+ : snapshot.error !== null && snapshot.error !== undefined
1512
+ ? h('p', { className: 'lmw-error' }, tr('import.error.scan', { message: snapshot.error }))
1513
+ : null,
1514
+ snapshot.applyError !== null && snapshot.applyError !== undefined
1515
+ ? h('p', { className: 'lmw-error' }, tr('import.error.apply', { message: snapshot.applyError }))
1516
+ : null,
1517
+ scan === null && (snapshot.error === null || snapshot.error === undefined)
1518
+ ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('import.empty'))
1519
+ : null,
1520
+ renderScanTop(),
1521
+ ),
1522
+ renderScanLists(),
1523
+ )
1524
+ }
1525
+
1526
+ const footer = () => {
1527
+ if (result !== null) return null
1528
+ return h(
1529
+ 'div',
1530
+ { className: 'lmw-footbar' },
1531
+ h('span', { className: 'lmw-summary' }, tr('import.selected', { sessions: selected.size })),
1532
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => store.close() }, tr('action.cancel')),
1533
+ h('button', {
1534
+ type: 'button',
1535
+ className: 'lmw-button lmw-primary',
1536
+ disabled: snapshot.applying === true || selected.size === 0,
1537
+ onClick: () => setConfirming(true),
1538
+ }, snapshot.applying ? tr('import.applying') : tr('import.action')),
1539
+ )
1540
+ }
1541
+
1542
+ const confirmLayer = confirming
1543
+ ? h('div', { className: 'lmw-confirm-layer' },
1544
+ h('div', {
1545
+ className: 'lmw-confirm-card',
1546
+ role: 'alertdialog',
1547
+ 'aria-modal': 'true',
1548
+ 'aria-label': tr('import.confirm.title'),
1549
+ },
1550
+ h('div', { className: 'lmw-confirm-title' }, tr('import.confirm.title')),
1551
+ h('p', { className: 'lmw-confirm-text' }, tr('import.confirm.text', { added: addedCount, replaced: replacedCount })),
1552
+ h('div', { className: 'lmw-confirm-actions' },
1553
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => setConfirming(false) }, tr('import.confirm.back')),
1554
+ h('button', {
1555
+ type: 'button',
1556
+ className: 'lmw-button lmw-primary',
1557
+ 'data-lmw-confirm-go': '',
1558
+ onClick: () => { void runApply() },
1559
+ }, tr('import.confirm.go')))))
1560
+ : null
1561
+
1562
+ return h('div', {
1563
+ className: 'lmw-backdrop',
1564
+ onMouseDown: (event) => {
1565
+ if (event.target === event.currentTarget) store.close()
1566
+ },
1567
+ },
1568
+ h('section', {
1569
+ ref: dialogRef,
1570
+ className: 'lmw-dialog',
1571
+ role: 'dialog',
1572
+ 'aria-modal': 'true',
1573
+ 'aria-label': tr('import.title'),
1574
+ },
1575
+ header,
1576
+ h('div', { className: 'lmw-body lmw-body-fixed' }, body()),
1577
+ footer(),
1578
+ confirmLayer,
1579
+ ),
1580
+ )
1581
+ }
1582
+
1583
+ /* ------------------------------------------------------------------ */
1584
+ /* Workspace sort and offline guard */
1585
+ /* ------------------------------------------------------------------ */
1586
+
1587
+ const SORT_GLYPH = h(
1588
+ 'svg',
1589
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
1590
+ h('path', { d: 'M3 4.5h10M3 8h7M3 11.5h4', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round' }),
1591
+ )
1592
+
1593
+ const SORT_STORAGE_KEY = 'lmw.workspaceSortMode'
1594
+ const SORT_MODES = ['path', 'title', 'activity']
1595
+
1596
+ function readStoredSortMode() {
1597
+ try {
1598
+ const mode = window.localStorage.getItem(SORT_STORAGE_KEY)
1599
+ return SORT_MODES.includes(mode) ? mode : null
1600
+ } catch {
1601
+ return null
1602
+ }
1603
+ }
1604
+
1605
+ function createSortStore() {
1606
+ let snapshot = { open: false, busy: false, error: null, mode: readStoredSortMode() }
1607
+ const listeners = new Set()
1608
+ const publish = (patch) => {
1609
+ snapshot = { ...snapshot, ...patch }
1610
+ for (const listener of [...listeners]) {
1611
+ try {
1612
+ listener()
1613
+ } catch (error) {
1614
+ console.error('[lmw-plugin] sort listener failed:', error)
1615
+ }
1616
+ }
1617
+ }
1618
+ const apply = async (mode) => {
1619
+ if (snapshot.busy) return
1620
+ if (mode === 'manual') {
1621
+ try {
1622
+ window.localStorage.removeItem(SORT_STORAGE_KEY)
1623
+ } catch {
1624
+ // A browser that refuses storage simply forgets the preference.
1625
+ }
1626
+ publish({ mode: null, open: false, error: null })
1627
+ return
1628
+ }
1629
+ publish({ busy: true, error: null })
1630
+ try {
1631
+ await requestJson('POST', 'workspaces/sort', { mode })
1632
+ try {
1633
+ window.localStorage.setItem(SORT_STORAGE_KEY, mode)
1634
+ } catch {
1635
+ // A browser that refuses storage simply forgets the preference.
1636
+ }
1637
+ publish({ busy: false, open: false, mode })
1638
+ } catch (error) {
1639
+ publish({ busy: false, error: messageOf(error) })
1640
+ }
1641
+ }
1642
+ /** Re-apply the remembered mode at startup and after a page reload. */
1643
+ const autoApply = async () => {
1644
+ const mode = snapshot.mode
1645
+ if (mode === null) return
1646
+ try {
1647
+ await requestJson('POST', 'workspaces/sort', { mode })
1648
+ } catch (error) {
1649
+ console.error('[lmw-plugin] applying the remembered workspace sort failed:', error)
1650
+ }
1651
+ }
1652
+ return {
1653
+ getSnapshot: () => snapshot,
1654
+ subscribe: (listener) => {
1655
+ listeners.add(listener)
1656
+ return () => listeners.delete(listener)
1657
+ },
1658
+ open: () => publish({ open: true, error: null }),
1659
+ close: () => publish({ open: false, error: null }),
1660
+ toggle: () => publish({ open: !snapshot.open, error: null }),
1661
+ apply,
1662
+ autoApply,
1663
+ }
1664
+ }
1665
+
1666
+ /** Always-mounted guard: mark Workspaces whose directory vanished and block them. */
1667
+ function WorkspaceOfflineGuard(props) {
1668
+ const tr = makeT(props.translate ?? props.t)
1669
+ useEffect(() => {
1670
+ let statuses = { workspaces: {}, sessions: {} }
1671
+ let disposed = false
1672
+ let timer = 0
1673
+
1674
+ const mark = () => {
1675
+ for (const row of document.querySelectorAll('[data-row-key^="workspace:"]')) {
1676
+ const id = row.getAttribute('data-row-key').slice('workspace:'.length)
1677
+ const missing = statuses.workspaces[id] === true
1678
+ row.toggleAttribute('data-lmw-offline', missing)
1679
+ if (missing) {
1680
+ row.setAttribute('title', tr('offline.workspace'))
1681
+ row.setAttribute('aria-disabled', 'true')
1682
+ } else {
1683
+ row.removeAttribute('title')
1684
+ row.removeAttribute('aria-disabled')
1685
+ }
1686
+ }
1687
+ for (const row of document.querySelectorAll('[data-row-key^="session:"]')) {
1688
+ const id = row.getAttribute('data-row-key').slice('session:'.length)
1689
+ const missing = statuses.sessions[id] === true
1690
+ row.toggleAttribute('data-lmw-offline', missing)
1691
+ if (missing) {
1692
+ row.setAttribute('title', tr('offline.session'))
1693
+ row.setAttribute('aria-disabled', 'true')
1694
+ } else {
1695
+ row.removeAttribute('title')
1696
+ row.removeAttribute('aria-disabled')
1697
+ }
1698
+ }
1699
+ const selected = document.querySelector('[data-row-key^="session:"][aria-selected="true"]')
1700
+ const sessionId = selected?.getAttribute('data-row-key')?.slice('session:'.length)
1701
+ const offlineActive = sessionId !== undefined && statuses.sessions[sessionId] === true
1702
+ const composer = document.querySelector('[data-lmw-composer]')
1703
+ ?? document.querySelector('[contenteditable="true"]')
1704
+ if (composer !== null) {
1705
+ composer.setAttribute('data-lmw-composer', '')
1706
+ composer.toggleAttribute('data-lmw-offline-composer', offlineActive)
1707
+ if (offlineActive) {
1708
+ composer.setAttribute('title', tr('offline.input'))
1709
+ composer.setAttribute('aria-disabled', 'true')
1710
+ } else {
1711
+ composer.removeAttribute('title')
1712
+ composer.removeAttribute('aria-disabled')
1713
+ }
1714
+ }
1715
+ }
1716
+
1717
+ const schedule = () => {
1718
+ if (timer !== 0) return
1719
+ timer = window.setTimeout(() => {
1720
+ timer = 0
1721
+ mark()
1722
+ }, 120)
1723
+ }
1724
+
1725
+ const load = async () => {
1726
+ try {
1727
+ const data = await requestJson('GET', 'workspaces/status')
1728
+ const workspaces = {}
1729
+ const sessions = {}
1730
+ for (const workspace of data.workspaces ?? []) {
1731
+ workspaces[workspace.id] = workspace.missing === true
1732
+ for (const sid of workspace.sessionIds ?? []) sessions[sid] = workspace.missing === true
1733
+ }
1734
+ if (!disposed) {
1735
+ statuses = { workspaces, sessions }
1736
+ mark()
1737
+ }
1738
+ } catch (error) {
1739
+ console.error('[lmw-plugin] workspace status failed:', error)
1740
+ }
1741
+ }
1742
+
1743
+ const blockRow = (event) => {
1744
+ const row = event.target instanceof Element ? event.target.closest('[data-lmw-offline]') : null
1745
+ if (row === null) return
1746
+ event.preventDefault()
1747
+ event.stopPropagation()
1748
+ }
1749
+ const blockInput = (event) => {
1750
+ const target = event.target instanceof Element ? event.target : null
1751
+ if (target === null || target.closest('[data-lmw-offline-composer]') === null) return
1752
+ event.preventDefault()
1753
+ event.stopPropagation()
1754
+ }
1755
+
1756
+ const observer = new MutationObserver(schedule)
1757
+ observer.observe(document.body, { childList: true, subtree: true })
1758
+ const unsubscribe = workspaces.list.subscribe(() => {
1759
+ schedule()
1760
+ void load()
1761
+ })
1762
+ document.addEventListener('click', blockRow, true)
1763
+ document.addEventListener('keydown', blockRow, true)
1764
+ for (const type of ['keydown', 'beforeinput', 'paste', 'drop']) document.addEventListener(type, blockInput, true)
1765
+ const interval = window.setInterval(() => { void load() }, 20000)
1766
+ void load()
1767
+
1768
+ return () => {
1769
+ disposed = true
1770
+ observer.disconnect()
1771
+ unsubscribe()
1772
+ window.clearInterval(interval)
1773
+ document.removeEventListener('click', blockRow, true)
1774
+ document.removeEventListener('keydown', blockRow, true)
1775
+ for (const type of ['keydown', 'beforeinput', 'paste', 'drop']) document.removeEventListener(type, blockInput, true)
1776
+ if (timer !== 0) window.clearTimeout(timer)
1777
+ for (const row of document.querySelectorAll('[data-lmw-offline]')) {
1778
+ row.removeAttribute('data-lmw-offline')
1779
+ row.removeAttribute('aria-disabled')
1780
+ }
1781
+ }
1782
+ }, [workspaces, tr])
1783
+ return null
1784
+ }
1785
+
1786
+ function SortDialog(props) {
1787
+ const { store } = props
1788
+ const tr = makeT(props.translate ?? props.t)
1789
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
1790
+ const dialogRef = useRef(null)
1791
+ useEffect(() => {
1792
+ if (!snapshot.open) return undefined
1793
+ const onKeyDown = (event) => {
1794
+ if (event.key !== 'Escape') return
1795
+ event.stopPropagation()
1796
+ store.close()
1797
+ }
1798
+ document.addEventListener('keydown', onKeyDown, true)
1799
+ const timer = window.setTimeout(() => dialogRef.current?.querySelector('button')?.focus(), 30)
1800
+ return () => {
1801
+ document.removeEventListener('keydown', onKeyDown, true)
1802
+ window.clearTimeout(timer)
1803
+ }
1804
+ }, [snapshot.open, store])
1805
+ if (!snapshot.open) return null
1806
+ const option = (mode, label) => {
1807
+ const active = (snapshot.mode ?? 'manual') === mode
1808
+ return h('button', {
1809
+ type: 'button',
1810
+ className: active ? 'lmw-button lmw-sort-option lmw-sort-active' : 'lmw-button lmw-sort-option',
1811
+ disabled: snapshot.busy,
1812
+ 'aria-pressed': active ? 'true' : 'false',
1813
+ onClick: () => { void store.apply(mode) },
1814
+ }, label, active ? h('span', { className: 'lmw-sort-check', 'aria-hidden': 'true' }, '✓') : null)
1815
+ }
1816
+ return h('div', {
1817
+ className: 'lmw-backdrop',
1818
+ onMouseDown: (event) => { if (event.target === event.currentTarget) store.close() },
1819
+ },
1820
+ h('section', { ref: dialogRef, className: 'lmw-dialog lmw-dialog-sm', role: 'dialog', 'aria-modal': 'true', 'aria-label': tr('sort.title') },
1821
+ h('header', { className: 'lmw-header' },
1822
+ h('div', { className: 'lmw-header-text' },
1823
+ h('div', { className: 'lmw-title' }, tr('sort.title')),
1824
+ h('div', { className: 'lmw-subtitle' }, tr('sort.hint'))),
1825
+ h('button', { type: 'button', className: 'lmw-close', 'aria-label': tr('dialog.close'), onClick: () => store.close() },
1826
+ h('svg', { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': 'true' },
1827
+ h('path', { d: 'M3 3l8 8M11 3l-8 8', stroke: 'currentColor', 'stroke-width': 1.6, 'stroke-linecap': 'round' })))),
1828
+ h('div', { className: 'lmw-body lmw-sort-body' },
1829
+ snapshot.error !== null ? h('p', { className: 'lmw-error' }, snapshot.error) : null,
1830
+ option('path', tr('sort.byPath')),
1831
+ option('title', tr('sort.byName')),
1832
+ option('activity', tr('sort.byActivity')),
1833
+ option('manual', tr('sort.manual')),
1834
+ snapshot.busy ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('sort.applying')) : null),
1835
+ h('div', { className: 'lmw-footbar' },
1836
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => store.close() }, tr('dialog.close')))))
1837
+ }
1838
+
1839
+ /* ------------------------------------------------------------------ */
1840
+ /* Workspace path subtitle decorator */
1841
+ /* ------------------------------------------------------------------ */
1842
+
1843
+ function WorkspacePathDecorator(props) {
1844
+ const { workspaces } = props
1845
+ useEffect(() => {
1846
+ const paths = new Map()
1847
+ const apply = () => {
1848
+ const rows = document.querySelectorAll('[data-row-key^="workspace:"]')
1849
+ if (rows.length === 0) return
1850
+ for (const row of rows) {
1851
+ const key = row.getAttribute('data-row-key') ?? ''
1852
+ const workspaceId = key.slice('workspace:'.length)
1853
+ const path = paths.get(workspaceId)
1854
+ let anchor = null
1855
+ for (const child of row.children) {
1856
+ if (child.tagName !== 'SPAN') continue
1857
+ if (child.querySelector('svg') !== null) continue
1858
+ const inner = child.firstElementChild
1859
+ if (inner !== null && inner.tagName === 'SPAN') {
1860
+ anchor = inner
1861
+ break
1862
+ }
1863
+ }
1864
+ let node = row.querySelector('[data-lmw-ws-path]')
1865
+ if (path === undefined || anchor === null) {
1866
+ if (node !== null) node.remove()
1867
+ row.removeAttribute('data-lmw-ws-row')
1868
+ continue
1869
+ }
1870
+ row.setAttribute('data-lmw-ws-row', '')
1871
+ if (node === null) {
1872
+ node = document.createElement('span')
1873
+ node.setAttribute('data-lmw-ws-path', '')
1874
+ anchor.parentElement.appendChild(node)
1875
+ }
1876
+ if (node.textContent !== path) node.textContent = path
1877
+ }
1878
+ }
1879
+ const readPaths = () => {
1880
+ const snapshot = workspaces.list.getSnapshot()
1881
+ paths.clear()
1882
+ for (const item of snapshot.items ?? []) paths.set(String(item.workspaceId), item.path)
1883
+ apply()
1884
+ }
1885
+ let scheduled = 0
1886
+ const schedule = () => {
1887
+ if (scheduled !== 0) return
1888
+ scheduled = window.setTimeout(() => {
1889
+ scheduled = 0
1890
+ apply()
1891
+ }, 120)
1892
+ }
1893
+ const observer = new MutationObserver(schedule)
1894
+ observer.observe(document.body, { childList: true, subtree: true })
1895
+ // The Workspace baseline usually lands after this entry mounts, and an
1896
+ // execution adds more rows later: rebuild the id -> path map on every
1897
+ // Workspace snapshot change, not only once at mount.
1898
+ const unsubscribe = workspaces.list.subscribe(readPaths)
1899
+ readPaths()
1900
+ return () => {
1901
+ observer.disconnect()
1902
+ unsubscribe()
1903
+ if (scheduled !== 0) window.clearTimeout(scheduled)
1904
+ for (const node of document.querySelectorAll('[data-lmw-ws-path]')) node.remove()
1905
+ for (const row of document.querySelectorAll('[data-lmw-ws-row]')) row.removeAttribute('data-lmw-ws-row')
1906
+ }
1907
+ }, [workspaces])
1908
+ return h('style', { 'data-lmw-style': 'base' }, BASE_CSS)
1909
+ }
1910
+
1911
+ /* ------------------------------------------------------------------ */
1912
+ /* Styles */
1913
+ /* ------------------------------------------------------------------ */
1914
+
1915
+ const DIALOG_CSS = [
1916
+ '.lmw-foot{display:flex;align-items:center;width:100%;min-width:0}',
1917
+ '.lmw-foot-stack{display:flex;flex-direction:column;gap:2px;flex:1 1 auto;min-width:0}',
1918
+ '.lmw-foot-button{display:flex;align-items:center;gap:8px;width:100%;min-width:0;min-height:32px;padding:0 8px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font-size:13px;line-height:20px;cursor:pointer;font-family:inherit}',
1919
+ '.lmw-foot-button:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-label-primary)}',
1920
+ '.lmw-foot-button[data-wide="0"]{justify-content:center;padding:0}',
1921
+ '.lmw-foot-glyph{display:inline-flex;flex:none;color:inherit}',
1922
+ '.lmw-foot-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}',
1923
+ '.lmw-foot-count{flex:none;min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-primary-foreground,#fff);font-size:11px;line-height:18px;text-align:center}',
1924
+ '.lmw-backdrop{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.32);pointer-events:auto}',
1925
+ '.lmw-dialog{position:relative;display:flex;flex-direction:column;width:min(760px,100%);max-height:min(86vh,760px);background:var(--dsw-alias-bg-overlay);color:var(--dsw-alias-label-primary);border:0.5px solid var(--dsw-alias-border-l2);border-radius:12px;box-shadow:0 18px 48px rgba(0,0,0,.2);overflow:hidden;font-size:13px;line-height:20px}',
1926
+ '.lmw-header{display:flex;align-items:flex-start;gap:12px;padding:16px 18px 12px;border-bottom:0.5px solid var(--dsw-alias-border-l1)}',
1927
+ '.lmw-header-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:4px}',
1928
+ '.lmw-title{font-size:15px;font-weight:600;line-height:20px}',
1929
+ '.lmw-subtitle{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px;overflow-wrap:anywhere}',
1930
+ '.lmw-close{flex:none;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;padding:0}',
1931
+ '.lmw-close:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-label-primary)}',
1932
+ '.lmw-body{flex:1;min-height:0;overflow-y:auto;padding:14px 18px 4px}',
1933
+ '.lmw-panels{display:flex;flex-direction:column}',
1934
+ '.lmw-panel{display:flex;flex-direction:column;gap:8px;padding-bottom:14px}',
1935
+ '.lmw-panel + .lmw-panel{border-top:1px solid var(--dsw-alias-border-l2);padding-top:14px}',
1936
+ '.lmw-panel-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}',
1937
+ '.lmw-panel-title{font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}',
1938
+ '.lmw-panel-meta{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px}',
1939
+ '.lmw-toolbar{display:flex;align-items:center;gap:14px}',
1940
+ '.lmw-link{appearance:none;border:0;background:transparent;color:var(--dsw-alias-brand-primary);font-size:12px;line-height:18px;padding:0;cursor:pointer;font-family:inherit}',
1941
+ '.lmw-link:hover{text-decoration:underline}',
1942
+ '.lmw-group{background:var(--dsw-alias-bg-layer-1);border:0.5px solid var(--dsw-alias-border-l1);border-radius:8px;margin:0 0 8px;overflow:hidden}',
1943
+ '.lmw-group[data-missing="1"]{border-color:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 45%,var(--dsw-alias-border-l1))}',
1944
+ '.lmw-group-head{display:flex;align-items:flex-start;gap:8px;padding:9px 10px;background:var(--dsw-alias-bg-layer-2);cursor:pointer}',
1945
+ '.lmw-group-path{flex:1;min-width:0;font-size:12.5px;line-height:17px;font-weight:600;overflow-wrap:anywhere;word-break:break-word}',
1946
+ '.lmw-count{flex:none;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px;white-space:nowrap}',
1947
+ '.lmw-sessions{list-style:none;margin:0;padding:5px 8px 7px 30px;display:flex;flex-direction:column;gap:2px}',
1948
+ '.lmw-session-label{display:flex;align-items:center;gap:8px;min-height:26px;padding:2px 6px;border-radius:6px;cursor:pointer}',
1949
+ '.lmw-session-label:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
1950
+ '.lmw-session-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
1951
+ '.lmw-session-id{flex:none;color:var(--dsw-alias-label-tertiary,var(--dsw-alias-label-secondary));font-size:11px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}',
1952
+ '.lmw-check{flex:none;width:14px;height:14px;margin:0;accent-color:var(--dsw-alias-brand-primary)}',
1953
+ '.lmw-badge{flex:none;padding:1px 6px;border-radius:8px;background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 12%,transparent);color:var(--dsw-alias-state-warn-primary);font-size:11px;line-height:16px;white-space:nowrap}',
1954
+ '.lmw-badge-warn{background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 14%,transparent)}',
1955
+ '.lmw-skill-line{display:flex;align-items:center;flex-wrap:wrap;gap:8px;padding:8px 10px;border:0.5px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1)}',
1956
+ '.lmw-skill-check{cursor:pointer}',
1957
+ '.lmw-skill-label{flex:0 1 auto;min-width:0;font-size:12.5px;color:var(--dsw-alias-label-primary)}',
1958
+ '.lmw-skill-state{flex:none;font-size:12px;color:var(--dsw-alias-label-secondary)}',
1959
+ '.lmw-check-ok{flex:none;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-state-success-primary)}',
1960
+ '.lmw-path{flex:1 1 160px;min-width:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px;line-height:16px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;word-break:break-word}',
1961
+ '.lmw-footbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px;row-gap:8px;padding:12px 18px;border-top:0.5px solid var(--dsw-alias-border-l1)}',
1962
+ '.lmw-summary{flex:1;min-width:0;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px}',
1963
+ '.lmw-button{appearance:none;flex:none;border:0.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-button-elevated-fill,transparent);color:var(--dsw-alias-label-primary);font-size:13px;line-height:18px;padding:5px 12px;border-radius:8px;cursor:pointer;font-family:inherit}',
1964
+ '.lmw-button:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
1965
+ '.lmw-button:disabled{opacity:.5;cursor:default}',
1966
+ '.lmw-primary{background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary));border-color:transparent;color:var(--dsw-alias-label-primary-foreground,#fff)}',
1967
+ '.lmw-primary:hover{background:var(--dsw-alias-button-primary-hover,var(--dsw-alias-brand-primary))}',
1968
+ '.lmw-state{display:flex;flex-direction:column;align-items:stretch;gap:10px;padding:4px 0}',
1969
+ '.lmw-note{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px;margin:6px 0 0}',
1970
+ '.lmw-note-flush{margin:0}',
1971
+ '.lmw-warn{color:var(--dsw-alias-state-warn-primary);font-size:12px;font-weight:400}',
1972
+ '.lmw-ok{color:var(--dsw-alias-state-success-primary);font-size:12px;font-weight:400}',
1973
+ '.lmw-error{color:var(--dsw-alias-state-error-primary);font-size:12px;line-height:17px;margin:6px 0 0;overflow-wrap:anywhere}',
1974
+ '.lmw-result{display:flex;flex-direction:column;gap:8px}',
1975
+ '.lmw-result-title{font-size:13px;font-weight:600}',
1976
+ '.lmw-result-text{margin:0;font-size:12px;line-height:17px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
1977
+ '.lmw-list{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:3px;font-size:12px;line-height:17px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
1978
+ '.lmw-result-fail{display:flex;flex-direction:column;gap:2px}',
1979
+ '.lmw-result-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:4px}',
1980
+ '.lmw-confirm-layer{position:absolute;inset:0;z-index:2;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.32)}',
1981
+ '.lmw-confirm-card{width:min(440px,100%);display:flex;flex-direction:column;gap:10px;padding:16px;border:0.5px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-overlay);box-shadow:0 12px 32px rgba(0,0,0,.22)}',
1982
+ '.lmw-confirm-title{font-size:14px;font-weight:600}',
1983
+ '.lmw-confirm-text{margin:0;font-size:12.5px;line-height:18px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
1984
+ '.lmw-confirm-actions{display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap}',
1985
+ '.lmw-body-fixed{display:flex;flex-direction:column;overflow:hidden}',
1986
+ '.lmw-dialog-sm{width:min(440px,100%)}',
1987
+ '.lmw-sort-body{display:flex;flex-direction:column;gap:8px}',
1988
+ '.lmw-sort-option{justify-content:flex-start;width:100%}',
1989
+ '.lmw-sort-active{color:var(--dsw-alias-brand-primary);border-color:color-mix(in srgb,var(--dsw-alias-brand-primary) 45%,var(--dsw-alias-border-l2))}',
1990
+ '.lmw-sort-check{margin-left:auto;font-size:12px}',
1991
+ '[data-lmw-offline]{opacity:.45;filter:grayscale(1);cursor:not-allowed!important}',
1992
+ '[data-lmw-offline] *{cursor:not-allowed!important}',
1993
+ '[data-lmw-offline-composer]{opacity:.55;cursor:not-allowed!important}',
1994
+ '.lmw-import-body{display:flex;flex-direction:column;flex:1;min-height:0;gap:10px}',
1995
+ '.lmw-import-top{display:flex;flex-direction:column;gap:8px;flex:none;min-width:0}',
1996
+ '.lmw-import-scroll{flex:1;min-height:0;overflow-y:auto;padding-right:2px}',
1997
+ '.lmw-import-path{display:flex;align-items:center;gap:8px;flex-wrap:wrap}',
1998
+ '.lmw-import-label{flex:none;font-size:12.5px;color:var(--dsw-alias-label-secondary)}',
1999
+ '.lmw-input{flex:1 1 260px;min-width:0;height:30px;padding:0 9px;box-sizing:border-box;border:0.5px solid var(--dsw-alias-border-l2);border-radius:7px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12.5px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;outline:none}',
2000
+ '.lmw-input:focus{border-color:var(--dsw-alias-brand-primary)}',
2001
+ '.lmw-import-summary{font-size:12px;line-height:17px;color:var(--dsw-alias-label-secondary)}',
2002
+ '.lmw-import-blocked{margin-top:12px;border-top:1px solid var(--dsw-alias-border-l2);padding-top:8px}',
2003
+ '.lmw-import-blocked-head{display:flex;align-items:center;gap:6px;width:100%;border:0;background:transparent;color:var(--dsw-alias-label-primary);font-size:12.5px;line-height:17px;padding:5px 4px;cursor:pointer;font-family:inherit;text-align:left;border-radius:6px}',
2004
+ '.lmw-import-blocked-head:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
2005
+ '.lmw-chev{flex:none;color:var(--dsw-alias-label-secondary);transition:transform 120ms ease}',
2006
+ '.lmw-chev-open{transform:rotate(90deg)}',
2007
+ '.lmw-import-entries{list-style:none;margin:0;padding:5px 8px 7px 10px;display:flex;flex-direction:column;gap:2px}',
2008
+ '.lmw-entry{min-width:0}',
2009
+ '.lmw-entry-label{display:flex;align-items:flex-start;gap:8px;padding:5px 6px;border-radius:6px;cursor:pointer}',
2010
+ '.lmw-entry-label:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
2011
+ '.lmw-entry-main{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}',
2012
+ '.lmw-entry-title{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:12.5px;line-height:17px}',
2013
+ '.lmw-entry-id{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px}',
2014
+ '.lmw-entry-meta{font-size:11px;line-height:15px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
2015
+ '.lmw-entry-reason{font-size:11px;line-height:15px;color:var(--dsw-alias-state-error-primary);overflow-wrap:anywhere}',
2016
+ '.lmw-warn-text{font-size:11px;line-height:15px;color:var(--dsw-alias-state-warn-primary);overflow-wrap:anywhere}',
2017
+ '.lmw-badge-new{background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 12%,transparent);color:var(--dsw-alias-state-success-primary)}',
2018
+ '.lmw-badge-replace{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 12%,transparent);color:var(--dsw-alias-brand-primary)}',
2019
+ '.lmw-badge-block{background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 12%,transparent);color:var(--dsw-alias-state-error-primary)}',
2020
+ ].join('\n')
2021
+
2022
+ const PATH_CSS = [
2023
+ '[data-lmw-ws-row]{height:auto!important;min-height:32px;padding-top:3px!important;padding-bottom:3px!important}',
2024
+ '[data-lmw-ws-path]{display:block;min-width:0;max-width:100%;font-size:11px;line-height:14px;font-weight:400;color:var(--dsw-alias-label-secondary);white-space:normal;overflow-wrap:anywhere;word-break:break-word;direction:ltr;unicode-bidi:plaintext;-webkit-user-select:text;user-select:text;cursor:text}',
2025
+ '[data-lmw-ws-path]:hover{color:var(--dsw-alias-label-primary)}',
2026
+ ].join('\n')
2027
+
2028
+ // One always-mounted stylesheet: the sidebar footer action must look right
2029
+ // before the dialog ever opens, so its rules cannot live in the dialog.
2030
+ const BASE_CSS = DIALOG_CSS + '\n' + PATH_CSS
2031
+
2032
+ /* ------------------------------------------------------------------ */
2033
+ /* Plugin */
2034
+ /* ------------------------------------------------------------------ */
2035
+
2036
+ return {
2037
+ inject: ['slots', 'locale', 'workspaces', 'sessions', 'uiWorkspace'],
2038
+ apply(ctx) {
2039
+ ctx.effect(
2040
+ () => ctx.locale.register(NS, { en: DICTIONARIES.en, zh: DICTIONARIES.zh }),
2041
+ 'lmw: locale dictionaries',
2042
+ )
2043
+ const t = ctx.locale.bind(NS)
2044
+ const refreshSessionList = typeof ctx.sessions?.refresh === 'function'
2045
+ ? () => ctx.sessions.refresh()
2046
+ : undefined
2047
+ const store = createStore({ refreshSessions: refreshSessionList })
2048
+ ctx.effect(() => () => store.dispose(), 'lmw: title refresh timers')
2049
+ const importStore = createImportStore({
2050
+ refreshAssignment: () => {
2051
+ void store.refresh()
2052
+ },
2053
+ refreshSessions: refreshSessionList,
2054
+ })
2055
+ const sortStore = createSortStore()
2056
+ // Re-apply the remembered arrangement at startup and after a page reload.
2057
+ void sortStore.autoApply()
2058
+
2059
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
2060
+ name: 'sidebar.footer.action',
2061
+ id: 'lmw-footer',
2062
+ order: 250,
2063
+ locale: NS,
2064
+ inject: () => ({ store, importStore, sortStore, translate: t }),
2065
+ }, FooterActionsPanel))
2066
+
2067
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2068
+ name: 'shell.overlay',
2069
+ id: 'lmw-session-assign-dialog',
2070
+ order: 600,
2071
+ locale: NS,
2072
+ inject: () => ({ store, workspaces: ctx.workspaces, translate: t }),
2073
+ }, AssignDialog))
2074
+
2075
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2076
+ name: 'shell.overlay',
2077
+ id: 'lmw-import-dialog',
2078
+ order: 610,
2079
+ locale: NS,
2080
+ inject: () => ({
2081
+ store: importStore,
2082
+ translate: t,
2083
+ pickDirectory: typeof ctx.uiWorkspace?.pickDirectory === 'function'
2084
+ ? () => ctx.uiWorkspace.pickDirectory()
2085
+ : undefined,
2086
+ }),
2087
+ }, ImportDialog))
2088
+
2089
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2090
+ name: 'shell.overlay',
2091
+ id: 'lmw-sort-dialog',
2092
+ order: 620,
2093
+ locale: NS,
2094
+ inject: () => ({ store: sortStore, translate: t }),
2095
+ }, SortDialog))
2096
+
2097
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2098
+ name: 'shell.overlay',
2099
+ id: 'lmw-workspace-offline',
2100
+ order: 920,
2101
+ locale: NS,
2102
+ inject: () => ({ workspaces: ctx.workspaces, translate: t }),
2103
+ }, WorkspaceOfflineGuard))
2104
+
2105
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2106
+ name: 'shell.overlay',
2107
+ id: 'lmw-workspace-path',
2108
+ order: 900,
2109
+ inject: () => ({ workspaces: ctx.workspaces }),
2110
+ }, WorkspacePathDecorator))
2111
+
2112
+ store.boot().catch((error) => {
2113
+ console.error('[lmw-plugin] startup scan failed:', error)
2114
+ })
2115
+ },
2116
+ }
2117
+ },
2118
+ })