session-manager.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. import type { PluginInput } from '@opencode-ai/plugin';
  2. import { POLL_INTERVAL_BACKGROUND_MS } from '../config';
  3. import type { MultiplexerConfig } from '../config/schema';
  4. import {
  5. getMultiplexer,
  6. isServerRunning,
  7. type Multiplexer,
  8. } from '../multiplexer';
  9. import type { BackgroundJobState } from '../utils/background-job-board';
  10. import type { BackgroundJobStore } from '../utils/background-job-store';
  11. import { log } from '../utils/logger';
  12. import {
  13. CmuxSessionLifecycle,
  14. type CmuxSessionLifecycleOptions,
  15. } from './cmux/session-lifecycle';
  16. import { CmuxSessionStore } from './cmux/session-state';
  17. type BackgroundJobReader = Pick<
  18. BackgroundJobStore,
  19. 'getState' | 'deferIfRunning' | 'clearDeferredClose'
  20. >;
  21. interface TrackedSession {
  22. sessionId: string;
  23. paneId: string;
  24. parentId: string;
  25. title: string;
  26. directory: string;
  27. ownerInstanceId: string;
  28. }
  29. interface KnownSession {
  30. parentId: string;
  31. title: string;
  32. directory: string;
  33. }
  34. interface SharedSessionState {
  35. sessions: Map<string, TrackedSession>;
  36. knownSessions: Map<string, KnownSession>;
  37. spawningSessions: Set<string>;
  38. closingSessions: Map<string, Promise<void>>;
  39. permanentlyClosedSessions: Set<string>;
  40. }
  41. interface SessionEvent {
  42. type: string;
  43. properties?: {
  44. info?: {
  45. id?: string;
  46. parentID?: string;
  47. title?: string;
  48. directory?: string;
  49. sessionID?: string;
  50. };
  51. part?: { sessionID?: string };
  52. sessionID?: string;
  53. status?: { type: string };
  54. };
  55. }
  56. type CloseReason = 'idle' | 'deleted';
  57. const SHARED_STATE_KEY = Symbol.for(
  58. 'oh-my-opencode-slim.multiplexer-session-manager.state',
  59. );
  60. function getSharedState(): SharedSessionState {
  61. const globalWithState = globalThis as typeof globalThis & {
  62. [SHARED_STATE_KEY]?: SharedSessionState;
  63. };
  64. let state = globalWithState[SHARED_STATE_KEY];
  65. if (!state) {
  66. state = {
  67. sessions: new Map(),
  68. knownSessions: new Map(),
  69. spawningSessions: new Set(),
  70. closingSessions: new Map(),
  71. permanentlyClosedSessions: new Set(),
  72. };
  73. globalWithState[SHARED_STATE_KEY] = state;
  74. }
  75. // Migrate state created by older plugin instances in this process.
  76. state.permanentlyClosedSessions ??= new Set();
  77. return state;
  78. }
  79. export function resetMultiplexerSessionManagerState(): void {
  80. const state = getSharedState();
  81. state.sessions.clear();
  82. state.knownSessions.clear();
  83. state.spawningSessions.clear();
  84. state.closingSessions.clear();
  85. state.permanentlyClosedSessions.clear();
  86. new CmuxSessionStore().resetForTests();
  87. }
  88. export type MultiplexerSessionManagerOptions = CmuxSessionLifecycleOptions;
  89. function validServerUrl(value: unknown): string | null {
  90. if (typeof value !== 'string' && !(value instanceof URL)) return null;
  91. try {
  92. const url = new URL(value.toString());
  93. return url.protocol === 'http:' || url.protocol === 'https:'
  94. ? url.toString()
  95. : null;
  96. } catch {
  97. return null;
  98. }
  99. }
  100. function clientBaseUrl(client: unknown): string | null {
  101. try {
  102. if (!client || typeof client !== 'object' || !('_client' in client))
  103. return null;
  104. const internal = client._client;
  105. if (!internal || typeof internal !== 'object' || !('getConfig' in internal))
  106. return null;
  107. const getConfig = internal.getConfig;
  108. if (typeof getConfig !== 'function') return null;
  109. const config: unknown = getConfig.call(internal);
  110. if (!config || typeof config !== 'object' || !('baseUrl' in config))
  111. return null;
  112. return validServerUrl(config.baseUrl);
  113. } catch {
  114. return null;
  115. }
  116. }
  117. function createServerUrlResolver(ctx: PluginInput): () => string | null {
  118. return () => {
  119. try {
  120. const serverUrl = validServerUrl(ctx.serverUrl);
  121. if (serverUrl) return serverUrl;
  122. } catch {}
  123. try {
  124. return clientBaseUrl(ctx.client);
  125. } catch {
  126. return null;
  127. }
  128. };
  129. }
  130. /**
  131. * Tracks child sessions and spawns/closes multiplexer panes for them.
  132. *
  133. * Uses session.status events for completion detection instead of polling,
  134. * with polling kept as a fallback for reliability.
  135. */
  136. export class MultiplexerSessionManager {
  137. private instanceId = Math.random().toString(36).slice(2, 8);
  138. private readonly resolveServerUrl: () => string | null;
  139. private directory: string;
  140. private multiplexer: Multiplexer | null = null;
  141. private sessions: SharedSessionState['sessions'];
  142. private knownSessions: SharedSessionState['knownSessions'];
  143. private spawningSessions: SharedSessionState['spawningSessions'];
  144. private closingSessions: SharedSessionState['closingSessions'];
  145. private permanentlyClosedSessions: SharedSessionState['permanentlyClosedSessions'];
  146. private pollInterval?: ReturnType<typeof setInterval>;
  147. private enabled = false;
  148. private cmuxLifecycle?: CmuxSessionLifecycle;
  149. constructor(
  150. ctx: PluginInput,
  151. config: MultiplexerConfig,
  152. private readonly backgroundJobBoard?: BackgroundJobReader,
  153. options: MultiplexerSessionManagerOptions = {},
  154. ) {
  155. const sharedState = getSharedState();
  156. this.sessions = sharedState.sessions;
  157. this.knownSessions = sharedState.knownSessions;
  158. this.spawningSessions = sharedState.spawningSessions;
  159. this.closingSessions = sharedState.closingSessions;
  160. this.permanentlyClosedSessions = sharedState.permanentlyClosedSessions;
  161. this.directory = ctx.directory;
  162. this.resolveServerUrl = createServerUrlResolver(ctx);
  163. this.multiplexer = getMultiplexer(config);
  164. this.enabled =
  165. config.type !== 'none' &&
  166. this.multiplexer !== null &&
  167. this.multiplexer.isInsideSession();
  168. if (this.enabled && this.multiplexer?.type === 'cmux') {
  169. this.cmuxLifecycle = new CmuxSessionLifecycle(
  170. this.instanceId,
  171. this.multiplexer,
  172. this.resolveServerUrl,
  173. this.directory,
  174. this.backgroundJobBoard,
  175. {
  176. ...options,
  177. permanentlyClosedSessions: this.permanentlyClosedSessions,
  178. },
  179. );
  180. }
  181. log('[multiplexer-session-manager] initialized', {
  182. instanceId: this.instanceId,
  183. enabled: this.enabled,
  184. type: config.type,
  185. serverUrl: 'dynamic',
  186. trackedSessions: this.sessions.size,
  187. knownSessions: this.knownSessions.size,
  188. });
  189. }
  190. async onSessionCreated(event: SessionEvent): Promise<void> {
  191. if (this.cmuxLifecycle) return this.cmuxLifecycle.onSessionCreated(event);
  192. if (!this.enabled || !this.multiplexer) return;
  193. if (event.type !== 'session.created') return;
  194. const info = event.properties?.info;
  195. if (!info?.id || !info?.parentID) {
  196. return;
  197. }
  198. const sessionId = info.id;
  199. const parentId = info.parentID;
  200. const title = info.title ?? 'Subagent';
  201. const directory = info.directory ?? this.directory;
  202. if (this.permanentlyClosedSessions.has(sessionId)) {
  203. log('[multiplexer-session-manager] ignoring permanently closed session', {
  204. instanceId: this.instanceId,
  205. sessionId,
  206. });
  207. return;
  208. }
  209. if (this.isTrackedOrSpawning(sessionId)) {
  210. log('[multiplexer-session-manager] session already tracked or spawning', {
  211. instanceId: this.instanceId,
  212. sessionId,
  213. });
  214. return;
  215. }
  216. const closing = this.closingSessions.get(sessionId);
  217. if (closing) await closing;
  218. if (this.permanentlyClosedSessions.has(sessionId)) return;
  219. if (this.isTrackedOrSpawning(sessionId)) return;
  220. this.knownSessions.set(sessionId, {
  221. parentId,
  222. title,
  223. directory,
  224. });
  225. this.spawningSessions.add(sessionId);
  226. try {
  227. const serverUrl = this.resolveServerUrl();
  228. if (!serverUrl) {
  229. log(
  230. '[multiplexer-session-manager] no valid server URL, skipping spawn',
  231. {
  232. instanceId: this.instanceId,
  233. sessionId,
  234. },
  235. );
  236. return;
  237. }
  238. const serverRunning = await isServerRunning(serverUrl);
  239. if (!serverRunning) {
  240. log('[multiplexer-session-manager] server not running, skipping', {
  241. instanceId: this.instanceId,
  242. serverUrl,
  243. });
  244. return;
  245. }
  246. if (
  247. this.permanentlyClosedSessions.has(sessionId) ||
  248. this.closingSessions.has(sessionId) ||
  249. this.sessions.has(sessionId)
  250. ) {
  251. return;
  252. }
  253. log(
  254. '[multiplexer-session-manager] child session created, spawning pane',
  255. {
  256. sessionId,
  257. parentId,
  258. title,
  259. instanceId: this.instanceId,
  260. },
  261. );
  262. const paneResult = await this.multiplexer
  263. .spawnPane(sessionId, title, serverUrl, directory)
  264. .catch((err) => {
  265. log('[multiplexer-session-manager] failed to spawn pane', {
  266. instanceId: this.instanceId,
  267. error: String(err),
  268. });
  269. return { success: false, paneId: undefined };
  270. });
  271. if (!paneResult.success || !paneResult.paneId) return;
  272. if (
  273. !this.knownSessions.has(sessionId) ||
  274. this.closingSessions.has(sessionId) ||
  275. this.permanentlyClosedSessions.has(sessionId)
  276. ) {
  277. await this.multiplexer.closePane(paneResult.paneId).catch((err) =>
  278. log(
  279. '[multiplexer-session-manager] closing stale spawned pane failed',
  280. {
  281. sessionId,
  282. paneId: paneResult.paneId,
  283. instanceId: this.instanceId,
  284. error: String(err),
  285. },
  286. ),
  287. );
  288. return;
  289. }
  290. this.sessions.set(sessionId, {
  291. sessionId,
  292. paneId: paneResult.paneId,
  293. parentId,
  294. title,
  295. directory,
  296. ownerInstanceId: this.instanceId,
  297. });
  298. log('[multiplexer-session-manager] pane spawned', {
  299. instanceId: this.instanceId,
  300. sessionId,
  301. paneId: paneResult.paneId,
  302. });
  303. this.startPolling();
  304. } finally {
  305. this.spawningSessions.delete(sessionId);
  306. }
  307. }
  308. async onSessionStatus(event: SessionEvent): Promise<void> {
  309. if (this.cmuxLifecycle) return this.cmuxLifecycle.onSessionStatus(event);
  310. if (!this.enabled) return;
  311. if (event.type === 'session.idle') {
  312. const sessionId = event.properties?.sessionID;
  313. if (!sessionId) return;
  314. log('[multiplexer-session-manager] session idle event received', {
  315. instanceId: this.instanceId,
  316. sessionId,
  317. tracked: this.sessions.has(sessionId),
  318. known: this.knownSessions.has(sessionId),
  319. ownerInstanceId: this.sessions.get(sessionId)?.ownerInstanceId,
  320. backgroundJobState: this.backgroundJobState(sessionId),
  321. });
  322. await this.closeSession(sessionId, 'idle');
  323. return;
  324. }
  325. if (event.type !== 'session.status') return;
  326. const sessionId = event.properties?.sessionID;
  327. if (!sessionId) return;
  328. const statusType = event.properties?.status?.type;
  329. if (statusType === 'idle') {
  330. log('[multiplexer-session-manager] session status idle received', {
  331. instanceId: this.instanceId,
  332. sessionId,
  333. tracked: this.sessions.has(sessionId),
  334. known: this.knownSessions.has(sessionId),
  335. ownerInstanceId: this.sessions.get(sessionId)?.ownerInstanceId,
  336. backgroundJobState: this.backgroundJobState(sessionId),
  337. });
  338. await this.closeSession(sessionId, 'idle');
  339. return;
  340. }
  341. if (statusType) {
  342. if (statusType !== 'busy') {
  343. this.backgroundJobBoard?.clearDeferredClose(sessionId);
  344. return;
  345. }
  346. log('[multiplexer-session-manager] session busy event received', {
  347. instanceId: this.instanceId,
  348. sessionId,
  349. tracked: this.sessions.has(sessionId),
  350. known: this.knownSessions.has(sessionId),
  351. ownerInstanceId: this.sessions.get(sessionId)?.ownerInstanceId,
  352. backgroundJobState: this.backgroundJobState(sessionId),
  353. });
  354. await this.respawnIfKnown(sessionId);
  355. }
  356. }
  357. async onSessionDeleted(event: SessionEvent): Promise<void> {
  358. if (this.cmuxLifecycle) return this.cmuxLifecycle.onSessionDeleted(event);
  359. if (!this.enabled) return;
  360. if (event.type !== 'session.deleted') return;
  361. const sessionId = this.getSessionId(event);
  362. if (!sessionId) return;
  363. log('[multiplexer-session-manager] session deleted, closing pane', {
  364. instanceId: this.instanceId,
  365. sessionId,
  366. tracked: this.sessions.has(sessionId),
  367. known: this.knownSessions.has(sessionId),
  368. ownerInstanceId: this.sessions.get(sessionId)?.ownerInstanceId,
  369. backgroundJobState: this.backgroundJobState(sessionId),
  370. });
  371. await this.closeSession(sessionId, 'deleted');
  372. }
  373. private startPolling(): void {
  374. if (this.pollInterval) return;
  375. this.pollInterval = setInterval(
  376. () => this.pollSessions(),
  377. POLL_INTERVAL_BACKGROUND_MS,
  378. );
  379. log('[multiplexer-session-manager] polling started', {
  380. instanceId: this.instanceId,
  381. });
  382. }
  383. private stopPolling(): void {
  384. if (this.pollInterval) {
  385. clearInterval(this.pollInterval);
  386. this.pollInterval = undefined;
  387. log('[multiplexer-session-manager] polling stopped', {
  388. instanceId: this.instanceId,
  389. });
  390. }
  391. }
  392. private async pollSessions(): Promise<void> {
  393. if (this.cmuxLifecycle) return this.cmuxLifecycle.pollOnce();
  394. if (this.sessions.size === 0) {
  395. this.stopPolling();
  396. return;
  397. }
  398. try {
  399. const allStatuses = await this.fetchSessionStatuses();
  400. const sessionsToClose: string[] = [];
  401. for (const [sessionId, tracked] of this.sessions.entries()) {
  402. if (tracked.ownerInstanceId !== this.instanceId) {
  403. log('[multiplexer-session-manager] skipping non-owner poll close', {
  404. instanceId: this.instanceId,
  405. ownerInstanceId: tracked.ownerInstanceId,
  406. sessionId,
  407. paneId: tracked.paneId,
  408. });
  409. continue;
  410. }
  411. const status = allStatuses[sessionId];
  412. if (!status) continue;
  413. if (status.type !== 'idle') {
  414. this.backgroundJobBoard?.clearDeferredClose(sessionId);
  415. continue;
  416. }
  417. sessionsToClose.push(sessionId);
  418. }
  419. for (const sessionId of sessionsToClose) {
  420. await this.closeSession(sessionId, 'idle');
  421. }
  422. } catch (err) {
  423. log('[multiplexer-session-manager] poll error', { error: String(err) });
  424. }
  425. }
  426. private async fetchSessionStatuses(): Promise<
  427. Record<string, { type: string }>
  428. > {
  429. const serverUrl = this.resolveServerUrl();
  430. if (!serverUrl) {
  431. log('[multiplexer-session-manager] no valid server URL, skipping poll', {
  432. instanceId: this.instanceId,
  433. });
  434. return {};
  435. }
  436. const url = new URL('/session/status', serverUrl);
  437. const response = await fetch(url, { signal: AbortSignal.timeout(2_000) });
  438. if (!response.ok) {
  439. throw new Error(
  440. `session status request failed: ${response.status} ${response.statusText}`,
  441. );
  442. }
  443. const body = await response.text();
  444. if (body.trim() === '') {
  445. throw new Error('session status response was empty');
  446. }
  447. try {
  448. return JSON.parse(body) as Record<string, { type: string }>;
  449. } catch (err) {
  450. throw new Error(`session status response was not valid JSON: ${err}`);
  451. }
  452. }
  453. private async closeSession(
  454. sessionId: string,
  455. reason: CloseReason,
  456. skipPolicyCheck = false,
  457. ): Promise<void> {
  458. if (reason === 'deleted') {
  459. this.knownSessions.delete(sessionId);
  460. this.backgroundJobBoard?.clearDeferredClose(sessionId);
  461. }
  462. const existingClose = this.closingSessions.get(sessionId);
  463. if (existingClose) return existingClose;
  464. const tracked = this.sessions.get(sessionId);
  465. if (!tracked || !this.multiplexer) {
  466. log('[multiplexer-session-manager] close skipped; session not tracked', {
  467. instanceId: this.instanceId,
  468. sessionId,
  469. reason,
  470. tracked: !!tracked,
  471. hasMultiplexer: !!this.multiplexer,
  472. });
  473. return;
  474. }
  475. if (reason !== 'deleted' && tracked.ownerInstanceId !== this.instanceId) {
  476. log('[multiplexer-session-manager] close skipped; non-owner instance', {
  477. instanceId: this.instanceId,
  478. ownerInstanceId: tracked.ownerInstanceId,
  479. sessionId,
  480. paneId: tracked.paneId,
  481. reason,
  482. });
  483. return;
  484. }
  485. if (reason === 'deleted' && tracked.ownerInstanceId !== this.instanceId) {
  486. log('[multiplexer-session-manager] closing deleted pane as non-owner', {
  487. instanceId: this.instanceId,
  488. ownerInstanceId: tracked.ownerInstanceId,
  489. sessionId,
  490. paneId: tracked.paneId,
  491. reason,
  492. });
  493. }
  494. if (
  495. reason === 'idle' &&
  496. !skipPolicyCheck &&
  497. !this.shouldCloseNow(sessionId)
  498. ) {
  499. log(
  500. '[multiplexer-session-manager] close skipped; background job running',
  501. {
  502. instanceId: this.instanceId,
  503. sessionId,
  504. paneId: tracked.paneId,
  505. reason,
  506. backgroundJobState: this.backgroundJobState(sessionId),
  507. },
  508. );
  509. return;
  510. }
  511. this.sessions.delete(sessionId);
  512. log('[multiplexer-session-manager] closing session pane', {
  513. instanceId: this.instanceId,
  514. sessionId,
  515. paneId: tracked.paneId,
  516. reason,
  517. backgroundJobState: this.backgroundJobState(sessionId),
  518. parentId: tracked.parentId,
  519. title: tracked.title,
  520. });
  521. const closePromise: Promise<void> = this.multiplexer
  522. .closePane(tracked.paneId)
  523. .then(() => undefined)
  524. .catch((err) =>
  525. log('[multiplexer-session-manager] failed to close session pane', {
  526. instanceId: this.instanceId,
  527. sessionId,
  528. paneId: tracked.paneId,
  529. reason,
  530. error: String(err),
  531. }),
  532. )
  533. .finally(() => {
  534. this.closingSessions.delete(sessionId);
  535. this.updatePolling();
  536. });
  537. this.closingSessions.set(sessionId, closePromise);
  538. await closePromise;
  539. }
  540. private async respawnIfKnown(sessionId: string): Promise<void> {
  541. if (!this.enabled || !this.multiplexer) return;
  542. if (this.permanentlyClosedSessions.has(sessionId)) return;
  543. const closing = this.closingSessions.get(sessionId);
  544. if (closing) await closing;
  545. if (this.permanentlyClosedSessions.has(sessionId)) return;
  546. if (this.isTrackedOrSpawning(sessionId)) {
  547. return;
  548. }
  549. const known = this.knownSessions.get(sessionId);
  550. if (!known) return;
  551. this.spawningSessions.add(sessionId);
  552. try {
  553. const serverUrl = this.resolveServerUrl();
  554. if (!serverUrl) {
  555. log(
  556. '[multiplexer-session-manager] no valid server URL, skipping respawn',
  557. {
  558. instanceId: this.instanceId,
  559. sessionId,
  560. },
  561. );
  562. return;
  563. }
  564. const serverRunning = await isServerRunning(serverUrl);
  565. if (!serverRunning) {
  566. log(
  567. '[multiplexer-session-manager] server not running, skipping busy respawn',
  568. {
  569. instanceId: this.instanceId,
  570. serverUrl,
  571. sessionId,
  572. },
  573. );
  574. return;
  575. }
  576. if (
  577. this.permanentlyClosedSessions.has(sessionId) ||
  578. this.sessions.has(sessionId) ||
  579. this.closingSessions.has(sessionId)
  580. ) {
  581. return;
  582. }
  583. log(
  584. '[multiplexer-session-manager] child session busy again, respawning pane',
  585. {
  586. instanceId: this.instanceId,
  587. sessionId,
  588. parentId: known.parentId,
  589. title: known.title,
  590. },
  591. );
  592. const paneResult = await this.multiplexer
  593. .spawnPane(sessionId, known.title, serverUrl, known.directory)
  594. .catch((err) => {
  595. log('[multiplexer-session-manager] failed to respawn pane', {
  596. instanceId: this.instanceId,
  597. error: String(err),
  598. });
  599. return { success: false, paneId: undefined };
  600. });
  601. if (!paneResult.success || !paneResult.paneId) return;
  602. if (
  603. !this.knownSessions.has(sessionId) ||
  604. this.closingSessions.has(sessionId) ||
  605. this.permanentlyClosedSessions.has(sessionId)
  606. ) {
  607. await this.multiplexer.closePane(paneResult.paneId).catch((err) =>
  608. log(
  609. '[multiplexer-session-manager] closing stale respawned pane failed',
  610. {
  611. instanceId: this.instanceId,
  612. sessionId,
  613. paneId: paneResult.paneId,
  614. error: String(err),
  615. },
  616. ),
  617. );
  618. return;
  619. }
  620. this.sessions.set(sessionId, {
  621. sessionId,
  622. paneId: paneResult.paneId,
  623. parentId: known.parentId,
  624. title: known.title,
  625. directory: known.directory,
  626. ownerInstanceId: this.instanceId,
  627. });
  628. this.backgroundJobBoard?.clearDeferredClose(sessionId);
  629. log('[multiplexer-session-manager] pane respawned on busy', {
  630. instanceId: this.instanceId,
  631. sessionId,
  632. paneId: paneResult.paneId,
  633. });
  634. this.startPolling();
  635. } finally {
  636. this.spawningSessions.delete(sessionId);
  637. }
  638. }
  639. private isTrackedOrSpawning(sessionId: string): boolean {
  640. return this.sessions.has(sessionId) || this.spawningSessions.has(sessionId);
  641. }
  642. private updatePolling(): void {
  643. if (this.sessions.size > 0 || this.closingSessions.size > 0) {
  644. this.startPolling();
  645. } else {
  646. this.stopPolling();
  647. }
  648. }
  649. private getSessionId(event: SessionEvent): string | undefined {
  650. return event.properties?.info?.id || event.properties?.sessionID;
  651. }
  652. private backgroundJobState(
  653. sessionId: string,
  654. ): BackgroundJobState | undefined {
  655. return this.backgroundJobBoard?.getState(sessionId);
  656. }
  657. private shouldCloseNow(sessionId: string): boolean {
  658. return this.backgroundJobBoard?.deferIfRunning(sessionId) ?? true;
  659. }
  660. async closeSessionFromCoordinator(sessionId: string): Promise<void> {
  661. if (this.cmuxLifecycle)
  662. return this.cmuxLifecycle.closeSessionFromCoordinator(sessionId);
  663. if (!this.enabled) return;
  664. // Coordinator already vetted lifecycle policy; skip re-check
  665. // ponytail: theoretical race if new job starts between coordinator's
  666. // retryDeferredClose() and this call, but session IDs are unique per launch
  667. await this.closeSession(sessionId, 'idle', true);
  668. }
  669. /** Permanently close a wall-clock timed-out pane and block late busy respawn. */
  670. async closeSessionPermanentlyFromCoordinator(
  671. sessionId: string,
  672. ): Promise<void> {
  673. if (this.cmuxLifecycle) {
  674. return this.cmuxLifecycle.closeSessionPermanentlyFromCoordinator(
  675. sessionId,
  676. );
  677. }
  678. if (!this.enabled) return;
  679. this.permanentlyClosedSessions.add(sessionId);
  680. await this.closeSession(sessionId, 'deleted', true);
  681. }
  682. async cleanup(): Promise<void> {
  683. if (this.cmuxLifecycle) {
  684. await this.cmuxLifecycle.cleanup();
  685. this.permanentlyClosedSessions.clear();
  686. return;
  687. }
  688. this.stopPolling();
  689. if (this.closingSessions.size > 0) {
  690. await Promise.all(this.closingSessions.values());
  691. }
  692. if (this.sessions.size > 0 && this.multiplexer) {
  693. log('[multiplexer-session-manager] closing all panes', {
  694. count: this.sessions.size,
  695. });
  696. const multiplexer = this.multiplexer;
  697. const closePromises = Array.from(this.sessions.values()).map((s) =>
  698. multiplexer.closePane(s.paneId).catch((err) =>
  699. log('[multiplexer-session-manager] cleanup error for pane', {
  700. paneId: s.paneId,
  701. error: String(err),
  702. }),
  703. ),
  704. );
  705. await Promise.all(closePromises);
  706. this.sessions.clear();
  707. }
  708. this.knownSessions.clear();
  709. this.spawningSessions.clear();
  710. this.closingSessions.clear();
  711. this.permanentlyClosedSessions.clear();
  712. // ponytail: deferred state lives in coordinator, not here
  713. // Note: coordinator has same lifetime as plugin, so no explicit cleanup needed
  714. log('[multiplexer-session-manager] cleanup complete');
  715. }
  716. async cleanupOnInstanceDisposed(): Promise<void> {
  717. if (this.cmuxLifecycle) await this.cmuxLifecycle.cleanup();
  718. }
  719. }
  720. /**
  721. * @deprecated Use MultiplexerSessionManager instead
  722. */
  723. export const TmuxSessionManager = MultiplexerSessionManager;