@in-the-loop-labs/pair-review 5.3.5 → 5.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -866,6 +866,12 @@ Two `chat_providers.<id>` keys control this: `model` sets the default model for
866
866
 
867
867
  Available chat provider IDs: `pi`, `omp`, `claude`, `codex`, `copilot-acp`, `opencode-acp`, `cursor-acp`. Each supports `command`, `args` (replaces defaults; for `pi`, `omp` and `claude` there are no default args — supplied args are appended after the generated flags, so use a multi-word `command` like `"devx omp"` for wrappers rather than `args`), `extra_args` (appends), and `env` overrides, plus `model` and `models_from` (see **Choosing a model** above). Codex chat also supports `sandbox`: use `workspace-write` by default, or `read-only` for discussion-only sessions. (Antigravity and Muse are analysis-only providers — neither CLI has an ACP mode, so there are no Antigravity or Muse chat providers.)
868
868
 
869
+ **Idle chat agents:** A chat's agent process is shut down after `chat.idle_timeout_minutes` minutes without activity (default `10`; `0` disables), so closing the browser doesn't leave agents running. The conversation is kept and transparently resumed, with its history, on your next message. An agent is never shut down while it is starting or still working on a reply, and a conversation whose agent can't be resumed with its history (for example, an ACP agent without session-loading support) is kept running instead. A chat with no messages yet may be shut down either way — your first message then starts a fresh agent with the same context. Set it in the **Chat** section of the [global settings page](#global-settings-page) (applies on next start) or in config:
870
+
871
+ ```json
872
+ { "chat": { "idle_timeout_minutes": 30 } }
873
+ ```
874
+
869
875
  **Keyboard shortcut:** Press `p` then `c` to toggle the chat panel.
870
876
 
871
877
  ### Customization
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@in-the-loop-labs/pair-review",
3
- "version": "5.3.5",
3
+ "version": "5.3.6",
4
4
  "description": "Your AI-powered code review partner - Close the feedback loop with AI coding agents",
5
5
  "main": "src/server.js",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pair-review",
3
- "version": "5.3.5",
3
+ "version": "5.3.6",
4
4
  "description": "pair-review app integration — Open PRs and local changes in the pair-review web UI, run server-side AI analysis, and address review feedback. Requires the pair-review MCP server.",
5
5
  "author": {
6
6
  "name": "in-the-loop-labs",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code-critic",
3
- "version": "5.3.5",
3
+ "version": "5.3.6",
4
4
  "description": "AI-powered code review analysis — Run three-level AI analysis directly in your coding agent. Works standalone, no server required.",
5
5
  "author": {
6
6
  "name": "in-the-loop-labs",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pair-loop",
3
- "version": "5.3.5",
3
+ "version": "5.3.6",
4
4
  "description": "Agent-orchestrated review loop — implement, review with pair-review multi-model councils via the headless CLI, triage, fix, and repeat until a final review returns no blockers. MCP-independent.",
5
5
  "author": {
6
6
  "name": "in-the-loop-labs",
@@ -5032,6 +5032,12 @@ class ChatPanel {
5032
5032
  console.debug('[ChatPanel] WS event:', data.type, 'tab:', tab.sessionId);
5033
5033
  }
5034
5034
 
5035
+ // Same handling whether or not the tab is in the foreground.
5036
+ if (data.type === 'session_closed') {
5037
+ this._handleSessionClosed(tab);
5038
+ return;
5039
+ }
5040
+
5035
5041
  const isActive = this.isOpen && this._getActiveTab() === tab;
5036
5042
 
5037
5043
  // Background tab (or panel closed): drive the per-tab DOM via tab-aware
@@ -5119,6 +5125,24 @@ class ChatPanel {
5119
5125
  }
5120
5126
  }
5121
5127
 
5128
+ /**
5129
+ * The server shut down this tab's agent process (idle timeout). The session
5130
+ * resumes transparently on the next send, so nothing is shown; clearing
5131
+ * `sessionWarm` makes that send show the ACP "Resuming" indicator.
5132
+ * The server does not reap a session mid-turn, but if this tab still thinks
5133
+ * it is streaming, no 'complete' will ever arrive for it: end the stream the
5134
+ * way 'complete' does (tab-aware, so it is correct for a background tab
5135
+ * too — UI controls are only touched when the tab is active).
5136
+ * @param {ChatTab} tab
5137
+ */
5138
+ _handleSessionClosed(tab) {
5139
+ if (tab.isStreaming) {
5140
+ tab.abortPending = false;
5141
+ this.finalizeStreamingMessage(null, tab);
5142
+ }
5143
+ tab.sessionWarm = false;
5144
+ }
5145
+
5122
5146
  /**
5123
5147
  * Close the review-scope subscription and every tab's chat subscription.
5124
5148
  */
@@ -76,6 +76,9 @@ class AcpBridge extends EventEmitter {
76
76
  this._accumulatedText = '';
77
77
  this._inMessage = false;
78
78
  this._firstMessage = !options.resumeSessionId;
79
+ // agentCapabilities.loadSession from the initialize response. ACP agents
80
+ // that omit it do not support loading (resuming) a session.
81
+ this._canLoadSession = false;
79
82
  }
80
83
 
81
84
  /**
@@ -164,6 +167,10 @@ class AcpBridge extends EventEmitter {
164
167
  .catch((err) => {
165
168
  if (!this._closing) {
166
169
  reject(new Error(`ACP initialization failed: ${err.message}`));
170
+ // start() has failed, so no one will close() this bridge: stop the
171
+ // spawned agent instead of leaving it running unowned.
172
+ this._closing = true;
173
+ try { proc.kill('SIGTERM'); } catch { /* already gone */ }
167
174
  }
168
175
  });
169
176
  });
@@ -201,13 +208,20 @@ class AcpBridge extends EventEmitter {
201
208
  stream
202
209
  );
203
210
 
204
- await this._connection.initialize({
211
+ const initResult = await this._connection.initialize({
205
212
  protocolVersion: deps.acp.PROTOCOL_VERSION,
206
213
  clientCapabilities: {},
207
214
  clientInfo: { name: 'pair-review', version: pkgVersion },
208
215
  });
216
+ this._canLoadSession = initResult?.agentCapabilities?.loadSession === true;
209
217
 
210
218
  if (this.resumeSessionId) {
219
+ if (!this._canLoadSession) {
220
+ // Fails start(): the session manager marks the row 'error' and the
221
+ // message route answers 410 with this text, so the client starts a
222
+ // replacement session instead of resuming into a blank one.
223
+ throw new Error(`${this.acpCommand} does not support resuming ACP sessions (no loadSession capability)`);
224
+ }
211
225
  // Resume a previous session — agent restores conversation history
212
226
  await this._connection.loadSession({
213
227
  sessionId: this.resumeSessionId,
@@ -353,6 +367,17 @@ class AcpBridge extends EventEmitter {
353
367
  return this._inMessage;
354
368
  }
355
369
 
370
+ /**
371
+ * Whether a closed session can be resumed with its history: the agent
372
+ * advertised `agentCapabilities.loadSession` at initialize. False before
373
+ * start(). The session manager keeps an unresumable session with history
374
+ * alive rather than shut it down when idle.
375
+ * @returns {boolean}
376
+ */
377
+ isResumable() {
378
+ return this._canLoadSession;
379
+ }
380
+
356
381
  // ---------------------------------------------------------------------------
357
382
  // Private methods
358
383
  // ---------------------------------------------------------------------------
@@ -314,6 +314,16 @@ class ClaudeCodeBridge extends EventEmitter {
314
314
  return this._inMessage;
315
315
  }
316
316
 
317
+ /**
318
+ * Whether a closed session can be resumed with its history (via the stored
319
+ * agent session ref). Always true for this bridge; the session manager uses
320
+ * it to decide whether an idle session may be shut down.
321
+ * @returns {boolean}
322
+ */
323
+ isResumable() {
324
+ return true;
325
+ }
326
+
317
327
  // ---------------------------------------------------------------------------
318
328
  // Private methods
319
329
  // ---------------------------------------------------------------------------
@@ -405,6 +405,16 @@ class CodexBridge extends EventEmitter {
405
405
  return this._inMessage;
406
406
  }
407
407
 
408
+ /**
409
+ * Whether a closed session can be resumed with its history (via the stored
410
+ * agent session ref). Always true for this bridge; the session manager uses
411
+ * it to decide whether an idle session may be shut down.
412
+ * @returns {boolean}
413
+ */
414
+ isResumable() {
415
+ return true;
416
+ }
417
+
408
418
  // ---------------------------------------------------------------------------
409
419
  // JSON-RPC 2.0 transport
410
420
  // ---------------------------------------------------------------------------
@@ -297,6 +297,16 @@ class PiBridge extends EventEmitter {
297
297
  return this._inMessage || this._continuing;
298
298
  }
299
299
 
300
+ /**
301
+ * Whether a closed session can be resumed with its history (via the stored
302
+ * agent session ref). Always true for this bridge; the session manager uses
303
+ * it to decide whether an idle session may be shut down.
304
+ * @returns {boolean}
305
+ */
306
+ isResumable() {
307
+ return true;
308
+ }
309
+
300
310
  // ---------------------------------------------------------------------------
301
311
  // Private methods
302
312
  // ---------------------------------------------------------------------------
@@ -5,10 +5,13 @@
5
5
  * Manages active chat sessions, each backed by a provider-specific bridge process.
6
6
  * Handles session lifecycle (create, message, close), persistence to SQLite,
7
7
  * and event dispatch (delta, complete, tool_use) to registered listeners.
8
+ * Sessions idle longer than `idleTimeoutMs` have their agent process closed by
9
+ * the idle reaper; they resume transparently on the next message.
8
10
  */
9
11
 
10
12
  const fs = require('fs');
11
13
  const path = require('path');
14
+ const { EventEmitter } = require('events');
12
15
  const PiBridge = require('./pi-bridge');
13
16
  const OmpBridge = require('./omp-bridge');
14
17
  const AcpBridge = require('./acp-bridge');
@@ -36,14 +39,52 @@ const OMP_CHAT_TOOLS = 'read,bash,grep,glob,task';
36
39
  /** Error code sendMessage() sets when the agent still owns the previous turn. */
37
40
  const SESSION_BUSY = 'SESSION_BUSY';
38
41
 
39
- class ChatSessionManager {
42
+ /** Upper bound on how often the idle reaper sweeps. */
43
+ const MAX_REAP_INTERVAL_MS = 60 * 1000;
44
+ /** Lower bound on how often the idle reaper sweeps (guards tiny timeouts). */
45
+ const MIN_REAP_INTERVAL_MS = 1000;
46
+
47
+ /** Real clock and timer functions; tests override them via `options._deps`. */
48
+ const defaults = {
49
+ now: () => Date.now(),
50
+ setInterval: (fn, ms) => setInterval(fn, ms),
51
+ clearInterval: (handle) => clearInterval(handle),
52
+ };
53
+
54
+ /**
55
+ * Normalise an idle timeout into milliseconds. Zero, negative, or non-finite
56
+ * values disable idle reaping (returns 0).
57
+ * @param {*} ms
58
+ * @returns {number}
59
+ */
60
+ function normalizeIdleTimeoutMs(ms) {
61
+ const n = Number(ms);
62
+ return Number.isFinite(n) && n > 0 ? n : 0;
63
+ }
64
+
65
+ class ChatSessionManager extends EventEmitter {
40
66
  /**
41
67
  * @param {Database} db - better-sqlite3 database instance
42
68
  * @param {Object} [configOverrides] - Provider config overrides from config.chat_providers
69
+ * @param {Object} [options]
70
+ * @param {number} [options.idleTimeoutMs=0] - Close a session's agent process after this
71
+ * long without activity (it is resumed transparently on the next message). 0 disables.
72
+ * @param {Object} [options._deps] - Dependency overrides (now, setInterval, clearInterval)
43
73
  */
44
- constructor(db, configOverrides = {}) {
74
+ constructor(db, configOverrides = {}, { idleTimeoutMs = 0, _deps } = {}) {
75
+ super();
45
76
  this._db = db;
46
- this._sessions = new Map(); // sessionId -> { bridge, listeners }
77
+ // sessionId -> { bridge, listeners, lastActivityAt, starting, turnInFlight, ... }
78
+ this._sessions = new Map();
79
+ // sessionId -> Promise for closes still waiting on bridge.close(). A resume
80
+ // for the same id must wait for the old process to exit before spawning.
81
+ this._closing = new Map();
82
+ // sessionId -> initialContext an idle close removed before the first message
83
+ // consumed it; resumeSession puts it back so that message still gets it.
84
+ this._carriedInitialContext = new Map();
85
+ this._deps = { ...defaults, ..._deps };
86
+ this._idleTimeoutMs = normalizeIdleTimeoutMs(idleTimeoutMs);
87
+ this._reaperHandle = null;
47
88
  applyChatConfigOverrides(configOverrides);
48
89
  }
49
90
 
@@ -121,6 +162,9 @@ class ChatSessionManager {
121
162
  initialContext: initialContext || null,
122
163
  model: resolvedModel,
123
164
  cliModel: resolved.cliModel,
165
+ lastActivityAt: this._deps.now(),
166
+ starting: true,
167
+ turnInFlight: false,
124
168
  });
125
169
 
126
170
  // Wire up bridge events
@@ -140,6 +184,9 @@ class ChatSessionManager {
140
184
  throw err;
141
185
  }
142
186
 
187
+ // Starting can take a while; the idle clock starts once the agent is up.
188
+ this._markStarted(sessionId, bridge);
189
+
143
190
  logger.info(`[ChatSession] Session ${sessionId} active`);
144
191
  return { id: sessionId, status: 'active', model: resolvedModel, cliModel: resolved.cliModel };
145
192
  }
@@ -174,6 +221,8 @@ class ChatSessionManager {
174
221
  throw busy;
175
222
  }
176
223
 
224
+ session.lastActivityAt = this._deps.now();
225
+
177
226
  // Build the message for the agent: initialContext > context > userMessage
178
227
  // (broad session context first, then narrow per-message context, then user text)
179
228
  let messageForAgent = content;
@@ -238,7 +287,17 @@ class ChatSessionManager {
238
287
 
239
288
  // Forward to bridge
240
289
  logger.debug(`[ChatSession] Session ${sessionId}: forwarding message to bridge (${messageForAgent.length} chars, delta listeners: ${session.listeners.delta.size})`);
241
- await session.bridge.sendMessage(messageForAgent);
290
+ // Tracked here rather than read from bridge.isBusy(): Pi only reports busy
291
+ // between message_start and message_end, so a turn running tools between
292
+ // messages would otherwise look idle to the reaper. Cleared on the turn's
293
+ // 'complete' or 'error' (every bridge's abort path ends in one of them).
294
+ session.turnInFlight = true;
295
+ try {
296
+ await session.bridge.sendMessage(messageForAgent);
297
+ } catch (err) {
298
+ if (this._sessions.get(sessionId) === session) session.turnInFlight = false;
299
+ throw err;
300
+ }
242
301
 
243
302
  return { id: messageId };
244
303
  }
@@ -335,9 +394,23 @@ class ChatSessionManager {
335
394
  /**
336
395
  * Close a session and kill the agent process.
337
396
  * @param {number} sessionId
397
+ * @param {Object} [options]
398
+ * @param {string} [options.reason] - 'idle' when the idle reaper closes the session:
399
+ * leaves `updated_at` alone, carries a pending initialContext over to the next
400
+ * resume, and emits 'session-idle-closed' once the close completes.
338
401
  * @returns {Promise<void>}
339
402
  */
340
- async closeSession(sessionId) {
403
+ async closeSession(sessionId, { reason } = {}) {
404
+ // A close for this id is already waiting on its bridge — share it rather
405
+ // than racing a second DB write against it.
406
+ const pending = this._closing.get(sessionId);
407
+ if (pending) return pending;
408
+
409
+ if (reason !== 'idle') {
410
+ // An explicit close ends the conversation; nothing will resume to claim it.
411
+ this._carriedInitialContext.delete(sessionId);
412
+ }
413
+
341
414
  const session = this._sessions.get(sessionId);
342
415
  if (!session) {
343
416
  // Session may already be closed — just update DB to be safe
@@ -351,16 +424,166 @@ class ChatSessionManager {
351
424
  // Remove from map first so the 'close' event handler doesn't double-update
352
425
  this._sessions.delete(sessionId);
353
426
 
354
- // Close the bridge process (PiBridge.close() handles listener cleanup internally)
355
- await session.bridge.close();
427
+ // Only a session with a stored agent ref can be resumed to claim it; one
428
+ // without gets a fresh replacement session (410 path) with its own context.
429
+ if (reason === 'idle' && session.initialContext && this._hasAgentSessionRef(sessionId)) {
430
+ this._carriedInitialContext.set(sessionId, session.initialContext);
431
+ }
356
432
 
357
- // Update DB status
358
- this._db.prepare(`
359
- UPDATE chat_sessions SET status = 'closed', updated_at = CURRENT_TIMESTAMP
360
- WHERE id = ?
361
- `).run(sessionId);
433
+ // The entry is removed inside the promise chain, so anyone awaiting this
434
+ // close (a resume, closeAll) sees `_closing` already cleared when it wakes.
435
+ // Only one close per id is ever in flight (see the short-circuit above).
436
+ const closing = this._finishClose(sessionId, session, reason)
437
+ .finally(() => { this._closing.delete(sessionId); });
438
+ this._closing.set(sessionId, closing);
439
+ await closing;
440
+ }
362
441
 
363
- logger.info(`[ChatSession] Session ${sessionId} closed`);
442
+ /**
443
+ * Second half of closeSession: wait for the bridge to exit, then persist the
444
+ * closed status. The status is written even when bridge.close() rejects (the
445
+ * session is out of the map either way); the close error still propagates.
446
+ * No resume can re-add the session meanwhile: resumeSession waits on `_closing`.
447
+ * @param {number} sessionId
448
+ * @param {Object} session - The removed _sessions entry
449
+ * @param {string} [reason]
450
+ * @returns {Promise<void>}
451
+ * @private
452
+ */
453
+ async _finishClose(sessionId, session, reason) {
454
+ try {
455
+ // Close the bridge process (PiBridge.close() handles listener cleanup internally)
456
+ await session.bridge.close();
457
+ } finally {
458
+ // An idle close is not user activity: leave updated_at (which orders the
459
+ // MRU session and the history list) untouched.
460
+ this._db.prepare(reason === 'idle'
461
+ ? `UPDATE chat_sessions SET status = 'closed' WHERE id = ?`
462
+ : `UPDATE chat_sessions SET status = 'closed', updated_at = CURRENT_TIMESTAMP WHERE id = ?`
463
+ ).run(sessionId);
464
+
465
+ logger.info(`[ChatSession] Session ${sessionId} closed`);
466
+
467
+ // Emitted before closeSession resolves, so a resume waiting on this close
468
+ // cannot re-register route listeners that the idle-close handler would then
469
+ // tear down.
470
+ if (reason === 'idle') {
471
+ try {
472
+ this.emit('session-idle-closed', { sessionId });
473
+ } catch (err) {
474
+ logger.warn(`[ChatSession] session-idle-closed listener error for session ${sessionId}: ${err.message}`);
475
+ }
476
+ }
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Whether idle reaping is enabled for this manager.
482
+ * @returns {boolean}
483
+ */
484
+ get idleTimeoutMs() {
485
+ return this._idleTimeoutMs;
486
+ }
487
+
488
+ /**
489
+ * Start the periodic idle-session sweep. No-op when idle reaping is disabled
490
+ * or the reaper is already running. The timer is unref'd so it never keeps
491
+ * the process alive.
492
+ */
493
+ startIdleReaper() {
494
+ if (!this._idleTimeoutMs || this._reaperHandle) return;
495
+ const period = Math.max(
496
+ MIN_REAP_INTERVAL_MS,
497
+ Math.min(MAX_REAP_INTERVAL_MS, Math.floor(this._idleTimeoutMs / 2))
498
+ );
499
+ this._reaperHandle = this._deps.setInterval(() => {
500
+ this.reapIdleSessions().catch((err) => {
501
+ logger.warn(`[ChatSession] Idle reaper sweep failed: ${err.message}`);
502
+ });
503
+ }, period);
504
+ if (this._reaperHandle && typeof this._reaperHandle.unref === 'function') {
505
+ this._reaperHandle.unref();
506
+ }
507
+ logger.debug(`[ChatSession] Idle reaper started (timeout ${this._idleTimeoutMs}ms, sweep every ${period}ms)`);
508
+ }
509
+
510
+ /**
511
+ * Stop the periodic idle-session sweep (idempotent).
512
+ */
513
+ stopIdleReaper() {
514
+ if (!this._reaperHandle) return;
515
+ this._deps.clearInterval(this._reaperHandle);
516
+ this._reaperHandle = null;
517
+ }
518
+
519
+ /**
520
+ * Close every session idle for at least the idle timeout. Never reaped:
521
+ * a session still starting, a session mid-turn (manager-tracked turn or
522
+ * bridge.isBusy()), and a session that has message history but could not be
523
+ * resumed with it (no stored agent session ref, or a bridge that reports
524
+ * itself unresumable). A session with no history is reaped either way — the
525
+ * next message's 410 path creates a fresh session that loses nothing.
526
+ * @returns {Promise<number[]>} IDs of the sessions whose close completed without error
527
+ */
528
+ async reapIdleSessions() {
529
+ if (!this._idleTimeoutMs) return [];
530
+ const now = this._deps.now();
531
+ const idle = [];
532
+ for (const [sessionId, session] of this._sessions) {
533
+ const idleFor = now - (session.lastActivityAt ?? now);
534
+ if (idleFor < this._idleTimeoutMs) continue;
535
+ if (session.starting || session.turnInFlight) continue;
536
+ let reapable;
537
+ try {
538
+ reapable = !session.bridge.isBusy() && this._canReapWithoutLoss(sessionId, session.bridge);
539
+ } catch (err) {
540
+ logger.warn(`[ChatSession] Could not check idle state for session ${sessionId}: ${err.message}`);
541
+ continue;
542
+ }
543
+ if (!reapable) continue;
544
+ idle.push({ sessionId, idleFor });
545
+ }
546
+
547
+ const closed = [];
548
+ await Promise.all(idle.map(async ({ sessionId, idleFor }) => {
549
+ const minutes = Math.round(idleFor / 60000);
550
+ logger.info(`[ChatSession] Session ${sessionId} idle for ${minutes}m — closing (resumable on next message)`);
551
+ try {
552
+ await this.closeSession(sessionId, { reason: 'idle' });
553
+ closed.push(sessionId);
554
+ } catch (err) {
555
+ logger.warn(`[ChatSession] Failed to close idle session ${sessionId}: ${err.message}`);
556
+ }
557
+ }));
558
+ return closed;
559
+ }
560
+
561
+ /**
562
+ * Whether the session row stores an agent session ref (file path, session id
563
+ * or thread id) — the prerequisite for resumeSession.
564
+ * @param {number} sessionId
565
+ * @returns {boolean}
566
+ * @private
567
+ */
568
+ _hasAgentSessionRef(sessionId) {
569
+ const row = this._db.prepare('SELECT agent_session_id FROM chat_sessions WHERE id = ?').get(sessionId);
570
+ return !!row?.agent_session_id;
571
+ }
572
+
573
+ /**
574
+ * Whether closing this session's process loses nothing: it can be resumed
575
+ * with its history, or it has no history to lose.
576
+ * @param {number} sessionId
577
+ * @param {Object} bridge
578
+ * @returns {boolean}
579
+ * @private
580
+ */
581
+ _canReapWithoutLoss(sessionId, bridge) {
582
+ if (this._hasAgentSessionRef(sessionId) && bridge.isResumable()) return true;
583
+ const history = this._db.prepare(
584
+ "SELECT 1 FROM chat_messages WHERE session_id = ? AND type = 'message' LIMIT 1"
585
+ ).get(sessionId);
586
+ return !history;
364
587
  }
365
588
 
366
589
  /**
@@ -458,6 +681,20 @@ class ChatSessionManager {
458
681
  * @returns {Promise<{id: number, status: string, model: string|null, cliModel: string|null}>}
459
682
  */
460
683
  async resumeSession(sessionId, { systemPrompt, cwd, loadSkills } = {}) {
684
+ // A close for this session is still waiting on its agent process. Let it
685
+ // finish first: spawning now would resume the same agent session while the
686
+ // old process is still exiting, and the close's final status write would
687
+ // land after ours. Errors belong to the closer, not to this resume.
688
+ const pendingClose = this._closing.get(sessionId);
689
+ if (pendingClose) {
690
+ logger.debug(`[ChatSession] Session ${sessionId}: waiting for in-flight close before resuming`);
691
+ try {
692
+ await pendingClose;
693
+ } catch {
694
+ // closeSession's caller reports its own failure
695
+ }
696
+ }
697
+
461
698
  // Already active — return immediately
462
699
  if (this._sessions.has(sessionId)) {
463
700
  const active = this._sessions.get(sessionId);
@@ -525,12 +762,17 @@ class ChatSessionManager {
525
762
  this._sessions.set(sessionId, {
526
763
  bridge,
527
764
  listeners,
528
- initialContext: null,
765
+ // An idle close may have removed this session before its first message
766
+ // consumed the initial context; that message still gets it.
767
+ initialContext: this._carriedInitialContext.get(sessionId) || null,
529
768
  // Canonical, not the raw stored value: a row written before an alias was
530
769
  // canonicalised (or one whose model now comes from `chat_providers.<id>.model`)
531
770
  // must report the same id the picker shows. See `resolveChatModel`'s `id` contract.
532
771
  model: resolved.id ?? null,
533
772
  cliModel: resolved.cliModel,
773
+ lastActivityAt: this._deps.now(),
774
+ starting: true,
775
+ turnInFlight: false,
534
776
  });
535
777
  this._wireBridgeEvents(sessionId, bridge, listeners);
536
778
 
@@ -547,6 +789,9 @@ class ChatSessionManager {
547
789
  throw err;
548
790
  }
549
791
 
792
+ this._carriedInitialContext.delete(sessionId);
793
+ this._markStarted(sessionId, bridge);
794
+
550
795
  // Update DB status back to active
551
796
  this._db.prepare(`
552
797
  UPDATE chat_sessions SET status = 'active', updated_at = CURRENT_TIMESTAMP
@@ -723,6 +968,59 @@ class ChatSessionManager {
723
968
  };
724
969
  }
725
970
 
971
+ /**
972
+ * Record activity on a session, resetting its idle clock. Ignored when the
973
+ * session map entry belongs to a different bridge (an old process still
974
+ * emitting after the session was closed and resumed).
975
+ * @param {number} sessionId
976
+ * @param {Object} bridge
977
+ * @private
978
+ */
979
+ _touch(sessionId, bridge) {
980
+ const session = this._ownEntry(sessionId, bridge);
981
+ if (session) session.lastActivityAt = this._deps.now();
982
+ }
983
+
984
+ /**
985
+ * The session map entry for this id, but only while it still belongs to
986
+ * `bridge` (not to a newer bridge after a close and resume).
987
+ * @param {number} sessionId
988
+ * @param {Object} bridge
989
+ * @returns {Object|null}
990
+ * @private
991
+ */
992
+ _ownEntry(sessionId, bridge) {
993
+ const session = this._sessions.get(sessionId);
994
+ return session && session.bridge === bridge ? session : null;
995
+ }
996
+
997
+ /**
998
+ * The bridge finished starting: the entry becomes reapable and its idle clock starts.
999
+ * @param {number} sessionId
1000
+ * @param {Object} bridge
1001
+ * @private
1002
+ */
1003
+ _markStarted(sessionId, bridge) {
1004
+ const session = this._ownEntry(sessionId, bridge);
1005
+ if (!session) return;
1006
+ session.starting = false;
1007
+ session.lastActivityAt = this._deps.now();
1008
+ }
1009
+
1010
+ /**
1011
+ * The current turn ended ('complete' or 'error'): touch the clock and clear
1012
+ * the manager-tracked turn flag.
1013
+ * @param {number} sessionId
1014
+ * @param {Object} bridge
1015
+ * @private
1016
+ */
1017
+ _endTurn(sessionId, bridge) {
1018
+ const session = this._ownEntry(sessionId, bridge);
1019
+ if (!session) return;
1020
+ session.turnInFlight = false;
1021
+ session.lastActivityAt = this._deps.now();
1022
+ }
1023
+
726
1024
  /**
727
1025
  * Wire up bridge event handlers that dispatch to the session's listener sets
728
1026
  * and handle DB persistence (e.g., storing assistant messages on completion).
@@ -732,6 +1030,7 @@ class ChatSessionManager {
732
1030
  */
733
1031
  _wireBridgeEvents(sessionId, bridge, listeners) {
734
1032
  bridge.on('delta', (data) => {
1033
+ this._touch(sessionId, bridge);
735
1034
  for (const cb of listeners.delta) {
736
1035
  try {
737
1036
  cb(data);
@@ -742,6 +1041,7 @@ class ChatSessionManager {
742
1041
  });
743
1042
 
744
1043
  bridge.on('complete', (data) => {
1044
+ this._endTurn(sessionId, bridge);
745
1045
  logger.debug(`[ChatSession] Session ${sessionId} complete: ${(data.fullText || '').length} chars, ${listeners.complete.size} listener(s)`);
746
1046
  // Store assistant message in DB
747
1047
  const fullText = data.fullText || '';
@@ -769,6 +1069,7 @@ class ChatSessionManager {
769
1069
  });
770
1070
 
771
1071
  bridge.on('tool_use', (data) => {
1072
+ this._touch(sessionId, bridge);
772
1073
  for (const cb of listeners.toolUse) {
773
1074
  try {
774
1075
  cb(data);
@@ -779,6 +1080,7 @@ class ChatSessionManager {
779
1080
  });
780
1081
 
781
1082
  bridge.on('status', (data) => {
1083
+ this._touch(sessionId, bridge);
782
1084
  for (const cb of listeners.status) {
783
1085
  try {
784
1086
  cb(data);
@@ -789,6 +1091,7 @@ class ChatSessionManager {
789
1091
  });
790
1092
 
791
1093
  bridge.on('error', (data) => {
1094
+ this._endTurn(sessionId, bridge);
792
1095
  logger.error(`[ChatSession] Bridge error for session ${sessionId}: ${data.error?.message || 'unknown'}`);
793
1096
  for (const cb of listeners.error) {
794
1097
  try {
@@ -800,8 +1103,10 @@ class ChatSessionManager {
800
1103
  });
801
1104
 
802
1105
  bridge.on('close', () => {
803
- // If the bridge closes unexpectedly (not via closeSession), update DB
804
- if (this._sessions.has(sessionId)) {
1106
+ // If the bridge closes unexpectedly (not via closeSession), update DB.
1107
+ // The identity check keeps a late 'close' from an old process (closed,
1108
+ // then the session resumed on a new bridge) from tearing down the new one.
1109
+ if (this._ownEntry(sessionId, bridge)) {
805
1110
  for (const cb of listeners.error) {
806
1111
  try {
807
1112
  cb({ message: 'Agent process ended unexpectedly' });
@@ -823,6 +1128,7 @@ class ChatSessionManager {
823
1128
  });
824
1129
 
825
1130
  bridge.on('session', (event) => {
1131
+ this._touch(sessionId, bridge);
826
1132
  const sessionRef = event.sessionFile || event.sessionId || event.threadId;
827
1133
  if (sessionRef) {
828
1134
  try {
@@ -842,10 +1148,18 @@ class ChatSessionManager {
842
1148
  */
843
1149
  async closeAll() {
844
1150
  const sessionIds = [...this._sessions.keys()];
845
- if (sessionIds.length === 0) return;
1151
+ const pendingCloses = [...this._closing.values()];
1152
+ if (sessionIds.length === 0 && pendingCloses.length === 0) return;
846
1153
 
847
- logger.info(`[ChatSession] Closing ${sessionIds.length} active session(s)`);
848
- await Promise.all(sessionIds.map((id) => this.closeSession(id)));
1154
+ if (sessionIds.length > 0) {
1155
+ logger.info(`[ChatSession] Closing ${sessionIds.length} active session(s)`);
1156
+ }
1157
+ await Promise.all([
1158
+ ...sessionIds.map((id) => this.closeSession(id)),
1159
+ // Closes already in flight (e.g. an idle reap) must finish before shutdown
1160
+ // proceeds; their failures are reported by their own callers.
1161
+ ...pendingCloses.map((p) => p.catch(() => {})),
1162
+ ]);
849
1163
  }
850
1164
  }
851
1165
 
package/src/config.js CHANGED
@@ -19,13 +19,12 @@ const IMPLEMENTATION_MATRIX = {
19
19
  pending_review_comments: _pendingReviewCommentsOps.IMPLEMENTED_MODES
20
20
  };
21
21
 
22
- // Recognised `_endpoint` sub-keys. These ride alongside the area key in
23
- // `features` (e.g. `pending_review_comments_endpoint`) and are validated
24
- // separately from area modes. Listed explicitly so a typo like
25
- // `pending_review_commentes_endpoint` is rejected at startup rather than
26
- // silently ignored.
27
- const KNOWN_ENDPOINT_SUBKEYS = new Set([
28
- 'pending_review_comments_endpoint'
22
+ // Recognised sub-keys that configure an implementation without selecting a
23
+ // feature area. They are validated separately from area modes. Listing them
24
+ // explicitly keeps typos from being silently ignored.
25
+ const KNOWN_FEATURE_SUBKEYS = new Set([
26
+ 'pending_review_comments_endpoint',
27
+ 'pending_review_comments_batch'
29
28
  ]);
30
29
 
31
30
  let _cachedCommandToken = null;
@@ -92,7 +91,7 @@ const DEFAULT_CONFIG = {
92
91
  enable_chat: true, // When true, enables the chat panel feature (uses chat_provider)
93
92
  chat_provider: "pi", // Chat provider: 'pi', 'copilot-acp', 'opencode-acp', 'cursor-acp', 'codex'
94
93
  comment_format: "legacy", // Comment format preset or custom template for adopted suggestions
95
- chat: { enable_shortcuts: true, enter_to_send: true }, // Chat panel settings (enable_shortcuts: show action shortcut buttons, enter_to_send: Enter sends message instead of newline)
94
+ chat: { enable_shortcuts: true, enter_to_send: true, idle_timeout_minutes: 10 }, // Chat panel settings (enable_shortcuts: show action shortcut buttons, enter_to_send: Enter sends message instead of newline, idle_timeout_minutes: shut down a chat agent process after this many idle minutes — resumed transparently on the next message; 0 disables)
96
95
  providers: {}, // Custom AI analysis provider configurations (overrides built-in defaults)
97
96
  chat_providers: {}, // Custom chat provider configurations (overrides built-in defaults)
98
97
  repos: {}, // Repository configurations: { "owner/repo": { path: "~/path/to/clone" } }
@@ -582,11 +581,10 @@ function _resolveFeatures(apiHost, explicit) {
582
581
  out[area] = 'rest';
583
582
  }
584
583
  }
585
- // Preserve endpoint-override sub-keys (e.g. `pending_review_comments_endpoint`)
586
- // so the operations layer can read them at dispatch time. Validation of
587
- // these keys happens in `validateRepoConfig()` at startup.
584
+ // Preserve implementation sub-keys so the operations layer can read them
585
+ // at dispatch time. Validation happens in `validateRepoConfig()` at startup.
588
586
  for (const [key, value] of Object.entries(overrides)) {
589
- if (key.endsWith('_endpoint') && typeof value === 'string') {
587
+ if (KNOWN_FEATURE_SUBKEYS.has(key)) {
590
588
  out[key] = value;
591
589
  }
592
590
  }
@@ -965,17 +963,15 @@ function validateRepoConfig(config) {
965
963
  }
966
964
 
967
965
  for (const [area, value] of Object.entries(features)) {
968
- // Endpoint-override sub-keys (e.g. `pending_review_comments_endpoint`)
969
- // are validated separately below. Reject anything that ends in
970
- // `_endpoint` but isn't a recognised override so typos surface here.
966
+ // Implementation sub-keys are validated separately below.
967
+ if (KNOWN_FEATURE_SUBKEYS.has(area)) continue;
968
+ // Reject unknown endpoint overrides with a specific error before the
969
+ // general unknown-feature check.
971
970
  if (area.endsWith('_endpoint')) {
972
- if (!KNOWN_ENDPOINT_SUBKEYS.has(area)) {
973
- throw new Error(
974
- `Invalid pair-review config: repos["${repoKey}"].features.${area} is not a recognised endpoint override. ` +
975
- `Valid endpoint overrides: ${Array.from(KNOWN_ENDPOINT_SUBKEYS).join(', ')}.`
976
- );
977
- }
978
- continue;
971
+ throw new Error(
972
+ `Invalid pair-review config: repos["${repoKey}"].features.${area} is not a recognised endpoint override. ` +
973
+ `Valid endpoint overrides: ${Array.from(KNOWN_FEATURE_SUBKEYS).filter((key) => key.endsWith('_endpoint')).join(', ')}.`
974
+ );
979
975
  }
980
976
  // Reject unknown feature keys (e.g. `pendin_review_check` typo).
981
977
  // Without this, the key is silently ignored by _resolveFeatures.
@@ -1020,7 +1016,7 @@ function validateRepoConfig(config) {
1020
1016
  // would resolve to a mode lacking a runtime implementation).
1021
1017
  const resolvedFeatures = _resolveFeatures(apiHost, features);
1022
1018
  for (const [area, value] of Object.entries(resolvedFeatures)) {
1023
- if (area.endsWith('_endpoint')) continue;
1019
+ if (KNOWN_FEATURE_SUBKEYS.has(area)) continue;
1024
1020
  if (Object.prototype.hasOwnProperty.call(features, area)) continue; // already checked above
1025
1021
  const implemented = IMPLEMENTATION_MATRIX[area];
1026
1022
  if (implemented && !implemented.has(value)) {
@@ -1033,8 +1029,9 @@ function validateRepoConfig(config) {
1033
1029
  }
1034
1030
 
1035
1031
  // Validate the optional endpoint override for the host-extension
1036
- // `pending_review_comments` area. Only meaningful when that area is
1037
- // set to "host" — applying it otherwise is a config error.
1032
+ // `pending_review_comments` area. Only meaningful when that area
1033
+ // resolves to "host" (explicitly, or by default on an alt-host) —
1034
+ // applying it otherwise is a config error.
1038
1035
  const endpointOverride = features.pending_review_comments_endpoint;
1039
1036
  if (endpointOverride !== undefined && endpointOverride !== null) {
1040
1037
  if (typeof endpointOverride !== 'string' || !endpointOverride) {
@@ -1042,7 +1039,7 @@ function validateRepoConfig(config) {
1042
1039
  `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_endpoint must be a non-empty string.`
1043
1040
  );
1044
1041
  }
1045
- if (features.pending_review_comments !== 'host') {
1042
+ if (resolvedFeatures.pending_review_comments !== 'host') {
1046
1043
  throw new Error(
1047
1044
  `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_endpoint is only valid when pending_review_comments = "host".`
1048
1045
  );
@@ -1065,6 +1062,23 @@ function validateRepoConfig(config) {
1065
1062
  }
1066
1063
  }
1067
1064
 
1065
+ // Some hosts expose the pending-review endpoint but accept one comment
1066
+ // per POST instead of the generic batch envelope. Batch mode remains the
1067
+ // default to preserve the documented host-extension contract.
1068
+ const batchComments = features.pending_review_comments_batch;
1069
+ if (batchComments !== undefined && batchComments !== null) {
1070
+ if (typeof batchComments !== 'boolean') {
1071
+ throw new Error(
1072
+ `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_batch must be a boolean.`
1073
+ );
1074
+ }
1075
+ if (resolvedFeatures.pending_review_comments !== 'host') {
1076
+ throw new Error(
1077
+ `Invalid pair-review config: repos["${repoKey}"].features.pending_review_comments_batch is only valid when pending_review_comments = "host".`
1078
+ );
1079
+ }
1080
+ }
1081
+
1068
1082
  if (repoEntry.url_pattern !== undefined && repoEntry.url_pattern !== null) {
1069
1083
  if (typeof repoEntry.url_pattern !== 'string') {
1070
1084
  throw new Error(
@@ -7,7 +7,9 @@ const logger = require('../../../utils/logger');
7
7
  * GitHub's REST API does not support adding inline comments to a *pending*
8
8
  * draft review (the `addPullRequestReviewThread` GraphQL mutation has no
9
9
  * REST equivalent). Alt-hosts that advertise a compatible extension expose
10
- * this via a single HTTP POST that accepts a batch of comments.
10
+ * this through a review-comments endpoint. The generic contract accepts a
11
+ * batch of comments in one POST. Hosts that accept one comment per POST can
12
+ * set `features.pending_review_comments_batch` to `false`.
11
13
  *
12
14
  * Documented generic contract:
13
15
  *
@@ -49,16 +51,23 @@ const logger = require('../../../utils/logger');
49
51
  * placeholders. The template must be a relative path (starting with
50
52
  * `/repos/` or similar) — absolute URLs are rejected at config validation.
51
53
  *
54
+ * Request shape: `features.pending_review_comments_batch` defaults to `true`.
55
+ * When set to `false`, each wire comment is sent as the complete request body
56
+ * in its own POST. This supports hosts whose review-comments extension is
57
+ * singular while preserving the generic batch contract by default. Any 2xx
58
+ * counts as success and the response body is ignored. A 400/422 fails only
59
+ * that comment; any other failure stops the loop and reports the remaining
60
+ * comments as skipped.
61
+ *
52
62
  * Note on `reviewId`: this argument is the *host's* review identifier
53
63
  * (e.g. a numeric REST id), not a GraphQL node id. The REST/host
54
64
  * `review_lifecycle` impl (Phase 4) returns this id when it creates the
55
65
  * pending review; the caller passes it through unchanged.
56
66
  *
57
67
  * Note on `batchSize`: the original parameter is kept in the signature
58
- * for API compatibility with the GraphQL impl, but the host endpoint
59
- * accepts arbitrary batch sizes in a single call. We send all comments
60
- * in one POST and let the server enforce its own limits. The argument
61
- * is otherwise ignored.
68
+ * for API compatibility with the GraphQL impl. It is ignored. Batch hosts
69
+ * receive all comments in one request. Singular hosts receive one request
70
+ * per comment.
62
71
  */
63
72
 
64
73
  const DEFAULT_ENDPOINT_TEMPLATE =
@@ -161,7 +170,8 @@ function toWireComment(comment, commitId) {
161
170
  * the binding token automatically.
162
171
  * @param {Object} features - Feature-flag object from the host binding.
163
172
  * May include `pending_review_comments_endpoint` to override the
164
- * default endpoint path.
173
+ * default endpoint path and `pending_review_comments_batch: false` for
174
+ * hosts that accept one comment per request.
165
175
  * @param {Object} prContext - `{ owner, repo, prNumber, headSha? }`.
166
176
  * Required — the host endpoint is path-shaped, so the GraphQL node IDs
167
177
  * are not sufficient on their own. `headSha` (the PR head SHA) is
@@ -237,17 +247,71 @@ async function addCommentsInBatches(octokit, features, prContext, reviewId, comm
237
247
  // field and let the host surface its own validation error.
238
248
  const commitId = prContext.headSha;
239
249
  const wireComments = comments.map((c) => toWireComment(c, commitId));
250
+ const useBatchRequest = !features || features.pending_review_comments_batch !== false;
240
251
  logger.info(
241
- `Posting ${wireComments.length} comment(s) to host endpoint ${endpoint}`
252
+ `Posting ${wireComments.length} comment(s) to host endpoint ${endpoint} ` +
253
+ `using ${useBatchRequest ? 'one batch request' : 'individual requests'}`
242
254
  );
243
255
 
256
+ const headers = {
257
+ 'content-type': 'application/json',
258
+ accept: 'application/json'
259
+ };
260
+
261
+ if (!useBatchRequest) {
262
+ let successCount = 0;
263
+ const failedDetails = [];
264
+ const locationOf = (c) => (c.line ? `${c.path}:${c.line}` : `${c.path}:file-level`);
265
+
266
+ for (let index = 0; index < wireComments.length; index++) {
267
+ try {
268
+ await octokit.request(`POST ${endpoint}`, {
269
+ headers,
270
+ data: wireComments[index]
271
+ });
272
+ successCount++;
273
+ } catch (error) {
274
+ const status = error && (error.status || error.statusCode);
275
+ const message = (error && error.message) || 'Unknown error';
276
+ const detail = `${locationOf(comments[index])} - ${status || 'network error'}: ${message}`;
277
+ failedDetails.push(detail);
278
+ logger.warn(`Host comment failed: ${detail}`);
279
+ // 400/422 reject this comment alone (e.g. a line outside the diff),
280
+ // so keep going and report every bad comment at once. Anything else
281
+ // (auth, a bad endpoint, rate limiting, server or network errors)
282
+ // shares the endpoint, review and credentials with the remaining
283
+ // comments and would fail them all, so stop here.
284
+ if (status !== 400 && status !== 422) {
285
+ for (const skipped of comments.slice(index + 1)) {
286
+ failedDetails.push(
287
+ `${locationOf(skipped)} - skipped after ${status || 'network error'}`
288
+ );
289
+ }
290
+ break;
291
+ }
292
+ }
293
+ }
294
+
295
+ if (failedDetails.length > 0) {
296
+ logger.error(
297
+ `Host pending_review_comments partial failure: ${successCount} added, ` +
298
+ `${failedDetails.length} failed`
299
+ );
300
+ } else {
301
+ logger.info(`Host pending_review_comments complete: ${successCount} comment(s) added`);
302
+ }
303
+
304
+ return {
305
+ successCount,
306
+ failed: failedDetails.length > 0,
307
+ failedDetails
308
+ };
309
+ }
310
+
244
311
  let response;
245
312
  try {
246
313
  response = await octokit.request(`POST ${endpoint}`, {
247
- headers: {
248
- 'content-type': 'application/json',
249
- accept: 'application/json'
250
- },
314
+ headers,
251
315
  data: { comments: wireComments }
252
316
  });
253
317
  } catch (error) {
@@ -23,7 +23,8 @@ const { buildChatStartedPayload, buildChatResumedPayload, buildChatHookContext,
23
23
  const { resolveFormat } = require('../utils/comment-formatter');
24
24
  const { getAllChatProviders, getAllCachedChatAvailability } = require('../chat/chat-providers');
25
25
  const { getChatModelCatalog, canonicalChatModel } = require('../chat/chat-models');
26
- const { SESSION_BUSY } = require('../chat/session-manager');
26
+ const ChatSessionManager = require('../chat/session-manager');
27
+ const { SESSION_BUSY } = ChatSessionManager;
27
28
  const { resolveLoadSkills } = require('../config');
28
29
 
29
30
  /**
@@ -218,6 +219,46 @@ function unregisterChatBroadcast(sessionId) {
218
219
  }
219
220
  }
220
221
 
222
+ /**
223
+ * React to the session manager closing an idle session: drop the session's
224
+ * broadcast listeners (they belong to the closed bridge) and tell connected
225
+ * clients, so the next send shows the resume indicator. The session resumes
226
+ * transparently on its next message.
227
+ * The listener for ChatSessionManager's 'session-idle-closed' event (see
228
+ * createChatSessionManager).
229
+ * @param {{sessionId: number}} event
230
+ */
231
+ function handleSessionIdleClosed({ sessionId }) {
232
+ unregisterChatBroadcast(sessionId);
233
+ broadcastChat(sessionId, { type: 'session_closed', reason: 'idle' });
234
+ }
235
+
236
+ /**
237
+ * Build the server's ChatSessionManager: provider overrides from
238
+ * `config.chat_providers`, the idle timeout from `config.chat.idle_timeout_minutes`
239
+ * (the manager decides what counts as disabled), the idle-close listener that
240
+ * keeps this module's broadcast registry and clients in sync, and a running
241
+ * idle reaper. Lives here because it needs both the manager class and this
242
+ * module's broadcast state; session-manager.js must not require a route module.
243
+ * @param {Database} db
244
+ * @param {Object} config - Effective config (post global-settings overlay)
245
+ * @param {Object} [options]
246
+ * @param {Object} [options._deps] - Clock/timer overrides passed to the manager
247
+ * @returns {ChatSessionManager}
248
+ */
249
+ function createChatSessionManager(db, config = {}, { _deps } = {}) {
250
+ const idleTimeoutMs = Number(config.chat?.idle_timeout_minutes) * 60 * 1000;
251
+ const manager = new ChatSessionManager(db, config.chat_providers || {}, { idleTimeoutMs, _deps });
252
+ manager.on('session-idle-closed', handleSessionIdleClosed);
253
+ manager.startIdleReaper();
254
+ if (manager.idleTimeoutMs) {
255
+ logger.info(`Chat sessions idle for ${manager.idleTimeoutMs / 60000} minute(s) will be closed (resumable on next message)`);
256
+ } else {
257
+ logger.info('Idle chat session shutdown is disabled (chat.idle_timeout_minutes is not a positive number)');
258
+ }
259
+ return manager;
260
+ }
261
+
221
262
  /**
222
263
  * Fetch chat instructions from repo settings for a review.
223
264
  * @param {Database} db - Database instance
@@ -791,6 +832,8 @@ router.get('/api.md', (req, res) => {
791
832
  });
792
833
 
793
834
  module.exports = router;
835
+ module.exports.handleSessionIdleClosed = handleSessionIdleClosed;
836
+ module.exports.createChatSessionManager = createChatSessionManager;
794
837
 
795
838
  // Expose internals for testing
796
839
  module.exports._broadcastUnsubscribers = broadcastUnsubscribers;
package/src/server.js CHANGED
@@ -495,9 +495,9 @@ async function startServer(sharedDb = null, sharedPoolLifecycle = null, options
495
495
  const snippetsRoutes = require('./routes/snippets');
496
496
  const { createSoundRouter } = require('./routes/sound');
497
497
 
498
- // Initialize chat session manager
499
- const ChatSessionManager = require('./chat/session-manager');
500
- chatSessionManager = new ChatSessionManager(db, config.chat_providers || {});
498
+ // Initialize chat session manager (idle chat agents are shut down after
499
+ // chat.idle_timeout_minutes and resumed transparently on the next message)
500
+ chatSessionManager = chatRoutes.createChatSessionManager(db, config);
501
501
  app.chatSessionManager = chatSessionManager;
502
502
 
503
503
  // Mount specific routes first to ensure they match before general PR routes
@@ -613,6 +613,8 @@ async function gracefulShutdown(signal) {
613
613
  // Close all active chat sessions
614
614
  if (chatSessionManager) {
615
615
  try {
616
+ // Stop the idle reaper first so no sweep starts a close mid-shutdown
617
+ chatSessionManager.stopIdleReaper();
616
618
  await chatSessionManager.closeAll();
617
619
  } catch (error) {
618
620
  console.error('Error closing chat sessions:', error.message);
@@ -279,6 +279,16 @@ const REGISTRY = [
279
279
  editable: true,
280
280
  restartRequired: false
281
281
  },
282
+ {
283
+ key: 'chat.idle_timeout_minutes',
284
+ label: 'Idle chat timeout (minutes)',
285
+ description: 'Shut down a chat agent process after this many idle minutes; it resumes on the next message. 0 disables.',
286
+ group: 'chat',
287
+ type: 'integer',
288
+ default: 10,
289
+ editable: true,
290
+ restartRequired: true
291
+ },
282
292
  {
283
293
  key: 'chat_spinner',
284
294
  label: 'Chat spinner style',