Files
plugins/packages/kimi-desktop/native-guards.test.mjs
T
Changtian Li bc5b8332ec kimi-desktop 0.1.6: per-role reasoning effort and context input budget (#813)
kimi-desktop 0.1.6: separate reasoning effort and an optional context input budget for the primary and secondary roles.

The change (f07e7f4a..1d14a185, since the round-6 approval):
- The settings page and API save `<role>ReasoningEffort` and `<role>ContextTokens` for each role. Only efforts and context limits the catalog publishes are offered; an unknown limit allows no custom budget.
- Inference drops Kimi's top-level `thinking`, `reasoning` and `reasoning_effort`, and sends the chosen effort, or none for the provider default. Kimi's native menu aliases no longer choose the model.
- A custom budget counts a copy of the request through magpie's `/v1/messages/count_tokens`. Over the budget gives 400 `context_length_exceeded`; a failed count gives fixed 503 `context_count_unavailable`. No generation is sent in either case. Without a budget, nothing extra is sent.
- Role-scoped worker profiles (`v2:[model, role]`) tell primary from secondary even on the same model. Older roleless profiles keep their binding and use defaults.
- 1d14a185 removes blank lines only.

Run at 1d14a1859f63fd4bb512d492d1de419ad3e6c79a on mote (macOS, Bun 1.4.2, HOME/TMPDIR/XDG in the run's own folder):
- `bun test` in packages/kimi-desktop: 626 pass, 0 fail, 29 files.
- `bun scripts/check.mjs kimi-desktop`: exit 0.
- 14 hand breaks, each red in the package suite:
  - drop `applyReasoningOptions`;
  - strip thinking fields only when an effort is set;
  - drop the budget check, or make it `>=`;
  - `useFresh` false, or without its model check;
  - a legacy roleless profile treated as primary;
  - a profile name without its role;
  - no `registerRoles`;
  - no `optionsMatch` in save;
  - no `refreshLiveModelOptions`;
  - count with `redirect: 'follow'`, or with no reply size limit;
  - a 131072 fallback for an unknown catalog context.
- CI at the head: test and on-npm pass. The PR merges onto main f379bf90+ with no conflicts.

Not blocking, left for a follow-up:
- Each inference now reads connection.json (adapter.mjs:547) with no fallback to the live connection. An unreadable file turns every request into 502, even without a budget.
- The comment above `applyReasoningOptions` ("Preserve the legacy connection untouched…") no longer matches the always-strip policy.
2026-11-09 10:07:07 +08:00

127 lines
6.6 KiB
JavaScript

// These exercise the production file commit and authenticated control client.
// All files and tokens are synthetic; the WebSocket server is loopback only.
import { test, expect } from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { KimiAdapter } from './adapter.mjs';
import { rpc as rpcCall } from './rpc.mjs';
test('native secondary commit refuses stale bytes and preserves the other writer exactly', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'magpie-kimi-commit-'));
try {
const adapter = Object.create(KimiAdapter.prototype);
adapter.nativeConfigFile = path.join(directory, 'config.toml');
const original = 'default_model = "k2d8-preview"\n# initial settings\n';
fs.writeFileSync(adapter.nativeConfigFile, original, { mode: 0o600 });
const bytes = fs.readFileSync(adapter.nativeConfigFile);
const target = original + '\n[secondary_model]\nmodel = "synthetic-new-alias"\n';
// Another writer changes only unrelated bytes after we computed the patch.
// Comparing parsed secondary fields would miss the comment and CRLF edit.
const otherWriter = Buffer.from('default_model = "k2d8-preview"\r\n# other writer: 保留字节\r\n');
fs.writeFileSync(adapter.nativeConfigFile, otherWriter);
expect(() => adapter.commitNativeSecondary(bytes, target)).toThrow('kimi_config_changed');
expect(fs.readFileSync(adapter.nativeConfigFile).equals(otherWriter)).toBe(true);
expect(fs.readFileSync(adapter.nativeConfigFile, 'utf8')).not.toContain('synthetic-new-alias');
expect(fs.readdirSync(directory)).toEqual(['config.toml']);
} finally { fs.rmSync(directory, { recursive: true, force: true }); }
});
const kernelSessionId = 'synthetic-kernel-session';
const reloadCases = [
['kimiPlugin.reloadActiveSessions', {}, { sessions: [{ kernelSessionId, status: 'reloaded' }] }],
['kimiPlugin.ReloadSession', { kernelSessionId }, { status: 'reloaded' }],
['kimiPlugin.installPlugin', { source: '/synthetic/role-plugin' }, { id: 'synthetic-role-plugin', enabled: true }],
['kimiPlugin.updatePlugin', { source: '/synthetic/role-plugin' }, { id: 'synthetic-role-plugin', enabled: true }],
['kimiPlugin.getPluginInfo', { id: 'synthetic-role-plugin' }, { id: 'synthetic-role-plugin', enabled: true }],
['kimiPlugin.setPluginEnabled', { id: 'synthetic-role-plugin', enabled: true }, { id: 'synthetic-role-plugin', enabled: true }],
['kimiPlugin.removePlugin', { id: 'synthetic-role-plugin' }, { ok: true }],
];
for (const [method, params, acknowledgement] of reloadCases) {
test(`production RPC sends ${method} and receives its acknowledgement`, async () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'magpie-kimi-control-'));
const token = 'synthetic-synthetic-control-token';
const handshakes = [], messages = [];
let server;
try {
server = Bun.serve({
hostname: '127.0.0.1', port: 0,
fetch(request, listener) {
handshakes.push({ path: new URL(request.url).pathname,
authorization: request.headers.get('authorization') });
if (new URL(request.url).pathname !== '/control'
|| request.headers.get('authorization') !== 'Bearer ' + token) {
return new Response('synthetic unauthorized', { status: 401 });
}
if (listener.upgrade(request)) return;
return new Response('WebSocket required', { status: 400 });
},
websocket: {
message(socket, data) {
const message = JSON.parse(String(data));
messages.push(message);
socket.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: acknowledgement }));
},
},
});
const runnerFile = path.join(directory, 'agents/main/runner.state.json');
fs.mkdirSync(path.dirname(runnerFile), { recursive: true });
fs.writeFileSync(runnerFile, JSON.stringify({ lifecycleStatus: 'running',
daemonGeneration: 'synthetic-generation',
control: { endpoint: { url: `ws://127.0.0.1:${server.port}/control`, auth: { token } } },
}), { mode: 0o600 });
const runner = JSON.parse(fs.readFileSync(runnerFile, 'utf8'));
await expect(rpcCall(runner, method, params, { timeout: 1000 })).resolves.toEqual(acknowledgement);
expect(handshakes).toEqual([{ path: '/control', authorization: 'Bearer ' + token }]);
expect(messages).toEqual([{ jsonrpc: '2.0', id: 1, method, params }]);
// Reject unknown names before opening another authenticated connection.
await expect(rpcCall(runner, 'kimiPlugin.unknownMethod', {}, { timeout: 1000 }))
.rejects.toThrow('unsupported_control_method');
expect(handshakes).toHaveLength(1);
expect(messages).toHaveLength(1);
} finally {
if (server) await server.stop(true);
fs.rmSync(directory, { recursive: true, force: true });
}
});
}
for (const [label, method, code, reasonCode, expected] of [
['confirmed plugin missing', 'kimiPlugin.getPluginInfo', -32003, 'KIMI_PLUGIN_NOT_FOUND', 'kimi_plugin_not_found'],
['generic rejection', 'kimiPlugin.getPluginInfo', -32000, 'KIMI_PLUGIN_NOT_FOUND', 'kimi_control_rejected'],
['unrelated not found', 'kimiPlugin.getPluginInfo', -32003, 'OTHER_NOT_FOUND', 'kimi_control_rejected'],
['unrelated method', 'models.current', -32003, 'KIMI_PLUGIN_NOT_FOUND', 'kimi_control_rejected'],
]) {
test('production RPC exposes only the fixed category for ' + label, async () => {
const token = 'synthetic-error-envelope-token';
const server = Bun.serve({
hostname: '127.0.0.1', port: 0,
fetch(request, listener) {
if (request.headers.get('authorization') !== 'Bearer ' + token) return new Response('', { status: 401 });
if (listener.upgrade(request)) return;
return new Response('', { status: 400 });
},
websocket: { message(socket, input) {
const request = JSON.parse(String(input));
socket.send(JSON.stringify({ jsonrpc: '2.0', id: request.id, error: {
code, message: 'synthetic private remote detail',
data: { reasonCode, unrelated: 'synthetic private data' },
} }));
} },
});
try {
const runner = { control: { endpoint: {
url: 'ws://127.0.0.1:' + server.port + '/control', auth: { token },
} } };
const failure = await rpcCall(runner, method, { id: 'synthetic-role-plugin' }, { timeout: 1000 }).catch(error => error);
expect(failure).toBeInstanceOf(Error);
expect(failure.message).toBe(expected);
expect(Object.keys(failure)).toEqual([]);
} finally { await server.stop(true); }
});
}