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
@@ -40,7 +40,8 @@ const THEME_META = [
40
40
  { id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
41
41
  { id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
42
42
  { id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] },
43
- { id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] }
43
+ { id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] },
44
+ { id: 'miku', sw: ['#F3FFFC', '#FFFFFF', '#126D69'] }
44
45
  ]
45
46
  function themeGet() {
46
47
  const v = LS.get('dshTheme', '')
@@ -88,7 +89,6 @@ const state = {
88
89
  questions: [],
89
90
  queues: {},
90
91
  sessionActivity: new Set(),
91
- queueSteering: {},
92
92
  compactionBootAt: Date.now(),
93
93
  compactions: {},
94
94
  pendingCommands: {},
@@ -109,6 +109,7 @@ const state = {
109
109
  workspaces: [],
110
110
  wb: { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false },
111
111
  archivedIds: [],
112
+ pinnedIds: [],
112
113
  view: 'sessions',
113
114
  subagentSessions: {}
114
115
  }
@@ -133,10 +134,10 @@ for (const key of ['server', 'token']) {
133
134
  state.current = null; state.history = emptyDesktopHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
134
135
  state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
135
136
  state.approvals = []; state.questions = []; state.questionModal = null
136
- state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
137
+ state.queues = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
137
138
  state.sessionActivity = new Set()
138
139
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
139
- state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
140
+ state.workspaces = []; state.archivedIds = []; state.pinnedIds = []; state.wb = { bound: false, path: '', projects: null }
140
141
  window.DshPluginCenter?.close()
141
142
  window.DshInsights?.close()
142
143
  window.DshExtensions?.close()
@@ -763,19 +764,20 @@ async function rpc(method, payload = {}, timeoutMs = 45000, cancellation = null)
763
764
  else if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
764
765
  opts.signal = AbortSignal.timeout(timeoutMs)
765
766
  }
766
- const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
767
+ const operation = window.DshOperations?.supports(method) && (window.DshOperations.requiresReceipt?.(method) || activeGatewayCapability('operations') === true)
767
768
  const connection = operation ? captureConnection() : null
768
769
  const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
769
770
  const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
770
771
  diagnostic?.end({phase:'response',httpStatus:res.status})
771
772
  if (res.status === 401) throw new Error('AUTH')
772
- if (!res.ok) throw new Error('HTTP ' + res.status)
773
+ if (!res.ok) { const error = new Error('HTTP ' + res.status); error.status = res.status; throw error }
773
774
  const full = await res.json()
774
775
  if (!full?.result) throw new Error('bad response')
775
776
  if (!full.result.ok) {
776
777
  const err = full.result.error || {}
777
778
  const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || 'dsh error')
778
779
  error.code = err.code
780
+ error.rpcRejected = true
779
781
  throw error
780
782
  }
781
783
  diagnostic?.end({phase:'complete'})
@@ -952,22 +954,15 @@ function serverCandidates() {
952
954
  if (location.origin && !list.some(s => s.url === location.origin)) list.push({ id: 'origin', url: location.origin, token: state.token, origin: true })
953
955
  return list
954
956
  }
955
- async function pingServer(base) {
957
+ function pingServer(base, token) {
956
958
  const u = String(base || '').replace(/\/+$/, '')
957
- if (!u) return Infinity
958
- const t0 = performance.now()
959
- const ctrl = new AbortController()
960
- const timer = setTimeout(() => ctrl.abort(), 3500)
961
- try {
962
- const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
963
- if (!res.ok) return Infinity
964
- const health = await res.json().catch(() => null)
965
- if (health && typeof health === 'object') {
959
+ return DshNetwork.probeGateway(u, {
960
+ headers: token === undefined ? undefined : { authorization: token ? 'Bearer ' + token : '', 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
961
+ onHealth: health => {
966
962
  state.gatewayHealth[u] = health
967
963
  renderOverviewDesktop()
968
- }
969
- return Math.round(performance.now() - t0)
970
- } catch { return Infinity } finally { clearTimeout(timer) }
964
+ },
965
+ })
971
966
  }
972
967
  function activeGatewayCapability(name) {
973
968
  const capabilities = activeGatewayHealth()?.capabilities
@@ -1000,7 +995,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
1000
995
  let best = null
1001
996
  let ms = Infinity
1002
997
  if (state.autoSelect[state.activeGroup] !== false) {
1003
- const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
998
+ const measured = await Promise.all(candidates.map(async server => [server, await pingServer(server.url, server.token)]))
1004
999
  if (!valid()) return null
1005
1000
  for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
1006
1001
  best = candidates.filter(server => Number.isFinite(state.serverLatency[serverKey(server)])).sort((a, b) => state.serverLatency[serverKey(a)] - state.serverLatency[serverKey(b)])[0] || null
@@ -1618,6 +1613,7 @@ setInterval(sessionSyncTick, 15000)
1618
1613
  function onMuxFrame(full) {
1619
1614
  const f = full.payload
1620
1615
  if (!f) return
1616
+ if (typeof planReviewController !== 'undefined') planReviewController?.handleFrame?.(full)
1621
1617
  if (f.type === 'session/reasoning') {
1622
1618
  if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
1623
1619
  return
@@ -1634,22 +1630,37 @@ function onMuxFrame(full) {
1634
1630
  if (f.type === 'question/requested') {
1635
1631
  state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
1636
1632
  state.questions.push({ ...f, rpcId: full.rpcId })
1637
- renderNotifStack()
1633
+ renderNotifStack(); if (typeof refreshPlanReview === 'function') refreshPlanReview()
1638
1634
  return
1639
1635
  }
1640
1636
  if (f.type === 'question/resolved') {
1641
1637
  state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
1642
1638
  if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
1643
- renderNotifStack(); return
1639
+ renderNotifStack(); if (typeof refreshPlanReview === 'function') refreshPlanReview(); return
1640
+ }
1641
+ if (f.type === 'session/queue') {
1642
+ if (hostQueue?.accept(f.sessionId, f.seq) !== false) state.queues[f.sessionId] = f.items || []
1643
+ renderQueue(); return
1644
+ }
1645
+ if (f.type === 'session/projection') {
1646
+ applyProjection(f.sessionId, f.key, f.value, f.seq)
1647
+ if (f.key === 'plan' && f.sessionId === state.current && typeof refreshPlanReview === 'function') refreshPlanReview()
1648
+ if (f.key === 'conversationContinuation' && f.sessionId === state.current) renderHistory()
1649
+ if (f.key === 'agentTeam') window.DshSubagents?.updateTeam?.(f.sessionId, f.value, f.seq)
1650
+ return
1644
1651
  }
1645
- if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
1646
- if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
1647
1652
  if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
1648
1653
  if (f.type === 'session/stream-error' && f.sessionId === state.current) { const message=f.error?.code==='session/migration-required'?t('session.migrationRequired'):f.error?.message;setSessionRecovery('error',message);toast(message,'err') }
1649
1654
  }
1650
1655
  function onHostFrame(full) {
1651
1656
  const f = full.payload
1652
1657
  if (!f) return
1658
+ if (f.type === 'schedule/changed') { void hostSchedule?.refresh(true); return }
1659
+ if (f.type === 'host/pinned-sessions-changed') {
1660
+ state.pinnedIds = Array.isArray(f.pinnedSessionIds) ? f.pinnedSessionIds : []
1661
+ renderSessions()
1662
+ return
1663
+ }
1653
1664
  if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) scheduleSessionsRefresh()
1654
1665
  if (f.type === 'host/session-activity') {
1655
1666
  const session = state.byId.get(f.sessionId)
@@ -1866,8 +1877,10 @@ function rememberRuntimeError(sessionId, message) {
1866
1877
  if (sessionId === state.current) { renderHistory(); scheduleSessionSync(sessionId) }
1867
1878
  }
1868
1879
  function resyncAfterStreamOpen() {
1880
+ if (typeof hostSchedule !== 'undefined') void hostSchedule?.refresh(true)
1869
1881
  if (!state.current || Date.now() - state.lastStreamResyncAt < 1200) return
1870
1882
  state.lastStreamResyncAt = Date.now()
1883
+ if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
1871
1884
  void refreshSessions().then(() => resyncCurrentSession())
1872
1885
  }
1873
1886
  function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
@@ -1950,6 +1963,8 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
1950
1963
  LS.set(COLLAPSED_GOALS_KEY, JSON.stringify(next.slice(-100)))
1951
1964
  }
1952
1965
  function onSessionEvent(sessionId, event, meta = {}) {
1966
+ if (typeof planReviewController !== 'undefined') planReviewController?.handleEvent?.(sessionId, event)
1967
+ if (typeof turnDiffController !== 'undefined') turnDiffController?.handleEvent?.(sessionId, event)
1953
1968
  if (collectApprovalEvent(sessionId, event)) renderApprovalRecordsDesktop()
1954
1969
  observeCompactionEvent(sessionId, event, meta)
1955
1970
  const failedSession = state.byId.get(sessionId)
@@ -2016,6 +2031,7 @@ async function refreshSessions() {
2016
2031
  renderSessions()
2017
2032
  scheduleWorkbenchRefresh()
2018
2033
  renderOverviewDesktop()
2034
+ if (typeof sessionManager !== 'undefined') sessionManager?.hydrate?.()
2019
2035
  }
2020
2036
  function sessionCwd(s) { return typeof s?.cwd === 'string' ? s.cwd.trim() : '' }
2021
2037
  function sessionWorkspaceLabel(s) {
@@ -2048,15 +2064,19 @@ function workspaceDisplayName(label) {
2048
2064
  }
2049
2065
  function sortedSessions() {
2050
2066
  const items = topLevelSessions()
2067
+ const pinned = new Set(state.pinnedIds || [])
2068
+ const pinRank = session => pinned.has(session.sessionId) ? 0 : 1
2051
2069
  if (state.sessionSort === 'workspace') {
2052
2070
  return items.sort((a, b) => {
2071
+ const byPin = pinRank(a) - pinRank(b)
2072
+ if (byPin) return byPin
2053
2073
  const aw = sessionCwd(a) || '\uffff'
2054
2074
  const bw = sessionCwd(b) || '\uffff'
2055
2075
  const byWorkspace = aw.localeCompare(bw, undefined, { numeric: true, sensitivity: 'base' })
2056
2076
  return byWorkspace || (sessionSortTime(b) - sessionSortTime(a))
2057
2077
  })
2058
2078
  }
2059
- return items.sort((a, b) => sessionSortTime(b) - sessionSortTime(a))
2079
+ return items.sort((a, b) => pinRank(a) - pinRank(b) || sessionSortTime(b) - sessionSortTime(a))
2060
2080
  }
2061
2081
  function renderSessions() {
2062
2082
  const allItems = sortedSessions()
@@ -2064,6 +2084,7 @@ function renderSessions() {
2064
2084
  if (state.wb.bound && state.wb.projects) for (const w of state.wb.projects) for (const id of (w.sessionIds || [])) wbIds.add(id)
2065
2085
  const root = state.wb.bound ? state.wb.path : ''
2066
2086
  const archivedSet = new Set(state.archivedIds || [])
2087
+ const pinnedSet = new Set(state.pinnedIds || [])
2067
2088
  const visible = allItems.filter(s => {
2068
2089
  if (!state.wb.bound) return true
2069
2090
  if (archivedSet.has(s.sessionId)) return true
@@ -2077,7 +2098,7 @@ function renderSessions() {
2077
2098
  const workspaceName = workspaceDisplayName(workspace)
2078
2099
  const title = sessionLabelOf(s)
2079
2100
  return `<button class="ds-session-item ${state.current === s.sessionId ? 'current' : ''}" data-id="${esc(s.sessionId)}">
2080
- <span class="ds-session-title">${esc(title)}</span>
2101
+ <span class="ds-session-title">${pinnedSet.has(s.sessionId) ? '<span class="ds-session-pin" aria-label="' + esc(t('ds.pinnedSession')) + '">📌</span> ' : ''}${esc(title)}</span>
2081
2102
  <span class="ds-session-workspace" title="${esc(workspace)}">⌂ ${esc(workspaceName)}</span>
2082
2103
  <span class="ds-session-meta"><span class="ds-session-dot ${s.running ? 'running' : ''}"></span>${fmtTime(sessionSortTime(s))}</span>
2083
2104
  </button>`
@@ -2161,6 +2182,8 @@ async function openSession(id) {
2161
2182
  if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
2162
2183
  cancelHistoryLoad()
2163
2184
  state.current = id
2185
+ if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
2186
+ if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(id)
2164
2187
  setSessionRecovery('loading')
2165
2188
  state.history = emptyDesktopHistory()
2166
2189
  const openingHistory=state.history, openingConnection=captureConnection()
@@ -2174,6 +2197,7 @@ async function openSession(id) {
2174
2197
  renderSessionCards()
2175
2198
  renderQueue()
2176
2199
  renderSessionPendingDesktop()
2200
+ if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
2177
2201
  updateComposerStatus()
2178
2202
  void refreshCompactionStatus(id)
2179
2203
  try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
@@ -2198,6 +2222,10 @@ async function closeSession() {
2198
2222
  cancelHistoryLoad()
2199
2223
  const cleanup=sessionId&&!wasLoading&&state.history.loaded&&!state.history.loading&&!state.history.renderError
2200
2224
  state.current = null
2225
+ if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
2226
+ if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(null)
2227
+ if (typeof turnDiffController !== 'undefined') turnDiffController?.setSession?.(null)
2228
+ if (typeof planReviewHost !== 'undefined') planReviewHost?.classList.add('hidden')
2201
2229
  setSessionRecovery('idle')
2202
2230
  state.history = emptyDesktopHistory()
2203
2231
  showView('view-sessions')
@@ -2359,7 +2387,8 @@ const INTERESTING_EVENTS = new Set([
2359
2387
  'agent/status', 'checkpoint/created', 'compaction/complete', 'compaction/summary',
2360
2388
  'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
2361
2389
  'todo/updated', 'plan/updated', 'question/asked', 'question/resolved',
2362
- 'approval/asked', 'approval/resolved'
2390
+ 'approval/asked', 'approval/resolved',
2391
+ 'deliverables/presented', 'workspace/changes'
2363
2392
  ])
2364
2393
  function messageSource(data) {
2365
2394
  const source = data?.source ?? data?.message?.source
@@ -2471,9 +2500,11 @@ function eventHtml(entry) {
2471
2500
  const ev = entry.event || {}
2472
2501
  const data = ev.data || {}
2473
2502
  const type = ev.type || 'event'
2474
- const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev)) || ''
2503
+ const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev), false, entry.view?.continuation) || ''
2475
2504
  if (entry.view?.turnResult) return failure + window.DshTurnResults.html(entry.view.turnResult)
2476
- if (type === 'turn/start' || type === 'turn/end') return failure
2505
+ if (type === 'turn/start') return failure
2506
+ if (type === 'turn/end') return failure + (entry.view?.turnDiffHtml || '')
2507
+ if (type === 'deliverables/presented' || type === 'workspace/changes') return ''
2477
2508
  if (type === 'assistant/attempt') return window.DshActivity?.attemptHtml?.(ev) || ''
2478
2509
  if (entry.view?.activityTurn) return window.DshActivity.turnHtml(entry.view.activityTurn)
2479
2510
  if (entry.view?.activityGroup) return window.DshActivity.groupHtml(entry.view.activityGroup, eventHtml)
@@ -2491,7 +2522,7 @@ function eventHtml(entry) {
2491
2522
  if (type === 'user/message' && !isHumanUserMessage(ev)) return ''
2492
2523
  const text = blocks.map((block,index)=>blockHtml(block,index,{...data,seq:entry.seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
2493
2524
  if (!text) return ''
2494
- return `<div class="ds-msg ${esc(role)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
2525
+ return `<div class="ds-msg ${esc(role)}" data-seq="${esc(entry.seq)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
2495
2526
  }
2496
2527
  if (type === 'tool/call') {
2497
2528
  const name = data.name || data.toolName || t('ds.toolDefault')
@@ -2535,6 +2566,7 @@ function bindTurnResultActions() {
2535
2566
  if (!state.byId.has(id)) {
2536
2567
  const branch = { ...parent, projections: parent?.projections ? { ...JSON.parse(JSON.stringify(parent.projections)), asOfSeq: 0 } : undefined,
2537
2568
  sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2569
+ if (branch.projections?.values) delete branch.projections.values.conversationContinuation
2538
2570
  state.byId.set(id, branch)
2539
2571
  state.sessions.unshift(branch)
2540
2572
  renderSessions()
@@ -2559,12 +2591,36 @@ function renderHistory(reset=false, mode='auto') {
2559
2591
  prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
2560
2592
  bindTurnResultActions()
2561
2593
  }
2594
+ if (typeof turnDiffController !== 'undefined' && turnDiffController) {
2595
+ turnDiffController.setLayout('desktop')
2596
+ turnDiffController.setSession(state.current)
2597
+ if (typeof turnDiffHtmlFor === 'function') prepared = prepared.map(entry => ({ ...entry, view: { ...entry.view, turnDiffHtml: turnDiffHtmlFor(entry) } }))
2598
+ }
2599
+ if (activity?.withContinuation && activeGatewayCapability('sessionContinuation') === true) {
2600
+ const sessionId = state.current, history = state.history, connection = captureConnection()
2601
+ const session = state.byId.get(sessionId)
2602
+ prepared = activity.withContinuation($('history'), prepared, {
2603
+ history, ending: session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required'
2604
+ && !(state.archivedIds || []).includes(sessionId)
2605
+ ? proj(session, 'conversationContinuation') : undefined,
2606
+ valid: () => connection.valid() && state.current === sessionId && state.history === history,
2607
+ render: () => renderHistory(),
2608
+ submit: ending => rpc('session.continue', { sessionId, ending }),
2609
+ failed: error => {
2610
+ if (error.operationPending) notifyPendingOperation(error, connection)
2611
+ else if (connection.valid() && state.current === sessionId && state.history === history) {
2612
+ toast(error.message, 'err'); void resyncCurrentSession()
2613
+ }
2614
+ },
2615
+ })
2616
+ }
2562
2617
  if(window.DshActivity?.groupFailures)prepared=window.DshActivity.groupFailures(prepared)
2563
2618
  const hostError = state.runtimeErrors?.get(state.current)
2564
2619
  const recordedError = state.history.visible.some(entry => window.DshActivity?.failure?.(entry.event)?.message === hostError)
2565
2620
  const runtimeHtml = hostError && !recordedError ? window.DshActivity?.failureHtml?.(hostError) || '' : ''
2566
2621
  getConversationView().set(prepared,{reset,follow:mode==='bottom',live:(groupLive?'':partialReasoningHtml())+runtimeHtml,hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2567
2622
  window.DshImagePreview?.hydrate?.($('history'))
2623
+ if (typeof refreshPlanReview === 'function') refreshPlanReview()
2568
2624
  }
2569
2625
  window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
2570
2626
 
@@ -2825,7 +2881,10 @@ async function sendMessage(requestedMode = 'queue') {
2825
2881
  if (typeof window !== 'undefined') window.DshSlashSuggestions?.close()
2826
2882
  if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
2827
2883
  const input = $('composer')
2828
- const originalText = input.value, text = originalText.trim()
2884
+ const originalText = input.value, clean = originalText.trim()
2885
+ const quoted = clean && !clean.startsWith('/') && typeof composerTools !== 'undefined' ? composerTools?.quotes() || [] : []
2886
+ const quoteText = quoted.length ? window.DshComposerTools.formatQuotes(quoted) : ''
2887
+ const text = [quoteText, clean].filter(Boolean).join('\n\n')
2829
2888
  if (!text || !state.current) return
2830
2889
  const sessionId = state.current, connection = captureConnection(), history = state.history
2831
2890
  const pending = sendMessage.pending ||= new Set()
@@ -2834,7 +2893,7 @@ async function sendMessage(requestedMode = 'queue') {
2834
2893
  const valid = () => connection.valid() && state.current === sessionId && state.history === history
2835
2894
  try {
2836
2895
  state.sessionActivity.add(sessionId)
2837
- if (await runSlashCommand(text)) { if (valid() && input.value === originalText) input.value = ''; return }
2896
+ if (await runSlashCommand(clean)) { if (valid() && input.value === originalText) input.value = ''; return }
2838
2897
  if (!valid()) return
2839
2898
  setSessionRecovery('resuming')
2840
2899
  const v = await safeRpc('session.prompt', {
@@ -2845,6 +2904,7 @@ async function sendMessage(requestedMode = 'queue') {
2845
2904
  if (!valid()) return
2846
2905
  if (v?.accepted) {
2847
2906
  if (input.value === originalText) input.value = ''
2907
+ if (quoted.length) composerTools?.clearQuotes(quoted.map(quote => quote.id))
2848
2908
  setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
2849
2909
  }
2850
2910
  else setSessionRecovery('error')
@@ -2923,43 +2983,28 @@ function updateComposerStatus() {
2923
2983
  : t('ds.composerRunning')
2924
2984
  updateSessionActions()
2925
2985
  }
2926
- function queuePreview(item) {
2927
- const blocks = item?.message?.content || item?.content || []
2928
- const text = Array.isArray(blocks)
2929
- ? blocks.filter(block => block?.type === 'text').map(block => String(block.text || '')).join(' ').trim()
2930
- : ''
2931
- return text || (Array.isArray(blocks) && blocks.some(block => block?.type === 'image') ? t('queue.image') : '…')
2932
- }
2933
- async function steerQueueItem(itemId) {
2934
- const sessionId = state.current
2935
- const key = `${sessionId}:${itemId}`
2936
- const s = state.byId.get(sessionId)
2937
- if (!sessionId || !s?.running || state.queueSteering[key]) return
2938
- state.queueSteering[key] = true
2939
- renderQueue()
2940
- try {
2941
- const v = await safeRpc('session.updateQueue', { sessionId, itemId, action: { kind: 'steer' } }, t('queue.steerFailed', { msg: '' }).replace(/:$/, '').replace(/: $/, ''))
2942
- if (v?.accepted) toast(t('queue.steerSubmitted'), 'ok')
2943
- } finally {
2944
- delete state.queueSteering[key]
2945
- renderQueue()
2946
- }
2947
- }
2986
+ const hostAccess = connection => window.DshHostQueue.readAccess(connection, apiUrl)
2987
+ const hostQueue = window.DshHostQueue?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('queue-dock'),
2988
+ session: () => state.current, items: () => state.queues[state.current], running: () => !!state.byId.get(state.current)?.running,
2989
+ apply(sessionId, snapshot) {
2990
+ state.queues[sessionId] = snapshot.items
2991
+ const session = state.byId.get(sessionId)
2992
+ if (session) session.running = snapshot.running
2993
+ },
2994
+ })
2995
+ const hostSchedule = window.DshHostSchedule?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('view-schedule'),
2996
+ workspaces: workspaceItems,
2997
+ sessions: () => state.sessions.filter(row => row.origin !== 'subagent' && !state.archivedIds.includes(row.sessionId)).map(row => ({ id: row.sessionId, label: titleOf(row) })),
2998
+ async openSession(id) {
2999
+ const connection = captureConnection()
3000
+ await refreshSessions()
3001
+ if (!connection.valid()) return
3002
+ if (!state.byId.has(id)) return toast(t('ds.sessionUntitled'), 'err')
3003
+ await openSession(id)
3004
+ },
3005
+ })
2948
3006
  function renderQueue() {
2949
- const box = $('queue-dock')
2950
- if (!box) return
2951
- const sessionId = state.current
2952
- const s = state.byId.get(sessionId)
2953
- const items = (state.queues[sessionId] || []).filter(item => item?.placement === 'queued')
2954
- box.classList.toggle('hidden', !items.length)
2955
- box.innerHTML = items.length ? `<div class="ds-queue-dock-head"><span>⌁</span><span>${esc(t('queue.title'))} · ${items.length}</span></div><div class="ds-queue-dock-list">${items.map(item => {
2956
- const key = `${sessionId}:${item.id}`
2957
- const busy = !!state.queueSteering[key]
2958
- return `<div class="ds-queue-dock-item"><span class="ds-queue-dock-preview" title="${esc(queuePreview(item))}">${esc(queuePreview(item))}</span><button type="button" class="ds-mini-btn ds-queue-dock-action" data-queue-steer="${esc(item.id)}" title="${esc(s?.running ? t('queue.steer') : t('queue.steerUnavailable'))}" ${s?.running && !busy ? '' : 'disabled'}>${busy ? '…' : esc(t('queue.steer'))}</button></div>`
2959
- }).join('')}</div>` : ''
2960
- box.querySelectorAll('[data-queue-steer]').forEach(button => {
2961
- button.addEventListener('click', () => steerQueueItem(button.dataset.queueSteer))
2962
- })
3007
+ hostQueue?.render()
2963
3008
  updateComposerStatus()
2964
3009
  }
2965
3010
 
@@ -3136,6 +3181,11 @@ function questionMarkup(item) {
3136
3181
 
3137
3182
  function openQuestionModal(q) {
3138
3183
  if (!q) return
3184
+ if (typeof isPlanReviewQuestion === 'function' && isPlanReviewQuestion(q)) {
3185
+ if (typeof refreshPlanReview === 'function') refreshPlanReview()
3186
+ if (typeof planReviewHost !== 'undefined') planReviewHost?.scrollIntoView?.({ behavior: 'smooth', block: 'center' })
3187
+ return
3188
+ }
3139
3189
  state.questionModal = q
3140
3190
  $('question-body').innerHTML = q.questions.map((item, i) => `
3141
3191
  <div class="ds-q-item">
@@ -3178,6 +3228,493 @@ async function submitQuestion() {
3178
3228
  } else toast(t('ds.stale'), 'err')
3179
3229
  }
3180
3230
 
3231
+ /* ---------------- B/C 输入、搜索与管理 ---------------- */
3232
+ let composerTools = null
3233
+ let sessionSearchController = null
3234
+ let sessionSearchMount = null
3235
+ let sessionManager = null
3236
+ let workspaceAdminMount = null
3237
+ let quoteSelectionButton = null
3238
+ let planReviewController = null
3239
+ let planReviewHost = null
3240
+ let turnDiffController = null
3241
+ let turnDiffRoot = null
3242
+
3243
+ function bcEnglish() { return I18N.lang === 'en' }
3244
+ function bcText(zh, en) { return bcEnglish() ? en : zh }
3245
+
3246
+ async function bcRpc(method, payload, options = {}) {
3247
+ return rpc(method, payload, Number.isFinite(options.timeoutMs) ? options.timeoutMs : 45000, options.signal || null)
3248
+ }
3249
+
3250
+ function composerToolsHost() {
3251
+ return {
3252
+ scope: () => ({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() }),
3253
+ async listReferences(scope, query) {
3254
+ const sessionId = scope?.sessionId || state.current
3255
+ if (!sessionId) return null
3256
+ const [files, sessions] = await Promise.allSettled([
3257
+ bcRpc('fileReferences.list', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
3258
+ bcRpc('sessionReferenceResolver.candidates', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
3259
+ ])
3260
+ if (files.status !== 'fulfilled' && sessions.status !== 'fulfilled') return null
3261
+ const references = []
3262
+ if (files.status === 'fulfilled' && Array.isArray(files.value)) {
3263
+ for (const row of files.value) {
3264
+ const insert = window.DshComposerTools.fileReferenceMention(row)
3265
+ if (!insert) continue
3266
+ references.push({
3267
+ insert,
3268
+ label: row?.kind === 'directory' ? String(row?.path || '') + '/' : String(row?.path || ''),
3269
+ detail: row?.kind === 'directory' ? bcText('目录', 'Directory') : bcText('文件', 'File'),
3270
+ kind: 'file',
3271
+ allowed: true,
3272
+ })
3273
+ }
3274
+ }
3275
+ if (sessions.status === 'fulfilled' && Array.isArray(sessions.value)) {
3276
+ for (const row of sessions.value) {
3277
+ if (typeof row?.mention !== 'string' || !row.mention.startsWith('@')) continue
3278
+ references.push({
3279
+ insert: row.mention,
3280
+ label: row.displayTitle || row.label || row.sessionId || '',
3281
+ detail: row.cwd || '',
3282
+ kind: 'session',
3283
+ allowed: true,
3284
+ })
3285
+ }
3286
+ }
3287
+ return { supported: true, references }
3288
+ },
3289
+ notice: (text, kind) => toast(text, kind === 'err' ? 'err' : ''),
3290
+ }
3291
+ }
3292
+
3293
+ function selectedMessageQuote() {
3294
+ const selection = window.getSelection?.()
3295
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null
3296
+ const range = selection.getRangeAt(0)
3297
+ const history = $('history')
3298
+ if (!history || !range.commonAncestorContainer) return null
3299
+ const startNode = range.startContainer.nodeType === 3 ? range.startContainer.parentElement : range.startContainer
3300
+ const endNode = range.endContainer.nodeType === 3 ? range.endContainer.parentElement : range.endContainer
3301
+ const startMessage = startNode?.closest?.('.ds-msg')
3302
+ const endMessage = endNode?.closest?.('.ds-msg')
3303
+ if (!startMessage || !endMessage || startMessage !== endMessage || !history.contains(startMessage)) return null
3304
+ const text = selection.toString().replace(/\r\n?/g, '\n').trim()
3305
+ if (!text) return null
3306
+ const role = startMessage.classList.contains('user') ? 'user' : startMessage.classList.contains('assistant') ? 'assistant' : ''
3307
+ return { text, role, messageId: startMessage.dataset.seq || '', rect: range.getBoundingClientRect() }
3308
+ }
3309
+
3310
+ function hideQuoteSelectionButton() {
3311
+ if (!quoteSelectionButton) return
3312
+ quoteSelectionButton.hidden = true
3313
+ quoteSelectionButton.classList.add('hidden')
3314
+ }
3315
+
3316
+ function updateQuoteSelectionButton() {
3317
+ if (!quoteSelectionButton || !composerTools) return
3318
+ const selected = selectedMessageQuote()
3319
+ if (!selected) { hideQuoteSelectionButton(); return }
3320
+ const rect = selected.rect
3321
+ quoteSelectionButton.style.left = Math.max(8, Math.min(window.innerWidth - 150, rect.left + rect.width / 2 - 70)) + 'px'
3322
+ quoteSelectionButton.style.top = Math.max(8, Math.min(window.innerHeight - 56, rect.bottom + 8)) + 'px'
3323
+ quoteSelectionButton.hidden = false
3324
+ quoteSelectionButton.classList.remove('hidden')
3325
+ }
3326
+
3327
+ function initQuoteSelection() {
3328
+ if (quoteSelectionButton) return
3329
+ quoteSelectionButton = document.createElement('button')
3330
+ quoteSelectionButton.type = 'button'
3331
+ quoteSelectionButton.className = 'ct-quote-pick hidden'
3332
+ quoteSelectionButton.hidden = true
3333
+ quoteSelectionButton.textContent = t('ds.quoteSelection')
3334
+ quoteSelectionButton.addEventListener('pointerdown', event => event.preventDefault())
3335
+ quoteSelectionButton.addEventListener('click', event => {
3336
+ event.preventDefault()
3337
+ const selected = selectedMessageQuote()
3338
+ hideQuoteSelectionButton()
3339
+ if (!selected || !composerTools) return
3340
+ composerTools.addQuote({ messageId: selected.messageId, role: selected.role, text: selected.text })
3341
+ window.getSelection?.()?.removeAllRanges?.()
3342
+ toast(t('ds.quoteAdded'), 'ok')
3343
+ })
3344
+ document.body.append(quoteSelectionButton)
3345
+ document.addEventListener('selectionchange', () => {
3346
+ if (document.activeElement === $('composer')) return
3347
+ updateQuoteSelectionButton()
3348
+ })
3349
+ window.addEventListener('scroll', hideQuoteSelectionButton, { passive: true })
3350
+ window.addEventListener('resize', hideQuoteSelectionButton)
3351
+ }
3352
+
3353
+ function initComposerToolsUi() {
3354
+ if (composerTools || !window.DshComposerTools) return
3355
+ const input = $('composer')
3356
+ if (!input) return
3357
+ const anchor = document.createElement('div')
3358
+ anchor.className = 'ct-anchor'
3359
+ const menu = document.createElement('div')
3360
+ menu.id = 'composer-tools-menu'
3361
+ menu.className = 'ct-menu hidden'
3362
+ menu.hidden = true
3363
+ anchor.append(menu)
3364
+ const quotes = document.createElement('div')
3365
+ quotes.id = 'composer-tools-quotes'
3366
+ quotes.className = 'ct-quotes hidden'
3367
+ quotes.hidden = true
3368
+ const hint = document.createElement('p')
3369
+ hint.id = 'composer-tools-hint'
3370
+ hint.className = 'ct-hint hidden'
3371
+ hint.hidden = true
3372
+ input.before(anchor)
3373
+ input.before(quotes)
3374
+ input.before(hint)
3375
+ composerTools = window.DshComposerTools.create({
3376
+ input,
3377
+ menu,
3378
+ hint,
3379
+ quoteList: quotes,
3380
+ host: composerToolsHost(),
3381
+ commands: false,
3382
+ onChange: () => window.DshWorkflow?.update(),
3383
+ })
3384
+ initQuoteSelection()
3385
+ }
3386
+
3387
+ function syncComposerToolsScope() {
3388
+ composerTools?.setScope?.({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() })
3389
+ }
3390
+
3391
+ function initSessionSearchUi() {
3392
+ if (sessionSearchController || !window.DshSessionSearch) return
3393
+ const sort = $('session-sort')
3394
+ const list = $('session-list')
3395
+ if (!sort || !list) return
3396
+ const toggle = document.createElement('button')
3397
+ toggle.id = 'btn-session-search'
3398
+ toggle.type = 'button'
3399
+ toggle.className = 'ds-icon-btn dr-bc-search-toggle'
3400
+ toggle.textContent = '⌕'
3401
+ toggle.title = t('ds.searchSessions')
3402
+ toggle.setAttribute('aria-label', t('ds.searchSessions'))
3403
+ toggle.setAttribute('aria-expanded', 'false')
3404
+ sort.before(toggle)
3405
+ const host = document.createElement('section')
3406
+ host.id = 'session-search-host'
3407
+ host.className = 'hidden'
3408
+ list.before(host)
3409
+ sessionSearchController = window.DshSessionSearch.init({
3410
+ rpc: bcRpc,
3411
+ sessions: () => (state.sessions || []).filter(s => s && s.sessionId && s.origin !== 'subagent' && s.blank !== true),
3412
+ workspaces: () => workspaceItems(),
3413
+ archivedSessionIds: () => state.archivedIds || [],
3414
+ pinnedSessionIds: () => state.pinnedIds || [],
3415
+ titleOf: session => titleOf(session),
3416
+ historyRoot: () => $('history'),
3417
+ openSession: async (sessionId) => { toggleSessionSearch(false); await openSession(sessionId) },
3418
+ notice: message => toast(message),
3419
+ })
3420
+ sessionSearchMount = window.DshSessionSearch.mount(host, sessionSearchController, {
3421
+ onOpen: result => { if (result?.opened) toggleSessionSearch(false) },
3422
+ })
3423
+ toggle.addEventListener('click', () => toggleSessionSearch())
3424
+ updateBcControlLabels()
3425
+ }
3426
+
3427
+ function toggleSessionSearch(force) {
3428
+ const host = $('session-search-host')
3429
+ const button = $('btn-session-search')
3430
+ if (!host || !button || !sessionSearchController) return
3431
+ const open = typeof force === 'boolean' ? force : host.classList.contains('hidden')
3432
+ host.classList.toggle('hidden', !open)
3433
+ button.classList.toggle('is-active', open)
3434
+ button.setAttribute('aria-expanded', String(open))
3435
+ if (open) {
3436
+ sessionSearchController.syncCatalog()
3437
+ sessionSearchMount?.refresh()
3438
+ requestAnimationFrame(() => host.querySelector('[data-dr-search-input]')?.focus())
3439
+ } else hideQuoteSelectionButton()
3440
+ }
3441
+
3442
+ function workspaceRemovalConfirmation(request) {
3443
+ const impact = request?.impact || {}
3444
+ return window.confirm([
3445
+ bcText(`移除工作区登记「${request?.displayTitle || impact.name || ''}」?`, `Remove the workspace registration "${request?.displayTitle || impact.name || ''}"?`),
3446
+ bcText('只删除工作区登记,不删除磁盘目录、文件或会话历史。', 'Only the Workspace registration is removed; directories, files and conversation history stay on disk.'),
3447
+ bcText(`该工作区关联 ${impact.total || 0} 个会话。移除后不再按该工作区分组。`, `${impact.total || 0} conversation(s) are associated. Their Workspace grouping disappears after removal.`),
3448
+ ].join('\n\n'))
3449
+ }
3450
+
3451
+ function promptWorkspaceTitle({ workspace, current }) {
3452
+ const value = window.prompt(t('ds.workspaceRenamePrompt'), current || workspace?.title || '')
3453
+ return value == null ? null : String(value)
3454
+ }
3455
+
3456
+ function initSessionManagementUi() {
3457
+ if (sessionManager || !window.DshSessionManagement) return
3458
+ sessionManager = window.DshSessionManagement.init({
3459
+ rpc: bcRpc,
3460
+ sessions: () => state.sessions,
3461
+ workspaces: () => workspaceItems(),
3462
+ archivedSessionIds: () => state.archivedIds || [],
3463
+ pinnedSessionIds: () => state.pinnedIds || [],
3464
+ titleOf: session => titleOf(session),
3465
+ refresh: async () => { await Promise.all([refreshWorkbench({ silent: true }), refreshSessions()]) },
3466
+ confirm: workspaceRemovalConfirmation,
3467
+ promptTitle: promptWorkspaceTitle,
3468
+ toast,
3469
+ })
3470
+ const create = $('btn-new-workspace')
3471
+ const manageButton = document.createElement('button')
3472
+ manageButton.id = 'btn-manage-workspaces'
3473
+ manageButton.type = 'button'
3474
+ manageButton.className = 'ds-icon-btn'
3475
+ manageButton.textContent = '⚙'
3476
+ manageButton.title = t('ds.manageWorkspaces')
3477
+ manageButton.setAttribute('aria-label', t('ds.manageWorkspaces'))
3478
+ create?.before(manageButton)
3479
+ manageButton.addEventListener('click', openWorkspaceAdmin)
3480
+ const dialog = $('session-actions')
3481
+ if (dialog) {
3482
+ const box = document.createElement('div')
3483
+ box.id = 'session-admin-actions'
3484
+ dialog.querySelector('#btn-archive-session')?.before(box)
3485
+ window.DshSessionManagement.bindWorkspaceAdmin(box, sessionManager, {
3486
+ onResult: result => { if (result?.ok) renderSessions() },
3487
+ })
3488
+ }
3489
+ updateBcControlLabels()
3490
+ }
3491
+
3492
+ function ensureWorkspaceAdminModal() {
3493
+ let modal = $('modal-workspace-admin')
3494
+ if (modal) return modal
3495
+ modal = document.createElement('div')
3496
+ modal.id = 'modal-workspace-admin'
3497
+ modal.className = 'ds-modal hidden'
3498
+ modal.setAttribute('role', 'dialog')
3499
+ modal.setAttribute('aria-modal', 'true')
3500
+ modal.innerHTML = `<div class="ds-modal-card"><div class="ds-modal-title" id="workspace-admin-title"></div><div class="ds-modal-body" id="workspace-admin-host"></div><div class="ds-modal-actions"><button type="button" class="ds-btn" data-workspace-admin-close></button></div></div>`
3501
+ document.body.append(modal)
3502
+ modal.addEventListener('click', event => {
3503
+ if (event.target === modal || event.target.closest('[data-workspace-admin-close]')) modal.classList.add('hidden')
3504
+ })
3505
+ return modal
3506
+ }
3507
+
3508
+ function openWorkspaceAdmin() {
3509
+ if (!sessionManager) return
3510
+ const modal = ensureWorkspaceAdminModal()
3511
+ sessionManager.hydrate()
3512
+ if (!workspaceAdminMount) {
3513
+ workspaceAdminMount = window.DshSessionManagement.mountWorkspaceAdmin($('workspace-admin-host'), sessionManager, {
3514
+ promptTitle: promptWorkspaceTitle,
3515
+ onResult: result => { if (result?.ok) { renderSessions(); workspaceAdminMount?.refresh() } },
3516
+ })
3517
+ } else workspaceAdminMount.refresh()
3518
+ updateBcControlLabels()
3519
+ modal.classList.remove('hidden')
3520
+ }
3521
+
3522
+ function refreshSessionAdminActions() {
3523
+ const box = $('session-admin-actions')
3524
+ const session = state.byId.get(state.current)
3525
+ if (!box || !sessionManager || !session) return
3526
+ box.innerHTML = window.DshSessionManagement.renderSessionAdminActions(session, sessionManager.getState())
3527
+ }
3528
+
3529
+ function updateBcControlLabels() {
3530
+ const search = $('btn-session-search')
3531
+ if (search) { search.title = t('ds.searchSessions'); search.setAttribute('aria-label', t('ds.searchSessions')) }
3532
+ const manage = $('btn-manage-workspaces')
3533
+ if (manage) { manage.title = t('ds.manageWorkspaces'); manage.setAttribute('aria-label', t('ds.manageWorkspaces')) }
3534
+ if (quoteSelectionButton) quoteSelectionButton.textContent = t('ds.quoteSelection')
3535
+ const modal = $('modal-workspace-admin')
3536
+ if (modal) {
3537
+ modal.querySelector('#workspace-admin-title').textContent = t('ds.manageWorkspaces')
3538
+ modal.querySelector('[data-workspace-admin-close]').textContent = t('ds.close')
3539
+ }
3540
+ }
3541
+
3542
+ function initBcFeatures() {
3543
+ initComposerToolsUi()
3544
+ initSessionSearchUi()
3545
+ initSessionManagementUi()
3546
+ initReviewFeatures()
3547
+ syncComposerToolsScope()
3548
+ }
3549
+
3550
+ function isPlanReviewQuestion(question) {
3551
+ return !!window.DshPlanReview?.planReviewOf?.(question?.questions)
3552
+ }
3553
+
3554
+ function planReviewSnapshot(sessionId) {
3555
+ const session = state.byId.get(sessionId)
3556
+ const plan = session?.projections?.values?.plan
3557
+ return {
3558
+ plan,
3559
+ questions: (state.questions || []).filter(frame => String(frame?.sessionId || '') === String(sessionId || '')),
3560
+ connected: !!state.streamsOk?.mux,
3561
+ readOnly: false,
3562
+ capability: plan === undefined ? undefined : true,
3563
+ }
3564
+ }
3565
+
3566
+ function updatePlanReviewVisibility(view) {
3567
+ if (!planReviewHost) return
3568
+ const visible = !!(view?.plan?.supported || view?.review || (Array.isArray(view?.plans) && view.plans.length)
3569
+ || (state.current && state.history.loaded))
3570
+ planReviewHost.classList.toggle('hidden', !visible)
3571
+ }
3572
+
3573
+ function refreshPlanReview() {
3574
+ if (!planReviewController) return
3575
+ let view = null
3576
+ try { view = planReviewController.render() } catch {}
3577
+ updatePlanReviewVisibility(view)
3578
+ return view
3579
+ }
3580
+
3581
+ function turnDiffEnabled() {
3582
+ return LS.get('turnDiffEnabled', '0') === '1'
3583
+ }
3584
+
3585
+ function turnDiffHtmlFor(entry) {
3586
+ if (!turnDiffController || !turnDiffController.isEnabled()) return ''
3587
+ if (entry?.event?.type !== 'turn/end') return ''
3588
+ const turnNumber = Number(entry.event?.data?.turn)
3589
+ if (!Number.isSafeInteger(turnNumber) || turnNumber < 1) return ''
3590
+ const full = turnDiffController.view()
3591
+ const turns = full.turns.filter(turn => turn.turn === turnNumber)
3592
+ if (!turns.length) return ''
3593
+ return `<div class="dr-diff-turn-slot" data-turn="${turnNumber}">${window.DshTurnDiff.viewHtml({ ...full, turns })}</div>`
3594
+ }
3595
+
3596
+ async function fetchHostChangesJson(path, query) {
3597
+ const url = new URL(apiUrl(path), location.href)
3598
+ for (const [key, value] of Object.entries(query || {})) url.searchParams.set(key, String(value))
3599
+ const res = await fetch(url.href, {
3600
+ headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
3601
+ cache: 'no-store',
3602
+ signal: AbortSignal.timeout(45000),
3603
+ })
3604
+ if (res.status === 401) toast(t('ds.toastAuth'), 'err')
3605
+ let data = null
3606
+ try { data = await res.json() } catch {}
3607
+ return { ok: res.ok, status: res.status, data }
3608
+ }
3609
+
3610
+ let turnDiffActionsBound = false
3611
+ function bindTurnDiffActions() {
3612
+ if (turnDiffActionsBound || !turnDiffController) return
3613
+ const container = $('history')
3614
+ if (!container) return
3615
+ turnDiffActionsBound = true
3616
+ container.addEventListener('click', event => {
3617
+ const button = event.target?.closest?.('[data-dr-diff-action]')
3618
+ if (!button || button.disabled) return
3619
+ const action = button.dataset?.drDiffAction || ''
3620
+ const turn = Number(button.dataset?.drDiffTurn)
3621
+ const index = Number(button.dataset?.drDiffFile)
3622
+ const delivery = Number(button.dataset?.drDiffDelivery)
3623
+ const run = {
3624
+ toggle: () => turnDiffController.toggleTurn(turn),
3625
+ file: () => turnDiffController.selectFile(turn, index),
3626
+ delivery: () => { turnDiffController.openDelivery(turn, delivery); return true },
3627
+ 'retry-summary': () => turnDiffController.retrySummary(turn),
3628
+ 'retry-diff': () => turnDiffController.retryDiff(turn, index),
3629
+ }[action]
3630
+ if (!run) return
3631
+ const finish = () => { if (state.current) renderHistory(false, 'keep') }
3632
+ try {
3633
+ const result = run()
3634
+ if (result && typeof result.then === 'function') result.then(finish, finish)
3635
+ else finish()
3636
+ } catch { finish() }
3637
+ })
3638
+ }
3639
+
3640
+ function initReviewFeatures() {
3641
+ if (window.DshPlanReview && !planReviewController) {
3642
+ const anchor = $('session-cards')
3643
+ if (anchor) {
3644
+ planReviewHost = document.createElement('section')
3645
+ planReviewHost.id = 'plan-review-host'
3646
+ planReviewHost.className = 'plan-review-host hidden'
3647
+ planReviewHost.setAttribute('aria-live', 'polite')
3648
+ anchor.after(planReviewHost)
3649
+ planReviewController = window.DshPlanReview.create({
3650
+ command: async line => ({ executed: await runSlashCommand(line, true) }),
3651
+ respond: (rpcId, value) => respond(rpcId, value),
3652
+ state: {
3653
+ sessionId: () => state.current,
3654
+ snapshot: sessionId => planReviewSnapshot(sessionId),
3655
+ entries: sessionId => state.current === sessionId ? state.history.visible : [],
3656
+ },
3657
+ dom: { root: planReviewHost },
3658
+ onOpenPlan: () => {},
3659
+ notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
3660
+ })
3661
+ updatePlanReviewVisibility(planReviewController.view())
3662
+ }
3663
+ }
3664
+ if (window.DshTurnDiff && !turnDiffController) {
3665
+ turnDiffRoot = document.createElement('div')
3666
+ turnDiffRoot.hidden = true
3667
+ turnDiffController = window.DshTurnDiff.create({
3668
+ state: {
3669
+ sessionId: () => state.current,
3670
+ entries: sessionId => state.current === sessionId ? state.history.visible : [],
3671
+ },
3672
+ fetchJson: fetchHostChangesJson,
3673
+ dom: { root: turnDiffRoot },
3674
+ layout: 'desktop',
3675
+ enabled: turnDiffEnabled,
3676
+ onOpenFile: ({ path }) => {
3677
+ const name = String(path || '').split(/[\\/]/).pop() || ''
3678
+ if (path && name) openFsPreview(path, name)
3679
+ },
3680
+ notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
3681
+ })
3682
+ turnDiffController.setEnabled(turnDiffEnabled())
3683
+ bindTurnDiffActions()
3684
+ }
3685
+ initTurnDiffSetting()
3686
+ }
3687
+
3688
+ function initTurnDiffSetting() {
3689
+ const page = $('settings-page-general')
3690
+ if (!page || $('opt-turn-diff')) return
3691
+ const group = page.querySelector('[data-workflow-settings-slot="input"]')
3692
+ || page.querySelector('[data-workflow-settings-slot]')
3693
+ || page
3694
+ const row = document.createElement('div')
3695
+ row.className = 'ds-setting-row'
3696
+ row.innerHTML = `<div><div class="ds-setting-name"></div><div class="ds-setting-desc"></div></div><label class="switch"><input type="checkbox" id="opt-turn-diff"><span class="slider"></span></label>`
3697
+ row.querySelector('.ds-setting-name').textContent = t('ds.turnDiffTitle')
3698
+ row.querySelector('.ds-setting-desc').textContent = t('ds.turnDiffDesc')
3699
+ group.append(row)
3700
+ const checkbox = row.querySelector('#opt-turn-diff')
3701
+ checkbox.checked = turnDiffEnabled()
3702
+ checkbox.addEventListener('change', () => {
3703
+ LS.set('turnDiffEnabled', checkbox.checked ? '1' : '0')
3704
+ turnDiffController?.setEnabled(checkbox.checked)
3705
+ if (state.current) renderHistory(false, 'keep')
3706
+ })
3707
+ }
3708
+
3709
+ function updateTurnDiffSettingLabel() {
3710
+ const row = $('opt-turn-diff')?.closest('.ds-setting-row')
3711
+ if (!row) return
3712
+ const name = row.querySelector('.ds-setting-name')
3713
+ const desc = row.querySelector('.ds-setting-desc')
3714
+ if (name) name.textContent = t('ds.turnDiffTitle')
3715
+ if (desc) desc.textContent = t('ds.turnDiffDesc')
3716
+ }
3717
+
3181
3718
  /* ---------------- 文件传输 ---------------- */
3182
3719
  function fsApiUrl(sub, params = {}) {
3183
3720
  const u = new URL(apiUrl('/fs' + sub), location.href)
@@ -3205,6 +3742,11 @@ async function chatImageAttachment(attachment, sessionId) {
3205
3742
  ...(ref.height === undefined ? {} : { height: ref.height }),
3206
3743
  ...(ref.name ? { name: ref.name } : {}),
3207
3744
  } }
3745
+ const session = state.byId?.get(sessionId)
3746
+ if (session?.origin === 'subagent' && session.parentSessionId) {
3747
+ payload.parentSessionId = session.parentSessionId
3748
+ payload.subagentMode = session.subagentMode || 'unknown'
3749
+ }
3208
3750
  const result = await rpc('session.attachment', payload, 120000)
3209
3751
  if (!connection.valid() || state.current !== sessionId) throw new Error('stale image')
3210
3752
  return result
@@ -3510,7 +4052,9 @@ function orderedWorkspaceItems(items) {
3510
4052
  }
3511
4053
  function orderedWorkspaceSessions(workspaceId, items) {
3512
4054
  const { value } = workbenchOrderScopeValue()
3513
- return orderedItems(items, value.sessionIds?.[String(workspaceId)], item => item.sessionId)
4055
+ const pinned = new Set(state.pinnedIds || [])
4056
+ const ordered = orderedItems(items, value.sessionIds?.[String(workspaceId)], item => item.sessionId)
4057
+ return ordered.sort((a, b) => Number(pinned.has(b.sessionId)) - Number(pinned.has(a.sessionId)))
3514
4058
  }
3515
4059
  function saveWorkbenchOrder(mutator) {
3516
4060
  const { store, value } = workbenchOrderScopeValue()
@@ -3552,6 +4096,7 @@ async function refreshWorkbench({ silent = false, discover = false } = {}) {
3552
4096
  if (!valid()) return
3553
4097
  if(wl){
3554
4098
  state.archivedIds = Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
4099
+ state.pinnedIds = Array.isArray(wl.pinnedSessionIds) ? wl.pinnedSessionIds : []
3555
4100
  state.workspaces = Array.isArray(wl.items) ? wl.items.slice() : []
3556
4101
  }
3557
4102
  if (!wb) { renderWorkbench(); renderSessions(); return }
@@ -4085,16 +4630,18 @@ function showView(id, pluginRoute = 'manage') {
4085
4630
  if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
4086
4631
  if (id !== 'view-chat') conversationView?.pause()
4087
4632
  if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
4633
+ if (state.view === 'view-schedule' && id !== 'view-schedule') hostSchedule?.leave()
4088
4634
  state.view = id
4089
4635
  window.DshFileInbox?.render()
4090
4636
  window.DshSessionDeck?.refresh()
4091
4637
  document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
4092
- for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
4638
+ for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings', 'view-schedule']) $(v).classList.toggle('hidden', v !== id)
4639
+ if (id === 'view-schedule') void hostSchedule?.refresh(true)
4093
4640
  if (id === 'view-chat') conversationView?.resume()
4094
4641
  document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
4095
4642
  if (narrowSidebarQuery.matches) setMobileSidebar(false)
4096
4643
  window.DshMotion?.view($(id))
4097
- const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings', 'view-plugins': 'ds.plugins' }
4644
+ const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings', 'view-plugins': 'ds.plugins', 'view-schedule': 'hostSchedule.title' }
4098
4645
  if (id === 'view-chat') { const s = state.byId.get(state.current); $('ds-title').textContent = s ? titleOf(s) : t('ds.sessions') }
4099
4646
  else $('ds-title').textContent = t(titles[id])
4100
4647
  if (id === 'view-overview') {startOverviewDetection(true);renderOverviewDesktop()}
@@ -4190,7 +4737,7 @@ function updateConn() {
4190
4737
 
4191
4738
  function bindSessionDialogs() {
4192
4739
  const actions=$('session-actions'), info=$('session-info');
4193
- $('btn-session-more').addEventListener('click',()=>actions.showModal());
4740
+ $('btn-session-more').addEventListener('click',()=>{if(typeof refreshSessionAdminActions === 'function')refreshSessionAdminActions();actions.showModal()});
4194
4741
  actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
4195
4742
  const openInfo=()=>{const s=state.byId.get(state.current);if(!s)return; $('session-info-name').textContent=titleOf(s);$('session-info-path').textContent=s.cwd||t('ds.noWorkspace');$('session-info-id').textContent=s.sessionId;$('btn-copy-session-workspace').disabled=!s.cwd;info.showModal()};
4196
4743
  $('ds-title').addEventListener('click',openInfo);
@@ -4289,7 +4836,8 @@ function bindUi() {
4289
4836
  readSkills: sessionId => rpc('skills.list', { sessionId }, 5000),
4290
4837
  })
4291
4838
  composer.addEventListener('keydown', (e) => {
4292
- if (!e.defaultPrevented && e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); sendMessage() }
4839
+ if (e.defaultPrevented || e.key !== 'Enter' || e.isComposing || composerTools?.keydown(e)) return
4840
+ if (!e.shiftKey) { e.preventDefault(); sendMessage() }
4293
4841
  })
4294
4842
  renderPresetMenuDesktop()
4295
4843
  renderPresetSummary()
@@ -4297,9 +4845,13 @@ function bindUi() {
4297
4845
  $('cmd-menu').addEventListener('click', (e) => {
4298
4846
  const item = e.target.closest('[data-ds-cmd]')
4299
4847
  if (item) {
4300
- const input = $('composer')
4301
- input.value = item.dataset.dsCmd + ' '
4302
- input.focus()
4848
+ const command = String(item.dataset.dsCmd || '').replace(/^\/+/, '')
4849
+ if (typeof composerTools === 'undefined' || !composerTools?.insertCommand?.(command)) {
4850
+ const input = $('composer')
4851
+ if (input.value.trim()) input.value = '/' + command + ' ' + input.value
4852
+ else input.value = '/' + command + ' '
4853
+ input.focus()
4854
+ }
4303
4855
  $('cmd-menu').classList.add('hidden')
4304
4856
  }
4305
4857
  })
@@ -4422,7 +4974,7 @@ function bindUi() {
4422
4974
  $('btn-lang').addEventListener('click', () => {
4423
4975
  I18N.setLang(I18N.lang === 'zh' ? 'en' : 'zh')
4424
4976
  $('btn-lang').textContent = I18N.lang === 'zh' ? 'EN' : '中文'
4425
- renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply(); void refreshInsightEntry()
4977
+ renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); if(typeof updateBcControlLabels === 'function')updateBcControlLabels(); if(typeof updateTurnDiffSettingLabel === 'function')updateTurnDiffSettingLabel(); if (state.current) { if(typeof refreshPlanReview === 'function')refreshPlanReview(); renderHistory(true) }; themeApply(); void refreshInsightEntry()
4426
4978
  })
4427
4979
  $('fs-up').addEventListener('click', fsUp)
4428
4980
  $('fs-root').addEventListener('change', (event) => {
@@ -4471,6 +5023,7 @@ async function start() {
4471
5023
  }
4472
5024
  $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
4473
5025
  bindUi()
5026
+ if (typeof initBcFeatures === 'function') initBcFeatures()
4474
5027
  window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest, resolveAttachment: chatImageAttachment, capture: captureChatImage })
4475
5028
  if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
4476
5029
  renderWorkbench()
@@ -4485,6 +5038,7 @@ async function start() {
4485
5038
  }
4486
5039
  overviewStarting=false
4487
5040
  renderOverviewDesktop()
5041
+ if (typeof initTurnDiffSetting === 'function') initTurnDiffSetting()
4488
5042
  }
4489
5043
 
4490
5044
  start()