codex-copilot-dx 1.2.9 → 1.2.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.
@@ -15,8 +15,9 @@ 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
- const viewHelpers = { element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator: globalThis.navigator,
19
- motionAllowed: () => !reducedMotion.matches && document.visibilityState === "visible" && element("usage-analytics").open && element("model-usage").open && !element("model-usage").closest("[hidden]") };
18
+ const time = (value, options) => globalThis.ccdxTime?.format(value, options) ?? (value ? new Date(value).toLocaleTimeString() : "—");
19
+ const viewHelpers = { time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator: globalThis.navigator,
20
+ motionAllowed: () => !reducedMotion.matches && document.visibilityState === "visible" && element("usage-analytics").open && !element("usage-analytics").closest("[hidden]") };
20
21
  const { render, renderProviders, renderFailures, renderContext } = globalThis.ccdxDashboardStatus.create(viewHelpers);
21
22
  const usageView = globalThis.ccdxDashboardUsage.create(viewHelpers);
22
23
  const { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay } = usageView;
@@ -36,186 +37,14 @@ element("refresh").addEventListener("click", () => {
36
37
  dashboardRefresh.refreshVisible({ force: true });
37
38
  });
38
39
 
39
- const animationRows = new Map();
40
- let animationTimelines = [];
41
- let savedAnimation = "";
42
- let selectedAnimation = "";
43
- let previewDisabledByEnvironment = false;
44
- let previewVisible = false;
45
- let previewTimer = null;
46
- let previewStarted = 0;
47
- let animationSaving = false;
48
- let animationFramesLoaded = false;
49
40
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
50
-
51
- function renderAnsiFrame(target, frame) {
52
- const fragments = String(frame).split(/\u001b\[([0-9;]+)m/);
53
- const content = document.createDocumentFragment();
54
- let color = "";
55
- for (let index = 0; index < fragments.length; index += 2) {
56
- if (fragments[index]) {
57
- const span = document.createElement("span");
58
- span.className = color;
59
- span.textContent = fragments[index];
60
- content.append(span);
61
- }
62
- const code = fragments[index + 1];
63
- color = code === "97" ? "ansi-white"
64
- : /^38;5;(159|123|87|51|45|39|33)$/.test(code || "") ? `ansi-${code.slice(5)}` : "";
65
- }
66
- target.replaceChildren(content);
67
- }
68
-
69
- function renderAnimationFrames(elapsed) {
70
- for (const timeline of animationTimelines) {
71
- const position = timeline.id === selectedAnimation ? elapsed % timeline.duration : 0;
72
- const frameIndex = timeline.frames.findIndex(({ until }) => position < until);
73
- if (frameIndex === timeline.lastFrame) continue;
74
- timeline.lastFrame = frameIndex;
75
- renderAnsiFrame(timeline.target, frameIndex < 0 ? `[${" ".repeat(20)}]` : timeline.frames[frameIndex].ansi);
76
- }
77
- }
78
-
79
- function stopAnimationPreview() {
80
- if (previewTimer !== null) clearTimeout(previewTimer);
81
- previewTimer = null;
82
- }
83
-
84
- function tickAnimationPreview() {
85
- previewTimer = null;
86
- if (!animationTimelines.length || !element("animation-settings").open || element("animation-settings").closest("[hidden]") || !previewVisible || document.visibilityState !== "visible" || reducedMotion.matches || previewDisabledByEnvironment) return;
87
- renderAnimationFrames(performance.now() - previewStarted);
88
- previewTimer = setTimeout(tickAnimationPreview, 32);
89
- }
90
-
91
- function syncAnimationPreview() {
92
- stopAnimationPreview();
93
- if (!animationTimelines.length || !element("animation-settings").open || element("animation-settings").closest("[hidden]") || !previewVisible || document.visibilityState !== "visible" || reducedMotion.matches || previewDisabledByEnvironment) {
94
- for (const timeline of animationTimelines) timeline.lastFrame = -2;
95
- renderAnimationFrames(0);
96
- return;
97
- }
98
- previewStarted = performance.now();
99
- tickAnimationPreview();
100
- }
101
-
102
- new IntersectionObserver(([entry]) => {
103
- previewVisible = entry.isIntersecting;
104
- syncAnimationPreview();
105
- }).observe(element("animation-options"));
106
- document.addEventListener("visibilitychange", syncAnimationPreview);
107
- reducedMotion.addEventListener("change", syncAnimationPreview);
41
+ const animationView = globalThis.ccdxDashboardAnimation.create({ element, phrase, localize, text, reducedMotion,
42
+ getRefresh: () => dashboardRefresh, document });
43
+ const { apply: applyAnimation, load: loadAnimation, save: saveAnimation, sync: syncAnimationPreview, stop: stopAnimationPreview } = animationView;
108
44
  reducedMotion.addEventListener("change", () => { if (reducedMotion.matches) usageView.stopMotion(); });
109
45
  document.addEventListener("visibilitychange", () => { if (document.visibilityState !== "visible") usageView.stopMotion(); });
110
46
  new IntersectionObserver(([entry]) => usageView.setChartVisible(entry.isIntersecting)).observe(element("daily-bars"));
111
47
 
112
- function buildAnimationOptions(data) {
113
- const container = element("animation-options");
114
- container.replaceChildren();
115
- animationRows.clear();
116
- animationTimelines = [];
117
- savedAnimation = data.theme;
118
- selectedAnimation = data.theme;
119
- previewDisabledByEnvironment = data.disabled_by_environment === true;
120
- for (const [index, theme] of data.themes.entries()) {
121
- const option = document.createElement("button");
122
- option.type = "button";
123
- option.className = "theme-option";
124
- option.setAttribute("aria-pressed", String(theme.id === data.theme));
125
- option.addEventListener("click", () => {
126
- selectedAnimation = theme.id;
127
- for (const [id, row] of animationRows) row.setAttribute("aria-pressed", String(id === theme.id));
128
- element("save-animation").disabled = selectedAnimation === savedAnimation;
129
- updateAnimationState();
130
- syncAnimationPreview();
131
- });
132
- const name = document.createElement("span");
133
- name.className = "theme-name";
134
- const label = document.createElement("span");
135
- localize(label, "index_theme", { index: String(index + 1).padStart(2, "0"), theme: phrase(theme.label) });
136
- name.append(label);
137
- if (theme.default) {
138
- const marker = document.createElement("small");
139
- localize(marker, "default");
140
- name.append(marker);
141
- }
142
- const preview = document.createElement("span");
143
- preview.className = "theme-preview";
144
- preview.setAttribute("aria-hidden", "true");
145
- option.append(name, preview);
146
- container.append(option);
147
- animationRows.set(theme.id, option);
148
- let until = 0;
149
- const frames = theme.frames.map((frame) => {
150
- until += frame.delay_ms;
151
- return { ansi: frame.ansi, until };
152
- });
153
- animationTimelines.push({ id: theme.id, target: preview, frames, duration: until + theme.loop_pause_ms, lastFrame: -2 });
154
- }
155
- element("save-animation").disabled = true;
156
- syncAnimationPreview();
157
- }
158
-
159
- function animationNote(data) {
160
- return data.disabled_by_environment
161
- ? "disabled_by_ccdx_terminal_animation_saved_choice_applies_after_o"
162
- : "saved_choice_applies_to_the_running_terminal";
163
- }
164
-
165
- function loadAnimation(options) {
166
- if (!animationSaving) return dashboardRefresh.refresh("animation", options);
167
- }
168
-
169
- function applyAnimation(data, { changed } = {}) {
170
- if (changed === false) { updateAnimationState(); return; }
171
- if (!animationFramesLoaded && data.themes.some(theme => theme.frames)) {
172
- buildAnimationOptions(data);
173
- animationFramesLoaded = true;
174
- } else {
175
- const dirty = selectedAnimation && selectedAnimation !== savedAnimation;
176
- savedAnimation = data.theme;
177
- if (!dirty) selectedAnimation = data.theme;
178
- previewDisabledByEnvironment = data.disabled_by_environment === true;
179
- for (const [id, row] of animationRows) row.setAttribute("aria-pressed", String(id === selectedAnimation));
180
- element("save-animation").disabled = selectedAnimation === savedAnimation;
181
- syncAnimationPreview();
182
- }
183
- updateAnimationState();
184
- text("animation-note", animationNote(data));
185
- }
186
-
187
- function updateAnimationState() {
188
- text("animation-state", "current_theme_unsaved", { theme: phrase(savedAnimation.toUpperCase()), unsaved: selectedAnimation !== savedAnimation ? phrase("unsaved") : "" });
189
- }
190
-
191
- async function saveAnimation() {
192
- const button = element("save-animation");
193
- if (!selectedAnimation || selectedAnimation === savedAnimation) return;
194
- animationSaving = true;
195
- dashboardRefresh.invalidate("animation");
196
- button.disabled = true;
197
- text("animation-note", "saving");
198
- try {
199
- const response = await fetch("/_ccdx/ui/animation", {
200
- method: "POST",
201
- headers: { "Content-Type": "application/json", "X-CCDX-Dashboard": "1" },
202
- body: JSON.stringify({ theme: selectedAnimation }),
203
- signal: AbortSignal.timeout(8000),
204
- });
205
- const data = await response.json();
206
- if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
207
- savedAnimation = data.theme;
208
- updateAnimationState();
209
- text("animation-note", animationNote(data));
210
- } catch (error) {
211
- text("animation-note", "not_saved_error", { error: String(error.message || error).slice(0, 150) });
212
- } finally {
213
- animationSaving = false;
214
- button.disabled = selectedAnimation === savedAnimation;
215
- loadAnimation({ force: true });
216
- }
217
- }
218
-
219
48
  function emptyTable(bodyId, columns, message) {
220
49
  const body = element(bodyId);
221
50
  body.replaceChildren();
@@ -268,10 +97,10 @@ function chooseProvider(id) {
268
97
  dashboardRefresh.invalidate("models", { clear: true });
269
98
  const previous = modelSnapshots.get(id);
270
99
  if (previous) applyModels(previous, { changed: true });
271
- else { emptyTable("live-models-body", 6, "reading_provider_catalog");text("models-note", "reading_provider_catalog"); }
100
+ else { emptyTable("live-models-body", 3, "reading_provider_catalog");text("models-note", "reading_provider_catalog"); }
272
101
  element("live-models-body").setAttribute("aria-labelledby", `model-provider-${id}`);
273
102
  window.dispatchEvent(new CustomEvent("ccdx:source-view"));
274
- void loadModels();
103
+ if (!element("upstream-models").closest("[hidden]")) void loadModels();
275
104
  }
276
105
 
277
106
  function syncProviderDetails() {
@@ -285,18 +114,18 @@ function applyProviders(data, { changed }) {
285
114
  let reloadModels = false;
286
115
  const previous = new Map(providerEntries.map(entry => [entry.id, JSON.stringify([entry.generation, entry.auth?.account])]));
287
116
  providerEntries = data.providers;
288
- if (sourceChoicesChanged) window.dispatchEvent(new CustomEvent("ccdx:providers"));
289
117
  for (const [id] of modelSnapshots) {
290
118
  const provider = providerEntries.find(entry => entry.id === id);
291
119
  if (!provider) {
292
120
  modelSnapshots.delete(id);
293
- if (id === selectedProvider) { reloadModels = true;dashboardRefresh.invalidate("models", { clear: true });emptyTable("live-models-body", 6, "reading_provider_catalog"); }
121
+ if (id === selectedProvider) { reloadModels = true;dashboardRefresh.invalidate("models", { clear: true });emptyTable("live-models-body", 3, "reading_provider_catalog"); }
294
122
  }
295
123
  }
296
124
  for (const provider of providerEntries) {
297
125
  if (previous.has(provider.id) && previous.get(provider.id) !== JSON.stringify([provider.generation, provider.auth?.account])) {
298
126
  modelSnapshots.delete(provider.id);
299
- if (provider.id === selectedProvider) { reloadModels = true;dashboardRefresh.invalidate("models", { clear: true });emptyTable("live-models-body", 6, "reading_provider_catalog"); }
127
+ if (dashboardRefresh.state("models").attemptVariant === provider.id) dashboardRefresh.invalidate("models", { clear: true });
128
+ if (provider.id === selectedProvider) { reloadModels = true;dashboardRefresh.invalidate("models", { clear: true });emptyTable("live-models-body", 3, "reading_provider_catalog"); }
300
129
  }
301
130
  }
302
131
  if (changed || dashboardRefresh.state("auth").error) renderProviders(data);
@@ -324,25 +153,52 @@ function applyProviders(data, { changed }) {
324
153
  button.textContent = provider.name;button.setAttribute("aria-selected", String(provider.id === selectedProvider));button.tabIndex = provider.id === selectedProvider ? 0 : -1;
325
154
  }
326
155
  element("live-models-body").setAttribute("aria-labelledby", `model-provider-${selectedProvider}`);
327
- if (wasInitialized && (reloadModels || selectedProvider !== previousSelection)) { dashboardRefresh.invalidate("models", { clear: true });void loadModels(); }
156
+ if (sourceChoicesChanged) window.dispatchEvent(new CustomEvent("ccdx:providers"));
157
+ if ((!wasInitialized || reloadModels || selectedProvider !== previousSelection) && !element("upstream-models").closest("[hidden]")) { dashboardRefresh.invalidate("models", { clear: true });void loadModels(); }
328
158
  }
329
159
 
330
- async function loadModels() { return dashboardRefresh.refresh("models", { force: true }); }
160
+ function catalogProvider() {
161
+ return element("source-provider").closest('[data-view="codex"]')?.hidden === false ? element("source-provider").value : selectedProvider;
162
+ }
163
+ function refreshCatalog({ force = false } = {}) {
164
+ const entry = dashboardRefresh.state("models");
165
+ if (entry.attemptVariant && entry.attemptVariant !== catalogProvider()) dashboardRefresh.invalidate("models", { clear: true });
166
+ return dashboardRefresh.refresh("models", { force });
167
+ }
168
+ async function readModelCatalog(provider) {
169
+ const data = await refreshCatalog();
170
+ const entry = dashboardRefresh.state("models");
171
+ if (entry.attemptVariant === provider && entry.error) throw entry.error;
172
+ if (!data || data.provider !== provider) throw new Error("Model list unavailable");
173
+ return data;
174
+ }
175
+ async function loadModels() { return refreshCatalog({ force: true }); }
331
176
 
332
177
  function applyModels(data, { changed }) {
178
+ modelSnapshots.set(data.provider || selectedProvider, data);
333
179
  if (data.provider && data.provider !== selectedProvider) return;
334
- modelSnapshots.set(selectedProvider, data);
335
180
  if (changed) {
336
- const body = element("live-models-body");body.replaceChildren();
181
+ const body = element("live-models-body");
182
+ const expanded = new Set([...body.querySelectorAll("details[open]")].map(node => node.dataset.model));
183
+ body.replaceChildren();
337
184
  for (const model of data.models) {
338
185
  const clients = (model.clients || []).map(id => ({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" })[id] || id).join(" / ") || "—";
339
- body.append(tableRow([model.id, model.vendor, model.endpoints.join(" / "), clients,
340
- model.reasoning_efforts === null || model.reasoning_efforts === undefined ? "—" : model.reasoning_efforts.join(" / ") || "—",
341
- model.preview ? "preview" : model.state || "listed"], { labels: [5] }));
186
+ const row = tableRow([model.id, clients, ""]);row.children[0].className = "model-name";
187
+ const details = document.createElement("details"), summary = document.createElement("summary"), fields = document.createElement("dl");
188
+ details.dataset.model = model.id;details.open = expanded.has(model.id);fields.className = "failure-detail";
189
+ localize(summary, "model_details");details.append(summary, fields);
190
+ for (const [key, value, translated] of [["vendor", model.vendor || "—"], ["api", model.endpoints.join(" / ") || "—"],
191
+ ["reasoning", model.reasoning_efforts?.join(" / ") || "—"], ["state", model.preview ? "preview" : model.state || "listed", true],
192
+ ["model_window", number(model.context_window)]]) {
193
+ const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
194
+ if (translated) localize(detail, value);else detail.textContent = value;
195
+ fields.append(term, detail);
196
+ }
197
+ row.children[2].append(details);body.append(row);
342
198
  }
343
- if (!data.models.length) emptyTable("live-models-body", 6, "no_models_advertised");
199
+ if (!data.models.length) emptyTable("live-models-body", 3, "no_models_advertised");
344
200
  }
345
- text("models-note", "selectable_selectable_advertised_advertised_host_time", { selectable: number(data.selectable), advertised: number(data.advertised), host: data.upstream_host, time: data.checked_at ? new Date(data.checked_at).toLocaleTimeString() : phrase("unknown") });
201
+ text("models-note", "selectable_selectable_advertised_advertised_host_time", { selectable: number(data.selectable), advertised: number(data.advertised), host: data.upstream_host, time: data.checked_at ? time(data.checked_at) : phrase("unknown") });
346
202
  }
347
203
 
348
204
  async function loadUsage() { return dashboardRefresh.refresh("usage", { force: true }); }
@@ -358,9 +214,9 @@ async function readDashboard(url, { signal, timeout = 15000, source } = {}) {
358
214
  }
359
215
 
360
216
  function refreshTime(target, state) {
361
- const time = state.updatedAt === null ? null : new Date(state.updatedAt).toLocaleTimeString();
362
- if (state.error) localize(target, time ? "update_failed_last_time" : "update_failed", { time });
363
- else if (time) localize(target, "updated_time", { time });
217
+ const updated = state.updatedAt === null ? null : time(state.updatedAt);
218
+ if (state.error) localize(target, updated ? "update_failed_last_time" : "update_failed", { time: updated });
219
+ else if (updated) localize(target, "updated_time", { time: updated });
364
220
  }
365
221
 
366
222
  const timestamps = new Map();
@@ -413,15 +269,15 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
413
269
  apply: applyProviders,
414
270
  state: state => {
415
271
  if (state.error) {
416
- if (state.value) localize(element("source-status-note"), "update_failed_last_time", { time: new Date(state.updatedAt).toLocaleTimeString() });
272
+ if (state.value) localize(element("source-status-note"), "update_failed_last_time", { time: time(state.updatedAt) });
417
273
  else text("source-status-note", "unavailable_eb0be");
418
274
  } else element("source-status-note").textContent = "";
419
275
  for (const node of timestamps.get("auth")) refreshTime(node, state);
420
276
  },
421
277
  },
422
278
  models: {
423
- visible: () => providerEntries.length > 0 && element("upstream-models").open && !element("upstream-models").closest("[hidden]"),
424
- variant: () => selectedProvider,
279
+ visible: () => providerEntries.length > 0 && (element("source-provider").closest('[data-view="codex"]')?.hidden === false || element("upstream-models").open && !element("upstream-models").closest("[hidden]")),
280
+ variant: catalogProvider,
425
281
  load: async ({ signal, variant }) => {
426
282
  if (!variant) throw new Error("reading_provider_catalog");
427
283
  const data = await readDashboard(`/_ccdx/ui/models/live?provider=${encodeURIComponent(variant)}`, { signal, source: ["live", "catalog"] });
@@ -431,6 +287,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
431
287
  project: data => [data.provider, data.models, data.selectable, data.advertised, data.upstream_host],
432
288
  apply: applyModels,
433
289
  state: state => {
290
+ if (state.attemptVariant !== selectedProvider) return;
434
291
  element("refresh-models").disabled = Boolean(state.pending);
435
292
  text("models-state", state.pending ? "checking_live" : state.error ? "live_lookup_failed" : state.value?.source === "catalog" ? "catalog_snapshot" : "live_snapshot");
436
293
  element("model-check-details").hidden = !state.error;
@@ -438,8 +295,8 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
438
295
  const message = String(state.error.message || state.error).slice(0, 240);
439
296
  const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
440
297
  const sourceReason = /^Model catalog unavailable \/ (m365_[a-z0-9_]+)$/.exec(message);
441
- const diagnostic = state.error.diagnostic || {}, network = diagnostic.network;
442
- const reason = network ? phrase(`network_cause_${network.cause_code}`) : httpError ? phrase("live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] })
298
+ const diagnostic = state.error.diagnostic || {}, network = diagnostic.network, catalog = diagnostic.catalog;
299
+ const reason = catalog ? phrase(`catalog_cause_${catalog.cause_code}`) : network ? phrase(`network_cause_${network.cause_code}`) : httpError ? phrase("live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] })
443
300
  : sourceReason ? phrase("source_catalog_unavailable", { code: sourceReason[1] }) : phrase(message);
444
301
  const source = providerEntries.find(entry => entry.id === selectedProvider)?.name || selectedProvider;
445
302
  const previous = modelSnapshots.get(selectedProvider);
@@ -447,13 +304,13 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
447
304
  element("models-note").replaceChildren();
448
305
  const summary = document.createElement("span"), kept = document.createElement("span");
449
306
  localize(summary, "source_check_failed", { source });
450
- localize(kept, previous?.checked_at ? "source_check_previous" : "source_check_none", { time: previous?.checked_at ? new Date(previous.checked_at).toLocaleTimeString() : "" });
307
+ localize(kept, previous?.checked_at ? "source_check_previous" : "source_check_none", { time: previous?.checked_at ? time(previous.checked_at) : "" });
451
308
  element("models-note").append(summary, document.createElement("br"), kept);
452
309
  const fields = element("model-check-fields");fields.replaceChildren();
453
310
  for (const [key, value] of [["source", source], ["source_check_time", diagnostic.checked_at], ["source_check_reason", reason],
454
311
  ["network_route_source", network ? phrase(`network_source_${network.source}`) : null],
455
312
  ["network_failure_stage", network ? phrase(`network_stage_${network.stage}`) : null],
456
- ["network_cause_code", network?.cause_code], ["http_status", diagnostic.http_status]]) {
313
+ ["network_cause_code", network?.cause_code], ["http_status", catalog?.http_status || diagnostic.http_status], ["last_success", catalog?.last_success_at], ["upstream_request_id", catalog?.request_id]]) {
457
314
  if (value === null || value === undefined || value === "") continue;
458
315
  const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
459
316
  if (value?.key) localize(detail, value.key, value.values);else detail.textContent = String(value).slice(0, 300);
@@ -462,17 +319,17 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
462
319
  if (Number.isFinite(diagnostic.retry_after_ms) && diagnostic.retry_after_ms > 0) {
463
320
  const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, "retry");
464
321
  const checked = Date.parse(diagnostic.checked_at);
465
- if (Number.isFinite(checked)) { localize(detail, "source_retry_time", { time: new Date(checked + diagnostic.retry_after_ms).toLocaleTimeString() });fields.append(term, detail); }
322
+ if (Number.isFinite(checked)) { localize(detail, "source_retry_time", { time: time(checked + diagnostic.retry_after_ms) });fields.append(term, detail); }
466
323
  }
467
324
  }
468
- if (state.error && !modelSnapshots.has(selectedProvider)) emptyTable("live-models-body", 6, "no_catalog_available");
325
+ if (state.error && !modelSnapshots.has(selectedProvider)) emptyTable("live-models-body", 3, "no_catalog_available");
469
326
  for (const node of timestamps.get("models")) refreshTime(node, state);
470
327
  },
471
328
  },
472
329
  usage: {
473
- visible: () => element("model-usage").open && !element("model-usage").closest("[hidden]"),
330
+ visible: () => (element("model-usage").open || element("usage-analytics").open) && !element("model-usage").closest("[hidden]"),
474
331
  variant: () => {
475
- const mode = ((element("model-usage").open && element("usage-analytics").open) || Boolean(usageView.selectedDate)) ? "analytics" : "summary";
332
+ const mode = (element("usage-analytics").open || Boolean(usageView.selectedDate)) ? "analytics" : "summary";
476
333
  const provider = element("usage-provider")?.value || "";
477
334
  return mode + (provider ? `:${provider}` : "");
478
335
  },
@@ -501,8 +358,8 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
501
358
  },
502
359
  },
503
360
  animation: {
504
- visible: () => element("animation-settings").open && !element("animation-settings").closest("[hidden]") && !animationSaving,
505
- variant: () => element("animation-settings").open && !animationFramesLoaded ? "frames" : "metadata",
361
+ visible: () => element("animation-settings").open && !element("animation-settings").closest("[hidden]") && !animationView.saving,
362
+ variant: () => element("animation-settings").open && !animationView.framesLoaded ? "frames" : "metadata",
506
363
  project: data => [data.theme, data.source, data.disabled_by_environment, data.themes.map(theme => [theme.id, theme.label, theme.default, Boolean(theme.frames)])],
507
364
  load: ({ variant, signal }) => readDashboard(`/_ccdx/ui/animation${variant === "frames" ? "" : "?frames=0"}`, { signal, timeout: 8000 }),
508
365
  apply: applyAnimation,
@@ -552,7 +409,7 @@ element("animation-settings").addEventListener("toggle", () => {
552
409
  });
553
410
  element("usage-analytics").addEventListener("toggle", () => {
554
411
  if (element("usage-analytics").open) usageView.revealChart();else usageView.stopMotion();
555
- if (element("usage-analytics").open && element("model-usage").open) dashboardRefresh.refresh("usage");
412
+ if (element("usage-analytics").open) dashboardRefresh.refresh("usage");
556
413
  });
557
414
  for (const id of ["analytics-model", "analytics-range", "analytics-metric", "analytics-view"]) element(id).addEventListener("change", () => {
558
415
  renderAnalytics();
@@ -24,7 +24,7 @@ try {
24
24
  sh "$ccdx_install_dir/install.sh"
25
25
  )`;
26
26
  }
27
- function create({ element, localize, navigator }) {
27
+ function create({ time = value => new Date(value).toLocaleString(), element, localize, navigator }) {
28
28
  let snapshot = null, platform = "macos";
29
29
  const date = value => typeof value === "string" && Number.isFinite(Date.parse(value)) ? value.slice(0, 10) : null;
30
30
  function install() {
@@ -46,8 +46,8 @@ try {
46
46
  localize(element("update-latest-date"), latestDate ? "released_date" : "release_date_unknown", { date: latestDate });
47
47
  localize(element("update-state"), checked ? data.update_available ? "new_version_available" : "already_latest" : data.status === "rate_limited" ? "update_rate_limited" : "update_check_failed");
48
48
  element("update-command-row").hidden = checked && !data.update_available;
49
- const time = typeof data.checked_at === "string" && Number.isFinite(Date.parse(data.checked_at)) ? new Date(data.checked_at).toLocaleString() : "—";
50
- localize(element("update-checked"), checked ? "update_checked_time" : "update_attempted_time", { time });
49
+ const checkedTime = typeof data.checked_at === "string" && Number.isFinite(Date.parse(data.checked_at)) ? time(data.checked_at, { date: true }) : "—";
50
+ localize(element("update-checked"), checked ? "update_checked_time" : "update_attempted_time", { time: checkedTime });
51
51
  install();
52
52
  }
53
53
  function state(value) {
@@ -7,7 +7,7 @@
7
7
  }).join(" ");
8
8
  }
9
9
 
10
- function create({ element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, motionAllowed = () => false }) {
10
+ function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, motionAllowed = () => false }) {
11
11
  function usageValues(row) {
12
12
  const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
13
13
  ? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
@@ -236,7 +236,7 @@
236
236
  if (data.analytics) renderAnalytics();
237
237
  }
238
238
  if (data.analytics) {
239
- text("analytics-updated", "updated_time", { time: new Date().toLocaleTimeString() });
239
+ text("analytics-updated", "updated_time", { time: time(Date.now()) });
240
240
  }
241
241
  }
242
242
  return { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay, usageValues, setChartVisible, revealChart, stopMotion, get data() { return usageData; }, get selectedDate() { return selectedUsageDate; } };
@@ -1,5 +1,6 @@
1
1
  import os from "node:os";
2
2
  import { isProviderId } from "./provider-metadata.mjs";
3
+ import { m365CatalogDiagnostic } from "./providers/m365-catalog-diagnostic.mjs";
3
4
  import { m365NetworkDiagnostic } from "./providers/m365-network-diagnostic.mjs";
4
5
  import { fetchLiveCopilotModels } from "./live-models.mjs";
5
6
  import { authStatus } from "./auth-status.mjs";
@@ -125,6 +126,7 @@ function dashboardProviders(providerStateFn, authStatusFn) {
125
126
  selection: { codex: entry.selection?.codex === true, models_required: entry.selection?.models_required === true },
126
127
  state: code(entry.state) || "unknown", reason: code(entry.reason), generation: finite(entry.generation),
127
128
  network_diagnostic: m365NetworkDiagnostic(entry.network_diagnostic),
129
+ catalog_diagnostic: m365CatalogDiagnostic(entry.catalog_diagnostic),
128
130
  auth: { state: code(auth.state) || "unknown", account: label(auth.account), token_cached: auth.token_cached === true,
129
131
  expires_in_ms: finite(auth.expires_in_ms), checked_at: label(auth.checked_at) || null },
130
132
  models: { count: finite(entry.models?.count), source: code(entry.models?.source) || "unknown", checked_at: label(entry.models?.checked_at) || null },
@@ -310,8 +312,8 @@ export async function handleDashboardApi(req, res, pathname, {
310
312
  const message = /^m365_[a-z0-9_]+$/.test(error.code || "") ? `Model catalog unavailable / ${error.code}` : liveModelError(error);
311
313
  if (!res.destroyed && !res.writableEnded) sendJson(res, error.statusCode || 502, { error: message,
312
314
  diagnostic: { provider: provider || null, checked_at: new Date().toISOString(), message,
313
- network: m365NetworkDiagnostic(error.network_diagnostic),
314
- http_status: Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
315
+ network: m365NetworkDiagnostic(error.network_diagnostic), catalog: m365CatalogDiagnostic(error.catalog_diagnostic),
316
+ http_status: m365CatalogDiagnostic(error.catalog_diagnostic)?.http_status || Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
315
317
  retry_after_ms: finite(error.retryAfterMs) } });
316
318
  } finally { abort.cleanup(); }
317
319
  return;
package/src/dashboard.mjs CHANGED
@@ -6,9 +6,11 @@ const ASSETS = new Map([
6
6
  ["/ui.css", ["./dashboard/ui.css", "text/css; charset=utf-8"]],
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
+ ["/animation.js", ["./dashboard/animation.js", "text/javascript; charset=utf-8"]],
9
10
  ["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
10
11
  ["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
11
12
  ["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
13
+ ["/time.js", ["./dashboard/time.js", "text/javascript; charset=utf-8"]],
12
14
  ["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
13
15
  ["/activity.js", ["./dashboard/activity.js", "text/javascript; charset=utf-8"]],
14
16
  ["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
@@ -1,4 +1,4 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/activity.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
2
2
  export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks"]);
3
3
 
4
4
  export function isOptionalRoute(method, pathname) {
@@ -0,0 +1,24 @@
1
+ // Read-only presentation data; provider selection and account transactions stay in composition.
2
+ export function providerDescriptors({ state, githubRuntime, githubRegistry, githubClientConfigured,
3
+ githubGeneration, m365Generation, claudeClients, claudeReason, gatewayRunning, lastClients, definitions }) {
4
+ const ms = state.m365;
5
+ const projections = [
6
+ { id: "github", generation: githubGeneration, enabled: true, state: githubRuntime.token_cached ? "ready" : "unknown",
7
+ auth: { state: "unknown", token_cached: githubRuntime.token_cached === true, expires_in_ms: githubRuntime.token_expires_in_ms ?? null },
8
+ models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
9
+ clients: [{ id: "codex", name: "Codex App", selected: state.codex_provider === "github", state: githubClientConfigured ? "configured" : "unknown" }] },
10
+ { id: "m365", generation: m365Generation, enabled: ms.enabled, state: ms.state, reason: ms.reason,
11
+ network_diagnostic: ms.network_diagnostic, catalog_diagnostic: ms.catalog_diagnostic,
12
+ auth: { state: ms.token_cached ? "authorized" : !ms.enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
13
+ account: ms.account?.login || "", tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
14
+ token_cached: ms.token_cached === true, expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
15
+ models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
16
+ clients: [{ id: "codex", name: "Codex App", selected: state.codex_provider === "m365", state: state.codex_provider === "m365" ? ms.state : "standby" },
17
+ ...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
18
+ selected: ms.enabled, state: claudeClients[id], gateway: gatewayRunning ? "running" : "unavailable", reason: claudeReason,
19
+ last_request_at: lastClients[`claude_${id}`] || null }))],
20
+ requests: ms.claude.requests, request_scope: "Claude Messages" },
21
+ ];
22
+ return definitions.map(definition => ({ ...projections.find(source => source.id === definition.id),
23
+ id: definition.id, name: definition.name, selection: { codex: definition.codex, models_required: definition.modelSelection } }));
24
+ }
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import { providerDescriptors } from "./provider-descriptors.mjs";
2
3
  import { autoReviewPreference, writeAutoReviewModel } from "./user-settings.mjs";
3
4
  import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesModelIdsFromCopilotModels } from "./models.mjs";
4
5
  import { publicModelCatalog } from "./provider-metadata.mjs";
@@ -201,34 +202,21 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
201
202
  },
202
203
  selection: () => selection,
203
204
  dashboardProviders() {
204
- const state = snapshot(), service = githubClient.runtimeStatus?.() || {}, ms = state.m365;
205
- const projections = [
206
- { id: "github", name: "GitHub Copilot", generation: dashboardGeneration(github), enabled: true, state: service.token_cached ? "ready" : "unknown",
207
- auth: { state: "unknown", token_cached: service.token_cached === true, expires_in_ms: service.token_expires_in_ms ?? null },
208
- models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
209
- clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "github", state: githubClientConfigured ? "configured" : "unknown" }] },
210
- { id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason, network_diagnostic: ms.network_diagnostic,
211
- auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
212
- account: ms.account?.login || "", token_cached: ms.token_cached === true,
213
- tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
214
- expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
215
- models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
216
- clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
217
- ...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
218
- selected: enabled, state: clientLifecycle.snapshot().clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
219
- last_request_at: lastClients[`claude_${id}`] || null }))],
220
- requests: ms.claude.requests, request_scope: "Claude Messages" },
221
- ];
222
- return providerRegistry.list().map(definition => ({ ...projections.find(source => source.id === definition.id),
223
- id: definition.id, name: definition.name, selection: { codex: definition.codex, models_required: definition.modelSelection } }));
205
+ return providerDescriptors({ state: snapshot(), githubRuntime: githubClient.runtimeStatus?.() || {}, githubRegistry,
206
+ githubClientConfigured, githubGeneration: dashboardGeneration(github), m365Generation: m365 ? dashboardGeneration(m365) : 0,
207
+ claudeClients: clientLifecycle.snapshot().clients, claudeReason, gatewayRunning: Boolean(gateway), lastClients,
208
+ definitions: providerRegistry.list() });
224
209
  },
225
210
  async dashboardCatalog({ provider = selection.codex } = {}) {
226
211
  if (provider === "github") return null;
227
212
  if (provider !== "m365") throw Object.assign(new Error("Unknown provider"), { statusCode: 400 });
228
213
  if (!enabled || !["darwin", "win32"].includes(platform)) throw unavailable(!enabled ? "m365_disabled" : "m365_unsupported");
229
214
  if (!m365) throw unavailable(reason || "m365_not_ready");
230
- await m365.refresh();
231
- const eligible = new Set([...m365.models("gpt"), ...m365.models("claude")]);
215
+ const source = m365;
216
+ await source.refresh();
217
+ if (closed || !enabled || source !== m365 || changingAccount) throw unavailable("m365_refresh_cancelled");
218
+ reason = null;
219
+ const eligible = new Set([...source.models("gpt"), ...source.models("claude")]);
232
220
  return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: "Microsoft 365",
233
221
  advertised: m365.catalog().length, models: publicModelCatalog(m365.catalog(), {
234
222
  selectable: model => eligible.has(model),
@@ -0,0 +1,38 @@
1
+ // The server body is inspected once. Only fixed causes and bounded IDs survive.
2
+ const causes = Object.freeze({
3
+ sign_in_rejected: "Microsoft 365 rejected the sign-in. Check account access.",
4
+ entra_access_disabled: "Copilot CLI Entra access is not enabled for this account.",
5
+ access_denied: "Microsoft 365 denied access to the model list.",
6
+ rate_limited: "Microsoft 365 limited model-list checks. Try again later.",
7
+ service_unavailable: "Microsoft 365 could not serve the model list.",
8
+ catalog_rejected: "Microsoft 365 rejected the model-list request.",
9
+ });
10
+
11
+ const date = value => typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value)
12
+ && Number.isFinite(Date.parse(value)) ? value : null;
13
+
14
+ export function m365CatalogDiagnostic(value) {
15
+ if (!value || value.stage !== "catalog" || !Object.hasOwn(causes, value.cause_code)
16
+ || !Number.isInteger(value.http_status) || value.http_status < 400 || value.http_status > 599) return null;
17
+ return { stage: "catalog", cause_code: value.cause_code, http_status: value.http_status,
18
+ checked_at: date(value.checked_at), last_success_at: date(value.last_success_at),
19
+ request_id: typeof value.request_id === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(value.request_id)
20
+ && !/^(?:github_pat_|gh[pousr]_|sk-|eyJ)/.test(value.request_id) ? value.request_id : null };
21
+ }
22
+
23
+ export function m365CatalogMessage(value) {
24
+ const diagnostic = m365CatalogDiagnostic(value);
25
+ return diagnostic ? causes[diagnostic.cause_code] : null;
26
+ }
27
+
28
+ export function catalogFailure(response, body, { checkedAt, lastSuccessAt } = {}) {
29
+ let message;
30
+ try { const value = JSON.parse(body);message = value?.error?.message ?? value?.message; } catch { /* Unrecognized bodies get the HTTP category only. */ }
31
+ const code = response.status;
32
+ const cause_code = code === 401 ? "sign_in_rejected"
33
+ : code === 403 ? typeof message === "string" && /^Copilot CLI Entra access is not enabled for this user\.?$/i.test(message.trim())
34
+ ? "entra_access_disabled" : "access_denied"
35
+ : code === 429 ? "rate_limited" : code >= 500 ? "service_unavailable" : "catalog_rejected";
36
+ return m365CatalogDiagnostic({ stage: "catalog", cause_code, http_status: code, checked_at: checkedAt,
37
+ last_success_at: lastSuccessAt, request_id: response.headers.get("request-id") || response.headers.get("x-ms-request-id") });
38
+ }