dsh-task-cat 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.
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-task-pet
3
+ name: 'dsh-task-cat'
package/desktop.js ADDED
@@ -0,0 +1,559 @@
1
+ /**
2
+ * dsh-task-pet — desktop overlay supervisor.
3
+ *
4
+ * The Web page can only float a pet inside its own window: the desktop shell
5
+ * hands plugins no window API (its preload bridge exposes file actions, the
6
+ * embedded browser, shortcuts and updates, never a BrowserWindow), Chromium's
7
+ * Document Picture-in-Picture is not implemented by Electron, and every
8
+ * `window.open` from the page is denied by the shell's window-open handler.
9
+ *
10
+ * So the screen-wide pet is a small native helper this module compiles once and
11
+ * runs beside the Host: a borderless, always-on-top, non-activating panel. State
12
+ * travels to it as JSON lines on stdin; clicks come back as JSON lines on
13
+ * stdout. The pipe is the whole protocol — no port, no token, nothing to guard.
14
+ *
15
+ * The helper is macOS-only by construction (AppKit). Everywhere else `capable()`
16
+ * answers false and the page keeps its in-window pet.
17
+ *
18
+ * @module dsh-task-pet/desktop
19
+ */
20
+ import { spawn } from 'node:child_process';
21
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
22
+ import { homedir } from 'node:os';
23
+ import { dirname, join } from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+
26
+ /** Where this package's Swift source lives. */
27
+ const SOURCE_PATH = fileURLToPath(new URL('./overlay/TaskPetOverlay.swift', import.meta.url));
28
+
29
+ /** `$DSH_HOME`, matching the persistence layer's own resolution. */
30
+ const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
31
+
32
+ /** Compiled helpers and the durable preference live under DSH_HOME. */
33
+ const CACHE_DIR = join(DSH_HOME, 'cache', 'dsh-task-pet');
34
+ const BINARY_PATH = join(CACHE_DIR, 'TaskPetOverlay');
35
+ const PREFERENCE_PATH = join(DSH_HOME, 'storages', 'dsh-task-pet', 'desktop.json');
36
+
37
+ /** Boundary on what one helper line may cost us. */
38
+ const LINE_LIMIT = 65536;
39
+
40
+ /** Quiet period before an idle overlay is told the app went away. */
41
+ const IDLE_MS = 15000;
42
+
43
+ /** A helper that stayed up this long is healthy; a shorter life is a crash. */
44
+ const HEALTHY_MS = 30000;
45
+
46
+ /** How long a helper may leave a liveness probe unanswered before it is killed. */
47
+ const PROBE_TIMEOUT_MS = 45000;
48
+
49
+ /** How often a liveness probe is sent while the helper runs. */
50
+ const PING_MS = 15000;
51
+
52
+ /**
53
+ * Read one JSON object from disk.
54
+ * @param path - absolute file path.
55
+ * @returns the parsed object, or undefined when absent or malformed.
56
+ */
57
+ function readJson(path) {
58
+ try {
59
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
60
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : undefined;
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Write one JSON object, creating parent directories.
68
+ * @param path - absolute file path.
69
+ * @param value - JSON-serializable payload.
70
+ */
71
+ function writeJson(path, value) {
72
+ try {
73
+ mkdirSync(dirname(path), { recursive: true });
74
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
75
+ } catch {
76
+ /* A preference that cannot be stored must not break the pet. */
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Best available language tag for the helper's own menu. DSH's resolved locale
82
+ * wins; `LANG` is only used when it looks like a real tag.
83
+ * @returns a BCP 47-ish tag such as `zh-CN`.
84
+ */
85
+ function resolvedLocale() {
86
+ for (const candidate of [process.env.DSH_LOCALE, process.env.DSH_DESKTOP_LOCALE, process.env.LC_ALL, process.env.LANG]) {
87
+ if (typeof candidate === 'string' && /^[A-Za-z]{2,3}(?:[_-][A-Za-z0-9]{2,8})?/.test(candidate) && !candidate.startsWith('C.')) {
88
+ return candidate.split('.')[0].replace('_', '-');
89
+ }
90
+ }
91
+ return 'en';
92
+ }
93
+
94
+ /**
95
+ * The compiler this machine offers, when it has one.
96
+ * @returns an absolute interpreter path, or undefined.
97
+ */
98
+ function compilerPath() {
99
+ if (process.platform !== 'darwin') return undefined;
100
+ if (existsSync('/usr/bin/swiftc')) return '/usr/bin/swiftc';
101
+ if (existsSync('/usr/bin/xcrun')) return '/usr/bin/xcrun';
102
+ return undefined;
103
+ }
104
+
105
+ /**
106
+ * Whether the compiled helper is newer than its source.
107
+ * @returns true when the binary can be used as-is.
108
+ */
109
+ function binaryIsFresh() {
110
+ try {
111
+ return statSync(BINARY_PATH).mtimeMs >= statSync(SOURCE_PATH).mtimeMs;
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Keep one helper process alive, compile it on demand, and relay its events.
119
+ *
120
+ * @param ctx - Host plugin context (for effects and logging).
121
+ * @returns the supervisor face used by the routes.
122
+ */
123
+ export function createDesktopPet(ctx) {
124
+ const stored = readJson(PREFERENCE_PATH);
125
+ /**
126
+ * The user's standing choice. Absent means never asked, and a native helper
127
+ * that compiles code and floats above every other window is opt-in: only an
128
+ * explicit `enabled: true` starts it.
129
+ */
130
+ let enabled = stored?.enabled === true;
131
+ /** Set when the helper reported its own menu hid it for this run. */
132
+ let supported = compilerPath() !== undefined;
133
+ let compiling = false;
134
+ let compilingPromise;
135
+ let compileError;
136
+ let child;
137
+ let stderr = '';
138
+ let restarts = 0;
139
+ /** When the current helper announced itself; 0 while it has not. */
140
+ let readyAt = 0;
141
+ /** Set while another Harness instance owns the one screen-wide pet. */
142
+ let conflict = false;
143
+ /** Slow re-check while a conflict or a crashed helper is pending. */
144
+ let retryTimer;
145
+ /** Backoff timer for the crash ladder. */
146
+ let restartTimer;
147
+ /** Last liveness reply from the helper; 0 until the first pong. */
148
+ let lastPongAt = 0;
149
+ /** When the current helper was started, used before the first pong arrives. */
150
+ let spawnedAt = 0;
151
+ /** When the last liveness probe went out. */
152
+ let lastPingAt = 0;
153
+ /** Bumped by every start/stop so a late await never revives a stopped helper. */
154
+ let generation = 0;
155
+ let lastStateAt = 0;
156
+ let latestState;
157
+ let idleTimer;
158
+ const listeners = new Set();
159
+
160
+ /**
161
+ * Tell the page what happened. Every subscriber is a `shell.overlay` entry
162
+ * that needs to know whether it should draw its own pet.
163
+ * @param event - event name.
164
+ * @param data - JSON payload.
165
+ */
166
+ function notify(event, data) {
167
+ for (const listener of [...listeners]) {
168
+ try {
169
+ listener(event, data);
170
+ } catch (error) {
171
+ ctx.logger?.warn?.(`dsh-task-pet: overlay listener failed: ${String(error)}`);
172
+ }
173
+ }
174
+ }
175
+
176
+ /** Publish the current capability so a late subscriber is never in the dark. */
177
+ function status() {
178
+ return {
179
+ supported,
180
+ enabled,
181
+ running: child !== undefined,
182
+ compiling,
183
+ ...(conflict ? { conflict: true } : {}),
184
+ ...(compileError === undefined ? {} : { error: compileError }),
185
+ };
186
+ }
187
+
188
+ /**
189
+ * Compile the helper once. Runs in the background: the in-window pet keeps
190
+ * working while this finishes, and a failure only costs the desktop mode.
191
+ * @returns a promise resolving to the binary path, or undefined.
192
+ */
193
+ async function ensureBinary() {
194
+ if (!supported) return undefined;
195
+ if (binaryIsFresh()) return BINARY_PATH;
196
+ if (compilingPromise !== undefined) return compilingPromise;
197
+ compiling = true;
198
+ compilingPromise = compile();
199
+ try {
200
+ return await compilingPromise;
201
+ } finally {
202
+ compilingPromise = undefined;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Compile the helper source into the cache directory.
208
+ * @returns the binary path, or undefined when the toolchain refused.
209
+ */
210
+ async function compile() {
211
+ const compiler = compilerPath();
212
+ const argv = compiler === '/usr/bin/xcrun'
213
+ ? ['/usr/bin/xcrun', '--sdk', 'macosx', 'swiftc', '-O', '-o', BINARY_PATH, SOURCE_PATH]
214
+ : [compiler, '-O', '-o', BINARY_PATH, SOURCE_PATH];
215
+ try {
216
+ mkdirSync(CACHE_DIR, { recursive: true });
217
+ const detail = await new Promise((resolve) => {
218
+ const proc = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'ignore', 'pipe'] });
219
+ let text = '';
220
+ proc.stderr?.setEncoding('utf8');
221
+ proc.stderr?.on('data', (chunk) => {
222
+ text = (text + chunk).slice(-8192);
223
+ });
224
+ proc.on('error', (error) => resolve(`spawn failed: ${error.message}`));
225
+ proc.on('close', (code) => resolve(code === 0 ? undefined : `swiftc exited ${String(code)}: ${text.trim()}`));
226
+ });
227
+ compiling = false;
228
+ if (detail !== undefined) {
229
+ compileError = detail.slice(0, 400);
230
+ supported = false;
231
+ notify('status', status());
232
+ return undefined;
233
+ }
234
+ compileError = undefined;
235
+ notify('status', status());
236
+ return BINARY_PATH;
237
+ } catch (error) {
238
+ compiling = false;
239
+ compileError = String(error).slice(0, 400);
240
+ supported = false;
241
+ notify('status', status());
242
+ return undefined;
243
+ }
244
+ }
245
+
246
+ /** Consume one stdout line from the helper. */
247
+ function handleLine(line) {
248
+ if (line === '') return;
249
+ let message;
250
+ try {
251
+ message = JSON.parse(line);
252
+ } catch {
253
+ return;
254
+ }
255
+ if (typeof message !== 'object' || message === null) return;
256
+ switch (message.type) {
257
+ case 'ready':
258
+ // Do NOT clear the crash ladder here: a helper that starts, dies, and is
259
+ // respawned would reset its own budget forever. Only a helper that has
260
+ // stayed up long enough counts as healthy.
261
+ readyAt = Date.now();
262
+ notify('status', status());
263
+ return;
264
+ case 'jump':
265
+ if (typeof message.id === 'string') notify('jump', { id: message.id });
266
+ return;
267
+ case 'activate':
268
+ notify('activate', {});
269
+ return;
270
+ case 'detach':
271
+ // The user asked for the pet in the app window instead. That is a
272
+ // standing choice, so it outlives this run.
273
+ enabled = false;
274
+ writeJson(PREFERENCE_PATH, { enabled });
275
+ notify('status', status());
276
+ void stop();
277
+ return;
278
+ case 'hidden':
279
+ // Hiding from the helper's menu retires the pet for this run only: the
280
+ // durable preference stays on, so the panel's toggle brings it back and
281
+ // a restart does not leave the user with no way to find it again.
282
+ enabled = false;
283
+ notify('status', status());
284
+ return;
285
+ case 'disabled':
286
+ // The helper checked the preference and found no opt-in. Stop trying: the
287
+ // user's file is the source of truth, and our own state was stale.
288
+ enabled = false;
289
+ compileError = undefined;
290
+ notify('status', status());
291
+ return;
292
+ case 'pong':
293
+ lastPongAt = Date.now();
294
+ return;
295
+ case 'log':
296
+ if (typeof message.message === 'string') ctx.logger?.debug?.(`dsh-task-pet overlay: ${message.message}`);
297
+ return;
298
+ case 'duplicate':
299
+ // Another Harness instance already owns the screen-wide pet for this
300
+ // DSH home. That is a conflict, not the user's choice: keep the
301
+ // preference on and keep looking, so closing the other window brings
302
+ // this pet back without a reload.
303
+ conflict = true;
304
+ notify('status', status());
305
+ scheduleRetry();
306
+ return;
307
+ default:
308
+ return;
309
+ }
310
+ }
311
+
312
+ /** Write one state line to the helper. */
313
+ function push(state) {
314
+ latestState = state;
315
+ lastStateAt = Date.now();
316
+ if (child === undefined || child.stdin === undefined) return;
317
+ try {
318
+ child.stdin.write(`${JSON.stringify({ type: 'state', ...state })}\n`);
319
+ } catch {
320
+ /* The exit handler will respawn or stop. */
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Keep the overlay honest when the page stops reporting: an app that is
326
+ * closed (or a page that crashed) must not leave a pet advertising work.
327
+ */
328
+ function startIdleWatch() {
329
+ if (idleTimer !== undefined) return;
330
+ idleTimer = setInterval(() => {
331
+ if (child === undefined) return;
332
+ // A frozen helper still holds the window on screen but answers nothing;
333
+ // restarts then go through the usual crash ladder.
334
+ if (Date.now() - Math.max(lastPongAt, spawnedAt) > PROBE_TIMEOUT_MS) {
335
+ try {
336
+ child.proc.kill('SIGKILL');
337
+ } catch {
338
+ /* already gone */
339
+ }
340
+ return;
341
+ }
342
+ // Probe on its own slower clock: the idle watch ticks every few seconds,
343
+ // and a ping per tick would be pure noise on the pipe.
344
+ if (Date.now() - lastPingAt > PING_MS) {
345
+ lastPingAt = Date.now();
346
+ try {
347
+ child.stdin?.write(`${JSON.stringify({ type: 'ping' })}\n`);
348
+ } catch {
349
+ /* the exit handler follows */
350
+ }
351
+ }
352
+ if (Date.now() - lastStateAt < IDLE_MS) return;
353
+ push({ mood: 'sleeping', badge: 0, attention: 0, running: 0, summary: '', sessions: [], idle: true });
354
+ }, 5000);
355
+ idleTimer.unref?.();
356
+ }
357
+
358
+ /**
359
+ * Re-check with a slow timer instead of spinning: a conflict clears when the
360
+ * other Harness window exits, which may be minutes later.
361
+ */
362
+ function scheduleRetry() {
363
+ if (retryTimer !== undefined) return;
364
+ retryTimer = setTimeout(() => {
365
+ retryTimer = undefined;
366
+ if (!enabled || !supported || child !== undefined) return;
367
+ void start();
368
+ }, 12000);
369
+ retryTimer.unref?.();
370
+ }
371
+
372
+ /** Start the helper when the user has not turned desktop mode off. */
373
+ async function start() {
374
+ if (!enabled || !supported || child !== undefined) return;
375
+ const mine = generation;
376
+ const binary = await ensureBinary();
377
+ // Between the await and here the user may have turned this off, another
378
+ // start may have won, or the plugin may have been unloaded.
379
+ if (binary === undefined || child !== undefined || !enabled || mine !== generation) return;
380
+ // The helper is a native GUI process; Electron's Node-mode flag belongs to
381
+ // this one and must not travel with it.
382
+ const env = { ...process.env };
383
+ delete env.ELECTRON_RUN_AS_NODE;
384
+ let handle;
385
+ try {
386
+ handle = spawn(binary, [], {
387
+ stdio: ['pipe', 'pipe', 'pipe'],
388
+ cwd: CACHE_DIR,
389
+ env: {
390
+ ...env,
391
+ // A language tag the helper can match; `LANG` is often `C.UTF-8` or
392
+ // unset, so fall back to English rather than shipping a non-tag.
393
+ DSH_TASK_PET_LOCALE: resolvedLocale(),
394
+ // The helper matches this bundle id (or the app's name) to bring the
395
+ // window forward after a jump.
396
+ DSH_DESKTOP_BUNDLE: process.env.DSH_DESKTOP_BUNDLE_ID ?? 'com.deepseek.dsh',
397
+ },
398
+ });
399
+ } catch (error) {
400
+ compileError = `overlay spawn failed: ${String(error).slice(0, 200)}`;
401
+ notify('status', status());
402
+ return;
403
+ }
404
+ conflict = false;
405
+ lastPongAt = 0;
406
+ lastPingAt = 0;
407
+ spawnedAt = Date.now();
408
+ // Remember which generation spawned this child: `stop()` bumps the counter,
409
+ // and an `exit` that arrives afterwards belongs to a helper nobody wants.
410
+ const spawnedFor = mine;
411
+ child = { proc: handle, stdin: handle.stdin, generation: spawnedFor };
412
+ handle.stdout?.setEncoding('utf8');
413
+ handle.stderr?.setEncoding('utf8');
414
+ // The helper speaks line JSON; buffer the tail across chunks.
415
+ let pending = '';
416
+ handle.stdout?.on('data', (chunk) => {
417
+ pending += chunk;
418
+ let index = pending.indexOf('\n');
419
+ while (index !== -1) {
420
+ handleLine(pending.slice(0, index));
421
+ pending = pending.slice(index + 1);
422
+ index = pending.indexOf('\n');
423
+ }
424
+ if (pending.length > LINE_LIMIT) pending = '';
425
+ });
426
+ handle.stderr?.on('data', (chunk) => {
427
+ stderr = (stderr + chunk).slice(-4096);
428
+ });
429
+ handle.on('error', (error) => {
430
+ compileError = `overlay error: ${error.message}`.slice(0, 300);
431
+ });
432
+ handle.on('exit', (code, signal) => {
433
+ const wasEnabled = enabled;
434
+ const duplicate = conflict;
435
+ // Ignore an exit from a child this supervisor no longer owns.
436
+ if (spawnedFor !== generation) {
437
+ if (child?.generation === spawnedFor) child = undefined;
438
+ notify('status', status());
439
+ return;
440
+ }
441
+ child = undefined;
442
+ if (!wasEnabled || duplicate) {
443
+ notify('status', status());
444
+ return;
445
+ }
446
+ // A helper that dies immediately is broken, not restarted forever.
447
+ if (restarts >= 3) {
448
+ // Three quick deaths mean the binary is broken on this machine, not that
449
+ // the user changed their mind: turn the preference off so a later start
450
+ // does not repeat the same crash loop.
451
+ enabled = false;
452
+ writeJson(PREFERENCE_PATH, { enabled });
453
+ compileError = `overlay exited ${String(code ?? signal)}: ${stderr.trim().slice(0, 200)}`;
454
+ notify('status', status());
455
+ return;
456
+ }
457
+ // A helper that died after a long healthy run starts from a clean slate;
458
+ // a quick death counts against the budget.
459
+ const lived = readyAt === 0 ? 0 : Date.now() - readyAt;
460
+ readyAt = 0;
461
+ if (lived > HEALTHY_MS) {
462
+ restarts = 0;
463
+ } else {
464
+ restarts += 1;
465
+ }
466
+ notify('status', status());
467
+ // Tracked so `stop()` can cancel it: an untracked restart would respawn a
468
+ // helper after the plugin was unloaded, outliving its page.
469
+ restartTimer = setTimeout(() => {
470
+ restartTimer = undefined;
471
+ void start();
472
+ }, 400 * restarts);
473
+ restartTimer.unref?.();
474
+ });
475
+ startIdleWatch();
476
+ if (latestState !== undefined) push(latestState);
477
+ notify('status', status());
478
+ }
479
+
480
+ /** Stop the helper and forget the child. */
481
+ async function stop() {
482
+ generation += 1;
483
+ if (retryTimer !== undefined) {
484
+ clearTimeout(retryTimer);
485
+ retryTimer = undefined;
486
+ }
487
+ if (restartTimer !== undefined) {
488
+ clearTimeout(restartTimer);
489
+ restartTimer = undefined;
490
+ }
491
+ const current = child;
492
+ child = undefined;
493
+ if (current !== undefined) {
494
+ try {
495
+ // `quit` lets the helper drop its pidfile through atexit; the signal
496
+ // below is the backstop for a helper that is not reading.
497
+ current.stdin?.write(`${JSON.stringify({ type: 'quit' })}\n`);
498
+ } catch {
499
+ /* already gone */
500
+ }
501
+ try {
502
+ current.stdin?.end();
503
+ } catch {
504
+ /* already gone */
505
+ }
506
+ try {
507
+ current.proc.kill('SIGTERM');
508
+ } catch {
509
+ /* already gone */
510
+ }
511
+ }
512
+ if (idleTimer !== undefined) {
513
+ clearInterval(idleTimer);
514
+ idleTimer = undefined;
515
+ }
516
+ notify('status', status());
517
+ }
518
+
519
+ /**
520
+ * Remember the user's choice and start or stop the helper accordingly.
521
+ * @param next - whether the pet should float on the whole screen.
522
+ */
523
+ async function setEnabled(next) {
524
+ enabled = next;
525
+ // An explicit choice is what makes `enabled: true` durable; nothing else
526
+ // may opt the user in.
527
+ writeJson(PREFERENCE_PATH, { enabled });
528
+ if (next) await start();
529
+ else await stop();
530
+ notify('status', status());
531
+ }
532
+
533
+ return {
534
+ status,
535
+ push,
536
+ start,
537
+ stop,
538
+ setEnabled,
539
+ /** Whether the helper can run here at all. */
540
+ get supported() {
541
+ return supported;
542
+ },
543
+ /** Whether the user wants the pet on the desktop. */
544
+ get enabled() {
545
+ return enabled;
546
+ },
547
+ /**
548
+ * Subscribe to overlay events.
549
+ * @param listener - receives `(event, data)`.
550
+ * @returns the unsubscriber.
551
+ */
552
+ subscribe(listener) {
553
+ listeners.add(listener);
554
+ return () => {
555
+ listeners.delete(listener);
556
+ };
557
+ },
558
+ };
559
+ }
package/icon.svg ADDED
@@ -0,0 +1,15 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect x="6" y="12" width="52" height="46" rx="18" fill="#7ec4a7"/>
3
+ <path d="M18 20l-2 -11 11 5z" fill="#f2a195"/>
4
+ <path d="M46 20l2 -11 -11 5z" fill="#f2a195"/>
5
+ <ellipse cx="32" cy="47" rx="14" ry="8" fill="#ffffff55"/>
6
+ <ellipse cx="24" cy="32" rx="3.4" ry="4" fill="#213b33"/>
7
+ <ellipse cx="40" cy="32" rx="3.4" ry="4" fill="#213b33"/>
8
+ <circle cx="25.1" cy="30.6" r="1.1" fill="#ffffff"/>
9
+ <circle cx="41.1" cy="30.6" r="1.1" fill="#ffffff"/>
10
+ <ellipse cx="17" cy="38" rx="3.6" ry="2.4" fill="#f2a19588"/>
11
+ <ellipse cx="47" cy="38" rx="3.6" ry="2.4" fill="#f2a19588"/>
12
+ <path d="M28 41q4 4 8 0" fill="none" stroke="#213b33" stroke-width="2.2" stroke-linecap="round"/>
13
+ <circle cx="52" cy="14" r="7" fill="#f2a195"/>
14
+ <path d="M52 10v4M52 16.6v.6" fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round"/>
15
+ </svg>