@genesislcap/ai-assistant 15.6.2 → 15.7.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 (76) hide show
  1. package/dist/ai-assistant.api.json +422 -6
  2. package/dist/ai-assistant.d.ts +654 -19
  3. package/dist/chat-driver.cjs +285 -26
  4. package/dist/chat-driver.cjs.map +3 -3
  5. package/dist/chat-driver.mjs +285 -26
  6. package/dist/chat-driver.mjs.map +3 -3
  7. package/dist/custom-elements.json +289 -32
  8. package/dist/dts/channel/ai-activity-channel.d.ts +51 -1
  9. package/dist/dts/channel/ai-activity-channel.d.ts.map +1 -1
  10. package/dist/dts/components/chat-driver/chat-driver.d.ts +99 -1
  11. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.test.d.ts.map +1 -1
  13. package/dist/dts/components/orchestrating-driver/orchestrating-driver.budget.test.d.ts +2 -0
  14. package/dist/dts/components/orchestrating-driver/orchestrating-driver.budget.test.d.ts.map +1 -0
  15. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +14 -0
  16. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  17. package/dist/dts/components/settings-modal/settings-modal.styles.d.ts.map +1 -1
  18. package/dist/dts/components/settings-modal/settings-modal.template.d.ts.map +1 -1
  19. package/dist/dts/main/blocked-state.test.d.ts +2 -0
  20. package/dist/dts/main/blocked-state.test.d.ts.map +1 -0
  21. package/dist/dts/main/main.d.ts +435 -19
  22. package/dist/dts/main/main.d.ts.map +1 -1
  23. package/dist/dts/main/main.styles.d.ts.map +1 -1
  24. package/dist/dts/main/main.styles.test.d.ts +2 -0
  25. package/dist/dts/main/main.styles.test.d.ts.map +1 -0
  26. package/dist/dts/main/main.template.d.ts +53 -0
  27. package/dist/dts/main/main.template.d.ts.map +1 -1
  28. package/dist/dts/state/ai-assistant-slice.d.ts +162 -6
  29. package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
  30. package/dist/dts/state/debug-event-log.d.ts +6 -1
  31. package/dist/dts/state/debug-event-log.d.ts.map +1 -1
  32. package/dist/dts/state/session-store.d.ts +11 -0
  33. package/dist/dts/state/session-store.d.ts.map +1 -1
  34. package/dist/dts/utils/banked-usage-baselines.d.ts +51 -0
  35. package/dist/dts/utils/banked-usage-baselines.d.ts.map +1 -0
  36. package/dist/esm/components/chat-driver/chat-driver.js +263 -21
  37. package/dist/esm/components/chat-driver/chat-driver.test.js +464 -1
  38. package/dist/esm/components/orchestrating-driver/orchestrating-driver.budget.test.js +312 -0
  39. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +89 -4
  40. package/dist/esm/components/settings-modal/settings-modal.styles.js +63 -18
  41. package/dist/esm/components/settings-modal/settings-modal.template.js +36 -7
  42. package/dist/esm/main/blocked-state.test.js +969 -0
  43. package/dist/esm/main/cost-session-banking.test.js +238 -8
  44. package/dist/esm/main/main.js +826 -48
  45. package/dist/esm/main/main.styles.js +72 -0
  46. package/dist/esm/main/main.styles.test.js +99 -0
  47. package/dist/esm/main/main.template.js +121 -4
  48. package/dist/esm/state/ai-assistant-slice.js +145 -7
  49. package/dist/esm/state/ai-assistant-slice.test.js +138 -1
  50. package/dist/esm/state/debug-event-log.js +7 -2
  51. package/dist/esm/state/debug-event-log.test.js +49 -1
  52. package/dist/esm/state/persistence/session-snapshot.test.js +18 -0
  53. package/dist/esm/utils/banked-usage-baselines.js +84 -0
  54. package/dist/tsconfig.tsbuildinfo +1 -1
  55. package/docs/migration-GENC-1464.md +562 -0
  56. package/docs/sub_agent.md +20 -3
  57. package/package.json +17 -17
  58. package/src/channel/ai-activity-channel.ts +56 -2
  59. package/src/components/chat-driver/chat-driver.test.ts +549 -0
  60. package/src/components/chat-driver/chat-driver.ts +324 -14
  61. package/src/components/orchestrating-driver/orchestrating-driver.budget.test.ts +438 -0
  62. package/src/components/orchestrating-driver/orchestrating-driver.ts +101 -6
  63. package/src/components/settings-modal/settings-modal.styles.ts +63 -18
  64. package/src/components/settings-modal/settings-modal.template.ts +38 -7
  65. package/src/main/blocked-state.test.ts +1316 -0
  66. package/src/main/cost-session-banking.test.ts +283 -11
  67. package/src/main/main.styles.test.ts +130 -0
  68. package/src/main/main.styles.ts +72 -0
  69. package/src/main/main.template.ts +131 -4
  70. package/src/main/main.ts +827 -42
  71. package/src/state/ai-assistant-slice.test.ts +215 -0
  72. package/src/state/ai-assistant-slice.ts +218 -8
  73. package/src/state/debug-event-log.test.ts +63 -0
  74. package/src/state/debug-event-log.ts +7 -2
  75. package/src/state/persistence/session-snapshot.test.ts +22 -0
  76. package/src/utils/banked-usage-baselines.ts +90 -0
package/src/main/main.ts CHANGED
@@ -24,12 +24,22 @@
24
24
  import type {
25
25
  AggregateUsage,
26
26
  AIProviderRegistryStatusEntry,
27
+ AIProviderType,
27
28
  ChatAttachment,
28
29
  ChatConfig,
30
+ ChatDriverResult,
29
31
  ChatInputDuringExecutionMode,
30
32
  ChatMessage,
33
+ TurnFailureReason,
34
+ } from '@genesislcap/foundation-ai';
35
+ import {
36
+ AIProviderRegistry,
37
+ BUDGETED_VENDORS,
38
+ DEFAULT_BUDGET_EXHAUSTED_MESSAGE,
39
+ isObservableAIProviderRegistry,
40
+ VENDOR_LABELS,
41
+ vendorTypeOfLabel,
31
42
  } from '@genesislcap/foundation-ai';
32
- import { AIProviderRegistry, isObservableAIProviderRegistry } from '@genesislcap/foundation-ai';
33
43
  import { showNotificationDialog } from '@genesislcap/foundation-notifications';
34
44
  import { avoidTreeShaking } from '@genesislcap/foundation-utils';
35
45
  import type { Modal } from '@genesislcap/rapid-design-system';
@@ -113,6 +123,11 @@ import { ChatSuggestions } from '../suggestions/chat-suggestions';
113
123
  import type { InteractionContext } from '../types/interaction-context';
114
124
  import { AnimatedPanelToggle } from '../utils/animated-panel-toggle';
115
125
  import { resolveExclusiveLoadingStyle } from '../utils/animation-exclusivity';
126
+ import {
127
+ deleteBankedBaseline,
128
+ getBankedBaseline,
129
+ setBankedBaseline,
130
+ } from '../utils/banked-usage-baselines';
116
131
  import { collectSessionModels } from '../utils/collect-session-models';
117
132
  import {
118
133
  clearCostSessionHistory,
@@ -208,6 +223,88 @@ const COMPOSER_MAX_HEIGHT_PX = 400;
208
223
  /** Keep at least this much of the message list visible while growing the composer. */
209
224
  const COMPOSER_MIN_MESSAGES_PX = 80;
210
225
 
226
+ /**
227
+ * Composer placeholder while the assistant is blocked (GENC-1464). Deliberately
228
+ * fixed and short, and NOT host-overridable — the banner directly above it
229
+ * carries the detail, and that one IS overridable via `setBlocked(true, reason)`.
230
+ * The banner's own default copy is `DEFAULT_BUDGET_EXHAUSTED_MESSAGE`, read
231
+ * straight from `foundation-ai` so the banner and the driver's transcript bubble
232
+ * cannot drift apart.
233
+ */
234
+ const BLOCKED_PLACEHOLDER = 'AI usage limit reached';
235
+
236
+ /**
237
+ * Closing sentence for a wall the user cannot route around. Singular/plural
238
+ * variants because the banner names one vendor or several.
239
+ */
240
+ const RAISE_LIMIT_ACTION = 'Contact your administrator to raise it.';
241
+ const RAISE_LIMITS_ACTION = 'Contact your administrator to raise them.';
242
+
243
+ /**
244
+ * Banner copy built from the figures a 402 actually reported, or `undefined`
245
+ * when the proxy sent none.
246
+ *
247
+ * `undefined` is the meaningful return, not a fallback: paired with the
248
+ * slice's "a re-latch without a reason keeps the existing explanation" rule, it
249
+ * makes a figureless driver latch leave a host-supplied reason intact rather
250
+ * than blanking it back to the default at the exact moment the wall is hit.
251
+ *
252
+ * Exported for the unit test that pins the formatting; not part of the element
253
+ * API.
254
+ *
255
+ * @internal
256
+ */
257
+ export function formatBlockedReason(
258
+ budget?: Extract<ChatDriverResult, { reason: 'done' }>['budget'],
259
+ vendor?: AIProviderType,
260
+ ): string | undefined {
261
+ if (!budget || (budget.budgetUsd == null && budget.spentUsd == null)) return undefined;
262
+ const money = (v?: number) => (v == null ? 'an unknown amount' : `$${v.toFixed(2)}`);
263
+ const figures = `(${money(budget.spentUsd)} of ${money(budget.budgetUsd)})`;
264
+ // A per-vendor statement carries NO action clause, because the right action is
265
+ // not knowable at latch time: whether "switch vendor" or "contact your
266
+ // administrator" is the honest advice depends on whether any OTHER vendor still
267
+ // has headroom, which only the composing getter can see. The vendor-agnostic
268
+ // form keeps its historical trailing sentence — nothing composes onto it.
269
+ return vendor
270
+ ? `${vendorDisplayName(vendor)}'s AI usage limit is reached ${figures}.`
271
+ : `AI usage limit reached ${figures}. Contact your administrator to raise it.`;
272
+ }
273
+
274
+ /**
275
+ * Human-readable name for a vendor, falling back to its raw type.
276
+ *
277
+ * `'none'` needs no special case: it is the "no provider configured" sentinel,
278
+ * it is filtered out of {@link FoundationAiAssistant.reachableVendors}, the latch
279
+ * refuses to attribute a wall to it, and
280
+ * {@link FoundationAiAssistant.setVendorBlocked} rejects it at the boundary — so
281
+ * nothing can put it in front of this function. The `?? vendor` fallback is for a
282
+ * vendor type added to `AIProviderType` without a label, which would print the
283
+ * type rather than nothing.
284
+ */
285
+ function vendorDisplayName(vendor: AIProviderType): string {
286
+ return (VENDOR_LABELS as Partial<Record<AIProviderType, string>>)[vendor] ?? vendor;
287
+ }
288
+
289
+ /**
290
+ * `a`, `a and b`, `a, b and c`.
291
+ *
292
+ * The general joiner is kept rather than hardcoded to a pair because the list
293
+ * is `BUDGETED_VENDORS`-shaped, and that list is a cross-repo contract owned by
294
+ * the proxy (today `anthropic` and `gemini`; `openai` is refused up front with
295
+ * 400 UNSUPPORTED_PROVIDER and can never be walled) — a vendor added there must
296
+ * not require an edit here. Its upper bound is not an assertion in a comment — it is
297
+ * the key count of `VENDOR_LABELS`, since every element of every list passed here
298
+ * comes from `blockedVendors` or `reachableVendors`, both of which hold
299
+ * `AIProviderType` values, and the type has five members of which `'none'` is
300
+ * excluded from both.
301
+ */
302
+ function formatVendorList(vendors: readonly AIProviderType[]): string {
303
+ const names = vendors.map(vendorDisplayName);
304
+ if (names.length <= 1) return names[0] ?? '';
305
+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
306
+ }
307
+
211
308
  // Register supporting components when the main component module is imported.
212
309
  avoidTreeShaking(
213
310
  AiChatMarkdown,
@@ -425,14 +522,26 @@ export class FoundationAiAssistant extends GenesisElement {
425
522
 
426
523
  /**
427
524
  * True when a new send must be refused: a turn is running (`busy`), a page-reload
428
- * restore is loading history that would clobber it (`restoring`), or a manual
429
- * compaction is rewriting history (`compacting`). Mirrors the composer's
430
- * `?disabled` gate so a **programmatic** `send`/`submitMessage` (e.g. a host's
431
- * custom input while the built-in composer is hidden) can't slip past it and have
432
- * its message wiped when the restored/compacted history lands (GENC-1351 §6).
525
+ * restore is loading history that would clobber it (`restoring`), a manual
526
+ * compaction is rewriting history (`compacting`), or a backend condition has
527
+ * locked the assistant outright (`blocked` e.g. an exhausted AI budget).
528
+ * Mirrors the composer's `?disabled` gate so a **programmatic**
529
+ * `send`/`submitMessage` (e.g. a host's custom input while the built-in composer
530
+ * is hidden) can't slip past it and have its message wiped when the
531
+ * restored/compacted history lands (GENC-1351 §6).
433
532
  */
434
533
  private get sendBlocked(): boolean {
435
- return this.busy || this.restoring || this.compacting;
534
+ return this.busy || this.restoring || this.compacting || this.blocked;
535
+ }
536
+
537
+ /**
538
+ * Why a programmatic send was refused, for `submitMessage`'s `errors`. A
539
+ * backend block is called out distinctly because — unlike the transient
540
+ * "busy" cases — waiting and retrying will never clear it, and a caller
541
+ * looping on "Assistant is busy" would spin forever.
542
+ */
543
+ private sendRefusalReason(): string {
544
+ return this.blocked ? this.effectiveBlockedReason : 'Assistant is busy';
436
545
  }
437
546
 
438
547
  /**
@@ -604,6 +713,545 @@ export class FoundationAiAssistant extends GenesisElement {
604
713
  this._sessionRef?.actions.aiAssistant.setRestoring(value);
605
714
  }
606
715
 
716
+ /**
717
+ * Whether the assistant is blocked by a backend condition and cannot send —
718
+ * today, an exhausted AI-spend budget (GENC-1464). While true the composer is
719
+ * disabled, `send`/`submitMessage` refuse, suggestions stop being fetched, and
720
+ * a persistent banner (`part="blocked-banner"`) sits above the composer
721
+ * explaining why. The transcript stays visible and scrollable throughout —
722
+ * unlike `compacting` and `restoring`, this does not replace the conversation.
723
+ *
724
+ * **Latched.** Nothing in the element clears it: not a new turn, not "Clear"
725
+ * / "New chat", not a pop-in/out. It stays set until the host writes
726
+ * `false` — because nothing the user can do inside the assistant refills a
727
+ * budget. Hosts typically set it from their own pre-flight budget check on
728
+ * mount, and clear it once a later check shows headroom again.
729
+ *
730
+ * The driver also latches it automatically when a turn ends with the
731
+ * `'budget-exhausted'` failure reason — off the `tool-loop-end` activity bus
732
+ * (which also covers a sub-agent wall, a turn this element did not start, and
733
+ * an element swapped in mid-turn) and off the driver's return value (which
734
+ * covers a wall hit during multi-agent classification, where no tool loop ran
735
+ * and so no bus event fires). So a host that does no pre-flight at all still
736
+ * gets a correct locked UI the moment the first 402 lands. The bus topic is
737
+ * tab-scoped, so a wall hit in a popped-out window latches the main window
738
+ * too — correct for a shared spend cap.
739
+ *
740
+ * **Lifetime — read this before relying on it as your source of truth.** The
741
+ * latch is in-memory and per-`stateKey`:
742
+ *
743
+ * - It does **not** survive `switchSession`. Switching away tears the outgoing
744
+ * session's store down entirely, so switching back yields a fresh, unblocked
745
+ * store.
746
+ * - It does **not** survive a page reload. It is deliberately absent from the
747
+ * persisted session snapshot: the snapshot is long-lived, so a persisted
748
+ * latch would outlive an out-of-band budget raise with no in-element way to
749
+ * clear it — a stale lock is worse than re-deriving the state.
750
+ *
751
+ * The durable source of truth is therefore the **host's pre-flight**, which
752
+ * should run on mount and on every session switch. See
753
+ * `docs/migration-GENC-1464.md` §"How to adopt", Option B.
754
+ *
755
+ * @beta
756
+ */
757
+ @volatile
758
+ get blocked(): boolean {
759
+ const session = this._sessionRef?.store.aiAssistant;
760
+ if (!session) return false;
761
+ if (session.blocked) return true;
762
+ // Byte-identical to the old stored read for every host that never adopts the
763
+ // per-vendor API — which is what makes this derivation non-breaking.
764
+ if (session.blockedVendors.length === 0) return false;
765
+ // Unknown reachability (statuses not loaded yet, or providers that report no
766
+ // status) fails SAFE — any wall blocks everything, exactly today's semantics —
767
+ // and needs no clause of its own: `every` on the empty set is vacuously true.
768
+ return this.reachableVendors.every((v) => session.blockedVendors.includes(v));
769
+ }
770
+ set blocked(value: boolean) {
771
+ this._sessionRef?.actions.aiAssistant.setBlocked({ blocked: value });
772
+ }
773
+
774
+ /**
775
+ * The distinct vendors the registry can currently reach, from the provider
776
+ * statuses this element already loads on connect and refreshes on every
777
+ * observable-registry change.
778
+ *
779
+ * This is the element's answer to "which vendor would the next turn use" — a
780
+ * question that has **no** correct answer and deliberately gets no API. The
781
+ * provider is resolved per turn AND per agent: `activeProviderInput` may be an
782
+ * async function of the turn's context, an orchestrated turn picks its agent
783
+ * with an LLM `classify()` call, and sub-agents resolve their own providers.
784
+ * Any pre-turn "peek" would therefore be a guess that is wrong precisely on the
785
+ * multi-agent hosts per-vendor budgets exist for.
786
+ *
787
+ * Asking instead which vendors are REACHABLE is answerable, synchronous, and
788
+ * free — and it is enough: the composer must stay live while any reachable
789
+ * vendor has headroom, and must lock when none does. It also makes vendor-switch
790
+ * recovery a derivation rather than a mutation: a host that swaps its registry
791
+ * to another vendor fires the observable, the statuses reload, the walled vendor
792
+ * drops out of this set, and `blocked` goes false with every latch left intact.
793
+ *
794
+ * @beta
795
+ */
796
+ @volatile
797
+ get reachableVendors(): readonly AIProviderType[] {
798
+ const seen = new Set<AIProviderType>();
799
+ for (const entry of this.providerStatuses) {
800
+ const provider = entry.status?.provider;
801
+ if (!provider || provider === 'none') continue;
802
+ // Reachable means "can serve the next turn", and `chat()` is OPTIONAL on
803
+ // `AIProvider` — the shipped `ChromeProvider` and `OpenAIProvider`
804
+ // implement `getStatus()` only. Counting a chat-less provider here made
805
+ // every consumer wrong at once: it was headroom for the `blocked`
806
+ // derivation (so `otherVendorAvailable: false` failed to lock the
807
+ // composer and each send burned another doomed 402), and it was a switch
808
+ // target for the banner ("Switch to Chrome to keep going" toward a
809
+ // provider that cannot chat).
810
+ //
811
+ // The gate is CAPABILITY, not vendor identity, so a host's custom
812
+ // chat-capable OpenAI provider still counts — the same distinction
813
+ // `validate-providers.ts` already enforces by throwing. And it drops a
814
+ // vendor only on positive evidence: statuses normally come from
815
+ // `providerRegistry.listStatuses()`, whose `name` always resolves, but a
816
+ // host (or test) that assigns `providerStatuses` directly may have no
817
+ // matching registry entry, and an unresolvable name must not silently
818
+ // erase a vendor the status layer vouched for.
819
+ const registered = this.providerRegistry?.get(entry.name);
820
+ if (registered && typeof registered.chat !== 'function') continue;
821
+ seen.add(provider);
822
+ }
823
+ return [...seen];
824
+ }
825
+
826
+ /**
827
+ * Vendors currently walled by the AI-spend budget, in the order they were
828
+ * walled. Empty for a host that never adopts the per-vendor API.
829
+ *
830
+ * May include a vendor this registry cannot reach — either because the registry
831
+ * moved on after the wall was latched, or because a 402's
832
+ * `otherVendorAvailable: false` walls every vendor the proxy meters (which is
833
+ * what that verdict is a statement about; see
834
+ * {@link FoundationAiAssistant.latchBlockedFrom}). Neither costs anything
835
+ * internally — {@link FoundationAiAssistant.blocked} asks only about the
836
+ * reachable set, and the banner reads the reachability-filtered
837
+ * {@link FoundationAiAssistant.relevantBlockedVendors} — but a host rendering
838
+ * this list itself should filter it against its own registry.
839
+ *
840
+ * Read-only on purpose: a settable array would let a host write a partial list
841
+ * and silently orphan the per-vendor banner copy.
842
+ * {@link FoundationAiAssistant.setVendorBlocked} is the write path.
843
+ *
844
+ * @beta
845
+ */
846
+ get blockedVendors(): readonly AIProviderType[] {
847
+ return this._sessionRef?.store.aiAssistant.blockedVendors ?? [];
848
+ }
849
+
850
+ /**
851
+ * Whether this specific vendor's budget is walled — regardless of whether any
852
+ * other vendor still has headroom.
853
+ *
854
+ * @beta
855
+ */
856
+ isVendorBlocked(vendor: AIProviderType): boolean {
857
+ return this.blockedVendors.includes(vendor);
858
+ }
859
+
860
+ /**
861
+ * Wall (or release) one vendor's budget, optionally with banner copy for it.
862
+ * The per-vendor mirror of {@link FoundationAiAssistant.setBlocked}.
863
+ *
864
+ * Walling a vendor does **not** on its own disable the composer: while another
865
+ * reachable vendor has headroom the assistant stays usable and the banner tells
866
+ * the user to switch. Only when every reachable vendor is walled does `blocked`
867
+ * become true.
868
+ *
869
+ * `reason` is composed into the banner sentence for that vendor, **however many
870
+ * vendors are walled** — see {@link FoundationAiAssistant.effectiveBlockedReason}.
871
+ * It is per-vendor copy, not a whole-banner override; {@link FoundationAiAssistant.blockedReason}
872
+ * is the override. Omitting it keeps whatever explanation that vendor already
873
+ * carried, so a driver latch landing after a host one cannot blank it.
874
+ *
875
+ * `'none'` is rejected with a warning rather than accepted: it is the "no
876
+ * provider configured" sentinel, not a vendor. Latching it would put the raw
877
+ * sentinel in the banner ("none's AI usage limit is reached") and could never
878
+ * be undone by derivation, because `'none'` never appears in
879
+ * {@link FoundationAiAssistant.reachableVendors} — so `blocked` could never
880
+ * become derivable from it either. Use {@link FoundationAiAssistant.setBlocked}
881
+ * for a vendor-agnostic block.
882
+ *
883
+ * @beta
884
+ */
885
+ setVendorBlocked(vendor: AIProviderType, blocked: boolean, reason?: string | null): void {
886
+ if (vendor === 'none') {
887
+ logger.warn(
888
+ "FoundationAiAssistant.setVendorBlocked: 'none' is the no-provider sentinel, not a vendor — " +
889
+ 'ignoring. Use setBlocked() for a vendor-agnostic block.',
890
+ );
891
+ return;
892
+ }
893
+ this._sessionRef?.actions.aiAssistant.setVendorBlocked({ vendor, blocked, reason });
894
+ }
895
+
896
+ /** Whether this vendor's wall came from the sweep alone — see the slice's `sweptVendors`. */
897
+ private isVendorSwept(vendor: AIProviderType): boolean {
898
+ return (this._sessionRef?.store.aiAssistant.sweptVendors ?? []).includes(vendor);
899
+ }
900
+
901
+ /**
902
+ * The walled vendors the user can still be routed to — i.e.
903
+ * {@link FoundationAiAssistant.blockedVendors} narrowed to the reachable set,
904
+ * which is the only set the banner may name.
905
+ *
906
+ * A wall the registry can no longer reach is not news: it cannot be hit, and
907
+ * naming it puts a vendor in front of the user that is not theirs. The concrete
908
+ * failure this exists to stop: a host ships Anthropic-only, Anthropic walls, the
909
+ * host swaps its registry to Gemini, Gemini walls — and the banner reads "AI
910
+ * usage limits are reached for Anthropic and Gemini" to a user who has never
911
+ * had an Anthropic key. The spurious second name also flips the copy onto the
912
+ * plural branch, so even the closing sentence is wrong.
913
+ *
914
+ * When nothing is reachable YET (the statuses are still loading — the exact
915
+ * window the pre-flight and the cross-tab bus latch into), the fallback keeps
916
+ * every wall for LOCKING (`blocked` still derives true) but names only the
917
+ * vendors walled by a REFUSAL, dropping the ones the `otherVendorAvailable`
918
+ * sweep added. A refusal is a fact about a vendor this user just used; a sweep
919
+ * entry is the proxy's headroom verdict about a vendor the host may not even
920
+ * ship — naming it here reproduced the exact failure above from the other
921
+ * direction ("Gemini's AI usage limit is reached" to an Anthropic-only user),
922
+ * and flipped the copy onto the plural branch with it. Self-corrects when the
923
+ * statuses land: from then on reachability, not provenance, decides.
924
+ *
925
+ * @internal
926
+ */
927
+ @volatile
928
+ private get relevantBlockedVendors(): readonly AIProviderType[] {
929
+ const walled = this.blockedVendors;
930
+ const reachable = this.reachableVendors;
931
+ if (reachable.length === 0) {
932
+ const swept = this._sessionRef?.store.aiAssistant.sweptVendors ?? [];
933
+ return walled.filter((v) => !swept.includes(v));
934
+ }
935
+ return walled.filter((v) => reachable.includes(v));
936
+ }
937
+
938
+ /**
939
+ * Whether the blocked banner has anything to say — a vendor-agnostic block, OR
940
+ * at least one walled vendor the registry can still reach. Broader than
941
+ * {@link FoundationAiAssistant.blocked} on purpose: partial exhaustion leaves
942
+ * the composer live but still needs to be announced, because the next turn may
943
+ * route to the walled vendor and fail.
944
+ *
945
+ * Reads the reachability-filtered list for the same reason the copy does — a
946
+ * host that has swapped its registry away from the walled vendor has nothing
947
+ * left to announce, and would otherwise get a banner that falls through to the
948
+ * generic default copy over a perfectly usable composer.
949
+ *
950
+ * @internal
951
+ */
952
+ @volatile
953
+ get bannerVisible(): boolean {
954
+ return this.blocked || this.relevantBlockedVendors.length > 0;
955
+ }
956
+
957
+ /**
958
+ * Whether a suggestions fetch would hit a wall.
959
+ *
960
+ * Unlike a chat turn, this one CAN be resolved exactly: both suggestion paths
961
+ * go to the registry **default** and never to a per-agent override
962
+ * (`ChatDriver.getSuggestions` calls `providerRegistry.default()`, and
963
+ * `OrchestratingDriver.getSuggestions` just delegates to it). So the vendor a
964
+ * suggestions call would use is knowable, and this is the one place in the
965
+ * feature where that is true.
966
+ *
967
+ * Same rationale as the guard it replaces: a doomed suggestions call burns a
968
+ * `suggestions.failed` meta event and parks a raw transport error in
969
+ * `suggestionsState` for hosts to find.
970
+ *
971
+ * @internal
972
+ */
973
+ @volatile
974
+ get suggestionsBlocked(): boolean {
975
+ if (this.blocked) return true;
976
+ const defaultVendor = this.providerStatuses.find((e) => e.isDefault)?.status?.provider;
977
+ return !!defaultVendor && defaultVendor !== 'none' && this.isVendorBlocked(defaultVendor);
978
+ }
979
+
980
+ /**
981
+ * Explanation shown in the blocked banner, or `null` for the element's default
982
+ * copy. Only meaningful while {@link FoundationAiAssistant.blocked} is true;
983
+ * setting `blocked = false` clears it.
984
+ *
985
+ * Writable, and symmetric with every other store-backed accessor on this
986
+ * class: writing it re-latches with the CURRENT `blocked` value, so it changes
987
+ * the copy without disturbing the flag. Assigning `null` clears the
988
+ * explanation while staying blocked (the banner falls back to the default
989
+ * copy). {@link FoundationAiAssistant.setBlocked} remains the way to write
990
+ * both in one atomic action.
991
+ *
992
+ * @beta
993
+ */
994
+ get blockedReason(): string | null {
995
+ return this._sessionRef?.store.aiAssistant.blockedReason ?? null;
996
+ }
997
+ set blockedReason(value: string | null) {
998
+ // Deliberately NOT `setBlocked({ blocked: this.blocked, reason })`: `blocked`
999
+ // is derived now, so re-latching with it would pass `false` for a partially
1000
+ // walled session and clear every per-vendor latch as a side effect of setting
1001
+ // a string.
1002
+ this._sessionRef?.actions.aiAssistant.setBlockedReason(value);
1003
+ }
1004
+
1005
+ /**
1006
+ * Latch the backend block off a turn outcome. The single decision point for
1007
+ * both latch sites (the `tool-loop-end` bus subscription and `send()`'s
1008
+ * return-value check), so the rule cannot diverge between them.
1009
+ *
1010
+ * Idempotent and one-way **per vendor**: it never unblocks, and it never
1011
+ * re-writes an existing wall. That guard is load-bearing, not just an
1012
+ * optimisation — the bus fires from the driver's `finally`, i.e. BEFORE
1013
+ * `sendMessage()` resolves, so a host subscribed to `tool-loop-end` (what the
1014
+ * migration guide's Option C recommends) sets its own detailed reason and the
1015
+ * return-value latch would otherwise land a moment later and blank it.
1016
+ *
1017
+ * The guard being per-vendor rather than global is the whole difference. A
1018
+ * single global "already blocked, do nothing" would swallow a second vendor's
1019
+ * wall — so a session walled on Anthropic could never record that Gemini went
1020
+ * too, and under a mixed registry an Anthropic-only wall would lock a composer
1021
+ * that Gemini could still serve.
1022
+ *
1023
+ * **Which field is authoritative**, in order:
1024
+ *
1025
+ * 1. `budget.vendorLabel` — stamped by the transport that was actually refused,
1026
+ * so it can never be stale. But it is a static per-transport string, so a
1027
+ * white-labelled or multiplexing gateway fronting several upstreams leaves
1028
+ * it unclaimed by any vendor.
1029
+ * 2. `budget.vendor` — which the driver resolved from the label where it could,
1030
+ * and otherwise from the proxy's own `vendor` field on the 402. It is
1031
+ * therefore NOT simply `vendorLabel` normalised, and the two can disagree;
1032
+ * that fallback is the only attribution on offer for the gateway case above.
1033
+ * 3. `vendorHint` — the bus detail's top-level vendor, i.e. the driver's
1034
+ * last-resolved provider. Last resort because it CAN be stale: an
1035
+ * orchestrated turn classifies against the registry default, a provider the
1036
+ * chat driver may never have resolved, so its last-resolved provider there is
1037
+ * the previous turn's vendor or nothing at all.
1038
+ *
1039
+ * A wall that names no recognised vendor falls back to the vendor-agnostic
1040
+ * block — fail-safe, and identical to the pre-per-vendor behaviour.
1041
+ *
1042
+ * **`otherVendorAvailable: false` is server-known truth and outranks every
1043
+ * inference made here.** The proxy meters the pots, so only it can say whether
1044
+ * anything else has headroom; this element can only observe which vendors the
1045
+ * registry can REACH, which says nothing about their remaining spend. So when
1046
+ * the proxy says no, every other *budgeted* vendor is walled in the same pass.
1047
+ * That is what makes `blocked` derive true — locking the composer on the first
1048
+ * response instead of after a second doomed turn — and what empties the "free"
1049
+ * set the banner would otherwise have advised switching to.
1050
+ *
1051
+ * The sweep runs over `BUDGETED_VENDORS`, deliberately **not** over
1052
+ * {@link FoundationAiAssistant.reachableVendors}. Reachability is loaded
1053
+ * asynchronously (`activateSession` kicks off `loadProviderStatuses()` and does
1054
+ * not await it), so a wall landing before the statuses resolve would have swept
1055
+ * an empty set — silently discarding the one fact on the 402 the client cannot
1056
+ * re-derive, with nothing to re-run it when the statuses arrived. Worse, it let
1057
+ * the verdict effectively un-latch: the single wall derived `blocked` only
1058
+ * while the reachable set was empty, so the moment the statuses landed the
1059
+ * composer came back to life against a budget the proxy had already said was
1060
+ * gone. Sweeping the metered vendor list instead makes the verdict independent
1061
+ * of load order and of registry membership, which is exactly what it is: a
1062
+ * statement about the proxy's pots, not about this user's registry.
1063
+ *
1064
+ * Walling a vendor the registry cannot reach costs nothing: `blocked` only asks
1065
+ * whether every REACHABLE vendor is walled, and the banner reads
1066
+ * {@link FoundationAiAssistant.relevantBlockedVendors}, which filters the walls
1067
+ * back down to the reachable set before naming any of them.
1068
+ *
1069
+ * One boundary remains on the sweep: it walls only vendors the proxy meters,
1070
+ * enforced structurally by iterating `BUDGETED_VENDORS` itself rather than
1071
+ * filtering a wider set through a predicate. Chrome runs on-device with no pot
1072
+ * to exhaust, so "no other vendor has budget" is not a statement about it, and
1073
+ * "Switch to Chrome to keep going." stays honest advice.
1074
+ *
1075
+ * The sweep runs last but sits OUTSIDE the per-vendor idempotence guard, and
1076
+ * both halves of that matter. Last, so the vendor that actually refused this
1077
+ * turn heads the wall order the multi-vendor banner reads. Outside the guard,
1078
+ * because the verdict can arrive on a LATER 402 for a vendor that is already
1079
+ * walled — turn 1 walls Anthropic while Gemini still has headroom, turn 2 walls
1080
+ * it again and reports that Gemini has since gone too — and an early return
1081
+ * would drop exactly the news the second turn was there to deliver.
1082
+ *
1083
+ * @param reason - the turn's failure reason; anything but `'budget-exhausted'` is ignored.
1084
+ * @param ref - session store to write through; defaults to the live one. `send()`
1085
+ * passes the ref it captured before its awaits, since a lifecycle event during the
1086
+ * turn may already have cleared `_sessionRef`.
1087
+ * @param budget - what the 402 reported: figures when the proxy sent any, the
1088
+ * refusing vendor, and its `otherVendorAvailable` verdict.
1089
+ * @param vendorHint - the `tool-loop-end` detail's top-level vendor, used only
1090
+ * when the budget payload names none.
1091
+ *
1092
+ * @internal
1093
+ */
1094
+ private latchBlockedFrom(
1095
+ reason?: TurnFailureReason,
1096
+ ref = this._sessionRef,
1097
+ budget?: Extract<ChatDriverResult, { reason: 'done' }>['budget'],
1098
+ vendorHint?: AIProviderType,
1099
+ ): void {
1100
+ if (reason !== 'budget-exhausted') return;
1101
+ const vendor = vendorTypeOfLabel(budget?.vendorLabel) ?? budget?.vendor ?? vendorHint;
1102
+ if (!vendor || vendor === 'none') {
1103
+ if (!this.blocked) {
1104
+ ref?.actions.aiAssistant.setBlocked({ blocked: true, reason: formatBlockedReason(budget) });
1105
+ }
1106
+ } else if (!this.isVendorBlocked(vendor) || this.isVendorSwept(vendor)) {
1107
+ // The idempotence guard protects a host-supplied reason from being
1108
+ // overwritten by this latch's boilerplate — but a SWEPT wall cannot carry
1109
+ // one (the sweep writes no reason, and any host call clears the swept
1110
+ // mark), so upgrading it on a first-hand refusal clobbers nothing and
1111
+ // gains the vendor its own figures plus a place in the early-window
1112
+ // banner (see `relevantBlockedVendors`).
1113
+ if (this.reachableVendors.length === 0) {
1114
+ // Not fatal — `blocked` still derives to true, so the UI is correct — but
1115
+ // the host gets no per-vendor benefit and would otherwise have no signal.
1116
+ logger.warn(
1117
+ `FoundationAiAssistant: ${vendor} hit its AI budget, but no registered provider counts ` +
1118
+ 'as reachable, so per-vendor blocking degrades to blocking everything. Two causes: no ' +
1119
+ 'provider reports a status (implement AIProvider.getStatus()), or every provider that ' +
1120
+ 'does is chat-less and so cannot serve a turn (implement chat() on at least one).',
1121
+ );
1122
+ }
1123
+ ref?.actions.aiAssistant.setVendorBlocked({
1124
+ vendor,
1125
+ blocked: true,
1126
+ reason: formatBlockedReason(budget, vendor),
1127
+ });
1128
+ }
1129
+ // Last, so the vendor that actually refused this turn heads the wall order the
1130
+ // multi-vendor banner reads — and unconditionally, NOT under the per-vendor
1131
+ // idempotence guard above, because the verdict can arrive on a later 402 for a
1132
+ // vendor that is already walled.
1133
+ if (budget?.otherVendorAvailable !== false) return;
1134
+ // Over the metered vendor list, NOT the reachable set: the statuses load
1135
+ // asynchronously, so a reachability-scoped sweep dropped the verdict entirely
1136
+ // when the wall beat them home. `relevantBlockedVendors` decides what the
1137
+ // banner may NAME — reachability-filtered when the statuses are in, and
1138
+ // refusals-only while they are not, which is what `swept: true` records.
1139
+ for (const other of BUDGETED_VENDORS) {
1140
+ if (other === vendor || this.isVendorBlocked(other)) continue;
1141
+ // No reason: the slice's "an omitted reason keeps the existing explanation"
1142
+ // rule applies, and there are no figures for this vendor — only the proxy's
1143
+ // word that it has nothing left. `swept: true` records exactly that
1144
+ // provenance, so the unknown-reachability banner can decline to name it.
1145
+ ref?.actions.aiAssistant.setVendorBlocked({ vendor: other, blocked: true, swept: true });
1146
+ }
1147
+ }
1148
+
1149
+ /**
1150
+ * Block or unblock the assistant, optionally with custom banner copy.
1151
+ * Equivalent to the {@link FoundationAiAssistant.blocked} setter, plus the
1152
+ * reason in one atomic write.
1153
+ *
1154
+ * Blocking writes the **vendor-agnostic** block — what a host with one budget
1155
+ * pot means — and does not populate
1156
+ * {@link FoundationAiAssistant.blockedVendors}. Unblocking clears the
1157
+ * per-vendor walls as well, so a host asserting "the wall is gone" after its
1158
+ * own pre-flight cannot be silently overruled by a driver latch it never saw.
1159
+ *
1160
+ * @beta
1161
+ */
1162
+ setBlocked(blocked: boolean, reason?: string | null): void {
1163
+ this._sessionRef?.actions.aiAssistant.setBlocked({ blocked, reason });
1164
+ }
1165
+
1166
+ /**
1167
+ * Copy shown in the blocked banner, in ascending specificity:
1168
+ *
1169
+ * 1. the host's `blockedReason` — a whole-banner override, unchanged;
1170
+ * 2. copy composed from the walled vendors (their per-vendor reasons when set,
1171
+ * otherwise their names) plus the action that is actually available;
1172
+ * 3. the default budget-exhaustion message.
1173
+ *
1174
+ * The action clause is computed here rather than stored, because whether
1175
+ * "switch vendor" or "contact your administrator" is honest depends on whether
1176
+ * another reachable vendor still has headroom — which changes when the registry
1177
+ * changes, long after the wall was latched. Telling a user to switch to a
1178
+ * vendor that is also exhausted is worse than saying nothing.
1179
+ *
1180
+ * The `free` set is a client-side inference — "reachable and not known to be
1181
+ * walled" — and it is only ever allowed to be one. Where the proxy has told us
1182
+ * otherwise (`otherVendorAvailable: false`) the latch has already walled those
1183
+ * vendors, so they are not in `free` here and no "switch to X" clause can be
1184
+ * composed from them. Both lists are filtered by reachability, so the copy
1185
+ * names only vendors this user's registry can actually route to.
1186
+ *
1187
+ * **Per-vendor copy is composed however many vendors are walled**, which is
1188
+ * what {@link FoundationAiAssistant.setVendorBlocked} and
1189
+ * `docs/migration-GENC-1464.md` both promise. It previously reached only the
1190
+ * single-vendor branch, so a host that had carefully set copy for each of its
1191
+ * vendors watched all of it vanish the moment a second one walled — replaced by
1192
+ * generic copy, at the exact moment the situation got worse.
1193
+ *
1194
+ * The compact "AI usage limits are reached for A and B." list is kept for the
1195
+ * case it was written for: NO walled vendor carries copy, so a statement per
1196
+ * vendor would just repeat one boilerplate sentence per name. As soon as any of
1197
+ * them does carry copy, the branch lists one statement per vendor instead —
1198
+ * falling back to that same boilerplate for the ones that have none, so the
1199
+ * sentence set stays complete rather than silently naming a subset.
1200
+ *
1201
+ * @internal
1202
+ */
1203
+ @volatile
1204
+ get effectiveBlockedReason(): string {
1205
+ if (this.blockedReason) return this.blockedReason;
1206
+
1207
+ const walled = this.relevantBlockedVendors;
1208
+ if (walled.length === 0) return DEFAULT_BUDGET_EXHAUSTED_MESSAGE;
1209
+
1210
+ const free = this.reachableVendors.filter((v) => !walled.includes(v));
1211
+ const action = free.length
1212
+ ? `Switch to ${formatVendorList(free)} to keep going.`
1213
+ : walled.length > 1
1214
+ ? RAISE_LIMITS_ACTION
1215
+ : RAISE_LIMIT_ACTION;
1216
+
1217
+ const reasons = this._sessionRef?.store.aiAssistant.blockedVendorReasons;
1218
+ const statementFor = (v: AIProviderType) =>
1219
+ reasons?.[v] ?? `${vendorDisplayName(v)}'s AI usage limit is reached.`;
1220
+
1221
+ if (walled.length === 1) return `${statementFor(walled[0])} ${action}`;
1222
+ // Several walled vendors carry several sets of figures, which do not fit one
1223
+ // sentence. With no per-vendor copy to preserve, name them in a list rather
1224
+ // than repeat the same boilerplate sentence per vendor.
1225
+ if (!walled.some((v) => reasons?.[v])) {
1226
+ return `AI usage limits are reached for ${formatVendorList(walled)}. ${action}`;
1227
+ }
1228
+ return `${walled.map(statementFor).join(' ')} ${action}`;
1229
+ }
1230
+
1231
+ /**
1232
+ * Copy the driver writes into the TRANSCRIPT when a turn hits the budget wall.
1233
+ *
1234
+ * A host-set `blockedReason` still wins, so a white-labelled host does not read
1235
+ * its own explanation in the banner and the shipped default directly below it —
1236
+ * that is the whole reason the driver takes this at all.
1237
+ *
1238
+ * What it deliberately is NOT is
1239
+ * {@link FoundationAiAssistant.effectiveBlockedReason}. That getter
1240
+ * composes advice — `"…Switch to Gemini to keep going."` — which is true only
1241
+ * while that vendor has headroom, and the transcript is a permanent record. The
1242
+ * driver reads this once at CONSTRUCTION, and `getOrCreateDriver` keys on the
1243
+ * agents list, so an agents swap *after* a wall re-runs `createDriver` and would
1244
+ * freeze that sentence into every later turn's bubble. Reading the latch's own
1245
+ * copy instead is structurally incapable of carrying the advice: the only
1246
+ * writer of `blockedReason` is the vendor-agnostic branch of
1247
+ * `latchBlockedFrom`, whose `formatBlockedReason(budget)` form has no switch
1248
+ * clause. Per-vendor copy lives in `blockedVendorReasons` and reaches the
1249
+ * banner alone.
1250
+ */
1251
+ private get transcriptBudgetExhaustedMessage(): string {
1252
+ return this.blockedReason ?? DEFAULT_BUDGET_EXHAUSTED_MESSAGE;
1253
+ }
1254
+
607
1255
  /**
608
1256
  * Name of the agent the user has pinned via the agent picker. `null` means
609
1257
  * automatic routing (Auto). Persisted on the session store, so it survives
@@ -892,9 +1540,9 @@ export class FoundationAiAssistant extends GenesisElement {
892
1540
  }
893
1541
 
894
1542
  /**
895
- * Spend for `projectKey` that predates the current transcript, resolved once per project
896
- * and memoised (`_bankedFor`) so it cannot drift mid-session as the row it came from is
897
- * rewritten by our own upserts.
1543
+ * Spend for `projectKey` that predates the current transcript, resolved once per SESSION and
1544
+ * shared by every element instance wired to it (see `banked-usage-baselines`), so it cannot
1545
+ * drift as the row it came from is rewritten by our own upserts.
898
1546
  *
899
1547
  * The two cases turn on whether the transcript is authoritative for this project:
900
1548
  *
@@ -904,28 +1552,77 @@ export class FoundationAiAssistant extends GenesisElement {
904
1552
  * - **Transcript starts empty**: nothing on screen accounts for the previous total, so the
905
1553
  * whole of it becomes banked. Without this the next turn would rewrite the row downwards
906
1554
  * to just that turn, losing the project's earlier spend.
1555
+ *
1556
+ * The baseline is deliberately NOT element state. This element is remounted repeatedly inside
1557
+ * a single session (the host re-rendering its layout, popping out, docking) and a fresh
1558
+ * instance re-deriving would take the second branch against rows that already hold the live
1559
+ * transcript — banking the session as its own baseline. Keying on the session instead means a
1560
+ * remount inherits the baseline that transcript was paired with.
907
1561
  */
908
1562
  private bankedUsageFor(projectKey: string): AggregateUsage {
909
- if (this._bankedFor === projectKey) return this._bankedUsage;
1563
+ const resolved = getBankedBaseline(projectKey);
1564
+ if (resolved) return resolved;
910
1565
  const existing = this.costSessionHistory.find((r) => r.projectKey === projectKey);
911
1566
  // `persistenceActive` is what decides whether the transcript speaks for the project's
912
1567
  // history: it is on only when a provider is wired AND the user is remembering the chat.
913
- this._bankedUsage = resolveBankedUsage(existing, this.persistenceActive);
914
- this._bankedFor = projectKey;
915
- return this._bankedUsage;
1568
+ const banked = resolveBankedUsage(existing, this.persistenceActive);
1569
+ setBankedBaseline(projectKey, banked);
1570
+ return banked;
916
1571
  }
917
1572
 
918
1573
  /**
919
- * Discard the banked figure for when the spend it stands for has been deliberately
920
- * thrown away (the user clearing history, or deleting this project's row).
1574
+ * Re-baseline this session against an emptied transcript: what came before, plus what the
1575
+ * transcript being discarded proved. `discarded` must be read BEFORE the live figures are
1576
+ * reset, since that is the only record of the latter.
1577
+ *
1578
+ * Not the same as dropping the baseline. Dropping it re-derives through `persistenceActive`,
1579
+ * and with persistence ON that carries the row's *old* banked figure forward — discarding
1580
+ * every turn between the last baseline and the clear. The transcript is gone either way, so
1581
+ * the branch that reads it as authoritative no longer applies.
921
1582
  *
922
- * NOT for reloads. A reload re-reads rows that already include our own upserts, so
923
- * re-deriving from them would fold the live session into its own baseline; only a genuine
924
- * project change should re-derive, which `bankedUsageFor`'s per-project memo handles.
1583
+ * Derived from the memoised baseline and the live figure rather than from the project's row,
1584
+ * because a row is only as current as the last `finalizeCostSession` which skips its write
1585
+ * while the ledger is unloaded, and while the session has no usage yet.
925
1586
  */
926
- private resetBankedUsage(): void {
927
- this._bankedFor = undefined;
928
- this._bankedUsage = emptyUsage();
1587
+ private rebaselineOnClearedTranscript(key: string, discarded: AggregateUsage): void {
1588
+ // Already resolved for this session? Then the new baseline is fully determined without
1589
+ // consulting the ledger at all — `bankedUsageFor` would short-circuit on this same value — so
1590
+ // answer before the guard below, which would otherwise discard a figure that is both correct
1591
+ // and independent of the rows. Losing it costs real spend: with a row at `usage: 120,
1592
+ // banked: 90` and 30 on screen, a clear during a reload would drop the memoised 90, and the
1593
+ // next turn would re-derive `row.banked` and rewrite the row BACKWARDS from 120 to 95.
1594
+ const resolved = getBankedBaseline(key);
1595
+ if (resolved) {
1596
+ setBankedBaseline(key, addUsage(resolved, discarded));
1597
+ return;
1598
+ }
1599
+
1600
+ // Nothing memoised, so a baseline can only come from the rows — and a stamped one is STICKY
1601
+ // (`bankedUsageFor` short-circuits on any stored entry, and a zero usage is a *resolved* value
1602
+ // there, not "unresolved"). So unless the rows are genuinely known, do not guess:
1603
+ //
1604
+ // - `enabled` false: `reloadCostSessionHistory` sets `_costHistoryLoaded` TRUE over a
1605
+ // deliberately empty list, meaning "nothing will be loaded" rather than "rows are known".
1606
+ // The flag alone therefore is not enough. Reachable because `enabled` is
1607
+ // `cost?.enabled === true` — false for an unbound `chatConfig`, and for any host resolving
1608
+ // it from an async setting, exactly as `chatConfigChanged` already expects.
1609
+ // - Provider read in flight: the list is emptied and the flag cleared synchronously, on
1610
+ // connect and again on every `chatConfig` rebind.
1611
+ // - Unreadable: the rows we hold are a fallback, not the ledger.
1612
+ //
1613
+ // In all three, pinning would bury this project's real total the moment it arrived — a later
1614
+ // load does NOT invalidate baselines (deliberately, see `reloadCostSessionHistory`), so the
1615
+ // next write would replace the row off the pinned figure and lose everything before it.
1616
+ //
1617
+ // Dropping instead leaves the next write to re-derive from rows that actually arrived. It
1618
+ // under-banks `discarded` in that window — a bounded loss, and what every clear did before
1619
+ // this method existed. Nothing is written while disabled, so there is no banked value to
1620
+ // preserve in that case either.
1621
+ if (!this.resolvedCostHistory.enabled || !this._costHistoryLoaded || this._ledgerUnreadable) {
1622
+ deleteBankedBaseline(key);
1623
+ return;
1624
+ }
1625
+ setBankedBaseline(key, addUsage(this.bankedUsageFor(key), discarded));
929
1626
  }
930
1627
 
931
1628
  showConfirmationDialog(
@@ -950,24 +1647,26 @@ export class FoundationAiAssistant extends GenesisElement {
950
1647
 
951
1648
  /** Remove one entry from persisted build history. */
952
1649
  removeCostSessionFromHistory(id: string): void {
953
- // Deleting the active project's row discards its banked spend by intent, so drop the
954
- // memo too — otherwise the next turn would rewrite the row we just removed, restoring
955
- // the total the user asked to be rid of.
1650
+ // Deleting a row discards its banked spend by intent, so drop the baseline too —
1651
+ // otherwise the next turn would rewrite the row we just removed, restoring the total the
1652
+ // user asked to be rid of.
956
1653
  //
957
- // Resolve the row first: `id` is a row id while `_bankedFor` is a projectKey. They match
958
- // only for rows this element wrote (`finalizeCostSession` sets `id: projectKey`); a row from
959
- // a host provider can carry any id, and comparing across the two namespaces would silently
960
- // skip the reset.
1654
+ // Resolve the row first: `id` is a row id while baselines are keyed by projectKey. They
1655
+ // match only for rows this element wrote (`finalizeCostSession` sets `id: projectKey`); a
1656
+ // row from a host provider can carry any id, and deleting by the wrong namespace would
1657
+ // silently leave the baseline in place.
961
1658
  const removed = this.costSessionHistory.find((record) => record.id === id);
962
- if (removed && this._bankedFor === removed.projectKey) this.resetBankedUsage();
1659
+ if (removed) deleteBankedBaseline(removed.projectKey);
963
1660
  this.persistCostHistory(this.costSessionHistory.filter((record) => record.id !== id));
964
1661
  }
965
1662
 
966
1663
  /** Clear all persisted build history for this assistant scope. */
967
1664
  clearCostSessionHistory(): void {
968
- // Every row is gone, so nothing is banked any more — without this the active project's
969
- // next turn would resurrect its pre-clear total.
970
- this.resetBankedUsage();
1665
+ // Every row is gone, so nothing is banked any more — without this the next turn would
1666
+ // resurrect the pre-clear total. Dropped per row rather than for the active session alone,
1667
+ // so a project whose row was cleared while another session was displaying it does not keep
1668
+ // a baseline pointing at spend that no longer exists anywhere.
1669
+ for (const record of this.costSessionHistory) deleteBankedBaseline(record.projectKey);
971
1670
  // Provider-backed: write an empty ledger through. The `localStorage` path instead
972
1671
  // removes its key outright rather than leaving an empty array behind.
973
1672
  if (this.costHistoryProvider()) {
@@ -1187,6 +1886,8 @@ export class FoundationAiAssistant extends GenesisElement {
1187
1886
  private driverCleanup?: () => void;
1188
1887
  private loadingTimer: ReturnType<typeof setTimeout> | undefined;
1189
1888
  private unsubBus?: () => void;
1889
+ /** Unsubscribe handle for the `tool-loop-end` budget latch (GENC-1464). */
1890
+ private _unsubBudgetLatch?: () => void;
1190
1891
  /** Unsubscribe handle for the provider-registry change listener (observable registries only). */
1191
1892
  private unsubProviderRegistry?: () => void;
1192
1893
  /** Unsubscribe handle for {@link (AssistantAppSettingsProvider:interface).subscribe}. */
@@ -1198,10 +1899,9 @@ export class FoundationAiAssistant extends GenesisElement {
1198
1899
  * (same key) from a project switch (key already flipped) — see `syncActiveCostSessionTitle`.
1199
1900
  */
1200
1901
  private _activeCostSessionKey?: string;
1201
- /** Memoised pre-transcript spend for `_bankedFor` see `bankedUsageFor`. */
1202
- private _bankedUsage: AggregateUsage = emptyUsage();
1203
- /** Project key `_bankedUsage` was resolved for; `undefined` means "not yet resolved". */
1204
- private _bankedFor: string | undefined;
1902
+ // NOTE: the pre-transcript ("banked") spend is deliberately NOT held here. It is keyed by
1903
+ // session in `banked-usage-baselines` so the many element instances a single session sees —
1904
+ // layout re-renders, popout, docking share one baseline. See `bankedUsageFor`.
1205
1905
  /**
1206
1906
  * Whether the row list reflects storage yet. Gates cost writes so a project's banked
1207
1907
  * spend is never derived from a ledger that simply hasn't arrived.
@@ -1570,6 +2270,7 @@ export class FoundationAiAssistant extends GenesisElement {
1570
2270
  maxFoldOperations: agent.maxFoldOperations,
1571
2271
  maxTurnSnapshots: agent.maxTurnSnapshots,
1572
2272
  activityBus: agenticActivityBus,
2273
+ budgetExhaustedMessage: this.transcriptBudgetExhaustedMessage,
1573
2274
  });
1574
2275
  }
1575
2276
 
@@ -1579,6 +2280,7 @@ export class FoundationAiAssistant extends GenesisElement {
1579
2280
  maxTurnSnapshots: agent.maxTurnSnapshots,
1580
2281
  sessionKey: this.getStateKey() ?? '',
1581
2282
  activityBus: agenticActivityBus,
2283
+ budgetExhaustedMessage: this.transcriptBudgetExhaustedMessage,
1582
2284
  });
1583
2285
  }
1584
2286
 
@@ -1942,6 +2644,19 @@ export class FoundationAiAssistant extends GenesisElement {
1942
2644
  });
1943
2645
  }
1944
2646
  this.wireAppSettingsProvider();
2647
+ // Latch the backend block off the activity bus (GENC-1464). This is the primary
2648
+ // seam: it fires for a turn this element did not start, for a sub-agent's
2649
+ // wall (the child inherits the parent's bus and publishes its own
2650
+ // `tool-loop-end`), and it writes through whichever element is connected NOW
2651
+ // rather than the one that happened to call `send()`. Re-subscribed per
2652
+ // connect (docking/popout remounts); balanced in `disconnectedCallback`.
2653
+ this._unsubBudgetLatch?.();
2654
+ this._unsubBudgetLatch = agenticActivityBus.subscribe('tool-loop-end', (d) =>
2655
+ // Pass the figures through: this seam wins the latch for an in-loop wall (the
2656
+ // common case), so dropping them here would render the generic banner copy in
2657
+ // exactly the path `ChatDriverResult.budget` was widened to serve.
2658
+ this.latchBlockedFrom(d?.failureReason, undefined, d?.budget, d?.vendor),
2659
+ );
1945
2660
  if (this.messagesEl) {
1946
2661
  this._scrollListener = () => {
1947
2662
  this._userScrolledAway =
@@ -2003,6 +2718,10 @@ export class FoundationAiAssistant extends GenesisElement {
2003
2718
  // keeping the high-water `lastEventIndex` would then skip every event of the
2004
2719
  // resumed session (GENC-1351 §5.12 / #9). Clear (same-session) still uses reset.
2005
2720
  deleteDiagnosticsCursorsFor(oldKey);
2721
+ // The cost baseline is paired with the transcript in the store just disposed, so it goes
2722
+ // with it (GENC-1475). A later switch back re-restores from the provider — or starts empty
2723
+ // where it does not — and re-derives from the ledger rows accordingly.
2724
+ deleteBankedBaseline(oldKey);
2006
2725
  clearMetaSession(oldKey);
2007
2726
  // Activate the incoming session. Swapping the observable `_sessionRef` re-points
2008
2727
  // every store-backed getter binding at the new store; `activateSession` rebuilds
@@ -2048,6 +2767,8 @@ export class FoundationAiAssistant extends GenesisElement {
2048
2767
  this.unwireDriver();
2049
2768
  this.unsubBus?.();
2050
2769
  this.unsubBus = undefined;
2770
+ this._unsubBudgetLatch?.();
2771
+ this._unsubBudgetLatch = undefined;
2051
2772
  this.unsubProviderRegistry?.();
2052
2773
  this.unsubProviderRegistry = undefined;
2053
2774
  this.unwireAppSettingsProvider();
@@ -2610,9 +3331,16 @@ export class FoundationAiAssistant extends GenesisElement {
2610
3331
  } catch (e) {
2611
3332
  logger.error('Session clear: agent serialize() failed:', e);
2612
3333
  }
3334
+ // Read BEFORE `resetSession()` zeroes it: this is what the transcript about to be discarded
3335
+ // proved, and nothing else records it. Banking it is what stops the next turn rewriting the
3336
+ // project's row down to itself and losing the spend up to the clear (GENC-1475).
3337
+ const discarded = this.sessionUsage;
2613
3338
  if (this.driver) this.teardownDriver(key);
2614
3339
  this._sessionRef?.actions.aiAssistant.resetSession();
2615
- if (key) this.rebuildDriver(key);
3340
+ if (key) {
3341
+ this.rebaselineOnClearedTranscript(key, discarded);
3342
+ this.rebuildDriver(key);
3343
+ }
2616
3344
  // Restore-core is owned by the shared per-session persister (GENC-1351 §5.10):
2617
3345
  // it drops the snapshot + resets the carry-forward cache. Diagnostics is
2618
3346
  // append-only and handled separately below.
@@ -2734,10 +3462,35 @@ export class FoundationAiAssistant extends GenesisElement {
2734
3462
  return this.settingsCostCurrentSlotted.length > 0;
2735
3463
  }
2736
3464
 
3465
+ /**
3466
+ * Whether the build-history section has anything in it — the built-in row list, or a host's own
3467
+ * markup in the `settings-cost-history` slot.
3468
+ *
3469
+ * Slotted content is checked FIRST, ahead of `enabled`. That flag governs the *built-in* ledger:
3470
+ * it gates the row writes, the reload, and the lifetime sum — and it defaults to `false`
3471
+ * (`cost?.enabled === true`), while the Usage tab itself shows for `showCost`/`showTokens`, which
3472
+ * default true. So a host can legitimately render its own build history into the slot and never
3473
+ * opt into our `localStorage` ledger. Short-circuiting on `enabled` above the slot check hid that
3474
+ * host's markup outright, since the slot is the only thing in the container.
3475
+ */
2737
3476
  @volatile
2738
3477
  get settingsCostHistorySectionVisible(): boolean {
3478
+ if (this.settingsCostHistorySlotted.length > 0) return true;
2739
3479
  if (!this.resolvedCostHistory.enabled) return false;
2740
- return this.costSessionHistory.length > 0 || this.settingsCostHistorySlotted.length > 0;
3480
+ return this.costSessionHistory.length > 0;
3481
+ }
3482
+
3483
+ /**
3484
+ * Whether the "Build history" heading has anything under it.
3485
+ *
3486
+ * Broader than {@link FoundationAiAssistant.settingsCostHistorySectionVisible} because the
3487
+ * heading also covers the lifetime total, which renders before the first row exists (rows are
3488
+ * written as spend accrues, the lifetime section only needs history switched on). Gating the
3489
+ * heading on the rows alone left that total sitting under nothing.
3490
+ */
3491
+ @volatile
3492
+ get settingsCostHistoryHeadingVisible(): boolean {
3493
+ return this.settingsCostHistorySectionVisible || this.settingsCostLifetimeVisible;
2741
3494
  }
2742
3495
 
2743
3496
  /** Whether the built-in Usage tab summary block has anything to show. */
@@ -2995,6 +3748,9 @@ export class FoundationAiAssistant extends GenesisElement {
2995
3748
  */
2996
3749
  @volatile
2997
3750
  get effectivePlaceholder(): string {
3751
+ // The block outranks the agent pin: while blocked the composer is disabled
3752
+ // anyway, so naming the pinned agent would only imply a send is possible.
3753
+ if (this.blocked) return BLOCKED_PLACEHOLDER;
2998
3754
  if (this.pinnedAgentName) return `Message ${this.pinnedAgentName}...`;
2999
3755
  return this.placeholder;
3000
3756
  }
@@ -3389,6 +4145,10 @@ export class FoundationAiAssistant extends GenesisElement {
3389
4145
  }
3390
4146
 
3391
4147
  handleSuggestionClick(suggestion: string) {
4148
+ // Belt-and-braces with the template gate that hides the chips while blocked:
4149
+ // `send()` refuses, but `inputValue` would already have been written, leaving
4150
+ // the chip's text stranded in a disabled textarea the user cannot clear.
4151
+ if (this.sendBlocked) return;
3392
4152
  this.inputValue = suggestion;
3393
4153
  this.send();
3394
4154
  }
@@ -3416,7 +4176,7 @@ export class FoundationAiAssistant extends GenesisElement {
3416
4176
  */
3417
4177
  async submitMessage(input: { text?: string; files?: File[] }): Promise<SubmitMessageResult> {
3418
4178
  if (this.sendBlocked) {
3419
- return { ok: false, errors: ['Assistant is busy'] };
4179
+ return { ok: false, errors: [this.sendRefusalReason()] };
3420
4180
  }
3421
4181
 
3422
4182
  let nextAttachments: ChatAttachment[] = [];
@@ -3430,7 +4190,7 @@ export class FoundationAiAssistant extends GenesisElement {
3430
4190
  // (Cast widens through TS's narrowing of `this.state` from the earlier
3431
4191
  // early-return; the getter can return a different value across an await.)
3432
4192
  if (this.sendBlocked) {
3433
- return { ok: false, errors: ['Assistant is busy'] };
4193
+ return { ok: false, errors: [this.sendRefusalReason()] };
3434
4194
  }
3435
4195
  if (errors.length) {
3436
4196
  this.attachmentErrors = errors;
@@ -3462,6 +4222,22 @@ export class FoundationAiAssistant extends GenesisElement {
3462
4222
  return;
3463
4223
  }
3464
4224
 
4225
+ // A guaranteed 402. This runs from the post-turn `finally` (the turn that
4226
+ // just latched), from `connectedCallback` (a pop-in against a blocked store),
4227
+ // and from the `pinnedAgentName` setter — which resets `suggestionsState`
4228
+ // first, defeating the already-fetched guard below. So without this a blocked
4229
+ // session still fires one doomed request per turn, per pop-in and per pin
4230
+ // change, each one burning a `suggestions.failed` meta event and parking a
4231
+ // raw transport-error string in `suggestionsState.message`.
4232
+ //
4233
+ // Resolved against the registry DEFAULT, not the whole composer gate: both
4234
+ // suggestion paths call `providerRegistry.default()`, so under partial
4235
+ // exhaustion this is knowable exactly — and suggestions stay available when
4236
+ // the default vendor is the one with headroom.
4237
+ if (this.suggestionsBlocked) {
4238
+ return;
4239
+ }
4240
+
3465
4241
  if (suggestionsConfig.behavior === 'initial' && this.messages.length > 0) {
3466
4242
  return;
3467
4243
  }
@@ -3551,7 +4327,16 @@ export class FoundationAiAssistant extends GenesisElement {
3551
4327
  ? `${input}\n\n*Attached: ${pendingAttachments.map((a) => a.name).join(', ')}*`
3552
4328
  : input;
3553
4329
  try {
3554
- await this.driver?.sendMessage(displayInput, pendingAttachments);
4330
+ const result = await this.driver?.sendMessage(displayInput, pendingAttachments);
4331
+ // Latch the backend block the moment the driver reports it, so the composer
4332
+ // locks without waiting on the host's next pre-flight. The bus subscription
4333
+ // in `connectedCallback` covers most walls; this covers the one it cannot —
4334
+ // a wall hit during multi-agent classification, where no tool loop ran and
4335
+ // so no `tool-loop-end` was published. `latchBlockedFrom` is idempotent, so
4336
+ // the two seams overlapping is harmless.
4337
+ if (result?.reason === 'done') {
4338
+ this.latchBlockedFrom(result.failureReason, capturedSessionRef, result.budget);
4339
+ }
3555
4340
  } finally {
3556
4341
  this.stopLoadingTimer();
3557
4342
  this._pendingSendPrompt = undefined;