@in-the-loop-labs/pair-review 5.3.4 → 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 +13 -1
- package/bin/git-diff-lines +2 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/skills/analyze/scripts/git-diff-lines +104 -25
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/public/css/pr.css +162 -46
- package/public/css/styles.css +0 -12
- package/public/js/components/AIPanel.js +3 -2
- package/public/js/components/AnalysisConfigModal.js +4 -1
- package/public/js/components/ChatPanel.js +39 -8
- package/public/js/components/PanelGroup.js +115 -21
- package/public/js/components/SuggestionNavigator.js +16 -3
- package/public/js/local.js +7 -12
- package/public/js/modules/diff-renderer.js +13 -0
- package/public/js/modules/file-comment-manager.js +19 -10
- package/public/js/modules/hunk-parser.js +39 -2
- package/public/js/modules/panel-resizer.js +41 -3
- package/public/js/modules/pierre-bridge.js +11 -2
- package/public/js/modules/suggestion-manager.js +128 -33
- package/public/js/pr.js +132 -29
- package/public/js/repo-settings.js +35 -19
- package/public/js/utils/git-paths.js +140 -0
- package/public/js/utils/smart-truncate.js +88 -0
- package/public/local.html +6 -0
- package/public/pr.html +6 -0
- package/src/ai/analyzer.js +15 -13
- package/src/ai/antigravity-provider.js +44 -24
- package/src/ai/cursor-agent-provider.js +4 -4
- package/src/ai/muse-provider.js +68 -3
- package/src/ai/summary-generator.js +8 -5
- package/src/chat/acp-bridge.js +26 -1
- package/src/chat/claude-code-bridge.js +10 -0
- package/src/chat/codex-bridge.js +10 -0
- package/src/chat/pi-bridge.js +10 -0
- package/src/chat/session-manager.js +333 -19
- package/src/config.js +40 -26
- package/src/git/diff-flags.js +26 -12
- package/src/git/worktree.js +21 -43
- package/src/github/client.js +0 -88
- package/src/github/impl/graphql/pending-review-comments.js +5 -1
- package/src/github/impl/host/pending-review-comments.js +75 -11
- package/src/github/submit-pr-context.js +56 -0
- package/src/local-review.js +34 -17
- package/src/main.js +80 -106
- package/src/routes/chat.js +44 -1
- package/src/routes/executable-analysis.js +14 -15
- package/src/routes/local.js +3 -5
- package/src/routes/pr.js +18 -105
- package/src/server.js +5 -3
- package/src/settings/registry.js +10 -0
- package/src/setup/pr-setup.js +1 -1
- package/src/setup/stack-setup.js +1 -1
- package/src/utils/diff-annotator.js +175 -25
- package/src/utils/diff-file-content.js +4 -26
- package/src/utils/diff-file-list.js +178 -42
- package/src/utils/git-paths.js +77 -0
- package/src/utils/paths.js +1 -25
package/src/chat/acp-bridge.js
CHANGED
|
@@ -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
|
// ---------------------------------------------------------------------------
|
package/src/chat/codex-bridge.js
CHANGED
|
@@ -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
|
// ---------------------------------------------------------------------------
|
package/src/chat/pi-bridge.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
355
|
-
|
|
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
|
-
//
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1151
|
+
const pendingCloses = [...this._closing.values()];
|
|
1152
|
+
if (sessionIds.length === 0 && pendingCloses.length === 0) return;
|
|
846
1153
|
|
|
847
|
-
|
|
848
|
-
|
|
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
|
|