File size: 19,382 Bytes
7c5ed63 | 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 | // apps/vis/server/test/lib/session-store.test.ts
import { describe, it, expect, afterEach } from 'vitest';
import { buildSessionFixture } from '../fixtures/build';
import { isSafeAgentId, listSessions, readSessionDetail } from '../../src/lib/session-store';
describe('session-store', () => {
let cleanup: (() => Promise<void>) | null = null;
afterEach(async () => { if (cleanup) await cleanup(); cleanup = null; });
it('lists native session with correct timestamps and counts', async () => {
const { home, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const sessions = await listSessions(home);
expect(sessions).toHaveLength(1);
const s = sessions[0]!;
expect(s.sessionId).toBe('session_fixture');
expect(s.title).toBe('fixture: hello world');
expect(s.lastPrompt).toBe('say hi');
expect(s.agentCount).toBe(2);
expect(s.mainAgentExists).toBe(true);
expect(s.mainWireRecordCount).toBe(10); // 10 lines in main wire incl. metadata
expect(s.wireProtocolVersion).toBe('1.1');
expect(s.health).toBe('ok');
expect(s.workDir).toBe('/tmp/work');
expect(s.createdAt).toBe(Date.parse('2026-05-20T05:59:51.085Z'));
expect(s.updatedAt).toBe(Date.parse('2026-05-21T03:12:08.000Z'));
});
it('treats a v1.0 wire as healthy (vis migrates on read)', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const wirePath = join(sessionDir, 'agents', 'main', 'wire.jsonl');
const lines = (await readFile(wirePath, 'utf8')).split('\n');
lines[0] = JSON.stringify({ type: 'metadata', protocol_version: '1.0', created_at: 1 });
await writeFile(wirePath, lines.join('\n'));
const sessions = await listSessions(home);
expect(sessions[0]!.health).toBe('ok');
expect(sessions[0]!.wireProtocolVersion).toBe('1.0');
});
it('treats unknown protocol versions as healthy (wire-reader best-efforts)', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const wirePath = join(sessionDir, 'agents', 'main', 'wire.jsonl');
const lines = (await readFile(wirePath, 'utf8')).split('\n');
lines[0] = JSON.stringify({ type: 'metadata', protocol_version: '2.2', created_at: 1 });
await writeFile(wirePath, lines.join('\n'));
const sessions = await listSessions(home);
expect(sessions[0]!.health).toBe('ok');
expect(sessions[0]!.wireProtocolVersion).toBe('2.2');
});
it('falls back to empty workDir when session is not in the index', async () => {
const { home, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { rm } = await import('node:fs/promises');
const { join } = await import('node:path');
await rm(join(home, 'session_index.jsonl'));
const sessions = await listSessions(home);
expect(sessions).toHaveLength(1);
expect(sessions[0]!.workDir).toBe('');
});
it('skips imported_from_kimi_cli sessions', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
// mark as imported
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const state = JSON.parse(await readFile(join(sessionDir, 'state.json'), 'utf8'));
state.custom = { imported_from_kimi_cli: true };
await writeFile(join(sessionDir, 'state.json'), JSON.stringify(state));
const sessions = await listSessions(home);
expect(sessions).toHaveLength(0);
});
it('marks a session broken_main_wire when its wire file cannot be scanned', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { rm, mkdir } = await import('node:fs/promises');
const { join } = await import('node:path');
// Replace the wire FILE with a directory of the same name, so the
// createReadStream below will reject with EISDIR.
const wirePath = join(sessionDir, 'agents', 'main', 'wire.jsonl');
await rm(wirePath);
await mkdir(wirePath);
const sessions = await listSessions(home);
expect(sessions).toHaveLength(1);
expect(sessions[0]!.health).toBe('broken_main_wire');
expect(sessions[0]!.mainWireRecordCount).toBe(0);
});
it('treats a headerless v1.4 wire as recoverable', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const wirePath = join(sessionDir, 'agents', 'main', 'wire.jsonl');
await writeFile(
wirePath,
'{"type":"config.update","cwd":"/x","time":1}\n',
);
const sessions = await listSessions(home);
expect(sessions).toHaveLength(1);
expect(sessions[0]!.health).toBe('ok');
expect(sessions[0]!.wireProtocolVersion).toBe('1.4');
});
it('skips untyped JSON before valid wire metadata', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
await writeFile(
join(sessionDir, 'agents', 'main', 'wire.jsonl'),
'{}\n{"type":"metadata","protocol_version":"1.5","created_at":1}\n',
);
const sessions = await listSessions(home);
expect(sessions[0]!.health).toBe('ok');
expect(sessions[0]!.wireProtocolVersion).toBe('1.5');
expect(sessions[0]!.mainWireRecordCount).toBe(1);
});
it('marks a session broken_main_wire when its wire has no typed records', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
await writeFile(join(sessionDir, 'agents', 'main', 'wire.jsonl'), '{}\n{}\n');
const sessions = await listSessions(home);
expect(sessions[0]!.health).toBe('broken_main_wire');
expect(sessions[0]!.mainWireRecordCount).toBe(0);
});
it.each([
'{"type":"metadata","created_at":1}\n',
'{"type":"metadata","protocol_version":"1.5","created_at":{}}\n',
])('marks a session broken_main_wire when metadata is malformed', async (wire) => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
await writeFile(join(sessionDir, 'agents', 'main', 'wire.jsonl'), wire);
const sessions = await listSessions(home);
expect(sessions[0]!.health).toBe('broken_main_wire');
});
it('rejects unsafe agent ids', () => {
expect(isSafeAgentId('main')).toBe(true);
expect(isSafeAgentId('agent-0')).toBe(true);
expect(isSafeAgentId('agent_0.v2')).toBe(true);
expect(isSafeAgentId('..')).toBe(false);
expect(isSafeAgentId('.')).toBe(false);
expect(isSafeAgentId('../foo')).toBe(false);
expect(isSafeAgentId('a/b')).toBe(false);
expect(isSafeAgentId('a\\b')).toBe(false);
expect(isSafeAgentId('')).toBe(false);
});
it('skips unsafe agent ids from state.json in the inventory', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile, mkdir } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
state.agents['../escape'] = {
homedir: '/tmp/whatever',
type: 'sub',
parentAgentId: 'main',
};
await writeFile(statePath, JSON.stringify(state));
// Plant a wire file under the "../escape" path that would be
// reachable if isSafeAgentId failed to gate path joins.
await mkdir(join(sessionDir, '..', 'escape'), { recursive: true });
await writeFile(
join(sessionDir, '..', 'escape', 'wire.jsonl'),
'{"type":"metadata","protocol_version":"1.1","created_at":1}\n',
);
const d = await readSessionDetail(home, 'session_fixture');
expect(d!.agents.map((a) => a.agentId).sort()).toEqual(['agent-0', 'main']);
});
it('rejects session_index entries that point outside KIMI_CODE_HOME', async () => {
const { home, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile, mkdir } = await import('node:fs/promises');
const { join } = await import('node:path');
// Poison the index: claim session_fixture lives at /tmp/elsewhere.
const elsewhere = '/tmp/vis-poison-test-' + Date.now();
await mkdir(elsewhere, { recursive: true });
await writeFile(
join(home, 'session_index.jsonl'),
JSON.stringify({
sessionId: 'session_fixture',
sessionDir: elsewhere,
workDir: '/somewhere',
}) + '\n',
);
// Detail must fall back to bucket scanning (legit path under home)
// rather than honour the poisoned index entry.
const d = await readSessionDetail(home, 'session_fixture');
expect(d).not.toBeNull();
expect(d!.sessionDir.startsWith(home)).toBe(true);
const { rm } = await import('node:fs/promises');
await rm(elsewhere, { recursive: true, force: true });
});
it('reports an unreadable subagent wire as wireExists=false in agent inventory', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
// Break the SUBAGENT's wire metadata; main wire stays intact so the
// session itself remains healthy.
await writeFile(
join(sessionDir, 'agents', 'agent-0', 'wire.jsonl'),
'not even json\n',
);
const d = await readSessionDetail(home, 'session_fixture');
expect(d).not.toBeNull();
const sub = d!.agents.find((a) => a.agentId === 'agent-0')!;
expect(sub.wireExists).toBe(false);
expect(sub.wireRecordCount).toBe(0);
});
it('exposes the canonical session directory in detail responses', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const d = await readSessionDetail(home, 'session_fixture');
expect(d!.sessionDir).toBe(sessionDir);
});
it('returns broken-state detail consistent with the listed broken summary', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
await writeFile(join(sessionDir, 'state.json'), '{ this is not json');
const summaries = await listSessions(home);
expect(summaries).toHaveLength(1);
expect(summaries[0]!.health).toBe('broken_state');
const d = await readSessionDetail(home, 'session_fixture');
expect(d).not.toBeNull();
expect(d!.state).toBeNull();
expect(d!.workDir).toBe('/tmp/work');
// Even with state.json broken, the on-disk agent directories should
// still be inventoried so users can open wire/context.
expect(d!.agents.map((a) => a.agentId).sort()).toEqual(['agent-0', 'main']);
const main = d!.agents.find((a) => a.agentId === 'main')!;
expect(main.wireExists).toBe(true);
expect(main.wireRecordCount).toBe(10);
});
it('reads session detail with full agent inventory', async () => {
const { home, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const d = await readSessionDetail(home, 'session_fixture');
expect(d).not.toBeNull();
expect(d!.workDir).toBe('/tmp/work');
expect(d!.agents.map((a) => a.agentId).sort()).toEqual(['agent-0', 'main']);
const main = d!.agents.find((a) => a.agentId === 'main')!;
expect(main.type).toBe('main');
expect(main.parentAgentId).toBeNull();
expect(main.wireExists).toBe(true);
expect(main.wireRecordCount).toBe(10);
const sub = d!.agents.find((a) => a.agentId === 'agent-0')!;
expect(sub.parentAgentId).toBe('main');
});
it('ignores persisted agent homedirs and uses the standard paths', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
delete state.agents.main.parentAgentId;
await writeFile(statePath, JSON.stringify(state));
const detail = await readSessionDetail(home, 'session_fixture');
expect(
detail!.agents
.map(({ agentId, homedir, parentAgentId }) => ({ agentId, homedir, parentAgentId }))
.toSorted((a, b) => a.agentId.localeCompare(b.agentId)),
).toEqual([
{
agentId: 'agent-0',
homedir: join(sessionDir, 'agents', 'agent-0'),
parentAgentId: 'main',
},
{
agentId: 'main',
homedir: join(sessionDir, 'agents', 'main'),
parentAgentId: null,
},
]);
});
it('reads v2 epoch millisecond timestamps', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
state.createdAt = 1_784_012_345_678;
state.updatedAt = 1_784_023_456_789;
await writeFile(statePath, JSON.stringify(state));
const [summary] = await listSessions(home);
expect(summary!.createdAt).toBe(state.createdAt);
expect(summary!.updatedAt).toBe(state.updatedAt);
});
it('recovers the workDir from v2 state when the append index is unavailable', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, rm, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
state.cwd = '/workspace/from-state';
await writeFile(statePath, JSON.stringify(state));
await rm(join(home, 'session_index.jsonl'));
const [summary] = await listSessions(home);
const detail = await readSessionDetail(home, 'session_fixture');
expect(summary!.workDir).toBe('/workspace/from-state');
expect(detail!.workDir).toBe('/workspace/from-state');
});
it('surfaces swarmItem from state.json onto AgentInfo (null when absent)', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
state.agents['agent-0'].swarmItem = 'task A';
await writeFile(statePath, JSON.stringify(state));
const d = await readSessionDetail(home, 'session_fixture');
expect(d).not.toBeNull();
const sub = d!.agents.find((a) => a.agentId === 'agent-0')!;
expect(sub.swarmItem).toBe('task A');
// main has no swarmItem in state.json → null, not undefined.
const main = d!.agents.find((a) => a.agentId === 'main')!;
expect(main.swarmItem).toBeNull();
});
it('prefers v2 labels for parentAgentId / swarmItem, top-level as fallback', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
// v2 writes a fixed top-level `parentAgentId: 'main'` for every sub agent
// and puts the real parent / swarm label under `labels`.
state.agents['agent-1'] = {
type: 'sub',
parentAgentId: 'main',
labels: {
parentAgentId: 'agent-0',
swarmItem: 'batch item',
profileName: 'explore',
},
};
await writeFile(statePath, JSON.stringify(state));
const d = await readSessionDetail(home, 'session_fixture');
const nested = d!.agents.find((a) => a.agentId === 'agent-1')!;
expect(nested.parentAgentId).toBe('agent-0');
expect(nested.swarmItem).toBe('batch item');
expect(nested.profileName).toBe('explore');
// agent-0 has no labels — the top-level v1 fields still apply.
const flat = d!.agents.find((a) => a.agentId === 'agent-0')!;
expect(flat.parentAgentId).toBe('main');
});
it('normalizes untrusted agent metadata before exposing it', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { readFile, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const statePath = join(sessionDir, 'state.json');
const state = JSON.parse(await readFile(statePath, 'utf8'));
state.agents.main.type = {};
state.agents.main.labels = {
parentAgentId: {},
profileName: {},
swarmItem: {},
};
state.agents['agent-0'].type = 'invalid';
state.agents['agent-0'].parentAgentId = [];
state.agents['agent-0'].swarmItem = 42;
state.agents['agent-0'].labels = { profileName: ' ' };
await writeFile(statePath, JSON.stringify(state));
const d = await readSessionDetail(home, 'session_fixture');
const main = d!.agents.find((a) => a.agentId === 'main')!;
expect(main).toMatchObject({
type: 'main',
parentAgentId: null,
profileName: null,
swarmItem: null,
});
const subagent = d!.agents.find((a) => a.agentId === 'agent-0')!;
expect(subagent).toMatchObject({
type: 'sub',
parentAgentId: null,
profileName: null,
swarmItem: null,
});
});
it('reads the legacy session-meta/state.json path when state.json is missing', async () => {
const { home, sessionDir, cleanup: c } = await buildSessionFixture('sample-main');
cleanup = c;
const { mkdir, rename } = await import('node:fs/promises');
const { join } = await import('node:path');
await mkdir(join(sessionDir, 'session-meta'), { recursive: true });
await rename(
join(sessionDir, 'state.json'),
join(sessionDir, 'session-meta', 'state.json'),
);
const sessions = await listSessions(home);
expect(sessions).toHaveLength(1);
expect(sessions[0]!.health).toBe('ok');
expect(sessions[0]!.title).toBe('fixture: hello world');
});
});
|