dsh-remote-plugin 0.8.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.en.md +16 -5
  2. package/README.md +15 -4
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +527 -78
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +53 -4
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/app.js +1204 -174
  11. package/public/bc-integration.css +81 -0
  12. package/public/build.json +2 -2
  13. package/public/composer-tools.css +184 -0
  14. package/public/composer-tools.js +888 -0
  15. package/public/desktop/desktop.html +92 -73
  16. package/public/desktop/desktop.js +631 -77
  17. package/public/file-inbox.js +77 -18
  18. package/public/genui.css +10 -0
  19. package/public/genui.js +22 -4
  20. package/public/host-queue.js +232 -0
  21. package/public/host-schedule.js +301 -0
  22. package/public/host-state.css +19 -0
  23. package/public/index.html +330 -140
  24. package/public/md.js +21 -1
  25. package/public/network.js +33 -1
  26. package/public/onboarding.js +3 -3
  27. package/public/operations.js +4 -3
  28. package/public/plan-review.css +297 -0
  29. package/public/plan-review.js +621 -0
  30. package/public/plugin.html +29 -28
  31. package/public/relay-autopair.js +25 -10
  32. package/public/relay-settings.css +11 -0
  33. package/public/relay-settings.js +350 -28
  34. package/public/session-management.css +61 -0
  35. package/public/session-management.js +742 -0
  36. package/public/session-search.css +137 -0
  37. package/public/session-search.js +977 -0
  38. package/public/skins/blue-fish/preview.html +3 -3
  39. package/public/skins/bocchi/preview.html +5 -5
  40. package/public/skins/kita/preview.html +6 -6
  41. package/public/skins/miku/SOURCES.json +10 -0
  42. package/public/skins/miku/chibi.png +0 -0
  43. package/public/skins/miku/preview.html +33 -0
  44. package/public/skins/miku/skin.css +82 -0
  45. package/public/skins/nijika/preview.html +6 -6
  46. package/public/skins/penguin/preview.html +3 -3
  47. package/public/skins/ryo/preview.html +6 -6
  48. package/public/slash-suggestions.js +15 -3
  49. package/public/sponsor-entry.js +11 -3
  50. package/public/styles.css +141 -21
  51. package/public/subagents.css +5 -0
  52. package/public/subagents.js +52 -0
  53. package/public/theme-vars.css +65 -1
  54. package/public/theme.js +4 -3
  55. package/public/turn-diff.css +323 -0
  56. package/public/turn-diff.js +778 -0
  57. package/public/update.json +8 -8
  58. package/public/version.json +1 -1
  59. package/public/workflow.css +305 -34
  60. package/public/workflow.js +141 -41
@@ -0,0 +1,742 @@
1
+ /* dsh-remote session management (C3) — host-authoritative pin/unpin, unarchive,
2
+ * workspace rename and registration removal.
3
+ *
4
+ * All writes go through an explicit adapter; state is only changed after the
5
+ * Host response is verified (or after a read-back reconciles an ambiguous
6
+ * timeout). Read-only/paired devices cannot write. Removing a workspace only
7
+ * deletes its registration: sessions, logs, directories and files stay on disk.
8
+ */
9
+ ;(function (root) {
10
+ 'use strict'
11
+
12
+ const KIND = Object.freeze({
13
+ READ_ONLY: 'read-only',
14
+ UNSUPPORTED: 'unsupported',
15
+ AUTH: 'auth',
16
+ CONFLICT: 'conflict',
17
+ NOT_FOUND: 'not-found',
18
+ ARCHIVED_SESSION: 'archived-session',
19
+ TIMEOUT: 'timeout',
20
+ NETWORK: 'network',
21
+ INVALID_RESPONSE: 'invalid-response',
22
+ NOT_VERIFIED: 'not-verified',
23
+ CANCELLED: 'cancelled',
24
+ CONFIRMATION_UNAVAILABLE: 'confirmation-unavailable',
25
+ FAILED: 'failed',
26
+ })
27
+
28
+ function isEnglish() { return !!root.I18N && root.I18N.lang === 'en' }
29
+ function text(zh, en) { return isEnglish() ? en : zh }
30
+ function esc(value) {
31
+ return String(value == null ? '' : value).replace(/[&<>"']/g, c => ({
32
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
33
+ }[c]))
34
+ }
35
+ function clip(value, max) {
36
+ const points = Array.from(String(value == null ? '' : value))
37
+ return points.length <= max ? points.join('') : points.slice(0, max).join('') + '…'
38
+ }
39
+ function pathKey(value) {
40
+ let key = String(value == null ? '' : value).replace(/\\/g, '/').replace(/\/+/g, '/')
41
+ if (key.length > 1) key = key.replace(/\/+$/, '')
42
+ const windows = /^[A-Za-z]:\//.test(key) || String(value == null ? '' : value).includes('\\')
43
+ || !!(root.navigator && /Windows/i.test(String(root.navigator.platform || root.navigator.userAgent || '')))
44
+ return windows ? key.toLowerCase() : key
45
+ }
46
+ function baseName(value) {
47
+ const clean = String(value == null ? '' : value).replace(/[\\/]+$/, '')
48
+ return clean.split(/[\\/]/).pop() || clean
49
+ }
50
+
51
+ function normalizeWorkspace(row) {
52
+ if (!row || typeof row !== 'object') return null
53
+ const workspaceId = typeof row.workspaceId === 'string' ? row.workspaceId : ''
54
+ if (!workspaceId) return null
55
+ const path = typeof row.path === 'string' ? row.path : ''
56
+ const title = typeof row.title === 'string' ? row.title.trim() : ''
57
+ return {
58
+ workspaceId,
59
+ path,
60
+ title,
61
+ name: title || baseName(path) || path,
62
+ sessionIds: Array.isArray(row.sessionIds) ? row.sessionIds.map(String) : [],
63
+ raw: row,
64
+ }
65
+ }
66
+
67
+ function sessionTitle(session, titleOf) {
68
+ if (typeof titleOf === 'function') {
69
+ try {
70
+ const custom = titleOf(session)
71
+ if (typeof custom === 'string' && custom.trim()) return custom.trim()
72
+ } catch {}
73
+ }
74
+ const projected = session && session.projections && session.projections.values && session.projections.values.title
75
+ if (typeof projected === 'string' && projected.trim()) return projected.trim()
76
+ if (session && typeof session.title === 'string' && session.title.trim()) return session.title.trim()
77
+ const id = session && session.sessionId ? String(session.sessionId) : ''
78
+ return id ? text('未命名会话', 'Untitled conversation') + ' · ' + id.slice(-8) : text('未知会话', 'Unknown conversation')
79
+ }
80
+
81
+ /** Workspace ownership: explicit workspaceId, membership list, then cwd inside path. */
82
+ function sessionBelongsToWorkspace(workspace, session) {
83
+ if (!workspace || !session || !session.sessionId) return false
84
+ const sessionId = String(session.sessionId)
85
+ if (typeof session.workspaceId === 'string' && session.workspaceId === workspace.workspaceId) return true
86
+ if (Array.isArray(workspace.sessionIds) && workspace.sessionIds.some(id => String(id) === sessionId)) return true
87
+ const cwdKey = pathKey(session.cwd)
88
+ const workspaceKey = pathKey(workspace.path)
89
+ if (!cwdKey || !workspaceKey) return false
90
+ return cwdKey === workspaceKey || cwdKey.startsWith(workspaceKey.endsWith('/') ? workspaceKey : workspaceKey + '/')
91
+ }
92
+
93
+ /** Everything a user must understand before a workspace registration is removed. */
94
+ function workspaceImpact(workspace, sessions, options = {}) {
95
+ const normalized = normalizeWorkspace(workspace)
96
+ const archived = new Set((options.archivedSessionIds || []).map(String))
97
+ const pinned = new Set((options.pinnedSessionIds || []).map(String))
98
+ const rows = []
99
+ const seen = new Set()
100
+ for (const session of Array.isArray(sessions) ? sessions : []) {
101
+ if (!session || !session.sessionId) continue
102
+ if (!sessionBelongsToWorkspace(normalized, session)) continue
103
+ const sessionId = String(session.sessionId)
104
+ if (seen.has(sessionId)) continue
105
+ seen.add(sessionId)
106
+ rows.push({
107
+ sessionId,
108
+ title: sessionTitle(session, options.titleOf),
109
+ archived: archived.has(sessionId),
110
+ pinned: pinned.has(sessionId),
111
+ })
112
+ }
113
+ return {
114
+ workspaceId: normalized ? normalized.workspaceId : '',
115
+ name: normalized ? normalized.name : '',
116
+ path: normalized ? normalized.path : '',
117
+ total: rows.length,
118
+ sessions: rows,
119
+ archivedCount: rows.filter(row => row.archived).length,
120
+ pinnedCount: rows.filter(row => row.pinned).length,
121
+ }
122
+ }
123
+
124
+ /** DSH trims, rejects blank titles and refuses exact duplicate titles. */
125
+ function validateWorkspaceTitle(rawValue, options = {}) {
126
+ const title = String(rawValue == null ? '' : rawValue).trim()
127
+ if (!title) return { ok: false, title: '', error: 'blank', message: text('工作区名称不能为空。', 'A workspace name cannot be blank.') }
128
+ const workspaces = (Array.isArray(options.workspaces) ? options.workspaces : [])
129
+ .map(normalizeWorkspace).filter(Boolean)
130
+ const currentId = options.currentWorkspaceId || ''
131
+ const current = workspaces.find(workspace => workspace.workspaceId === currentId)
132
+ if (current && current.title === title) {
133
+ return { ok: false, title, error: 'unchanged', message: text('名称未改变。', 'The name is unchanged.') }
134
+ }
135
+ if (workspaces.some(workspace => workspace.workspaceId !== currentId && workspace.title === title)) {
136
+ return { ok: false, title, error: 'conflict', message: text(`名称「${title}」已被其他工作区使用。`, `The name "${title}" is already used by another workspace.`) }
137
+ }
138
+ return { ok: true, title, error: null, message: '' }
139
+ }
140
+
141
+ function idsArray(value, key) {
142
+ return value && Array.isArray(value[key]) ? value[key].map(String) : null
143
+ }
144
+
145
+ function applyPinResult(value, sessionId, action) {
146
+ const ids = idsArray(value, 'pinnedSessionIds')
147
+ if (!ids) return { ok: false, error: 'invalid-response', message: text('主机未返回置顶集合,无法确认写入结果。', 'The Host returned no pin set, so the write cannot be confirmed.') }
148
+ const id = String(sessionId)
149
+ const included = ids.includes(id)
150
+ if (action === 'unpin' ? included : !included) {
151
+ return { ok: false, error: 'not-verified', message: text('主机未确认置顶状态变更。', 'The Host did not confirm the pin change.'), pinnedSessionIds: ids }
152
+ }
153
+ return { ok: true, pinnedSessionIds: ids }
154
+ }
155
+
156
+ function applyUnarchiveResult(value, sessionId) {
157
+ const ids = idsArray(value, 'archivedSessionIds')
158
+ if (!ids) return { ok: false, error: 'invalid-response', message: text('主机未返回归档集合,无法确认取消归档结果。', 'The Host returned no archive set, so the unarchive cannot be confirmed.') }
159
+ if (ids.includes(String(sessionId))) {
160
+ return { ok: false, error: 'not-verified', message: text('主机仍将该会话标记为归档,取消归档未生效。', 'The Host still marks the session archived; unarchive did not take effect.'), archivedSessionIds: ids }
161
+ }
162
+ return { ok: true, archivedSessionIds: ids }
163
+ }
164
+
165
+ function applyRenameResult(value, workspaceId, title) {
166
+ const workspace = value && value.workspace && typeof value.workspace === 'object' ? value.workspace : null
167
+ if (!workspace || String(workspace.workspaceId || '') !== String(workspaceId || '')) {
168
+ return { ok: false, error: 'invalid-response', message: text('主机未返回被重命名的工作区。', 'The Host returned no renamed workspace.') }
169
+ }
170
+ if (String(workspace.title || '').trim() !== String(title || '').trim()) {
171
+ return { ok: false, error: 'not-verified', message: text('主机返回的工作区名称与新名称不一致。', 'The workspace name returned by the Host differs from the requested name.'), workspace }
172
+ }
173
+ return { ok: true, workspace }
174
+ }
175
+
176
+ function applyDeleteResult(value) {
177
+ if (!value || value.deleted !== true) {
178
+ return { ok: false, error: 'invalid-response', message: text('主机未确认工作区登记已删除。', 'The Host did not confirm the workspace registration deletion.') }
179
+ }
180
+ return { ok: true, deleted: true }
181
+ }
182
+
183
+ function errorCode(error) {
184
+ const code = error && (error.code || error.rpcCode || error.errorCode)
185
+ return code == null ? '' : String(code)
186
+ }
187
+ function errorStatus(error) {
188
+ const status = Number(error && (error.status || error.httpStatus))
189
+ return Number.isFinite(status) ? status : 0
190
+ }
191
+ function errorMessage(error) {
192
+ if (!error) return ''
193
+ if (typeof error === 'string') return error
194
+ return String(error.message || error.error || '')
195
+ }
196
+
197
+ const UNSUPPORTED_CODES = new Set([
198
+ 'method-unavailable', 'not-found', 'unsupported-method', 'unsupported_endpoint',
199
+ 'no-generated-rpc-adapter', 'upstream-incompatible', 'gateway/not-found',
200
+ ])
201
+
202
+ /** Map a Host write failure to an actionable kind, including ambiguity. */
203
+ function classifyManagementError(error) {
204
+ const code = errorCode(error).toLowerCase()
205
+ const status = errorStatus(error)
206
+ const message = errorMessage(error)
207
+ if (UNSUPPORTED_CODES.has(code) || [404, 405, 501].includes(status)
208
+ || /no generated rpc adapter|method-unavailable|does not mount|unsupported/i.test(message)) {
209
+ return {
210
+ kind: KIND.UNSUPPORTED,
211
+ ambiguous: false,
212
+ code: code || `http-${status || 'unknown'}`,
213
+ message: text('当前主机或网关版本不支持该管理操作,未写入任何状态。', 'This Host or gateway version does not support this management action; nothing was written.'),
214
+ detail: message,
215
+ }
216
+ }
217
+ if (code === 'auth' || code === 'unauthorized' || code === 'permission-denied' || status === 401 || status === 403) {
218
+ return {
219
+ kind: KIND.AUTH,
220
+ ambiguous: false,
221
+ code: code || `http-${status || 'auth'}`,
222
+ message: text('无权限或登录已失效,操作未执行。', 'Permission denied or signed out; nothing was changed.'),
223
+ detail: message,
224
+ }
225
+ }
226
+ if (code === 'workspace/name-conflict' || /already in use|name-conflict/i.test(message)) {
227
+ return {
228
+ kind: KIND.CONFLICT,
229
+ ambiguous: false,
230
+ code: code || 'workspace/name-conflict',
231
+ message: text('该工作区名称已被使用,未修改。', 'That workspace name is already in use; nothing was changed.'),
232
+ detail: message,
233
+ }
234
+ }
235
+ if (code === 'workspace/archived-session' || /archived session/i.test(message)) {
236
+ return {
237
+ kind: KIND.ARCHIVED_SESSION,
238
+ ambiguous: false,
239
+ code: code || 'workspace/archived-session',
240
+ message: text('归档会话不能置顶;请先取消归档。', 'An archived conversation cannot be pinned; unarchive it first.'),
241
+ detail: message,
242
+ }
243
+ }
244
+ if (code === 'session/not-found' || code === 'workspace/not-found'
245
+ || /not found/i.test(message) && /session|workspace/i.test(message)) {
246
+ return {
247
+ kind: KIND.NOT_FOUND,
248
+ ambiguous: false,
249
+ code: code || 'not-found',
250
+ message: text('目标会话或工作区不存在,可能已被其他客户端更新。', 'The session or workspace no longer exists; another client may have updated it.'),
251
+ detail: message,
252
+ }
253
+ }
254
+ const timeout = error && ['AbortError', 'TimeoutError'].includes(error.name)
255
+ || ['timeout', 'operation-pending', 'upstream-uncertain', 'unknown'].includes(code)
256
+ || [502, 503, 504].includes(status)
257
+ || /timeout|unconfirmed|upstream-unreachable|network|fetch failed/i.test(message)
258
+ if (timeout) {
259
+ return {
260
+ kind: /network|fetch failed|upstream-unreachable/i.test(message) ? KIND.NETWORK : KIND.TIMEOUT,
261
+ ambiguous: true,
262
+ code: code || 'timeout',
263
+ message: text('写入结果未知(超时/连接中断)。正在核对主机状态,不会盲目重试。', 'The write outcome is unknown (timeout or connection loss). Checking Host state; the write is not retried blindly.'),
264
+ detail: message,
265
+ }
266
+ }
267
+ return {
268
+ kind: KIND.FAILED,
269
+ ambiguous: false,
270
+ code: code || 'write-failed',
271
+ message: text('主机拒绝了本次操作,未修改任何状态。', 'The Host rejected the operation; nothing was changed.'),
272
+ detail: message,
273
+ }
274
+ }
275
+
276
+ /** Confirmation payload for workspace registration removal. */
277
+ function removeWorkspaceConfirmation(workspace, impact, options = {}) {
278
+ const normalized = normalizeWorkspace(workspace)
279
+ const name = normalized ? normalized.name : (impact && impact.name) || ''
280
+ const path = normalized ? normalized.path : (impact && impact.path) || ''
281
+ const total = impact && Number.isFinite(impact.total) ? impact.total : 0
282
+ const sample = impact && Array.isArray(impact.sessions) ? impact.sessions.slice(0, 8) : []
283
+ const lines = []
284
+ lines.push(text(`移除工作区登记「${name}」?`, `Remove workspace registration "${name}"?`))
285
+ if (path) lines.push(text(`路径:${path}`, `Path: ${path}`))
286
+ lines.push(total
287
+ ? text(`影响:该工作区当前登记了 ${total} 个会话,移除后将不再归属该工作区。`, `Impact: ${total} ${total === 1 ? 'conversation is' : 'conversations are'} registered to this workspace; after removal they no longer belong to it.`)
288
+ : text('影响:当前没有会话登记到该工作区。', 'Impact: no conversations are registered to this workspace.'))
289
+ if (sample.length) {
290
+ lines.push(text('会话示例:', 'Example conversations:'))
291
+ for (const session of sample) lines.push('- ' + clip(session.title, 80))
292
+ }
293
+ if (impact && impact.archivedCount) lines.push(text(`其中 ${impact.archivedCount} 个处于归档状态。`, `${impact.archivedCount} of them are archived.`))
294
+ if (impact && impact.pinnedCount) lines.push(text(`其中 ${impact.pinnedCount} 个处于置顶状态。`, `${impact.pinnedCount} of them are pinned.`))
295
+ lines.push('')
296
+ lines.push(text('此操作只移除 DSH 中的工作区登记,不删除磁盘目录、文件或会话历史。会话本身不会被删除。', 'This only removes the workspace registration in DSH. The directory, files and conversation history on disk are not deleted, and conversations themselves are not deleted.'))
297
+ return {
298
+ title: text('移除工作区登记', 'Remove workspace registration'),
299
+ message: lines.join('\n'),
300
+ confirmLabel: options.confirmLabel || text('仅移除登记', 'Remove registration only'),
301
+ cancelLabel: options.cancelLabel || text('取消', 'Cancel'),
302
+ impact: impact || { total: 0, sessions: [] },
303
+ }
304
+ }
305
+
306
+ function adapterValue(adapter, method, fallback) {
307
+ if (!adapter || typeof adapter[method] !== 'function') return fallback
308
+ try { const value = adapter[method](); return value == null ? fallback : value } catch { return fallback }
309
+ }
310
+
311
+ function createManager(adapter) {
312
+ if (!adapter || typeof adapter.rpc !== 'function') throw new TypeError('DshSessionManagement.init requires an adapter.rpc(method, payload, options) function')
313
+ const writeTimeoutMs = Number.isFinite(adapter.writeTimeoutMs) ? adapter.writeTimeoutMs : 12000
314
+ const inflight = new Map()
315
+ let lastResult = null
316
+ let lastError = null
317
+ let busyKey = ''
318
+ const host = {
319
+ workspaces: [],
320
+ sessions: [],
321
+ archived: new Set(),
322
+ pinned: new Set(),
323
+ }
324
+
325
+ function writable() {
326
+ if (adapter.readOnly === true) return false
327
+ if (typeof adapter.readOnly === 'function') {
328
+ try { if (adapter.readOnly() === true) return false } catch { return false }
329
+ }
330
+ if (typeof adapter.canWrite === 'function') {
331
+ try { if (adapter.canWrite() === false) return false } catch { return false }
332
+ }
333
+ return true
334
+ }
335
+
336
+ function notify() {
337
+ try { if (typeof adapter.onState === 'function') adapter.onState(snapshot()) } catch {}
338
+ }
339
+
340
+ function hydrate(extra = {}) {
341
+ const workspaces = adapterValue(adapter, 'workspaces', [])
342
+ host.workspaces = (Array.isArray(workspaces) ? workspaces : []).map(normalizeWorkspace).filter(Boolean)
343
+ const sessions = adapterValue(adapter, 'sessions', [])
344
+ host.sessions = Array.isArray(sessions) ? sessions : []
345
+ host.archived = new Set((Array.isArray(extra.archivedSessionIds) ? extra.archivedSessionIds : adapterValue(adapter, 'archivedSessionIds', [])).map(String))
346
+ host.pinned = new Set((Array.isArray(extra.pinnedSessionIds) ? extra.pinnedSessionIds : adapterValue(adapter, 'pinnedSessionIds', [])).map(String))
347
+ notify()
348
+ return snapshot()
349
+ }
350
+
351
+ async function refreshHost(scope) {
352
+ let refreshed = false
353
+ if (typeof adapter.refresh === 'function') {
354
+ try { await adapter.refresh(scope); refreshed = true } catch { refreshed = false }
355
+ }
356
+ // Only overwrite the locally verified state when a fresh Host read really
357
+ // happened; a failed refresh must not resurrect pre-write state.
358
+ if (refreshed) hydrate()
359
+ return refreshed
360
+ }
361
+
362
+ function snapshot() {
363
+ return {
364
+ canWrite: writable(),
365
+ workspaces: host.workspaces.map(workspace => ({ ...workspace, sessionIds: workspace.sessionIds.slice() })),
366
+ sessions: host.sessions.slice(),
367
+ archivedSessionIds: [...host.archived],
368
+ pinnedSessionIds: [...host.pinned],
369
+ busyKey,
370
+ lastResult: lastResult ? { ...lastResult } : null,
371
+ lastError: lastError ? { ...lastError } : null,
372
+ }
373
+ }
374
+
375
+ function failure(error, extra = {}) {
376
+ lastError = { ...error }
377
+ lastResult = { ok: false, error: lastError, ...extra }
378
+ try { if (typeof adapter.toast === 'function') adapter.toast(lastError.message, 'err') } catch {}
379
+ notify()
380
+ return lastResult
381
+ }
382
+
383
+ function success(extra = {}) {
384
+ lastError = null
385
+ lastResult = { ok: true, ...extra }
386
+ notify()
387
+ return lastResult
388
+ }
389
+
390
+ function readOnlyFailure() {
391
+ return failure({ kind: KIND.READ_ONLY, ambiguous: false, message: text('只读/配对设备不能修改主机状态。', 'Read-only/paired devices cannot change Host state.') })
392
+ }
393
+
394
+ function requireWritable() { return writable() ? null : readOnlyFailure() }
395
+
396
+ async function runWrite(config) {
397
+ const key = config.key
398
+ if (inflight.has(key)) return inflight.get(key)
399
+ const job = (async () => {
400
+ busyKey = key
401
+ notify()
402
+ try {
403
+ let value
404
+ try {
405
+ value = await adapter.rpc(config.method, config.payload, { timeoutMs: writeTimeoutMs })
406
+ } catch (error) {
407
+ const classified = classifyManagementError(error)
408
+ if (!classified.ambiguous) return failure(classified)
409
+ const reconciled = await config.reconcile()
410
+ if (reconciled && reconciled.ok) {
411
+ try { if (typeof adapter.toast === 'function') adapter.toast(config.reconciledMessage || config.successMessage, 'ok') } catch {}
412
+ return success({ reconciled: true, method: config.method, ...config.resultExtra })
413
+ }
414
+ return failure({ ...classified, reconciled: false })
415
+ }
416
+ const verified = config.verify(value)
417
+ if (verified.ok) {
418
+ config.apply(verified, value)
419
+ await refreshHost(config.refreshScope)
420
+ try { if (typeof adapter.toast === 'function') adapter.toast(config.successMessage, 'ok') } catch {}
421
+ return success({ method: config.method, ...config.resultExtra })
422
+ }
423
+ const reconciled = await config.reconcile()
424
+ if (reconciled && reconciled.ok) {
425
+ try { if (typeof adapter.toast === 'function') adapter.toast(config.reconciledMessage || config.successMessage, 'ok') } catch {}
426
+ return success({ reconciled: true, method: config.method, ...config.resultExtra })
427
+ }
428
+ return failure({ kind: KIND.NOT_VERIFIED, ambiguous: true, code: 'not-verified', message: verified.message || text('主机未确认写入结果。', 'The Host did not confirm the write.'), detail: '' })
429
+ } finally {
430
+ busyKey = ''
431
+ inflight.delete(key)
432
+ notify()
433
+ }
434
+ })()
435
+ inflight.set(key, job)
436
+ return job
437
+ }
438
+
439
+ function requireSession(sessionId) {
440
+ const id = sessionId == null ? '' : String(sessionId)
441
+ if (!id) return failure({ kind: KIND.INVALID_RESPONSE, ambiguous: false, message: text('缺少会话 ID。', 'A session ID is required.') })
442
+ return null
443
+ }
444
+
445
+ async function reconcileSet(kind, sessionId, desired) {
446
+ const refreshed = await refreshHost('workspaces')
447
+ if (!refreshed) return { ok: false, reason: 'cannot-verify' }
448
+ const ids = kind === 'pin' ? host.pinned : host.archived
449
+ return { ok: ids.has(String(sessionId)) === desired, reason: 'read-back' }
450
+ }
451
+
452
+ async function pin(sessionId) {
453
+ const readOnly = requireWritable(); if (readOnly) return readOnly
454
+ const missing = requireSession(sessionId); if (missing) return missing
455
+ const id = String(sessionId)
456
+ if (host.pinned.has(id)) return success({ noop: true, method: 'workspace.pinSession' })
457
+ if (host.archived.has(id)) {
458
+ return failure({ kind: KIND.ARCHIVED_SESSION, ambiguous: false, code: 'workspace/archived-session', message: text('归档会话不能置顶;请先取消归档。', 'An archived conversation cannot be pinned; unarchive it first.') })
459
+ }
460
+ return runWrite({
461
+ key: 'pin:' + id,
462
+ method: 'workspace.pinSession',
463
+ payload: { sessionId: id },
464
+ verify: value => applyPinResult(value, id, 'pin'),
465
+ apply: verified => { host.pinned = new Set(verified.pinnedSessionIds) },
466
+ reconcile: () => reconcileSet('pin', id, true),
467
+ successMessage: text('已置顶,主机已保存;官方 DSH 和其他 Remote 重新加载后可见。', 'Pinned on the Host; official DSH and other Remote clients see it after reload.'),
468
+ refreshScope: 'workspaces',
469
+ resultExtra: { sessionId: id },
470
+ })
471
+ }
472
+
473
+ async function unpin(sessionId) {
474
+ const readOnly = requireWritable(); if (readOnly) return readOnly
475
+ const missing = requireSession(sessionId); if (missing) return missing
476
+ const id = String(sessionId)
477
+ if (!host.pinned.has(id)) return success({ noop: true, method: 'workspace.unpinSession' })
478
+ return runWrite({
479
+ key: 'unpin:' + id,
480
+ method: 'workspace.unpinSession',
481
+ payload: { sessionId: id },
482
+ verify: value => applyPinResult(value, id, 'unpin'),
483
+ apply: verified => { host.pinned = new Set(verified.pinnedSessionIds) },
484
+ reconcile: () => reconcileSet('pin', id, false),
485
+ successMessage: text('已取消置顶,主机已保存。', 'Unpinned on the Host.'),
486
+ refreshScope: 'workspaces',
487
+ resultExtra: { sessionId: id },
488
+ })
489
+ }
490
+
491
+ async function unarchive(sessionId) {
492
+ const readOnly = requireWritable(); if (readOnly) return readOnly
493
+ const missing = requireSession(sessionId); if (missing) return missing
494
+ const id = String(sessionId)
495
+ if (!host.archived.has(id)) return success({ noop: true, method: 'workspace.unarchiveSession' })
496
+ return runWrite({
497
+ key: 'unarchive:' + id,
498
+ method: 'workspace.unarchiveSession',
499
+ payload: { sessionId: id },
500
+ verify: value => applyUnarchiveResult(value, id),
501
+ apply: verified => { host.archived = new Set(verified.archivedSessionIds) },
502
+ reconcile: () => reconcileSet('archive', id, false),
503
+ successMessage: text('已取消归档,会话回到正常列表;主机已保存。', 'Unarchived on the Host; the conversation is back in the normal list.'),
504
+ refreshScope: 'sessions',
505
+ resultExtra: { sessionId: id },
506
+ })
507
+ }
508
+
509
+ async function renameWorkspace(workspaceId, rawTitle) {
510
+ const readOnly = requireWritable(); if (readOnly) return readOnly
511
+ const id = String(workspaceId == null ? '' : workspaceId)
512
+ const workspace = host.workspaces.find(item => item.workspaceId === id)
513
+ if (!workspace) return failure({ kind: KIND.NOT_FOUND, ambiguous: false, message: text('工作区不存在,可能已被移除。', 'The workspace does not exist; it may have been removed.') })
514
+ const validation = validateWorkspaceTitle(rawTitle, { workspaces: host.workspaces, currentWorkspaceId: id })
515
+ if (!validation.ok) return failure({ kind: validation.error === 'conflict' ? KIND.CONFLICT : KIND.FAILED, ambiguous: false, code: validation.error, message: validation.message })
516
+ return runWrite({
517
+ key: 'rename:' + id,
518
+ method: 'workspace.rename',
519
+ payload: { workspaceId: id, title: validation.title },
520
+ verify: value => applyRenameResult(value, id, validation.title),
521
+ apply: verified => {
522
+ const row = normalizeWorkspace(verified.workspace)
523
+ host.workspaces = host.workspaces.map(item => item.workspaceId === id ? row : item)
524
+ },
525
+ reconcile: async () => {
526
+ const refreshed = await refreshHost('workspaces')
527
+ if (!refreshed) return { ok: false, reason: 'cannot-verify' }
528
+ return { ok: !!host.workspaces.find(item => item.workspaceId === id && item.title === validation.title), reason: 'read-back' }
529
+ },
530
+ successMessage: text('工作区名称已更新,主机已保存。', 'Workspace name updated on the Host.'),
531
+ refreshScope: 'workspaces',
532
+ resultExtra: { workspaceId: id, title: validation.title },
533
+ })
534
+ }
535
+
536
+ function getWorkspaceImpact(workspaceId) {
537
+ const workspace = host.workspaces.find(item => item.workspaceId === String(workspaceId || ''))
538
+ if (!workspace) return null
539
+ return workspaceImpact(workspace, host.sessions, {
540
+ archivedSessionIds: [...host.archived],
541
+ pinnedSessionIds: [...host.pinned],
542
+ titleOf: adapter.titleOf,
543
+ })
544
+ }
545
+
546
+ async function removeWorkspace(workspaceId, options = {}) {
547
+ const readOnly = requireWritable(); if (readOnly) return readOnly
548
+ const id = String(workspaceId == null ? '' : workspaceId)
549
+ const workspace = host.workspaces.find(item => item.workspaceId === id)
550
+ if (!workspace) return failure({ kind: KIND.NOT_FOUND, ambiguous: false, message: text('工作区不存在,可能已被移除。', 'The workspace does not exist; it may have been removed.') })
551
+ const impact = getWorkspaceImpact(id)
552
+ const request = removeWorkspaceConfirmation(workspace, impact)
553
+ if (options.confirm !== false && options.confirmed !== true) {
554
+ if (typeof adapter.confirm !== 'function') {
555
+ return failure({ kind: KIND.CONFIRMATION_UNAVAILABLE, ambiguous: false, message: text('缺少移除确认,操作未执行。', 'No removal confirmation is available; nothing was removed.') })
556
+ }
557
+ const approved = await adapter.confirm(request)
558
+ if (!approved) return failure({ kind: KIND.CANCELLED, ambiguous: false, message: text('已取消移除。', 'Removal cancelled.') })
559
+ }
560
+ return runWrite({
561
+ key: 'delete:' + id,
562
+ method: 'workspace.delete',
563
+ payload: { workspaceId: id },
564
+ verify: value => applyDeleteResult(value),
565
+ apply: () => { host.workspaces = host.workspaces.filter(item => item.workspaceId !== id) },
566
+ reconcile: async () => {
567
+ const refreshed = await refreshHost('workspaces')
568
+ if (!refreshed) return { ok: false, reason: 'cannot-verify' }
569
+ return { ok: !host.workspaces.some(item => item.workspaceId === id), reason: 'read-back' }
570
+ },
571
+ successMessage: text(`已移除工作区登记「${workspace.name}」;会话与磁盘文件均未删除。`, `Removed the workspace registration "${workspace.name}"; conversations and files on disk were not deleted.`),
572
+ refreshScope: 'workspaces',
573
+ resultExtra: { workspaceId: id, impact },
574
+ })
575
+ }
576
+
577
+ const manager = {
578
+ hydrate,
579
+ getState: snapshot,
580
+ canWrite: writable,
581
+ isPinned: sessionId => host.pinned.has(String(sessionId == null ? '' : sessionId)),
582
+ isArchived: sessionId => host.archived.has(String(sessionId == null ? '' : sessionId)),
583
+ pin,
584
+ unpin,
585
+ unarchive,
586
+ renameWorkspace,
587
+ removeWorkspace,
588
+ getWorkspaceImpact,
589
+ validateWorkspaceTitle: (rawValue, workspaceId) => validateWorkspaceTitle(rawValue, { workspaces: host.workspaces, currentWorkspaceId: workspaceId || '' }),
590
+ get workspaces() { return host.workspaces.map(item => ({ ...item, sessionIds: item.sessionIds.slice() })) },
591
+ adapter,
592
+ }
593
+ hydrate()
594
+ return manager
595
+ }
596
+
597
+ function workspaceRowHtml(workspace, state) {
598
+ const disabled = state.canWrite ? '' : ' disabled'
599
+ const count = workspace.sessionIds.length
600
+ return `<li class="dr-session-admin-workspace" data-dr-session-admin-workspace="${esc(workspace.workspaceId)}">
601
+ <div class="dr-session-admin-workspace-info">
602
+ <span class="dr-session-admin-workspace-name">${esc(workspace.name)}</span>
603
+ <span class="dr-session-admin-workspace-path" title="${esc(workspace.path)}">${esc(workspace.path)}</span>
604
+ <span class="dr-session-admin-workspace-count">${esc(text(`${count} 个会话`, `${count} ${count === 1 ? 'conversation' : 'conversations'}`))}</span>
605
+ </div>
606
+ <div class="dr-session-admin-workspace-actions">
607
+ <button type="button" class="dr-session-admin-btn" data-dr-session-admin-action="rename-workspace" data-workspace-id="${esc(workspace.workspaceId)}"${disabled}>${esc(text('重命名', 'Rename'))}</button>
608
+ <button type="button" class="dr-session-admin-btn dr-session-admin-btn-danger" data-dr-session-admin-action="remove-workspace" data-workspace-id="${esc(workspace.workspaceId)}"${disabled}>${esc(text('移除登记', 'Remove registration'))}</button>
609
+ </div>
610
+ </li>`
611
+ }
612
+
613
+ /** Markup for the workspace management section (rename + registration removal). */
614
+ function renderWorkspaceAdminHtml(state = {}) {
615
+ const workspaces = Array.isArray(state.workspaces) ? state.workspaces : []
616
+ const rows = workspaces.length
617
+ ? `<ul class="dr-session-admin-workspaces">${workspaces.map(workspace => workspaceRowHtml(workspace, state)).join('')}</ul>`
618
+ : `<div class="dr-session-admin-empty">${esc(text('没有已登记的工作区。', 'No registered workspaces.'))}</div>`
619
+ const readOnly = state.canWrite === false
620
+ ? `<div class="dr-session-admin-readonly" role="note">${esc(text('只读/配对设备:不能重命名或移除工作区,也不会写入主机状态。', 'Read-only/paired device: rename and removal are disabled and nothing is written to the Host.'))}</div>`
621
+ : ''
622
+ return `<section class="dr-session-admin" data-dr-session-admin>
623
+ <div class="dr-session-admin-head">
624
+ <strong class="dr-session-admin-title">${esc(text('工作区管理', 'Workspace management'))}</strong>
625
+ <span class="dr-session-admin-hint">${esc(text('重命名与移除都写入主机;移除只删除登记,不删除磁盘目录、文件或会话历史。', 'Rename and removal are written to the Host. Removal deletes the registration only, not directories, files or conversation history on disk.'))}</span>
626
+ </div>
627
+ ${readOnly}
628
+ ${rows}
629
+ </section>`
630
+ }
631
+
632
+ /** Markup for per-session pin/unpin/unarchive actions. */
633
+ function renderSessionAdminActions(session, state = {}) {
634
+ if (!session || !session.sessionId) return ''
635
+ const sessionId = String(session.sessionId)
636
+ const archived = state.archivedSessionIds ? state.archivedSessionIds.map(String).includes(sessionId) : false
637
+ const pinned = state.pinnedSessionIds ? state.pinnedSessionIds.map(String).includes(sessionId) : false
638
+ const disabled = state.canWrite === false ? ' disabled' : ''
639
+ const buttons = []
640
+ if (archived) {
641
+ buttons.push(`<button type="button" class="dr-session-admin-btn" data-dr-session-admin-action="unarchive-session" data-session-id="${esc(sessionId)}"${disabled}>${esc(text('取消归档', 'Unarchive'))}</button>`)
642
+ } else {
643
+ buttons.push(pinned
644
+ ? `<button type="button" class="dr-session-admin-btn is-active" data-dr-session-admin-action="unpin-session" data-session-id="${esc(sessionId)}"${disabled}>${esc(text('取消置顶', 'Unpin'))}</button>`
645
+ : `<button type="button" class="dr-session-admin-btn" data-dr-session-admin-action="pin-session" data-session-id="${esc(sessionId)}"${disabled}>${esc(text('置顶', 'Pin'))}</button>`)
646
+ }
647
+ return `<span class="dr-session-admin-actions" data-dr-session-admin-actions data-session-id="${esc(sessionId)}">${buttons.join('')}</span>`
648
+ }
649
+
650
+ function bindWorkspaceAdmin(panel, manager, options = {}) {
651
+ if (!panel || typeof panel.addEventListener !== 'function') return () => {}
652
+ const redraw = () => {
653
+ try { if (typeof options.render === 'function') options.render() } catch {}
654
+ }
655
+ const onClick = async event => {
656
+ const target = event.target && event.target.closest ? event.target : null
657
+ if (!target) return
658
+ const control = target.closest('[data-dr-session-admin-action]')
659
+ if (!control || !control.dataset) return
660
+ const action = control.dataset.drSessionAdminAction
661
+ let result = null
662
+ if (action === 'rename-workspace') {
663
+ const workspace = manager.workspaces.find(item => item.workspaceId === control.dataset.workspaceId)
664
+ if (!workspace) return
665
+ let title = workspace.title
666
+ if (typeof options.promptTitle === 'function') {
667
+ title = await options.promptTitle({ workspace, current: workspace.title })
668
+ if (title == null) return
669
+ } else if (typeof manager.adapter.promptTitle === 'function') {
670
+ title = await manager.adapter.promptTitle({ workspace, current: workspace.title })
671
+ if (title == null) return
672
+ }
673
+ result = await manager.renameWorkspace(workspace.workspaceId, title)
674
+ } else if (action === 'remove-workspace') {
675
+ result = await manager.removeWorkspace(control.dataset.workspaceId)
676
+ } else if (action === 'pin-session' || action === 'unpin-session' || action === 'unarchive-session') {
677
+ const sessionId = control.dataset.sessionId
678
+ result = action === 'pin-session' ? await manager.pin(sessionId)
679
+ : action === 'unpin-session' ? await manager.unpin(sessionId)
680
+ : await manager.unarchive(sessionId)
681
+ }
682
+ if (result) {
683
+ try { if (typeof options.onResult === 'function') options.onResult(result, action) } catch {}
684
+ redraw()
685
+ }
686
+ }
687
+ panel.addEventListener('click', onClick)
688
+ return () => panel.removeEventListener('click', onClick)
689
+ }
690
+
691
+ function mountWorkspaceAdmin(container, manager, options = {}) {
692
+ const doc = options.document || root.document
693
+ if (!container || !doc || typeof doc.createElement !== 'function') return null
694
+ const element = doc.createElement('div')
695
+ element.className = 'dr-session-admin-host'
696
+ container.appendChild(element)
697
+ let destroyed = false
698
+ const paint = () => {
699
+ if (destroyed) return
700
+ element.innerHTML = renderWorkspaceAdminHtml(manager.getState())
701
+ }
702
+ paint()
703
+ const unbind = bindWorkspaceAdmin(element, manager, { ...options, render: paint })
704
+ return {
705
+ element,
706
+ refresh: paint,
707
+ destroy() { destroyed = true; unbind(); if (element.parentNode) element.parentNode.removeChild(element) },
708
+ }
709
+ }
710
+
711
+ const api = {
712
+ kinds: KIND,
713
+ esc,
714
+ text,
715
+ normalizeWorkspace,
716
+ sessionTitle,
717
+ sessionBelongsToWorkspace,
718
+ workspaceImpact,
719
+ validateWorkspaceTitle,
720
+ applyPinResult,
721
+ applyUnarchiveResult,
722
+ applyRenameResult,
723
+ applyDeleteResult,
724
+ classifyManagementError,
725
+ removeWorkspaceConfirmation,
726
+ createManager,
727
+ init: adapter => {
728
+ const manager = createManager(adapter)
729
+ instance = manager
730
+ return manager
731
+ },
732
+ renderWorkspaceAdminHtml,
733
+ renderSessionAdminActions,
734
+ bindWorkspaceAdmin,
735
+ mountWorkspaceAdmin,
736
+ get instance() { return instance },
737
+ }
738
+ let instance = null
739
+ Object.defineProperty(api, 'manager', { get: () => instance })
740
+ root.DshSessionManagement = api
741
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
742
+ })(typeof window !== 'undefined' ? window : globalThis)