@sususgh/gamer-dsh-plugin 1.0.0 → 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
@@ -11,6 +11,7 @@ The key design is simple:
11
11
  The phone is not expected to host a large language model. It can perform lightweight device-side work, while the computer handles the heavier vision pipeline, game context, model requests, planning, validation, telemetry and coordination.
12
12
 
13
13
  - **Repository:** https://github.com/sususgh/Gamer-DSH-Plugin
14
+ - **DSH plugin package:** `@sususgh/gamer-dsh-plugin` (install this package name from DSH Plugins → Add plugin)
14
15
  - **Companion project:** Gamer-Mobile (Android)
15
16
  - **Primary target:** Windows desktop + Android phone
16
17
  - **DSH role:** agent entry point, tool orchestration, session and task coordination
@@ -366,7 +367,7 @@ The desktop UI is a view of actual runtime events, not the source of truth. Its
366
367
 
367
368
  Telemetry must come from real measurements. TCP and UDP metrics must be reported separately. Do not infer UDP packet loss from TCP metrics. If a metric is unavailable, show N/A rather than a fabricated zero. Decorative animation must not be presented as real network traffic.
368
369
 
369
- Open `desktop-ui/index.html` in a modern browser to inspect the current UI prototype. Its telemetry panel intentionally shows “等待连接”; the animated trace is decorative until a real telemetry source is integrated.
370
+ **Run the desktop UI with its local pairing service (Node.js 22.13+):** do not open `desktop-ui/index.html` directly. From the repository root run `cd desktop-runtime`, `npm install`, then `npm start`; open `http://127.0.0.1:8765` on the computer. Choose the computer's LAN adapter and click **生成二维码**. The QR is generated locally and expires after five minutes. The phone must be on the same trusted LAN. Scanning opens a validation page; it does not yet complete Android pairing because the Android Companion handshake is not implemented. Never expose this HTTP pairing service to the public internet. The telemetry panel still shows “等待连接”; its animated trace is decorative until a real telemetry source is integrated.
370
371
 
371
372
  ## 11. Companion state and voice
372
373
 
@@ -403,7 +404,8 @@ The integration is optional and endpoint-based. The voice service should remain
403
404
 
404
405
  ## 13. Repository layout
405
406
 
406
- - `desktop-ui/` — responsive desktop dashboard prototype.
407
+ - `desktop-ui/` — responsive desktop dashboard and real QR preview.
408
+ - `desktop-runtime/` — local HTTP server, LAN interface discovery, short-lived QR token manager and QR image generation.
407
409
  - `docs/architecture.md` — runtime architecture and integration contract.
408
410
  - `docs/runtime-protocol-v1.md` — Android ↔ desktop pairing, observations, actions, telemetry, model failover and companion protocol.
409
411
  - Future runtime modules — Android bridge, telemetry collector, local inference adapter, model health router, game-agent coordinator and PC input adapter.
@@ -443,7 +445,7 @@ Platform-specific code should stay behind adapters. DSH orchestration, model pro
443
445
 
444
446
  The README and protocol documents define the target behavior and contracts. A feature should be called **implemented** only after its code exists, dependencies are declared and the workflow has been tested.
445
447
 
446
- This repository's current UI shell is a visual prototype. The presence of architecture documentation does not mean Android pairing, ADB control, PC input injection, OCR, model routing, live telemetry or automatic gameplay are already operational. Those capabilities must be delivered and verified module by module.
448
+ This repository's desktop UI remains a prototype for most gameplay and telemetry features. The standalone desktop runtime can now generate a real, five-minute LAN QR code and validate its scan landing page. This is not a completed Android pairing: Android Companion identity submission, mutual authentication, ADB control, PC input injection, OCR, model routing, live telemetry and automatic gameplay are not yet operational. Those capabilities must be delivered and verified module by module.
447
449
 
448
450
  ## 16. Contributing
449
451
 
@@ -536,9 +538,9 @@ The repository now includes a native DSH bundle package manifest and plugin entr
536
538
 
537
539
  For CLI-managed profiles, use:
538
540
  ```bash
539
- npx -y @deepseek-ai/dsh plugin --profile web add @sususgh/gamer-dsh-plugin@1.0.0
541
+ npx -y @deepseek-ai/dsh plugin --profile web add @sususgh/gamer-dsh-plugin@1.0.1
540
542
  ```
541
543
 
542
544
  See [DSH installation instructions](docs/DSH-INSTALL.zh-CN.md).
543
545
 
544
- **Important implementation status:** the native DSH package currently provides the plugin bundle, a status tool and a status card. The Windows game-control runtime, Android APK/companion bridge, QR pairing, live visual perception and autonomous game actions are not implemented yet. Installing the DSH bundle does not enable game control.
546
+ **Current release (v1.0.1):** the native DSH package provides the plugin bundle, a status tool and a bilingual configuration page (简体中文 / English) on the bundle's own page in the DSH Plugins sidebar. The page includes an Android QR-pairing status panel. The standalone desktop runtime now provides real QR generation and a scan-validation landing page. The Android APK/companion bridge, device identity approval, authenticated session handshake, live visual perception and autonomous game actions are not implemented yet; scanning the QR does not mean the phone is paired. Installing the DSH bundle does not enable game control.
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "gamer-desktop-runtime",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Local Gamer desktop UI and short-lived QR pairing server",
7
+ "scripts": {
8
+ "start": "node server.js",
9
+ "check": "node --check server.js && node --check pairing.js"
10
+ },
11
+ "dependencies": {
12
+ "qrcode": "^1.5.4"
13
+ },
14
+ "engines": {
15
+ "node": ">=22.13"
16
+ }
17
+ }
@@ -0,0 +1,75 @@
1
+ import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'node:crypto';
2
+
3
+ const DEFAULT_TTL_MS = 5 * 60 * 1000;
4
+
5
+ export class PairingManager {
6
+ #active = null;
7
+
8
+ constructor({ ttlMs = DEFAULT_TTL_MS } = {}) {
9
+ if (!Number.isInteger(ttlMs) || ttlMs < 10_000 || ttlMs > 15 * 60 * 1000) {
10
+ throw new RangeError('ttlMs must be between 10 seconds and 15 minutes');
11
+ }
12
+ this.ttlMs = ttlMs;
13
+ this.instanceId = randomUUID();
14
+ }
15
+
16
+ create({ host, port, protocol = 'gamer-runtime/1' }) {
17
+ if (typeof host !== 'string' || !host.trim()) throw new TypeError('A LAN host address is required');
18
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new RangeError('Invalid port');
19
+ if (protocol !== 'gamer-runtime/1') throw new TypeError('Unsupported pairing protocol');
20
+
21
+ const token = randomBytes(32).toString('base64url');
22
+ const now = Date.now();
23
+ this.#active = {
24
+ tokenHash: createHash('sha256').update(token).digest(),
25
+ createdAt: now,
26
+ expiresAt: now + this.ttlMs,
27
+ host,
28
+ port,
29
+ protocol,
30
+ };
31
+
32
+ return {
33
+ token,
34
+ protocol,
35
+ instanceId: this.instanceId,
36
+ host,
37
+ port,
38
+ createdAt: now,
39
+ expiresAt: now + this.ttlMs,
40
+ };
41
+ }
42
+
43
+ verify(token, { consume = false } = {}) {
44
+ const current = this.#active;
45
+ if (!current || Date.now() >= current.expiresAt || typeof token !== 'string') {
46
+ if (current && Date.now() >= current.expiresAt) this.#active = null;
47
+ return false;
48
+ }
49
+
50
+ const candidate = createHash('sha256').update(token).digest();
51
+ const valid = candidate.length === current.tokenHash.length
52
+ && timingSafeEqual(candidate, current.tokenHash);
53
+
54
+ if (valid && consume) this.#active = null;
55
+ return valid;
56
+ }
57
+
58
+ status() {
59
+ if (this.#active && Date.now() >= this.#active.expiresAt) this.#active = null;
60
+ if (!this.#active) return { active: false, expiresAt: null, host: null, port: null };
61
+ return {
62
+ active: true,
63
+ createdAt: this.#active.createdAt,
64
+ expiresAt: this.#active.expiresAt,
65
+ remainingMs: Math.max(0, this.#active.expiresAt - Date.now()),
66
+ host: this.#active.host,
67
+ port: this.#active.port,
68
+ };
69
+ }
70
+
71
+ stop() {
72
+ this.#active = null;
73
+ return this.status();
74
+ }
75
+ }
@@ -0,0 +1,203 @@
1
+ import http from 'node:http';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import QRCode from 'qrcode';
7
+ import { PairingManager } from './pairing.js';
8
+
9
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
10
+ const UI_ROOT = path.join(ROOT, 'desktop-ui');
11
+ const PORT = Number.parseInt(process.env.GAMER_PORT || '8765', 10);
12
+ const manager = new PairingManager();
13
+ const MIME = {
14
+ '.html': 'text/html; charset=utf-8',
15
+ '.js': 'text/javascript; charset=utf-8',
16
+ '.css': 'text/css; charset=utf-8',
17
+ '.svg': 'image/svg+xml',
18
+ '.png': 'image/png',
19
+ '.ico': 'image/x-icon',
20
+ };
21
+
22
+ function isPrivateIPv4(address) {
23
+ const parts = address.split('.').map(Number);
24
+ if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return false;
25
+ return parts[0] === 10
26
+ || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31)
27
+ || (parts[0] === 192 && parts[1] === 168)
28
+ || (parts[0] === 169 && parts[1] === 254);
29
+ }
30
+
31
+ function getLanAddresses() {
32
+ const found = [];
33
+ for (const [name, entries] of Object.entries(os.networkInterfaces())) {
34
+ for (const item of entries || []) {
35
+ if (item.family === 'IPv4' && !item.internal && isPrivateIPv4(item.address)) {
36
+ found.push({ name, address: item.address });
37
+ }
38
+ }
39
+ }
40
+ return found;
41
+ }
42
+
43
+ function isLoopback(remoteAddress = '') {
44
+ return remoteAddress === '127.0.0.1'
45
+ || remoteAddress === '::1'
46
+ || remoteAddress === '::ffff:127.0.0.1';
47
+ }
48
+
49
+ function sendJson(res, status, value) {
50
+ res.writeHead(status, {
51
+ 'content-type': 'application/json; charset=utf-8',
52
+ 'cache-control': 'no-store',
53
+ 'x-content-type-options': 'nosniff',
54
+ });
55
+ res.end(JSON.stringify(value));
56
+ }
57
+
58
+ function readJson(req) {
59
+ return new Promise((resolve, reject) => {
60
+ let body = '';
61
+ req.on('data', chunk => {
62
+ body += chunk;
63
+ if (body.length > 8_192) {
64
+ reject(new Error('Request body too large'));
65
+ req.destroy();
66
+ }
67
+ });
68
+ req.on('end', () => {
69
+ try { resolve(body ? JSON.parse(body) : {}); }
70
+ catch { reject(new Error('Invalid JSON body')); }
71
+ });
72
+ req.on('error', reject);
73
+ });
74
+ }
75
+
76
+ function pairLandingPage(valid) {
77
+ const title = valid ? 'Gamer 配对码已识别' : 'Gamer 配对码无效或已过期';
78
+ const detail = valid
79
+ ? '电脑端已生成真实配对二维码。下一步需要安装 Gamer Android Companion,才能提交设备身份并完成双端认证。当前尚未建立连接。'
80
+ : '请回到电脑端重新生成二维码,再使用 Gamer 手机伴侣扫码。';
81
+ return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>${title}</title><body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#edf5fa;color:#30465d;font:16px system-ui,'Noto Sans SC',sans-serif"><main style="max-width:480px;margin:24px;padding:28px;border-radius:20px;background:#fff;box-shadow:0 12px 40px #496b841c"><h2>${title}</h2><p style="line-height:1.8;color:#71869a">${detail}</p><small style="color:#9aa9b5">Gamer · gamer-runtime/1</small></main></body></html>`;
82
+ }
83
+
84
+ async function handle(req, res) {
85
+ const url = new URL(req.url, 'http://127.0.0.1');
86
+ res.setHeader('x-content-type-options', 'nosniff');
87
+ res.setHeader('referrer-policy', 'no-referrer');
88
+ res.setHeader('cache-control', 'no-store');
89
+
90
+ if (url.pathname === '/api/network/interfaces' && req.method === 'GET') {
91
+ return sendJson(res, 200, { addresses: getLanAddresses() });
92
+ }
93
+
94
+ if (url.pathname === '/api/pairing/status' && req.method === 'GET') {
95
+ return sendJson(res, 200, manager.status());
96
+ }
97
+
98
+ if (url.pathname === '/api/pairing/start' && req.method === 'POST') {
99
+ if (!isLoopback(req.socket.remoteAddress)) {
100
+ return sendJson(res, 403, { error: 'PAIRING_CONTROL_LOCAL_ONLY' });
101
+ }
102
+ let body;
103
+ try { body = await readJson(req); }
104
+ catch (error) { return sendJson(res, 400, { error: error.message }); }
105
+
106
+ const addresses = getLanAddresses();
107
+ if (!addresses.length) return sendJson(res, 400, { error: 'NO_PRIVATE_LAN_IPV4' });
108
+ const requestedHost = body.host;
109
+ const selected = addresses.find(item => item.address === requestedHost);
110
+ const host = selected?.address || null;
111
+ if (!host) return sendJson(res, 400, { error: 'INVALID_LAN_ADDRESS', addresses });
112
+
113
+ const pairing = manager.create({ host, port: PORT });
114
+ const pairingUrl = new URL('/pair', `http://${host}:${PORT}`);
115
+ pairingUrl.searchParams.set('protocol', pairing.protocol);
116
+ pairingUrl.searchParams.set('instance_id', pairing.instanceId);
117
+ pairingUrl.searchParams.set('token', pairing.token);
118
+ const qrDataUrl = await QRCode.toDataURL(pairingUrl.toString(), {
119
+ errorCorrectionLevel: 'M',
120
+ margin: 2,
121
+ width: 360,
122
+ color: { dark: '#26394a', light: '#ffffff' },
123
+ });
124
+
125
+ return sendJson(res, 200, {
126
+ active: true,
127
+ host,
128
+ port: PORT,
129
+ instanceId: pairing.instanceId,
130
+ createdAt: pairing.createdAt,
131
+ expiresAt: pairing.expiresAt,
132
+ qrDataUrl,
133
+ message: 'QR generated. Scanning is not the same as a completed device pairing.',
134
+ });
135
+ }
136
+
137
+ if (url.pathname === '/api/pairing/stop' && req.method === 'POST') {
138
+ if (!isLoopback(req.socket.remoteAddress)) {
139
+ return sendJson(res, 403, { error: 'PAIRING_CONTROL_LOCAL_ONLY' });
140
+ }
141
+ manager.stop();
142
+ return sendJson(res, 200, { active: false });
143
+ }
144
+
145
+ if (url.pathname === '/pair' && req.method === 'GET') {
146
+ const valid = url.searchParams.get('protocol') === 'gamer-runtime/1'
147
+ && url.searchParams.get('instance_id') === manager.instanceId
148
+ && manager.verify(url.searchParams.get('token'));
149
+ res.writeHead(valid ? 200 : 410, {
150
+ 'content-type': 'text/html; charset=utf-8',
151
+ 'cache-control': 'no-store',
152
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
153
+ });
154
+ return res.end(pairLandingPage(valid));
155
+ }
156
+
157
+ if (url.pathname.startsWith('/api/')) {
158
+ return sendJson(res, 404, { error: 'NOT_FOUND' });
159
+ }
160
+
161
+ const requested = url.pathname === '/' ? '/index.html' : decodeURIComponent(url.pathname);
162
+ const target = path.resolve(UI_ROOT, '.' + requested);
163
+ if (!target.startsWith(UI_ROOT + path.sep) && target !== path.join(UI_ROOT, 'index.html')) {
164
+ return sendJson(res, 403, { error: 'PATH_NOT_ALLOWED' });
165
+ }
166
+ try {
167
+ const content = await readFile(target);
168
+ res.writeHead(200, {
169
+ 'content-type': MIME[path.extname(target)] || 'application/octet-stream',
170
+ 'cache-control': 'no-cache',
171
+ });
172
+ res.end(content);
173
+ } catch {
174
+ sendJson(res, 404, { error: 'NOT_FOUND' });
175
+ }
176
+ }
177
+
178
+ const server = http.createServer((req, res) => {
179
+ Promise.resolve(handle(req, res)).catch(error => {
180
+ console.error('[gamer-desktop] request failed:', error.message);
181
+ if (!res.headersSent) sendJson(res, 500, { error: 'INTERNAL_ERROR' });
182
+ else res.end();
183
+ });
184
+ });
185
+
186
+ server.listen(PORT, '0.0.0.0', () => {
187
+ const addresses = getLanAddresses();
188
+ console.log(`Gamer Desktop UI: http://127.0.0.1:${PORT}`);
189
+ if (addresses.length) {
190
+ for (const item of addresses) console.log(`Phone LAN URL: http://${item.address}:${PORT}`);
191
+ } else {
192
+ console.warn('No private IPv4 LAN address found. QR pairing will use loopback and cannot be reached by a phone.');
193
+ }
194
+ console.log('Pairing QR tokens expire in 5 minutes. Pairing control endpoints accept loopback requests only.');
195
+ });
196
+
197
+ function shutdown() {
198
+ manager.stop();
199
+ server.close(() => process.exit(0));
200
+ setTimeout(() => process.exit(1), 3_000).unref();
201
+ }
202
+ process.on('SIGINT', shutdown);
203
+ process.on('SIGTERM', shutdown);
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ command -v node >/dev/null 2>&1 || { echo "[Gamer] Node.js 22.13+ is required."; exit 1; }
5
+ node -e "const [a,b]=process.versions.node.split('.').map(Number);process.exit(a>22||(a===22&&b>=13)?0:1)" || { echo "[Gamer] Please upgrade Node.js to 22.13 or newer."; exit 1; }
6
+ if [[ ! -d node_modules/qrcode ]]; then
7
+ echo "[Gamer] Installing desktop QR dependencies..."
8
+ npm install --no-audit --no-fund
9
+ fi
10
+ echo "[Gamer] Starting desktop pairing service..."
11
+ npm start
@@ -0,0 +1,26 @@
1
+ @echo off
2
+ setlocal
3
+ cd /d "%~dp0"
4
+ where node >nul 2>nul
5
+ if errorlevel 1 (
6
+ echo [Gamer] Node.js 22.13+ is required. Install it from https://nodejs.org/
7
+ pause
8
+ exit /b 1
9
+ )
10
+ node -e "const [a,b]=process.versions.node.split('.').map(Number);process.exit(a>22||(a===22&&b>=13)?0:1)"
11
+ if errorlevel 1 (
12
+ echo [Gamer] Please upgrade Node.js to 22.13 or newer.
13
+ pause
14
+ exit /b 1
15
+ )
16
+ if not exist "node_modules\qrcode" (
17
+ echo [Gamer] Installing desktop QR dependencies...
18
+ npm install --no-audit --no-fund
19
+ if errorlevel 1 (
20
+ pause
21
+ exit /b 1
22
+ )
23
+ )
24
+ echo [Gamer] Starting desktop pairing service...
25
+ npm start
26
+ pause
@@ -0,0 +1,133 @@
1
+ const $=id=>document.getElementById(id);
2
+ const log=(message)=>{const list=$('eventLog');const row=document.createElement('div');row.className='event';const t=document.createElement('time');t.textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});const dot=document.createElement('span');dot.className='event-dot';const p=document.createElement('p');p.textContent=message;row.append(t,dot,p);list.prepend(row);while(list.children.length>8)list.lastChild.remove();};
3
+ let mode='USB';
4
+ document.querySelectorAll('.choice').forEach(btn=>btn.addEventListener('click',()=>{document.querySelectorAll('.choice').forEach(x=>x.classList.remove('selected'));btn.classList.add('selected');mode=btn.dataset.mode;$('transportMode').textContent=mode==='USB'?'USB / ADB':'Wi-Fi / LAN';log('连接方式已选择:'+mode+'。等待设备桥接服务接入。');}));
5
+ $('connectBtn').addEventListener('click',()=>{log('已请求设备连接;当前原型尚未接入 ADB / Wi-Fi 桥接服务。');$('globalState').textContent='等待设备桥接服务';});
6
+ $('stopBtn').addEventListener('click',()=>{log('停止请求已记录。真实运行时接入后,此按钮将向 Agent Coordinator 发送紧急停止指令。');});
7
+ $('probeBtn').addEventListener('click',()=>{log('模型健康检查暂不可执行:尚未配置本地推理运行时。');$('modelState').textContent='等待推理适配器';});
8
+ $('modelConfigBtn').addEventListener('click',()=>{const primary=prompt('主模型标识(例如本地服务中的模型 ID):');if(primary){$('activeModel').textContent=primary;$('modelState').textContent='已保存到本次界面会话;尚未连接模型服务';log('主模型候选已填写:'+primary+'。等待运行时探测。');}const fallback=prompt('备用模型标识(可留空):');if(fallback!==null&&fallback.trim()){$('fallbackModel').textContent=fallback.trim();log('备用模型候选已填写:'+fallback.trim()+'。尚未执行真实健康检查。');}});
9
+ $('clearLog').addEventListener('click',()=>{$('eventLog').replaceChildren();log('日志已清空。');});
10
+ const canvas=$('flowCanvas'),ctx=canvas.getContext('2d');let phase=0;
11
+ function draw(){const dpr=Math.max(1,window.devicePixelRatio||1),w=canvas.clientWidth,h=150;if(canvas.width!==Math.round(w*dpr)||canvas.height!==Math.round(h*dpr)){canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);}ctx.setTransform(dpr,0,0,dpr,0,0);ctx.clearRect(0,0,w,h);for(let j=0;j<2;j++){ctx.beginPath();for(let x=0;x<=w;x+=3){const y=h/2+Math.sin(x*.023+phase+j*1.5)*(15+j*8)+Math.sin(x*.009-phase*.7)*(7+j*4);if(x===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);}ctx.strokeStyle=j===0?'rgba(91,190,199,.72)':'rgba(160,145,211,.58)';ctx.lineWidth=j===0?2:1.6;ctx.stroke();}phase+=.025;requestAnimationFrame(draw);}draw();window.addEventListener('resize',()=>{canvas.width=0;});
12
+
13
+ /* Model selection UI is intentionally empty until the real local-model registry reports installed models. */
14
+ $('selectAllModels')?.addEventListener('click',()=>{log('模型列表尚未从本地运行时加载,暂时没有可选择的模型。');});
15
+ /* Desktop-generated, real QR pairing. The UI must be served by desktop-runtime/server.js. */
16
+ const pairQrImage=$('pairQrImage');
17
+ const pairQrEmpty=$('pairQrEmpty');
18
+ const pairHostSelect=$('pairHostSelect');
19
+ const pairRefresh=$('pairRefresh');
20
+ const pairStop=$('pairStop');
21
+ let pairExpiryTimer=null;
22
+
23
+ function setPairState(text){$('pairState').textContent=text;}
24
+ function clearPairQr(){
25
+ if(pairQrImage){pairQrImage.hidden=true;pairQrImage.removeAttribute('src');}
26
+ if(pairQrEmpty)pairQrEmpty.hidden=false;
27
+ $('pairQrCaption').textContent='点击生成二维码';
28
+ $('pairExpires').textContent='5 分钟 · 未生成';
29
+ if(pairStop)pairStop.disabled=true;
30
+ if(pairExpiryTimer){clearInterval(pairExpiryTimer);pairExpiryTimer=null;}
31
+ }
32
+ async function loadPairNetworks(){
33
+ try{
34
+ const response=await fetch('/api/network/interfaces',{cache:'no-store'});
35
+ if(!response.ok)throw new Error('HTTP '+response.status);
36
+ const data=await response.json();
37
+ pairHostSelect.replaceChildren();
38
+ for(const item of data.addresses||[]){
39
+ const option=document.createElement('option');
40
+ option.value=item.address;option.textContent=item.name+' · '+item.address;
41
+ pairHostSelect.append(option);
42
+ }
43
+ if(!pairHostSelect.options.length){
44
+ const option=document.createElement('option');option.value='';option.textContent='未发现局域网 IPv4 地址';pairHostSelect.append(option);
45
+ $('pairHost').textContent='未发现局域网地址';
46
+ setPairState('请连接 Wi-Fi 或检查网络');
47
+ pairRefresh.disabled=true;
48
+ }else{
49
+ $('pairHost').textContent=pairHostSelect.value;
50
+ setPairState('配对服务已就绪');
51
+ pairRefresh.disabled=false;
52
+ }
53
+ }catch(error){
54
+ pairHostSelect.replaceChildren();
55
+ const option=document.createElement('option');option.value='';option.textContent='桌面配对服务未启动';pairHostSelect.append(option);
56
+ setPairState('请通过启动脚本打开桌面控制台');
57
+ pairRefresh.disabled=true;
58
+ log('无法连接桌面配对服务:'+error.message+'。请勿直接双击 index.html。');
59
+ }
60
+ }
61
+ pairHostSelect?.addEventListener('change',()=>{$('pairHost').textContent=pairHostSelect.value||'未选择';});
62
+ pairRefresh?.addEventListener('click',async()=>{
63
+ try{
64
+ pairRefresh.disabled=true;setPairState('正在生成安全二维码…');
65
+ const response=await fetch('/api/pairing/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({host:pairHostSelect.value})});
66
+ const data=await response.json();
67
+ if(!response.ok)throw new Error(data.error||'HTTP '+response.status);
68
+ pairQrImage.src=data.qrDataUrl;pairQrImage.hidden=false;pairQrEmpty.hidden=true;
69
+ $('pairQrCaption').textContent='真实二维码 · 手机扫码';
70
+ $('pairHost').textContent=data.host+':'+data.port;
71
+ $('pairExpires').textContent='05:00';
72
+ setPairState('二维码已生成 · 等待手机扫码');
73
+ pairStop.disabled=false;
74
+ if(pairExpiryTimer)clearInterval(pairExpiryTimer);
75
+ const expiresAt=data.expiresAt;
76
+ pairExpiryTimer=setInterval(()=>{
77
+ const remaining=Math.max(0,expiresAt-Date.now());
78
+ const mm=String(Math.floor(remaining/60000)).padStart(2,'0');
79
+ const ss=String(Math.floor((remaining%60000)/1000)).padStart(2,'0');
80
+ $('pairExpires').textContent=mm+':'+ss;
81
+ if(remaining<=0){clearInterval(pairExpiryTimer);pairExpiryTimer=null;clearPairQr();setPairState('二维码已过期,请重新生成');log('手机配对二维码已过期。');}
82
+ },250);
83
+ log('电脑端已生成真实配对二维码:'+data.host+':'+data.port+',有效期 5 分钟。');
84
+ }catch(error){
85
+ setPairState('生成失败:'+error.message);log('二维码生成失败:'+error.message);
86
+ }finally{pairRefresh.disabled=!pairHostSelect.value;}
87
+ });
88
+ pairStop?.addEventListener('click',async()=>{
89
+ try{
90
+ const response=await fetch('/api/pairing/stop',{method:'POST'});
91
+ if(!response.ok)throw new Error('HTTP '+response.status);
92
+ clearPairQr();setPairState('二维码已撤销');log('电脑端配对二维码已撤销。');
93
+ }catch(error){setPairState('撤销失败:'+error.message);log('撤销二维码失败:'+error.message);}
94
+ });
95
+ loadPairNetworks();
96
+
97
+
98
+ $('visionTestBtn')?.addEventListener('click',()=>{log('视觉自检请求已记录;当前仓库尚未接入帧采集、OCR 或目标检测运行时。');$('visionEngineState').textContent='运行时未接入';});
99
+ $('researchBtn')?.addEventListener('click',()=>{log('攻略检索检查请求已记录;联网搜索适配器尚未接入,当前不会生成未经来源核验的攻略。');$('researchState').textContent='搜索适配器未接入';});
100
+ $('memoryBtn')?.addEventListener('click',()=>{log('经验记忆检查请求已记录;本地存储、检索与用户清除接口尚未接入。');$('memoryState').textContent='记忆库未接入';});
101
+
102
+
103
+ /* Optional community TTS bridge. The model weights stay outside this repository. */
104
+ const ttsEndpoint=$('ttsEndpoint');
105
+ const ttsAudio=$('ttsAudio');
106
+ const savedTtsEndpoint=localStorage.getItem('gamer.tts.endpoint');
107
+ if(savedTtsEndpoint&&ttsEndpoint)ttsEndpoint.value=savedTtsEndpoint;
108
+ const getTtsBase=()=>{const raw=(ttsEndpoint?.value||'').trim().replace(/\/+$/,'');if(!raw)throw new Error('请填写 TTS 服务地址');const u=new URL(raw);if(!['http:','https:'].includes(u.protocol))throw new Error('只支持 HTTP(S) 地址');return raw;};
109
+ $('ttsHealthBtn')?.addEventListener('click',async()=>{
110
+ try{
111
+ const base=getTtsBase();localStorage.setItem('gamer.tts.endpoint',base);
112
+ $('ttsState').textContent='正在检测…';
113
+ const response=await fetch(base+'/health',{method:'GET'});
114
+ if(!response.ok)throw new Error('HTTP '+response.status);
115
+ const data=await response.json();
116
+ if(data.status!=='ok'||data.loaded!==true)throw new Error('服务在线,但音色模型尚未加载');
117
+ $('ttsState').textContent='已连接 · '+(data.model||'TTS 模型')+' · '+(data.device||'device');
118
+ log('派蒙 TTS 服务健康检查通过。');
119
+ }catch(e){$('ttsState').textContent='连接失败:'+e.message;log('派蒙 TTS 检查失败:'+e.message);}
120
+ });
121
+ $('ttsPreviewBtn')?.addEventListener('click',async()=>{
122
+ try{
123
+ const base=getTtsBase();localStorage.setItem('gamer.tts.endpoint',base);
124
+ const text=($('ttsText')?.value||'').trim();if(!text)throw new Error('请输入试听文本');
125
+ $('ttsState').textContent='正在合成语音…';
126
+ const response=await fetch(base+'/tts_to_audio',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({text,length_scale:1.0})});
127
+ if(!response.ok){let detail='HTTP '+response.status;try{const data=await response.json();detail=data.error?.message||detail;}catch{}throw new Error(detail);}
128
+ const blob=await response.blob();if(!blob.type.includes('audio'))throw new Error('服务返回的不是音频文件');
129
+ if(ttsAudio.dataset.objectUrl)URL.revokeObjectURL(ttsAudio.dataset.objectUrl);
130
+ const objectUrl=URL.createObjectURL(blob);ttsAudio.dataset.objectUrl=objectUrl;ttsAudio.src=objectUrl;
131
+ await ttsAudio.play();$('ttsState').textContent='语音合成成功 · 正在播放';log('派蒙 TTS 试听合成成功。');
132
+ }catch(e){$('ttsState').textContent='试听失败:'+e.message;log('派蒙 TTS 试听失败:'+e.message);}
133
+ });