@genesislcap/ai-assistant 15.7.3-alpha-e7d4aa5.0 → 15.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-assistant.api.json +191 -1
- package/dist/ai-assistant.d.ts +155 -1
- package/dist/custom-elements.json +114 -2
- package/dist/dts/components/settings-modal/settings-modal.styles.d.ts.map +1 -1
- package/dist/dts/components/settings-modal/settings-modal.styles.test.d.ts +2 -0
- package/dist/dts/components/settings-modal/settings-modal.styles.test.d.ts.map +1 -0
- package/dist/dts/components/settings-modal/settings-modal.template.d.ts +22 -0
- package/dist/dts/components/settings-modal/settings-modal.template.d.ts.map +1 -1
- package/dist/dts/components/settings-modal/settings-modal.template.test.d.ts +2 -0
- package/dist/dts/components/settings-modal/settings-modal.template.test.d.ts.map +1 -0
- package/dist/dts/main/budget-meter.test.d.ts +2 -0
- package/dist/dts/main/budget-meter.test.d.ts.map +1 -0
- package/dist/dts/main/main.d.ts +113 -2
- package/dist/dts/main/main.d.ts.map +1 -1
- package/dist/dts/main/main.types.d.ts +25 -0
- package/dist/dts/main/main.types.d.ts.map +1 -1
- package/dist/dts/state/ai-assistant-slice.d.ts +47 -0
- package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
- package/dist/dts/state/session-store.d.ts +4 -0
- package/dist/dts/state/session-store.d.ts.map +1 -1
- package/dist/dts/utils/format-usd.d.ts +24 -0
- package/dist/dts/utils/format-usd.d.ts.map +1 -0
- package/dist/esm/components/settings-modal/settings-modal.styles.js +33 -3
- package/dist/esm/components/settings-modal/settings-modal.styles.test.js +80 -0
- package/dist/esm/components/settings-modal/settings-modal.template.js +64 -14
- package/dist/esm/components/settings-modal/settings-modal.template.test.js +91 -0
- package/dist/esm/main/budget-meter.test.js +317 -0
- package/dist/esm/main/main.js +189 -3
- package/dist/esm/state/ai-assistant-slice.js +38 -0
- package/dist/esm/utils/format-usd.js +23 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/docs/migration-GENC-1464.md +63 -0
- package/docs/styling.md +23 -0
- package/package.json +17 -17
- package/src/components/settings-modal/settings-modal.styles.test.ts +94 -0
- package/src/components/settings-modal/settings-modal.styles.ts +33 -3
- package/src/components/settings-modal/settings-modal.template.test.ts +124 -0
- package/src/components/settings-modal/settings-modal.template.ts +82 -13
- package/src/main/budget-meter.test.ts +427 -0
- package/src/main/main.ts +198 -3
- package/src/main/main.types.ts +26 -0
- package/src/state/ai-assistant-slice.ts +74 -0
- package/src/utils/format-usd.ts +26 -0
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import type { ChatMessage } from '@genesislcap/foundation-ai';
|
|
2
|
+
import { assert, createLogicSuite } from '@genesislcap/foundation-testing';
|
|
3
|
+
import type { VendorBudgetFigures } from '../state/ai-assistant-slice';
|
|
4
|
+
import type { SessionStoreReturn } from '../state/session-store';
|
|
5
|
+
import { clearAllSessionStores, getSessionStore } from '../state/session-store';
|
|
6
|
+
import { logger } from '../utils/logger';
|
|
7
|
+
import { budgetPercentOf, FoundationAiAssistant } from './main';
|
|
8
|
+
|
|
9
|
+
// Hold a reference so the custom-element registration isn't tree-shaken.
|
|
10
|
+
FoundationAiAssistant;
|
|
11
|
+
|
|
12
|
+
// GENC-1464 — the settings-modal per-vendor budget meter.
|
|
13
|
+
//
|
|
14
|
+
// Like `blocked-state.test.ts`, this pins the GETTER LOGIC the template bindings
|
|
15
|
+
// depend on rather than the rendered DOM, and for the same reason: mounting the
|
|
16
|
+
// assistant runs `connectedCallback`, which subscribes to `agenticActivityBus`
|
|
17
|
+
// and leaves the runner's event loop open. `document.createElement` only
|
|
18
|
+
// upgrades the element — it does not connect — so nothing subscribes here.
|
|
19
|
+
//
|
|
20
|
+
// The bindings under test in `settings-modal.template.ts` are:
|
|
21
|
+
// ${when((x) => x.settingsBudgetUsageVisible, …)} (the whole meter)
|
|
22
|
+
// ${repeat((x) => x.settingsBudgetRows, …)} (one row per vendor)
|
|
23
|
+
// <…-progress value="${(row) => row.barValue}"> (the clamped bar)
|
|
24
|
+
// plus `settingsModelSectionVisible`, which decides whether the "AI Model
|
|
25
|
+
// Settings" section renders at all.
|
|
26
|
+
|
|
27
|
+
const Suite = createLogicSuite('FoundationAiAssistant budget meter');
|
|
28
|
+
|
|
29
|
+
let storeSeq = 0;
|
|
30
|
+
|
|
31
|
+
/** A fresh (unconnected) element wired to its own real session store. */
|
|
32
|
+
function element(): FoundationAiAssistant {
|
|
33
|
+
const el = document.createElement('foundation-ai-assistant') as FoundationAiAssistant;
|
|
34
|
+
storeSeq += 1;
|
|
35
|
+
(el as unknown as { _sessionRef: unknown })._sessionRef = getSessionStore(
|
|
36
|
+
`budget-meter-test-${storeSeq}`,
|
|
37
|
+
false,
|
|
38
|
+
);
|
|
39
|
+
return el;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The raw stored figures, read the way the rows getter reads them. */
|
|
43
|
+
const storedBudgets = (el: FoundationAiAssistant) =>
|
|
44
|
+
(el as unknown as { _sessionRef: SessionStoreReturn })._sessionRef.store.aiAssistant
|
|
45
|
+
.vendorBudgets;
|
|
46
|
+
|
|
47
|
+
/** The store half of "Clear" / "New chat" — see blocked-state.test.ts. */
|
|
48
|
+
const resetSession = (el: FoundationAiAssistant): void =>
|
|
49
|
+
(
|
|
50
|
+
el as unknown as { _sessionRef: SessionStoreReturn }
|
|
51
|
+
)._sessionRef.actions.aiAssistant.resetSession();
|
|
52
|
+
|
|
53
|
+
/** Count `logger.warn` calls during `run` — the boundary warns ONCE per element. */
|
|
54
|
+
const countWarns = (run: () => void): number => {
|
|
55
|
+
const original = logger.warn;
|
|
56
|
+
let calls = 0;
|
|
57
|
+
logger.warn = ((...args: unknown[]) => {
|
|
58
|
+
calls += 1;
|
|
59
|
+
void args;
|
|
60
|
+
}) as typeof logger.warn;
|
|
61
|
+
try {
|
|
62
|
+
run();
|
|
63
|
+
} finally {
|
|
64
|
+
logger.warn = original;
|
|
65
|
+
}
|
|
66
|
+
return calls;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Count reads of `settingsBudgetRows` during `run`.
|
|
71
|
+
*
|
|
72
|
+
* Building the rows formats every vendor's money text — a `formatUsd` pair and
|
|
73
|
+
* a `budgetPercentOf` each — so a gate that answers THROUGH the rows pays for
|
|
74
|
+
* all of it. Counting reads of the getter is the direct probe of that; the spy
|
|
75
|
+
* goes on the prototype (where the accessor lives) and is put back after.
|
|
76
|
+
*/
|
|
77
|
+
const countRowBuilds = (run: () => void): number => {
|
|
78
|
+
const proto = FoundationAiAssistant.prototype;
|
|
79
|
+
const original = Object.getOwnPropertyDescriptor(proto, 'settingsBudgetRows')!;
|
|
80
|
+
let calls = 0;
|
|
81
|
+
Object.defineProperty(proto, 'settingsBudgetRows', {
|
|
82
|
+
...original,
|
|
83
|
+
get(this: FoundationAiAssistant) {
|
|
84
|
+
calls += 1;
|
|
85
|
+
return original.get!.call(this);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
try {
|
|
89
|
+
run();
|
|
90
|
+
} finally {
|
|
91
|
+
Object.defineProperty(proto, 'settingsBudgetRows', original);
|
|
92
|
+
}
|
|
93
|
+
return calls;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
Suite.after(() => {
|
|
97
|
+
clearAllSessionStores();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// ── Feeding figures ─────────────────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
Suite('feeding two vendors renders two rows with the real money text', () => {
|
|
103
|
+
const el = element();
|
|
104
|
+
|
|
105
|
+
assert.is(el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 }), true);
|
|
106
|
+
assert.is(el.setVendorBudget('gemini', { budgetUsd: 200, spentUsd: 30.5 }), true);
|
|
107
|
+
|
|
108
|
+
const rows = el.settingsBudgetRows;
|
|
109
|
+
assert.is(rows.length, 2);
|
|
110
|
+
assert.is(rows[0].vendor, 'anthropic');
|
|
111
|
+
assert.is(rows[0].label, 'Anthropic', 'display name comes from VENDOR_LABELS');
|
|
112
|
+
assert.is(rows[0].figures, '$45.00 / $50.00 (90%)');
|
|
113
|
+
assert.is(rows[0].barValue, 90);
|
|
114
|
+
assert.is(rows[1].vendor, 'gemini');
|
|
115
|
+
assert.is(rows[1].figures, '$30.50 / $200.00 (15%)', 'two decimals always, percent rounded');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
Suite('rows keep BUDGETED_VENDORS order however the host ordered its feed', () => {
|
|
119
|
+
// The feed loops over a server response whose order is the server's business;
|
|
120
|
+
// the meter must not reorder itself between turns because of it.
|
|
121
|
+
const el = element();
|
|
122
|
+
el.setVendorBudget('gemini', { budgetUsd: 10, spentUsd: 1 });
|
|
123
|
+
el.setVendorBudget('anthropic', { budgetUsd: 10, spentUsd: 2 });
|
|
124
|
+
|
|
125
|
+
assert.equal(
|
|
126
|
+
el.settingsBudgetRows.map((r) => r.vendor),
|
|
127
|
+
['anthropic', 'gemini'],
|
|
128
|
+
);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
Suite('a vendor with no figures gets no row — that is how "unlimited" renders', () => {
|
|
132
|
+
// Display rule: hosts simply do not feed a vendor the server marks
|
|
133
|
+
// `unlimited: true` / `limitUsd: null`, and the meter shows only what it was
|
|
134
|
+
// fed. No "∞" row, no empty bar.
|
|
135
|
+
const el = element();
|
|
136
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 15 });
|
|
137
|
+
|
|
138
|
+
const rows = el.settingsBudgetRows;
|
|
139
|
+
assert.is(rows.length, 1);
|
|
140
|
+
assert.is(rows[0].vendor, 'anthropic');
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
// ── Overshoot: the text tells the truth, the bar clamps ─────────────────────
|
|
144
|
+
|
|
145
|
+
Suite('spend past the cap shows the real figures but clamps the bar at 100', () => {
|
|
146
|
+
// Real overshoot exists — the last allowed call can cross the cap (the demo
|
|
147
|
+
// "Exhaust" lands at $62.34 of $50 on purpose). A bar past its end renders
|
|
148
|
+
// nonsense, so only the bar clamps.
|
|
149
|
+
const el = element();
|
|
150
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 62.34 });
|
|
151
|
+
|
|
152
|
+
const [row] = el.settingsBudgetRows;
|
|
153
|
+
assert.is(row.figures, '$62.34 / $50.00 (125%)', 'the text is the truth, unclamped');
|
|
154
|
+
assert.is(row.barValue, 100, 'the bar is full, not broken');
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
Suite('a $0 cap reads as a full meter, not a division by zero', () => {
|
|
158
|
+
// The platform treats a $0 budget as "no spend allowed" (not "unlimited"), so
|
|
159
|
+
// it has no headroom by definition.
|
|
160
|
+
assert.is(budgetPercentOf({ budgetUsd: 0, spentUsd: 0 }), 100);
|
|
161
|
+
assert.is(budgetPercentOf({ budgetUsd: 0, spentUsd: 3 }), 100);
|
|
162
|
+
const el = element();
|
|
163
|
+
el.setVendorBudget('gemini', { budgetUsd: 0, spentUsd: 0 });
|
|
164
|
+
assert.is(el.settingsBudgetRows[0].figures, '$0.00 / $0.00 (100%)');
|
|
165
|
+
assert.is(el.settingsBudgetRows[0].barValue, 100);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// ── Clearing ────────────────────────────────────────────────────────────────
|
|
169
|
+
|
|
170
|
+
Suite('setVendorBudget(vendor, null) clears that row and only that row', () => {
|
|
171
|
+
const el = element();
|
|
172
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
173
|
+
el.setVendorBudget('gemini', { budgetUsd: 50, spentUsd: 15 });
|
|
174
|
+
|
|
175
|
+
assert.is(el.setVendorBudget('anthropic', null), true);
|
|
176
|
+
|
|
177
|
+
assert.equal(
|
|
178
|
+
el.settingsBudgetRows.map((r) => r.vendor),
|
|
179
|
+
['gemini'],
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
Suite('clearing a vendor that has no figures is a true no-op', () => {
|
|
184
|
+
const el = element();
|
|
185
|
+
assert.is(el.setVendorBudget('anthropic', null), true, 'clearing nothing is not an error');
|
|
186
|
+
assert.is(el.settingsBudgetRows.length, 0);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
Suite("undefined clears too — an untyped host's missing lookup is not a crash", () => {
|
|
190
|
+
// The `| null` parameter type is for typed callers; the runtime is more
|
|
191
|
+
// forgiving on purpose. Untyped JS hosts feed this straight from
|
|
192
|
+
// GET /api/budget, where a per-vendor lookup that MISSES yields `undefined`,
|
|
193
|
+
// not `null` — and a boundary whose whole contract is "return false, never
|
|
194
|
+
// throw" must not TypeError on it. "No figures" means "no row", either way.
|
|
195
|
+
const el = element();
|
|
196
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
197
|
+
el.setVendorBudget('gemini', { budgetUsd: 50, spentUsd: 15 });
|
|
198
|
+
|
|
199
|
+
const warns = countWarns(() => {
|
|
200
|
+
assert.is(el.setVendorBudget('anthropic', undefined as never), true, 'accepted, not refused');
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
assert.is(warns, 0, 'a missing lookup is not garbage input — nothing to warn about');
|
|
204
|
+
assert.equal(
|
|
205
|
+
el.settingsBudgetRows.map((r) => r.vendor),
|
|
206
|
+
['gemini'],
|
|
207
|
+
'it cleared that vendor and only that vendor, exactly as null does',
|
|
208
|
+
);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// ── Invalid input: false + warn once, never a throw, never a write ──────────
|
|
212
|
+
|
|
213
|
+
Suite('an unbudgeted vendor is refused with false and no state change', () => {
|
|
214
|
+
const el = element();
|
|
215
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 15 });
|
|
216
|
+
|
|
217
|
+
// 'none' is the no-provider sentinel; 'chrome' is on-device (no pot to
|
|
218
|
+
// meter); 'openai' is refused by the proxy up front — none can carry figures.
|
|
219
|
+
for (const vendor of ['none', 'chrome', 'openai', 'acme-ai']) {
|
|
220
|
+
assert.is(el.setVendorBudget(vendor, { budgetUsd: 1, spentUsd: 0 }), false, vendor);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
assert.equal(
|
|
224
|
+
el.settingsBudgetRows.map((r) => r.vendor),
|
|
225
|
+
['anthropic'],
|
|
226
|
+
'nothing was stored for any of them',
|
|
227
|
+
);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
Suite('non-finite or negative figures are refused with false and no state change', () => {
|
|
231
|
+
const el = element();
|
|
232
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 15 });
|
|
233
|
+
|
|
234
|
+
const bad: Array<{ budgetUsd: number; spentUsd: number }> = [
|
|
235
|
+
{ budgetUsd: NaN, spentUsd: 1 },
|
|
236
|
+
{ budgetUsd: 1, spentUsd: NaN },
|
|
237
|
+
{ budgetUsd: Infinity, spentUsd: 1 },
|
|
238
|
+
{ budgetUsd: 1, spentUsd: -0.01 },
|
|
239
|
+
{ budgetUsd: -50, spentUsd: 1 },
|
|
240
|
+
// The endpoint's `limitUsd: null` (unlimited) must be dropped by the host,
|
|
241
|
+
// not forwarded; forwarded anyway, it is garbage, not a clear.
|
|
242
|
+
{ budgetUsd: null as unknown as number, spentUsd: 1 },
|
|
243
|
+
];
|
|
244
|
+
for (const figures of bad) {
|
|
245
|
+
assert.is(el.setVendorBudget('anthropic', figures), false, JSON.stringify(figures));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
assert.is(el.settingsBudgetRows[0].figures, '$15.00 / $50.00 (30%)', 'the good figures survive');
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
Suite('garbage warns once per element, not once per call', () => {
|
|
252
|
+
// The documented feed re-runs after every turn, so a host bug would repeat
|
|
253
|
+
// the same warning on every send for the life of the page.
|
|
254
|
+
const el = element();
|
|
255
|
+
|
|
256
|
+
const warns = countWarns(() => {
|
|
257
|
+
assert.is(el.setVendorBudget('openai', { budgetUsd: 1, spentUsd: 0 }), false);
|
|
258
|
+
assert.is(el.setVendorBudget('openai', { budgetUsd: 1, spentUsd: 0 }), false);
|
|
259
|
+
assert.is(el.setVendorBudget('anthropic', { budgetUsd: NaN, spentUsd: 0 }), false);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
assert.is(warns, 1, 'one warning covers the whole broken feed');
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
// ── Not ready yet: the other reason a feed is refused ───────────────────────
|
|
266
|
+
|
|
267
|
+
Suite('a feed before the element has a session store is refused, not silently dropped', () => {
|
|
268
|
+
// The lifecycle window: a host feeding ahead of the first append, or during a
|
|
269
|
+
// pop-out remount, has no store to write to. The dispatch no-ops there, so
|
|
270
|
+
// returning true reported a write that never happened and the caller — which
|
|
271
|
+
// reads the boolean as "accepted" — would never retry.
|
|
272
|
+
const el = document.createElement('foundation-ai-assistant') as FoundationAiAssistant;
|
|
273
|
+
|
|
274
|
+
const warns = countWarns(() => {
|
|
275
|
+
assert.is(el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 }), false);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
assert.is(warns, 0, 'a lifecycle window is not bad input — the warn-once channel is for garbage');
|
|
279
|
+
assert.is(el.settingsBudgetRows.length, 0, 'nothing was stored');
|
|
280
|
+
assert.is(el.settingsBudgetUsageVisible, false, 'and nothing is shown');
|
|
281
|
+
|
|
282
|
+
// The recovery is the documented per-turn re-feed, which lands as soon as the
|
|
283
|
+
// store exists — the connected path is unchanged.
|
|
284
|
+
const ready = element();
|
|
285
|
+
assert.is(ready.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 }), true);
|
|
286
|
+
assert.is(ready.settingsBudgetRows.length, 1);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
// ── Idempotence ─────────────────────────────────────────────────────────────
|
|
290
|
+
|
|
291
|
+
Suite('re-feeding identical figures leaves the stored object untouched', () => {
|
|
292
|
+
// The feed re-runs unconditionally after every turn; identical dollars must
|
|
293
|
+
// not publish a new store reference (and re-render an unchanged meter).
|
|
294
|
+
const el = element();
|
|
295
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 15 });
|
|
296
|
+
const before = storedBudgets(el).anthropic;
|
|
297
|
+
|
|
298
|
+
assert.is(el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 15 }), true);
|
|
299
|
+
|
|
300
|
+
assert.is(storedBudgets(el).anthropic, before, 'same dollars, same object');
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
Suite('the store keeps its own copy, not the host object', () => {
|
|
304
|
+
// The store must not adopt an object the host still owns: immer finalizes
|
|
305
|
+
// whatever the reducer assigns into the draft and FREEZES it — so adoption
|
|
306
|
+
// would freeze state the host believes is its own, turning the host's next
|
|
307
|
+
// `figures.spentUsd += x` into a strict-mode TypeError (or a silent no-op).
|
|
308
|
+
// The frozen-ness probe is the observable that catches adoption directly;
|
|
309
|
+
// the mutation-isolation assertion is the user-visible consequence.
|
|
310
|
+
const el = element();
|
|
311
|
+
const hostFigures: VendorBudgetFigures = { budgetUsd: 50, spentUsd: 15 };
|
|
312
|
+
el.setVendorBudget('anthropic', hostFigures);
|
|
313
|
+
|
|
314
|
+
assert.is(Object.isFrozen(hostFigures), false, 'the host object was not adopted-and-frozen');
|
|
315
|
+
|
|
316
|
+
hostFigures.spentUsd = 999;
|
|
317
|
+
|
|
318
|
+
assert.is(el.settingsBudgetRows[0].figures, '$15.00 / $50.00 (30%)');
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// ── Lifetime ────────────────────────────────────────────────────────────────
|
|
322
|
+
|
|
323
|
+
Suite('the figures survive "Clear" / "New chat" — budget is not conversation state', () => {
|
|
324
|
+
// Same side of the resetSession preserve-list as the blocked latch: a new
|
|
325
|
+
// chat refills no budget, so wiping the meter would blank real dollars until
|
|
326
|
+
// the host's next re-feed. Opposite side from contextTokens, which IS
|
|
327
|
+
// conversation state (a fresh chat genuinely has an empty context window).
|
|
328
|
+
const el = element();
|
|
329
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
330
|
+
el.messages = [{ id: '1', role: 'user', content: 'hello' } as ChatMessage];
|
|
331
|
+
|
|
332
|
+
resetSession(el);
|
|
333
|
+
|
|
334
|
+
assert.is(el.messages.length, 0, 'the transcript is gone');
|
|
335
|
+
assert.is(el.contextTokens, undefined, 'context usage reset with the conversation');
|
|
336
|
+
assert.is(el.settingsBudgetRows[0].figures, '$45.00 / $50.00 (90%)', 'the meter is not');
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
Suite('the figures are per session store — a different stateKey starts empty', () => {
|
|
340
|
+
const first = element();
|
|
341
|
+
const second = element();
|
|
342
|
+
|
|
343
|
+
first.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
344
|
+
|
|
345
|
+
assert.is(first.settingsBudgetRows.length, 1);
|
|
346
|
+
assert.is(second.settingsBudgetRows.length, 0, 'a different session store is unaffected');
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// ── Visibility ──────────────────────────────────────────────────────────────
|
|
350
|
+
|
|
351
|
+
Suite('showBudgetUsage: false hides the meter even with figures fed', () => {
|
|
352
|
+
const el = element();
|
|
353
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
354
|
+
assert.is(el.settingsBudgetUsageVisible, true, 'default ON — undefined shows');
|
|
355
|
+
|
|
356
|
+
el.chatConfig = { ui: { showBudgetUsage: false } };
|
|
357
|
+
|
|
358
|
+
assert.is(el.settingsBudgetUsageVisible, false);
|
|
359
|
+
assert.is(el.settingsBudgetRows.length, 1, 'the state itself is kept, only the render is off');
|
|
360
|
+
|
|
361
|
+
el.chatConfig = { ui: { showBudgetUsage: true } };
|
|
362
|
+
assert.is(el.settingsBudgetUsageVisible, true, 'explicit true shows too');
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
Suite('no figures → the meter behaves like the context indicator with no data', () => {
|
|
366
|
+
// The absent case mirrors settingsContextUsageVisible exactly: nothing to
|
|
367
|
+
// show means no meter AND no "AI Model Settings" section on its account.
|
|
368
|
+
const el = element();
|
|
369
|
+
|
|
370
|
+
assert.is(el.settingsContextUsageVisible, false, 'the sibling gate this one mirrors');
|
|
371
|
+
assert.is(el.settingsBudgetUsageVisible, false);
|
|
372
|
+
assert.is(el.settingsModelSectionVisible, false, 'no slot content, no data — no section');
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
Suite('clearing the last vendor takes the meter back out of view', () => {
|
|
376
|
+
// The gate reads the RAW slice state rather than counting formatted rows, so
|
|
377
|
+
// this is the case that keeps the two readings honest: a vendor that was fed
|
|
378
|
+
// and then cleared must leave NO trace the gate could mistake for data.
|
|
379
|
+
const el = element();
|
|
380
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
381
|
+
assert.is(el.settingsBudgetUsageVisible, true);
|
|
382
|
+
|
|
383
|
+
el.setVendorBudget('anthropic', null);
|
|
384
|
+
|
|
385
|
+
assert.is(el.settingsBudgetUsageVisible, false, 'cleared is invisible, not an empty meter');
|
|
386
|
+
assert.is(el.settingsBudgetRows.length, 0, 'the rows agree');
|
|
387
|
+
assert.is(el.settingsModelSectionVisible, false, 'and the section goes with it');
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
Suite('the visibility gate answers without building a single row', () => {
|
|
391
|
+
// The gate is read several times per render pass — this getter, the section
|
|
392
|
+
// gate, the template's `when` — and answering it through
|
|
393
|
+
// `settingsBudgetRows.length` formatted every vendor's money text each time
|
|
394
|
+
// just to ask whether any rows exist. It reads the raw slice state instead;
|
|
395
|
+
// the context sibling it mirrors gates on a bare `!= null` for the same
|
|
396
|
+
// reason. The rendering path still builds rows, of course — the control below.
|
|
397
|
+
const el = element();
|
|
398
|
+
el.setVendorBudget('anthropic', { budgetUsd: 50, spentUsd: 45 });
|
|
399
|
+
el.setVendorBudget('gemini', { budgetUsd: 200, spentUsd: 30.5 });
|
|
400
|
+
|
|
401
|
+
assert.is(
|
|
402
|
+
countRowBuilds(() => void el.settingsBudgetUsageVisible),
|
|
403
|
+
0,
|
|
404
|
+
'the gate builds nothing',
|
|
405
|
+
);
|
|
406
|
+
assert.is(
|
|
407
|
+
countRowBuilds(() => void el.settingsBudgetRows),
|
|
408
|
+
1,
|
|
409
|
+
'the rendering path does (the control that the probe can see a read at all)',
|
|
410
|
+
);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
Suite('figures alone are enough to surface the AI Model Settings section', () => {
|
|
414
|
+
// The wiring into settingsModelSectionVisible, the same way
|
|
415
|
+
// settingsContextUsageVisible is wired in.
|
|
416
|
+
const el = element();
|
|
417
|
+
assert.is(el.settingsModelSectionVisible, false);
|
|
418
|
+
|
|
419
|
+
el.setVendorBudget('gemini', { budgetUsd: 50, spentUsd: 15 });
|
|
420
|
+
|
|
421
|
+
assert.is(el.settingsModelSectionVisible, true);
|
|
422
|
+
|
|
423
|
+
el.chatConfig = { ui: { showBudgetUsage: false } };
|
|
424
|
+
assert.is(el.settingsModelSectionVisible, false, 'and the config flag takes it back out');
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
Suite.run();
|
package/src/main/main.ts
CHANGED
|
@@ -73,6 +73,7 @@ import {
|
|
|
73
73
|
type AssistantAppSettingsHeading,
|
|
74
74
|
type AssistantAppSettingsToggle,
|
|
75
75
|
} from '../provider/assistant-app-settings';
|
|
76
|
+
import type { VendorBudgetFigures } from '../state/ai-assistant-slice';
|
|
76
77
|
import {
|
|
77
78
|
recordMetaEvent,
|
|
78
79
|
getMetaEvents,
|
|
@@ -144,6 +145,7 @@ import {
|
|
|
144
145
|
deriveCostSessionTitleFromMessages,
|
|
145
146
|
resolveCostSessionTitle,
|
|
146
147
|
} from '../utils/derive-cost-session-title';
|
|
148
|
+
import { formatUsd } from '../utils/format-usd';
|
|
147
149
|
import { logger } from '../utils/logger';
|
|
148
150
|
import { filterVisibleMessages, trailingInteractionRow } from '../utils/message-partition';
|
|
149
151
|
import {
|
|
@@ -163,6 +165,7 @@ import type {
|
|
|
163
165
|
ChatHeaderMouseDownDetail,
|
|
164
166
|
PopoutMode,
|
|
165
167
|
SessionClearedDetail,
|
|
168
|
+
SettingsBudgetRow,
|
|
166
169
|
SubmitMessageResult,
|
|
167
170
|
SuggestionsState,
|
|
168
171
|
} from './main.types';
|
|
@@ -259,7 +262,7 @@ export function formatBlockedReason(
|
|
|
259
262
|
vendor?: AIProviderType,
|
|
260
263
|
): string | undefined {
|
|
261
264
|
if (!budget || (budget.budgetUsd == null && budget.spentUsd == null)) return undefined;
|
|
262
|
-
const money = (v?: number) => (v == null ? 'an unknown amount' :
|
|
265
|
+
const money = (v?: number) => (v == null ? 'an unknown amount' : formatUsd(v));
|
|
263
266
|
const figures = `(${money(budget.spentUsd)} of ${money(budget.budgetUsd)})`;
|
|
264
267
|
// A per-vendor statement carries NO action clause, because the right action is
|
|
265
268
|
// not knowable at latch time: whether "switch vendor" or "contact your
|
|
@@ -305,6 +308,24 @@ function formatVendorList(vendors: readonly AIProviderType[]): string {
|
|
|
305
308
|
return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
|
|
306
309
|
}
|
|
307
310
|
|
|
311
|
+
/**
|
|
312
|
+
* Whole-number percentage of a budget consumed, for the meter (GENC-1464).
|
|
313
|
+
*
|
|
314
|
+
* Deliberately unclamped — spend can genuinely overshoot the cap (the last
|
|
315
|
+
* allowed call may cross it), and the meter's TEXT shows the truth; only the
|
|
316
|
+
* bar clamps, at the render site. The one special case is a `$0` cap, which the
|
|
317
|
+
* platform treats as "no spend allowed" (not "unlimited"): it has no headroom
|
|
318
|
+
* by definition, so the meter reads full rather than dividing by zero.
|
|
319
|
+
*
|
|
320
|
+
* Exported for the unit test that pins the arithmetic; not element API.
|
|
321
|
+
*
|
|
322
|
+
* @internal
|
|
323
|
+
*/
|
|
324
|
+
export function budgetPercentOf(figures: VendorBudgetFigures): number {
|
|
325
|
+
if (figures.budgetUsd <= 0) return 100;
|
|
326
|
+
return Math.round((figures.spentUsd / figures.budgetUsd) * 100);
|
|
327
|
+
}
|
|
328
|
+
|
|
308
329
|
// Register supporting components when the main component module is imported.
|
|
309
330
|
avoidTreeShaking(
|
|
310
331
|
AiChatMarkdown,
|
|
@@ -893,6 +914,118 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
893
914
|
this._sessionRef?.actions.aiAssistant.setVendorBlocked({ vendor, blocked, reason });
|
|
894
915
|
}
|
|
895
916
|
|
|
917
|
+
/**
|
|
918
|
+
* One warning per element for garbage fed to
|
|
919
|
+
* {@link FoundationAiAssistant.setVendorBudget}. Once, not per call, because
|
|
920
|
+
* the documented feed re-runs after every turn — a host bug would otherwise
|
|
921
|
+
* repeat the same warning on every send for the life of the page.
|
|
922
|
+
*/
|
|
923
|
+
private vendorBudgetWarningIssued = false;
|
|
924
|
+
|
|
925
|
+
private warnVendorBudgetOnce(message: string): void {
|
|
926
|
+
if (this.vendorBudgetWarningIssued) return;
|
|
927
|
+
this.vendorBudgetWarningIssued = true;
|
|
928
|
+
logger.warn(`FoundationAiAssistant.setVendorBudget: ${message}`);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Feed (or clear) one vendor's AI-spend figures for the settings-modal budget
|
|
933
|
+
* meter — the numeric companion to
|
|
934
|
+
* {@link FoundationAiAssistant.setVendorBlocked}, and like it a host-driven
|
|
935
|
+
* write: the element meters nothing itself.
|
|
936
|
+
*
|
|
937
|
+
* The meter renders a row for exactly the vendors that currently HAVE
|
|
938
|
+
* figures. An **unlimited** vendor (the budget endpoint reports
|
|
939
|
+
* `unlimited: true` / `limitUsd: null`) is expressed by never feeding it —
|
|
940
|
+
* there is deliberately no "unlimited" figure shape, because a bar with no
|
|
941
|
+
* cap has nothing truthful to fill to. `spentUsd` MAY exceed `budgetUsd`
|
|
942
|
+
* (the last allowed call can overshoot the cap): the row's text shows the
|
|
943
|
+
* real figures and only the bar clamps.
|
|
944
|
+
*
|
|
945
|
+
* Returns `false` — and warns once, not per call — instead of throwing when
|
|
946
|
+
* `vendor` is not a budgeted vendor (`BUDGETED_VENDORS`, the proxy's own
|
|
947
|
+
* metered list) or either figure is not a finite number `>= 0`. Invalid input
|
|
948
|
+
* changes no state. Idempotent: re-feeding a vendor's current figures is a
|
|
949
|
+
* no-op, so hosts can re-feed unconditionally after every turn.
|
|
950
|
+
*
|
|
951
|
+
* `false` ALSO means "not stored, because the element is not ready yet": a
|
|
952
|
+
* feed that lands before the element has its session store (a host calling
|
|
953
|
+
* ahead of the first append, or during a pop-out remount) stores nothing and
|
|
954
|
+
* says so, rather than reporting a write that never happened. That case is
|
|
955
|
+
* transient and needs no host handling — the documented per-turn re-feed is
|
|
956
|
+
* what recovers it — so it is deliberately NOT warned about; the warn-once
|
|
957
|
+
* channel is for garbage input only.
|
|
958
|
+
*
|
|
959
|
+
* `figures` is nullish-checked at run time, so `undefined` behaves exactly
|
|
960
|
+
* like `null` and CLEARS that vendor's row. Untyped JS hosts feed this
|
|
961
|
+
* straight from `GET /api/budget`, where a per-vendor lookup that misses
|
|
962
|
+
* yields `undefined`, not `null` — and "no figures" coherently means "no
|
|
963
|
+
* row". The `| null` parameter type is unchanged for typed callers; the
|
|
964
|
+
* runtime is deliberately the more forgiving of the two.
|
|
965
|
+
*
|
|
966
|
+
* The intended feed is the platform budget endpoint:
|
|
967
|
+
*
|
|
968
|
+
* ```ts
|
|
969
|
+
* // `vendors` is an OBJECT keyed by vendor id, not an array.
|
|
970
|
+
* const { vendors } = await (await fetch('/api/budget')).json();
|
|
971
|
+
* for (const v of Object.values(vendors)) {
|
|
972
|
+
* if (v.unlimited || v.limitUsd == null) {
|
|
973
|
+
* assistantEl.setVendorBudget(v.vendor, null); // clear stale figures after a cap is lifted
|
|
974
|
+
* continue;
|
|
975
|
+
* }
|
|
976
|
+
* assistantEl.setVendorBudget(v.vendor, { budgetUsd: v.limitUsd, spentUsd: v.spentUsd });
|
|
977
|
+
* }
|
|
978
|
+
* ```
|
|
979
|
+
*
|
|
980
|
+
* Re-run it on mount and after each turn. Scope and lifetime follow the rest
|
|
981
|
+
* of the session slice (per `stateKey`, survives pop-in/out and "Clear" /
|
|
982
|
+
* "New chat") — except that the figures are NOT persisted to the session
|
|
983
|
+
* snapshot: the server is authoritative and the host re-feeds at boot, so a
|
|
984
|
+
* persisted copy could only show stale dollars after a reload.
|
|
985
|
+
*
|
|
986
|
+
* @beta
|
|
987
|
+
*/
|
|
988
|
+
setVendorBudget(
|
|
989
|
+
vendor: string,
|
|
990
|
+
figures: { budgetUsd: number; spentUsd: number } | null,
|
|
991
|
+
): boolean {
|
|
992
|
+
if (!(BUDGETED_VENDORS as readonly string[]).includes(vendor)) {
|
|
993
|
+
this.warnVendorBudgetOnce(
|
|
994
|
+
`'${vendor}' is not a budgeted vendor — ignoring. Only the proxy-metered vendors ` +
|
|
995
|
+
`(${BUDGETED_VENDORS.join(', ')}) can carry budget figures.`,
|
|
996
|
+
);
|
|
997
|
+
return false;
|
|
998
|
+
}
|
|
999
|
+
// Nullish, not `!== null`: an untyped host's missing lookup arrives as
|
|
1000
|
+
// `undefined`, and dereferencing it here would throw at a boundary whose
|
|
1001
|
+
// whole contract is to return false instead. `undefined` clears, like null.
|
|
1002
|
+
if (figures != null) {
|
|
1003
|
+
const validUsd = (v: number) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
|
1004
|
+
if (!validUsd(figures.budgetUsd) || !validUsd(figures.spentUsd)) {
|
|
1005
|
+
this.warnVendorBudgetOnce(
|
|
1006
|
+
`invalid figures for '${vendor}' — ignoring. budgetUsd and spentUsd must both be ` +
|
|
1007
|
+
`finite numbers >= 0 (got budgetUsd: ${figures.budgetUsd}, spentUsd: ${figures.spentUsd}).`,
|
|
1008
|
+
);
|
|
1009
|
+
return false;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
const session = this._sessionRef;
|
|
1013
|
+
// No store yet (fed before the first append, or mid pop-out remount): there
|
|
1014
|
+
// is nowhere to write, so say so rather than returning an accepted the
|
|
1015
|
+
// caller would never retry. Not warned — this is a lifecycle window, not
|
|
1016
|
+
// bad input, and the documented per-turn re-feed lands the figures as soon
|
|
1017
|
+
// as the store exists.
|
|
1018
|
+
if (!session) return false;
|
|
1019
|
+
session.actions.aiAssistant.setVendorBudget({
|
|
1020
|
+
vendor: vendor as AIProviderType,
|
|
1021
|
+
// A fresh literal, never the caller's object — see the reducer, which
|
|
1022
|
+
// must not adopt (and potentially freeze) state the host still owns.
|
|
1023
|
+
figures:
|
|
1024
|
+
figures == null ? null : { budgetUsd: figures.budgetUsd, spentUsd: figures.spentUsd },
|
|
1025
|
+
});
|
|
1026
|
+
return true;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
896
1029
|
/** Whether this vendor's wall came from the sweep alone — see the slice's `sweptVendors`. */
|
|
897
1030
|
private isVendorSwept(vendor: AIProviderType): boolean {
|
|
898
1031
|
return (this._sessionRef?.store.aiAssistant.sweptVendors ?? []).includes(vendor);
|
|
@@ -3395,10 +3528,14 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3395
3528
|
return (this.agents ?? []).some((a) => a.manualSelection?.enabled);
|
|
3396
3529
|
}
|
|
3397
3530
|
|
|
3398
|
-
/** Whether the settings modal AI Model section has slotted app content or
|
|
3531
|
+
/** Whether the settings modal AI Model section has slotted app content, context usage or budget figures. */
|
|
3399
3532
|
@volatile
|
|
3400
3533
|
get settingsModelSectionVisible(): boolean {
|
|
3401
|
-
return
|
|
3534
|
+
return (
|
|
3535
|
+
this.settingsModelSlotted.length > 0 ||
|
|
3536
|
+
this.settingsContextUsageVisible ||
|
|
3537
|
+
this.settingsBudgetUsageVisible
|
|
3538
|
+
);
|
|
3402
3539
|
}
|
|
3403
3540
|
|
|
3404
3541
|
/** Built-in context window indicator (generic platform concern). */
|
|
@@ -3410,6 +3547,64 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3410
3547
|
);
|
|
3411
3548
|
}
|
|
3412
3549
|
|
|
3550
|
+
/**
|
|
3551
|
+
* Built-in per-vendor budget meter (GENC-1464) — the money sibling of
|
|
3552
|
+
* {@link FoundationAiAssistant.settingsContextUsageVisible}, with the same
|
|
3553
|
+
* shape of gate: not configured off, and there is data to show. "Data" here
|
|
3554
|
+
* is "at least one vendor has figures", so a host that feeds nothing (or only
|
|
3555
|
+
* unlimited vendors) gets no meter and no empty container — exactly the
|
|
3556
|
+
* context indicator's absent case.
|
|
3557
|
+
*
|
|
3558
|
+
* Answered from the RAW slice state rather than from
|
|
3559
|
+
* {@link FoundationAiAssistant.settingsBudgetRows}, whose `.length` would
|
|
3560
|
+
* format every row (a `formatUsd` pair and a `budgetPercentOf` each) only to
|
|
3561
|
+
* ask whether any exist. This is read several times per render pass — the
|
|
3562
|
+
* getter, the section gate, the template's `when` — so it stays as cheap as
|
|
3563
|
+
* the context sibling's `!= null`.
|
|
3564
|
+
*
|
|
3565
|
+
* @internal
|
|
3566
|
+
*/
|
|
3567
|
+
@volatile
|
|
3568
|
+
get settingsBudgetUsageVisible(): boolean {
|
|
3569
|
+
const budgets = this._sessionRef?.store.aiAssistant.vendorBudgets;
|
|
3570
|
+
return (
|
|
3571
|
+
this.chatConfig.ui?.showBudgetUsage !== false &&
|
|
3572
|
+
budgets != null &&
|
|
3573
|
+
// Keyed off BUDGETED_VENDORS, exactly as the rows are, so a key outside
|
|
3574
|
+
// that list could never surface a meter with no row to show.
|
|
3575
|
+
BUDGETED_VENDORS.some((vendor) => budgets[vendor] != null)
|
|
3576
|
+
);
|
|
3577
|
+
}
|
|
3578
|
+
|
|
3579
|
+
/**
|
|
3580
|
+
* The meter's rows — one per vendor that currently has figures, in
|
|
3581
|
+
* `BUDGETED_VENDORS` order (the proxy's own metered list) so the rendering is
|
|
3582
|
+
* stable however the host ordered its feed calls. Pre-formatted; see
|
|
3583
|
+
* {@link SettingsBudgetRow} for why the text is unclamped while the bar is.
|
|
3584
|
+
*
|
|
3585
|
+
* @internal
|
|
3586
|
+
*/
|
|
3587
|
+
@volatile
|
|
3588
|
+
get settingsBudgetRows(): readonly SettingsBudgetRow[] {
|
|
3589
|
+
const budgets = this._sessionRef?.store.aiAssistant.vendorBudgets;
|
|
3590
|
+
if (!budgets) return [];
|
|
3591
|
+
const rows: SettingsBudgetRow[] = [];
|
|
3592
|
+
for (const vendor of BUDGETED_VENDORS) {
|
|
3593
|
+
const figures = budgets[vendor];
|
|
3594
|
+
if (!figures) continue;
|
|
3595
|
+
const percent = budgetPercentOf(figures);
|
|
3596
|
+
rows.push({
|
|
3597
|
+
vendor,
|
|
3598
|
+
label: vendorDisplayName(vendor),
|
|
3599
|
+
figures: `${formatUsd(figures.spentUsd)} / ${formatUsd(figures.budgetUsd)} (${percent}%)`,
|
|
3600
|
+
// The same clamp the context indicator applies to its bar. No lower
|
|
3601
|
+
// clamp needed: the boundary refuses negative figures.
|
|
3602
|
+
barValue: Math.min(100, percent),
|
|
3603
|
+
});
|
|
3604
|
+
}
|
|
3605
|
+
return rows;
|
|
3606
|
+
}
|
|
3607
|
+
|
|
3413
3608
|
/** Whether the settings modal UI Builder section should render. */
|
|
3414
3609
|
@volatile
|
|
3415
3610
|
get settingsAppSectionVisible(): boolean {
|