dsh-remote-plugin 0.8.0-rc.8 → 0.8.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 (58) hide show
  1. package/README.en.md +12 -5
  2. package/README.md +12 -5
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +402 -165
  5. package/index.mjs +49 -20
  6. package/insights.mjs +33 -2
  7. package/package.json +2 -1
  8. package/plugin-center.mjs +12 -3
  9. package/plugin-transaction.mjs +18 -2
  10. package/public/admin.html +1 -1
  11. package/public/admin.js +2 -1
  12. package/public/app.js +296 -97
  13. package/public/approval-records.js +229 -0
  14. package/public/build.json +2 -2
  15. package/public/desktop/desktop.css +53 -1
  16. package/public/desktop/desktop.html +40 -2
  17. package/public/desktop/desktop.js +197 -60
  18. package/public/doctor-entry.js +33 -4
  19. package/public/doctor.js +41 -13
  20. package/public/extensions.css +96 -1
  21. package/public/extensions.js +43 -5
  22. package/public/index.html +45 -9
  23. package/public/insights.css +5 -0
  24. package/public/insights.js +40 -11
  25. package/public/md.js +7 -1
  26. package/public/onboarding.css +36 -0
  27. package/public/onboarding.js +253 -0
  28. package/public/operations.js +1 -1
  29. package/public/permission-presets.js +159 -0
  30. package/public/plugin-center.css +3 -0
  31. package/public/plugin-center.js +58 -9
  32. package/public/plugin.html +1 -1
  33. package/public/plugin.js +5 -1
  34. package/public/skills.js +16 -5
  35. package/public/skins/blue-fish/skin.css +51 -0
  36. package/public/styles.css +43 -1
  37. package/public/task-board.js +109 -0
  38. package/public/teams.js +35 -13
  39. package/public/theme.js +5 -11
  40. package/public/turn-results.js +2 -0
  41. package/public/update.json +8 -8
  42. package/public/version.json +1 -1
  43. package/public/workflow.css +6 -12
  44. package/public/workflow.js +13 -4
  45. package/skills/dsh-remote-doctor/SKILL.md +16 -0
  46. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  47. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  48. package/skills/dsh-remote-doctor/references/wiki/connection.md +74 -0
  49. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  50. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  51. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  52. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  53. package/skills/dsh-remote-doctor/references/wiki/notifications.md +29 -0
  54. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  55. package/skills/dsh-remote-doctor/references/wiki/plugins.md +69 -0
  56. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  57. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  58. package/task-board.mjs +57 -0
@@ -22,6 +22,7 @@ const CLIENT_ID = (() => {
22
22
  return id
23
23
  } catch { return '' }
24
24
  })()
25
+ let doctorSessionHandoff = false
25
26
  function clientIdHeaders() { return CLIENT_ID ? { 'x-dsh-remote-client-id': CLIENT_ID } : {} }
26
27
  const CAP = window.Capacitor || null
27
28
 
@@ -35,14 +36,12 @@ const THEME_META = [
35
36
  { id: 'fish', sw: ['#EAF6FF', '#FFFFFF', '#2F52D0'] }
36
37
  ]
37
38
  function themeGet() {
38
- let v = LS.get('dshTheme', '')
39
- if (!THEME_META.some(m => m.id === v)) v = ''
40
- return v
39
+ const v = LS.get('dshTheme', '')
40
+ return THEME_META.some(m => m.id === v) ? v : 'fish'
41
41
  }
42
42
  function themeApply() {
43
43
  const v = themeGet()
44
- if (!v) document.documentElement.removeAttribute('data-theme')
45
- else document.documentElement.setAttribute('data-theme', v)
44
+ document.documentElement.setAttribute('data-theme', v)
46
45
  const meta = THEME_META.find(m => m.id === v) || THEME_META[0]
47
46
  const btn = $('btn-theme')
48
47
  if (btn) btn.textContent = t('ds.theme.' + meta.id)
@@ -77,6 +76,8 @@ const state = {
77
76
  hostInfo: null,
78
77
  history: emptyDesktopHistory(),
79
78
  approvals: [],
79
+ approvalRecords: new Map(),
80
+ approvalRecordsServer: null,
80
81
  questions: [],
81
82
  queues: {},
82
83
  sessionActivity: new Set(),
@@ -289,7 +290,37 @@ function togglePresetMenuDesktop() {
289
290
  function toggleCmdMenuDesktop() {
290
291
  const menu = $('cmd-menu')
291
292
  if (!menu) return
292
- menu.classList.toggle('hidden')
293
+ const willOpen = menu.classList.contains('hidden')
294
+ if (willOpen) void refreshPermissionPresetsDesktop()
295
+ menu.classList.toggle('hidden', !willOpen)
296
+ }
297
+
298
+ /* 主机权限模式(沙箱+审批捆绑)目录;直接列在“指令”菜单里,旧主机回退三种沙箱模式。 */
299
+ function currentPermissionPreset() {
300
+ const perms = state.current ? proj(state.byId.get(state.current), 'permissions') : null
301
+ return typeof perms?.currentValue === 'string' ? perms.currentValue : ''
302
+ }
303
+ let permissionPresetRequest = 0
304
+ function refreshPermissionPresetsDesktop() {
305
+ const box = $('cmd-perm-inline')
306
+ if (!box || !window.DshPermissionPresets) return
307
+ const request = ++permissionPresetRequest
308
+ const sessionId = state.current
309
+ const permissionConnection = captureConnection()
310
+ return window.DshPermissionPresets.open({
311
+ container: box,
312
+ current: currentPermissionPreset(),
313
+ connection: permissionConnection,
314
+ currentValid: () => permissionConnection.valid() && state.current === sessionId && request === permissionPresetRequest,
315
+ rpc,
316
+ t,
317
+ toast,
318
+ request: async value => {
319
+ if (!permissionConnection.valid() || !sessionId || state.current !== sessionId || request !== permissionPresetRequest) return false
320
+ return runSlashCommand('/permission ' + value, true)
321
+ },
322
+ close: () => { $('cmd-menu')?.classList.add('hidden') },
323
+ })
293
324
  }
294
325
 
295
326
  /* ---------------- 模型 / 思考深度 ---------------- */
@@ -477,7 +508,7 @@ function openDoctor() {
477
508
  loadTarget:()=>window.DshDoctorEntry.loadTarget({url:apiUrl,headers:{authorization:'Bearer '+accessToken},connection}),
478
509
  surface: 'desktop',
479
510
  rpc: (method, payload) => rpc(method, payload),
480
- openSession: id => openSession(id),
511
+ openSession: async id => { await openSession(id); return connection.valid() && state.current===id && !$('view-chat').classList.contains('hidden') },
481
512
  workspaceId: workspace?.workspaceId || '',
482
513
  cwd: cwd || '',
483
514
  environment: doctorEnvironment,
@@ -686,13 +717,18 @@ async function getWsTicket() {
686
717
  const server = state.server
687
718
  const job = (async () => {
688
719
  if (activeGatewayCapability('wsTicket') === false) throw Object.assign(new Error('ws ticket unsupported'), { unsupported: true })
689
- const res = await fetch(apiUrl('/api/ws-ticket'), {
690
- method: 'POST',
691
- signal: AbortSignal.timeout(8000),
692
- headers: { authorization: 'Bearer ' + token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
693
- })
694
- if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
695
- const data = await res.json()
720
+ const read = async signal => {
721
+ const res = await fetch(apiUrl('/api/ws-ticket'), {
722
+ method: 'POST',
723
+ signal,
724
+ headers: { authorization: 'Bearer ' + token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
725
+ })
726
+ if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
727
+ return res.json()
728
+ }
729
+ const data = await (globalThis.DshNetwork?.readWithDeadline
730
+ ? globalThis.DshNetwork.readWithDeadline(read,8000)
731
+ : read(AbortSignal.timeout(8000)))
696
732
  if (!connection.valid()) throw new Error('stale ws ticket')
697
733
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
698
734
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
@@ -753,6 +789,7 @@ async function safeRpc(method, payload, errText) {
753
789
  catch (e) {
754
790
  if (!connection.valid()) return null
755
791
  if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); return null }
792
+ if (e.operationPending) { toast(e.message, 'err'); return null }
756
793
  toast(errText ? `${errText}:${e.message}` : e.message, 'err')
757
794
  return null
758
795
  }
@@ -1469,18 +1506,26 @@ async function pollKind(kind, cancellation) {
1469
1506
  const connection = captureConnection(), cursors = state.pollSeq
1470
1507
  const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1471
1508
  const since = state.pollSeq[kind] || 0
1472
- let res
1509
+ let res, data
1473
1510
  try {
1474
- const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1475
- const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1511
+ const timeoutMs = window.DshNetwork?.profile().pollTimeout || 30000
1476
1512
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
1477
- res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1513
+ const read = async signal => {
1514
+ const response = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1515
+ return {res:response,data:response.ok ? await response.json() : null}
1516
+ }
1517
+ let result
1518
+ if(globalThis.DshNetwork?.readWithDeadline)result=await globalThis.DshNetwork.readWithDeadline(read,timeoutMs,cancellation)
1519
+ else {
1520
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined
1521
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1522
+ result=await read(signal)
1523
+ }
1524
+ res=result.res;data=result.data
1478
1525
  } catch { return }
1479
1526
  if (!valid()) return
1480
1527
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1481
1528
  if (!res.ok) return
1482
- let data
1483
- try { data = await res.json() } catch { return }
1484
1529
  if (!valid()) return
1485
1530
  if (!data || !Array.isArray(data.events)) return
1486
1531
  const reset = data.reset === true || (!!data.epoch && !!cursors[kind + 'Epoch'] && cursors[kind + 'Epoch'] !== data.epoch) || data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
@@ -1554,10 +1599,11 @@ function onMuxFrame(full) {
1554
1599
  if (f.type === 'approval/requested') {
1555
1600
  state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
1556
1601
  state.approvals.push({ ...f, rpcId: full.rpcId })
1602
+ collectApprovalFrame(f)
1557
1603
  renderNotifStack()
1558
1604
  return
1559
1605
  }
1560
- if (f.type === 'approval/resolved') { state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderNotifStack(); return }
1606
+ if (f.type === 'approval/resolved') { collectApprovalFrame(f); state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderNotifStack(); return }
1561
1607
  if (f.type === 'question/requested') {
1562
1608
  state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
1563
1609
  state.questions.push({ ...f, rpcId: full.rpcId })
@@ -1594,8 +1640,7 @@ function onHostFrame(full) {
1594
1640
  const s = state.byId.get(f.sessionId)
1595
1641
  if (s) { s.error = true; s.running = false }
1596
1642
  rememberRuntimeError(f.sessionId, f.message)
1597
- if (state.current === f.sessionId) { renderQueue(); updateComposerStatus() }
1598
- toast(String(f.message || ''), 'err')
1643
+ if (state.current === f.sessionId) { renderQueue(); updateComposerStatus(); toast(String(f.message || ''), 'err') }
1599
1644
  }
1600
1645
  }
1601
1646
  function activeCompaction(sessionId = state.current) {
@@ -1878,6 +1923,7 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
1878
1923
  LS.set(COLLAPSED_GOALS_KEY, JSON.stringify(next.slice(-100)))
1879
1924
  }
1880
1925
  function onSessionEvent(sessionId, event, meta = {}) {
1926
+ if (collectApprovalEvent(sessionId, event)) renderApprovalRecordsDesktop()
1881
1927
  observeCompactionEvent(sessionId, event, meta)
1882
1928
  const failedSession = state.byId.get(sessionId)
1883
1929
  if (event?.type === 'turn/end' && event.data?.reason?.kind === 'error' && failedSession) {
@@ -2243,10 +2289,12 @@ async function loadHistory(reset = true) {
2243
2289
  liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2244
2290
  hydrateSessionProjections(id,v.projections);history.loaded=true
2245
2291
  const incoming=v.events||[],prepared=[]
2292
+ let approvalChanged=false
2246
2293
  for (const entry of incoming) {
2247
2294
  const ev=entry?.event
2248
2295
  applyReasoningStreamEvent(ev)
2249
2296
  if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2297
+ if(collectApprovalEvent(id,ev))approvalChanged=true
2250
2298
  if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2251
2299
  prepared.push({seq:ev.seq,event:ev,view:entry.view})
2252
2300
  }
@@ -2263,6 +2311,7 @@ async function loadHistory(reset = true) {
2263
2311
  renderHistory(!hadContent,reset?'fixed':'keep')
2264
2312
  history.renderError=!!getConversationView().renderErrors
2265
2313
  historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
2314
+ if(approvalChanged)renderApprovalRecordsDesktop()
2266
2315
  diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
2267
2316
  if(!history.renderError)scheduleHistoryCacheSave()
2268
2317
  } catch(error) { failLoad(error,true) }
@@ -2431,7 +2480,11 @@ function eventHtml(entry) {
2431
2480
  const text = data.text || data.content || safeJson(data.message?.content ?? data)
2432
2481
  return `<details class="ds-tool"><summary>📦 ${esc(callId)}</summary><pre>${esc(safeJson(text))}</pre></details>`
2433
2482
  }
2434
- if (type === 'approval/asked') return `<div class="ds-tool">🔐 ${esc(t('ds.approvalTitle'))} · ${esc(data.toolName || '')}</div>`
2483
+ if (type === 'approval/asked') {
2484
+ const record = state.approvalRecords?.get(data.id)
2485
+ if (record && window.DshApprovalRecords) return window.DshApprovalRecords.lineHtml(record, t)
2486
+ return `<div class="approval-event">🔐 ${esc(data.toolName || t('ds.toolDefault'))}</div>`
2487
+ }
2435
2488
  if (type === 'question/asked') return `<div class="ds-tool">❓ ${esc(data.question || '')}</div>`
2436
2489
  return `<div class="ds-tool">${esc(type)}</div>`
2437
2490
  }
@@ -2450,10 +2503,11 @@ function bindTurnResultActions() {
2450
2503
  fork: payload => rpc('session.fork', payload),
2451
2504
  open: async (id, context) => {
2452
2505
  const parent = state.byId.get(context.sessionId)
2453
- try { await refreshSessions() } catch {} // A successful fork remains usable if the roster refresh fails.
2454
2506
  if (!context.valid()) return
2507
+ // A confirmed fork remains usable while the session catalog is stalled.
2455
2508
  if (!state.byId.has(id)) {
2456
- const branch = { ...parent, sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2509
+ const branch = { ...parent, projections: parent?.projections ? JSON.parse(JSON.stringify(parent.projections)) : undefined,
2510
+ sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2457
2511
  state.byId.set(id, branch)
2458
2512
  state.sessions.unshift(branch)
2459
2513
  renderSessions()
@@ -2670,52 +2724,74 @@ async function downloadSessionExport(sessionId) {
2670
2724
  }
2671
2725
  }
2672
2726
 
2673
- async function runSlashCommand(text) {
2727
+ async function runSlashCommand(text, requireExecuted = false) {
2674
2728
  const clean = String(text || '').trim()
2675
2729
  if (!clean.startsWith('/') || !state.current) return false
2676
2730
  const sessionId = state.current, connection = captureConnection()
2677
2731
  const command = slashCommandName(clean)
2678
- const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
2679
- const longRunning = command === 'export'
2732
+ const noFallback = command === 'permission' || NO_FALLBACK_SLASH_COMMANDS.has(command)
2680
2733
  try {
2681
- const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2682
- ? AbortSignal.timeout(longRunning ? LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS : SLASH_COMMAND_TIMEOUT_MS)
2683
- : undefined
2684
2734
  const res = await fetch(apiUrl('/remote/api/command'), {
2685
2735
  method: 'POST',
2686
2736
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2687
2737
  body: JSON.stringify({ sessionId, line: clean, async: true }),
2688
- ...(signal ? { signal } : {})
2738
+ signal: AbortSignal.timeout(command === 'export' ? LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS : SLASH_COMMAND_TIMEOUT_MS),
2689
2739
  })
2690
- if (!connection.valid()) return true
2691
- if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return true }
2692
- if (!res.ok) {
2693
- if (noFallback) toast(t('ds.commandTimedOut'), 'err')
2694
- return noFallback
2695
- }
2696
- const data = await res.json().catch(() => null)
2697
- if (!connection.valid()) return true
2698
- if (data?.ok === false) return true
2699
- if (data?.ok === true && data.executed === true) {
2700
- if (data.accepted) {
2701
- if (command === 'compact' || command === 'export') {
2702
- setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2703
- } else {
2704
- state.pendingCommands[sessionId] = command
2705
- setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
2706
- }
2707
- } else if (command === 'export') await downloadSessionExport(sessionId)
2708
- return true
2740
+ if (!connection.valid() || (state.current !== sessionId && command !== 'compact' && command !== 'export')) return !requireExecuted
2741
+ if ([404, 405].includes(res.status) && !noFallback) return false
2742
+ if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return !requireExecuted }
2743
+ if (!res.ok) throw new Error('command response unavailable')
2744
+ const data = await res.json()
2745
+ if (!connection.valid() || (state.current !== sessionId && command !== 'compact' && command !== 'export')) return !requireExecuted
2746
+ if (!data?.ok) throw new Error('command rejected')
2747
+ if (data.executed === false) {
2748
+ if (!noFallback) return false
2749
+ throw new Error('control command not executed')
2709
2750
  }
2710
- } catch (e) {
2711
- if (!connection.valid() || state.current !== sessionId) return true
2712
- console.error('slash command bridge failed', e)
2713
- if (noFallback) {
2714
- toast(t('ds.commandTimedOut'), 'err')
2715
- return true
2751
+ if (data.executed !== true) throw new Error('unknown command result')
2752
+ if (data.accepted) {
2753
+ if (command === 'compact' || command === 'export') {
2754
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2755
+ } else {
2756
+ state.pendingCommands ||= {}
2757
+ state.pendingCommands[sessionId] = command
2758
+ const result = await waitCommandOperation(sessionId, data.operation, connection)
2759
+ if (!connection.valid() || state.current !== sessionId) return !requireExecuted
2760
+ delete state.pendingCommands[sessionId]
2761
+ if (result.executed === false && !noFallback) return false
2762
+ if (result.phase !== 'complete' || result.executed === false) throw new Error('command did not complete')
2763
+ }
2764
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2765
+ else if (!requireExecuted) toast(t('ds.commandExecuted'), 'ok')
2766
+ return true
2767
+ } catch (error) {
2768
+ if (!connection.valid() || state.current !== sessionId) return !requireExecuted
2769
+ if (!requireExecuted) toast(t('ds.commandTimedOut'), 'err')
2770
+ // A lost response may follow execution. Only explicit not-executed responses can fall back.
2771
+ return !requireExecuted
2772
+ }
2773
+ }
2774
+
2775
+ async function waitCommandOperation(sessionId, initial, connection) {
2776
+ if (!initial || !initial.startedAt) throw new Error('missing operation identity')
2777
+ const deadline = Date.now() + SLASH_COMMAND_TIMEOUT_MS
2778
+ let operation = initial
2779
+ while (Date.now() < deadline) {
2780
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale command')
2781
+ if (!operation.active) {
2782
+ if (!['complete', 'failed'].includes(operation.phase)) throw new Error('unknown operation')
2783
+ return operation
2716
2784
  }
2785
+ await new Promise(resolve => setTimeout(resolve, 100))
2786
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale command')
2787
+ const url = apiUrl('/remote/api/command-status') + '?sessionId=' + encodeURIComponent(sessionId)
2788
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + state.token, ...clientIdHeaders() }, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) })
2789
+ if (!res.ok) throw new Error('command status unavailable')
2790
+ const body = await res.json()
2791
+ operation = body?.operation
2792
+ if (body?.ok !== true || !operation || (initial.id ? operation.id !== initial.id : operation.startedAt !== initial.startedAt)) throw new Error('operation changed')
2717
2793
  }
2718
- return !connection.valid() || state.current !== sessionId
2794
+ throw new Error('command result unconfirmed')
2719
2795
  }
2720
2796
 
2721
2797
  async function sendMessage(requestedMode = 'queue') {
@@ -2896,6 +2972,58 @@ function renderSessionPendingDesktop() {
2896
2972
  box.querySelectorAll('[data-session-approve]').forEach(button => button.addEventListener('click', () => approveApproval(button.closest('[data-session-approval]')?.dataset.sessionApproval || '', button.dataset.sessionApprove === '1')))
2897
2973
  box.querySelectorAll('[data-session-question]').forEach(button => button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.dataset.sessionQuestion))))
2898
2974
  }
2975
+ /* ---------------- 审批记录 ---------------- */
2976
+ const APPROVAL_RECORDS_KEY = 'dshApprovalRecordsV1:'
2977
+ function approvalRecordsKey() { return APPROVAL_RECORDS_KEY + encodeURIComponent(String(state.server || '')) }
2978
+ function ensureApprovalRecords() {
2979
+ if (state.approvalRecordsServer === state.server) return
2980
+ flushApprovalRecords()
2981
+ state.approvalRecordsServer = state.server
2982
+ state.approvalRecords = window.DshApprovalRecords ? window.DshApprovalRecords.restore(LS.get(approvalRecordsKey(), '[]')) : new Map()
2983
+ }
2984
+ let approvalRecordsSaveTimer = null
2985
+ let approvalRecordsPendingSave = null
2986
+ function flushApprovalRecords() {
2987
+ clearTimeout(approvalRecordsSaveTimer); approvalRecordsSaveTimer = null
2988
+ const pending = approvalRecordsPendingSave; approvalRecordsPendingSave = null
2989
+ if (pending) { try { LS.set(pending.key, pending.value) } catch {} }
2990
+ }
2991
+ function resetApprovalRecords() {
2992
+ clearTimeout(approvalRecordsSaveTimer); approvalRecordsSaveTimer = null; approvalRecordsPendingSave = null
2993
+ state.approvalRecords = new Map(); state.approvalRecordsServer = state.server
2994
+ }
2995
+ function saveApprovalRecords() {
2996
+ if (!window.DshApprovalRecords) return
2997
+ clearTimeout(approvalRecordsSaveTimer)
2998
+ approvalRecordsPendingSave = { key: approvalRecordsKey(), value: window.DshApprovalRecords.serialize(state.approvalRecords) }
2999
+ approvalRecordsSaveTimer = setTimeout(flushApprovalRecords, 800)
3000
+ }
3001
+ function collectApprovalEvent(sessionId, event) {
3002
+ ensureApprovalRecords()
3003
+ if (!window.DshApprovalRecords?.fromEvent(state.approvalRecords, sessionId, event)) return false
3004
+ saveApprovalRecords()
3005
+ return true
3006
+ }
3007
+ function collectApprovalFrame(frame) {
3008
+ ensureApprovalRecords()
3009
+ if (!window.DshApprovalRecords?.fromFrame(state.approvalRecords, frame)) return false
3010
+ saveApprovalRecords()
3011
+ renderApprovalRecordsDesktop()
3012
+ return true
3013
+ }
3014
+ function renderApprovalRecordsDesktop() {
3015
+ const box = $('ds-approval-records-list')
3016
+ if (!box) return
3017
+ ensureApprovalRecords()
3018
+ const api = window.DshApprovalRecords
3019
+ const rows = api ? api.list(state.approvalRecords, 8) : []
3020
+ const count = $('ds-approval-records-count')
3021
+ if (count) count.textContent = rows.length ? t('ds.pendingCount', { n: rows.length }) : '—'
3022
+ box.innerHTML = rows.length
3023
+ ? rows.map(record => api.recordHtml(record, t, { session: titleOf(state.byId.get(record.sessionId)) })).join('')
3024
+ : '<div class="empty">' + t('approval.recordsEmpty') + '</div>'
3025
+ }
3026
+
2899
3027
  function renderNotifStack() {
2900
3028
  const stack = $('notif-stack')
2901
3029
  const items = [
@@ -3821,6 +3949,7 @@ function renderOverviewDesktop() {
3821
3949
  }).join('') : `<div class="ds-overview-empty">${t('ds.nothingPending')}</div>`
3822
3950
  $('ds-overview-attention-list').querySelectorAll('[data-ds-overview-approve]').forEach(btn => btn.addEventListener('click', () => approveApproval(btn.closest('[data-ds-overview-approval]')?.dataset.dsOverviewApproval || '', btn.dataset.dsOverviewApprove === '1')))
3823
3951
  $('ds-overview-attention-list').querySelectorAll('[data-ds-overview-question]').forEach(btn => btn.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === btn.dataset.dsOverviewQuestion))))
3952
+ renderApprovalRecordsDesktop()
3824
3953
 
3825
3954
  const topSessions = topLevelSessions()
3826
3955
  const running = topSessions.filter(s => s.running).length
@@ -3879,6 +4008,11 @@ function openDesktopPlugins(route = 'manage') {
3879
4008
  window.DshExtensions.mount({connection,getWorkspaces: () => state.workspaces || [],
3880
4009
  getWorkspaceId: () => (state.workspaces || []).find(w => (w.sessionIds || []).includes(state.current))?.workspaceId || '',
3881
4010
  openTeamCaptain: async id => { if (!connection.valid()) return; await openSession(id) },
4011
+ openTaskSession: async (id, workspaceId) => {
4012
+ if (!connection.valid() || state.view !== 'view-plugins') return
4013
+ if (!(state.workspaces || []).some(row => row.workspaceId === workspaceId)) throw Error('unavailable')
4014
+ await openSession(id)
4015
+ },
3882
4016
  openTeamMember: async (id, parentId) => {
3883
4017
  const selected = state.current
3884
4018
  const catalog = await loadSessionSubagents(parentId)
@@ -4262,6 +4396,7 @@ async function start() {
4262
4396
  history.replaceState(null, '', location.pathname)
4263
4397
  }
4264
4398
  loadServers()
4399
+ doctorSessionHandoff = window.DshDoctorEntry?.restoreSessionConnection?.({state,newId:newServerId,persist:()=>{LS.set('token',state.token);saveServers()}}) === true
4265
4400
  renderServers()
4266
4401
  showView(window.DshWorkflow?.isMounted() ? 'view-sessions' : 'view-overview')
4267
4402
  if (urlToken) {
@@ -4280,7 +4415,7 @@ async function start() {
4280
4415
  updateConn()
4281
4416
  checkNotesOnStart()
4282
4417
  if (state.token) {
4283
- await selectFastestServer({ silent: true, reconnect: false })
4418
+ if (!doctorSessionHandoff) await selectFastestServer({ silent: true, reconnect: false })
4284
4419
  overviewStarting=false
4285
4420
  openStreams()
4286
4421
  await Promise.all([refreshSessions(),refreshHostDescriptionDesktop()])
@@ -4316,6 +4451,8 @@ function mountWorkflowDesktop() {
4316
4451
  discover:()=>{if(confirm('登记当前绑定目录下的子目录为工作区?'))void refreshWorkbench({discover:true})},
4317
4452
  files:()=>{const cwd=sessionCwd(state.byId.get(state.current));if(!cwd)return toast('当前会话没有工作目录','err');state.fs.loaded=true;showView('view-files');void loadFs(cwd,true)},
4318
4453
  admin:()=>window.open(new URL(apiUrl('/admin/'),location.href).href,'_blank','noopener,noreferrer'),
4454
+ approvalRecords: renderApprovalRecordsDesktop,
4455
+ clearApprovalRecords: resetApprovalRecords,
4319
4456
  clear:async kind=>{
4320
4457
  const text=kind==='history'?'清除本机历史缓存?主机记录保留。':kind==='connection'?'移除当前地址和保存的凭证?其他连接条目保留。':'清除本机全部 Remote 配置与凭证?主机数据保留。'
4321
4458
  if(!confirm(text))return
@@ -1,7 +1,34 @@
1
1
  /* Doctor entry for the authenticated host panel and gateway management page. */
2
2
  'use strict'
3
3
  ;(function(root) {
4
- const uuid=()=>crypto.randomUUID?.() || Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)
4
+ const uuid=()=>globalThis.crypto?.randomUUID?.() || Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)
5
+ const HANDOFF_KEY='dshRemoteDoctorHandoffV1'
6
+ function saveSessionHandoff(sessionId,token) {
7
+ const value=JSON.stringify({sessionId,token,origin:location.origin,at:Date.now()})
8
+ try { root.sessionStorage.setItem(HANDOFF_KEY,value);if(root.sessionStorage.getItem(HANDOFF_KEY)===value)return } catch {}
9
+ throw Error('无法保存本次连接,请在该主机的会话列表查看诊断结果。')
10
+ }
11
+ function restoreSessionConnection({state,newId=uuid,persist=()=>{}}) {
12
+ let raw
13
+ try { raw=root.sessionStorage.getItem(HANDOFF_KEY);root.sessionStorage.removeItem(HANDOFF_KEY) } catch { return false }
14
+ if(!raw)return false
15
+ let handoff
16
+ try { handoff=JSON.parse(raw) } catch { return false }
17
+ if(!handoff || typeof handoff!=='object' || Array.isArray(handoff))return false
18
+ const sessionId=new URL(location.href).searchParams.get('sessionId'),age=Date.now()-handoff.at
19
+ if(handoff.origin!==location.origin || !/^https?:$/.test(location.protocol) || !/^[a-zA-Z0-9_-]{1,200}$/.test(sessionId||'')
20
+ || sessionId!==handoff.sessionId || !Number.isFinite(age) || age<0 || age>120000 || typeof handoff.token!=='string' || !handoff.token || handoff.token.length>4096)return false
21
+ // Adopt this explicit same-origin navigation without overwriting another
22
+ // saved identity or disabling the user's normal automatic selection policy.
23
+ let server=state.servers.find(row=>String(row.url||'').replace(/\/+$/,'')===handoff.origin && row.token===handoff.token)
24
+ if(!server){server={id:newId(),url:handoff.origin,token:handoff.token,note:'',group:state.activeGroup||'默认'};state.servers.unshift(server)}
25
+ const group=server.group||'默认'
26
+ if(!state.groups.includes(group))state.groups.push(group)
27
+ state.activeGroup=group;state.groupActive[group]=server.id
28
+ state.server=handoff.origin;state.token=handoff.token
29
+ persist()
30
+ return true
31
+ }
5
32
  async function loadTarget({url=route=>route,headers={},connection={valid:()=>true},pluginMode=false}={}) {
6
33
  if(!connection.valid())throw Error('Connection changed')
7
34
  const response=await fetch(url(pluginMode?'/remote/admin/api/doctor-target':'/remote/api/doctor/target'),{headers,credentials:'same-origin',signal:AbortSignal.timeout(15000)})
@@ -11,6 +38,7 @@
11
38
  return JSON.parse(text)
12
39
  }
13
40
  function open({state, pluginMode, token = () => '', copy, toast}) {
41
+ if(typeof root.DshDoctor?.open!=='function'){toast?.('诊疗组件未能加载,请刷新页面后重试。','err');return false}
14
42
  const initial = state() || {}, identity = initial.hostname || location.host, savedToken = token()
15
43
  const valid = () => !!state() && (state().hostname || location.host) === identity && token() === savedToken
16
44
  async function rpc(method, payload) {
@@ -23,7 +51,7 @@
23
51
  for (const route of routes) {
24
52
  const modern = route.includes('/')
25
53
  const response = await fetch('/api/' + route, {method:'POST', credentials:'same-origin',headers,
26
- body:JSON.stringify({type:'client-request',rpcId:id,method:route,payload:modern ? {args:{request:payload}} : payload}),signal:AbortSignal.timeout(30000)})
54
+ body:JSON.stringify({type:'client-request',rpcId:id,method:route,payload:modern ? {args:{request:method==='session.prompt'?{...payload,requestId:payload.requestId||id}:payload}} : payload}),signal:AbortSignal.timeout(30000)})
27
55
  if (!valid()) throw new Error('Connection changed')
28
56
  if ([404,405,501].includes(response.status) && route !== routes.at(-1)) { await response.body?.cancel(); continue }
29
57
  const body = await response.json()
@@ -47,8 +75,9 @@
47
75
  }
48
76
  // Web host tabs can return to DSH's recent conversations. Gateway
49
77
  // management tabs open the Remote conversation UI with a public ID only.
78
+ if(!valid())return
50
79
  if (pluginMode) location.assign('/')
51
- else location.assign('/?sessionId=' + encodeURIComponent(sessionId))
80
+ else { saveSessionHandoff(sessionId,savedToken);location.assign('/?sessionId=' + encodeURIComponent(sessionId)) }
52
81
  }
53
82
  root.DshDoctor.open({connection:{valid},rpc,openSession,surface:'management',copy,toast,
54
83
  loadTarget:()=>loadTarget({pluginMode,connection:{valid},headers:pluginMode?{}:{authorization:'Bearer '+savedToken,'x-dsh-remote-client':'admin'}}),
@@ -61,5 +90,5 @@
61
90
  url.searchParams.delete('sessionId');history.replaceState(null,'',url.pathname + url.search + url.hash)
62
91
  void openSession(id)
63
92
  }
64
- root.DshDoctorEntry = {open,loadTarget,consumeSessionLink}
93
+ root.DshDoctorEntry = {open,loadTarget,consumeSessionLink,restoreSessionConnection}
65
94
  })(window)
package/public/doctor.js CHANGED
@@ -29,6 +29,9 @@
29
29
  openIssue: '打开 GitHub Issue',
30
30
  start: '开始只读诊断',
31
31
  starting: '正在创建诊断会话…',
32
+ sending: '会话已创建,正在发送诊断请求…',
33
+ opening: '正在打开已创建的诊断会话…',
34
+ reopen: '打开诊断会话',
32
35
  close: '关闭',
33
36
  cancel: '取消',
34
37
  noSymptom: '请先描述问题现象,再开始诊断。',
@@ -47,6 +50,7 @@
47
50
  createdPromptCopied: '诊断会话已创建,但请求未发送;排查提示词已复制,请粘贴后发送。',
48
51
  createdPromptManual: '诊断会话已创建,但请求未发送;请在新会话中粘贴排查提示词。',
49
52
  started: '诊断会话已开始。它会先收集只读证据,再给出原因和反馈草稿。',
53
+ openFailed: '诊断会话已创建,但未能打开。可点击“打开诊断会话”重试,或在该主机的会话列表查看。{msg}',
50
54
  },
51
55
  en: {
52
56
  title: 'AI plugin diagnosis',
@@ -67,6 +71,9 @@
67
71
  openIssue: 'Open GitHub Issue',
68
72
  start: 'Start read-only diagnosis',
69
73
  starting: 'Creating diagnostic session…',
74
+ sending: 'Session created. Sending the diagnostic request…',
75
+ opening: 'Opening the created diagnostic conversation…',
76
+ reopen: 'Open diagnostic conversation',
70
77
  close: 'Close',
71
78
  cancel: 'Cancel',
72
79
  noSymptom: 'Describe the symptom before starting the diagnosis.',
@@ -85,6 +92,7 @@
85
92
  createdPromptCopied: 'The diagnostic session was created but the request was not sent. The prompt was copied; paste and send it.',
86
93
  createdPromptManual: 'The diagnostic session was created but the request was not sent. Paste the diagnostic prompt in the new session.',
87
94
  started: 'Diagnostic session started. It will collect read-only evidence, then explain the cause and prepare a feedback draft.',
95
+ openFailed: 'The diagnostic conversation was created but could not be opened. Retry with “Open diagnostic conversation” or find it in this host’s conversation list. {msg}',
88
96
  },
89
97
  }
90
98
  const ENV_LABELS = {
@@ -425,9 +433,9 @@
425
433
  if (!ui || !active) return
426
434
  const connected = connectionValid(active) && typeof active.rpc === 'function'
427
435
  const symptom = ui.symptom.value.trim()
428
- ui.start.disabled = !!active.busy || !connected || !symptom || active.targetLoading || (!!active.loadTarget && !active.target)
429
- ui.targetSelect.disabled = !!active.busy || !!active.targetLoading
430
- ui.start.textContent = active.busy ? strings().starting : strings().start
436
+ ui.start.disabled = !!active.busy || !connected || (!active.startedSessionId && (!symptom || active.targetLoading || (!!active.loadTarget && !active.target)))
437
+ ui.targetSelect.disabled = !!active.busy || !!active.targetLoading || !!active.startedSessionId
438
+ ui.start.textContent = active.busy ? (active.startedSessionId ? strings().opening : strings().starting) : active.startedSessionId ? strings().reopen : strings().start
431
439
  if (!preserveStatus) {
432
440
  if (!connected) setStatus(strings().disconnected, 'warn')
433
441
  else if (active.targetLoading) setStatus(language()==='en'?'Locating the loaded plugin…':'正在定位当前加载的插件…', '')
@@ -435,8 +443,8 @@
435
443
  else if (!symptom) setStatus(strings().noSymptom, '')
436
444
  else if (!active.busy) setStatus(strings().ready, '')
437
445
  }
438
- ui.include.disabled = !!active.busy
439
- ui.symptom.disabled = !!active.busy
446
+ ui.include.disabled = !!active.busy || !!active.startedSessionId
447
+ ui.symptom.disabled = !!active.busy || !!active.startedSessionId
440
448
  ui.copyPrompt.disabled = !!active.busy
441
449
  ui.copyDraft.disabled = !!active.busy
442
450
  }
@@ -529,6 +537,7 @@
529
537
  if (!ui || !active || active.busy) return
530
538
  const options = active
531
539
  const s = strings()
540
+ if(options.startedSessionId){await openStartedSession(options);return}
532
541
  const symptom = ui.symptom.value.trim()
533
542
  if (!symptom) {
534
543
  setStatus(s.noSymptom, 'err')
@@ -559,6 +568,7 @@
559
568
  if (!current()) return
560
569
  sessionId = short(created && created.sessionId, 200)
561
570
  if (!sessionId) throw new Error(s.createFailed)
571
+ setStatus(s.sending, 'pending')
562
572
  const value = await options.rpc('session.prompt', {
563
573
  sessionId,
564
574
  mode: 'queue',
@@ -566,20 +576,17 @@
566
576
  })
567
577
  if (!current()) return
568
578
  if (value && value.accepted === false) throw new Error(s.promptRejected)
569
- close()
570
- retainedSymptom = ''
571
- retainedInclude = false
572
- try { await options.openSession(sessionId) } catch {}
573
- toast(options, s.started, 'ok')
579
+ options.startedSessionId=sessionId
580
+ await openStartedSession(options)
574
581
  } catch (error) {
575
582
  if (!current()) return
576
583
  options.busy = false
577
584
  if (sessionId) {
578
585
  const copied = await copyWith(options, prompt)
579
586
  if (!current()) return
580
- close()
581
- try { await options.openSession(sessionId) } catch {}
582
- toast(options, copied ? s.createdPromptCopied : s.createdPromptManual, 'err')
587
+ options.startedSessionId=sessionId
588
+ options.fallbackNotice=copied ? s.createdPromptCopied : s.createdPromptManual
589
+ await openStartedSession(options)
583
590
  } else if (active === options) {
584
591
  setStatus(format(s.startFailed, { msg: short(error && error.message, 240) || 'unknown' }), 'err')
585
592
  }
@@ -589,6 +596,27 @@
589
596
  }
590
597
  }
591
598
 
599
+ async function openStartedSession(options) {
600
+ const current=()=>active===options && connectionValid(options)
601
+ if(!current()){if(active===options)updateStart();return}
602
+ options.busy=true
603
+ updateStart(true)
604
+ setStatus(strings().opening,'pending')
605
+ try {
606
+ const opened=await options.openSession(options.startedSessionId)
607
+ if(!current())return
608
+ if(opened===false)throw new Error(language()==='en'?'Conversation did not open.':'未能切换到诊断会话。')
609
+ close()
610
+ retainedSymptom='';retainedInclude=false
611
+ toast(options,options.fallbackNotice || strings().started,options.fallbackNotice ? 'err' : 'ok')
612
+ } catch(error) {
613
+ if(current())setStatus(format(strings().openFailed,{msg:short(error?.message,180)}),'err')
614
+ } finally {
615
+ options.busy=false
616
+ if(active===options)updateStart(connectionValid(options))
617
+ }
618
+ }
619
+
592
620
  function close() {
593
621
  if (!ui) return
594
622
  retainedSymptom = ui.symptom.value