dsh-chat-embed 0.6.11 → 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/README.md +99 -46
- package/client.js +508 -178
- package/index.js +858 -134
- package/package.json +1 -4
- package/tools/shell-patch/shell-patch.cmd +66 -0
- package/tools/shell-patch/shell-patch.command +70 -0
- package/tools/shell-patch/shell-patch.mjs +1260 -0
- package/docs/architecture.md +0 -387
- package/docs/publishing.md +0 -188
- package/restore-shell-patch.cmd +0 -39
- package/tools/shell-patch/clean-cache.ps1 +0 -76
- package/tools/shell-patch/patch-asar.cjs +0 -272
- package/tools/shell-patch/watchdog.ps1 +0 -124
- package//346/270/205/347/220/206/350/201/212/345/244/251/347/274/223/345/255/230.cmd +0 -12
|
@@ -0,0 +1,1260 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* shell-patch.mjs — turn "logins survive a restart" on or off for the DSH
|
|
4
|
+
* desktop shell, on Windows and macOS, without an agent and without editing
|
|
5
|
+
* anything by hand.
|
|
6
|
+
*
|
|
7
|
+
* Why a patch is needed at all: the desktop shell names every embedded browser
|
|
8
|
+
* partition `dsh-sidebar-browser-<random uuid>` — no `persist:` prefix, so
|
|
9
|
+
* Chromium keeps it in memory, and a fresh uuid on every launch, so every
|
|
10
|
+
* embedded page is signed out by a restart. Hashing the workspace identity
|
|
11
|
+
* instead makes the partition stable on disk; the login itself already lives
|
|
12
|
+
* there, so nothing else has to change.
|
|
13
|
+
*
|
|
14
|
+
* Usage:
|
|
15
|
+
*
|
|
16
|
+
* node shell-patch.mjs interactive menu
|
|
17
|
+
* node shell-patch.mjs status report only, writes nothing
|
|
18
|
+
* node shell-patch.mjs apply turn the feature on
|
|
19
|
+
* node shell-patch.mjs revert turn it off again
|
|
20
|
+
*
|
|
21
|
+
* Options:
|
|
22
|
+
* --resources <dir> the install directory that holds app.asar
|
|
23
|
+
* (default: $DSH_RESOURCES, then the usual locations)
|
|
24
|
+
* --yes answer every question with yes
|
|
25
|
+
* --no-cache-patch keep the disk cache; only the partition goes persistent
|
|
26
|
+
* --restart wait for DSH to exit, swap, then start it again
|
|
27
|
+
* --pid <n> the DSH process --restart waits for
|
|
28
|
+
* --exe <path> what --restart starts again once the swap is in
|
|
29
|
+
* --wait-minutes <n> how long --restart may wait for that exit (0 = forever)
|
|
30
|
+
*
|
|
31
|
+
* Safety: the new archive is rebuilt from the old one's own bytes, every
|
|
32
|
+
* untouched entry must come out byte-identical, and only then is it swapped in.
|
|
33
|
+
* The previous archive is kept. Running the same command twice is harmless.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
37
|
+
import { createHash } from 'node:crypto'
|
|
38
|
+
import * as nodeFs from 'node:fs'
|
|
39
|
+
import { createRequire } from 'node:module'
|
|
40
|
+
import { homedir } from 'node:os'
|
|
41
|
+
import { join, resolve, sep } from 'node:path'
|
|
42
|
+
import { fileURLToPath } from 'node:url'
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The file system this script actually needs.
|
|
46
|
+
*
|
|
47
|
+
* Electron's `node:fs` treats any `*.asar` path as an archive: reading the
|
|
48
|
+
* archive file itself raises ENOENT, `statSync` reports 0, `existsSync` says
|
|
49
|
+
* false and a write is refused with "Invalid package". This script exists to
|
|
50
|
+
* read and rewrite exactly that file, and the panel starts it with the desktop
|
|
51
|
+
* app's own runtime, so under Electron it must use the unpatched binding.
|
|
52
|
+
* `original-fs` is that binding; a plain Node has no such module and is already
|
|
53
|
+
* literal, so the ordinary one is used there.
|
|
54
|
+
*/
|
|
55
|
+
const fs = (() => {
|
|
56
|
+
try {
|
|
57
|
+
const original = createRequire(import.meta.url)('original-fs')
|
|
58
|
+
if (original !== undefined && original !== null && typeof original.readFileSync === 'function') return original
|
|
59
|
+
} catch (error) {
|
|
60
|
+
void error
|
|
61
|
+
}
|
|
62
|
+
return nodeFs
|
|
63
|
+
})()
|
|
64
|
+
|
|
65
|
+
const { existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } = fs
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// The patch: two literal rewrites, each inverted by `revert`
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
const PERSIST_FROM = 'partition = `dsh-sidebar-browser-${randomUUID()}`;'
|
|
72
|
+
const PERSIST_TO =
|
|
73
|
+
'partition = `persist:dsh-sidebar-${createHash("sha256").update(workspace).digest("hex").slice(0, 24)}`;'
|
|
74
|
+
const CACHE_FROM = 'this.configureSession(session.fromPartition(partition));'
|
|
75
|
+
const CACHE_TO = 'this.configureSession(session.fromPartition(partition, { cache: false }));'
|
|
76
|
+
|
|
77
|
+
/** Marks that tell a patched archive from a pristine one. */
|
|
78
|
+
const PATCH_MARK = 'persist:dsh-sidebar-'
|
|
79
|
+
const CACHE_MARK = 'fromPartition(partition, { cache: false })'
|
|
80
|
+
|
|
81
|
+
const MAIN_ENTRY = 'lib/main.js'
|
|
82
|
+
const BACKUP = 'app.asar.orig'
|
|
83
|
+
const PATCHED_COPY = 'app.asar.patched.bak'
|
|
84
|
+
const STAGED = 'app.asar.new'
|
|
85
|
+
const LOCK_NAME = '.dsh-chat-embed-patch.lock'
|
|
86
|
+
const PATCH_LOG_NAME = 'dsh-chat-embed-patch.log'
|
|
87
|
+
const BLOCK_SIZE = 4194304
|
|
88
|
+
|
|
89
|
+
const SELF = fileURLToPath(import.meta.url)
|
|
90
|
+
const isTty = process.stdout.isTTY === true
|
|
91
|
+
|
|
92
|
+
/** Set when a command actually replaced app.asar, so a no-op never says "restart". */
|
|
93
|
+
let changed = false
|
|
94
|
+
/** Set when the same run also started DSH again, so the last line can say so. */
|
|
95
|
+
let reopened = false
|
|
96
|
+
/** The Task Scheduler entry that started this run, removed on the way out. */
|
|
97
|
+
let pendingTask
|
|
98
|
+
/** Set once this run owns the lock, so a failure still releases only its own. */
|
|
99
|
+
let ownedLock
|
|
100
|
+
/** Where `say` also writes, once a writing command has opened it. */
|
|
101
|
+
let patchLog
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Output
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Start a fresh log beside the archive.
|
|
109
|
+
*
|
|
110
|
+
* The switch runs this script with a hidden console, so a timeout that only
|
|
111
|
+
* reaches stdout is invisible: the user quits later, finds an untouched
|
|
112
|
+
* archive, and has no sentence that says why. One file per install also keeps
|
|
113
|
+
* a parallel test from wiping another run's log.
|
|
114
|
+
*
|
|
115
|
+
* @param {string} resources
|
|
116
|
+
*/
|
|
117
|
+
function openLog(resources) {
|
|
118
|
+
const path = join(resources, PATCH_LOG_NAME)
|
|
119
|
+
try {
|
|
120
|
+
writeFileSync(path, '')
|
|
121
|
+
patchLog = path
|
|
122
|
+
} catch (error) {
|
|
123
|
+
void error
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** @param {string} [line] */
|
|
128
|
+
function say(line) {
|
|
129
|
+
const text = line === undefined ? '' : line
|
|
130
|
+
console.log(text)
|
|
131
|
+
if (patchLog === undefined) return
|
|
132
|
+
try {
|
|
133
|
+
nodeFs.appendFileSync(patchLog, text + '\n')
|
|
134
|
+
} catch (error) {
|
|
135
|
+
void error
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Mention the log in a failure, so the hidden-console case still points at it. */
|
|
140
|
+
function sayLog() {
|
|
141
|
+
if (patchLog === undefined) return
|
|
142
|
+
say(' 过程写在 ' + patchLog)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** @param {number} bytes */
|
|
146
|
+
function plural(bytes) {
|
|
147
|
+
if (bytes >= 1024 * 1024 * 1024) return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
|
|
148
|
+
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** @param {unknown} error @returns {string} */
|
|
152
|
+
function reasonOf(error) {
|
|
153
|
+
const text = error instanceof Error ? error.message : String(error)
|
|
154
|
+
return text.split('\n')[0].slice(0, 300)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** @param {string} question @returns {Promise<string>} '' when nobody can answer */
|
|
158
|
+
async function ask(question) {
|
|
159
|
+
if (!isTty) return ''
|
|
160
|
+
process.stdout.write(' ' + question + ' ')
|
|
161
|
+
return new Promise((done) => {
|
|
162
|
+
const onData = (chunk) => {
|
|
163
|
+
process.stdin.pause()
|
|
164
|
+
process.stdin.removeListener('data', onData)
|
|
165
|
+
done(String(chunk).trim())
|
|
166
|
+
}
|
|
167
|
+
process.stdin.resume()
|
|
168
|
+
process.stdin.once('data', onData)
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
// Install locations
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
/** @returns {string[]} candidate `resources` directories, most likely first */
|
|
177
|
+
function resourcesCandidates() {
|
|
178
|
+
const out = []
|
|
179
|
+
const push = (value) => {
|
|
180
|
+
if (typeof value === 'string' && value !== '' && !out.includes(value)) out.push(value)
|
|
181
|
+
}
|
|
182
|
+
push(process.env.DSH_RESOURCES)
|
|
183
|
+
if (process.platform === 'win32') {
|
|
184
|
+
const local = process.env.LOCALAPPDATA
|
|
185
|
+
if (local !== undefined && local !== '') push(join(local, 'Programs', 'DeepSeek Harness', 'resources'))
|
|
186
|
+
push('C:\\Program Files\\DeepSeek Harness\\resources')
|
|
187
|
+
push('C:\\Program Files (x86)\\DeepSeek Harness\\resources')
|
|
188
|
+
} else if (process.platform === 'darwin') {
|
|
189
|
+
push('/Applications/DeepSeek Harness.app/Contents/Resources')
|
|
190
|
+
push(join(homedir(), 'Applications', 'DeepSeek Harness.app', 'Contents', 'Resources'))
|
|
191
|
+
} else {
|
|
192
|
+
push(join(homedir(), '.local', 'share', 'DeepSeek Harness', 'resources'))
|
|
193
|
+
}
|
|
194
|
+
return out
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @returns {string | undefined} */
|
|
198
|
+
function detectResources() {
|
|
199
|
+
for (const candidate of resourcesCandidates()) {
|
|
200
|
+
if (existsSync(join(candidate, 'app.asar'))) return candidate
|
|
201
|
+
}
|
|
202
|
+
return undefined
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
// asar: parse a header, rebuild the data section, rewrite offsets + integrity
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* @param {Buffer} buf
|
|
211
|
+
*/
|
|
212
|
+
function parseAsar(buf) {
|
|
213
|
+
if (buf.length < 16) throw new Error('the archive is too small to be an asar')
|
|
214
|
+
const jsonLength = buf.readUInt32LE(12)
|
|
215
|
+
const start = 16
|
|
216
|
+
if (jsonLength <= 0 || start + jsonLength > buf.length) throw new Error('the asar header is truncated')
|
|
217
|
+
const header = JSON.parse(buf.toString('utf8', start, start + jsonLength))
|
|
218
|
+
const pad = (4 - (jsonLength % 4)) % 4
|
|
219
|
+
const dataStart = start + jsonLength + pad
|
|
220
|
+
return { header, dataStart, data: buf.subarray(dataStart) }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** @param {string} file */
|
|
224
|
+
function readAsar(file) {
|
|
225
|
+
return parseAsar(readFileSync(file))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** @param {any} header @returns {{ path: string, node: any }[]} */
|
|
229
|
+
function collect(header) {
|
|
230
|
+
const files = []
|
|
231
|
+
const walk = (node, prefix) => {
|
|
232
|
+
for (const [name, child] of Object.entries(node.files || {})) {
|
|
233
|
+
const path = prefix === '' ? name : prefix + '/' + name
|
|
234
|
+
if (child.files !== undefined) walk(child, path)
|
|
235
|
+
else files.push({ path, node: child })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
walk(header, '')
|
|
239
|
+
return files
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** @param {any} data @param {any} node */
|
|
243
|
+
function entryBytes(data, node) {
|
|
244
|
+
return data.subarray(Number(node.offset), Number(node.offset) + Number(node.size))
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The sha256 block list Electron validates a packed entry against. */
|
|
248
|
+
function integrityFor(content) {
|
|
249
|
+
const blocks = []
|
|
250
|
+
for (let offset = 0; offset < content.length; offset += BLOCK_SIZE) {
|
|
251
|
+
blocks.push(
|
|
252
|
+
createHash('sha256').update(content.subarray(offset, Math.min(offset + BLOCK_SIZE, content.length))).digest('hex'),
|
|
253
|
+
)
|
|
254
|
+
}
|
|
255
|
+
if (blocks.length === 0) blocks.push(createHash('sha256').update(Buffer.alloc(0)).digest('hex'))
|
|
256
|
+
return {
|
|
257
|
+
algorithm: 'SHA256',
|
|
258
|
+
hash: createHash('sha256').update(content).digest('hex'),
|
|
259
|
+
blockSize: BLOCK_SIZE,
|
|
260
|
+
blocks,
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Rebuild the archive with `lib/main.js` rewritten.
|
|
266
|
+
*
|
|
267
|
+
* @param {Buffer} buf the archive to rebuild
|
|
268
|
+
* @param {Array<[string, string]>} rewrites literal `[from, to]` pairs
|
|
269
|
+
* @returns {{ buffer: Buffer, applied: number }}
|
|
270
|
+
*/
|
|
271
|
+
function rebuild(buf, rewrites) {
|
|
272
|
+
const { header, data } = parseAsar(buf)
|
|
273
|
+
const packed = collect(header)
|
|
274
|
+
.filter((file) => file.node.unpacked !== true)
|
|
275
|
+
.sort((a, b) => Number(a.node.offset) - Number(b.node.offset))
|
|
276
|
+
|
|
277
|
+
const chunks = []
|
|
278
|
+
let applied = 0
|
|
279
|
+
let cursor = 0
|
|
280
|
+
let touched = false
|
|
281
|
+
|
|
282
|
+
for (const file of packed) {
|
|
283
|
+
let content = entryBytes(data, file.node)
|
|
284
|
+
if (file.path === MAIN_ENTRY) {
|
|
285
|
+
let text = content.toString('utf8')
|
|
286
|
+
for (const [from, to] of rewrites) {
|
|
287
|
+
if (!text.includes(from)) continue
|
|
288
|
+
text = text.split(from).join(to)
|
|
289
|
+
applied += 1
|
|
290
|
+
}
|
|
291
|
+
if (applied === 0) throw new Error('lib/main.js contains none of the expected patch sites')
|
|
292
|
+
content = Buffer.from(text, 'utf8')
|
|
293
|
+
file.node.size = content.length
|
|
294
|
+
file.node.integrity = integrityFor(content)
|
|
295
|
+
touched = true
|
|
296
|
+
}
|
|
297
|
+
file.node.offset = String(cursor)
|
|
298
|
+
chunks.push(content)
|
|
299
|
+
cursor += content.length
|
|
300
|
+
}
|
|
301
|
+
if (!touched) throw new Error('lib/main.js was not found in the archive')
|
|
302
|
+
|
|
303
|
+
const headerJson = Buffer.from(JSON.stringify(header), 'utf8')
|
|
304
|
+
const pad = (4 - (headerJson.length % 4)) % 4
|
|
305
|
+
// The two pickle size fields count the alignment padding as well. Omitting it
|
|
306
|
+
// still produced an archive Electron reads — the JSON length at offset 12 is
|
|
307
|
+
// what locates the header — but it made a revert differ from the original by
|
|
308
|
+
// two bytes, so "put it back" was only content-identical. Measured against a
|
|
309
|
+
// real shell archive: [4] = json + pad + 8, [8] = json + pad + 4.
|
|
310
|
+
const prefix = Buffer.alloc(16)
|
|
311
|
+
prefix.writeUInt32LE(4, 0)
|
|
312
|
+
prefix.writeUInt32LE(headerJson.length + pad + 8, 4)
|
|
313
|
+
prefix.writeUInt32LE(headerJson.length + pad + 4, 8)
|
|
314
|
+
prefix.writeUInt32LE(headerJson.length, 12)
|
|
315
|
+
return { buffer: Buffer.concat([prefix, headerJson, Buffer.alloc(pad), Buffer.concat(chunks)]), applied }
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Prove a rebuilt archive differs from its source only where it must: the same
|
|
320
|
+
* entries, every untouched file byte-identical, `lib/main.js` in the expected
|
|
321
|
+
* state.
|
|
322
|
+
*
|
|
323
|
+
* @param {Buffer} before the archive the rebuild started from
|
|
324
|
+
* @param {Buffer} after the rebuilt archive
|
|
325
|
+
* @param {(text: string) => boolean} ok
|
|
326
|
+
* @returns {number} how many files were compared and matched
|
|
327
|
+
*/
|
|
328
|
+
function verify(before, after, ok) {
|
|
329
|
+
const from = parseAsar(before)
|
|
330
|
+
const to = parseAsar(after)
|
|
331
|
+
const beforeFiles = collect(from.header)
|
|
332
|
+
const afterFiles = collect(to.header)
|
|
333
|
+
if (beforeFiles.length !== afterFiles.length) {
|
|
334
|
+
throw new Error(`entry count changed: ${beforeFiles.length} -> ${afterFiles.length}`)
|
|
335
|
+
}
|
|
336
|
+
const byPath = new Map(beforeFiles.map((file) => [file.path, file]))
|
|
337
|
+
let compared = 0
|
|
338
|
+
for (const file of afterFiles) {
|
|
339
|
+
const original = byPath.get(file.path)
|
|
340
|
+
if (original === undefined) throw new Error('a new entry appeared: ' + file.path)
|
|
341
|
+
const next = entryBytes(to.data, file.node)
|
|
342
|
+
if (file.path === MAIN_ENTRY) {
|
|
343
|
+
if (!ok(next.toString('utf8'))) throw new Error('lib/main.js is not in the expected state after the rebuild')
|
|
344
|
+
continue
|
|
345
|
+
}
|
|
346
|
+
if (file.node.unpacked === true || original.node.unpacked === true) {
|
|
347
|
+
if (Number(file.node.size) !== Number(original.node.size)) throw new Error('size drifted on ' + file.path)
|
|
348
|
+
continue
|
|
349
|
+
}
|
|
350
|
+
if (!entryBytes(from.data, original.node).equals(next)) {
|
|
351
|
+
throw new Error('an untouched file changed: ' + file.path)
|
|
352
|
+
}
|
|
353
|
+
compared += 1
|
|
354
|
+
}
|
|
355
|
+
return compared
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ---------------------------------------------------------------------------
|
|
359
|
+
// State
|
|
360
|
+
// ---------------------------------------------------------------------------
|
|
361
|
+
|
|
362
|
+
/** @param {Buffer} buf */
|
|
363
|
+
function mainTextOf(buf) {
|
|
364
|
+
const { header, data } = parseAsar(buf)
|
|
365
|
+
const file = collect(header).find((entry) => entry.path === MAIN_ENTRY)
|
|
366
|
+
if (file === undefined) throw new Error('the archive has no ' + MAIN_ENTRY + '; the shell layout changed')
|
|
367
|
+
return entryBytes(data, file.node).toString('utf8')
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* @param {string} resources
|
|
372
|
+
* @returns {{ archive: string, patched: boolean, patchSite: boolean, cachePatched: boolean, bytes: number }}
|
|
373
|
+
*/
|
|
374
|
+
function inspect(resources) {
|
|
375
|
+
const archive = join(resources, 'app.asar')
|
|
376
|
+
if (!existsSync(archive)) throw new Error('there is no app.asar in ' + resources)
|
|
377
|
+
const main = mainTextOf(readFileSync(archive))
|
|
378
|
+
return {
|
|
379
|
+
archive,
|
|
380
|
+
patched: main.includes(PATCH_MARK),
|
|
381
|
+
patchSite: main.includes(PERSIST_FROM),
|
|
382
|
+
cachePatched: main.includes(CACHE_MARK),
|
|
383
|
+
bytes: statSync(archive).size,
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Whether the backup on disk is a genuine unpatched archive.
|
|
389
|
+
*
|
|
390
|
+
* @param {string} resources
|
|
391
|
+
* @returns {'clean' | 'dirty' | 'missing'}
|
|
392
|
+
*/
|
|
393
|
+
function backupState(resources) {
|
|
394
|
+
const backup = join(resources, BACKUP)
|
|
395
|
+
if (!existsSync(backup)) return 'missing'
|
|
396
|
+
try {
|
|
397
|
+
return mainTextOf(readFileSync(backup)).includes(PATCH_MARK) ? 'dirty' : 'clean'
|
|
398
|
+
} catch (error) {
|
|
399
|
+
void error
|
|
400
|
+
return 'dirty'
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** @param {string} dir */
|
|
405
|
+
function canWrite(dir) {
|
|
406
|
+
const probe = join(dir, '.dsh-chat-embed-write-probe')
|
|
407
|
+
try {
|
|
408
|
+
writeFileSync(probe, 'x')
|
|
409
|
+
unlinkSync(probe)
|
|
410
|
+
return true
|
|
411
|
+
} catch (error) {
|
|
412
|
+
void error
|
|
413
|
+
return false
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ---------------------------------------------------------------------------
|
|
418
|
+
// Swapping the archive in, around a running app
|
|
419
|
+
// ---------------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
const delay = (ms) => new Promise((done) => setTimeout(done, ms))
|
|
422
|
+
|
|
423
|
+
/** @param {unknown} error @returns {boolean} */
|
|
424
|
+
function isBusy(error) {
|
|
425
|
+
const code =
|
|
426
|
+
error !== null && error !== undefined && typeof error === 'object' && 'code' in error ? String(error.code) : ''
|
|
427
|
+
return code === 'EBUSY' || code === 'EPERM' || code === 'EACCES' || code === 'ETXTBSY'
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Replace `archive` with `staged`, keeping the old archive at `keepAs` (or
|
|
432
|
+
* deleting it when `keepAs` is undefined).
|
|
433
|
+
*
|
|
434
|
+
* A running DSH keeps app.asar memory-mapped, and on Windows a mapped file
|
|
435
|
+
* cannot be renamed. That wait has to be bounded: an unbounded one is
|
|
436
|
+
* indistinguishable from a hang, and a patcher that never exits is worse than
|
|
437
|
+
* one that fails — it holds the archive open, which is exactly the state that
|
|
438
|
+
* keeps a pending shell update from installing.
|
|
439
|
+
*
|
|
440
|
+
* @param {string} archive
|
|
441
|
+
* @param {string} staged
|
|
442
|
+
* @param {string | undefined} keepAs
|
|
443
|
+
* @param {{ waitMinutes?: number }} [options] the same budget `--restart` obeys
|
|
444
|
+
* @returns {Promise<boolean>} false when the app never let go in time
|
|
445
|
+
*/
|
|
446
|
+
async function swapIn(archive, staged, keepAs, options = {}) {
|
|
447
|
+
const parked = archive + '.prev'
|
|
448
|
+
const minutes = Number.isFinite(options.waitMinutes) && options.waitMinutes > 0 ? options.waitMinutes : 0
|
|
449
|
+
const deadline = minutes > 0 ? Date.now() + minutes * 60000 : 0
|
|
450
|
+
let waitedSince = 0
|
|
451
|
+
for (;;) {
|
|
452
|
+
try {
|
|
453
|
+
if (existsSync(parked)) unlinkSync(parked)
|
|
454
|
+
renameSync(archive, parked)
|
|
455
|
+
} catch (error) {
|
|
456
|
+
if (!isBusy(error)) throw error
|
|
457
|
+
const now = Date.now()
|
|
458
|
+
if (deadline !== 0 && now > deadline) {
|
|
459
|
+
say('')
|
|
460
|
+
say(' ✗ app.asar 被 DSH 占着,等了 ' + minutes + ' 分钟仍没释放。')
|
|
461
|
+
say(' 没有改动任何文件,暂存副本也一并删掉。')
|
|
462
|
+
sayLog()
|
|
463
|
+
say('')
|
|
464
|
+
say(' 要换文件,DSH 必须完全退出:右键托盘图标 →「退出」。')
|
|
465
|
+
say(' 只是关窗口不够——那会把窗口收进托盘,进程还在。')
|
|
466
|
+
return false
|
|
467
|
+
}
|
|
468
|
+
if (waitedSince === 0) {
|
|
469
|
+
waitedSince = now
|
|
470
|
+
say('')
|
|
471
|
+
say(' DSH 正在运行,app.asar 被它占用。')
|
|
472
|
+
say(' 请完全退出 DSH(托盘 →「退出」),脚本会在这里等待并自动继续。')
|
|
473
|
+
say('')
|
|
474
|
+
} else if (now - waitedSince > 8000) {
|
|
475
|
+
waitedSince = now
|
|
476
|
+
const budget = minutes > 0 ? '(最多再等 ' + Math.max(1, Math.ceil((deadline - now) / 60000)) + ' 分钟)' : ''
|
|
477
|
+
say(' 仍在等待 DSH 退出 …' + budget)
|
|
478
|
+
}
|
|
479
|
+
await delay(700)
|
|
480
|
+
continue
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
try {
|
|
484
|
+
renameSync(staged, archive)
|
|
485
|
+
} catch (error) {
|
|
486
|
+
try {
|
|
487
|
+
renameSync(parked, archive)
|
|
488
|
+
} catch (restoreError) {
|
|
489
|
+
void restoreError
|
|
490
|
+
}
|
|
491
|
+
throw error
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
if (keepAs === undefined) {
|
|
495
|
+
try {
|
|
496
|
+
unlinkSync(parked)
|
|
497
|
+
} catch (error) {
|
|
498
|
+
void error
|
|
499
|
+
}
|
|
500
|
+
} else {
|
|
501
|
+
try {
|
|
502
|
+
if (existsSync(keepAs)) unlinkSync(keepAs)
|
|
503
|
+
renameSync(parked, keepAs)
|
|
504
|
+
} catch (error) {
|
|
505
|
+
// The swap already happened; a stranded copy is not a failure.
|
|
506
|
+
say(' · 旧版本没能另存为 ' + keepAs + ':' + reasonOf(error))
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return true
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// ---------------------------------------------------------------------------
|
|
514
|
+
// Handing off: wait for DSH to exit, swap, start it again
|
|
515
|
+
// ---------------------------------------------------------------------------
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Remove the scheduled task that started this run.
|
|
519
|
+
*
|
|
520
|
+
* On Windows the Host cannot start this script as a plain child: DSH keeps every
|
|
521
|
+
* process it spawns in a job object that dies with it, so the patcher would be
|
|
522
|
+
* killed exactly while it waits. The Host therefore registers a Task Scheduler
|
|
523
|
+
* entry, which `svchost` starts outside that job. Such a task has one purpose
|
|
524
|
+
* and no reason to survive it — and leaving it behind would fire it again after
|
|
525
|
+
* the next reboot.
|
|
526
|
+
*
|
|
527
|
+
* @param {string | undefined} name
|
|
528
|
+
*/
|
|
529
|
+
function forgetTask(name) {
|
|
530
|
+
if (process.platform !== 'win32') return
|
|
531
|
+
if (typeof name !== 'string' || name === '') return
|
|
532
|
+
// A scheduled task gets the machine environment, not this shell's; resolving
|
|
533
|
+
// the path here keeps the deletion independent of whatever PATH it inherits.
|
|
534
|
+
const systemRoot = process.env.SystemRoot !== undefined ? process.env.SystemRoot : 'C:\\Windows'
|
|
535
|
+
try {
|
|
536
|
+
spawnSync(join(systemRoot, 'System32', 'schtasks.exe'), ['/delete', '/tn', name, '/f'], {
|
|
537
|
+
stdio: 'ignore',
|
|
538
|
+
windowsHide: true,
|
|
539
|
+
})
|
|
540
|
+
} catch (error) {
|
|
541
|
+
// A task that will not delete is litter, not a failed patch.
|
|
542
|
+
void error
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** Drop the archive a `--restart` run staged but never swapped in. @param {string} staged */
|
|
547
|
+
function discardStaged(staged) {
|
|
548
|
+
try {
|
|
549
|
+
unlinkSync(staged)
|
|
550
|
+
} catch (error) {
|
|
551
|
+
void error
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Whether a process is still there.
|
|
557
|
+
*
|
|
558
|
+
* `signal 0` asks the OS and changes nothing; EPERM means "it exists, it is
|
|
559
|
+
* just not yours", and anything else means it is gone.
|
|
560
|
+
*
|
|
561
|
+
* @param {number} pid
|
|
562
|
+
* @returns {boolean}
|
|
563
|
+
*/
|
|
564
|
+
function isRunning(pid) {
|
|
565
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
566
|
+
try {
|
|
567
|
+
process.kill(pid, 0)
|
|
568
|
+
return true
|
|
569
|
+
} catch (error) {
|
|
570
|
+
const code =
|
|
571
|
+
error !== null && error !== undefined && typeof error === 'object' && 'code' in error ? String(error.code) : ''
|
|
572
|
+
return code === 'EPERM'
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Claim the right to rewrite this install, or refuse because another patcher
|
|
578
|
+
* already has it.
|
|
579
|
+
*
|
|
580
|
+
* The switch starts the script detached, and the task that started it exits
|
|
581
|
+
* at once. A second click therefore cannot stop the first process: both would
|
|
582
|
+
* wait for the same quit and then rename one archive. The lock is the refusal.
|
|
583
|
+
* A stale lock (its pid is gone) is taken over; a lock that cannot be created
|
|
584
|
+
* must not block the only writer.
|
|
585
|
+
*
|
|
586
|
+
* @param {string} resources
|
|
587
|
+
* @returns {boolean} false when a live patcher already holds it
|
|
588
|
+
*/
|
|
589
|
+
function claimPatcher(resources) {
|
|
590
|
+
const lockPath = join(resources, LOCK_NAME)
|
|
591
|
+
const own = String(process.pid)
|
|
592
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
593
|
+
try {
|
|
594
|
+
writeFileSync(lockPath, own, { flag: 'wx' })
|
|
595
|
+
ownedLock = lockPath
|
|
596
|
+
return true
|
|
597
|
+
} catch (error) {
|
|
598
|
+
const code =
|
|
599
|
+
error !== null && error !== undefined && typeof error === 'object' && 'code' in error ? String(error.code) : ''
|
|
600
|
+
if (code !== 'EEXIST') return true
|
|
601
|
+
let holder = 0
|
|
602
|
+
try {
|
|
603
|
+
holder = Number(readFileSync(lockPath, 'utf8').trim())
|
|
604
|
+
} catch (readError) {
|
|
605
|
+
void readError
|
|
606
|
+
}
|
|
607
|
+
if (holder !== process.pid && isRunning(holder)) return false
|
|
608
|
+
try {
|
|
609
|
+
unlinkSync(lockPath)
|
|
610
|
+
} catch (unlinkError) {
|
|
611
|
+
void unlinkError
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return false
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** Release the lock only if this process still owns it. */
|
|
619
|
+
function releasePatcher() {
|
|
620
|
+
if (ownedLock === undefined) return
|
|
621
|
+
const lockPath = ownedLock
|
|
622
|
+
ownedLock = undefined
|
|
623
|
+
try {
|
|
624
|
+
const holder = Number(readFileSync(lockPath, 'utf8').trim())
|
|
625
|
+
if (holder === process.pid) unlinkSync(lockPath)
|
|
626
|
+
} catch (error) {
|
|
627
|
+
void error
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Ask the user to quit DSH, and wait for it.
|
|
633
|
+
*
|
|
634
|
+
* The caller has staged the new archive but has not touched the old one yet: a
|
|
635
|
+
* running DSH keeps app.asar mapped, and on Windows a mapped file cannot be
|
|
636
|
+
* renamed. Nothing else in this script can free it — the shell's close button
|
|
637
|
+
* only hides the window, its quit path is a menu item behind a confirmation,
|
|
638
|
+
* and a plugin has no way to ask for either. So the user quits, this waits, and
|
|
639
|
+
* the rest happens without them.
|
|
640
|
+
*
|
|
641
|
+
* Without a pid there is nothing to watch: the swap keeps its own retry loop as
|
|
642
|
+
* the wait, so this returns immediately.
|
|
643
|
+
*
|
|
644
|
+
* @param {{ pid: number | undefined, exe: string | undefined, waitMinutes: number }} options
|
|
645
|
+
* @returns {Promise<boolean>} false when the wait ran out
|
|
646
|
+
*/
|
|
647
|
+
async function waitForQuit(options) {
|
|
648
|
+
say('')
|
|
649
|
+
say(' 补丁已准备好,接下来要替换 app.asar。')
|
|
650
|
+
say(' 这个文件被运行中的 DSH 占着,请先把它关掉:')
|
|
651
|
+
say(' 右键任务栏托盘里的 DSH 图标 →「退出」')
|
|
652
|
+
say(
|
|
653
|
+
options.exe === undefined
|
|
654
|
+
? ' 退出后我会替换文件;替换完请自己打开 DSH。'
|
|
655
|
+
: ' 退出后我会替换文件,并自动重新打开 DSH。',
|
|
656
|
+
)
|
|
657
|
+
const pid = options.pid
|
|
658
|
+
if (pid === undefined) return true
|
|
659
|
+
|
|
660
|
+
const minutes = Number.isFinite(options.waitMinutes) ? options.waitMinutes : 0
|
|
661
|
+
const deadline = minutes > 0 ? Date.now() + minutes * 60000 : 0
|
|
662
|
+
say(minutes > 0 ? ' 最多等 ' + minutes + ' 分钟。超时就放弃,不改任何文件。' : ' 会一直等到退出。')
|
|
663
|
+
say('')
|
|
664
|
+
let waited = 0
|
|
665
|
+
while (isRunning(pid)) {
|
|
666
|
+
if (deadline !== 0 && Date.now() > deadline) {
|
|
667
|
+
say(' ✗ 等了 ' + minutes + ' 分钟,DSH 还没退出。')
|
|
668
|
+
say(' 未改动任何文件。要继续就再运行一次。')
|
|
669
|
+
sayLog()
|
|
670
|
+
return false
|
|
671
|
+
}
|
|
672
|
+
await delay(500)
|
|
673
|
+
waited += 500
|
|
674
|
+
if (waited % 12000 === 0) say(' 仍在等待 DSH 退出 …')
|
|
675
|
+
}
|
|
676
|
+
say(' ✓ DSH 已退出,正在替换 …')
|
|
677
|
+
return true
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* The `.app` bundle that contains an executable, for `open` on macOS.
|
|
682
|
+
*
|
|
683
|
+
* @param {string} exe
|
|
684
|
+
* @returns {string | undefined}
|
|
685
|
+
*/
|
|
686
|
+
function appBundleOf(exe) {
|
|
687
|
+
const at = exe.lastIndexOf('.app' + sep)
|
|
688
|
+
return at === -1 ? undefined : exe.slice(0, at + '.app'.length)
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Start DSH again after a `--restart` swap.
|
|
693
|
+
*
|
|
694
|
+
* The old instance has already exited when this runs, so the shell's
|
|
695
|
+
* single-instance lock cannot swallow the launch and leave a hidden window.
|
|
696
|
+
*
|
|
697
|
+
* @param {{ exe: string | undefined }} options
|
|
698
|
+
*/
|
|
699
|
+
async function relaunchApp(options) {
|
|
700
|
+
const exe = options.exe
|
|
701
|
+
if (exe === undefined) return
|
|
702
|
+
const bundle = process.platform === 'darwin' ? appBundleOf(exe) : undefined
|
|
703
|
+
say(' 正在重新打开 DSH …')
|
|
704
|
+
let failure = ''
|
|
705
|
+
try {
|
|
706
|
+
const child =
|
|
707
|
+
bundle === undefined
|
|
708
|
+
? spawn(exe, [], { detached: true, stdio: 'ignore' })
|
|
709
|
+
: spawn('/usr/bin/open', [bundle], { detached: true, stdio: 'ignore' })
|
|
710
|
+
if (typeof child.unref === 'function') child.unref()
|
|
711
|
+
// A missing program fails asynchronously; without this listener Node would
|
|
712
|
+
// die on the unhandled error and the user would never learn why.
|
|
713
|
+
const started = await new Promise((done) => {
|
|
714
|
+
child.once('spawn', () => done(true))
|
|
715
|
+
child.once('error', (error) => {
|
|
716
|
+
failure = reasonOf(error)
|
|
717
|
+
done(false)
|
|
718
|
+
})
|
|
719
|
+
})
|
|
720
|
+
if (started !== true) throw new Error(failure === '' ? '没能启动' : failure)
|
|
721
|
+
// Give the launcher a moment to take the process over before we exit.
|
|
722
|
+
await delay(400)
|
|
723
|
+
reopened = true
|
|
724
|
+
say(' ✓ 已重新打开 DSH。')
|
|
725
|
+
} catch (error) {
|
|
726
|
+
say(' · 没能自动打开 DSH:' + reasonOf(error))
|
|
727
|
+
say(' 请手动打开它。')
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// ---------------------------------------------------------------------------
|
|
732
|
+
// Commands
|
|
733
|
+
// ---------------------------------------------------------------------------
|
|
734
|
+
|
|
735
|
+
/** @param {string} resources */
|
|
736
|
+
function status(resources) {
|
|
737
|
+
const state = inspect(resources)
|
|
738
|
+
const backup = backupState(resources)
|
|
739
|
+
say(' 安装目录 ' + resources)
|
|
740
|
+
say(' 系统 ' + process.platform + ' / node ' + process.version)
|
|
741
|
+
say(' app.asar ' + plural(state.bytes))
|
|
742
|
+
say(
|
|
743
|
+
' 当前状态 ' +
|
|
744
|
+
(state.patched ? '已开启(persist: 分区)' : state.patchSite ? '未开启(内存分区)' : '补丁点不存在,脚本该更新了'),
|
|
745
|
+
)
|
|
746
|
+
say(
|
|
747
|
+
' 原版备份 ' +
|
|
748
|
+
(backup === 'clean' ? '有,干净' : backup === 'dirty' ? '有,但本身是补丁版(还原不依赖它)' : '无'),
|
|
749
|
+
)
|
|
750
|
+
say(' 可写 ' + (canWrite(resources) ? '是' : '否,需要管理员权限'))
|
|
751
|
+
return state.patched || state.patchSite ? 0 : 1
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* @param {string} resources
|
|
756
|
+
* @param {{ cachePatch: boolean, restart?: boolean, pid?: number, exe?: string, waitMinutes?: number }} options
|
|
757
|
+
*/
|
|
758
|
+
async function apply(resources, options) {
|
|
759
|
+
const state = inspect(resources)
|
|
760
|
+
if (state.patched) {
|
|
761
|
+
say(' 已经开启,无需操作。')
|
|
762
|
+
return 0
|
|
763
|
+
}
|
|
764
|
+
if (!state.patchSite) {
|
|
765
|
+
say(' ✗ 这个桌面壳版本里找不到补丁点。')
|
|
766
|
+
say(' 壳的分区写法变了,本脚本需要更新。未改动任何文件。')
|
|
767
|
+
return 1
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
say(' 正在生成补丁后的 app.asar …')
|
|
771
|
+
const original = readFileSync(state.archive)
|
|
772
|
+
const rewrites = [[PERSIST_FROM, PERSIST_TO]]
|
|
773
|
+
if (options.cachePatch) rewrites.push([CACHE_FROM, CACHE_TO])
|
|
774
|
+
const built = rebuild(original, rewrites)
|
|
775
|
+
const compared = verify(original, built.buffer, (text) => text.includes(PATCH_MARK))
|
|
776
|
+
say(` ✓ 校验通过:${compared} 个文件逐字节一致,只有 ${MAIN_ENTRY} 变了`)
|
|
777
|
+
|
|
778
|
+
const staged = join(resources, STAGED)
|
|
779
|
+
writeFileSync(staged, built.buffer)
|
|
780
|
+
|
|
781
|
+
if (options.restart === true && !(await waitForQuit(options))) {
|
|
782
|
+
discardStaged(staged)
|
|
783
|
+
return 1
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// Park a pristine copy the first time. A backup that is itself patched is
|
|
787
|
+
// worthless as a restore point, so it never gets to overwrite a clean one.
|
|
788
|
+
const keep = backupState(resources) === 'clean' ? undefined : join(resources, BACKUP)
|
|
789
|
+
if (!(await swapIn(state.archive, staged, keep, options))) {
|
|
790
|
+
discardStaged(staged)
|
|
791
|
+
return 1
|
|
792
|
+
}
|
|
793
|
+
if (keep !== undefined) say(' ✓ 原版已留作 ' + BACKUP)
|
|
794
|
+
changed = true
|
|
795
|
+
if (options.restart === true) await relaunchApp(options)
|
|
796
|
+
return 0
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* @param {string} resources
|
|
801
|
+
* @param {{ restart?: boolean, pid?: number, exe?: string, waitMinutes?: number }} [options]
|
|
802
|
+
*/
|
|
803
|
+
async function revert(resources, options = {}) {
|
|
804
|
+
const state = inspect(resources)
|
|
805
|
+
if (!state.patched) {
|
|
806
|
+
say(' 本来就没打补丁,无需还原。')
|
|
807
|
+
return 0
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// Undo the literals rather than restoring a file: the archive in front of us
|
|
811
|
+
// is the only thing that says what is actually there. The cache rewrite is
|
|
812
|
+
// part of the patch, so leaving it behind would keep an 18-byte scar that
|
|
813
|
+
// every future comparison would trip over.
|
|
814
|
+
say(' 正在还原 …')
|
|
815
|
+
const original = readFileSync(state.archive)
|
|
816
|
+
const undo = [[PERSIST_TO, PERSIST_FROM]]
|
|
817
|
+
if (state.cachePatched) undo.push([CACHE_TO, CACHE_FROM])
|
|
818
|
+
let built
|
|
819
|
+
try {
|
|
820
|
+
built = rebuild(original, undo)
|
|
821
|
+
} catch (error) {
|
|
822
|
+
say(' ✗ 无法从当前文件还原:' + reasonOf(error))
|
|
823
|
+
say(' 未改动任何文件。')
|
|
824
|
+
return 1
|
|
825
|
+
}
|
|
826
|
+
let compared
|
|
827
|
+
try {
|
|
828
|
+
compared = verify(
|
|
829
|
+
original,
|
|
830
|
+
built.buffer,
|
|
831
|
+
(text) => !text.includes(PATCH_MARK) && !text.includes(CACHE_MARK) && text.includes(PERSIST_FROM),
|
|
832
|
+
)
|
|
833
|
+
} catch (error) {
|
|
834
|
+
say(' ✗ 校验失败:' + reasonOf(error))
|
|
835
|
+
say(' 未改动任何文件。')
|
|
836
|
+
return 1
|
|
837
|
+
}
|
|
838
|
+
say(` ✓ 校验通过:${compared} 个文件逐字节一致`)
|
|
839
|
+
|
|
840
|
+
const staged = join(resources, STAGED)
|
|
841
|
+
writeFileSync(staged, built.buffer)
|
|
842
|
+
if (options.restart === true && !(await waitForQuit(options))) {
|
|
843
|
+
discardStaged(staged)
|
|
844
|
+
return 1
|
|
845
|
+
}
|
|
846
|
+
if (!(await swapIn(state.archive, staged, join(resources, PATCHED_COPY), options))) {
|
|
847
|
+
discardStaged(staged)
|
|
848
|
+
return 1
|
|
849
|
+
}
|
|
850
|
+
say(' ✓ 补丁版已留作 ' + PATCHED_COPY)
|
|
851
|
+
changed = true
|
|
852
|
+
if (options.restart === true) await relaunchApp(options)
|
|
853
|
+
return 0
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// ---------------------------------------------------------------------------
|
|
857
|
+
// Cache cleanup (the other half of the persistent partition)
|
|
858
|
+
// ---------------------------------------------------------------------------
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* The panel's own workspace identities. Must stay equal to `client.js`
|
|
862
|
+
* `PROVIDERS` and to the Host's `CHAT_WORKSPACES`: the directory name is
|
|
863
|
+
* derived from the string, so a drift here deletes the wrong folder or none.
|
|
864
|
+
*/
|
|
865
|
+
const CHAT_WORKSPACES = [
|
|
866
|
+
'dsh-chat-embed:chat:v1',
|
|
867
|
+
'dsh-chat-embed:doubao:v1',
|
|
868
|
+
'dsh-chat-embed:chatgpt:v1',
|
|
869
|
+
'dsh-chat-embed:minimax:v1',
|
|
870
|
+
'dsh-chat-embed:kimi:v1',
|
|
871
|
+
'dsh-chat-embed:gemini:v1',
|
|
872
|
+
'dsh-chat-embed:grok:v1',
|
|
873
|
+
]
|
|
874
|
+
|
|
875
|
+
/** Directories Chromium recreates on demand; the login never lives in them. */
|
|
876
|
+
const CACHE_DIRS = [
|
|
877
|
+
'Cache',
|
|
878
|
+
'Code Cache',
|
|
879
|
+
'GPUCache',
|
|
880
|
+
'DawnGraphiteCache',
|
|
881
|
+
'DawnWebGPUCache',
|
|
882
|
+
'GrShaderCache',
|
|
883
|
+
'ShaderCache',
|
|
884
|
+
'Shared Dictionary',
|
|
885
|
+
]
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* @param {string} workspace
|
|
889
|
+
* @returns {string} `dsh-sidebar-` plus the same 24 hex chars the patch writes
|
|
890
|
+
*/
|
|
891
|
+
function partitionDirName(workspace) {
|
|
892
|
+
return 'dsh-sidebar-' + createHash('sha256').update(workspace).digest('hex').slice(0, 24)
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** @returns {string[]} candidate Partitions directories */
|
|
896
|
+
function partitionsCandidates() {
|
|
897
|
+
const out = []
|
|
898
|
+
const push = (value) => {
|
|
899
|
+
if (typeof value === 'string' && value !== '' && !out.includes(value)) out.push(value)
|
|
900
|
+
}
|
|
901
|
+
push(process.env.DSH_PARTITIONS)
|
|
902
|
+
const appData =
|
|
903
|
+
process.platform === 'win32'
|
|
904
|
+
? process.env.APPDATA
|
|
905
|
+
: process.platform === 'darwin'
|
|
906
|
+
? join(homedir(), 'Library', 'Application Support')
|
|
907
|
+
: process.env.XDG_CONFIG_HOME !== undefined && process.env.XDG_CONFIG_HOME !== ''
|
|
908
|
+
? process.env.XDG_CONFIG_HOME
|
|
909
|
+
: join(homedir(), '.config')
|
|
910
|
+
if (appData !== undefined && appData !== '') {
|
|
911
|
+
push(join(appData, '@deepseek-ai', 'dsh-desktop', 'Partitions'))
|
|
912
|
+
push(join(appData, 'DeepSeek Harness', 'Partitions'))
|
|
913
|
+
}
|
|
914
|
+
return out
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** @param {string} dir @returns {number} bytes under it */
|
|
918
|
+
function sizeOf(dir) {
|
|
919
|
+
let total = 0
|
|
920
|
+
const walk = (path) => {
|
|
921
|
+
let entries
|
|
922
|
+
try {
|
|
923
|
+
entries = readdirSync(path, { withFileTypes: true })
|
|
924
|
+
} catch (error) {
|
|
925
|
+
void error
|
|
926
|
+
return
|
|
927
|
+
}
|
|
928
|
+
for (const entry of entries) {
|
|
929
|
+
const next = join(path, entry.name)
|
|
930
|
+
if (entry.isDirectory()) walk(next)
|
|
931
|
+
else {
|
|
932
|
+
try {
|
|
933
|
+
total += statSync(next).size
|
|
934
|
+
} catch (error) {
|
|
935
|
+
void error
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
walk(dir)
|
|
941
|
+
return total
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Clear this plugin's partitions, and nothing else under `Partitions`.
|
|
946
|
+
*
|
|
947
|
+
* The patch decides the depth. While it is on, the running session is the
|
|
948
|
+
* persistent one, so only disposable caches go — IndexedDB, Local Storage and
|
|
949
|
+
* `Network` (cookies) stay. While it is off, the shell is using a fresh
|
|
950
|
+
* in-memory partition and these directories are leftovers; the whole seven are
|
|
951
|
+
* removed. An unknown sibling is never a candidate, even if its name starts
|
|
952
|
+
* with `dsh-sidebar-`.
|
|
953
|
+
*
|
|
954
|
+
* @param {string} resources install directory, so the archive — not the panel — decides
|
|
955
|
+
* @returns {number}
|
|
956
|
+
*/
|
|
957
|
+
function cleanChatCache(resources) {
|
|
958
|
+
const state = inspect(resources)
|
|
959
|
+
if (state.patched !== true && state.patched !== false) {
|
|
960
|
+
say(' ✗ 无法判断补丁状态,没有删除任何文件。')
|
|
961
|
+
return 1
|
|
962
|
+
}
|
|
963
|
+
const purge = state.patched !== true
|
|
964
|
+
const base = partitionsCandidates().find((candidate) => existsSync(candidate))
|
|
965
|
+
if (base === undefined) {
|
|
966
|
+
say(' 没有找到 Partitions 目录,无需清理。')
|
|
967
|
+
say(' 找过这些位置:')
|
|
968
|
+
for (const candidate of partitionsCandidates()) say(' ' + candidate)
|
|
969
|
+
return 0
|
|
970
|
+
}
|
|
971
|
+
const allowed = new Set(CHAT_WORKSPACES.map(partitionDirName))
|
|
972
|
+
say(purge ? ' 补丁未开启,将删除这 7 个服务留下的全部分区。' : ' 补丁已开启,只删除缓存,登录保留。')
|
|
973
|
+
say(' ' + base)
|
|
974
|
+
if (purge) say(' 如果 DSH 仍占着这些目录,删不掉的会留在原地。')
|
|
975
|
+
say('')
|
|
976
|
+
let freed = 0
|
|
977
|
+
let stuck = 0
|
|
978
|
+
for (const name of allowed) {
|
|
979
|
+
if (!/^dsh-sidebar-[0-9a-f]{24}$/.test(name)) continue
|
|
980
|
+
const dir = join(base, name)
|
|
981
|
+
if (!existsSync(dir)) continue
|
|
982
|
+
const targets = purge ? [dir] : CACHE_DIRS.map((cacheName) => join(dir, cacheName))
|
|
983
|
+
for (const target of targets) {
|
|
984
|
+
if (!existsSync(target)) continue
|
|
985
|
+
const size = sizeOf(target)
|
|
986
|
+
const label = purge ? name : name + '/' + target.slice(dir.length + 1)
|
|
987
|
+
try {
|
|
988
|
+
rmSync(target, { recursive: true, force: true })
|
|
989
|
+
if (!existsSync(target)) freed += size
|
|
990
|
+
else {
|
|
991
|
+
stuck += size
|
|
992
|
+
say(' · ' + label + ' 仍在')
|
|
993
|
+
}
|
|
994
|
+
} catch (error) {
|
|
995
|
+
stuck += size
|
|
996
|
+
say(' · ' + label + ' 没删掉:' + reasonOf(error))
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
say(' 释放 ' + plural(freed) + (stuck > 0 ? ',仍占用 ' + plural(stuck) : ''))
|
|
1001
|
+
if (!purge) say(' 登录状态、Cookie、Local Storage、IndexedDB 均未改动。')
|
|
1002
|
+
return stuck > 0 ? 1 : 0
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// ---------------------------------------------------------------------------
|
|
1006
|
+
// Elevation
|
|
1007
|
+
// ---------------------------------------------------------------------------
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Re-run this script with administrator rights, waiting for it to finish.
|
|
1011
|
+
*
|
|
1012
|
+
* @param {string[]} argv the original arguments
|
|
1013
|
+
* @returns {boolean} whether an elevated run completed successfully
|
|
1014
|
+
*/
|
|
1015
|
+
function relaunchElevated(argv) {
|
|
1016
|
+
const args = [SELF, ...argv]
|
|
1017
|
+
try {
|
|
1018
|
+
if (process.platform === 'win32') {
|
|
1019
|
+
const list = args.map((value) => `'${value.replace(/'/g, "''")}'`).join(',')
|
|
1020
|
+
const command = `Start-Process -FilePath '${process.execPath.replace(/'/g, "''")}' -ArgumentList @(${list}) -Verb RunAs -Wait`
|
|
1021
|
+
const result = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command], {
|
|
1022
|
+
stdio: 'inherit',
|
|
1023
|
+
})
|
|
1024
|
+
return result.status === 0
|
|
1025
|
+
}
|
|
1026
|
+
if (process.platform === 'darwin') {
|
|
1027
|
+
const command = args.map((value) => `'${value.replace(/'/g, "'\\''")}'`).join(' ')
|
|
1028
|
+
const script = `do shell script "${process.execPath} ${command.replace(/"/g, '\\"')}" with administrator privileges`
|
|
1029
|
+
const result = spawnSync('osascript', ['-e', script], { stdio: 'inherit' })
|
|
1030
|
+
return result.status === 0
|
|
1031
|
+
}
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
void error
|
|
1034
|
+
}
|
|
1035
|
+
return false
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// ---------------------------------------------------------------------------
|
|
1039
|
+
// Entry
|
|
1040
|
+
// ---------------------------------------------------------------------------
|
|
1041
|
+
|
|
1042
|
+
/** @param {string[]} argv */
|
|
1043
|
+
function parseArgs(argv) {
|
|
1044
|
+
const options = {
|
|
1045
|
+
action: 'menu',
|
|
1046
|
+
resources: undefined,
|
|
1047
|
+
yes: false,
|
|
1048
|
+
cachePatch: true,
|
|
1049
|
+
elevated: false,
|
|
1050
|
+
help: false,
|
|
1051
|
+
restart: false,
|
|
1052
|
+
pid: undefined,
|
|
1053
|
+
exe: undefined,
|
|
1054
|
+
waitMinutes: 10,
|
|
1055
|
+
task: undefined,
|
|
1056
|
+
}
|
|
1057
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
1058
|
+
const arg = argv[index]
|
|
1059
|
+
if (arg === 'apply' || arg === 'on') options.action = 'apply'
|
|
1060
|
+
else if (arg === 'revert' || arg === 'off') options.action = 'revert'
|
|
1061
|
+
else if (arg === 'status') options.action = 'status'
|
|
1062
|
+
else if (arg === 'cache') options.action = 'cache'
|
|
1063
|
+
else if (arg === '--resources') options.resources = argv[++index]
|
|
1064
|
+
else if (arg === '--yes' || arg === '-y') options.yes = true
|
|
1065
|
+
else if (arg === '--no-cache-patch') options.cachePatch = false
|
|
1066
|
+
else if (arg === '--elevated') options.elevated = true
|
|
1067
|
+
else if (arg === '--restart') options.restart = true
|
|
1068
|
+
else if (arg === '--pid') options.pid = Number(argv[++index])
|
|
1069
|
+
else if (arg === '--exe') options.exe = argv[++index]
|
|
1070
|
+
else if (arg === '--wait-minutes') options.waitMinutes = Number(argv[++index])
|
|
1071
|
+
else if (arg === '--task') options.task = argv[++index]
|
|
1072
|
+
else if (arg === '--help' || arg === '-h') options.help = true
|
|
1073
|
+
else {
|
|
1074
|
+
console.error('unknown argument: ' + arg)
|
|
1075
|
+
options.help = true
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
pendingTask = options.task
|
|
1079
|
+
return options
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
function usage() {
|
|
1083
|
+
say('')
|
|
1084
|
+
say(' DSH「重启保持登录」补丁 — 安装或撤掉')
|
|
1085
|
+
say('')
|
|
1086
|
+
say(' node shell-patch.mjs [status|apply|revert] [选项]')
|
|
1087
|
+
say('')
|
|
1088
|
+
say(' status 只报告状态,不改动任何文件')
|
|
1089
|
+
say(' apply 开启:让内嵌聊天的登录跨重启保留')
|
|
1090
|
+
say(' revert 关闭:还原原版 app.asar')
|
|
1091
|
+
say(' cache 清理本面板的分区(开启时只清缓存,关闭时删除残留登录)')
|
|
1092
|
+
say(' (不带命令时打开菜单)')
|
|
1093
|
+
say('')
|
|
1094
|
+
say(' --resources <dir> 指定含 app.asar 的安装目录')
|
|
1095
|
+
say(' --yes 不询问,直接执行')
|
|
1096
|
+
say(' --no-cache-patch 保留磁盘缓存,只让分区持久')
|
|
1097
|
+
say(' --restart 等 DSH 退出后再替换,并重新打开它')
|
|
1098
|
+
say(' --pid <n> --restart 等待的 DSH 进程')
|
|
1099
|
+
say(' --exe <path> --restart 完成后要重新打开的程序')
|
|
1100
|
+
say(' --wait-minutes <n> --restart 最多等多久退出(0 = 一直等,默认 10)')
|
|
1101
|
+
say('')
|
|
1102
|
+
say(' 改完请重新打开 DSH 使其生效。')
|
|
1103
|
+
say('')
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* @param {string} resources
|
|
1108
|
+
* @param {{ cachePatch: boolean, yes: boolean }} options
|
|
1109
|
+
*/
|
|
1110
|
+
async function menu(resources, options) {
|
|
1111
|
+
const state = inspect(resources)
|
|
1112
|
+
say('')
|
|
1113
|
+
say(' 安装目录:' + resources)
|
|
1114
|
+
say(' 当前状态:' + (state.patched ? '已开启' : state.patchSite ? '未开启' : '补丁点不存在,脚本该更新了'))
|
|
1115
|
+
say('')
|
|
1116
|
+
say(' 1) 开启')
|
|
1117
|
+
say(' 2) 关闭')
|
|
1118
|
+
say(' 3) 只看状态')
|
|
1119
|
+
say(' 4) 清理本面板缓存')
|
|
1120
|
+
say(' 0) 退出')
|
|
1121
|
+
say('')
|
|
1122
|
+
const choice = await ask('选择 [0-4]:')
|
|
1123
|
+
if (choice === '' || choice === '3') return status(resources)
|
|
1124
|
+
if (choice === '0') return 0
|
|
1125
|
+
if (choice === '1') {
|
|
1126
|
+
if (state.patched) {
|
|
1127
|
+
say(' 已经开启,无需操作。')
|
|
1128
|
+
return 0
|
|
1129
|
+
}
|
|
1130
|
+
say('')
|
|
1131
|
+
say(' 这会改写 DSH 桌面版的 app.asar。DSH 升级会覆盖它,到时再运行一次即可。')
|
|
1132
|
+
const answer = options.yes ? 'y' : await ask(' 继续?[y/N]')
|
|
1133
|
+
if (answer.toLowerCase() !== 'y') {
|
|
1134
|
+
say(' 已取消。')
|
|
1135
|
+
return 0
|
|
1136
|
+
}
|
|
1137
|
+
return apply(resources, options)
|
|
1138
|
+
}
|
|
1139
|
+
if (choice === '2') {
|
|
1140
|
+
if (!state.patched) {
|
|
1141
|
+
say(' 本来就没打补丁,无需还原。')
|
|
1142
|
+
return 0
|
|
1143
|
+
}
|
|
1144
|
+
const answer = options.yes ? 'y' : await ask(' 关闭后每次重启都要重新登录。继续?[y/N]')
|
|
1145
|
+
if (answer.toLowerCase() !== 'y') {
|
|
1146
|
+
say(' 已取消。')
|
|
1147
|
+
return 0
|
|
1148
|
+
}
|
|
1149
|
+
return revert(resources)
|
|
1150
|
+
}
|
|
1151
|
+
if (choice === '4') return cleanChatCache(resources)
|
|
1152
|
+
say(' 没有这个选项。')
|
|
1153
|
+
return 1
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
async function main() {
|
|
1157
|
+
const options = parseArgs(process.argv.slice(2))
|
|
1158
|
+
try {
|
|
1159
|
+
if (options.help) {
|
|
1160
|
+
usage()
|
|
1161
|
+
return 0
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// Mode follows the archive, not the panel: a click that still thinks the
|
|
1165
|
+
// patch is off must not wipe a login the running shell is using. That
|
|
1166
|
+
// decision needs the install directory, even though the files themselves
|
|
1167
|
+
// live under the user-data Partitions folder.
|
|
1168
|
+
if (options.action === 'cache') {
|
|
1169
|
+
const resources = options.resources !== undefined ? resolve(options.resources) : detectResources()
|
|
1170
|
+
say('')
|
|
1171
|
+
say(' DSH 聊天页缓存清理')
|
|
1172
|
+
if (resources === undefined || !existsSync(join(resources, 'app.asar'))) {
|
|
1173
|
+
say(' ✗ 无法判断补丁状态,没有删除任何文件。')
|
|
1174
|
+
say('')
|
|
1175
|
+
return 1
|
|
1176
|
+
}
|
|
1177
|
+
return cleanChatCache(resources)
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
const resources = options.resources !== undefined ? resolve(options.resources) : detectResources()
|
|
1181
|
+
if (resources === undefined) {
|
|
1182
|
+
say('')
|
|
1183
|
+
say(' ✗ 没有找到 DSH 安装目录。常见位置:')
|
|
1184
|
+
for (const candidate of resourcesCandidates()) say(' ' + candidate)
|
|
1185
|
+
say('')
|
|
1186
|
+
say(' 装在别处请传进来:')
|
|
1187
|
+
say(' node shell-patch.mjs apply --resources "<安装目录>/resources"')
|
|
1188
|
+
say('')
|
|
1189
|
+
return 1
|
|
1190
|
+
}
|
|
1191
|
+
if (!existsSync(join(resources, 'app.asar'))) {
|
|
1192
|
+
say('')
|
|
1193
|
+
say(' ✗ ' + resources + ' 里没有 app.asar,不像是 DSH 的安装目录。')
|
|
1194
|
+
say('')
|
|
1195
|
+
return 1
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// Anything that writes needs the directory to accept a file. Ask for
|
|
1199
|
+
// elevation up front rather than halfway through a swap.
|
|
1200
|
+
const writing = options.action === 'apply' || options.action === 'revert' || options.action === 'menu'
|
|
1201
|
+
if (writing && !options.elevated && !canWrite(resources)) {
|
|
1202
|
+
say('')
|
|
1203
|
+
say(' 安装目录不可写,需要管理员权限。正在请求提权 …')
|
|
1204
|
+
if (relaunchElevated(process.argv.slice(2))) return 0
|
|
1205
|
+
say('')
|
|
1206
|
+
say(' ✗ 没能提权。请手动以管理员身份运行:')
|
|
1207
|
+
if (process.platform === 'win32') say(' 右键 shell-patch.cmd →「以管理员身份运行」')
|
|
1208
|
+
else say(' sudo node "' + SELF + '" ' + (options.action === 'menu' ? '' : options.action))
|
|
1209
|
+
say('')
|
|
1210
|
+
return 1
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// A second click cannot stop the patcher already waiting: the task that
|
|
1214
|
+
// started it has exited, so only the lock can keep two writers apart.
|
|
1215
|
+
if (writing && options.restart === true && !claimPatcher(resources)) {
|
|
1216
|
+
say('')
|
|
1217
|
+
say(' 已有一个补丁进程在等这次退出,这一次不再另起。')
|
|
1218
|
+
say('')
|
|
1219
|
+
return 0
|
|
1220
|
+
}
|
|
1221
|
+
if (writing) openLog(resources)
|
|
1222
|
+
|
|
1223
|
+
say('')
|
|
1224
|
+
say(' DSH「重启保持登录」补丁')
|
|
1225
|
+
if (patchLog !== undefined) say(' 日志 ' + patchLog)
|
|
1226
|
+
|
|
1227
|
+
let code
|
|
1228
|
+
if (options.action === 'status') code = status(resources)
|
|
1229
|
+
else if (options.action === 'apply') code = await apply(resources, options)
|
|
1230
|
+
else if (options.action === 'revert') code = await revert(resources, options)
|
|
1231
|
+
else if (options.action === 'cache') code = cleanChatCache(resources)
|
|
1232
|
+
else code = await menu(resources, options)
|
|
1233
|
+
|
|
1234
|
+
if (code === 0 && changed) {
|
|
1235
|
+
say('')
|
|
1236
|
+
say(' ──────────────────────────────────────')
|
|
1237
|
+
say(reopened ? ' ✓ 完成,DSH 已重新打开。' : ' ✓ 完成。请重新打开 DSH 使其生效。')
|
|
1238
|
+
say(' ──────────────────────────────────────')
|
|
1239
|
+
}
|
|
1240
|
+
say('')
|
|
1241
|
+
return code
|
|
1242
|
+
} finally {
|
|
1243
|
+
releasePatcher()
|
|
1244
|
+
forgetTask(options.task)
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
main().then(
|
|
1249
|
+
(code) => {
|
|
1250
|
+
process.exitCode = code
|
|
1251
|
+
},
|
|
1252
|
+
(error) => {
|
|
1253
|
+
say('')
|
|
1254
|
+
say(' ✗ ' + reasonOf(error))
|
|
1255
|
+
say('')
|
|
1256
|
+
releasePatcher()
|
|
1257
|
+
forgetTask(pendingTask)
|
|
1258
|
+
process.exitCode = 1
|
|
1259
|
+
},
|
|
1260
|
+
)
|