codex-copilot-dx 1.4.8 → 1.4.10

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/docs/REFERENCE.md CHANGED
@@ -85,7 +85,7 @@ Choose its exposed models on the Antigravity page or with
85
85
  `app antigravity models --edit`. Each WebUI row represents one model. Compatible Gemini chat models come from the current GitHub catalog, rather than a fixed Carbon/Argon list. The Reasoning column lists advertised levels, including Hydrogen's `xhigh` when available. The model checkbox controls visibility. Save/Discard, refresh, navigation, pausing and an off/on toggle preserve an existing saved route subset. CLI model editing and model files remain available for fine-grained effort selection. Refresh on this page or run `app antigravity models --refresh` to read the upstream catalog through the existing GitHub refresh runtime. Refresh does not change saved choices, save drafts, restart clients or invoke inference; failed reads retain the last usable list.
86
86
 
87
87
  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-hydrogen"]}` to expose all of its advertised levels, or individual `ccdx-copilot-...-<effort>` aliases to choose a subset. Existing Carbon/Argon aliases remain valid. Models without declared reasoning levels use one plain alias.
88
- Choose **Set default** on a Copilot model row, or **Use app default** to clear the preference. The row action uses `medium` if selected, otherwise the first selected level. `app antigravity models --edit` can choose an exact level; a model file can add `"default_model"` with a selected base ID or route alias, or `null` to clear. The gateway changes only the agent-default field in a compatible catalog; it leaves requests, existing conversation bindings, ordinary Gemini chat and background tasks unchanged. An unavailable saved default does not silently pick another Copilot model. The page reports when the catalog still needs to be loaded. Reopen Gemini through CCDX if needed; a fetched catalog does not prove that the app changed its current picker selection.
88
+ In the **New chat default** column, choose **Set default** on a Copilot model row, or choose **Use app default** to clear the preference on save. The row action uses `medium` if selected, otherwise the first selected level. `app antigravity models --edit` can choose an exact level; a model file can add `"default_model"` with a selected base ID or route alias, or `null` to clear. The gateway changes only the agent-default field in a compatible catalog; it leaves requests, existing conversation bindings, ordinary Gemini chat and background tasks unchanged. An unavailable saved default does not silently pick another Copilot model. The page reports when the catalog still needs to be loaded. Use **Reopen** in the Antigravity page when it indicates settings need loading. CCDX never reopens the app automatically. An observed connection or fetched catalog does not prove the app adopted the new default.
89
89
 
90
90
  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.
91
91
 
@@ -257,9 +257,9 @@ For an identified conversation, hovering a point in the input-history chart show
257
257
 
258
258
  ## Shared source concurrency
259
259
 
260
- In **Settings → Advanced: request limits**, **Shared request-body limit** sets the shared gateway reservation to 32–128 MiB (default 32 MiB). It applies at the next CCDX start. `ccdx config limits` shows the saved and running values. `CCDX_MAX_INFLIGHT_BODY_BYTES` still overrides the saved value. This control does not change per-request size limits, the decompressed-body or response-history pools, Claude's separate Messages queue, or provider concurrency. Increasing this limit does not fix a provider timeout. Antigravity control GETs without a framed body do not enter the upload queue.
260
+ In **Settings → Advanced: request limits**, **Shared request-body limit** sets the shared gateway reservation to 32–128 MiB (default 32 MiB). It applies at the next CCDX start. `ccdx config limits` shows the saved and running values. `CCDX_MAX_INFLIGHT_BODY_BYTES` still overrides the saved value. This control does not change per-request size limits, the decompressed-body or response-history pools, Claude's separate Messages queue, or provider concurrency. Increasing this limit does not fix a provider timeout. Antigravity control GETs without a framed body do not enter the upload queue. Allowlisted read-only control POSTs with a known, uncompressed body of at most 8 KiB use four independent slots and an eight-request waiting limit. Other requests still use the shared body queue. `ccdx status --json` reports the short queue under `gemini.activity.short_control_queue`.
261
261
 
262
- `ccdx status` shows the longest admitted wait in the gateway's local request-body queue. `status --json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream.
262
+ `ccdx status` shows the longest admitted wait in the gateway's local request-body queue. `status --json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The request table shows the total time. Its details keep source, input usage, and the separate phases. An open request detail in view retains its place as new records arrive. If its disclosure held keyboard focus, that focus is restored. In **Checks → Service requests**, the error category table separates generation, capability and access, request method, request path, and other errors. These classify the same errors shown in the 4xx/5xx totals. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream. For Antigravity Copilot Chat, `ccdx status --json` reports how many body bytes were passed to the socket (`attempts[].body_written_bytes`), when the local send finished (`body_sent_ms`, measured from request receipt), the outbound client correlation ID (`client_request_id`), and any observed transport error (`transport_error`). The WebUI shows total duration, sending time, response-header wait and first usable output when available. Copy details keeps the local ID, outbound ID and upstream response ID distinct. Valid upstream retry guidance is preserved on 429 and 503; neither response triggers an automatic resend. A local timeout is not a recorded connection error. None of these markers prove the source received or processed the body.
263
263
 
264
264
  All three Apps share admission for the same configured source and account. A slot spans the real upstream response body through completion, cancellation or error. Request-body memory is tracked separately; uploads of unknown length start with a minimal reservation and grow it by bytes read, before retaining the data for parsing. If there is not enough room, reading pauses until existing requests release memory. Only one such reader per pool may grow at a time; a reader waiting for more memory takes priority over new admissions. Once upload is complete, another reader can start while the earlier request retains its actual body reservation. Requests larger than the pool still run exclusively at the pool ceiling, subject to the existing per-request limits. Growth waits share the existing upload deadline and can appear in the body-read time; the entry queue is recorded separately. Recovery and internal summaries acquire fresh slots after the rejected response releases its slot.
265
265
 
@@ -855,7 +855,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
855
855
  | `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
856
856
  | `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
857
857
 
858
- Antigravity starts the body deadline after queue admission. Its generation requests release body reservations after the final upstream response opens, while keeping response-restoration state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. These limits and queue ordering remain unchanged.
858
+ Antigravity starts the body deadline after queue admission. Its generation requests release body reservations after the final upstream response opens, while keeping response-restoration state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. An HTTP success with no Copilot stream body returns `502` before CCDX opens its response stream.
859
859
 
860
860
  ## Usage logging
861
861
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.8",
3
+ "version": "1.4.10",
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",
@@ -1,7 +1,8 @@
1
+ import {createRequestAdmission} from "./request-admission.mjs";
1
2
  import {randomUUID,createHash} from "node:crypto";
2
3
  import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
3
- import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
4
- import {safeUpstreamResponseHeaders} from "./upstream-headers.mjs";
4
+ import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError,sendUpstreamError} from "./http-transport.mjs";
5
+ import {safeUpstreamResponseHeaders,upstreamRejectionHeaders} from "./upstream-headers.mjs";
5
6
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
6
7
  import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
7
8
  import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
@@ -19,6 +20,10 @@ const PREFIX="/antigravity";
19
20
  const MAX_REPLY=64*1024*1024;
20
21
  const GOOGLE_ORIGIN="https://daily-cloudcode-pa.googleapis.com";
21
22
  const controlMethods=new Set(["loadCodeAssist","fetchUserInfo","fetchAdminControls","fetchAvailableModels","retrieveUserQuotaSummary","listExperiments","buildWithGooglePlugins","writeTrajectoryAcls","cascadeNuxes"]);
23
+ const smallReadControls=new Set(["loadCodeAssist","fetchUserInfo","fetchAdminControls","fetchAvailableModels","retrieveUserQuotaSummary","listExperiments"]);
24
+ const CONTROL_BODY_BYTES=8*1024;
25
+ // Reserve a full slot so many tiny bodies cannot fan out unbounded upstream calls.
26
+ const controlSlot={headers:{"content-length":String(CONTROL_BODY_BYTES)}};
22
27
  const passthrough=body=>({body,count:0,restoreText:value=>value,restoreValue:value=>value,restoreToolValue:value=>value,release(){}});
23
28
  const nativeHeaders=req=>Object.fromEntries(["authorization","user-agent","x-goog-api-client","x-goog-user-project","accept"].filter(key=>typeof req.headers[key]==="string").map(key=>[key,req.headers[key]]));
24
29
 
@@ -40,10 +45,11 @@ function groundedSearch(result,query){
40
45
  export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,defaultModel=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
41
46
  compaction,compactionProfile=()=>"github",rememberConversationSource=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
42
47
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
48
+ const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
43
49
  let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
44
50
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
45
51
  const handler=async(req,res)=>{
46
- const abort=createRequestAbort(req,res);let release=()=>{},session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
52
+ const abort=createRequestAbort(req,res);let release=()=>{},releaseControl,session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
47
53
  const releaseInput=()=>{
48
54
  body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
49
55
  const done=release;release=()=>{};done();
@@ -76,12 +82,15 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
76
82
  const length=req.headers["content-length"];
77
83
  const bodylessControl=req.method==="GET"&&controlMethods.has(method)&&req.headers["transfer-encoding"]===undefined
78
84
  &&(length===undefined||typeof length==="string"&&/^0+$/.test(length));
85
+ const smallControl=req.method==="POST"&&smallReadControls.has(method)&&req.headers["transfer-encoding"]===undefined
86
+ &&(req.headers["content-encoding"]===undefined||req.headers["content-encoding"]==="identity")
87
+ &&typeof length==="string"&&/^\d+$/.test(length)&&Number(length)<=CONTROL_BODY_BYTES;
79
88
  phase="admission";
80
- // A framed request still needs the existing reservation. A known control
81
- // GET with no body does not occupy space in the upload queue.
82
- if(!bodylessControl)release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal,streamingBody:req.method==="POST"}));
89
+ if(smallControl)releaseControl=await measureRequestStageAsync("admission",()=>acquireControl(controlSlot,{signal:abort.signal}));
90
+ else if(!bodylessControl)release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal,streamingBody:req.method==="POST"}));
83
91
  phase="body";abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");
84
- body=req.method==="POST"?await measureRequestStageAsync("body",()=>readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody})):null;
92
+ body=req.method==="POST"?await measureRequestStageAsync("body",()=>readJsonBody(req,{signal:abort.signal,parse:parseBody,
93
+ ...(smallControl?{maxBodyBytes:CONTROL_BODY_BYTES,maxDecodedBodyBytes:CONTROL_BODY_BYTES}:{admission:release})})):null;
85
94
  phase="preparation";
86
95
  const context=currentRequestContext();if(context)context.application="gemini_app";
87
96
  const compacting=isCompactionRequest("gemini",body);
@@ -203,7 +212,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
203
212
  converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
204
213
  markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
205
214
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
206
- const callOptions={signal:abort.signal,sourceBodyManaged:true,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
215
+ const callOptions={signal:abort.signal,sourceBodyManaged:true,observeBodyWrite:true,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
207
216
  phase="upstream";
208
217
  const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
209
218
  inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
@@ -211,13 +220,23 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
211
220
  releaseInput();
212
221
  markUpstreamHeaders(upstream.status);
213
222
  applicationEvidence?.accept(req,"antigravity","inference");
214
- if(!upstream.ok){markResponseErrorOrigin("upstream_http");await cancelSourceResponse(upstream).catch(()=>{});throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
223
+ if(!upstream.ok){
224
+ const status=upstream.status,headers=upstreamRejectionHeaders(status,upstream.headers);
225
+ markResponseErrorOrigin("upstream_http");await cancelSourceResponse(upstream).catch(()=>{});
226
+ abort.signal.throwIfAborted();counts.failed++;outcome="failed";markResponseTerminal(outcome,{origin:"upstream_http"});
227
+ sendUpstreamError(res,{status,headers},JSON.stringify({error:"Copilot generation was refused (HTTP "+status+")"}));return;
228
+ }
215
229
  if(!stream){
216
230
  const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
217
231
  const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
218
232
  outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
219
233
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
220
234
  }
235
+ if (!upstream.body) {
236
+ sourceResponseFailed(upstream);
237
+ markResponseErrorOrigin("upstream_event");
238
+ throw httpError("Upstream Chat stream has no body",502);
239
+ }
221
240
  const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
222
241
  res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
223
242
  const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
@@ -246,7 +265,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
246
265
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
247
266
  else sendJsonError(res,error,error.statusCode||502);
248
267
  }finally{
249
- releaseInput();session?.release();abort.cleanup();active--;
268
+ releaseInput();releaseControl?.();session?.release();abort.cleanup();active--;
250
269
  if(usageEvent){
251
270
  const u=usageEvent.usage,record=buildResponsesUsageRecord({surface:"antigravity",mode:usageMode,model:usageModel,
252
271
  response:{id:usageEvent.id,model:usageEvent.model||usageModel,usage:u?{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,
@@ -261,6 +280,10 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
261
280
  }
262
281
  }
263
282
  };
264
- handler.snapshot=()=>({enabled:enabled(),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts});
283
+ handler.snapshot=()=>{
284
+ const queue=acquireControl.diagnostics();
285
+ return {enabled:enabled(),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts,
286
+ short_control_queue:{active:queue.activeRequests,waiting:queue.queued,queued_total:queue.queuedTotal,rejected:queue.rejected,timed_out:queue.timedOut,wait_ms_max:queue.waitMsMax}};
287
+ };
265
288
  return handler;
266
289
  }
@@ -76,7 +76,7 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
76
76
  const defaultUnavailable=config.default_model!==null&&(!desiredDefault||activity.catalog_default_supported===false);
77
77
  const current=applicationControl?.snapshot().antigravity;
78
78
  const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
79
- return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,default_model_unavailable:defaultUnavailable,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:handler.snapshot().observed,
79
+ return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,default_model_unavailable:defaultUnavailable,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:activity.observed,
80
80
  model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
81
81
  compaction_source:"Observed conversation source; existing background policy when unassigned",
82
82
  models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
@@ -32,7 +32,7 @@ export async function inspectApplicationConfiguration(id, { port = 2026, host =
32
32
  || (value.provider === "ccdx_gateway" && sameUrl(value.gateway?.base_url, `http://${host}:${port}/v1`)) ? "configured" : "preserved";
33
33
  } else {
34
34
  let settings;try { settings = await read(userSettingsPath(options)); } catch (error) { if (error.code !== "ENOENT") throw error;settings = {}; }
35
- value = { enabled: settings.gemini_antigravity_enabled === true, models: settings.gemini_antigravity_models || null, port, host };
35
+ value = { enabled: settings.gemini_antigravity_enabled === true, models: settings.gemini_antigravity_models || null, defaultModel: settings.gemini_antigravity_default_model ?? null, port, host };
36
36
  state = value.enabled ? "configured" : "native";
37
37
  }
38
38
  const reload = { ...value };delete reload.key;
@@ -0,0 +1,72 @@
1
+ const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
2
+ const schemaMaps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
3
+ const schemaLists = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
4
+ const schemaValues = new Set(["additionalProperties", "unevaluatedProperties", "additionalItems",
5
+ "unevaluatedItems", "contains", "propertyNames", "not", "if", "then", "else", "contentSchema"]);
6
+ const references = ["$ref", "$dynamicRef", "$recursiveRef"];
7
+
8
+ function mapChanged(value, map) {
9
+ const entries = Object.entries(value).map(([key, item]) => [key, map(item, key)]);
10
+ return entries.every(([key, item]) => item === value[key]) ? value : Object.fromEntries(entries);
11
+ }
12
+ const requiredList = value => value === undefined
13
+ || Array.isArray(value) && value.every(item => typeof item === "string") && new Set(value).size === value.length;
14
+
15
+ // Carbon rejects object-union schemas whose type/required sit next to anyOf
16
+ // while the properties are declared inside its branches. Distribute these two
17
+ // conjunctive assertions into every branch: T & (A | B) == (T & A) | (T & B).
18
+ // Keep nullable types, const discriminators and all branch-specific constraints.
19
+ export function normalizeCarbonToolSchema(schema, depth = 0) {
20
+ if (!object(schema) || depth > 128) return schema;
21
+ const recurse = child => normalizeCarbonToolSchema(child, depth + 1);
22
+ const result = mapChanged(schema, (value, key) => {
23
+ if (schemaMaps.has(key) && object(value)) return mapChanged(value, recurse);
24
+ if ((schemaLists.has(key) || key === "items") && Array.isArray(value)) {
25
+ const next = value.map(recurse);
26
+ return next.every((item, index) => item === value[index]) ? value : next;
27
+ }
28
+ if (schemaValues.has(key) || key === "items") return recurse(value);
29
+ if (key === "dependencies" && object(value)) {
30
+ return mapChanged(value, item => Array.isArray(item) ? item : recurse(item));
31
+ }
32
+ // Literal values under const/enum/default/examples are data, not schemas.
33
+ return value;
34
+ });
35
+ return distributeAssertions(result, depth);
36
+ }
37
+
38
+ function distributeAssertions(schema, depth) {
39
+ if (depth > 128) return schema;
40
+ let result = schema;
41
+ const { anyOf, type, required } = result;
42
+ const validType = type === undefined || typeof type === "string"
43
+ || Array.isArray(type) && type.length > 0 && type.every(item => typeof item === "string");
44
+ if (!Array.isArray(anyOf) || !anyOf.length || result.properties !== undefined
45
+ || type === undefined && required === undefined || !validType || !requiredList(required)
46
+ || references.some(key => Object.hasOwn(result, key))
47
+ || !anyOf.every(branch => object(branch) && !references.some(key => Object.hasOwn(branch, key))
48
+ && (type === undefined || branch.type === undefined || JSON.stringify(type) === JSON.stringify(branch.type))
49
+ && requiredList(branch.required))) return result;
50
+
51
+ result = { ...result, anyOf: anyOf.map(branch => distributeAssertions({ ...branch,
52
+ ...(type === undefined ? {} : { type }),
53
+ ...(required === undefined ? {} : { required: [...new Set([...(branch.required || []), ...required])] }),
54
+ }, depth + 1))};
55
+ delete result.type;
56
+ delete result.required;
57
+ return result;
58
+ }
59
+
60
+ // Operate only on outbound tool parameters, after the Carbon namespace/deferred
61
+ // tool bridge. Canonical request/history objects and non-Carbon routes stay intact.
62
+ export function normalizeCarbonToolSchemas(body) {
63
+ if (!Array.isArray(body?.tools)) return body;
64
+ const tools = body.tools.map(tool => {
65
+ if (tool?.type !== "function") return tool;
66
+ const owner = object(tool.function) ? tool.function : tool;
67
+ const parameters = normalizeCarbonToolSchema(owner.parameters);
68
+ if (parameters === owner.parameters) return tool;
69
+ return owner === tool ? { ...tool, parameters } : { ...tool, function: { ...owner, parameters } };
70
+ });
71
+ return tools.every((tool, index) => tool === body.tools[index]) ? body : { ...body, tools };
72
+ }
@@ -91,6 +91,7 @@ export function createCopilotClientRuntime({
91
91
  fetchImpl,
92
92
  retryOptions,
93
93
  bodyText,
94
+ observeBodyWrite,
94
95
  onUpstreamStart,
95
96
  ...sourceOptions
96
97
  } = {}) {
@@ -106,14 +107,15 @@ export function createCopilotClientRuntime({
106
107
  initiator: computeInitiator(messages),
107
108
  vision: computeVision(messages),
108
109
  });
109
- headers["Content-Length"] = String(Buffer.byteLength(serializedBody));
110
- return sourceTransport({ ...sourceOptions, signal, onUpstreamStart }, { send: fetchCopilotUpstream, model: upstreamReq.model, bodyText: serializedBody, stream: upstreamReq.stream === true, observe: true,
111
- args: [`${tokenSession.getApiBase()}/chat/completions`, {
110
+ const bodyBytes = Buffer.byteLength(serializedBody);
111
+ headers["Content-Length"] = String(bodyBytes);
112
+ return sourceTransport({ ...sourceOptions, signal, onUpstreamStart }, { send: fetchCopilotUpstream, model: upstreamReq.model, bodyText: serializedBody, bodyBytes, stream: upstreamReq.stream === true, observe: true,
113
+ evidence: { payload_bytes: bodyBytes }, args: [`${tokenSession.getApiBase()}/chat/completions`, {
112
114
  method: "POST",
113
115
  headers,
114
116
  body: serializedBody,
115
117
  signal,
116
- }, { fetchImpl, ...retryOptions }] });
118
+ }, { fetchImpl, ...retryOptions, observeBodyWrite }] });
117
119
  }
118
120
 
119
121
  async function fetchModels({ signal, fetchImpl, retryOptions }) {
@@ -0,0 +1,63 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { channel } from "node:diagnostics_channel";
3
+
4
+ const scope = new AsyncLocalStorage();
5
+ const requests = new WeakMap();
6
+ const create = channel("undici:request:create");
7
+ const chunks = channel("undici:request:bodyChunkSent");
8
+ const sent = channel("undici:request:bodySent");
9
+ const errors = channel("undici:request:error");
10
+ const transportCodes = new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "UND_ERR_SOCKET", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH"]);
11
+ let active = 0;
12
+
13
+ function onCreate({ request }) {
14
+ const state = scope.getStore();
15
+ if (!state?.callback || state.request) return;
16
+ state.request = request;
17
+ requests.set(request, state);
18
+ state.callback("start");
19
+ }
20
+
21
+ function onChunk({ request, chunk }) {
22
+ const state = requests.get(request);
23
+ if (!state) return;
24
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk?.byteLength;
25
+ if (Number.isSafeInteger(bytes) && bytes > 0) state.callback("chunk", bytes);
26
+ }
27
+
28
+ function onSent({ request }) {
29
+ requests.get(request)?.callback("sent");
30
+ }
31
+
32
+ function onError({ request, error }) {
33
+ const state = requests.get(request);
34
+ // An intentional abort destroys the socket. Its error is not evidence that
35
+ // the connection had already failed.
36
+ if (!state || state.signal?.aborted || error?.name === "AbortError") return;
37
+ const code = error?.cause?.code || error?.code;
38
+ if (transportCodes.has(code)) state.callback("error", code);
39
+ }
40
+
41
+ // Only subscribe while an observed POST is open. Retain the request identity
42
+ // for correlation; do not read its URL, headers or body.
43
+ export async function fetchWithBodyWriteTiming(url, init, callback, fetchImpl = fetch) {
44
+ if (active++ === 0) {
45
+ create.subscribe(onCreate);
46
+ chunks.subscribe(onChunk);
47
+ sent.subscribe(onSent);
48
+ errors.subscribe(onError);
49
+ }
50
+ const state = { callback, request: null, signal: init.signal };
51
+ try {
52
+ return await scope.run(state, fetchImpl, url, init);
53
+ } finally {
54
+ if (state.request) requests.delete(state.request);
55
+ state.request = state.callback = null;
56
+ if (--active === 0) {
57
+ create.unsubscribe(onCreate);
58
+ chunks.unsubscribe(onChunk);
59
+ sent.unsubscribe(onSent);
60
+ errors.unsubscribe(onError);
61
+ }
62
+ }
63
+ }
package/src/copilot.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { fetchWithBodyWriteTiming } from "./copilot-send-timing.mjs";
2
+ import { observeUpstreamBodyWrite } from "./stream-performance.mjs";
1
3
  import { randomUUID } from "node:crypto";
2
4
  import { status } from "./status.mjs";
3
5
  import { debugLog } from "./log.mjs";
@@ -160,6 +162,7 @@ export async function fetchCopilotUpstream(
160
162
  fetchImpl = fetch,
161
163
  retries = UPSTREAM_RETRIES,
162
164
  retryDelayMs = UPSTREAM_RETRY_DELAY_MS,
165
+ observeBodyWrite = false,
163
166
  } = {},
164
167
  ) {
165
168
  const retryCount = parseUpstreamRetries(retries);
@@ -173,7 +176,8 @@ export async function fetchCopilotUpstream(
173
176
  const attemptStart = Date.now();
174
177
  debugLog(`upstream ${method} ${target} attempt=${attempt + 1}/${retryCount + 1}`);
175
178
  try {
176
- const resp = await fetchImpl(url, init);
179
+ const onBodySent = observeBodyWrite && method === "POST" && fetchImpl === fetch && observeUpstreamBodyWrite(init.headers?.["X-Request-Id"]);
180
+ const resp = await (onBodySent ? fetchWithBodyWriteTiming(url, init, onBodySent) : fetchImpl(url, init));
177
181
  debugLog(`upstream ${method} ${target} status=${resp.status} attempt=${attempt + 1}/${retryCount + 1} attempt_ms=${Date.now() - attemptStart} total_ms=${Date.now() - totalStart}`);
178
182
  if (attempt < retryCount && isRetryableUpstreamStatus(resp.status, method)) {
179
183
  await discardBoundedResponseBody(resp);
@@ -1,9 +1,10 @@
1
1
  (() => {
2
2
  function create({ element: el, change, localize, isBusy = () => false }) {
3
- let data, pending = false, sequence = 0, confirmation = null, claudeApp = true, note = null, autoError = false;
3
+ let data, pending = false, sequence = 0, confirmation = null, claudeApp = true, note = null, autoError = false, antigravityCatalogPending = false;
4
4
  const route = () => ({ codex: "codex", claude: claudeApp ? "claude_app" : null, gemini: "antigravity" })[location.hash.slice(1)] || null;
5
5
  const label = (id, key) => localize(el(id), key);
6
- const buttonKey = state => state?.status === "running" ? state.needs_reload ? "application_reopen" : "application_focus"
6
+ const needsReload = state => state?.needs_reload || route() === "antigravity" && antigravityCatalogPending;
7
+ const buttonKey = state => state?.status === "running" ? needsReload(state) ? "application_reopen" : "application_focus"
7
8
  : state?.status === "starting" ? "application_opening" : state?.status === "stopped" ? "application_open" : "application_check";
8
9
  function render() {
9
10
  const id = route(), state = data?.applications?.[id];
@@ -15,7 +16,7 @@
15
16
  label("application-open-label", buttonKey(state));
16
17
  el("application-open").disabled = pending || isBusy() || ["starting", "unsupported", "not_installed", "multiple"].includes(state?.status);
17
18
  el("application-open").setAttribute("aria-busy", String(pending || isBusy() || state?.status === "starting"));
18
- label("application-state", note || (state?.status === "running" ? state.needs_reload ? "application_reload_pending" : state.connection === "observed" ? "application_connected" : "application_pending"
19
+ label("application-state", note || (state?.status === "running" ? needsReload(state) ? id === "antigravity" ? "gemini_settings_saved" : "application_reload_pending" : state.connection === "observed" ? "application_connected" : "application_pending"
19
20
  : state?.status === "stopped" ? "application_stopped" : state?.status === "starting" ? "application_opening" : "application_" + (state?.status || "unknown")));
20
21
  if (!pending) {
21
22
  el("codex-auto-launch").checked = data?.effective?.codex_auto_launch?.value === true;
@@ -47,7 +48,9 @@
47
48
  ...(operation === "restart" ? { confirmed: true, expected_pid: expected.pid, expected_started: expected.started } : {}) }, el("application-open"), { quiet: true });
48
49
  if (!next) { note = "application_action_failed";return; }
49
50
  data = next;const result = next.last_operation?.feature === "application" ? next.last_operation.result : null;
50
- if (["opened", "opening"].includes(result?.status)) for (const delay of [1000, 10500]) setTimeout(() => { if (route() === id && document.visibilityState === "visible") void check(true); }, delay);
51
+ if (["opened", "opening"].includes(result?.status)) for (const delay of [1000, 10500]) setTimeout(() => { if (route() === id && document.visibilityState === "visible") {
52
+ void check(true);if (id === "antigravity") void globalThis.ccdxAntigravity?.refreshStatus();
53
+ } }, delay);
51
54
  if (result && !["opened", "opening", "focused", "checked"].includes(result.status)) {
52
55
  const direct = { unknown: "application_unknown", app_check_failed: "application_unknown", not_installed: "application_not_installed", multiple: "application_multiple", multiple_apps: "application_multiple", unsupported: "application_unsupported", app_not_running: "application_stopped", app_route_conflict: "application_action_route_conflict" };
53
56
  note = direct[result.status] || (["open_failed", "focus_unavailable", "quit_refused", "quit_timeout", "app_changed", "needs_app_relaunch", "route_conflict"].includes(result.status) ? "application_action_" + result.status : "application_action_failed");
@@ -56,7 +59,7 @@
56
59
  }
57
60
  function openCurrent() {
58
61
  const id = route(), state = data?.applications?.[id];
59
- if (state?.status === "running" && state.needs_reload) { confirmation = { id, pid: state.pid, started: state.started };render(); }
62
+ if (state?.status === "running" && needsReload(state)) { confirmation = { id, pid: state.pid, started: state.started };render(); }
60
63
  else if (state?.status === "running") void act("focus");
61
64
  else if (state?.status === "stopped") void act("open");
62
65
  else void check(true);
@@ -75,6 +78,7 @@
75
78
  });
76
79
  window.addEventListener("focus", () => { if (document.visibilityState === "visible") void check(); });
77
80
  window.addEventListener("ccdx-gemini-state", event => {
81
+ antigravityCatalogPending = event.detail?.needsCatalogReload === true;
78
82
  const state = event.detail?.application;if (state) sync({ ...data, applications: { ...data?.applications, antigravity: state } });
79
83
  });
80
84
  return { sync, render, open(id) { if (route() === id && !pending && !isBusy()) openCurrent(); }, routeChanged() { confirmation = null;note = null;sequence++;render();void check(); }, refresh: () => check(true) };
@@ -241,7 +241,10 @@
241
241
  function showCapabilities() {
242
242
  const values = resolved(model, protocol.value), fresh = model.metadata?.deployment === source(editing)?.deployment_revision;
243
243
  words(status, fresh ? "cap_catalog_" + (model.metadata.state || "reported") : "cap_unknown");
244
- if (fresh && model.metadata.checked_at) status.append(" · ", new Date(model.metadata.checked_at).toLocaleString());
244
+ if (fresh && model.metadata.checked_at) {
245
+ const checkedAt = document.createElement("time");checkedAt.className = "metadata-check-time";
246
+ checkedAt.textContent = new Date(model.metadata.checked_at).toLocaleString();status.append(checkedAt);
247
+ }
245
248
  body.replaceChildren();
246
249
  for (const key of ["context_window", "max_input_tokens", "max_output_tokens", "max_tool_definitions", "supported_parameters", "reasoning_efforts", "reasoning_adaptive", "tools", "input_modalities", "web_search"]) {
247
250
  const row = node("tr"), label = node("th");words(label, ({ reasoning_efforts: "cap_reasoning", input_modalities: "cap_input_types", web_search: "cap_search" })[key] || "cap_field_" + key);
@@ -455,7 +458,7 @@
455
458
  if (editingClient === "codex" && memoryMatches(item)) { const badge = node("span", undefined, "memory-model-badge");words(badge, "memory_extract_role");name.append(badge); }
456
459
  const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);rememberDraft();bindingRows({ kind: "default", key }); });
457
460
  action.setAttribute("aria-pressed", String(bindingDefault === routeId(item) && bindingSelection.has(key)));
458
- action.dataset.binding = key;action.disabled = Boolean(item.unavailable);action.setAttribute("aria-label", item.id + " · " + format(bindingDefault === routeId(item) ? "cap_default" : "cap_set_default"));
461
+ action.dataset.binding = key;action.disabled = Boolean(item.unavailable);action.setAttribute("aria-label", format("model_action_label", { name: item.id, action: format(bindingDefault === routeId(item) ? "cap_default" : "cap_set_default") }));
459
462
  if (item.unavailable) { const warning = node("span", undefined, "hint binding-unavailable");words(warning, item.reason ? "visibility_" + item.reason : "cap_model_unavailable");name.append(warning); }
460
463
  const cell = node("td");cell.append(action);
461
464
  const details = [node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability))];
@@ -465,7 +468,7 @@
465
468
  const saved = bindingEfforts.get(key);
466
469
  if (saved && !levels.includes(saved)) { const option = node("option");option.value = saved;option.disabled = true;words(option, "cap_effort_unavailable", { effort: saved });select.append(option); }
467
470
  for (const effort of levels) { const option = node("option", effort);option.value = effort;select.append(option); }
468
- select.value = saved || "";select.dataset.effortBinding = key;select.setAttribute("aria-label", (item.display_name || item.id) + " · " + format("cap_reasoning"));
471
+ select.value = saved || "";select.dataset.effortBinding = key;select.setAttribute("aria-label", format("model_action_label", { name: item.display_name || item.id, action: format("cap_reasoning") }));
469
472
  select.disabled = busy || Boolean(item.unavailable) || !bindingSelection.has(key);
470
473
  select.addEventListener("change", () => { if (select.value) bindingEfforts.set(key, select.value);else bindingEfforts.delete(key);bindingDirty = true;rememberDraft();bindingRows({ kind: "effort", key }); });
471
474
  details[2].replaceChildren(select);effortControls++;
@@ -13,9 +13,9 @@
13
13
  const node = el(`client-version-${client}`);if (!node) continue;
14
14
  const rows = Array.isArray(value?.[client]) ? value[client] : [];
15
15
  if (!rows.length) { node.removeAttribute("data-i18n");node.textContent = "—";node.title = "";continue; }
16
- const version = rows.map(row => `${rows.length > 1 ? `${row.name} ` : ""}${row.version}${row.build && row.build !== row.version ? ` (${row.build})` : ""}${row.cli_version ? ` · CLI ${row.cli_version}` : ""}`).join(" / ");
16
+ const version = rows.map(row => `${rows.length > 1 ? `${row.name} ` : ""}${row.version}${row.build && row.build !== row.version ? ` (${row.build})` : ""}${row.cli_version ? ` (CLI ${row.cli_version})` : ""}`).join(" / ");
17
17
  label(node, rows.some(row => row.changed_at) ? "client_version_changed" : "client_version_observed", { version });
18
- node.title = rows.filter(row => row.changed_at).map(row => `${row.previous?.version || "—"} → ${row.version} · ${time(row.changed_at, { date: true })}`).join(" / ");
18
+ node.title = rows.filter(row => row.changed_at).map(row => `${row.previous?.version || "—"} → ${row.version} (${time(row.changed_at, { date: true })})`).join(" / ");
19
19
  }
20
20
  }
21
21
  globalThis.ccdxClientVersions = { render: renderClientVersions };
@@ -93,7 +93,7 @@
93
93
  let tr = detailRows.get(id);
94
94
  if (!tr) { tr = entry("tr");for (let i = 0; i < 6; i++) tr.append(entry("td"));detailRows.set(id, tr); }
95
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()];
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
+ 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) }) + ")";
97
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");
98
98
  values.forEach((value, i) => { if (tr.children[i].textContent !== value) tr.children[i].textContent = value; });
99
99
  if (body.children[index] !== tr) body.insertBefore(tr, body.children[index] || null);
@@ -1,7 +1,7 @@
1
1
  (() => {
2
2
  const el=id=>document.getElementById(id),language=globalThis.ccdxLanguage;
3
3
  let busy=false,state=null,draft=null,defaultDraft,notice=null,pendingAction=null;
4
- let sharedApplication=null,sharedPending=false;
4
+ let sharedApplication=null,sharedPending=false,savedTimer,showSaved=false;
5
5
  const words=(id,key)=>language.set(el(id),key);
6
6
  const clear=id=>{el(id).removeAttribute('data-i18n');el(id).removeAttribute('data-i18n-args');el(id).textContent='';el(id).title=''};
7
7
  const controls=['gemini-enabled','gemini-open','gemini-refresh','gemini-save','gemini-cancel','gemini-use-app-default'];
@@ -27,16 +27,21 @@
27
27
  if(!busy)el('gemini-enabled').checked=state.enabled;
28
28
  el('gemini-save').disabled=busy||sharedPending||!dirty();el('gemini-cancel').disabled=busy||sharedPending||!dirty();
29
29
  words('gemini-save',busy&&pendingAction==='models'?'api_saving':'api_save');if(busy&&pendingAction==='models')el('gemini-save').setAttribute('aria-busy','true');else el('gemini-save').removeAttribute('aria-busy');
30
- words('gemini-draft-state',dirty()?'cap_unsaved':'cap_saved');
30
+ el('gemini-draft-state').hidden=dirty()||!showSaved||state.app.status==='running'&&(state.models_reload_required===true||sharedApplication?.needs_reload===true);
31
+ if(!el('gemini-draft-state').hidden)words('gemini-draft-state','cap_saved');
31
32
  el('gemini-use-app-default').hidden=currentDefault()===null;
32
33
  el('gemini-default-note').hidden=!state.default_model_unavailable||currentDefault()!==savedDefault();
33
34
  if(!el('gemini-default-note').hidden)words('gemini-default-note','gemini_default_unavailable');
34
- words('gemini-route-state',!state.enabled?'gemini_disabled':state.source_enabled===false?'gemini_source_disabled':state.app.status==='starting'?'gemini_route_waiting':state.models_reload_required===null?'gemini_catalog_unknown':state.models_reload_required?'gemini_models_pending':state.route_observed?'gemini_route_observed':'gemini_route_waiting');
35
+ const fallback=!globalThis.ccdxApplicationControls;
36
+ const sourceDisabled=state.enabled&&state.source_enabled===false;
37
+ el('gemini-route-state').hidden=!sourceDisabled;
38
+ if(sourceDisabled)words('gemini-route-state','gemini_source_disabled');
35
39
  el('gemini-version').textContent=state.app.version||'—';
36
- words('gemini-app-state',state.app.status==='running'?'gemini_running':state.app.status==='stopped'?'gemini_stopped':state.app.status==='starting'?'gemini_starting':'gemini_unavailable');
37
- const needsReload=state.enabled&&state.source_enabled!==false&&(state.models_reload_required===true||state.models_reload_required===null);
38
- const hint=!state.enabled&&state.app.status==='running'?'gemini_pause_reopen':needsReload?(state.app.status==='running'?(state.models_reload_required===null?'gemini_maybe_reopen':'gemini_reopen'):state.app.status==='stopped'?'gemini_open_to_load':null):null;
39
- el('gemini-reopen').hidden=!hint;if(hint)words('gemini-reopen',hint);
40
+ el('gemini-app-state').hidden=!fallback;
41
+ if(fallback)words('gemini-app-state',state.app.status==='running'?'gemini_running':state.app.status==='stopped'?'gemini_stopped':state.app.status==='starting'?'gemini_starting':'gemini_unavailable');
42
+ const hint=fallback&&state.app.status==='running'&&(!state.enabled||state.models_reload_required===true);
43
+ el('gemini-reopen').hidden=!hint;if(hint)words('gemini-reopen',state.enabled?'gemini_reopen':'gemini_pause_reopen');
44
+ el('gemini-open').hidden=!fallback;
40
45
  el('gemini-open').disabled=busy||sharedPending||state.app.status!=='stopped';
41
46
  const list=el('gemini-models'),focused=list.contains(document.activeElement)?document.activeElement:null;
42
47
  const focus={value:focused?.value,kind:focused?.tagName};list.replaceChildren();
@@ -50,11 +55,11 @@
50
55
  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)}
51
56
  const efforts=document.createElement('td');efforts.dataset.label=language.format('cap_reasoning');
52
57
  efforts.textContent=model.efforts.map(item=>item.effort||'—').join(' / ');
53
- const preferred=document.createElement('td'),button=document.createElement('button');preferred.dataset.label=language.format('cap_default');
58
+ const preferred=document.createElement('td'),button=document.createElement('button');preferred.dataset.label=language.format('gemini_new_chat_default');
54
59
  const isDefault=ids.includes(currentDefault())&&chosen.has(currentDefault());
55
60
  button.type='button';button.value=model.id;button.disabled=busy||sharedPending;
56
61
  const title=isDefault?'cap_default':'cap_set_default';language.set(button,title);
57
- button.setAttribute('aria-pressed',String(isDefault));button.setAttribute('aria-label',model.name+' · '+language.format(title));
62
+ button.setAttribute('aria-pressed',String(isDefault));button.setAttribute('aria-label',language.format('model_action_label',{name:model.name,action:language.format(title)}));
58
63
  button.addEventListener('click',()=>{
59
64
  if(isDefault)return;
60
65
  const saved=ids.filter(id=>selected().includes(id)),visible=model.efforts.filter(item=>chosen.has(item.id));
@@ -76,7 +81,9 @@
76
81
  try{
77
82
  const write=action&&action!=='summary',response=await fetch('/_ccdx/ui/gemini'+(action==='summary'?'?scope=summary':''),{method:write?'POST':'GET',headers:{'X-CCDX-Dashboard':'1',...(write?{'Content-Type':'application/json'}:{})},cache:'no-store',signal:AbortSignal.timeout(20000),...(write?{body:JSON.stringify({action,...(action==='enable'?{accept_background_copilot:true}:{}),...extra})}:{})});
78
83
  const value=await response.json();if(!response.ok)throw Error(value.error||'Antigravity setup failed');
79
- state=value;if(action==='models'){draft=null;defaultDraft=undefined;}
84
+ state=value;if(action==='models'){
85
+ draft=null;defaultDraft=undefined;showSaved=true;clearTimeout(savedTimer);savedTimer=setTimeout(()=>{showSaved=false;render()},2200);
86
+ }
80
87
  globalThis.ccdxGeminiStatus=state;
81
88
  if(action&&action!=='summary'){
82
89
  const status=state.last_operation?.status;notice=action==='models'?null:status==='needs_app_relaunch'?'gemini_reopen':status==='opened'?'gemini_opened':status==='route_conflict'?'gemini_conflict':null;
@@ -84,9 +91,9 @@
84
91
  }
85
92
  return state;
86
93
  }catch(error){if(!report)throw error;notice='gemini_operation_failed';words('gemini-note',notice);el('gemini-note').title=error.message}
87
- finally{busy=false;pendingAction=null;render();window.dispatchEvent(new CustomEvent('ccdx-gemini-state',{detail:{application:state?.application}}))}
94
+ finally{busy=false;pendingAction=null;render();window.dispatchEvent(new CustomEvent('ccdx-gemini-state',{detail:{application:state?.application,needsCatalogReload:state?.enabled===true&&state.source_enabled!==false&&state.models_reload_required===true&&state.default_model_unavailable!==true}}))}
88
95
  }
89
- globalThis.ccdxAntigravity={get state(){return state},get pending(){return busy},setEnabled:enabled=>load(enabled?'enable':'disable',{},false)};
96
+ globalThis.ccdxAntigravity={get state(){return state},get pending(){return busy},refreshStatus:()=>load('summary'),setEnabled:enabled=>load(enabled?'enable':'disable',{},false)};
90
97
  el('gemini-enabled').addEventListener('change',event=>void load(event.target.checked?'enable':'disable'));
91
98
  el('gemini-model-form').addEventListener('submit',event=>{event.preventDefault();if(dirty())void load('models',{models:draft||selected(),...(defaultDraft!==undefined?{default_model:defaultDraft}:{})})});
92
99
  el('gemini-cancel').addEventListener('click',()=>{draft=null;defaultDraft=undefined;notice=null;clear('gemini-note');render()});