dsh-remote-plugin 0.8.0-rc.4 → 0.8.0-rc.8

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/apk/dsh-remote.apk +0 -0
  2. package/client.js +21 -4
  3. package/doctor-skill.mjs +99 -0
  4. package/doctor-target.mjs +24 -0
  5. package/gateway.cjs +261 -15
  6. package/index.mjs +58 -6
  7. package/insights.mjs +11 -6
  8. package/market.mjs +83 -0
  9. package/package.json +6 -1
  10. package/peak-reminders.mjs +7 -4
  11. package/plugin-center.mjs +162 -32
  12. package/plugin-transaction.mjs +261 -0
  13. package/public/activity.js +58 -1
  14. package/public/admin.html +51 -16
  15. package/public/admin.js +158 -117
  16. package/public/app.js +188 -65
  17. package/public/build.json +2 -2
  18. package/public/desktop/desktop.html +25 -8
  19. package/public/desktop/desktop.js +193 -53
  20. package/public/doctor-entry.js +65 -0
  21. package/public/doctor.css +205 -0
  22. package/public/doctor.js +741 -0
  23. package/public/extensions.js +5 -5
  24. package/public/history.js +6 -1
  25. package/public/image-preview.js +22 -6
  26. package/public/index.html +25 -7
  27. package/public/insights.css +7 -0
  28. package/public/insights.js +11 -5
  29. package/public/md.js +91 -34
  30. package/public/network.js +15 -1
  31. package/public/plugin-center.css +12 -0
  32. package/public/plugin-center.js +161 -26
  33. package/public/plugin.html +36 -130
  34. package/public/plugin.js +62 -66
  35. package/public/remote-state.js +27 -0
  36. package/public/remote-ui.css +148 -0
  37. package/public/remote-ui.js +243 -0
  38. package/public/session-presets.js +47 -0
  39. package/public/setup.css +18 -0
  40. package/public/setup.js +213 -0
  41. package/public/skins/blue-fish/face.png +0 -0
  42. package/public/skins/blue-fish/icon-blush.png +0 -0
  43. package/public/skins/blue-fish/icon-sleep.png +0 -0
  44. package/public/skins/blue-fish/icon-smile.png +0 -0
  45. package/public/skins/blue-fish/icon-star.png +0 -0
  46. package/public/skins/blue-fish/icon-wink.png +0 -0
  47. package/public/skins/blue-fish/icon.png +0 -0
  48. package/public/skins/blue-fish/mascot.png +0 -0
  49. package/public/skins/blue-fish/pattern.png +0 -0
  50. package/public/skins/blue-fish/preview.html +289 -0
  51. package/public/skins/blue-fish/skin.css +561 -0
  52. package/public/styles.css +5 -1
  53. package/public/theme-vars.css +79 -4
  54. package/public/theme.js +2 -2
  55. package/public/turn-results.js +1 -1
  56. package/public/update.json +4 -4
  57. package/public/version.json +1 -1
  58. package/public/workflow.css +3 -0
  59. package/public/workflow.js +1 -0
  60. package/skills/dsh-remote-doctor/SKILL.md +170 -0
package/index.mjs CHANGED
@@ -18,6 +18,8 @@ import { readTeamInsights } from './teams.mjs'
18
18
  import { readPeakReminders } from './peak-reminders.mjs'
19
19
  import { serveSessionFile } from './session-file.mjs'
20
20
  import { createSkillsAdapter } from './skills.mjs'
21
+ import { registerDoctorSkill } from './doctor-skill.mjs'
22
+ import { readDoctorTarget, watchDoctorWorkspaces } from './doctor-target.mjs'
21
23
 
22
24
  export const name = 'dsh-remote'
23
25
  export const inject = ['webServer', 'commands', 'agents', 'connection']
@@ -634,7 +636,9 @@ function beginCommandOperation(ctx, agent, sessionId, line, command) {
634
636
  }
635
637
 
636
638
  async function resolveFile(pathname) {
637
- let abs = targetPath(pathname)
639
+ // 安装包在 public/ 之外,精确映射此文件,不能开放整个插件目录。
640
+ let abs = pathname === `${MOUNT}/dsh-remote.apk`
641
+ ? fileURLToPath(new URL('./apk/dsh-remote.apk', import.meta.url)) : targetPath(pathname)
638
642
  if (abs === null) return null
639
643
  try {
640
644
  let info = await stat(abs)
@@ -662,8 +666,39 @@ async function resolveFile(pathname) {
662
666
  }
663
667
  }
664
668
 
669
+ // Read metadata inside the actual DSH Host, never from the gateway's cwd/version.
670
+ export function hostDescription(ctx, runtime = process) {
671
+ let dshVersion = null, attachedSessions = null
672
+ const profile = detectProfile(ctx, runtime.argv[1], runtime)
673
+ if (profile?.cli) {
674
+ try {
675
+ const pkg = JSON.parse(readFileSync(resolve(dirname(profile.cli), '../package.json'), 'utf8'))
676
+ const expected = profile.cliMode === 'desktop' ? '@deepseek-ai/dsh-desktop-host' : '@deepseek-ai/dsh'
677
+ if (pkg.name === expected && typeof pkg.version === 'string') dshVersion = pkg.version.slice(0, 100)
678
+ } catch {}
679
+ }
680
+ try {
681
+ const agents = ctx.agents.list()
682
+ if (Array.isArray(agents)) attachedSessions = agents.length
683
+ } catch {}
684
+ return { version: dshVersion, cwd: runtime.cwd(), attachedSessions, home: homedir(), canOpenPath: false, metadataOnly: true }
685
+ }
686
+
665
687
  async function serveStatic(req, res, ctx) {
666
688
  const pathname = new URL(req.url ?? '/', 'http://x').pathname
689
+ if (pathname === `${MOUNT}/api/doctor/target` || pathname === `${MOUNT}/admin/api/doctor-target`) {
690
+ res.setHeader('cache-control','no-store')
691
+ if(pathname===`${MOUNT}/api/doctor/target` && !remoteCommandAuthorized(req))return sendJson(res,401,{ok:false,code:'unauthorized'})
692
+ if(req.method!=='GET')return sendJson(res,405,{ok:false,code:'read-only'})
693
+ if([...new URL(req.url,'http://x').searchParams].length)return sendJson(res,400,{ok:false,code:'invalid-query'})
694
+ return sendJson(res,200,readDoctorTarget(ctx))
695
+ }
696
+ if (pathname === `${MOUNT}/api/host-description`) {
697
+ res.setHeader('cache-control', 'no-store')
698
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
699
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
700
+ return sendJson(res, 200, { ok: true, ...hostDescription(ctx) })
701
+ }
667
702
  if (pathname.startsWith(`${MOUNT}/api/skills/`)) {
668
703
  res.setHeader('cache-control', 'no-store')
669
704
  if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
@@ -743,7 +778,16 @@ async function serveStatic(req, res, ctx) {
743
778
  return
744
779
  }
745
780
 
746
- // 统计面板数据: 代理到本地网关 /stats/*(网关未运行则返回 502)
781
+ // The embedded panel is already authenticated by the DSH web listener,
782
+ // like the adjacent admin/state route. Read cost-meter without a gateway.
783
+ if (pathname === `${MOUNT}/admin/api/cost`) {
784
+ res.setHeader('cache-control', 'no-store')
785
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
786
+ const result = await readCostInsights(ctx)
787
+ return sendJson(res, result.status, result.body)
788
+ }
789
+
790
+ // Legacy stats API retained for older clients.
747
791
  if (pathname === `${MOUNT}/admin/api/stats/summary` || pathname === `${MOUNT}/admin/api/stats/detail`) {
748
792
  const query = new URL(req.url ?? '/', 'http://x').search
749
793
  const sub = pathname.slice(`${MOUNT}/admin/api/stats`.length)
@@ -825,10 +869,10 @@ async function serveStatic(req, res, ctx) {
825
869
  [`${MOUNT}/admin/api/device-keys/rotate`, '/device-keys/rotate'],
826
870
  [`${MOUNT}/admin/api/device-keys/revoke`, '/device-keys/revoke'],
827
871
  ])
828
- if (pathname === `${MOUNT}/admin/api/relay`) {
872
+ if (pathname === `${MOUNT}/admin/api/relay` || pathname === `${MOUNT}/admin/api/autostart`) {
829
873
  if (!['GET', 'POST'].includes(req.method)) { res.writeHead(405, { allow: 'GET, POST' }); res.end(); return }
830
874
  const body = req.method === 'POST' ? await readBody(req, 4096) : undefined
831
- const proxied = await proxyGateway('/admin/api/relay', req.method, body)
875
+ const proxied = await proxyGateway(pathname.endsWith('/autostart') ? '/admin/api/autostart' : '/admin/api/relay', req.method, body)
832
876
  sendJson(res, proxied?.status || 502, proxied?.json || { error: 'GATEWAY_UNAVAILABLE' })
833
877
  return
834
878
  }
@@ -1059,7 +1103,8 @@ async function serveStatic(req, res, ctx) {
1059
1103
  return
1060
1104
  }
1061
1105
  res.writeHead(200, {
1062
- 'content-type': MIME[extname(abs)] ?? 'application/octet-stream',
1106
+ 'content-type': extname(abs) === '.apk' ? 'application/vnd.android.package-archive' : MIME[extname(abs)] ?? 'application/octet-stream',
1107
+ ...(extname(abs) === '.apk' ? { 'content-disposition': 'attachment; filename="dsh-remote.apk"', 'x-content-type-options': 'nosniff' } : {}),
1063
1108
  'content-length': info.size,
1064
1109
  'cache-control': 'no-cache',
1065
1110
  'last-modified': lastModified,
@@ -1068,7 +1113,10 @@ async function serveStatic(req, res, ctx) {
1068
1113
  res.end()
1069
1114
  return
1070
1115
  }
1071
- createReadStream(abs).pipe(res)
1116
+ const stream = createReadStream(abs)
1117
+ stream.on('error', () => res.destroy())
1118
+ res.on('close', () => stream.destroy())
1119
+ stream.pipe(res)
1072
1120
  }
1073
1121
 
1074
1122
  const pluginCenters = new WeakMap()
@@ -1121,6 +1169,10 @@ export function apply(ctx) {
1121
1169
  dshListen = { host: ctx.webServer.host, port: ctx.webServer.port }
1122
1170
  dshConnection = ctx.connection
1123
1171
  saveDshLaunchConfig(ctx)
1172
+ // Optional on older DSH: register the packaged read-only doctor skill when
1173
+ // the host exposes a skill registry. Failure never blocks the plugin.
1174
+ registerDoctorSkill(ctx)
1175
+ watchDoctorWorkspaces(ctx)
1124
1176
  ctx.effect(() => ctx.webServer.register({
1125
1177
  kind: 'prefix',
1126
1178
  path: MOUNT,
package/insights.mjs CHANGED
@@ -6,13 +6,17 @@ const text = (value, max = 80) => typeof value === 'string' ? value.slice(0, max
6
6
  const status = value => ['ok', 'off', 'error', 'stale', 'loading'].includes(value) ? value : 'unknown'
7
7
  function amount(value) {
8
8
  const row = record(value)
9
- return { cost: number(row.cost), apiCost: number(row.apiCost ?? row.cost), calls: number(row.calls) }
9
+ const tokens = Object.fromEntries(['input', 'cacheRead', 'cacheWrite', 'output'].map(key => [key, number(row[key])]))
10
+ const cost = number(row.cost), apiCost = number(row.apiCost)
11
+ return { cost, apiCost, planEquivalent: cost !== null && apiCost !== null && cost >= apiCost ? cost - apiCost : null, calls: number(row.calls), tokens,
12
+ totalTokens: Object.values(tokens).every(value => value !== null) ? Object.values(tokens).reduce((sum, value) => sum + value, 0) : null }
10
13
  }
11
- function windows(value) {
14
+ function windows(value, statistics) {
12
15
  return Object.entries(record(value)).slice(0, 8).map(([key, raw]) => {
13
16
  const row = record(raw), percent = number(row.percent)
17
+ const stat = record(record(statistics)[key] || record(statistics)[{ rolling: 'fiveHour', five_hour: 'fiveHour', seven_day: 'weekly' }[key]])
14
18
  return { name: text(key), percent: percent !== null && percent <= 100 ? percent : null,
15
- resetsAt: text(row.resetsAt), unlimited: row.unlimited === true }
19
+ resetsAt: text(row.resetsAt), unlimited: row.unlimited === true, localTokens: number(stat.localTokens) }
16
20
  })
17
21
  }
18
22
  export function summarizeCost(state, session, sessionId) {
@@ -21,17 +25,18 @@ export function summarizeCost(state, session, sessionId) {
21
25
  .filter(([, row]) => record(row).enabled === true && record(row).display !== 'off')
22
26
  .map(([name, value]) => {
23
27
  const row = record(value)
24
- return { name: text(name), status: status(row.status), fetchedAt: number(row.fetchedAt), windows: windows(row.windows) }
28
+ return { name: text(name), status: status(row.status), fetchedAt: number(row.fetchedAt), windows: windows(row.windows, record(record(raw.planStats).providers)[name]?.windows) }
25
29
  })
26
30
  const go = record(raw.goQuota)
27
31
  if (record(config.goQuota).enabled === true && record(config.goQuota).display !== 'off') {
28
32
  plans.unshift({ name: 'OpenCode Go', status: status(go.status), fetchedAt: number(go.fetchedAt),
29
- windows: windows({ rolling: go.rolling, weekly: go.weekly, monthly: go.monthly }).filter(row => row.percent !== null) })
33
+ windows: windows({ rolling: go.rolling, weekly: go.weekly, monthly: go.monthly }, record(record(raw.planStats).providers).go?.windows).filter(row => row.percent !== null) })
30
34
  }
31
35
  const s = record(session)
32
36
  return { schema: 1, available: true, source: 'dsh-cost-meter', generatedAt: Date.now(), currency: 'USD',
33
- day: text(record(raw.runtime).dayKey || record(raw.today).date, 10),
37
+ day: text(record(raw.meta).dayKey || record(raw.runtime).dayKey || record(raw.today).date, 10),
34
38
  today: config.hideTodayCost === true ? null : amount(raw.today),
39
+ history: config.hideTodayCost === true ? [] : (Array.isArray(raw.history) ? raw.history : []).slice(0, 90).filter(row => /^\d{4}-\d{2}-\d{2}$/.test(row?.date)).sort((a, b) => a.date.localeCompare(b.date)).slice(-7).map(row => ({ date: row.date, ...amount(row) })),
35
40
  session: sessionId ? { found: s.found === true, own: s.found === true ? amount(s.own) : null,
36
41
  subagents: s.found === true ? amount(s.subagents) : null, subagentCount: number(s.subagentCount) } : null,
37
42
  balance: config.hideOfficialBalance === true || record(config.balance).display === 'off' ? null : {
package/market.mjs ADDED
@@ -0,0 +1,83 @@
1
+ /* Read-only facade over DSH's official market. No index fetcher or ranking here. */
2
+ const packageName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
3
+ const versionName = /^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/
4
+ const text = (value, max = 300) => typeof value === 'string' ? value.slice(0, max) : ''
5
+ function localized(value) {
6
+ if (typeof value === 'string') return text(value)
7
+ return Object.fromEntries(Object.entries(value || {}).filter(([key, val]) => /^[a-z]{2}(?:-[A-Za-z]{2,4})?$/.test(key) && typeof val === 'string').slice(0, 8).map(([key, val]) => [key, text(val)]))
8
+ }
9
+ function safeUrl(value) {
10
+ try { const url = new URL(value); return /^https?:$/.test(url.protocol) && !url.username && !url.password && value.length <= 2048 ? url.href : '' } catch { return '' }
11
+ }
12
+ async function bounded(task, ms) {
13
+ let timer
14
+ try { return await Promise.race([task, new Promise((_, reject) => { timer = setTimeout(() => reject(Error('timeout')), ms) })]) } finally { clearTimeout(timer) }
15
+ }
16
+ function validQuery(query) {
17
+ if (!query || typeof query !== 'object' || Array.isArray(query) || Object.keys(query).some(key => !['text','category','labels','sort','offset','limit','fetchedAt','refresh'].includes(key))) return false
18
+ if (query.text != null && (typeof query.text !== 'string' || query.text.length > 80)) return false
19
+ if (query.category != null && (typeof query.category !== 'string' || query.category.length > 100)) return false
20
+ if (query.labels != null && (!Array.isArray(query.labels) || query.labels.length > 20 || query.labels.some(v => typeof v !== 'string' || v.length > 100))) return false
21
+ if (!Number.isSafeInteger(query.offset) || query.offset < 0 || !Number.isInteger(query.limit) || query.limit < 1 || query.limit > 100) return false
22
+ if (query.fetchedAt != null && (!Number.isSafeInteger(query.fetchedAt) || query.fetchedAt < 0) || query.refresh != null && typeof query.refresh !== 'boolean') return false
23
+ const sort = query.sort
24
+ if (!sort || typeof sort !== 'object' || Array.isArray(sort)) return false
25
+ if (['index','relevance'].includes(sort.kind)) return Object.keys(sort).length === 1
26
+ if (!['published','key'].includes(sort.kind) || !['asc','desc'].includes(sort.direction)) return false
27
+ return sort.kind === 'published' ? Object.keys(sort).length === 2 : Object.keys(sort).length === 3 && typeof sort.id === 'string' && !!sort.id && sort.id.length <= 100
28
+ }
29
+ export function createMarketAdapter(ctx, { timeoutMs = 20000 } = {}) {
30
+ function service() { try { return ctx.get?.('pluginMarket') } catch {} }
31
+ async function indexes() {
32
+ const host = service()
33
+ const base = { ok: true, source: 'official', indexes: [] }
34
+ if (!host) return { ...base, available: false, code: 'not-installed' }
35
+ if (typeof host.listIndexes !== 'function' || typeof host.search !== 'function') return { ...base, available: false, code: 'unsupported' }
36
+ try {
37
+ const rows = await bounded(Promise.resolve().then(() => host.listIndexes()), timeoutMs)
38
+ if (!Array.isArray(rows) || rows.length > 100) throw Error('unsupported')
39
+ return { ...base, available: true, indexes: rows.map(row => ({ url: safeUrl(row.url), title: localized(row.title), description: localized(row.description), ...(row.error || !safeUrl(row.url) ? { code: 'index-unavailable' } : {}) })) }
40
+ } catch { return { ...base, available: false, code: 'market-unavailable' } }
41
+ }
42
+ async function search(url, query) {
43
+ const empty = { ok: true, available: false, source: 'official', items: [], total: 0, nextOffset: null }
44
+ if (!validQuery(query)) return { ...empty, ok: false, code: 'invalid-query' }
45
+ const state = await indexes()
46
+ if (!state.available) return { ...empty, code: state.code }
47
+ const index = url ? state.indexes.find(row => row.url === url) : state.indexes.find(row => !row.code)
48
+ if (!index) return { ...empty, code: state.indexes.length ? 'unknown-index' : 'no-indexes' }
49
+ if (index.code) return { ...empty, code: 'index-unavailable' }
50
+ try {
51
+ const result = await bounded(Promise.resolve().then(() => service().search(index.url, query)), timeoutMs)
52
+ if (!Array.isArray(result.entries)) throw Error('invalid response')
53
+ const categories = Object.entries(result.metadata?.categories || {}).slice(0, 100).map(([id, row]) => ({ id: text(id, 100), title: localized(row.title) }))
54
+ const items = result.entries.slice(0, query.limit).filter(row => packageName.test(row.name)).map(row => {
55
+ const versions = Array.isArray(row.versions) ? row.versions : [], selected = versions.find(v => v.version === row.defaultVersion) || versions[0] || {}
56
+ return { name: row.name, version: text(selected.version, 100), title: localized(row.title), description: localized(row.description), author: text(row.author), homepage: safeUrl(row.homepage), repository: { url: safeUrl(row.repository?.url), directory: text(row.repository?.directory) }, category: text(row.metadata?.category, 100), versionCount: versions.length,
57
+ installSupported: selected.source?.type === 'npm' && (!selected.source.registry || safeUrl(selected.source.registry).replace(/\/$/, '') === 'https://registry.npmjs.org'),
58
+ installation: { status: ['not-installed','installed','update-available','different-version','provided'].includes(row.installation?.status) ? row.installation.status : 'unknown', installedVersion: text(row.installation?.installedVersion, 100) },
59
+ compatibility: typeof selected.compatibility?.compatible === 'boolean' ? { compatible: selected.compatibility.compatible, runtimeVersion: text(selected.compatibility.runtimeVersion, 100), requirements: { 'engines.dsh': text(selected.compatibility.requirements?.['engines.dsh'], 100) } } : null }
60
+ })
61
+ return { ok: true, available: true, source: 'official', index: { ...index, title: localized(result.title), description: localized(result.description) }, categories, items, total: Number.isSafeInteger(result.total) && result.total >= 0 ? result.total : items.length, nextOffset: Number.isSafeInteger(result.nextOffset) && result.nextOffset > query.offset ? result.nextOffset : null, fetchedAt: Number.isSafeInteger(result.fetchedAt) ? result.fetchedAt : null }
62
+ } catch { return { ...empty, code: 'market-unavailable' } }
63
+ }
64
+ return { indexes, search }
65
+ }
66
+
67
+ export function createReadmeReader(registry) {
68
+ const cache = new Map()
69
+ return async (name, version = '') => {
70
+ if (!packageName.test(name) || version && !versionName.test(version)) return { ok: false, code: 'invalid-name' }
71
+ try {
72
+ let record = cache.get(name)
73
+ if (!record || record.until < Date.now()) {
74
+ const data = await registry('/' + encodeURIComponent(name))
75
+ if (data.name !== name) throw Error('invalid package')
76
+ const content = typeof data.readme === 'string' ? data.readme : ''
77
+ record = { until: Date.now() + 600000, value: content.trim() ? { ok: true, available: true, source: 'npm', content: content.slice(0, 100000), truncated: content.length > 100000, version: versionName.test(data['dist-tags']?.latest || '') ? data['dist-tags'].latest : '', versionBasis: 'dist-tag:latest' } : { ok: true, available: false, code: 'no-readme' } }
78
+ cache.set(name, record); if (cache.size > 30) cache.delete(cache.keys().next().value)
79
+ }
80
+ return { ...record.value }
81
+ } catch { return { ok: false, code: 'readme-unavailable' } }
82
+ }
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.8.0-rc.4",
3
+ "version": "0.8.0-rc.8",
4
4
  "description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -20,10 +20,15 @@
20
20
  "cordis.patch.yml",
21
21
  "*.md",
22
22
  "plugin-center.mjs",
23
+ "plugin-transaction.mjs",
24
+ "market.mjs",
23
25
  "insights.mjs",
24
26
  "teams.mjs",
25
27
  "peak-reminders.mjs",
26
28
  "skills.mjs",
29
+ "doctor-skill.mjs",
30
+ "doctor-target.mjs",
31
+ "skills",
27
32
  "session-file.mjs"
28
33
  ],
29
34
  "keywords": [
@@ -26,12 +26,15 @@ export function peakReminderSchedule(config, now = Date.now()) {
26
26
  candidates.add(start + 16 * 3600000)
27
27
  for (const w of windows) { candidates.add(start + w.start * 3600000); candidates.add(start + w.end * 3600000) }
28
28
  }
29
- const events = [...candidates].sort((a,b) => a-b).flatMap(at => {
29
+ const transitions = [...candidates].sort((a,b) => a-b).flatMap(at => {
30
30
  const intoPeak = isPeak(at)
31
- if (at < now - 30 * 60000 || at > base.validUntil || isPeak(at - 1) === intoPeak || target !== 'both' && (target === 'peak') !== intoPeak) return []
31
+ if (at < now - 30 * 60000 || at > base.validUntil || isPeak(at - 1) === intoPeak) return []
32
32
  return [{ id: at + ':' + (intoPeak ? 'peak' : 'offpeak'), at, notifyAt: at - ahead * 60000, intoPeak }]
33
- }).slice(0,64)
34
- return { ...base, available: true, enabled: true, aheadMinutes: ahead, target, timezone: 'Asia/Shanghai', events }
33
+ })
34
+ const events = transitions.filter(e => target === 'both' || (target === 'peak') === e.intoPeak).slice(0,64)
35
+ // Status needs every boundary even when alerts target only peak or offpeak.
36
+ const phase = { intoPeak: isPeak(now), transitions: transitions.filter(e => e.at > now).map(({ at, intoPeak }) => ({ at, intoPeak })) }
37
+ return { ...base, available: true, enabled: true, aheadMinutes: ahead, target, timezone: 'Asia/Shanghai', phase, events }
35
38
  }
36
39
 
37
40
  export async function readPeakReminders(ctx) {