dsh-chat-embed 0.6.12 → 0.6.14

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/index.js CHANGED
@@ -8,36 +8,129 @@
8
8
  * 1. the loader row named by `cordis.patch.yml` needs a Node-side export;
9
9
  * 2. the optional shell patch needs a **Host-side** answer, because the
10
10
  * patched archive lives on the Host's disk and only the Host can read
11
- * and test it. The panel asks over the exposed channel, so a user can
12
- * see why cross-restart login is off without being told to run a
13
- * command and read its output.
11
+ * and test it. The panel asks over the exposed channel, so the dialog can
12
+ * name the exact script to run instead of guessing a path;
13
+ * 3. the same switch has to *start* that script, and only a Node process can.
14
+ * The Host spawns it and nothing else: every byte written to the shell is
15
+ * written by `tools/shell-patch/shell-patch.mjs`, never by this module.
14
16
  *
15
17
  * Keep this module inert beyond that probe. It must not import browser
16
18
  * globals, and anything it registers must be cleaned up through `ctx.effect`
17
19
  * so uninstalling the bundle leaves the Host process exactly as it was.
18
20
  */
19
21
 
20
- import { createHash } from 'node:crypto'
21
- import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
22
+ import { spawn, spawnSync } from 'node:child_process'
23
+ import { createHash, randomUUID } from 'node:crypto'
24
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
22
25
  import { homedir } from 'node:os'
23
- import { dirname, join } from 'node:path'
26
+ import { basename, dirname, join } from 'node:path'
24
27
  import { createRequire } from 'node:module'
25
28
  import { fileURLToPath } from 'node:url'
26
29
 
27
30
  export const name = 'dsh-chat-embed'
28
31
 
29
32
  /**
30
- * Wait for the two Host services before apply runs.
33
+ * Wait for the web server before apply runs.
31
34
  *
32
- * Without this the loader calls apply while the tree is still assembling, both
33
- * looksups below read undefined, and the probe route and the agent tool are
34
- * silently skipped — which is exactly what happened until 0.6.10.
35
+ * Without this the loader calls apply while the tree is still assembling, the
36
+ * lookup below reads undefined, and the probe route is silently skipped — which
37
+ * is exactly what happened until 0.6.10.
35
38
  */
36
- export const inject = ['webServer', 'tools']
39
+ export const inject = ['webServer']
37
40
 
38
41
  /** Route the panel fetches for the read-only shell probe. */
39
42
  const PROBE_PATH = '/dsh-chat-embed/patch-check'
40
43
 
44
+ /** Route the panel fetches for the size of this plugin's own chat partitions. */
45
+ const CACHE_PATH = '/dsh-chat-embed/cache'
46
+
47
+ /**
48
+ * Route the panel asks to clear that cache.
49
+ *
50
+ * Same constraint as the patch switch: the carrier is GET-only, so the token
51
+ * from the size route is what keeps a stray GET from deleting anything.
52
+ */
53
+ const CACHE_CLEAR_PATH = '/dsh-chat-embed/cache-clear'
54
+
55
+ /**
56
+ * Route the panel asks to actually run the patch script.
57
+ *
58
+ * A GET, not a POST: the carrier behind these routes answers GET and HEAD only
59
+ * and replies 405 to every other method before the handler runs
60
+ * (`@deepseek-ai/dsh-host-webserver`, `serveResource`). What protects the state
61
+ * change is a token instead — minted once per Host process, handed out only
62
+ * inside the probe body, unguessable, and unreadable from another origin
63
+ * because this server sends no CORS headers.
64
+ */
65
+ const PATCH_PATH = '/dsh-chat-embed/patch'
66
+
67
+ /** Query parameters of the action route. */
68
+ const ACTION_PARAM = 'action'
69
+ const TOKEN_PARAM = 'token'
70
+
71
+ /** The one token this Host process accepts. */
72
+ const PATCH_TOKEN = randomUUID().replace(/-/g, '')
73
+
74
+ /**
75
+ * The Task Scheduler entry that carries the swap across DSH's exit.
76
+ *
77
+ * The name lets a second click replace the task definition. It does not stop
78
+ * the patcher already waiting: that process was started detached, and the
79
+ * wrapper that the task runs has already exited. The script's lock is what
80
+ * refuses the second writer.
81
+ */
82
+ const PATCH_TASK = 'dsh-chat-embed-patch'
83
+
84
+ /**
85
+ * How long the switch's patcher waits for the user to quit, in minutes.
86
+ *
87
+ * The click happens inside DSH, and the user keeps working there. The script's
88
+ * own default (10 minutes) is shorter than one conversation: it then deletes
89
+ * the staged archive and the task, and the later quit finds nothing waiting.
90
+ * Twelve hours covers a work day. The waiter only polls a pid; it does not
91
+ * hold app.asar open.
92
+ *
93
+ * The panel copy says "12 hours". Change both together.
94
+ */
95
+ const PATCH_WAIT_MINUTES = 720
96
+
97
+ /**
98
+ * The panel's own workspace identities.
99
+ *
100
+ * The shell names a persistent partition `dsh-sidebar-` plus the first 24 hex
101
+ * characters of sha256(workspace). These seven strings are the only identities
102
+ * this plugin asks for (`client.js` `PROVIDERS`). A size or a delete that
103
+ * walked every directory under `Partitions` would take the shell's own sidebar
104
+ * browser with it — one such directory is already on disk and is not ours.
105
+ */
106
+ const CHAT_WORKSPACES = Object.freeze([
107
+ 'dsh-chat-embed:chat:v1',
108
+ 'dsh-chat-embed:doubao:v1',
109
+ 'dsh-chat-embed:chatgpt:v1',
110
+ 'dsh-chat-embed:minimax:v1',
111
+ 'dsh-chat-embed:kimi:v1',
112
+ 'dsh-chat-embed:gemini:v1',
113
+ 'dsh-chat-embed:grok:v1',
114
+ ])
115
+
116
+ /**
117
+ * Chromium directories that are cache, not a login.
118
+ *
119
+ * Cookies live in `Network`, the session in `IndexedDB` and `Local Storage`.
120
+ * None of those names are here. `File System` and `Session Storage` are site
121
+ * data too, so they stay when the patch is on and go only with a full purge.
122
+ */
123
+ const CACHE_DIR_NAMES = Object.freeze([
124
+ 'Cache',
125
+ 'Code Cache',
126
+ 'GPUCache',
127
+ 'DawnGraphiteCache',
128
+ 'DawnWebGPUCache',
129
+ 'GrShaderCache',
130
+ 'ShaderCache',
131
+ 'Shared Dictionary',
132
+ ])
133
+
41
134
  /** Strings that identify the patch in a rebuilt archive. */
42
135
  const PATCH_MARK = 'persist:dsh-sidebar-'
43
136
  const CACHE_MARK = '{ cache: false }'
@@ -83,14 +176,50 @@ function resourcesCandidates() {
83
176
  /** @returns {string | undefined} the directory that actually holds app.asar */
84
177
  function detectResources() {
85
178
  for (const candidate of resourcesCandidates()) {
86
- if (existsSync(join(candidate, 'app.asar'))) return candidate
179
+ if (existsReal(join(candidate, 'app.asar'))) return candidate
87
180
  }
88
181
  return undefined
89
182
  }
90
183
 
184
+ /**
185
+ * Electron's unpatched file system, when this process is running on it.
186
+ *
187
+ * `node:fs` inside Electron treats any `*.asar` path as an archive: the archive
188
+ * file itself reads as ENOENT, `statSync` reports 0 and `existsSync` says false.
189
+ * Every question this half asks about the shell archive has to go through the
190
+ * unpatched binding, or the probe answers "there is no install here" on a
191
+ * machine that has one. A plain Node has no `original-fs` and needs none.
192
+ */
193
+ const ORIGINAL_FS = (() => {
194
+ try {
195
+ const original = createRequire(import.meta.url)('original-fs')
196
+ if (original !== undefined && original !== null && typeof original.readFileSync === 'function') return original
197
+ } catch (error) {
198
+ void error
199
+ }
200
+ return undefined
201
+ })()
202
+
203
+ /** @param {string} file @returns {boolean} */
204
+ function existsReal(file) {
205
+ try {
206
+ if (ORIGINAL_FS !== undefined && typeof ORIGINAL_FS.existsSync === 'function') {
207
+ return ORIGINAL_FS.existsSync(file) === true
208
+ }
209
+ return existsSync(file)
210
+ } catch (error) {
211
+ void error
212
+ return false
213
+ }
214
+ }
215
+
91
216
  /** @param {string} file @returns {boolean} */
92
217
  function isWritable(file) {
93
218
  try {
219
+ if (ORIGINAL_FS !== undefined && typeof ORIGINAL_FS.accessSync === 'function') {
220
+ ORIGINAL_FS.accessSync(file, constants.W_OK)
221
+ return true
222
+ }
94
223
  accessSync(file, constants.W_OK)
95
224
  return true
96
225
  } catch (error) {
@@ -111,27 +240,14 @@ function isWritable(file) {
111
240
  * @returns {Buffer}
112
241
  */
113
242
  function readRealFile(file) {
114
- const fallback = () => readFileSync(file)
115
- try {
116
- const original = createRequire(import.meta.url)('original-fs')
117
- if (original !== undefined && original !== null && typeof original.readFileSync === 'function') {
118
- return original.readFileSync(file)
119
- }
120
- } catch (error) {
121
- void error
122
- }
123
- return fallback()
243
+ if (ORIGINAL_FS !== undefined) return ORIGINAL_FS.readFileSync(file)
244
+ return readFileSync(file)
124
245
  }
125
246
 
126
247
  /** @param {string} file @returns {number} the real byte length */
127
248
  function statRealSize(file) {
128
- try {
129
- const original = createRequire(import.meta.url)('original-fs')
130
- if (original !== undefined && original !== null && typeof original.statSync === 'function') {
131
- return original.statSync(file).size
132
- }
133
- } catch (error) {
134
- void error
249
+ if (ORIGINAL_FS !== undefined && typeof ORIGINAL_FS.statSync === 'function') {
250
+ return ORIGINAL_FS.statSync(file).size
135
251
  }
136
252
  return statSync(file).size
137
253
  }
@@ -164,28 +280,52 @@ function readAsarEntry(file, entry) {
164
280
  }
165
281
 
166
282
  /**
167
- * Locate a Node binary that can run the patch tool.
283
+ * The command line for one direction of the patch.
168
284
  *
169
- * DSH runs every profile on its own packaged runtime, so the archive can be
170
- * patched without the user installing Node. The order is: the runtime this
171
- * Host is already running on, the managed runtime directory, then a system
172
- * `node` on PATH.
285
+ * The launcher is what a user double-clicks: it opens a window that stays open
286
+ * and finds Node by itself. Windows and macOS ship one; every other platform
287
+ * gets the equivalent `node <script>` line, because the script itself is
288
+ * platform-neutral and there is no desktop build to point at.
173
289
  *
174
- * @returns {string | undefined} an absolute path, or undefined when none exists
290
+ * @param {'apply' | 'revert'} action
291
+ * @param {{ launcher?: string, script?: string }} files
292
+ * @param {string} [nodeBinary] path to a Node binary, for the fallback
293
+ * @returns {string | undefined}
175
294
  */
176
- function findNodeBinary() {
295
+ function launcherCommand(action, files, nodeBinary) {
296
+ const quote = (value) => (value.includes(' ') ? '"' + value + '"' : value)
297
+ if (typeof files.launcher === 'string' && files.launcher !== '') return quote(files.launcher) + ' ' + action
298
+ if (typeof files.script !== 'string' || files.script === '') return undefined
299
+ const node =
300
+ typeof nodeBinary === 'string' && nodeBinary !== '' ? quote(nodeBinary) : 'node'
301
+ return node + ' ' + quote(files.script) + ' ' + action
302
+ }
303
+
304
+ /**
305
+ * Locate a Node binary for the non-desktop fallback. The desktop app ships its
306
+ * own runtime under `dsh-runtimes`; a plain install just uses PATH.
307
+ *
308
+ * @param {string} [dshHome] the DSH home, defaulting to `$DSH_HOME` or `~/.dsh`
309
+ * @returns {string | undefined}
310
+ */
311
+ function nodeCandidates(dshHome) {
177
312
  const candidates = []
178
- // A Node-hosted dsh reports its own executable.
179
- if (typeof process.execPath === 'string' && process.execPath !== '' && /node(.exe)?$/i.test(process.execPath)) {
180
- candidates.push(process.execPath)
181
- }
182
- // The managed runtime the desktop app installs beside its own data.
183
- const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh')
313
+ if (typeof process.execPath === 'string' && /node(\.exe)?$/i.test(process.execPath)) candidates.push(process.execPath)
314
+ const home =
315
+ dshHome !== undefined && dshHome !== ''
316
+ ? dshHome
317
+ : process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== ''
318
+ ? process.env.DSH_HOME
319
+ : join(homedir(), '.dsh')
184
320
  const runtimes = join(home, 'dsh-runtimes')
185
321
  try {
186
322
  for (const entry of readdirSync(runtimes)) {
187
- const base = join(runtimes, entry, 'dependencies', 'node', 'bin')
188
- candidates.push(join(base, process.platform === 'win32' ? 'node.exe' : 'node'))
323
+ // Both suffixes: the runtime is `node.exe` on Windows and `node`
324
+ // elsewhere. Asking only for the bare name found nothing on Windows, so
325
+ // the task silently fell back to a system-wide Node — or, on a machine
326
+ // without one, to the shell binary through cmd.
327
+ candidates.push(join(runtimes, entry, 'dependencies', 'node', 'bin', 'node.exe'))
328
+ candidates.push(join(runtimes, entry, 'dependencies', 'node', 'bin', 'node'))
189
329
  }
190
330
  } catch (error) {
191
331
  void error
@@ -193,40 +333,42 @@ function findNodeBinary() {
193
333
  if (process.platform === 'win32' && process.env.ProgramFiles !== undefined) {
194
334
  candidates.push(join(process.env.ProgramFiles, 'nodejs', 'node.exe'))
195
335
  } else {
196
- candidates.push('/usr/local/bin/node')
197
- candidates.push('/usr/bin/node')
198
- }
199
- for (const candidate of candidates) {
200
- if (typeof candidate === 'string' && candidate !== '' && existsSync(candidate)) return candidate
336
+ candidates.push('/usr/local/bin/node', '/usr/bin/node')
201
337
  }
202
- return undefined
338
+ return candidates
203
339
  }
204
340
 
205
341
  /**
206
- * @param {string} node absolute path to a Node binary
207
- * @param {string} script absolute path to patch-asar.cjs
208
- * @param {string} [resources] install directory, so a non-standard location works
209
- * @returns {string} a copy-pasteable command line
342
+ * Locate a Node binary for the non-desktop fallback. The desktop app ships its
343
+ * own runtime under `dsh-runtimes`; a plain install just uses PATH.
344
+ *
345
+ * @param {string} [dshHome] the DSH home, defaulting to `$DSH_HOME` or `~/.dsh`
346
+ * @returns {string | undefined}
210
347
  */
211
- function patchCommand(node, script, resources) {
212
- const quote = (value) => (value.includes(' ') ? '"' + value + '"' : value)
213
- const parts = [quote(node), quote(script), 'build']
214
- // The tool only searches the usual install locations. When the Host found the
215
- // shell somewhere else (a portable or custom install), it must say where.
216
- if (typeof resources === 'string' && resources !== '') parts.push('--resources', quote(resources))
217
- return parts.join(' ')
348
+ function findNodeBinary(dshHome) {
349
+ return nodeCandidates(dshHome).find((candidate) => typeof candidate === 'string' && candidate !== '' && existsSync(candidate))
218
350
  }
219
351
 
220
352
  /**
221
- * Locate the patch tool inside this package, so the reported command points at
222
- * a file that actually exists on the user's disk.
353
+ * Locate the patch entry point inside this package, so what the panel offers
354
+ * points at files that actually exist on the user's disk.
223
355
  *
224
- * @returns {string | undefined}
356
+ * @returns {{ script?: string, launcher?: string }}
225
357
  */
226
- function findPatchScript() {
358
+ function findPatchFiles() {
227
359
  const here = dirname(fileURLToPath(import.meta.url))
228
- const candidate = join(here, 'tools', 'shell-patch', 'patch-asar.cjs')
229
- return existsSync(candidate) ? candidate : undefined
360
+ const dir = join(here, 'tools', 'shell-patch')
361
+ const script = join(dir, 'shell-patch.mjs')
362
+ const launcher =
363
+ process.platform === 'win32'
364
+ ? join(dir, 'shell-patch.cmd')
365
+ : process.platform === 'darwin'
366
+ ? join(dir, 'shell-patch.command')
367
+ : undefined
368
+ return {
369
+ script: existsSync(script) ? script : undefined,
370
+ launcher: launcher !== undefined && existsSync(launcher) ? launcher : undefined,
371
+ }
230
372
  }
231
373
 
232
374
  /**
@@ -248,7 +390,7 @@ function inspectShell(resources) {
248
390
  }
249
391
  }
250
392
  const asar = join(resolved, 'app.asar')
251
- if (!existsSync(asar)) {
393
+ if (!existsReal(asar)) {
252
394
  return {
253
395
  found: false,
254
396
  platform: process.platform,
@@ -267,8 +409,14 @@ function inspectShell(resources) {
267
409
  resources: resolved,
268
410
  asar,
269
411
  exists: true,
270
- writable: existsSync(asar) ? isWritable(asar) : isWritable(resolved),
412
+ // The swap renames the archive inside its own directory and stages a new
413
+ // one beside it, so the directory is what has to be writable.
414
+ writable: isWritable(resolved),
271
415
  backup: existsSync(backup),
416
+ // A backup that is itself patched cannot restore anything, and reporting it
417
+ // as "present" is exactly what made a rollback look available when it was
418
+ // not. Say which kind it is.
419
+ backupClean: undefined,
272
420
  staged: existsSync(staged),
273
421
  patched: undefined,
274
422
  patchSite: undefined,
@@ -289,6 +437,15 @@ function inspectShell(resources) {
289
437
  }
290
438
  report.patched = main.includes(PATCH_MARK)
291
439
  report.cachePatch = main.includes(CACHE_MARK)
440
+ if (report.backup === true) {
441
+ try {
442
+ const copy = readAsarEntry(backup, 'lib/main.js')
443
+ report.backupClean = copy !== undefined && !copy.includes(PATCH_MARK)
444
+ } catch (error) {
445
+ void error
446
+ report.backupClean = false
447
+ }
448
+ }
292
449
  report.patchSite = main.includes(PATCH_SITE_MARK) || main.includes(PATCH_MARK)
293
450
  if (report.patched !== true && report.patchSite === false) {
294
451
  report.detail = '补丁点不存在:当前桌面壳版本的分区写法与补丁预期不一致,需要更新补丁'
@@ -298,49 +455,527 @@ function inspectShell(resources) {
298
455
  } catch (error) {
299
456
  report.detail = '解析 app.asar 失败:' + firstLine(error)
300
457
  }
301
- // The user needs a Node binary to run the patch tool. The desktop app ships
302
- // its own runtime, so nobody has to install one — report the exact command
303
- // instead of telling them to install Node first.
304
- report.patchScript = findPatchScript()
305
- report.nodeBinary = findNodeBinary()
306
- report.patchCommand =
307
- report.nodeBinary === undefined ? undefined : patchCommand(report.nodeBinary, report.patchScript, resolved)
458
+ // The patch is one script with one command for each direction. The launcher
459
+ // is what the user double-clicks; it finds Node on its own, so the panel never
460
+ // has to talk about runtimes.
461
+ const files = findPatchFiles()
462
+ const node = findNodeBinary()
463
+ report.script = files.script
464
+ report.launcher = files.launcher
465
+ report.nodeBinary = node
466
+ report.applyCommand = launcherCommand('apply', files, node)
467
+ report.revertCommand = launcherCommand('revert', files, node)
308
468
  return report
309
469
  }
310
470
 
471
+ /**
472
+ * Directory name the shell uses for one persistent workspace.
473
+ *
474
+ * @param {string} workspace
475
+ * @returns {string}
476
+ */
477
+ function partitionDirName(workspace) {
478
+ return 'dsh-sidebar-' + createHash('sha256').update(workspace).digest('hex').slice(0, 24)
479
+ }
480
+
481
+ /** @returns {string | undefined} the Partitions directory, if one can be named */
482
+ function partitionsDir() {
483
+ if (typeof process.env.DSH_PARTITIONS === 'string' && process.env.DSH_PARTITIONS !== '') {
484
+ return process.env.DSH_PARTITIONS
485
+ }
486
+ const appData =
487
+ process.platform === 'win32'
488
+ ? process.env.APPDATA
489
+ : process.platform === 'darwin'
490
+ ? join(homedir(), 'Library', 'Application Support')
491
+ : process.env.XDG_CONFIG_HOME !== undefined && process.env.XDG_CONFIG_HOME !== ''
492
+ ? process.env.XDG_CONFIG_HOME
493
+ : join(homedir(), '.config')
494
+ if (appData === undefined || appData === '') return undefined
495
+ const primary = join(appData, '@deepseek-ai', 'dsh-desktop', 'Partitions')
496
+ if (existsSync(primary)) return primary
497
+ const alternate = join(appData, 'DeepSeek Harness', 'Partitions')
498
+ if (existsSync(alternate)) return alternate
499
+ return primary
500
+ }
501
+
502
+ /** @param {string} dir @returns {number} */
503
+ function directoryBytes(dir) {
504
+ let total = 0
505
+ const walk = (path) => {
506
+ let entries
507
+ try {
508
+ entries = readdirSync(path, { withFileTypes: true })
509
+ } catch (error) {
510
+ void error
511
+ return
512
+ }
513
+ for (const entry of entries) {
514
+ const next = join(path, entry.name)
515
+ if (entry.isDirectory()) walk(next)
516
+ else {
517
+ try {
518
+ total += statSync(next).size
519
+ } catch (error) {
520
+ void error
521
+ }
522
+ }
523
+ }
524
+ }
525
+ walk(dir)
526
+ return total
527
+ }
528
+
529
+ /**
530
+ * Bytes the clear button would remove, and which kind of clear that is.
531
+ *
532
+ * `keep` (patch on) sums only {@link CACHE_DIR_NAMES} inside the seven known
533
+ * partitions. `purge` (patch off) sums those partitions whole, because they
534
+ * are leftovers the running in-memory session no longer opens. An unknown
535
+ * sibling is never counted.
536
+ *
537
+ * @param {boolean} patched
538
+ * @param {string} [base] partition root; tests pass their own
539
+ * @returns {{ bytes: number, mode: 'keep' | 'purge', dir: string | undefined }}
540
+ */
541
+ function measureChatCache(patched, base) {
542
+ const root = base !== undefined ? base : partitionsDir()
543
+ const mode = patched ? 'keep' : 'purge'
544
+ let bytes = 0
545
+ if (root !== undefined && existsSync(root)) {
546
+ for (const workspace of CHAT_WORKSPACES) {
547
+ const dir = join(root, partitionDirName(workspace))
548
+ if (!existsSync(dir)) continue
549
+ if (mode === 'keep') {
550
+ for (const name of CACHE_DIR_NAMES) bytes += directoryBytes(join(dir, name))
551
+ } else bytes += directoryBytes(dir)
552
+ }
553
+ }
554
+ return { bytes, mode, dir: root }
555
+ }
556
+
557
+ /**
558
+ * Whether the installed shell currently has the persist patch.
559
+ *
560
+ * Reads one archive entry, not a content hash of the whole file: the panel
561
+ * asks for this when the settings menu opens.
562
+ *
563
+ * @param {string} [resources]
564
+ * @returns {boolean | undefined}
565
+ */
566
+ function readPatchState(resources) {
567
+ const resolved = typeof resources === 'string' && resources !== '' ? resources : detectResources()
568
+ if (resolved === undefined) return undefined
569
+ const asar = join(resolved, 'app.asar')
570
+ if (!existsReal(asar)) return undefined
571
+ try {
572
+ const main = readAsarEntry(asar, 'lib/main.js')
573
+ if (main === undefined) return undefined
574
+ return main.includes(PATCH_MARK)
575
+ } catch (error) {
576
+ void error
577
+ return undefined
578
+ }
579
+ }
580
+
581
+ /**
582
+ * Facts the cache row renders. Read-only.
583
+ *
584
+ * @param {string} [resources]
585
+ * @param {(patched: boolean, base?: string) => { bytes: number, mode: string, dir: string | undefined }} [measure]
586
+ * @returns {object}
587
+ */
588
+ function cacheReport(resources, measure = measureChatCache) {
589
+ const resolved = typeof resources === 'string' && resources !== '' ? resources : detectResources()
590
+ const files = findPatchFiles()
591
+ const patched = resolved === undefined ? undefined : readPatchState(resolved)
592
+ if (patched !== true && patched !== false) {
593
+ return {
594
+ ok: false,
595
+ patched,
596
+ mode: 'unknown',
597
+ bytes: 0,
598
+ resources: resolved,
599
+ script: files.script,
600
+ detail: '无法判断补丁状态,没有测量缓存',
601
+ }
602
+ }
603
+ const measured = measure(patched)
604
+ return {
605
+ ok: true,
606
+ patched,
607
+ mode: measured.mode,
608
+ bytes: measured.bytes,
609
+ resources: resolved,
610
+ script: files.script,
611
+ detail: '',
612
+ }
613
+ }
614
+
615
+ /**
616
+ * Ask the script to clear this plugin's partitions. This module does not delete.
617
+ *
618
+ * The script re-reads the archive and chooses keep-or-purge itself, so a stale
619
+ * panel cannot turn a cache clear into a login wipe.
620
+ *
621
+ * @param {object} report
622
+ * @param {typeof spawnSync} [run]
623
+ * @param {(patched: boolean) => { bytes: number, mode: string }} [measure]
624
+ * @returns {object}
625
+ */
626
+ function clearChatCache(report, run = spawnSync, measure = measureChatCache) {
627
+ if (report === undefined || report === null || (report.patched !== true && report.patched !== false)) {
628
+ return { ok: false, state: 'failed', detail: '无法判断补丁状态,没有删除任何文件', bytes: 0, mode: 'unknown', freed: 0 }
629
+ }
630
+ if (typeof report.script !== 'string' || report.script === '') {
631
+ return { ok: false, state: 'failed', detail: '找不到补丁脚本(tools/shell-patch)', bytes: 0, mode: 'unknown', freed: 0 }
632
+ }
633
+ if (typeof report.resources !== 'string' || report.resources === '') {
634
+ return { ok: false, state: 'noapp', detail: '没有找到 DSH 安装目录', bytes: 0, mode: 'unknown', freed: 0 }
635
+ }
636
+ const before = measure(report.patched === true)
637
+ const node = findNodeBinary()
638
+ const exec = node ?? process.execPath
639
+ const env = { ...process.env }
640
+ if (node === undefined) env.ELECTRON_RUN_AS_NODE = '1'
641
+ let result
642
+ try {
643
+ result = run(exec, [report.script, 'cache', '--resources', report.resources], {
644
+ encoding: 'utf8',
645
+ timeout: 60000,
646
+ windowsHide: true,
647
+ env,
648
+ })
649
+ } catch (error) {
650
+ return {
651
+ ok: false,
652
+ state: 'failed',
653
+ detail: firstLine(error),
654
+ bytes: before.bytes,
655
+ mode: before.mode,
656
+ freed: 0,
657
+ }
658
+ }
659
+ const after = measure(report.patched === true)
660
+ const output = result !== undefined && result !== null && typeof result.stdout === 'string' ? result.stdout : ''
661
+ const err = result !== undefined && result !== null && typeof result.stderr === 'string' ? result.stderr : ''
662
+ const ok = result !== undefined && result !== null && result.status === 0
663
+ return {
664
+ ok,
665
+ state: ok ? 'cleared' : 'failed',
666
+ mode: before.mode,
667
+ bytes: after.bytes,
668
+ freed: Math.max(0, before.bytes - after.bytes),
669
+ detail: ok ? '' : firstLine((err + '\n' + output).trim() || '清理没有完成'),
670
+ }
671
+ }
672
+
311
673
  /** @param {unknown} error @returns {string} */
312
674
  function firstLine(error) {
313
675
  const text = error instanceof Error ? error.message : String(error)
314
676
  return text.split('\n')[0].slice(0, 200)
315
677
  }
316
678
 
679
+ /** @param {unknown} body @param {number} [status] @returns {Response} */
680
+ function jsonResponse(body, status = 200) {
681
+ return new Response(JSON.stringify(body), {
682
+ status,
683
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
684
+ })
685
+ }
686
+
687
+ /**
688
+ * What the switch asked for, and whether it can happen without the user falling
689
+ * back to the copyable command.
690
+ *
691
+ * Pure: it reads the probe report and decides. Nothing here writes anything —
692
+ * the script is the only thing in this package that ever does.
693
+ *
694
+ * @param {string} action 'apply' or 'revert'
695
+ * @param {object} report the probe's answer
696
+ * @returns {{ state: string, detail: string, command: string }}
697
+ */
698
+ function planPatchAction(action, report) {
699
+ const wantsOn = action === 'apply'
700
+ if (report === undefined || report === null || report.found !== true) {
701
+ return { state: 'noapp', detail: '没有找到 DSH 安装目录;Web 端没有桌面壳可以打补丁', command: '' }
702
+ }
703
+ const command = (wantsOn ? report.applyCommand : report.revertCommand) ?? ''
704
+ if (report.patched !== true && report.patched !== false) {
705
+ return { state: 'failed', detail: report.detail === '' ? '无法判断 app.asar 的当前状态' : report.detail, command }
706
+ }
707
+ if (report.patched === wantsOn) {
708
+ return { state: 'same', detail: wantsOn ? 'app.asar 已经是补丁版' : 'app.asar 已经是原版', command }
709
+ }
710
+ if (report.patchSite === false) {
711
+ return { state: 'unsupported', detail: '当前桌面壳的分区写法与补丁不一致,脚本也需要更新', command }
712
+ }
713
+ if (report.writable !== true) {
714
+ return { state: 'denied', detail: '安装目录不可写,需要管理员权限', command }
715
+ }
716
+ if (typeof report.script !== 'string' || report.script === '') {
717
+ return { state: 'failed', detail: '找不到补丁脚本(tools/shell-patch)', command }
718
+ }
719
+ return { state: 'started', detail: '', command }
720
+ }
721
+
722
+ /**
723
+ * The program to run the script with, and to start DSH again with afterwards.
724
+ *
725
+ * In the desktop app the Host is a child of the shell launched from the shell's
726
+ * own Electron binary in Node mode, so `process.execPath` is
727
+ * `DeepSeek Harness.exe`: the exact runtime the script wants, and the exact
728
+ * program to relaunch. A plain Node Host is nothing to relaunch, so it yields
729
+ * undefined and the script only asks the user to reopen DSH.
730
+ *
731
+ * @returns {string | undefined}
732
+ */
733
+ function selfExecutable() {
734
+ const exec = process.execPath
735
+ if (typeof exec !== 'string' || exec === '') return undefined
736
+ return /^node(\.exe)?$/i.test(basename(exec)) ? undefined : exec
737
+ }
738
+
739
+ /**
740
+ * @param {string} action 'apply' or 'revert'
741
+ * @param {object} report the probe's answer
742
+ * @returns {string[]} the script's arguments
743
+ */
744
+ function launchArgs(action, report) {
745
+ const args = [report.script, action, '--restart', '--resources', String(report.resources)]
746
+ // The shell itself: the swap needs it closed, and the script starts it again.
747
+ const pid = Number(process.ppid)
748
+ if (Number.isInteger(pid) && pid > 0) args.push('--pid', String(pid))
749
+ const exe = selfExecutable()
750
+ if (exe !== undefined) args.push('--exe', exe)
751
+ // Passed explicitly: omitting it selects the script's 10-minute default,
752
+ // which gives up while the user is still in this conversation.
753
+ args.push('--wait-minutes', String(PATCH_WAIT_MINUTES))
754
+ return args
755
+ }
756
+
757
+ /**
758
+ * Quote one argument for a Windows command line.
759
+ *
760
+ * @param {string} value
761
+ * @returns {string}
762
+ */
763
+ function winQuote(value) {
764
+ return /[\s"]/.test(value) ? '"' + value.replace(/"/g, '\\"') + '"' : value
765
+ }
766
+
317
767
  /**
318
- * Serve the read-only probe over the Web GUI's HTTP carrier, so the panel can
319
- * read it with a plain relative `fetch` — no Remote RPC endpoint, no shell
768
+ * Build the PowerShell that registers and starts the patch task.
769
+ *
770
+ * A plain child process cannot do this job on Windows. The desktop shell puts
771
+ * itself and everything it spawns into a job object carrying
772
+ * `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, and without breakaway, so `detached`
773
+ * buys nothing: the patcher is destroyed at the very moment it is waiting for,
774
+ * leaving `app.asar.new` staged and `app.asar` untouched. Measured twice — once
775
+ * through `spawn`, once through WMI, which came back with a console-close
776
+ * interrupt in its log.
777
+ *
778
+ * A task started by Task Scheduler is created by `svchost` instead: outside the
779
+ * job, but still in the interactive session, so the window the script reopens
780
+ * lands on the user's desktop rather than nowhere.
781
+ *
782
+ * @param {string} taskName
783
+ * @param {string} execute the program the task runs
784
+ * @param {string} argument its command line
785
+ * @returns {string} one PowerShell script
786
+ */
787
+ function patchTaskCommand(taskName, execute, argument) {
788
+ const quote = (value) => "'" + String(value).replace(/'/g, "''") + "'"
789
+ return [
790
+ "$ErrorActionPreference = 'Stop'",
791
+ `$action = New-ScheduledTaskAction -Execute ${quote(execute)} -Argument ${quote(argument)}`,
792
+ // The trigger is a formality: Task Scheduler will not register a task
793
+ // without one, but this task is started explicitly and must never fire on
794
+ // its own. A near-future trigger would — a patcher that failed fast and did
795
+ // not get to delete its task would be re-run a minute later, and two
796
+ // patchers racing over one archive is how an install gets corrupted.
797
+ '$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddDays(30)',
798
+ // Belt and braces for the same reason: never run a second copy while one is
799
+ // still waiting for DSH to close.
800
+ // The registered action is a wrapper that exits in a second; the patcher is
801
+ // a Start-Process child and is not covered by this limit (measured: the
802
+ // task was Ready while that child was still running). If a build fails to
803
+ // break the child away, the limit becomes the wait's ceiling, so it has to
804
+ // outlast PATCH_WAIT_MINUTES.
805
+ '$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes ' +
806
+ String(PATCH_WAIT_MINUTES + 60) +
807
+ ')',
808
+ `Register-ScheduledTask -TaskName ${quote(taskName)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`,
809
+ `Start-ScheduledTask -TaskName ${quote(taskName)}`,
810
+ ].join('; ')
811
+ }
812
+
813
+ /**
814
+ * Wrap a command so the process the task runs gets a console of its own.
815
+ *
816
+ * A task started from the panel inherits the console DSH is running under, and
817
+ * that console dies with DSH. Windows then delivers CTRL_CLOSE to everything
818
+ * attached to it, so the patcher is killed at the exact moment it is waiting
819
+ * for — measured as Last Result 0xC000013A (STATUS_CONTROL_C_EXIT), with the
820
+ * staged archive left behind and app.asar untouched.
821
+ *
822
+ * `Start-Process` (without `-NoNewWindow`) gives the child a fresh console, and
823
+ * the PowerShell wrapper itself exits within a second, so nothing that matters
824
+ * is attached to DSH's console any more. `-EncodedCommand` keeps the nested
825
+ * quoting out of this: the payload is base64 of UTF-16LE, so no layer has to
826
+ * re-escape the arguments.
827
+ *
828
+ * @param {string} execute
829
+ * @param {string} argument
830
+ * @returns {{ execute: string, argument: string }}
831
+ */
832
+ function detachedPayload(execute, argument) {
833
+ const quote = (value) => "'" + String(value).replace(/'/g, "''") + "'"
834
+ const script =
835
+ `Start-Process -FilePath ${quote(execute)} -ArgumentList ${quote(argument)} -WindowStyle Hidden | Out-Null`
836
+ const encoded = Buffer.from(script, 'utf16le').toString('base64')
837
+ return {
838
+ execute: 'powershell.exe',
839
+ argument: '-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ' + encoded,
840
+ }
841
+ }
842
+
843
+ /**
844
+ * The command the task runs, and the runtime that runs it.
845
+ *
846
+ * The DSH runtime ships a real Node, which is preferable to the shell binary in
847
+ * Node mode: no `ELECTRON_RUN_AS_NODE` to smuggle through a task definition, and
848
+ * its `fs` reads `app.asar` literally, which is all the script needs.
849
+ *
850
+ * Either way the payload is wrapped, because the console it would otherwise
851
+ * inherit is the one that closes when DSH quits.
852
+ *
853
+ * @param {string} action
854
+ * @param {object} report
855
+ * @returns {{ execute: string, argument: string } | undefined}
856
+ */
857
+ function patchTaskTarget(action, report) {
858
+ const args = [...launchArgs(action, report), '--task', PATCH_TASK]
859
+ const node = findNodeBinary()
860
+ if (node !== undefined) return detachedPayload(node, args.map(winQuote).join(' '))
861
+ // No Node anywhere: the shell binary in Node mode, which needs the variable
862
+ // set for it — cmd is the only place to put it in a task definition.
863
+ const exe = selfExecutable()
864
+ if (exe === undefined) return undefined
865
+ return detachedPayload('cmd.exe', '/c set "ELECTRON_RUN_AS_NODE=1" && ' + [exe, ...args].map(winQuote).join(' '))
866
+ }
867
+
868
+ /**
869
+ * Hand the patch to Task Scheduler.
870
+ *
871
+ * @param {string} action
872
+ * @param {object} report
873
+ * @param {typeof spawnSync} run
874
+ * @returns {{ kill: () => void } | undefined} undefined when the task would not register
875
+ */
876
+ function startPatchTask(action, report, run) {
877
+ const target = patchTaskTarget(action, report)
878
+ if (target === undefined) return undefined
879
+ const command = patchTaskCommand(PATCH_TASK, target.execute, target.argument)
880
+ const result = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], {
881
+ stdio: 'ignore',
882
+ windowsHide: true,
883
+ timeout: 30000,
884
+ })
885
+ if (result.status !== 0) return undefined
886
+ return {
887
+ kill() {
888
+ run('schtasks.exe', ['/end', '/tn', PATCH_TASK], { stdio: 'ignore', windowsHide: true, timeout: 15000 })
889
+ run('schtasks.exe', ['/delete', '/tn', PATCH_TASK, '/f'], {
890
+ stdio: 'ignore',
891
+ windowsHide: true,
892
+ timeout: 15000,
893
+ })
894
+ },
895
+ }
896
+ }
897
+
898
+ /**
899
+ * Start the patch script so that it outlives this process.
900
+ *
901
+ * It has to: the swap waits for DSH to exit, and that exit takes this Host with
902
+ * it. On Windows that means Task Scheduler (see {@link patchTaskCommand}); on
903
+ * the other platforms a `detached` child is enough, because nothing there kills
904
+ * a process for the crime of sharing a parent.
905
+ *
906
+ * @param {string} action 'apply' or 'revert'
907
+ * @param {object} report the probe's answer
908
+ * @param {typeof spawn} spawnProcess
909
+ * @param {typeof spawnSync} [run] the seam the task path uses
910
+ * @param {string} [platform] the seam the tests use to reach both paths
911
+ * @returns {import('node:child_process').ChildProcess | { kill: () => void } | undefined}
912
+ */
913
+ function spawnPatcher(action, report, spawnProcess, run = spawnSync, platform = process.platform) {
914
+ if (platform === 'win32') {
915
+ const task = startPatchTask(action, report, run)
916
+ if (task !== undefined) return task
917
+ // Fall through: a shell without Task Scheduler still deserves the attempt,
918
+ // even though the patcher will not survive the quit on this platform.
919
+ }
920
+ const child = spawnProcess(selfExecutable() ?? process.execPath, launchArgs(action, report), {
921
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
922
+ detached: true,
923
+ stdio: 'ignore',
924
+ windowsHide: true,
925
+ })
926
+ if (child !== null && child !== undefined && typeof child.unref === 'function') child.unref()
927
+ return child
928
+ }
929
+
930
+ /**
931
+ * Serve the probe and the switch action over the Web GUI's HTTP carrier, so the
932
+ * panel can use plain relative `fetch` — no Remote RPC endpoint, no shell
320
933
  * bridge, and the same code path in the desktop app and the Web GUI.
321
934
  *
322
- * The route is GET-only and writes nothing; it reports where the shell is and
323
- * what the archive contains, which is what a user needs to file a useful bug
324
- * report when cross-restart login stops working.
935
+ * The probe is read-only and reports where the shell is and what the archive
936
+ * contains. The action route starts the patch script, which waits for DSH to
937
+ * exit and then does the swap and the relaunch; this half never writes a byte.
325
938
  *
326
939
  * @param {import('@deepseek-ai/cordis').Context} ctx
940
+ * @param {{ inspect?: () => object, spawn?: typeof spawn, run?: typeof spawnSync, measure?: typeof measureChatCache, cache?: () => object }} [deps] test seams
327
941
  * @returns {(() => void) | undefined} a disposer, or undefined without a webserver
328
942
  */
329
- function installHttpProbe(ctx) {
943
+ function installHttpRoutes(ctx, deps = {}) {
330
944
  const server = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
331
945
  if (server === undefined || server === null || typeof server.register !== 'function') return undefined
332
- const route = {
946
+ const read = typeof deps.inspect === 'function' ? deps.inspect : inspectShell
947
+ const spawnProcess = typeof deps.spawn === 'function' ? deps.spawn : spawn
948
+ const run = typeof deps.run === 'function' ? deps.run : spawnSync
949
+ const platform = typeof deps.platform === 'string' ? deps.platform : process.platform
950
+ const measure = typeof deps.measure === 'function' ? deps.measure : measureChatCache
951
+ const describeCache = typeof deps.cache === 'function' ? deps.cache : () => cacheReport(undefined, measure)
952
+ /** The patcher this panel started, so a second click replaces it. */
953
+ let waiting
954
+ /** A clear already in flight; a second click must not start another delete. */
955
+ let clearing = false
956
+
957
+ const stopWaiting = () => {
958
+ if (waiting === undefined) return
959
+ try {
960
+ waiting.kill()
961
+ } catch (error) {
962
+ void error
963
+ }
964
+ waiting = undefined
965
+ }
966
+
967
+ const probe = {
333
968
  kind: 'exact',
334
969
  path: PROBE_PATH,
335
970
  resource(request) {
336
971
  if (request.method !== 'GET' && request.method !== 'HEAD') {
337
- return new Response('method not allowed', { status: 405 })
972
+ return new Response('method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } })
338
973
  }
339
974
  let body
340
975
  try {
341
- body = JSON.stringify(inspectShell())
976
+ body = JSON.stringify({ ...read(), token: PATCH_TOKEN })
342
977
  } catch (error) {
343
- body = JSON.stringify({ found: false, detail: firstLine(error) })
978
+ body = JSON.stringify({ found: false, detail: firstLine(error), token: PATCH_TOKEN })
344
979
  }
345
980
  return new Response(request.method === 'HEAD' ? null : body, {
346
981
  status: 200,
@@ -348,70 +983,137 @@ function installHttpProbe(ctx) {
348
983
  })
349
984
  },
350
985
  }
351
- try {
352
- const dispose = server.register(route)
353
- return typeof dispose === 'function' ? dispose : () => {}
354
- } catch (error) {
355
- // Another composition already claimed the path, or the carrier rejected the
356
- // shape. The probe is optional: the panel still reports the local state.
357
- void error
358
- return undefined
359
- }
360
- }
361
986
 
362
- /**
363
- * Register the patch checker as an agent tool, so the model can answer
364
- * "why does my login not survive a restart?" by looking instead of asking the
365
- * user to run a command and paste its output.
366
- *
367
- * The tool is read-only and needs no approval: it reports paths, byte counts
368
- * and whether the patch marks are present, which the user could read off the
369
- * disk themselves.
370
- *
371
- * @param {import('@deepseek-ai/cordis').Context} ctx
372
- * @returns {(() => void) | undefined} a disposer, or undefined without a tool registry
373
- */
374
- function installTool(ctx) {
375
- const tools = typeof ctx.get === 'function' ? ctx.get('tools') : undefined
376
- if (tools === undefined || tools === null || typeof tools.register !== 'function') return undefined
377
- const definition = {
378
- name: 'dsh_chat_embed_patch_check',
379
- description:
380
- 'Report whether the DSH desktop shell has the optional patch that keeps embedded chat logins across restarts: the install directory, whether app.asar is writable, whether it is already patched, whether the patch can still be applied to this shell version, and whether a backup exists. Read-only.',
381
- parameters: {
382
- resources: {
383
- type: 'string',
384
- description:
385
- 'Optional install directory that contains app.asar. Omit to let the plugin detect the running shell.',
386
- },
987
+ const action = {
988
+ kind: 'exact',
989
+ path: PATCH_PATH,
990
+ resource(request) {
991
+ // GET only: a HEAD here would perform the action without returning a body.
992
+ if (request.method !== 'GET') {
993
+ return new Response('method not allowed', { status: 405, headers: { allow: 'GET' } })
994
+ }
995
+ let url
996
+ try {
997
+ url = new URL(request.url)
998
+ } catch (error) {
999
+ return jsonResponse({ ok: false, state: 'bad-request', detail: firstLine(error) }, 400)
1000
+ }
1001
+ if (url.searchParams.get(TOKEN_PARAM) !== PATCH_TOKEN) {
1002
+ return jsonResponse({ ok: false, state: 'forbidden', detail: '缺少或不匹配的 token' }, 403)
1003
+ }
1004
+ const which = url.searchParams.get(ACTION_PARAM)
1005
+ if (which !== 'apply' && which !== 'revert') {
1006
+ return jsonResponse({ ok: false, state: 'bad-request', detail: 'action 只能是 apply 或 revert' }, 400)
1007
+ }
1008
+ let report
1009
+ try {
1010
+ report = read()
1011
+ } catch (error) {
1012
+ return jsonResponse({ ok: false, state: 'failed', detail: firstLine(error), command: '' })
1013
+ }
1014
+ const plan = planPatchAction(which, report)
1015
+ if (plan.state !== 'started') {
1016
+ return jsonResponse({ ok: false, state: plan.state, detail: plan.detail, command: plan.command })
1017
+ }
1018
+ stopWaiting()
1019
+ try {
1020
+ waiting = spawnPatcher(which, report, spawnProcess, run, platform)
1021
+ } catch (error) {
1022
+ return jsonResponse({ ok: false, state: 'failed', detail: firstLine(error), command: plan.command })
1023
+ }
1024
+ return jsonResponse({ ok: true, state: 'started', action: which, command: launchArgs(which, report).join(' ') })
387
1025
  },
388
- output: {
389
- schema: { type: 'object' },
390
- render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
1026
+ }
1027
+
1028
+ const cache = {
1029
+ kind: 'exact',
1030
+ path: CACHE_PATH,
1031
+ resource(request) {
1032
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
1033
+ return new Response('method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } })
1034
+ }
1035
+ let body
1036
+ try {
1037
+ body = JSON.stringify({ ...describeCache(), token: PATCH_TOKEN })
1038
+ } catch (error) {
1039
+ body = JSON.stringify({ ok: false, mode: 'unknown', bytes: 0, detail: firstLine(error), token: PATCH_TOKEN })
1040
+ }
1041
+ return new Response(request.method === 'HEAD' ? null : body, {
1042
+ status: 200,
1043
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
1044
+ })
391
1045
  },
392
- async execute(args) {
393
- const requested = args !== undefined && args !== null && typeof args.resources === 'string' ? args.resources : undefined
394
- return inspectShell(requested)
1046
+ }
1047
+
1048
+ const cacheClear = {
1049
+ kind: 'exact',
1050
+ path: CACHE_CLEAR_PATH,
1051
+ resource(request) {
1052
+ if (request.method !== 'GET') {
1053
+ return new Response('method not allowed', { status: 405, headers: { allow: 'GET' } })
1054
+ }
1055
+ let url
1056
+ try {
1057
+ url = new URL(request.url)
1058
+ } catch (error) {
1059
+ return jsonResponse({ ok: false, state: 'bad-request', detail: firstLine(error) }, 400)
1060
+ }
1061
+ if (url.searchParams.get(TOKEN_PARAM) !== PATCH_TOKEN) {
1062
+ return jsonResponse({ ok: false, state: 'forbidden', detail: '缺少或不匹配的 token' }, 403)
1063
+ }
1064
+ if (clearing) return jsonResponse({ ok: false, state: 'busy', detail: '正在清理', bytes: 0, mode: 'unknown', freed: 0 })
1065
+ clearing = true
1066
+ try {
1067
+ const described = describeCache()
1068
+ return jsonResponse(clearChatCache(described, run, measure))
1069
+ } catch (error) {
1070
+ return jsonResponse({ ok: false, state: 'failed', detail: firstLine(error), bytes: 0, mode: 'unknown', freed: 0 })
1071
+ } finally {
1072
+ clearing = false
1073
+ }
395
1074
  },
396
1075
  }
1076
+
1077
+ const disposers = []
397
1078
  try {
398
- const dispose = tools.register(definition)
399
- return typeof dispose === 'function' ? dispose : () => {}
1079
+ for (const route of [probe, action, cache, cacheClear]) {
1080
+ const dispose = server.register(route)
1081
+ if (typeof dispose === 'function') disposers.push(dispose)
1082
+ }
400
1083
  } catch (error) {
1084
+ // Another composition already claimed a path, or the carrier rejected the
1085
+ // shape. Both routes are optional: the panel still reports local state and
1086
+ // still offers the copyable command.
1087
+ for (const dispose of disposers) {
1088
+ try {
1089
+ dispose()
1090
+ } catch (ignored) {
1091
+ void ignored
1092
+ }
1093
+ }
401
1094
  void error
402
1095
  return undefined
403
1096
  }
1097
+ return () => {
1098
+ stopWaiting()
1099
+ for (const dispose of disposers) {
1100
+ try {
1101
+ dispose()
1102
+ } catch (error) {
1103
+ void error
1104
+ }
1105
+ }
1106
+ }
404
1107
  }
405
1108
 
406
1109
  /**
407
- * Register the Host-side patch probe and the agent tool.
1110
+ * Register the Host-side probe and the action route behind the panel switch.
408
1111
  *
409
1112
  * @param {import('@deepseek-ai/cordis').Context} ctx
410
1113
  */
411
1114
  export function apply(ctx) {
412
1115
  if (ctx === undefined || ctx === null || typeof ctx.effect !== 'function') return
413
- ctx.effect(() => installHttpProbe(ctx), 'dsh-chat-embed: shell patch probe')
414
- ctx.effect(() => installTool(ctx), 'dsh-chat-embed: shell patch tool')
1116
+ ctx.effect(() => installHttpRoutes(ctx), 'dsh-chat-embed: shell patch routes')
415
1117
  }
416
1118
 
417
1119
  /** Exposed for tests and for the patch checker to reuse without a Context. */
@@ -421,8 +1123,30 @@ export const internals = {
421
1123
  readAsarEntry,
422
1124
  readRealFile,
423
1125
  resourcesCandidates,
1126
+ launcherCommand,
424
1127
  findNodeBinary,
425
- findPatchScript,
426
- patchCommand,
1128
+ nodeCandidates,
1129
+ findPatchFiles,
1130
+ installHttpRoutes,
1131
+ planPatchAction,
1132
+ launchArgs,
1133
+ selfExecutable,
1134
+ spawnPatcher,
1135
+ patchTaskCommand,
1136
+ patchTaskTarget,
1137
+ detachedPayload,
1138
+ startPatchTask,
1139
+ PATCH_TASK,
1140
+ PATCH_WAIT_MINUTES,
1141
+ CHAT_WORKSPACES,
1142
+ CACHE_DIR_NAMES,
1143
+ partitionDirName,
1144
+ measureChatCache,
1145
+ cacheReport,
1146
+ clearChatCache,
427
1147
  PROBE_PATH,
1148
+ CACHE_PATH,
1149
+ CACHE_CLEAR_PATH,
1150
+ PATCH_PATH,
1151
+ PATCH_TOKEN,
428
1152
  }