dsh-sitmax 0.0.0-stage → 1.0.1

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.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # dsh-sitmax-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DSH 插件包(npm bundle 形态,**自用、不分发**):久坐监督「跑道小人」。
4
+
5
+ - 顶部居中:**环形操场跑道**,一个小人沿跑道跑动(即本轮久坐进度,默认 15 分钟跑完一圈),跑道中心的沙金小字显示已坐时间 / 状态;
6
+ - 每连续坐 30 分钟弹出「该起来走走了」卡片(可休息 5 分钟 / 暂缓 5 分钟),附桌面系统通知 + 提示音;
7
+ - 键鼠活动检测:无操作自动暂停,回来智能恢复,离开过久自动按一次休息重置;**默认使用 Windows 系统级空闲检测(`GetLastInputInfo`)**——在别的软件/标签页活动也算在工作,只有整个系统都无输入才判定离开(仅 Windows;不可用时自动回退为页面内检测);
8
+ - 设置页(`settings.section`):循环/提醒/休息/暂缓/离开判定时长 + 开关,存 localStorage;
9
+ - 每日报告页:今天久坐时长、提醒/休息/轮次次数,近 7 天柱状图。
10
+
11
+ ## 目录结构(本目录即 npm 包)
12
+
13
+ | 文件 | 作用 |
14
+ | --- | --- |
15
+ | `package.json` | 包清单:`dsh.bundle.patch` + `dsh.client`(web 平台) |
16
+ | `cordis.patch.yml` | bundle 补丁层:向组合树插入一行 `dsh-sitmax` |
17
+ | `host.cjs` | Host 半部:常驻 PowerShell 子进程轮询 Windows `GetLastInputInfo`(系统级键鼠空闲),经 `/api/dsh-sitmax/idle` 供浏览器端读取 |
18
+ | `src-client/index.js` | 浏览器半部:HUD + 弹窗 + 设置页 + 报告页 |
19
+ | `lib/client.js` | 构建产物(`build-client.cjs` 生成,随包发布) |
20
+ | `build-client.cjs` | 客户端 bundle 构建脚本(无外部构建依赖) |
21
+
22
+ ## 安装 / 升级(自用)
23
+
24
+ ```powershell
25
+ # 安装(本机 link 安装)
26
+ dsh plugin --profile web add D:\traeProjects\harness-plugins\dsh-sitmax-plugin
27
+
28
+ # 改动 src-client/ 后重新构建,再重启 dsh web
29
+ node build-client.cjs
30
+ ```
31
+
32
+ bundle 列表在 dsh web 启动时读取,安装/升级后需重启 dsh web 生效。
33
+
34
+ ## 使用
35
+
36
+ - 点跑道:手动暂停 / 继续;
37
+ - **收起 / 展开**:平时只显示 30px 的小进度环(不挡界面),悬停展开完整跑道 + 时间 + 按钮;
38
+ - **可拖动**:按住拖到任意位置,位置存 localStorage(`dsh.sitmax.pos.v1`)自动记住;**双击复位**回顶部居中;
39
+ - 左侧栏「设置」→「久坐沙漏 · 设置 / 报告」;
40
+ - 桌面通知首次使用需在设置页点「请求 / 测试桌面通知」授权;
41
+ - 数据(配置 + 每日历史)存在浏览器 localStorage(`dsh.sitmax.cfg.v1` / `dsh.sitmax.hist.v1`),跨会话累计。
@@ -0,0 +1,7 @@
1
+ # dsh-sitmax bundle patch layer: inserts one row into the composed tree.
2
+ # Client-only bundle: host.cjs is an inert row holder; the dsh.client
3
+ # declaration contributes the browser HUD + reminder popup + settings and
4
+ # report pages.
5
+ - insert:
6
+ - id: dsh-sitmax
7
+ name: dsh-sitmax
package/host.cjs ADDED
@@ -0,0 +1,222 @@
1
+ // dsh-sitmax host plugin (npm bundle node half): system-wide idle detection.
2
+ // A browser page can only see its own keyboard/mouse events; to know whether
3
+ // the USER (not the page) is active, this half runs one long-lived PowerShell
4
+ // child that polls the Windows GetLastInputInfo API and prints `IDLE <ms>`
5
+ // lines every second, then serves the latest sample at /api/dsh-sitmax/idle.
6
+ //
7
+ // The route registers unconditionally: the monitor child may fail (non-Windows,
8
+ // spawn error, exit), and the route then reports `supported: false` so the
9
+ // client HUD falls back to page-local detection instead of breaking.
10
+ 'use strict'
11
+
12
+ const { spawn } = require('node:child_process')
13
+ const https = require('node:https')
14
+
15
+ // One PowerShell child: compile the P/Invoke wrapper once, then print the
16
+ // system-wide idle milliseconds every second as `IDLE <ms>` lines (UTF-8,
17
+ // flushed) on stdout.
18
+ const PS_SCRIPT = [
19
+ "$src = @'",
20
+ 'using System;',
21
+ 'using System.Runtime.InteropServices;',
22
+ 'public static class ConsoleIdle {',
23
+ ' [StructLayout(LayoutKind.Sequential)]',
24
+ ' struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }',
25
+ ' [DllImport("user32.dll")]',
26
+ ' static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);',
27
+ ' public static uint GetIdleTicks() {',
28
+ ' LASTINPUTINFO lii = new LASTINPUTINFO();',
29
+ ' lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));',
30
+ ' if (!GetLastInputInfo(ref lii)) return 0;',
31
+ ' return unchecked((uint)Environment.TickCount) - lii.dwTime;',
32
+ ' }',
33
+ '}',
34
+ "'@",
35
+ 'Add-Type -TypeDefinition $src',
36
+ "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
37
+ 'while ($true) {',
38
+ ' try { $t = [ConsoleIdle]::GetIdleTicks() } catch { $t = 0 }',
39
+ " [Console]::Out.WriteLine('IDLE ' + $t)",
40
+ ' [Console]::Out.Flush()',
41
+ ' Start-Sleep -Milliseconds 1000',
42
+ '}',
43
+ ].join('\n')
44
+
45
+ module.exports = {
46
+ name: 'dsh-sitmax',
47
+ inject: ['webServer'],
48
+ apply(ctx) {
49
+ const webServer = ctx.webServer
50
+
51
+ const state = {
52
+ supported: false,
53
+ idleMs: null,
54
+ sampleAt: 0,
55
+ attempts: 0,
56
+ lastError: null,
57
+ idlePeak: 0,
58
+ idlePeakEndedAt: 0,
59
+ idlePeakLast: 0,
60
+ }
61
+
62
+ let child = null
63
+ let stopped = false
64
+
65
+ // Chinese statutory holiday calendar (timor.tech, no key required): per
66
+ // year a map of MM-DD → { holiday, name }. holiday=false entries are
67
+ // make-up workdays (调休上班). Cached for a day; failures are retried
68
+ // after 30 minutes.
69
+ const holidaysCache = new Map()
70
+ function fetchHolidays(year) {
71
+ return new Promise((resolve, reject) => {
72
+ const req = https.get('https://timor.tech/api/holiday/year/' + year, (res) => {
73
+ let d = ''
74
+ res.on('data', (c) => { d += c })
75
+ res.on('end', () => {
76
+ try { resolve(JSON.parse(d)) } catch (err) { reject(err) }
77
+ })
78
+ })
79
+ req.on('error', reject)
80
+ req.setTimeout(8000, () => { req.destroy(new Error('holiday fetch timeout')) })
81
+ })
82
+ }
83
+
84
+ function start() {
85
+ if (stopped || process.platform !== 'win32') return
86
+ let proc = null
87
+ try {
88
+ proc = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', PS_SCRIPT], {
89
+ stdio: ['ignore', 'pipe', 'pipe'],
90
+ windowsHide: true,
91
+ })
92
+ } catch (err) {
93
+ state.lastError = String(err && err.message ? err.message : err)
94
+ return
95
+ }
96
+ child = proc
97
+ let buf = ''
98
+ let errBuf = ''
99
+ proc.stdout.on('data', (chunk) => {
100
+ buf += chunk.toString('utf8')
101
+ const lines = buf.split(/\r?\n/)
102
+ buf = lines.pop()
103
+ for (const line of lines) {
104
+ const m = /^IDLE (\d+)$/.exec(line.trim())
105
+ if (m !== null) {
106
+ const idle = Number(m[1])
107
+ state.idleMs = idle
108
+ state.sampleAt = Date.now()
109
+ state.supported = true
110
+ state.attempts = 0
111
+ state.lastError = null
112
+ // Track away stretches: the peak idle of the current stretch, and
113
+ // the timestamp at which it ended (idle dropped below 2s). The
114
+ // browser tab may be throttled/frozen during a locked workstation,
115
+ // so the client corrects its sitting clock from these values when
116
+ // it comes back.
117
+ if (idle < 2000) {
118
+ if (state.idlePeak >= 5000) {
119
+ state.idlePeakLast = state.idlePeak
120
+ state.idlePeakEndedAt = Date.now()
121
+ }
122
+ state.idlePeak = idle
123
+ } else if (idle > state.idlePeak) {
124
+ state.idlePeak = idle
125
+ }
126
+ }
127
+ }
128
+ })
129
+ proc.stderr.on('data', (chunk) => {
130
+ errBuf += chunk.toString('utf8')
131
+ if (errBuf.length > 4000) errBuf = errBuf.slice(-4000)
132
+ if (state.supported === false) state.lastError = errBuf.slice(-300)
133
+ })
134
+ proc.on('error', (err) => {
135
+ state.lastError = String(err && err.message ? err.message : err)
136
+ })
137
+ proc.on('exit', () => {
138
+ if (child === proc) child = null
139
+ if (stopped) return
140
+ state.supported = false
141
+ state.idleMs = null
142
+ // Never give up: retry with capped exponential backoff so a transient
143
+ // PowerShell death can always recover without a dsh restart.
144
+ state.attempts += 1
145
+ setTimeout(start, Math.min(30000, 5000 * state.attempts))
146
+ })
147
+ }
148
+
149
+ ctx.effect(() => {
150
+ start()
151
+ return () => {
152
+ stopped = true
153
+ if (child !== null) {
154
+ try { child.kill() } catch (err) { }
155
+ child = null
156
+ }
157
+ }
158
+ })
159
+
160
+ ctx.effect(() => webServer.register({
161
+ kind: 'exact',
162
+ path: '/api/dsh-sitmax/idle',
163
+ handler(req, res) {
164
+ const body = JSON.stringify({
165
+ ok: true,
166
+ supported: state.supported,
167
+ idleMs: state.idleMs,
168
+ ageMs: state.sampleAt === 0 ? null : Date.now() - state.sampleAt,
169
+ idlePeak: state.idlePeak,
170
+ idlePeakLast: state.idlePeakLast,
171
+ idlePeakEndedAt: state.idlePeakEndedAt,
172
+ lastError: state.lastError,
173
+ })
174
+ res.writeHead(200, {
175
+ 'content-type': 'application/json; charset=utf-8',
176
+ 'cache-control': 'no-store',
177
+ })
178
+ res.end(body)
179
+ },
180
+ }))
181
+
182
+ ctx.effect(() => webServer.register({
183
+ kind: 'exact',
184
+ path: '/api/dsh-sitmax/holidays',
185
+ handler(req, res) {
186
+ const url = new URL(req.url ?? '/', 'http://x')
187
+ const year = Number(url.searchParams.get('year')) || new Date().getFullYear()
188
+ const serve = (ok, map, error) => {
189
+ res.writeHead(200, {
190
+ 'content-type': 'application/json; charset=utf-8',
191
+ 'cache-control': 'no-store',
192
+ })
193
+ res.end(JSON.stringify({ ok, year, map: map || null, error: error || null }))
194
+ }
195
+ const cached = holidaysCache.get(year)
196
+ if (cached !== undefined) {
197
+ const age = Date.now() - cached.at
198
+ if (cached.map !== null && age < 86400000) return serve(true, cached.map)
199
+ if (cached.map === null && age < 1800000) return serve(false, null, 'holiday fetch recently failed, retrying later')
200
+ }
201
+ fetchHolidays(year).then((j) => {
202
+ if (!j || j.code !== 0 || typeof j.holiday !== 'object' || j.holiday === null) {
203
+ holidaysCache.set(year, { at: Date.now(), map: null })
204
+ return serve(false, null, 'holiday api returned an unexpected shape')
205
+ }
206
+ const map = {}
207
+ for (const k of Object.keys(j.holiday)) {
208
+ const e = j.holiday[k]
209
+ if (e && typeof e === 'object' && typeof e.holiday === 'boolean') {
210
+ map[year + '-' + k] = { holiday: e.holiday, name: typeof e.name === 'string' ? e.name : '' }
211
+ }
212
+ }
213
+ holidaysCache.set(year, { at: Date.now(), map })
214
+ serve(true, map)
215
+ }).catch((err) => {
216
+ holidaysCache.set(year, { at: Date.now(), map: null })
217
+ serve(false, null, String(err && err.message ? err.message : err))
218
+ })
219
+ },
220
+ }))
221
+ },
222
+ }