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
package/public/app.js CHANGED
@@ -25,6 +25,7 @@ const CLIENT_ID = (() => {
25
25
  return id
26
26
  } catch { return '' }
27
27
  })()
28
+ let doctorSessionHandoff = false
28
29
  function clientIdHeaders() { return CLIENT_ID ? { 'x-dsh-remote-client-id': CLIENT_ID } : {} }
29
30
 
30
31
  /* 按连接身份隔离:本地缓存先显示,远端历史在后台校验与合并。 */
@@ -72,6 +73,8 @@ const state = {
72
73
  announcementIndex: 0,
73
74
  announcements: [],
74
75
  approvals: [], // 待处理审批
76
+ approvalRecords: new Map(), // 审批记录:审计事件(approval/asked+decided)与实时审批帧
77
+ approvalRecordsServer: null,
75
78
  questions: [], // 待处理提问
76
79
  queues: {}, // sessionId -> queue items
77
80
  queueSteering: {}, // sessionId:itemId -> pending steer request
@@ -367,7 +370,7 @@ function openDoctor() {
367
370
  loadTarget:()=>window.DshDoctorEntry.loadTarget({url:apiUrl,headers:{authorization:'Bearer '+accessToken},connection}),
368
371
  surface: 'mobile',
369
372
  rpc: (method, payload) => rpc(method, payload),
370
- openSession: id => openSession(id),
373
+ openSession: async id => { await openSession(id); return connection.valid() && state.current===id && !$('view-session').classList.contains('hidden') },
371
374
  workspaceId: () => workspaceForSession(state.byId.get(state.current))?.workspaceId || workspaceById(state.workspaceFilter)?.workspaceId || '',
372
375
  cwd: () => sessionCwd(state.byId.get(state.current)) || '',
373
376
  environment: doctorEnvironment,
@@ -377,14 +380,16 @@ function openDoctor() {
377
380
  toast,
378
381
  })
379
382
  }
380
- function openFeedbackModal() {
381
- state.feedbackType = 'bug'
382
- document.querySelectorAll('#fb-chips .fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
383
- $('fb-msg').value = ''
384
- $('fb-contact').value = ''
385
- $('fb-include-diagnostics').checked = false
386
- $('fb-include-crashes').checked = false
387
- $('fb-crash-details').open = false
383
+ function openFeedbackModal(options = {}) {
384
+ if (!options.preserveDraft) {
385
+ state.feedbackType = 'bug'
386
+ document.querySelectorAll('#fb-chips .fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
387
+ $('fb-msg').value = ''
388
+ $('fb-contact').value = ''
389
+ $('fb-include-diagnostics').checked = false
390
+ $('fb-include-crashes').checked = false
391
+ $('fb-crash-details').open = false
392
+ }
388
393
  void loadCrashPreview()
389
394
  $('modal-feedback').classList.remove('hidden')
390
395
  setTimeout(() => $('fb-msg').focus(), 50)
@@ -501,17 +506,22 @@ async function getWsTicket() {
501
506
  const server = state.server
502
507
  const job = (async () => {
503
508
  if (activeGatewayCapability('wsTicket') === false) throw Object.assign(new Error('ws ticket unsupported'), { unsupported: true })
504
- const res = await fetch(apiUrl('/api/ws-ticket'), {
505
- method: 'POST',
506
- signal: AbortSignal.timeout(8000),
507
- headers: {
508
- authorization: 'Bearer ' + token,
509
- 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web',
510
- ...clientIdHeaders(),
511
- }
512
- })
513
- if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
514
- const data = await res.json()
509
+ const read = async signal => {
510
+ const res = await fetch(apiUrl('/api/ws-ticket'), {
511
+ method: 'POST',
512
+ signal,
513
+ headers: {
514
+ authorization: 'Bearer ' + token,
515
+ 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web',
516
+ ...clientIdHeaders(),
517
+ }
518
+ })
519
+ if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
520
+ return res.json()
521
+ }
522
+ const data = await (globalThis.DshNetwork?.readWithDeadline
523
+ ? globalThis.DshNetwork.readWithDeadline(read,8000)
524
+ : read(AbortSignal.timeout(8000)))
515
525
  if (!connection.valid()) throw new Error('stale ws ticket')
516
526
  if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
517
527
  state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
@@ -602,6 +612,7 @@ async function safeRpc(method, payload, errText) {
602
612
  catch (e) {
603
613
  if (!connection.valid()) return null
604
614
  if (e.message === 'AUTH') authFailure()
615
+ else if (e.operationPending) toast(e.message, 'err')
605
616
  else toast(errText ? `${errText}:${e.message}` : e.message, 'err')
606
617
  return null
607
618
  }
@@ -1483,18 +1494,26 @@ async function pollKind(kind, cancellation) {
1483
1494
  const connection = captureConnection(), cursors = state.pollSeq
1484
1495
  const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1485
1496
  const since = state.pollSeq[kind] || 0
1486
- let res
1497
+ let res, data
1487
1498
  try {
1488
- const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1489
- const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1499
+ const timeoutMs = window.DshNetwork?.profile().pollTimeout || 30000
1490
1500
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1491
- res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1501
+ const read = async signal => {
1502
+ const response = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1503
+ return {res:response,data:response.ok ? await response.json() : null}
1504
+ }
1505
+ let result
1506
+ if(globalThis.DshNetwork?.readWithDeadline)result=await globalThis.DshNetwork.readWithDeadline(read,timeoutMs,cancellation)
1507
+ else {
1508
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined
1509
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1510
+ result=await read(signal)
1511
+ }
1512
+ res=result.res;data=result.data
1492
1513
  } catch { return }
1493
1514
  if (!valid()) return
1494
1515
  if (res.status === 401) { authFailure(); return }
1495
1516
  if (!res.ok) return
1496
- let data
1497
- try { data = await res.json() } catch { return }
1498
1517
  if (!valid()) return
1499
1518
  if (!data || !Array.isArray(data.events)) return
1500
1519
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
@@ -1606,10 +1625,11 @@ function onMuxFrame(full) {
1606
1625
  if (f.type === 'approval/requested') {
1607
1626
  state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
1608
1627
  state.approvals.push({ ...f, rpcId: full.rpcId })
1628
+ collectApprovalFrame(f)
1609
1629
  notifyPendingRequest(full, t('notify.approvalTitle'), t('notify.approvalBody', { tool: f.toolName || t('tool.unknown') }))
1610
1630
  renderPending(); return
1611
1631
  }
1612
- if (f.type === 'approval/resolved') { clearPendingNotification(f); state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderPending(); return }
1632
+ if (f.type === 'approval/resolved') { collectApprovalFrame(f); clearPendingNotification(f); state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderPending(); return }
1613
1633
  if (f.type === 'question/requested') {
1614
1634
  state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
1615
1635
  state.questions.push({ ...f, rpcId: full.rpcId })
@@ -1649,8 +1669,8 @@ function onHostFrame(full) {
1649
1669
  const s = state.byId.get(f.sessionId)
1650
1670
  if (s) { s.error = true; s.running = false }
1651
1671
  rememberRuntimeError(f.sessionId, f.message)
1652
- if (state.current === f.sessionId) { renderSessionSub(); updateSessionStatus() }
1653
- return toast(t('session.errorMsg', { msg: f.message }), 'err')
1672
+ if (state.current === f.sessionId) { renderSessionSub(); updateSessionStatus(); toast(t('session.errorMsg', { msg: f.message }), 'err') }
1673
+ return
1654
1674
  }
1655
1675
  if (f.type === 'host/remote-event') return scheduleRefresh()
1656
1676
  }
@@ -2842,10 +2862,12 @@ async function loadHistory(reset = true) {
2842
2862
  liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2843
2863
  hydrateSessionProjections(id,v.projections);history.loaded=true
2844
2864
  const incoming=v.events||[],prepared=[]
2865
+ let approvalChanged=false
2845
2866
  for (const entry of incoming) {
2846
2867
  const ev=entry?.event
2847
2868
  applyReasoningStreamEvent(ev)
2848
2869
  if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2870
+ if(collectApprovalEvent(id,ev))approvalChanged=true
2849
2871
  if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2850
2872
  prepared.push({seq:ev.seq,event:ev,view:entry.view})
2851
2873
  }
@@ -2862,6 +2884,7 @@ async function loadHistory(reset = true) {
2862
2884
  renderHistory(!hadContent,reset?'fixed':'keep')
2863
2885
  history.renderError=!!getConversationView().renderErrors
2864
2886
  historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
2887
+ if(approvalChanged)renderApprovalRecords()
2865
2888
  $('history-hint').textContent=t('history.count',{n:history.visible.filter(entry=>!['turn/start','turn/end'].includes(entry.event?.type)).length})
2866
2889
  diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
2867
2890
  if(!history.renderError)scheduleHistoryCacheSave()
@@ -2872,6 +2895,8 @@ async function loadHistory(reset = true) {
2872
2895
 
2873
2896
  function insertLiveEvent(event) {
2874
2897
  const h = state.history
2898
+ const approvalChanged = collectApprovalEvent(state.current, event)
2899
+ if (approvalChanged) renderApprovalRecords()
2875
2900
  const reasoningChanged = applyReasoningStreamEvent(event)
2876
2901
  if (event?.type === 'assistant/chunk' || event?.type === 'reasoning-chunks') {
2877
2902
  if (reasoningChanged) scheduleReasoningRender()
@@ -2926,10 +2951,12 @@ function bindTurnResultActions() {
2926
2951
  fork: payload => rpc('session.fork', payload),
2927
2952
  open: async (id, context) => {
2928
2953
  const parent = state.byId.get(context.sessionId)
2929
- try { await refreshSessions() } catch {} // A successful fork remains usable if the roster refresh fails.
2930
2954
  if (!context.valid()) return
2955
+ // The fork already returned a confirmed ID. Do not wait for a catalog
2956
+ // read before opening it: a reconnecting host can leave that read pending.
2931
2957
  if (!state.byId.has(id)) {
2932
- const branch = { ...parent, sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2958
+ const branch = { ...parent, projections: parent?.projections ? JSON.parse(JSON.stringify(parent.projections)) : undefined,
2959
+ sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2933
2960
  state.byId.set(id, branch)
2934
2961
  state.sessions.unshift(branch)
2935
2962
  renderSessions()
@@ -3100,6 +3127,10 @@ function eventHtml(entry, ctx = {}) {
3100
3127
  const name = (callId && ctx.toolNames?.get(callId)) || t('tool.result')
3101
3128
  const err = data.error || data.ok === false
3102
3129
  inner = `<details class="tool result ${err ? 'error' : ''}" data-seq="${seq}"><summary>📦 ${esc(name)}<span class="tool-meta-inline">${t('tool.result')}</span></summary><pre>${esc(truncate(safeJson(data.result ?? data.output ?? data.message ?? data), 4000))}</pre></details>`
3130
+ } else if (type === 'approval/asked') {
3131
+ const record = state.approvalRecords?.get(data.id)
3132
+ inner = record && window.DshApprovalRecords?.lineHtml(record, t)
3133
+ || `<div class="approval-event">🔐 ${esc(data.toolName || t('tool.default'))}</div>`
3103
3134
  } else if (type === 'agent/status') {
3104
3135
  const running = !!data.running
3105
3136
  inner = `<div class="event" data-seq="${seq}">${running ? t('event.taskStart') : t('event.taskEnd')}</div>`
@@ -3366,53 +3397,74 @@ async function downloadSessionExport(sessionId) {
3366
3397
  }
3367
3398
  }
3368
3399
 
3369
- async function runSlashCommand(text) {
3400
+ async function runSlashCommand(text, requireExecuted = false) {
3370
3401
  const clean = String(text || '').trim()
3371
3402
  if (!clean.startsWith('/') || !state.current) return false
3372
3403
  const sessionId = state.current, connection = captureConnection()
3373
3404
  const command = slashCommandName(clean)
3374
- const noFallback = NO_FALLBACK_SLASH_COMMANDS.has(command)
3375
- const longRunning = command === 'export'
3405
+ const noFallback = command === 'permission' || NO_FALLBACK_SLASH_COMMANDS.has(command)
3376
3406
  try {
3377
- const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
3378
- ? AbortSignal.timeout(longRunning ? LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS : SLASH_COMMAND_TIMEOUT_MS)
3379
- : undefined
3380
3407
  const res = await fetch(apiUrl('/remote/api/command'), {
3381
3408
  method: 'POST',
3382
3409
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
3383
3410
  body: JSON.stringify({ sessionId, line: clean, async: true }),
3384
- ...(signal ? { signal } : {})
3411
+ signal: AbortSignal.timeout(command === 'export' ? LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS : SLASH_COMMAND_TIMEOUT_MS),
3385
3412
  })
3386
- if (!connection.valid()) return true
3387
- if (res.status === 401) { authFailure(); return true }
3388
- if (!res.ok) {
3389
- if (noFallback) toast(t('session.commandTimedOut'), 'err')
3390
- return noFallback
3391
- }
3392
- const data = await res.json().catch(() => null)
3393
- if (!connection.valid()) return true
3394
- if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
3395
- if (data?.ok && data.executed === true) {
3396
- if (data.accepted) {
3397
- if (command === 'compact' || command === 'export') {
3398
- setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3399
- } else {
3400
- state.pendingCommands[sessionId] = command
3401
- setTimeout(() => { if (connection.valid() && state.current === sessionId) void refreshCompactionStatus(sessionId) }, 600)
3402
- }
3403
- } else if (command === 'export') await downloadSessionExport(sessionId)
3404
- else toast(t('send.commandExecuted'), 'ok')
3405
- return true
3413
+ if (!connection.valid() || (state.current !== sessionId && command !== 'compact' && command !== 'export')) return !requireExecuted
3414
+ if ([404, 405].includes(res.status) && !noFallback) return false
3415
+ if (res.status === 401) { authFailure(); return !requireExecuted }
3416
+ if (!res.ok) throw new Error('command response unavailable')
3417
+ const data = await res.json()
3418
+ if (!connection.valid() || (state.current !== sessionId && command !== 'compact' && command !== 'export')) return !requireExecuted
3419
+ if (!data?.ok) throw new Error('command rejected')
3420
+ if (data.executed === false) {
3421
+ if (!noFallback) return false
3422
+ throw new Error('control command not executed')
3406
3423
  }
3407
- } catch (e) {
3408
- if (!connection.valid() || state.current !== sessionId) return true
3409
- console.error('slash command bridge failed', e)
3410
- if (noFallback) {
3411
- toast(t('session.commandTimedOut'), 'err')
3412
- return true
3424
+ if (data.executed !== true) throw new Error('unknown command result')
3425
+ if (data.accepted) {
3426
+ if (command === 'compact' || command === 'export') {
3427
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3428
+ } else {
3429
+ state.pendingCommands ||= {}
3430
+ state.pendingCommands[sessionId] = command
3431
+ const result = await waitCommandOperation(sessionId, data.operation, connection)
3432
+ if (!connection.valid() || state.current !== sessionId) return !requireExecuted
3433
+ delete state.pendingCommands[sessionId]
3434
+ if (result.executed === false && !noFallback) return false
3435
+ if (result.phase !== 'complete' || result.executed === false) throw new Error('command did not complete')
3436
+ }
3437
+ } else if (command === 'export') await downloadSessionExport(sessionId)
3438
+ else if (!requireExecuted) toast(t('send.commandExecuted'), 'ok')
3439
+ return true
3440
+ } catch (error) {
3441
+ if (!connection.valid() || state.current !== sessionId) return !requireExecuted
3442
+ if (!requireExecuted) toast(t('session.commandTimedOut'), 'err')
3443
+ // A lost response may follow execution. Only explicit not-executed responses can fall back.
3444
+ return !requireExecuted
3445
+ }
3446
+ }
3447
+
3448
+ async function waitCommandOperation(sessionId, initial, connection) {
3449
+ if (!initial || !initial.startedAt) throw new Error('missing operation identity')
3450
+ const deadline = Date.now() + SLASH_COMMAND_TIMEOUT_MS
3451
+ let operation = initial
3452
+ while (Date.now() < deadline) {
3453
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale command')
3454
+ if (!operation.active) {
3455
+ if (!['complete', 'failed'].includes(operation.phase)) throw new Error('unknown operation')
3456
+ return operation
3413
3457
  }
3458
+ await new Promise(resolve => setTimeout(resolve, 100))
3459
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale command')
3460
+ const url = apiUrl('/remote/api/command-status') + '?sessionId=' + encodeURIComponent(sessionId)
3461
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + state.token, ...clientIdHeaders() }, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) })
3462
+ if (!res.ok) throw new Error('command status unavailable')
3463
+ const body = await res.json()
3464
+ operation = body?.operation
3465
+ if (body?.ok !== true || !operation || (initial.id ? operation.id !== initial.id : operation.startedAt !== initial.startedAt)) throw new Error('operation changed')
3414
3466
  }
3415
- return !connection.valid() || state.current !== sessionId
3467
+ throw new Error('command result unconfirmed')
3416
3468
  }
3417
3469
 
3418
3470
  function bytesToBase64(bytes) {
@@ -3625,6 +3677,7 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3625
3677
  if ((!clean && !images.length) || !state.current || composerSending) return false
3626
3678
  const sessionId = state.current
3627
3679
  const context = composerContext()
3680
+ const onboardingContext = window.DshOnboarding ? { connection: connectionGeneration, session: sessionId } : null
3628
3681
  const mode = requestedMode === 'steer' && (window.DshWorkflow?.isMounted() || steerSendingEnabled()) && composerIsBusy() ? 'steer' : 'queue'
3629
3682
  if (mode === 'steer' && clean.startsWith('/')) {
3630
3683
  setComposerSendFeedback(context, 'send.steerSlash', 'error')
@@ -3660,6 +3713,8 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3660
3713
  if (composerContext() !== context) return !!v?.accepted
3661
3714
  if (v?.accepted) {
3662
3715
  state.sessionActivity.add(sessionId)
3716
+ // Optional teaching UI must never turn a confirmed send into a failure.
3717
+ if (!clean.startsWith('/')) { try { window.DshOnboarding?.record('message-accepted', onboardingContext) } catch {} }
3663
3718
  if (composerContext() === context) {
3664
3719
  setSessionRecovery('ready')
3665
3720
  noteSessionTurnTime(sessionId, Date.now())
@@ -3715,7 +3770,37 @@ async function sendMessage(requestedMode) {
3715
3770
  function hideComposerMenu() {
3716
3771
  $('composer-menu').classList.add('hidden')
3717
3772
  $('btn-plus').classList.remove('active')
3718
- $('permission-submenu')?.classList.add('hidden')
3773
+ }
3774
+
3775
+ // 主机拥有权限模式(沙箱+审批捆绑)与可选目录;Remote 只按主机返回渲染,
3776
+ // 不为未安装或不存在的预设造选项。旧主机没有该目录时回退三种沙箱模式。
3777
+ // 目录直接作为“指令”列表中的权限模式行显示,Auto review 可用时同样出现在这里。
3778
+ function currentPermissionPreset() {
3779
+ const perms = state.current ? proj(state.byId.get(state.current), 'permissions') : null
3780
+ return typeof perms?.currentValue === 'string' ? perms.currentValue : ''
3781
+ }
3782
+
3783
+ let permissionPresetRequest = 0
3784
+ function refreshPermissionPresets() {
3785
+ const submenu = $('permission-submenu')
3786
+ if (!submenu || !window.DshPermissionPresets) return
3787
+ const request = ++permissionPresetRequest
3788
+ const sessionId = state.current
3789
+ const permissionConnection = captureConnection()
3790
+ void window.DshPermissionPresets.open({
3791
+ container: submenu,
3792
+ current: currentPermissionPreset(),
3793
+ connection: permissionConnection,
3794
+ currentValid: () => permissionConnection.valid() && state.current === sessionId && request === permissionPresetRequest,
3795
+ rpc,
3796
+ t,
3797
+ toast,
3798
+ request: async (value) => {
3799
+ if (!permissionConnection.valid() || !sessionId || state.current !== sessionId || request !== permissionPresetRequest) return false
3800
+ return runSlashCommand('/permission ' + value, true)
3801
+ },
3802
+ close: hideComposerMenu,
3803
+ })
3719
3804
  }
3720
3805
 
3721
3806
  function toggleComposerMenu() {
@@ -3723,6 +3808,7 @@ function toggleComposerMenu() {
3723
3808
  const show = menu.classList.contains('hidden')
3724
3809
  menu.classList.toggle('hidden', !show)
3725
3810
  $('btn-plus').classList.toggle('active', show)
3811
+ if (show) refreshPermissionPresets()
3726
3812
  if (show && !state.models.loaded && !state.models.loading) loadSessionModels()
3727
3813
  }
3728
3814
 
@@ -4138,6 +4224,7 @@ function renderOverview() {
4138
4224
  $('overview-attention-list').querySelectorAll('[data-overview-question]').forEach(btn => {
4139
4225
  btn.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === btn.dataset.overviewQuestion)))
4140
4226
  })
4227
+ renderApprovalRecords()
4141
4228
 
4142
4229
  const topSessions = topLevelSessions()
4143
4230
  const running = topSessions.filter(s => s.running).length
@@ -4177,6 +4264,60 @@ function renderOverview() {
4177
4264
  $('overview-session-list').querySelectorAll('[data-overview-session]').forEach(btn => btn.addEventListener('click', () => openSession(btn.dataset.overviewSession)))
4178
4265
  }
4179
4266
 
4267
+ /* ---------------- 审批记录 ---------------- */
4268
+ // 审批内容与结果来自会话审计事件(approval/asked + approval/decided)与实时审批帧;
4269
+ // 只记录主机已写日志的最小字段,不计模型 token,也不改写主机数据。
4270
+ const APPROVAL_RECORDS_KEY = 'dshApprovalRecordsV1:'
4271
+ function approvalRecordsKey() { return APPROVAL_RECORDS_KEY + encodeURIComponent(String(state.server || '')) }
4272
+ function ensureApprovalRecords() {
4273
+ if (state.approvalRecordsServer === state.server) return
4274
+ flushApprovalRecords()
4275
+ state.approvalRecordsServer = state.server
4276
+ state.approvalRecords = window.DshApprovalRecords ? window.DshApprovalRecords.restore(LS.get(approvalRecordsKey(), '[]')) : new Map()
4277
+ }
4278
+ let approvalRecordsSaveTimer = null
4279
+ let approvalRecordsPendingSave = null
4280
+ function flushApprovalRecords() {
4281
+ clearTimeout(approvalRecordsSaveTimer); approvalRecordsSaveTimer = null
4282
+ const pending = approvalRecordsPendingSave; approvalRecordsPendingSave = null
4283
+ if (pending) { try { LS.set(pending.key, pending.value) } catch {} }
4284
+ }
4285
+ function resetApprovalRecords() {
4286
+ clearTimeout(approvalRecordsSaveTimer); approvalRecordsSaveTimer = null; approvalRecordsPendingSave = null
4287
+ state.approvalRecords = new Map(); state.approvalRecordsServer = state.server
4288
+ }
4289
+ function saveApprovalRecords() {
4290
+ if (!window.DshApprovalRecords) return
4291
+ clearTimeout(approvalRecordsSaveTimer)
4292
+ approvalRecordsPendingSave = { key: approvalRecordsKey(), value: window.DshApprovalRecords.serialize(state.approvalRecords) }
4293
+ approvalRecordsSaveTimer = setTimeout(flushApprovalRecords, 800)
4294
+ }
4295
+ function collectApprovalEvent(sessionId, event) {
4296
+ ensureApprovalRecords()
4297
+ if (!window.DshApprovalRecords?.fromEvent(state.approvalRecords, sessionId, event)) return false
4298
+ saveApprovalRecords()
4299
+ return true
4300
+ }
4301
+ function collectApprovalFrame(frame) {
4302
+ ensureApprovalRecords()
4303
+ if (!window.DshApprovalRecords?.fromFrame(state.approvalRecords, frame)) return false
4304
+ saveApprovalRecords()
4305
+ renderApprovalRecords()
4306
+ return true
4307
+ }
4308
+ function renderApprovalRecords() {
4309
+ const box = $('approval-records-list')
4310
+ if (!box) return
4311
+ ensureApprovalRecords()
4312
+ const api = window.DshApprovalRecords
4313
+ const rows = api ? api.list(state.approvalRecords, 8) : []
4314
+ const count = $('approval-records-count')
4315
+ if (count) count.textContent = rows.length ? t('pending.count', { n: rows.length }) : '—'
4316
+ box.innerHTML = rows.length
4317
+ ? rows.map(record => api.recordHtml(record, t, { session: titleOf(state.byId.get(record.sessionId)) })).join('')
4318
+ : '<div class="empty">' + t('approval.recordsEmpty') + '</div>'
4319
+ }
4320
+
4180
4321
  function renderPending() {
4181
4322
  const list = $('pending-list')
4182
4323
  const items = [
@@ -4473,6 +4614,12 @@ function fsPathInside(candidate, root) {
4473
4614
  }
4474
4615
 
4475
4616
  function resetFsForServer() {
4617
+ const upload = state.fs.upload
4618
+ if (upload) {
4619
+ upload.cancelled = true
4620
+ upload.controller?.abort()
4621
+ try { upload.xhr?.abort() } catch {}
4622
+ }
4476
4623
  state.fs.path = null
4477
4624
  state.fs.initial = null
4478
4625
  state.fs.loaded = false
@@ -4815,12 +4962,14 @@ async function cancelFsUpload() {
4815
4962
  const up = state.fs.upload
4816
4963
  if (!up) return
4817
4964
  up.cancelled = true
4965
+ up.controller?.abort()
4818
4966
  try { up.xhr?.abort() } catch {}
4819
4967
  try {
4820
4968
  await fetch(fsApiUrl('/upload-control', { path: up.path, name: up.name, session: up.session, action: 'cancel' }), {
4821
- method: 'POST', headers: fsHeaders()
4969
+ method: 'POST', headers: fsHeaders(), signal: AbortSignal.timeout(15000)
4822
4970
  })
4823
4971
  } catch {}
4972
+ if (state.fs.upload !== up) return
4824
4973
  state.fs.upload = null
4825
4974
  hideFsProgress()
4826
4975
  setFsButtons(false)
@@ -4859,8 +5008,8 @@ function uploadFsFile(file) {
4859
5008
  try { prev.xhr?.abort() } catch {}
4860
5009
  try {
4861
5010
  fetch(fsApiUrl('/upload-control', { path: prev.path, name: prev.name, session: prev.session, action: 'cancel' }), {
4862
- method: 'POST', headers: fsHeaders()
4863
- })
5011
+ method: 'POST', headers: fsHeaders(), signal: AbortSignal.timeout(15000)
5012
+ }).catch(() => {})
4864
5013
  } catch {}
4865
5014
  }
4866
5015
  const up = {
@@ -4872,7 +5021,11 @@ function uploadFsFile(file) {
4872
5021
  }
4873
5022
 
4874
5023
  async function runFsUpload(up) {
4875
- if (!up || !up.file) return
5024
+ if (!up || !up.file || up.active) return
5025
+ const connection = up.connection ||= captureConnection()
5026
+ const valid = () => connection.valid() && state.fs.upload === up && !up.cancelled
5027
+ if (!valid()) return
5028
+ up.controller = new AbortController()
4876
5029
  up.active = true
4877
5030
  up.cancelled = false
4878
5031
  up.paused = false
@@ -4914,34 +5067,46 @@ async function runFsUpload(up) {
4914
5067
  })
4915
5068
 
4916
5069
  const probe = async () => {
4917
- const res = await fetch(fsApiUrl('/upload-probe', { path: up.path, name: up.name, session: up.session, size: String(up.size) }), { headers: fsHeaders() })
4918
- if (res.status === 401) { fsAuthError(401); return null }
4919
- const json = await res.json().catch(() => ({}))
4920
- if (json.ok) up.offset = json.partialSize || 0
5070
+ const read = async signal => {
5071
+ const res = await fetch(fsApiUrl('/upload-probe', { path: up.path, name: up.name, session: up.session, size: String(up.size) }), { headers: fsHeaders(), signal })
5072
+ const json = await res.json()
5073
+ return { status: res.status, json }
5074
+ }
5075
+ const { status, json } = window.DshNetwork?.readWithDeadline
5076
+ ? await window.DshNetwork.readWithDeadline(read, window.DshNetwork.profile().readTimeout, up.controller.signal)
5077
+ : await read(AbortSignal.timeout(45000))
5078
+ if (!valid()) return null
5079
+ if (status === 401) { fsAuthError(401); return null }
5080
+ if (status !== 200 || !json.ok) throw new Error(json.error || ('HTTP ' + status))
5081
+ if (!Number.isSafeInteger(json.partialSize) || json.partialSize < 0 || json.partialSize > up.size) throw new Error('Invalid upload offset')
5082
+ up.offset = json.partialSize
4921
5083
  return json
4922
5084
  }
4923
5085
 
4924
5086
  let overwrite = false
4925
5087
  let wasResumed = false
5088
+ let offsetCorrections = 0
4926
5089
  let hasher = new SHA256()
4927
5090
  try {
4928
5091
  const info = await probe()
4929
- if (info === null || up.cancelled) return
5092
+ if (info === null || !valid()) return
4930
5093
  if (info.partialSize > 0) wasResumed = true
4931
5094
  if (info.targetExists && info.targetSize === up.size && !overwrite) {
4932
5095
  if (!confirm(t('fs.confirmOverwrite'))) { state.fs.upload = null; hideFsProgress(); setFsButtons(false); return }
4933
5096
  overwrite = true
4934
5097
  }
4935
5098
  if (up.offset > 0) await hashFsRange(up.file, hasher, 0, up.offset, up)
5099
+ if (!valid()) return
4936
5100
  showFsProgress(Math.round(up.offset / Math.max(1, up.size) * 100), up.offset, up.size)
4937
5101
 
4938
5102
  while (up.offset < up.size) {
4939
- if (up.cancelled) return
5103
+ if (!valid()) return
4940
5104
  const chunkSize = up.chunkSize || (window.DshNetwork?.profile().weak ? 256 * 1024 : FS_CHUNK_SIZE)
4941
5105
  const end = Math.min(up.offset + chunkSize, up.size)
4942
5106
  const blob = up.file.slice(up.offset, end)
4943
5107
  const before = hasher.clone()
4944
5108
  const chunkBytes = new Uint8Array(await blob.arrayBuffer())
5109
+ if (!valid()) return
4945
5110
  if (up.pauseRequested) {
4946
5111
  const err = new Error(t('fs.pausedErr')); err.code = 'PAUSED'; throw err
4947
5112
  }
@@ -4952,6 +5117,7 @@ async function runFsUpload(up) {
4952
5117
  if (overwrite) params.overwrite = '1'
4953
5118
  const startedAt = Date.now()
4954
5119
  const r = await uploadChunk(params, blob)
5120
+ if (!valid()) return
4955
5121
  const elapsed = Date.now() - startedAt
4956
5122
  up.chunkSize = elapsed > 15000 ? Math.max(65536, Math.floor(chunkSize / 2)) : elapsed < 2000 ? Math.min(FS_CHUNK_SIZE, chunkSize * 2) : chunkSize
4957
5123
  if (r.status === 401) { fsAuthError(401); return }
@@ -4976,8 +5142,10 @@ async function runFsUpload(up) {
4976
5142
  continue
4977
5143
  }
4978
5144
  if (r.status === 409 && r.json.error === 'offset-mismatch') {
4979
- hasher = before
4980
- await probe()
5145
+ if (++offsetCorrections > 3) throw new Error('Upload offset keeps changing; query progress before retrying')
5146
+ if (await probe() === null || !valid()) return
5147
+ hasher = new SHA256()
5148
+ if (up.offset > 0) await hashFsRange(up.file, hasher, 0, up.offset, up)
4981
5149
  continue
4982
5150
  }
4983
5151
  if (r.status === 422 && r.json.error === 'checksum-mismatch') {
@@ -4994,12 +5162,17 @@ async function runFsUpload(up) {
4994
5162
  const expected = hasher.hex()
4995
5163
  const params = { path: up.path, name: up.name, session: up.session, offset: String(up.offset), size: String(up.size), finish: '1', sha256: expected }
4996
5164
  if (overwrite) params.overwrite = '1'
4997
- const r = await uploadChunk(params, new Blob([]))
5165
+ if (!valid()) return
5166
+ if (up.pauseRequested) { const err = new Error(t('fs.pausedErr')); err.code = 'PAUSED'; throw err }
5167
+ let r = await uploadChunk(params, new Blob([]))
5168
+ if (!valid()) return
4998
5169
  if (r.status === 401) { fsAuthError(401); return }
4999
5170
  if (r.status === 409 && r.json.error === 'conflict') {
5000
5171
  if (!confirm(t('fs.confirmOverwrite2'))) { state.fs.upload = null; hideFsProgress(); setFsButtons(false); return }
5001
5172
  params.overwrite = '1'
5002
- return runFsUpload(up) // 目标冲突未写入, 重新走 probe + 空 finish
5173
+ r = await uploadChunk(params, new Blob([]))
5174
+ if (!valid()) return
5175
+ if (r.status === 401) { fsAuthError(401); return }
5003
5176
  }
5004
5177
  if (r.status === 422 && r.json.error === 'checksum-mismatch') {
5005
5178
  const err = new Error(t('fs.checksumCleared'))
@@ -5023,7 +5196,7 @@ async function runFsUpload(up) {
5023
5196
  setFsButtons(false)
5024
5197
  } catch (e) {
5025
5198
  up.active = false
5026
- if (up.cancelled || e?.code === 'CANCELLED') return
5199
+ if (!valid() || e?.code === 'CANCELLED') return
5027
5200
  if (e?.code === 'PAUSED') {
5028
5201
  up.paused = true
5029
5202
  setFsButtons(true, true)
@@ -5048,6 +5221,8 @@ async function runFsUpload(up) {
5048
5221
  up.paused = true
5049
5222
  setFsButtons(true, true)
5050
5223
  toast(t('fs.uploadInterrupted', { msg: e.message }), 'err')
5224
+ } finally {
5225
+ up.active = false
5051
5226
  }
5052
5227
  }
5053
5228
 
@@ -7200,6 +7375,7 @@ function initToken() {
7200
7375
  state.token = LS.get('token', '')
7201
7376
  }
7202
7377
  loadServers()
7378
+ doctorSessionHandoff = window.DshDoctorEntry?.restoreSessionConnection?.({state,newId:newServerId,persist:()=>{LS.set('token',state.token);saveServers()}}) === true
7203
7379
  if (urlToken) {
7204
7380
  state.token = normalizedServerToken(urlToken)
7205
7381
  LS.set('token', state.token)
@@ -7755,12 +7931,6 @@ function bindUi() {
7755
7931
  $('composer-menu').addEventListener('click', async (e) => {
7756
7932
  const chip = e.target.closest('[data-cmd]')
7757
7933
  if (chip) {
7758
- if (chip.dataset.cmd === '/permission') {
7759
- const submenu = $('permission-submenu')
7760
- submenu?.classList.toggle('hidden')
7761
- return
7762
- }
7763
- $('permission-submenu')?.classList.add('hidden')
7764
7934
  const input = $('composer-input')
7765
7935
  input.value = chip.dataset.cmd + ' '
7766
7936
  input.focus()
@@ -7768,15 +7938,6 @@ function bindUi() {
7768
7938
  hideComposerMenu()
7769
7939
  return
7770
7940
  }
7771
- const perm = e.target.closest('[data-perm]')
7772
- if (perm) {
7773
- const input = $('composer-input')
7774
- input.value = '/permission ' + perm.dataset.perm + ' '
7775
- input.focus()
7776
- autosize(input)
7777
- hideComposerMenu()
7778
- return
7779
- }
7780
7941
  const preset = e.target.closest('[data-preset]')
7781
7942
  if (preset) {
7782
7943
  const found = readPresets().find(x => x.id === preset.dataset.preset)
@@ -8064,7 +8225,7 @@ async function boot() {
8064
8225
  $('token-desc').textContent = t('token.notSetHint')
8065
8226
  } else {
8066
8227
  // 多服务器: 启动时静默测速一次, 选最快的连接(同源页面也参与比较)
8067
- await selectFastestServer({ silent: true, reconnect: false })
8228
+ if (!doctorSessionHandoff) await selectFastestServer({ silent: true, reconnect: false })
8068
8229
  await maybeWarnAppBehindGateway({ probe: true })
8069
8230
  overviewStarting=false
8070
8231
  openStreams()
@@ -8116,6 +8277,8 @@ function mountWorkflow() {
8116
8277
  if (!cwd) return toast('当前会话没有工作目录', 'err')
8117
8278
  state.fs.loaded = true; showView('view-files'); void loadFs(cwd, { resetRoot: true })
8118
8279
  },
8280
+ approvalRecords: renderApprovalRecords,
8281
+ clearApprovalRecords: resetApprovalRecords,
8119
8282
  clear: clearWorkflowData,
8120
8283
  admin: () => {
8121
8284
  const url = new URL(adminApiUrl('/admin/'), location.href)
@@ -8129,6 +8292,37 @@ function mountWorkflow() {
8129
8292
  if (row.sessionId === state.current) void resyncCurrentSession()
8130
8293
  },
8131
8294
  })
8295
+ mountOnboarding()
8296
+ }
8297
+
8298
+ function mountOnboarding() {
8299
+ window.DshOnboarding?.mount({
8300
+ snapshot: () => ({ connection: connectionGeneration, session: state.current,
8301
+ connected: navigator.onLine !== false && !!state.token && dshReachable()
8302
+ && (!!state.streamsOk?.mux || (state.streamMode === 'poll' && !!state.hostInfo)),
8303
+ sessionReady: state.sessionRecovery.status === 'ready' && !state.history.loading }),
8304
+ actions: {
8305
+ connect: () => { showView('view-settings'); showSettingsPage('servers') },
8306
+ session: () => { showView('view-home'); return newSession() },
8307
+ message: () => { if (state.current) showView('view-session'); else { showView('view-home'); return newSession() } },
8308
+ results: () => window.DshWorkflow?.showOperations(),
8309
+ files: () => showView('view-files'),
8310
+ branch: () => { if (state.current) showView('view-session'); else showView('view-home') },
8311
+ doctor: openDoctor,
8312
+ feedback: () => openFeedbackModal({ preserveDraft: true }),
8313
+ },
8314
+ example: value => {
8315
+ const input = $('composer-input')
8316
+ if (!state.current || input.value.trim()) return false
8317
+ input.value = value
8318
+ input.dispatchEvent(new Event('input', { bubbles: true }))
8319
+ showView('view-session'); input.focus()
8320
+ return true
8321
+ },
8322
+ closePractice: () => {
8323
+ closeNewSessionModal(); closeFeedbackModal(); window.DshWorkflow?.close()
8324
+ },
8325
+ })
8132
8326
  }
8133
8327
 
8134
8328
  async function clearWorkflowData(kind) {
@@ -8171,6 +8365,11 @@ function openPluginPage(route = 'manage') {
8171
8365
  connection,getWorkspaces: () => workspaceItems(),
8172
8366
  getWorkspaceId: () => workspaceById(state.workspaceFilter)?.workspaceId || workspaceForSession(state.byId.get(state.current))?.workspaceId || '',
8173
8367
  openTeamCaptain: async id => { if (!connection.valid()) return; await openSession(id) },
8368
+ openTaskSession: async (id, workspaceId) => {
8369
+ if (!connection.valid() || $('view-plugins').classList.contains('hidden')) return
8370
+ if (!workspaceItems().some(row => row.workspaceId === workspaceId)) throw Error('unavailable')
8371
+ await openSession(id)
8372
+ },
8174
8373
  openTeamMember: async (id, parentId) => {
8175
8374
  const selected = state.current
8176
8375
  const catalog = await loadSessionSubagents(parentId)