File size: 12,263 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 | import { existsSync } from 'node:fs';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
drainQueryStoreDisposals,
drainSessionIndexMirror,
ISessionIndex,
ISessionIndexMirror,
} from '@moonshot-ai/agent-core-v2';
import { createKimiHarness, SDKRpcClientV2 } from '#/index';
import type { KimiError } from '#/index';
import { TEST_IDENTITY } from './test-identity';
const tempDirs: string[] = [];
afterEach(async () => {
for (const dir of tempDirs.splice(0)) {
await removeTempDir(dir);
}
});
async function removeTempDir(dir: string): Promise<void> {
for (let attempt = 0; attempt < 10; attempt += 1) {
try {
await rm(dir, { recursive: true, force: true });
return;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== 'ENOTEMPTY' && code !== 'EBUSY' && code !== 'EPERM') {
throw error;
}
await delay(10);
}
}
await rm(dir, { recursive: true, force: true });
}
async function makeTempDir(): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), 'kimi-sdk-list-'));
tempDirs.push(dir);
return dir;
}
describe('KimiHarness.listSessions', () => {
it('rejects whitespace-only workDir with request.work_dir_required', async () => {
const homeDir = await makeTempDir();
const harness = createKimiHarness({
identity: TEST_IDENTITY,
homeDir,
});
try {
await expect(harness.listSessions({ workDir: ' ' })).rejects.toMatchObject({
name: 'KimiError',
code: 'request.work_dir_required',
} satisfies Partial<KimiError>);
} finally {
await harness.close();
}
});
it('lists all sessions when no payload is provided', async () => {
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const otherWorkDir = await makeTempDir();
const harness = createKimiHarness({
identity: TEST_IDENTITY,
homeDir,
});
try {
await harness.createSession({ id: 'ses_harness_all_a', workDir });
await harness.createSession({ id: 'ses_harness_all_b', workDir: otherWorkDir });
const sessions = await harness.listSessions();
expect(sessions.map((session) => session.id).toSorted()).toEqual([
'ses_harness_all_a',
'ses_harness_all_b',
]);
} finally {
await harness.close();
}
});
it('lists a session from a workDir containing spaces and non-ASCII characters', async () => {
const homeDir = await makeTempDir();
const root = await makeTempDir();
const workDir = join(root, 'Workspace With Spaces', '项目');
await mkdir(workDir, { recursive: true });
const harness = createKimiHarness({
identity: TEST_IDENTITY,
homeDir,
});
try {
const session = await harness.createSession({ id: 'ses_unicode_workdir', workDir });
const sessions = await harness.listSessions({ workDir });
expect(sessions.map((item) => item.id)).toEqual([session.id]);
} finally {
await harness.close();
}
});
it('resolves relative workDir inputs before filtering', async () => {
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const harness = createKimiHarness({
identity: TEST_IDENTITY,
homeDir,
});
const originalCwd = process.cwd();
try {
process.chdir(workDir);
const session = await harness.createSession({ id: 'ses_relative_workdir', workDir: '.' });
const sessions = await harness.listSessions({ workDir: '.' });
expect(sessions.map((item) => item.id)).toEqual([session.id]);
} finally {
process.chdir(originalCwd);
await harness.close();
}
});
it('lists persisted sessions after the active Session has been closed', async () => {
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const harness = createKimiHarness({
identity: TEST_IDENTITY,
homeDir,
});
try {
const session = await harness.createSession({ id: 'ses_closed_but_listed', workDir });
await harness.closeSession(session.id);
const sessions = await harness.listSessions({ workDir });
expect(sessions.map((item) => item.id)).toEqual([session.id]);
} finally {
await harness.close();
}
});
});
describe('SDKRpcClientV2.listSessionsPage', () => {
it('pages through the listing with keyset cursors (read model off)', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_PERSISTENCE_MINIDB_READMODEL', '0');
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const client = new SDKRpcClientV2({ homeDir, identity: TEST_IDENTITY });
try {
for (let i = 0; i < 5; i += 1) {
const created = await client.createSession({ id: `ses_page_${i}`, workDir });
await client.closeSession({ sessionId: created.id });
}
const page1 = await client.listSessionsPage({ workDir, limit: 2 });
expect(page1.items).toHaveLength(2);
expect(page1.nextCursor).toBe(page1.items.at(-1)?.id);
const page2 = await client.listSessionsPage({ workDir, limit: 2, before: page1.nextCursor });
expect(page2.items).toHaveLength(2);
expect(page2.nextCursor).toBe(page2.items.at(-1)?.id);
const page3 = await client.listSessionsPage({ workDir, limit: 2, before: page2.nextCursor });
expect(page3.items).toHaveLength(1);
expect(page3.nextCursor).toBeUndefined();
const pagedIds = [...page1.items, ...page2.items, ...page3.items].map((item) => item.id);
expect(new Set(pagedIds)).toEqual(
new Set([0, 1, 2, 3, 4].map((i) => `ses_page_${String(i)}`)),
);
// Draining pages yields exactly the unpaged listing, in the same order.
const full = await client.listSessions({ workDir });
expect(pagedIds).toEqual(full.map((item) => item.id));
} finally {
await client.close();
vi.unstubAllEnvs();
}
});
it('answers an empty terminal page for an unknown cursor', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_PERSISTENCE_MINIDB_READMODEL', '0');
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const client = new SDKRpcClientV2({ homeDir, identity: TEST_IDENTITY });
try {
const created = await client.createSession({ id: 'ses_cursor_probe', workDir });
await client.closeSession({ sessionId: created.id });
await expect(
client.listSessionsPage({ workDir, before: 'ses_unknown' }),
).resolves.toEqual({ items: [], nextCursor: undefined });
} finally {
await client.close();
vi.unstubAllEnvs();
}
});
it('drains follow-up pages when the mapping drops entries (read model on)', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_PERSISTENCE_MINIDB_READMODEL', '1');
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const client = new SDKRpcClientV2({ homeDir, identity: TEST_IDENTITY });
try {
for (let i = 0; i < 3; i += 1) {
const created = await client.createSession({ id: `ses_drain_${i}`, workDir });
await client.closeSession({ sessionId: created.id });
}
const index = client.engineAccessor.get(ISessionIndex);
await index.prepare();
// A summary whose workDir can no longer be resolved (unknown workspace,
// no cwd) is dropped by the mapping; the page must still fill.
client.engineAccessor.get(ISessionIndexMirror).record({
id: 'ses_ghost',
workspaceId: 'ws_missing',
createdAt: 1,
updatedAt: Date.now() + 60_000,
archived: false,
});
await drainSessionIndexMirror();
const page1 = await client.listSessionsPage({ limit: 2 });
expect(page1.items).toHaveLength(2);
expect(page1.items.some((item) => item.id === 'ses_ghost')).toBe(false);
expect(page1.nextCursor).toBeDefined();
const page2 = await client.listSessionsPage({ limit: 2, before: page1.nextCursor });
expect(page2.items).toHaveLength(1);
expect(page2.items[0]?.id).not.toBe('ses_ghost');
expect(page2.nextCursor).toBeUndefined();
const ids = [...page1.items, ...page2.items].map((item) => item.id).toSorted();
expect(ids).toEqual(['ses_drain_0', 'ses_drain_1', 'ses_drain_2']);
} finally {
await client.close();
// Dispose fired the mirror/query-store async closes; await them before
// the shared afterEach removes the temp home.
await drainSessionIndexMirror();
await drainQueryStoreDisposals();
vi.unstubAllEnvs();
}
});
});
describe('SDKRpcClientV2 search-index separation', () => {
// The global full-text search database (`<homeDir>/search-index`) belongs
// to the kap-server search surface. The TUI-side chain (rpc client →
// klient → `ISessionIndex`) must list, resume and continue sessions without
// ever opening it — including while the session read model is still
// preparing.
it('listSessions / resumeSession never open the global search index (read model off)', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_PERSISTENCE_MINIDB_READMODEL', '0');
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const client = new SDKRpcClientV2({ homeDir, identity: TEST_IDENTITY });
try {
const created = await client.createSession({ id: 'ses_search_sep_off', workDir });
await client.closeSession({ sessionId: created.id });
const sessions = await client.listSessions({ workDir });
expect(sessions.map((item) => item.id)).toEqual([created.id]);
const resumed = await client.resumeSession({ id: created.id });
expect(resumed.id).toBe(created.id);
expect(existsSync(join(homeDir, 'search-index'))).toBe(false);
// With the read model off, the session query-store is never opened either.
expect(existsSync(join(homeDir, 'cache', 'query-store'))).toBe(false);
} finally {
await client.close();
vi.unstubAllEnvs();
}
});
it('listSessions / resumeSession never open the global search index (read model on)', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_PERSISTENCE_MINIDB_READMODEL', '1');
const homeDir = await makeTempDir();
const workDir = await makeTempDir();
const client = new SDKRpcClientV2({ homeDir, identity: TEST_IDENTITY });
try {
const created = await client.createSession({ id: 'ses_search_sep_on', workDir });
await client.closeSession({ sessionId: created.id });
// The read model is still preparing here: the first list kicks the
// background projection and answers from authoritative metadata, the
// resume reads the authoritative document — neither waits for, nor
// opens, any full-text index.
const sessions = await client.listSessions({ workDir });
expect(sessions.map((item) => item.id)).toEqual([created.id]);
const resumed = await client.resumeSession({ id: created.id });
expect(resumed.id).toBe(created.id);
expect(existsSync(join(homeDir, 'search-index'))).toBe(false);
// Settle the kicked projection before close so teardown never races it,
// and prove the read model really did engage (the flag took effect).
const status = await client.engineAccessor.get(ISessionIndex).prepare();
expect(status.state).toBe('ready');
expect(existsSync(join(homeDir, 'cache', 'query-store'))).toBe(true);
expect(existsSync(join(homeDir, 'search-index'))).toBe(false);
} finally {
await client.close();
// Dispose fired the mirror/query-store async closes; await them before
// the shared afterEach removes the temp home.
await drainSessionIndexMirror();
await drainQueryStoreDisposals();
vi.unstubAllEnvs();
}
});
});
|