Files
plugins/packages/kimi-work/kimi-work.test.mjs
T
Changtian Li 280d522830 kimi-work 0.1.15: renew membership tokens and keep existing accounts (#218)
Explicit sign-in now imports Kimi desktop's membership access/refresh pair
when the desktop has one, and magpie renews it through the host's
auth.refresh (conditional commit under the auth-store lock). Accounts saved
through 0.1.14 (reference-only, no pair) keep reading the desktop's web
token for usage, with no reconnect, no import and no refresh spent. The
usage card is one monthly meter, with Code's share as text. Request-body
reads follow the caller's abort signal.

Kept from main (0.1.11 to 0.1.14): callback errors split into no session /
Work 401 / HTTP-timeout-network (#425), per-uid account ids
`Kimi Work · <uid6>` (#440), share-folder-missing as kept (#444),
spent-quota 403 -> 429 (#465).

Reviewed head 96f7f52501082e4747ef649d836d955a8ece3f4c, merged onto
origin/main fdc5002 locally (clean), run on mote (macOS, Bun 1.4.2) with
HOME=$(mktemp -d):
- bun test packages/kimi-work: 99 pass, 0 fail
- bun test (whole repo): 3681 pass, 8 skip, 0 fail
- bun scripts/check.mjs: all packages pass

Broken by hand, each red in packages/kimi-work:
- legacy (no pair) usage throws expired: 7 fail
- callback 401 folded into the generic error: 3 fail
- callback network error folded into "no session": 3 fail
- accountId back to 'Kimi Work (local)': 2 fail
- AuthService 401 marked signIn expired: 2 fail
- refresh hook returning a pair for a legacy account: 2 fail

Version 0.1.15: main has 0.1.14; npm has no kimi-work package (served
from dist, highest 0.1.14), so 0.1.15 is free.

Not tried: a live Kimi sign-in or renewal at this head. The author's
live coexistence evidence is one cycle on 2026-10-24 at f67d742
(COMPATIBILITY.md). The rewritten COMPATIBILITY.md replaces main's 0.1.4
macOS record; that record stays in git history at fdc5002.
2026-10-30 01:34:05 +08:00

150 lines
9.4 KiB
JavaScript

import {test, expect} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {_internal as I} from './index.mjs';
const session = {uid: 'synthetic-account', workToken: 'synthetic-work-token', webToken: 'synthetic-web-token', webRefresh:'synthetic-refresh-token'};
const auth = {source: 'kimi-work-desktop', uid: session.uid,access:session.webToken,refresh:session.webRefresh,expires:0};
const models = {data: [{id: 'k3-agent', display_name: 'K3', context_length: 1000000,
supports_image_in: true, supports_reasoning: true, reasoningEffortOptions: [{effort: 'REASONING_EFFORT_LOW'}, {effort: 'REASONING_EFFORT_MAX'}]}]};
test('sign-in imports web renewal credentials and dynamic models/usage retain Work accounting', async () => {
const calls = [];
const p = I.createPlugin({readSession: () => session, fetchImpl: async (url, init) => {
calls.push({url, init});
return Response.json(url.endsWith('/models') ? models : {subscriptionBalance: {amountUsedRatio: 0.42}, ratelimitCode5h: {ratio: 1}});
}});
const result = await (await p.auth.methods[0].authorize()).callback();
expect(result).toMatchObject({type: 'success', source: auth.source, uid: auth.uid});
expect(JSON.stringify(result)).not.toContain(session.workToken);
expect(result).toMatchObject({access:session.webToken,refresh:session.webRefresh});
const catalog = await p.provider.models({models: {}}, {auth});
expect(catalog['k3-agent'].limit.context).toBe(262144);
expect(Object.keys(catalog['k3-agent'].variants)).toEqual(['low', 'max']);
expect((await p.auth.usage(async () => auth)).windows).toEqual([{name: '本月', used: 42}]);
expect(calls.at(-1).init.headers.Authorization).toBe('Bearer ' + session.webToken);
});
test('requests preserve prompts, tools, streaming and cancellation while rotating only Work credentials', async () => {
let live = {...session}; const calls = [];
const p = I.createPlugin({readSession: () => live, fetchImpl: async (url, init) => {
calls.push({url, init}); return new Response('data: [DONE]\n\n', {headers: {'Content-Type': 'text/event-stream'}});
}});
const loader = await p.auth.loader(async () => auth);
const body = JSON.stringify({model: 'k3-agent', messages: [{role: 'system', content: 'synthetic shared instruction'}],
tools: [{type: 'function', function: {name: 'Read', parameters: {type: 'object'}}}], stream: true});
const signal = new AbortController().signal;
const request = new Request(I.BASE + '/chat/completions', {method: 'POST', body, signal,
headers: {Authorization: 'Bearer synthetic-code-token', Cookie: 'synthetic-cookie'}});
expect(await (await loader.fetch(request)).text()).toBe('data: [DONE]\n\n');
expect(await new Response(calls[0].init.body).text()).toBe(body);
expect(calls[0].init.headers.get('authorization')).toBe('Bearer ' + session.workToken);
expect(calls[0].init.headers.get('cookie')).toBeNull();
expect(calls[0].init.signal.aborted).toBe(false);
live.workToken = 'synthetic-rotated';
await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body, signal});
expect(calls[1].init.headers.get('authorization')).toBe('Bearer synthetic-rotated');
live.uid = 'different-account';
await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body})).rejects.toMatchObject({signIn: 'expired'});
expect(calls).toHaveLength(2);
});
test('a rejected desktop token requires reconnecting the provider', async () => {
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => new Response('{}', {status: 401})});
const loader = await p.auth.loader(async () => auth);
await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST'}))
.rejects.toMatchObject({signIn: 'expired', code: 'kimi_work_login_expired'});
});
for (const {name, status, body, type} of [
{name: 'concurrency 429 retains rate-limit wording without adding quota wording', status: 429,
body: JSON.stringify({error: {type: 'rate_limit_error', code: 'concurrency_limit', message: 'Too many requests'}}), type: 'application/json'},
{name: 'quota 429 retains the upstream allowance and reset details', status: 429,
body: JSON.stringify({error: {type: 'quota_exceeded', message: 'Plan quota exhausted', resetsAt: '2030-01-01T00:00:00Z'}}), type: 'application/json'},
{name: '5xx retains even a non-JSON upstream failure', status: 502, body: 'Bad gateway: upstream unavailable', type: 'text/plain'},
]) test(name, async () => {
const upstream = new Response(body, {status, statusText: 'Upstream failure', headers: {'Retry-After': '30', 'Content-Type': type}});
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => upstream});
const loader = await p.auth.loader(async () => auth);
const response = await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body: '{}'});
expect(response).toBe(upstream);
expect(response.status).toBe(status);
expect(response.headers.get('retry-after')).toBe('30');
expect(response.headers.get('content-type')).toBe(type);
expect(await response.text()).toBe(body);
});
test('network failures keep diagnostic causes and ordinary fetch messages', async () => {
for (const error of [Error('fetch failed', {cause: {code: 'ENOTFOUND'}}), Error('proxy connection refused')]) {
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => {throw error;}});
const loader = await p.auth.loader(async () => auth);
await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST'})).rejects.toMatchObject({
code: 'kimi_work_connection_failed', cause: error,
message: 'Kimi Work 连接失败:' + (error.cause?.code || error.message),
});
}
});
test('cancellation keeps the original abort error', async () => {
const controller = new AbortController(), error = new DOMException('Cancelled', 'AbortError');
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => {controller.abort(); throw error;}});
const loader = await p.auth.loader(async () => auth);
await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST', signal: controller.signal})).rejects.toBe(error);
});
test('desktop import is read-only and never substitutes a Code endpoint', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kimi-provider-fixture-'));
const file = path.join(dir, 'config.json');
const doc = {credentials: {kimiCode: {apiKey: session.workToken, baseUrl: I.BASE},
kimiWeb: {accessToken: session.webToken, userId: 'synthetic-user'}}};
try {
fs.writeFileSync(file, JSON.stringify(doc)); const before = fs.readFileSync(file);
expect(I.readDesktop(file).workToken).toBe(session.workToken);
expect(fs.readFileSync(file)).toEqual(before);
doc.credentials.kimiCode.baseUrl = 'https://api.kimi.com/coding/v1'; fs.writeFileSync(file, JSON.stringify(doc));
expect(() => I.readDesktop(file)).toThrow();
} finally {fs.rmSync(dir, {recursive: true, force: true});}
});
test('the Work token goes only to the official Work chat endpoint', async () => {
let called = 0;
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => {called++; return new Response('{}');}});
const loader = await p.auth.loader(async () => auth);
for (const url of ['https://example.invalid/coding/v1/chat/completions', I.BASE + '/models',
I.BASE + '/chat/completions?x=1', 'https://user:pw@agent-gw.kimi.com/coding/v1/chat/completions']) {
await expect(loader.fetch(url, {method: 'POST', body: '{}'})).rejects.toThrow('仅接受官方');
}
await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'GET'})).rejects.toThrow('仅接受官方');
expect(called).toBe(0);
});
// #465 (kongbai01203): Kimi answered a spent account with a 403, which magpie
// took for a key fault and kept routing to. The words are the reporter's own
// (usage.jsonl and `magpie provider test kimi-work`); the issue doesn't show
// the JSON around them, so both an OpenAI-style and a Connect-style body are
// tried.
for (const body of [
JSON.stringify({error: {message: "You've reached your usage limit for this billing cycle.", type: 'permission_denied_error'}}),
JSON.stringify({code: 'resource_exhausted', message: 'insufficient balance'}),
JSON.stringify({error: {code: 'resource_exhausted', message: 'insufficient balance'}}),
]) test('a spent allowance\'s 403 goes out as a 429 with Kimi\'s words: ' + body, async () => {
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => new Response(body,
{status: 403, headers: {'Content-Type': 'application/json', 'Retry-After': '3600'}})});
const loader = await p.auth.loader(async () => auth);
const response = await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body: '{}'});
expect(response.status).toBe(429);
expect(response.headers.get('retry-after')).toBe('3600');
expect(response.headers.get('content-type')).toBe('application/json');
expect(await response.text()).toBe(body);
});
test('a 403 that is not about the allowance stays a 403', async () => {
const body = JSON.stringify({error: {message: 'Access denied for this model', type: 'permission_denied_error'}});
const p = I.createPlugin({readSession: () => session, fetchImpl: async () => new Response(body, {status: 403})});
const loader = await p.auth.loader(async () => auth);
const response = await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body: '{}'});
expect(response.status).toBe(403);
expect(await response.text()).toBe(body);
});