@genesislcap/ai-assistant 15.7.0 → 15.7.2

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.
@@ -305,9 +305,9 @@ export const settingsModalStyles = css`
305
305
  }
306
306
 
307
307
  /*
308
- * Deliberately quieter than the live block: no pulsing badge and no accent, so the
309
- * eye still lands on what is being built now. It leads only because it is the wider
310
- * figure, not because it is the more urgent one.
308
+ * Deliberately quieter than the live block: no pulsing badge and no accent, so the eye lands
309
+ * on what is being built now which is why that block leads the tab and this one follows,
310
+ * under the history heading whose rows it totals.
311
311
  */
312
312
  .settings-lifetime-usage-top {
313
313
  display: flex;
@@ -490,7 +490,14 @@ export const settingsModalStyles = css`
490
490
 
491
491
  .settings-token-bucket {
492
492
  display: flex;
493
- min-width: 0;
493
+
494
+ /*
495
+ * min-content (not 0) so a bucket cannot be shrunk narrower than its own unbreakable label.
496
+ * With the label set to nowrap, a zero minimum would overflow it into the next column instead
497
+ * of wrapping — so the container's flex-wrap takes over and moves a bucket to a second row,
498
+ * which is the degradation we want when the modal is dragged narrow.
499
+ */
500
+ min-width: min-content;
494
501
  flex-direction: column;
495
502
  gap: 2px;
496
503
  }
@@ -501,6 +508,15 @@ export const settingsModalStyles = css`
501
508
  text-transform: uppercase;
502
509
  letter-spacing: 0.06em;
503
510
  color: var(--neutral-foreground-hint);
511
+
512
+ /*
513
+ * One line, always. The rate marker is a separate inline box after collapsible whitespace, so
514
+ * a wrappable label gives it a break opportunity of its own — in a narrow column it orphaned
515
+ * onto line 2, which also pushed that bucket's value a line below the other three and broke
516
+ * the row of figures. nowrap removes every break opportunity in the label, the space before
517
+ * the marker included, so no glue character is needed.
518
+ */
519
+ white-space: nowrap;
504
520
  }
505
521
 
506
522
  .settings-token-bucket-value {
@@ -510,13 +526,24 @@ export const settingsModalStyles = css`
510
526
  }
511
527
 
512
528
  /*
513
- * Cache reads bill at a fraction of the uncached input rate, and in an agentic
514
- * session they are usually the largest bucket by a wide margin. Muted so the biggest
515
- * number on the row doesn't read as the dominant cost driver when it is the cheapest.
529
+ * The price-direction marker on a cache bucket's label down for reads (a fraction of the
530
+ * uncached input rate), up for writes (a premium over it). Three tiers, so a bucket with no
531
+ * marker is the reference rate rather than an unlabelled fourth case.
532
+ *
533
+ * Carried by the label rather than the value, which is what this used to do: cache reads are
534
+ * usually the largest bucket by a wide margin in an agentic session, so the value was muted to
535
+ * stop the biggest number reading as the dominant cost driver. That priced the treatment to the
536
+ * wrong thing — a dimmed 0 (every Gemini cache write) looked disabled next to a normal 0, and a
537
+ * rate is a property of the bucket, not of this turn's figure.
538
+ *
539
+ * Sized down and nudged up rather than tinted: the label is already the hint colour, so a
540
+ * dimmer marker would vanish and a brighter one would out-shout the word it qualifies.
516
541
  */
517
- .settings-token-bucket.is-discounted .settings-token-bucket-value {
518
- font-weight: 500;
519
- color: var(--neutral-foreground-hint);
542
+ .settings-token-bucket-rate {
543
+ font-size: 8px;
544
+ line-height: 1;
545
+ vertical-align: 0.15em;
546
+ letter-spacing: 0;
520
547
  }
521
548
 
522
549
  /*
@@ -538,9 +565,15 @@ export const settingsModalStyles = css`
538
565
  margin-bottom: 0;
539
566
  }
540
567
 
541
- /* Equal columns, so the four buckets line up as a grid rather than bunching left. */
568
+ /*
569
+ * Basis auto, not 0: a zero basis splits the row into four equal columns, so CACHE WRITE is
570
+ * squeezed exactly as hard as INPUT despite being twice the label. Sizing from content gives the
571
+ * long labels the room their text needs and lets the short ones concede it, which is what makes
572
+ * white-space: nowrap above safe — every column starts at least as wide as its own content,
573
+ * then shares the slack. Still grows and shrinks, so the four stay flush edge to edge.
574
+ */
542
575
  .settings-usage-row .settings-token-bucket {
543
- flex: 1 1 0;
576
+ flex: 1 1 auto;
544
577
  }
545
578
 
546
579
  .settings-model-tags {
@@ -580,6 +613,16 @@ export const settingsModalStyles = css`
580
613
  margin: calc(var(--design-unit) * 4px) 0 calc(var(--design-unit) * 2px);
581
614
  }
582
615
 
616
+ /*
617
+ * The heading labels the lifetime card as well as the rows, so the card gives up its own top
618
+ * margin and the gap becomes the heading's alone. Adjacent siblings collapse to the LARGER of
619
+ * the two margins, so leaving both would space the caps 3 units off the block they label while
620
+ * the rows below sit at 2 — reading as though the heading belonged to neither.
621
+ */
622
+ .settings-cost-history-title + .settings-lifetime-usage {
623
+ margin-top: 0;
624
+ }
625
+
583
626
  .settings-cost-history {
584
627
  display: flex;
585
628
  flex-direction: column;
@@ -616,14 +659,16 @@ export const settingsModalStyles = css`
616
659
  }
617
660
 
618
661
  /*
619
- * Both of these carry a ?hidden binding (showTokens), and both declare display: flex — which
620
- * silently beat the UA [hidden] { display: none } rule, because author-origin declarations
621
- * outrank user-agent origin whatever the specificity. Without this, showTokens: false still
622
- * rendered the full breakdown in the lifetime block, the live block and every history row.
623
- * Sibling elements that hide correctly do so only by declaring no display at all. Same
624
- * treatment as .settings-modal-tab-panel[hidden] near the top of this file.
662
+ * All of these carry a ?hidden binding, and all declare display: flex — which silently beat the
663
+ * UA [hidden] { display: none } rule, because author-origin declarations outrank user-agent
664
+ * origin whatever the specificity. Without this, showTokens: false still rendered the full
665
+ * breakdown in the lifetime block, the live block and every history row, and an empty row list
666
+ * still occupied its padding under the lifetime total. Sibling elements that hide correctly do
667
+ * so only by declaring no display at all. Same treatment as .settings-modal-tab-panel[hidden]
668
+ * near the top of this file.
625
669
  */
626
670
  .settings-usage-row-tokens[hidden],
671
+ .settings-cost-history[hidden],
627
672
  .settings-cost-history-row-content[hidden] {
628
673
  display: none !important;
629
674
  }
@@ -375,6 +375,12 @@ const modelTagTemplate = html<CostSessionModelEntry>`
375
375
  * this puts output between the three buckets that partition the prompt, so their relationship is
376
376
  * carried by the tooltips rather than by adjacency.
377
377
  *
378
+ * The two cache buckets carry a direction marker on their LABEL, not their value: below the input
379
+ * rate for reads, above it for writes. On the label because the rate is a fixed property of the
380
+ * bucket, whereas the value changes every turn — and because styling the values instead means a
381
+ * bucket reading 0 (every Gemini cache write, which has no write bucket to bill) renders in a
382
+ * dimmed treatment that looks disabled beside a normal 0. All four values stay identical.
383
+ *
378
384
  * `partPrefix` keeps the shadow-part names caller-specific (`session-tokens-input`,
379
385
  * `lifetime-tokens-input`, …) so a host can style one context without hitting the others.
380
386
  */
@@ -414,12 +420,17 @@ const tokenBreakdownTemplate = <T>(
414
420
  :innerHTML="${(x: T) => formatCompactTokenCountSafe(usageOf(x).outputTokens)}"
415
421
  ></span>
416
422
  </div>
417
- <div class="settings-token-bucket is-discounted" part="${partPrefix}-tokens-cache-read">
423
+ <div class="settings-token-bucket" part="${partPrefix}-tokens-cache-read">
418
424
  <span
419
425
  class="settings-token-bucket-label"
420
426
  title="Prompt tokens served from the provider cache — billed at a fraction of the uncached rate"
421
427
  >
422
428
  Cache read
429
+ <!--
430
+ aria-hidden: the marker is a restatement of the tooltip this label already carries, and
431
+ a screen reader announcing "black down-pointing small triangle" mid-heading is noise.
432
+ -->
433
+ <span class="settings-token-bucket-rate" aria-hidden="true">▾</span>
423
434
  </span>
424
435
  <span
425
436
  class="settings-token-bucket-value"
@@ -432,6 +443,7 @@ const tokenBreakdownTemplate = <T>(
432
443
  title="Prompt tokens written to the provider cache — billed at a premium over the uncached rate"
433
444
  >
434
445
  Cache write
446
+ <span class="settings-token-bucket-rate" aria-hidden="true">▴</span>
435
447
  </span>
436
448
  <span
437
449
  class="settings-token-bucket-value"
@@ -445,9 +457,14 @@ const tokenBreakdownTemplate = <T>(
445
457
  /**
446
458
  * Lifetime usage across every project in the history scope.
447
459
  *
448
- * Sits above the live session block because it is the wider figure. It used to live inside
449
- * that block as a lone "Total build cost", where the live badge and project name directly
450
- * above it implied the total belonged to the open project.
460
+ * Sits under the "Build history" heading, above the rows it totals the live block leads the tab
461
+ * instead, because the project open now is what a user came to check. Being inside the history
462
+ * grouping is also what identifies this figure: it is the sum of the rows below it, not a rival
463
+ * reading of the block above it.
464
+ *
465
+ * It must not sit inside the live block, which is where it began life as a lone "Total build
466
+ * cost": the live badge and project name directly above it implied the total belonged to the open
467
+ * project.
451
468
  */
452
469
  const lifetimeUsageTemplate =
453
470
  (): ViewTemplate<FoundationAiAssistant> => html<FoundationAiAssistant>`
@@ -727,7 +744,6 @@ export const SettingsModalTemplate = (
727
744
  part="cost-tab-panel"
728
745
  >
729
746
  <div class="settings-modal-body" part="settings-modal-body">
730
- ${lifetimeUsageTemplate()}
731
747
  ${sessionCostSummaryTemplate()}
732
748
  <div
733
749
  class="settings-cost-current"
@@ -736,9 +752,15 @@ export const SettingsModalTemplate = (
736
752
  >
737
753
  <slot name="settings-cost-current" ${slotted('settingsCostCurrentSlotted')}></slot>
738
754
  </div>
739
- <p class="settings-cost-history-title" ?hidden=${(x) => !x.settingsCostHistorySectionVisible}>
755
+ <!--
756
+ The heading covers everything below it, lifetime total included — that total IS the sum of
757
+ the history rows, so it reads as their summary rather than a rival figure. Hence the
758
+ heading's own visibility gate, which is broader than the rows'.
759
+ -->
760
+ <p class="settings-cost-history-title" ?hidden=${(x) => !x.settingsCostHistoryHeadingVisible}>
740
761
  Build history
741
762
  </p>
763
+ ${lifetimeUsageTemplate()}
742
764
  <div
743
765
  class="settings-cost-history"
744
766
  part="settings-cost-history"
@@ -801,7 +823,16 @@ export const SettingsModalTemplate = (
801
823
  ${(x) => x.resolvedCostHistory.summaryHint}
802
824
  `,
803
825
  )}Costs
804
- are estimated from token usage at list price.
826
+ are estimated from token usage at list
827
+ price.${when(
828
+ // Only where the markers actually render. Every place they appear is gated on
829
+ // showTokens, so with cost figures but no token buckets this sentence would
830
+ // define two glyphs that are nowhere on screen.
831
+ (x) => x.resolvedCostHistory.showTokens,
832
+ html<FoundationAiAssistant>`
833
+ Cache reads bill below the input rate (▾) and cache writes above it (▴).
834
+ `,
835
+ )}
805
836
  </span>
806
837
  `,
807
838
  )}
@@ -1,5 +1,10 @@
1
1
  import type { AggregateUsage, ChatConfig, ChatMessage } from '@genesislcap/foundation-ai';
2
2
  import { assert, createLogicSuite } from '@genesislcap/foundation-testing';
3
+ import {
4
+ getBankedBaseline,
5
+ resetBankedBaselines,
6
+ setBankedBaseline,
7
+ } from '../utils/banked-usage-baselines';
3
8
  import {
4
9
  clearCostSessionHistory,
5
10
  loadCostSessionHistory,
@@ -48,6 +53,12 @@ type Internals = {
48
53
  /**
49
54
  * An unconnected element with just enough session state wired for `finalizeCostSession`:
50
55
  * the live usage it projects, the transcript it titles from, and the key it upserts against.
56
+ *
57
+ * Banked baselines are module state keyed by session (so remounts share one), which means they
58
+ * outlive an element. Cleared by default, because every suite but the remount ones is modelling
59
+ * a *fresh page load* — and because leaving them would leak one suite's baseline into the next
60
+ * under the shared `PROJECT` key. Pass `remount: true` to model a new element joining a session
61
+ * that has already banked, which is the case this file exists to pin.
51
62
  */
52
63
  function element(options: {
53
64
  scope: string;
@@ -56,7 +67,9 @@ function element(options: {
56
67
  persistenceActive?: boolean;
57
68
  loaded?: boolean;
58
69
  providerStatuses?: unknown[];
70
+ remount?: boolean;
59
71
  }): FoundationAiAssistant {
72
+ if (!options.remount) resetBankedBaselines();
60
73
  const el = document.createElement('foundation-ai-assistant') as FoundationAiAssistant;
61
74
  const messages: ChatMessage[] = [{ role: 'user', content: 'build me a blotter' } as ChatMessage];
62
75
  const internals = el as unknown as Internals;
@@ -351,10 +364,10 @@ Suite(
351
364
  );
352
365
 
353
366
  Suite('deleting a provider row whose id differs from its projectKey still drops the memo', () => {
354
- // `_bankedFor` holds a projectKey; the delete action passes a row id. A host provider can assign
355
- // any id, so comparing across the two namespaces skipped the reset and the next turn resurrected
356
- // the deleted total. Reachable when a provider load lands AFTER a finalize has banked: our own
357
- // upsert would otherwise have rewritten the row's id to the projectKey.
367
+ // Baselines are keyed by projectKey; the delete action passes a row id. A host provider can
368
+ // assign any id, so deleting by the wrong namespace left the baseline in place and the next
369
+ // turn resurrected the deleted total. Reachable when a provider load lands AFTER a finalize has
370
+ // banked: our own upsert would otherwise have rewritten the row's id to the projectKey.
358
371
  const scope = 'ledger-remove-id';
359
372
  clearCostSessionHistory(scope);
360
373
  const el = element({
@@ -363,13 +376,10 @@ Suite('deleting a provider row whose id differs from its projectKey still drops
363
376
  rows: [row({ id: 'host-assigned-uuid', projectKey: PROJECT, usage: usage(10) })],
364
377
  persistenceActive: false,
365
378
  });
366
- // Memo already populated for this project, as it would be after a turn.
367
- const internals = el as unknown as Internals & {
368
- _bankedFor?: string;
369
- _bankedUsage: AggregateUsage;
370
- };
371
- internals._bankedFor = PROJECT;
372
- internals._bankedUsage = usage(10);
379
+ // Baseline already resolved for this project, as it would be after a turn — set directly
380
+ // rather than by finalizing, because our own upsert would rewrite the row's id to the
381
+ // projectKey and the id mismatch under test would vanish with it.
382
+ setBankedBaseline(PROJECT, usage(10));
373
383
 
374
384
  el.removeCostSessionFromHistory('host-assigned-uuid');
375
385
  assert.is(el.costSessionHistory.length, 0);
@@ -379,6 +389,250 @@ Suite('deleting a provider row whose id differs from its projectKey still drops
379
389
  clearCostSessionHistory(scope);
380
390
  });
381
391
 
392
+ Suite('a remount mid-session does not re-bank what the row already holds', () => {
393
+ // The reported regression (GENC-1475). Reproduces the field report exactly: with persistence
394
+ // off, the host remounted the assistant part-way through a session (a layout re-render — the
395
+ // debug log showed seven connects in one session) and the LIFETIME figure jumped by the whole
396
+ // session-to-date while the live figure kept climbing normally.
397
+ //
398
+ // The new element joins a live session: same key, same transcript, and rows that already
399
+ // contain the previous instance's upsert. An element-scoped baseline re-derived here and, with
400
+ // no restore to defer to, banked `row.usage` — which already included this very transcript.
401
+ const scope = 'bank-remount';
402
+ clearCostSessionHistory(scope);
403
+ const first = element({
404
+ scope,
405
+ live: usage(6),
406
+ rows: [row({ usage: usage(1), banked: usage(1) })],
407
+ persistenceActive: false,
408
+ });
409
+ first.finalizeCostSession();
410
+ assert.is(first.costSessionHistory[0].usage.costUsd, 7, '1 banked + 6 live');
411
+
412
+ // Remount: a brand new element wired to the same session, handed the rows as they now stand.
413
+ const second = element({
414
+ scope,
415
+ live: usage(6),
416
+ rows: first.costSessionHistory,
417
+ persistenceActive: false,
418
+ remount: true,
419
+ });
420
+ second.finalizeCostSession();
421
+
422
+ assert.is(second.costSessionHistory[0].usage.costUsd, 7, 'remount must not inflate the row');
423
+ assert.is(second.costSessionHistory[0].banked?.costUsd, 1, 'baseline unchanged by the remount');
424
+
425
+ // And the session keeps accruing normally afterwards, on top of the SAME baseline.
426
+ const third = element({
427
+ scope,
428
+ live: usage(9),
429
+ rows: second.costSessionHistory,
430
+ persistenceActive: false,
431
+ remount: true,
432
+ });
433
+ third.finalizeCostSession();
434
+ assert.is(third.costSessionHistory[0].usage.costUsd, 10, '1 banked + 9 live');
435
+ clearCostSessionHistory(scope);
436
+ });
437
+
438
+ Suite('a page reload still absorbs the prior total after a remount banked nothing new', () => {
439
+ // The other half of the pairing: dropping the baseline on remount is wrong, but keeping it
440
+ // across a *page load* would be too — the transcript starts empty there (persistence off), so
441
+ // the row's whole total must be banked. `resetBankedBaselines` stands in for the realm dying.
442
+ const scope = 'bank-reload';
443
+ clearCostSessionHistory(scope);
444
+ const before = element({
445
+ scope,
446
+ live: usage(6),
447
+ rows: [row({ usage: usage(1), banked: usage(1) })],
448
+ persistenceActive: false,
449
+ });
450
+ before.finalizeCostSession();
451
+ assert.is(before.costSessionHistory[0].usage.costUsd, 7);
452
+
453
+ const afterReload = element({
454
+ scope,
455
+ live: usage(2),
456
+ rows: before.costSessionHistory,
457
+ persistenceActive: false,
458
+ });
459
+ afterReload.finalizeCostSession();
460
+ assert.is(afterReload.costSessionHistory[0].usage.costUsd, 9, 'prior 7 banked, this load adds 2');
461
+ clearCostSessionHistory(scope);
462
+ });
463
+
464
+ Suite('clearing the transcript re-baselines instead of discarding spend', () => {
465
+ // Clear empties the transcript, so the row's total now predates what is on screen and has to be
466
+ // banked wholesale. Merely dropping the baseline would re-derive through `persistenceActive`,
467
+ // which with persistence ON carries the row's OLD banked figure forward and silently loses
468
+ // every turn between that baseline and the clear.
469
+ const scope = 'bank-clear-session';
470
+ clearCostSessionHistory(scope);
471
+ const el = element({
472
+ scope,
473
+ live: usage(6),
474
+ rows: [row({ usage: usage(10), banked: usage(4) })],
475
+ persistenceActive: true,
476
+ });
477
+ el.finalizeCostSession();
478
+ assert.is(el.costSessionHistory[0].usage.costUsd, 10);
479
+
480
+ // `clearSession` itself tears down and rebuilds the driver, which an unconnected element has
481
+ // none of — so drive the one step under test. `clearSession` reads the live figure before
482
+ // `resetSession` zeroes it and passes it in; the 6 here is that capture.
483
+ const priv = el as unknown as {
484
+ rebaselineOnClearedTranscript(key: string, discarded: AggregateUsage): void;
485
+ _sessionRef: { store: { aiAssistant: { sessionUsage: AggregateUsage } } };
486
+ _costHistoryLoaded: boolean;
487
+ };
488
+ priv.rebaselineOnClearedTranscript(PROJECT, usage(6));
489
+
490
+ // A fresh transcript worth 3, on top of the whole 10 the project had accrued.
491
+ priv._sessionRef.store.aiAssistant.sessionUsage = usage(3);
492
+ el.finalizeCostSession();
493
+ assert.is(el.costSessionHistory[0].usage.costUsd, 13, 'pre-clear spend kept, new turn added');
494
+ assert.is(el.costSessionHistory[0].banked?.costUsd, 10, 'whole pre-clear total banked');
495
+ clearCostSessionHistory(scope);
496
+ });
497
+
498
+ Suite('clearing while the ledger is still loading must not pin a baseline', () => {
499
+ // Review case. A stamped baseline is sticky — `bankedUsageFor` short-circuits on any stored
500
+ // entry and a zero usage is a *resolved* value there. On the provider path the row list is empty
501
+ // and `_costHistoryLoaded` false while the read is in flight, so a clear landing in that window
502
+ // used to pin a baseline derived from no rows at all. The load arriving afterwards with the
503
+ // project's real total was then never consulted, and the next write replaced its row with
504
+ // `banked: 0` — the project's whole history gone.
505
+ const scope = 'bank-clear-unloaded';
506
+ clearCostSessionHistory(scope);
507
+ const el = element({ scope, live: usage(5), loaded: false });
508
+ const priv = el as unknown as {
509
+ rebaselineOnClearedTranscript(key: string, discarded: AggregateUsage): void;
510
+ _sessionRef: { store: { aiAssistant: { sessionUsage: AggregateUsage } } };
511
+ _costHistoryLoaded: boolean;
512
+ };
513
+
514
+ // Clear arrives before the provider read lands: rows are empty and nothing is known yet.
515
+ priv.rebaselineOnClearedTranscript(PROJECT, usage(5));
516
+ assert.is(getBankedBaseline(PROJECT), undefined, 'nothing pinned from a ledger we cannot see');
517
+
518
+ // The read lands with this project's real history, and a turn follows.
519
+ el.costSessionHistory = [row({ usage: usage(42), banked: usage(40) })];
520
+ priv._costHistoryLoaded = true;
521
+ priv._sessionRef.store.aiAssistant.sessionUsage = usage(1);
522
+ el.finalizeCostSession();
523
+
524
+ assert.is(el.costSessionHistory[0].usage.costUsd, 43, "the project's 42 survives the race");
525
+ assert.is(el.costSessionHistory[0].banked?.costUsd, 42, 'baseline re-derived from real rows');
526
+ clearCostSessionHistory(scope);
527
+ });
528
+
529
+ Suite('clearing banks a transcript the row has not caught up with', () => {
530
+ // Review case: without this, the suite passed identically against the OLD derivation
531
+ // (`existing?.usage`), because everywhere else the row already agreed with baseline + live.
532
+ //
533
+ // The formulas only diverge when the row is STALE relative to the transcript — which is exactly
534
+ // what the new one exists for, since `finalizeCostSession` skips its write while the ledger is
535
+ // unloaded and while the session has no usage. No finalize here, so the row lags by 3.
536
+ const scope = 'bank-clear-stale-row';
537
+ clearCostSessionHistory(scope);
538
+ const el = element({
539
+ scope,
540
+ live: usage(3),
541
+ rows: [row({ usage: usage(42), banked: usage(40) })],
542
+ persistenceActive: false,
543
+ });
544
+ const priv = el as unknown as {
545
+ rebaselineOnClearedTranscript(key: string, discarded: AggregateUsage): void;
546
+ _sessionRef: { store: { aiAssistant: { sessionUsage: AggregateUsage } } };
547
+ };
548
+
549
+ priv.rebaselineOnClearedTranscript(PROJECT, usage(3));
550
+ // 42 from the row plus the 3 the discarded transcript proved. The old row-read banked 42 flat.
551
+ assert.is(getBankedBaseline(PROJECT)?.costUsd, 45, 'the stale 3 is banked, not dropped');
552
+
553
+ priv._sessionRef.store.aiAssistant.sessionUsage = usage(1);
554
+ el.finalizeCostSession();
555
+ assert.is(el.costSessionHistory[0].usage.costUsd, 46, '45 banked + the new turn');
556
+ clearCostSessionHistory(scope);
557
+ });
558
+
559
+ Suite('a memoised baseline survives a clear during a reload instead of being dropped', () => {
560
+ // Review case. The guard is broader than the derivation needs: once a baseline is memoised the
561
+ // new figure is determined without any rows, so deleting it there throws away something correct.
562
+ // Concretely — row at usage 120 / banked 90, baseline memoised at 90, 30 on screen — dropping it
563
+ // made the next turn re-derive `row.banked` and rewrite the row BACKWARDS from 120 to 95.
564
+ const scope = 'bank-clear-memoised';
565
+ clearCostSessionHistory(scope);
566
+ const el = element({
567
+ scope,
568
+ live: usage(30),
569
+ rows: [row({ usage: usage(120), banked: usage(90) })],
570
+ persistenceActive: true,
571
+ });
572
+ el.finalizeCostSession();
573
+ assert.is(getBankedBaseline(PROJECT)?.costUsd, 90, 'baseline memoised off the restored row');
574
+
575
+ // A chatConfig rebind puts the ledger back in flight, and the clear lands inside that window.
576
+ const priv = el as unknown as {
577
+ rebaselineOnClearedTranscript(key: string, discarded: AggregateUsage): void;
578
+ _sessionRef: { store: { aiAssistant: { sessionUsage: AggregateUsage } } };
579
+ _costHistoryLoaded: boolean;
580
+ };
581
+ priv._costHistoryLoaded = false;
582
+ priv.rebaselineOnClearedTranscript(PROJECT, usage(30));
583
+ assert.is(getBankedBaseline(PROJECT)?.costUsd, 120, '90 kept and the discarded 30 added');
584
+
585
+ priv._costHistoryLoaded = true;
586
+ priv._sessionRef.store.aiAssistant.sessionUsage = usage(5);
587
+ el.finalizeCostSession();
588
+ assert.is(el.costSessionHistory[0].usage.costUsd, 125, 'row moves forward, never backwards');
589
+ clearCostSessionHistory(scope);
590
+ });
591
+
592
+ Suite('clearing with the ledger disabled pins nothing, even though it reads as loaded', () => {
593
+ // Review case. `reloadCostSessionHistory` sets `_costHistoryLoaded` TRUE over a deliberately
594
+ // empty list when `enabled` is false — "nothing will be loaded", not "rows are known" — so the
595
+ // flag alone let a clear pin a baseline from a ledger that was never read. A host enabling
596
+ // history afterwards (an async setting, a feature flag) then had its real row buried by it.
597
+ const scope = 'bank-clear-disabled';
598
+ clearCostSessionHistory(scope);
599
+ const el = element({ scope, live: usage(3) });
600
+ el.chatConfig = { costHistory: { enabled: false, scope } } as ChatConfig;
601
+ const priv = el as unknown as {
602
+ rebaselineOnClearedTranscript(key: string, discarded: AggregateUsage): void;
603
+ _sessionRef: { store: { aiAssistant: { sessionUsage: AggregateUsage } } };
604
+ _costHistoryLoaded: boolean;
605
+ };
606
+ assert.is(priv._costHistoryLoaded, true, 'reads as loaded despite nothing being known');
607
+
608
+ priv.rebaselineOnClearedTranscript(PROJECT, usage(3));
609
+ assert.is(getBankedBaseline(PROJECT), undefined, 'nothing pinned while the ledger is off');
610
+
611
+ // History switched on afterwards, and this project turns out to have real spend.
612
+ el.chatConfig = { costHistory: { enabled: true, scope, title: 'Trade Blotter' } } as ChatConfig;
613
+ el.costSessionHistory = [row({ usage: usage(50), banked: usage(50) })];
614
+ priv._costHistoryLoaded = true;
615
+ priv._sessionRef.store.aiAssistant.sessionUsage = usage(1);
616
+ el.finalizeCostSession();
617
+
618
+ assert.is(el.costSessionHistory[0].usage.costUsd, 51, "the project's 50 is not buried");
619
+ clearCostSessionHistory(scope);
620
+ });
621
+
622
+ Suite('a host slotting its own build history does not have to enable our ledger', () => {
623
+ // Review case. `enabled` governs the BUILT-IN ledger and defaults false, while the Usage tab
624
+ // shows for showCost/showTokens which default true. Once the section's ?hidden binding became
625
+ // effective, short-circuiting on `enabled` above the slot check hid a host's own markup — and
626
+ // the slot is the only thing in that container.
627
+ const el = element({ scope: 'slotted-history', live: usage(1) });
628
+ el.chatConfig = { costHistory: { enabled: false } } as ChatConfig;
629
+ assert.is(el.settingsCostHistorySectionVisible, false, 'nothing slotted, ledger off → hidden');
630
+
631
+ el.settingsCostHistorySlotted = [document.createElement('div')];
632
+ assert.is(el.settingsCostHistorySectionVisible, true, 'slotted content shows without `enabled`');
633
+ assert.is(el.settingsCostHistoryHeadingVisible, true, 'and the heading comes with it');
634
+ });
635
+
382
636
  Suite('hides the lifetime section when no state key at all can produce a row', () => {
383
637
  const el = element({ scope: 'ledger-nokey', live: usage(3) });
384
638
  assert.is(el.settingsCostLifetimeVisible, true, 'visible with a key');
@@ -404,4 +658,22 @@ Suite('labels the live figures by whether the transcript is authoritative', () =
404
658
  assert.is(without.liveUsageIsProjectLifetime, false, 'not restored → this session only');
405
659
  });
406
660
 
661
+ Suite('a stored baseline is isolated from the row and the caller it passed through', () => {
662
+ // A baseline arrives as a reference into a ledger row (`resolveBankedUsage` returns `row.banked`
663
+ // or `row.usage`) and is read back onto the NEXT row's `banked` field, so an uncloned map entry
664
+ // is reachable from page-global state, two rows, and any host handed the row list. Mutating
665
+ // either end must not move the stored figure, or a project's baseline is silently rewritten for
666
+ // the rest of the page.
667
+ resetBankedBaselines();
668
+ const source = usage(10);
669
+ setBankedBaseline(PROJECT, source);
670
+
671
+ source.costUsd = 999;
672
+ assert.is(getBankedBaseline(PROJECT)?.costUsd, 10, 'mutating the source cannot reach the map');
673
+
674
+ const readBack = getBankedBaseline(PROJECT)!;
675
+ readBack.costUsd = 777;
676
+ assert.is(getBankedBaseline(PROJECT)?.costUsd, 10, 'mutating a read copy cannot reach the map');
677
+ });
678
+
407
679
  Suite.run();
@@ -93,6 +93,33 @@ suite('the blocked banner keeps its unblocked container visually inert', () => {
93
93
  }
94
94
  });
95
95
 
96
+ suite('the visible banner hands its end margin to the resize handle', () => {
97
+ // Reviewer's manual-testing note: the banner's block-end margin plus the 7px
98
+ // handle stacked into a gap the hover pill was NOT centred in (it centres in
99
+ // the handle alone). The adjacency rule collapses the two so the handle IS
100
+ // the gap. What gets pinned is the INVARIANT, not the selector's existence:
101
+ // both rules must read the ONE shared token, because the cancellation only
102
+ // works while the banner's margin and the handle's pull are equal-and-
103
+ // opposite — two hand-kept magnitudes ~80 lines apart regress silently, and
104
+ // an existence-only assertion stayed green while they did.
105
+ assert.ok(
106
+ /:host\s*\{[^}]*--blocked-banner-gap:/.test(cssText),
107
+ 'the shared gap token is declared on the host (a sibling cannot read one on the banner)',
108
+ );
109
+ assert.ok(
110
+ /\.blocked-banner\.is-visible\s*\{[^}]*margin-block:\s*var\(--blocked-banner-gap\)/.test(
111
+ cssText,
112
+ ),
113
+ "the banner's block margin IS the token",
114
+ );
115
+ assert.ok(
116
+ /\.blocked-banner\.is-visible \+ \.composer-resize-handle\s*\{[^}]*margin-block-start:\s*calc\(var\(--blocked-banner-gap\) \* -1\)/.test(
117
+ cssText,
118
+ ),
119
+ 'and the handle pulls up by exactly that token, negated — equal and opposite by construction',
120
+ );
121
+ });
122
+
96
123
  suite('partial exhaustion has its own modifier, layered on the visible state', () => {
97
124
  // `.is-visible` carries the layout and surface for BOTH states; `.is-partial`
98
125
  // only softens it. Additive, never a replacement — so host CSS keyed on the
@@ -16,6 +16,19 @@ const baseStyles = css`
16
16
  float still triggers at 1500px. */
17
17
  --ai-conversation-max-width: 1500px;
18
18
 
19
+ /* INTERNAL — not a supported override point, despite sitting beside one.
20
+ Deliberately NOT --ai-*-namespaced and absent from docs/styling.md: the
21
+ documented banner surface is ::part(blocked-banner), and this token is
22
+ plumbing, not a knob. It is the banner's block margin AND the exact
23
+ amount the resize handle pulls itself up by when it follows the banner —
24
+ one name, on the host only because a sibling cannot read a custom
25
+ property declared on the banner (they inherit downward), so the
26
+ cancellation is structural: change the gap here and both rules move
27
+ together, instead of two magnitudes ~80 lines apart that only prose kept
28
+ in sync. A host that overrides it anyway gets a consistent gap, but that
29
+ is a side effect, not a promise. */
30
+ --blocked-banner-gap: calc(var(--design-unit) * 1px);
31
+
19
32
  display: flex;
20
33
  flex-direction: column;
21
34
  height: 100%;
@@ -644,7 +657,7 @@ const baseStyles = css`
644
657
  /* Block axis only. The inline-axis margin is owned by the composer width group
645
658
  above (margin-inline: auto), which centres the banner on the same column as
646
659
  the input row — an inline margin here would fight it. */
647
- margin-block: calc(var(--design-unit) * 1px);
660
+ margin-block: var(--blocked-banner-gap);
648
661
  padding: calc(var(--design-unit) * 2px) calc(var(--design-unit) * 3px);
649
662
  border: calc(var(--stroke-width) * 1px) solid var(--warning-color);
650
663
  border-radius: calc(var(--control-corner-radius) * 1px);
@@ -710,6 +723,18 @@ const baseStyles = css`
710
723
  opacity: 70%;
711
724
  }
712
725
 
726
+ /* With the banner visible, its block-end margin and the handle's height used
727
+ to STACK into an ~11px void between the exhausted message and the composer
728
+ — and the hover pill centres in the handle's own 7px slice, i.e. below the
729
+ middle of the gap the user actually sees. Pull the handle up over the
730
+ banner's end margin instead: the handle's height becomes the whole gap and
731
+ the pill lands dead-centre of it. FAST's when-anchors are comment nodes,
732
+ so the adjacency holds whenever the handle renders; without a handle
733
+ (resize disabled) the banner keeps its normal margin before the input row. */
734
+ .blocked-banner.is-visible + .composer-resize-handle {
735
+ margin-block-start: calc(var(--blocked-banner-gap) * -1);
736
+ }
737
+
713
738
  .file-input {
714
739
  display: none;
715
740
  }