agent-things 0.0.0-stage → 1.2.2

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 (124) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +5 -0
  3. package/README.md +221 -2
  4. package/bin/agent-things.cjs +8 -0
  5. package/bin/antigravity-session-status.cjs +96 -0
  6. package/bin/claude-session-status.cjs +55 -0
  7. package/bin/codex-session-status.cjs +287 -0
  8. package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
  9. package/mods/agent-things-ui/SKILL.md +10 -0
  10. package/mods/agent-things-ui/hooks/controls.js +112 -0
  11. package/mods/agent-things-ui/hooks/foundation.js +431 -0
  12. package/mods/agent-things-ui/hooks/hooks.json +1 -0
  13. package/mods/agent-things-ui/hooks/presentation.js +223 -0
  14. package/mods/agent-things-ui/hooks/progress.js +1 -0
  15. package/mods/agent-things-ui/hooks/register.js +382 -0
  16. package/native/bin/bridge +0 -0
  17. package/native/bin/bridge.json +20 -0
  18. package/native/session-status-bridge.swift +280 -0
  19. package/outputs/antigravity-session-status.js +2476 -0
  20. package/outputs/codex-session-status.js +1761 -0
  21. package/package.json +75 -4
  22. package/scripts/build-antigravity-bundle.cjs +35 -0
  23. package/scripts/build-codex-bundle.cjs +31 -0
  24. package/scripts/build-native-bridge.cjs +55 -0
  25. package/scripts/build-shared-ui.cjs +16 -0
  26. package/scripts/setup-antigravity-service.cjs +71 -0
  27. package/scripts/setup-claude-service.cjs +21 -0
  28. package/skills/agent-things/SKILL.en.md +95 -0
  29. package/skills/agent-things/SKILL.md +99 -0
  30. package/skills/codex/things/SKILL.en.md +10 -0
  31. package/skills/codex/things/SKILL.md +10 -0
  32. package/skills/things/SKILL.en.md +10 -0
  33. package/skills/things/SKILL.md +10 -0
  34. package/skills/things/checklist.en.md +91 -0
  35. package/skills/things/checklist.md +95 -0
  36. package/src/analysis-app-server.cjs +74 -0
  37. package/src/analysis-assets/output.en.schema.json +93 -0
  38. package/src/analysis-assets/output.schema.json +93 -0
  39. package/src/analysis-assets/prompt.en.txt +17 -0
  40. package/src/analysis-assets/prompt.zh-CN.txt +18 -0
  41. package/src/analysis-budget.cjs +105 -0
  42. package/src/analysis-git.cjs +38 -0
  43. package/src/analysis-history.cjs +150 -0
  44. package/src/analysis-ledger.cjs +82 -0
  45. package/src/analysis-log.cjs +62 -0
  46. package/src/analysis-runner.cjs +203 -0
  47. package/src/analysis-service.cjs +197 -0
  48. package/src/analysis-source.cjs +72 -0
  49. package/src/antigravity-card.cjs +2063 -0
  50. package/src/antigravity-hook.cjs +138 -0
  51. package/src/antigravity-mcp-config.cjs +36 -0
  52. package/src/app-server.cjs +96 -0
  53. package/src/cdp.cjs +115 -0
  54. package/src/claude-inline-install.cjs +38 -0
  55. package/src/claude-mcp-config.cjs +29 -0
  56. package/src/cli/arguments.cjs +30 -0
  57. package/src/cli/environment-probe.cjs +130 -0
  58. package/src/cli/integration-state.cjs +15 -0
  59. package/src/cli/interactive-cli.cjs +236 -0
  60. package/src/cli/prompt-tui.cjs +420 -0
  61. package/src/cli/setup-orchestrator.cjs +449 -0
  62. package/src/codex-mcp-config.cjs +67 -0
  63. package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
  64. package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
  65. package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
  66. package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
  67. package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
  68. package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
  69. package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
  70. package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
  71. package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
  72. package/src/harnesses/antigravity/transcript-source.cjs +100 -0
  73. package/src/harnesses/claude/claude-harness.js +93 -0
  74. package/src/harnesses/claude/claude-host-helper.cjs +176 -0
  75. package/src/harnesses/claude/claude-injector.cjs +95 -0
  76. package/src/harnesses/claude/claude-local-source.cjs +106 -0
  77. package/src/harnesses/claude/claude-navigation.cjs +99 -0
  78. package/src/harnesses/claude/claude-runner.cjs +74 -0
  79. package/src/harnesses/claude/claude-service.cjs +313 -0
  80. package/src/harnesses/claude/claude-source.cjs +70 -0
  81. package/src/harnesses/codex/codex-analysis.cjs +10 -0
  82. package/src/harnesses/codex/codex-card-bridge.js +123 -0
  83. package/src/harnesses/codex/codex-card-events.cjs +76 -0
  84. package/src/harnesses/codex/codex-card.cjs +169 -0
  85. package/src/harnesses/codex/codex-git.cjs +24 -0
  86. package/src/harnesses/codex/codex-harness.js +229 -0
  87. package/src/harnesses/codex/codex-local-card.js +97 -0
  88. package/src/harnesses/codex/codex-progress-context.cjs +84 -0
  89. package/src/harnesses/codex/codex-service.cjs +502 -0
  90. package/src/i18n.cjs +174 -0
  91. package/src/launchd.cjs +105 -0
  92. package/src/lifecycle-lock.cjs +13 -0
  93. package/src/local-progress-http.cjs +267 -0
  94. package/src/manual-status-agent.cjs +12 -0
  95. package/src/manual-status-startup.cjs +66 -0
  96. package/src/manual-status-store.cjs +466 -0
  97. package/src/mcp-stdio.cjs +67 -0
  98. package/src/model-router.cjs +63 -0
  99. package/src/native-bridge.cjs +17 -0
  100. package/src/npm-updates.cjs +228 -0
  101. package/src/plugins/things/assets/logo.svg +13 -0
  102. package/src/plugins/things/plugin.json +6 -0
  103. package/src/plugins/things/sidecars/things_board/app.js +447 -0
  104. package/src/plugins/things/sidecars/things_board/index.html +2141 -0
  105. package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
  106. package/src/plugins/things/sidecars/things_board/package.json +6 -0
  107. package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
  108. package/src/plugins/things/sidecars/things_board/styles.css +560 -0
  109. package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
  110. package/src/progress-error.cjs +54 -0
  111. package/src/progress-tools.cjs +145 -0
  112. package/src/project-path.cjs +15 -0
  113. package/src/renderer-resource.cjs +17 -0
  114. package/src/request-budget.cjs +24 -0
  115. package/src/resolve.cjs +51 -0
  116. package/src/runtime-install.cjs +635 -0
  117. package/src/session-status-filter.cjs +136 -0
  118. package/src/session-status.js +992 -0
  119. package/src/session-view.cjs +34 -0
  120. package/src/startup/controller.cjs +354 -0
  121. package/src/startup/watch.cjs +126 -0
  122. package/src/state-file-lock.cjs +31 -0
  123. package/src/task-provenance.cjs +42 -0
  124. package/src/ui-foundation.cjs +435 -0
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const vm = require('node:vm');
7
+ const { tryAcquirePidLock } = require('../src/state-file-lock.cjs');
8
+ const { ManualStatusStore } = require('../src/manual-status-store.cjs');
9
+ const { ManualStatusAgent, attachmentStatus } = require('../src/manual-status-agent.cjs');
10
+ const { CDP_PORT } = require('../src/cdp.cjs');
11
+ const { installAutostart, disableAutostart, startupStatus } = require('../src/manual-status-startup.cjs');
12
+ const { installCodexMcp, disableCodexMcp } = require('../src/codex-mcp-config.cjs');
13
+ const { runInteractiveCli, showHealthStatus } = require('../src/cli/interactive-cli.cjs');
14
+ const { readConfiguredLang } = require('../src/i18n.cjs');
15
+
16
+ function resolveSessionKey(store, convId) { return store.resolveKey(convId); }
17
+
18
+ async function runMcpServer({ store, directory, port }) {
19
+ const { assertIntegrationEnabled } = require('../src/cli/integration-state.cjs');
20
+ assertIntegrationEnabled('codex');
21
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
22
+ const lock = path.join(directory, 'agent.lock');
23
+
24
+ let agent = null;
25
+ let scanTimer = null;
26
+ const canRunAgent = tryAcquirePidLock(lock);
27
+
28
+ if (canRunAgent) {
29
+ try {
30
+ store.recoverPending();
31
+ agent = new ManualStatusAgent({
32
+ store,
33
+ port,
34
+ logFile: path.join(os.homedir(), 'Library', 'Logs', 'CodexSessionStatus', 'analysis.jsonl'),
35
+ onError: err => process.stderr.write(`[agent-things codex] ${err.message}\n`),
36
+ });
37
+ await agent.startControl();
38
+ const scan = async () => {
39
+ try { assertIntegrationEnabled('codex'); await agent.scan(); }
40
+ catch (error) { if (error.code === 'INTEGRATION_DISABLED') await cleanup(); }
41
+ };
42
+ scanTimer = setInterval(scan, 2500);
43
+ scan();
44
+ } catch (err) {
45
+ if (agent) { await agent.stop(); agent = null; }
46
+ if (fs.existsSync(lock) && fs.readFileSync(lock, 'utf8').trim() === String(process.pid)) fs.unlinkSync(lock);
47
+ if (err.code !== 'EEXIST') throw err;
48
+ }
49
+ }
50
+
51
+
52
+ async function cleanup() {
53
+ if (scanTimer) clearInterval(scanTimer);
54
+ if (agent) {
55
+ try { await agent.stop(); } catch {}
56
+ agent = null;
57
+ }
58
+ if (fs.existsSync(lock)) {
59
+ try {
60
+ if (fs.readFileSync(lock, 'utf8').trim() === String(process.pid)) {
61
+ fs.unlinkSync(lock);
62
+ }
63
+ } catch {}
64
+ }
65
+ };
66
+
67
+ const { serveMcp } = require('../src/mcp-stdio.cjs');
68
+ const { requestProgressHttp } = require('../src/local-progress-http.cjs');
69
+ const { createCodexCard, tools: staticExtraTools, getCardTools, resource } = require('../src/harnesses/codex/codex-card.cjs');
70
+ const card = createCodexCard({ store });
71
+ serveMcp({ name: 'codex-session-status', extraTools: lang => getCardTools(lang), resource,
72
+ onClose: async () => {
73
+ card.stopEvents();
74
+ if (agent?.analysisService) await Promise.allSettled([...agent.analysisService.active.values()].map(job => job.promise));
75
+ await cleanup();
76
+ },
77
+ callTool: async (name, args, meta, options) => {
78
+ assertIntegrationEnabled('codex');
79
+ if (staticExtraTools.some(tool => tool.name === name)) return card.call(name, args, meta, options);
80
+ return (await requestProgressHttp(store.file, '/tools', { name, args }, undefined, options)).value;
81
+ },
82
+ });
83
+
84
+ process.once('SIGINT', () => cleanup().then(() => process.exit(0)));
85
+ process.once('SIGTERM', () => cleanup().then(() => process.exit(0)));
86
+ }
87
+
88
+ async function main() {
89
+ const options = require('../src/cli/arguments.cjs').parseArguments(process.argv.slice(2));
90
+ if (options.command === 'setup') {
91
+ await runInteractiveCli({ yes: options.yes, lang: options.lang });
92
+ return;
93
+ }
94
+ if (options.command === 'doctor') {
95
+ await showHealthStatus();
96
+ return;
97
+ }
98
+ const { command, port, watchStartup } = options;
99
+ const directory = options.directory || path.join(os.homedir(), 'Library/Application Support/CodexSessionStatus');
100
+ const en = readConfiguredLang({ dataDir: directory }) === 'en';
101
+
102
+ if (command === 'help' || command === '--help' || command === '-h') {
103
+ if (en) {
104
+ console.log('Usage: agent-things [command] [options]\n');
105
+ console.log('Run with no arguments: launch interactive wizard (environment probe, language toggle, app selection, background daemon)\n');
106
+ console.log('Core commands:');
107
+ console.log(' setup Interactive setup & management; --yes/--all auto-configures detected apps; --lang zh|en');
108
+ console.log(' doctor Inspect client, daemon, and mounting diagnostics');
109
+ console.log(' run Run foreground debug mode on port 39222 and attach UI (Ctrl+C to exit)');
110
+ console.log(' status Print recorded session progress snapshot (JSON)');
111
+ console.log(' mcp Run as native companion MCP server (JSON-RPC stdio)');
112
+ console.log(' install-mcp Register this server in ~/.codex/config.toml as a native companion MCP server');
113
+ console.log(' disable-mcp Remove this companion MCP server from ~/.codex/config.toml');
114
+ console.log(' update-renderer / install-autostart / disable-autostart: advanced renderer updates & Codex autostart management');
115
+ console.log(' run/status/mcp support --port; run/status/mcp/update-renderer/install-autostart support --data-dir; run supports --watch-startup');
116
+ } else {
117
+ console.log('用法:agent-things [command] [options]\n');
118
+ console.log('无参数直接运行:启动交互式向导(环境探测、中英切换、App 多选、后台无感常驻)\n');
119
+ console.log('核心命令:');
120
+ console.log(' setup 交互式安装与管理;--yes/--all 自动配置已安装的支持应用;--lang zh|en');
121
+ console.log(' doctor 查看客户端、后台和挂载诊断');
122
+ console.log(' run 前台运行调试模式,连接 39222 端口并挂载 UI (按 Ctrl+C 退出)');
123
+ console.log(' status 查看已记录会话进度快照 (JSON)');
124
+ console.log(' mcp 作为原生 MCP 伴生服务运行 (JSON-RPC stdio)');
125
+ console.log(' install-mcp 将本服务写入 ~/.codex/config.toml 中作为原生伴生 MCP 服务');
126
+ console.log(' disable-mcp 从 ~/.codex/config.toml 中移除伴生 MCP 服务');
127
+ console.log(' update-renderer / install-autostart / disable-autostart:高级面板更新与Codex后台管理');
128
+ console.log(' run/status/mcp 支持 --port;run/status/mcp/update-renderer/install-autostart 支持 --data-dir;run 支持 --watch-startup');
129
+ }
130
+ return;
131
+ }
132
+
133
+ if (command === 'install-mcp') {
134
+ const scriptPath = path.join(directory, 'runtime/bin/codex-session-status.cjs');
135
+ if (!fs.existsSync(scriptPath)) throw new Error(en ? 'Please run agent-things setup first to install the runtime.' : '请先运行 agent-things setup 安装运行时。');
136
+ const res = installCodexMcp({ scriptPath });
137
+ console.log(en
138
+ ? `✅ Registered Agent Things (session_status) as a native Codex MCP server!\nConfig file: ${res.file}`
139
+ : `✅ 已成功将 Agent Things (session_status) 注册为 Codex 原生伴生 MCP 服务!\n配置文件:${res.file}`);
140
+ return;
141
+ }
142
+
143
+ if (command === 'disable-mcp') {
144
+ const res = disableCodexMcp({});
145
+ console.log(en
146
+ ? (res.removed ? '✅ Removed Agent Things (session_status) from ~/.codex/config.toml.' : 'ℹ️ No Agent Things (session_status) configuration found.')
147
+ : (res.removed ? '✅ 已从 ~/.codex/config.toml 中移除 Agent Things (session_status) 伴生配置。' : 'ℹ️ 未发现 Agent Things (session_status) 配置。'));
148
+ return;
149
+ }
150
+
151
+ if (command === 'update-renderer') {
152
+ const resources = ['session-status.js', 'harnesses/codex/codex-harness.js', 'ui-foundation.cjs'].map(name => {
153
+ const source = path.join(__dirname, '../src', name);
154
+ const destination = path.join(directory, 'runtime/src', name);
155
+ if (name !== 'ui-foundation.cjs' && !fs.existsSync(destination)) throw new Error(en ? 'Installed renderer resource not found' : '未找到已安装的渲染资源');
156
+ const contents = fs.readFileSync(source);
157
+ new vm.Script(contents.toString('utf8'));
158
+ return { contents, destination };
159
+ });
160
+ for (const { contents, destination } of resources) {
161
+ const temporary = `${destination}.${process.pid}.tmp`;
162
+ try { fs.writeFileSync(temporary, contents, { flag: 'wx', mode: 0o600 }); fs.renameSync(temporary, destination); }
163
+ finally { fs.rmSync(temporary, { force: true }); }
164
+ }
165
+ console.log(en ? 'Renderer resources updated' : '渲染资源已更新');
166
+ return;
167
+ }
168
+
169
+ if (command === 'install-autostart') {
170
+ console.log(en ? 'Configuring background autostart…' : '正在设置后台自动挂载…');
171
+ console.log(JSON.stringify(await installAutostart(directory), null, 2));
172
+ return;
173
+ }
174
+
175
+ if (command === 'disable-autostart') {
176
+ await disableAutostart();
177
+ console.log(en ? 'Background autostart disabled; manual records preserved.' : '已关闭自动挂载,手动记录保留。');
178
+ return;
179
+ }
180
+
181
+ const store = new ManualStatusStore(path.join(directory, 'manual-state.json'));
182
+
183
+ if (command === 'status') {
184
+ const data = store.snapshot();
185
+ console.log(JSON.stringify({
186
+ file: store.file,
187
+ revision: data.revision,
188
+ markedConversations: Object.values(data.records).filter(record => record.state).length,
189
+ autostart: startupStatus(directory),
190
+ diagnosticLog: path.join(os.homedir(), 'Library/Logs/CodexSessionStatus/analysis.jsonl'),
191
+ installedRendererVersion: (() => {
192
+ try { return require('../src/renderer-resource.cjs').readRendererResource({ rendererFile: path.join(directory, 'runtime/src/session-status.js'), harnessFile: path.join(directory, 'runtime/src/harnesses/codex/codex-harness.js') }).version; } catch { return null; }
193
+ })(),
194
+ attachment: await attachmentStatus(port),
195
+ }, null, 2));
196
+ return;
197
+ }
198
+
199
+ if (command === 'mcp') {
200
+ await runMcpServer({ store, directory, port });
201
+ return;
202
+ }
203
+
204
+ if (command !== 'run') throw new Error(en ? `Unknown command: ${command}` : `未知命令:${command}`);
205
+
206
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
207
+ const lock = path.join(directory, 'agent.lock');
208
+ if (!tryAcquirePidLock(lock)) throw new Error(en ? 'Another process is already running for this data directory' : '此数据目录已有进程运行,请使用已有进程');
209
+ let agent;
210
+ try {
211
+ store.recoverPending();
212
+ agent = new ManualStatusAgent({
213
+ store, port,
214
+ logFile: path.join(os.homedir(), 'Library/Logs/CodexSessionStatus/analysis.jsonl'),
215
+ onError: error => console.error(error.message),
216
+ });
217
+ await agent.startControl();
218
+ } catch (error) {
219
+ await agent?.stop();
220
+ if (fs.existsSync(lock) && fs.readFileSync(lock, 'utf8').trim() === String(process.pid)) fs.unlinkSync(lock);
221
+ throw error;
222
+ }
223
+ agent.log('agent.start', { parentPid: process.ppid, revision: store.snapshot().revision });
224
+
225
+ let watcher = null;
226
+ let stopping = false;
227
+ let reported = '';
228
+ const scan = async () => {
229
+ try {
230
+ await agent.scan();
231
+ const message = agent.sessions.size
232
+ ? (en ? `Connected to ${agent.sessions.size} Codex window(s)` : `已连接 ${agent.sessions.size} 个 Codex 窗口`)
233
+ : (en ? 'Waiting for Codex main window' : '等待 Codex 主窗口');
234
+ if (message !== reported) { console.log(message); reported = message; }
235
+ } catch {
236
+ const message = en
237
+ ? `Waiting for local debug port ${port}; save your work and launch the client with --remote-debugging-port=${port}.`
238
+ : `等待本地调试端口 ${port};保存工作后,以 --remote-debugging-port=${port} 启动客户端。`;
239
+ if (message !== reported) { console.log(message); reported = message; }
240
+ }
241
+ };
242
+ const timer = setInterval(scan, 2000);
243
+ let startupScanTimer = null, startupScanEnd = null;
244
+ const boostStartupScan = () => {
245
+ if (stopping) return;
246
+ clearInterval(startupScanTimer); clearTimeout(startupScanEnd);
247
+ const scanUntilConnected = async () => {
248
+ if (agent.scanning) return;
249
+ await scan();
250
+ if (agent.sessions.size) { clearInterval(startupScanTimer); startupScanTimer = null; clearTimeout(startupScanEnd); }
251
+ };
252
+ startupScanTimer = setInterval(scanUntilConnected, 200);
253
+ startupScanEnd = setTimeout(() => { clearInterval(startupScanTimer); startupScanTimer = null; }, 15000);
254
+ scanUntilConnected();
255
+ };
256
+ const stop = async () => {
257
+ if (stopping) return;
258
+ stopping = true;
259
+ clearInterval(timer); clearInterval(startupScanTimer); clearTimeout(startupScanEnd);
260
+ watcher?.stop();
261
+ try {
262
+ await agent.stop();
263
+ }
264
+ finally {
265
+ if (fs.existsSync(lock) && fs.readFileSync(lock, 'utf8').trim() === String(process.pid)) fs.unlinkSync(lock);
266
+ }
267
+ };
268
+ for (const event of ['SIGINT', 'SIGTERM']) process.once(event, () => stop().then(() => { process.exitCode = 0; }));
269
+ if (watchStartup) {
270
+ const settings = JSON.parse(fs.readFileSync(path.join(directory, 'autostart.json'), 'utf8'));
271
+ watcher = require('../src/startup/watch.cjs').startWatcher({ root: directory, settings, log: console.log, onLaunch: boostStartupScan });
272
+ watcher.exited.catch(error => {
273
+ console.error(error.message);
274
+ stop().then(() => { process.exitCode = 1; });
275
+ });
276
+ }
277
+ await scan();
278
+ }
279
+
280
+ if (require.main === module) {
281
+ main().catch(error => {
282
+ console.error(error.message);
283
+ process.exitCode = error.code === 'CLI_CANCELLED' ? 130 : 1;
284
+ });
285
+ }
286
+
287
+ module.exports = { main, resolveSessionKey, runMcpServer };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "agent-things-ui",
3
+ "version": "0.2.7",
4
+ "description": "Agent Things session task progress, manual status, task sources, and notes",
5
+ "author": {
6
+ "name": "Agent Things"
7
+ },
8
+ "license": "MIT",
9
+ "skills": [
10
+ "./"
11
+ ]
12
+ }
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: agent-things-ui
3
+ description: Agent Things native conversation progress card for Claude Desktop Code, opened with /things.
4
+ user-invocable: false
5
+ disable-model-invocation: true
6
+ ---
7
+
8
+ # Agent Things (`/things`)
9
+
10
+ Run `/things` to open the interactive Agent Things progress card for the current Claude Desktop Code conversation. The card reads and writes the local Agent Things ledger. Task tools and conversational progress requests are provided by the companion `agent-things` skill and `session_status` MCP.
@@ -0,0 +1,112 @@
1
+ import { CONTENT_WIDTH, colors, svg, slider, primary, clearButton, paneIcon, paneIconWidth, measureButtonWidth, measureClearWidth } from './presentation.js';
2
+ import { progressValue, progressState } from './progress.js';
3
+
4
+ export default function controls(props, surface) {
5
+ const sliderWidth = Number.isFinite(Number(props.width)) && Number(props.width) > 0
6
+ ? Math.max(130, Math.round(Number(props.width)))
7
+ : CONTENT_WIDTH;
8
+ const current = surface.state;
9
+ if (!current || current.received !== props.value && !current.dragging && !current.editingNumber) {
10
+ surface.setState({ received: props.value, value: props.value, dragging: false });
11
+ }
12
+ const state = surface.state || { received: props.value, value: props.value, dragging: false };
13
+ const update = (value, dragging) => {
14
+ value = progressValue(value, dragging);
15
+ surface.setState({ ...surface.state, received: props.value, value, dragging });
16
+ return value;
17
+ };
18
+ const pointerValue = event => ((event.fine?.x ?? event.x + .5) / Math.max(1, surface.columns) * sliderWidth - 7) / (sliderWidth - 14) * 100;
19
+ surface.onPointer(event => {
20
+ if (props.disabled || event.button && event.button !== 'left') return;
21
+ const latest = surface.state || state;
22
+ if (props.kind === 'icon') {
23
+ // 只有右侧图标区域可点;左侧留给悬停提示。
24
+ const totalWidth = paneIconWidth(props.label);
25
+ const x = (event.fine?.x ?? event.x + .5) / Math.max(1, surface.columns) * totalWidth;
26
+ const inside = x >= (totalWidth - 30) && x <= totalWidth + 2 && event.y >= 0 && event.y <= surface.rows;
27
+ if (event.type === 'enter' || event.type === 'move') surface.setState({ ...latest, hovered: inside });
28
+ if (event.type === 'leave') surface.setState({ ...latest, hovered: false, pressed: false });
29
+ if (event.type === 'down' && inside) surface.setState({ ...latest, hovered: true, pressed: true });
30
+ if (event.type === 'up' && latest.pressed) {
31
+ surface.setState({ ...latest, hovered: inside, pressed: false });
32
+ if (inside) surface.post({ action: props.action });
33
+ }
34
+ return;
35
+ }
36
+ if (props.kind === 'button') {
37
+ // Desktop reports whole cells; include each region's final partial cell.
38
+ const inside = event.x >= 0 && event.x <= surface.columns && event.y >= 0 && event.y <= surface.rows;
39
+ if (event.type === 'enter' || event.type === 'move') surface.setState({ ...latest, hovered: inside });
40
+ if (event.type === 'leave') surface.setState({ ...latest, hovered: false });
41
+ if (event.type === 'down' && inside) surface.setState({ ...latest, hovered: true, pressed: true });
42
+ if (event.type === 'up' && latest.pressed) {
43
+ surface.setState({ ...latest, hovered: inside, pressed: false });
44
+ if (inside) surface.post({ action: props.action });
45
+ }
46
+ return;
47
+ }
48
+ const y = (event.fine?.y ?? event.y + .5) / Math.max(1, surface.rows) * 110;
49
+ const hitThreshold = Math.min(0.85, Math.max(0.66, (sliderWidth - 96) / sliderWidth));
50
+ if (event.type === 'down') {
51
+ if (y < 45) {
52
+ if (event.x / Math.max(1, surface.columns) > hitThreshold) surface.setState({ ...latest, editingNumber: true, buffer: latest.value == null ? '' : String(latest.value), selectAll: true });
53
+ } else { surface.setState({ ...latest, editingNumber: false }); update(pointerValue(event), true); }
54
+ } else if (event.type === 'move' && latest.dragging) {
55
+ update(pointerValue(event), true);
56
+ } else if (event.type === 'up') {
57
+ if (latest.dragging) {
58
+ surface.post({ value: update(pointerValue(event), true) });
59
+ surface.setState({ ...surface.state, dragging: false });
60
+ }
61
+ }
62
+ });
63
+ surface.onKey(event => {
64
+ if (props.disabled) return;
65
+ if ((props.kind === 'button' || props.kind === 'icon') && ['return', 'enter', ' '].includes(event.key)) surface.post({ action: props.action });
66
+ if (props.kind === 'slider') {
67
+ const latest = surface.state || state;
68
+ if (latest.editingNumber) {
69
+ if ((event.ctrl || event.meta) && event.key.toLowerCase() === 'a') {
70
+ surface.setState({ ...latest, selectAll: true }); return;
71
+ }
72
+ if (event.key === 'return' || event.key === 'enter') {
73
+ surface.setState({ ...latest, editingNumber: false }); return;
74
+ }
75
+ let buffer = latest.buffer;
76
+ if (/^\d$/.test(event.key)) buffer = latest.selectAll ? event.key : buffer + event.key;
77
+ else if (event.key === 'backspace') buffer = latest.selectAll ? '' : buffer.slice(0, -1);
78
+ else if (event.key === 'delete') buffer = '';
79
+ else return;
80
+ const value = buffer === '' ? null : progressValue(Number(buffer));
81
+ if (value !== null) buffer = String(value);
82
+ surface.setState({ ...latest, value, buffer, selectAll: false });
83
+ surface.post({ value });
84
+ } else {
85
+ if (event.key === 'left' || event.key === 'right') {
86
+ surface.post({ value: update((latest.value || 0) + (event.key === 'left' ? -1 : 1), false) });
87
+ }
88
+ if (event.key === 'enter' || event.key === 'return') surface.setState({ ...latest, editingNumber: true, buffer: latest.value == null ? '' : String(latest.value), selectAll: true });
89
+ }
90
+ }
91
+ });
92
+ if (props.kind === 'slider') {
93
+ const color = colors[state.value == null ? props.state : progressState(props.state, state.value)] || colors.unstarted;
94
+ const number = state.editingNumber ? state.buffer || '—' : state.value ?? '—';
95
+ const numRight = sliderWidth - 25;
96
+ const pctX = sliderWidth - 16;
97
+ const selX = sliderWidth - 90;
98
+ const caretX = sliderWidth - 23;
99
+ const selection = state.editingNumber && state.selectAll ? `<rect x="${selX}" y="5" width="65" height="30" rx="3" fill="#0169cc30"/>` : '';
100
+ const caret = state.editingNumber && !state.selectAll ? `<path d="M${caretX} 7V33" stroke="#0169cc"/>` : '';
101
+ const progressWord = props.progressLabel || '进度';
102
+ const unrecordedWord = props.unrecordedWord || '未记录';
103
+ const picture = svg(`${selection}<text x="0" y="28" font-size="11" fill="currentColor" opacity=".68">${progressWord}</text><text x="${numRight}" y="30" text-anchor="end" font-size="27" font-weight="550" fill="currentColor">${number}</text>${caret}<text x="${pctX}" y="26" font-size="12" fill="currentColor" opacity=".68">%</text><path d="M${selX} 41H${numRight}" stroke="currentColor" opacity=".2"/><g transform="translate(0 55)">${slider(state.value, color, sliderWidth)}</g>`, sliderWidth, 110, 'xMinYMid meet');
104
+ // The desktop Client tree accepts Svg nodes although its terminal element table has no Svg constructor.
105
+ return { type: 'Svg', props: { source: picture, alt: `${progressWord} ${state.value ?? unrecordedWord}%`, width: sliderWidth, height: 110 } };
106
+ }
107
+ if (props.kind === 'icon') return { type: 'Svg', props: { source: paneIcon(state.hovered, state.pressed, props.label), alt: props.label, width: paneIconWidth(props.label), height: 28 } };
108
+ const buttonWidth = props.action === 'clear'
109
+ ? (props.label === '清除进度' || !props.label ? 64 : measureClearWidth(props.label))
110
+ : measureButtonWidth(props.label);
111
+ return { type: 'Svg', props: { source: props.action === 'clear' ? clearButton(state.hovered, state.pressed, props.label, buttonWidth) : primary(props.label, props.disabled, state.hovered, state.pressed && state.hovered, buttonWidth), alt: props.label, width: buttonWidth, height: props.action === 'clear' ? 28 : 36 } };
112
+ }