@zeyos/zx 5.4.0 → 5.6.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/CHANGELOG.md +136 -0
- package/README.md +23 -16
- package/dist/types/components/agent-thread/agent-thread.d.ts +583 -0
- package/dist/types/components/app-sidebar/app-sidebar.d.ts +33 -0
- package/dist/types/components/approval-card/approval-card.d.ts +596 -0
- package/dist/types/components/avatar/avatar.d.ts +91 -4
- package/dist/types/components/badge/badge.d.ts +5 -4
- package/dist/types/components/block-view/block-view.d.ts +205 -0
- package/dist/types/components/composer/composer.d.ts +736 -0
- package/dist/types/components/datebox/date-range-box.d.ts +15 -2
- package/dist/types/components/datebox/datebox.d.ts +37 -3
- package/dist/types/components/kbd/kbd.d.ts +41 -0
- package/dist/types/components/launcher/launcher.d.ts +4 -2
- package/dist/types/components/prose/prose.d.ts +69 -0
- package/dist/types/components/questionnaire/questionnaire.d.ts +0 -36
- package/dist/types/components/run-status/run-status.d.ts +393 -0
- package/dist/types/components/run-trace/run-trace.d.ts +624 -0
- package/dist/types/components/source-list/source-list.d.ts +177 -0
- package/dist/types/components/stat-tile/stat-tile.d.ts +20 -0
- package/dist/types/components/tag-picker/tag-picker.d.ts +11 -5
- package/dist/types/components/tree/tree.d.ts +44 -3
- package/dist/types/core/icons.d.ts +22 -1
- package/dist/types/core/messages.d.ts +135 -0
- package/dist/types/index.d.ts +12 -2
- package/dist/types/internal/agent-model.d.ts +587 -0
- package/dist/types/internal/app-rail.d.ts +10 -3
- package/dist/types/internal/highlight.d.ts +24 -0
- package/dist/types/internal/presence-loop.d.ts +148 -0
- package/dist/types/internal/row-actions.d.ts +151 -0
- package/dist/zx-zeyos.esm.js +4852 -4535
- package/dist/zx-zeyos.esm.min.js +4 -4
- package/dist/zx.css +3152 -434
- package/dist/zx.esm.js +13730 -6595
- package/dist/zx.esm.min.js +27 -8
- package/dist/zx.global.js +13730 -6595
- package/dist/zx.global.min.js +27 -8
- package/dist/zx.min.css +1 -1
- package/docs/api.json +1474 -205
- package/docs/llms.md +698 -39
- package/docs/llms.txt +12 -1
- package/package.json +1 -1
- package/src/components/account-menu/account-menu.js +2 -2
- package/src/components/agent-thread/agent-thread.css +417 -0
- package/src/components/agent-thread/agent-thread.js +1365 -0
- package/src/components/app-rail/app-rail.css +11 -11
- package/src/components/app-sidebar/app-sidebar.css +90 -17
- package/src/components/app-sidebar/app-sidebar.js +120 -12
- package/src/components/approval-card/approval-card.css +289 -0
- package/src/components/approval-card/approval-card.js +1377 -0
- package/src/components/avatar/avatar.css +56 -1
- package/src/components/avatar/avatar.js +148 -26
- package/src/components/badge/badge.css +33 -20
- package/src/components/badge/badge.js +5 -4
- package/src/components/block-view/block-view.css +300 -0
- package/src/components/block-view/block-view.js +523 -0
- package/src/components/breadcrumb/breadcrumb.css +28 -3
- package/src/components/breadcrumb/breadcrumb.js +2 -2
- package/src/components/button/button.css +24 -13
- package/src/components/button/button.js +20 -2
- package/src/components/calendar/calendar.css +14 -4
- package/src/components/card-view/card-view.js +2 -2
- package/src/components/chart/chart.js +20 -5
- package/src/components/check-button/check-button.css +11 -3
- package/src/components/check-button/check-button.js +3 -3
- package/src/components/composer/composer.css +403 -0
- package/src/components/composer/composer.js +1441 -0
- package/src/components/context-menu/context-menu.css +7 -1
- package/src/components/date-picker/date-picker.css +6 -0
- package/src/components/date-picker/date-picker.js +5 -5
- package/src/components/date-picker/date-range-picker.css +6 -0
- package/src/components/date-picker/date-range-picker.js +3 -3
- package/src/components/date-picker/month-picker.js +3 -3
- package/src/components/date-picker/time-picker.css +6 -0
- package/src/components/datebox/date-range-box.js +30 -6
- package/src/components/datebox/datebox.js +44 -7
- package/src/components/dialog/dialog.css +0 -1
- package/src/components/dialog/dialog.js +2 -1
- package/src/components/dock/dock.js +2 -2
- package/src/components/dropdown/dropdown.css +2 -1
- package/src/components/entity-ref/entity-ref.css +8 -1
- package/src/components/file-item/file-item.css +1 -1
- package/src/components/finder/finder.js +2 -2
- package/src/components/groupbox/groupbox.js +2 -2
- package/src/components/kanban-view/kanban-view.css +8 -4
- package/src/components/kanban-view/kanban-view.js +3 -3
- package/src/components/kbd/kbd.css +64 -0
- package/src/components/kbd/kbd.js +121 -0
- package/src/components/launcher/launcher.css +30 -25
- package/src/components/launcher/launcher.js +15 -21
- package/src/components/list-toolbar/list-toolbar.css +7 -1
- package/src/components/menu-button/menu-button.css +9 -2
- package/src/components/message/message.js +2 -2
- package/src/components/module-bar/module-bar.css +11 -1
- package/src/components/multi-value-editor/multi-value-editor.js +4 -4
- package/src/components/navigation-bar/navigation-bar.css +3 -2
- package/src/components/pagination/pagination.js +2 -2
- package/src/components/panel/panel.js +2 -2
- package/src/components/prose/prose.css +53 -0
- package/src/components/prose/prose.js +152 -0
- package/src/components/questionnaire/questionnaire.css +7 -17
- package/src/components/questionnaire/questionnaire.js +16 -1
- package/src/components/rating/rating.css +3 -1
- package/src/components/run-status/run-status.css +208 -0
- package/src/components/run-status/run-status.js +782 -0
- package/src/components/run-trace/run-trace.css +443 -0
- package/src/components/run-trace/run-trace.js +1209 -0
- package/src/components/search/search.js +2 -2
- package/src/components/select/glyphs.js +3 -3
- package/src/components/select/select.css +35 -7
- package/src/components/select/select.js +4 -4
- package/src/components/source-list/source-list.css +208 -0
- package/src/components/source-list/source-list.js +355 -0
- package/src/components/stat-tile/stat-tile.css +56 -2
- package/src/components/stat-tile/stat-tile.js +25 -2
- package/src/components/stepper/stepper.css +2 -1
- package/src/components/stepper/stepper.js +3 -3
- package/src/components/tabbox/tabbox.css +2 -2
- package/src/components/tabbox/tabbox.js +2 -2
- package/src/components/table/table.css +52 -16
- package/src/components/table/table.js +7 -5
- package/src/components/tag-picker/tag-picker.css +56 -43
- package/src/components/tag-picker/tag-picker.js +21 -16
- package/src/components/tree/tree.css +44 -0
- package/src/components/tree/tree.js +97 -9
- package/src/components/value-list/value-list.css +25 -4
- package/src/components/value-list/value-list.js +2 -1
- package/src/components/view/record-view.js +3 -3
- package/src/components/view-settings/view-settings.css +2 -1
- package/src/components/workspace-switcher/workspace-switcher.js +3 -3
- package/src/core/icons.js +34 -3
- package/src/core/messages.js +143 -0
- package/src/elements/define.js +1 -0
- package/src/index.js +12 -2
- package/src/internal/agent-model.js +488 -0
- package/src/internal/app-rail.js +5 -1
- package/src/internal/highlight.js +104 -0
- package/src/internal/presence-loop.js +343 -0
- package/src/internal/row-actions.js +203 -0
- package/styles/base.css +26 -1
- package/styles/prose.css +306 -0
- package/styles/tokens/dark.css +97 -120
- package/styles/tokens/global.css +24 -9
- package/styles/tokens/semantic.css +464 -184
- package/styles/tokens/themes.css +9 -0
- package/styles/zx.css +10 -0
|
@@ -0,0 +1,782 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { Component } from '../../core/component.js';
|
|
3
|
+
import { formatDate, isSameDay } from '../../core/date.js';
|
|
4
|
+
import { h, restoreTarget, snapshotTarget } from '../../core/dom.js';
|
|
5
|
+
import { formatCurrency, formatNumber } from '../../core/format.js';
|
|
6
|
+
import { getLanguage, printf } from '../../core/i18n.js';
|
|
7
|
+
import { AGENT_MESSAGES, STATUS, formatElapsed, normalizeRunState } from '../../internal/agent-model.js';
|
|
8
|
+
import { button } from '../button/button.js';
|
|
9
|
+
import { statusIcon } from '../select/glyphs.js';
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('../../internal/agent-model.js').RunState} RunState */
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A button beside the run's state, for what the reader can do about it now: "Review the request"
|
|
15
|
+
* while it waits, "Renew the consent" when it failed.
|
|
16
|
+
* @typedef {Object} RunStatusAction
|
|
17
|
+
* @property {string} label Visible label.
|
|
18
|
+
* @property {'default'|'primary'|'danger'|'ghost'} [kind='default'] Visual intent.
|
|
19
|
+
* @property {string|null} [icon=null] Icon name.
|
|
20
|
+
* @property {(event: MouseEvent) => void} [onclick] Called on activation, before the `action` event.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* What a run has cost so far, and the budget it may spend.
|
|
25
|
+
* @typedef {Object} RunCost
|
|
26
|
+
* @property {number} amount Spent so far.
|
|
27
|
+
* @property {number|null} [budget] The most it may spend. With a budget the cost is a meter that
|
|
28
|
+
* turns to the warning tone from 80% and to the danger tone at 100%.
|
|
29
|
+
* @property {string} [currency] ISO 4217 code, such as `EUR`.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** @typedef {{done: number, total: number}} RunSteps */
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Tokens a run has used: `[input, output]`, or the total as a single number.
|
|
36
|
+
* @typedef {[number, number]|number} RunTokens
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* How the state is drawn on its own: `'word'` is the glyph and the word (`compact: true`), `'icon'`
|
|
41
|
+
* the glyph alone with the word kept for assistive technology and the tooltip.
|
|
42
|
+
* @typedef {'word'|'icon'} RunCompactMode
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The tokens drawn as a meter against their budget.
|
|
47
|
+
* @typedef {Object} RunTokenMeter
|
|
48
|
+
* @property {number} total Tokens used.
|
|
49
|
+
* @property {number} budget The most the run may use.
|
|
50
|
+
* @property {'normal'|'warning'|'danger'} level `warning` from 80%, `danger` at 100%.
|
|
51
|
+
* @property {string} text "22.8K of 60K tokens".
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
/** A local ISO date-time string (`2026-09-29T11:20:04`) or a `Date`. @typedef {string|Date} RunTime */
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @typedef {Object} RunStatusOptions
|
|
58
|
+
* @property {RunState} [state='queued'] Where the run stands. Also the root's `data-state`. A
|
|
59
|
+
* `blocked` run is not over: it shows since when it is blocked, never a finished time.
|
|
60
|
+
* @property {string} [summary=''] One sentence on what is happening: "Step 3 of 6 needs your
|
|
61
|
+
* approval." Text only.
|
|
62
|
+
* @property {RunSteps|null} [steps=null] Steps done out of the total, drawn as a progressbar.
|
|
63
|
+
* @property {RunTime|null} [started=null] When the run started.
|
|
64
|
+
* @property {RunTime|null} [finished=null] When it finished, failed, or was stopped. Shown once
|
|
65
|
+
* the run is over.
|
|
66
|
+
* @property {number|null} [workMs=null] How long the agent has worked, in milliseconds. Waiting
|
|
67
|
+
* for a person is not work. The row shows only when this is a number.
|
|
68
|
+
* @property {RunTime|null} [waitingSince=null] Since when the run has waited for a person, or been
|
|
69
|
+
* blocked. Shown as "Waiting since" while the state is `waiting` and "Blocked since" while it is
|
|
70
|
+
* `blocked`.
|
|
71
|
+
* @property {RunTokens|null} [tokens=null] Input and output tokens as `[in, out]`, or the total as
|
|
72
|
+
* one number.
|
|
73
|
+
* @property {number|null} [tokenBudget=null] The most tokens the run may use. With a budget the
|
|
74
|
+
* tokens are a meter, read in compact figures ("22.8K of 60K tokens"), that turns to the warning
|
|
75
|
+
* tone from 80% and to the danger tone at 100%. Without one they stay text.
|
|
76
|
+
* @property {RunCost|null} [cost=null] What the run has cost, against its budget.
|
|
77
|
+
* @property {string|null} [model=null] The model the agent runs on.
|
|
78
|
+
* @property {RunStatusAction[]} [actions=[]] Buttons under the summary.
|
|
79
|
+
* @property {boolean} [ticking=true] While the state is `running`, the working time counts on
|
|
80
|
+
* once a second from `workMs` and the moment of the last `update()`. One interval, which sleeps
|
|
81
|
+
* while the page is hidden.
|
|
82
|
+
* @property {boolean|'icon'} [compact=false] Draws only the state: `true` as a pill of glyph and
|
|
83
|
+
* word for a narrow header, `'icon'` as the glyph alone, its word visually hidden but still the
|
|
84
|
+
* accessible text, and shown as the pill's tooltip.
|
|
85
|
+
* @property {(() => Date)|null} [now=null] The clock: what decides whether a time is today (a
|
|
86
|
+
* time on another day shows its date too) and what the working time counts against while
|
|
87
|
+
* `ticking`. Null is real time. Fixed at construction.
|
|
88
|
+
* @property {string} [locale] BCP 47 tag for numbers and amounts; defaults to the active language.
|
|
89
|
+
* @property {Record<string, string>|Record<string, Record<string, string>>} [msg] Localized
|
|
90
|
+
* messages: the state words (`agent.status.*`) and the `runStatus.*` labels.
|
|
91
|
+
* @property {(event: CustomEvent<{index: number, action: RunStatusAction}>) => void} [onaction]
|
|
92
|
+
* Action listener.
|
|
93
|
+
*/
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The run's values as they stand. `workMs` includes the time counted since the last update.
|
|
97
|
+
* @typedef {Object} RunStatusState
|
|
98
|
+
* @property {RunState} state
|
|
99
|
+
* @property {string} summary
|
|
100
|
+
* @property {RunSteps|null} steps
|
|
101
|
+
* @property {RunTime|null} started
|
|
102
|
+
* @property {RunTime|null} finished
|
|
103
|
+
* @property {number|null} workMs
|
|
104
|
+
* @property {RunTime|null} waitingSince
|
|
105
|
+
* @property {RunTokens|null} tokens
|
|
106
|
+
* @property {number|null} tokenBudget
|
|
107
|
+
* @property {RunCost|null} cost
|
|
108
|
+
* @property {string|null} model
|
|
109
|
+
* @property {RunStatusAction[]} actions
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
const MESSAGES = Object.freeze({
|
|
113
|
+
...AGENT_MESSAGES,
|
|
114
|
+
'runStatus.started': 'Started',
|
|
115
|
+
'runStatus.workingTime': 'Working time',
|
|
116
|
+
'runStatus.waitingSince': 'Waiting since',
|
|
117
|
+
'runStatus.blockedSince': 'Blocked since',
|
|
118
|
+
'runStatus.finished': 'Finished',
|
|
119
|
+
'runStatus.failedAt': 'Failed at',
|
|
120
|
+
'runStatus.stoppedAt': 'Stopped at',
|
|
121
|
+
'runStatus.model': 'Model',
|
|
122
|
+
'runStatus.tokens': 'Tokens',
|
|
123
|
+
'runStatus.tokensValue': '%1 in · %2 out',
|
|
124
|
+
'runStatus.tokenBudget': '%1 of %2 tokens',
|
|
125
|
+
'runStatus.costLabel': 'Cost',
|
|
126
|
+
'runStatus.cost': '%1 of %2',
|
|
127
|
+
'runStatus.stepsLabel': 'Steps done',
|
|
128
|
+
'runStatus.steps': '%1 of %2 steps',
|
|
129
|
+
'runStatus.timeFormat': '%H:%M',
|
|
130
|
+
'runStatus.dateTimeFormat': '%e %b, %H:%M'
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
/** The values `update()` merges; everything else is fixed at construction. */
|
|
134
|
+
const VALUE_KEYS = Object.freeze(['state', 'summary', 'steps', 'started', 'finished', 'workMs', 'waitingSince',
|
|
135
|
+
'tokens', 'tokenBudget', 'cost', 'model', 'actions', 'ticking', 'compact']);
|
|
136
|
+
|
|
137
|
+
/** The label of the "finished" row for each state that ends a run. */
|
|
138
|
+
const FINISHED_KEYS = Object.freeze({
|
|
139
|
+
done: 'runStatus.finished',
|
|
140
|
+
failed: 'runStatus.failedAt',
|
|
141
|
+
stopped: 'runStatus.stoppedAt',
|
|
142
|
+
skipped: 'runStatus.finished'
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The label of the "since" row for each state that holds the run for someone or something. A
|
|
147
|
+
* blocked run is not over: it shows since when it has been blocked, never when it finished.
|
|
148
|
+
*/
|
|
149
|
+
const SINCE_KEYS = Object.freeze({
|
|
150
|
+
waiting: 'runStatus.waitingSince',
|
|
151
|
+
blocked: 'runStatus.blockedSince'
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
/** What can take focus inside the panel, in document order. */
|
|
155
|
+
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), '
|
|
156
|
+
+ 'textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Where an agent's run stands: its state in a glyph and a word, a sentence on what is happening,
|
|
160
|
+
* its steps as a progressbar, when it started and how long the agent has worked, what it has cost
|
|
161
|
+
* against its budget, and the buttons for what the reader can do about it now. `compact` draws the
|
|
162
|
+
* state alone, for a header.
|
|
163
|
+
*
|
|
164
|
+
* It announces nothing itself: the conversation the run belongs to says when it starts, waits,
|
|
165
|
+
* fails, or finishes.
|
|
166
|
+
*
|
|
167
|
+
* @fires RunStatus#action
|
|
168
|
+
* @extends {Component<RunStatusOptions>}
|
|
169
|
+
*/
|
|
170
|
+
export class RunStatus extends Component {
|
|
171
|
+
static cssName = 'run-status';
|
|
172
|
+
|
|
173
|
+
/** @type {Readonly<RunStatusOptions>} */
|
|
174
|
+
static defaults = {
|
|
175
|
+
state: 'queued',
|
|
176
|
+
summary: '',
|
|
177
|
+
steps: null,
|
|
178
|
+
started: null,
|
|
179
|
+
finished: null,
|
|
180
|
+
workMs: null,
|
|
181
|
+
waitingSince: null,
|
|
182
|
+
tokens: null,
|
|
183
|
+
tokenBudget: null,
|
|
184
|
+
cost: null,
|
|
185
|
+
model: null,
|
|
186
|
+
actions: [],
|
|
187
|
+
ticking: true,
|
|
188
|
+
compact: false,
|
|
189
|
+
now: null,
|
|
190
|
+
msg: MESSAGES
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
/** @returns {HTMLElement} */
|
|
194
|
+
render() {
|
|
195
|
+
const created = !this.el;
|
|
196
|
+
const root = /** @type {HTMLElement} */ (this.el ?? h('div'));
|
|
197
|
+
this.el = root;
|
|
198
|
+
this._original = created ? null : snapshotTarget(root);
|
|
199
|
+
if (!created) root.replaceChildren();
|
|
200
|
+
/** @type {Record<string, any>} */
|
|
201
|
+
this._values = {};
|
|
202
|
+
for (const key of VALUE_KEYS) this._values[key] = copyValue(this.options[key]);
|
|
203
|
+
this._workBase = finiteOrNull(this.options.workMs);
|
|
204
|
+
this._workAt = this._clock();
|
|
205
|
+
/** @type {HTMLElement|null} */
|
|
206
|
+
this._elapsed = null;
|
|
207
|
+
/** @type {HTMLElement|null} The action row as drawn, kept across updates that leave it unchanged. */
|
|
208
|
+
this._actionsEl = null;
|
|
209
|
+
this._actionsKey = '';
|
|
210
|
+
/** Whether the root took `tabindex="-1"` to hold focus that had nowhere else to go. */
|
|
211
|
+
this._heldFocus = false;
|
|
212
|
+
/** @type {ReturnType<typeof setInterval>|0} */
|
|
213
|
+
this._interval = 0;
|
|
214
|
+
this._destroyed = false;
|
|
215
|
+
const doc = root.ownerDocument;
|
|
216
|
+
this.listen(root, 'click', (event) => this._onClick(/** @type {MouseEvent} */ (event)));
|
|
217
|
+
this.listen(root, 'blur', () => this._releaseFocus());
|
|
218
|
+
this.listen(doc, 'visibilitychange', () => {
|
|
219
|
+
if (!doc.hidden) this._tick();
|
|
220
|
+
this._syncTicker();
|
|
221
|
+
});
|
|
222
|
+
this._draw();
|
|
223
|
+
return root;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Merges new values and redraws. The working time carries on from where it stood unless the
|
|
228
|
+
* update brings a new `workMs`. Focus inside the panel stays where it was: an action row that
|
|
229
|
+
* did not change is kept as it is, and otherwise focus moves to the action at the same index (or
|
|
230
|
+
* the nearest one left), or to the panel itself when no action is left.
|
|
231
|
+
* @param {Partial<Omit<RunStatusOptions, 'locale'|'msg'|'onaction'|'now'>>} values
|
|
232
|
+
* @returns {this}
|
|
233
|
+
*/
|
|
234
|
+
update(values = {}) {
|
|
235
|
+
if (this._destroyed || !values || typeof values !== 'object') return this;
|
|
236
|
+
const current = this._workTime();
|
|
237
|
+
for (const key of VALUE_KEYS) {
|
|
238
|
+
if (Object.hasOwn(values, key)) this._values[key] = copyValue(/** @type {Record<string, unknown>} */ (values)[key]);
|
|
239
|
+
}
|
|
240
|
+
this._workBase = Object.hasOwn(values, 'workMs') ? finiteOrNull(values.workMs) : current;
|
|
241
|
+
this._workAt = this._clock();
|
|
242
|
+
this._draw();
|
|
243
|
+
return this;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** @returns {RunStatusState} The run's values as they stand, as copies. */
|
|
247
|
+
getState() {
|
|
248
|
+
const values = this._values;
|
|
249
|
+
return {
|
|
250
|
+
state: normalizeRunState(values.state),
|
|
251
|
+
summary: String(values.summary ?? ''),
|
|
252
|
+
steps: copyValue(values.steps) ?? null,
|
|
253
|
+
started: values.started ?? null,
|
|
254
|
+
finished: values.finished ?? null,
|
|
255
|
+
workMs: this._workTime(),
|
|
256
|
+
waitingSince: values.waitingSince ?? null,
|
|
257
|
+
tokens: copyValue(values.tokens) ?? null,
|
|
258
|
+
tokenBudget: finiteOrNull(values.tokenBudget),
|
|
259
|
+
cost: copyValue(values.cost) ?? null,
|
|
260
|
+
model: values.model ?? null,
|
|
261
|
+
actions: Array.isArray(values.actions) ? [...values.actions] : []
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Stops the clock, removes what the component drew, and restores an enhanced target. @returns {void} */
|
|
266
|
+
destroy() {
|
|
267
|
+
if (this._destroyed) return;
|
|
268
|
+
this._destroyed = true;
|
|
269
|
+
this._stopTicker();
|
|
270
|
+
this._releaseFocus();
|
|
271
|
+
super.destroy();
|
|
272
|
+
if (this._original) restoreTarget(this.el, this._original);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** @private @returns {number} Milliseconds on the clock the working time counts against. */
|
|
276
|
+
_clock() {
|
|
277
|
+
return typeof this.options.now === 'function' ? currentTime(this.options.now).getTime() : clock();
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** @private @returns {number|null} Milliseconds worked, including the time counted since the last update. */
|
|
281
|
+
_workTime() {
|
|
282
|
+
if (this._workBase === null) return null;
|
|
283
|
+
const counting = this._values.ticking !== false && normalizeRunState(this._values.state) === 'running';
|
|
284
|
+
return this._workBase + (counting ? Math.max(0, this._clock() - this._workAt) : 0);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** @private @returns {void} */
|
|
288
|
+
_draw() {
|
|
289
|
+
const root = /** @type {HTMLElement} */ (this.el);
|
|
290
|
+
const values = this._values;
|
|
291
|
+
const state = normalizeRunState(values.state);
|
|
292
|
+
const mode = compactMode(values.compact);
|
|
293
|
+
const focus = this._focusKey();
|
|
294
|
+
if (root.ownerDocument.activeElement !== root) this._releaseFocus();
|
|
295
|
+
root.dataset.state = state;
|
|
296
|
+
if (mode) root.setAttribute('data-compact', mode === 'icon' ? 'icon' : '');
|
|
297
|
+
else root.removeAttribute('data-compact');
|
|
298
|
+
this._elapsed = null;
|
|
299
|
+
if (mode) {
|
|
300
|
+
this._actionsEl = null;
|
|
301
|
+
this._actionsKey = '';
|
|
302
|
+
const word = this.msg(STATUS[state].key);
|
|
303
|
+
this._place([h('span', { class: 'zx-run-status__pill', title: mode === 'icon' ? word : undefined },
|
|
304
|
+
...this._stateParts(state))]);
|
|
305
|
+
this._restoreFocus(focus);
|
|
306
|
+
this._syncTicker();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const steps = stepProgress(values.steps);
|
|
310
|
+
const summary = values.summary == null ? '' : String(values.summary);
|
|
311
|
+
const rows = this._rows(state);
|
|
312
|
+
this._place([
|
|
313
|
+
h('p', { class: 'zx-run-status__state' }, ...this._stateParts(state)),
|
|
314
|
+
summary ? h('p', { class: 'zx-run-status__summary' }, summary) : null,
|
|
315
|
+
steps ? this._steps(steps) : null,
|
|
316
|
+
this._actions(),
|
|
317
|
+
rows.length ? h('dl', { class: 'zx-run-status__props' }, rows.map(([key, value]) => h('div', { class: 'zx-run-status__prop' },
|
|
318
|
+
h('dt', { class: 'zx-run-status__label' }, this.msg(key)),
|
|
319
|
+
h('dd', { class: 'zx-run-status__value' }, value)))) : null
|
|
320
|
+
]);
|
|
321
|
+
this._restoreFocus(focus);
|
|
322
|
+
this._syncTicker();
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Puts the drawn parts in the root in order. A part kept from the last draw stays where it is
|
|
327
|
+
* rather than being taken out and put back, so focus inside it survives.
|
|
328
|
+
* @private
|
|
329
|
+
* @param {Array<Node|null>} parts
|
|
330
|
+
* @returns {void}
|
|
331
|
+
*/
|
|
332
|
+
_place(parts) {
|
|
333
|
+
const root = /** @type {HTMLElement} */ (this.el);
|
|
334
|
+
const nodes = parts.filter((node) => node !== null);
|
|
335
|
+
const keep = new Set(nodes);
|
|
336
|
+
for (const node of Array.from(root.childNodes)) {
|
|
337
|
+
if (!keep.has(node)) node.remove();
|
|
338
|
+
}
|
|
339
|
+
let next = root.firstChild;
|
|
340
|
+
for (const node of nodes) {
|
|
341
|
+
if (node === next) next = next.nextSibling;
|
|
342
|
+
else root.insertBefore(node, next);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* The action row: the one already drawn when the actions read the same, a new one otherwise.
|
|
348
|
+
* @private
|
|
349
|
+
* @returns {HTMLElement|null}
|
|
350
|
+
*/
|
|
351
|
+
_actions() {
|
|
352
|
+
const actions = Array.isArray(this._values.actions) ? this._values.actions : [];
|
|
353
|
+
if (!actions.length) {
|
|
354
|
+
this._actionsEl = null;
|
|
355
|
+
this._actionsKey = '';
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
const key = JSON.stringify(actions.map((action) => [String(action?.label ?? ''), action?.kind ?? null, action?.icon ?? null]));
|
|
359
|
+
if (this._actionsEl && key === this._actionsKey) return this._actionsEl;
|
|
360
|
+
this._actionsKey = key;
|
|
361
|
+
this._actionsEl = h('div', { class: 'zx-run-status__actions' }, actions.map((action, index) => {
|
|
362
|
+
const element = button({
|
|
363
|
+
label: String(action?.label ?? ''), kind: action?.kind, icon: action?.icon ?? null, size: 'sm'
|
|
364
|
+
});
|
|
365
|
+
element.dataset.runAction = String(index);
|
|
366
|
+
return element;
|
|
367
|
+
}));
|
|
368
|
+
return this._actionsEl;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Where focus is inside the panel, in terms that survive a redraw: the index of an action, or
|
|
373
|
+
* of a focusable element among all of them.
|
|
374
|
+
* @private
|
|
375
|
+
* @returns {{action: number}|{focusable: number}|null} Null when focus is elsewhere, or on the root.
|
|
376
|
+
*/
|
|
377
|
+
_focusKey() {
|
|
378
|
+
const root = /** @type {HTMLElement} */ (this.el);
|
|
379
|
+
const active = root.ownerDocument.activeElement;
|
|
380
|
+
if (!active || active === root || !root.contains(active)) return null;
|
|
381
|
+
const control = /** @type {HTMLElement|null} */ (active.closest('[data-run-action]'));
|
|
382
|
+
if (control && root.contains(control)) return { action: Number(control.dataset.runAction) };
|
|
383
|
+
const index = Array.from(root.querySelectorAll(FOCUSABLE)).indexOf(active);
|
|
384
|
+
return index >= 0 ? { focusable: index } : null;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Puts focus back after a redraw when the element that had it is gone: on the action at the same
|
|
389
|
+
* index or the nearest one left, else on the focusable at the same index, else on the root.
|
|
390
|
+
* @private
|
|
391
|
+
* @param {{action: number}|{focusable: number}|null} key What `_focusKey()` returned before the draw.
|
|
392
|
+
* @returns {void}
|
|
393
|
+
*/
|
|
394
|
+
_restoreFocus(key) {
|
|
395
|
+
if (!key) return;
|
|
396
|
+
const root = /** @type {HTMLElement} */ (this.el);
|
|
397
|
+
const active = root.ownerDocument.activeElement;
|
|
398
|
+
if (active && active !== root.ownerDocument.body && root.contains(active)) return;
|
|
399
|
+
const pick = (/** @type {Element[]} */ list, /** @type {number} */ index) => list[Math.min(index, list.length - 1)] ?? null;
|
|
400
|
+
const target = 'action' in key
|
|
401
|
+
? pick(Array.from(root.querySelectorAll('[data-run-action]')), key.action)
|
|
402
|
+
?? pick(Array.from(root.querySelectorAll(FOCUSABLE)), 0)
|
|
403
|
+
: pick(Array.from(root.querySelectorAll(FOCUSABLE)), key.focusable);
|
|
404
|
+
if (target instanceof HTMLElement) {
|
|
405
|
+
target.focus({ preventScroll: true });
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (!root.hasAttribute('tabindex')) {
|
|
409
|
+
root.tabIndex = -1;
|
|
410
|
+
this._heldFocus = true;
|
|
411
|
+
}
|
|
412
|
+
root.focus({ preventScroll: true });
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** @private Gives back the `tabindex` the root took to hold focus. @returns {void} */
|
|
416
|
+
_releaseFocus() {
|
|
417
|
+
if (!this._heldFocus) return;
|
|
418
|
+
this._heldFocus = false;
|
|
419
|
+
this.el.removeAttribute('tabindex');
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** @private @param {RunState} state @returns {Node[]} The state's glyph and its word. */
|
|
423
|
+
_stateParts(state) {
|
|
424
|
+
const entry = STATUS[state];
|
|
425
|
+
return [
|
|
426
|
+
statusIcon(entry.status, { tone: /** @type {import('../select/glyphs.js').StatusTone} */ (entry.tone) }),
|
|
427
|
+
h('span', { class: 'zx-run-status__word' }, this.msg(entry.key))
|
|
428
|
+
];
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** @private @param {{done: number, total: number, percent: number}} steps @returns {HTMLElement} */
|
|
432
|
+
_steps(steps) {
|
|
433
|
+
const locale = this.options.locale;
|
|
434
|
+
const done = formatNumber(steps.done, { locale });
|
|
435
|
+
const total = formatNumber(steps.total, { locale });
|
|
436
|
+
return h('div', { class: 'zx-run-status__steps' },
|
|
437
|
+
h('span', {
|
|
438
|
+
class: 'zx-run-status__bar',
|
|
439
|
+
role: 'progressbar',
|
|
440
|
+
'aria-label': this.msg('runStatus.stepsLabel'),
|
|
441
|
+
'aria-valuemin': '0',
|
|
442
|
+
'aria-valuemax': String(steps.total),
|
|
443
|
+
'aria-valuenow': String(steps.done),
|
|
444
|
+
'aria-valuetext': this.msg('runStatus.steps', done, total)
|
|
445
|
+
}, h('span', { class: 'zx-run-status__bar-fill', style: { inlineSize: `${steps.percent}%` } })),
|
|
446
|
+
h('span', { class: 'zx-run-status__steps-text', 'aria-hidden': 'true' }, `${done}/${total}`));
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* The property rows that apply to the state: started, working time, waiting or blocked since,
|
|
451
|
+
* or finished, then model, tokens, and cost.
|
|
452
|
+
* @private
|
|
453
|
+
* @param {RunState} state
|
|
454
|
+
* @returns {Array<[string, Node|string|Array<Node>]>}
|
|
455
|
+
*/
|
|
456
|
+
_rows(state) {
|
|
457
|
+
const values = this._values;
|
|
458
|
+
const locale = this.options.locale;
|
|
459
|
+
const keys = runTimeKeys(state);
|
|
460
|
+
/** @type {Array<[string, Node|string|Array<Node>]>} */
|
|
461
|
+
const rows = [];
|
|
462
|
+
const started = this._time(values.started);
|
|
463
|
+
if (started) rows.push(['runStatus.started', started]);
|
|
464
|
+
const worked = this._workTime();
|
|
465
|
+
if (worked !== null) {
|
|
466
|
+
this._elapsed = h('span', { class: 'zx-run-status__elapsed' }, formatElapsed(worked));
|
|
467
|
+
rows.push(['runStatus.workingTime', this._elapsed]);
|
|
468
|
+
}
|
|
469
|
+
const since = keys.since ? this._time(values.waitingSince) : null;
|
|
470
|
+
if (since && keys.since) rows.push([keys.since, since]);
|
|
471
|
+
const finished = keys.finished ? this._time(values.finished) : null;
|
|
472
|
+
if (finished && keys.finished) rows.push([keys.finished, finished]);
|
|
473
|
+
if (values.model) rows.push(['runStatus.model', String(values.model)]);
|
|
474
|
+
const meter = tokenMeter(values.tokens, values.tokenBudget, { locale, template: this.msg('runStatus.tokenBudget') });
|
|
475
|
+
if (meter) {
|
|
476
|
+
rows.push(['runStatus.tokens', [
|
|
477
|
+
h('span', { class: 'zx-run-status__tokens', 'aria-hidden': 'true' }, meter.text),
|
|
478
|
+
this._meter(this.msg('runStatus.tokens'), meter.total, meter.budget, meter.text)
|
|
479
|
+
]]);
|
|
480
|
+
} else {
|
|
481
|
+
const tokens = formatTokens(values.tokens, { locale, template: this.msg('runStatus.tokensValue') });
|
|
482
|
+
if (tokens) rows.push(['runStatus.tokens', tokens]);
|
|
483
|
+
}
|
|
484
|
+
const cost = this._cost(values.cost);
|
|
485
|
+
if (cost) rows.push(['runStatus.costLabel', cost]);
|
|
486
|
+
return rows;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** @private @param {unknown} value @returns {HTMLElement|null} A `<time>` with the clock time, and the date when it is not today. */
|
|
490
|
+
_time(value) {
|
|
491
|
+
const date = runDate(value);
|
|
492
|
+
if (!date) return null;
|
|
493
|
+
const format = isSameDay(date, currentTime(this.options.now)) ? 'runStatus.timeFormat' : 'runStatus.dateTimeFormat';
|
|
494
|
+
return h('time', { datetime: formatDate(date, '%Y-%m-%dT%H:%M:%S') }, formatDate(date, this.msg(format)));
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** @private @param {unknown} cost @returns {Node[]|null} The cost, and a meter against the budget when there is one. */
|
|
498
|
+
_cost(cost) {
|
|
499
|
+
const text = formatRunCost(cost, { locale: this.options.locale, template: this.msg('runStatus.cost') });
|
|
500
|
+
if (!text) return null;
|
|
501
|
+
const { amount, budget } = /** @type {RunCost} */ (cost);
|
|
502
|
+
const limit = Number(budget);
|
|
503
|
+
if (!(limit > 0)) return [h('span', { class: 'zx-run-status__cost' }, text)];
|
|
504
|
+
return [
|
|
505
|
+
h('span', { class: 'zx-run-status__cost', 'aria-hidden': 'true' }, text),
|
|
506
|
+
this._meter(this.msg('runStatus.costLabel'), Math.max(0, Number(amount) || 0), limit, text)
|
|
507
|
+
];
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* A thin `role="meter"` bar of a value against its limit, toned by how close it is.
|
|
512
|
+
* @private
|
|
513
|
+
* @param {string} label
|
|
514
|
+
* @param {number} value
|
|
515
|
+
* @param {number} limit
|
|
516
|
+
* @param {string} text The value in words, its `aria-valuetext`.
|
|
517
|
+
* @returns {HTMLElement}
|
|
518
|
+
*/
|
|
519
|
+
_meter(label, value, limit, text) {
|
|
520
|
+
return h('span', {
|
|
521
|
+
class: 'zx-run-status__meter',
|
|
522
|
+
role: 'meter',
|
|
523
|
+
'aria-label': label,
|
|
524
|
+
'aria-valuemin': '0',
|
|
525
|
+
'aria-valuemax': String(limit),
|
|
526
|
+
'aria-valuenow': String(Math.min(value, limit)),
|
|
527
|
+
'aria-valuetext': text,
|
|
528
|
+
dataset: { level: costLevel(value, limit) }
|
|
529
|
+
}, h('span', { class: 'zx-run-status__meter-fill', style: { inlineSize: `${Math.min(100, (value / limit) * 100)}%` } }));
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** @private @returns {boolean} Whether the working time should count on screen now. */
|
|
533
|
+
_shouldTick() {
|
|
534
|
+
return !this._destroyed
|
|
535
|
+
&& this._values.ticking !== false
|
|
536
|
+
&& normalizeRunState(this._values.state) === 'running'
|
|
537
|
+
&& this._elapsed !== null
|
|
538
|
+
&& !this.el.ownerDocument.hidden;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** @private @returns {void} */
|
|
542
|
+
_syncTicker() {
|
|
543
|
+
if (this._shouldTick()) {
|
|
544
|
+
if (!this._interval) this._interval = setInterval(() => this._tick(), 1000);
|
|
545
|
+
} else {
|
|
546
|
+
this._stopTicker();
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** @private @returns {void} */
|
|
551
|
+
_stopTicker() {
|
|
552
|
+
if (this._interval) clearInterval(this._interval);
|
|
553
|
+
this._interval = 0;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** @private @returns {void} */
|
|
557
|
+
_tick() {
|
|
558
|
+
const worked = this._workTime();
|
|
559
|
+
if (this._elapsed && worked !== null) this._elapsed.textContent = formatElapsed(worked);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** @private @param {MouseEvent} event @returns {void} */
|
|
563
|
+
_onClick(event) {
|
|
564
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
565
|
+
const control = /** @type {HTMLElement|null} */ (target?.closest('[data-run-action]') ?? null);
|
|
566
|
+
if (!control || !this.el.contains(control)) return;
|
|
567
|
+
const index = Number(control.dataset.runAction);
|
|
568
|
+
const action = /** @type {RunStatusAction|undefined} */ (this._values.actions?.[index]);
|
|
569
|
+
if (!action) return;
|
|
570
|
+
if (typeof action.onclick === 'function') action.onclick(event);
|
|
571
|
+
this.emit('action', { index, action });
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Fired when one of the run's action buttons is activated.
|
|
577
|
+
* @event RunStatus#action
|
|
578
|
+
* @type {CustomEvent<{index: number, action: RunStatusAction}>}
|
|
579
|
+
*/
|
|
580
|
+
|
|
581
|
+
/** @returns {number} A monotonic clock in milliseconds. */
|
|
582
|
+
function clock() {
|
|
583
|
+
return typeof performance === 'object' && typeof performance.now === 'function' ? performance.now() : Date.now();
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** @param {unknown} value @returns {number|null} */
|
|
587
|
+
function finiteOrNull(value) {
|
|
588
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* A shallow copy, so the options and later updates are never mutated or shared.
|
|
593
|
+
* @template T
|
|
594
|
+
* @param {T} value
|
|
595
|
+
* @returns {T}
|
|
596
|
+
*/
|
|
597
|
+
function copyValue(value) {
|
|
598
|
+
if (Array.isArray(value)) return /** @type {T} */ ([...value]);
|
|
599
|
+
if (value && typeof value === 'object' && !(value instanceof Date)) return /** @type {T} */ ({ ...value });
|
|
600
|
+
return value;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* How close a run's cost is to its budget: `'warning'` from 80%, `'danger'` at 100% and over,
|
|
605
|
+
* `'normal'` below, and without a budget.
|
|
606
|
+
* @param {number} amount
|
|
607
|
+
* @param {number|null|undefined} budget
|
|
608
|
+
* @returns {'normal'|'warning'|'danger'}
|
|
609
|
+
*/
|
|
610
|
+
export function costLevel(amount, budget) {
|
|
611
|
+
const limit = Number(budget);
|
|
612
|
+
const spent = Number(amount);
|
|
613
|
+
if (!(limit > 0) || !Number.isFinite(spent)) return 'normal';
|
|
614
|
+
const ratio = spent / limit;
|
|
615
|
+
if (ratio >= 1) return 'danger';
|
|
616
|
+
if (ratio >= 0.8) return 'warning';
|
|
617
|
+
return 'normal';
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Reads a steps count: whole numbers, the done count kept within the total. Null for no steps.
|
|
622
|
+
* @param {unknown} steps `{done, total}`.
|
|
623
|
+
* @returns {{done: number, total: number, percent: number}|null}
|
|
624
|
+
*/
|
|
625
|
+
export function stepProgress(steps) {
|
|
626
|
+
if (!steps || typeof steps !== 'object') return null;
|
|
627
|
+
const { done, total } = /** @type {{done?: unknown, total?: unknown}} */ (steps);
|
|
628
|
+
const all = Math.max(0, Math.floor(Number(total) || 0));
|
|
629
|
+
if (all === 0) return null;
|
|
630
|
+
const finished = Math.min(all, Math.max(0, Math.floor(Number(done) || 0)));
|
|
631
|
+
return { done: finished, total: all, percent: Math.round((finished / all) * 100) };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Token counts in words: "18,420 in · 1,236 out" for a pair, "22,840" for a total. Empty without
|
|
636
|
+
* counts.
|
|
637
|
+
* @param {unknown} tokens `[input, output]`, or the total as one number.
|
|
638
|
+
* @param {{locale?: string, template?: string}} [options={}] `template` takes the two formatted
|
|
639
|
+
* counts of a pair as `%1` and `%2`.
|
|
640
|
+
* @returns {string}
|
|
641
|
+
*/
|
|
642
|
+
export function formatTokens(tokens, options = {}) {
|
|
643
|
+
if (typeof tokens === 'number') {
|
|
644
|
+
return Number.isFinite(tokens) ? formatNumber(Math.max(0, tokens), { locale: options.locale }) : '';
|
|
645
|
+
}
|
|
646
|
+
if (!Array.isArray(tokens) || tokens.length < 2) return '';
|
|
647
|
+
const counts = tokens.slice(0, 2).map((count) => Math.max(0, Number(count) || 0));
|
|
648
|
+
return printf(options.template ?? MESSAGES['runStatus.tokensValue'],
|
|
649
|
+
counts.map((count) => formatNumber(count, { locale: options.locale })));
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* How many tokens a run has used in all: the number itself, or input and output added up.
|
|
654
|
+
* @param {unknown} tokens `[input, output]`, or the total as one number.
|
|
655
|
+
* @returns {number|null} Null without counts.
|
|
656
|
+
*/
|
|
657
|
+
export function tokenTotal(tokens) {
|
|
658
|
+
if (typeof tokens === 'number') return Number.isFinite(tokens) ? Math.max(0, tokens) : null;
|
|
659
|
+
if (!Array.isArray(tokens) || tokens.length < 2) return null;
|
|
660
|
+
return tokens.slice(0, 2).reduce((sum, count) => sum + Math.max(0, Number(count) || 0), 0);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* A count in the locale's compact notation (`Intl.NumberFormat` with `notation: 'compact'`) and at
|
|
665
|
+
* most one decimal: "22.8K", "60K", "1.2M" in English, "22.840" in German, which has no compact
|
|
666
|
+
* form for thousands.
|
|
667
|
+
* @param {number} value
|
|
668
|
+
* @param {{locale?: string}} [options={}]
|
|
669
|
+
* @returns {string} Empty for anything that is not a finite number.
|
|
670
|
+
*/
|
|
671
|
+
export function formatCompactNumber(value, options = {}) {
|
|
672
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return '';
|
|
673
|
+
const number = value;
|
|
674
|
+
/** @type {Intl.NumberFormatOptions} */
|
|
675
|
+
const format = { notation: 'compact', maximumFractionDigits: 1 };
|
|
676
|
+
try {
|
|
677
|
+
return new Intl.NumberFormat(options.locale ?? getLanguage(), format).format(number);
|
|
678
|
+
} catch {
|
|
679
|
+
return new Intl.NumberFormat(undefined, format).format(number);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* The tokens as a meter against their budget: the total, the budget, the level (`warning` from
|
|
685
|
+
* 80%, `danger` at 100%, as for the cost), and the words "22.8K of 60K tokens". Null without
|
|
686
|
+
* counts or without a budget above zero, when the tokens stay text.
|
|
687
|
+
* @param {unknown} tokens `[input, output]`, or the total as one number.
|
|
688
|
+
* @param {unknown} budget The most tokens the run may use.
|
|
689
|
+
* @param {{locale?: string, template?: string}} [options={}] `template` takes the compact total and
|
|
690
|
+
* budget as `%1` and `%2`.
|
|
691
|
+
* @returns {RunTokenMeter|null}
|
|
692
|
+
*/
|
|
693
|
+
export function tokenMeter(tokens, budget, options = {}) {
|
|
694
|
+
const total = tokenTotal(tokens);
|
|
695
|
+
const limit = typeof budget === 'number' ? budget : Number.NaN;
|
|
696
|
+
if (total === null || !(limit > 0) || !Number.isFinite(limit)) return null;
|
|
697
|
+
const locale = options.locale;
|
|
698
|
+
return {
|
|
699
|
+
total,
|
|
700
|
+
budget: limit,
|
|
701
|
+
level: costLevel(total, limit),
|
|
702
|
+
text: printf(options.template ?? MESSAGES['runStatus.tokenBudget'],
|
|
703
|
+
[formatCompactNumber(total, { locale }), formatCompactNumber(limit, { locale })])
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Reads the `compact` option: `'icon'` for the glyph alone, `'word'` for any other truthy value
|
|
709
|
+
* (the pill of glyph and word), null for the full panel.
|
|
710
|
+
* @param {unknown} value
|
|
711
|
+
* @returns {RunCompactMode|null}
|
|
712
|
+
*/
|
|
713
|
+
export function compactMode(value) {
|
|
714
|
+
if (value === 'icon') return 'icon';
|
|
715
|
+
return value ? 'word' : null;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* The message keys of the time rows a state shows besides "Started": the "since" row while the
|
|
720
|
+
* run is held (`waiting`: "Waiting since", `blocked`: "Blocked since"), and the "finished" row
|
|
721
|
+
* once it is over ("Finished", "Failed at", "Stopped at"). A blocked run is not over, so it never
|
|
722
|
+
* shows a finished row.
|
|
723
|
+
* @param {unknown} state
|
|
724
|
+
* @returns {{since: string|null, finished: string|null}}
|
|
725
|
+
*/
|
|
726
|
+
export function runTimeKeys(state) {
|
|
727
|
+
const known = normalizeRunState(state);
|
|
728
|
+
return {
|
|
729
|
+
since: SINCE_KEYS[/** @type {keyof typeof SINCE_KEYS} */ (known)] ?? null,
|
|
730
|
+
finished: FINISHED_KEYS[/** @type {keyof typeof FINISHED_KEYS} */ (known)] ?? null
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* Reads the `now` option: the date its function returns (a `Date` or a millisecond timestamp),
|
|
736
|
+
* or the real time when there is no function or it returns nothing usable.
|
|
737
|
+
* @param {unknown} now
|
|
738
|
+
* @returns {Date}
|
|
739
|
+
*/
|
|
740
|
+
export function currentTime(now) {
|
|
741
|
+
if (typeof now === 'function') {
|
|
742
|
+
const value = now();
|
|
743
|
+
const date = value instanceof Date ? new Date(value.getTime()) : typeof value === 'number' ? new Date(value) : null;
|
|
744
|
+
if (date && !Number.isNaN(date.getTime())) return date;
|
|
745
|
+
}
|
|
746
|
+
return new Date();
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* A run's cost in words: "€0.14 of €2.00" against a budget, "€0.14" without one. Empty without a
|
|
751
|
+
* cost.
|
|
752
|
+
* @param {unknown} cost `{amount, budget?, currency?}`.
|
|
753
|
+
* @param {{locale?: string, template?: string}} [options={}] `template` takes the amount and the
|
|
754
|
+
* budget as `%1` and `%2`.
|
|
755
|
+
* @returns {string}
|
|
756
|
+
*/
|
|
757
|
+
export function formatRunCost(cost, options = {}) {
|
|
758
|
+
if (!cost || typeof cost !== 'object') return '';
|
|
759
|
+
const { amount, budget, currency } = /** @type {RunCost} */ (cost);
|
|
760
|
+
if (!Number.isFinite(Number(amount))) return '';
|
|
761
|
+
const spent = formatCurrency(Number(amount), currency, { locale: options.locale });
|
|
762
|
+
const limit = Number(budget);
|
|
763
|
+
if (budget == null || !(limit > 0)) return spent;
|
|
764
|
+
return printf(options.template ?? MESSAGES['runStatus.cost'], [spent, formatCurrency(limit, currency, { locale: options.locale })]);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Reads a run time: a `Date`, or a local ISO date-time string (`2026-09-29T11:20:04`; a bare date
|
|
769
|
+
* is midnight local time). Null for anything else.
|
|
770
|
+
* @param {unknown} value
|
|
771
|
+
* @returns {Date|null}
|
|
772
|
+
*/
|
|
773
|
+
export function runDate(value) {
|
|
774
|
+
/** @type {Date|null} */
|
|
775
|
+
let date = null;
|
|
776
|
+
if (value instanceof Date) date = new Date(value.getTime());
|
|
777
|
+
else if (typeof value === 'string' && value.trim()) {
|
|
778
|
+
const text = value.trim();
|
|
779
|
+
date = new Date(/^\d{4}-\d{2}-\d{2}$/.test(text) ? `${text}T00:00` : text);
|
|
780
|
+
}
|
|
781
|
+
return date && !Number.isNaN(date.getTime()) ? date : null;
|
|
782
|
+
}
|