dsh-convenient-window 0.2.0-beta.3 → 0.2.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.
@@ -1,493 +1,493 @@
1
- // The DSH renderer never receives the engine token or a generic IPC/shell/file API.
2
- import { readFile, stat } from 'node:fs/promises';
3
- import { join, resolve } from 'node:path';
4
- import { randomUUID } from 'node:crypto';
5
- import { verifyNative } from './native-service.js';
6
- import { Helper } from './helper.js';
7
- import { assets, metadata, root, verifyPayload } from './assets.js';
8
- import { atomicJSON, readPrefs, runtimeConfig } from './settings.js';
9
- import {
10
- defaultSettings,
11
- normalizeSettings,
12
- settingsForHelper,
13
- MAX_SETTINGS_STORAGE_BYTES,
14
- gestureLabels,
15
- translator,
16
- toHostAccelerator,
17
- filterLayoutWindows,
18
- normalizeLayoutExclusions,
19
- } from '../lib/model.mjs';
20
- const keys = new Set([
21
- 'convenient-window-theme',
22
- 'convenient-window-language',
23
- 'convenient-window-navigation',
24
- 'convenient-window-pane-widths',
25
- 'convenient-window-layouts',
26
- 'convenient-window-layout-exclusions',
27
- ]);
28
- const allowedEvents = new Set([
29
- 'helper.ready',
30
- 'helper.pong',
31
- 'runtime.status',
32
- 'runtime.error',
33
- 'action.triggered',
34
- 'gesture.recognized',
35
- 'ocr.completed',
36
- 'usage.status',
37
- 'taskbar.status',
38
- 'shortcut.recording',
39
- 'shortcut.hotkeys.synced',
40
- 'window.layout.captured',
41
- 'window.layout.restored',
42
- 'adjustment.updated',
43
- ]);
44
- const plain = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
45
- const idOk = (v) => typeof v === 'string' && /^[a-zA-Z0-9._:-]{1,128}$/.test(v);
46
- async function boundedJSON(path, limit) {
47
- if ((await stat(path)).size > limit) throw Error('settings-unreadable');
48
- return JSON.parse(await readFile(path, 'utf8'));
49
- }
50
- export function cleanConfig(s) {
51
- if (
52
- !plain(s) ||
53
- s.schemaVersion !== 9 ||
54
- typeof s.enabled !== 'boolean' ||
55
- !Array.isArray(s.hotzones) ||
56
- !plain(s.mouseGestures) ||
57
- Buffer.byteLength(JSON.stringify(s)) > MAX_SETTINGS_STORAGE_BYTES
58
- )
59
- throw Error('invalid-settings');
60
- const cfg = normalizeSettings(s);
61
- return cfg;
62
- }
63
- export function configuredCommands(cfg) {
64
- const actions = [
65
- ...cfg.hotzones,
66
- ...cfg.monitorProfiles.flatMap((p) => p.hotzones),
67
- ]
68
- .flatMap((z) => z.actions)
69
- .concat(cfg.mouseGestures.gestures);
70
- const commands = new Set();
71
- for (const s of actions)
72
- for (const a of [
73
- s.action,
74
- ...(s.modifierActions ?? []).map((x) => x.action),
75
- ])
76
- if (a?.kind === 'open-command' && a.value?.trim()) commands.add(a.value);
77
- return [...commands].sort();
78
- }
79
- export async function readPanel(dir) {
80
- try {
81
- const v = await boundedJSON(
82
- join(dir, 'panel-settings.json'),
83
- MAX_SETTINGS_STORAGE_BYTES + 1024,
84
- );
85
- if (v.format !== 2 || !Number.isSafeInteger(v.rev) || v.rev < 0)
86
- throw Error();
87
- return { rev: v.rev, settings: cleanConfig(v.settings) };
88
- } catch (e) {
89
- if (e.code !== 'ENOENT') throw Error('settings-unreadable');
90
- }
91
- try {
92
- await stat(join(dir, 'settings.json'));
93
- const legacy = await readPrefs(dir);
94
- const cfg = await runtimeConfig(legacy.prefs);
95
- return { rev: 0, settings: { ...cfg, enabled: false } };
96
- } catch (e) {
97
- if (e.code !== 'ENOENT') throw Error('settings-unreadable');
98
- }
99
- return {
100
- rev: 0,
101
- settings: { ...structuredClone(defaultSettings), enabled: false },
102
- };
103
- }
104
- export async function loadView(dir) {
105
- try {
106
- const v = await boundedJSON(join(dir, 'panel-view.json'), 2 * 1024 * 1024);
107
- if (
108
- !plain(v) ||
109
- Object.entries(v).some(([k, v]) => !keys.has(k) || typeof v !== 'string')
110
- )
111
- throw Error();
112
- return v;
113
- } catch (e) {
114
- if (e.code === 'ENOENT') return {};
115
- throw Error('settings-unreadable');
116
- }
117
- }
118
- function viewJSON(view, key, fallback) {
119
- try {
120
- return JSON.parse(view[key]);
121
- } catch {
122
- return fallback;
123
- }
124
- }
125
- export class PanelController {
126
- constructor(dir, helper = new Helper(join(dir, 'runtime'))) {
127
- this.dir = dir;
128
- this.helper = helper;
129
- this.session = randomUUID();
130
- this.queue = Promise.resolve();
131
- this.seq = 0;
132
- this.events = [];
133
- this.disposed = false;
134
- this.waiters = new Set();
135
- helper.onEnd = () => this.notify();
136
- helper.onFrame = (m) => this.record(m);
137
- }
138
- load() {
139
- return (this.loaded ??= Promise.all([
140
- readPanel(this.dir),
141
- loadView(this.dir),
142
- Promise.all([verifyPayload(), verifyNative()]).then(
143
- () => true,
144
- () => false,
145
- ),
146
- ]).then(([v, view, valid]) => {
147
- this.v = v;
148
- this.view = view;
149
- this.payloadValid = valid;
150
- if (this.helper.native)
151
- this.helper.native.lang =
152
- view['convenient-window-language'] === 'en-US' ? 'en-US' : 'zh-CN';
153
- }));
154
- }
155
- serial(fn) {
156
- const p = this.queue.then(fn);
157
- this.queue = p.catch(() => {});
158
- return p;
159
- }
160
- snapshot() {
161
- return {
162
- ...this.v,
163
- view: this.view,
164
- session: this.session,
165
- helperVersion: assets.version,
166
- installed: this.payloadValid,
167
- product: metadata.productVersion,
168
- bytes: assets.files.reduce((n, f) => n + f.bytes, 0),
169
- running: !!this.helper.running,
170
- elevated: this.helper.running ? (this.helper.elevated ?? null) : false,
171
- adapter: metadata.version,
172
- };
173
- }
174
- send(type, data = {}, id = randomUUID()) {
175
- if (!this.helper.running) throw Error('helper-disconnected');
176
- this.helper.ws.send(JSON.stringify({ type, id, data, time: Date.now() }));
177
- }
178
- record(m) {
179
- if (m.type === 'shortcut.hotkey.triggered') {
180
- const layouts = viewJSON(
181
- this.view ?? {},
182
- 'convenient-window-layouts',
183
- [],
184
- ),
185
- l =
186
- Array.isArray(layouts) &&
187
- layouts.find((l) => l?.id === m.data?.hotkeyId);
188
- if (l && Array.isArray(l.windows) && l.windows.length <= 64) {
189
- const exclusions = normalizeLayoutExclusions(
190
- viewJSON(this.view, 'convenient-window-layout-exclusions', []),
191
- );
192
- try {
193
- this.send('window.layout.restore', {
194
- windows: filterLayoutWindows(l.windows, exclusions),
195
- });
196
- } catch {}
197
- }
198
- return;
199
- }
200
- if (!allowedEvents.has(m.type)) return;
201
- if (m.type === 'helper.ready') {
202
- this.epoch = randomUUID();
203
- this.events = [];
204
- this.status = null;
205
- this.taskbar = null;
206
- this.ready = m;
207
- }
208
- if (m.type === 'runtime.status' && Array.isArray(m.data?.displays))
209
- this.status = m;
210
- if (m.type === 'taskbar.status') this.taskbar = m;
211
- const item = { seq: ++this.seq, m };
212
- this.events.push(item);
213
- if (this.events.length > 128) this.events.shift();
214
- this.notify();
215
- }
216
- notify() {
217
- for (const wake of this.waiters) wake();
218
- }
219
- async observe(b, signal) {
220
- const check = () => {
221
- if (this.disposed || b.session !== this.session) throw Error('stale');
222
- if (
223
- !this.helper.running ||
224
- !this.ready ||
225
- (b.epoch && b.epoch !== this.epoch)
226
- )
227
- throw Error('helper-disconnected');
228
- };
229
- check();
230
- if (b.cursor === null)
231
- return {
232
- epoch: this.epoch,
233
- cursor: this.seq,
234
- frames: [this.ready, this.status, this.taskbar].filter(Boolean),
235
- };
236
- if (!Number.isSafeInteger(b.cursor) || b.cursor < 0 || b.cursor > this.seq)
237
- throw Error('stream-expired');
238
- if (b.wait === true && b.cursor === this.seq && !signal?.aborted) {
239
- if (this.waiters.size >= 4) throw Error('stream-busy');
240
- await new Promise((ok) => {
241
- const wake = () => {
242
- clearTimeout(timer);
243
- signal?.removeEventListener('abort', wake);
244
- this.waiters.delete(wake);
245
- ok();
246
- };
247
- const timer = setTimeout(wake, 8000);
248
- this.waiters.add(wake);
249
- signal?.addEventListener('abort', wake, { once: true });
250
- });
251
- }
252
- check();
253
- if (b.cursor < (this.events[0]?.seq ?? 1) - 1)
254
- throw Error('stream-expired');
255
- return {
256
- epoch: this.epoch,
257
- cursor: this.seq,
258
- frames: this.events.filter((x) => x.seq > b.cursor).map((x) => x.m),
259
- };
260
- }
261
- syncHotkeys(id) {
262
- const layouts = viewJSON(this.view, 'convenient-window-layouts', []);
263
- const hotkeys = (Array.isArray(layouts) ? layouts : [])
264
- .filter((l) => l && idOk(l.id) && typeof l.shortcut === 'string')
265
- .map((l) => ({ id: l.id, accelerator: toHostAccelerator(l.shortcut) }))
266
- .filter((l) => l.accelerator)
267
- .slice(0, 24);
268
- this.send('shortcut.hotkeys.sync', { hotkeys }, id);
269
- }
270
- activate(loginDir, requestAdmin) {
271
- return this.serial(async () => {
272
- await this.load();
273
- if (this.disposed || !this.v.settings.enabled || this.helper.running)
274
- return;
275
- try {
276
- // Restore the saved master switch even when the settings tab is never opened.
277
- await this.helper.start();
278
- if (
279
- loginDir &&
280
- resolve(loginDir).toLowerCase() === resolve(this.dir).toLowerCase() &&
281
- requestAdmin === '1'
282
- ) {
283
- const login = await this.helper.native.call('login');
284
- if (login.enabled && login.admin) await this.helper.elevation(true);
285
- }
286
- const cfg = settingsForHelper(this.v.settings);
287
- const lang = this.helper.native.lang;
288
- await this.helper.apply(
289
- cfg,
290
- this.v.rev,
291
- gestureLabels(cfg.mouseGestures.gestures, translator(lang)),
292
- );
293
- this.syncHotkeys();
294
- } catch (e) {
295
- await this.helper.stop().catch(() => {});
296
- this.helper.fault = e.message;
297
- }
298
- });
299
- }
300
- request(b, signal) {
301
- if (b?.action === 'observe') return this.observe(b, signal);
302
- return this.serial(async () => {
303
- if (this.disposed) throw Error('unloaded');
304
- await this.load();
305
- if (b === null) return this.snapshot();
306
- if (!plain(b) || b.session !== this.session) throw Error('stale');
307
- if (b.action === 'stop') {
308
- await this.helper.stop();
309
- return { ok: true };
310
- }
311
- if (b.action === 'save') {
312
- if (b.rev !== this.v.rev) throw Error('stale');
313
- const settings = cleanConfig(b.settings);
314
- const previous = new Set(configuredCommands(this.v.settings));
315
- const added = configuredCommands(settings).filter(
316
- (x) => !previous.has(x),
317
- );
318
- if (
319
- added.length &&
320
- !(await this.helper.native.call('confirm-commands', added))
321
- )
322
- throw Error('cancelled');
323
- const next = { rev: this.v.rev + 1, settings };
324
- await atomicJSON(this.dir, 'panel-settings.json', {
325
- format: 2,
326
- ...next,
327
- });
328
- this.v = next;
329
- return { rev: next.rev };
330
- }
331
- if (b.action === 'view') {
332
- if (
333
- !keys.has(b.key) ||
334
- typeof b.value !== 'string' ||
335
- b.value.length > 750000
336
- )
337
- throw Error('invalid-settings');
338
- if ((this.view[b.key] ?? null) !== b.previous) throw Error('stale');
339
- const v = { ...this.view, [b.key]: b.value };
340
- if (Buffer.byteLength(JSON.stringify(v)) > 2 * 1024 * 1024)
341
- throw Error('invalid-settings');
342
- await atomicJSON(this.dir, 'panel-view.json', v);
343
- this.view = v;
344
- if (b.key === 'convenient-window-layouts' && this.helper.running)
345
- this.syncHotkeys();
346
- return { ok: true };
347
- }
348
- if (b.action === 'start') {
349
- if (b.rev !== this.v.rev) throw Error('stale');
350
- if (!this.v.settings.enabled) throw Error('power-off');
351
- const alreadyRunning = !!this.helper.running;
352
- const info = await this.helper.start();
353
- if (!alreadyRunning) this.syncHotkeys();
354
- return {
355
- alreadyRunning,
356
- elevated: info?.elevated ?? false,
357
- warning: info?.warning ?? null,
358
- };
359
- }
360
- if (b.action === 'native') {
361
- if (!this.payloadValid && this.helper instanceof Helper)
362
- throw Error('payload-invalid');
363
- if (
364
- ![
365
- 'startup',
366
- 'pick',
367
- 'login',
368
- 'set-login',
369
- 'set-login-admin',
370
- 'language',
371
- ].includes(b.op)
372
- )
373
- throw Error('invalid-command');
374
- if (
375
- b.op === 'startup' &&
376
- !['list', 'add', 'setEnabled'].includes(b.data?.action)
377
- )
378
- throw Error('invalid-command');
379
- if (
380
- ['set-login', 'set-login-admin'].includes(b.op) &&
381
- typeof b.data !== 'boolean'
382
- )
383
- throw Error('invalid-command');
384
- if (b.op === 'language') {
385
- this.helper.native.lang = b.data === 'en-US' ? 'en-US' : 'zh-CN';
386
- if (!this.helper.native.child) return null;
387
- }
388
- return this.helper.native.call(b.op, b.data);
389
- }
390
- if (b.action === 'elevation') {
391
- if (
392
- b.rev !== this.v.rev ||
393
- typeof b.enabled !== 'boolean' ||
394
- !this.helper.running
395
- )
396
- throw Error('stale');
397
- const r = await this.helper.elevation(b.enabled);
398
- this.syncHotkeys();
399
- return { elevated: r.elevated, warning: r.warning };
400
- }
401
- if (b.action === 'diagnostics') {
402
- const native = this.helper.native?.session
403
- ? await this.helper.native.call('status').catch(() => null)
404
- : null;
405
- return {
406
- installed: this.payloadValid,
407
- development: false,
408
- helperRunning: !!this.helper.running,
409
- lastExitCode: native?.lastExitCode ?? null,
410
- hudTitle: native?.hudTitle ?? null,
411
- loginTargetValid: native?.loginTargetValid ?? false,
412
- installedProfile: native?.installedProfile ?? false,
413
- lastError: this.helper.fault ?? null,
414
- };
415
- }
416
- if (
417
- b.action !== 'engine' ||
418
- !this.helper.running ||
419
- !idOk(b.id) ||
420
- b.epoch !== this.epoch ||
421
- !plain(b.data)
422
- )
423
- throw Error('invalid-command');
424
- const d = b.data;
425
- switch (b.type) {
426
- case 'config.update': {
427
- if (
428
- b.rev !== this.v.rev ||
429
- !Number.isSafeInteger(d.revision) ||
430
- d.revision < 0
431
- )
432
- throw Error('stale');
433
- const cfg = settingsForHelper(this.v.settings);
434
- const lang =
435
- this.view['convenient-window-language'] === 'en-US'
436
- ? 'en-US'
437
- : 'zh-CN';
438
- try {
439
- await this.helper.apply(
440
- cfg,
441
- d.revision,
442
- gestureLabels(cfg.mouseGestures.gestures, translator(lang)),
443
- );
444
- } catch (e) {
445
- await this.helper.stop();
446
- throw e;
447
- }
448
- return { applied: d.revision };
449
- }
450
- case 'helper.stop':
451
- await this.helper.stop();
452
- break;
453
- case 'helper.ping':
454
- case 'usage.get':
455
- case 'window.layout.capture':
456
- this.send(b.type, {}, b.id);
457
- break;
458
- case 'shortcut.record.begin':
459
- case 'shortcut.record.cancel':
460
- if (!idOk(d.sessionId)) throw Error('invalid-command');
461
- this.send(b.type, { sessionId: d.sessionId }, b.id);
462
- break;
463
- case 'shortcut.hotkeys.sync':
464
- this.syncHotkeys(b.id);
465
- break;
466
- case 'window.layout.restore':
467
- if (
468
- !Array.isArray(d.windows) ||
469
- d.windows.length > 64 ||
470
- d.windows.some(
471
- (w) =>
472
- !plain(w) ||
473
- typeof w.processName !== 'string' ||
474
- !plain(w.rect),
475
- )
476
- )
477
- throw Error('invalid-command');
478
- this.send(b.type, { windows: d.windows }, b.id);
479
- break;
480
- default:
481
- throw Error('invalid-command');
482
- }
483
- return { ok: true };
484
- });
485
- }
486
- dispose() {
487
- this.disposed = true;
488
- this.notify();
489
- return this.helper.dispose
490
- ? this.helper.dispose()
491
- : this.serial(() => this.helper.stop());
492
- }
493
- }
1
+ // The DSH renderer never receives the engine token or a generic IPC/shell/file API.
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { verifyNative } from './native-service.js';
6
+ import { Helper } from './helper.js';
7
+ import { assets, metadata, root, verifyPayload } from './assets.js';
8
+ import { atomicJSON, readPrefs, runtimeConfig } from './settings.js';
9
+ import {
10
+ defaultSettings,
11
+ normalizeSettings,
12
+ settingsForHelper,
13
+ MAX_SETTINGS_STORAGE_BYTES,
14
+ gestureLabels,
15
+ translator,
16
+ toHostAccelerator,
17
+ filterLayoutWindows,
18
+ normalizeLayoutExclusions,
19
+ } from '../lib/model.mjs';
20
+ const keys = new Set([
21
+ 'convenient-window-theme',
22
+ 'convenient-window-language',
23
+ 'convenient-window-navigation',
24
+ 'convenient-window-pane-widths',
25
+ 'convenient-window-layouts',
26
+ 'convenient-window-layout-exclusions',
27
+ ]);
28
+ const allowedEvents = new Set([
29
+ 'helper.ready',
30
+ 'helper.pong',
31
+ 'runtime.status',
32
+ 'runtime.error',
33
+ 'action.triggered',
34
+ 'gesture.recognized',
35
+ 'ocr.completed',
36
+ 'usage.status',
37
+ 'taskbar.status',
38
+ 'shortcut.recording',
39
+ 'shortcut.hotkeys.synced',
40
+ 'window.layout.captured',
41
+ 'window.layout.restored',
42
+ 'adjustment.updated',
43
+ ]);
44
+ const plain = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
45
+ const idOk = (v) => typeof v === 'string' && /^[a-zA-Z0-9._:-]{1,128}$/.test(v);
46
+ async function boundedJSON(path, limit) {
47
+ if ((await stat(path)).size > limit) throw Error('settings-unreadable');
48
+ return JSON.parse(await readFile(path, 'utf8'));
49
+ }
50
+ export function cleanConfig(s) {
51
+ if (
52
+ !plain(s) ||
53
+ s.schemaVersion !== 9 ||
54
+ typeof s.enabled !== 'boolean' ||
55
+ !Array.isArray(s.hotzones) ||
56
+ !plain(s.mouseGestures) ||
57
+ Buffer.byteLength(JSON.stringify(s)) > MAX_SETTINGS_STORAGE_BYTES
58
+ )
59
+ throw Error('invalid-settings');
60
+ const cfg = normalizeSettings(s);
61
+ return cfg;
62
+ }
63
+ export function configuredCommands(cfg) {
64
+ const actions = [
65
+ ...cfg.hotzones,
66
+ ...cfg.monitorProfiles.flatMap((p) => p.hotzones),
67
+ ]
68
+ .flatMap((z) => z.actions)
69
+ .concat(cfg.mouseGestures.gestures);
70
+ const commands = new Set();
71
+ for (const s of actions)
72
+ for (const a of [
73
+ s.action,
74
+ ...(s.modifierActions ?? []).map((x) => x.action),
75
+ ])
76
+ if (a?.kind === 'open-command' && a.value?.trim()) commands.add(a.value);
77
+ return [...commands].sort();
78
+ }
79
+ export async function readPanel(dir) {
80
+ try {
81
+ const v = await boundedJSON(
82
+ join(dir, 'panel-settings.json'),
83
+ MAX_SETTINGS_STORAGE_BYTES + 1024,
84
+ );
85
+ if (v.format !== 2 || !Number.isSafeInteger(v.rev) || v.rev < 0)
86
+ throw Error();
87
+ return { rev: v.rev, settings: cleanConfig(v.settings) };
88
+ } catch (e) {
89
+ if (e.code !== 'ENOENT') throw Error('settings-unreadable');
90
+ }
91
+ try {
92
+ await stat(join(dir, 'settings.json'));
93
+ const legacy = await readPrefs(dir);
94
+ const cfg = await runtimeConfig(legacy.prefs);
95
+ return { rev: 0, settings: { ...cfg, enabled: false } };
96
+ } catch (e) {
97
+ if (e.code !== 'ENOENT') throw Error('settings-unreadable');
98
+ }
99
+ return {
100
+ rev: 0,
101
+ settings: { ...structuredClone(defaultSettings), enabled: false },
102
+ };
103
+ }
104
+ export async function loadView(dir) {
105
+ try {
106
+ const v = await boundedJSON(join(dir, 'panel-view.json'), 2 * 1024 * 1024);
107
+ if (
108
+ !plain(v) ||
109
+ Object.entries(v).some(([k, v]) => !keys.has(k) || typeof v !== 'string')
110
+ )
111
+ throw Error();
112
+ return v;
113
+ } catch (e) {
114
+ if (e.code === 'ENOENT') return {};
115
+ throw Error('settings-unreadable');
116
+ }
117
+ }
118
+ function viewJSON(view, key, fallback) {
119
+ try {
120
+ return JSON.parse(view[key]);
121
+ } catch {
122
+ return fallback;
123
+ }
124
+ }
125
+ export class PanelController {
126
+ constructor(dir, helper = new Helper(join(dir, 'runtime'))) {
127
+ this.dir = dir;
128
+ this.helper = helper;
129
+ this.session = randomUUID();
130
+ this.queue = Promise.resolve();
131
+ this.seq = 0;
132
+ this.events = [];
133
+ this.disposed = false;
134
+ this.waiters = new Set();
135
+ helper.onEnd = () => this.notify();
136
+ helper.onFrame = (m) => this.record(m);
137
+ }
138
+ load() {
139
+ return (this.loaded ??= Promise.all([
140
+ readPanel(this.dir),
141
+ loadView(this.dir),
142
+ Promise.all([verifyPayload(), verifyNative()]).then(
143
+ () => true,
144
+ () => false,
145
+ ),
146
+ ]).then(([v, view, valid]) => {
147
+ this.v = v;
148
+ this.view = view;
149
+ this.payloadValid = valid;
150
+ if (this.helper.native)
151
+ this.helper.native.lang =
152
+ view['convenient-window-language'] === 'en-US' ? 'en-US' : 'zh-CN';
153
+ }));
154
+ }
155
+ serial(fn) {
156
+ const p = this.queue.then(fn);
157
+ this.queue = p.catch(() => {});
158
+ return p;
159
+ }
160
+ snapshot() {
161
+ return {
162
+ ...this.v,
163
+ view: this.view,
164
+ session: this.session,
165
+ helperVersion: assets.version,
166
+ installed: this.payloadValid,
167
+ product: metadata.productVersion,
168
+ bytes: assets.files.reduce((n, f) => n + f.bytes, 0),
169
+ running: !!this.helper.running,
170
+ elevated: this.helper.running ? (this.helper.elevated ?? null) : false,
171
+ adapter: metadata.version,
172
+ };
173
+ }
174
+ send(type, data = {}, id = randomUUID()) {
175
+ if (!this.helper.running) throw Error('helper-disconnected');
176
+ this.helper.ws.send(JSON.stringify({ type, id, data, time: Date.now() }));
177
+ }
178
+ record(m) {
179
+ if (m.type === 'shortcut.hotkey.triggered') {
180
+ const layouts = viewJSON(
181
+ this.view ?? {},
182
+ 'convenient-window-layouts',
183
+ [],
184
+ ),
185
+ l =
186
+ Array.isArray(layouts) &&
187
+ layouts.find((l) => l?.id === m.data?.hotkeyId);
188
+ if (l && Array.isArray(l.windows) && l.windows.length <= 64) {
189
+ const exclusions = normalizeLayoutExclusions(
190
+ viewJSON(this.view, 'convenient-window-layout-exclusions', []),
191
+ );
192
+ try {
193
+ this.send('window.layout.restore', {
194
+ windows: filterLayoutWindows(l.windows, exclusions),
195
+ });
196
+ } catch {}
197
+ }
198
+ return;
199
+ }
200
+ if (!allowedEvents.has(m.type)) return;
201
+ if (m.type === 'helper.ready') {
202
+ this.epoch = randomUUID();
203
+ this.events = [];
204
+ this.status = null;
205
+ this.taskbar = null;
206
+ this.ready = m;
207
+ }
208
+ if (m.type === 'runtime.status' && Array.isArray(m.data?.displays))
209
+ this.status = m;
210
+ if (m.type === 'taskbar.status') this.taskbar = m;
211
+ const item = { seq: ++this.seq, m };
212
+ this.events.push(item);
213
+ if (this.events.length > 128) this.events.shift();
214
+ this.notify();
215
+ }
216
+ notify() {
217
+ for (const wake of this.waiters) wake();
218
+ }
219
+ async observe(b, signal) {
220
+ const check = () => {
221
+ if (this.disposed || b.session !== this.session) throw Error('stale');
222
+ if (
223
+ !this.helper.running ||
224
+ !this.ready ||
225
+ (b.epoch && b.epoch !== this.epoch)
226
+ )
227
+ throw Error('helper-disconnected');
228
+ };
229
+ check();
230
+ if (b.cursor === null)
231
+ return {
232
+ epoch: this.epoch,
233
+ cursor: this.seq,
234
+ frames: [this.ready, this.status, this.taskbar].filter(Boolean),
235
+ };
236
+ if (!Number.isSafeInteger(b.cursor) || b.cursor < 0 || b.cursor > this.seq)
237
+ throw Error('stream-expired');
238
+ if (b.wait === true && b.cursor === this.seq && !signal?.aborted) {
239
+ if (this.waiters.size >= 4) throw Error('stream-busy');
240
+ await new Promise((ok) => {
241
+ const wake = () => {
242
+ clearTimeout(timer);
243
+ signal?.removeEventListener('abort', wake);
244
+ this.waiters.delete(wake);
245
+ ok();
246
+ };
247
+ const timer = setTimeout(wake, 8000);
248
+ this.waiters.add(wake);
249
+ signal?.addEventListener('abort', wake, { once: true });
250
+ });
251
+ }
252
+ check();
253
+ if (b.cursor < (this.events[0]?.seq ?? 1) - 1)
254
+ throw Error('stream-expired');
255
+ return {
256
+ epoch: this.epoch,
257
+ cursor: this.seq,
258
+ frames: this.events.filter((x) => x.seq > b.cursor).map((x) => x.m),
259
+ };
260
+ }
261
+ syncHotkeys(id) {
262
+ const layouts = viewJSON(this.view, 'convenient-window-layouts', []);
263
+ const hotkeys = (Array.isArray(layouts) ? layouts : [])
264
+ .filter((l) => l && idOk(l.id) && typeof l.shortcut === 'string')
265
+ .map((l) => ({ id: l.id, accelerator: toHostAccelerator(l.shortcut) }))
266
+ .filter((l) => l.accelerator)
267
+ .slice(0, 24);
268
+ this.send('shortcut.hotkeys.sync', { hotkeys }, id);
269
+ }
270
+ activate(loginDir, requestAdmin) {
271
+ return this.serial(async () => {
272
+ await this.load();
273
+ if (this.disposed || !this.v.settings.enabled || this.helper.running)
274
+ return;
275
+ try {
276
+ // Restore the saved master switch even when the settings tab is never opened.
277
+ await this.helper.start();
278
+ if (
279
+ loginDir &&
280
+ resolve(loginDir).toLowerCase() === resolve(this.dir).toLowerCase() &&
281
+ requestAdmin === '1'
282
+ ) {
283
+ const login = await this.helper.native.call('login');
284
+ if (login.enabled && login.admin) await this.helper.elevation(true);
285
+ }
286
+ const cfg = settingsForHelper(this.v.settings);
287
+ const lang = this.helper.native.lang;
288
+ await this.helper.apply(
289
+ cfg,
290
+ this.v.rev,
291
+ gestureLabels(cfg.mouseGestures.gestures, translator(lang)),
292
+ );
293
+ this.syncHotkeys();
294
+ } catch (e) {
295
+ await this.helper.stop().catch(() => {});
296
+ this.helper.fault = e.message;
297
+ }
298
+ });
299
+ }
300
+ request(b, signal) {
301
+ if (b?.action === 'observe') return this.observe(b, signal);
302
+ return this.serial(async () => {
303
+ if (this.disposed) throw Error('unloaded');
304
+ await this.load();
305
+ if (b === null) return this.snapshot();
306
+ if (!plain(b) || b.session !== this.session) throw Error('stale');
307
+ if (b.action === 'stop') {
308
+ await this.helper.stop();
309
+ return { ok: true };
310
+ }
311
+ if (b.action === 'save') {
312
+ if (b.rev !== this.v.rev) throw Error('stale');
313
+ const settings = cleanConfig(b.settings);
314
+ const previous = new Set(configuredCommands(this.v.settings));
315
+ const added = configuredCommands(settings).filter(
316
+ (x) => !previous.has(x),
317
+ );
318
+ if (
319
+ added.length &&
320
+ !(await this.helper.native.call('confirm-commands', added))
321
+ )
322
+ throw Error('cancelled');
323
+ const next = { rev: this.v.rev + 1, settings };
324
+ await atomicJSON(this.dir, 'panel-settings.json', {
325
+ format: 2,
326
+ ...next,
327
+ });
328
+ this.v = next;
329
+ return { rev: next.rev };
330
+ }
331
+ if (b.action === 'view') {
332
+ if (
333
+ !keys.has(b.key) ||
334
+ typeof b.value !== 'string' ||
335
+ b.value.length > 750000
336
+ )
337
+ throw Error('invalid-settings');
338
+ if ((this.view[b.key] ?? null) !== b.previous) throw Error('stale');
339
+ const v = { ...this.view, [b.key]: b.value };
340
+ if (Buffer.byteLength(JSON.stringify(v)) > 2 * 1024 * 1024)
341
+ throw Error('invalid-settings');
342
+ await atomicJSON(this.dir, 'panel-view.json', v);
343
+ this.view = v;
344
+ if (b.key === 'convenient-window-layouts' && this.helper.running)
345
+ this.syncHotkeys();
346
+ return { ok: true };
347
+ }
348
+ if (b.action === 'start') {
349
+ if (b.rev !== this.v.rev) throw Error('stale');
350
+ if (!this.v.settings.enabled) throw Error('power-off');
351
+ const alreadyRunning = !!this.helper.running;
352
+ const info = await this.helper.start();
353
+ if (!alreadyRunning) this.syncHotkeys();
354
+ return {
355
+ alreadyRunning,
356
+ elevated: info?.elevated ?? false,
357
+ warning: info?.warning ?? null,
358
+ };
359
+ }
360
+ if (b.action === 'native') {
361
+ if (!this.payloadValid && this.helper instanceof Helper)
362
+ throw Error('payload-invalid');
363
+ if (
364
+ ![
365
+ 'startup',
366
+ 'pick',
367
+ 'login',
368
+ 'set-login',
369
+ 'set-login-admin',
370
+ 'language',
371
+ ].includes(b.op)
372
+ )
373
+ throw Error('invalid-command');
374
+ if (
375
+ b.op === 'startup' &&
376
+ !['list', 'add', 'setEnabled'].includes(b.data?.action)
377
+ )
378
+ throw Error('invalid-command');
379
+ if (
380
+ ['set-login', 'set-login-admin'].includes(b.op) &&
381
+ typeof b.data !== 'boolean'
382
+ )
383
+ throw Error('invalid-command');
384
+ if (b.op === 'language') {
385
+ this.helper.native.lang = b.data === 'en-US' ? 'en-US' : 'zh-CN';
386
+ if (!this.helper.native.child) return null;
387
+ }
388
+ return this.helper.native.call(b.op, b.data);
389
+ }
390
+ if (b.action === 'elevation') {
391
+ if (
392
+ b.rev !== this.v.rev ||
393
+ typeof b.enabled !== 'boolean' ||
394
+ !this.helper.running
395
+ )
396
+ throw Error('stale');
397
+ const r = await this.helper.elevation(b.enabled);
398
+ this.syncHotkeys();
399
+ return { elevated: r.elevated, warning: r.warning };
400
+ }
401
+ if (b.action === 'diagnostics') {
402
+ const native = this.helper.native?.session
403
+ ? await this.helper.native.call('status').catch(() => null)
404
+ : null;
405
+ return {
406
+ installed: this.payloadValid,
407
+ development: false,
408
+ helperRunning: !!this.helper.running,
409
+ lastExitCode: native?.lastExitCode ?? null,
410
+ hudTitle: native?.hudTitle ?? null,
411
+ loginTargetValid: native?.loginTargetValid ?? false,
412
+ installedProfile: native?.installedProfile ?? false,
413
+ lastError: this.helper.fault ?? null,
414
+ };
415
+ }
416
+ if (
417
+ b.action !== 'engine' ||
418
+ !this.helper.running ||
419
+ !idOk(b.id) ||
420
+ b.epoch !== this.epoch ||
421
+ !plain(b.data)
422
+ )
423
+ throw Error('invalid-command');
424
+ const d = b.data;
425
+ switch (b.type) {
426
+ case 'config.update': {
427
+ if (
428
+ b.rev !== this.v.rev ||
429
+ !Number.isSafeInteger(d.revision) ||
430
+ d.revision < 0
431
+ )
432
+ throw Error('stale');
433
+ const cfg = settingsForHelper(this.v.settings);
434
+ const lang =
435
+ this.view['convenient-window-language'] === 'en-US'
436
+ ? 'en-US'
437
+ : 'zh-CN';
438
+ try {
439
+ await this.helper.apply(
440
+ cfg,
441
+ d.revision,
442
+ gestureLabels(cfg.mouseGestures.gestures, translator(lang)),
443
+ );
444
+ } catch (e) {
445
+ await this.helper.stop();
446
+ throw e;
447
+ }
448
+ return { applied: d.revision };
449
+ }
450
+ case 'helper.stop':
451
+ await this.helper.stop();
452
+ break;
453
+ case 'helper.ping':
454
+ case 'usage.get':
455
+ case 'window.layout.capture':
456
+ this.send(b.type, {}, b.id);
457
+ break;
458
+ case 'shortcut.record.begin':
459
+ case 'shortcut.record.cancel':
460
+ if (!idOk(d.sessionId)) throw Error('invalid-command');
461
+ this.send(b.type, { sessionId: d.sessionId }, b.id);
462
+ break;
463
+ case 'shortcut.hotkeys.sync':
464
+ this.syncHotkeys(b.id);
465
+ break;
466
+ case 'window.layout.restore':
467
+ if (
468
+ !Array.isArray(d.windows) ||
469
+ d.windows.length > 64 ||
470
+ d.windows.some(
471
+ (w) =>
472
+ !plain(w) ||
473
+ typeof w.processName !== 'string' ||
474
+ !plain(w.rect),
475
+ )
476
+ )
477
+ throw Error('invalid-command');
478
+ this.send(b.type, { windows: d.windows }, b.id);
479
+ break;
480
+ default:
481
+ throw Error('invalid-command');
482
+ }
483
+ return { ok: true };
484
+ });
485
+ }
486
+ dispose() {
487
+ this.disposed = true;
488
+ this.notify();
489
+ return this.helper.dispose
490
+ ? this.helper.dispose()
491
+ : this.serial(() => this.helper.stop());
492
+ }
493
+ }