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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Use your model services in **Codex App, Claude App and Claude Code** through one local gateway.
4
4
 
5
- On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google. Set it up on the Antigravity page; inspect it with `ccdx app antigravity status`. Existing clients keep their setup.
5
+ On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google. The Antigravity page lists each model once, with its reasoning choices on the same row. Inspect it with `ccdx app antigravity status`. Existing clients keep their setup.
6
6
 
7
7
  Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CI and prebuilt releases cover **macOS on Apple Silicon** and **Windows on x64/ARM64**. Intel Mac code remains available, without CI coverage or new prebuilt assets.
8
8
 
@@ -52,7 +52,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
52
52
  | Preview client setup | `ccdx app claude-app sync --preview` |
53
53
  | Set up Antigravity | `ccdx app antigravity status` / `enable` / `open` |
54
54
  | Inspect failures | `ccdx requests --failed` |
55
- | Read usage | `ccdx usage` / `ccdx usage --scope run` |
55
+ | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --scope run` |
56
56
  | Inspect preferences | `ccdx config show --effective` |
57
57
  | Inspect local masking | `ccdx config privacy status` |
58
58
  | Check local setup | `ccdx doctor` |
@@ -17,6 +17,10 @@ Client integration, image tools and the dashboard are not a general plugin frame
17
17
 
18
18
  ## Gemini native boundary
19
19
 
20
+ `antigravity-usage.mjs` observes Google JSON/SSE within the original forwarding loop, with the existing SSE byte limit and no stream tee or read-ahead. Observation failures mark usage unavailable and never change response bytes. The handler coalesces reported numeric fields and settles one usage row per request, including usage received before failure/cancellation. Google candidate/thought output and prompt/tool-use input are normalized without treating missing cache counts as zero. Request ID, original model, actual model and usage availability are scalar metadata; prompts and response text are not persisted by this observer.
21
+
22
+ The management snapshot keeps native per-effort aliases in `models` and adds `model_groups` for one model row with several reasoning choices. Saved alias subsets and the native catalog are unchanged. The WebUI and terminal group the display and selection while JSON clients retain the compatible alias list.
23
+
20
24
  Antigravity tool schemas are converted to Chat Completions schemas. Object schemas always include an explicit `properties` map, including zero-argument functions. The upstream Copilot service rejects native schemas that omit that map. Pausing Copilot access keeps model choices visible while generation remains gated.
21
25
 
22
26
  The dashboard separates source enablement, source-to-app authorization and per-app model choices. Source enablement is immediate; authorization and model drafts use explicit Save / Discard actions. GitHub, Microsoft 365 and custom APIs share the same authorization form. Antigravity's source authorization and its Copilot access switch represent the same saved integration state.
@@ -553,6 +557,8 @@ projects the optional lightweight response; full status stays the default public
553
557
  contract. Hidden status regions defer DOM updates, and summary rendering never
554
558
  replaces the full request/history cache.
555
559
 
560
+ `usage-query.mjs` defines provider/model and inclusive calendar-date selection for the WebUI and CLI. `usage-analysis.mjs` keys its existing bounded cache by that selection and applies the same predicate to full scans and witnessed appends. Model choices are collected before the predicate so changing a filter does not lose the other options. Tables, totals and charts consume one filtered snapshot. Up to 365 daily points remain bounded; older valid records share an earlier bucket, preserving all-history totals without unbounded DOM growth. Chart type and language changes remain local; changes to source, model or period invalidate only usage.
561
+
556
562
  `dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals. It keeps paired input/cache-read sums and known/unknown record counts separate from full token totals; CLI/TUI, WebUI and daily analytics use those same sums for the weighted rate and partial-coverage flag. Aggregate snapshots expose that basis without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
557
563
 
558
564
  `dashboard-updates.mjs` is loaded only by the protected update-information route. It projects bounded public stable-release metadata and publication dates, with process-local single-flight, five-minute success and one-minute failure caches. Its asynchronous npm network-configuration read reuses the installer's existing policy-preserving downloader; it adds no runtime dependency, credentials or synchronous child process on the service event loop. Metadata has a four-second per-request deadline and 128 KiB decoded-body bound. It never installs or restarts anything and does not alter startup's independent web-redirect lookup. `dashboard/updates.js` renders current/available/unknown states and validated, pinned installation command text; `refresh.js` owns its visible Settings refresh cadence. Failed checks preserve explicitly labeled prior metadata. No provider authentication or inference is involved.
package/docs/REFERENCE.md CHANGED
@@ -38,7 +38,7 @@ For installation and first use, start with the [README](../README.md). This refe
38
38
  | `ccdx config reset --preview` / `restore` | Preview defaults or restore the pre-reset backup |
39
39
  | `ccdx requests [--failed] [--active]` | Inspect retained requests |
40
40
  | `ccdx requests show <request_id>` | Read one retained request |
41
- | `ccdx usage [--scope all\|run] [--provider ID]` | Read recorded usage or current-run usage |
41
+ | `ccdx usage [--scope all\|run] [--provider ID] [--model ID] [--days N\|all]` | Read filtered retained usage or current-run totals |
42
42
  | `ccdx doctor [--online] [--compat] [--fix] [--json]` | Check local setup; optional access checks and repairs |
43
43
  | `ccdx doctor config` / `network` / `report` | Read configuration, routing or a redacted local report |
44
44
  | `ccdx doctor cache [--limit MiB\|default]` | Inspect runtime buffers or change their limit |
@@ -68,7 +68,9 @@ inspection. Use `app antigravity status` to check the signed installation explic
68
68
  The old `app gemini` commands remain available. Authorize Antigravity on the GitHub
69
69
  Copilot source page, or with `source github access --edit --apps codex,antigravity --yes`.
70
70
  Choose its exposed models on the Antigravity page or with
71
- `app antigravity models --edit`. A model file uses `{"models":["<ccdx-copilot-model-id>"]}`.
71
+ `app antigravity models --edit`. Each WebUI/terminal row represents one model; reasoning levels are independent choices in that row. A model checkbox selects or clears all its levels, and a mixed checkbox preserves a saved subset. Save/Discard, refresh, navigation and pausing keep that subset.
72
+
73
+ The native Gemini catalog still uses distinct routing aliases for each level so its original selector can choose the intended effort. JSON model output retains those aliases for compatibility, with a `model` field identifying the actual model; the management status also includes `model_groups`. A model file accepts `{"models":["gemini-4-carbon"]}` to expose all of its levels, or the existing `ccdx-copilot-...-low|medium|high` aliases to choose a subset.
72
74
  After saving, the Antigravity page reports whether the client has fetched the current model list. If the list is pending, reopen Gemini through CCDX.
73
75
 
74
76
  The WebUI uses one authorization form for GitHub Copilot, Microsoft 365 and custom APIs. Source switches apply immediately. App-authorization and model checkboxes are drafts until **Save**; **Discard changes** restores the saved selection. Drafts survive refresh and navigation. Source authorization does not choose app models.
@@ -157,6 +159,25 @@ Catalog diagnostics distinguish local cached data from an online response and ex
157
159
 
158
160
  Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
159
161
 
162
+ Antigravity Copilot answers/background summaries and native Google generation record returned Gemini token usage for JSON and streaming responses. Each request records its latest reported fields once, including usage received before failure or cancellation. Missing upstream token/cache counts remain unknown; a real zero cache count stays zero. This starts with 1.3.26; previously unrecorded usage cannot be recovered from the ledger. Ordinary Gemini chat remains outside the Antigravity bridge.
163
+
164
+ Native records use source `google`; Copilot records use `github`. Google output includes reported candidate and thought tokens, with thought tokens also identified separately. Reported tool-use prompt tokens are included in input; cached tokens remain a subset of input. The original Google response bytes, status and backpressure remain unchanged. Observation uses the existing SSE buffer limit per event or non-streaming response; oversized/unreadable metadata is marked unavailable and the response continues normally. Only numeric usage and routing metadata are retained.
165
+
166
+ Requests and usage share the CCDX request ID; an upstream response ID is separate. Request details show the original model when it differs from the actual model, and distinguish reported, partial, missing and unreadable usage metadata. Requests waiting for body parsing show “Model pending” and “Source pending”; queue, input processing, upstream wait and response delivery have separate states. The CLI exposes the same retained metadata with `ccdx requests show ID --format json`; `ccdx requests --app antigravity` filters the native integration.
167
+
168
+ Usage source, model and time controls apply to the entire token-usage page: totals, model rows and charts. Selecting a day narrows that shared query; Clear date restores the previous period. Chart type, language and theme changes remain local. All retained history remains available; date charts keep at most 365 daily points and combine earlier valid records into an Earlier records bucket. Invalid/future timestamps remain in all-history totals but are excluded from date charts and bounded date filters, with the exclusion count shown. Model choices are bounded to 100 and preserve other available choices while a filter is active.
169
+
170
+ CLI and TUI subcommands share the same source/model/calendar semantics:
171
+
172
+ ```sh
173
+ ccdx usage --provider google --days 7
174
+ ccdx usage --model 'github / gemini-4-carbon' --from 2026-11-01 --to 2026-11-13 --time-zone Asia/Shanghai
175
+ ccdx usage --scope run --provider google
176
+ ccdx requests --app antigravity --active
177
+ ```
178
+
179
+ `--days` accepts 1–365 or `all` (the default). Explicit inclusive `--from`/`--to` dates use YYYY-MM-DD and cannot be combined with a numeric `--days`. Dates use UTC by default; `--time-zone` chooses another IANA zone. An unqualified model includes matching models across sources; `source / model` narrows it to one source. Current-run totals support only the provider filter; model/date filters use retained history. The service TUI includes returned Google usage in its existing current-run totals without scanning the ledger.
180
+
160
181
  For an identified conversation, hovering a point in the input-history chart shows that request's available cache-reuse ratio. Missing or invalid counts remain unknown; the bounded in-memory history and retained usage do not change.
161
182
 
162
183
  ## Settings and appearance
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.25",
3
+ "version": "1.3.26",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -179,7 +179,7 @@ export function chatToAntigravity(response, originalNames) {
179
179
  ...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) };
180
180
  }
181
181
 
182
- export async function* chatStreamToAntigravity(response, originalNames, { onChunk } = {}) {
182
+ export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage } = {}) {
183
183
  if (!response?.body) throw invalid("Upstream Chat stream has no body", 502);
184
184
  const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false;
185
185
  const frame = async function* () {
@@ -189,6 +189,7 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
189
189
  let event;try { event = JSON.parse(raw); } catch { throw invalid("Invalid upstream Chat stream event", 502); }
190
190
  const upstreamError = upstreamChatStreamError(event);if (upstreamError) throw upstreamError;
191
191
  if (event?.usage) usage = event.usage;
192
+ if (event?.usage || event?.copilot_usage) onUsage?.(event);
192
193
  const choice = event?.choices?.[0];
193
194
  if (!choice) return;
194
195
  if (choice.finish_reason) finish = choice.finish_reason;
@@ -1,12 +1,14 @@
1
1
  import {randomUUID} from "node:crypto";
2
+ import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
2
3
  import {createRequestAbort,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
3
4
  import {safeUpstreamResponseHeaders} from "./upstream-headers.mjs";
4
5
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
5
6
  import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
6
7
  import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,mergeAntigravityModels} from "./antigravity-models.mjs";
7
8
  import {createPrivacyTextFragments} from "./privacy-stream.mjs";
9
+ import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
8
10
  import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
9
- import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markResponseTerminal} from "./stream-performance.mjs";
11
+ import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseTerminal} from "./stream-performance.mjs";
10
12
 
11
13
  const PREFIX="/antigravity";
12
14
  const MAX_REPLY=64*1024*1024;
@@ -31,12 +33,26 @@ function groundedSearch(result,query){
31
33
  }
32
34
 
33
35
  export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},
34
- fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
36
+ recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
35
37
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
36
38
  let active=0,observed=false,catalogModels=null;
37
39
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
38
40
  const handler=async(req,res)=>{
39
- const abort=createRequestAbort(req,res);let release=()=>{},session;
41
+ const abort=createRequestAbort(req,res);let release=()=>{},session,usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
42
+ const captureUsage=event=>{
43
+ if(!event?.usage&&!event?.copilot_usage)return;
44
+ const known=value=>Number.isSafeInteger(value)&&value>=0,u={...usageEvent?.usage},incoming=event.usage;
45
+ for(const key of ["prompt_tokens","completion_tokens","total_tokens"])if(known(incoming?.[key]))u[key]=incoming[key];
46
+ for(const [key,field]of [["prompt_tokens_details","cached_tokens"],["completion_tokens_details","reasoning_tokens"]])if(known(incoming?.[key]?.[field]))u[key]={[field]:incoming[key][field]};
47
+ const billing=Array.isArray(event.copilot_usage?.token_details)?event.copilot_usage:undefined;
48
+ usageEvent={...usageEvent,...(Object.keys(u).length?{usage:u}:{}),...(billing?{copilot_usage:billing}:{}),
49
+ ...(typeof event.id==="string"?{id:event.id}:{}),...(typeof event.model==="string"?{model:event.model}:{})};
50
+ markOutputTokens(u.completion_tokens);
51
+ if(typeof event.model==="string")markResponseModel(event.model);
52
+ const hasBilling=usageEvent.copilot_usage?.token_details.some(item=>known(item?.token_count)&&item.token_count>0);
53
+ markRequestObservation({input_tokens:u.prompt_tokens,cached_input_tokens:u.prompt_tokens_details?.cached_tokens,
54
+ usage_state:known(u.prompt_tokens)&&known(u.completion_tokens)&&known(u.prompt_tokens_details?.cached_tokens)?"reported":Object.keys(u).length||hasBilling?"partial":"missing"});
55
+ };
40
56
  active++;counts.total++;
41
57
  try{
42
58
  if(!enabled())throw httpError("Antigravity integration is disabled",503);
@@ -51,11 +67,16 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
51
67
  const body=req.method==="POST"?await readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody}):null;
52
68
  const context=currentRequestContext();if(context)context.application="gemini_app";
53
69
  if(body?.model)observeRequestedModel(body);
70
+ markRequestObservation({requested_model:context?.requestedModel});
54
71
  abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");
55
72
  const generation=["streamGenerateContent","generateContent"].includes(method);
56
73
  const native=async()=>{
57
74
  counts.google++;
58
- if(generation)markUpstreamStarted(method==="streamGenerateContent");
75
+ if(generation){
76
+ usageModel=body.model;usageProvider="google";usageMode=method==="streamGenerateContent"?"sse":"json";
77
+ if(context){context.provider="google";context.streamPerformance?.setProvider?.("google")}
78
+ markRequestObservation({usage_state:"pending"});markUpstreamStarted(method==="streamGenerateContent");
79
+ }
59
80
  const upstream=await fetchGoogle(googleOrigin+route+local.search,{method:req.method,headers:{...nativeHeaders(req),...(body?{"content-type":"application/json"}:{})},
60
81
  ...(body?{body:JSON.stringify(body)}:{}),signal:abort.signal,redirect:"error"});
61
82
  if(generation)markUpstreamHeaders(upstream.status);
@@ -65,8 +86,26 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
65
86
  catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX));
66
87
  res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
67
88
  }
89
+ const nativeStreaming=/text\/event-stream/i.test(upstream.headers.get("content-type")||"");
90
+ if(generation)usageMode=nativeStreaming?"sse":"json";
91
+ const observer=generation&&upstream.ok?createGoogleResponseObserver({streaming:nativeStreaming,onEvent:value=>{
92
+ const response=value?.response||value,event=googleUsageEvent(value);if(event)captureUsage(event);
93
+ const candidates=response?.candidates||[];
94
+ if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&typeof part.text==="string"&&part.text)))markFirstOutput("delta");
95
+ if(response?.error)outcome="failed";
96
+ else if(outcome!=="failed"&&candidates.some(candidate=>candidate.finishReason)){
97
+ outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";
98
+ }
99
+ }}):null;
68
100
  res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
69
- if(upstream.body)for await(const data of upstream.body){abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");await writeOrDrain(res,data,{signal:abort.signal})}
101
+ try{
102
+ if(upstream.body)for await(const data of upstream.body){
103
+ abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");observer?.push(data);
104
+ if(!await writeOrDrain(res,data,{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);
105
+ }
106
+ }finally{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})}
107
+ if(generation&&!upstream.ok)outcome="failed";
108
+ if(outcome)markResponseTerminal(outcome);
70
109
  res.end();
71
110
  };
72
111
  if(!generation){
@@ -105,38 +144,53 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
105
144
  if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported Antigravity inference type",400);
106
145
  const target=body.requestType==="agent"?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
107
146
  if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
108
- const stream=method==="streamGenerateContent";
147
+ const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
109
148
  const converted=antigravityToChat(request,{model:target.model,effort:target.effort,stream});
110
- observeRequestedModel({model:target.model});
149
+ markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
111
150
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
112
151
  const upstream=await client.chatCompletions(session.body,{signal:abort.signal,retryOptions:{retries:0}});
113
152
  markUpstreamHeaders(upstream.status);
114
153
  if(!upstream.ok){await upstream.body?.cancel();throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
115
154
  if(!stream){
116
- const result=chatToAntigravity(JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"})),converted.originalNames);
117
- markResponseTerminal(result.candidates[0].finishReason==="STOP"?"completed":"incomplete");
155
+ const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
156
+ const result=chatToAntigravity(data,converted.originalNames);
157
+ outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
118
158
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
119
159
  }
120
160
  const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
121
161
  res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
122
162
  const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
123
- for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout")})){
163
+ for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage})){
124
164
  const candidate=chunk.response?.candidates?.[0];
125
165
  for(const part of candidate?.content?.parts||[]){
126
166
  if(part.functionCall||typeof part.text==="string"&&part.text&&!part.thought)markFirstOutput("delta");
127
167
  if(part.functionCall){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});Object.assign(part,session.restoreToolValue(part));}
128
168
  else if(typeof part.text==="string"&&!part.thought)part.text=text.push(part.text);
129
169
  }
130
- if(candidate?.finishReason){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});markResponseTerminal(candidate.finishReason==="STOP"?"completed":"incomplete")}
170
+ if(candidate?.finishReason){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});outcome=candidate.finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome)}
131
171
  await emit(chunk);
132
172
  }
133
173
  res.end();
134
174
  }catch(error){
135
175
  counts.failed++;
136
- markResponseTerminal(abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed");
176
+ outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";markResponseTerminal(outcome);
137
177
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
138
178
  else sendJsonError(res,error,error.statusCode||502);
139
- }finally{session?.release();release();abort.cleanup();active--}
179
+ }finally{
180
+ session?.release();release();abort.cleanup();active--;
181
+ if(usageEvent){
182
+ const u=usageEvent.usage,record=buildResponsesUsageRecord({surface:"antigravity",mode:usageMode,model:usageModel,
183
+ response:{id:usageEvent.id,model:usageEvent.model||usageModel,usage:u?{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,
184
+ total_tokens:u.total_tokens,input_tokens_details:u.prompt_tokens_details,output_tokens_details:u.completion_tokens_details}:undefined},
185
+ event:{copilot_usage:usageEvent.copilot_usage}});
186
+ if(record){
187
+ markRequestObservation({input_tokens:record.usage?.input_tokens,cached_input_tokens:record.usage?.cached_input_tokens});
188
+ const context=currentRequestContext();
189
+ recordUsageFn({...record,provider:usageProvider,client:"gemini",request_id:context?.requestId,requested_model:context?.requestedModel,
190
+ outcome:outcome||"unknown",...(outcome!=="completed"?{partial:true}:{})});
191
+ }
192
+ }
193
+ }
140
194
  };
141
195
  handler.snapshot=()=>({enabled:enabled(),observed,catalog_models:catalogModels,active,...counts});
142
196
  return handler;
@@ -42,12 +42,17 @@ export function createAntigravityRuntime({client,models=()=>[],privacy,home=os.h
42
42
  imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,fetchGoogle:googleFetch,acquireRequest,...timeouts});
43
43
  function snapshot(){
44
44
  const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot();
45
- const listed=antigravityCopilotModels(models()).map(({id,displayName,effort,maxTokens})=>({id,name:displayName,effort,context_window:maxTokens,selected:config.selected_models===null||config.selected_models.includes(id)}));
45
+ const listed=antigravityCopilotModels(models()).map(({id,model,displayName,effort,maxTokens})=>({id,model,name:displayName,effort,context_window:maxTokens,selected:config.selected_models===null||config.selected_models.includes(id)}));
46
+ const groups=new Map();
47
+ for(const variant of listed){
48
+ if(!groups.has(variant.model))groups.set(variant.model,{id:variant.model,name:variant.name.split(" · Copilot")[0],source:"github",context_window:variant.context_window,efforts:[]});
49
+ groups.get(variant.model).efforts.push({id:variant.id,effort:variant.effort,selected:variant.selected});
50
+ }
46
51
  const expected=listed.filter(model=>model.selected).map(model=>model.id).sort();
47
52
  const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
48
53
  return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app,route_observed:handler.snapshot().observed,
49
54
  model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
50
- models:listed,activity,last_operation:lastOperation};
55
+ models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
51
56
  }
52
57
  async function action(input={},baseUrl){
53
58
  if(input&&Object.keys(input).some(name=>!["action","accept_background_copilot","models"].includes(name)))throw httpError("Invalid Gemini operation",400);
@@ -0,0 +1,86 @@
1
+ import { loadRuntimeConfig } from "./runtime-config.mjs";
2
+
3
+ const MAX_BYTES = loadRuntimeConfig().maxSseBufferBytes;
4
+ const count = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
5
+
6
+ export function googleUsageEvent(value) {
7
+ const response = value?.response || value, usage = response?.usageMetadata;
8
+ if (!usage || typeof usage !== "object") return null;
9
+ const prompt = count(usage.promptTokenCount), output = count(usage.candidatesTokenCount);
10
+ const thoughts = count(usage.thoughtsTokenCount), tools = count(usage.toolUsePromptTokenCount);
11
+ return {
12
+ id: response.responseId, model: response.modelVersion,
13
+ usage: {
14
+ prompt_tokens: prompt === undefined ? undefined : prompt + (tools ?? 0),
15
+ completion_tokens: output === undefined ? undefined : output + (thoughts ?? 0),
16
+ total_tokens: count(usage.totalTokenCount),
17
+ prompt_tokens_details: { cached_tokens: count(usage.cachedContentTokenCount) },
18
+ completion_tokens_details: { reasoning_tokens: thoughts },
19
+ },
20
+ };
21
+ }
22
+
23
+ // Observe the same chunks the caller forwards, without buffering delivery,
24
+ // changing bytes or reading ahead. Oversized metadata is unavailable, not zero.
25
+ export function createGoogleResponseObserver({ streaming, onEvent, maxBytes = MAX_BYTES }) {
26
+ const decoder = new TextDecoder("utf-8", { fatal: true });
27
+ let parts = [], bytes = 0, data = [], frameBytes = 0, skipLF = false, skipFrame = false, unavailable = false;
28
+ const parse = text => {
29
+ if (!text || text === "[DONE]") return;
30
+ try { const value = JSON.parse(text);for (const item of Array.isArray(value) ? value : [value]) onEvent(item); }
31
+ catch { unavailable = true; }
32
+ };
33
+ const line = () => {
34
+ const text = parts.join("");parts = [];bytes = 0;
35
+ if (!text) {
36
+ if (!skipFrame) parse(data.join("\n"));
37
+ data = [];frameBytes = 0;skipFrame = false;
38
+ } else if (!skipFrame && text.startsWith("data:")) {
39
+ const value = text.slice(5).replace(/^ /, "");frameBytes += Buffer.byteLength(value);
40
+ if (frameBytes > maxBytes) { data = [];skipFrame = true;unavailable = true; }
41
+ else data.push(value);
42
+ }
43
+ };
44
+ const consume = text => {
45
+ if (!streaming) {
46
+ if (unavailable) return;
47
+ bytes += Buffer.byteLength(text);
48
+ if (bytes > maxBytes) { parts = [];unavailable = true; } else parts.push(text);
49
+ return;
50
+ }
51
+ let start = 0;
52
+ if (skipLF && text.length) { if (text[0] === "\n") start = 1;skipLF = false; }
53
+ const newline = /[\r\n]/g;newline.lastIndex = start;let match;
54
+ const append = fragment => {
55
+ if (skipFrame) return;
56
+ bytes += Buffer.byteLength(fragment);
57
+ if (bytes > maxBytes) { parts = [];data = [];skipFrame = true;unavailable = true; }
58
+ else parts.push(fragment);
59
+ };
60
+ while ((match = newline.exec(text))) {
61
+ const hadLine = bytes > 0 || parts.length > 0 || skipFrame && match.index > start;
62
+ append(text.slice(start, match.index));
63
+ if (skipFrame && (hadLine || match.index > start)) { parts = [];bytes = 0; }
64
+ else line();
65
+ start = match.index + 1;
66
+ if (match[0] === "\r") {
67
+ if (text[start] === "\n") start++;
68
+ else if (start === text.length) skipLF = true;
69
+ newline.lastIndex = start;
70
+ }
71
+ }
72
+ append(text.slice(start));
73
+ };
74
+ return {
75
+ push(chunk) { try { consume(decoder.decode(chunk, { stream: true })); } catch { unavailable = true;parts = [];data = []; } },
76
+ finish() {
77
+ try {
78
+ consume(decoder.decode());
79
+ if (streaming) { if (parts.length) line();if (!skipFrame && data.length) parse(data.join("\n")); }
80
+ else if (!unavailable) parse(parts.join(""));
81
+ } catch { unavailable = true; }
82
+ parts = [];data = [];
83
+ return { unavailable };
84
+ },
85
+ };
86
+ }
@@ -184,6 +184,11 @@ export const MANAGED_COMMANDS = [
184
184
  ...read,
185
185
  "--scope": "scope",
186
186
  "--provider": "value",
187
+ "--model": "value",
188
+ "--days": "value",
189
+ "--from": "value",
190
+ "--to": "value",
191
+ "--time-zone": "value",
187
192
  }),
188
193
  command("update check", "Check a stable release without installing", read),
189
194
  command("update apply", "Request the WebUI's verified idle service update", { "--yes": "flag" }, flags => ({ command: "update-managed", yes: !!flags.yes })),
@@ -225,8 +230,8 @@ function optionsFor(args, definition) {
225
230
  throw new Error("Limit must be an integer from 1 to 100");
226
231
  values[key] = type === "integer" ? Number(value) : value;
227
232
  }
228
- if (values.app && !Object.hasOwn(CLI_CLIENTS, values.app))
229
- throw new Error("Choose codex, claude-app or claude-code");
233
+ if (values.app && !Object.hasOwn(CLI_CLIENTS, values.app) && !(definition.path[0] === "requests" && values.app === "antigravity"))
234
+ throw new Error("Choose codex, claude-app, claude-code or antigravity for requests");
230
235
  if (values.provider && !isProviderId(values.provider)) throw new Error("Enter a valid usage source ID");
231
236
  if (values.source && !isProviderId(values.source)) throw new Error("Enter a listed source ID");
232
237
  if (values.active && values.failed) throw new Error("Choose --active or --failed");
@@ -276,11 +281,11 @@ const extras = {
276
281
  config:
277
282
  "Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
278
283
  requests:
279
- "Only retained records are available. Unknown clients are not guessed from an API route.\n--failed filters failed model outcomes and structured HTTP/model errors.\nUsage records, HTTP calls and model outcomes are distinct counters.",
284
+ "Only retained records are available. Unknown clients are not guessed from an API route.\nApp filters: codex, claude-app, claude-code, antigravity.\n--failed filters failed model outcomes and structured HTTP/model errors.\nUsage records, HTTP calls and model outcomes are distinct counters.",
280
285
  status:
281
286
  "Default interactive status is brief; --details retains the complete diagnostic view.\nThe installed package version can differ from the running service.\nA listening gateway does not prove upstream model access.",
282
287
  usage:
283
- "Default usage includes all recorded usage. --scope run reads the running service.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
288
+ "Default usage includes all recorded usage. Filter it with --provider, --model and --days 1..365|all, or --from/--to YYYY-MM-DD.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
284
289
  doctor:
285
290
  "Default checks are read-only. Explicit online/compatibility checks and owned repairs have separate options.",
286
291
  update:
@@ -3,7 +3,7 @@ import { createInterface } from "node:readline/promises";
3
3
  import { dashboardToolRequest } from "./cli-tools.mjs";
4
4
  import { readAdapterStatus } from "./cli-status.mjs";
5
5
  import { CLI_CLIENTS } from "./cli-command-spec.mjs";
6
- import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES, terminalUptime } from "./terminal-state.mjs";
6
+ import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES, terminalUptime, terminalRequestState } from "./terminal-state.mjs";
7
7
  import { formatResponsiveCliTable, cliOutputWidth, terminalCell } from "./cli-table.mjs";
8
8
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
9
9
  import { settingsPreferencesSnapshot, writeSettingsPreferences, checkedPreferenceValues } from "./settings-preferences.mjs";
@@ -115,17 +115,22 @@ export async function runManagementCommand(command, options = {}) {
115
115
  const found = rows.find(row => row.request_id === ids.request);if (!found) throw new Error("Request not retained. No full-history lookup is available.");return print(found);
116
116
  }
117
117
  rows = rows.filter(row => (!flags.active || row.active) && (!flags.failed || row.state !== "cancelled" && (row.state === "failed" || row.error))
118
- && (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === CLI_CLIENTS[flags.app]))).slice(-(flags.limit || 20));
119
- return print(rows, [["request_id", "Request"], ["application", "Client"], ["provider", "Source"], ["model", "Model"], ["route", "Route"], ["state", "State"]]);
118
+ && (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === (flags.app === "antigravity" ? "gemini_app" : CLI_CLIENTS[flags.app])))).slice(-(flags.limit || 20));
119
+ return print(flags.format === "json" ? rows : rows.map(row => ({ ...row, state_label: terminalRequestState(row) })), [["request_id", "Request"], ["application", "Client"], ["provider", "Source"], ["model", "Model"], ["route", "Route"], ["state_label", "State"]]);
120
120
  }
121
121
  if (group === "usage") {
122
122
  if (flags.scope === "run") {
123
+ if (flags.model || flags.days || flags.from || flags.to || flags.time_zone) throw new Error("Model and date filters require --scope all; current-run totals support only --provider.");
123
124
  const usage = (await readStatus()).data.runtime_usage;
124
125
  if (!usage) throw new Error("Current-run usage is unavailable.");
125
126
  return print(flags.provider ? usage.by_provider?.[flags.provider] || { records: 0 } : usage);
126
127
  }
127
128
  const { summarizeUsageLogs } = await import("./usage-store.mjs");
128
- const summary = await summarizeUsageLogs(undefined, { ...(flags.provider ? { provider: flags.provider } : {}) });
129
+ const { createUsageQuery } = await import("./usage-query.mjs");
130
+ const selection = createUsageQuery({ provider: flags.provider, model: flags.model, days: flags.days, from: flags.from, to: flags.to, timeZone: flags.time_zone });
131
+ const filtered = selection.filters.model || selection.filters.from || selection.filters.to;
132
+ const summary = await summarizeUsageLogs(undefined, { ...(flags.provider ? { provider: flags.provider } : {}), ...(filtered ? { recordFilter: selection.matches } : {}) });
133
+ summary.filters = selection.filters;
129
134
  if (flags.format === "json") return print(summary);
130
135
  const { formatUsageSummary } = await import("./usage.mjs");
131
136
  return formatUsageSummary(summary, { format: flags.format || "auto", output });
@@ -191,13 +196,28 @@ export async function runManagementCommand(command, options = {}) {
191
196
  }
192
197
  if(action==="models"&&flags.edit){
193
198
  const state=await request({path:"gemini"});
194
- const ids=flags.file?readFile().models:(await choose(state.models.map(model=>model.name),state.models.flatMap((model,index)=>model.selected!==false?[index]:[]))).map(index=>state.models[index].id);
199
+ let ids;
200
+ if(flags.file){
201
+ const listed=readFile().models;if(!Array.isArray(listed))throw new Error("Model files require a models array.");
202
+ ids=listed.flatMap(id=>state.model_groups?.find(model=>model.id===id)?.efforts.map(item=>item.id)||[id]);
203
+ }
204
+ else if(Array.isArray(state.model_groups)){
205
+ const groups=state.model_groups,selected=await choose(groups.map(model=>model.name),groups.flatMap((model,index)=>model.efforts.some(item=>item.selected)?[index]:[]));
206
+ ids=[];
207
+ for(const index of selected){
208
+ const model=groups[index],previous=model.efforts.flatMap((item,i)=>item.selected?[i]:[]);
209
+ const efforts=await choose(model.efforts.map(item=>model.name+" / "+item.effort),previous.length?previous:model.efforts.map((_,i)=>i));
210
+ ids.push(...efforts.map(i=>model.efforts[i].id));
211
+ }
212
+ }else ids=(await choose(state.models.map(model=>model.name),state.models.flatMap((model,index)=>model.selected!==false?[index]:[]))).map(index=>state.models[index].id);
195
213
  if(!Array.isArray(ids)||new Set(ids).size!==ids.length||ids.some(id=>!state.models.some(model=>model.id===id)))throw new Error("Choose listed Antigravity model IDs.");
196
214
  if(flags.preview)return print({models:ids,saved:false});
197
215
  await confirm("Save Antigravity model selection? Reopen Gemini afterward to reload it.");
198
216
  return print(await request({path:"gemini",body:{action:"models",models:ids}}));
199
217
  }
200
218
  const state = await request({ path: "gemini", ...(["status", "models"].includes(action) ? {} : { body: { action: flags.preview ? "preview" : action, ...(action === "enable" ? { accept_background_copilot: true } : {}) }, timeoutMs: 20000 }) });
219
+ if(action==="models"&&flags.format!=="json"&&state.model_groups)return print(state.model_groups.map(model=>({model:model.name,id:model.id,source:"GitHub Copilot",context:model.context_window,
220
+ efforts:model.efforts.map(item=>item.effort+(item.selected?" ✓":"")).join(" / ")})),[["model","Model"],["id","ID"],["source","Source"],["context","Context"],["efforts","Reasoning (selected ✓)"]]);
201
221
  return print(action === "models" ? state.models : state);
202
222
  }
203
223
  const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
@@ -16,16 +16,18 @@
16
16
  const visible = () => document.visibilityState === "visible" && !root.closest("[hidden]");
17
17
  const integer = value => Number.isSafeInteger(value) && value >= 0;
18
18
  const appName = id => format(`flow_app_${id}`);
19
- const sourceName = id => id === "github" ? "GitHub Copilot" : id === "m365" ? "Microsoft 365" : globalThis.ccdxConnectionNames?.[id] || format("flow_source_unknown");
20
- const modelName = id => !id || id === "other" ? format("flow_model_unknown") : id;
19
+ const awaitingMetadata = row => !row.terminal_outcome && row.upstream_attempts === 0 && ["received", "admission", "body", "history", "images", "serialization"].includes(row.phase);
20
+ const sourceName = (id, pending = false) => id === "github" ? "GitHub Copilot" : id === "m365" ? "Microsoft 365" : id === "google" ? "Google" : globalThis.ccdxConnectionNames?.[id] || format(pending ? "flow_source_pending" : "flow_source_unknown");
21
+ const modelName = (id, pending = false) => !id || id === "other" ? format(pending ? "flow_model_pending" : "flow_model_unknown") : id;
21
22
  const modelKey = row => JSON.stringify([row.provider, row.model]);
22
23
  const related = row => !selected || (selected.type === "apps" ? row.application === selected.id : modelKey(row) === selected.id);
23
24
  const responding = row => row.first_output_ms !== null && !row.terminal_outcome;
24
25
  function status(row) {
25
26
  if (row.terminal_outcome) return "flow_finishing";
26
27
  if (responding(row)) return "flow_responding";
28
+ if (row.phase === "admission") return "flow_queued";
27
29
  if (row.upstream_attempts > 1) return "flow_retrying";
28
- return row.upstream_attempts ? "flow_waiting" : "flow_preparing";
30
+ return row.upstream_attempts ? "flow_waiting" : row.phase === "received" ? "flow_preparing" : "flow_input";
29
31
  }
30
32
  function entry(tag, className) { const node = document.createElement(tag);if (className) node.className = className;return node; }
31
33
  function svg(tag, values) { const node = document.createElementNS(ns, tag);for (const [key, value] of Object.entries(values)) node.setAttribute(key, value);return node; }
@@ -41,8 +43,8 @@
41
43
  const map = new Map();
42
44
  for (const row of rows) {
43
45
  const id = type === "apps" ? row.application : modelKey(row);
44
- if (!map.has(id)) map.set(id, { id, provider: row.provider, model: row.model, rows: [] });
45
- map.get(id).rows.push(row);
46
+ if (!map.has(id)) map.set(id, { id, provider: row.provider, model: row.model, rows: [], pending: true });
47
+ map.get(id).rows.push(row);map.get(id).pending &&= awaitingMetadata(row);
46
48
  }
47
49
  const order = ["codex_app", "codex_cli", "codex", "claude_code", "claude_app", "claude", "gemini_app", "api"];
48
50
  return [...map.values()].sort((a, b) => type === "apps" ? order.indexOf(a.id) - order.indexOf(b.id) : a.id.localeCompare(b.id));
@@ -65,16 +67,15 @@
65
67
  cache.set(group.id, node);resize.observe(node);positions = null;
66
68
  }
67
69
  const [button, count, note] = node.children;
68
- const title = type === "apps" ? appName(group.id) : modelName(group.model);
70
+ const title = type === "apps" ? appName(group.id) : modelName(group.model, group.pending);
69
71
  if (button.textContent !== title) { button.textContent = title;positions = null; }
70
72
  button.setAttribute("aria-pressed", String(selected?.type === type && selected.id === group.id));
71
73
  count.hidden = fresh && omitted === 0 && group.rows.length < 2;
72
74
  if (fresh && (group.rows.length || total === 0)) label(count, omitted ? "flow_count_lower" : "flow_count", { count: group.rows.length.toLocaleString() });
73
75
  else count.textContent = "—";
74
- if (type === "models" && node.children[3].textContent !== sourceName(group.provider)) { node.children[3].textContent = sourceName(group.provider);positions = null; }
76
+ if (type === "models" && node.children[3].textContent !== sourceName(group.provider, group.pending)) { node.children[3].textContent = sourceName(group.provider, group.pending);positions = null; }
75
77
  const output = group.rows.filter(responding).length;
76
- const phase = group.rows.every(row => row.terminal_outcome) ? "flow_finishing"
77
- : group.rows.every(row => row.upstream_attempts > 1) ? "flow_retrying" : "flow_waiting";
78
+ const phases = new Set(group.rows.map(status)), phase = phases.size === 1 ? [...phases][0] : "flow_processing";
78
79
  label(note, !fresh || total && !group.rows.length ? "flow_last_observed" : !group.rows.length ? "flow_idle" : output ? group.rows.length === 1 ? "flow_responding" : "flow_group_response" : phase, { count: output });
79
80
  node.dataset.related = String(!selected || group.rows.some(related));fragments.push(node);
80
81
  }
@@ -91,7 +92,7 @@
91
92
  const id = row.request_id || JSON.stringify([row.application, row.provider, row.model, index]);wanted.add(id);
92
93
  let tr = detailRows.get(id);
93
94
  if (!tr) { tr = entry("tr");for (let i = 0; i < 6; i++) tr.append(entry("td"));detailRows.set(id, tr); }
94
- const values = [appName(row.application), sourceName(row.provider), modelName(row.model), format(fresh ? status(row) : "flow_last_observed"), `${((row.elapsed_ms + Math.max(0, Date.now() - sampledAt)) / 1000).toFixed(1)} s`, row.upstream_attempts.toLocaleString()];
95
+ const values = [appName(row.application), sourceName(row.provider, awaitingMetadata(row)), modelName(row.model, awaitingMetadata(row)), format(fresh ? status(row) : "flow_last_observed"), `${((row.elapsed_ms + Math.max(0, Date.now() - sampledAt)) / 1000).toFixed(1)} s`, row.upstream_attempts.toLocaleString()];
95
96
  if (row.previous_request) values[3] += " · " + format("flow_previous_result", { reason: row.previous_request.stop_reason || row.previous_request.outcome || "—", seconds: (row.previous_request.elapsed_ms / 1000).toFixed(1) });
96
97
  tr.title = row.session_id ? format("flow_session_previous", { session: row.session_id, reason: row.previous_request?.stop_reason || row.previous_request?.outcome || "—", seconds: row.previous_request ? (row.previous_request.elapsed_ms / 1000).toFixed(1) : "—" }) : format("flow_session_unknown");
97
98
  values.forEach((value, i) => { if (tr.children[i].textContent !== value) tr.children[i].textContent = value; });
@@ -107,7 +108,7 @@
107
108
  root.dataset.paused = "false";
108
109
  const apps = group("apps"), allModels = group("models");
109
110
  if (fresh && rows.length) { lastApps = apps;lastModels = allModels; }
110
- if (fresh && !rows.length) { for (const groups of [lastApps, lastModels]) for (const group of groups) group.rows = []; }
111
+ if (fresh && !rows.length) { lastModels = lastModels.filter(group => !(group.pending && (!group.model || group.model === "other")));for (const groups of [lastApps, lastModels]) for (const group of groups) group.rows = []; }
111
112
  const shownApps = apps.length ? apps : lastApps, models = allModels.length ? allModels : lastModels;
112
113
  if (selected && !rows.some(related)) selected = null;
113
114
  const signature = JSON.stringify([fresh, total, omitted, selected, expanded, rows.map(row => [row.request_id, row.application, row.provider, row.model, row.phase, row.upstream_attempts, row.first_output_ms !== null, row.terminal_outcome])]);