dsh-lmw-plugin 0.0.0-stage → 1.0.2

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,1806 @@
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
+ },
137
+ zh: {
138
+ 'footer.label': '会话分配检查',
139
+ 'footer.aria': '检查会话分配',
140
+ 'dialog.title': 'LMW-DSH基础功能',
141
+ 'dialog.description': '本插件包含两项基础功能:会话分配——按会话目录列出未分配工作区的会话,勾选后创建或复用工作区并挂载会话;Skill 目录——检查默认 Skill 目录,缺失时可一并创建。勾选后点「确认执行」一次完成。',
142
+ 'dialog.titleAssign': '会话分配',
143
+ 'dialog.descriptionAssign': '仅运行会话分配功能:按会话目录列出未分配工作区的会话,勾选后创建或复用工作区并挂载会话。',
144
+ 'dialog.loading': '正在读取会话…',
145
+ 'dialog.error': '读取失败:{message}',
146
+ 'dialog.refreshFailed': '刷新失败,显示的是上次结果:{message}',
147
+ 'dialog.retry': '重试',
148
+ 'dialog.close': '关闭',
149
+ 'toolbar.all': '全选',
150
+ 'toolbar.none': '全不选',
151
+ 'panel.sessions': '会话分配',
152
+ 'panel.sessionsMeta': '{sessions} 个会话 / {dirs} 个目录',
153
+ 'panel.skill': 'Skill 目录',
154
+ 'empty': '没有未分配工作区的会话。',
155
+ 'group.aria': '选择目录 {path}',
156
+ 'group.count': '{n} 个会话',
157
+ 'group.missing': '目录不存在,无法分配',
158
+ 'session.aria': '选择会话 {title}',
159
+ 'session.untitled': '未命名会话',
160
+ 'session.archived': '已归档',
161
+ 'summary': '已选 {sessions} 个会话 / {dirs} 个目录',
162
+ 'action.cancel': '取消',
163
+ 'action.execute': '确认执行',
164
+ 'confirm.title': '确认执行',
165
+ 'confirm.text': '将分配 {sessions} 个会话({dirs} 个目录)。是否继续?',
166
+ 'confirm.textSkill': '将分配 {sessions} 个会话({dirs} 个目录),并创建 Skill 目录。是否继续?',
167
+ 'confirm.textSkillOnly': '将创建 Skill 目录。是否继续?',
168
+ 'confirm.textNothing': '没有勾选任何可执行项。',
169
+ 'confirm.go': '确认',
170
+ 'confirm.back': '取消',
171
+ 'executing': '正在执行…',
172
+ 'skill.exists': '已存在',
173
+ 'skill.create': '创建 Skill 目录',
174
+ 'skill.createAria': '勾选创建 Skill 目录 {path}',
175
+ 'result.title': '执行完成',
176
+ 'result.titlePartial': '执行完成,存在失败项',
177
+ 'result.summary': '成功分配 {assigned} 个会话,涉及 {workspaces} 个工作区。',
178
+ 'result.created': '新建',
179
+ 'result.reused': '复用',
180
+ 'result.skipped': '{n} 个会话原本已分配,已跳过。',
181
+ 'result.failed': '{n} 个会话未能分配:',
182
+ 'result.skillCreated': 'Skill 目录已创建:{path}',
183
+ 'result.skillExists': 'Skill 目录已存在:{path}',
184
+ 'result.skillFailed': 'Skill 目录创建失败:{message}',
185
+ 'result.assignmentFailed': '会话分配请求失败:{message}',
186
+ 'result.rescan': '重新扫描',
187
+ 'result.close': '关闭',
188
+ 'unassignable': '另有 {n} 个会话无法分配(无 cwd 或旧格式日志)。',
189
+ 'unassignableEmpty': '另有 {n} 个空会话(尚无对话内容)未列出。',
190
+ 'reload.action': '重新加载页面',
191
+ 'import.footer': '导入会话',
192
+ 'import.footerAria': '从目录导入会话',
193
+ 'import.title': '导入会话',
194
+ 'import.subtitle': '把其它目录中的 DSH 会话文件复制到本机默认会话目录:相同会话直接替换,新会话自动分配工作区。',
195
+ 'import.pathLabel': '会话目录',
196
+ 'import.pathPlaceholder': '例如 X:\\AI\\_Agent\\DSH\\session-pi',
197
+ 'import.browse': '浏览…',
198
+ 'import.scan': '识别',
199
+ 'import.scanning': '识别中…',
200
+ 'import.empty': '填写目录后点击「识别」。',
201
+ 'import.summary': '新增 {added} / 可替换 {replace} / 跳过 {skipped} / 阻止 {blocked}',
202
+ 'import.status.new': '新增',
203
+ 'import.status.replace': '替换',
204
+ 'import.status.unchanged': '不变',
205
+ 'import.status.live': '使用中',
206
+ 'import.status.conflict': '冲突',
207
+ 'import.status.invalid': '无效',
208
+ 'import.status.duplicate': '重复',
209
+ 'import.status.empty': '空会话',
210
+ 'import.warning.largerOnly': '文件更大,但修改时间不更新',
211
+ 'import.warning.newerOnly': '修改时间更新,但文件更小',
212
+ 'import.entry.source': '目录副本:{size} · {time}',
213
+ 'import.entry.existing': '现有:{size} · {time}',
214
+ 'import.selected': '已选 {sessions} 个会话',
215
+ 'import.action': '添加所选',
216
+ 'import.confirm.title': '确认添加',
217
+ 'import.confirm.text': '将添加 {added} 个新会话、替换 {replaced} 个相同会话,并为新会话自动分配工作区。是否继续?',
218
+ 'import.confirm.go': '确认添加',
219
+ 'import.confirm.back': '取消',
220
+ 'import.applying': '正在添加…',
221
+ 'import.result.title': '添加完成',
222
+ 'import.result.summary': '新增 {added} 个,替换 {replaced} 个,失败 {failed} 个,跳过 {skipped} 个。',
223
+ 'import.result.added': '新增',
224
+ 'import.result.replaced': '替换',
225
+ 'import.result.failed': '失败',
226
+ 'import.result.skipped': '跳过',
227
+ 'import.result.rescan': '重新识别',
228
+ 'import.result.close': '关闭',
229
+ 'import.error.noPath': '请填写目录',
230
+ 'import.error.scan': '识别失败:{message}',
231
+ 'import.error.apply': '添加失败:{message}',
232
+ 'import.note.subagent': '已跳过 {n} 个子代理会话',
233
+ 'import.note.large': '已跳过 {n} 个过大的文件',
234
+ 'import.blocked.title': '不可添加的会话({n})',
235
+ 'import.none': '没有可添加的会话。',
236
+ 'import.count': '{n} 个会话',
237
+ },
238
+ }
239
+
240
+ /** Fallback translate that never throws and always returns a string. */
241
+ function makeT(t) {
242
+ return (key, params) => {
243
+ if (typeof t !== 'function') return key
244
+ try {
245
+ return t(key, params)
246
+ } catch {
247
+ return key
248
+ }
249
+ }
250
+ }
251
+
252
+ function messageOf(error) {
253
+ return error instanceof Error ? error.message : String(error)
254
+ }
255
+
256
+ /* ------------------------------------------------------------------ */
257
+ /* Host transport */
258
+ /* ------------------------------------------------------------------ */
259
+
260
+ async function requestJson(method, path, body) {
261
+ const init = { method, credentials: 'same-origin' }
262
+ if (body !== undefined) {
263
+ init.headers = { 'content-type': 'application/json' }
264
+ init.body = JSON.stringify(body)
265
+ }
266
+ const response = await fetch(`${ROUTE}/${path}`, init)
267
+ const text = await response.text()
268
+ let payload = null
269
+ if (text.trim().length > 0) {
270
+ try {
271
+ payload = JSON.parse(text)
272
+ } catch {
273
+ payload = null
274
+ }
275
+ }
276
+ if (!response.ok) {
277
+ throw new Error(payload?.error?.message ?? `HTTP ${response.status}`)
278
+ }
279
+ return payload
280
+ }
281
+
282
+ /* ------------------------------------------------------------------ */
283
+ /* Store */
284
+ /* ------------------------------------------------------------------ */
285
+
286
+ function createStore(options = {}) {
287
+ const refreshSessions = typeof options.refreshSessions === 'function' ? options.refreshSessions : undefined
288
+ let snapshot = {
289
+ data: null,
290
+ error: null,
291
+ dialogOpen: false,
292
+ mode: 'assign',
293
+ executing: false,
294
+ result: null,
295
+ }
296
+ const listeners = new Set()
297
+ const publish = (patch) => {
298
+ snapshot = { ...snapshot, ...patch }
299
+ for (const listener of [...listeners]) {
300
+ try {
301
+ listener()
302
+ } catch (error) {
303
+ console.error('[lmw-plugin] listener failed:', error)
304
+ }
305
+ }
306
+ }
307
+ let loading = null
308
+ let autoOpened = false
309
+ let titleTimers = null
310
+
311
+ // The Host warms missing title-cache rows after answering the scan; the
312
+ // sidebar's session list only re-reads titles on a pull, so pull it a few
313
+ // times while the background warm settles.
314
+ const scheduleTitleRefresh = (pending) => {
315
+ if (pending <= 0 || refreshSessions === undefined || titleTimers !== null) return
316
+ const delays = [1500, 5000, 12000, 25000]
317
+ titleTimers = delays.map((delay, index) => window.setTimeout(() => {
318
+ void refreshSessions().catch((error) => {
319
+ console.error('[lmw-plugin] session list refresh failed:', error)
320
+ })
321
+ if (index === delays.length - 1) titleTimers = null
322
+ }, delay))
323
+ }
324
+
325
+ const refresh = async () => {
326
+ if (loading !== null) return loading
327
+ loading = (async () => {
328
+ if (snapshot.data === null) publish({ error: null })
329
+ try {
330
+ const data = await requestJson('GET', 'state')
331
+ publish({ data, error: null })
332
+ scheduleTitleRefresh(data?.titleWarm?.pending ?? 0)
333
+ return data
334
+ } catch (error) {
335
+ publish({ error: messageOf(error) })
336
+ return null
337
+ } finally {
338
+ loading = null
339
+ }
340
+ })()
341
+ return loading
342
+ }
343
+
344
+ const boot = async () => {
345
+ const data = await refresh()
346
+ if (data === null || autoOpened) return
347
+ const unassigned = data.counts?.unassignedSessions ?? 0
348
+ const skillMissing = data.skillDir?.exists === false
349
+ if (data.config?.autoOpenOnStartup !== false && (unassigned > 0 || skillMissing)) {
350
+ autoOpened = true
351
+ publish({ dialogOpen: true, mode: 'full', result: null })
352
+ }
353
+ }
354
+
355
+ const open = (mode = 'assign') => {
356
+ publish({ dialogOpen: true, mode, result: null })
357
+ void refresh()
358
+ }
359
+ const close = () => {
360
+ publish({ dialogOpen: false, result: null })
361
+ }
362
+ const toggle = () => {
363
+ if (snapshot.dialogOpen) close()
364
+ else open('assign')
365
+ }
366
+
367
+ const execute = async (request) => {
368
+ if (snapshot.executing) return snapshot.result
369
+ publish({ executing: true, result: null })
370
+ const failures = []
371
+ let assignment = null
372
+ let skill = null
373
+ if (request.sessionIds.length > 0) {
374
+ try {
375
+ assignment = await requestJson('POST', 'assign', { sessionIds: request.sessionIds })
376
+ } catch (error) {
377
+ failures.push({ part: 'assignment', message: messageOf(error) })
378
+ }
379
+ }
380
+ if (request.createSkillDir) {
381
+ try {
382
+ skill = await requestJson('POST', 'skills', { action: 'create' })
383
+ } catch (error) {
384
+ failures.push({ part: 'skill', message: messageOf(error) })
385
+ }
386
+ }
387
+ const result = { assignment, skill, failures }
388
+ publish({ executing: false, result })
389
+ void refresh()
390
+ return result
391
+ }
392
+
393
+ const dispose = () => {
394
+ if (titleTimers === null) return
395
+ for (const timer of titleTimers) window.clearTimeout(timer)
396
+ titleTimers = null
397
+ }
398
+
399
+ return {
400
+ getSnapshot: () => snapshot,
401
+ subscribe: (listener) => {
402
+ listeners.add(listener)
403
+ return () => {
404
+ listeners.delete(listener)
405
+ }
406
+ },
407
+ boot,
408
+ open,
409
+ close,
410
+ toggle,
411
+ refresh,
412
+ execute,
413
+ dispose,
414
+ }
415
+ }
416
+
417
+ /* ------------------------------------------------------------------ */
418
+ /* Shared helpers */
419
+ /* ------------------------------------------------------------------ */
420
+
421
+ function formatBytes(bytes) {
422
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '—'
423
+ if (bytes < 1024) return `${bytes} B`
424
+ const units = ['KB', 'MB', 'GB', 'TB']
425
+ let value = bytes / 1024
426
+ let index = 0
427
+ while (value >= 1024 && index < units.length - 1) {
428
+ value /= 1024
429
+ index += 1
430
+ }
431
+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[index]}`
432
+ }
433
+
434
+ function formatTime(ms) {
435
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return '—'
436
+ try {
437
+ return new Date(ms).toLocaleString()
438
+ } catch {
439
+ return '—'
440
+ }
441
+ }
442
+
443
+ /** Expand the given Workspace groups if the sidebar renders them folded. */
444
+ function expandWorkspaceRows(workspaceIds) {
445
+ const ids = (workspaceIds ?? []).map((id) => String(id)).filter((id) => id.length > 0)
446
+ if (ids.length === 0) return undefined
447
+ const expand = () => {
448
+ for (const id of ids) {
449
+ let row = null
450
+ try {
451
+ row = document.querySelector(`[data-row-key="workspace:${id}"]`)
452
+ } catch {
453
+ row = null
454
+ }
455
+ if (row instanceof HTMLElement && row.getAttribute('aria-expanded') === 'false') row.click()
456
+ }
457
+ }
458
+ const timers = [window.setTimeout(expand, 300), window.setTimeout(expand, 1200)]
459
+ return () => {
460
+ for (const timer of timers) window.clearTimeout(timer)
461
+ }
462
+ }
463
+
464
+ /* ------------------------------------------------------------------ */
465
+ /* Import store */
466
+ /* ------------------------------------------------------------------ */
467
+
468
+ function createImportStore(options = {}) {
469
+ const refreshSessions = typeof options.refreshSessions === 'function' ? options.refreshSessions : undefined
470
+ let snapshot = {
471
+ dialogOpen: false,
472
+ path: '',
473
+ scanning: false,
474
+ scan: null,
475
+ error: null,
476
+ applying: false,
477
+ result: null,
478
+ applyError: null,
479
+ }
480
+ const listeners = new Set()
481
+ const publish = (patch) => {
482
+ snapshot = { ...snapshot, ...patch }
483
+ for (const listener of [...listeners]) {
484
+ try {
485
+ listener()
486
+ } catch (error) {
487
+ console.error('[lmw-plugin] import listener failed:', error)
488
+ }
489
+ }
490
+ }
491
+
492
+ const open = () => publish({ dialogOpen: true })
493
+ const close = () => publish({ dialogOpen: false, result: null, applyError: null, error: null })
494
+ const toggle = () => {
495
+ if (snapshot.dialogOpen) close()
496
+ else open()
497
+ }
498
+ const setPath = (path) => publish({ path })
499
+ const reset = () => publish({ scan: null, result: null, error: null, applyError: null })
500
+
501
+ const scanNow = async () => {
502
+ const path = snapshot.path.trim()
503
+ if (path.length === 0) {
504
+ publish({ error: 'no-path' })
505
+ return null
506
+ }
507
+ publish({ scanning: true, error: null, scan: null, result: null, applyError: null })
508
+ try {
509
+ const data = await requestJson('POST', 'import/scan', { path })
510
+ publish({ scanning: false, scan: data })
511
+ return data
512
+ } catch (error) {
513
+ publish({ scanning: false, error: messageOf(error) })
514
+ return null
515
+ }
516
+ }
517
+
518
+ const apply = async (sessionIds) => {
519
+ if (snapshot.applying) return null
520
+ if (sessionIds.length === 0) return null
521
+ publish({ applying: true, result: null, applyError: null })
522
+ try {
523
+ const data = await requestJson('POST', 'import/apply', { path: snapshot.path.trim(), sessionIds })
524
+ publish({ applying: false, result: data })
525
+ const workspaceIds = (data?.results ?? [])
526
+ .map((entry) => entry?.workspace?.workspaceId)
527
+ .filter((id) => typeof id === 'string' && id.length > 0)
528
+ expandWorkspaceRows(workspaceIds)
529
+ if (typeof options.refreshAssignment === 'function') {
530
+ try {
531
+ options.refreshAssignment()
532
+ } catch (error) {
533
+ console.error('[lmw-plugin] refreshing the assignment scan failed:', error)
534
+ }
535
+ }
536
+ if (refreshSessions !== undefined) {
537
+ for (const delay of [1200, 4000]) {
538
+ window.setTimeout(() => {
539
+ void refreshSessions().catch((error) => {
540
+ console.error('[lmw-plugin] session list refresh failed:', error)
541
+ })
542
+ }, delay)
543
+ }
544
+ }
545
+ return data
546
+ } catch (error) {
547
+ publish({ applying: false, applyError: messageOf(error) })
548
+ return null
549
+ }
550
+ }
551
+
552
+ return {
553
+ getSnapshot: () => snapshot,
554
+ subscribe: (listener) => {
555
+ listeners.add(listener)
556
+ return () => {
557
+ listeners.delete(listener)
558
+ }
559
+ },
560
+ open,
561
+ close,
562
+ toggle,
563
+ setPath,
564
+ reset,
565
+ scanNow,
566
+ apply,
567
+ }
568
+ }
569
+
570
+ /* ------------------------------------------------------------------ */
571
+ /* Shared UI atoms */
572
+ /* ------------------------------------------------------------------ */
573
+
574
+ const GLYPH = h(
575
+ 'svg',
576
+ { width: 16, height: 16, viewBox: '0 0 36 36', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
577
+ h('path', {
578
+ 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',
579
+ fill: 'currentColor',
580
+ opacity: 0.9,
581
+ }),
582
+ h('path', { d: 'M17.25 14.2v7.2', stroke: 'var(--dsw-alias-bg-base)', 'stroke-width': 2.4, 'stroke-linecap': 'round' }),
583
+ 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' }),
584
+ )
585
+
586
+ const CHECK_GLYPH = h(
587
+ 'svg',
588
+ { width: 14, height: 14, viewBox: '0 0 14 14', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
589
+ h('circle', { cx: 7, cy: 7, r: 6.3, stroke: 'currentColor', 'stroke-width': 1.3 }),
590
+ h('path', {
591
+ d: 'M4.1 7.2l2 2 3.8-4',
592
+ stroke: 'currentColor',
593
+ 'stroke-width': 1.6,
594
+ 'stroke-linecap': 'round',
595
+ 'stroke-linejoin': 'round',
596
+ }),
597
+ )
598
+
599
+ function Checkbox({ checked, indeterminate, disabled, onChange, label }) {
600
+ const ref = useRef(null)
601
+ useEffect(() => {
602
+ if (ref.current !== null) ref.current.indeterminate = indeterminate === true
603
+ }, [indeterminate])
604
+ return h('input', {
605
+ ref,
606
+ type: 'checkbox',
607
+ className: 'lmw-check',
608
+ checked: checked === true,
609
+ disabled: disabled === true,
610
+ 'aria-label': label,
611
+ onChange: () => onChange(),
612
+ })
613
+ }
614
+
615
+ function shortId(id) {
616
+ const text = String(id)
617
+ return text.length > 15 ? `${text.slice(0, 12)}…` : text
618
+ }
619
+
620
+ /* ------------------------------------------------------------------ */
621
+ /* Assignment dialog */
622
+ /* ------------------------------------------------------------------ */
623
+
624
+ function AssignDialog(props) {
625
+ const { store, workspaces } = props
626
+ const tr = makeT(props.translate ?? props.t)
627
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
628
+ const dialogRef = useRef(null)
629
+ const [selected, setSelected] = useState(() => new Set())
630
+ const [createSkill, setCreateSkill] = useState(false)
631
+ const [confirming, setConfirming] = useState(false)
632
+
633
+ const open = snapshot.dialogOpen
634
+ const data = snapshot.data
635
+ const groups = data?.groups ?? []
636
+ const result = snapshot.result
637
+ const showSkill = snapshot.mode === 'full'
638
+ const skillDir = data?.skillDir
639
+ const skillExists = skillDir?.exists === true
640
+
641
+ const subscribeWorkspaces = useCallback((listener) => workspaces.list.subscribe(listener), [workspaces])
642
+ const readWorkspaces = useCallback(() => workspaces.list.getSnapshot(), [workspaces])
643
+ const workspaceSnapshot = useSyncExternalStore(subscribeWorkspaces, readWorkspaces)
644
+ const archived = useMemo(
645
+ () => new Set((workspaceSnapshot.archivedSessionIds ?? []).map((id) => String(id))),
646
+ [workspaceSnapshot.archivedSessionIds],
647
+ )
648
+
649
+ const assignableIds = useMemo(() => {
650
+ const ids = []
651
+ for (const group of groups) {
652
+ if (group.exists === false) continue
653
+ for (const session of group.sessions) ids.push(session.id)
654
+ }
655
+ return ids
656
+ }, [groups])
657
+
658
+ useEffect(() => {
659
+ if (!open) return
660
+ setSelected(new Set(assignableIds))
661
+ setCreateSkill(showSkill && data?.skillDir?.exists === false)
662
+ setConfirming(false)
663
+ }, [open, data?.generatedAt, showSkill])
664
+
665
+ useEffect(() => {
666
+ if (!open) return undefined
667
+ const timer = window.setTimeout(() => {
668
+ dialogRef.current?.querySelector('[data-lmw-autofocus]')?.focus()
669
+ }, 40)
670
+ return () => {
671
+ window.clearTimeout(timer)
672
+ try {
673
+ document.querySelector('[data-lmw-foot-button]')?.focus()
674
+ } catch {
675
+ // A detached trigger is not worth reporting.
676
+ }
677
+ }
678
+ }, [open])
679
+
680
+ useEffect(() => {
681
+ if (!open) return undefined
682
+ const onKeyDown = (event) => {
683
+ if (event.key !== 'Escape') return
684
+ event.stopPropagation()
685
+ if (confirming) setConfirming(false)
686
+ else store.close()
687
+ }
688
+ document.addEventListener('keydown', onKeyDown, true)
689
+ return () => {
690
+ document.removeEventListener('keydown', onKeyDown, true)
691
+ }
692
+ }, [open, confirming, store])
693
+
694
+ useEffect(() => {
695
+ if (!open || !confirming) return undefined
696
+ const timer = window.setTimeout(() => {
697
+ dialogRef.current?.querySelector('[data-lmw-confirm-go]')?.focus()
698
+ }, 30)
699
+ return () => {
700
+ window.clearTimeout(timer)
701
+ }
702
+ }, [open, confirming])
703
+
704
+ // While the confirm layer is up, the dialog content behind it must not
705
+ // take focus or clicks (inert also hides it from assistive technology).
706
+ useEffect(() => {
707
+ if (!open || !confirming) return undefined
708
+ const root = dialogRef.current
709
+ if (root === null) return undefined
710
+ const parts = [...root.querySelectorAll(':scope > .lmw-header, :scope > .lmw-body, :scope > .lmw-footbar')]
711
+ for (const part of parts) part.setAttribute('inert', '')
712
+ return () => {
713
+ for (const part of parts) part.removeAttribute('inert')
714
+ }
715
+ }, [open, confirming])
716
+
717
+ // DSH renders every Workspace group folded unless it was expanded
718
+ // before, so a freshly assigned Workspace would show its name with no
719
+ // visible sessions. Expand the groups this run touched so the result is
720
+ // visible immediately; the user can fold them again as usual.
721
+ useEffect(() => {
722
+ if (result === null) return undefined
723
+ return expandWorkspaceRows((result.assignment?.workspaces ?? []).map((workspace) => workspace.workspaceId))
724
+ }, [result])
725
+
726
+ const toggleSession = (id) => {
727
+ setSelected((current) => {
728
+ const next = new Set(current)
729
+ if (next.has(id)) next.delete(id)
730
+ else next.add(id)
731
+ return next
732
+ })
733
+ }
734
+
735
+ const toggleGroup = (group) => {
736
+ setSelected((current) => {
737
+ const next = new Set(current)
738
+ const ids = group.sessions.map((session) => session.id)
739
+ const all = ids.length > 0 && ids.every((id) => next.has(id))
740
+ for (const id of ids) {
741
+ if (all) next.delete(id)
742
+ else next.add(id)
743
+ }
744
+ return next
745
+ })
746
+ }
747
+
748
+ const selectedCount = selected.size
749
+ const selectedDirs = groups.filter(
750
+ (group) => group.exists !== false && group.sessions.some((session) => selected.has(session.id)),
751
+ ).length
752
+ const skillWillCreate = showSkill && !skillExists && createSkill
753
+ const actionable = selectedCount > 0 || skillWillCreate
754
+
755
+ const runExecute = async () => {
756
+ if (snapshot.executing || !actionable) return
757
+ setConfirming(false)
758
+ await store.execute({
759
+ sessionIds: [...selected],
760
+ createSkillDir: skillWillCreate,
761
+ })
762
+ }
763
+
764
+ if (!open) return null
765
+
766
+ const subtitle = () => tr(showSkill ? 'dialog.description' : 'dialog.descriptionAssign')
767
+
768
+ const header = h(
769
+ 'header',
770
+ { className: 'lmw-header' },
771
+ h(
772
+ 'div',
773
+ { className: 'lmw-header-text' },
774
+ h('div', { className: 'lmw-title' }, tr(showSkill ? 'dialog.title' : 'dialog.titleAssign')),
775
+ h('div', { className: 'lmw-subtitle' }, subtitle()),
776
+ ),
777
+ h(
778
+ 'button',
779
+ {
780
+ type: 'button',
781
+ className: 'lmw-close',
782
+ 'aria-label': tr('dialog.close'),
783
+ 'data-lmw-autofocus': '',
784
+ onClick: () => store.close(),
785
+ },
786
+ h('svg', { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': 'true' },
787
+ h('path', { d: 'M3 3l8 8M11 3l-8 8', stroke: 'currentColor', 'stroke-width': 1.6, 'stroke-linecap': 'round' })),
788
+ ),
789
+ )
790
+
791
+ const renderGroup = (group) => {
792
+ const ids = group.sessions.map((session) => session.id)
793
+ const chosen = ids.filter((id) => selected.has(id)).length
794
+ const all = ids.length > 0 && chosen === ids.length
795
+ const some = chosen > 0 && !all
796
+ const missing = group.exists === false
797
+ return h(
798
+ 'section',
799
+ { className: 'lmw-group', 'data-missing': missing ? '1' : undefined, key: group.cwd },
800
+ h(
801
+ 'label',
802
+ { className: 'lmw-group-head' },
803
+ h(Checkbox, {
804
+ checked: all,
805
+ indeterminate: some,
806
+ disabled: missing || snapshot.executing === true,
807
+ label: tr('group.aria', { path: group.cwd }),
808
+ onChange: () => toggleGroup(group),
809
+ }),
810
+ h('span', { className: 'lmw-group-path' }, group.cwd),
811
+ missing
812
+ ? h('span', { className: 'lmw-badge lmw-badge-warn' }, tr('group.missing'))
813
+ : h('span', { className: 'lmw-count' }, tr('group.count', { n: group.sessions.length })),
814
+ ),
815
+ h(
816
+ 'ul',
817
+ { className: 'lmw-sessions' },
818
+ group.sessions.map((session) => {
819
+ const isArchived = archived.has(session.id)
820
+ const title = session.title.length > 0 ? session.title : tr('session.untitled')
821
+ return h(
822
+ 'li',
823
+ { className: 'lmw-session', key: session.id },
824
+ h(
825
+ 'label',
826
+ { className: 'lmw-session-label' },
827
+ h(Checkbox, {
828
+ checked: selected.has(session.id),
829
+ disabled: missing || snapshot.executing === true,
830
+ label: tr('session.aria', { title }),
831
+ onChange: () => toggleSession(session.id),
832
+ }),
833
+ h('span', { className: 'lmw-session-title' }, title),
834
+ isArchived ? h('span', { className: 'lmw-badge' }, tr('session.archived')) : null,
835
+ h('span', { className: 'lmw-session-id' }, shortId(session.id)),
836
+ ),
837
+ )
838
+ }),
839
+ ),
840
+ )
841
+ }
842
+
843
+ const renderSkillPanel = () => {
844
+ if (!showSkill || !skillDir) return null
845
+ return h(
846
+ 'section',
847
+ { className: 'lmw-panel' },
848
+ h('div', { className: 'lmw-panel-head' },
849
+ h('span', { className: 'lmw-panel-title' }, tr('panel.skill'))),
850
+ skillExists
851
+ ? h('div', { className: 'lmw-skill-line' },
852
+ h('code', { className: 'lmw-path' }, skillDir.path),
853
+ h('span', { className: 'lmw-skill-state' }, tr('skill.exists')),
854
+ h('span', {
855
+ className: 'lmw-check-ok',
856
+ role: 'img',
857
+ 'aria-label': tr('skill.exists'),
858
+ }, CHECK_GLYPH))
859
+ : h('label', { className: 'lmw-skill-line lmw-skill-check' },
860
+ h(Checkbox, {
861
+ checked: createSkill,
862
+ disabled: snapshot.executing === true,
863
+ label: tr('skill.createAria', { path: skillDir.path }),
864
+ onChange: () => setCreateSkill((value) => !value),
865
+ }),
866
+ h('span', { className: 'lmw-skill-label' }, tr('skill.create')),
867
+ h('code', { className: 'lmw-path' }, skillDir.path)),
868
+ )
869
+ }
870
+
871
+ const renderResult = () => {
872
+ const assignment = result.assignment
873
+ const failed = assignment && Array.isArray(assignment.failed) ? assignment.failed : []
874
+ const skipped = assignment && Array.isArray(assignment.skipped) ? assignment.skipped : []
875
+ const workspacesTouched = assignment && Array.isArray(assignment.workspaces) ? assignment.workspaces : []
876
+ const skill = result.skill
877
+ const failures = Array.isArray(result.failures) ? result.failures : []
878
+ const hasFailure = failures.length > 0 || failed.length > 0
879
+ const items = []
880
+ if (assignment !== null) {
881
+ items.push(h('p', { className: 'lmw-result-text', key: 'summary' },
882
+ tr('result.summary', { assigned: assignment.assigned ?? 0, workspaces: workspacesTouched.length })))
883
+ if (workspacesTouched.length > 0) {
884
+ items.push(h('ul', { className: 'lmw-list', key: 'workspaces' },
885
+ workspacesTouched.map((workspace) => h('li', { key: workspace.workspaceId },
886
+ `${workspace.created ? tr('result.created') : tr('result.reused')} · ${workspace.path}`))))
887
+ }
888
+ if (skipped.length > 0) {
889
+ items.push(h('p', { className: 'lmw-result-text', key: 'skipped' }, tr('result.skipped', { n: skipped.length })))
890
+ }
891
+ if (failed.length > 0) {
892
+ items.push(h('div', { className: 'lmw-result-fail', key: 'failed' },
893
+ h('p', { className: 'lmw-error' }, tr('result.failed', { n: failed.length })),
894
+ h('ul', { className: 'lmw-list' }, failed.slice(0, 12).map((item, index) =>
895
+ h('li', { key: `${item.sessionId}:${index}` }, `${shortId(item.sessionId)} — ${item.code}: ${item.message}`)))))
896
+ }
897
+ }
898
+ if (skill !== null) {
899
+ items.push(h('p', {
900
+ className: skill.created ? 'lmw-result-text lmw-ok' : 'lmw-result-text',
901
+ key: 'skill',
902
+ }, tr(skill.created ? 'result.skillCreated' : 'result.skillExists', { path: skill.path })))
903
+ }
904
+ for (const failure of failures) {
905
+ items.push(h('p', { className: 'lmw-error', key: `failure:${failure.part}` },
906
+ tr(failure.part === 'skill' ? 'result.skillFailed' : 'result.assignmentFailed', { message: failure.message })))
907
+ }
908
+ return h(
909
+ 'div',
910
+ { className: 'lmw-result' },
911
+ h('div', { className: hasFailure ? 'lmw-result-title lmw-warn' : 'lmw-result-title lmw-ok' },
912
+ tr(hasFailure ? 'result.titlePartial' : 'result.title')),
913
+ ...items,
914
+ h('div', { className: 'lmw-result-actions' },
915
+ h('button', {
916
+ type: 'button',
917
+ className: 'lmw-button',
918
+ onClick: () => {
919
+ store.close()
920
+ store.open(snapshot.mode)
921
+ },
922
+ }, tr('result.rescan')),
923
+ h('button', { type: 'button', className: 'lmw-button lmw-primary', onClick: () => store.close() }, tr('result.close'))),
924
+ )
925
+ }
926
+
927
+ const body = () => {
928
+ if (result !== null) return renderResult()
929
+ if (snapshot.error !== null && data === null) {
930
+ return h('div', { className: 'lmw-state' },
931
+ h('p', { className: 'lmw-error' }, tr('dialog.error', { message: snapshot.error })),
932
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => { void store.refresh() } }, tr('dialog.retry')))
933
+ }
934
+ if (data === null) {
935
+ return h('div', { className: 'lmw-state' }, h('p', { className: 'lmw-note' }, tr('dialog.loading')))
936
+ }
937
+ const staleError = snapshot.error !== null && snapshot.error !== undefined
938
+ ? h('p', { className: 'lmw-error' }, tr('dialog.refreshFailed', { message: snapshot.error }))
939
+ : null
940
+ const extra = (data.unassignable?.noCwd ?? 0) + (data.unassignable?.legacyFormat ?? 0)
941
+ const extraNote = extra > 0 ? h('p', { className: 'lmw-note' }, tr('unassignable', { n: extra })) : null
942
+ const emptyCount = data.unassignable?.empty ?? 0
943
+ const emptyNote = emptyCount > 0
944
+ ? h('p', { className: 'lmw-note' }, tr('unassignableEmpty', { n: emptyCount }))
945
+ : null
946
+ const sessionsPanel = h('section', { className: 'lmw-panel' },
947
+ h('div', { className: 'lmw-panel-head' },
948
+ h('span', { className: 'lmw-panel-title' }, tr('panel.sessions')),
949
+ h('span', { className: 'lmw-panel-meta' },
950
+ tr('panel.sessionsMeta', {
951
+ sessions: groups.reduce((total, group) => total + group.sessions.length, 0),
952
+ dirs: groups.length,
953
+ }))),
954
+ groups.length === 0
955
+ ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('empty'))
956
+ : h('div', null,
957
+ h('div', { className: 'lmw-toolbar' },
958
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set(assignableIds)) }, tr('toolbar.all')),
959
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set()) }, tr('toolbar.none'))),
960
+ h('div', { className: 'lmw-groups' }, groups.map(renderGroup))),
961
+ extraNote,
962
+ emptyNote)
963
+ return h('div', { className: 'lmw-panels' },
964
+ staleError,
965
+ sessionsPanel,
966
+ renderSkillPanel())
967
+ }
968
+
969
+ const executeText = () => {
970
+ if (selectedCount === 0 && !skillWillCreate) return tr('confirm.textNothing')
971
+ if (selectedCount === 0) return tr('confirm.textSkillOnly')
972
+ if (skillWillCreate) return tr('confirm.textSkill', { sessions: selectedCount, dirs: selectedDirs })
973
+ return tr('confirm.text', { sessions: selectedCount, dirs: selectedDirs })
974
+ }
975
+
976
+ const footer = () => {
977
+ if (result !== null) return null
978
+ return h('div', { className: 'lmw-footbar' },
979
+ h('span', { className: 'lmw-summary' },
980
+ actionable ? tr('summary', { sessions: selectedCount, dirs: selectedDirs }) : tr('confirm.textNothing')),
981
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => store.close() }, tr('action.cancel')),
982
+ h('button', {
983
+ type: 'button',
984
+ className: 'lmw-button lmw-primary',
985
+ disabled: snapshot.executing === true || !actionable,
986
+ onClick: () => setConfirming(true),
987
+ }, snapshot.executing ? tr('executing') : tr('action.execute')))
988
+ }
989
+
990
+ const confirmLayer = confirming
991
+ ? h('div', { className: 'lmw-confirm-layer' },
992
+ h('div', {
993
+ className: 'lmw-confirm-card',
994
+ role: 'alertdialog',
995
+ 'aria-modal': 'true',
996
+ 'aria-label': tr('confirm.title'),
997
+ },
998
+ h('div', { className: 'lmw-confirm-title' }, tr('confirm.title')),
999
+ h('p', { className: 'lmw-confirm-text' }, executeText()),
1000
+ h('div', { className: 'lmw-confirm-actions' },
1001
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => setConfirming(false) }, tr('confirm.back')),
1002
+ h('button', {
1003
+ type: 'button',
1004
+ className: 'lmw-button lmw-primary',
1005
+ 'data-lmw-confirm-go': '',
1006
+ disabled: !actionable,
1007
+ onClick: () => { void runExecute() },
1008
+ }, tr('confirm.go')))))
1009
+ : null
1010
+
1011
+ return h('div', {
1012
+ className: 'lmw-backdrop',
1013
+ onMouseDown: (event) => {
1014
+ if (event.target === event.currentTarget) store.close()
1015
+ },
1016
+ },
1017
+ h('section', {
1018
+ ref: dialogRef,
1019
+ className: 'lmw-dialog',
1020
+ role: 'dialog',
1021
+ 'aria-modal': 'true',
1022
+ 'aria-label': tr(showSkill ? 'dialog.title' : 'dialog.titleAssign'),
1023
+ },
1024
+ header,
1025
+ h('div', { className: 'lmw-body' }, body()),
1026
+ footer(),
1027
+ confirmLayer,
1028
+ ),
1029
+ )
1030
+ }
1031
+
1032
+ /* ------------------------------------------------------------------ */
1033
+ /* Sidebar reload and import actions */
1034
+ /* ------------------------------------------------------------------ */
1035
+
1036
+ const RELOAD_GLYPH = h(
1037
+ 'svg',
1038
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
1039
+ h('path', { d: 'M13 8a5 5 0 1 1-1.46-3.54', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round' }),
1040
+ h('path', { d: 'M13 3.55v3.2h-3.2', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }),
1041
+ )
1042
+
1043
+ const IMPORT_GLYPH = h(
1044
+ 'svg',
1045
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
1046
+ h('path', { d: 'M8 3v6.1', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round' }),
1047
+ 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' }),
1048
+ 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' }),
1049
+ )
1050
+
1051
+ function FootRow(props) {
1052
+ const { wide, glyph, label, aria, expanded, onClick, badge, badgeAlert } = props
1053
+ return h(
1054
+ 'div',
1055
+ { className: 'lmw-foot' },
1056
+ h(
1057
+ 'button',
1058
+ {
1059
+ type: 'button',
1060
+ className: 'lmw-foot-button',
1061
+ 'data-lmw-foot-button': '',
1062
+ 'data-wide': wide ? '1' : '0',
1063
+ 'aria-label': aria,
1064
+ 'aria-expanded': expanded === undefined ? undefined : (expanded ? 'true' : 'false'),
1065
+ title: aria,
1066
+ onClick,
1067
+ },
1068
+ h('span', { className: 'lmw-foot-glyph', 'aria-hidden': 'true' }, glyph),
1069
+ wide ? h('span', { className: 'lmw-foot-text' }, label) : null,
1070
+ badge !== undefined && badge.length > 0
1071
+ ? h('span', { className: 'lmw-foot-count', 'data-alert': badgeAlert === true ? '1' : undefined }, badge)
1072
+ : null,
1073
+ ),
1074
+ )
1075
+ }
1076
+
1077
+ /** One footer seat holding the three actions stacked, so labels stay readable. */
1078
+ function FooterActionsPanel(props) {
1079
+ const { wide, store, importStore } = props
1080
+ const tr = makeT(props.translate ?? props.t)
1081
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
1082
+ const importSnapshot = useSyncExternalStore(importStore.subscribe, importStore.getSnapshot)
1083
+ const count = snapshot.data?.counts?.unassignedSessions ?? 0
1084
+ return h(
1085
+ 'div',
1086
+ { className: 'lmw-foot-stack' },
1087
+ h(FootRow, {
1088
+ wide,
1089
+ glyph: RELOAD_GLYPH,
1090
+ label: tr('reload.action'),
1091
+ aria: tr('reload.action'),
1092
+ onClick: () => {
1093
+ try {
1094
+ window.location.reload()
1095
+ } catch {
1096
+ // A context that cannot reload simply stays as it is.
1097
+ }
1098
+ },
1099
+ }),
1100
+ h(FootRow, {
1101
+ wide,
1102
+ glyph: GLYPH,
1103
+ label: tr('footer.label'),
1104
+ aria: tr('footer.aria'),
1105
+ expanded: snapshot.dialogOpen === true,
1106
+ badge: count > 0 ? String(count) : '',
1107
+ onClick: () => store.toggle(),
1108
+ }),
1109
+ h(FootRow, {
1110
+ wide,
1111
+ glyph: IMPORT_GLYPH,
1112
+ label: tr('import.footer'),
1113
+ aria: tr('import.footerAria'),
1114
+ expanded: importSnapshot.dialogOpen === true,
1115
+ onClick: () => importStore.toggle(),
1116
+ }),
1117
+ )
1118
+ }
1119
+
1120
+ /* ------------------------------------------------------------------ */
1121
+ /* Import dialog */
1122
+ /* ------------------------------------------------------------------ */
1123
+
1124
+ function ImportDialog(props) {
1125
+ const { store, pickDirectory } = props
1126
+ const tr = makeT(props.translate ?? props.t)
1127
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
1128
+ const dialogRef = useRef(null)
1129
+ const [selected, setSelected] = useState(() => new Set())
1130
+ const [confirming, setConfirming] = useState(false)
1131
+ const [browsing, setBrowsing] = useState(false)
1132
+ const [showBlocked, setShowBlocked] = useState(false)
1133
+
1134
+ const open = snapshot.dialogOpen
1135
+ const scan = snapshot.scan
1136
+ const result = snapshot.result
1137
+ const entries = scan?.entries ?? []
1138
+ const addable = useMemo(
1139
+ () => entries.filter((entry) => entry.status === 'new' || entry.status === 'replace'),
1140
+ [entries],
1141
+ )
1142
+ const blockedEntries = useMemo(
1143
+ () => entries.filter((entry) => entry.status !== 'new' && entry.status !== 'replace'),
1144
+ [entries],
1145
+ )
1146
+ const addableIds = useMemo(() => addable.map((entry) => entry.id), [addable])
1147
+ const addableGroups = useMemo(() => {
1148
+ const map = new Map()
1149
+ for (const entry of addable) {
1150
+ const key = typeof entry.cwd === 'string' && entry.cwd.length > 0 ? entry.cwd : '—'
1151
+ let list = map.get(key)
1152
+ if (list === undefined) {
1153
+ list = []
1154
+ map.set(key, list)
1155
+ }
1156
+ list.push(entry)
1157
+ }
1158
+ return [...map.entries()]
1159
+ .map(([cwd, list]) => ({
1160
+ cwd,
1161
+ entries: list.sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0)),
1162
+ }))
1163
+ .sort((left, right) => left.cwd.localeCompare(right.cwd))
1164
+ }, [addable])
1165
+
1166
+ useEffect(() => {
1167
+ if (!open) return
1168
+ setSelected(new Set())
1169
+ setConfirming(false)
1170
+ setBrowsing(false)
1171
+ setShowBlocked(false)
1172
+ }, [open])
1173
+
1174
+ useEffect(() => {
1175
+ if (!open || scan === null) return
1176
+ setSelected(new Set(addableIds))
1177
+ setShowBlocked(false)
1178
+ }, [open, scan?.generatedAt])
1179
+
1180
+ useEffect(() => {
1181
+ if (!open) return undefined
1182
+ const timer = window.setTimeout(() => {
1183
+ dialogRef.current?.querySelector('[data-lmw-autofocus]')?.focus()
1184
+ }, 40)
1185
+ return () => {
1186
+ window.clearTimeout(timer)
1187
+ try {
1188
+ document.querySelector('[data-lmw-foot-button]')?.focus()
1189
+ } catch {
1190
+ // A detached trigger is not worth reporting.
1191
+ }
1192
+ }
1193
+ }, [open])
1194
+
1195
+ useEffect(() => {
1196
+ if (!open) return undefined
1197
+ const onKeyDown = (event) => {
1198
+ if (event.key !== 'Escape') return
1199
+ event.stopPropagation()
1200
+ if (confirming) setConfirming(false)
1201
+ else store.close()
1202
+ }
1203
+ document.addEventListener('keydown', onKeyDown, true)
1204
+ return () => {
1205
+ document.removeEventListener('keydown', onKeyDown, true)
1206
+ }
1207
+ }, [open, confirming, store])
1208
+
1209
+ useEffect(() => {
1210
+ if (!open || !confirming) return undefined
1211
+ const timer = window.setTimeout(() => {
1212
+ dialogRef.current?.querySelector('[data-lmw-confirm-go]')?.focus()
1213
+ }, 30)
1214
+ return () => {
1215
+ window.clearTimeout(timer)
1216
+ }
1217
+ }, [open, confirming])
1218
+
1219
+ const toggleEntry = (entry) => {
1220
+ if (entry.status !== 'new' && entry.status !== 'replace') return
1221
+ setSelected((current) => {
1222
+ const next = new Set(current)
1223
+ if (next.has(entry.id)) next.delete(entry.id)
1224
+ else next.add(entry.id)
1225
+ return next
1226
+ })
1227
+ }
1228
+
1229
+ const selectedEntries = addable.filter((entry) => selected.has(entry.id))
1230
+ const addedCount = selectedEntries.filter((entry) => entry.status === 'new').length
1231
+ const replacedCount = selectedEntries.filter((entry) => entry.status === 'replace').length
1232
+
1233
+ const runApply = async () => {
1234
+ if (snapshot.applying || selected.size === 0) return
1235
+ setConfirming(false)
1236
+ await store.apply([...selected])
1237
+ }
1238
+
1239
+ if (!open) return null
1240
+
1241
+ const statusBadge = (entry) => {
1242
+ const cls = entry.status === 'new'
1243
+ ? 'lmw-badge lmw-badge-new'
1244
+ : entry.status === 'replace'
1245
+ ? 'lmw-badge lmw-badge-replace'
1246
+ : entry.status === 'live' || entry.status === 'conflict'
1247
+ ? 'lmw-badge lmw-badge-block'
1248
+ : 'lmw-badge'
1249
+ return h('span', { className: cls }, tr(`import.status.${entry.status}`))
1250
+ }
1251
+
1252
+ const renderEntry = (entry) => {
1253
+ const checkable = entry.status === 'new' || entry.status === 'replace'
1254
+ return h(
1255
+ 'li',
1256
+ { className: 'lmw-entry', key: `${entry.id}:${entry.sourceFile}` },
1257
+ h(
1258
+ 'label',
1259
+ { className: 'lmw-entry-label' },
1260
+ h(Checkbox, {
1261
+ checked: checkable && selected.has(entry.id),
1262
+ disabled: !checkable || snapshot.applying === true,
1263
+ label: shortId(entry.id),
1264
+ onChange: () => toggleEntry(entry),
1265
+ }),
1266
+ h(
1267
+ 'div',
1268
+ { className: 'lmw-entry-main' },
1269
+ h('div', { className: 'lmw-entry-title' },
1270
+ h('span', { className: 'lmw-entry-id', title: entry.id }, shortId(entry.id)),
1271
+ ' ',
1272
+ statusBadge(entry)),
1273
+ h('div', { className: 'lmw-entry-meta' },
1274
+ tr('import.entry.source', {
1275
+ size: formatBytes(entry.sourceBytes),
1276
+ time: formatTime(entry.sourceMtime),
1277
+ })),
1278
+ checkable && entry.existingPath
1279
+ ? h('div', { className: 'lmw-entry-meta' },
1280
+ tr('import.entry.existing', {
1281
+ size: formatBytes(entry.existingBytes),
1282
+ time: formatTime(entry.existingMtime),
1283
+ }))
1284
+ : null,
1285
+ entry.warning !== null && entry.warning !== undefined
1286
+ ? h('div', { className: 'lmw-warn-text' },
1287
+ tr(entry.warning === 'larger-only' ? 'import.warning.largerOnly' : 'import.warning.newerOnly'))
1288
+ : null,
1289
+ !checkable && entry.reason !== undefined
1290
+ ? h('div', { className: 'lmw-entry-reason' }, entry.reason)
1291
+ : null,
1292
+ ),
1293
+ ),
1294
+ )
1295
+ }
1296
+
1297
+ const renderScanTop = () => {
1298
+ if (scan === null) return null
1299
+ const blocked = (scan.counts?.blocked ?? 0) + (scan.counts?.invalid ?? 0)
1300
+ return h(
1301
+ 'div',
1302
+ { className: 'lmw-import-top' },
1303
+ h('div', { className: 'lmw-import-summary' },
1304
+ tr('import.summary', {
1305
+ added: scan.counts?.new ?? 0,
1306
+ replace: scan.counts?.replace ?? 0,
1307
+ skipped: scan.counts?.unchanged ?? 0,
1308
+ blocked,
1309
+ })),
1310
+ (scan.counts?.skippedSubagent ?? 0) > 0
1311
+ ? h('p', { className: 'lmw-note lmw-note-flush' },
1312
+ tr('import.note.subagent', { n: scan.counts.skippedSubagent }))
1313
+ : null,
1314
+ (scan.counts?.skippedLarge ?? 0) > 0
1315
+ ? h('p', { className: 'lmw-note lmw-note-flush' },
1316
+ tr('import.note.large', { n: scan.counts.skippedLarge }))
1317
+ : null,
1318
+ h('div', { className: 'lmw-toolbar' },
1319
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set(addableIds)) }, tr('toolbar.all')),
1320
+ h('button', { type: 'button', className: 'lmw-link', onClick: () => setSelected(new Set()) }, tr('toolbar.none'))),
1321
+ )
1322
+ }
1323
+
1324
+ const renderScanLists = () => {
1325
+ if (scan === null) return null
1326
+ const blocked = blockedEntries.length
1327
+ return h(
1328
+ 'div',
1329
+ { className: 'lmw-import-scroll' },
1330
+ addableGroups.length === 0
1331
+ ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('import.none'))
1332
+ : addableGroups.map((group) => h(
1333
+ 'section',
1334
+ { className: 'lmw-group', key: group.cwd },
1335
+ h('div', { className: 'lmw-group-head' },
1336
+ h('span', { className: 'lmw-group-path' }, group.cwd),
1337
+ h('span', { className: 'lmw-count' }, tr('import.count', { n: group.entries.length }))),
1338
+ h('ul', { className: 'lmw-import-entries' }, group.entries.map(renderEntry)),
1339
+ )),
1340
+ blocked > 0
1341
+ ? h(
1342
+ 'section',
1343
+ { className: 'lmw-import-blocked' },
1344
+ h(
1345
+ 'button',
1346
+ {
1347
+ type: 'button',
1348
+ className: 'lmw-import-blocked-head',
1349
+ 'aria-expanded': showBlocked ? 'true' : 'false',
1350
+ onClick: () => setShowBlocked((value) => !value),
1351
+ },
1352
+ h(
1353
+ 'svg',
1354
+ {
1355
+ width: 10,
1356
+ height: 10,
1357
+ viewBox: '0 0 10 10',
1358
+ 'aria-hidden': 'true',
1359
+ className: showBlocked ? 'lmw-chev lmw-chev-open' : 'lmw-chev',
1360
+ },
1361
+ h('path', {
1362
+ d: 'M3 1.5 6.5 5 3 8.5',
1363
+ fill: 'none',
1364
+ stroke: 'currentColor',
1365
+ 'stroke-width': 1.4,
1366
+ 'stroke-linecap': 'round',
1367
+ 'stroke-linejoin': 'round',
1368
+ }),
1369
+ ),
1370
+ h('span', null, tr('import.blocked.title', { n: blocked })),
1371
+ ),
1372
+ showBlocked
1373
+ ? h('ul', { className: 'lmw-import-entries' }, blockedEntries.map(renderEntry))
1374
+ : null,
1375
+ )
1376
+ : null,
1377
+ )
1378
+ }
1379
+
1380
+ const renderResult = () => {
1381
+ const counts = result?.counts ?? {}
1382
+ const list = Array.isArray(result?.results) ? result.results : []
1383
+ return h(
1384
+ 'div',
1385
+ { className: 'lmw-result' },
1386
+ h('div', { className: 'lmw-result-title lmw-ok' }, tr('import.result.title')),
1387
+ h('p', { className: 'lmw-result-text' },
1388
+ tr('import.result.summary', {
1389
+ added: counts.added ?? 0,
1390
+ replaced: counts.replaced ?? 0,
1391
+ failed: counts.failed ?? 0,
1392
+ skipped: counts.skipped ?? 0,
1393
+ })),
1394
+ list.length > 0
1395
+ ? h('ul', { className: 'lmw-list' }, list.map((entry, index) => h(
1396
+ 'li',
1397
+ { key: `${entry.sessionId}:${index}` },
1398
+ `${shortId(entry.sessionId)} — ${tr(`import.result.${entry.action}`)}`
1399
+ + (entry.workspace === undefined ? '' : ` · ${entry.workspace.path}`)
1400
+ + (entry.message === undefined ? '' : ` · ${entry.message}`),
1401
+ )))
1402
+ : null,
1403
+ h('div', { className: 'lmw-result-actions' },
1404
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => { void store.scanNow() } }, tr('import.result.rescan')),
1405
+ h('button', { type: 'button', className: 'lmw-button lmw-primary', onClick: () => store.close() }, tr('import.result.close'))),
1406
+ )
1407
+ }
1408
+
1409
+ const header = h(
1410
+ 'header',
1411
+ { className: 'lmw-header' },
1412
+ h(
1413
+ 'div',
1414
+ { className: 'lmw-header-text' },
1415
+ h('div', { className: 'lmw-title' }, tr('import.title')),
1416
+ h('div', { className: 'lmw-subtitle' }, tr('import.subtitle')),
1417
+ ),
1418
+ h(
1419
+ 'button',
1420
+ {
1421
+ type: 'button',
1422
+ className: 'lmw-close',
1423
+ 'aria-label': tr('dialog.close'),
1424
+ 'data-lmw-autofocus': '',
1425
+ onClick: () => store.close(),
1426
+ },
1427
+ h('svg', { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': 'true' },
1428
+ h('path', { d: 'M3 3l8 8M11 3l-8 8', stroke: 'currentColor', 'stroke-width': 1.6, 'stroke-linecap': 'round' })),
1429
+ ),
1430
+ )
1431
+
1432
+ const body = () => {
1433
+ if (result !== null) return h('div', { className: 'lmw-import-scroll' }, renderResult())
1434
+ return h(
1435
+ 'div',
1436
+ { className: 'lmw-import-body' },
1437
+ h(
1438
+ 'div',
1439
+ { className: 'lmw-import-top' },
1440
+ h(
1441
+ 'div',
1442
+ { className: 'lmw-import-path' },
1443
+ h('label', { className: 'lmw-import-label' }, tr('import.pathLabel')),
1444
+ h('input', {
1445
+ className: 'lmw-input',
1446
+ type: 'text',
1447
+ spellCheck: false,
1448
+ value: snapshot.path,
1449
+ placeholder: tr('import.pathPlaceholder'),
1450
+ onChange: (event) => store.setPath(event.target.value),
1451
+ onKeyDown: (event) => {
1452
+ if (event.key !== 'Enter' || snapshot.scanning) return
1453
+ event.preventDefault()
1454
+ void store.scanNow()
1455
+ },
1456
+ }),
1457
+ h('button', {
1458
+ type: 'button',
1459
+ className: 'lmw-button',
1460
+ disabled: browsing || typeof pickDirectory !== 'function',
1461
+ onClick: async () => {
1462
+ setBrowsing(true)
1463
+ try {
1464
+ const picked = await pickDirectory()
1465
+ if (typeof picked === 'string' && picked.length > 0) store.setPath(picked)
1466
+ } catch {
1467
+ // A cancelled or unavailable chooser leaves the field as it is.
1468
+ } finally {
1469
+ setBrowsing(false)
1470
+ }
1471
+ },
1472
+ }, browsing ? tr('import.scanning') : tr('import.browse')),
1473
+ h('button', {
1474
+ type: 'button',
1475
+ className: 'lmw-button lmw-primary',
1476
+ disabled: snapshot.scanning === true,
1477
+ onClick: () => { void store.scanNow() },
1478
+ }, snapshot.scanning ? tr('import.scanning') : tr('import.scan')),
1479
+ ),
1480
+ snapshot.error === 'no-path'
1481
+ ? h('p', { className: 'lmw-error' }, tr('import.error.noPath'))
1482
+ : snapshot.error !== null && snapshot.error !== undefined
1483
+ ? h('p', { className: 'lmw-error' }, tr('import.error.scan', { message: snapshot.error }))
1484
+ : null,
1485
+ snapshot.applyError !== null && snapshot.applyError !== undefined
1486
+ ? h('p', { className: 'lmw-error' }, tr('import.error.apply', { message: snapshot.applyError }))
1487
+ : null,
1488
+ scan === null && (snapshot.error === null || snapshot.error === undefined)
1489
+ ? h('p', { className: 'lmw-note lmw-note-flush' }, tr('import.empty'))
1490
+ : null,
1491
+ renderScanTop(),
1492
+ ),
1493
+ renderScanLists(),
1494
+ )
1495
+ }
1496
+
1497
+ const footer = () => {
1498
+ if (result !== null) return null
1499
+ return h(
1500
+ 'div',
1501
+ { className: 'lmw-footbar' },
1502
+ h('span', { className: 'lmw-summary' }, tr('import.selected', { sessions: selected.size })),
1503
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => store.close() }, tr('action.cancel')),
1504
+ h('button', {
1505
+ type: 'button',
1506
+ className: 'lmw-button lmw-primary',
1507
+ disabled: snapshot.applying === true || selected.size === 0,
1508
+ onClick: () => setConfirming(true),
1509
+ }, snapshot.applying ? tr('import.applying') : tr('import.action')),
1510
+ )
1511
+ }
1512
+
1513
+ const confirmLayer = confirming
1514
+ ? h('div', { className: 'lmw-confirm-layer' },
1515
+ h('div', {
1516
+ className: 'lmw-confirm-card',
1517
+ role: 'alertdialog',
1518
+ 'aria-modal': 'true',
1519
+ 'aria-label': tr('import.confirm.title'),
1520
+ },
1521
+ h('div', { className: 'lmw-confirm-title' }, tr('import.confirm.title')),
1522
+ h('p', { className: 'lmw-confirm-text' }, tr('import.confirm.text', { added: addedCount, replaced: replacedCount })),
1523
+ h('div', { className: 'lmw-confirm-actions' },
1524
+ h('button', { type: 'button', className: 'lmw-button', onClick: () => setConfirming(false) }, tr('import.confirm.back')),
1525
+ h('button', {
1526
+ type: 'button',
1527
+ className: 'lmw-button lmw-primary',
1528
+ 'data-lmw-confirm-go': '',
1529
+ onClick: () => { void runApply() },
1530
+ }, tr('import.confirm.go')))))
1531
+ : null
1532
+
1533
+ return h('div', {
1534
+ className: 'lmw-backdrop',
1535
+ onMouseDown: (event) => {
1536
+ if (event.target === event.currentTarget) store.close()
1537
+ },
1538
+ },
1539
+ h('section', {
1540
+ ref: dialogRef,
1541
+ className: 'lmw-dialog',
1542
+ role: 'dialog',
1543
+ 'aria-modal': 'true',
1544
+ 'aria-label': tr('import.title'),
1545
+ },
1546
+ header,
1547
+ h('div', { className: 'lmw-body lmw-body-fixed' }, body()),
1548
+ footer(),
1549
+ confirmLayer,
1550
+ ),
1551
+ )
1552
+ }
1553
+
1554
+ /* ------------------------------------------------------------------ */
1555
+ /* Workspace path subtitle decorator */
1556
+ /* ------------------------------------------------------------------ */
1557
+
1558
+ function WorkspacePathDecorator(props) {
1559
+ const { workspaces } = props
1560
+ useEffect(() => {
1561
+ const paths = new Map()
1562
+ const apply = () => {
1563
+ const rows = document.querySelectorAll('[data-row-key^="workspace:"]')
1564
+ if (rows.length === 0) return
1565
+ for (const row of rows) {
1566
+ const key = row.getAttribute('data-row-key') ?? ''
1567
+ const workspaceId = key.slice('workspace:'.length)
1568
+ const path = paths.get(workspaceId)
1569
+ let anchor = null
1570
+ for (const child of row.children) {
1571
+ if (child.tagName !== 'SPAN') continue
1572
+ if (child.querySelector('svg') !== null) continue
1573
+ const inner = child.firstElementChild
1574
+ if (inner !== null && inner.tagName === 'SPAN') {
1575
+ anchor = inner
1576
+ break
1577
+ }
1578
+ }
1579
+ let node = row.querySelector('[data-lmw-ws-path]')
1580
+ if (path === undefined || anchor === null) {
1581
+ if (node !== null) node.remove()
1582
+ row.removeAttribute('data-lmw-ws-row')
1583
+ continue
1584
+ }
1585
+ row.setAttribute('data-lmw-ws-row', '')
1586
+ if (node === null) {
1587
+ node = document.createElement('span')
1588
+ node.setAttribute('data-lmw-ws-path', '')
1589
+ anchor.parentElement.appendChild(node)
1590
+ }
1591
+ if (node.textContent !== path) node.textContent = path
1592
+ }
1593
+ }
1594
+ const readPaths = () => {
1595
+ const snapshot = workspaces.list.getSnapshot()
1596
+ paths.clear()
1597
+ for (const item of snapshot.items ?? []) paths.set(String(item.workspaceId), item.path)
1598
+ apply()
1599
+ }
1600
+ let scheduled = 0
1601
+ const schedule = () => {
1602
+ if (scheduled !== 0) return
1603
+ scheduled = window.setTimeout(() => {
1604
+ scheduled = 0
1605
+ apply()
1606
+ }, 120)
1607
+ }
1608
+ const observer = new MutationObserver(schedule)
1609
+ observer.observe(document.body, { childList: true, subtree: true })
1610
+ // The Workspace baseline usually lands after this entry mounts, and an
1611
+ // execution adds more rows later: rebuild the id -> path map on every
1612
+ // Workspace snapshot change, not only once at mount.
1613
+ const unsubscribe = workspaces.list.subscribe(readPaths)
1614
+ readPaths()
1615
+ return () => {
1616
+ observer.disconnect()
1617
+ unsubscribe()
1618
+ if (scheduled !== 0) window.clearTimeout(scheduled)
1619
+ for (const node of document.querySelectorAll('[data-lmw-ws-path]')) node.remove()
1620
+ for (const row of document.querySelectorAll('[data-lmw-ws-row]')) row.removeAttribute('data-lmw-ws-row')
1621
+ }
1622
+ }, [workspaces])
1623
+ return h('style', { 'data-lmw-style': 'base' }, BASE_CSS)
1624
+ }
1625
+
1626
+ /* ------------------------------------------------------------------ */
1627
+ /* Styles */
1628
+ /* ------------------------------------------------------------------ */
1629
+
1630
+ const DIALOG_CSS = [
1631
+ '.lmw-foot{display:flex;align-items:center;width:100%;min-width:0}',
1632
+ '.lmw-foot-stack{display:flex;flex-direction:column;gap:2px;flex:1 1 auto;min-width:0}',
1633
+ '.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}',
1634
+ '.lmw-foot-button:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-label-primary)}',
1635
+ '.lmw-foot-button[data-wide="0"]{justify-content:center;padding:0}',
1636
+ '.lmw-foot-glyph{display:inline-flex;flex:none;color:inherit}',
1637
+ '.lmw-foot-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}',
1638
+ '.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}',
1639
+ '.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}',
1640
+ '.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}',
1641
+ '.lmw-header{display:flex;align-items:flex-start;gap:12px;padding:16px 18px 12px;border-bottom:0.5px solid var(--dsw-alias-border-l1)}',
1642
+ '.lmw-header-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:4px}',
1643
+ '.lmw-title{font-size:15px;font-weight:600;line-height:20px}',
1644
+ '.lmw-subtitle{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px;overflow-wrap:anywhere}',
1645
+ '.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}',
1646
+ '.lmw-close:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-label-primary)}',
1647
+ '.lmw-body{flex:1;min-height:0;overflow-y:auto;padding:14px 18px 4px}',
1648
+ '.lmw-panels{display:flex;flex-direction:column}',
1649
+ '.lmw-panel{display:flex;flex-direction:column;gap:8px;padding-bottom:14px}',
1650
+ '.lmw-panel + .lmw-panel{border-top:1px solid var(--dsw-alias-border-l2);padding-top:14px}',
1651
+ '.lmw-panel-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}',
1652
+ '.lmw-panel-title{font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}',
1653
+ '.lmw-panel-meta{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px}',
1654
+ '.lmw-toolbar{display:flex;align-items:center;gap:14px}',
1655
+ '.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}',
1656
+ '.lmw-link:hover{text-decoration:underline}',
1657
+ '.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}',
1658
+ '.lmw-group[data-missing="1"]{border-color:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 45%,var(--dsw-alias-border-l1))}',
1659
+ '.lmw-group-head{display:flex;align-items:flex-start;gap:8px;padding:9px 10px;background:var(--dsw-alias-bg-layer-2);cursor:pointer}',
1660
+ '.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}',
1661
+ '.lmw-count{flex:none;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px;white-space:nowrap}',
1662
+ '.lmw-sessions{list-style:none;margin:0;padding:5px 8px 7px 30px;display:flex;flex-direction:column;gap:2px}',
1663
+ '.lmw-session-label{display:flex;align-items:center;gap:8px;min-height:26px;padding:2px 6px;border-radius:6px;cursor:pointer}',
1664
+ '.lmw-session-label:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
1665
+ '.lmw-session-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
1666
+ '.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}',
1667
+ '.lmw-check{flex:none;width:14px;height:14px;margin:0;accent-color:var(--dsw-alias-brand-primary)}',
1668
+ '.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}',
1669
+ '.lmw-badge-warn{background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 14%,transparent)}',
1670
+ '.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)}',
1671
+ '.lmw-skill-check{cursor:pointer}',
1672
+ '.lmw-skill-label{flex:0 1 auto;min-width:0;font-size:12.5px;color:var(--dsw-alias-label-primary)}',
1673
+ '.lmw-skill-state{flex:none;font-size:12px;color:var(--dsw-alias-label-secondary)}',
1674
+ '.lmw-check-ok{flex:none;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-state-success-primary)}',
1675
+ '.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}',
1676
+ '.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)}',
1677
+ '.lmw-summary{flex:1;min-width:0;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px}',
1678
+ '.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}',
1679
+ '.lmw-button:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
1680
+ '.lmw-button:disabled{opacity:.5;cursor:default}',
1681
+ '.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)}',
1682
+ '.lmw-primary:hover{background:var(--dsw-alias-button-primary-hover,var(--dsw-alias-brand-primary))}',
1683
+ '.lmw-state{display:flex;flex-direction:column;align-items:stretch;gap:10px;padding:4px 0}',
1684
+ '.lmw-note{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:17px;margin:6px 0 0}',
1685
+ '.lmw-note-flush{margin:0}',
1686
+ '.lmw-warn{color:var(--dsw-alias-state-warn-primary);font-size:12px;font-weight:400}',
1687
+ '.lmw-ok{color:var(--dsw-alias-state-success-primary);font-size:12px;font-weight:400}',
1688
+ '.lmw-error{color:var(--dsw-alias-state-error-primary);font-size:12px;line-height:17px;margin:6px 0 0;overflow-wrap:anywhere}',
1689
+ '.lmw-result{display:flex;flex-direction:column;gap:8px}',
1690
+ '.lmw-result-title{font-size:13px;font-weight:600}',
1691
+ '.lmw-result-text{margin:0;font-size:12px;line-height:17px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
1692
+ '.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}',
1693
+ '.lmw-result-fail{display:flex;flex-direction:column;gap:2px}',
1694
+ '.lmw-result-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:4px}',
1695
+ '.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)}',
1696
+ '.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)}',
1697
+ '.lmw-confirm-title{font-size:14px;font-weight:600}',
1698
+ '.lmw-confirm-text{margin:0;font-size:12.5px;line-height:18px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
1699
+ '.lmw-confirm-actions{display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap}',
1700
+ '.lmw-body-fixed{display:flex;flex-direction:column;overflow:hidden}',
1701
+ '.lmw-import-body{display:flex;flex-direction:column;flex:1;min-height:0;gap:10px}',
1702
+ '.lmw-import-top{display:flex;flex-direction:column;gap:8px;flex:none;min-width:0}',
1703
+ '.lmw-import-scroll{flex:1;min-height:0;overflow-y:auto;padding-right:2px}',
1704
+ '.lmw-import-path{display:flex;align-items:center;gap:8px;flex-wrap:wrap}',
1705
+ '.lmw-import-label{flex:none;font-size:12.5px;color:var(--dsw-alias-label-secondary)}',
1706
+ '.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}',
1707
+ '.lmw-input:focus{border-color:var(--dsw-alias-brand-primary)}',
1708
+ '.lmw-import-summary{font-size:12px;line-height:17px;color:var(--dsw-alias-label-secondary)}',
1709
+ '.lmw-import-blocked{margin-top:12px;border-top:1px solid var(--dsw-alias-border-l2);padding-top:8px}',
1710
+ '.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}',
1711
+ '.lmw-import-blocked-head:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
1712
+ '.lmw-chev{flex:none;color:var(--dsw-alias-label-secondary);transition:transform 120ms ease}',
1713
+ '.lmw-chev-open{transform:rotate(90deg)}',
1714
+ '.lmw-import-entries{list-style:none;margin:0;padding:5px 8px 7px 10px;display:flex;flex-direction:column;gap:2px}',
1715
+ '.lmw-entry{min-width:0}',
1716
+ '.lmw-entry-label{display:flex;align-items:flex-start;gap:8px;padding:5px 6px;border-radius:6px;cursor:pointer}',
1717
+ '.lmw-entry-label:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))}',
1718
+ '.lmw-entry-main{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}',
1719
+ '.lmw-entry-title{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:12.5px;line-height:17px}',
1720
+ '.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}',
1721
+ '.lmw-entry-meta{font-size:11px;line-height:15px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
1722
+ '.lmw-entry-reason{font-size:11px;line-height:15px;color:var(--dsw-alias-state-error-primary);overflow-wrap:anywhere}',
1723
+ '.lmw-warn-text{font-size:11px;line-height:15px;color:var(--dsw-alias-state-warn-primary);overflow-wrap:anywhere}',
1724
+ '.lmw-badge-new{background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 12%,transparent);color:var(--dsw-alias-state-success-primary)}',
1725
+ '.lmw-badge-replace{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 12%,transparent);color:var(--dsw-alias-brand-primary)}',
1726
+ '.lmw-badge-block{background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 12%,transparent);color:var(--dsw-alias-state-error-primary)}',
1727
+ ].join('\n')
1728
+
1729
+ const PATH_CSS = [
1730
+ '[data-lmw-ws-row]{height:auto!important;min-height:32px;padding-top:3px!important;padding-bottom:3px!important}',
1731
+ '[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}',
1732
+ '[data-lmw-ws-path]:hover{color:var(--dsw-alias-label-primary)}',
1733
+ ].join('\n')
1734
+
1735
+ // One always-mounted stylesheet: the sidebar footer action must look right
1736
+ // before the dialog ever opens, so its rules cannot live in the dialog.
1737
+ const BASE_CSS = DIALOG_CSS + '\n' + PATH_CSS
1738
+
1739
+ /* ------------------------------------------------------------------ */
1740
+ /* Plugin */
1741
+ /* ------------------------------------------------------------------ */
1742
+
1743
+ return {
1744
+ inject: ['slots', 'locale', 'workspaces', 'sessions', 'uiWorkspace'],
1745
+ apply(ctx) {
1746
+ ctx.effect(
1747
+ () => ctx.locale.register(NS, { en: DICTIONARIES.en, zh: DICTIONARIES.zh }),
1748
+ 'lmw: locale dictionaries',
1749
+ )
1750
+ const t = ctx.locale.bind(NS)
1751
+ const refreshSessionList = typeof ctx.sessions?.refresh === 'function'
1752
+ ? () => ctx.sessions.refresh()
1753
+ : undefined
1754
+ const store = createStore({ refreshSessions: refreshSessionList })
1755
+ ctx.effect(() => () => store.dispose(), 'lmw: title refresh timers')
1756
+ const importStore = createImportStore({
1757
+ refreshAssignment: () => {
1758
+ void store.refresh()
1759
+ },
1760
+ refreshSessions: refreshSessionList,
1761
+ })
1762
+
1763
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
1764
+ name: 'sidebar.footer.action',
1765
+ id: 'lmw-footer',
1766
+ order: 250,
1767
+ locale: NS,
1768
+ inject: () => ({ store, importStore, translate: t }),
1769
+ }, FooterActionsPanel))
1770
+
1771
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1772
+ name: 'shell.overlay',
1773
+ id: 'lmw-session-assign-dialog',
1774
+ order: 600,
1775
+ locale: NS,
1776
+ inject: () => ({ store, workspaces: ctx.workspaces, translate: t }),
1777
+ }, AssignDialog))
1778
+
1779
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1780
+ name: 'shell.overlay',
1781
+ id: 'lmw-import-dialog',
1782
+ order: 610,
1783
+ locale: NS,
1784
+ inject: () => ({
1785
+ store: importStore,
1786
+ translate: t,
1787
+ pickDirectory: typeof ctx.uiWorkspace?.pickDirectory === 'function'
1788
+ ? () => ctx.uiWorkspace.pickDirectory()
1789
+ : undefined,
1790
+ }),
1791
+ }, ImportDialog))
1792
+
1793
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1794
+ name: 'shell.overlay',
1795
+ id: 'lmw-workspace-path',
1796
+ order: 900,
1797
+ inject: () => ({ workspaces: ctx.workspaces }),
1798
+ }, WorkspacePathDecorator))
1799
+
1800
+ store.boot().catch((error) => {
1801
+ console.error('[lmw-plugin] startup scan failed:', error)
1802
+ })
1803
+ },
1804
+ }
1805
+ },
1806
+ })