codex-copilot-dx 1.0.0 → 1.1.0

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/src/adapter.mjs CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  import { httpError } from "./http-errors.mjs";
29
29
  import { createRequestAdmission } from "./request-admission.mjs";
30
30
  import { PROVIDER_MANAGEMENT_PATH, handleProviderManagement } from "./provider-management.mjs";
31
+ import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
31
32
 
32
33
  export {
33
34
  abortErrorStatusCode,
@@ -169,9 +170,10 @@ export function createAdapterHandler(options = {}) {
169
170
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
170
171
  ...(options.providerRuntime ? { providerCatalogFn: input => options.providerRuntime.dashboardCatalog(input),
171
172
  providerStateFn: () => options.providerRuntime.dashboardProviders() } : {}) } });
173
+ let statusSnapshot;
172
174
  const managementHandler = createManagementHandler({
173
175
  nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
174
- statusSnapshot: () => {
176
+ statusSnapshot: statusSnapshot = () => {
175
177
  const snapshot = runtimeStatusPayload({ metrics: requestMetrics, streamPerformance: streamPerformanceMetrics, admission: acquireRequest,
176
178
  imagePressure, responseFailures, imageGeneration: optionalRoutes.imageStats(),
177
179
  modelRegistry: codexModelRegistry, codexClient, codexModelRegistry, codexModelCatalog,
@@ -239,6 +241,16 @@ export function createAdapterHandler(options = {}) {
239
241
  return providerHandlers.get(provider);
240
242
  }
241
243
  const dispatch = async (req, res, pathname) => {
244
+ if (pathname.startsWith("/anthropic/")) {
245
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
246
+ || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
247
+ if (!options.providerRuntime?.handleClaude) { sendJsonError(res, httpError("Claude is not configured", 503));return; }
248
+ const original = req.url;
249
+ const query = new URL(req.url, "http://localhost").search;
250
+ req.url = pathname.slice("/anthropic".length) + query;
251
+ try { return await options.providerRuntime.handleClaude(req, res); }
252
+ finally { req.url = original; }
253
+ }
242
254
  if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
243
255
  && Object.hasOwn(req.headers || {}, "origin")) {
244
256
  const error = httpError("Browser origins are not allowed for inference", 403);
@@ -368,7 +380,7 @@ export function createAdapterHandler(options = {}) {
368
380
  const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
369
381
  const streamPerformance = trackRequest ? streamPerformanceMetrics.begin(routeName, { requestId }) : null;
370
382
  let finishTerminalActivity = () => {};
371
- if (trackRequest) {
383
+ if (trackRequest && ["responses", "responses_compact", "messages", "image_mcp"].includes(routeName)) {
372
384
  try {
373
385
  const finish = options.terminalActivity?.beginRequest?.();
374
386
  if (typeof finish === "function") finishTerminalActivity = finish;
@@ -382,7 +394,7 @@ export function createAdapterHandler(options = {}) {
382
394
  if (trackRequest && statusCode >= 400) {
383
395
  try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model,
384
396
  method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
385
- target: ["/v1/responses", "/v1/responses/compact", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
397
+ target: ["/v1/responses", "/v1/responses/compact", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
386
398
  request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
387
399
  attempt_timings: streamPerformance?.attemptTimings?.(),
388
400
  requested_model: context?.requestedModel, provider: context?.provider,
@@ -445,6 +457,7 @@ export function createAdapterHandler(options = {}) {
445
457
  containUnexpectedError(error);
446
458
  }
447
459
  };
460
+ handler.snapshot = statusSnapshot;
448
461
  return handler;
449
462
  }
450
463
 
@@ -457,6 +470,7 @@ export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
457
470
  : options.terminalActivity;
458
471
  const handler = createAdapterHandler({ ...options, terminalActivity, imageMcpHostname: host });
459
472
  const server = http.createServer(handler);
473
+ server.ccdxSnapshot = handler.snapshot;
460
474
  const cleanupTerminalActivity = () => {
461
475
  if (ownsTerminalActivity) terminalActivity?.cleanup?.();
462
476
  handler.cleanup?.();
@@ -0,0 +1,22 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ export async function openDashboard(baseUrl, { env = process.env, platform = process.platform, spawnImpl = spawn,
5
+ interactive = process.stdout.isTTY === true, enabled = true, timeoutMs = 3000 } = {}) {
6
+ const url = new URL(baseUrl);
7
+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
8
+ || url.username || url.password || url.search || url.hash) throw new Error("Dashboard launch requires a local HTTP URL");
9
+ if (!enabled || !interactive || env.CI && !/^(0|false|no|off)$/i.test(env.CI) || env.SSH_CONNECTION || env.SSH_TTY
10
+ || platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return { opened: false, state: "skipped" };
11
+ const command = platform === "darwin" ? "open" : platform === "win32"
12
+ ? path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "rundll32.exe") : "xdg-open";
13
+ const args = platform === "win32" ? ["url.dll,FileProtocolHandler", url.href] : [url.href];
14
+ return new Promise(resolve => {
15
+ let child, timer;
16
+ const finish = opened => { clearTimeout(timer);resolve({ opened, state: opened ? "opened" : "unavailable" }); };
17
+ try { child = spawnImpl(command, args, { stdio: "ignore", windowsHide: true }); }
18
+ catch { finish(false);return; }
19
+ child.once("error", () => finish(false));child.once("exit", code => finish(code === 0));
20
+ timer = setTimeout(() => { child.unref?.();finish(false); }, timeoutMs);timer.unref?.();
21
+ });
22
+ }
@@ -156,7 +156,10 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
156
156
  const entries = claudeModelEntries(models);
157
157
  const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
158
158
  const endpoint = new URL(baseUrl);
159
- if (endpoint.protocol !== "http:" || endpoint.hostname !== "127.0.0.1" || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error("Claude gateway must use a local root URL");
159
+ if (endpoint.protocol !== "http:" || endpoint.hostname !== "127.0.0.1" || !["/", "/anthropic"].includes(endpoint.pathname) || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error("Claude gateway must use a local root or /anthropic URL");
160
+ const journal = readM365Json(m365Paths(options).ownership, { version: 1, operations: [] });
161
+ const owns = (file, keys, value) => journal.version === 1 && Array.isArray(journal.operations)
162
+ && journal.operations.some(op => op.file === file && isDeepStrictEqual(op.keys, keys) && isDeepStrictEqual(op.after, value));
160
163
  const add = (file, keys, value, itemId) => operations.push({ file, keys, value, ...(itemId ? { itemId } : {}) });
161
164
  const env = options.env || process.env;
162
165
  let code;
@@ -170,7 +173,8 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
170
173
  || code?.apiKeyHelper
171
174
  || ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_ANTHROPIC_AWS", "CLAUDE_CODE_USE_GATEWAY"].some(key => /^(1|true)$/i.test(env[key] || codeEnv[key] || ""));
172
175
  if (!code) { /* Keep independent App setup available when Code settings are damaged. */ }
173
- else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl) result.code = "preserved";
176
+ else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl
177
+ && !owns(paths.code, ["env", "ANTHROPIC_BASE_URL"], codeEnv.ANTHROPIC_BASE_URL)) result.code = "preserved";
174
178
  else {
175
179
  add(paths.code, ["env", "ANTHROPIC_BASE_URL"], baseUrl);
176
180
  add(paths.code, ["env", "ANTHROPIC_AUTH_TOKEN"], apiKey);
@@ -194,6 +198,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
194
198
  else if (meta.hybridPointer || meta.appliedId && meta.appliedId !== M365_CLAUDE_PROFILE_ID
195
199
  || profile.inferenceProvider && profile.inferenceProvider !== "gateway"
196
200
  || profile.inferenceGatewayBaseUrl && profile.inferenceGatewayBaseUrl !== baseUrl
201
+ && !owns(paths.profile, ["inferenceGatewayBaseUrl"], profile.inferenceGatewayBaseUrl)
197
202
  || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey) result.app = "preserved";
198
203
  else {
199
204
  add(paths.profile, ["inferenceProvider"], "gateway");
@@ -7,7 +7,7 @@ import { createRequestAdmission } from "./request-admission.mjs";
7
7
  import { loadRuntimeConfig } from "./runtime-config.mjs";
8
8
  import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
9
9
  import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
10
- import { runWithRequestContext } from "./request-context.mjs";
10
+ import { runWithRequestContext, currentRequestContext } from "./request-context.mjs";
11
11
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
12
12
  import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
13
13
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
@@ -77,7 +77,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
77
77
  if (!["/v1/messages", "/v1/messages/count_tokens"].includes(pathname)) { send(res, 404, apiError("ccdx_not_found", "Not found"));return; }
78
78
  if (req.method !== "POST") { send(res, 405, apiError("ccdx_method", "Use POST"));return; }
79
79
  if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { send(res, 415, apiError("ccdx_media_type", "Expected application/json"));return; }
80
- const countTokens = pathname.endsWith("/count_tokens"), requestId = randomUUID();
80
+ const parent = currentRequestContext();
81
+ if (parent) parent.provider = provider.id;
82
+ const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
81
83
  const tracker = countTokens ? null : performance.begin("messages", { requestId });
82
84
  tracker?.setProvider(provider.id);
83
85
  const abort = createRequestAbort(req, res);
@@ -159,6 +161,20 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
159
161
  return handler;
160
162
  }
161
163
 
164
+ // Mounted by the main dispatcher. Own only Claude responses, never the shared listener.
165
+ export function createClaudeGateway(options = {}) {
166
+ const handler = createClaudeGatewayHandler(options), responses = new Set();
167
+ let closed = false;
168
+ return { port: options.port, snapshot: handler.snapshot,
169
+ handle(req, res) {
170
+ if (closed) { send(res, 503, apiError("ccdx_gateway_closed", "Claude is stopping"));return; }
171
+ responses.add(res);
172
+ return Promise.resolve(handler(req, res)).finally(() => responses.delete(res));
173
+ },
174
+ async close() { closed = true;for (const res of responses) res.destroy?.();responses.clear(); },
175
+ };
176
+ }
177
+
162
178
  export async function startClaudeGateway(options = {}) {
163
179
  const handler = createClaudeGatewayHandler(options), server = http.createServer(handler);
164
180
  server.headersTimeout = 15000;server.requestTimeout = 120000;
@@ -137,7 +137,7 @@ export async function runAnimationCommand({
137
137
  output.write(`CCDX_TERMINAL_ANIMATION=${disabledValue} remains effective until it is unset; terminal animation stays disabled.\n`);
138
138
  output.write("The saved animation will be used on the next ccdx start after the override is unset.\n");
139
139
  } else {
140
- output.write("The next ccdx start will use this animation.\n");
140
+ output.write("Running CCDX 1.1.0+ picks up this animation without restart; older services need a restart.\n");
141
141
  }
142
142
  return { ...result, cancelled: false, theme: selectedTheme };
143
143
  }
package/src/cli-image.mjs CHANGED
@@ -9,6 +9,7 @@ import { terminalCell } from "./cli-table.mjs";
9
9
  import { computeImageMcpCodexConfig } from "./config.mjs";
10
10
  import { probeImageTool } from "./image-readiness.mjs";
11
11
  import { updateImageSkill } from "./image-skill.mjs";
12
+ import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
12
13
  import {
13
14
  imageProviderConfigPath,
14
15
  inspectImageProvider,
@@ -193,6 +194,7 @@ export async function runImageCommand({
193
194
  }
194
195
  const summary = configSummary(config);
195
196
  output.write(`Image generation: enabled\nEndpoint: ${terminalCell(summary.endpoint)}\nModel: ${terminalCell(summary.model)}\nProtocol: ${terminalCell(summary.protocol)}\n`);
197
+ if (!servicePreferences({ env, home }).image_enabled) output.write("New image calls: paused by the WebUI preference; provider configuration is retained.\n");
196
198
  const readiness = await probeImageTool(fileContent(codexPath), { fetchImpl: probeFetchImpl });
197
199
  printImageReadiness(readiness, output, commandName);
198
200
  return { enabled: true, ...summary, readiness };
@@ -249,6 +251,7 @@ export async function runImageCommand({
249
251
  adapterPort,
250
252
  adapterHost,
251
253
  });
254
+ if (!servicePreferences({ env, home }).image_enabled) writeServicePreference("image_enabled", true, { env, home });
252
255
  output.write(`Enabled image generation with ${terminalCell(model)}.\n`);
253
256
  const readiness = await probeImageTool(fileContent(codexPath), { fetchImpl: probeFetchImpl });
254
257
  printImageReadiness(readiness, output, commandName);
package/src/cli-m365.mjs CHANGED
@@ -36,7 +36,7 @@ export function formatM365Status(state) {
36
36
  `Microsoft 365: ${terminalCell(m.state || "not running")}${m.reason ? ` (${terminalCell(m.reason)})` : ""}`,
37
37
  ...(m.account?.login ? [`Account: ${terminalCell(m.account.login)}`] : []),
38
38
  `Models: ${models.claude || 0} Claude / ${models.gpt || 0} GPT (${models.source || "unavailable"})`,
39
- `Claude gateway: ${claude.gateway || "not running"}${claude.port ? ` / http://127.0.0.1:${claude.port}` : ""}`,
39
+ `Claude gateway: ${claude.gateway || "not running"}${claude.base_url ? ` / ${claude.base_url}` : ""}`,
40
40
  ...(claude.reason ? [`Claude detail: ${terminalCell(claude.reason)}`] : []),
41
41
  ...(claude.requests ? [`Claude requests: ${claude.requests.completed} completed / ${claude.requests.incomplete} incomplete / ${claude.requests.failed} failed / ${claude.requests.active} active`] : []),
42
42
  `Claude Code: ${claude.clients?.code || "unknown"}; Claude App: ${claude.clients?.app || "unknown"}`,
@@ -5,6 +5,8 @@ const HELP_COMMANDS = new Set(["help", "--help", "-h"]);
5
5
  const VERSION_COMMANDS = new Set(["version", "--version", "-v"]);
6
6
  const START_OPTIONS = new Map([
7
7
  ["--show-request-id", "show-request-id"],
8
+ ["--no-browser", "no-browser"],
9
+ ["--verbose", "verbose"],
8
10
  ]);
9
11
  const RETIRED_CLAUDE_OPTIONS = new Set([
10
12
  "--configure-claude-desktop",
@@ -119,6 +121,8 @@ function parseStartOptions(args) {
119
121
  }
120
122
  return baseCommand("start", {
121
123
  showRequestId: seen.has("show-request-id"),
124
+ ...(seen.has("no-browser") ? { noBrowser: true } : {}),
125
+ ...(seen.has("verbose") ? { verbose: true } : {}),
122
126
  });
123
127
  }
124
128
 
@@ -376,7 +380,7 @@ export function cliCommandName() {
376
380
 
377
381
  function topicHelp(name, topic) {
378
382
  const sections = {
379
- start: `Usage:\n ${name} [start] [--show-request-id]\n\nStarts or reuses the local adapter, updates Codex configuration, and attempts to open Codex App when auto-launch is enabled and supported.`,
383
+ start: `Usage:\n ${name} [start] [--show-request-id] [--no-browser] [--verbose]\n\nStarts or reuses the local adapter, updates Codex configuration, and attempts to open Codex App when auto-launch is enabled and supported. Interactive desktop starts also open WebUI once; --no-browser skips that attempt. After startup the terminal shows fixed status/returned usage; --verbose or --show-request-id retains request detail.`,
380
384
  auth: `Usage:\n ${name} auth status [--online] [--format table|plain]\n\nShows the saved GitHub Copilot account without exposing credentials. --online also verifies its entitlement and model catalog.`,
381
385
  "auth status": `Usage:\n ${name} auth status [--online] [--format table|plain]\n\nShows the saved GitHub Copilot account without exposing credentials. --online also verifies its entitlement and model catalog. Interactive terminals use a table by default.`,
382
386
  doctor: `Usage:\n ${name} doctor [--online] [--compat] [--fix] [--json]\n ${name} doctor config\n\nChecks credentials, managed configuration, command launchers, adapter, enabled optional features and observed client catalog. Default is read-only; no inference requests. --online validates account entitlement; --compat sends minimal inference requests and consumes a small amount of Copilot usage, requiring successful model completion rather than HTTP 200 alone. --fix repairs owned Windows launchers and managed config, imports a verified existing credential only if none is saved, and asks the running adapter to repair enabled predictions once. No interactive login, client program edits, forced App restarts, policy changes or optional feature activation. Missing-credential repair can contact GitHub without --online. Changed existing config is backed up to config.toml.ccdx-doctor.bak. Partial repairs exit 1. --json emits a redacted report, including before_checks for repairs. App-internal cache and visible predictions are not externally verified. The config subcommand remains strictly read-only.`,
@@ -386,7 +390,7 @@ function topicHelp(name, topic) {
386
390
  usage: `Usage:\n ${name} usage [--format table|plain] [--provider ID]\n\nSummarizes local token usage metadata without reading prompt or completion content. Optional provider filtering separates sources; default totals include all recorded sources. Interactive terminals use a table by default.`,
387
391
  cache: `Usage:\n ${name} cache\n ${name} cache --limit <MiB|default>\n ${name} cache --clean [--history] [--yes]\n\nShows runtime cache use, saves and applies the shared response-history limit, or clears the rebuildable image-transform cache. --history also clears in-memory response history for all tasks and can make their next continuation fail, so interactive confirmation or --yes is required. Generated image files and saved Codex transcripts are never deleted. Short aliases: -128 sets 128 MiB and -clean equals --clean.`,
388
392
  limits: `Usage:\n ${name} limits\n ${name} limits --decoded <MiB|default>\n\nShows configured and running request-body limits, or saves a decoded request-body limit from 128 to 512 MiB. The raw-body limit is unchanged. Restart ccdx to apply a saved change; no conversation or cache is cleared. Short alias: -256 sets 256 MiB.`,
389
- animation: `Usage:\n ${name} animation\n\nPreviews all terminal activity animations together and selects the theme used the next time the adapter starts.`,
393
+ animation: `Usage:\n ${name} animation\n\nPreviews all terminal activity animations together and selects the saved theme. Running CCDX 1.1.0+ applies it live; older services need a restart.`,
390
394
  "enable-image": `Usage:\n ${name} enable-image\n\nInteractively configures an HTTPS image API endpoint (base URLs are also accepted) and API key, detects its supported image model and protocol, installs CCDX image guidance, and checks the local image tool for Codex App without generating an image. A blank key preserves the saved key only for the same origin; a new origin requires explicit key entry. Concurrent unrelated config edits are preserved.`,
391
395
  "disable-image": `Usage:\n ${name} disable-image\n\nDisables the local CCDX image tool and removes its stored API credential and unmodified CCDX image guidance.`,
392
396
  "image-status": `Usage:\n ${name} image-status\n\nShows provider configuration and locally advertised generation/editing tools without generating an image or exposing its API key.`,
@@ -405,7 +409,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
405
409
  const normalizedTopic = checkedHelpTopic(topic ? topic.split(" ") : []);
406
410
  if (normalizedTopic) return topicHelp(name, normalizedTopic);
407
411
  return `Usage:
408
- ${name} [start] [--show-request-id]
412
+ ${name} [start] [--show-request-id] [--no-browser] [--verbose]
409
413
  ${name} auth status [--online] [--format table|plain]
410
414
  ${name} doctor [--online] [--compat] [--fix] [--json]
411
415
  ${name} doctor config
package/src/cli-table.mjs CHANGED
@@ -35,7 +35,7 @@ function graphemeWidth(segment) {
35
35
  return width;
36
36
  }
37
37
 
38
- function displayWidth(value) {
38
+ export function displayWidth(value) {
39
39
  if (SIMPLE_WIDTH.test(value)) return value.length;
40
40
  graphemeSegmenter ||= new Intl.Segmenter("en", { granularity: "grapheme" });
41
41
  let width = 0;
@@ -116,7 +116,11 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
116
116
  }); },
117
117
  pacUrl() { return native?.pacUrl || null; },
118
118
  launched(route) { prediction.launch(route); },
119
- snapshot() { return { prediction: prediction.snapshot() }; },
119
+ setPredictionActive(value) {
120
+ const active = native?.setActive?.(value) ?? false;
121
+ return { active, state: active ? "active" : native ? "paused" : "needs_setup" };
122
+ },
123
+ snapshot() { return { prediction: { ...prediction.snapshot(), active: native?.enabled?.() === true } }; },
120
124
  async close() { closed = true;try { await operation; } finally { await native?.close();native = null; } },
121
125
  };
122
126
  }
@@ -0,0 +1,141 @@
1
+ (() => {
2
+ const el = id => document.getElementById(id);
3
+ const label = (node, key, values = {}) => globalThis.ccdxLanguage.set(node, key, values);
4
+ const titles = { overview: "Overview", codex: "Codex", claude: "Claude", models: "Model services", usage: "Usage and diagnostics", system: "System and settings" };
5
+ let current = "overview", settings = null, settingsPending = false, stopped = false, timer = null, ticks = 0;
6
+ let sourceDirty = false, sourceGeneration = 0;
7
+ let settingsReadAt = null;
8
+ function navigate() {
9
+ const route = location.hash.slice(1), next = Object.hasOwn(titles, route) ? route : "overview";
10
+ current = next;
11
+ for (const view of document.querySelectorAll("[data-view]")) view.hidden = view.dataset.view !== next;
12
+ for (const item of document.querySelectorAll("[data-route]")) {
13
+ if (item.dataset.route === next) item.setAttribute("aria-current", "page");else item.removeAttribute("aria-current");
14
+ }
15
+ label(el("page-title"), titles[next]);
16
+ if (["codex", "models", "system"].includes(next)) void loadSettings();
17
+ if (next === "models") { void dashboardRefresh.refresh("models");void dashboardRefresh.refresh("auth"); }
18
+ if (next === "usage") void dashboardRefresh.refresh("usage");
19
+ if (next === "system") void dashboardRefresh.refresh("animation");
20
+ syncAnimationPreview();
21
+ }
22
+ async function api(body) {
23
+ const response = await fetch("/_ccdx/ui/settings", { method: body ? "POST" : "GET", cache: "no-store",
24
+ headers: { "X-CCDX-Dashboard": "1", ...(body ? { "Content-Type": "application/json" } : {}) },
25
+ ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(15000) });
26
+ const data = await response.json();if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);return data;
27
+ }
28
+ const states = { immediate: "Effective now", terminal_unavailable: "Terminal animation unavailable in this output mode", next_start: "Next CCDX start", next_call: "Applies to new calls", needs_setup: "Setup required",
29
+ next_config_request: "Next configuration request; cached suggestions may remain", needs_app_relaunch: "Reopen the client to finish", needs_service_restart: "Restart CCDX to finish" };
30
+ function applySettings(data) {
31
+ settings = data;
32
+ for (const key of ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled"]) {
33
+ const input = el(`setting-${key}`), effective = data.effective[key];
34
+ input.checked = data.saved[key];input.disabled = Boolean(effective.locked);
35
+ label(el(`effect-${key}`), "Saved {saved} / effective {effective} / {state}", {
36
+ saved: { key: data.saved[key] ? "On" : "Off" }, effective: { key: effective.value ? "On" : "Off" },
37
+ state: { key: effective.locked ? "Controlled by environment" : states[effective.state] || effective.state } });
38
+ }
39
+ if (document.activeElement !== el("history-limit")) el("history-limit").value = data.history.maxBytes / 1048576;
40
+ el("history-limit").disabled = data.history.source === "environment";
41
+ el("save-history").disabled = data.history.source === "environment";
42
+ label(el("effect-history"), data.history.source === "environment" ? "Controlled by environment" : "Applies to new calls");
43
+ label(el("settings-note"), "Settings read from the running service.");
44
+ el("page-settings-note").textContent = "";
45
+ const state = data.providers;
46
+ if (state && !sourceDirty && el("source-provider").value !== state.codex_provider) {
47
+ el("source-provider").value = state.codex_provider;void loadSourceModels();
48
+ }
49
+ el("source-control-note").textContent = state ? `Codex → ${state.codex_provider} / Microsoft 365: ${state.m365.state}${state.m365.reason ? ` / ${state.m365.reason}` : ""}` : "—";
50
+ el("process-notice").textContent = data.terminal?.last_notice || "";
51
+ }
52
+ async function loadSettings() {
53
+ if (settingsPending) return;
54
+ settingsPending = true;
55
+ try { applySettings(await api());settingsReadAt = new Date().toLocaleTimeString(); }
56
+ catch (error) {
57
+ const detail = `${error.message}${settingsReadAt ? ` / ${settingsReadAt}` : ""}`;
58
+ el("settings-note").textContent = detail;el("page-settings-note").textContent = detail;
59
+ }
60
+ finally { settingsPending = false; }
61
+ }
62
+ async function change(body, button) {
63
+ if (settingsPending) return;
64
+ settingsPending = true;
65
+ const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #m365-on, #m365-off")];
66
+ controls.forEach(input => { input.disabled = true; });
67
+ label(el("settings-note"), "Applying…");
68
+ if (button) button.setAttribute("aria-busy", "true");
69
+ try {
70
+ const data = await api(body);if (body.action === "provider" && body.operation === "switch") sourceDirty = false;
71
+ applySettings(data);await dashboardRefresh.refresh("status", { force: true });await dashboardRefresh.refresh("auth", { force: true });
72
+ }
73
+ catch (error) {
74
+ if (settings) applySettings(settings);
75
+ el("settings-note").textContent = error.message;el("source-control-note").textContent = error.message;el("effect-history").textContent = error.message;
76
+ if (body.key) el(`effect-${body.key}`).textContent = error.message;
77
+ } finally {
78
+ settingsPending = false;controls.forEach(input => { input.disabled = false; });
79
+ if (settings) for (const [key, value] of Object.entries(settings.effective)) if (value.locked) el(`setting-${key}`).disabled = true;
80
+ if (settings?.history.source === "environment") el("save-history").disabled = true;
81
+ if (el("source-provider").value === "m365") el("apply-source").disabled = !el("source-model").value || !el("source-review").value;
82
+ button?.removeAttribute("aria-busy");
83
+ }
84
+ }
85
+ for (const input of document.querySelectorAll("[role=switch]")) input.addEventListener("change", () => {
86
+ void change({ action: "preference", key: input.id.slice("setting-".length), value: input.checked }, input);
87
+ });
88
+ el("save-history").addEventListener("click", () => void change({ action: "history_limit", mib: Number(el("history-limit").value) }, el("save-history")));
89
+ el("clean-history").addEventListener("click", () => {
90
+ if (window.confirm(globalThis.ccdxLanguage.format("Clear inactive Codex conversation data? Older continuation IDs may stop working."))) void change({ action: "history_clean" }, el("clean-history"));
91
+ });
92
+ el("fix-prediction").addEventListener("click", () => void change({ action: "prediction_fix" }, el("fix-prediction")));
93
+ for (const operation of ["on", "off"]) el(`m365-${operation}`).addEventListener("click", () => void change({ action: "provider", operation }, el(`m365-${operation}`)));
94
+ async function loadSourceModels() {
95
+ const generation = ++sourceGeneration;
96
+ const m365 = el("source-provider").value === "m365";
97
+ el("source-model").disabled = el("source-review").disabled = !m365;
98
+ if (!m365) { el("apply-source").disabled = settingsPending;return; }
99
+ el("apply-source").disabled = true;
100
+ el("source-model").replaceChildren();el("source-review").replaceChildren();
101
+ try {
102
+ const response = await fetch("/_ccdx/ui/models/live?provider=m365", { headers: { "X-CCDX-Dashboard": "1" }, cache: "no-store", signal: AbortSignal.timeout(15000) });
103
+ const data = await response.json();if (!response.ok) throw new Error(data.error);
104
+ if (generation !== sourceGeneration) return;
105
+ const models = data.models.filter(model => model.selectable && model.clients.includes("codex"));
106
+ for (const [id, list] of [["source-model", models], ["source-review", models.filter(model => model.reasoning_efforts?.includes("low"))]]) {
107
+ el(id).replaceChildren(...list.map(model => { const option = document.createElement("option");option.value = model.id;option.textContent = model.id;return option; }));
108
+ const saved = settings?.providers?.m365?.preference?.[id === "source-model" ? "model" : "auto_review_model"];
109
+ if (!sourceDirty && saved && list.some(model => model.id === saved)) el(id).value = saved;
110
+ }
111
+ el("apply-source").disabled = !el("source-model").value || !el("source-review").value;
112
+ } catch (error) { if (generation === sourceGeneration) el("source-control-note").textContent = error.message; }
113
+ }
114
+ el("source-provider").addEventListener("change", () => { sourceDirty = true;void loadSourceModels(); });
115
+ for (const id of ["source-model", "source-review"]) el(id).addEventListener("change", () => { sourceDirty = true; });
116
+ el("apply-source").addEventListener("click", () => {
117
+ const provider = el("source-provider").value;
118
+ void change({ action: "provider", operation: "switch", provider, ...(provider === "m365" ? { model: el("source-model").value, auto_review_model: el("source-review").value } : {}) }, el("apply-source"));
119
+ });
120
+ // Only the small in-memory status snapshot is read at this cadence. Catalogs
121
+ // and retained usage keep their existing on-demand, bounded refresh policy.
122
+ function schedule() {
123
+ clearTimeout(timer);if (stopped) return;
124
+ timer = setTimeout(async () => {
125
+ if (document.visibilityState === "visible" && dashboardRefresh.automatic) {
126
+ await dashboardRefresh.refresh("status", { force: true });
127
+ if (++ticks % 8 === 0) {
128
+ await dashboardRefresh.refresh("auth", { force: true });
129
+ if (["codex", "models", "system"].includes(current)) await loadSettings();
130
+ }
131
+ }
132
+ schedule();
133
+ }, 2000);
134
+ }
135
+ window.addEventListener("hashchange", navigate);
136
+ el("refresh").addEventListener("click", () => { if (["codex", "models", "system"].includes(current)) void loadSettings(); });
137
+ window.addEventListener("pagehide", () => { stopped = true;clearTimeout(timer); });
138
+ window.addEventListener("pageshow", () => { stopped = false;schedule(); });
139
+ el("open-animation").addEventListener("click", () => { location.hash = "system";navigate(); });
140
+ navigate();schedule();
141
+ })();