codex-copilot-dx 1.3.25 → 1.3.26
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/README.md +2 -2
- package/docs/ARCHITECTURE.md +6 -0
- package/docs/REFERENCE.md +23 -2
- package/package.json +1 -1
- package/src/antigravity-chat-bridge.mjs +2 -1
- package/src/antigravity-handler.mjs +67 -13
- package/src/antigravity-runtime.mjs +7 -2
- package/src/antigravity-usage.mjs +86 -0
- package/src/cli-command-spec.mjs +9 -4
- package/src/cli-management.mjs +25 -5
- package/src/dashboard/flow.js +12 -11
- package/src/dashboard/gemini.js +24 -5
- package/src/dashboard/index.html +8 -8
- package/src/dashboard/language.js +31 -9
- package/src/dashboard/status.js +3 -1
- package/src/dashboard/ui.js +18 -7
- package/src/dashboard/usage.js +35 -19
- package/src/dashboard-api.mjs +19 -6
- package/src/stream-performance.mjs +5 -1
- package/src/terminal-state.mjs +8 -0
- package/src/usage-analysis.mjs +19 -8
- package/src/usage-analytics.mjs +9 -7
- package/src/usage-query.mjs +36 -0
- package/src/usage-store.mjs +4 -3
- package/src/usage.mjs +7 -3
package/src/dashboard/gemini.js
CHANGED
|
@@ -7,6 +7,16 @@
|
|
|
7
7
|
const selected=()=>state?.models.filter(model=>model.selected!==false).map(model=>model.id)||[];
|
|
8
8
|
const dirty=()=>draft!==null&&JSON.stringify([...draft].sort())!==JSON.stringify(selected().sort());
|
|
9
9
|
const count=value=>!value?'—':value>=1000000?`${Number((value/1000000).toFixed(2))}M`:value>=1000?`${Number((value/1000).toFixed(1))}K`:String(value);
|
|
10
|
+
const groupedModels=()=>{
|
|
11
|
+
if(Array.isArray(state.model_groups))return state.model_groups;
|
|
12
|
+
const groups=new Map();
|
|
13
|
+
for(const variant of state.models){
|
|
14
|
+
const name=variant.name.split(' · Copilot')[0],id=variant.model||name;
|
|
15
|
+
if(!groups.has(id))groups.set(id,{id,name,context_window:variant.context_window,efforts:[]});
|
|
16
|
+
groups.get(id).efforts.push({id:variant.id,effort:variant.effort,selected:variant.selected});
|
|
17
|
+
}
|
|
18
|
+
return [...groups.values()];
|
|
19
|
+
};
|
|
10
20
|
function render(){
|
|
11
21
|
for(const id of controls)el(id).disabled=busy||!state;
|
|
12
22
|
if(!state)return;
|
|
@@ -22,12 +32,21 @@
|
|
|
22
32
|
el('gemini-reopen').hidden=!hint;if(hint)words('gemini-reopen',hint);
|
|
23
33
|
el('gemini-open').disabled=busy||state.app.status!=='stopped';
|
|
24
34
|
const list=el('gemini-models'),focus=list.contains(document.activeElement)?document.activeElement.value:null;list.replaceChildren();
|
|
25
|
-
for(const model of
|
|
35
|
+
for(const model of groupedModels()){
|
|
36
|
+
const chosen=new Set(draft||selected()),ids=model.efforts.map(item=>item.id);
|
|
26
37
|
const row=document.createElement('tr'),name=document.createElement('td'),label=document.createElement('label'),input=document.createElement('input');
|
|
27
|
-
input.type='checkbox';input.value=model.id;input.checked=(
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
38
|
+
input.type='checkbox';input.value=model.id;input.checked=ids.every(id=>chosen.has(id));input.indeterminate=!input.checked&&ids.some(id=>chosen.has(id));input.disabled=busy;input.setAttribute('aria-label',model.name);
|
|
39
|
+
const update=(values,checked)=>{const next=new Set(draft||selected());for(const id of values)if(checked)next.add(id);else next.delete(id);draft=[...next];notice=null;clear('gemini-note');render()};
|
|
40
|
+
input.addEventListener('change',()=>update(ids,input.checked));
|
|
41
|
+
label.append(input,document.createTextNode(model.name));name.append(label);row.append(name);
|
|
42
|
+
for(const [key,value]of [['source','GitHub Copilot'],['cap_context',count(model.context_window)]]){const cell=document.createElement('td');cell.textContent=value;cell.dataset.label=language.format(key);row.append(cell)}
|
|
43
|
+
const efforts=document.createElement('td');efforts.dataset.label=language.format('cap_reasoning');
|
|
44
|
+
for(const item of model.efforts){
|
|
45
|
+
const label=document.createElement('label'),choice=document.createElement('input');choice.type='checkbox';choice.value=item.id;choice.checked=chosen.has(item.id);choice.disabled=busy;
|
|
46
|
+
choice.setAttribute('aria-label',model.name+' · '+language.format(item.effort));choice.addEventListener('change',()=>update([item.id],choice.checked));
|
|
47
|
+
label.append(choice,document.createTextNode(language.format(item.effort)));efforts.append(label,document.createTextNode(' '));
|
|
48
|
+
}
|
|
49
|
+
row.append(efforts);list.append(row);
|
|
31
50
|
}
|
|
32
51
|
if(!state.models.length){const row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=4;language.set(cell,'gemini_no_models');row.append(cell);list.append(row)}
|
|
33
52
|
if(focus)[...list.querySelectorAll('input')].find(input=>input.value===focus)?.focus();
|
package/src/dashboard/index.html
CHANGED
|
@@ -316,29 +316,29 @@
|
|
|
316
316
|
<div data-view="usage" hidden>
|
|
317
317
|
<div class="context-tabs" role="tablist" aria-label="Usage view" data-i18n-label="context_tabs"><button type="button" id="usage-tokens-tab" role="tab" aria-selected="true" aria-controls="usage-tokens-pane" data-i18n="context_tokens">Tokens</button><button type="button" id="usage-context-tab" role="tab" aria-selected="false" aria-controls="usage-context-pane" data-i18n="context_title">Context</button></div>
|
|
318
318
|
<div id="usage-tokens-pane" role="tabpanel" aria-labelledby="usage-tokens-tab">
|
|
319
|
-
<div class="section-actions usage-source-controls"><label><span data-i18n="source_entire_page">Source / entire page</span><select id="usage-provider"><option value="" data-i18n="all_providers">All providers</option></select></label
|
|
319
|
+
<div class="section-actions usage-source-controls"><label><span data-i18n="source_entire_page">Source / entire page</span><select id="usage-provider"><option value="" data-i18n="all_providers">All providers</option></select></label>
|
|
320
|
+
<label><span data-i18n="usage_model_page">Model / entire page</span><select id="analytics-model"><option value="" data-i18n="all_models">All models</option></select></label>
|
|
321
|
+
<label><span data-i18n="usage_range_page">Time / entire page</span><select id="analytics-range"><option value="all" selected data-i18n="usage_all_history">All retained history</option><option value="7" data-i18n="7_days">Last 7 days</option><option value="30" data-i18n="30_days">Last 30 days</option><option value="90" data-i18n="90_days">Last 90 days</option><option value="365" data-i18n="usage_365_days">Last 365 days</option></select></label>
|
|
322
|
+
<button id="refresh-usage" type="button" data-i18n="refresh_usage">Refresh usage</button></div>
|
|
320
323
|
|
|
321
324
|
<details id="usage-analytics" class="panel dashboard-section analytics-section">
|
|
322
325
|
<summary data-i18n="usage_analytics">USAGE TRENDS</summary>
|
|
323
|
-
<div class="analytics-controls">
|
|
324
|
-
<label><span data-i18n="model_both_charts">Model / both charts</span> <select id="analytics-model"><option value="" data-i18n="all_models">All models</option></select></label>
|
|
325
|
-
</div>
|
|
326
326
|
<p id="analytics-note" class="table-note" role="status" data-i18n="open_to_read_retained_usage_history">Loading usage trends…</p>
|
|
327
327
|
<p id="analytics-updated" class="refresh-time"></p>
|
|
328
|
-
<div class="chart-heading"><h3 data-i18n="daily_tokens">
|
|
328
|
+
<div class="chart-heading"><h3 data-i18n="daily_tokens">USAGE BY DATE</h3><div class="analytics-controls">
|
|
329
329
|
<label><span data-i18n="chart_view">Chart view</span> <select id="analytics-view"><option value="bars" selected data-i18n="bar_chart">Bar chart</option><option value="line" data-i18n="line_chart">Line chart</option></select></label></div></div>
|
|
330
330
|
<div id="daily-bars" class="daily-bars" aria-label="Daily usage in Token" data-i18n-label="daily_token_usage"></div>
|
|
331
331
|
<div class="daily-axis"><span id="daily-from"></span><span id="daily-to"></span></div>
|
|
332
332
|
<div class="chart-legend"><span class="legend-input" data-i18n="input_36ecb">Input usage</span><span class="legend-output" data-i18n="output_b2439">Output usage</span></div>
|
|
333
|
-
<div class="chart-heading"><h3 data-i18n="
|
|
333
|
+
<div class="chart-heading"><h3 data-i18n="usage_activity_range">ACTIVITY</h3><div class="analytics-controls"><label><span data-i18n="calendar_measure">Calendar measure</span> <select id="analytics-metric"><option value="requests" data-i18n="recorded_usage">Usage records</option><option value="tokens" data-i18n="tokens">Usage (Token)</option></select></label></div></div><p id="activity-scale" class="hint">—</p>
|
|
334
334
|
<div class="calendar-scroll"><div class="calendar-grid"><div id="calendar-months" class="calendar-months" aria-hidden="true"></div><div id="activity-calendar" class="activity-calendar" aria-label="Daily recorded activity over 365 days" data-i18n-label="daily_recorded_request_activity"></div></div></div>
|
|
335
335
|
<p id="analytics-selection" class="hint" role="status" data-i18n="select_a_day_to_inspect_its_model_totals_no_history_is_distinct_">Select a day for its usage. No records does not mean zero requests.</p>
|
|
336
336
|
</details>
|
|
337
337
|
<details class="panel dashboard-section" id="model-usage" open>
|
|
338
338
|
<summary class="panel-heading"><h2 data-i18n="usage_totals">USAGE TOTALS</h2><span id="usage-state" data-i18n="reading_log">COUNTING</span></summary>
|
|
339
|
-
<div class="section-actions"><button id="clear-usage-day" type="button" hidden data-i18n="
|
|
339
|
+
<div class="section-actions"><button id="clear-usage-day" type="button" hidden data-i18n="usage_clear_date">Clear date</button></div>
|
|
340
340
|
<p id="usage-note" class="table-note" data-i18n="aggregating_local_usage_metadata">Counting local usage…</p>
|
|
341
|
-
<div class="table-wrap"><table class="usage-table"><thead><tr><th scope="col" data-i18n="model">MODEL</th><th scope="col" data-i18n="
|
|
341
|
+
<div class="table-wrap"><table class="usage-table"><thead><tr><th scope="col" data-i18n="model">MODEL</th><th scope="col" data-i18n="usage_records">RECORDS</th><th scope="col" data-i18n="input">INPUT USAGE</th><th scope="col" data-i18n="cache_read">REUSED INPUT</th><th scope="col" data-i18n="cache_write">CACHE WRITE</th><th scope="col" data-i18n="output">OUTPUT USAGE</th><th scope="col" data-i18n="total">TOTAL</th><th scope="col" data-i18n="cache_hit">REUSE RATE</th></tr></thead><tbody id="usage-body"><tr><td colspan="8" data-i18n="loading">Loading…</td></tr></tbody></table></div>
|
|
342
342
|
<p class="hint" data-i18n="cache_hit_recorded_cached_input_tokens_incomplete_history_unavai">Unit: Token. Reused input is part of input. Rate uses records with valid input and cache-read counts.
|
|
343
343
|
~ Partial coverage. — No valid input basis.</p>
|
|
344
344
|
|
|
@@ -492,7 +492,7 @@
|
|
|
492
492
|
"flow_active_count": ["Active requests · {count}", "进行中 · {count}"],
|
|
493
493
|
"flow_last_count": ["Last observed · {count}", "上次记录 · {count}"],
|
|
494
494
|
"flow_related_count": ["{count} related requests", "{count} 个相关请求"],
|
|
495
|
-
"flow_group_scope": ["{apps} apps · {models}
|
|
495
|
+
"flow_group_scope": ["{apps} apps · {models} model groups", "{apps} 个应用 · {models} 个模型分组"],
|
|
496
496
|
"flow_omitted": ["Showing {count} requests; {omitted} more have no detail", "显示 {count} 个请求,另有 {omitted} 个暂无详情"],
|
|
497
497
|
"flow_more_models": ["Show {count} more models", "显示其余 {count} 个模型"],
|
|
498
498
|
"flow_fewer_models": ["Show fewer models", "收起模型"],
|
|
@@ -503,11 +503,33 @@
|
|
|
503
503
|
"flow_app_gemini_app": ["Antigravity", "Antigravity"],
|
|
504
504
|
"flow_app_claude": ["Claude (app unspecified)", "Claude(未区分应用)"],
|
|
505
505
|
"flow_app_api": ["Unidentified app", "未识别应用"],
|
|
506
|
+
"flow_source_pending": ["Source pending", "来源待确认"],
|
|
507
|
+
"flow_model_pending": ["Model pending", "模型待确认"],
|
|
506
508
|
"flow_source_unknown": ["Source unknown", "来源未知"],
|
|
507
509
|
"flow_model_unknown": ["Model not identified", "未识别模型"],
|
|
508
510
|
"flow_responding": ["Responding", "响应中"],
|
|
509
511
|
"flow_group_response": ["{count} responding", "{count} 个响应中"],
|
|
510
|
-
"flow_waiting": ["Waiting
|
|
512
|
+
"flow_waiting": ["Waiting upstream", "等待上游"],
|
|
513
|
+
"flow_queued": ["Queued", "排队中"],
|
|
514
|
+
"flow_input": ["Processing input", "处理输入"],
|
|
515
|
+
"flow_processing": ["Processing", "处理中"],
|
|
516
|
+
"request_usage_state": ["Usage received", "用量接收状态"],
|
|
517
|
+
"request_usage_reported": ["Reported", "已收到"],
|
|
518
|
+
"request_usage_partial": ["Some counts unavailable", "部分计数未提供"],
|
|
519
|
+
"request_usage_missing": ["No valid usage received", "未收到有效用量"],
|
|
520
|
+
"request_usage_unavailable": ["Metadata could not be read", "元数据无法读取"],
|
|
521
|
+
"usage_model_page": ["Model / entire page", "模型/整页"],
|
|
522
|
+
"usage_range_page": ["Time / entire page", "时间/整页"],
|
|
523
|
+
"usage_all_history": ["All retained history", "全部已保留历史"],
|
|
524
|
+
"usage_365_days": ["Last 365 days", "最近 365 天"],
|
|
525
|
+
"usage_clear_date": ["Clear date", "清除日期"],
|
|
526
|
+
"usage_records": ["RECORDS", "用量记录"],
|
|
527
|
+
"recorded_usage": ["Usage records", "用量记录"],
|
|
528
|
+
"usage_earlier": ["Earlier records", "更早记录"],
|
|
529
|
+
"usage_earlier_before": ["Records before {date}", "{date} 之前的记录"],
|
|
530
|
+
"usage_empty_selection": ["No recorded usage matches these filters. No records does not mean zero requests.", "当前筛选没有已记录用量。没有记录不代表没有请求。"],
|
|
531
|
+
"usage_activity_range": ["ACTIVITY", "用量活动"],
|
|
532
|
+
"usage_cache_coverage": ["Cache counts available: {known} records; unavailable: {unknown}.", "缓存计数已知 {known} 条,未知 {unknown} 条。"],
|
|
511
533
|
"flow_preparing": ["Preparing", "准备中"],
|
|
512
534
|
"flow_retrying": ["Retrying", "正在重试"],
|
|
513
535
|
"flow_finishing": ["Finishing delivery", "正在完成交付"],
|
|
@@ -992,13 +1014,13 @@
|
|
|
992
1014
|
"calls_b73a5": ["Requests", "请求次数"],
|
|
993
1015
|
"tokens": ["Usage (Token)", "处理用量"],
|
|
994
1016
|
"open_to_read_retained_usage_history": ["Loading usage trends…", "读取用量趋势中…"],
|
|
995
|
-
"daily_tokens": ["
|
|
1017
|
+
"daily_tokens": ["USAGE BY DATE", "按日期用量"],
|
|
996
1018
|
"input_output_cache_included_in_input": ["INPUT + OUTPUT / REUSED INPUT IS PART OF INPUT", "输入与输出合计。\n复用部分已计入输入。"],
|
|
997
|
-
"daily_token_usage": ["
|
|
1019
|
+
"daily_token_usage": ["Input and output usage by date", "按日期记录的输入与输出用量"],
|
|
998
1020
|
"input_36ecb": ["Input usage", "输入用量"],
|
|
999
1021
|
"output_b2439": ["Output usage", "输出用量"],
|
|
1000
1022
|
"request_activity_365_days": ["ACTIVITY · LAST 365 DAYS", "活跃日历"],
|
|
1001
|
-
"daily_recorded_request_activity": ["
|
|
1023
|
+
"daily_recorded_request_activity": ["Recorded usage by date", "按日期记录的用量"],
|
|
1002
1024
|
"select_a_day_to_inspect_its_model_totals_no_history_is_distinct_": ["Select a day for usage. Blank means no records.", "点击日期查看当天用量。空白表示无记录。"],
|
|
1003
1025
|
"recent_failures": ["Recent issues", "异常记录"],
|
|
1004
1026
|
"recent_response_failures": ["RECENT ISSUES", "异常记录"],
|
|
@@ -1087,17 +1109,17 @@
|
|
|
1087
1109
|
"records_records_shown_of_models_models_shown_day": ["Records: {records} · models: {shown} of {models}{day}", "记录:{records}条\n模型:展示{shown}个,共{models}个{day}"],
|
|
1088
1110
|
"zone_model": [" / {zone} / {model}", " / {zone} / {model}"],
|
|
1089
1111
|
"no_retained_history": ["no records", "没有记录"],
|
|
1090
|
-
"calls_recorded_calls_input_input_output_output_cached_cached_inc": ["{calls}
|
|
1112
|
+
"calls_recorded_calls_input_input_output_output_cached_cached_inc": ["{calls} usage records\nInput: {input} / output: {output}\nReused input: {cached} Token\nReused input is part of input.{partial}", "用量记录:{calls}\n输入:{input}/输出:{output}\n复用输入:{cached} Token\n复用部分已计入输入。{partial}"],
|
|
1091
1113
|
"partial_token_counts": ["\nIncomplete usage records.", "\n用量记录不完整。"],
|
|
1092
1114
|
"date_description": ["{date} / {description}", "{date} / {description}"],
|
|
1093
|
-
"metric_peak_peak": ["
|
|
1115
|
+
"metric_peak_peak": ["{metric} · Peak {peak}", "{metric} · 峰值 {peak}"],
|
|
1094
1116
|
"input_output": ["TOTAL USAGE (Token)", "总用量"],
|
|
1095
1117
|
"recorded_calls": ["RECORDED REQUESTS", "请求次数"],
|
|
1096
1118
|
"zone_from_to_retained_history_starts_first_oldest_day_may_be_par": ["Zone: {zone}\nRange: {from}–{to}\nFirst record: {first}\nThe first day may be partial.{excluded}{limit}", "时区:{zone}\n记录范围:{from}—{to}\n最早记录:{first}\n最早一天可能记录不全。{excluded}{limit}"],
|
|
1097
1119
|
"count_records_with_invalid_future_timestamps_excluded": ["\nSkipped {count} records with invalid or future dates.", "\n已跳过{count}条时间异常记录。"],
|
|
1098
1120
|
"model_filters_limited_to_100_all_model_totals_include_the_remain": ["\nFilters show up to 100 models. Totals include the rest.", "\n只列出前100个模型。\n总计包含其余模型。"],
|
|
1099
|
-
"selected_date_model_totals_in_the_usage_table_above_all_history_": ["Selected: {date} / {model}\
|
|
1100
|
-
"select_a_day_for_model_totals_calls_are_usage_records_not_messag": ["Select a day for usage.\nCounts are
|
|
1121
|
+
"selected_date_model_totals_in_the_usage_table_above_all_history_": ["Selected: {date} / {model}\nClear date restores the time filter.", "已选:{date}/{model}\n清除日期后恢复时间筛选。"],
|
|
1122
|
+
"select_a_day_for_model_totals_calls_are_usage_records_not_messag": ["Select a day for usage.\nCounts are usage records, not messages or time.\nHatched: no retained history. Blank: zero recorded usage.", "点击日期查看当天用量。\n计数为用量记录,不代表消息或时长。\n斜线格:没有保留记录。\n空白格:用量记录为零。"],
|
|
1101
1123
|
"log_unavailable": ["READ FAILED", "读取失败"],
|
|
1102
1124
|
"no_usage_summary_available": ["Cannot read usage records.", "无法读取用量记录。"],
|
|
1103
1125
|
"analytics_unavailable_refresh_usage_to_retry": ["Trends unavailable. Refresh Model usage to retry.", "统计失败,请刷新用量。"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
let issueGroups = { issues: [], capability: [], connection: [] }, issueRequests = [];
|
|
10
10
|
element("failure-kind")?.addEventListener?.("change", () => renderFailures(issueGroups[element("failure-kind").value] || [], element("failure-kind").value === "issues" ? issueRequests : []));
|
|
11
11
|
let contextSignature;
|
|
12
|
-
const sourceNames = new Map([["github", "GitHub Copilot"], ["m365", "Microsoft 365"]]);
|
|
12
|
+
const sourceNames = new Map([["github", "GitHub Copilot"], ["m365", "Microsoft 365"], ["google", "Google"]]);
|
|
13
13
|
|
|
14
14
|
const sourceLabel = id => globalThis.ccdxConnectionNames?.[id] || sourceNames.get(id) || id;
|
|
15
15
|
function renderProviders(data) {
|
|
@@ -398,6 +398,8 @@
|
|
|
398
398
|
["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
|
|
399
399
|
["images", number(context.images)], ["model_window", number(context.context_window_tokens)], ["input_window", ratio],
|
|
400
400
|
["output_requested", number(context.max_output_tokens_requested)], ["output_sent", number(context.max_output_tokens_sent)], ["output_used", number(context.output_tokens)], ["stop_reason", request.stop_reason || "—"],
|
|
401
|
+
...(context.requested_model && context.requested_model !== request.model ? [["requested_model", context.requested_model]] : []),
|
|
402
|
+
...(["reported", "partial", "missing", "unavailable"].includes(context.usage_state) ? [["request_usage_state", globalThis.ccdxLanguage?.format("request_usage_" + context.usage_state) || context.usage_state]] : []),
|
|
401
403
|
...(context.client_tool_errors_received > 0 ? [["client_tool_errors_received", number(context.client_tool_errors_received)]] : [])]) {
|
|
402
404
|
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);detail.textContent = value;fields.append(term, detail);
|
|
403
405
|
}
|
package/src/dashboard/ui.js
CHANGED
|
@@ -17,6 +17,7 @@ const number = (value) => finite(value) ? Math.max(0, Math.round(Number(value)))
|
|
|
17
17
|
const mib = (value) => finite(value) ? `${(Number(value) / 1048576).toFixed(1)} MiB` : "—";
|
|
18
18
|
const time = (value, options) => globalThis.ccdxTime?.format(value, options) ?? (value ? new Date(value).toLocaleTimeString() : "—");
|
|
19
19
|
const viewHelpers = { time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator: globalThis.navigator, modelLabel: usageModelLabel,
|
|
20
|
+
usageChanged: () => { dashboardRefresh.invalidate("usage");return dashboardRefresh.refresh("usage", { force: true }); },
|
|
20
21
|
motionAllowed: () => !reducedMotion.matches && document.visibilityState === "visible" && element("usage-analytics").open && !element("usage-analytics").closest("[hidden]") };
|
|
21
22
|
const { render, renderActivity, renderProviders, renderFailures, renderContext } = globalThis.ccdxViewBoundary.create("client-features", () => globalThis.ccdxDashboardStatus.create(viewHelpers), ["render", "renderActivity", "renderProviders", "renderFailures", "renderContext"]);
|
|
22
23
|
const usageView = globalThis.ccdxViewBoundary.create("usage-analytics", () => globalThis.ccdxDashboardUsage.create(viewHelpers), ["applyUsage", "renderUsageState", "renderAnalytics", "renderUsageTable", "selectUsageDay", "usageValues", "setChartVisible", "revealChart", "stopMotion", "refreshModelLabels"]);
|
|
@@ -80,8 +81,8 @@ let selectedProvider = "";
|
|
|
80
81
|
function usageModelLabel(value) {
|
|
81
82
|
if (typeof value !== "string") return value;
|
|
82
83
|
const at = value.indexOf(" / "), id = value.slice(0, at);
|
|
83
|
-
if (at < 0
|
|
84
|
-
const name = providerEntries.find(provider => provider.id === id)?.name;
|
|
84
|
+
if (at < 0) return value;
|
|
85
|
+
const name = providerEntries.find(provider => provider.id === id)?.name || ({ github: "GitHub Copilot", m365: "Microsoft 365", google: "Google" })[id];
|
|
85
86
|
return name ? name + value.slice(at) : value;
|
|
86
87
|
}
|
|
87
88
|
const modelSnapshots = new Map();
|
|
@@ -91,7 +92,7 @@ try { selectedProvider = localStorage.getItem("ccdx.dashboard.modelProvider") ||
|
|
|
91
92
|
function syncUsageProviders() {
|
|
92
93
|
const selector = element("usage-provider"), selected = selector.value;
|
|
93
94
|
const entries = new Map(providerEntries.map(provider => [provider.id, provider.name]));
|
|
94
|
-
for (const id of Object.keys(usageProviders)) if (usageProviders[id] > 0 && !entries.has(id)) entries.set(id, id);
|
|
95
|
+
for (const id of Object.keys(usageProviders)) if (usageProviders[id] > 0 && !entries.has(id)) entries.set(id, ({ google: "Google", github: "GitHub Copilot", m365: "Microsoft 365" })[id] || id);
|
|
95
96
|
const signature = JSON.stringify([...entries]);
|
|
96
97
|
if (selector.dataset.providers === signature) return;
|
|
97
98
|
selector.dataset.providers = signature;
|
|
@@ -390,12 +391,17 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
|
390
391
|
variant: () => {
|
|
391
392
|
const mode = (element("usage-analytics").open || Boolean(usageView.selectedDate)) ? "analytics" : "summary";
|
|
392
393
|
const provider = element("usage-provider")?.value || "";
|
|
393
|
-
return mode
|
|
394
|
+
return JSON.stringify({ mode, provider, model: element("analytics-model").value || "", days: element("analytics-range").value || "all", date: usageView.selectedDate });
|
|
394
395
|
},
|
|
395
396
|
load: async ({ variant, signal }) => {
|
|
396
|
-
const
|
|
397
|
+
const { mode, provider, model, days, date } = JSON.parse(variant), query = new URLSearchParams();
|
|
397
398
|
if (mode === "analytics") { query.set("analytics", "1");query.set("time_zone", Intl.DateTimeFormat().resolvedOptions().timeZone); }
|
|
398
399
|
if (provider) query.set("provider", provider);
|
|
400
|
+
if (model) query.set("model", model);
|
|
401
|
+
if (date?.startsWith("<")) query.set("to", new Date(Date.parse(date.slice(1)) - 86400000).toISOString().slice(0, 10));
|
|
402
|
+
else if (date) { query.set("from", date);query.set("to", date); }
|
|
403
|
+
else if (days !== "all") query.set("days", days);
|
|
404
|
+
if (date || days !== "all") query.set("time_zone", Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
399
405
|
const data = await readDashboard(`/_ccdx/ui/usage${query.size ? `?${query}` : ""}`, { signal, source: "local_usage_log" });
|
|
400
406
|
if (!data.total || !Array.isArray(data.rows) || (mode === "analytics" && (!Array.isArray(data.analytics?.days) || !data.analytics.days.length))) throw new Error("Invalid usage snapshot");
|
|
401
407
|
return data;
|
|
@@ -495,12 +501,17 @@ element("usage-analytics").addEventListener("toggle", () => {
|
|
|
495
501
|
if (element("usage-analytics").open) usageView.revealChart();else usageView.stopMotion();
|
|
496
502
|
if (element("usage-analytics").open) dashboardRefresh.refresh("usage");
|
|
497
503
|
});
|
|
498
|
-
for (const id of ["analytics-
|
|
504
|
+
for (const id of ["analytics-metric", "analytics-view"]) element(id).addEventListener("change", () => {
|
|
499
505
|
renderAnalytics();
|
|
500
506
|
if (usageView.data && usageView.selectedDate) renderUsageTable();
|
|
501
507
|
});
|
|
508
|
+
for (const id of ["analytics-model", "analytics-range"]) element(id).addEventListener("change", () => {
|
|
509
|
+
if (id === "analytics-range" && usageView.selectedDate) { const range = element(id).value;selectUsageDay("", { refresh: false });element(id).value = range; }
|
|
510
|
+
renderAnalytics();if (usageView.data && !usageView.data.filters) renderUsageTable();
|
|
511
|
+
dashboardRefresh.invalidate("usage");void dashboardRefresh.refresh("usage", { force: true });
|
|
512
|
+
});
|
|
502
513
|
element("clear-usage-day").addEventListener("click", () => selectUsageDay(""));
|
|
503
|
-
element("usage-provider")?.addEventListener("change", () => { dashboardRefresh.invalidate("usage");dashboardRefresh.refresh("usage", { force: true }); });
|
|
514
|
+
element("usage-provider")?.addEventListener("change", () => { selectUsageDay("", { refresh: false });element("analytics-model").value = "";dashboardRefresh.invalidate("usage");dashboardRefresh.refresh("usage", { force: true }); });
|
|
504
515
|
element("refresh-models").addEventListener("click", loadModels);
|
|
505
516
|
element("refresh-usage").addEventListener("click", loadUsage);
|
|
506
517
|
for (const link of document.querySelectorAll("[data-source-link]")) link.addEventListener("click", () => {
|
package/src/dashboard/usage.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
}).join(" ");
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, modelLabel = value => value, motionAllowed = () => false }) {
|
|
10
|
+
function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, modelLabel = value => value, usageChanged = () => {}, motionAllowed = () => false }) {
|
|
11
11
|
function usageValues(row) {
|
|
12
12
|
const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
|
|
13
13
|
? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
let usageData = null;
|
|
18
18
|
let analyticsSignature, calendarSignature;
|
|
19
19
|
let selectedUsageDate = "";
|
|
20
|
+
let previousRange = "all";
|
|
20
21
|
let dailySignature, dailySelection, chartVisible = false, motionPending = false;
|
|
21
22
|
let motionTargets = [];
|
|
22
23
|
const animations = new Set();
|
|
@@ -103,18 +104,20 @@
|
|
|
103
104
|
}
|
|
104
105
|
|
|
105
106
|
function renderUsageTable() {
|
|
106
|
-
const day = selectedUsageDate && usageData.analytics?.days.find((entry) => entry.date === selectedUsageDate);
|
|
107
|
+
const day = !usageData.filters && selectedUsageDate && usageData.analytics?.days.find((entry) => entry.date === selectedUsageDate);
|
|
107
108
|
const model = element("analytics-model").value;
|
|
108
109
|
const total = day ? { ...analyticsPoint(day, model), model: "TOTAL" } : usageData.total;
|
|
109
110
|
const rows = day ? day.models.filter((row) => !model || row.model === model).sort((a, b) => b.total_tokens - a.total_tokens || a.model.localeCompare(b.model)) : usageData.rows;
|
|
110
111
|
const body = element("usage-body");
|
|
111
112
|
body.replaceChildren();
|
|
112
113
|
if (total.requests > 0) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
114
|
+
for (const [index, row] of [total, ...rows].entries()) {
|
|
115
|
+
const entry = tableRow(usageValues(row), { total: index === 0 });
|
|
116
|
+
localize(entry.children[7], "usage_cache_coverage", { known: number(row.cache_hit_known_requests), unknown: number(row.cache_hit_unknown_requests) }, "title");body.append(entry);
|
|
117
|
+
}
|
|
118
|
+
} else { emptyTable("usage-body", 8, usageData.filters ? "usage_empty_selection" : "no_usage_records"); }
|
|
119
|
+
element("clear-usage-day").hidden = !selectedUsageDate;
|
|
120
|
+
renderUsageState();
|
|
118
121
|
text("usage-note", "records_records_shown_of_models_models_shown_day", {
|
|
119
122
|
records: number(total.requests), shown: number(rows.length), models: number(day ? rows.length : usageData.model_count),
|
|
120
123
|
day: day ? phrase("zone_model", { zone: usageData.analytics.time_zone, model: model ? modelLabel(model) : phrase("all_models") }) : "",
|
|
@@ -122,17 +125,29 @@
|
|
|
122
125
|
}
|
|
123
126
|
|
|
124
127
|
function renderUsageState() {
|
|
125
|
-
text("usage-state",
|
|
128
|
+
if (selectedUsageDate.startsWith("<")) text("usage-state", "usage_earlier_before", { date: selectedUsageDate.slice(1) });
|
|
129
|
+
else text("usage-state", selectedUsageDate || "local_log");
|
|
126
130
|
}
|
|
127
131
|
|
|
128
132
|
function analyticsPoint(day, model) {
|
|
133
|
+
if (usageData?.filters) return day;
|
|
129
134
|
return model ? day.models.find((row) => row.model === model) || { requests: 0, input_tokens: 0, output_tokens: 0 } : day;
|
|
130
135
|
}
|
|
131
136
|
|
|
132
|
-
function selectUsageDay(date) {
|
|
137
|
+
function selectUsageDay(date, { refresh = true } = {}) {
|
|
138
|
+
const select = element("analytics-range");
|
|
139
|
+
const hadDate = Boolean(selectedUsageDate);
|
|
140
|
+
if (date && !selectedUsageDate) previousRange = select.value;
|
|
133
141
|
selectedUsageDate = date;
|
|
142
|
+
for (const option of [...select.children]) if (option.value === "date") option.remove();
|
|
143
|
+
if (date) {
|
|
144
|
+
const option = document.createElement("option");option.value = "date";
|
|
145
|
+
if (date.startsWith("<")) localize(option, "usage_earlier_before", { date: date.slice(1) });else option.textContent = date;
|
|
146
|
+
select.append(option);select.value = "date";
|
|
147
|
+
} else if (hadDate) select.value = previousRange;
|
|
134
148
|
renderUsageTable();
|
|
135
149
|
renderAnalytics();
|
|
150
|
+
if (refresh) usageChanged();
|
|
136
151
|
}
|
|
137
152
|
|
|
138
153
|
function dayButton(day, point) {
|
|
@@ -142,10 +157,10 @@
|
|
|
142
157
|
button.setAttribute("aria-pressed", String(day.date === selectedUsageDate));
|
|
143
158
|
const description = !day.available ? phrase("no_retained_history")
|
|
144
159
|
: phrase("calls_recorded_calls_input_input_output_output_cached_cached_inc", {
|
|
145
|
-
|
|
160
|
+
calls: number(point.requests), input: number(point.input_tokens), output: number(point.output_tokens), cached: number(point.cache_read_tokens), partial: point.tokens_partial ? phrase("partial_token_counts") : "",
|
|
146
161
|
});
|
|
147
|
-
for (const attribute of ["title", "aria-label"]) localize(button, "date_description", { date: day.date, description }, attribute);
|
|
148
|
-
button.addEventListener("click", () => selectUsageDay(day.date));
|
|
162
|
+
for (const attribute of ["title", "aria-label"]) localize(button, "date_description", { date: day.date === "earlier" ? phrase("usage_earlier_before", { date: day.before }) : day.date, description }, attribute);
|
|
163
|
+
button.addEventListener("click", () => selectUsageDay(day.date === "earlier" ? "<" + day.before : day.date));
|
|
149
164
|
return button;
|
|
150
165
|
}
|
|
151
166
|
|
|
@@ -158,13 +173,14 @@
|
|
|
158
173
|
if (signature === analyticsSignature) return;
|
|
159
174
|
analyticsSignature = signature;
|
|
160
175
|
const days = analytics.days;
|
|
161
|
-
const
|
|
176
|
+
const range = element("analytics-range").value === "date" ? previousRange : element("analytics-range").value;
|
|
177
|
+
const daily = usageData.filters ? [...(analytics.earlier ? [analytics.earlier] : []), ...days] : range === "all" ? days : days.slice(-Number(range));
|
|
162
178
|
const maximum = Math.max(1, ...daily.map((day) => {
|
|
163
179
|
const point = analyticsPoint(day, model);
|
|
164
180
|
return point.input_tokens + point.output_tokens;
|
|
165
181
|
}));
|
|
166
182
|
renderDaily(daily, model, maximum);
|
|
167
|
-
text("daily-from", daily[0].date);
|
|
183
|
+
text("daily-from", daily[0].date === "earlier" ? "usage_earlier" : daily[0].date);
|
|
168
184
|
text("daily-to", analytics.to);
|
|
169
185
|
if (commonSignature === calendarSignature) return;
|
|
170
186
|
calendarSignature = commonSignature;
|
|
@@ -174,7 +190,7 @@
|
|
|
174
190
|
return metric === "tokens" ? point.input_tokens + point.output_tokens : point.requests;
|
|
175
191
|
};
|
|
176
192
|
const peak = Math.max(1, ...days.map(value));
|
|
177
|
-
text("activity-scale", "metric_peak_peak", { metric: phrase(metric === "tokens" ? "input_output" : "
|
|
193
|
+
text("activity-scale", "metric_peak_peak", { metric: phrase(metric === "tokens" ? "input_output" : "recorded_usage"), peak: number(peak === 1 && days.every((day) => value(day) === 0) ? 0 : peak) });
|
|
178
194
|
const calendar = element("activity-calendar");
|
|
179
195
|
calendar.replaceChildren();
|
|
180
196
|
const offset = (new Date(`${days[0].date}T00:00:00Z`).getUTCDay() + 6) % 7;
|
|
@@ -205,7 +221,7 @@
|
|
|
205
221
|
calendar.append(button);
|
|
206
222
|
}
|
|
207
223
|
text("analytics-note", "zone_from_to_retained_history_starts_first_oldest_day_may_be_par", {
|
|
208
|
-
zone: analytics.time_zone, from: daily[0].date, to: analytics.to, first: analytics.first_date || phrase("unknown"),
|
|
224
|
+
zone: analytics.time_zone, from: analytics.earlier ? analytics.first_date : daily[0].date, to: analytics.to, first: analytics.first_date || phrase("unknown"),
|
|
209
225
|
excluded: analytics.undated_records ? phrase("count_records_with_invalid_future_timestamps_excluded", { count: number(analytics.undated_records) }) : "",
|
|
210
226
|
limit: analytics.models_truncated ? phrase("model_filters_limited_to_100_all_model_totals_include_the_remain") : "",
|
|
211
227
|
});
|
|
@@ -216,7 +232,7 @@
|
|
|
216
232
|
const select = element("analytics-model");
|
|
217
233
|
const previous = select.value;
|
|
218
234
|
select.replaceChildren();
|
|
219
|
-
for (const model of [...new Set(["", ...usageData.analytics
|
|
235
|
+
for (const model of [...new Set(["", ...(usageData.available_models || usageData.analytics?.models || []), ...(previous ? [previous] : [])])]) {
|
|
220
236
|
const option = document.createElement("option");
|
|
221
237
|
option.value = model;
|
|
222
238
|
if (model) option.textContent = modelLabel(model);
|
|
@@ -228,10 +244,10 @@
|
|
|
228
244
|
|
|
229
245
|
function applyUsage(data, { changed }) {
|
|
230
246
|
const sameProvider = (data.provider || "all") === (usageData?.provider || "all");
|
|
231
|
-
if (!sameProvider
|
|
247
|
+
if (!sameProvider && selectedUsageDate) selectUsageDay("", { refresh: false });
|
|
232
248
|
usageData = { ...data, ...(!data.analytics && sameProvider && usageData?.analytics ? { analytics: usageData.analytics } : {}) };
|
|
233
249
|
if (changed) {
|
|
234
|
-
if (data.analytics) updateAnalyticsModels();
|
|
250
|
+
if (data.available_models || data.analytics) updateAnalyticsModels();
|
|
235
251
|
renderUsageTable();
|
|
236
252
|
if (data.analytics) renderAnalytics();
|
|
237
253
|
}
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -14,9 +14,10 @@ import {
|
|
|
14
14
|
renderTerminalAnimationFrame,
|
|
15
15
|
TERMINAL_ANIMATION_THEMES,
|
|
16
16
|
} from "./terminal-animation.mjs";
|
|
17
|
-
import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups } from "./usage-store.mjs";
|
|
17
|
+
import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups, usageProvider } from "./usage-store.mjs";
|
|
18
18
|
import { createUsageAnalytics } from "./usage-analytics.mjs";
|
|
19
19
|
import { analyzeUsageLogs } from "./usage-analysis.mjs";
|
|
20
|
+
import { createUsageQuery } from "./usage-query.mjs";
|
|
20
21
|
import { readUserSettings, terminalAnimationPreference, writeTerminalAnimationTheme } from "./user-settings.mjs";
|
|
21
22
|
import { settingsPreferencesSnapshot } from "./settings-preferences.mjs";
|
|
22
23
|
|
|
@@ -383,12 +384,15 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
383
384
|
const query = new URL(req.url, "http://localhost").searchParams;
|
|
384
385
|
const provider = query.get("provider") || "";
|
|
385
386
|
if (provider && !isProviderId(provider)) { sendJson(res, 400, { error: "Select a valid provider" });return; }
|
|
387
|
+
let selection;
|
|
388
|
+
try { selection = createUsageQuery({ provider, model: query.get("model") || "", days: query.get("days") || "all", from: query.get("from") || "", to: query.get("to") || "", timeZone: query.get("time_zone") || "UTC" }); }
|
|
389
|
+
catch (error) { sendJson(res, 400, { error: error.message });return; }
|
|
386
390
|
let analytics = null;
|
|
387
391
|
if (query.get("analytics") === "1") {
|
|
388
392
|
try {
|
|
389
393
|
const timeZone = query.get("time_zone") || "UTC";
|
|
390
394
|
if (timeZone.length > 100) throw new Error("Invalid time zone");
|
|
391
|
-
analytics = createUsageAnalytics({ timeZone, qualifyProviders: !provider });
|
|
395
|
+
analytics = createUsageAnalytics({ timeZone, qualifyProviders: !provider, from: selection.filters.from, to: selection.filters.to });
|
|
392
396
|
} catch {
|
|
393
397
|
sendJson(res, 400, { error: "Select a valid usage time zone" });
|
|
394
398
|
return;
|
|
@@ -396,10 +400,19 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
396
400
|
}
|
|
397
401
|
const abort = createRequestAbort(req, res);
|
|
398
402
|
try {
|
|
399
|
-
const
|
|
400
|
-
|
|
401
|
-
const
|
|
402
|
-
|
|
403
|
+
const filtered = selection.filters.model || selection.filters.from || selection.filters.to;
|
|
404
|
+
const observedModels = new Set();
|
|
405
|
+
const recordFilter = record => {
|
|
406
|
+
if (observedModels.size < 100) observedModels.add(provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`);
|
|
407
|
+
return selection.matches(record);
|
|
408
|
+
};
|
|
409
|
+
const analysis = (analytics || filtered) && !usageSummaryFn
|
|
410
|
+
? await analyzeUsageLogs(undefined, { provider, model: selection.filters.model, from: selection.filters.from, to: selection.filters.to, timeZone: selection.filters.time_zone, signal: abort.signal }) : null;
|
|
411
|
+
const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, { ...options, signal: abort.signal })))({ provider,
|
|
412
|
+
...(filtered ? { recordFilter } : {}), ...(analytics ? { onRecord: analytics.record } : {}) });
|
|
413
|
+
const availableModels = analysis?.analytics.models || (observedModels.size ? [...observedModels].sort() : Object.keys(provider ? summary.byModel : summary.bySourceModel || summary.byModel).sort().slice(0, 100));
|
|
414
|
+
if (!abort.signal.aborted) sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, filters: selection.filters, available_models: availableModels,
|
|
415
|
+
...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
|
|
403
416
|
} catch {
|
|
404
417
|
if (!abort.signal.aborted) sendJson(res, 500, { error: "Could not read local usage summary" });
|
|
405
418
|
} finally { abort.cleanup(); }
|
|
@@ -4,6 +4,7 @@ import { isProviderId } from "./provider-metadata.mjs";
|
|
|
4
4
|
import { applicationLabel } from "./request-application.mjs";
|
|
5
5
|
import { createContextMetrics } from "./context-metrics.mjs";
|
|
6
6
|
import { createChangeSignal } from "./activity-events.mjs";
|
|
7
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
7
8
|
|
|
8
9
|
const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
|
|
9
10
|
const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
|
|
@@ -346,8 +347,10 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
346
347
|
observeContext(values) {
|
|
347
348
|
if (finished || !values || typeof values !== "object") return;
|
|
348
349
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
349
|
-
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
|
|
350
|
+
for (const key of [...Object.keys(context), "requested_model", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
|
|
350
351
|
const value = values[key];
|
|
352
|
+
if (key === "requested_model") { if (typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value) context[key] = value;continue; }
|
|
353
|
+
if (key === "usage_state") { if (["pending", "reported", "partial", "missing", "unavailable"].includes(value)) context[key] = value;continue; }
|
|
351
354
|
if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
|
|
352
355
|
if (["privacy_error", "privacy_event_type", "privacy_channel_type"].includes(key)) {
|
|
353
356
|
if (typeof value === "string" && /^[a-z0-9_.]{1,80}$/.test(value)) context[key] = value;continue;
|
|
@@ -377,6 +380,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
377
380
|
},
|
|
378
381
|
finish({ failed: finishFailed = false, aborted = false, statusCode = 0, rejectionReason } = {}) {
|
|
379
382
|
if (finished) return;
|
|
383
|
+
if (context.usage_state === "pending") context.usage_state = "missing";
|
|
380
384
|
if (!sourceStats) assignProvider("unknown");
|
|
381
385
|
finished = true;
|
|
382
386
|
activeTotal--;activeRequests.delete(activeId);
|
package/src/terminal-state.mjs
CHANGED
|
@@ -3,6 +3,14 @@ import { terminalCell } from "./terminal-text.mjs";
|
|
|
3
3
|
const integer = value => Number.isSafeInteger(value) && value >= 0;
|
|
4
4
|
const appIds = { codex_app: "codex", codex_cli: "codex", codex: "codex", claude_app: "claude_app", claude_code: "claude_code", gemini_app: "antigravity" };
|
|
5
5
|
export const TERMINAL_CLIENT_NAMES = Object.freeze({ codex: "Codex", claude_app: "Claude App", claude_code: "Claude Code", gemini: "Antigravity", antigravity: "Antigravity" });
|
|
6
|
+
export function terminalRequestState(row) {
|
|
7
|
+
if (!row.active) return row.state || "unknown";
|
|
8
|
+
if (row.terminal_outcome) return "Finishing";
|
|
9
|
+
if (row.first_output_ms != null) return "Responding";
|
|
10
|
+
if (row.phase === "admission") return "Queued";
|
|
11
|
+
if (row.upstream_attempts > 1) return "Retrying";
|
|
12
|
+
return row.upstream_attempts ? "Waiting upstream" : "Processing input";
|
|
13
|
+
}
|
|
6
14
|
const labels = { configured: "Configured", paused: "Paused", disabled: "Disabled", not_configured: "Not configured", not_installed: "Not installed",
|
|
7
15
|
preserved: "Unchanged", partially_preserved: "Partly unchanged", manual_sync: "Manual sync", default_unavailable: "Default unavailable", configuration_unavailable: "Unreadable", unavailable: "Unavailable" };
|
|
8
16
|
export function terminalUptime(milliseconds) {
|
package/src/usage-analysis.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
import { summarizeUsage, summarizeUsageLogs, usageLogPath, usageSummaryVersion, subscribeUsageAppends, usageProvider, mergeUsageSummary } from "./usage-store.mjs";
|
|
4
4
|
import { createUsageAnalytics } from "./usage-analytics.mjs";
|
|
5
5
|
import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
|
|
6
|
+
import { createUsageQuery } from "./usage-query.mjs";
|
|
6
7
|
|
|
7
8
|
const MAX_ENTRIES = 2;
|
|
8
9
|
const MAX_BYTES = 2 * 1024 * 1024;
|
|
@@ -56,9 +57,10 @@ function observe() {
|
|
|
56
57
|
});
|
|
57
58
|
}
|
|
58
59
|
|
|
59
|
-
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", signal } = {}) {
|
|
60
|
+
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", model = "", days = "all", from = "", to = "", signal } = {}) {
|
|
61
|
+
const selection = createUsageQuery({ provider, model, days, from, to, timeZone, now });
|
|
60
62
|
const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
61
|
-
const file = path.resolve(filePath), query = `${file}\0${
|
|
63
|
+
const file = path.resolve(filePath), query = `${file}\0${selection.key}\0${zone.format(new Date(now))}`;
|
|
62
64
|
const version = warn === console.error ? await usageSummaryVersion(file, { settled: false }) : null;
|
|
63
65
|
const collect = async () => {
|
|
64
66
|
const cached = version && cache.get(query);
|
|
@@ -68,25 +70,34 @@ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "
|
|
|
68
70
|
for (const line of cached.pending) {
|
|
69
71
|
const record = JSON.parse(line);
|
|
70
72
|
if (provider && provider !== usageProvider(record)) continue;
|
|
73
|
+
const label = provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`;
|
|
74
|
+
if (cached.models.size < 100) cached.models.add(label);else if (!cached.models.has(label)) cached.modelsTruncated = true;
|
|
75
|
+
if (!selection.matches(record)) continue;
|
|
71
76
|
const one = summarizeUsage([record]);mergeUsageSummary(cached.summary, one);cached.analytics.record(record, one);
|
|
72
77
|
}
|
|
73
78
|
cached.pending = [];cached.pendingBytes = 0;
|
|
74
|
-
const
|
|
79
|
+
const snapshot = cached.analytics.snapshot();
|
|
80
|
+
const result = { summary: cached.summary, analytics: { ...snapshot, models: [...cached.models].sort(), models_truncated: snapshot.models_truncated || cached.modelsTruncated }, filters: selection.filters };
|
|
75
81
|
cached.bytes = Buffer.byteLength(JSON.stringify(result));
|
|
76
82
|
if (result.analytics.undated_records > 0) cache.delete(query);
|
|
77
83
|
prune();return result;
|
|
78
84
|
}
|
|
79
85
|
cache.delete(query);prune();
|
|
80
|
-
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
|
|
81
|
-
let warned = false;
|
|
82
|
-
const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record,
|
|
86
|
+
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider, from: selection.filters.from, to: selection.filters.to }), models = new Set();
|
|
87
|
+
let warned = false, modelsTruncated = false;
|
|
88
|
+
const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record, recordFilter: record => {
|
|
89
|
+
const label = provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`;
|
|
90
|
+
if (models.size < 100) models.add(label);else if (!models.has(label)) modelsTruncated = true;
|
|
91
|
+
return selection.matches(record);
|
|
92
|
+
},
|
|
83
93
|
warn(message) { warned = true;warn(message); } });
|
|
84
|
-
const
|
|
94
|
+
const snapshot = analytics.snapshot();
|
|
95
|
+
const result = { summary, analytics: { ...snapshot, models: [...models].sort(), models_truncated: snapshot.models_truncated || modelsTruncated }, filters: selection.filters };
|
|
85
96
|
const complete = version && await completeLines(file);
|
|
86
97
|
const after = version ? await usageSummaryVersion(file, { settled: false }) : null;
|
|
87
98
|
const bytes = Buffer.byteLength(JSON.stringify(result));
|
|
88
99
|
if (version && complete && after === version && !warned && !result.analytics.undated_records && bytes <= MAX_BYTES) {
|
|
89
|
-
cache.set(query, { file, version, summary, analytics, bytes, pending: [], pendingBytes: 0 });observe();prune();
|
|
100
|
+
cache.set(query, { file, version, summary, analytics, models, modelsTruncated, bytes, pending: [], pendingBytes: 0 });observe();prune();
|
|
90
101
|
}
|
|
91
102
|
return result;
|
|
92
103
|
};
|