@in-the-loop-labs/pair-review 5.2.3 → 5.3.1

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.
Files changed (49) hide show
  1. package/README.md +11 -3
  2. package/package.json +1 -1
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-code-critic/skills/analyze/references/level1-thorough.md +52 -121
  6. package/plugin-code-critic/skills/analyze/references/level2-thorough.md +49 -113
  7. package/plugin-code-critic/skills/analyze/references/level3-thorough.md +46 -195
  8. package/plugin-code-critic/skills/analyze/references/orchestration-thorough.md +56 -112
  9. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  10. package/public/css/analysis-config.css +29 -0
  11. package/public/css/pr.css +208 -0
  12. package/public/js/components/AIPanel.js +14 -9
  13. package/public/js/components/ChatPanel.js +790 -54
  14. package/public/js/components/ConfirmDialog.js +70 -2
  15. package/public/js/modules/pierre-bridge.js +58 -97
  16. package/public/js/modules/suggestion-manager.js +9 -121
  17. package/public/js/pr.js +15 -28
  18. package/public/js/utils/scroll-into-view.js +18 -4
  19. package/src/ai/analyzer.js +30 -5
  20. package/src/ai/antigravity-provider.js +7 -6
  21. package/src/ai/claude-provider.js +4 -8
  22. package/src/ai/codex-provider.js +3 -4
  23. package/src/ai/index.js +2 -0
  24. package/src/ai/muse-provider.js +3 -4
  25. package/src/ai/omp-provider.js +27 -12
  26. package/src/ai/pi-provider.js +12 -6
  27. package/src/ai/prompts/baseline/consolidation/thorough.js +56 -43
  28. package/src/ai/prompts/baseline/level1/thorough.js +76 -138
  29. package/src/ai/prompts/baseline/level2/thorough.js +76 -129
  30. package/src/ai/prompts/baseline/level3/thorough.js +67 -212
  31. package/src/ai/prompts/baseline/orchestration/thorough.js +79 -130
  32. package/src/ai/prompts/render-for-skill.js +5 -0
  33. package/src/ai/prompts/shared/adversarial-verification.js +68 -0
  34. package/src/ai/provider.js +60 -1
  35. package/src/ai/stream-parser.js +22 -1
  36. package/src/chat/acp-bridge.js +11 -0
  37. package/src/chat/chat-models.js +348 -0
  38. package/src/chat/chat-providers.js +17 -0
  39. package/src/chat/claude-code-bridge.js +9 -0
  40. package/src/chat/codex-bridge.js +6 -1
  41. package/src/chat/omp-bridge.js +5 -0
  42. package/src/chat/pi-bridge.js +20 -5
  43. package/src/chat/session-manager.js +158 -63
  44. package/src/config.js +92 -5
  45. package/src/git/worktree.js +29 -10
  46. package/src/github/client.js +30 -10
  47. package/src/hooks/payloads.js +5 -1
  48. package/src/routes/chat.js +83 -11
  49. package/src/setup/pr-setup.js +54 -1
@@ -10,6 +10,26 @@ const DISMISS_ICON = `<svg viewBox="0 0 16 16" fill="currentColor" width="12" he
10
10
  /** Pixel threshold for considering the user "near the bottom" of the messages container. */
11
11
  const NEAR_BOTTOM_THRESHOLD = 80;
12
12
 
13
+ /**
14
+ * localStorage key recording that the user has seen (and dismissed) the
15
+ * "a conversation keeps one model" explainer. Per-browser convenience only —
16
+ * losing it just means the dialog is shown once more.
17
+ */
18
+ const MODEL_SWITCH_ACK_KEY = 'pair-review:chat-model-switch-ack';
19
+
20
+ /**
21
+ * localStorage key prefix for the last model the user picked for a chat
22
+ * provider. One key per provider id (`pair-review:chat-model:claude`), holding
23
+ * the canonical catalog id. Deliberately NOT scoped by reviewId: this is a
24
+ * preference ("I work in Sonnet"), not session state. Absent means "provider
25
+ * default", which is also what an explicit pick of the default row writes
26
+ * (by removing the key).
27
+ */
28
+ const LAST_MODEL_KEY_PREFIX = 'pair-review:chat-model:';
29
+
30
+ /** Checkmark used by both the provider and model dropdown rows. */
31
+ const DROPDOWN_CHECK_ICON = `<svg class="chat-panel__model-check" viewBox="0 0 16 16" fill="currentColor" width="12" height="12"><path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"/></svg>`;
32
+
13
33
  const LOOP_SPINNER_HTML = `<span class="chat-panel__loop-spinner"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" width="20" height="20"><path transform="rotate(-50 12 12)" d="M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.133-8-12.356-8-5.096 0-5.096 8 0 8 5.223 0 7.26-8 12.356-8z"/></svg></span>`;
14
34
  const DOTS_SPINNER_HTML = '<span class="chat-panel__typing-indicator"><span></span><span></span><span></span></span>';
15
35
 
@@ -65,6 +85,25 @@ class ChatPanel {
65
85
  this._chatProviders = window.__pairReview?.chatProviders || [];
66
86
  this._enterToSend = window.__pairReview?.chatEnterToSend ?? true;
67
87
 
88
+ /**
89
+ * providerId -> { models, configuredModel, hasCatalog }, populated by
90
+ * _ensureChatCatalog. Empty until the first successful fetch; every reader
91
+ * degrades to "Provider default only".
92
+ * @type {Map<string, {models: Array<Object>, configuredModel: string|null, hasCatalog: boolean}>}
93
+ */
94
+ this._chatCatalog = new Map();
95
+ /** In-flight/settled catalog fetch, so open() + the dropdown share one request. */
96
+ this._chatCatalogPromise = null;
97
+
98
+ /**
99
+ * Generation counters for the two dropdowns that await before showing themselves.
100
+ * Bumped by every show AND every hide, so an open that was superseded (a second
101
+ * open, or a hide that landed while the fetch was in flight) can tell it is stale
102
+ * and leave the DOM alone instead of un-hiding itself.
103
+ */
104
+ this._modelDropdownOpenToken = 0;
105
+ this._sessionDropdownOpenToken = 0;
106
+
68
107
  /** @type {ChatTab[]} Open tabs, in display order (left to right). */
69
108
  this.tabs = [];
70
109
  /** @type {number|null} Sentinel ID of the active tab; matches sessionId once saved. */
@@ -671,14 +710,30 @@ class ChatPanel {
671
710
  * - Appends it to the strip and focuses it.
672
711
  * - Surfaces analysis context (when one is available locally) so the user
673
712
  * sees the card before they ever type a message.
713
+ * @param {Object} [init]
714
+ * @param {string} [init.provider] - Provider for the new tab (defaults to the active one)
715
+ * @param {string|null} [init.model] - Model selector for the new tab. OMIT the key
716
+ * to start from the provider's remembered model; pass `null` explicitly to
717
+ * force the provider default.
674
718
  * @returns {Promise<void>}
675
719
  */
676
- async _openNewTab() {
720
+ async _openNewTab(init = {}) {
677
721
  if (!this.reviewId) {
678
722
  console.warn('[ChatPanel] _openNewTab: no reviewId yet');
679
723
  return;
680
724
  }
681
- const tab = this._createTab({ provider: this._activeProvider });
725
+ const providerId = init.provider || this._activeProvider;
726
+ // `undefined` = the caller has no opinion, so the provider's remembered
727
+ // model seeds the tab. An explicit `null` (the "Provider default" row, and
728
+ // the provider picker's new-tab path) is an opinion and must not be
729
+ // overridden.
730
+ const model = init.model !== undefined
731
+ ? (init.model ?? null)
732
+ : await this._seedModelFor(providerId);
733
+ const tab = this._createTab({
734
+ provider: providerId,
735
+ model,
736
+ });
682
737
  this._appendTab(tab, { focus: true });
683
738
  // No session yet, so _showAnalysisContextIfPresent gets a null sessionData.
684
739
  // We still want the auto-detected analysis card surfaced on the fresh tab
@@ -688,6 +743,61 @@ class ChatPanel {
688
743
  if (this.isOpen) this.inputEl?.focus();
689
744
  }
690
745
 
746
+ /**
747
+ * Build the POST /api/chat/session request body for a tab. Single source of
748
+ * truth for BOTH creation paths (_createSessionForTab and the legacy public
749
+ * createSession) so a field cannot be added to one and forgotten in the
750
+ * other. Purely synchronous — callers that capture state before an await
751
+ * must call this before awaiting.
752
+ *
753
+ * @param {ChatTab|null} tab
754
+ * @returns {Object} Request body ({ provider, reviewId, model, skipAnalysisContext? })
755
+ */
756
+ _sessionRequestBody(tab) {
757
+ const body = {
758
+ provider: tab?.provider || this._activeProvider,
759
+ reviewId: this.reviewId,
760
+ // null means "provider default" — the backend resolves it from config.
761
+ model: tab?.model ?? null,
762
+ };
763
+ if (tab?.analysisContextRemoved) body.skipAnalysisContext = true;
764
+ return body;
765
+ }
766
+
767
+ /**
768
+ * Adopt the model the server actually bound the session to.
769
+ *
770
+ * A tab that asked for "Provider default" (null) can come back pinned to a
771
+ * concrete canonical id — the backend resolves `chat_providers.<id>.model`
772
+ * when the request carries none. The header must show that id, otherwise
773
+ * re-picking the very same model from the dropdown looks like a change and
774
+ * fires the switch dialog for nothing.
775
+ *
776
+ * Shared by BOTH creation paths (_createSessionForTab and the legacy public
777
+ * createSession) so they cannot drift. Callers MUST invoke this only after
778
+ * their in-flight identity guards have passed — adopting a model onto a tab
779
+ * whose session is about to be DELETEd would write the abandoned session's
780
+ * model onto the tab.
781
+ *
782
+ * @param {ChatTab} tab
783
+ * @param {Object} sessionData - `data` from POST /api/chat/session
784
+ */
785
+ _adoptServerModel(tab, sessionData) {
786
+ if (!tab || !sessionData) return;
787
+ // Absent field (older server, or a response that does not report it) means
788
+ // "no opinion" — keep what the tab already has.
789
+ if (sessionData.model === undefined || sessionData.model === null) return;
790
+ if ((tab.model ?? null) === sessionData.model) return;
791
+ tab.model = sessionData.model;
792
+ // Both call sites run us between assigning tab.sessionId and re-keying
793
+ // activeTabKey off tab._localKey, so _getActiveTab() cannot find the tab
794
+ // yet. Accept either key. _localKey counts down from 0 while session ids
795
+ // are positive, so the two spaces never collide across tabs.
796
+ const isActive = this.activeTabKey === tab.sessionId
797
+ || this.activeTabKey === tab._localKey;
798
+ if (isActive) this._updateTitle(tab.provider, tab.model);
799
+ }
800
+
691
801
  /**
692
802
  * Create a backend chat session bound to a specific tab. Subscribes the tab
693
803
  * to its session's WebSocket topic and updates the tab's sessionId.
@@ -697,16 +807,16 @@ class ChatPanel {
697
807
  async _createSessionForTab(tab) {
698
808
  if (!this.reviewId) return null;
699
809
  if (!tab) return null;
700
- // Capture the provider at entry. If the user swaps providers on this tab
701
- // while the POST is in flight, the response describes a session for the
702
- // wrong provider — we must abandon it and let the next send (with the new
703
- // provider) start fresh.
810
+ // Capture the provider AND model at entry. If the user swaps either on this
811
+ // tab while the POST is in flight, the response describes a session for the
812
+ // wrong provider/model — we must abandon it and let the next send (with the
813
+ // new selection) start fresh.
704
814
  const capturedProvider = tab.provider;
815
+ const capturedModel = tab.model ?? null;
705
816
  const isAcp = this._getProviderType(capturedProvider) === 'acp';
706
817
  if (isAcp) this._showStatusFlash('Starting Agent Client Protocol');
707
818
  try {
708
- const body = { provider: capturedProvider, reviewId: this.reviewId };
709
- if (tab.analysisContextRemoved) body.skipAnalysisContext = true;
819
+ const body = this._sessionRequestBody(tab);
710
820
  const response = await fetch('/api/chat/session', {
711
821
  method: 'POST',
712
822
  headers: { 'Content-Type': 'application/json' },
@@ -732,7 +842,14 @@ class ChatPanel {
732
842
  fetch(`/api/chat/session/${result.data.id}`, { method: 'DELETE' }).catch(() => {});
733
843
  return null;
734
844
  }
845
+ // Same treatment for the model: the DB row was created with
846
+ // capturedModel, so a late DELETE is the only correct cleanup.
847
+ if ((tab.model ?? null) !== capturedModel) {
848
+ fetch(`/api/chat/session/${result.data.id}`, { method: 'DELETE' }).catch(() => {});
849
+ return null;
850
+ }
735
851
  tab.sessionId = result.data.id;
852
+ this._adoptServerModel(tab, result.data);
736
853
  tab.sessionWarm = true;
737
854
  if (tab.messagesEl) tab.messagesEl.dataset.tabKey = String(tab.sessionId);
738
855
  // Re-key the active marker if this is the focused tab (so getters work)
@@ -790,6 +907,15 @@ class ChatPanel {
790
907
  </button>
791
908
  <div class="chat-panel__provider-dropdown" style="display: none;"></div>
792
909
  </div>
910
+ <div class="chat-panel__model-picker">
911
+ <button class="chat-panel__model-picker-btn" title="Model for this conversation">
912
+ <span class="chat-panel__model-text">Default</span>
913
+ <svg class="chat-panel__model-chevron" viewBox="0 0 16 16" fill="currentColor" width="10" height="10">
914
+ <path d="M4.427 7.427l3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"/>
915
+ </svg>
916
+ </button>
917
+ <div class="chat-panel__model-dropdown" style="display: none;"></div>
918
+ </div>
793
919
  <div class="chat-panel__session-picker">
794
920
  <div class="chat-panel__session-dropdown" style="display: none;"></div>
795
921
  </div>
@@ -913,6 +1039,10 @@ class ChatPanel {
913
1039
  this.providerPickerEl = this.container.querySelector('.chat-panel__provider-picker');
914
1040
  this.providerPickerBtn = this.container.querySelector('.chat-panel__provider-picker-btn');
915
1041
  this.providerDropdown = this.container.querySelector('.chat-panel__provider-dropdown');
1042
+ this.modelPickerEl = this.container.querySelector('.chat-panel__model-picker');
1043
+ this.modelPickerBtn = this.container.querySelector('.chat-panel__model-picker-btn');
1044
+ this.modelDropdown = this.container.querySelector('.chat-panel__model-dropdown');
1045
+ this.modelTextEl = this.container.querySelector('.chat-panel__model-text');
916
1046
  this.sessionPickerEl = this.container.querySelector('.chat-panel__session-picker');
917
1047
  this.sessionDropdown = this.container.querySelector('.chat-panel__session-dropdown');
918
1048
  this.historyBtn = this.container.querySelector('.chat-panel__history-btn');
@@ -937,6 +1067,9 @@ class ChatPanel {
937
1067
  // Provider picker button
938
1068
  this.providerPickerBtn.addEventListener('click', () => this._toggleProviderDropdown());
939
1069
 
1070
+ // Model picker button
1071
+ this.modelPickerBtn?.addEventListener('click', () => this._toggleModelDropdown());
1072
+
940
1073
  // Session history button
941
1074
  this.historyBtn.addEventListener('click', () => this._toggleSessionDropdown());
942
1075
 
@@ -997,14 +1130,27 @@ class ChatPanel {
997
1130
  // Escape: close dropdown if open, stop agent if streaming, blur textarea if focused, otherwise close panel
998
1131
  this._onKeydown = (e) => {
999
1132
  if (e.key === 'Escape' && this.isOpen) {
1000
- // Escape ladder (first match wins): save-snippet pill → provider
1001
- // dropdown → session dropdown → snippet dropdown → stop streaming →
1002
- // blur input → close panel. The pill goes first so dismissing it
1003
- // never falls through to closing the panel.
1133
+ // Escape ladder (first match wins): confirm dialog → save-snippet pill
1134
+ // → provider dropdown → model dropdown → session dropdown → snippet
1135
+ // dropdown → stop streaming → blur input → close panel. The pill goes
1136
+ // first among our own rungs so dismissing it never falls through to
1137
+ // closing the panel.
1138
+ //
1139
+ // ConfirmDialog's own Escape handler is a bubble-phase document
1140
+ // listener that cancels without stopPropagation, so its Escape reaches
1141
+ // us too. The model-switch dialog is opened *after* the model dropdown
1142
+ // is hidden, meaning every dropdown rung is false and Escape would fall
1143
+ // through to _stopAgent()/close() on exactly the tabs routed into that
1144
+ // dialog. Yield while any confirm dialog is up. (Repo pattern:
1145
+ // SnippetManager.js, TextInputDialog.js.)
1146
+ if (window.confirmDialog?.isVisible) return;
1147
+
1004
1148
  if (this._saveSnippetPill) {
1005
1149
  this._hideSaveSnippetPill();
1006
1150
  } else if (this._isProviderDropdownOpen()) {
1007
1151
  this._hideProviderDropdown();
1152
+ } else if (this._isModelDropdownOpen()) {
1153
+ this._hideModelDropdown();
1008
1154
  } else if (this._isSessionDropdownOpen()) {
1009
1155
  this._hideSessionDropdown();
1010
1156
  } else if (this._isSnippetDropdownOpen()) {
@@ -1149,19 +1295,209 @@ class ChatPanel {
1149
1295
  }
1150
1296
 
1151
1297
  /**
1152
- * Update the chat panel title with provider and model info.
1298
+ * Update the chat panel header: provider text on the provider button, model
1299
+ * label on the model button. The model is deliberately NOT appended to the
1300
+ * provider text any more \u2014 it has its own picker.
1301
+ *
1153
1302
  * @param {string} [providerId] - Provider ID (looked up in _chatProviders for display name)
1154
- * @param {string} [model] - Model ID or display name (e.g. 'default', 'multi-model')
1303
+ * @param {string|null} [model] - Model selector for this conversation. Omit the
1304
+ * argument entirely to keep showing the active tab's model; pass `null`
1305
+ * explicitly to render "Default".
1155
1306
  */
1156
1307
  _updateTitle(providerId, model) {
1157
- if (!this.titleTextEl) return;
1158
- const providerName = this._getProviderDisplayName(providerId || this._activeProvider);
1159
- const modelDisplay = model
1160
- ? model.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')
1161
- : null;
1162
- const parts = ['Chat', providerName];
1163
- if (modelDisplay) parts.push(modelDisplay);
1164
- this.titleTextEl.textContent = parts.join(' \u00b7 ');
1308
+ const resolvedProvider = providerId || this._activeProvider;
1309
+ if (this.titleTextEl) {
1310
+ const providerName = this._getProviderDisplayName(resolvedProvider);
1311
+ this.titleTextEl.textContent = `Chat \u00b7 ${providerName}`;
1312
+ }
1313
+ if (this.modelTextEl) {
1314
+ const resolvedModel = model !== undefined
1315
+ ? model
1316
+ : (this._getActiveTab()?.model ?? null);
1317
+ this.modelTextEl.textContent = this._getModelDisplayName(resolvedProvider, resolvedModel);
1318
+ }
1319
+ }
1320
+
1321
+ // \u2500\u2500 Chat model catalog \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1322
+
1323
+ /**
1324
+ * Fetch the chat model catalog (`GET /api/chat/providers`) at most once per
1325
+ * panel lifetime, caching the promise so open() and the model dropdown share
1326
+ * one request. Failure degrades gracefully: the map stays empty, every model
1327
+ * label falls back to a prettified id and the dropdown shows only the
1328
+ * "Provider default" row. The cached promise is dropped on failure so a
1329
+ * later open/dropdown can retry.
1330
+ *
1331
+ * @returns {Promise<Map<string, Object>>} providerId -> catalog entry
1332
+ */
1333
+ _ensureChatCatalog() {
1334
+ if (this._chatCatalogPromise) return this._chatCatalogPromise;
1335
+
1336
+ this._chatCatalogPromise = (async () => {
1337
+ try {
1338
+ const response = await fetch('/api/chat/providers');
1339
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1340
+ const result = await response.json();
1341
+ const providers = Array.isArray(result?.data?.providers) ? result.data.providers : [];
1342
+ const map = new Map();
1343
+ for (const p of providers) {
1344
+ if (!p || !p.id) continue;
1345
+ map.set(p.id, {
1346
+ models: Array.isArray(p.models) ? p.models : [],
1347
+ configuredModel: p.configuredModel ?? null,
1348
+ hasCatalog: !!p.hasCatalog,
1349
+ });
1350
+ }
1351
+ this._chatCatalog = map;
1352
+ return map;
1353
+ } catch (err) {
1354
+ console.warn('[ChatPanel] Failed to load chat model catalog:', err);
1355
+ // Drop the cached promise so the next open/dropdown retries.
1356
+ this._chatCatalogPromise = null;
1357
+ return this._chatCatalog;
1358
+ }
1359
+ })();
1360
+
1361
+ return this._chatCatalogPromise;
1362
+ }
1363
+
1364
+ /**
1365
+ * Catalog entry for a provider, or null when the catalog has not loaded (or
1366
+ * the provider has none).
1367
+ * @param {string} [providerId]
1368
+ * @returns {{models: Array<Object>, configuredModel: string|null, hasCatalog: boolean}|null}
1369
+ */
1370
+ _getCatalogEntry(providerId) {
1371
+ const id = providerId || this._activeProvider;
1372
+ return this._chatCatalog?.get(id) || null;
1373
+ }
1374
+
1375
+ /**
1376
+ * Title-case a raw model id so an uncatalogued selector still reads as a name.
1377
+ * @param {string} modelId
1378
+ * @returns {string}
1379
+ */
1380
+ _prettifyModelId(modelId) {
1381
+ return String(modelId)
1382
+ .split('-')
1383
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))
1384
+ .join(' ');
1385
+ }
1386
+
1387
+ /**
1388
+ * Display label for a model selector: the catalog name when known, a
1389
+ * prettified id when not, "Default" for the provider default (null).
1390
+ * @param {string} providerId
1391
+ * @param {string|null} modelId
1392
+ * @returns {string}
1393
+ */
1394
+ _getModelDisplayName(providerId, modelId) {
1395
+ if (!modelId) return 'Default';
1396
+ const entry = this._getCatalogEntry(providerId);
1397
+ const match = entry?.models?.find(m => m && m.id === modelId);
1398
+ if (match?.name) return match.name;
1399
+ return this._prettifyModelId(modelId);
1400
+ }
1401
+
1402
+ // ── Remembered model per provider ──────────────────────────────────────
1403
+ //
1404
+ // The last model the user PICKED for a provider is remembered per browser and
1405
+ // seeds every new tab on that provider. Only explicit picks write (see
1406
+ // _selectModel); restore, MRU and server-adoption paths never do — they
1407
+ // describe a session that already exists, not a preference.
1408
+
1409
+ /**
1410
+ * Raw remembered selector for a provider, straight out of storage. No catalog
1411
+ * validation. A throwing/absent storage reads as "nothing remembered".
1412
+ * @param {string} providerId
1413
+ * @returns {string|null}
1414
+ */
1415
+ _readRememberedModel(providerId) {
1416
+ if (!providerId) return null;
1417
+ try {
1418
+ const raw = window.localStorage?.getItem(LAST_MODEL_KEY_PREFIX + providerId);
1419
+ return raw || null;
1420
+ } catch {
1421
+ return null;
1422
+ }
1423
+ }
1424
+
1425
+ /**
1426
+ * Persist (or clear) the remembered model for a provider. `null` REMOVES the
1427
+ * key: choosing "Provider default" is an explicit choice and must stick, so a
1428
+ * previously remembered id cannot come back on the next tab.
1429
+ * @param {string} providerId
1430
+ * @param {string|null} modelId
1431
+ */
1432
+ _rememberModel(providerId, modelId) {
1433
+ if (!providerId) return;
1434
+ const key = LAST_MODEL_KEY_PREFIX + providerId;
1435
+ try {
1436
+ if (modelId) {
1437
+ window.localStorage?.setItem(key, modelId);
1438
+ } else {
1439
+ window.localStorage?.removeItem(key);
1440
+ }
1441
+ } catch { /* per-browser convenience only; a throwing storage just forgets */ }
1442
+ }
1443
+
1444
+ /** Drop a remembered selector that no longer names anything. */
1445
+ _forgetRememberedModel(providerId) {
1446
+ try {
1447
+ window.localStorage?.removeItem(LAST_MODEL_KEY_PREFIX + providerId);
1448
+ } catch { /* noop */ }
1449
+ }
1450
+
1451
+ /**
1452
+ * Remembered model for a provider, validated against the catalog that is
1453
+ * loaded RIGHT NOW. Synchronous — callers that can afford to wait for a cold
1454
+ * catalog should use _seedModelFor instead.
1455
+ *
1456
+ * Validation rules:
1457
+ * - provider has a catalog entry and it lists the id → honour it
1458
+ * - provider has a catalog entry and it does NOT → stale: forget it
1459
+ * - no entry at all (catalog not loaded, or an unknown/unavailable
1460
+ * provider) → honour optimistically
1461
+ *
1462
+ * The optimistic branch matters: it is the only reason a seeded label can
1463
+ * appear before /api/chat/providers answers, and the id came from a pick the
1464
+ * user made against this very catalog, so it is almost always still valid.
1465
+ *
1466
+ * @param {string} providerId
1467
+ * @returns {string|null}
1468
+ */
1469
+ _rememberedModelFor(providerId) {
1470
+ const raw = this._readRememberedModel(providerId);
1471
+ if (!raw) return null;
1472
+ const entry = this._getCatalogEntry(providerId);
1473
+ if (!entry) return raw;
1474
+ const models = Array.isArray(entry.models) ? entry.models : [];
1475
+ if (models.some(m => m && m.id === raw)) return raw;
1476
+ // The catalog answered and does not know this id (config change, provider
1477
+ // upgrade, disabled_models). Seeding it would spawn a session on a model
1478
+ // the CLI rejects.
1479
+ this._forgetRememberedModel(providerId);
1480
+ return null;
1481
+ }
1482
+
1483
+ /**
1484
+ * Remembered model for a provider, waiting for the catalog when it has not
1485
+ * arrived yet. Used by _openNewTab, the one seeding path that can afford an
1486
+ * await: its callers already await it, and open() warms the catalog on every
1487
+ * panel open, so in practice the map is populated and this adds no await at
1488
+ * all. A cold panel joins the in-flight request rather than issuing a new one.
1489
+ *
1490
+ * @param {string} providerId
1491
+ * @returns {Promise<string|null>}
1492
+ */
1493
+ async _seedModelFor(providerId) {
1494
+ if (!this._readRememberedModel(providerId)) return null;
1495
+ if (!this._chatCatalog?.has(providerId)) {
1496
+ try {
1497
+ await this._ensureChatCatalog();
1498
+ } catch { /* _ensureChatCatalog already degrades; fall through to optimistic */ }
1499
+ }
1500
+ return this._rememberedModelFor(providerId);
1165
1501
  }
1166
1502
 
1167
1503
  /**
@@ -1305,6 +1641,14 @@ class ChatPanel {
1305
1641
  this.panel.classList.remove('chat-panel--closed');
1306
1642
  this.panel.classList.add('chat-panel--open');
1307
1643
 
1644
+ // Warm the model catalog so the header can show real model names. Never
1645
+ // blocks the open; the header is re-rendered if/when it lands.
1646
+ this._ensureChatCatalog().then(() => {
1647
+ if (!this.isOpen) return;
1648
+ const active = this._getActiveTab();
1649
+ this._updateTitle(active?.provider, active?.model ?? null);
1650
+ }).catch(() => { /* _ensureChatCatalog already degrades */ });
1651
+
1308
1652
  // Ensure review-scope subscription is active. Per-tab subscriptions are
1309
1653
  // attached as tabs are created/restored.
1310
1654
  this._ensureSubscriptions();
@@ -1335,7 +1679,13 @@ class ChatPanel {
1335
1679
  }
1336
1680
  }
1337
1681
  if (!restored) {
1338
- const tab = this._createTab({ provider: this._activeProvider });
1682
+ // Seeded like any other fresh tab. If _loadMRUSession then adopts an
1683
+ // existing session it overwrites provider AND model from that row, so
1684
+ // the seed only survives when this really is a brand-new conversation.
1685
+ const tab = this._createTab({
1686
+ provider: this._activeProvider,
1687
+ model: this._rememberedModelFor(this._activeProvider),
1688
+ });
1339
1689
  this._appendTab(tab, { focus: true });
1340
1690
  if (!hasExplicitContext) {
1341
1691
  await this._loadMRUSession();
@@ -1420,6 +1770,7 @@ class ChatPanel {
1420
1770
  */
1421
1771
  close() {
1422
1772
  this._hideProviderDropdown();
1773
+ this._hideModelDropdown();
1423
1774
  this._hideSessionDropdown();
1424
1775
  this._hideSnippetDropdown();
1425
1776
  this._hideSaveSnippetPill();
@@ -1468,6 +1819,7 @@ class ChatPanel {
1468
1819
  */
1469
1820
  async _startNewConversation() {
1470
1821
  this._hideProviderDropdown();
1822
+ this._hideModelDropdown();
1471
1823
  this._hideSessionDropdown();
1472
1824
  this._hideSnippetDropdown();
1473
1825
  // Multi-chat replaces the legacy in-place reset with a fresh tab; the
@@ -1555,16 +1907,25 @@ class ChatPanel {
1555
1907
  this._persistOpenTabs();
1556
1908
  console.debug('[ChatPanel] Loaded MRU session:', mru.id, 'messages:', mru.message_count);
1557
1909
 
1910
+ // The adopted session's model is authoritative — unconditionally, even
1911
+ // for a row with no provider. The placeholder tab this runs on was seeded
1912
+ // with the provider's remembered model, and that seed describes a NEW
1913
+ // conversation; leaving it on a tab now bound to an existing session
1914
+ // would label the session with a model it never ran on.
1915
+ tab.model = mru.model ?? null;
1558
1916
  if (mru.provider) {
1559
1917
  tab.provider = mru.provider;
1560
- tab.model = mru.model;
1561
1918
  // Only update the global header/active provider when this tab is in the
1562
1919
  // foreground; otherwise a stale MRU load would yank the header out from
1563
1920
  // under the user's currently focused tab.
1564
1921
  if (this._getActiveTab() === tab) {
1565
1922
  this._activeProvider = mru.provider;
1566
- this._updateTitle(mru.provider, mru.model);
1923
+ this._updateTitle(mru.provider, tab.model);
1567
1924
  }
1925
+ } else if (this._getActiveTab() === tab) {
1926
+ // No provider on the row, but the model still changed out from under
1927
+ // the seeded label.
1928
+ this._updateTitle(tab.provider, tab.model);
1568
1929
  }
1569
1930
 
1570
1931
  // Title heuristic: prefer first user message preview if available
@@ -1740,7 +2101,8 @@ class ChatPanel {
1740
2101
 
1741
2102
  _showProviderDropdown() {
1742
2103
  if (!this.providerDropdown) return;
1743
- // Close session + snippet dropdowns if open
2104
+ // Close model + session + snippet dropdowns if open
2105
+ this._hideModelDropdown();
1744
2106
  this._hideSessionDropdown();
1745
2107
  this._hideSnippetDropdown();
1746
2108
 
@@ -1832,31 +2194,356 @@ class ChatPanel {
1832
2194
  async _selectProvider(id) {
1833
2195
  if (id === this._activeProvider) return;
1834
2196
  this._activeProvider = id;
1835
- this._updateTitle();
2197
+ // The model catalog belongs to the provider, so any open model dropdown is
2198
+ // now rendering a stale list.
2199
+ this._hideModelDropdown();
1836
2200
 
1837
2201
  const tab = this._getActiveTab();
1838
- const isFresh = tab
2202
+
2203
+ if (!this._isTabFresh(tab)) {
2204
+ // The new tab starts on the new provider at its default model, and
2205
+ // _openNewTab -> _activateTab renders exactly that. Set it here too so an
2206
+ // early bail (no reviewId) still leaves the header agreeing with
2207
+ // _activeProvider instead of showing the old tab's model under the new
2208
+ // provider name.
2209
+ this._updateTitle(id, null);
2210
+ await this._openNewTab();
2211
+ return;
2212
+ }
2213
+
2214
+ tab.provider = id;
2215
+ // A model selector only means something under its own provider's catalog,
2216
+ // so the old one is dropped. The NEW provider's remembered pick takes its
2217
+ // place — same starting point a brand-new tab on that provider would get.
2218
+ // Read synchronously (no await): this handler mutates the active tab in
2219
+ // place, and an await here would let the user swap tab/provider underneath
2220
+ // it. On a cold catalog the remembered id seeds optimistically.
2221
+ tab.model = this._rememberedModelFor(id);
2222
+ this._updateTitle(id, tab.model);
2223
+ this._discardEmptySession(tab);
2224
+ this._renderTabStrip();
2225
+ }
2226
+
2227
+ /**
2228
+ * Detach a fresh tab from a session that was already created for it: unbind the
2229
+ * WebSocket, clear the session id (re-keying the active marker so getter
2230
+ * delegation still finds the tab), and tell the server to drop the row.
2231
+ *
2232
+ * Only ever called for a tab that passed `_isTabFresh` — the session has no
2233
+ * messages, so the DELETE is a cleanup, not a data loss. Shared by the provider
2234
+ * picker and the model picker; the two used to carry byte-identical copies.
2235
+ *
2236
+ * @param {ChatTab} tab
2237
+ */
2238
+ _discardEmptySession(tab) {
2239
+ if (!tab) return;
2240
+ if (tab.wsUnsub) { try { tab.wsUnsub(); } catch { /* noop */ } tab.wsUnsub = null; }
2241
+ if (tab.sessionId == null) return;
2242
+ const staleId = tab.sessionId;
2243
+ tab.sessionId = null;
2244
+ tab.sessionWarm = false;
2245
+ // Restore the active marker so getter delegation still finds this tab.
2246
+ if (this.activeTabKey === staleId) this.activeTabKey = tab._localKey;
2247
+ fetch(`/api/chat/session/${staleId}`, { method: 'DELETE' }).catch(() => {});
2248
+ }
2249
+
2250
+ /**
2251
+ * True when a tab can still have its provider/model swapped in place: no
2252
+ * messages exchanged, nothing streaming, and the title is still the
2253
+ * auto-generated one. Shared by the provider picker and the model picker so
2254
+ * the two gates cannot drift.
2255
+ * @param {ChatTab|null} tab
2256
+ * @returns {boolean}
2257
+ */
2258
+ _isTabFresh(tab) {
2259
+ return !!tab
2260
+ && Array.isArray(tab.messages)
1839
2261
  && tab.messages.length === 0
1840
2262
  && !tab.isStreaming
1841
2263
  && !tab.streamingContent
1842
2264
  && !tab.titleFromUser;
2265
+ }
1843
2266
 
1844
- if (!isFresh) {
1845
- await this._openNewTab();
2267
+ // ── Model picker dropdown ──────────────────────────────────────────────
2268
+
2269
+ _isModelDropdownOpen() {
2270
+ return !!this.modelDropdown && this.modelDropdown.style.display !== 'none';
2271
+ }
2272
+
2273
+ _toggleModelDropdown() {
2274
+ if (this._isModelDropdownOpen()) {
2275
+ this._hideModelDropdown();
2276
+ } else {
2277
+ this._showModelDropdown();
2278
+ }
2279
+ }
2280
+
2281
+ async _showModelDropdown() {
2282
+ if (!this.modelDropdown) return;
2283
+ // Close the sibling dropdowns — exclusion is pairwise/hand-maintained.
2284
+ this._hideProviderDropdown();
2285
+ this._hideSessionDropdown();
2286
+ this._hideSnippetDropdown();
2287
+
2288
+ // Claim this open. Every hide bumps the same counter, so a _hideModelDropdown
2289
+ // that lands while the catalog fetch is in flight (or a second open) makes this
2290
+ // one stale — it must not un-hide the dropdown or register a second listener.
2291
+ const token = ++this._modelDropdownOpenToken;
2292
+
2293
+ // The catalog is what the rows are built from; a failure degrades to the
2294
+ // "Provider default" row only.
2295
+ await this._ensureChatCatalog();
2296
+ if (!this.modelDropdown) return;
2297
+ if (token !== this._modelDropdownOpenToken) return;
2298
+
2299
+ this._renderModelDropdown();
2300
+ this.modelDropdown.style.display = '';
2301
+ this.modelPickerBtn?.classList.add('chat-panel__model-picker-btn--open');
2302
+
2303
+ // The dropdown is position:fixed (it must escape the chat panel's
2304
+ // overflow:hidden), so it has to be placed after it is displayed.
2305
+ this._positionModelDropdown();
2306
+
2307
+ // Bind outside-click-to-close (one-shot). Drop any handler still installed by a
2308
+ // previous open before replacing the reference, or it can never be removed.
2309
+ if (this._modelOutsideClickHandler) {
2310
+ document.removeEventListener('click', this._modelOutsideClickHandler);
2311
+ this._modelOutsideClickHandler = null;
2312
+ }
2313
+ const handler = (e) => {
2314
+ if (this.modelPickerEl && !this.modelPickerEl.contains(e.target)) {
2315
+ this._hideModelDropdown();
2316
+ }
2317
+ };
2318
+ this._modelOutsideClickHandler = handler;
2319
+ setTimeout(() => {
2320
+ // A hide (or another open) between here and the tick already cleared/replaced
2321
+ // the reference; adding it now would leak a listener nothing removes.
2322
+ if (this._modelOutsideClickHandler !== handler) return;
2323
+ document.addEventListener('click', handler);
2324
+ }, 0);
2325
+ }
2326
+
2327
+ /**
2328
+ * Place the fixed-position model dropdown under the picker button, anchored to
2329
+ * the button's RIGHT edge (it is wider than the button and grows leftwards).
2330
+ * Clamped so a dropdown wider than the space to its left cannot run off the
2331
+ * left of the viewport — reachable with a narrow window or a narrow panel.
2332
+ */
2333
+ _positionModelDropdown() {
2334
+ if (!this.modelDropdown || !this.modelPickerBtn) return;
2335
+ const margin = 8;
2336
+ const rect = this.modelPickerBtn.getBoundingClientRect();
2337
+ const viewportWidth = window.innerWidth || document.documentElement?.clientWidth || 0;
2338
+ const width = this.modelDropdown.getBoundingClientRect().width;
2339
+
2340
+ // Offset from the viewport's right edge; a LARGER value pushes it further left.
2341
+ let right = viewportWidth - rect.right;
2342
+ const maxRight = viewportWidth - width - margin;
2343
+ if (right > maxRight) right = maxRight;
2344
+ if (right < margin) right = margin;
2345
+
2346
+ this.modelDropdown.style.top = `${rect.bottom + 4}px`;
2347
+ this.modelDropdown.style.right = `${right}px`;
2348
+ }
2349
+
2350
+ _hideModelDropdown() {
2351
+ // Bumped before the element guard so a hide always invalidates a pending open,
2352
+ // even on a panel whose DOM is not built yet.
2353
+ this._modelDropdownOpenToken += 1;
2354
+ if (!this.modelDropdown) return;
2355
+ this.modelDropdown.style.display = 'none';
2356
+ this.modelPickerBtn?.classList.remove('chat-panel__model-picker-btn--open');
2357
+ if (this._modelOutsideClickHandler) {
2358
+ document.removeEventListener('click', this._modelOutsideClickHandler);
2359
+ this._modelOutsideClickHandler = null;
2360
+ }
2361
+ }
2362
+
2363
+ /**
2364
+ * Render the model dropdown for the ACTIVE tab's provider: a "Provider
2365
+ * default" row first (subtitled with the configured model, or "CLI default"),
2366
+ * then one row per catalog model.
2367
+ */
2368
+ _renderModelDropdown() {
2369
+ if (!this.modelDropdown) return;
2370
+
2371
+ const tab = this._getActiveTab();
2372
+ const providerId = tab?.provider || this._activeProvider;
2373
+ const entry = this._getCatalogEntry(providerId);
2374
+ const models = Array.isArray(entry?.models) ? entry.models : [];
2375
+ const activeModel = tab ? (tab.model ?? null) : null;
2376
+
2377
+ const defaultSubtitle = entry?.configuredModel
2378
+ ? this._getModelDisplayName(providerId, entry.configuredModel)
2379
+ : 'CLI default';
2380
+
2381
+ const rows = [];
2382
+ rows.push(`
2383
+ <button class="chat-panel__model-item${activeModel == null ? ' chat-panel__model-item--active' : ''}"
2384
+ data-model-id=""
2385
+ data-default="true">
2386
+ <span class="chat-panel__model-item-body">
2387
+ <span class="chat-panel__model-item-name">Provider default</span>
2388
+ <span class="chat-panel__model-item-subtitle">${this._escapeHtml(defaultSubtitle)}</span>
2389
+ </span>
2390
+ ${activeModel == null ? DROPDOWN_CHECK_ICON : ''}
2391
+ </button>
2392
+ `);
2393
+
2394
+ for (const model of models) {
2395
+ if (!model || !model.id) continue;
2396
+ const isActive = activeModel === model.id;
2397
+ const badgeLabel = model.badge || model.tier || '';
2398
+ const badgeClasses = ['chat-panel__model-badge'];
2399
+ if (model.tier) {
2400
+ badgeClasses.push(`chat-panel__model-badge--${String(model.tier).toLowerCase().replace(/[^a-z0-9]+/g, '-')}`);
2401
+ }
2402
+ const badge = badgeLabel
2403
+ ? `<span class="${badgeClasses.join(' ')}">${this._escapeHtml(badgeLabel)}</span>`
2404
+ : '';
2405
+ const tagline = model.tagline
2406
+ ? `<span class="chat-panel__model-item-subtitle">${this._escapeHtml(model.tagline)}</span>`
2407
+ : '';
2408
+
2409
+ rows.push(`
2410
+ <button class="chat-panel__model-item${isActive ? ' chat-panel__model-item--active' : ''}"
2411
+ data-model-id="${this._escapeAttr(model.id)}">
2412
+ <span class="chat-panel__model-item-body">
2413
+ <span class="chat-panel__model-item-head">
2414
+ <span class="chat-panel__model-item-name">${this._escapeHtml(model.name || model.id)}</span>
2415
+ ${badge}
2416
+ </span>
2417
+ ${tagline}
2418
+ </span>
2419
+ ${isActive ? DROPDOWN_CHECK_ICON : ''}
2420
+ </button>
2421
+ `);
2422
+ }
2423
+
2424
+ if (models.length === 0) {
2425
+ rows.push(`<div class="chat-panel__model-empty">No model catalog for this provider</div>`);
2426
+ }
2427
+
2428
+ this.modelDropdown.innerHTML = rows.join('');
2429
+
2430
+ this.modelDropdown.querySelectorAll('.chat-panel__model-item').forEach(btn => {
2431
+ btn.addEventListener('click', () => {
2432
+ const raw = btn.dataset.modelId;
2433
+ this._selectModel(raw ? raw : null);
2434
+ });
2435
+ });
2436
+ }
2437
+
2438
+ /**
2439
+ * Select a model for the conversation.
2440
+ *
2441
+ * A fresh tab (see _isTabFresh) swaps in place — exactly like the provider
2442
+ * picker, including DELETEing an already-created empty session so the next
2443
+ * send starts one under the new model. A tab that has a conversation keeps
2444
+ * the model it started with: the user is offered a new tab instead, after a
2445
+ * one-time explainer (_confirmModelSwitch).
2446
+ *
2447
+ * @param {string|null} modelId - Catalog model id, or null for "provider default"
2448
+ */
2449
+ async _selectModel(modelId) {
2450
+ const normalized = modelId || null;
2451
+ const tab = this._getActiveTab();
2452
+ if (!tab) {
2453
+ // The picker stays live in the zero-tab state (reachable by closing the
2454
+ // last tab), so a selection here must not be silently dropped — the next
2455
+ // send would start on the provider default. Mirror _selectProvider and
2456
+ // open a tab carrying the choice.
2457
+ this._hideModelDropdown();
2458
+ this._rememberModel(this._activeProvider, normalized);
2459
+ await this._openNewTab({ provider: this._activeProvider, model: normalized });
2460
+ return;
2461
+ }
2462
+ if ((tab.model ?? null) === normalized) {
2463
+ this._hideModelDropdown();
1846
2464
  return;
1847
2465
  }
1848
2466
 
1849
- tab.provider = id;
1850
- if (tab.wsUnsub) { try { tab.wsUnsub(); } catch { /* noop */ } tab.wsUnsub = null; }
1851
- if (tab.sessionId != null) {
1852
- const staleId = tab.sessionId;
1853
- tab.sessionId = null;
1854
- tab.sessionWarm = false;
1855
- // Restore the active marker so getter delegation still finds this tab.
1856
- if (this.activeTabKey === staleId) this.activeTabKey = tab._localKey;
1857
- fetch(`/api/chat/session/${staleId}`, { method: 'DELETE' }).catch(() => {});
2467
+ if (this._isTabFresh(tab)) {
2468
+ tab.model = normalized;
2469
+ this._rememberModel(tab.provider || this._activeProvider, normalized);
2470
+ this._discardEmptySession(tab);
2471
+ this._updateTitle(tab.provider, tab.model);
2472
+ this._renderTabStrip();
2473
+ this._hideModelDropdown();
2474
+ return;
1858
2475
  }
1859
- this._renderTabStrip();
2476
+
2477
+ // Capture identity BEFORE the await: the dialog can sit open while the
2478
+ // stream finishes, the tab is closed, or the provider is swapped.
2479
+ const capturedProvider = tab.provider || this._activeProvider;
2480
+ this._hideModelDropdown();
2481
+
2482
+ const confirmed = await this._confirmModelSwitch(tab, normalized);
2483
+ // A cancelled switch is not a pick: the preference must stay exactly as it
2484
+ // was, or backing out of the dialog would silently re-aim every later tab.
2485
+ if (!confirmed) return;
2486
+ // The tab may have been closed while the dialog was up.
2487
+ if (!this.tabs.includes(tab)) return;
2488
+
2489
+ this._rememberModel(capturedProvider, normalized);
2490
+ await this._openNewTab({ provider: capturedProvider, model: normalized });
2491
+ }
2492
+
2493
+ /**
2494
+ * One-time explainer for "a conversation keeps one model". Resolves true when
2495
+ * the caller should open a new tab.
2496
+ *
2497
+ * Short-circuits to true when the user has ticked "Don't ask again" (a
2498
+ * localStorage flag; a throwing storage means "not acknowledged"), and also
2499
+ * when no ConfirmDialog is loaded on the page — the switch itself is not
2500
+ * destructive, so a missing dialog must not block it.
2501
+ *
2502
+ * @param {ChatTab} tab - Tab being switched away from (captured by the caller)
2503
+ * @param {string|null} modelId - Target model selector
2504
+ * @returns {Promise<boolean>}
2505
+ */
2506
+ async _confirmModelSwitch(tab, modelId) {
2507
+ const providerId = tab?.provider || this._activeProvider;
2508
+ const providerName = this._getProviderDisplayName(providerId);
2509
+ const targetLabel = this._getModelDisplayName(providerId, modelId);
2510
+ const currentLabel = this._getModelDisplayName(providerId, tab?.model ?? null);
2511
+
2512
+ let acknowledged = false;
2513
+ try {
2514
+ acknowledged = window.localStorage?.getItem(MODEL_SWITCH_ACK_KEY) === '1';
2515
+ } catch {
2516
+ acknowledged = false;
2517
+ }
2518
+ if (acknowledged) return true;
2519
+
2520
+ const dialog = window.confirmDialog;
2521
+ if (!dialog || typeof dialog.show !== 'function') return true;
2522
+
2523
+ let checkboxChecked = false;
2524
+ const choice = await dialog.show({
2525
+ title: 'Start a new conversation?',
2526
+ message:
2527
+ `Choosing ${targetLabel} opens a new tab with ${providerName} · ${targetLabel}. `
2528
+ + 'This conversation stays open.\n\n'
2529
+ + 'pair-review does not switch models mid-conversation. Each chat keeps the model it '
2530
+ + 'started with. Chats are meant to be lightweight, so starting a new one is the intended '
2531
+ + 'way to try a different model.',
2532
+ confirmText: 'New conversation',
2533
+ confirmClass: 'btn-primary',
2534
+ cancelText: `Keep ${currentLabel}`,
2535
+ checkboxLabel: "Don't ask again",
2536
+ onConfirm: (result) => { checkboxChecked = !!result?.checkboxChecked; },
2537
+ });
2538
+
2539
+ if (choice !== 'confirm') return false;
2540
+
2541
+ if (checkboxChecked) {
2542
+ try {
2543
+ window.localStorage?.setItem(MODEL_SWITCH_ACK_KEY, '1');
2544
+ } catch { /* per-browser convenience only; losing it just re-shows the dialog */ }
2545
+ }
2546
+ return true;
1860
2547
  }
1861
2548
 
1862
2549
  // ── Prompt-snippet picker dropdown ─────────────────────────────────────
@@ -1880,6 +2567,7 @@ class ChatPanel {
1880
2567
  if (!this.snippetDropdown) return;
1881
2568
  // Close the sibling dropdowns — exclusion is pairwise/hand-maintained.
1882
2569
  this._hideProviderDropdown();
2570
+ this._hideModelDropdown();
1883
2571
  this._hideSessionDropdown();
1884
2572
 
1885
2573
  // In-flight guard so a double-click doesn't fire two overlapping fetches.
@@ -2177,11 +2865,19 @@ class ChatPanel {
2177
2865
 
2178
2866
  async _showSessionDropdown() {
2179
2867
  if (!this.sessionDropdown) return;
2180
- // Close provider + snippet dropdowns if open
2868
+ // Close provider + model + snippet dropdowns if open
2181
2869
  this._hideProviderDropdown();
2870
+ this._hideModelDropdown();
2182
2871
  this._hideSnippetDropdown();
2183
2872
 
2873
+ // Same generation guard as the model dropdown: a hide (or a second open) that
2874
+ // lands while the session list is in flight must win.
2875
+ const token = ++this._sessionDropdownOpenToken;
2876
+
2184
2877
  const sessions = await this._fetchSessions();
2878
+ if (!this.sessionDropdown) return;
2879
+ if (token !== this._sessionDropdownOpenToken) return;
2880
+
2185
2881
  this._renderSessionDropdown(sessions);
2186
2882
  this.sessionDropdown.style.display = '';
2187
2883
  this.historyBtn.classList.add('chat-panel__history-btn--open');
@@ -2189,15 +2885,22 @@ class ChatPanel {
2189
2885
  // Position the fixed dropdown relative to the history button
2190
2886
  this._positionSessionDropdown();
2191
2887
 
2192
- // Bind outside-click-to-close (one-shot)
2193
- this._sessionOutsideClickHandler = (e) => {
2888
+ // Bind outside-click-to-close (one-shot). Remove a handler left over from a
2889
+ // previous open first — overwriting the reference orphans the listener.
2890
+ if (this._sessionOutsideClickHandler) {
2891
+ document.removeEventListener('click', this._sessionOutsideClickHandler);
2892
+ this._sessionOutsideClickHandler = null;
2893
+ }
2894
+ const handler = (e) => {
2194
2895
  if (!this.sessionPickerEl.contains(e.target) && !this.historyBtn.contains(e.target)) {
2195
2896
  this._hideSessionDropdown();
2196
2897
  }
2197
2898
  };
2899
+ this._sessionOutsideClickHandler = handler;
2198
2900
  // Use setTimeout so the current click event doesn't immediately trigger close
2199
2901
  setTimeout(() => {
2200
- document.addEventListener('click', this._sessionOutsideClickHandler);
2902
+ if (this._sessionOutsideClickHandler !== handler) return;
2903
+ document.addEventListener('click', handler);
2201
2904
  }, 0);
2202
2905
  }
2203
2906
 
@@ -2209,6 +2912,8 @@ class ChatPanel {
2209
2912
  }
2210
2913
 
2211
2914
  _hideSessionDropdown() {
2915
+ // Bumped before the element guard so a hide always invalidates a pending open.
2916
+ this._sessionDropdownOpenToken += 1;
2212
2917
  if (!this.sessionDropdown) return;
2213
2918
  this.sessionDropdown.style.display = 'none';
2214
2919
  this.historyBtn.classList.remove('chat-panel__history-btn--open');
@@ -2481,7 +3186,12 @@ class ChatPanel {
2481
3186
  }
2482
3187
  if (!restored) {
2483
3188
  if (this.tabs.length === 0) {
2484
- const tab = this._createTab({ provider: this._activeProvider });
3189
+ // Same seeding as open()'s placeholder; _loadMRUSession overwrites it
3190
+ // when it adopts an existing session.
3191
+ const tab = this._createTab({
3192
+ provider: this._activeProvider,
3193
+ model: this._rememberedModelFor(this._activeProvider),
3194
+ });
2485
3195
  this._appendTab(tab, { focus: true });
2486
3196
  }
2487
3197
  await this._loadMRUSession();
@@ -2499,7 +3209,12 @@ class ChatPanel {
2499
3209
  // Ensure there is an active tab to bind the new session to. This happens
2500
3210
  // for lazy-creation paths (first sendMessage on an empty panel).
2501
3211
  if (!this._getActiveTab()) {
2502
- const tab = this._createTab({ provider: this._activeProvider });
3212
+ // Lazy tab for a session about to be created — seed it so the POST body
3213
+ // carries the remembered model, exactly like a "+" tab would.
3214
+ const tab = this._createTab({
3215
+ provider: this._activeProvider,
3216
+ model: this._rememberedModelFor(this._activeProvider),
3217
+ });
2503
3218
  this._appendTab(tab, { focus: true });
2504
3219
  }
2505
3220
  if (!this.reviewId) {
@@ -2509,16 +3224,18 @@ class ChatPanel {
2509
3224
  const tab = this._getActiveTab();
2510
3225
  if (!tab) return null;
2511
3226
 
3227
+ // Same in-flight capture as _createSessionForTab: the user can swap provider or
3228
+ // model on this tab while the POST is out, and the row the server just created
3229
+ // belongs to the captured pair, not the current one.
3230
+ const capturedProvider = tab.provider;
3231
+ const capturedModel = tab.model ?? null;
3232
+
2512
3233
  const isAcp = this._isAcpProvider();
2513
3234
  if (isAcp) this._showStatusFlash('Starting Agent Client Protocol');
2514
3235
 
2515
3236
  try {
2516
- const body = {
2517
- provider: tab.provider || this._activeProvider,
2518
- reviewId: this.reviewId
2519
- };
3237
+ const body = this._sessionRequestBody(tab);
2520
3238
  if (contextCommentId) body.contextCommentId = contextCommentId;
2521
- if (tab.analysisContextRemoved) body.skipAnalysisContext = true;
2522
3239
 
2523
3240
  console.debug('[ChatPanel] Creating session for review', this.reviewId);
2524
3241
  const response = await fetch('/api/chat/session', {
@@ -2539,7 +3256,15 @@ class ChatPanel {
2539
3256
  fetch(`/api/chat/session/${result.data.id}`, { method: 'DELETE' }).catch(() => {});
2540
3257
  return null;
2541
3258
  }
3259
+ // Provider or model swapped between the captured snapshot and the response:
3260
+ // the session was created for the old selection, so drop it and let the next
3261
+ // send start one under the new selection.
3262
+ if (tab.provider !== capturedProvider || (tab.model ?? null) !== capturedModel) {
3263
+ fetch(`/api/chat/session/${result.data.id}`, { method: 'DELETE' }).catch(() => {});
3264
+ return null;
3265
+ }
2542
3266
  tab.sessionId = result.data.id;
3267
+ this._adoptServerModel(tab, result.data);
2543
3268
  this.activeTabKey = result.data.id;
2544
3269
  tab.sessionWarm = true;
2545
3270
  if (tab.messagesEl) tab.messagesEl.dataset.tabKey = String(tab.sessionId);
@@ -2570,7 +3295,12 @@ class ChatPanel {
2570
3295
  // Capture the originating tab BEFORE any awaits. Bail if no tab.
2571
3296
  let tab = this._getActiveTab();
2572
3297
  if (!tab) {
2573
- tab = this._createTab({ provider: this._activeProvider });
3298
+ // Lazy tab (send with an empty strip). Seeded synchronously — sendMessage
3299
+ // must not gain an await before it captures its tab.
3300
+ tab = this._createTab({
3301
+ provider: this._activeProvider,
3302
+ model: this._rememberedModelFor(this._activeProvider),
3303
+ });
2574
3304
  this._appendTab(tab, { focus: true });
2575
3305
  }
2576
3306
  if (tab.isStreaming) return;
@@ -4562,9 +5292,14 @@ class ChatPanel {
4562
5292
  }
4563
5293
  } else {
4564
5294
  if (isTask) {
4565
- // Remove spinner from completed Task badge
4566
- const badges = streamingMsg.querySelectorAll('.chat-panel__tool-badge[data-tool="Task"]:not(.chat-panel__tool-badge--transient), .chat-panel__tool-badge[data-tool="Agent"]:not(.chat-panel__tool-badge--transient)');
5295
+ // Remove spinner from completed Task badges. Tool names arrive with
5296
+ // provider-specific casing (Claude sends `Task`, OMP/Pi send `task`) and
5297
+ // dataset.tool stores the name verbatim, so match case-insensitively
5298
+ // instead of with an exact [data-tool="Task"] selector.
5299
+ const badges = streamingMsg.querySelectorAll('.chat-panel__tool-badge:not(.chat-panel__tool-badge--transient)');
4567
5300
  badges.forEach(b => {
5301
+ const badgeTool = (b.dataset?.tool || '').toLowerCase();
5302
+ if (badgeTool !== 'task' && badgeTool !== 'agent') return;
4568
5303
  const spinner = b.querySelector('.chat-panel__tool-spinner');
4569
5304
  if (spinner) spinner.remove();
4570
5305
  });
@@ -5346,6 +6081,7 @@ class ChatPanel {
5346
6081
  // container is cleared (each open dropdown holds a one-shot handler;
5347
6082
  // these hide methods safely no-op when their dropdown is already closed).
5348
6083
  this._hideProviderDropdown();
6084
+ this._hideModelDropdown();
5349
6085
  this._hideSessionDropdown();
5350
6086
  this._hideSnippetDropdown();
5351
6087
  this._hideSaveSnippetPill();