@lynn123411/dsh-kimi-cu 0.3.1 → 0.3.3

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.
@@ -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 ?? '';
@@ -266,7 +269,29 @@ await test('MCP 命令缺失:即使 doctor 全绿也显示本机检查未通
266
269
  });
267
270
  const text = container.textContent ?? '';
268
271
  assert.match(text, /已安装 KimiCU,但本机检查未通过/);
269
- assert.match(text, /MCP 行要启动的文件不存在/);
272
+ assert.match(text, /MCP 启动文件不存在/);
273
+ });
274
+
275
+ await test('MCP 连接失败时显示原因,即使本机检查通过', async () => {
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' } });
277
+ const text = container.textContent ?? '';
278
+ assert.match(text, /MCP 连接失败/);
279
+ assert.match(text, /launcher failed/);
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
+ }
270
295
  });
271
296
 
272
297
  await test('重新检测请求带 refresh=1', async () => {
@@ -277,7 +302,7 @@ await test('重新检测请求带 refresh=1', async () => {
277
302
  button.click();
278
303
  await new Promise((done) => setTimeout(done, 0));
279
304
  });
280
- assert.match(fetchUrl, /refresh=1/);
305
+ assert.match(statusUrl, /refresh=1/);
281
306
  });
282
307
 
283
308
  const INSTALLED = {
@@ -378,4 +403,16 @@ await test('更新失败:显示分类文案、可展开原始输出与重试',
378
403
  assert.ok(buttonByText(container, '重试') !== undefined);
379
404
  });
380
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
+
381
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;
@@ -97,12 +98,41 @@ class FakeMcpManager extends Service {
97
98
  super(ctx, 'mcpManager');
98
99
  this.calls = [];
99
100
  this.disposed = 0;
101
+ this.status = { state: 'connecting' };
102
+ this.active = undefined;
103
+ this.changed = Promise.withResolvers();
104
+ }
105
+
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
+ }
100
126
  }
101
127
 
102
128
  register(name, entry) {
103
129
  this.calls.push({ name, entry });
130
+ this.active = name;
131
+ this.notify();
104
132
  return () => {
105
133
  this.disposed += 1;
134
+ this.active = undefined;
135
+ this.notify();
106
136
  };
107
137
  }
108
138
  }
@@ -123,6 +153,22 @@ await test('组合里没有 computerUse 时行为不变:照常注册 MCP 连
123
153
  assert.equal(mcp.calls[0].name, 'kimi-cu');
124
154
  });
125
155
 
156
+ await test('状态工具返回实时 MCP 连接失败与恢复', async () => {
157
+ const ctx = host();
158
+ const mcp = new FakeMcpManager(ctx);
159
+ plugin.apply(ctx, { detect: fakeDetect });
160
+ await waitFor(() => mcp.calls.length === 1, '注册 MCP');
161
+ const tool = ctx.tools.get('kimi_cu_status');
162
+ const exec = { signal: new AbortController().signal };
163
+ mcp.status = { state: 'failed', lastError: 'launcher failed' };
164
+ let status = JSON.parse((await tool.execute({}, exec)).status);
165
+ assert.equal(status.mcpStatus.state, 'failed');
166
+ assert.equal(status.mcpStatus.lastError, 'launcher failed');
167
+ mcp.status = { state: 'connected' };
168
+ status = JSON.parse((await tool.execute({}, exec)).status);
169
+ assert.equal(status.mcpStatus.state, 'connected');
170
+ });
171
+
126
172
  await test('槽位空着时先占位,占到了才注册 MCP 连接', async () => {
127
173
  const ctx = host();
128
174
  const cu = new FakeComputerUse(ctx);
@@ -142,7 +188,13 @@ await test('槽位被别的后端占着时不抢,也不交出工具', async ()
142
188
  await new Promise((resolve) => setTimeout(resolve, 300));
143
189
  assert.equal(cu.providerName, 'cua-driver-mcp', '别的后端占着时不能顶掉它');
144
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');
145
194
  await release();
195
+ await tool.execute({ refresh: true }, exec);
196
+ assert.equal(cu.providerName, 'kimi-cu');
197
+ assert.equal(mcp.calls.length, 1);
146
198
  });
147
199
 
148
200
  await test('占位后别的后端再注册会被拒:独占是双向的', async () => {
@@ -155,4 +207,92 @@ await test('占位后别的后端再注册会被拒:独占是双向的', async
155
207
  assert.throws(() => cu.register('cua-driver-mcp'), /already registered/);
156
208
  });
157
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
+
158
298
  console.log('\ntest-exclusivity: ' + passed + '/' + total + ' 条断言通过');
@@ -12,6 +12,7 @@ import {
12
12
  DOCS_URL,
13
13
  DOCS_URL_EN,
14
14
  MACOS_BINARY,
15
+ MACOS_MCP_LAUNCHER,
15
16
  MACOS_INSTALL_COMMAND,
16
17
  WINDOWS_INSTALL_COMMAND,
17
18
  } from '../src/shared/status.ts';
@@ -56,7 +57,7 @@ await test('macOS 安装计划:官方命令、权限步骤、文档地址', ()
56
57
  const plan = installPlan('darwin');
57
58
  assert.equal(plan.command, MACOS_INSTALL_COMMAND);
58
59
  assert.match(plan.command, /setup_macos\.sh/);
59
- assert.deepEqual(plan.steps, ['install', 'grant-permissions', 'reload-plugin']);
60
+ assert.deepEqual(plan.steps, ['install', 'grant-permissions', 'recheck']);
60
61
  assert.equal(plan.docsUrl, DOCS_URL);
61
62
  assert.equal(plan.docsUrlEn, DOCS_URL_EN);
62
63
  });
@@ -65,19 +66,19 @@ await test('Windows 安装计划:官方 PowerShell 命令、无权限步骤',
65
66
  const plan = installPlan('win32');
66
67
  assert.equal(plan.command, WINDOWS_INSTALL_COMMAND);
67
68
  assert.match(plan.command, /setup_windows\.ps1/);
68
- assert.deepEqual(plan.steps, ['install', 'reload-plugin']);
69
+ assert.deepEqual(plan.steps, ['install', 'recheck']);
69
70
  });
70
71
 
71
72
  await test('不支持的平台没有安装计划', () => {
72
73
  assert.equal(installPlan('other'), null);
73
74
  });
74
75
 
75
- await test('macOS:找到二进制时 installed 为真,MCP 命令带 -s user', () => {
76
- const resolved = resolveInstall({ platform: 'darwin', env: {}, exists: (path) => path === MACOS_BINARY });
76
+ await test('macOS:找到二进制和官方启动脚本时使用 CodeAct', () => {
77
+ const resolved = resolveInstall({ platform: 'darwin', env: {}, exists: (path) => [MACOS_BINARY, MACOS_MCP_LAUNCHER].includes(path) });
77
78
  assert.equal(resolved.supported, true);
78
79
  assert.equal(resolved.installed, true);
79
80
  assert.equal(resolved.path, MACOS_BINARY);
80
- assert.deepEqual(resolved.mcp, { command: MACOS_BINARY, args: ['mcp', '-s', 'user'] });
81
+ assert.deepEqual(resolved.mcp, { command: MACOS_MCP_LAUNCHER, args: ['mcp', '-s', 'user', '--surface', 'codeact'] });
81
82
  assert.deepEqual(resolved.notes, []);
82
83
  });
83
84
 
@@ -85,7 +86,14 @@ await test('macOS:没找到二进制时 installed 为假,但 MCP 命令仍
85
86
  const resolved = resolveInstall({ platform: 'darwin', env: {}, exists: () => false });
86
87
  assert.equal(resolved.installed, false);
87
88
  assert.equal(resolved.path, null);
88
- assert.equal(resolved.mcp.command, MACOS_BINARY);
89
+ assert.equal(resolved.mcp.command, MACOS_MCP_LAUNCHER);
90
+ });
91
+
92
+ await test('macOS:启动脚本缺失时报告未就绪,不回退旧入口', () => {
93
+ const resolved = resolveInstall({ platform: 'darwin', env: {}, exists: (path) => path === MACOS_BINARY });
94
+ assert.equal(resolved.installed, true);
95
+ assert.deepEqual(resolved.notes, ['mcp-command-missing']);
96
+ assert.equal(resolved.mcp.command, MACOS_MCP_LAUNCHER);
89
97
  });
90
98
 
91
99
  await test('Windows:新目录存在时用它,MCP 命令与 patch 表达式一致', () => {
@@ -171,6 +179,20 @@ await test('macOS doctor:五项全绿时 ok 为真,id 映射对得上', () =
171
179
  assert.equal(parsed.version, null);
172
180
  });
173
181
 
182
+ await test('macOS doctor:以服务权限为准,忽略调用进程的权限', () => {
183
+ const raw = [
184
+ 'Service (authoritative — the launchd Service performs the actions):',
185
+ '✅ Accessibility (AX)', '✅ Screen Recording', '✅ Runtime control channel: listening',
186
+ 'This process (diagnostic only — a terminal’s TCC grants differ from the Service’s):',
187
+ '❌ Screen Recording',
188
+ ].join('\n');
189
+ const report = parseDoctor('darwin', raw);
190
+ assert.equal(report.ok, true);
191
+ assert.equal(report.checks.length, 3);
192
+ const failed = parseDoctor('darwin', raw.replace('✅ Accessibility (AX)', '❌ Accessibility (AX)'));
193
+ assert.equal(failed.ok, false);
194
+ });
195
+
174
196
  await test('macOS doctor:有一项失败时 ok 为假', () => {
175
197
  const parsed = parseDoctor('darwin', MAC_DOCTOR_BAD);
176
198
  assert.equal(parsed.ok, false);
@@ -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 () => {
@@ -1,105 +1,36 @@
1
1
  ---
2
2
  name: kimi-cu
3
3
  description: |
4
- 使用 KimiCU 读取和操作本机 macOS app:查看界面或截图,点击、输入、滚动、拖拽,以及列出应用和窗口。用户需要代为操作桌面界面时使用;仅讨论或修改 app 代码时不需要。
4
+ 使用 KimiCU CodeAct 读取和操作本机 macOS 应用或浏览器网页,包括观察、点击、输入、滚动和拖拽。用户需要代为操作桌面或浏览器时使用;仅讨论或修改代码时不需要。
5
5
  ---
6
6
 
7
- # kimi-cu — macOS 后台 GUI 操作
7
+ # kimi-cu — macOS CodeAct 操作
8
8
 
9
- 通过 KimiCU MCP 的无障碍(AX)树和截图观察界面,再定向操作目标应用。参数以当前工具 schema 为准;本 skill 说明目标绑定、操作选择和验证规则。
9
+ DSH 的 KimiCU MCP 提供 `js` 和 `js_reset`(完整工具名为 `mcp__kimi-cu__js` / `mcp__kimi-cu__js_reset`)。通过它们调用运行时自带的 `cua`,无需 import;参数和可用 API 以当前工具描述及 `cua.help()` 为准。工具缺失或连接失败时先调用 `kimi_cu_status`,报告安装或修复结果。
10
10
 
11
- DSH 把这些工具注册为 `mcp__kimi-cu__<name>`(例如 `mcp__kimi-cu__list_apps`);下文用去掉前缀的短名指代。
11
+ ## 观察与操作
12
12
 
13
- 如果 `mcp__kimi-cu__*` 工具不存在或连接失败,先调用 DSH 的 `kimi_cu_status` 工具查安装状态与修复步骤,把结论转告用户;不要在缺装时假装能操作。
13
+ 1. 用 `await cua.listApps({running_only:true})` 找应用,从返回对象的 `apps` 数组选择目标;用 `cua.getApp(bundle_id)` 创建句柄。首次调用只做发现或观察,并读取返回的 API 参考。
14
+ 2. 用 `app.getState({mode:"ax"})` 读界面;需要截图用 `mode:"image"`,确需两者时用 `mode:"full"`。多窗口先用 `app.listWindows()` 找窗口,再观察目标窗口。
15
+ 3. 基于本次观察选择唯一目标;按 index 操作时传相应的 `snapshot_id`。坐标使用所选截图的像素,并绑定该图的 `window_id` 和 `screenshot_id`;AX bbox 是窗口内点坐标,不能当截图像素。
16
+ 4. 执行动作后观察并验证实际结果,检查 `verified`、`effect` 和 `verification_required`。投递成功不等于生效;结果不明时先观察,不盲目重放。
14
17
 
15
- ## 操作边界
18
+ 界面变化、窗口切换或快照过期后重新观察。默认 AX 树可能被截断;目标可能遗漏时用 `app.getState({mode:"ax",offset:0})` 开始分页,按返回的 `next_offset` 和 `snapshot_id` 续读直到 `has_more` 为 false。分页过期或被新观察替换后重新开始。
16
19
 
17
- - 默认后台操作,不自行激活应用、抬窗或开启前台 fallback。永不移动真实光标、使用 HID 投递或拦截用户真实点击;不要用 AppleScript / cliclick 等绕过这些限制。
18
- - `activate_window` 会把目标窗口带到前台并取得键盘焦点;只有用户明确要求把窗口切到前面时才用,其余情况保持后台投递。
19
- - 前台应用、键盘焦点、窗口层叠顺序是不同状态;`foreground_changed:false` 不能单独证明窗口未抬起。发现抬窗或打断用户输入时,停止相关重试并如实说明。
20
- - 发送、提交、删除、付款等动作须在用户已明确授权的目标和范围内;已有授权不重复确认,缺少必要信息时再问。
20
+ 表单整体赋值优先 `app.setValue`;聊天框和富文本优先定向 `app.typeText`。替换内容时显式 `clear:true`,追加前确认插入点。输入和发送分开判断,只在任务包含发送时提交。滚动优先使用 `page`(正数向上),滚动后重新定位。
21
21
 
22
- ## 观察与目标绑定
22
+ 同窗口批量笔画可用 `app.drag({paths,...})`;保留用户操作守卫。批量不是事务,检查 `delivered` 和 `results`,结合画面确定完成情况后只处理剩余路径。
23
23
 
24
- 1. 目标不明确时优先用 `list_apps(running_only:true)` / `list_windows` 定位已打开的应用和窗口,避免输出全部安装目录。需要找尚未启动的应用时才用 `list_apps(running_only:false)`;不传参数同样包含已安装用户应用,内部 helper 和系统后台组件已过滤。需要把尚未运行的应用启动起来时用 `launch_app`,它只启动,不激活。
25
- 2. 用 MCP `get_app_state` 观察目标;后续 index 和坐标必须来自这次观察。`mode:"full"` 返回树和图,`mode:"image"` 适合看图、浮层和视觉验证,`mode:"ax"` 适合读文本及按 index 操作;`ax_filter` 可缩小树的输出。
26
- 3. 只需要某一个窗口(尤其是浮窗)时,用 `get_window_state` 传 `window_id`,**同时要给 `app` 或 `pid`**(只给 `window_id` 会报 `app or pid required`);用 `include_screenshot` / `include_text` 选择截图与 AX 文本;`get_window` 只用来把窗口标识解析成 app、pid 与标题。
27
- 4. 执行动作;页面切换、滚动、弹窗或布局变化影响目标时,重新观察再决定下一步。
28
- 5. 验证任务要求的结果。投递成功不等于生效;尤其检查 `verified`、`verification_required`、`effect`,必要时再次观察。
24
+ ## 浏览器与 JS 会话
29
25
 
30
- 坐标纪律:
26
+ 浏览器任务使用 `cua.createTab`、`cua.listBrowserTabs` 或 `cua.attachTab`,再通过标签页对象观察和操作。页面动作使用当前观察的 ref,导航或重渲染后重新观察。浏览器功能关闭时引导用户开启,不绕过开关;扩展及本地服务须已连接。
31
27
 
32
- - `click` / `scroll` / `drag` / 定向 `type_text` 的 x/y 是所用截图的像素坐标,不是屏幕坐标。不要自行换算缩放比例。`mode:"ax"` 的 bbox 是窗口内点坐标,不能直接当作截图像素点击;用 index 或重新取图。
33
- - 多窗口及浮层从 `screenshots[]` 选正确图片,传其 `window_id`;支持 `screenshot_id` 的动作同时传图片标识(主图为响应的 `screenshot_id`,数组项为 `id`)。浮窗必须用浮窗自己的图和窗口,不能省略窗口让路由猜测,也不能借用主图坐标。
34
- - `rect:{x,y,width,height}` 使用窗口内点坐标,并把该窗口的当前截图锚点切到局部区域。区域图内的操作直接使用区域图像素;改回全窗坐标前重新取全窗图。歧义、过期或越界报错时重新观察,不强行换算重试。
35
- - 正常观察使用 MCP;不要用 shell 的 `kimi-cu shot` / `app-state` / `windows` 代替。开发调试 CLI 不刷新 MCP 快照缓存。
28
+ DSH 的多个会话共用一条 MCP 连接及其持久 JS 状态,变量、句柄和 `js_reset` 会互相影响;跨会话没有隔离。多个会话操作 KimiCU 时必须错开,不能把持久变量当作私有数据。一次性调用优先用 `scope:"cell"`,但它仍可读取已有持久变量,不是隔离机制。已确定的操作可以放在同一 cell,遇到需要判断的新界面时先返回观察结果。异常可能发生在部分动作完成之后;检查错误结果与实际界面。重连或 `js_reset` 不会撤销动作,重连后重新发现目标,不沿用旧句柄、快照或截图。
36
29
 
37
- ## 输入与编辑
30
+ ## 操作边界与排障
38
31
 
39
- - 普通表单整体赋值优先 `set_value`。聊天框、富文本输入优先 `type_text` 并显式指定 `index`,或使用已绑定窗口的截图 x/y。需要替换时显式 `clear:true`;保留原文插入时用 `clear:false`,追加前确认插入点在末尾。
40
- - 只需聚焦或放置光标时可用 `click(index)` / 坐标点击。点击失败或未建立文本焦点时,重新观察,不能继续盲目输入。
41
- - 不带 index/x/y 的 `type_text` 和 `paste` 依赖目标应用的实际文本焦点;无焦点失败时改为定向聚焦。`paste` 可携带富文本,按返回的验证要求检查内容及格式。
42
- - 富文本编辑交给输入工具处理,不绕过工具直接写 AXValue,也不用“清空再恢复”修复内容。验证失败可能已有部分效果,先读取现状,不盲目重贴或覆盖原文。
43
- - 输入和发送分开判断;仅在任务包含发送时使用 `submit` / `autosubmit` 或发送按钮。
32
+ 默认后台操作,不移动真实光标或用其他工具绕过限制;只有任务需要且用户已授权前台操作时才激活窗口。发送、删除、付款等动作以用户已授权的目标和范围为准。
44
33
 
45
- ## 点击、滚动与批量
34
+ 缺少 `js` / `js_reset` 时检查 KimiCU 安装版本、官方启动脚本和 MCP 连接;更新插件后重连 MCP,已有会话仍显示旧工具时新建会话。重连后先用 `console.log(cua.help())` 和 `console.log(await cua.listApps({running_only:true}))` 做只读验证。
46
35
 
47
- - 优先使用目标实际提供的 AX 动作;动作名称来自观察结果。弹上下文菜单可用 `perform_secondary_action` 的 `AXShowMenu`,网页右键手势也可用 `click(mouse_button:"right")`,并观察结果。
48
- - 原生列表可用 `scroll(index, dy)`,按 AX 动作以整页粒度滚动;页面指定位置用截图 x/y。`dy>0` 向上。滚动后重新定位受影响的目标。
49
- - `effect:"unverifiable"` + `verified:false` 表示投递完成但效果未验证(遮挡窗口或 CEF 原生 chrome 目标;点击已不做像素校验);不能当作任务已完成,要重新观察核对是否达到预期。
50
- - 动作未生效时先重新观察目标和状态,再选择界面提供的等价操作。不要连续盲重试,也不要为了绕过失败改做会产生不同结果的动作。
51
- - 全遮挡且已节流的 Chromium/CEF 窗口会静默吞掉或分钟级延迟窗口路由事件:自动通道点击无效时,可用 `click(channel:"public")`——整段序列(hover/primer/down/up)以带窗口号的 NSEvent 工厂事件经 postToPid 投递,导航、聚焦、按钮全有效。被吞事件可能分钟级后才执行,不要因此盲目重发同一点位;先重新观察再按次决定。
52
- - 目标稳定、后续步骤能用代码判断的批量操作逐个 `await`;DSH 注册的 KimiCU MCP 只有 18 个直接工具,没有 `js` / `js_reset`。下一步需要模型读新截图时,先返回观察结果再决定下一步。同一窗口的多条笔画用 `drag_paths`,见下文。
53
-
54
- ## 批量操作
55
-
56
- DSH 注册的是 KimiCU MCP 的 18 个直接工具:`list_apps`、`launch_app`、`list_windows`、`get_window`、`activate_window`、`get_app_state`、`get_window_state`、`click`、`type_text`、`paste`、`press_key`、`scroll`、`set_value`、`perform_secondary_action`、`select_text`、`drag`、`drag_paths`、`debug_tap`。没有 CodeAct 的 `js` / `js_reset`,也没有浏览器标签页工具;需要批量就逐个 `await`,不要临时搭一个运行时。
57
-
58
- ### drag_paths
59
-
60
- 用于同一窗口内已规划好的笔画、拖动或短路径;不替代需要逐步观察的导航点击。
61
-
62
- - 每批 1–500 条路径,每项为 `{points:[[x,y], ...], steps?, hold_ms?, step_ms?}`。每条至少两个点;dab 可用两个相近点。
63
- - 必须显式传 `window_id`,并使用该窗口最近一次图像观察的像素坐标。当前服务的该路径不消费 `screenshot_id`,不能靠它单独选窗或恢复旧截图锚点。批内不切换窗口/坐标系。
64
- - 传 `abort_if_cursor_in_window:true` 保持用户操作守卫。用户在窗口内移动真实鼠标或按住鼠标时会拒投或中途停止;光标静止在窗口内本身不触发。触发后等待用户停止相关操作,重新观察再继续,不关闭守卫硬投。
65
- - 批量不是事务,已投笔画不回滚。普通工具返回 `results`、`delivered`、`total`,中断时可能带 `cursor_in_window:true`。结合界面核对后,仅处理未完成路径;中途止投可从第一个 false 位置续作,其他失败须逐项检查,不能整批重放。
66
- - 无法确定哪些笔画已完成时,先核对画面和错误信息;不能猜测断点或重新提交整个批次。
67
-
68
- ## 排障与升级
69
-
70
- ### 先根据结果分流
71
-
72
- - 歧义窗口、坐标越界或旧 index:按前文重新绑定窗口和观察,不重装或抢前台。
73
- - 缺图/黑图:先看 `screenshot_diagnosis`,区分最小化、窗口关闭、其他 Space、锁屏、未渲染和权限问题。需要用户恢复窗口或切回所在桌面时明确说明,不自行切 Space。
74
- - **连续两次截图字节完全相同**:窗口被遮挡或停在别的 Space 时,截图会一直返回同一帧,看着像「按键没生效」。别据此重试投递——先 `activate_window` 或看 `screenshot_diagnosis`,再判断动作到底有没有落下去。
75
- - 窗口在另一个 Space 或另一块屏幕上时,AX 树照常可读、动作照常可投递,但截图取不到(`screenshot_diagnosis` 报 `not on-screen` 或 `no shareable content`)。这时用 AX 文本验证结果,不要据此判断权限丢失或动作失败;`activate_window` 的 `foreground_changed:true` 也不证明窗口已经来到当前 Space。
76
- - 空 AX 树也可能是自绘或远程渲染控件;有可用截图时可按图操作,不直接认定权限丢失。
77
- - `unknown field` / `KIMI_CU_UNKNOWN_FIELD`:先核对当前入口的 schema;刚升级时优先排查旧 MCP 桥和 JS 内核,不能据此直接断言新功能不存在。
78
- - 怀疑某个进程收不到事件时,用 `debug_tap` 在服务侧记录它的投递事件;它不改变界面,也不是常规操作入口。排查完如实报告结论,不要靠反复投递试探。
79
-
80
- ### 服务和权限
81
-
82
- KimiCU 的权限由 launchd 后台 Service 持有。`kimi-cu doctor` 检查调用者上下文,不能代替服务权限判断。仅在服务连接或权限故障时使用以下只读 CLI:
83
-
84
- ```bash
85
- ls /Applications/KimiCU.app/Contents/MacOS/kimi-cu
86
- /Applications/KimiCU.app/Contents/MacOS/kimi-cu service-status
87
- /Applications/KimiCU.app/Contents/MacOS/kimi-cu xpc-ping
88
- ```
89
-
90
- `xpc-ping` 应报告 `accessibility=true`、`screenRecording=true`;运行时连接还可看 `runtimeSocket` 是否 listening。
91
-
92
- - app 不存在:说明需要安装。用户要求安装或已授权时执行官方安装流程:
93
- ```bash
94
- curl -fsSL https://cdn.kimi.com/kimi-computer-use/latest/setup_macos.sh | bash
95
- ```
96
- - 服务未注册:用 `/Applications/KimiCU.app/Contents/MacOS/kimi-cu install` 注册,再检查状态。已经注册但仍不通时保留错误信息继续定位,不反复 install。
97
- - 服务明确报告权限缺失:运行 `/Applications/KimiCU.app/Contents/MacOS/kimi-cu request-permissions --ax --screen`,提示用户在系统设置为 KimiCU 开启缺失权限;系统授权开关由用户操作。完成后检查 `xpc-ping` 并重试观察。
98
-
99
- ### 升级后的连接
100
-
101
- 收到新版本提示时转告用户:插件页的 KimiCU 卡片上有更新按钮,也可以运行 `kimi-cu upgrade`。不要仅因有新版就中断任务或自行升级。
102
-
103
- 服务升级不会自动替换长寿的 MCP 桥。插件页的更新按钮在升级成功后会自动重连 MCP;手动升级后在客户端重连 KimiCU MCP(支持 `/mcp` 的客户端可用该入口)即可。
104
-
105
- CLI 只用于排障/安装维护;日常取图、取坐标和操作仍用 MCP。
36
+ 权限由 KimiCU 后台服务持有。服务或权限故障时可用 `/Applications/KimiCU.app/Contents/MacOS/kimi-cu xpc-ping` 检查;需要系统授权时引导用户操作。日常观察和输入使用 CodeAct,不用 CLI 截图生成坐标。用户明确要求恢复服务时可用 `/Applications/KimiCU.app/Contents/MacOS/kimi-cu fix --json`;它会重建服务并结束旧 CodeAct 会话,事后重连并重新观察。