manager.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. import { describe, expect, mock, test } from 'bun:test';
  2. import * as fs from 'node:fs/promises';
  3. import { createServer as createHttpServer } from 'node:http';
  4. import { createServer as createNetServer } from 'node:net';
  5. import type { PluginConfig } from '../config';
  6. import { readDashboardAuthFile } from './dashboard';
  7. import { createInterviewManager } from './manager';
  8. // Intercept getClient so the manager's service uses the same session mocks.
  9. mock.module('../utils/opencode-client', () => ({
  10. getClient: (ctx: any) => ({
  11. session: ctx._sessionMock ?? ctx.client.session,
  12. }),
  13. }));
  14. // Helper to find a free port (matches interview.test.ts pattern)
  15. async function findFreePort(): Promise<number> {
  16. return new Promise((resolve, reject) => {
  17. const server = createHttpServer();
  18. server.listen(0, () => {
  19. const address = server.address();
  20. if (address && typeof address !== 'string') {
  21. const port = address.port;
  22. server.close(() => resolve(port));
  23. } else {
  24. server.close(() => reject(new Error('Failed to get port')));
  25. }
  26. });
  27. });
  28. }
  29. // Mock context pattern from interview.test.ts
  30. function createMockContext(overrides?: {
  31. directory?: string;
  32. messagesData?: Array<{
  33. info?: { role: string };
  34. parts?: Array<{ type: string; text?: string }>;
  35. }>;
  36. promptImpl?: (args: any) => Promise<unknown>;
  37. }) {
  38. const messagesData = overrides?.messagesData ?? [];
  39. const sessionMock = {
  40. messages: mock(async () => ({ data: messagesData })),
  41. prompt: mock(async (args: any) => {
  42. if (overrides?.promptImpl) {
  43. return await overrides.promptImpl(args);
  44. }
  45. return {};
  46. }),
  47. promptAsync: mock(async (args: any) => {
  48. if (overrides?.promptImpl) {
  49. return await overrides.promptImpl(args);
  50. }
  51. return {};
  52. }),
  53. update: mock(async () => ({})),
  54. };
  55. return {
  56. client: {
  57. session: sessionMock,
  58. },
  59. directory: overrides?.directory ?? '/test/directory',
  60. _sessionMock: sessionMock,
  61. } as any;
  62. }
  63. function createTestConfig(
  64. overrides: Partial<NonNullable<PluginConfig['interview']>> = {},
  65. ): PluginConfig {
  66. return {
  67. interview: {
  68. autoOpenBrowser: false,
  69. ...overrides,
  70. },
  71. } as PluginConfig;
  72. }
  73. // Helper to extract text from output parts
  74. function _extractOutputText(output: {
  75. parts: Array<{ type: string; text?: string }>;
  76. }): string {
  77. const textPart = output.parts.find((part) => part.type === 'text');
  78. return textPart?.text ?? '';
  79. }
  80. describe('interview manager - per-session mode', () => {
  81. describe('basic functionality', () => {
  82. test('returns correct interface when port is 0 (default)', () => {
  83. const ctx = createMockContext();
  84. const config = createTestConfig({ port: 0 });
  85. const manager = createInterviewManager(ctx, config);
  86. expect(manager).toHaveProperty('registerCommand');
  87. expect(manager).toHaveProperty('handleCommandExecuteBefore');
  88. expect(manager).toHaveProperty('handleEvent');
  89. expect(typeof manager.registerCommand).toBe('function');
  90. expect(typeof manager.handleCommandExecuteBefore).toBe('function');
  91. expect(typeof manager.handleEvent).toBe('function');
  92. });
  93. test('creates interview with /interview command', async () => {
  94. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  95. const ctx = createMockContext({ directory: tempDir });
  96. const config = createTestConfig({ port: 0 });
  97. const manager = createInterviewManager(ctx, config);
  98. const output = { parts: [] as Array<{ type: string; text?: string }> };
  99. await manager.handleCommandExecuteBefore(
  100. {
  101. command: 'interview',
  102. sessionID: 'session-123',
  103. arguments: 'My App Idea',
  104. },
  105. output,
  106. );
  107. // Should inject kickoff prompt into output
  108. expect(output.parts.length).toBe(1);
  109. expect(output.parts[0].type).toBe('text');
  110. expect(output.parts[0].text).toContain('My App Idea');
  111. expect(output.parts[0].text).toContain('<interview_state>');
  112. // Cleanup
  113. await fs.rm(tempDir, { recursive: true, force: true });
  114. });
  115. test('marks interview as abandoned on session.deleted event', async () => {
  116. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  117. const ctx = createMockContext({ directory: tempDir });
  118. const config = createTestConfig({ port: 0 });
  119. const manager = createInterviewManager(ctx, config);
  120. // Create interview
  121. const output = { parts: [] as Array<{ type: string; text?: string }> };
  122. await manager.handleCommandExecuteBefore(
  123. {
  124. command: 'interview',
  125. sessionID: 'session-delete-test',
  126. arguments: 'Delete Test',
  127. },
  128. output,
  129. );
  130. // Simulate session deletion
  131. await manager.handleEvent({
  132. event: {
  133. type: 'session.deleted',
  134. properties: { sessionID: 'session-delete-test' },
  135. },
  136. });
  137. // Interview should still exist (file not deleted)
  138. const interviewDir = `${tempDir}/interview`;
  139. const remainingFiles = await fs.readdir(interviewDir);
  140. expect(remainingFiles.length).toBe(1);
  141. // Status is only tracked in memory, not written to markdown
  142. // We verify the session deletion handler doesn't throw
  143. // Cleanup
  144. await fs.rm(tempDir, { recursive: true, force: true });
  145. });
  146. test('registers session when interview is created', async () => {
  147. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  148. const ctx = createMockContext({ directory: tempDir });
  149. const freePort = await findFreePort();
  150. const config = createTestConfig({
  151. port: freePort,
  152. dashboard: true,
  153. });
  154. const manager = createInterviewManager(ctx, config);
  155. // Wait for dashboard init
  156. await new Promise((r) => setTimeout(r, 100));
  157. try {
  158. // Create interview (should trigger session registration)
  159. const output = { parts: [] as Array<{ type: string; text?: string }> };
  160. await manager.handleCommandExecuteBefore(
  161. {
  162. command: 'interview',
  163. sessionID: 'session-reg-after-cmd',
  164. arguments: 'Register After Cmd',
  165. },
  166. output,
  167. );
  168. // Extract interview ID
  169. const promptCalls = ctx.client.session.prompt.mock.calls;
  170. expect(promptCalls.length).toBeGreaterThan(0);
  171. const text =
  172. promptCalls[promptCalls.length - 1][0].parts?.[0]?.text ?? '';
  173. const match = text.match(/interview\/([^\s]+)/);
  174. expect(match).not.toBeNull();
  175. const interviewId = match?.[1];
  176. // Give registration a moment
  177. await new Promise((r) => setTimeout(r, 100));
  178. // Read auth token
  179. const auth = await readDashboardAuthFile(freePort);
  180. expect(auth).not.toBeNull();
  181. // Verify session is registered (interview exists in cache)
  182. const listResponse = await fetch(
  183. `http://127.0.0.1:${freePort}/api/interviews/${interviewId}/state?token=${auth?.token}`,
  184. );
  185. expect(listResponse.status).toBe(200);
  186. } finally {
  187. await fs.rm(tempDir, { recursive: true, force: true });
  188. }
  189. });
  190. });
  191. describe('dashboard: true with port 0', () => {
  192. test('activates dashboard mode and creates interview', async () => {
  193. const freePort = await findFreePort();
  194. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  195. const ctx = createMockContext({ directory: tempDir });
  196. const config = createTestConfig({
  197. port: freePort,
  198. dashboard: true,
  199. });
  200. const manager = createInterviewManager(ctx, config);
  201. // Wait for async init
  202. await new Promise((r) => setTimeout(r, 100));
  203. try {
  204. const output = { parts: [] as Array<{ type: string; text?: string }> };
  205. await manager.handleCommandExecuteBefore(
  206. {
  207. command: 'interview',
  208. sessionID: 'session-dashboard-bool',
  209. arguments: 'Dashboard Bool Test',
  210. },
  211. output,
  212. );
  213. expect(output.parts.length).toBe(1);
  214. expect(output.parts[0].text).toContain('Dashboard Bool Test');
  215. } finally {
  216. await fs.rm(tempDir, { recursive: true, force: true });
  217. }
  218. });
  219. });
  220. });
  221. describe('interview manager - state push callback wiring', () => {
  222. test('in dashboard mode, state push callback is wired', async () => {
  223. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  224. const ctx = createMockContext({ directory: tempDir });
  225. const freePort = await findFreePort();
  226. const config = createTestConfig({
  227. port: freePort,
  228. dashboard: true,
  229. });
  230. const manager = createInterviewManager(ctx, config);
  231. // Wait for dashboard init
  232. await new Promise((r) => setTimeout(r, 100));
  233. try {
  234. // Create interview
  235. const output = { parts: [] as Array<{ type: string; text?: string }> };
  236. await manager.handleCommandExecuteBefore(
  237. {
  238. command: 'interview',
  239. sessionID: 'session-state-callback',
  240. arguments: 'State Callback Test',
  241. },
  242. output,
  243. );
  244. // Extract interview ID from prompt calls
  245. const promptCalls = ctx.client.session.prompt.mock.calls;
  246. expect(promptCalls.length).toBeGreaterThan(0);
  247. const text =
  248. promptCalls[promptCalls.length - 1][0].parts?.[0]?.text ?? '';
  249. const match = text.match(/interview\/([^\s]+)/);
  250. expect(match).not.toBeNull();
  251. const interviewId = match?.[1];
  252. // Give state push a moment
  253. await new Promise((r) => setTimeout(r, 100));
  254. // Read auth token
  255. const auth = await readDashboardAuthFile(freePort);
  256. expect(auth).not.toBeNull();
  257. // Verify state was pushed to dashboard cache
  258. const stateResponse = await fetch(
  259. `http://127.0.0.1:${freePort}/api/interviews/${interviewId}/state?token=${auth?.token}`,
  260. );
  261. expect(stateResponse.status).toBe(200);
  262. const stateData = (await stateResponse.json()) as {
  263. interview: { idea: string };
  264. mode: string;
  265. };
  266. expect(stateData.interview.idea).toBe('State Callback Test');
  267. } finally {
  268. await fs.rm(tempDir, { recursive: true, force: true });
  269. }
  270. });
  271. test('in per-session mode, setBaseUrlResolver is called', async () => {
  272. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  273. const ctx = createMockContext({ directory: tempDir });
  274. const config = createTestConfig({ port: 0 });
  275. const manager = createInterviewManager(ctx, config);
  276. try {
  277. // Create interview (this triggers server start via setBaseUrlResolver)
  278. const output = { parts: [] as Array<{ type: string; text?: string }> };
  279. await manager.handleCommandExecuteBefore(
  280. {
  281. command: 'interview',
  282. sessionID: 'session-base-url',
  283. arguments: 'Base URL Test',
  284. },
  285. output,
  286. );
  287. // Should create a markdown file (proof that server was initialized)
  288. const interviewDir = `${tempDir}/interview`;
  289. const files = await fs.readdir(interviewDir);
  290. expect(files.length).toBe(1);
  291. } finally {
  292. await fs.rm(tempDir, { recursive: true, force: true });
  293. }
  294. });
  295. });
  296. describe('interview manager - session registration', () => {
  297. test('registers session after handleCommandExecuteBefore in dashboard mode', async () => {
  298. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  299. const ctx = createMockContext({ directory: tempDir });
  300. const freePort = await findFreePort();
  301. const config = createTestConfig({
  302. port: freePort,
  303. dashboard: true,
  304. });
  305. const manager = createInterviewManager(ctx, config);
  306. // Wait for dashboard init
  307. await new Promise((r) => setTimeout(r, 100));
  308. try {
  309. // Create interview (should trigger session registration)
  310. const output = { parts: [] as Array<{ type: string; text?: string }> };
  311. await manager.handleCommandExecuteBefore(
  312. {
  313. command: 'interview',
  314. sessionID: 'session-reg-after-cmd',
  315. arguments: 'Register After Cmd',
  316. },
  317. output,
  318. );
  319. // Extract interview ID
  320. const promptCalls = ctx.client.session.prompt.mock.calls;
  321. expect(promptCalls.length).toBeGreaterThan(0);
  322. const text =
  323. promptCalls[promptCalls.length - 1][0].parts?.[0]?.text ?? '';
  324. const match = text.match(/interview\/([^\s]+)/);
  325. expect(match).not.toBeNull();
  326. const interviewId = match?.[1];
  327. // Give registration a moment
  328. await new Promise((r) => setTimeout(r, 100));
  329. // Read auth token
  330. const auth = await readDashboardAuthFile(freePort);
  331. expect(auth).not.toBeNull();
  332. // Verify session was registered by checking the interview state
  333. const stateResponse = await fetch(
  334. `http://127.0.0.1:${freePort}/api/interviews/${interviewId}/state?token=${auth?.token}`,
  335. );
  336. expect(stateResponse.status).toBe(200);
  337. } finally {
  338. await fs.rm(tempDir, { recursive: true, force: true });
  339. }
  340. });
  341. test('removes session on session.deleted event', async () => {
  342. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  343. const ctx = createMockContext({ directory: tempDir });
  344. const freePort = await findFreePort();
  345. const config = createTestConfig({
  346. port: freePort,
  347. dashboard: true,
  348. });
  349. const manager = createInterviewManager(ctx, config);
  350. // Wait for dashboard init
  351. await new Promise((r) => setTimeout(r, 100));
  352. try {
  353. // Create interview
  354. const output = { parts: [] as Array<{ type: string; text?: string }> };
  355. await manager.handleCommandExecuteBefore(
  356. {
  357. command: 'interview',
  358. sessionID: 'session-delete-reg',
  359. arguments: 'Delete Register Test',
  360. },
  361. output,
  362. );
  363. // Extract interview ID
  364. const promptCalls = ctx.client.session.prompt.mock.calls;
  365. expect(promptCalls.length).toBeGreaterThan(0);
  366. const text =
  367. promptCalls[promptCalls.length - 1][0].parts?.[0]?.text ?? '';
  368. const match = text.match(/interview\/([^\s]+)/);
  369. expect(match).not.toBeNull();
  370. const _interviewId = match?.[1];
  371. // Give registration a moment
  372. await new Promise((r) => setTimeout(r, 100));
  373. // Delete session
  374. await manager.handleEvent({
  375. event: {
  376. type: 'session.deleted',
  377. properties: { sessionID: 'session-delete-reg' },
  378. },
  379. });
  380. // Give cleanup a moment
  381. await new Promise((r) => setTimeout(r, 50));
  382. // Interview file should still exist
  383. const interviewDir = `${tempDir}/interview`;
  384. const files = await fs.readdir(interviewDir);
  385. expect(files.length).toBe(1);
  386. // Status is only tracked in memory, not written to markdown
  387. } finally {
  388. await fs.rm(tempDir, { recursive: true, force: true });
  389. }
  390. });
  391. test('clears fallback timer when last registered session is deleted', async () => {
  392. const dashboardDir = await fs.mkdtemp('/tmp/manager-test-');
  393. const clientDir = await fs.mkdtemp('/tmp/manager-test-');
  394. const dashboardCtx = createMockContext({ directory: dashboardDir });
  395. const clientCtx = createMockContext({ directory: clientDir });
  396. const freePort = await findFreePort();
  397. const config = createTestConfig({
  398. port: freePort,
  399. dashboard: true,
  400. });
  401. const originalSetInterval = globalThis.setInterval;
  402. const originalClearInterval = globalThis.clearInterval;
  403. const intervalHandles: Array<{ unref: ReturnType<typeof mock> }> = [];
  404. const setIntervalSpy = mock(() => {
  405. const handle = { unref: mock(() => {}) };
  406. intervalHandles.push(handle);
  407. return handle;
  408. });
  409. const clearIntervalSpy = mock(() => {});
  410. try {
  411. (globalThis as any).setInterval = setIntervalSpy;
  412. (globalThis as any).clearInterval = clearIntervalSpy;
  413. createInterviewManager(dashboardCtx, config);
  414. // Wait for dashboard init
  415. await new Promise((r) => setTimeout(r, 100));
  416. const clientManager = createInterviewManager(clientCtx, config);
  417. // Wait for client init to connect to the dashboard
  418. await new Promise((r) => setTimeout(r, 100));
  419. const output = { parts: [] as Array<{ type: string; text?: string }> };
  420. await clientManager.handleCommandExecuteBefore(
  421. {
  422. command: 'interview',
  423. sessionID: 'session-fallback-cleanup',
  424. arguments: 'Fallback Cleanup Test',
  425. },
  426. output,
  427. );
  428. expect(intervalHandles.length).toBeGreaterThan(0);
  429. const fallbackTimerHandle = intervalHandles.at(-1);
  430. expect(fallbackTimerHandle).toBeDefined();
  431. await clientManager.handleEvent({
  432. event: {
  433. type: 'session.deleted',
  434. properties: { sessionID: 'session-fallback-cleanup' },
  435. },
  436. });
  437. expect(clearIntervalSpy).toHaveBeenCalledTimes(1);
  438. expect(clearIntervalSpy).toHaveBeenCalledWith(fallbackTimerHandle);
  439. expect(fallbackTimerHandle?.unref).toHaveBeenCalledTimes(1);
  440. } finally {
  441. (globalThis as any).setInterval = originalSetInterval;
  442. (globalThis as any).clearInterval = originalClearInterval;
  443. await fs.rm(dashboardDir, { recursive: true, force: true });
  444. await fs.rm(clientDir, { recursive: true, force: true });
  445. }
  446. });
  447. });
  448. describe('interview manager - edge cases', () => {
  449. test('handles session.status event with idle status', async () => {
  450. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  451. const ctx = createMockContext({ directory: tempDir });
  452. const config = createTestConfig({ port: 0 });
  453. const manager = createInterviewManager(ctx, config);
  454. try {
  455. // Create interview
  456. const output = { parts: [] as Array<{ type: string; text?: string }> };
  457. await manager.handleCommandExecuteBefore(
  458. {
  459. command: 'interview',
  460. sessionID: 'session-idle',
  461. arguments: 'Idle Event Test',
  462. },
  463. output,
  464. );
  465. // Send idle status event
  466. await manager.handleEvent({
  467. event: {
  468. type: 'session.status',
  469. properties: {
  470. sessionID: 'session-idle',
  471. status: { type: 'idle' },
  472. },
  473. },
  474. });
  475. // Should not throw
  476. expect(true).toBe(true);
  477. } finally {
  478. await fs.rm(tempDir, { recursive: true, force: true });
  479. }
  480. });
  481. test('handles session.status event without sessionID in properties', async () => {
  482. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  483. const ctx = createMockContext({ directory: tempDir });
  484. const config = createTestConfig({ port: 0 });
  485. const manager = createInterviewManager(ctx, config);
  486. try {
  487. // Send idle status event without sessionID
  488. await manager.handleEvent({
  489. event: {
  490. type: 'session.status',
  491. properties: {
  492. status: { type: 'idle' },
  493. },
  494. },
  495. });
  496. // Should not throw
  497. expect(true).toBe(true);
  498. } finally {
  499. await fs.rm(tempDir, { recursive: true, force: true });
  500. }
  501. });
  502. test('handles unknown event types', async () => {
  503. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  504. const ctx = createMockContext({ directory: tempDir });
  505. const config = createTestConfig({ port: 0 });
  506. const manager = createInterviewManager(ctx, config);
  507. try {
  508. // Send unknown event type
  509. await manager.handleEvent({
  510. event: {
  511. type: 'unknown.event',
  512. properties: { sessionID: 'session-unknown' },
  513. },
  514. });
  515. // Should not throw
  516. expect(true).toBe(true);
  517. } finally {
  518. await fs.rm(tempDir, { recursive: true, force: true });
  519. }
  520. });
  521. test('handles handleCommandExecuteBefore without sessionID', async () => {
  522. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  523. const ctx = createMockContext({ directory: tempDir });
  524. const config = createTestConfig({ port: 0 });
  525. const manager = createInterviewManager(ctx, config);
  526. try {
  527. const output = { parts: [] as Array<{ type: string; text?: string }> };
  528. await manager.handleCommandExecuteBefore(
  529. {
  530. command: 'interview',
  531. sessionID: '',
  532. arguments: 'No Session Test',
  533. },
  534. output,
  535. );
  536. // Should create interview (sessionID is optional in per-session mode)
  537. expect(output.parts.length).toBe(1);
  538. } finally {
  539. await fs.rm(tempDir, { recursive: true, force: true });
  540. }
  541. });
  542. });
  543. describe('interview manager - integration with real dashboard', () => {
  544. test('two managers on same port: first becomes dashboard, second becomes session', async () => {
  545. const tempDir1 = await fs.mkdtemp('/tmp/manager-test-');
  546. const tempDir2 = await fs.mkdtemp('/tmp/manager-test-');
  547. const ctx1 = createMockContext({ directory: tempDir1 });
  548. const ctx2 = createMockContext({ directory: tempDir2 });
  549. const freePort = await findFreePort();
  550. const config = createTestConfig({
  551. port: freePort,
  552. dashboard: true,
  553. });
  554. const manager1 = createInterviewManager(ctx1, config);
  555. // Wait for manager1 to become dashboard
  556. await new Promise((r) => setTimeout(r, 100));
  557. try {
  558. // Manager1 should be the dashboard
  559. const healthResponse = await fetch(
  560. `http://127.0.0.1:${freePort}/api/health`,
  561. );
  562. expect(healthResponse.status).toBe(200);
  563. // Manager2 should become a session (not throw when dashboard is found)
  564. const manager2 = createInterviewManager(ctx2, config);
  565. // Wait for manager2 init (probes dashboard)
  566. await new Promise((r) => setTimeout(r, 100));
  567. // Both managers should work
  568. const output1 = { parts: [] as Array<{ type: string; text?: string }> };
  569. await manager1.handleCommandExecuteBefore(
  570. {
  571. command: 'interview',
  572. sessionID: 'session-1',
  573. arguments: 'Manager 1 Test',
  574. },
  575. output1,
  576. );
  577. const output2 = { parts: [] as Array<{ type: string; text?: string }> };
  578. await manager2.handleCommandExecuteBefore(
  579. {
  580. command: 'interview',
  581. sessionID: 'session-2',
  582. arguments: 'Manager 2 Test',
  583. },
  584. output2,
  585. );
  586. // Give state pushes a moment
  587. await new Promise((r) => setTimeout(r, 100));
  588. // Extract interview IDs
  589. const promptCalls1 = ctx1.client.session.prompt.mock.calls;
  590. const text1 =
  591. promptCalls1[promptCalls1.length - 1][0].parts?.[0]?.text ?? '';
  592. const match1 = text1.match(/interview\/([^\s]+)/);
  593. expect(match1).not.toBeNull();
  594. const interviewId1 = match1?.[1];
  595. const promptCalls2 = ctx2.client.session.prompt.mock.calls;
  596. const text2 =
  597. promptCalls2[promptCalls2.length - 1][0].parts?.[0]?.text ?? '';
  598. const match2 = text2.match(/interview\/([^\s]+)/);
  599. expect(match2).not.toBeNull();
  600. const interviewId2 = match2?.[1];
  601. // Read auth token
  602. const auth = await readDashboardAuthFile(freePort);
  603. expect(auth).not.toBeNull();
  604. // Both interviews should be in dashboard cache
  605. const state1Response = await fetch(
  606. `http://127.0.0.1:${freePort}/api/interviews/${interviewId1}/state?token=${auth?.token}`,
  607. );
  608. expect(state1Response.status).toBe(200);
  609. // Trigger active event poll to register session2/interviewId2 explicitly in dashboard
  610. await manager2.handleEvent({
  611. event: {
  612. type: 'session.status',
  613. properties: {
  614. sessionID: 'session-2',
  615. status: { type: 'idle' },
  616. },
  617. },
  618. });
  619. const state2Response = await fetch(
  620. `http://127.0.0.1:${freePort}/api/interviews/${interviewId2}/state?token=${auth?.token}`,
  621. );
  622. expect(state2Response.status).toBe(200);
  623. } finally {
  624. await fs.rm(tempDir1, { recursive: true, force: true });
  625. await fs.rm(tempDir2, { recursive: true, force: true });
  626. }
  627. });
  628. });
  629. describe('interview manager - dashboard election failure fallback', () => {
  630. test('falls back to per-session mode when tryBecomeDashboard fails and dashboard is unreachable', async () => {
  631. // Create a TCP server that blocks a port but immediately destroys
  632. // connections. This simulates a port in use by a non-dashboard
  633. // process, causing:
  634. // 1. tryBecomeDashboard → probes fail, bind fails (EADDRINUSE),
  635. // returns null after retries
  636. // 2. probeDashboard × 2 → fails (no valid HTTP response)
  637. // 3. Throws → caught → falls back via createPerSessionInterviewServer
  638. const tcpServer = createNetServer((socket) => {
  639. socket.destroy();
  640. });
  641. const port = await new Promise<number>((resolve) => {
  642. tcpServer.listen(0, () => {
  643. const address = tcpServer.address();
  644. if (address && typeof address !== 'string') {
  645. resolve(address.port);
  646. } else {
  647. resolve(0);
  648. }
  649. });
  650. });
  651. const tempDir = await fs.mkdtemp('/tmp/manager-test-');
  652. const ctx = createMockContext({ directory: tempDir });
  653. const config = createTestConfig({
  654. port,
  655. dashboard: true,
  656. });
  657. try {
  658. const manager = createInterviewManager(ctx, config);
  659. // handleCommandExecuteBefore calls ensureInitialized internally,
  660. // which awaits initPromise. This naturally waits for all retries,
  661. // probes, and fallback logic to complete before proceeding.
  662. const output = {
  663. parts: [] as Array<{ type: string; text?: string }>,
  664. };
  665. await manager.handleCommandExecuteBefore(
  666. {
  667. command: 'interview',
  668. sessionID: 'session-fallback',
  669. arguments: 'Fallback Test Idea',
  670. },
  671. output,
  672. );
  673. // Verify interview was created in per-session fallback mode
  674. expect(output.parts.length).toBe(1);
  675. expect(output.parts[0].type).toBe('text');
  676. expect(output.parts[0].text).toContain('Fallback Test Idea');
  677. expect(output.parts[0].text).toContain('<interview_state>');
  678. // Verify interview file was created (per-session mode writes markdown)
  679. const interviewDir = `${tempDir}/interview`;
  680. const files = await fs.readdir(interviewDir);
  681. expect(files.length).toBe(1);
  682. } finally {
  683. await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {});
  684. tcpServer.close();
  685. }
  686. });
  687. });