codex-copilot-dx 0.9.27 → 0.9.29

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.
@@ -15,30 +15,19 @@ const text = (id, key, values) => { localize(element(id), key, values); };
15
15
  const finite = (value) => value !== null && value !== undefined && Number.isFinite(Number(value));
16
16
  const number = (value) => finite(value) ? Math.max(0, Math.round(Number(value))).toLocaleString() : "—";
17
17
  const mib = (value) => finite(value) ? `${(Number(value) / 1048576).toFixed(1)} MiB` : "—";
18
- let authLoading = false;
19
18
  let contextRequests = [];
20
19
  let contextCompactions = {};
20
+ let failureSignature;
21
+ let contextSignature;
21
22
 
22
- function renderAuth(data) {
23
+ function renderAuth(data, { failed = false } = {}) {
23
24
  const account = data.login ? `@${data.login}` : data.id ? `ID ${data.id}` : phrase("account unknown");
24
25
  const label = data.reason === "credential_read_failed" ? "UNAVAILABLE"
25
26
  : !data.configured ? "NOT CONFIGURED" : !data.valid ? "INVALID" : "SAVED";
26
- text("auth-account", label === "SAVED" ? "GitHub / {account} / SAVED" : `GitHub / ${label}`, { account });
27
+ text("auth-account", failed ? "GitHub / {account} / UPDATE FAILED" : label === "SAVED" ? "GitHub / {account} / SAVED" : `GitHub / ${label}`, { account });
27
28
  }
28
29
 
29
- async function loadAuth() {
30
- if (authLoading) return;
31
- authLoading = true;
32
- text("auth-account", "GitHub / READING");
33
- try {
34
- const response = await fetch("/_ccdx/ui/auth", { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(5000) });
35
- const data = await response.json();
36
- if (!response.ok || data.source !== "local_auth_status") throw new Error("Auth status unavailable");
37
- renderAuth(data);
38
- } catch {
39
- text("auth-account", "GitHub / UNAVAILABLE");
40
- } finally { authLoading = false; }
41
- }
30
+ const loadAuth = () => dashboardRefresh.refresh("auth", { force: true });
42
31
 
43
32
  function duration(value) {
44
33
  if (!finite(value)) return "—";
@@ -50,6 +39,9 @@ function duration(value) {
50
39
  }
51
40
 
52
41
  function renderFailures(recent, recentRequests = []) {
42
+ const signature = JSON.stringify([recent, recentRequests]);
43
+ if (signature === failureSignature) return;
44
+ failureSignature = signature;
53
45
  const list = element("failures");
54
46
  const expanded = new Set([...list.querySelectorAll("details[open]")].map((item) => item.dataset.key));
55
47
  list.replaceChildren();
@@ -192,6 +184,9 @@ function renderContext(performance) {
192
184
  completed: number(contextCompactions.completed), incomplete: number(contextCompactions.incomplete), failed: number(contextCompactions.failed),
193
185
  });
194
186
  if (element("request-context")?.open === false) return;
187
+ const signature = JSON.stringify(contextRequests);
188
+ if (signature === contextSignature) return;
189
+ contextSignature = signature;
195
190
  body.replaceChildren();
196
191
  for (const request of contextRequests) {
197
192
  const context = request.context || {};
@@ -207,36 +202,9 @@ function renderContext(performance) {
207
202
  if (!contextRequests.length) emptyTable("context-body", 7, "No observed request metadata.");
208
203
  }
209
204
 
210
- async function refresh() {
211
- const button = element("refresh");
212
- button.disabled = true;
213
- text("connection", "READING");
214
- element("connection").className = "badge neutral";
215
- try {
216
- const response = await fetch("/_ccdx/status", {
217
- cache: "no-store",
218
- headers: { Accept: "application/json" },
219
- signal: AbortSignal.timeout(5000),
220
- });
221
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
222
- const data = await response.json();
223
- if (data?.ok !== true || data?.name !== "codex-copilot-dx") throw new Error("Unexpected status response");
224
- render(data);
225
- text("connection", "LOCAL OK");
226
- element("connection").className = "badge good";
227
- } catch {
228
- text("connection", "UNAVAILABLE");
229
- element("connection").className = "badge bad";
230
- text("updated", "Status unavailable / check ccdx, then refresh");
231
- } finally {
232
- button.disabled = false;
233
- }
234
- }
205
+ const refresh = () => dashboardRefresh.refresh("status", { force: true });
235
206
 
236
- element("refresh").addEventListener("click", () => { refresh(); loadAuth(); });
237
- element("request-context").addEventListener("toggle", () => { if (element("request-context").open) renderContext(); });
238
- refresh();
239
- loadAuth();
207
+ element("refresh").addEventListener("click", () => dashboardRefresh.refreshVisible({ force: true }));
240
208
 
241
209
  const animationRows = new Map();
242
210
  let animationTimelines = [];
@@ -246,7 +214,7 @@ let previewDisabledByEnvironment = false;
246
214
  let previewVisible = false;
247
215
  let previewTimer = null;
248
216
  let previewStarted = 0;
249
- let animationLoading = false;
217
+ let animationSaving = false;
250
218
  let animationFramesLoaded = false;
251
219
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
252
220
 
@@ -361,28 +329,26 @@ function animationNote(data) {
361
329
  : "Saved choice applies on next ccdx start.";
362
330
  }
363
331
 
364
- async function loadAnimation() {
365
- const includeFrames = element("animation-settings").open;
366
- if (animationLoading || (includeFrames && animationFramesLoaded)) return;
367
- animationLoading = true;
368
- text("animation-state", "READING");
369
- try {
370
- const response = await fetch(`/_ccdx/ui/animation${includeFrames ? "" : "?frames=0"}`, { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(8000) });
371
- const data = await response.json();
372
- if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
373
- if (includeFrames) {
374
- buildAnimationOptions(data);
375
- animationFramesLoaded = true;
376
- } else { savedAnimation = data.theme; selectedAnimation = data.theme; }
377
- updateAnimationState();
378
- text("animation-note", animationNote(data));
379
- } catch (error) {
380
- text("animation-state", "UNAVAILABLE");
381
- text("animation-note", String(error.message || error).slice(0, 180));
382
- } finally {
383
- animationLoading = false;
384
- if (!includeFrames && element("animation-settings").open) loadAnimation();
332
+ function loadAnimation(options) {
333
+ if (!animationSaving) return dashboardRefresh.refresh("animation", options);
334
+ }
335
+
336
+ function applyAnimation(data, { changed } = {}) {
337
+ if (changed === false) { updateAnimationState(); return; }
338
+ if (!animationFramesLoaded && data.themes.some(theme => theme.frames)) {
339
+ buildAnimationOptions(data);
340
+ animationFramesLoaded = true;
341
+ } else {
342
+ const dirty = selectedAnimation && selectedAnimation !== savedAnimation;
343
+ savedAnimation = data.theme;
344
+ if (!dirty) selectedAnimation = data.theme;
345
+ previewDisabledByEnvironment = data.disabled_by_environment === true;
346
+ for (const [id, row] of animationRows) row.setAttribute("aria-pressed", String(id === selectedAnimation));
347
+ element("save-animation").disabled = selectedAnimation === savedAnimation;
348
+ syncAnimationPreview();
385
349
  }
350
+ updateAnimationState();
351
+ text("animation-note", animationNote(data));
386
352
  }
387
353
 
388
354
  function updateAnimationState() {
@@ -392,6 +358,8 @@ function updateAnimationState() {
392
358
  async function saveAnimation() {
393
359
  const button = element("save-animation");
394
360
  if (!selectedAnimation || selectedAnimation === savedAnimation) return;
361
+ animationSaving = true;
362
+ dashboardRefresh.invalidate("animation");
395
363
  button.disabled = true;
396
364
  text("animation-note", "Saving…");
397
365
  try {
@@ -409,7 +377,9 @@ async function saveAnimation() {
409
377
  } catch (error) {
410
378
  text("animation-note", "Not saved / {error}", { error: String(error.message || error).slice(0, 150) });
411
379
  } finally {
380
+ animationSaving = false;
412
381
  button.disabled = selectedAnimation === savedAnimation;
382
+ loadAnimation({ force: true });
413
383
  }
414
384
  }
415
385
 
@@ -436,34 +406,18 @@ function tableRow(values, { total = false, labels = [] } = {}) {
436
406
  return row;
437
407
  }
438
408
 
439
- async function loadModels() {
440
- const button = element("refresh-models");
441
- button.disabled = true;
442
- text("models-state", "CHECKING LIVE");
443
- text("models-note", "Querying GitHub Copilot…");
444
- emptyTable("live-models-body", 4, "Loading…");
445
- try {
446
- const response = await fetch("/_ccdx/ui/models/live", { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(15000) });
447
- const data = await response.json();
448
- if (!response.ok || data.source !== "live") throw new Error(data.error || `HTTP ${response.status}`);
409
+ async function loadModels() { return dashboardRefresh.refresh("models", { force: true }); }
410
+
411
+ function applyModels(data, { changed }) {
412
+ if (changed) {
449
413
  const body = element("live-models-body");
450
414
  body.replaceChildren();
451
415
  for (const model of data.models) {
452
416
  body.append(tableRow([model.id, model.vendor, model.endpoints.join(" / "), model.preview ? "preview" : "—"], { labels: [3] }));
453
417
  }
454
418
  if (!data.models.length) emptyTable("live-models-body", 4, "No selectable GPT models advertised.");
455
- text("models-state", "LIVE SNAPSHOT");
456
- text("models-note", "{selectable} selectable / {advertised} advertised / {host} / {time}", { selectable: number(data.selectable), advertised: number(data.advertised), host: data.upstream_host, time: new Date(data.checked_at).toLocaleTimeString() });
457
- } catch (error) {
458
- text("models-state", "LIVE LOOKUP FAILED");
459
- const message = String(error.message || error).slice(0, 240);
460
- const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
461
- if (httpError) text("models-note", "Live model lookup failed (HTTP {status}). Run ccdx models for details.", { status: httpError[1] });
462
- else text("models-note", message);
463
- emptyTable("live-models-body", 4, "No live catalog available.");
464
- } finally {
465
- button.disabled = false;
466
419
  }
420
+ text("models-note", "{selectable} selectable / {advertised} advertised / {host} / {time}", { selectable: number(data.selectable), advertised: number(data.advertised), host: data.upstream_host, time: new Date(data.checked_at).toLocaleTimeString() });
467
421
  }
468
422
 
469
423
  function usageValues(row) {
@@ -473,7 +427,7 @@ function usageValues(row) {
473
427
  }
474
428
 
475
429
  let usageData = null;
476
- let usageLoading = false;
430
+ let analyticsSignature;
477
431
  let selectedUsageDate = "";
478
432
 
479
433
  function renderUsageTable() {
@@ -495,6 +449,10 @@ function renderUsageTable() {
495
449
  });
496
450
  }
497
451
 
452
+ function renderUsageState() {
453
+ text("usage-state", selectedUsageDate && usageData.analytics?.days.some(day => day.date === selectedUsageDate) ? selectedUsageDate : "LOCAL LOG");
454
+ }
455
+
498
456
  function analyticsPoint(day, model) {
499
457
  return model ? day.models.find((row) => row.model === model) || { requests: 0, input_tokens: 0, output_tokens: 0 } : day;
500
458
  }
@@ -523,6 +481,9 @@ function renderAnalytics() {
523
481
  const analytics = usageData?.analytics;
524
482
  if (!analytics) return;
525
483
  const model = element("analytics-model").value;
484
+ const signature = JSON.stringify([analytics, model, element("analytics-range").value, element("analytics-metric").value, selectedUsageDate]);
485
+ if (signature === analyticsSignature) return;
486
+ analyticsSignature = signature;
526
487
  const days = analytics.days;
527
488
  const daily = days.slice(-Number(element("analytics-range").value));
528
489
  const maximum = Math.max(1, ...daily.map((day) => {
@@ -593,44 +554,167 @@ function updateAnalyticsModels() {
593
554
  const select = element("analytics-model");
594
555
  const previous = select.value;
595
556
  select.replaceChildren();
596
- for (const model of ["", ...usageData.analytics.models]) {
557
+ for (const model of [...new Set(["", ...usageData.analytics.models, ...(previous ? [previous] : [])])]) {
597
558
  const option = document.createElement("option");
598
559
  option.value = model;
599
560
  if (model) option.textContent = model;
600
561
  else localize(option, "All models");
601
562
  select.append(option);
602
563
  }
603
- select.value = usageData.analytics.models.includes(previous) ? previous : "";
564
+ select.value = previous;
604
565
  }
605
566
 
606
- async function loadUsage() {
607
- if (usageLoading) return;
608
- usageLoading = true;
609
- const includeAnalytics = element("usage-analytics").open || Boolean(selectedUsageDate);
610
- const button = element("refresh-usage");
611
- button.disabled = true;
612
- text("usage-state", "READING LOG");
613
- text("usage-note", "Aggregating local usage metadata…");
614
- emptyTable("usage-body", 7, "Loading…");
615
- try {
616
- const query = includeAnalytics ? `?analytics=1&time_zone=${encodeURIComponent(Intl.DateTimeFormat().resolvedOptions().timeZone)}` : "";
617
- const response = await fetch(`/_ccdx/ui/usage${query}`, { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(15000) });
618
- const data = await response.json();
619
- if (!response.ok || data.source !== "local_usage_log") throw new Error(data.error || `HTTP ${response.status}`);
620
- usageData = data;
567
+ async function loadUsage() { return dashboardRefresh.refresh("usage", { force: true }); }
568
+
569
+ function applyUsage(data, { changed }) {
570
+ usageData = { ...data, ...(!data.analytics && usageData?.analytics ? { analytics: usageData.analytics } : {}) };
571
+ if (changed) {
621
572
  if (data.analytics) updateAnalyticsModels();
622
573
  renderUsageTable();
623
- renderAnalytics();
624
- } catch (error) {
625
- text("usage-state", "LOG UNAVAILABLE");
626
- text("usage-note", String(error.message || error).slice(0, 180));
627
- emptyTable("usage-body", 7, "No usage summary available.");
628
- if (includeAnalytics) text("analytics-note", "Analytics unavailable / refresh Usage to retry.");
629
- } finally {
630
- usageLoading = false;
631
- button.disabled = false;
632
- if (!includeAnalytics && element("usage-analytics").open) loadUsage();
574
+ if (data.analytics) renderAnalytics();
633
575
  }
576
+ if (data.analytics) {
577
+ text("analytics-updated", "Updated {time}", { time: new Date().toLocaleTimeString() });
578
+ }
579
+ }
580
+
581
+ async function readDashboard(url, { signal, timeout = 15000, source } = {}) {
582
+ const response = await fetch(url, { cache: "no-store", headers: { "X-CCDX-Dashboard": "1", Accept: "application/json" },
583
+ signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]) });
584
+ const data = await response.json();
585
+ if (!response.ok || (source && data.source !== source)) throw new Error(data.error || `HTTP ${response.status}`);
586
+ return data;
587
+ }
588
+
589
+ function refreshTime(target, state) {
590
+ const time = state.updatedAt === null ? null : new Date(state.updatedAt).toLocaleTimeString();
591
+ if (state.error) localize(target, time ? "Update failed / last {time}" : "Update failed", { time });
592
+ else if (time) localize(target, "Updated {time}", { time });
593
+ }
594
+
595
+ const timestamps = new Map();
596
+ for (const [key, ids] of [["status", ["client-features", "request-context", "recent-failures"]], ["models", ["upstream-models"]], ["usage", ["model-usage"]], ["animation", ["animation-settings"]]]) {
597
+ timestamps.set(key, ids.map(id => {
598
+ const node = document.createElement("p");
599
+ node.className = "refresh-time";
600
+ element(id).append(node);
601
+ return node;
602
+ }));
603
+ }
604
+
605
+ const dashboardRefresh = globalThis.ccdxRefresh.createController({
606
+ visible: () => document.visibilityState === "visible",
607
+ resources: {
608
+ status: {
609
+ visible: () => true,
610
+ load: async ({ signal }) => {
611
+ const data = await readDashboard("/_ccdx/status", { signal, timeout: 5000 });
612
+ if (data.ok !== true || data.name !== "codex-copilot-dx") throw new Error("Unexpected status response");
613
+ return data;
614
+ },
615
+ apply: render,
616
+ state: state => {
617
+ element("refresh").disabled = Boolean(state.pending);
618
+ text("connection", state.pending || (!state.value && !state.error) ? "READING" : state.error ? "UNAVAILABLE" : "LOCAL OK");
619
+ element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
620
+ if (state.error) refreshTime(element("updated"), state);
621
+ for (const node of timestamps.get("status")) refreshTime(node, state);
622
+ },
623
+ },
624
+ auth: {
625
+ visible: () => true,
626
+ load: ({ signal }) => readDashboard("/_ccdx/ui/auth", { signal, timeout: 5000, source: "local_auth_status" }),
627
+ apply: renderAuth,
628
+ state: state => {
629
+ if (state.value) renderAuth(state.value, { failed: Boolean(state.error) });
630
+ else text("auth-account", state.error ? "GitHub / UNAVAILABLE" : "GitHub / READING");
631
+ if (state.updatedAt !== null) localize(element("auth-account"), "Saved account / updated {time}", { time: new Date(state.updatedAt).toLocaleTimeString() }, "title");
632
+ },
633
+ },
634
+ models: {
635
+ visible: () => element("upstream-models").open,
636
+ load: async ({ signal }) => {
637
+ const data = await readDashboard("/_ccdx/ui/models/live", { signal, source: "live" });
638
+ if (!Array.isArray(data.models) || data.models.some(model => !model || typeof model.id !== "string" || !Array.isArray(model.endpoints))) throw new Error("Invalid model snapshot");
639
+ return data;
640
+ },
641
+ project: data => [data.models, data.selectable, data.advertised, data.upstream_host],
642
+ apply: applyModels,
643
+ state: state => {
644
+ element("refresh-models").disabled = Boolean(state.pending);
645
+ text("models-state", state.pending ? "CHECKING LIVE" : state.error ? "LIVE LOOKUP FAILED" : "LIVE SNAPSHOT");
646
+ if (state.error) {
647
+ const message = String(state.error.message || state.error).slice(0, 240);
648
+ const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
649
+ if (httpError) text("models-note", "Live model lookup failed (HTTP {status}). Run ccdx models for details.", { status: httpError[1] });
650
+ else text("models-note", message);
651
+ }
652
+ if (state.error && !state.value) emptyTable("live-models-body", 4, "No live catalog available.");
653
+ for (const node of timestamps.get("models")) refreshTime(node, state);
654
+ },
655
+ },
656
+ usage: {
657
+ visible: () => element("model-usage").open,
658
+ variant: () => ((element("model-usage").open && element("usage-analytics").open) || Boolean(selectedUsageDate)) ? "analytics" : "summary",
659
+ load: async ({ variant, signal }) => {
660
+ const data = await readDashboard(`/_ccdx/ui/usage${variant === "analytics" ? `?analytics=1&time_zone=${encodeURIComponent(Intl.DateTimeFormat().resolvedOptions().timeZone)}` : ""}`, { signal, source: "local_usage_log" });
661
+ if (!data.total || !Array.isArray(data.rows) || (variant === "analytics" && (!Array.isArray(data.analytics?.days) || !data.analytics.days.length))) throw new Error("Invalid usage snapshot");
662
+ return data;
663
+ },
664
+ apply: applyUsage,
665
+ state: state => {
666
+ element("refresh-usage").disabled = Boolean(state.pending);
667
+ if (state.pending) text("usage-state", "READING LOG");
668
+ else if (state.error) {
669
+ text("usage-state", "LOG UNAVAILABLE");
670
+ if (element("usage-analytics").open) text("analytics-note", "Analytics unavailable / refresh Usage to retry.");
671
+ if (!state.value) emptyTable("usage-body", 7, "No usage summary available.");
672
+ } else if (state.value) renderUsageState();
673
+ for (const node of timestamps.get("usage")) refreshTime(node, state);
674
+ },
675
+ },
676
+ animation: {
677
+ visible: () => element("animation-settings").open && !animationSaving,
678
+ variant: () => element("animation-settings").open && !animationFramesLoaded ? "frames" : "metadata",
679
+ project: data => [data.theme, data.source, data.disabled_by_environment, data.themes.map(theme => [theme.id, theme.label, theme.default, Boolean(theme.frames)])],
680
+ load: ({ variant, signal }) => readDashboard(`/_ccdx/ui/animation${variant === "frames" ? "" : "?frames=0"}`, { signal, timeout: 8000 }),
681
+ apply: applyAnimation,
682
+ state: state => {
683
+ if (state.error) {
684
+ text("animation-state", "UNAVAILABLE");
685
+ text("animation-note", String(state.error.message || state.error).slice(0, 180));
686
+ }
687
+ for (const node of timestamps.get("animation")) refreshTime(node, state);
688
+ },
689
+ },
690
+ },
691
+ });
692
+
693
+ const autoRefreshKey = "ccdx.dashboard.autoRefresh";
694
+ const updateAutoRefresh = () => {
695
+ element("auto-refresh").setAttribute("aria-pressed", String(dashboardRefresh.automatic));
696
+ text("auto-refresh", dashboardRefresh.automatic ? "Auto refresh / ON" : "Auto refresh / OFF");
697
+ };
698
+ let automatic = true;
699
+ try { automatic = localStorage.getItem(autoRefreshKey) !== "off"; } catch { /* Keep the default when browser storage is unavailable. */ }
700
+ dashboardRefresh.setAutomatic(automatic);
701
+ updateAutoRefresh();
702
+ element("auto-refresh").addEventListener("click", () => {
703
+ dashboardRefresh.setAutomatic(!dashboardRefresh.automatic);
704
+ updateAutoRefresh();
705
+ try { localStorage.setItem(autoRefreshKey, dashboardRefresh.automatic ? "on" : "off"); } catch { /* Keep the current choice. */ }
706
+ });
707
+ document.addEventListener("visibilitychange", () => dashboardRefresh.visibilityChanged());
708
+ window.addEventListener("pagehide", () => { dashboardRefresh.suspend(); stopAnimationPreview(); });
709
+ window.addEventListener("pageshow", () => { dashboardRefresh.resume(); syncAnimationPreview(); });
710
+
711
+ for (const [id, key] of [["client-features", "status"], ["request-context", "status"], ["recent-failures", "status"], ["upstream-models", "models"], ["model-usage", "usage"]]) {
712
+ element(id).addEventListener("toggle", () => {
713
+ if (element(id).open) {
714
+ if (id === "request-context") renderContext();
715
+ dashboardRefresh.refresh(key);
716
+ }
717
+ });
634
718
  }
635
719
 
636
720
  element("save-animation").addEventListener("click", saveAnimation);
@@ -646,7 +730,7 @@ element("open-animation").addEventListener("click", () => {
646
730
  settings.querySelector("summary").focus();
647
731
  });
648
732
  element("usage-analytics").addEventListener("toggle", () => {
649
- if (element("usage-analytics").open && !usageData?.analytics) loadUsage();
733
+ if (element("usage-analytics").open && element("model-usage").open) dashboardRefresh.refresh("usage");
650
734
  });
651
735
  for (const id of ["analytics-model", "analytics-range", "analytics-metric"]) element(id).addEventListener("change", () => {
652
736
  renderAnalytics();
@@ -658,3 +742,5 @@ element("refresh-usage").addEventListener("click", loadUsage);
658
742
  loadAnimation();
659
743
  loadModels();
660
744
  loadUsage();
745
+ refresh();
746
+ loadAuth();
package/src/dashboard.mjs CHANGED
@@ -7,6 +7,7 @@ const ASSETS = new Map([
7
7
  ["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],
8
8
  ["/language.js", ["./dashboard/language.js", "text/javascript; charset=utf-8"]],
9
9
  ["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
10
+ ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
10
11
  ]);
11
12
 
12
13
  export async function serveDashboard(req, res, pathname) {
@@ -19,146 +19,15 @@ const zstdDecompressAsync = zlib.zstdDecompress ? promisify(zlib.zstdDecompress)
19
19
 
20
20
  const HTTP_RUNTIME_CONFIG = loadRuntimeConfig();
21
21
  const MAX_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxBodyBytes;
22
- const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
22
+ export const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
23
23
 
24
- export const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
25
- export const MAX_UPSTREAM_MODEL_CATALOG_BYTES = 8 * 1024 * 1024;
26
- export const MAX_UPSTREAM_RETRY_DRAIN_BYTES = 64 * 1024;
24
+ export {
25
+ MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_RETRY_DRAIN_BYTES,
26
+ readBoundedResponseBuffer, readBoundedResponseText, discardBoundedResponseBody,
27
+ } from "./upstream-body.mjs";
27
28
  export const MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxUpstreamChatResponseBytes;
28
29
  export const MAX_UPSTREAM_RESPONSES_SUCCESS_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxUpstreamResponsesResponseBytes;
29
30
 
30
- function upstreamBodyTooLarge(label, maxBytes) {
31
- const error = httpError(`${label} exceeds ${maxBytes} bytes`, 502);
32
- error.code = "ccdx_upstream_response_too_large";
33
- error.jsonBody = {
34
- error: {
35
- message: error.message,
36
- type: "upstream_error",
37
- code: error.code,
38
- },
39
- };
40
- return error;
41
- }
42
-
43
- function unreadableUpstreamBody(label) {
44
- const error = httpError(`${label} is not a readable web stream`, 502);
45
- error.code = "ccdx_upstream_response_unreadable";
46
- error.jsonBody = {
47
- error: {
48
- message: error.message,
49
- type: "upstream_error",
50
- code: error.code,
51
- },
52
- };
53
- return error;
54
- }
55
-
56
- async function cancelResponseBody(response) {
57
- try { await response?.body?.cancel?.(); } catch {}
58
- }
59
-
60
- function responseAbortError(signal) {
61
- if (signal?.reason instanceof Error) return signal.reason;
62
- const error = new Error("The operation was aborted");
63
- error.name = "AbortError";
64
- return error;
65
- }
66
-
67
- function readResponseChunk(reader, signal) {
68
- if (!signal) return reader.read();
69
- if (signal.aborted) return Promise.reject(responseAbortError(signal));
70
- return new Promise((resolve, reject) => {
71
- let settled = false;
72
- const finish = (callback, value) => {
73
- if (settled) return;
74
- settled = true;
75
- signal.removeEventListener("abort", onAbort);
76
- callback(value);
77
- };
78
- const onAbort = () => {
79
- const error = responseAbortError(signal);
80
- try { Promise.resolve(reader.cancel(error)).catch(() => {}); } catch {}
81
- finish(reject, error);
82
- };
83
- signal.addEventListener("abort", onAbort, { once: true });
84
- reader.read().then(
85
- (value) => finish(resolve, value),
86
- (error) => finish(reject, error),
87
- );
88
- });
89
- }
90
-
91
- function responseContentLength(response) {
92
- const raw = response?.headers?.get?.("content-length")
93
- ?? response?.headers?.["content-length"]
94
- ?? response?.headers?.["Content-Length"];
95
- const parsed = Number.parseInt(raw || "", 10);
96
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
97
- }
98
-
99
- export async function readBoundedResponseBuffer(response, {
100
- maxBytes,
101
- label = "Upstream response body",
102
- signal,
103
- } = {}) {
104
- const limit = Number.isFinite(maxBytes) && maxBytes >= 0 ? Math.floor(maxBytes) : 0;
105
- if (signal?.aborted) {
106
- cancelResponseBody(response);
107
- throw responseAbortError(signal);
108
- }
109
- if (responseContentLength(response) > limit) {
110
- await cancelResponseBody(response);
111
- throw upstreamBodyTooLarge(label, limit);
112
- }
113
- if (!response?.body) {
114
- if (typeof response?.text === "function") {
115
- const buffer = Buffer.from(await response.text());
116
- if (buffer.length > limit) throw upstreamBodyTooLarge(label, limit);
117
- return buffer;
118
- }
119
- if ((responseContentLength(response) || 0) > 0) throw unreadableUpstreamBody(label);
120
- return Buffer.alloc(0);
121
- }
122
- const reader = response?.body?.getReader?.();
123
- if (!reader) throw unreadableUpstreamBody(label);
124
- const chunks = [];
125
- let total = 0;
126
- try {
127
- while (true) {
128
- const { done, value } = await readResponseChunk(reader, signal);
129
- if (done) break;
130
- const chunk = Buffer.from(value);
131
- total += chunk.length;
132
- if (total > limit) {
133
- await reader.cancel().catch(() => {});
134
- throw upstreamBodyTooLarge(label, limit);
135
- }
136
- chunks.push(chunk);
137
- }
138
- return Buffer.concat(chunks, total);
139
- } finally {
140
- try {
141
- reader.releaseLock();
142
- } catch (error) {
143
- if (!signal?.aborted) throw error;
144
- }
145
- }
146
- }
147
-
148
- export async function readBoundedResponseText(response, options) {
149
- return new TextDecoder().decode(await readBoundedResponseBuffer(response, options));
150
- }
151
-
152
- export async function discardBoundedResponseBody(response, maxBytes = MAX_UPSTREAM_RETRY_DRAIN_BYTES) {
153
- try {
154
- await readBoundedResponseBuffer(response, { maxBytes, label: "Upstream retry response body" });
155
- return true;
156
- } catch {
157
- await cancelResponseBody(response);
158
- return false;
159
- }
160
- }
161
-
162
31
  function payloadTooLarge(kind, maxBytes) {
163
32
  return httpError(`${kind} request body exceeds ${maxBytes} bytes`, 413);
164
33
  }
@@ -2,6 +2,7 @@ import os from "node:os";
2
2
  import { validateGithubToken } from "./auth.mjs";
3
3
  import { AUTH_PROFILE_CODEX, readAuthProfileCredentials } from "./auth-profile.mjs";
4
4
  import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.mjs";
5
+ import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "./upstream-body.mjs";
5
6
 
6
7
  const DEFAULT_MODELS_TIMEOUT_MS = 10000;
7
8
  const SUPPORTED_ENDPOINTS = [
@@ -59,14 +60,6 @@ function validationFailure(validation) {
59
60
  return `GitHub Copilot authentication failed: ${validation?.reason || "unknown error"}${httpStatus}`;
60
61
  }
61
62
 
62
- async function responseText(response) {
63
- try {
64
- return await response.text();
65
- } catch {
66
- return "";
67
- }
68
- }
69
-
70
63
  function readModelCredentials(home) {
71
64
  let credentials;
72
65
  try {
@@ -110,7 +103,11 @@ export async function fetchLiveCopilotModels({
110
103
  redirect: "error",
111
104
  signal: controller.signal,
112
105
  });
113
- const body = await responseText(response);
106
+ const body = await readBoundedResponseText(response, {
107
+ maxBytes: response.ok ? MAX_UPSTREAM_MODEL_CATALOG_BYTES : MAX_UPSTREAM_ERROR_BODY_BYTES,
108
+ label: "Copilot live model catalog",
109
+ signal: controller.signal,
110
+ });
114
111
  if (!response.ok) {
115
112
  const detail = safeText(body).slice(0, 240);
116
113
  throw new Error(`Copilot models endpoint returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);