File size: 26,089 Bytes
4e23b01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 | import { describe, expect, it, vi } from 'vitest';
import type {
EventSourceRef,
IDisposable,
KlientChannel,
ScopeRef,
} from '../src/core/channel.js';
import { createKlientFromChannel } from '../src/core/klient.js';
import { KlientValidationError } from '../src/core/validation.js';
const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
/** Records calls, replays scripted results, and captures listen subscriptions. */
class FakeChannel implements KlientChannel {
readonly calls: Array<{ scope: ScopeRef; service: string; method: string; args: unknown[] }> = [];
readonly subscriptions: Array<{
scope: ScopeRef;
source: EventSourceRef;
dispose: ReturnType<typeof vi.fn>;
}> = [];
result: unknown;
/** Keyed `${service}.${method}` result overrides. */
readonly results = new Map<string, unknown>();
private readonly handlers = new Map<number, (data: unknown) => void>();
private nextSub = 0;
call(scope: ScopeRef, service: string, method: string, args: unknown[]): Promise<unknown> {
this.calls.push({ scope, service, method, args });
const key = `${service}.${method}`;
return Promise.resolve(this.results.has(key) ? this.results.get(key) : this.result);
}
// eslint-disable-next-line @typescript-eslint/require-await
async *stream(_scope: ScopeRef, _service: string, _method: string, _args: unknown[]): AsyncIterableIterator<unknown> {
// stub — streaming is not exercised in facade tests
}
listen(scope: ScopeRef, source: EventSourceRef, handler: (data: unknown) => void): IDisposable {
const id = this.nextSub;
this.nextSub += 1;
this.handlers.set(id, handler);
const dispose = vi.fn(() => {
this.handlers.delete(id);
});
this.subscriptions.push({ scope, source, dispose });
return { dispose };
}
/** Push a raw payload into the Nth subscription (0-based). */
emit(index: number, data: unknown): void {
this.handlers.get(index)?.(data);
}
close(): Promise<void> {
return Promise.resolve();
}
}
const SUMMARY = {
id: 's1',
workspaceId: 'w1',
createdAt: 1,
updatedAt: 2,
archived: false,
};
describe('facade routing', () => {
it('reshapes single-object params into positional wire args', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.result = { id: 'w1', root: '/x', name: 'n', createdAt: 1, lastOpenedAt: 2 };
await klient.global.workspaces.createOrTouch({ root: '/x', name: 'n' });
expect(channel.calls[0]).toMatchObject({
service: 'workspaceService',
method: 'createOrTouch',
args: ['/x', 'n'],
});
channel.result = undefined; // void output
await klient.global.plugins.setMcpServerEnabled({ id: 'p', server: 's', enabled: true });
expect(channel.calls[1]).toMatchObject({
service: 'pluginService',
method: 'setPluginMcpServerEnabled',
args: [{ id: 'p', server: 's', enabled: true }],
});
channel.results.set('oauthService.status', { loggedIn: false });
await klient.global.auth.status();
expect(channel.calls[2]).toMatchObject({
service: 'oauthService',
method: 'status',
args: [undefined],
});
});
it('forwards the login region option through the wire contract', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.results.set('oauthService.startLogin', {
flow_id: 'f1',
provider: 'managed:kimi-code',
status: 'pending',
verification_uri: 'https://example.com/device',
verification_uri_complete: 'https://example.com/device?user_code=ABCD',
user_code: 'ABCD',
expires_in: 1800,
expires_at: '2026-08-19T15:00:00.000Z',
interval: 5,
});
await klient.global.auth.startLogin('managed:kimi-code', { region: 'global' });
expect(channel.calls[0]).toMatchObject({
service: 'oauthService',
method: 'startLogin',
args: ['managed:kimi-code', { region: 'global' }],
});
});
it('routes capability calls through the registered app service contract', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const status = {
id: 'kimi-cu',
displayName: 'Kimi Computer Use',
description: 'Background GUI automation',
supported: true,
state: 'partial',
steps: [{ id: 'permissions', state: 'missing' }],
// The completed-install note survives the contract parse (not stripped).
install: { running: false, note: 'user-skill-migrated' },
};
channel.result = [status];
await expect(klient.global.capabilities.list()).resolves.toEqual([status]);
channel.result = status;
await expect(klient.global.capabilities.get('kimi-cu')).resolves.toEqual(status);
await expect(klient.global.capabilities.install('kimi-cu')).resolves.toEqual(status);
expect(channel.calls).toEqual([
{ scope: {}, service: 'capabilityService', method: 'listCapabilities', args: [] },
{ scope: {}, service: 'capabilityService', method: 'getCapability', args: ['kimi-cu'] },
{ scope: {}, service: 'capabilityService', method: 'installCapability', args: ['kimi-cu'] },
]);
});
it('env() fans out property reads and merges them', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.result = 'v';
channel.results.set('bootstrapService.clientIdentity', {
productName: 'v',
version: 'v',
platform: 'v',
});
const env = await klient.global.env();
expect(env.platform).toBe('v');
expect(env.logsDir).toBe('v');
expect(env.clientVersion).toBe('v');
expect(channel.calls).toHaveLength(12);
expect(channel.calls.every((call) => call.service === 'bootstrapService')).toBe(true);
});
it('env() resolves once and serves repeats from the cache', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.result = 'v';
channel.results.set('bootstrapService.clientIdentity', {
productName: 'v',
version: 'v',
platform: 'v',
});
await klient.global.env();
expect(channel.calls).toHaveLength(12);
const again = await klient.global.env();
expect(again.platform).toBe('v');
expect(channel.calls).toHaveLength(12);
});
});
describe('agent profile routing', () => {
it('thinking calls route to agentProfileService with the agent scope', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
channel.result = undefined; // void output
await agent.setThinking('on');
expect(channel.calls[0]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentProfileService',
method: 'setThinking',
args: ['on'],
});
channel.result = 'high';
await expect(agent.getThinking()).resolves.toBe('high');
expect(channel.calls[1]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentProfileService',
method: 'getEffectiveThinkingLevel',
args: [],
});
});
});
describe('agent skill routing', () => {
it('promptWithSkills routes to agentSkillService.promptWithSkills with the agent scope', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
channel.result = {
turn_id: 7,
prompt_id: 'p1',
created_at: '2026-01-01T00:00:00.000Z',
state: 'running',
};
await expect(
agent.promptWithSkills({
input: [{ type: 'text', text: 'Review this change.' }],
skills: [{ name: 'review' }, { name: 'security', args: 'src/app.ts' }],
}),
).resolves.toEqual({
turn_id: 7,
prompt_id: 'p1',
created_at: '2026-01-01T00:00:00.000Z',
state: 'running',
});
expect(channel.calls[0]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentSkillService',
method: 'promptWithSkills',
args: [
{
input: [{ type: 'text', text: 'Review this change.' }],
skills: [{ name: 'review' }, { name: 'security', args: 'src/app.ts' }],
},
],
});
});
});
describe('session skills routing', () => {
it('skills.list routes to sessionSkillCatalog.list with the session scope', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const summaries = [
{
name: 'review',
description: 'review changes',
path: '/skills/review/SKILL.md',
source: 'project',
},
];
channel.result = summaries;
await expect(klient.session('s1').skills.list()).resolves.toEqual(summaries);
expect(channel.calls[0]).toEqual({
scope: { sessionId: 's1' },
service: 'sessionSkillCatalog',
method: 'list',
args: [],
});
});
it('skills.changed maps to the sessionSkillCatalog emitter', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const seen: unknown[] = [];
klient.session('s1').events.on('skills.changed', (event) => seen.push(event));
expect(channel.subscriptions[0]?.source).toEqual({
kind: 'emitter',
service: 'sessionSkillCatalog',
event: 'onDidChange',
});
channel.emit(0, 'workspace');
await tick();
expect(seen).toEqual(['workspace']);
});
it('activateSkill routes to agentSkillService with the agent scope', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
channel.result = { turn_id: 3 };
await expect(agent.activateSkill({ name: 'review', args: 'src/app.ts' })).resolves.toEqual({
turn_id: 3,
});
expect(channel.calls[0]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentSkillService',
method: 'activate',
args: [{ name: 'review', args: 'src/app.ts' }],
});
});
it('turn-driving calls route to their domain services with the agent scope', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
const scope = { sessionId: 's1', agentId: 'main' };
channel.results.set('agentPromptService.submit', { turn_id: 1 });
channel.results.set('agentPromptService.submitSteer', { turn_id: 1 });
channel.results.set('agentCommandService.list', []);
await agent.prompt({ input: [{ type: 'text', text: 'hi' }] });
await agent.steer({ input: [{ type: 'text', text: 'steer' }] });
await agent.cancel({ turnId: 2 });
await agent.cancel();
await agent.setPermission('yolo');
await agent.listCommands();
await agent.runCommand({ name: 'cmd', args: 'a b' });
await agent.runCommand({ name: 'plain' });
expect(channel.calls).toEqual([
{
scope,
service: 'agentPromptService',
method: 'submit',
args: [{ input: [{ type: 'text', text: 'hi' }] }],
},
{
scope,
service: 'agentPromptService',
method: 'submitSteer',
args: [{ input: [{ type: 'text', text: 'steer' }] }],
},
{ scope, service: 'agentLoopService', method: 'cancelFromUser', args: [2] },
{ scope, service: 'agentLoopService', method: 'cancelFromUser', args: [] },
{ scope, service: 'agentPermissionModeService', method: 'setModeAndBroadcast', args: ['yolo'] },
{ scope, service: 'agentCommandService', method: 'list', args: [] },
{ scope, service: 'agentCommandService', method: 'run', args: ['cmd', 'a b'] },
{ scope, service: 'agentCommandService', method: 'run', args: ['plain'] },
]);
});
it('getContext merges the contextMemory and tokenCounting reads', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
const scope = { sessionId: 's1', agentId: 'main' };
channel.results.set('agentContextMemoryService.get', [{ role: 'user' }]);
channel.results.set('agentTokenCountingService.statusSize', 42);
await expect(agent.getContext()).resolves.toEqual({
history: [{ role: 'user' }],
tokenCount: 42,
});
expect(channel.calls).toEqual([
{ scope, service: 'agentContextMemoryService', method: 'get', args: [] },
{ scope, service: 'agentTokenCountingService', method: 'statusSize', args: [] },
]);
});
});
describe('agent mcp / compaction routing', () => {
it('getMcpServers returns the live snapshot with the agent scope', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
const entries = [
{ name: 'mock', transport: 'stdio', status: 'pending', toolCount: 0 },
];
channel.results.set('agentMcpService.list', entries);
await expect(agent.getMcpServers()).resolves.toEqual(entries);
expect(channel.calls[0]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentMcpService',
method: 'list',
args: [],
});
expect(channel.calls).toHaveLength(1);
});
it('compact issues a manual begin with the optional instruction', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
channel.result = true;
await expect(agent.compact()).resolves.toBe(true);
expect(channel.calls[0]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentFullCompactionService',
method: 'begin',
args: [{ source: 'manual', instruction: undefined }],
});
channel.result = false;
await expect(agent.compact({ instruction: 'keep the plan' })).resolves.toBe(false);
expect(channel.calls[1]).toEqual({
scope: { sessionId: 's1', agentId: 'main' },
service: 'agentFullCompactionService',
method: 'begin',
args: [{ source: 'manual', instruction: 'keep the plan' }],
});
});
});
describe('session lifecycle routing', () => {
it('delete calls the App session manager', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.results.set('sessionManager.delete', undefined);
await klient.session('s1').delete();
expect(channel.calls).toEqual([
{ scope: {}, service: 'sessionManager', method: 'delete', args: ['s1'] },
]);
});
it('restore forwards resume options to the App session manager', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.results.set('sessionManager.restore', { id: 's1', kind: 'session' });
const opts = {
mcpServers: { example: { transport: 'stdio' as const, command: 'node' } },
};
await expect(klient.session('s1').restore(opts)).resolves.toBe(true);
expect(channel.calls[0]).toEqual({
scope: {},
service: 'sessionManager',
method: 'restore',
args: ['s1', opts],
});
});
it('sessions.create forwards mcpServers to the App session manager', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.results.set('sessionManager.create', { id: 's1', kind: 'session' });
channel.results.set('sessionMetadata.read', {
id: 's1',
createdAt: 1,
updatedAt: 2,
archived: false,
});
const mcpServers = {
example: { transport: 'stdio' as const, command: 'node', args: ['server.mjs'] },
};
await klient.global.sessions.create({ workDir: '/x', mcpServers });
expect(channel.calls[0]).toMatchObject({
scope: {},
service: 'sessionManager',
method: 'create',
args: [{ workDir: '/x', mcpServers }],
});
});
it('sessions.create rejects malformed mcpServers before the call leaves the client', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
await expect(
klient.global.sessions.create({
workDir: '/x',
mcpServers: { bad: { transport: 'http', url: 'not-a-url' } },
}),
).rejects.toBeInstanceOf(KlientValidationError);
expect(channel.calls.some((call) => call.method === 'create')).toBe(false);
});
});
describe('contract validation', () => {
it('rejects invalid input before the call leaves the client', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
await expect(
klient.global.sessions.list({ limit: '20' as unknown as number }),
).rejects.toBeInstanceOf(KlientValidationError);
expect(channel.calls).toHaveLength(0);
});
it('rejects drifted output payloads', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.result = { id: 's1' }; // missing required SessionSummary fields
await expect(klient.global.sessions.get('s1')).rejects.toBeInstanceOf(KlientValidationError);
});
it('passes valid payloads through and returns parsed output', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.result = SUMMARY;
await expect(klient.global.sessions.get('s1')).resolves.toEqual(SUMMARY);
});
it('validate:false skips both directions', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel, { validate: false });
channel.result = { anything: true };
await expect(
klient.global.sessions.list({ limit: '20' as unknown as number }),
).resolves.toEqual({ anything: true });
});
});
describe('event hub', () => {
it('maps public names to emitter sources and validates payloads', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const seen: unknown[] = [];
const errors: Error[] = [];
klient.events.onError((error) => {
errors.push(error);
});
klient.events.on('kosong.providers.changed', (event) => seen.push(event));
expect(channel.subscriptions[0]?.source).toEqual({
kind: 'emitter',
service: 'providerService',
event: 'onDidChangeProviders',
});
channel.emit(0, { added: ['p1'], removed: [], changed: [] });
channel.emit(0, { added: 'not-an-array' });
await tick();
expect(seen).toEqual([{ added: ['p1'], removed: [], changed: [] }]);
expect(errors).toHaveLength(1);
expect(errors[0]).toBeInstanceOf(KlientValidationError);
});
it('shares one bus subscription across bus-derived events and filters by type', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const archived: unknown[] = [];
const catalog: unknown[] = [];
const subA = klient.events.on('session.archived', (event) => archived.push(event));
const subB = klient.events.on('kosong.changed', (event) => catalog.push(event));
expect(channel.subscriptions).toHaveLength(1);
expect(channel.subscriptions[0]?.source).toEqual({ kind: 'stream', name: 'events' });
channel.emit(0, { type: 'event.session.archived', payload: { sessionId: 's1' } });
channel.emit(0, { type: 'event.model_catalog.changed', payload: { changed: [], unchanged: [], failed: [] } });
channel.emit(0, { type: 'unrelated.type', payload: {} });
await tick();
expect(archived).toEqual([{ sessionId: 's1' }]);
expect(catalog).toEqual([{ changed: [], unchanged: [], failed: [] }]);
subA.dispose();
expect(channel.subscriptions[0]?.dispose).not.toHaveBeenCalled();
subB.dispose();
expect(channel.subscriptions[0]?.dispose).toHaveBeenCalledTimes(1);
});
it('delivers session.metaUpdated when the patch carries no lastPrompt', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const seen: unknown[] = [];
const errors: Error[] = [];
klient.events.onError((error) => {
errors.push(error);
});
klient.events.on('session.metaUpdated', (event) => seen.push(event));
channel.emit(0, {
type: 'session.meta.updated',
payload: {
agentId: 'main',
sessionId: 's1',
title: 'generated title',
patch: { title: 'generated title', isCustomTitle: false },
},
});
await tick();
expect(seen).toEqual([
{
agentId: 'main',
sessionId: 's1',
title: 'generated title',
patch: { title: 'generated title', isCustomTitle: false },
},
]);
expect(errors).toHaveLength(0);
});
it('disposes the emitter subscription when the last listener detaches', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const a = klient.events.on('config.changed', () => undefined);
const b = klient.events.on('config.changed', () => undefined);
expect(channel.subscriptions).toHaveLength(1);
a.dispose();
expect(channel.subscriptions[0]?.dispose).not.toHaveBeenCalled();
b.dispose();
expect(channel.subscriptions[0]?.dispose).toHaveBeenCalledTimes(1);
});
it('forwards the newly registered agent stream events and validates payloads', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
const agent = klient.session('s1').agent('main');
const seen = {
delta: [] as unknown[],
progress: [] as unknown[],
started: [] as unknown[],
blocked: [] as unknown[],
cancelled: [] as unknown[],
completed: [] as unknown[],
};
const errors: Error[] = [];
agent.events.onError((error) => {
errors.push(error);
});
agent.events.on('tool.call.delta', (event) => seen.delta.push(event));
agent.events.on('tool.progress', (event) => seen.progress.push(event));
agent.events.on('compaction.started', (event) => seen.started.push(event));
agent.events.on('compaction.blocked', (event) => seen.blocked.push(event));
agent.events.on('compaction.cancelled', (event) => seen.cancelled.push(event));
agent.events.on('compaction.completed', (event) => seen.completed.push(event));
// All six registrations share one `events` stream subscription bound to
// the agent scope.
expect(channel.subscriptions).toHaveLength(1);
expect(channel.subscriptions[0]?.scope).toEqual({ sessionId: 's1', agentId: 'main' });
expect(channel.subscriptions[0]?.source).toEqual({ kind: 'stream', name: 'events' });
const delta = { type: 'tool.call.delta', turnId: 1, toolCallId: 'tc1', name: 'Bash', argumentsPart: '{"command":' };
const progress = {
type: 'tool.progress',
turnId: 1,
toolCallId: 'tc1',
update: { kind: 'stdout', text: 'chunk' },
};
const started = { type: 'compaction.started', trigger: 'auto' };
const blocked = { type: 'compaction.blocked', turnId: 2 };
const cancelled = { type: 'compaction.cancelled' };
const completed = {
type: 'compaction.completed',
result: { summary: 's', compactedCount: 3, tokensBefore: 100, tokensAfter: 40 },
};
channel.emit(0, delta);
channel.emit(0, progress);
channel.emit(0, started);
channel.emit(0, blocked);
channel.emit(0, cancelled);
channel.emit(0, completed);
channel.emit(0, { type: 'tool.progress', turnId: 1, toolCallId: 'tc1' }); // missing update
channel.emit(0, { type: 'unregistered.type', turnId: 1 });
await tick();
expect(seen.delta).toEqual([delta]);
expect(seen.progress).toEqual([progress]);
expect(seen.started).toEqual([started]);
expect(seen.blocked).toEqual([blocked]);
expect(seen.cancelled).toEqual([cancelled]);
expect(seen.completed).toEqual([completed]);
expect(errors).toHaveLength(1);
expect(errors[0]).toBeInstanceOf(KlientValidationError);
});
});
describe('files routing', () => {
const META = {
id: 'f_1',
name: 'a.png',
media_type: 'image/png',
size: 4,
created_at: '2026-01-01T00:00:00.000Z',
};
it('routes the files save/get/delete lifecycle through fileService', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
channel.result = META;
const meta = await klient.global.files.save({
data: new Uint8Array([1, 2, 3, 4]),
filename: 'a.png',
mimeType: 'image/png',
});
expect(meta).toEqual(META);
expect(channel.calls[0]).toMatchObject({
scope: {},
service: 'fileService',
method: 'save',
args: ['AQIDBA==', 'a.png', { mimeType: 'image/png' }],
});
channel.result = { meta: META, data: 'AQIDBA==' };
const got = await klient.global.files.get('f_1');
expect(got.meta).toEqual(META);
expect([...got.data]).toEqual([1, 2, 3, 4]);
expect(channel.calls[1]).toMatchObject({
scope: {},
service: 'fileService',
method: 'get',
args: ['f_1'],
});
channel.result = undefined;
await expect(klient.global.files.delete('f_1')).resolves.toBeUndefined();
expect(channel.calls[2]).toMatchObject({
scope: {},
service: 'fileService',
method: 'delete',
args: ['f_1'],
});
});
it('files.save rejects invalid input before it hits the wire', async () => {
const channel = new FakeChannel();
const klient = createKlientFromChannel(channel);
await expect(
klient.global.files.save({ data: new Uint8Array(0), filename: '' }),
).rejects.toBeInstanceOf(KlientValidationError);
expect(channel.calls).toHaveLength(0);
});
});
|