@lynn123411/dsh-kimi-cu 0.3.2 → 0.3.4

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.
@@ -6,6 +6,7 @@
6
6
  * 跑法:pnpm test / node scripts/smoke-client.mjs
7
7
  */
8
8
  import { fileURLToPath } from 'node:url';
9
+ import { JSDOM } from 'jsdom';
9
10
  import { dirname, join, resolve } from 'node:path';
10
11
 
11
12
  import { loadClientBundle } from './lib/client-bundle.mjs';
@@ -19,34 +20,15 @@ const check = (label, ok) => {
19
20
  else { console.error(' FAIL ' + label); failures.push(label); }
20
21
  };
21
22
 
22
- // --- 浏览器环境的最小替身:插件 apply 期间不碰真实 DOM,只碰样式表那几样 ---
23
- const stubElement = {
24
- dataset: {}, style: {}, appendChild() {}, remove() {}, setAttribute() {},
25
- addEventListener() {}, removeEventListener() {}, classList: { add() {}, remove() {} },
26
- };
27
- const appendedStyles = [];
28
- globalThis.document = {
29
- ...stubElement,
30
- documentElement: stubElement,
31
- body: stubElement,
32
- head: {
33
- ...stubElement,
34
- appendChild: (node) => { appendedStyles.push(node); },
35
- querySelector: () => null,
36
- querySelectorAll: () => [],
37
- },
38
- createElement: () => ({ ...stubElement, id: '', textContent: '' }),
39
- createTextNode: () => ({}),
40
- getElementById: () => null,
41
- querySelector: () => null,
42
- querySelectorAll: () => [],
43
- };
23
+ const dom = new JSDOM();
24
+ globalThis.document = dom.window.document;
44
25
 
45
26
  const { exported, requires } = await loadClientBundle(root);
46
27
 
47
28
  const locales = [];
48
29
  const registrations = [];
49
30
  const errors = [];
31
+ const effects = [];
50
32
 
51
33
  /** cordis 忠实的上下文:读未声明的服务抛 cannot get property "x" without inject。 */
52
34
  function makeCtx(label, declared = []) {
@@ -72,7 +54,11 @@ function makeCtx(label, declared = []) {
72
54
  };
73
55
  const base = {
74
56
  label,
75
- effect: (fn) => { fn(); return () => {}; },
57
+ effect: (fn) => {
58
+ const dispose = fn();
59
+ if (typeof dispose === 'function') effects.push(dispose);
60
+ return dispose;
61
+ },
76
62
  inject: () => () => {},
77
63
  get: (name) => table[name],
78
64
  };
@@ -117,6 +103,15 @@ check('状态卡注册在 plugins.bundle.config 且 key 是包名', card?.option
117
103
  check('状态卡带本插件的字典命名空间', card?.options?.locale === 'kimiCu');
118
104
  check('状态卡组件是个函数', typeof card?.component === 'function');
119
105
 
106
+ const pluginStyles = () => document.head.querySelectorAll(`style[data-plugin="${pkgName}"]`);
107
+ check('启用后挂载插件样式', pluginStyles().length === 1);
108
+ for (const dispose of effects.splice(0).reverse()) dispose();
109
+ check('停用后不残留插件样式', pluginStyles().length === 0);
110
+ exported.apply(makeCtx('restarted', exported.inject ?? []));
111
+ check('重新启用后每张样式各有一份', pluginStyles().length === 1);
112
+ for (const dispose of effects.splice(0).reverse()) dispose();
113
+ dom.window.close();
114
+
120
115
  check('apply 期间没有接线错误', errors.length === 0);
121
116
  for (const error of errors) console.error(' ' + error);
122
117
 
@@ -64,6 +64,7 @@ const t = (key) => zh[key] ?? key;
64
64
  const DEFAULT_UPDATE = { current: '0.7.5', latest: '0.7.5', hasUpdate: false, error: null, checkedAt: 1 };
65
65
 
66
66
  let fetchUrl = '';
67
+ let statusUrl = '';
67
68
  let fetchMethod = 'GET';
68
69
  let fetchBody = null;
69
70
  let fetchCode = 200;
@@ -86,6 +87,7 @@ globalThis.fetch = async (url, init = {}) => {
86
87
  headers: { 'Content-Type': 'application/json' },
87
88
  });
88
89
  }
90
+ statusUrl = fetchUrl;
89
91
  return new Response(JSON.stringify(fetchBody), {
90
92
  status: fetchCode,
91
93
  headers: { 'Content-Type': 'application/json' },
@@ -108,7 +110,7 @@ const BASE = {
108
110
  mcp: { command: '/Applications/KimiCU.app/Contents/MacOS/kimi-cu', args: ['mcp', '-s', 'user'] },
109
111
  install: {
110
112
  command: 'curl -fsSL https://cdn.kimi.com/kimi-computer-use/latest/setup_macos.sh | bash',
111
- steps: ['install', 'grant-permissions', 'reload-plugin'],
113
+ steps: ['install', 'grant-permissions', 'recheck'],
112
114
  docsUrl: 'https://example.com/zh',
113
115
  docsUrlEn: 'https://example.com/en',
114
116
  },
@@ -189,6 +191,7 @@ await test('本机检查通过:显示版本与恢复提示,不再展示安
189
191
  installed: true,
190
192
  path: '/Applications/KimiCU.app/Contents/MacOS/kimi-cu',
191
193
  version: '0.6.8',
194
+ mcpStatus: { state: 'connected' },
192
195
  doctor: { ran: true, ok: true, checks: [{ id: 'accessibility', label: 'Accessibility (AX)', ok: true }], raw: '' },
193
196
  });
194
197
  const text = container.textContent ?? '';
@@ -272,9 +275,23 @@ await test('MCP 命令缺失:即使 doctor 全绿也显示本机检查未通
272
275
  await test('MCP 连接失败时显示原因,即使本机检查通过', async () => {
273
276
  const { container } = await mount({ ...BASE, installed: true, path: '/Applications/KimiCU.app/Contents/MacOS/kimi-cu', doctor: { ran: true, ok: true, checks: [], raw: '' }, mcpStatus: { state: 'failed', lastError: 'launcher failed' } });
274
277
  const text = container.textContent ?? '';
275
- assert.match(text, /MCP 连接失败或正在重连/);
278
+ assert.match(text, /MCP 连接失败/);
276
279
  assert.match(text, /launcher failed/);
277
- assert.match(text, /本机检查未通过/);
280
+ assert.match(text, /MCP 尚未就绪/);
281
+ });
282
+
283
+ await test('本机检查通过但连接未建立时显示实际状态', async () => {
284
+ for (const [mcpStatus, hint] of [
285
+ [null, /MCP 未连接/],
286
+ [{ state: 'connecting' }, /正在连接 MCP/],
287
+ [{ state: 'reconnecting', lastError: 'launcher failed' }, /正在重新连接 MCP.*launcher failed/],
288
+ [{ state: 'conflict', lastError: 'cua-driver-mcp' }, /桌面操作已由其他后端占用.*cua-driver-mcp/],
289
+ ]) {
290
+ const { container, reactRoot } = await mount({ ...BASE, installed: true, doctor: { ...BASE.doctor, ran: true, ok: true }, mcpStatus });
291
+ assert.match(container.textContent ?? '', hint);
292
+ assert.doesNotMatch(container.textContent ?? '', /本机检查通过|MCP 连接失败/);
293
+ await act(async () => { reactRoot.unmount(); });
294
+ }
278
295
  });
279
296
 
280
297
  await test('重新检测请求带 refresh=1', async () => {
@@ -285,7 +302,7 @@ await test('重新检测请求带 refresh=1', async () => {
285
302
  button.click();
286
303
  await new Promise((done) => setTimeout(done, 0));
287
304
  });
288
- assert.match(fetchUrl, /refresh=1/);
305
+ assert.match(statusUrl, /refresh=1/);
289
306
  });
290
307
 
291
308
  const INSTALLED = {
@@ -386,4 +403,16 @@ await test('更新失败:显示分类文案、可展开原始输出与重试',
386
403
  assert.ok(buttonByText(container, '重试') !== undefined);
387
404
  });
388
405
 
406
+ await test('更新流提前结束时显示结果未知,恢复重新检测', async () => {
407
+ const { container } = await mount(INSTALLED, { update: NEWER });
408
+ await act(async () => { buttonByText(container, '更新到 0.7.6').click(); });
409
+ await act(async () => {
410
+ postController.enqueue(new TextEncoder().encode('{"type":"stage","stage":"installing"}\n'));
411
+ postController.close();
412
+ });
413
+ await flush();
414
+ assert.match(container.textContent ?? '', /更新结果未知/);
415
+ assert.equal(buttonByText(container, '重新检测').disabled, false);
416
+ });
417
+
389
418
  console.log('\ntest-card: ' + passed + '/' + total + ' 条断言通过');
@@ -14,6 +14,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt';
14
14
  import ToolRuntime from '@deepseek-ai/dsh-tools';
15
15
 
16
16
  import * as plugin from '../lib/index.js';
17
+ import { createMcpConnection } from '../src/server/mcp.ts';
17
18
 
18
19
  let passed = 0;
19
20
  let total = 0;
@@ -98,14 +99,40 @@ class FakeMcpManager extends Service {
98
99
  this.calls = [];
99
100
  this.disposed = 0;
100
101
  this.status = { state: 'connecting' };
102
+ this.active = undefined;
103
+ this.changed = Promise.withResolvers();
101
104
  }
102
105
 
103
- list() { return this.calls.map(({ name }) => ({ name, status: this.status })); }
106
+ list() { return this.active === undefined ? [] : [{ name: this.active, status: this.status, configured: true }]; }
107
+
108
+ notify() {
109
+ this.changed.resolve();
110
+ this.changed = Promise.withResolvers();
111
+ }
112
+
113
+ async *watch(signal) {
114
+ const aborted = Promise.withResolvers();
115
+ const stop = () => aborted.resolve();
116
+ signal.addEventListener('abort', stop, { once: true });
117
+ try {
118
+ while (!signal.aborted) {
119
+ const pending = this.changed.promise;
120
+ yield this.list();
121
+ await Promise.race([pending, aborted.promise]);
122
+ }
123
+ } finally {
124
+ signal.removeEventListener('abort', stop);
125
+ }
126
+ }
104
127
 
105
128
  register(name, entry) {
106
129
  this.calls.push({ name, entry });
130
+ this.active = name;
131
+ this.notify();
107
132
  return () => {
108
133
  this.disposed += 1;
134
+ this.active = undefined;
135
+ this.notify();
109
136
  };
110
137
  }
111
138
  }
@@ -161,7 +188,13 @@ await test('槽位被别的后端占着时不抢,也不交出工具', async ()
161
188
  await new Promise((resolve) => setTimeout(resolve, 300));
162
189
  assert.equal(cu.providerName, 'cua-driver-mcp', '别的后端占着时不能顶掉它');
163
190
  assert.equal(mcp.calls.length, 0, '占不到位就不该注册 mcp__kimi-cu__* 工具');
191
+ const tool = ctx.tools.get('kimi_cu_status');
192
+ const exec = { signal: new AbortController().signal };
193
+ assert.equal(JSON.parse((await tool.execute({}, exec)).status).mcpStatus.state, 'conflict');
164
194
  await release();
195
+ await tool.execute({ refresh: true }, exec);
196
+ assert.equal(cu.providerName, 'kimi-cu');
197
+ assert.equal(mcp.calls.length, 1);
165
198
  });
166
199
 
167
200
  await test('占位后别的后端再注册会被拒:独占是双向的', async () => {
@@ -174,4 +207,92 @@ await test('占位后别的后端再注册会被拒:独占是双向的', async
174
207
  assert.throws(() => cu.register('cua-driver-mcp'), /already registered/);
175
208
  });
176
209
 
210
+ await test('缺装、缺启动文件或 doctor 失败均不占槽,重新检测后补连', async () => {
211
+ const ctx = host();
212
+ const cu = new FakeComputerUse(ctx);
213
+ const mcp = new FakeMcpManager(ctx);
214
+ const ready = await fakeDetect();
215
+ let status = { ...ready, installed: false };
216
+ plugin.apply(ctx, { detect: async () => status });
217
+ const tool = ctx.tools.get('kimi_cu_status');
218
+ const exec = { signal: new AbortController().signal };
219
+ for (const unavailable of [status, { ...ready, notes: ['mcp-command-missing'] }, { ...ready, doctor: { ...ready.doctor, ok: false } }]) {
220
+ status = unavailable;
221
+ await tool.execute({ refresh: true }, exec);
222
+ assert.equal(cu.providerName, undefined);
223
+ assert.equal(mcp.calls.length, 0);
224
+ }
225
+ status = ready;
226
+ await tool.execute({ refresh: true }, exec);
227
+ assert.equal(cu.providerName, 'kimi-cu');
228
+ assert.equal(mcp.calls.length, 1);
229
+ });
230
+
231
+ await test('MCP 注册失败后释放槽,重检能补连', async () => {
232
+ const ctx = host();
233
+ const cu = new FakeComputerUse(ctx);
234
+ const mcp = new FakeMcpManager(ctx);
235
+ const register = mcp.register.bind(mcp);
236
+ mcp.register = () => { throw new Error('duplicate server'); };
237
+ plugin.apply(ctx, { detect: fakeDetect });
238
+ const tool = ctx.tools.get('kimi_cu_status');
239
+ const exec = { signal: new AbortController().signal };
240
+ const status = JSON.parse((await tool.execute({ refresh: true }, exec)).status);
241
+ assert.equal(cu.providerName, undefined);
242
+ assert.equal(status.mcpStatus.state, 'registration-failed');
243
+ mcp.register = register;
244
+ await tool.execute({ refresh: true }, exec);
245
+ assert.equal(cu.providerName, 'kimi-cu');
246
+ assert.equal(mcp.calls.length, 1);
247
+ });
248
+
249
+ await test('MCP 终态失败后撤回工具并释放独占槽', async () => {
250
+ const ctx = host();
251
+ const cu = new FakeComputerUse(ctx);
252
+ const manager = new FakeMcpManager(ctx);
253
+ plugin.apply(ctx, { detect: fakeDetect });
254
+ await waitFor(() => manager.calls.length === 1, '注册 MCP');
255
+ manager.status = { state: 'failed', lastError: 'launcher failed' };
256
+ manager.notify();
257
+ await waitFor(() => cu.providerName === undefined, '连接失败后释放独占槽');
258
+ const tool = ctx.tools.get('kimi_cu_status');
259
+ const status = JSON.parse((await tool.execute({}, { signal: new AbortController().signal })).status);
260
+ assert.equal(manager.disposed, 1);
261
+ assert.deepEqual(status.mcpStatus, { state: 'failed', lastError: 'launcher failed' });
262
+ });
263
+
264
+ await test('升级后复用管理器的重启,等到 MCP 连通才返回成功', async () => {
265
+ const manager = new FakeMcpManager(host());
266
+ const mcp = createMcpConnection(() => {});
267
+ const status = await fakeDetect();
268
+ const restarted = Promise.withResolvers();
269
+ manager.restart = async (name) => {
270
+ assert.equal(name, 'kimi-cu');
271
+ restarted.resolve();
272
+ };
273
+ await mcp.setManager(manager);
274
+ await mcp.sync(status);
275
+ let finished = false;
276
+ const result = mcp.restart(status).finally(() => { finished = true; });
277
+ await restarted.promise;
278
+ await settle();
279
+ assert.equal(finished, false, 'restart 完成时 MCP 仍在连接');
280
+ manager.status = { state: 'connected' };
281
+ manager.notify();
282
+ assert.equal(await result, true);
283
+ assert.equal(manager.calls.length, 1, '可复用注册时不重复创建');
284
+ await mcp.setManager(undefined);
285
+ });
286
+
287
+ await test('卸载插件时撤回 MCP 注册,然后释放独占槽', async () => {
288
+ const ctx = host();
289
+ const slot = new FakeComputerUse(ctx);
290
+ const manager = new FakeMcpManager(ctx);
291
+ const fiber = ctx.plugin((child) => plugin.apply(child, { detect: fakeDetect }));
292
+ await waitFor(() => slot.providerName === 'kimi-cu', '占用独占槽');
293
+ await fiber.dispose();
294
+ assert.equal(manager.disposed, 1);
295
+ assert.equal(slot.providerName, undefined);
296
+ });
297
+
177
298
  console.log('\ntest-exclusivity: ' + passed + '/' + total + ' 条断言通过');
@@ -57,7 +57,7 @@ await test('macOS 安装计划:官方命令、权限步骤、文档地址', ()
57
57
  const plan = installPlan('darwin');
58
58
  assert.equal(plan.command, MACOS_INSTALL_COMMAND);
59
59
  assert.match(plan.command, /setup_macos\.sh/);
60
- assert.deepEqual(plan.steps, ['install', 'grant-permissions', 'reload-plugin']);
60
+ assert.deepEqual(plan.steps, ['install', 'grant-permissions', 'recheck']);
61
61
  assert.equal(plan.docsUrl, DOCS_URL);
62
62
  assert.equal(plan.docsUrlEn, DOCS_URL_EN);
63
63
  });
@@ -66,7 +66,7 @@ await test('Windows 安装计划:官方 PowerShell 命令、无权限步骤',
66
66
  const plan = installPlan('win32');
67
67
  assert.equal(plan.command, WINDOWS_INSTALL_COMMAND);
68
68
  assert.match(plan.command, /setup_windows\.ps1/);
69
- assert.deepEqual(plan.steps, ['install', 'reload-plugin']);
69
+ assert.deepEqual(plan.steps, ['install', 'recheck']);
70
70
  });
71
71
 
72
72
  await test('不支持的平台没有安装计划', () => {
@@ -10,6 +10,9 @@ import assert from 'node:assert/strict';
10
10
  import { dirname, join, resolve } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
12
 
13
+ import { Context } from '@deepseek-ai/cordis';
14
+ import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection';
15
+
13
16
  import {
14
17
  classifyFailure,
15
18
  compareVersions,
@@ -19,6 +22,9 @@ import {
19
22
  parseStage,
20
23
  } from '../src/server/update.ts';
21
24
 
25
+ import { createStatusRoute } from '../src/server/router.ts';
26
+ import { createUpdateRoute } from '../src/server/update-router.ts';
27
+
22
28
  const root = resolve(process.argv[2] ?? join(dirname(fileURLToPath(import.meta.url)), '..'));
23
29
 
24
30
  let passed = 0;
@@ -196,11 +202,12 @@ await test('run:有新版时先报阶段再执行,版本变了才重连', as
196
202
  assert.equal(calls.upgrade[0].version, null, 'macOS 不带版本号,让 KimiCU 自己判断');
197
203
  });
198
204
 
199
- await test('run:版本没变就不重连', async () => {
205
+ await test('run:版本低于目标时报告无法确认且不重连', async () => {
200
206
  const { updater, calls } = harness({
201
207
  runUpgrade: async () => ({ code: 0, raw: '✓ 升级完成', timedOut: false, whenExited: Promise.resolve() }),
202
208
  });
203
- await collect(updater);
209
+ const events = await collect(updater);
210
+ assert.equal(events.at(-1).kind, 'unconfirmed');
204
211
  assert.equal(calls.reconnect, 0);
205
212
  });
206
213
 
@@ -244,7 +251,7 @@ await test('run:并发调用被单飞锁挡住', async () => {
244
251
  release();
245
252
  await first;
246
253
  const third = await collect(updater);
247
- assert.equal(third.at(-1).type, 'done', '锁要在结束后释放');
254
+ assert.equal(third.at(-1).kind, 'unconfirmed', '锁要在结束后释放');
248
255
  });
249
256
 
250
257
  await test('run:超时归类为 timeout', async () => {
@@ -291,7 +298,7 @@ await test('run:超时后锁留到子进程真的退出', async () => {
291
298
  exit();
292
299
  await new Promise((done) => setTimeout(done, 0));
293
300
  const third = await collect(updater);
294
- assert.equal(third.at(-1).type, 'done', '进程退出后锁要放');
301
+ assert.equal(third.at(-1).kind, 'unconfirmed', '进程退出后锁要放');
295
302
  });
296
303
 
297
304
  await test('run:升级后版本读不出来不算确认变化,不重连', async () => {
@@ -306,7 +313,96 @@ await test('run:升级后版本读不出来不算确认变化,不重连', as
306
313
  });
307
314
  const events = await collect(updater);
308
315
  assert.equal(calls.reconnect, 0);
309
- assert.equal(events.at(-1).reconnect, 'skipped');
316
+ assert.equal(events.at(-1).kind, 'unconfirmed');
317
+ });
318
+
319
+ await test('浏览器断流后升级继续,原进程退出前拒绝第二次升级', async () => {
320
+ const started = Promise.withResolvers();
321
+ const finish = Promise.withResolvers();
322
+ const reconnected = Promise.withResolvers();
323
+ let version = '0.7.5';
324
+ const { updater, calls } = harness({
325
+ current: async () => ({ path: '/fake/kimi-cu', version }),
326
+ runUpgrade: async () => {
327
+ started.resolve();
328
+ await finish.promise;
329
+ version = '0.7.6';
330
+ return { code: 0, raw: '', timedOut: false, whenExited: Promise.resolve() };
331
+ },
332
+ reconnect: async () => { reconnected.resolve(); return true; },
333
+ });
334
+ const route = createUpdateRoute(updater);
335
+ const request = () => new Request('https://example.test' + route.path, { method: 'POST' });
336
+ const first = await route.fetch(request());
337
+ await started.promise;
338
+ await first.body.cancel();
339
+ const second = await route.fetch(request());
340
+ assert.deepEqual(JSON.parse(await second.text()), { type: 'error', kind: 'busy', raw: '' });
341
+ finish.resolve();
342
+ await reconnected.promise;
343
+ assert.equal(version, '0.7.6');
344
+ assert.equal(calls.upgrade.length, 1);
345
+ });
346
+
347
+ await test('Connection 精确路由仅允许已认证的 owner 读状态、重检和更新', async () => {
348
+ const ctx = new Context();
349
+ const authentication = new ConnectionAuthentication(ctx);
350
+ const connection = new HostConnectionService(ctx, []);
351
+ const guest = connection.createPeer({ principal: { kind: 'guest' } });
352
+ authentication.register({
353
+ authenticate({ headers }) {
354
+ switch (headers.get('x-test-peer')) {
355
+ case 'owner': return connection.browserPeer;
356
+ case 'guest': return guest;
357
+ default: return undefined;
358
+ }
359
+ },
360
+ });
361
+
362
+ const detections = [];
363
+ const statusRoute = createStatusRoute(async (refresh) => {
364
+ detections.push(refresh);
365
+ return { version: '0.7.5' };
366
+ });
367
+ const { updater, calls } = harness();
368
+ const updateRoute = createUpdateRoute(updater);
369
+ connection.fetch.register(statusRoute);
370
+ connection.fetch.register(updateRoute);
371
+ const shared = connection.createSharedFetchHandler('/api');
372
+
373
+ const dispatch = (path, method, role) => {
374
+ const headers = { host: 'localhost' };
375
+ if (role !== undefined) headers['x-test-peer'] = role;
376
+ const request = new Request('http://localhost' + path, { method, headers });
377
+ const admission = connection.admit(request);
378
+ return 'rejection' in admission
379
+ ? new Response(null, { status: admission.rejection })
380
+ : shared.fetch(request, admission.peer);
381
+ };
382
+
383
+ const routes = [
384
+ [statusRoute.path, 'GET'],
385
+ [statusRoute.path + '?refresh=1', 'GET'],
386
+ [updateRoute.path, 'GET'],
387
+ [updateRoute.path, 'POST'],
388
+ ];
389
+ for (const [path, method] of routes) {
390
+ assert.equal((await dispatch(path, method)).status, 401);
391
+ assert.equal((await dispatch(path, method, 'guest')).status, 403);
392
+ }
393
+ assert.deepEqual(detections, []);
394
+ assert.equal(calls.fetch.length, 0);
395
+ assert.equal(calls.upgrade.length, 0);
396
+
397
+ for (const [path, method] of routes) {
398
+ const response = await dispatch(path, method, 'owner');
399
+ assert.equal(response.status, 200);
400
+ await response.text();
401
+ }
402
+ assert.deepEqual(detections, [false, true]);
403
+ assert.equal(calls.fetch.length, 2);
404
+ assert.equal(calls.upgrade.length, 1);
405
+ await guest.dispose();
310
406
  });
311
407
 
312
408
  await test('路由常量与包内约定一致', async () => {