dsh-aupdate 0.3.1 → 0.4.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 (4) hide show
  1. package/README.md +28 -3
  2. package/client.js +106 -0
  3. package/index.js +53 -2
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -118,7 +118,17 @@ mtime 为准:那是磁盘事实。会话目录整个读不到时返回「不
118
118
  ## 设置页
119
119
 
120
120
  插件页里的这一行有摘要和整页两种视图,保存后立刻按新节奏重排,不用重启。
121
- 读写走 `/api/dsh-aupdate/{state,run,rollback}`。
121
+ 读写走 `/api/dsh-aupdate/{state,run,rollback,logs}`。
122
+
123
+ 整页最下面是**运行日志**卡片,直接看插件最近写了什么,不用再去翻文件:
124
+
125
+ - 可选显示最近 100 / 200 / 500 / 1000 行,默认 200
126
+ - 打开「自动刷新」后每 5 秒拉一次,正在排查时开着;关掉就完全不动
127
+ - 读之前会先把待写队列刷下去,所以刚点完检查,那几行马上就在里面
128
+ - 时间戳按本地时区显示,文件超过 1MB 轮转给一句提示,另附总行数
129
+
130
+ 日志只经由 `GET /api/dsh-aupdate/logs?lines=N` 读,参数夹在 1 到 1000 之间,
131
+ 不提供写入口——面板能看,但改不了日志。
122
132
 
123
133
  ## 效率
124
134
 
@@ -136,12 +146,24 @@ mtime 为准:那是磁盘事实。会话目录整个读不到时返回「不
136
146
 
137
147
  `~/.dsh/aupdate.log`,写完即刷,超过上限自动轮转。设置覆盖存于 `~/.dsh/aupdate-settings.json`。
138
148
 
149
+ 这个文件可以在设置页里直接看,见上一节。路径可用 `DSH_AUTO_UPDATE_LOG` 改。
150
+
139
151
  ## English
140
152
 
141
153
  Scheduled updater for the DSH plugins installed in a profile. It checks npm on an
142
154
  interval, installs one package at a time, and applies the result without restarting
143
- DSH. A settings page lets you change the policy, read the update history, and roll
144
- a bad version back.
155
+ DSH. A settings page lets you change the policy, read the update history, roll
156
+ a bad version back, and watch the run log without leaving the page.
157
+
158
+ The full-page view ends with a **run log** card, so you never have to go open the
159
+ file: pick the last 100 / 200 / 500 / 1000 lines (200 by default), and turn on
160
+ auto-refresh to poll every 5 seconds while you are debugging. The pending write
161
+ queue is flushed before reading, so lines from the check you just triggered are
162
+ already there. Timestamps render in local time, rotation past 1 MB is called out,
163
+ and the total line count is shown.
164
+
165
+ The log is read through `GET /api/dsh-aupdate/logs?lines=N` only, with the count
166
+ clamped between 1 and 1000. There is no write path: the page can look, not edit.
145
167
 
146
168
  ### Install
147
169
 
@@ -286,6 +308,9 @@ pile up one row per cycle and bury the entry you actually want to return to.
286
308
  `~/.dsh/aupdate.log`, flushed on write and rotated when it grows. Setting overrides
287
309
  live in `~/.dsh/aupdate-settings.json`.
288
310
 
311
+ You can read this file straight from the settings page (see above). Point it
312
+ elsewhere with `DSH_AUTO_UPDATE_LOG`.
313
+
289
314
  ## License
290
315
 
291
316
  MIT
package/client.js CHANGED
@@ -73,6 +73,16 @@ window.__ModuleLoader__.load({
73
73
  gateLocked: '另一个进程正在装:{who}',
74
74
  allowPrerelease: '允许预发布版本',
75
75
  allowPrereleaseHint: '关闭时只装正式版;走 next 标签的 DSH 本体不受影响',
76
+ logs: '运行日志',
77
+ logsHint: '插件最近写了什么。装完包、查到新版本、失败原因都在这里',
78
+ logsEmpty: '还没有日志;这个 profile 下这次启动还没跑过检查',
79
+ logsMissing: '日志文件不存在(还没跑过,或被删了)',
80
+ logsLines: '显示行数',
81
+ logsRefresh: '刷新',
82
+ logsAuto: '自动刷新',
83
+ logsAutoHint: '每 5 秒拉一次,正在排查时开着',
84
+ logsRotated: '日志已超过 1MB,旧内容在 .old 里',
85
+ logsTotal: '共 {n} 行',
76
86
  history: '更新记录',
77
87
  historyEmpty: '还没有安装过任何更新',
78
88
  rollback: '回滚',
@@ -148,6 +158,16 @@ window.__ModuleLoader__.load({
148
158
  gateLocked: 'another process is installing: {who}',
149
159
  allowPrerelease: 'Allow prereleases',
150
160
  allowPrereleaseHint: 'Off installs stable only; DSH itself on the next tag is unaffected',
161
+ logs: 'Run log',
162
+ logsHint: 'What the plugin has been doing: installs, new versions found, failure reasons',
163
+ logsEmpty: 'No log lines yet; no check has run in this profile since it started',
164
+ logsMissing: 'Log file does not exist (never ran, or it was deleted)',
165
+ logsLines: 'Lines',
166
+ logsRefresh: 'Refresh',
167
+ logsAuto: 'Auto refresh',
168
+ logsAutoHint: 'Polls every 5s; turn it on while debugging',
169
+ logsRotated: 'Log passed 1MB; older content is in .old',
170
+ logsTotal: '{n} lines',
151
171
  history: 'Update history',
152
172
  historyEmpty: 'No update has been installed yet',
153
173
  rollback: 'Roll back',
@@ -230,6 +250,15 @@ window.__ModuleLoader__.load({
230
250
  return response.json()
231
251
  }
232
252
 
253
+ async function getLogs(lines) {
254
+ const response = await fetch(endpoint('logs') + '?lines=' + encodeURIComponent(String(lines)), {
255
+ headers: { accept: 'application/json' },
256
+ cache: 'no-store',
257
+ })
258
+ if (!response.ok) throw new Error('logs ' + response.status)
259
+ return response.json()
260
+ }
261
+
233
262
  async function saveState(patch) {
234
263
  const response = await fetch(endpoint('state'), {
235
264
  method: 'POST',
@@ -281,6 +310,10 @@ window.__ModuleLoader__.load({
281
310
  status: { fontSize: '12px', opacity: 0.7 },
282
311
  err: { fontSize: '12px', color: '#d9534f' },
283
312
  meta: { display: 'flex', gap: '14px', flexWrap: 'wrap', fontSize: '12px', opacity: 0.7 },
313
+ // 等宽 + 可滚动:日志要能对齐看时间戳,也不能把整页顶长。
314
+ logBox: { margin: 0, padding: '8px 10px', borderRadius: '6px', border: '1px solid rgba(128,128,128,0.22)', background: 'rgba(128,128,128,0.06)', fontSize: '11.5px', lineHeight: 1.55, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', maxHeight: '260px', overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word' },
315
+ logTime: { opacity: 0.5 },
316
+ logText: {},
284
317
  }
285
318
 
286
319
  function Toggle(props) {
@@ -654,10 +687,83 @@ window.__ModuleLoader__.load({
654
687
  ),
655
688
  rollHint ? h('span', { style: S.status }, rollHint) : null,
656
689
  ),
690
+ h(LogCard, null),
657
691
  h('span', { style: S.hint }, T.scope),
658
692
  )
659
693
  }
660
694
 
695
+ /**
696
+ * 日志卡片。
697
+ *
698
+ * 单独成一个组件,而不是塞进 AutoUpdateCard:日志要能在「自动刷新」开着时
699
+ * 每 5 秒重渲染自己,不该把整张设置卡片连同输入框一起重渲染——那样光标会跳。
700
+ */
701
+ function LogCard() {
702
+ const [lines, setLines] = useState(200)
703
+ const [data, setData] = useState(null)
704
+ const [phase, setPhase] = useState('loading') // loading | ready | missing
705
+ const [auto, setAuto] = useState(false)
706
+ const [tick, setTick] = useState(0)
707
+
708
+ const refresh = useCallback(async () => {
709
+ try {
710
+ const next = await getLogs(lines)
711
+ setData(next)
712
+ setPhase(next?.exists === false ? 'missing' : 'ready')
713
+ } catch {
714
+ setPhase('missing')
715
+ }
716
+ }, [lines])
717
+
718
+ // lines 变了要立刻重取;tick 是自动刷新用来触发同一段逻辑的。
719
+ useEffect(() => { void refresh() }, [refresh, tick])
720
+
721
+ useEffect(() => {
722
+ if (!auto) return undefined
723
+ const timer = setInterval(() => setTick((n) => n + 1), 5000)
724
+ return () => clearInterval(timer)
725
+ }, [auto])
726
+
727
+ const rows = data?.rows ?? []
728
+ const total = data?.total ?? 0
729
+
730
+ return h('div', { style: S.card },
731
+ h('div', { style: S.row },
732
+ h('div', { style: S.labelBox },
733
+ h('span', { style: S.label }, T.logs),
734
+ h('span', { style: S.hint }, T.logsHint),
735
+ ),
736
+ h('div', { style: S.actions },
737
+ h('select', {
738
+ value: String(lines),
739
+ onChange: (event) => setLines(Number(event.target.value)),
740
+ style: S.select,
741
+ }, [100, 200, 500, 1000].map((n) => h('option', { key: n, value: String(n) }, n + ' ' + T.logsLines))),
742
+ h('button', { type: 'button', style: S.btn, onClick: () => setTick((n) => n + 1) }, T.logsRefresh),
743
+ ),
744
+ ),
745
+ h(SwitchRow, { label: T.logsAuto, hint: T.logsAutoHint, value: auto, onChange: setAuto }),
746
+ phase === 'loading' && data === null
747
+ ? h('span', { style: S.status }, '…')
748
+ : phase === 'missing' || (data !== null && data.exists === false)
749
+ ? h('span', { style: S.status }, T.logsMissing)
750
+ : rows.length === 0
751
+ ? h('span', { style: S.status }, T.logsEmpty)
752
+ : h('pre', { style: S.logBox, title: data?.path || '' },
753
+ rows.map((row, index) => h('div', { key: index },
754
+ row.at ? h('span', { style: S.logTime }, row.at.replace('T', ' ').replace('Z', '') + ' ') : null,
755
+ h('span', { style: S.logText }, row.text),
756
+ )),
757
+ ),
758
+ data !== null && data.exists !== false
759
+ ? h('div', { style: S.meta },
760
+ h('span', { title: data.path || '' }, T.logsTotal.replace('{n}', String(total))),
761
+ data.rotated === true ? h('span', null, T.logsRotated) : null,
762
+ )
763
+ : null,
764
+ )
765
+ }
766
+
661
767
  /**
662
768
  * 插件页里这一行有两个视图:收起时是 summary(一行摘要),展开后是整页。
663
769
  * summary 只报最关键的一件事——上次检查的结果,别把整页塞进一行。
package/index.js CHANGED
@@ -110,6 +110,44 @@ function flushLogNow() {
110
110
  } catch {}
111
111
  }
112
112
 
113
+ /** 设置页最多回看多少行。再多就不该在这个面板里看了,直接开文件。 */
114
+ const LOG_TAIL_MAX_LINES = 1000
115
+
116
+ /**
117
+ * 读日志尾部给设置页看。
118
+ *
119
+ * 日志文件满 1MB 就轮转成 .old,整份读进来再切尾巴比拼 offset 简单得多,
120
+ * 代价也就是一次 1MB 的同步读。读之前先把待写队列刷下去,否则「刚点了检查、
121
+ * 面板里却没有这一行」——差的就是 setImmediate 那一拍。
122
+ * 读不到不算错误:可能从没跑过检查,也可能用户把文件删了。
123
+ */
124
+ function readLogTail(limit) {
125
+ try {
126
+ flushLogNow()
127
+ } catch {}
128
+ const file = logPath()
129
+ const want = Math.min(Math.max(Math.floor(Number(limit)) || 200, 1), LOG_TAIL_MAX_LINES)
130
+ let raw
131
+ try {
132
+ raw = readFileSync(file, 'utf8')
133
+ } catch {
134
+ return { path: file, exists: false, size: 0, total: 0, rows: [], rotated: existsSync(file + '.old') }
135
+ }
136
+ const all = raw.split('\n')
137
+ // 每个进程都会补换行,split 后末尾必然多一个空串。
138
+ if (all.length > 0 && all[all.length - 1] === '') all.pop()
139
+ const rows = []
140
+ for (const line of all.slice(-want)) {
141
+ const match = /^\[([^\]]+)\] ([\s\S]*)$/u.exec(line)
142
+ rows.push(match === null ? { at: '', text: line } : { at: match[1], text: match[2] })
143
+ }
144
+ let size = 0
145
+ try {
146
+ size = statSync(file).size
147
+ } catch {}
148
+ return { path: file, exists: true, size, total: all.length, rows, rotated: existsSync(file + '.old') }
149
+ }
150
+
113
151
  /** 防御性读属性:Cordis 对未声明的读会抛。 */
114
152
  function propOf(target, key) {
115
153
  try {
@@ -1549,7 +1587,11 @@ function settingsSnapshot(config, ctxRef) {
1549
1587
  history: readHistory().slice(0, 40),
1550
1588
  historyPath: historyPath(),
1551
1589
  // 下一轮什么时候跑:设置页把它直接显示出来,用户不用自己推算。
1552
- nextInMinutes: nextDelayMinutes(settings, new Date()),
1590
+ // 调度器已经把「这一轮真实等多久」记在 pendingMinutes 上,优先用它;
1591
+ // 取不到(比如定时器还没排上)才退回按当前规则现算。
1592
+ nextInMinutes: typeof ctxRef?.pendingMinutes === 'number'
1593
+ ? ctxRef.pendingMinutes
1594
+ : nextDelayMinutes(settings, new Date()),
1553
1595
  // 被抑制的 pkg@版本:让人看得见「为什么这个包不更新了」。
1554
1596
  failures: readFailures().slice(0, 20).map((row) => {
1555
1597
  const at = Date.parse(String(row.at ?? ''))
@@ -1599,6 +1641,10 @@ function registerRoutes(scope, ctxRef) {
1599
1641
  sendJson(res, 200, settingsSnapshot(ctxRef.config, ctxRef))
1600
1642
  return
1601
1643
  }
1644
+ if (suffix === '/logs') {
1645
+ sendJson(res, 200, readLogTail(url.searchParams.get('lines')))
1646
+ return
1647
+ }
1602
1648
  sendJson(res, 404, { error: 'unknown endpoint' })
1603
1649
  return
1604
1650
  }
@@ -1673,7 +1719,7 @@ function registerRoutes(scope, ctxRef) {
1673
1719
  }
1674
1720
  }
1675
1721
 
1676
- export { compareVersions, upgradeVerdict, pickRollbackTarget, readHistory, historyPath, distTagFor, cliRunner, dependencyList, installedVersion, registryTags, hotApply, runCycle, settingsOf, readOverrides, writeOverrides, takeProfileLock, releaseProfileLock, sessionAgeMinutes, activityReasons, settingsSnapshot, snapshotProfile, snapshotRoot, pruneSnapshots, nextDelayMinutes }
1722
+ export { compareVersions, upgradeVerdict, pickRollbackTarget, readHistory, historyPath, distTagFor, cliRunner, dependencyList, installedVersion, registryTags, hotApply, runCycle, settingsOf, readOverrides, writeOverrides, takeProfileLock, releaseProfileLock, sessionAgeMinutes, activityReasons, settingsSnapshot, snapshotProfile, snapshotRoot, pruneSnapshots, nextDelayMinutes, readLogTail, logPath }
1677
1723
 
1678
1724
  export function apply(ctx, config) {
1679
1725
  const ctxRef = { ctx, config }
@@ -1766,6 +1812,7 @@ export function apply(ctx, config) {
1766
1812
  let firstPending = true
1767
1813
 
1768
1814
  const clearScheduled = () => {
1815
+ ctxRef.pendingMinutes = null
1769
1816
  if (scheduled === null) return
1770
1817
  try {
1771
1818
  clearTimeout(scheduled)
@@ -1784,6 +1831,10 @@ export function apply(ctx, config) {
1784
1831
  // 启动后第一次仍然只看 firstDelayMinutes,之后按当前调度模式算。
1785
1832
  const minutes = firstPending && live.checkOnStart ? live.firstDelayMinutes : nextDelayMinutes(live, new Date())
1786
1833
  firstPending = false
1834
+ // 记下这一轮真实的等待时长,设置页按它显示「下一轮」。
1835
+ // 直接拿 nextDelayMinutes 算会漏掉启动后那次短期检查:明明 5 分钟后就要跑,
1836
+ // 面板却显示 1440 分钟,看的人只会以为「启动后根本不查」,于是手动点一次。
1837
+ ctxRef.pendingMinutes = minutes
1787
1838
  const handle = setTimeout(() => {
1788
1839
  scheduled = null
1789
1840
  runSafely('update')
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-aupdate",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
- "description": "定时检查 DSH 插件更新,串行安装后就地生效,不重启;支持多种调度节奏、失败抑制、按包回滚,并在动手前留快照、忙时自动让开。",
5
+ "description": "定时检查 DSH 插件更新,串行安装后就地生效,不重启;支持多种调度节奏、失败抑制、按包回滚,并在动手前留快照、忙时自动让开;设置页里可直接查看运行日志。",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",