@karoy/dsh-wsl-desktop 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import { createRequire } from 'node:module'
5
+ import { spawnSync } from 'node:child_process'
6
+
7
+ const require$ = createRequire(import.meta.url)
8
+ const yaml = require$('yaml')
9
+
10
+ /** Windows temp file path spoken in WSL terms (`C:\...` → `/mnt/c/...`). */
11
+ function wslTempPath() {
12
+ const tmp = path.join(os.tmpdir(), 'dsh-wsl-patch-merge.yml')
13
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(tmp)
14
+ return match === null ? tmp : '/mnt/' + match[1].toLowerCase() + '/' + match[2].replaceAll('\\', '/')
15
+ }
16
+
17
+ function readDesktopProfile() {
18
+ const manifest = path.join(os.homedir(), '.dsh', 'profiles', 'desktop', 'package.json')
19
+ const data = JSON.parse(fs.readFileSync(manifest, 'utf8'))
20
+ return { deps: data.dependencies ?? {}, bundles: data.dsh?.profile?.bundles ?? [] }
21
+ }
22
+
23
+ function readWslPatch() {
24
+ const result = spawnSync('wsl.exe', ['--', 'bash', '-s'], {
25
+ input: 'cat "$HOME/.dsh/profiles/web/cordis.patch.yml"',
26
+ encoding: 'utf8',
27
+ timeout: 30000,
28
+ maxBuffer: 4 * 1024 * 1024,
29
+ windowsHide: true,
30
+ })
31
+ if (result.status !== 0) throw new Error('wsl-desktop: cannot read the WSL patch: ' + String(result.stderr))
32
+ return yaml.parse(String(result.stdout))
33
+ }
34
+
35
+ function writeWslPatch(documents) {
36
+ const text = yaml.stringify(documents)
37
+ const winTmp = path.join(os.tmpdir(), 'dsh-wsl-patch-merge.yml')
38
+ fs.writeFileSync(winTmp, text, 'utf8')
39
+ const result = spawnSync('wsl.exe', ['--', 'bash', '-s'], {
40
+ input: 'cat "' + wslTempPath() + '" > "$HOME/.dsh/profiles/web/cordis.patch.yml"',
41
+ encoding: 'utf8',
42
+ timeout: 30000,
43
+ windowsHide: true,
44
+ })
45
+ try { fs.unlinkSync(winTmp) } catch { /* ignore */ }
46
+ if (result.status !== 0) throw new Error('wsl-desktop: cannot write the WSL patch: ' + String(result.stderr))
47
+ }
48
+
49
+ /**
50
+ * Copy every non-link plugin's profile rows (id/name/enabled/config) from the
51
+ * Windows desktop patch into the WSL web patch, honoring the enable state:
52
+ * plugins not enabled on Windows get `enabled: false` rows and stay out of the
53
+ * WSL bundle list. Shipped `@deepseek-ai/*` and local `link:` packages are not
54
+ * touched.
55
+ * @returns whether the WSL patch changed.
56
+ */
57
+ export function mergePluginConfigs(onlyNames) {
58
+ const { deps, bundles } = readDesktopProfile()
59
+ const enabledSet = new Set(bundles.filter((name) => !name.startsWith('@deepseek-ai/')))
60
+ const names = (onlyNames ?? Object.keys(deps))
61
+ .filter((name) => deps[name] !== undefined && !deps[name].toString().startsWith('link:'))
62
+ .filter((name) => !name.startsWith('@deepseek-ai/') && !name.startsWith('@local/') && !name.includes('dsh-wsl-desktop'))
63
+
64
+ if (names.length === 0) return false
65
+
66
+ const desktopRows = yaml.parse(fs.readFileSync(path.join(os.homedir(), '.dsh', 'profiles', 'desktop', 'cordis.patch.yml'), 'utf8')) ?? []
67
+ const wslRows = readWslPatch() ?? []
68
+ const wslById = new Map(wslRows.filter((row) => row && typeof row.id === 'string').map((row) => [row.id, row]))
69
+ let changed = false
70
+
71
+ for (const name of names) {
72
+ const fromDesktop = desktopRows.filter((row) => row && row.name === name)
73
+ const enabled = enabledSet.has(name)
74
+ if (fromDesktop.length === 0) continue
75
+ for (const row of fromDesktop) {
76
+ const copy = { id: row.id, name: row.name }
77
+ if (row.enabled !== undefined || !enabled) copy.enabled = row.enabled === true ? true : enabled
78
+ if (row.config !== undefined) copy.config = row.config
79
+ const existing = wslById.get(row.id)
80
+ if (existing === undefined) {
81
+ wslRows.push(copy)
82
+ wslById.set(row.id, copy)
83
+ changed = true
84
+ } else {
85
+ const prev = JSON.stringify(existing)
86
+ Object.keys(existing).forEach((key) => delete existing[key])
87
+ Object.assign(existing, copy)
88
+ if (JSON.stringify(existing) !== prev) changed = true
89
+ }
90
+ }
91
+ }
92
+
93
+ if (changed) writeWslPatch(wslRows)
94
+ return changed
95
+ }
package/lib/setup.js ADDED
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Install a patched DSH Desktop copy that proxies its Host connection to a DSH
3
+ * Host running inside WSL. Nothing in the original installation is modified:
4
+ * the copy lives in `installDir` and keeps its own Electron userData and DSH_HOME.
5
+ *
6
+ * `mode: 'proxy'` keeps the dsh-app://app page (desktop chrome, native dialogs)
7
+ * and swaps only the Host URL/cookie; it requires the WSL Host to serve the
8
+ * same profile/plugin graph as the copy's local child Host.
9
+ * `mode: 'direct'` loads the WSL Host page in the main window (no desktop chrome,
10
+ * no profile parity requirement).
11
+ *
12
+ * @module @karoy/dsh-wsl-desktop/setup
13
+ */
14
+ import { spawnSync } from 'node:child_process'
15
+ import fs from 'node:fs'
16
+ import { createRequire } from 'node:module'
17
+ import os from 'node:os'
18
+ import path from 'node:path'
19
+ import { writeStamp } from './state.js'
20
+
21
+ const require$ = createRequire(import.meta.url)
22
+
23
+ const MARKER = 'wsl-desktop patch'
24
+ const HELPER_MARKER = 'wslDesktopRequire'
25
+
26
+ export const DEFAULT_CONFIG = {
27
+ installDir: '',
28
+ userDataDirName: 'DeepSeek Harness WSL',
29
+ port: 3080,
30
+ distro: '',
31
+ autoInstall: true,
32
+ mode: 'proxy',
33
+ autoRun: true,
34
+ autoSetup: true,
35
+ autoLaunch: false,
36
+ syncWslPlugins: true,
37
+ }
38
+
39
+ /** Default copy location: `%LOCALAPPDATA%\\DeepSeek Harness WSL Desktop` (any drive, per user). */
40
+ export function defaultInstallDir() {
41
+ const base = process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData', 'Local')
42
+ return path.join(base, 'DeepSeek Harness WSL Desktop')
43
+ }
44
+
45
+ /** Merge plugin config with defaults and resolve the copy directory. */
46
+ export function resolveConfig(pluginConfig = {}) {
47
+ const config = { ...DEFAULT_CONFIG, ...pluginConfig }
48
+ if (config.installDir === '' || config.installDir === undefined) config.installDir = defaultInstallDir()
49
+ return config
50
+ }
51
+
52
+ function log(line) {
53
+ console.log('[wsl-desktop] ' + line)
54
+ }
55
+
56
+ function run(command, args, options) {
57
+ log(command + ' ' + args.join(' '))
58
+ const result = spawnSync(command, args, { stdio: 'inherit', windowsHide: true, ...options })
59
+ if (result.error !== undefined) throw result.error
60
+ return result.status ?? 0
61
+ }
62
+
63
+ /** Locate the installed Desktop application (the directory holding resources/app.asar). */
64
+ export function resolveSourceDir(configured) {
65
+ const candidates = []
66
+ if (configured) candidates.push(configured)
67
+ const exeDir = path.dirname(process.execPath)
68
+ candidates.push(exeDir)
69
+ if (process.env.DSH_DESKTOP_DIR) candidates.push(process.env.DSH_DESKTOP_DIR)
70
+ if (process.env.LOCALAPPDATA) candidates.push(path.join(process.env.LOCALAPPDATA, 'Programs', 'DeepSeek Harness'))
71
+ if (process.env.ProgramFiles) candidates.push(path.join(process.env.ProgramFiles, 'DeepSeek Harness'))
72
+ for (const candidate of candidates) {
73
+ if (fs.existsSync(path.join(candidate, 'resources', 'app.asar'))) return candidate
74
+ }
75
+ throw new Error('wsl-desktop: cannot find the Desktop install (resources/app.asar)')
76
+ }
77
+
78
+ function copyInstall(sourceDir, installDir) {
79
+ if (fs.existsSync(installDir)) {
80
+ log('removing previous copy ' + installDir)
81
+ fs.rmSync(installDir, { recursive: true, force: true })
82
+ }
83
+ fs.mkdirSync(installDir, { recursive: true })
84
+ // Skip what the copy does not need: app.asar (extracted straight from the
85
+ // installed app) and its unpacked payload (extractAll pulls those files from
86
+ // the source's app.asar.unpacked). Together they are ~450 MB of the ~1 GB
87
+ // install, and skipping the archive also avoids racing its rename (EBUSY).
88
+ const status = run('robocopy', [
89
+ sourceDir, installDir, '/E', '/NFL', '/NDL', '/NJH', '/NP',
90
+ '/XF', 'app.asar', '/XD', 'app.asar.unpacked',
91
+ ])
92
+ if (status > 7) throw new Error('wsl-desktop: robocopy failed with ' + String(status))
93
+ }
94
+
95
+ function extractAsar(sourceDir, resourcesDir) {
96
+ const sourceAsar = path.join(sourceDir, 'resources', 'app.asar')
97
+ if (!fs.existsSync(sourceAsar)) throw new Error('wsl-desktop: source resources/app.asar is missing')
98
+ const app = path.join(resourcesDir, 'app')
99
+ const mainPath = path.join(app, 'lib', 'main.js')
100
+ if (!fs.existsSync(mainPath)) {
101
+ fs.rmSync(app, { recursive: true, force: true })
102
+ require$('@electron/asar').extractAll(sourceAsar, app)
103
+ }
104
+ if (!fs.existsSync(mainPath)) throw new Error('wsl-desktop: asar extraction produced no app/lib/main.js')
105
+ }
106
+
107
+ export function patchMain(mainPath, config) {
108
+ let text = fs.readFileSync(mainPath, 'utf8')
109
+
110
+ if (!text.includes(HELPER_MARKER)) {
111
+ const anchor = 'import { REMOTE_STREAM_MUX_PATH, parseRemoteStreamServerMessage } from "@deepseek-ai/dsh-api-gateway/stream-protocol";\n'
112
+ if (!text.includes(anchor)) throw new Error('wsl-desktop: import anchor not found in main.js')
113
+ const helper = anchor + `/* ---- ${MARKER} ---- */
114
+ const wslDesktopRequire = createRequire(import.meta.url);
115
+ function desktopWslUrl() {
116
+ if (process.env.DSH_WSL_DESKTOP !== "1") return null;
117
+ try { return wslDesktopRequire("./wsl-remote.cjs").remoteUrl(); }
118
+ catch (error) { console.error("wsl-desktop: WSL Host unavailable, using local Host", error); return null; }
119
+ }
120
+ if (process.env.DSH_WSL_DESKTOP === "1") {
121
+ try { app.setPath("userData", join(app.getPath("appData"), ${JSON.stringify(config.userDataDirName)})); }
122
+ catch (error) { console.error("wsl-desktop: userData override failed", error); }
123
+ }
124
+ /* ---- end ${MARKER} ---- */
125
+ `
126
+ text = text.replace(anchor, helper)
127
+ }
128
+
129
+ const readyLine = 'const ready = await host.start();'
130
+ const readyCount = text.split(readyLine).length - 1
131
+ if (readyCount !== 1) throw new Error('wsl-desktop: expected one host.start() site, found ' + String(readyCount))
132
+
133
+ if (config.mode === 'direct') {
134
+ if (!text.includes('DSH_WSL_DIRECT')) {
135
+ const target = 'navigateMain(applicationUrl)'
136
+ const sites = text.split(target).length - 1
137
+ if (sites !== 4) throw new Error('wsl-desktop: expected 4 navigation sites, found ' + String(sites))
138
+ text = text.split(target).join('navigateMain(await desktopWslUrl() ?? applicationUrl)')
139
+ text = text.replace(
140
+ 'openInitialWindow() : navigateMain(await desktopWslUrl() ?? applicationUrl)',
141
+ 'openInitialWindow() : navigateMain(desktopWslUrl() ?? applicationUrl)',
142
+ )
143
+ text = text.replace(
144
+ 'webPreferences: {\n\t\t\tpreload,\n\t\t\tnodeIntegration: false,',
145
+ 'webPreferences: {\n\t\t\tpreload: process.env.DSH_WSL_DESKTOP === "1" ? void 0 : preload,\n\t\t\tnodeIntegration: false,',
146
+ )
147
+ text = text.replace(
148
+ '...process.platform === "win32" && primary ? {\n\t\t\tbackgroundColor: chromeFallbackFill(),\n\t\t\ttitleBarStyle: "hidden",',
149
+ '...process.platform === "win32" && primary ? (process.env.DSH_WSL_DESKTOP === "1" ? {\n\t\t\tbackgroundColor: chromeFallbackFill(),\n\t\t\t/* DSH_WSL_DIRECT */\n\t\t} : {\n\t\t\tbackgroundColor: chromeFallbackFill(),\n\t\t\ttitleBarStyle: "hidden",',
150
+ )
151
+ text = text.replace(
152
+ '\t\t\t\tcolor: chromeFallbackFill(),\n\t\t\t\tsymbolColor: nativeTheme.shouldUseDarkColors ? "#f9fafb" : "#0f1115"\n\t\t\t}\n\t\t} : {},',
153
+ '\t\t\t\tcolor: chromeFallbackFill(),\n\t\t\t\tsymbolColor: nativeTheme.shouldUseDarkColors ? "#f9fafb" : "#0f1115"\n\t\t\t}\n\t\t}) : {},',
154
+ )
155
+ text = text.replace(
156
+ '\tconst refreshApplicationMenu = () => {\n\t\tMenu.setApplicationMenu(',
157
+ '\tconst refreshApplicationMenu = () => {\n\t\tif (process.env.DSH_WSL_DESKTOP === "1") { Menu.setApplicationMenu(null); tray?.relabel(); return; }\n\t\t/* DSH_WSL_DIRECT */\n\t\tMenu.setApplicationMenu(',
158
+ )
159
+ }
160
+ } else if (!text.includes('/* DSH_WSL_PROXY */')) {
161
+ const injection = readyLine + `
162
+ \t\t\t\t/* DSH_WSL_PROXY */
163
+ \t\t\t\tif (process.env.DSH_WSL_DESKTOP === "1") { const wslUrl = desktopWslUrl(); if (wslUrl !== null) ready.url = wslUrl; }`
164
+ text = text.replace(readyLine, injection)
165
+ }
166
+
167
+ if (config.mode !== 'direct' && !text.includes('/* DSH_WSL_INJECTIONS */')) {
168
+ const cookieLine = 'const cookie = await authenticateWebHost(ready.url);'
169
+ const sites = text.split(cookieLine).length - 1
170
+ if (sites !== 1) throw new Error('wsl-desktop: expected one authenticateWebHost site, found ' + String(sites))
171
+ text = text.replace(cookieLine, cookieLine + `
172
+ \t\t\t\t/* DSH_WSL_INJECTIONS */
173
+ \t\t\t\tif (process.env.DSH_WSL_DESKTOP === "1") {
174
+ \t\t\t\t\ttry {
175
+ \t\t\t\t\t\tconst pageHtml = await (await fetch(new URL("/", ready.url), { headers: { cookie } })).text();
176
+ \t\t\t\t\t\tconst rows = [];
177
+ \t\t\t\t\t\tconst bodyAt = pageHtml.search(/<body(?:\\s[^>]*)?>/i);
178
+ \t\t\t\t\t\tconst tagRe = /<(script|style|link)([^>]*)>([\\s\\S]*?)<\\/\\1>/gi;
179
+ \t\t\t\t\t\tlet tagMatch;
180
+ \t\t\t\t\t\twhile ((tagMatch = tagRe.exec(pageHtml)) !== null) {
181
+ \t\t\t\t\t\t\tconst tag = tagMatch[1].toLowerCase();
182
+ \t\t\t\t\t\t\tconst attrs = tagMatch[2];
183
+ \t\t\t\t\t\t\tconst inner = tagMatch[3];
184
+ \t\t\t\t\t\t\tconst placement = bodyAt !== -1 && tagMatch.index > bodyAt ? "body" : "head";
185
+ \t\t\t\t\t\t\tif (tag === "script") {
186
+ \t\t\t\t\t\t\t\tif (/\\btype\\s*=\\s*["']module["']/i.test(attrs)) continue;
187
+ \t\t\t\t\t\t\t\tif (inner.indexOf("__DSH_BOOT_READY__") !== -1) continue;
188
+ \t\t\t\t\t\t\t\tconst srcMatch = /\\bsrc\\s*=\\s*["']([^"']+)["']/i.exec(attrs);
189
+ \t\t\t\t\t\t\t\tif (srcMatch !== null) rows.push({ kind: "script-src", placement, src: srcMatch[1].replace(/&amp;/g, "&") });
190
+ \t\t\t\t\t\t\t\telse if (inner.trim() !== "") rows.push({ kind: "script", placement, text: inner });
191
+ \t\t\t\t\t\t\t} else if (tag === "style") {
192
+ \t\t\t\t\t\t\t\trows.push({ kind: "style", text: inner });
193
+ \t\t\t\t\t\t\t} else {
194
+ \t\t\t\t\t\t\t\tconst rel = /\\brel\\s*=\\s*["']([^"']+)["']/i.exec(attrs);
195
+ \t\t\t\t\t\t\t\tif (rel === null) continue;
196
+ \t\t\t\t\t\t\t\tif (rel[1].toLowerCase() === "stylesheet") rows.push({ kind: "html", placement, html: tagMatch[0] });
197
+ \t\t\t\t\t\t\t\telse if (rel[1].toLowerCase() === "preload") {
198
+ \t\t\t\t\t\t\t\t\tconst href = /\\bhref\\s*=\\s*["']([^"']+)["']/i.exec(attrs);
199
+ \t\t\t\t\t\t\t\t\tif (href !== null) rows.push({ kind: "script-preload", src: href[1].replace(/&amp;/g, "&") });
200
+ \t\t\t\t\t\t\t\t}
201
+ \t\t\t\t\t\t\t}
202
+ \t\t\t\t\t\t}
203
+ \t\t\t\t\t\tif (rows.length > 0) ready.injections = rows;
204
+ \t\t\t\t\t} catch (error) { console.error("wsl-desktop: injection bridge failed", error); }
205
+ \t\t\t\t/* DSH_WSL_RUNNING */
206
+ \t\t\t\tif (process.env.DSH_WSL_DESKTOP === "1" && process.env.DSH_WSL_MODE !== "direct") {
207
+ \t\t\t\t\ttry {
208
+ \t\t\t\t\t\tconst marker = join(app.getAppPath(), "..", "..", ".dsh-wsl-running.json");
209
+ \t\t\t\t\t\twriteFileSync(marker, JSON.stringify({ mode: "proxy", pid: process.pid, at: new Date().toISOString() }));
210
+ \t\t\t\t\t} catch (error) { console.error("wsl-desktop: running marker failed", error); }
211
+ \t\t\t\t}
212
+ \t\t\t\t}`)
213
+ }
214
+
215
+ fs.writeFileSync(mainPath, text)
216
+ }
217
+
218
+ function installHelper(resourcesDir) {
219
+ const source = new URL('./wsl-remote.cjs', import.meta.url)
220
+ const target = path.join(resourcesDir, 'app', 'lib', 'wsl-remote.cjs')
221
+ fs.copyFileSync(source, target)
222
+ }
223
+
224
+ function writeLaunchers(installDir, config) {
225
+ const launcher = `@echo off
226
+ rem Launch the WSL-hosted DSH Desktop proxy (${config.mode}); the original install is untouched.
227
+ set ELECTRON_RUN_AS_NODE=
228
+ set DSH_WSL_DESKTOP=1
229
+ set DSH_WSL_MODE=${config.mode}
230
+ set DSH_WSL_PORT=${String(config.port)}
231
+ set DSH_WSL_DISTRO=${config.distro ?? ''}
232
+ set DSH_WSL_AUTOINSTALL=${config.autoInstall ? '1' : '0'}
233
+ set DSH_HOME=%~dp0dsh-home
234
+ start "" "%~dp0DeepSeek Harness.exe"
235
+ `
236
+ fs.writeFileSync(path.join(installDir, '启动-WSL-Desktop.cmd'), launcher)
237
+
238
+ const rollback = `@echo off
239
+ rem Remove the WSL Desktop copy and its isolated Electron profile.
240
+ rmdir /s /q "%~dp0"
241
+ rmdir /s /q "%APPDATA%\\${config.userDataDirName}"
242
+ `
243
+ fs.writeFileSync(path.join(installDir, '卸载-WSL-Desktop.cmd'), rollback)
244
+ }
245
+
246
+ /**
247
+ * Install (or reinstall) the patched copy.
248
+ * @returns a short summary for the command result.
249
+ */
250
+ export function setup(pluginConfig = {}) {
251
+ const config = resolveConfig(pluginConfig)
252
+ const sourceDir = resolveSourceDir(config.sourceDir)
253
+ const installDir = config.installDir
254
+ log('source: ' + sourceDir + ' -> ' + installDir + ' (mode ' + config.mode + ')')
255
+
256
+ copyInstall(sourceDir, installDir)
257
+ const resourcesDir = path.join(installDir, 'resources')
258
+ extractAsar(sourceDir, resourcesDir)
259
+ const mainPath = path.join(resourcesDir, 'app', 'lib', 'main.js')
260
+ patchMain(mainPath, config)
261
+ installHelper(resourcesDir)
262
+ writeLaunchers(installDir, config)
263
+ writeStamp(installDir, config)
264
+
265
+ return [
266
+ `已安装:${installDir}(mode=${config.mode})`,
267
+ '启动:双击 启动-WSL-Desktop.cmd(会复用/启动 WSL 内的 DSH Host)',
268
+ '卸载:双击 卸载-WSL-Desktop.cmd,或删除该目录与 %APPDATA%\\' + config.userDataDirName,
269
+ ].join('\n')
270
+ }
271
+
272
+ /** @returns whether the copy is installed and which mode it carries. */
273
+ export function status(pluginConfig = {}) {
274
+ const config = resolveConfig(pluginConfig)
275
+ const mainPath = path.join(config.installDir, 'resources', 'app', 'lib', 'main.js')
276
+ if (!fs.existsSync(mainPath)) return '未安装:' + config.installDir
277
+ const text = fs.readFileSync(mainPath, 'utf8')
278
+ const mode = text.includes('DSH_WSL_PROXY') ? 'proxy' : text.includes('DSH_WSL_DIRECT') ? 'direct' : '未知'
279
+ return `已安装:${config.installDir}(mode=${mode})`
280
+ }
281
+
282
+ /** Remove the copy and its isolated Electron profile. */
283
+ export function remove(pluginConfig = {}) {
284
+ const config = resolveConfig(pluginConfig)
285
+ fs.rmSync(config.installDir, { recursive: true, force: true })
286
+ const userData = path.join(process.env.APPDATA ?? '', config.userDataDirName)
287
+ fs.rmSync(userData, { recursive: true, force: true })
288
+ return '已删除:' + config.installDir + ' 与 ' + userData
289
+ }
package/lib/state.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * State for the WSL Desktop copy: version stamp, auto-run status and the
3
+ * "is a rebuild needed" decision.
4
+ *
5
+ * @module @karoy/dsh-wsl-desktop/state
6
+ */
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+
10
+ /** Bumped whenever the main.js patch changes, so an old copy is rebuilt. */
11
+ export const PATCH_VERSION = '3'
12
+
13
+ export function stampFile(installDir) {
14
+ return path.join(installDir, '.dsh-wsl-version')
15
+ }
16
+
17
+ export function statusFile(installDir) {
18
+ return path.join(installDir, '.dsh-wsl-auto-status.json')
19
+ }
20
+
21
+ /** The running Desktop version, injected by the shell into the Host. */
22
+ export function currentVersion() {
23
+ return process.env.DSH_CLIENT_VERSION ?? ''
24
+ }
25
+
26
+ export function readStamp(installDir) {
27
+ try {
28
+ return JSON.parse(fs.readFileSync(stampFile(installDir), 'utf8'))
29
+ } catch {
30
+ return null
31
+ }
32
+ }
33
+
34
+ export function writeStamp(installDir, config) {
35
+ fs.writeFileSync(stampFile(installDir), JSON.stringify({
36
+ version: currentVersion(),
37
+ mode: config.mode,
38
+ patch: PATCH_VERSION,
39
+ at: new Date().toISOString(),
40
+ }, null, 2))
41
+ }
42
+
43
+ /** True when the copy is missing, carries another mode, or predates this Desktop build. */
44
+ export function needsBuild(config) {
45
+ const mainPath = path.join(config.installDir, 'resources', 'app', 'lib', 'main.js')
46
+ if (!fs.existsSync(mainPath)) return true
47
+ const stamp = readStamp(config.installDir)
48
+ if (stamp === null) return true
49
+ if (stamp.mode !== config.mode) return true
50
+ if (stamp.patch !== PATCH_VERSION) return true
51
+ const version = currentVersion()
52
+ return version !== '' && stamp.version !== version
53
+ }
54
+
55
+ export function readStatus(installDir) {
56
+ try {
57
+ return JSON.parse(fs.readFileSync(statusFile(installDir), 'utf8'))
58
+ } catch {
59
+ return null
60
+ }
61
+ }
62
+
63
+ export function writeStatus(installDir, status) {
64
+ fs.mkdirSync(installDir, { recursive: true })
65
+ fs.writeFileSync(statusFile(installDir), JSON.stringify({ ...status, at: new Date().toISOString() }, null, 2))
66
+ }
67
+ /** First-sync stamp: sync runs only once until removed. */
68
+ export function initializedFile(installDir) {
69
+ return path.join(installDir, '.dsh-wsl-initialized')
70
+ }
71
+
72
+ export function isInitialized(installDir) {
73
+ return fs.existsSync(initializedFile(installDir))
74
+ }
75
+
76
+ export function markInitialized(installDir) {
77
+ fs.mkdirSync(installDir, { recursive: true })
78
+ fs.writeFileSync(initializedFile(installDir), new Date().toISOString())
79
+ }
package/lib/sync.js ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Mirror the complete plugin state of the Windows desktop profile into the WSL
3
+ * web profile: enabled plugins are installed and enabled, disabled ones are
4
+ * installed but kept disabled, and their profile config rows (id/name/enabled/
5
+ * config) are carried over with the same enable state.
6
+ *
7
+ * This runs once during the first initialization (and on demand via
8
+ * `/wsl-desktop-sync`); afterwards the WSL side is authoritative.
9
+ *
10
+ * `link:` packages are skipped unless `syncLinked` is set.
11
+ *
12
+ * @module @karoy/dsh-wsl-desktop/sync
13
+ */
14
+ import { spawnSync } from 'node:child_process'
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+ import { mergePluginConfigs } from './merge-patch.js'
19
+
20
+ const SKIP = [/^@deepseek-ai\//]
21
+
22
+ function wsl(script, timeoutMs = 900000) {
23
+ const result = spawnSync('wsl.exe', ['--', 'bash', '-s'], {
24
+ input: script,
25
+ encoding: 'utf8',
26
+ timeout: timeoutMs,
27
+ maxBuffer: 32 * 1024 * 1024,
28
+ windowsHide: true,
29
+ })
30
+ return { ok: result.status === 0, out: String(result.stdout ?? '') + String(result.stderr ?? '') }
31
+ }
32
+
33
+ export function toWslPath(value) {
34
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(value)
35
+ return match === null ? value : '/mnt/' + match[1].toLowerCase() + '/' + match[2].replaceAll('\\', '/')
36
+ }
37
+
38
+ export function readWindowsProfile() {
39
+ const manifest = path.join(os.homedir(), '.dsh', 'profiles', 'desktop', 'package.json')
40
+ if (!fs.existsSync(manifest)) return { dependencies: {}, bundles: [] }
41
+ const data = JSON.parse(fs.readFileSync(manifest, 'utf8'))
42
+ return { dependencies: data.dependencies ?? {}, bundles: data.dsh?.profile?.bundles ?? [] }
43
+ }
44
+
45
+ export function readWslManifest() {
46
+ const result = wsl('cat "$HOME/.dsh/profiles/web/package.json"', 30000)
47
+ const start = result.out.indexOf('{')
48
+ if (start === -1) return { bundles: [], dependencies: {} }
49
+ try {
50
+ const manifest = JSON.parse(result.out.slice(start))
51
+ return { bundles: manifest.dsh?.profile?.bundles ?? [], dependencies: manifest.dependencies ?? {} }
52
+ } catch {
53
+ return { bundles: [], dependencies: {} }
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Split the Windows plugins into enabled, disabled (installed but not enabled)
59
+ * and skipped.
60
+ * @returns `{ enabled, disabled, skipped }` — each entry `{ name, spec }`.
61
+ */
62
+ export function planPlugins(config) {
63
+ const { dependencies, bundles } = readWindowsProfile()
64
+ const enabledSet = new Set(bundles)
65
+ const enabled = []
66
+ const disabled = []
67
+ const skipped = []
68
+ for (const [name, version] of Object.entries(dependencies)) {
69
+ if (SKIP.some((pattern) => pattern.test(name))) continue
70
+ const isLink = version.startsWith('link:')
71
+ const target = isLink ? { name, spec: 'link:' + toWslPath(version.slice(5)) } : { name, spec: name + '@' + version.replace(/^[\^~]/, '') }
72
+ if (enabledSet.has(name)) {
73
+ if (isLink && !config.syncLinked) skipped.push({ name, reason: 'link (set syncLinked to include)' })
74
+ else enabled.push(target)
75
+ } else if (isLink && !config.syncLinked) {
76
+ skipped.push({ name, reason: 'disabled link (set syncLinked to include)' })
77
+ } else {
78
+ disabled.push(target)
79
+ }
80
+ }
81
+ return { enabled, disabled, skipped }
82
+ }
83
+
84
+ /** Make sure the enabled plugins sit in the WSL bundle list. */
85
+ export function ensureBundles(names) {
86
+ const script = [
87
+ "python3 - <<'PY'",
88
+ 'import json, os',
89
+ "p = os.path.expanduser('~/.dsh/profiles/web/package.json')",
90
+ 'd = json.load(open(p))',
91
+ "b = d.setdefault('dsh', {}).setdefault('profile', {}).setdefault('bundles', [])",
92
+ 'names = ' + JSON.stringify(names),
93
+ 'changed = False',
94
+ 'for n in names:',
95
+ ' if n not in b:',
96
+ ' b.append(n); changed = True',
97
+ "json.dump(d, open(p, 'w'), indent=2, ensure_ascii=False)",
98
+ "print('BUNDLES_' + ('UPDATED' if changed else 'OK'))",
99
+ 'PY',
100
+ ].join('\n')
101
+ return wsl(script, 30000).out.includes('BUNDLES_UPDATED')
102
+ }
103
+
104
+ /** Keep disabled plugins OUT of the WSL bundle list. */
105
+ export function deactivateBundles(names) {
106
+ const script = [
107
+ "python3 - <<'PY'",
108
+ 'import json, os',
109
+ "p = os.path.expanduser('~/.dsh/profiles/web/package.json')",
110
+ 'd = json.load(open(p))',
111
+ "b = d.get('dsh', {}).get('profile', {}).get('bundles', [])",
112
+ 'names = ' + JSON.stringify(names),
113
+ 'changed = False',
114
+ 'for n in names:',
115
+ ' if n in b:',
116
+ ' b.remove(n); changed = True',
117
+ "json.dump(d, open(p, 'w'), indent=2, ensure_ascii=False)",
118
+ "print('BUNDLES_' + ('UPDATED' if changed else 'OK'))",
119
+ 'PY',
120
+ ].join('\n')
121
+ return wsl(script, 30000).out.includes('BUNDLES_UPDATED')
122
+ }
123
+
124
+ /**
125
+ * Full mirror of the Windows plugin state (enabled + disabled) into WSL.
126
+ * @returns `{ added, removed, failed, unchanged, bundlesUpdated, configsMerged }`.
127
+ */
128
+ export function syncPlugins(config) {
129
+ const { enabled, disabled, skipped } = planPlugins(config)
130
+ const enabledNames = enabled.map((p) => p.name)
131
+ const disabledNames = disabled.map((p) => p.name)
132
+ const wslManifest = readWslManifest()
133
+ const toInstall = [...enabled, ...disabled].filter((p) => wslManifest.dependencies[p.name] === undefined)
134
+
135
+ const lines = [
136
+ 'export PATH="$HOME/.local/node/bin:$PATH"',
137
+ 'if ! command -v pnpm >/dev/null 2>&1; then corepack enable pnpm >/dev/null 2>&1 || true; fi',
138
+ 'NODE="$HOME/.local/node/bin/node"',
139
+ 'DSH_JS="$HOME/.local/dsh/lib/node_modules/@deepseek-ai/dsh/lib/bin.js"',
140
+ 'if [ ! -f "$DSH_JS" ]; then echo WSL_DESKTOP_NO_DSH; exit 4; fi',
141
+ 'add() {',
142
+ ' if "$NODE" "$DSH_JS" plugin --profile web add "$1" >/tmp/wsl-desktop-add.log 2>&1; then echo "ADD_OK $1"; else echo "ADD_FAIL $1"; tail -2 /tmp/wsl-desktop-add.log; fi',
143
+ '}',
144
+ ]
145
+ for (const plan of toInstall) lines.push("add '" + plan.spec.replaceAll("'", "'\\''") + "'")
146
+
147
+ const result = wsl(lines.join('\n'))
148
+ const added = []
149
+ const failed = []
150
+ for (const match of result.out.matchAll(/ADD_OK (\S+)/g)) added.push(match[1])
151
+ for (const match of result.out.matchAll(/ADD_FAIL (\S+)/g)) failed.push(match[1])
152
+ if (result.out.includes('WSL_DESKTOP_NO_DSH')) failed.push('WSL DSH runtime missing')
153
+
154
+ const bundlesUpdated = ensureBundles(enabledNames)
155
+ const bundlesDeactivated = deactivateBundles(disabledNames)
156
+ const configsMerged = mergePluginConfigs([...enabledNames, ...disabledNames])
157
+ const changed = toInstall.length > 0 || bundlesUpdated || bundlesDeactivated || configsMerged
158
+ return { added, removed: [], failed, skipped, unchanged: !changed, bundlesUpdated, bundlesDeactivated, configsMerged }
159
+ }
160
+
161
+ /** Remove plugins again (used to roll back a profile that no longer boots). */
162
+ export function removePlugins(names) {
163
+ if (names.length === 0) return
164
+ const lines = [
165
+ 'export PATH="$HOME/.local/node/bin:$PATH"',
166
+ 'NODE="$HOME/.local/node/bin/node"',
167
+ 'DSH_JS="$HOME/.local/dsh/lib/node_modules/@deepseek-ai/dsh/lib/bin.js"',
168
+ ]
169
+ for (const name of names) lines.push('"$NODE" "$DSH_JS" plugin --profile web remove \'' + name.replaceAll("'", "'\\''") + '\' >/tmp/wsl-desktop-remove.log 2>&1 || true')
170
+ wsl(lines.join('\n'), 600000)
171
+ }
172
+
173
+ /** Restart the WSL Host and wait for it to report its web URL. */
174
+ export function restartAndVerify() {
175
+ const script = [
176
+ 'if [ -f "$HOME/dsh-wsl-host.pid" ] && kill -0 "$(cat "$HOME/dsh-wsl-host.pid")" 2>/dev/null; then kill "$(cat "$HOME/dsh-wsl-host.pid")"; sleep 1; fi',
177
+ 'NODE="$HOME/.local/node/bin/node"',
178
+ 'DSH_JS="$HOME/.local/dsh/lib/node_modules/@deepseek-ai/dsh/lib/bin.js"',
179
+ 'setsid nohup "$NODE" "$DSH_JS" --profile web --no-open --port 3080 > "$HOME/dsh-wsl-host.log" 2>&1 < /dev/null &',
180
+ 'echo $! > "$HOME/dsh-wsl-host.pid"',
181
+ 'for i in $(seq 1 90); do grep -q "^dsh web:" "$HOME/dsh-wsl-host.log" && break; sleep 1; done',
182
+ 'if grep -q "^dsh web:" "$HOME/dsh-wsl-host.log"; then echo HOST_OK; else echo HOST_FAIL; tail -8 "$HOME/dsh-wsl-host.log"; fi',
183
+ ].join('\n')
184
+ return wsl(script, 180000).out.includes('HOST_OK')
185
+ }
186
+
187
+ export function stopWslHost() {
188
+ return wsl([
189
+ 'if [ -f "$HOME/dsh-wsl-host.pid" ] && kill -0 "$(cat "$HOME/dsh-wsl-host.pid")" 2>/dev/null; then',
190
+ ' kill "$(cat "$HOME/dsh-wsl-host.pid")"; sleep 1; rm -f "$HOME/dsh-wsl-host.pid"; echo STOPPED',
191
+ 'else',
192
+ ' echo NOT_RUNNING',
193
+ 'fi',
194
+ ].join('\n'), 30000)
195
+ }
196
+
197
+ export function isCopyRunning(config) {
198
+ const exe = path.join(config.installDir, 'DeepSeek Harness.exe')
199
+ const command = `(Get-CimInstance Win32_Process -Filter "Name='DeepSeek Harness.exe'" | Where-Object { $_.ExecutablePath -eq '${exe.replaceAll("'", "''")}' }).Count`
200
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-Command', command], {
201
+ encoding: 'utf8',
202
+ timeout: 20000,
203
+ windowsHide: true,
204
+ })
205
+ const count = Number(String(result.stdout ?? '').trim())
206
+ return Number.isFinite(count) && count > 0
207
+ }