@michengai/dsh-codex-ui 2.0.11 → 2.0.13

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,21 @@
1
+ import { Context } from "@deepseek-ai/cordis";
2
+ //#region src/desktop-menu-plugin.d.ts
3
+ declare const name = "codex-ui-desktop-menu";
4
+ declare const inject: string[];
5
+ /**
6
+ * 检查 profile 的 cordis.patch.yml 中是否显式配置了 disabled: true。
7
+ */
8
+ declare function isSubPluginDisabledOnDisk(id: string, homeDir?: string, ctx?: Context): boolean;
9
+ /**
10
+ * 桌面端标题栏窗口菜单子组件 (Host 侧)
11
+ *
12
+ * 通过 webServer 暴露 /api/michengai/dsh-codex-ui/desktop-menu:
13
+ * - 无 action:返回子插件启用状态(客户端据此决定是否注入菜单)
14
+ * - ?action=status:重启能力探测 + 一次性令牌 + 当前重启阶段
15
+ * - ?action=restart:请求重启应用(必须带 x-dcu-restart-key)
16
+ *
17
+ * 停用此子组件或端点返回 disabled 时,客户端不注入任何菜单。
18
+ */
19
+ declare function apply(ctx: Context): void;
20
+ //#endregion
21
+ export { apply, inject, isSubPluginDisabledOnDisk, name };
@@ -0,0 +1,582 @@
1
+ import { r as CODEX_UI_API_ENDPOINTS, t as isSubPluginDisabledOnDisk$1 } from "./profile-resolver-BkTv7lmZ.mjs";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { randomBytes, timingSafeEqual } from "node:crypto";
7
+ //#region src/restart.ts
8
+ /**
9
+ * 桌面应用重启:平台识别、重启计划与脱离进程的助手生成。
10
+ *
11
+ * 为什么需要这一层:DSH 桌面端的 Host 只是 Electron 主进程的子进程,
12
+ * 插件拿不到 `app.relaunch()`,也没有 IPC 能让主进程重启。所以「重启应用」
13
+ * 只能从外部完成:先让应用**正常退出**,再由一个脱离进程的助手把它拉起来。
14
+ *
15
+ * 这里刻意不做强杀:Windows 发 WM_CLOSE、macOS 走 AppleScript quit、Linux 发 SIGTERM,
16
+ * 应用没退(多半是用户在官方退出确认框里点了取消)就当作本次重启作废,
17
+ * 绝不补刀——补刀会让新旧两个实例抢同一个端口。
18
+ *
19
+ * 参考社区成熟实现(dsh-refresh-restart / dsh-restart-now)的做法,但代码为自研。
20
+ */
21
+ /** macOS 上 DeepSeek Harness 桌面版的 bundle id。 */
22
+ const MAC_BUNDLE_ID = "com.deepseek.dsh";
23
+ /** 取路径最后一段(同时兼容 Windows 反斜杠)。 */
24
+ function baseName(value) {
25
+ const parts = String(value).split(/[\\/]/);
26
+ return parts[parts.length - 1] ?? "";
27
+ }
28
+ /**
29
+ * 判断当前进程是不是「桌面应用本体」,并给出重启需要的路径。
30
+ *
31
+ * - macOS:从 `process.execPath` 里找 `.app/Contents/MacOS/`。
32
+ * - Windows:可执行文件是 `.exe` 且不是 `node.exe` / `electron.exe`。
33
+ * - Linux:优先用 AppImage 自带的 `APPIMAGE`;否则 execPath 不是 node/electron 就当桌面程序。
34
+ * - 纯 `dsh web`(execPath 是 node)一律不可重启,`canRestart=false`。
35
+ */
36
+ function detectApp(input = {}) {
37
+ const platform = typeof input.platform === "string" ? input.platform : process.platform;
38
+ const execPath = typeof input.execPath === "string" ? input.execPath : process.execPath;
39
+ const env = input.env ?? process.env;
40
+ if (platform === "darwin") {
41
+ const index = execPath.indexOf(".app/Contents/MacOS/");
42
+ const appPath = index === -1 ? "" : execPath.slice(0, index + 4);
43
+ return {
44
+ platform,
45
+ kind: appPath === "" ? "node" : "mac",
46
+ appPath,
47
+ execPath,
48
+ imageName: baseName(execPath),
49
+ canRestart: appPath !== ""
50
+ };
51
+ }
52
+ if (platform === "win32") {
53
+ const name = baseName(execPath);
54
+ const lower = name.toLowerCase();
55
+ const isApp = lower.endsWith(".exe") && lower !== "node.exe" && lower !== "electron.exe";
56
+ return {
57
+ platform,
58
+ kind: isApp ? "win" : "node",
59
+ appPath: isApp ? execPath : "",
60
+ execPath,
61
+ imageName: name,
62
+ canRestart: isApp
63
+ };
64
+ }
65
+ const appImage = typeof env.APPIMAGE === "string" ? env.APPIMAGE.trim() : "";
66
+ const resolved = appImage !== "" ? appImage : execPath;
67
+ const lower = baseName(resolved).toLowerCase();
68
+ const runtime = lower === "" || lower === "node" || lower === "node.exe" || lower === "electron" || lower === "electron.exe";
69
+ return {
70
+ platform,
71
+ kind: runtime ? "node" : "linux",
72
+ appPath: runtime ? "" : resolved,
73
+ execPath: resolved,
74
+ imageName: baseName(resolved),
75
+ canRestart: !runtime
76
+ };
77
+ }
78
+ /** 默认给用户的等待上限:超过就算了,不补刀。 */
79
+ const DEFAULT_QUIT_TIMEOUT_MS = 2e4;
80
+ const DEFAULT_OPEN_DELAY_MS = 800;
81
+ /** 把平台差异拍成一份纯数据计划。 */
82
+ function buildPlan(app, options) {
83
+ return {
84
+ platform: app.platform,
85
+ kind: app.kind,
86
+ appPath: app.appPath,
87
+ imageName: app.imageName,
88
+ appId: MAC_BUNDLE_ID,
89
+ match: app.kind === "mac" ? `${app.appPath}/Contents/` : app.execPath,
90
+ logPath: options.logPath,
91
+ statePath: options.statePath ?? "",
92
+ mainPid: options.mainPid ?? 0,
93
+ hostPid: options.hostPid ?? 0,
94
+ bootId: options.bootId ?? "",
95
+ quitTimeoutMs: options.quitTimeoutMs ?? DEFAULT_QUIT_TIMEOUT_MS,
96
+ openDelayMs: options.openDelayMs ?? DEFAULT_OPEN_DELAY_MS
97
+ };
98
+ }
99
+ /**
100
+ * 生成助手脚本(CommonJS,交给 Electron 自带的 Node 执行)。
101
+ *
102
+ * 为什么不写成 bat / ps1:三个平台用同一套逻辑最省事,而 `process.execPath` +
103
+ * `ELECTRON_RUN_AS_NODE=1` 可以借用应用自带的 Node,用户机器上不需要另装 Node。
104
+ */
105
+ function helperSource(plan) {
106
+ return `'use strict'
107
+ // DeepSeek Harness 重启助手(由 codex-ui 生成,放在临时目录,可随时删除)
108
+ const { spawn, spawnSync } = require('node:child_process')
109
+ const fs = require('node:fs')
110
+
111
+ const plan = ${JSON.stringify(plan, null, 2)}
112
+ const SELF = process.pid
113
+
114
+ function stamp() {
115
+ return new Date().toISOString().replace('T', ' ').slice(0, 19)
116
+ }
117
+
118
+ function log(message) {
119
+ try { fs.appendFileSync(plan.logPath, '[' + stamp() + '] codex-ui restart: ' + message + '\\n') } catch {}
120
+ }
121
+
122
+ function writeState(phase, detail) {
123
+ if (!plan.statePath) return
124
+ try {
125
+ fs.writeFileSync(plan.statePath, JSON.stringify({
126
+ phase: phase, detail: detail || '', at: Date.now(), helper: SELF,
127
+ platform: plan.platform, bootId: plan.bootId
128
+ }), 'utf8')
129
+ } catch (error) {
130
+ log('写状态失败: ' + (error && error.message ? error.message : String(error)))
131
+ }
132
+ }
133
+
134
+ // 重开时必须摘掉「把 Electron 当 Node 用」的开关,否则新实例只有进程没有窗口。
135
+ const childEnv = (function () {
136
+ const env = {}
137
+ for (const key of Object.keys(process.env)) {
138
+ if (key.indexOf('ELECTRON_') === 0) continue
139
+ if (key === 'NODE_OPTIONS' || key === 'NODE_PATH') continue
140
+ env[key] = process.env[key]
141
+ }
142
+ return env
143
+ })()
144
+
145
+ function run(command, args) {
146
+ try {
147
+ return spawnSync(command, args, { encoding: 'utf8', timeout: 20000, windowsHide: true, env: childEnv })
148
+ } catch (error) {
149
+ log('spawn 失败 ' + command + ': ' + (error && error.message ? error.message : String(error)))
150
+ return { status: -1, stdout: '', stderr: '' }
151
+ }
152
+ }
153
+
154
+ function sleep(ms) {
155
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
156
+ }
157
+
158
+ function alive(pid) {
159
+ try { process.kill(pid, 0); return true } catch { return false }
160
+ }
161
+
162
+ /** 还活着的应用进程(永远排除助手自己)。 */
163
+ function appPids() {
164
+ const pids = []
165
+ if (plan.platform === 'win32') {
166
+ const result = run('tasklist', ['/FI', 'IMAGENAME eq ' + plan.imageName, '/NH', '/FO', 'CSV'])
167
+ const text = String(result.stdout || '').trim()
168
+ if (text === '' || /^INFO:/i.test(text)) return pids
169
+ for (const line of text.split(/\\r?\\n/)) {
170
+ const match = line.match(/^"([^"]+)","(\\d+)"/)
171
+ if (match) pids.push(Number(match[2]))
172
+ }
173
+ } else {
174
+ const result = run('ps', ['-Ao', 'pid=,command='])
175
+ const needle = plan.match || plan.appPath
176
+ for (const line of String(result.stdout || '').split('\\n')) {
177
+ const match = line.match(/^\\s*(\\d+)\\s+(.*)$/)
178
+ if (!match) continue
179
+ if (needle !== '' && match[2].indexOf(needle) === -1) continue
180
+ pids.push(Number(match[1]))
181
+ }
182
+ }
183
+ return pids.filter(function (pid) { return pid !== SELF })
184
+ }
185
+
186
+ function waitUntil(predicate, ms) {
187
+ const deadline = Date.now() + ms
188
+ while (Date.now() < deadline) {
189
+ if (predicate()) return true
190
+ sleep(250)
191
+ }
192
+ return predicate()
193
+ }
194
+
195
+ /** Windows 的 tasklist 看不到命令行参数,只能退回「进程在就算起来了」。 */
196
+ function windowSeen(ms) {
197
+ if (plan.platform === 'win32') return true
198
+ return waitUntil(function () {
199
+ const result = run('ps', ['-Ao', 'pid=,command='])
200
+ const needle = plan.match || plan.appPath
201
+ return String(result.stdout || '').split('\\n').some(function (line) {
202
+ return line.indexOf('--type=renderer') !== -1 && (needle === '' || line.indexOf(needle) !== -1)
203
+ })
204
+ }, ms)
205
+ }
206
+
207
+ /**
208
+ * 让应用退出。
209
+ *
210
+ * Windows 只能结束 Electron 主进程:安装版宿主的 window.on('close') 是无条件
211
+ * preventDefault + hideMainWindow(收进托盘),所以 WM_CLOSE / CloseMainWindow 永远不会
212
+ * 让应用退出。结束主进程后,主进程退出,我们先给予 Host 3 秒等待其自行落盘与退出,
213
+ * 若超时仍未退出则按 PID 执行兜底清理。
214
+ * 刻意不带 /T:带 /T 会把刚起的助手自己一起杀掉。
215
+ */
216
+ function requestQuit() {
217
+ if (plan.kind === 'win') {
218
+ if (!plan.mainPid) {
219
+ log('缺少主进程 PID,放弃重启')
220
+ return false
221
+ }
222
+ const result = run('taskkill', ['/PID', String(plan.mainPid), '/F'])
223
+ log('taskkill main pid=' + plan.mainPid + ' status=' + result.status)
224
+ return true
225
+ }
226
+ if (plan.kind === 'mac') {
227
+ const result = run('osascript', ['-e', 'tell application id "' + plan.appId + '" to quit'])
228
+ log('osascript quit status=' + result.status)
229
+ return result.status === 0
230
+ }
231
+ let sent = 0
232
+ for (const pid of appPids()) {
233
+ try { process.kill(pid, 'SIGTERM'); sent += 1 } catch {}
234
+ }
235
+ log('SIGTERM 发送给 ' + sent + ' 个进程')
236
+ return sent > 0
237
+ }
238
+
239
+ function launch() {
240
+ try {
241
+ if (plan.kind === 'mac') {
242
+ const first = run('open', ['-a', plan.appPath])
243
+ if (first.status !== 0) {
244
+ log('open -a 失败: ' + (first.stderr || first.status))
245
+ const second = run('open', ['-b', plan.appId])
246
+ if (second.status !== 0) return false
247
+ }
248
+ return waitUntil(function () { return appPids().some(alive) }, 20000) && windowSeen(20000)
249
+ }
250
+ const child = spawn(plan.appPath, [], {
251
+ detached: true,
252
+ stdio: 'ignore',
253
+ cwd: plan.appPath.replace(/[\\\\/][^\\\\/]+$/, '') || undefined,
254
+ env: childEnv,
255
+ windowsHide: false,
256
+ })
257
+ child.once('error', function () {})
258
+ child.unref()
259
+ return waitUntil(function () { return appPids().some(alive) }, 20000)
260
+ } catch (error) {
261
+ log('重新打开失败: ' + (error && error.message ? error.message : String(error)))
262
+ return false
263
+ }
264
+ }
265
+
266
+ function main() {
267
+ log('helper start pid=' + SELF + ' kind=' + plan.kind + ' platform=' + plan.platform)
268
+ writeState('starting', '')
269
+ sleep(1000)
270
+
271
+ writeState('quitting', '')
272
+ requestQuit()
273
+
274
+ // Windows 上判断「应用已退出」以 Electron 主进程为准:它才是窗口与托盘的所有者。
275
+ const targetGone = function () {
276
+ return plan.platform !== 'win32' ? appPids().filter(alive).length === 0 : !alive(plan.mainPid)
277
+ }
278
+ if (!waitUntil(targetGone, plan.quitTimeoutMs)) {
279
+ // 主进程没死:不补刀,否则可能留下两个实例抢同一个端口。
280
+ log('主进程仍在运行,本次重启作废,不动进程')
281
+ writeState('cancelled', '应用没有退出')
282
+ return
283
+ }
284
+ log('主进程已退出')
285
+
286
+ // 主进程一死,Host 会失去父子 IPC 通道。先给予 3 秒让 Host 自行正常清理并落盘退出;
287
+ // 若超时仍未退出(依然占着单实例锁和端口),再按 PID 发起兜底清理。
288
+ if (plan.platform === 'win32' && plan.hostPid && alive(plan.hostPid)) {
289
+ var hostGone = waitUntil(function () { return !alive(plan.hostPid) }, 3000)
290
+ if (!hostGone && alive(plan.hostPid)) {
291
+ run('taskkill', ['/PID', String(plan.hostPid), '/F'])
292
+ log('Host 超时未退,执行兜底清理 pid=' + plan.hostPid)
293
+ waitUntil(function () { return !alive(plan.hostPid) }, 3000)
294
+ } else {
295
+ log('Host 已自行正常退出 pid=' + plan.hostPid)
296
+ }
297
+ }
298
+ // 等旧实例的渲染进程等散场,再拉新的。
299
+ waitUntil(function () { return appPids().filter(alive).length === 0 }, 5000)
300
+
301
+ sleep(Math.max(0, plan.openDelayMs))
302
+ if (launch()) {
303
+ writeState('relaunched', '')
304
+ log('应用已重新打开')
305
+ } else {
306
+ writeState('launch-failed', '')
307
+ log('重开失败:请手动打开 DeepSeek Harness')
308
+ }
309
+ }
310
+
311
+ try { main() } catch (error) {
312
+ log('helper 异常: ' + (error && error.stack ? error.stack : String(error)))
313
+ } finally {
314
+ try { fs.unlinkSync(process.argv[1]) } catch {}
315
+ }
316
+ `;
317
+ }
318
+ /** 把助手脚本写进临时目录并交给 Electron 的 Node 跑起来(脱离本进程)。 */
319
+ function spawnHelper(plan) {
320
+ try {
321
+ const scriptPath = join(tmpdir(), `dcu-restart-${Date.now().toString(36)}.cjs`);
322
+ writeFileSync(scriptPath, helperSource(plan), "utf8");
323
+ const child = spawn(process.execPath, [scriptPath], {
324
+ detached: true,
325
+ stdio: "ignore",
326
+ windowsHide: true,
327
+ env: {
328
+ ...process.env,
329
+ ELECTRON_RUN_AS_NODE: "1"
330
+ },
331
+ cwd: dirname(scriptPath)
332
+ });
333
+ child.once("error", () => {});
334
+ child.unref();
335
+ return {
336
+ ok: true,
337
+ scriptPath
338
+ };
339
+ } catch (error) {
340
+ return {
341
+ ok: false,
342
+ error: error instanceof Error ? error.message : String(error)
343
+ };
344
+ }
345
+ }
346
+ /** 默认日志与状态文件位置。 */
347
+ function defaultPaths() {
348
+ const base = join(tmpdir(), "dsh-codex-ui-restart");
349
+ return {
350
+ logPath: join(base, "restart.log"),
351
+ statePath: join(base, "state.json")
352
+ };
353
+ }
354
+ //#endregion
355
+ //#region src/desktop-menu-route.ts
356
+ /**
357
+ * 桌面端窗口菜单的 Host 路由。
358
+ *
359
+ * 三条通道,同一个端点:
360
+ * GET ?action=status → 状态文档(含一次性重启令牌与当前重启阶段)
361
+ * POST ?action=restart → 请求重启(必须带 status 文档里的令牌)
362
+ * GET (无 action) → 兼容旧调用方,仅返回 { enabled }
363
+ *
364
+ * 安全:只接受环回调用(Host 头必须是本机),POST 还必须带令牌。
365
+ * 只校验环回没有意义——本机任何进程都能伪造 Host 头,令牌才能证明调用方是读过
366
+ * 我们状态文档的那个页面(同一套思路见社区 dsh-refresh-restart)。
367
+ */
368
+ function headerValue(headers, key) {
369
+ const value = headers[key];
370
+ if (typeof value === "string") return value;
371
+ if (Array.isArray(value) && typeof value[0] === "string") return value[0];
372
+ }
373
+ /** `Host` 头是否指向本机。 */
374
+ function hostIsLoopback(host) {
375
+ if (typeof host !== "string" || host.trim() === "") return false;
376
+ const value = host.trim().toLowerCase();
377
+ const name = value.startsWith("[") ? value.slice(1, value.indexOf("]")) : value.split(":")[0];
378
+ return name === "127.0.0.1" || name === "localhost" || name === "::1" || name === "[::1]";
379
+ }
380
+ /** 常数时间比较两个令牌。 */
381
+ function tokenMatches(expected, provided) {
382
+ if (typeof provided !== "string" || provided === "") return false;
383
+ const a = Buffer.from(expected);
384
+ const b = Buffer.from(provided);
385
+ if (a.length !== b.length) return false;
386
+ return timingSafeEqual(a, b);
387
+ }
388
+ function sendJson(response, status, payload) {
389
+ const body = JSON.stringify(payload);
390
+ response.writeHead(status, {
391
+ "content-type": "application/json; charset=utf-8",
392
+ "content-length": String(Buffer.byteLength(body)),
393
+ "cache-control": "no-store"
394
+ });
395
+ response.end(body);
396
+ }
397
+ /**
398
+ * 创建路由处理器。
399
+ * @param deps - 子插件状态、平台信息与可注入的副作用。
400
+ */
401
+ function createDesktopMenuHandler(deps) {
402
+ const token = deps.token ?? randomBytes(16).toString("hex");
403
+ /** 本次 Host 启动的标识:只认自己这一轮写出的状态,丢掉上次运行留下的结果。 */
404
+ const bootId = randomBytes(8).toString("hex");
405
+ const paths = deps.paths ?? defaultPaths();
406
+ const spawnPlan = deps.spawn ?? spawnHelper;
407
+ /** 已排程的重启;超时后允许重试,避免一次失败把入口永久锁死。 */
408
+ let scheduledAt = 0;
409
+ const scheduleTimeoutMs = 12e4;
410
+ try {
411
+ mkdirSync(dirname(paths.statePath), { recursive: true });
412
+ mkdirSync(dirname(paths.logPath), { recursive: true });
413
+ } catch {}
414
+ const target = () => detectApp({
415
+ platform: deps.platform,
416
+ execPath: deps.execPath,
417
+ env: deps.env
418
+ });
419
+ const readState = () => {
420
+ try {
421
+ const state = JSON.parse(readFileSync(paths.statePath, "utf8"));
422
+ if (state.bootId !== bootId) return {};
423
+ return state;
424
+ } catch {
425
+ return {};
426
+ }
427
+ };
428
+ const statusView = () => {
429
+ const app = target();
430
+ const state = readState();
431
+ return {
432
+ enabled: !deps.isDisabled(),
433
+ canRestart: app.canRestart,
434
+ reason: app.canRestart ? void 0 : unsupportedReason(app.platform, app.kind),
435
+ platform: app.platform,
436
+ kind: app.kind,
437
+ appPath: app.appPath,
438
+ token,
439
+ phase: state.phase,
440
+ detail: state.detail
441
+ };
442
+ };
443
+ return async (request, response) => {
444
+ const rawUrl = typeof request.url === "string" ? request.url : "/";
445
+ let url;
446
+ try {
447
+ url = new URL(rawUrl, "http://dsh.internal");
448
+ } catch {
449
+ sendJson(response, 400, {
450
+ ok: false,
451
+ error: "bad-url"
452
+ });
453
+ return;
454
+ }
455
+ if (!hostIsLoopback(headerValue(request.headers, "host"))) {
456
+ sendJson(response, 403, {
457
+ ok: false,
458
+ error: "forbidden"
459
+ });
460
+ return;
461
+ }
462
+ const action = url.searchParams.get("action");
463
+ if (action === null) {
464
+ sendJson(response, 200, { enabled: !deps.isDisabled() });
465
+ return;
466
+ }
467
+ if (action === "status") {
468
+ if (request.method !== "GET" && request.method !== "HEAD") {
469
+ sendJson(response, 405, {
470
+ ok: false,
471
+ error: "method"
472
+ });
473
+ return;
474
+ }
475
+ sendJson(response, 200, statusView());
476
+ return;
477
+ }
478
+ if (action === "restart") {
479
+ if (request.method !== "POST") {
480
+ sendJson(response, 405, {
481
+ ok: false,
482
+ error: "method"
483
+ });
484
+ return;
485
+ }
486
+ if (!tokenMatches(token, headerValue(request.headers, "x-dcu-restart-key"))) {
487
+ sendJson(response, 403, {
488
+ ok: false,
489
+ error: "bad-token"
490
+ });
491
+ return;
492
+ }
493
+ const app = target();
494
+ if (!app.canRestart) {
495
+ sendJson(response, 409, {
496
+ ok: false,
497
+ error: "unsupported",
498
+ reason: unsupportedReason(app.platform, app.kind)
499
+ });
500
+ return;
501
+ }
502
+ if (scheduledAt !== 0 && Date.now() - scheduledAt < scheduleTimeoutMs) {
503
+ sendJson(response, 409, {
504
+ ok: false,
505
+ error: "busy"
506
+ });
507
+ return;
508
+ }
509
+ scheduledAt = Date.now();
510
+ const outcome = spawnPlan(buildPlan(app, {
511
+ ...paths,
512
+ mainPid: deps.mainPid ?? process.ppid,
513
+ hostPid: deps.hostPid ?? process.pid,
514
+ bootId
515
+ }));
516
+ if (!outcome.ok) {
517
+ scheduledAt = 0;
518
+ sendJson(response, 500, {
519
+ ok: false,
520
+ error: "spawn-failed",
521
+ detail: outcome.error
522
+ });
523
+ return;
524
+ }
525
+ sendJson(response, 200, {
526
+ ok: true,
527
+ phase: "starting"
528
+ });
529
+ return;
530
+ }
531
+ sendJson(response, 404, {
532
+ ok: false,
533
+ error: "not-found"
534
+ });
535
+ };
536
+ }
537
+ /** @returns 不能重启时的原因代码;能重启时为 undefined。 */
538
+ function unsupportedReason(platform, kind) {
539
+ if (kind !== "node") return void 0;
540
+ if (platform === "win32" || platform === "darwin" || platform === "linux") return "missing-app";
541
+ return "desktop-only";
542
+ }
543
+ //#endregion
544
+ //#region src/desktop-menu-plugin.ts
545
+ const name = "codex-ui-desktop-menu";
546
+ const inject = ["webServer"];
547
+ /** 子组件自身在 profile 配置里的 id。 */
548
+ const SUB_PLUGIN_ID = "codex-ui-desktop-menu";
549
+ /**
550
+ * 检查 profile 的 cordis.patch.yml 中是否显式配置了 disabled: true。
551
+ */
552
+ function isSubPluginDisabledOnDisk(id, homeDir, ctx) {
553
+ return isSubPluginDisabledOnDisk$1(id, homeDir, ctx);
554
+ }
555
+ /**
556
+ * 桌面端标题栏窗口菜单子组件 (Host 侧)
557
+ *
558
+ * 通过 webServer 暴露 /api/michengai/dsh-codex-ui/desktop-menu:
559
+ * - 无 action:返回子插件启用状态(客户端据此决定是否注入菜单)
560
+ * - ?action=status:重启能力探测 + 一次性令牌 + 当前重启阶段
561
+ * - ?action=restart:请求重启应用(必须带 x-dcu-restart-key)
562
+ *
563
+ * 停用此子组件或端点返回 disabled 时,客户端不注入任何菜单。
564
+ */
565
+ function apply(ctx) {
566
+ const endpoint = CODEX_UI_API_ENDPOINTS.desktopMenu;
567
+ const handler = createDesktopMenuHandler({ isDisabled: () => isSubPluginDisabledOnDisk(SUB_PLUGIN_ID, void 0, ctx) });
568
+ ctx.effect(() => {
569
+ const webServer = ctx.get("webServer");
570
+ if (!webServer || typeof webServer.register !== "function") return () => {};
571
+ const dispose = webServer.register({
572
+ kind: "prefix",
573
+ path: endpoint,
574
+ handler
575
+ });
576
+ return () => {
577
+ dispose?.();
578
+ };
579
+ }, "michengai-codex-ui: desktop menu state");
580
+ }
581
+ //#endregion
582
+ export { apply, inject, isSubPluginDisabledOnDisk, name };
package/lib/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as resolveCurrentProfile, r as CODEX_UI_API_ENDPOINTS } from "./profile-resolver-D81fBy52.mjs";
1
+ import { n as resolveCurrentProfile, r as CODEX_UI_API_ENDPOINTS } from "./profile-resolver-BkTv7lmZ.mjs";
2
2
  import { spawn } from "node:child_process";
3
3
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { readFile, rm, unlink, writeFile } from "node:fs/promises";
@@ -3,13 +3,18 @@ import { homedir } from "node:os";
3
3
  import { basename, isAbsolute, join, resolve } from "node:path";
4
4
  //#region src/business-api.ts
5
5
  const CODEX_UI_API_BASE = "/api/michengai/dsh-codex-ui";
6
+ /** 请求重启时携带一次性令牌的请求头(客户端与 Host 共用)。 */
7
+ const CODEX_UI_RESTART_HEADER = "x-dcu-restart-key";
6
8
  const CODEX_UI_API_ENDPOINTS = Object.freeze({
7
9
  dependencies: `${CODEX_UI_API_BASE}/dependencies`,
8
10
  settingsSkin: `${CODEX_UI_API_BASE}/settings-skin`,
9
11
  composer: `${CODEX_UI_API_BASE}/composer`,
12
+ composerPrediction: `${CODEX_UI_API_BASE}/composer/prediction`,
13
+ composerPredictionStream: `${CODEX_UI_API_BASE}/composer/prediction/stream`,
10
14
  sidebar: `${CODEX_UI_API_BASE}/sidebar`,
11
15
  sections: `${CODEX_UI_API_BASE}/sections`,
12
- theme: `${CODEX_UI_API_BASE}/theme`
16
+ theme: `${CODEX_UI_API_BASE}/theme`,
17
+ desktopMenu: `${CODEX_UI_API_BASE}/desktop-menu`
13
18
  });
14
19
  //#endregion
15
20
  //#region src/profile-resolver.ts
@@ -81,4 +86,4 @@ function isSubPluginDisabledOnDisk(id, homeDir, ctx) {
81
86
  return false;
82
87
  }
83
88
  //#endregion
84
- export { resolveCurrentProfile as n, CODEX_UI_API_ENDPOINTS as r, isSubPluginDisabledOnDisk as t };
89
+ export { CODEX_UI_RESTART_HEADER as i, resolveCurrentProfile as n, CODEX_UI_API_ENDPOINTS as r, isSubPluginDisabledOnDisk as t };