@in-the-loop-labs/pair-review 5.3.2 → 5.3.3

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
@@ -726,7 +726,7 @@ You can override provider settings and define custom models in your config file.
726
726
  | `advisor` | OMP only. Set to `true` to enable OMP's advisor runtime during analysis (`--advisor`). Defaults to `false`: pair-review disables the advisor via a bundled config overlay, even when it is enabled in your global OMP configuration. |
727
727
  | `models` | Array of model definitions (see below) |
728
728
  | `default_model` | Model `id` to use as the provider's default (in the picker and when no model is specified). Preferred over the per-model `default: true` flag. If it names an unknown or disabled model, the provider falls back to automatic selection. |
729
- | `disabled_models` | Array of model selectors to hide, matched by model `id` or alias. Disabled models disappear from the model picker for that provider. Works on built-in models too, so you can remove a built-in option without redefining the rest. A list that would hide *every* model is ignored. |
729
+ | `disabled_models` | Array of canonical model `id`s to hide. Aliases (such as `opus`, or a retired id that now redirects to a newer model) are not matched and log a warning. Disabled models disappear from the model picker for that provider. Works on built-in models too, so you can remove a built-in option without redefining the rest. A list that would hide *every* model is ignored. |
730
730
 
731
731
  #### Model Configuration Fields
732
732
 
@@ -762,7 +762,7 @@ Use the provider-level `default_model` and `disabled_models` fields to tailor wh
762
762
  }
763
763
  ```
764
764
 
765
- - `disabled_models` removes those models from the picker. It matches by model id or alias, so either a canonical id (`opus-5.5-xhigh`) or a convenience alias (`opus`) works. The bare `opus` and `fable` aliases follow the newest generation, so list the canonical id to keep hiding one exact entry. To find the built-in IDs for a provider, see the comments in `config.example.json` (e.g. Claude ships `opus-4.8-xhigh`, `sonnet-4.6`, `haiku`, …).
765
+ - `disabled_models` removes those models from the picker. It matches canonical ids only (`opus-5.5-xhigh`, not the `opus` alias). An alias entry is ignored with a warning, so hiding a retired id such as `opus-4.7-high` never hides the newer model it now redirects to. To find the built-in IDs for a provider, see the comments in `config.example.json` (e.g. Claude ships `opus-5.5-medium`, `sonnet-4.6`, `haiku`, …).
766
766
  - `default_model` selects which of the *remaining* models is the default. If it points at a model that is unknown or also disabled, the provider falls back to automatic selection (the model marked `default: true`, then the first `balanced`-tier model, then the first model).
767
767
  - Prefer `default_model` over the per-model `default: true` flag, which is deprecated. Setting `default_model` suppresses the deprecation warning.
768
768
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@in-the-loop-labs/pair-review",
3
- "version": "5.3.2",
3
+ "version": "5.3.3",
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.2",
3
+ "version": "5.3.3",
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.2",
3
+ "version": "5.3.3",
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.2",
3
+ "version": "5.3.3",
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",
@@ -61,6 +61,8 @@ function getChatSpinnerHTML() {
61
61
  * @property {string|null} sessionAnalysisRunId
62
62
  * @property {HTMLElement} messagesEl - Per-tab scrollable messages container
63
63
  * @property {HTMLElement|null} streamingMsgEl - Reference to the in-progress assistant bubble
64
+ * @property {boolean} abortPending - True from a user Stop until the aborted run's complete/error arrives
65
+ * @property {boolean} streamJoinedMidTurn - True while the streaming bubble was opened by agent output rather than sendMessage (see _ensureStreamingMessage)
64
66
  * @property {boolean} userScrolledAway - Auto-scroll engagement flag
65
67
  * @property {Function|null} wsUnsub - Unsubscribe handle for the per-session WS topic
66
68
  * @property {Promise<void>|null} historyLoadPromise - Set while history is loading
@@ -167,6 +169,8 @@ class ChatPanel {
167
169
  sessionAnalysisRunId: null,
168
170
  messagesEl: null,
169
171
  streamingMsgEl: null,
172
+ abortPending: false,
173
+ streamJoinedMidTurn: false,
170
174
  userScrolledAway: false,
171
175
  wsUnsub: null,
172
176
  titleFromUser: false,
@@ -1969,6 +1973,9 @@ class ChatPanel {
1969
1973
  // before writing.
1970
1974
  const capturedEl = tab.messagesEl;
1971
1975
  if (!capturedEl) return;
1976
+ // The tab is already subscribed, so live output can land while the fetch
1977
+ // is in flight. Remember what was here so that output can be told apart.
1978
+ const elsBeforeFetch = new Set(capturedEl.children);
1972
1979
 
1973
1980
  let response;
1974
1981
  try {
@@ -2015,6 +2022,13 @@ class ChatPanel {
2015
2022
  const emptyState = capturedEl.querySelector('.chat-panel__empty');
2016
2023
  if (emptyState) emptyState.remove();
2017
2024
 
2025
+ // Elements added during the fetch — an agent turn already under way when
2026
+ // the tab subscribed, its errors, anything the user sent meanwhile — are
2027
+ // newer than the history. A reply that finished live may also be in the
2028
+ // fetched history; the live bubble stands in for it.
2029
+ const liveEls = Array.from(capturedEl.children).filter(el => !elsBeforeFetch.has(el));
2030
+ const liveMessageIds = new Set(liveEls.map(el => Number(el.dataset?.messageId)).filter(Boolean));
2031
+
2018
2032
  // Render into the target tab. The helper methods (_addContextCard,
2019
2033
  // addMessage, etc.) read `this.messagesEl` via the active-tab getter, so
2020
2034
  // we temporarily redirect the active marker for the synchronous render
@@ -2043,10 +2057,13 @@ class ChatPanel {
2043
2057
  // Not JSON — skip malformed context
2044
2058
  }
2045
2059
  } else if (msg.type === 'message') {
2060
+ if (liveMessageIds.has(msg.id)) continue;
2046
2061
  this.addMessage(msg.role, msg.content, msg.id);
2047
2062
  }
2048
2063
  }
2049
2064
  });
2065
+ // History was appended after the live elements; move them back below it.
2066
+ for (const el of liveEls) capturedEl.appendChild(el);
2050
2067
 
2051
2068
  // The tab was initialized as 'pending' (gray dot) before history loaded.
2052
2069
  // Now that messages exist, promote to 'idle' (blue dot) — but don't
@@ -3021,6 +3038,9 @@ class ChatPanel {
3021
3038
  tab.messages = [];
3022
3039
  tab.streamingContent = '';
3023
3040
  tab.streamingMsgEl = null;
3041
+ tab.streamJoinedMidTurn = false;
3042
+ // A Stop on the old session must not swallow the new session's turns.
3043
+ tab.abortPending = false;
3024
3044
  tab.pendingContext = [];
3025
3045
  tab.pendingContextData = [];
3026
3046
  tab.latestDiffState = null;
@@ -3127,6 +3147,7 @@ class ChatPanel {
3127
3147
  </div>
3128
3148
  `;
3129
3149
  tab.streamingMsgEl = null;
3150
+ tab.streamJoinedMidTurn = false;
3130
3151
  }
3131
3152
 
3132
3153
  /**
@@ -3329,6 +3350,7 @@ class ChatPanel {
3329
3350
 
3330
3351
  // Display user message (just the user's actual text)
3331
3352
  const msgElRef = this.addMessage('user', content, undefined, tab);
3353
+ const userMsgEntry = msgElRef ? tab.messages[tab.messages.length - 1] : null;
3332
3354
 
3333
3355
  // Lazy session creation: create on first message, not on panel open
3334
3356
  if (tab.sessionId == null) {
@@ -3357,8 +3379,11 @@ class ChatPanel {
3357
3379
  }
3358
3380
  // If sessionId is set (from MRU), just send — server auto-resumes
3359
3381
 
3360
- // Prepare streaming UI. Clear any previous error on this tab.
3382
+ // Prepare streaming UI. Clear any previous error on this tab, and any
3383
+ // Stop still waiting on its aborted run — this bubble is a new turn.
3361
3384
  tab.errorMessage = null;
3385
+ tab.abortPending = false;
3386
+ tab.streamJoinedMidTurn = false;
3362
3387
  tab.isStreaming = true;
3363
3388
  this._updateTabStatus(tab, 'streaming');
3364
3389
  if (this._getActiveTab() === tab) {
@@ -3369,6 +3394,7 @@ class ChatPanel {
3369
3394
  }
3370
3395
  tab.streamingContent = '';
3371
3396
  this._addStreamingPlaceholder(tab);
3397
+ const placeholderEl = tab.streamingMsgEl;
3372
3398
 
3373
3399
  // Build the API payload — may include pending context from "Ask about this"
3374
3400
  const payload = { content };
@@ -3437,6 +3463,10 @@ class ChatPanel {
3437
3463
  this._showStatusFlash('Resuming Agent Client Protocol');
3438
3464
  }
3439
3465
 
3466
+ // The session the message is posted to. A tab switched to another session
3467
+ // mid-request has torn this send's bubble down.
3468
+ let sentSessionId = tab.sessionId;
3469
+
3440
3470
  // Send to API
3441
3471
  try {
3442
3472
  console.debug('[ChatPanel] Sending message to session', tab.sessionId);
@@ -3462,6 +3492,9 @@ class ChatPanel {
3462
3492
  // _localKey check (rather than orphaning this tab and spawning a new).
3463
3493
  const wasActive = this._getActiveTab() === tab;
3464
3494
  tab.sessionId = null;
3495
+ // Per-session flags: a Stop clicked on the dead session must not
3496
+ // swallow the replacement session's output.
3497
+ tab.abortPending = false;
3465
3498
  if (wasActive) this.activeTabKey = tab._localKey;
3466
3499
  const sessionData = await this._createSessionForTab(tab);
3467
3500
  if (!this.tabs.includes(tab)) return;
@@ -3469,6 +3502,7 @@ class ChatPanel {
3469
3502
  throw new Error('Failed to create replacement session');
3470
3503
  }
3471
3504
 
3505
+ sentSessionId = tab.sessionId;
3472
3506
  response = await fetch(`/api/chat/session/${tab.sessionId}/message`, {
3473
3507
  method: 'POST',
3474
3508
  headers: { 'Content-Type': 'application/json' },
@@ -3479,12 +3513,31 @@ class ChatPanel {
3479
3513
 
3480
3514
  if (!response.ok) {
3481
3515
  const err = await response.json().catch(() => ({}));
3482
- throw new Error(err.error || 'Failed to send message');
3516
+ const sendError = new Error(err.error || 'Failed to send message');
3517
+ // 409: the agent still owns its previous turn and the server did not
3518
+ // store this message.
3519
+ sendError.notStored = response.status === 409;
3520
+ throw sendError;
3483
3521
  }
3484
3522
  console.debug('[ChatPanel] Message accepted, waiting for WebSocket events');
3485
3523
  } catch (error) {
3486
3524
  if (!this.tabs.includes(tab)) return;
3487
3525
  if (acpResuming) this._hideStatusFlash();
3526
+ if (error.notStored) {
3527
+ // Take the unsent message back into the input so it can be sent once
3528
+ // the reply finishes — unless the user has moved on or typed again.
3529
+ if (msgElRef) msgElRef.remove();
3530
+ const idx = tab.messages.indexOf(userMsgEntry);
3531
+ if (idx !== -1) tab.messages.splice(idx, 1);
3532
+ if (this._getActiveTab() === tab && !this.inputEl.value) {
3533
+ this.inputEl.value = messageText;
3534
+ this._autoResizeTextarea();
3535
+ }
3536
+ // A tab switched to another session mid-request already dropped this
3537
+ // send's bubbles and pending state; the new session's streaming state
3538
+ // and context are not this send's to touch.
3539
+ if (tab.sessionId !== sentSessionId) return;
3540
+ }
3488
3541
  // Restore pending state on the originating tab so it's not lost.
3489
3542
  tab.pendingContext = savedContext;
3490
3543
  tab.pendingContextData = savedContextData;
@@ -3496,6 +3549,30 @@ class ChatPanel {
3496
3549
  // Restore removability on context cards that were locked before the failed send
3497
3550
  this._restoreRemovableCards(tab);
3498
3551
  console.error('[ChatPanel] Error sending message:', error);
3552
+ if (error.notStored) {
3553
+ // The busy turn's complete can beat this response (it is sent after
3554
+ // the server's busy check) and finalize this send's bubble with only
3555
+ // the output seen during the request. Show all of that reply.
3556
+ const savedId = Number(placeholderEl?.dataset.messageId);
3557
+ if (savedId) this._showSavedReply(tab, placeholderEl, savedId);
3558
+ if (tab.streamingMsgEl) {
3559
+ // The agent is still mid-turn — e.g. an OMP run paused on a
3560
+ // background job, seen from a page reloaded mid-reply. Keep the
3561
+ // bubble streaming, with Stop, so the rest of the turn renders
3562
+ // there; this page missed the turn's start, so complete swaps in
3563
+ // the saved reply. The notice goes above the bubble and, unlike
3564
+ // _showError, leaves the tab 'streaming'.
3565
+ if (tab.streamingMsgEl === placeholderEl) tab.streamJoinedMidTurn = true;
3566
+ if (this._appendErrorBubble('Failed to send message. The agent is still working on its previous reply. Wait for it to finish, or click Stop, then send your message again.', tab)) {
3567
+ tab.messagesEl.appendChild(tab.streamingMsgEl);
3568
+ if (this._getActiveTab() === tab) this.scrollToBottom();
3569
+ }
3570
+ return;
3571
+ }
3572
+ this._showError('Failed to send message. The agent was still finishing its previous reply, which has now ended. Send your message again.', tab);
3573
+ this._finalizeStreaming(tab);
3574
+ return;
3575
+ }
3499
3576
  this._showError('Failed to send message. ' + error.message, tab);
3500
3577
  this._finalizeStreaming(tab);
3501
3578
  }
@@ -4888,7 +4965,17 @@ class ChatPanel {
4888
4965
  }
4889
4966
 
4890
4967
  async _recoverTabAfterReconnect(tab) {
4891
- if (!tab?.isStreaming || tab.sessionId == null) return;
4968
+ if (!tab) return;
4969
+ if (!tab.isStreaming) {
4970
+ // A Stop's aborted run may have sent its complete/error while the
4971
+ // socket was down; left set, abortPending would drop every later
4972
+ // agent-started turn until the next send. Tradeoff: output still
4973
+ // trailing the stopped run after the reconnect can open a bubble.
4974
+ // Streaming tabs keep it: their Stop request is still in flight.
4975
+ tab.abortPending = false;
4976
+ return;
4977
+ }
4978
+ if (tab.sessionId == null) return;
4892
4979
  const capturedSessionId = tab.sessionId;
4893
4980
  try {
4894
4981
  const response = await fetch(`/api/chat/session/${tab.sessionId}/messages`);
@@ -4946,22 +5033,32 @@ class ChatPanel {
4946
5033
  if (!isActive) {
4947
5034
  switch (data.type) {
4948
5035
  case 'delta':
4949
- if (!tab.streamingMsgEl) this._addStreamingPlaceholder(tab);
5036
+ if (!this._ensureStreamingMessage(tab)) break;
4950
5037
  tab.streamingContent += data.text;
4951
5038
  this.updateStreamingMessage(tab.streamingContent, tab);
4952
5039
  this._markStreaming(tab);
4953
5040
  break;
4954
5041
  case 'status':
4955
- if (data.status === 'working') this._markStreaming(tab);
5042
+ if (data.status === 'working' && this._ensureStreamingMessage(tab)) this._markStreaming(tab);
4956
5043
  break;
4957
- case 'complete':
5044
+ case 'complete': {
5045
+ // Read before the finalize clears them; see _showSavedReply.
5046
+ const wasAborting = tab.abortPending;
5047
+ const hadBubble = !!tab.streamingMsgEl;
5048
+ const joinedMsgEl = tab.streamJoinedMidTurn ? tab.streamingMsgEl : null;
5049
+ tab.abortPending = false;
4958
5050
  this._finalizeTabStream(tab, data.messageId);
4959
5051
  tab.streamingContent = '';
4960
5052
  tab.isStreaming = false;
4961
5053
  tab.errorMessage = null;
4962
5054
  this._updateTabStatus(tab, 'idle');
5055
+ if (data.messageId && (joinedMsgEl || (!hadBubble && !wasAborting))) {
5056
+ this._showSavedReply(tab, joinedMsgEl, data.messageId);
5057
+ }
4963
5058
  break;
5059
+ }
4964
5060
  case 'error':
5061
+ tab.abortPending = false;
4965
5062
  // Render the error inline so the user sees what happened when
4966
5063
  // they switch back to this tab.
4967
5064
  this._showError(data.message || 'An error occurred', tab);
@@ -4976,21 +5073,34 @@ class ChatPanel {
4976
5073
  // Foreground path — drive the DOM directly
4977
5074
  switch (data.type) {
4978
5075
  case 'delta':
5076
+ if (!this._ensureStreamingMessage(tab)) break;
4979
5077
  this._hideThinkingIndicator(tab);
4980
5078
  tab.streamingContent += data.text;
4981
5079
  this.updateStreamingMessage(tab.streamingContent, tab);
4982
5080
  break;
4983
5081
  case 'tool_use':
5082
+ if (!this._ensureStreamingMessage(tab)) break;
4984
5083
  this._showToolUse(data.toolName, data.status, data.toolInput, tab);
4985
5084
  break;
4986
5085
  case 'status':
5086
+ if (data.status === 'working' && !this._ensureStreamingMessage(tab)) break;
4987
5087
  this._handleAgentStatus(data.status, tab);
4988
5088
  break;
4989
- case 'complete':
5089
+ case 'complete': {
5090
+ // Read before the finalize clears them; see _showSavedReply.
5091
+ const wasAborting = tab.abortPending;
5092
+ const hadBubble = !!tab.streamingMsgEl;
5093
+ const joinedMsgEl = tab.streamJoinedMidTurn ? tab.streamingMsgEl : null;
5094
+ tab.abortPending = false;
4990
5095
  tab.errorMessage = null;
4991
5096
  this.finalizeStreamingMessage(data.messageId, tab);
5097
+ if (data.messageId && (joinedMsgEl || (!hadBubble && !wasAborting))) {
5098
+ this._showSavedReply(tab, joinedMsgEl, data.messageId);
5099
+ }
4992
5100
  break;
5101
+ }
4993
5102
  case 'error':
5103
+ tab.abortPending = false;
4994
5104
  tab.errorMessage = data.message || 'An error occurred';
4995
5105
  this._updateTabStatus(tab, 'error');
4996
5106
  this._showError(tab.errorMessage, tab);
@@ -5022,9 +5132,11 @@ class ChatPanel {
5022
5132
  * @param {string} content - Message text
5023
5133
  * @param {number} [id] - Optional message ID
5024
5134
  * @param {ChatTab} [targetTab] - Explicit tab; defaults to active tab
5135
+ * @param {{forceScroll?: boolean}} [opts] - forceScroll: false keeps the
5136
+ * user's scroll position when they have scrolled away from the bottom
5025
5137
  * @returns {HTMLElement} The message element that was appended
5026
5138
  */
5027
- addMessage(role, content, id, targetTab) {
5139
+ addMessage(role, content, id, targetTab, { forceScroll = true } = {}) {
5028
5140
  const tab = targetTab || this._getActiveTab();
5029
5141
  if (!tab || !tab.messagesEl) return null;
5030
5142
 
@@ -5064,7 +5176,7 @@ class ChatPanel {
5064
5176
  }
5065
5177
  }
5066
5178
 
5067
- if (this._getActiveTab() === tab) this.scrollToBottom({ force: true });
5179
+ if (this._getActiveTab() === tab) this.scrollToBottom({ force: forceScroll });
5068
5180
  return msgEl;
5069
5181
  }
5070
5182
 
@@ -5109,8 +5221,10 @@ class ChatPanel {
5109
5221
  /**
5110
5222
  * Add a streaming placeholder for the assistant's response on a tab.
5111
5223
  * @param {ChatTab} [targetTab] - Defaults to active tab
5224
+ * @param {{forceScroll?: boolean}} [opts] - forceScroll: false keeps the
5225
+ * user's scroll position when they have scrolled away from the bottom
5112
5226
  */
5113
- _addStreamingPlaceholder(targetTab) {
5227
+ _addStreamingPlaceholder(targetTab, { forceScroll = true } = {}) {
5114
5228
  const tab = targetTab || this._getActiveTab();
5115
5229
  if (!tab || !tab.messagesEl) return;
5116
5230
  const msgEl = document.createElement('div');
@@ -5123,7 +5237,45 @@ class ChatPanel {
5123
5237
  msgEl.appendChild(bubble);
5124
5238
  tab.messagesEl.appendChild(msgEl);
5125
5239
  tab.streamingMsgEl = msgEl;
5126
- if (this._getActiveTab() === tab) this.scrollToBottom({ force: true });
5240
+ if (this._getActiveTab() === tab) this.scrollToBottom({ force: forceScroll });
5241
+ }
5242
+
5243
+ /**
5244
+ * Make sure a tab has a streaming bubble for incoming agent output.
5245
+ * sendMessage() normally creates it, but an agent can start a turn on its
5246
+ * own after the previous one completed — OMP resumes when an advisor steers
5247
+ * it or an async job delivers its result. Without a bubble that turn's
5248
+ * deltas and tool badges have nowhere to render, while its 'working' status
5249
+ * still marks the tab streaming, so sends are silently dropped until a page
5250
+ * refresh.
5251
+ *
5252
+ * Output that trails a user Stop is not a new turn: it belongs to the run
5253
+ * being aborted and is dropped until that run's complete/error arrives.
5254
+ *
5255
+ * The bubble is marked streamJoinedMidTurn: this page may have missed the
5256
+ * start of the turn (a reload mid-reply, or an OMP run resuming text the
5257
+ * bridge accumulated before its pause), so on complete the saved reply
5258
+ * replaces the streamed text. Every auto-opened bubble is marked — even
5259
+ * one opened by a 'working' status, since OMP emits one per LLM turn
5260
+ * inside a run — at the cost of one message fetch per such turn.
5261
+ * @param {ChatTab} tab
5262
+ * @returns {boolean} False when the event should be dropped
5263
+ */
5264
+ _ensureStreamingMessage(tab) {
5265
+ if (tab.streamingMsgEl) return true;
5266
+ if (tab.abortPending) return false;
5267
+ // Agent output the user did not ask for must not yank them back down
5268
+ // from history they are reading.
5269
+ this._addStreamingPlaceholder(tab, { forceScroll: false });
5270
+ tab.streamJoinedMidTurn = true;
5271
+ this._markStreaming(tab);
5272
+ if (this.isOpen && this._getActiveTab() === tab) {
5273
+ this.sendBtn.disabled = true;
5274
+ this.sendBtn.style.display = 'none';
5275
+ this.stopBtn.style.display = '';
5276
+ this._updateActionButtons();
5277
+ }
5278
+ return true;
5127
5279
  }
5128
5280
 
5129
5281
  /**
@@ -5201,6 +5353,72 @@ class ChatPanel {
5201
5353
  tab.messages.push({ role: 'assistant', content: tab.streamingContent, id: messageId });
5202
5354
  }
5203
5355
  tab.streamingMsgEl = null;
5356
+ tab.streamJoinedMidTurn = false;
5357
+ }
5358
+
5359
+ /**
5360
+ * Show a just-completed reply as saved. Runs after the synchronous
5361
+ * finalize, so the tab is already idle: a Stop, a send, or the agent's next
5362
+ * turn never race this fetch for the bubble.
5363
+ *
5364
+ * With msgEl, replace that finalized bubble's text: a bubble opened by
5365
+ * _ensureStreamingMessage may have seen only the tail of the turn, while
5366
+ * the saved message holds all of it.
5367
+ *
5368
+ * With msgEl null, add the reply as a new bubble. A page that loaded its
5369
+ * history mid-turn — during an OMP pause, before the reply was saved — and
5370
+ * saw no output before 'complete' (a Stop from another window, an OMP exit
5371
+ * or failed prompt ending the pause) has no bubble to fill. Callers skip
5372
+ * this after a Stop on this tab, whose finalize already shows the reply;
5373
+ * a reply already in tab.messages (history returned it) is skipped here.
5374
+ *
5375
+ * Message ids are numbers ('complete' and the saved rows); a dataset value
5376
+ * is a string, so it is converted with Number() where read.
5377
+ * @param {ChatTab} tab
5378
+ * @param {HTMLElement|null} msgEl - The finalized reply's message element, or null to add one
5379
+ * @param {number} messageId - Saved assistant message id from 'complete'
5380
+ */
5381
+ async _showSavedReply(tab, msgEl, messageId) {
5382
+ const isShown = () => tab.messages.some(m => m.role === 'assistant' && m.id === messageId);
5383
+ if (!msgEl && isShown()) return;
5384
+ const capturedSessionId = tab.sessionId;
5385
+ let saved = null;
5386
+ try {
5387
+ const response = await fetch(`/api/chat/session/${capturedSessionId}/messages`);
5388
+ if (!response.ok) return;
5389
+ const result = await response.json();
5390
+ saved = (result.data?.messages || []).find(m => m.id === messageId) || null;
5391
+ } catch (err) {
5392
+ console.warn('[ChatPanel] Failed to load saved reply:', err);
5393
+ return;
5394
+ }
5395
+ if (!this.tabs.includes(tab) || tab.sessionId !== capturedSessionId) return;
5396
+ if (!saved?.content) return;
5397
+
5398
+ if (!msgEl) {
5399
+ // History that rendered during the fetch may show it by now. Otherwise
5400
+ // the bubble carries its id, so a history render still to come skips
5401
+ // the row and moves the bubble below the history.
5402
+ if (isShown()) return;
5403
+ // Agent output: don't pull a user reading history back down.
5404
+ this.addMessage('assistant', saved.content, messageId, tab, { forceScroll: false });
5405
+ if (tab.status === 'pending') this._updateTabStatus(tab, 'idle');
5406
+ return;
5407
+ }
5408
+
5409
+ const entry = tab.messages.find(m => m.role === 'assistant' && m.id === messageId);
5410
+ if (entry) {
5411
+ entry.content = saved.content;
5412
+ } else {
5413
+ // Nothing streamed, so the finalize recorded no message.
5414
+ tab.messages.push({ role: 'assistant', content: saved.content, id: messageId });
5415
+ }
5416
+ const bubble = msgEl.querySelector('.chat-panel__bubble');
5417
+ if (bubble) {
5418
+ bubble.innerHTML = this.renderMarkdown(saved.content);
5419
+ this._linkifyFileReferences(bubble);
5420
+ bubble.appendChild(this._createCopyButton(saved.content));
5421
+ }
5204
5422
  }
5205
5423
 
5206
5424
  /**
@@ -5211,12 +5429,19 @@ class ChatPanel {
5211
5429
  async _stopAgent() {
5212
5430
  const tab = this._getActiveTab();
5213
5431
  if (!tab || !tab.isStreaming || tab.sessionId == null) return;
5432
+ // Output still in flight from the aborted run must not reopen a bubble
5433
+ // after the finalize below. Set before the request so a complete that
5434
+ // beats the response still clears it.
5435
+ tab.abortPending = true;
5214
5436
  try {
5215
5437
  await fetch(`/api/chat/session/${tab.sessionId}/abort`, { method: 'POST' });
5216
5438
  } catch (error) {
5217
5439
  console.error('[ChatPanel] Error aborting:', error);
5218
5440
  }
5219
- if (!this.tabs.includes(tab)) return;
5441
+ // A cleared flag means the aborted run already finished (complete/error
5442
+ // finalized its bubble) or the tab moved to another session. Any bubble
5443
+ // now streaming belongs to a newer turn and must be left alone.
5444
+ if (!this.tabs.includes(tab) || !tab.abortPending) return;
5220
5445
  // Finalize the streaming message with whatever content we have so far.
5221
5446
  this.finalizeStreamingMessage(null, tab);
5222
5447
  }
@@ -5232,6 +5457,7 @@ class ChatPanel {
5232
5457
  tab.isStreaming = false;
5233
5458
  tab.streamingContent = '';
5234
5459
  tab.streamingMsgEl = null;
5460
+ tab.streamJoinedMidTurn = false;
5235
5461
  this._updateTabStatus(tab, tab.errorMessage ? 'error' : 'idle');
5236
5462
  }
5237
5463
  if (!tab || this._getActiveTab() === tab) {
@@ -5431,8 +5657,21 @@ class ChatPanel {
5431
5657
  tab.errorMessage = message;
5432
5658
  this._updateTabStatus(tab, 'error');
5433
5659
  }
5660
+ if (!this._appendErrorBubble(message, tab)) return;
5661
+ if (this._getActiveTab() === tab) this.scrollToBottom({ force: true });
5662
+ }
5663
+
5664
+ /**
5665
+ * Append an error bubble to a tab's messages without changing the tab's
5666
+ * status or errorMessage — for a notice that must not mark a turn still
5667
+ * streaming as errored. _showError does both.
5668
+ * @param {string} message - Error text
5669
+ * @param {ChatTab} [tab]
5670
+ * @returns {HTMLElement|null} The bubble, or null when the tab has no messages element
5671
+ */
5672
+ _appendErrorBubble(message, tab) {
5434
5673
  const messagesEl = tab?.messagesEl;
5435
- if (!messagesEl) return;
5674
+ if (!messagesEl) return null;
5436
5675
  const errorEl = document.createElement('div');
5437
5676
  errorEl.className = 'chat-panel__message chat-panel__message--error';
5438
5677
  errorEl.innerHTML = `
@@ -5444,7 +5683,7 @@ class ChatPanel {
5444
5683
  </div>
5445
5684
  `;
5446
5685
  messagesEl.appendChild(errorEl);
5447
- if (this._getActiveTab() === tab) this.scrollToBottom({ force: true });
5686
+ return errorEl;
5448
5687
  }
5449
5688
 
5450
5689
  /**
@@ -27,8 +27,8 @@ const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
27
27
  * (e.g., Haiku uses adaptive thinking for efficiency).
28
28
  *
29
29
  * Effort support by model (newest CLIs): Fable 5.1, Fable 5, Opus 5.5, Opus 5,
30
- * Opus 4.8 / 4.7, and Sonnet 5 support low|medium|high|xhigh|max; Opus 4.6 &
31
- * Sonnet 4.6 support low|medium|high|max (no xhigh); Haiku has no effort levels.
30
+ * and Sonnet 5 support low|medium|high|xhigh|max; Sonnet 4.6 supports
31
+ * low|medium|high|max (no xhigh); Haiku has no effort levels.
32
32
  * The CLI's own default effort for Opus 5.5 is `medium` (and it ignores a
33
33
  * top-level `effortLevel` in user settings), so its entries rely on the env var,
34
34
  * which the CLI treats as an explicit choice at the top of its effort precedence.
@@ -95,8 +95,10 @@ const CLAUDE_MODELS = [
95
95
  },
96
96
  {
97
97
  id: 'opus-5.5-xhigh',
98
- // Generation alias; see fable-5.1-xhigh above.
99
- aliases: ['opus'],
98
+ // Generation alias; see fable-5.1-xhigh above. The Opus 4.x entries were
99
+ // dropped; their ids resolve to the Opus 5.5 entry at the matching effort so
100
+ // saved configs, councils, and --model flags keep working.
101
+ aliases: ['opus', 'opus-4.8-xhigh', 'opus-4.7-xhigh'],
100
102
  cli_model: 'claude-opus-5-5',
101
103
  env: { CLAUDE_CODE_EFFORT_LEVEL: 'xhigh' },
102
104
  name: 'Opus 5.5 XHigh',
@@ -112,6 +114,7 @@ const CLAUDE_MODELS = [
112
114
  },
113
115
  {
114
116
  id: 'opus-5.5-high',
117
+ aliases: ['opus-4.8-high', 'opus-4.7-high', 'opus-4.6-high', 'opus-4.6-1m', 'opus-4.5'],
115
118
  cli_model: 'claude-opus-5-5',
116
119
  env: { CLAUDE_CODE_EFFORT_LEVEL: 'high' },
117
120
  name: 'Opus 5.5 High',
@@ -145,62 +148,6 @@ const CLAUDE_MODELS = [
145
148
  badge: 'High Effort',
146
149
  badgeClass: 'badge-power'
147
150
  },
148
- {
149
- id: 'opus-4.8-xhigh',
150
- cli_model: 'claude-opus-4-8',
151
- env: { CLAUDE_CODE_EFFORT_LEVEL: 'xhigh' },
152
- name: 'Opus 4.8 XHigh',
153
- tier: 'thorough',
154
- tagline: 'Previous Gen',
155
- description: 'Opus 4.8 with extra-high effort',
156
- badge: 'Previous Gen',
157
- badgeClass: 'badge-power'
158
- },
159
- {
160
- id: 'opus-4.8-high',
161
- cli_model: 'claude-opus-4-8',
162
- env: { CLAUDE_CODE_EFFORT_LEVEL: 'high' },
163
- name: 'Opus 4.8 High',
164
- tier: 'thorough',
165
- tagline: 'High Effort',
166
- description: 'Opus 4.8 with high effort — thorough, quicker than XHigh',
167
- badge: 'Thorough',
168
- badgeClass: 'badge-power'
169
- },
170
- {
171
- id: 'opus-4.7-xhigh',
172
- cli_model: 'claude-opus-4-7',
173
- env: { CLAUDE_CODE_EFFORT_LEVEL: 'xhigh' },
174
- name: 'Opus 4.7 XHigh',
175
- tier: 'thorough',
176
- tagline: 'Previous Gen',
177
- description: 'Opus 4.7 with extra-high effort',
178
- badge: 'Previous Gen',
179
- badgeClass: 'badge-power'
180
- },
181
- {
182
- id: 'opus-4.7-high',
183
- cli_model: 'claude-opus-4-7',
184
- env: { CLAUDE_CODE_EFFORT_LEVEL: 'high' },
185
- name: 'Opus 4.7 High',
186
- tier: 'thorough',
187
- tagline: 'High Effort',
188
- description: 'Opus 4.7 with high effort — thorough, quicker than XHigh',
189
- badge: 'Thorough',
190
- badgeClass: 'badge-power'
191
- },
192
- {
193
- id: 'opus-4.6-high',
194
- aliases: ['opus-4.6-low', 'opus-4.6-medium', 'opus-4.5'],
195
- cli_model: 'claude-opus-4-6',
196
- env: { CLAUDE_CODE_EFFORT_LEVEL: 'high' },
197
- name: 'Opus 4.6 High',
198
- tier: 'thorough',
199
- tagline: 'Previous Gen',
200
- description: 'Opus 4.6 with high effort',
201
- badge: 'Previous Gen',
202
- badgeClass: 'badge-power'
203
- },
204
151
  // ── Balanced tier ───────────────────────────────────────────────────────
205
152
  {
206
153
  id: 'sonnet-5-xhigh',
@@ -224,6 +171,19 @@ const CLAUDE_MODELS = [
224
171
  badge: 'Quick & Sharp',
225
172
  badgeClass: 'badge-speed'
226
173
  },
174
+ {
175
+ id: 'opus-5.5-medium',
176
+ aliases: ['opus-4.6-medium'],
177
+ cli_model: 'claude-opus-5-5',
178
+ env: { CLAUDE_CODE_EFFORT_LEVEL: 'medium' },
179
+ name: 'Opus 5.5 Medium',
180
+ tier: 'balanced',
181
+ tagline: 'Everyday Opus',
182
+ description: 'Opus 5.5 with medium effort — strong everyday reviews at lower cost and latency',
183
+ badge: 'Medium Effort',
184
+ badgeClass: 'badge-balanced',
185
+ extra_args: ['--thinking', 'adaptive']
186
+ },
227
187
  {
228
188
  id: 'sonnet-4.6',
229
189
  cli_model: 'claude-sonnet-4-6',
@@ -234,16 +194,6 @@ const CLAUDE_MODELS = [
234
194
  badge: 'Previous Gen',
235
195
  badgeClass: 'badge-balanced'
236
196
  },
237
- {
238
- id: 'opus-4.6-1m',
239
- cli_model: 'claude-opus-4-6[1m]',
240
- name: 'Opus 4.6 1M',
241
- tier: 'balanced',
242
- tagline: 'Extended Context',
243
- description: 'Opus 4.6 high effort with 1M token context window',
244
- badge: 'More Context',
245
- badgeClass: 'badge-power'
246
- },
247
197
  // ── Fast tier ───────────────────────────────────────────────────────────
248
198
  {
249
199
  id: 'haiku',
@@ -255,6 +205,21 @@ const CLAUDE_MODELS = [
255
205
  badge: 'Fastest',
256
206
  badgeClass: 'badge-speed',
257
207
  extra_args: ['--thinking', 'adaptive']
208
+ },
209
+ {
210
+ // Kept after haiku: getFastTierModel() takes the first fast-tier entry for
211
+ // extraction and hunk summaries, which should stay on Haiku.
212
+ id: 'opus-5.5-low',
213
+ aliases: ['opus-4.6-low'],
214
+ cli_model: 'claude-opus-5-5',
215
+ env: { CLAUDE_CODE_EFFORT_LEVEL: 'low' },
216
+ name: 'Opus 5.5 Low',
217
+ tier: 'fast',
218
+ tagline: 'Quick Opus',
219
+ description: 'Opus 5.5 with low effort — fast passes over simple changes',
220
+ badge: 'Low Effort',
221
+ badgeClass: 'badge-speed',
222
+ extra_args: ['--thinking', 'adaptive']
258
223
  }
259
224
  ];
260
225
 
@@ -593,7 +593,7 @@ function resolveCliModelConfig(builtIn, configModel, modelId) {
593
593
  /**
594
594
  * Match a model definition against a selector that may be the model's canonical
595
595
  * id OR one of its aliases. Used by config-driven selectors (`default_model`,
596
- * `disabled_models`, `models` overrides) so legacy config naming an alias (e.g.
596
+ * `models` overrides) so legacy config naming an alias (e.g.
597
597
  * `opus`, an alias of the canonical `opus-5.5-xhigh`) keeps working.
598
598
  *
599
599
  * Optional-chaining is intentional: a model with no `aliases` short-circuits to
@@ -918,7 +918,8 @@ function mergeModels(builtInModels, configModels) {
918
918
 
919
919
  /**
920
920
  * Compute the effective model list for a provider: built-in models merged with
921
- * config-override models, then with any `disabled_models` IDs removed.
921
+ * config-override models, then with any `disabled_models` IDs removed. Only
922
+ * canonical ids disable a model; aliases are ignored (see below).
922
923
  *
923
924
  * This is the single source of truth for "which models does this provider
924
925
  * actually expose" — every call site that surfaces or selects a model should go
@@ -940,8 +941,11 @@ function applyModelOverrides(builtInModels, overrides) {
940
941
  if (!Array.isArray(disabled) || disabled.length === 0) {
941
942
  return merged;
942
943
  }
943
- // Drop a model if ANY disabled selector matches it by canonical id or alias.
944
- const filtered = merged.filter(m => !disabled.some(d => modelMatches(m, d)));
944
+ // Drop a model only when a disabled selector names its canonical id. Aliases
945
+ // are deliberately not matched: they include redirects for retired ids (e.g.
946
+ // `opus-4.7-high` -> `opus-5.5-high`), so a list that hid an old model would
947
+ // otherwise hide the newer model that inherited its id.
948
+ const filtered = merged.filter(m => !disabled.includes(m.id));
945
949
  // Never strip a provider down to zero models — fall back to the unfiltered set.
946
950
  return filtered.length > 0 ? filtered : merged;
947
951
  }
@@ -986,11 +990,15 @@ function validateModelSelectors(providerId, builtInModels, configModels, disable
986
990
 
987
991
  if (disabledModels) {
988
992
  for (const id of disabledModels) {
989
- if (!isKnown(id)) {
993
+ if (merged.some(m => m.id === id)) continue;
994
+ const aliased = merged.find(m => modelMatches(m, id));
995
+ if (aliased) {
996
+ logger.warn(`Provider "${providerId}": disabled_models entry "${id}" is an alias of "${aliased.id}", not an id; disabled_models needs canonical ids. Ignored.`);
997
+ } else {
990
998
  logger.warn(`Provider "${providerId}": disabled_models references unknown model "${id}".`);
991
999
  }
992
1000
  }
993
- const remaining = merged.filter(m => !disabledModels.some(d => modelMatches(m, d)));
1001
+ const remaining = merged.filter(m => !disabledModels.includes(m.id));
994
1002
  if (merged.length > 0 && remaining.length === 0) {
995
1003
  logger.warn(`Provider "${providerId}": disabled_models removes every model; the filter will be ignored.`);
996
1004
  }
@@ -999,7 +1007,7 @@ function validateModelSelectors(providerId, builtInModels, configModels, disable
999
1007
  if (defaultModel != null) {
1000
1008
  if (!isKnown(defaultModel)) {
1001
1009
  logger.warn(`Provider "${providerId}": default_model "${defaultModel}" is not a known model; falling back to automatic default.`);
1002
- } else if (disabledModels && disabledModels.includes(defaultModel)) {
1010
+ } else if (disabledModels && disabledModels.includes(merged.find(m => modelMatches(m, defaultModel)).id)) {
1003
1011
  logger.warn(`Provider "${providerId}": default_model "${defaultModel}" is also listed in disabled_models; falling back to automatic default.`);
1004
1012
  }
1005
1013
  }
@@ -18,11 +18,38 @@
18
18
  * - OMP's `autoResume` setting reopens the most recent session in the cwd
19
19
  * when no session flag is passed, so new chats must explicitly request a
20
20
  * fresh session via the `new_session` RPC command before session discovery.
21
+ * - OMP emits session events Pi does not: `notice` diagnostics and status-line
22
+ * updates (advisor, compaction, retry, ...). See _handleOtherEvent.
21
23
  */
22
24
 
23
25
  const PiBridge = require('./pi-bridge');
24
26
  const logger = require('../utils/logger');
25
27
 
28
+ /**
29
+ * OMP session events that only drive its TUI status line. They carry nothing
30
+ * the chat panel renders, so they are acknowledged at debug level rather than
31
+ * reported as unhandled. Mirrors the informational members of OMP's
32
+ * `AgentSessionEvent` union (src/session/agent-session-events.ts).
33
+ */
34
+ const OMP_STATUS_EVENTS = new Set([
35
+ 'advisor_cost_changed',
36
+ 'advisor_yielded',
37
+ 'auto_compaction_end',
38
+ 'auto_compaction_start',
39
+ 'auto_retry_end',
40
+ 'auto_retry_start',
41
+ 'config_warnings_changed',
42
+ 'goal_updated',
43
+ 'irc_message',
44
+ 'model_changed',
45
+ 'retry_fallback_applied',
46
+ 'retry_fallback_succeeded',
47
+ 'thinking_level_changed',
48
+ 'todo_auto_clear',
49
+ 'todo_reminder',
50
+ 'ttsr_triggered',
51
+ ]);
52
+
26
53
  class OmpBridge extends PiBridge {
27
54
  /**
28
55
  * @param {Object} options - Same options as PiBridge, except:
@@ -55,6 +82,35 @@ class OmpBridge extends PiBridge {
55
82
  this._splitProviderModel = false;
56
83
  }
57
84
 
85
+ /**
86
+ * Handle OMP-only session events. A `notice` is OMP reporting a problem or
87
+ * status of its own (config warnings, advisor quota, session persistence
88
+ * failures), so it is logged at its own level; status-line events are
89
+ * acknowledged quietly.
90
+ * @param {Object} event - The parsed event
91
+ */
92
+ _handleOtherEvent(event) {
93
+ if (event.type === 'notice') {
94
+ const source = event.source ? ` (${event.source})` : '';
95
+ const text = `[${this.logName}] OMP notice${source}: ${event.message}`;
96
+ if (event.level === 'error') {
97
+ logger.error(text);
98
+ } else if (event.level === 'warning') {
99
+ logger.warn(text);
100
+ } else {
101
+ logger.debug(text);
102
+ }
103
+ return;
104
+ }
105
+
106
+ if (OMP_STATUS_EVENTS.has(event.type)) {
107
+ logger.debug(`[${this.logName}] ${event.type}`);
108
+ return;
109
+ }
110
+
111
+ super._handleOtherEvent(event);
112
+ }
113
+
58
114
  /**
59
115
  * No sessionPath means this is a new chat. Launching OMP without a session
60
116
  * flag would let its `autoResume` setting reopen the user's most recent
@@ -76,6 +76,12 @@ class PiBridge extends EventEmitter {
76
76
  // Accumulate text across streaming deltas for each turn
77
77
  this._accumulatedText = '';
78
78
  this._inMessage = false;
79
+ // OMP pause tracking (see _handleAgentEnd). _continuing: a non-terminal
80
+ // agent_end arrived and the run's terminal agent_end has not, so the agent
81
+ // still owns the turn. _paused: the part of that window before the resumed
82
+ // run's agent_start, while OMP has no agent loop running.
83
+ this._continuing = false;
84
+ this._paused = false;
79
85
  // Pending callbacks for RPC responses keyed by command type
80
86
  this._pendingCallbacks = new Map();
81
87
  }
@@ -133,11 +139,18 @@ class PiBridge extends EventEmitter {
133
139
 
134
140
  if (!this._closing) {
135
141
  logger.warn(`[${this.logName}] Process exited unexpectedly (code=${code}, signal=${signal})`);
142
+ // A paused run's reply up to the pause is finished text that OMP
143
+ // reported with an agent_end; save it rather than lose it with the
144
+ // process. No terminal agent_end can follow now.
145
+ if (this._continuing) this._handleAgentEnd({});
136
146
  this.emit('error', { error: new Error(`${this.cliName} process exited (code=${code}, signal=${signal})`) });
137
147
  } else {
138
148
  logger.info(`[${this.logName}] Process exited (code=${code}, signal=${signal})`);
139
149
  }
140
150
 
151
+ this._inMessage = false;
152
+ this._continuing = false;
153
+ this._paused = false;
141
154
  this.emit('close');
142
155
  });
143
156
 
@@ -206,6 +219,14 @@ class PiBridge extends EventEmitter {
206
219
  const command = JSON.stringify({ type: 'abort' });
207
220
  logger.debug(`[${this.logName}] Sending abort`);
208
221
  this._write(command);
222
+ // OMP answers an abort during a pause with no agent_end: no agent loop is
223
+ // running for it to stop. End the paused run here so its reply so far is
224
+ // saved and 'complete' fires. Once the run has resumed (agent_start), OMP
225
+ // ends the aborted loop with its own terminal agent_end instead.
226
+ if (this._paused) {
227
+ logger.debug(`[${this.logName}] Abort during a pause; ending the run`);
228
+ this._handleAgentEnd({});
229
+ }
209
230
  }
210
231
 
211
232
  /**
@@ -216,6 +237,10 @@ class PiBridge extends EventEmitter {
216
237
  if (!this._process) return;
217
238
 
218
239
  this._closing = true;
240
+ // Emit the paused reply while the session manager is still listening,
241
+ // so its complete handler saves it to chat_messages. The process close
242
+ // event cannot: listeners are gone by then, and _closing skips it.
243
+ if (this._continuing) this._handleAgentEnd({});
219
244
  this.removeAllListeners();
220
245
 
221
246
  // Try to abort any in-flight work first
@@ -262,11 +287,14 @@ class PiBridge extends EventEmitter {
262
287
  }
263
288
 
264
289
  /**
265
- * Check if the bridge is currently processing a message.
290
+ * Check if the bridge is currently processing a message. A run paused by a
291
+ * non-terminal agent_end stays busy until its terminal agent_end: a prompt
292
+ * sent in the gap would start a new turn and drop the reply accumulated so
293
+ * far, which has not been saved yet.
266
294
  * @returns {boolean}
267
295
  */
268
296
  isBusy() {
269
- return this._inMessage;
297
+ return this._inMessage || this._continuing;
270
298
  }
271
299
 
272
300
  // ---------------------------------------------------------------------------
@@ -462,6 +490,10 @@ class PiBridge extends EventEmitter {
462
490
  callback(event);
463
491
  } else if (!event.success) {
464
492
  logger.error(`[${this.logName}] Command failed: ${event.error}`);
493
+ // OMP reports a failed prompt after the run's last agent_end. If
494
+ // that was a pause, nothing may resume it, and a run left paused
495
+ // keeps the bridge busy for good.
496
+ if (event.command === 'prompt' && this._paused) this._handleAgentEnd({});
465
497
  this.emit('error', { error: new Error(event.error || 'Unknown command error') });
466
498
  } else {
467
499
  logger.debug(`[${this.logName}] Command acknowledged: ${JSON.stringify(event).substring(0, 200)}`);
@@ -469,6 +501,11 @@ class PiBridge extends EventEmitter {
469
501
  break;
470
502
 
471
503
  case 'agent_start':
504
+ // A paused OMP run resumes in a new agent loop (see _handleAgentEnd)
505
+ this._paused = false;
506
+ logger.debug(`[${this.logName}] ${type}`);
507
+ this.emit('status', { status: 'working' });
508
+ break;
472
509
  case 'turn_start':
473
510
  logger.debug(`[${this.logName}] ${type}`);
474
511
  this.emit('status', { status: 'working' });
@@ -486,10 +523,20 @@ class PiBridge extends EventEmitter {
486
523
  break;
487
524
 
488
525
  default:
489
- logger.debug(`[${this.logName}] Unhandled event type: ${type}`);
526
+ this._handleOtherEvent(event);
490
527
  }
491
528
  }
492
529
 
530
+ /**
531
+ * Handle an event type the shared switch in _handleLine does not recognize.
532
+ * Subclasses override this for CLI-specific events (see OmpBridge) and fall
533
+ * back to super for anything they do not recognize either.
534
+ * @param {Object} event - The parsed event
535
+ */
536
+ _handleOtherEvent(event) {
537
+ logger.debug(`[${this.logName}] Unhandled event type: ${event.type}`);
538
+ }
539
+
493
540
  /**
494
541
  * Handle a message_update event containing streaming content deltas.
495
542
  * @param {Object} event - The message_update event
@@ -547,12 +594,32 @@ class PiBridge extends EventEmitter {
547
594
  /**
548
595
  * Handle agent_end event which signals the completion of the agent's work.
549
596
  * Emits 'complete' with the full accumulated text.
550
- * @param {Object} _event - The agent_end event
597
+ *
598
+ * OMP marks a scheduling pause with `isTerminal: false` — an async job
599
+ * result, a queued advisor steer, or a compaction/retry continuation will
600
+ * resume the loop, and a terminal agent_end follows. Completing on the pause
601
+ * would persist a truncated reply and finalize the chat UI while the agent
602
+ * keeps working, so keep accumulating instead. Pi never sets the field, so
603
+ * every Pi agent_end is terminal.
604
+ *
605
+ * The pause stays open (isBusy) until the terminal agent_end, or until
606
+ * abort(), a failed prompt, close(), or process exit ends it through this
607
+ * method.
608
+ * @param {Object} event - The agent_end event
551
609
  */
552
- _handleAgentEnd(_event) {
610
+ _handleAgentEnd(event) {
611
+ if (event?.isTerminal === false) {
612
+ this._continuing = true;
613
+ this._paused = true;
614
+ logger.debug(`[${this.logName}] Non-terminal agent_end; waiting for the agent to resume`);
615
+ return;
616
+ }
617
+
553
618
  const fullText = this._accumulatedText;
554
619
  this._accumulatedText = '';
555
620
  this._inMessage = false;
621
+ this._continuing = false;
622
+ this._paused = false;
556
623
 
557
624
  logger.debug(`[${this.logName}] Agent ended, accumulated ${fullText.length} chars`);
558
625
  this.emit('complete', { fullText });
@@ -33,6 +33,9 @@ const CHAT_TOOLS = 'read,bash,grep,find,ls';
33
33
  // comment block in src/ai/omp-provider.js for detail.
34
34
  const OMP_CHAT_TOOLS = 'read,bash,grep,glob,task';
35
35
 
36
+ /** Error code sendMessage() sets when the agent still owns the previous turn. */
37
+ const SESSION_BUSY = 'SESSION_BUSY';
38
+
36
39
  class ChatSessionManager {
37
40
  /**
38
41
  * @param {Database} db - better-sqlite3 database instance
@@ -165,7 +168,10 @@ class ChatSessionManager {
165
168
  }
166
169
 
167
170
  if (session.bridge.isBusy()) {
168
- throw new Error(`Session ${sessionId} is currently processing a message`);
171
+ // Checked before the message is stored, so a rejected send leaves no trace.
172
+ const busy = new Error(`Session ${sessionId} is currently processing a message`);
173
+ busy.code = SESSION_BUSY;
174
+ throw busy;
169
175
  }
170
176
 
171
177
  // Build the message for the agent: initialContext > context > userMessage
@@ -844,3 +850,4 @@ class ChatSessionManager {
844
850
  }
845
851
 
846
852
  module.exports = ChatSessionManager;
853
+ module.exports.SESSION_BUSY = SESSION_BUSY;
package/src/main.js CHANGED
@@ -231,9 +231,8 @@ OPTIONS:
231
231
  Available models: opus, sonnet, haiku (Claude Code);
232
232
  also: fable-5.1-xhigh, fable-5.1-high,
233
233
  fable-5-xhigh, fable-5-high, opus-5.5-xhigh,
234
- opus-5.5-high, opus-5-xhigh, opus-5-high,
235
- opus-4.8-xhigh, opus-4.8-high, opus-4.7-xhigh,
236
- opus-4.7-high, opus-4.6-high, opus-4.6-1m,
234
+ opus-5.5-high, opus-5.5-medium, opus-5.5-low,
235
+ opus-5-xhigh, opus-5-high,
237
236
  sonnet-5-xhigh, sonnet-5-high, sonnet-4.6
238
237
  (default is opus-5.5-high; opus is Opus 5.5 XHigh;
239
238
  a saved default_model wins over the default)
@@ -23,6 +23,7 @@ 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
27
  const { resolveLoadSkills } = require('../config');
27
28
 
28
29
  /**
@@ -511,6 +512,15 @@ router.post('/api/chat/session/:id/message', async (req, res) => {
511
512
  logger.debug(`[ChatRoute] Message stored as ID ${result.id}, awaiting agent response via WebSocket`);
512
513
  res.json({ data: { messageId: result.id } });
513
514
  } catch (error) {
515
+ if (error.code === SESSION_BUSY) {
516
+ // The agent still owns its previous turn — e.g. an OMP run paused on a
517
+ // background job, seen from a page reloaded mid-reply. The message was
518
+ // not stored, so the client can send it again once the reply finishes.
519
+ logger.warn(`Chat message rejected: ${error.message}`);
520
+ return res.status(409).json({
521
+ error: 'The agent is still working on its previous reply. Wait for it to finish, then send your message again.'
522
+ });
523
+ }
514
524
  logger.error(`Error sending chat message: ${error.message}`);
515
525
  res.status(500).json({ error: 'Failed to send message' });
516
526
  }