codex-copilot-dx 1.2.25 → 1.2.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/docs/ARCHITECTURE.md +20 -1
- package/docs/REFERENCE.md +52 -4
- package/package.json +1 -1
- package/src/cli-m365.mjs +3 -1
- package/src/dashboard/animation.js +8 -0
- package/src/dashboard/console.js +18 -7
- package/src/dashboard/index.html +15 -0
- package/src/dashboard/language.js +40 -0
- package/src/dashboard/preferences.js +194 -0
- package/src/dashboard/status.js +32 -15
- package/src/dashboard/theme.js +10 -3
- package/src/dashboard/ui.css +19 -0
- package/src/dashboard/ui.js +26 -13
- package/src/dashboard-api.mjs +1 -1
- package/src/dashboard.mjs +1 -0
- package/src/management-routes.mjs +3 -1
- package/src/optional-routes.mjs +1 -1
- package/src/provider-runtime.mjs +2 -1
- package/src/providers/m365-endpoint.mjs +4 -0
- package/src/providers/m365-network.mjs +3 -3
- package/src/providers/m365.mjs +7 -5
- package/src/service-control.mjs +10 -2
- package/src/settings-preferences.mjs +76 -0
- package/src/status-summary.mjs +6 -0
- package/src/user-settings.mjs +3 -3
- package/src/windows-http-network.mjs +2 -1
- package/src/windows-prediction-network.cs +1 -1
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ npm install -g codex-copilot-dx@latest
|
|
|
11
11
|
ccdx
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
14
|
+
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.26/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.26/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
|
|
15
15
|
|
|
16
16
|
CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
|
|
17
17
|
|
|
@@ -56,12 +56,11 @@ Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter t
|
|
|
56
56
|
|
|
57
57
|
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Selecting no models pauses access; enable a source and select models to resume. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
|
|
58
58
|
|
|
59
|
-
Model lists/details preserve the upstream maker declaration separately from your API source name. Missing maker metadata shows Not provided; model names are never used to guess a maker. Maker evidence is rebuildable display cache and does not change the strict connection schema or routing identity. Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.
|
|
59
|
+
Model lists/details preserve the upstream maker declaration separately from your API source name. Missing maker metadata shows Not provided; model names are never used to guess a maker. Maker evidence is rebuildable display cache and does not change the strict connection schema or routing identity. Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.26 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.26.md) cover the M365 service origin, automatic settings saving, bounded restore backups and lighter dashboard status while retaining native GitHub sign-in/model protections.
|
|
60
60
|
|
|
61
61
|
## Microsoft 365 access
|
|
62
62
|
|
|
63
|
-
Eligible macOS/Windows machines attempt silent Microsoft authorization at startup, without Copilot CLI or a browser login. MDM alone is insufficient: account, tenant,
|
|
64
|
-
device policy and Loki entitlement must permit access. Optional failure does not block GitHub. Saved bindings stay selected; unresolved company accounts can be chosen under **Model sources → Microsoft 365** or `ccdx m365 account` in the updated running service. Listing is local; changing accounts validates only the selected account, affects M365 in Codex/Claude and requires new conversations. See the reference for identity and history limits.
|
|
63
|
+
Eligible macOS/Windows machines attempt silent Microsoft authorization at startup, without Copilot CLI or a browser login. MDM alone is insufficient: account, tenant, device policy and Loki entitlement must permit access. Optional failure does not block GitHub. Saved bindings stay selected; unresolved company accounts can be chosen under **Model sources → Microsoft 365** or `ccdx m365 account` in the updated running service. Listing is local; changing accounts validates only the selected account, affects M365 in Codex/Claude and requires new conversations. See the reference for identity and history limits. Microsoft 365 uses the fixed `loki.delve.office.com` service origin. Account/origin-bound model discovery is separate from inference; old environment caches are not advertised as current. This does not enable a paused source or change existing application routing.
|
|
65
64
|
|
|
66
65
|
Claude clients use `http://127.0.0.1:2026/anthropic` (or the configured main port), a private local gateway key and a Claude-only catalog. No second Claude listener is opened. Existing unchanged CCDX-owned 2027 addresses migrate automatically; hand-written or managed addresses are preserved and need explicit migration. The optional prediction CONNECT/PAC bridge remains a separate transport.
|
|
67
66
|
Existing custom/managed settings are preserved; already-running clients may need a normal restart.
|
|
@@ -111,6 +110,7 @@ See the [M365 reference](docs/REFERENCE.md#microsoft-365-provider) for ownership
|
|
|
111
110
|
for the API. Inference rejects browser Origin headers; native clients remain supported. Diagnostic errors may contain sensitive upstream text.
|
|
112
111
|
|
|
113
112
|
Open `ccdx web` for source-specific account tools and Checks & repairs without signing in first. It starts a management-only service when needed; stop it before normal app startup. Safe reauth, config preview/backup, local reports, feature pause/resume and matching circle SVG status icons are described in the [account tools reference](docs/REFERENCE.md#account-and-repair-tools). Existing themes, layout and bilingual support are preserved. Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`. Settings → Version & updates shows the running version, release dates and newer releases, with copyable update and macOS/Windows recovery commands. This separate, cached GitHub metadata check never installs; failed checks remain unknown. The separate **Update overnight** switch defaults off and requires a normal CCDX restart after enabling. Its foreground supervisor checks during 00:00–04:00 local time after ten observed idle minutes, selects same-series stable patches at least 24 hours old, stages verified packages and attempts rollback on failure. Ctrl+C stops it; no OS service is installed. Review the displayed risk and [handoff limits](docs/REFERENCE.md#nightly-updates-opt-in) before enabling. See the [reference](docs/REFERENCE.md#version-and-update-information).
|
|
113
|
+
Settings → **Save & restore**, immediately after Version & updates, defaults to automatic saving of this page’s preferences. Turn it off to save or discard drafts manually. Restore defaults backs up the saved preferences first and offers Restore backup; it preserves accounts, keys, model/source selections, native sign-in, client connections, image/prediction access, chats and usage. Browser appearance stays browser-local; failed or conflicting saves retain the draft and show the actual result. See the [scope and recovery rules](docs/REFERENCE.md#settings-saving-and-restore).
|
|
114
114
|
GitHub updates verify and install the exact Release tarball without Git; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects. For npm `EALLOWREMOTE`, only if policy permits and the update is trusted, use `ccdx update github --allow-remote`: explicit URL-download permission for that installation's whole dependency tree, not a hostname allowlist. Persistent npm settings stay unchanged.
|
|
115
115
|
Updates back up the discovered CCDX package and commands, restore them on install/runtime-check failure, and verify the installed version (exact for GitHub). Mismatched npm targets warn without changing PATH/prefix. Manual updates require a separate adapter restart. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
|
|
116
116
|
Recent errors separate HTTP and model failures. By default HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged. Explicit, bounded error-excerpt collection is described in the [reference](docs/REFERENCE.md#http-error-diagnostics).
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -184,6 +184,8 @@ absence and policy refusal do not disable GitHub.
|
|
|
184
184
|
|
|
185
185
|
`network-route.mjs` canonicalizes abbreviated IPv4 CIDRs only while adapting system `ExceptionsList` input, before merging it with the unchanged strict `NO_PROXY` input. `network-bypass.mjs` remains the shared strict Node/PAC matcher; it performs no DNS lookup. This fixes no-proxy and static-proxy macOS configurations without dropping exception rules or weakening unsupported dynamic-PAC protection.
|
|
186
186
|
|
|
187
|
+
`providers/m365-endpoint.mjs` declares the fixed production origin and path shared by Node transport and the Windows parent whitelist. A regression checks the C# worker’s matching fixed-host policy. Catalog publication and history namespaces include the service origin and company account; legacy/different-origin caches stay on disk but do not publish as the new catalog. No cross-environment retry or implicit source switch is introduced.
|
|
188
|
+
|
|
187
189
|
`providers/m365-network-diagnostic.mjs` is a small pure projection of fixed proxy failure codes, source and stage, shared by transport, provider state, protected dashboard routes and CLI. Raw error chains/settings never cross that boundary. M365 retains existing outer error categories; the source runtime forwards the bounded diagnostic, and existing bilingual renderers expose a readable explanation with technical details. Startup uses the same fixed English explanation. Refresh failures retain last-good catalogs and never change the selected provider; successful transport creation clears the setup diagnostic. No new service, storage, dependency, route fallback or provider retry is introduced.
|
|
188
190
|
|
|
189
191
|
`claude-client-lifecycle.mjs` owns configuration reconciliation and restore state, independently from source auth/catalog code. It checks lifecycle/profile validity after asynchronous policy inspection and preserves the existing field-ownership writer.
|
|
@@ -417,11 +419,28 @@ prevents stale apply across tabs. `status.js` renders source-neutral authorizati
|
|
|
417
419
|
and client evidence; `usage.js` renders usage and date selection. View state remains
|
|
418
420
|
page-local; only existing preferences and the viewed model Provider are saved in
|
|
419
421
|
the browser. Expanded sections read on demand. The directory and Codex selectors share the same catalog resource, freshness and single-flight read. Changing sources cancels an obsolete waiter; generation checks reject late results. Account changes clear old-source drafts and snapshots; ordinary refreshes retain pending choices. There is no Node data watcher.
|
|
420
|
-
The sidebar controller reads
|
|
422
|
+
The sidebar controller reads view-scoped process-local status snapshots every two seconds
|
|
421
423
|
while visible/automatic, and source/settings evidence every eight status ticks.
|
|
422
424
|
Catalog and retained-log reads retain their slower, view-scoped policy. Animation
|
|
423
425
|
frames still load once per page when opened.
|
|
424
426
|
|
|
427
|
+
`settings-preferences.mjs` owns the explicit settings-page allowlist, normalized
|
|
428
|
+
defaults, revision checks and the single private pre-reset snapshot. Reset uses the
|
|
429
|
+
existing file-pair transaction with the backup written first; unrelated config
|
|
430
|
+
keys stay in the original file and never enter the backup. `service-control.mjs`
|
|
431
|
+
keeps its existing serialized action boundary and applies terminal/update effects
|
|
432
|
+
after the saved preferences commit. It never routes this operation through client
|
|
433
|
+
setup, account recovery or connection migration.
|
|
434
|
+
|
|
435
|
+
`dashboard/preferences.js` owns page-local drafts, coalesced writes, manual saving,
|
|
436
|
+
revision conflicts and browser-local appearance backup. The existing theme and
|
|
437
|
+
animation views expose small explicit preview/selection hooks. Settings writes
|
|
438
|
+
invalidate only animation/settings evidence, without model or account refresh.
|
|
439
|
+
Summary and complete status have separate refresh resources. `status-summary.mjs`
|
|
440
|
+
projects the optional lightweight response; full status stays the default public
|
|
441
|
+
contract. Hidden status regions defer DOM updates, and summary rendering never
|
|
442
|
+
replaces the full request/history cache.
|
|
443
|
+
|
|
425
444
|
`dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals; runtime snapshots expose the weighted cache ratio plus a partial-evidence flag, without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
|
|
426
445
|
|
|
427
446
|
`dashboard-updates.mjs` is loaded only by the protected update-information route. It projects bounded public stable-release metadata and publication dates, with process-local single-flight, five-minute success and one-minute failure caches. Its asynchronous npm network-configuration read reuses the installer's existing policy-preserving downloader; it adds no runtime dependency, credentials or synchronous child process on the service event loop. Metadata has a four-second per-request deadline and 128 KiB decoded-body bound. It never installs or restarts anything and does not alter startup's independent web-redirect lookup. `dashboard/updates.js` renders current/available/unknown states and validated, pinned installation command text; `refresh.js` owns its visible Settings refresh cadence. Failed checks preserve explicitly labeled prior metadata. No provider authentication or inference is involved.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -333,10 +333,10 @@ restore existing client settings; use `m365 off` for that explicit operation.
|
|
|
333
333
|
Entra tokens are retained in memory until renewal/close, never saved in a CCDX
|
|
334
334
|
credential file. Renewal is silent and single-flight, with a 28-second helper
|
|
335
335
|
deadline and one-minute failure backoff. The provider uses only
|
|
336
|
-
`https://
|
|
336
|
+
`https://loki.delve.office.com/api/v1/llmapi`; discovery uses `/models` and
|
|
337
337
|
inference uses its advertised native Responses or Messages endpoints. This is a
|
|
338
|
-
|
|
339
|
-
origin. Explicit proxy/trust settings are preserved. Windows delegates system
|
|
338
|
+
private service, not a promised public SLA. Its fixed origin is shared by the Node and Windows target policies; authentication resources and company network policy are unchanged. No request is redirected to another
|
|
339
|
+
origin. Model caches and replay namespaces are bound to this service origin and account. A legacy cache with no origin, or one from the prior dogfood origin, is preserved on disk but is not published as this environment’s catalog; a successful discovery replaces it. Disabled sources and saved client/model selections are not automatically changed. Explicit proxy/trust settings are preserved. Windows delegates system
|
|
340
340
|
PAC/WPAD and integrated authentication to its own isolated WinHTTP worker;
|
|
341
341
|
unsupported macOS dynamic PAC is reported rather than bypassed.
|
|
342
342
|
|
|
@@ -1316,7 +1316,7 @@ Unknown support prevents an explicitly requested exception from starting.
|
|
|
1316
1316
|
For an older updater that still requires Git, install the Release tarball directly:
|
|
1317
1317
|
|
|
1318
1318
|
```sh
|
|
1319
|
-
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
1319
|
+
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.26/codex-copilot-dx-1.2.26.tgz
|
|
1320
1320
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
1321
1321
|
```
|
|
1322
1322
|
|
|
@@ -1506,6 +1506,54 @@ reads. Catalog requests are deduplicated, stale tab reads are cancelled and late
|
|
|
1506
1506
|
results rejected. Failed reads preserve last-good data and label it as stale.
|
|
1507
1507
|
Service-setting errors are visible on the current page and can be retried manually.
|
|
1508
1508
|
|
|
1509
|
+
### Settings saving and restore
|
|
1510
|
+
|
|
1511
|
+
Settings → **Save & restore**, after Version & updates, controls only this page’s
|
|
1512
|
+
preferences. **Save changes automatically** defaults on. Terminal palette,
|
|
1513
|
+
animation, animation enablement, opening the webpage at startup and overnight-update
|
|
1514
|
+
preferences save after a short coalescing delay. Webpage appearance stays in the
|
|
1515
|
+
current browser. Turning automatic saving off reveals Save changes and Discard
|
|
1516
|
+
changes; enabling it with a draft asks before saving that draft. Invalid or failed
|
|
1517
|
+
saves keep the draft. Polls do not overwrite drafts, old responses do not replace
|
|
1518
|
+
newer edits, and a conflicting settings revision requires reviewing the current
|
|
1519
|
+
settings. Ordinary appearance saves do not enumerate accounts, authenticate or
|
|
1520
|
+
refresh provider catalogs. Overnight updates remain off by default and enabling
|
|
1521
|
+
them confirms the existing restart risk; saving the preference never installs an update.
|
|
1522
|
+
|
|
1523
|
+
Restore defaults confirms the scope, backs up the saved preferences first, then
|
|
1524
|
+
writes the settings-page fields in one locked atomic transaction. Defaults are:
|
|
1525
|
+
green webpage and terminal palettes, dark webpage appearance, Comet animation,
|
|
1526
|
+
terminal animation on, open webpage on startup, overnight updates off and automatic
|
|
1527
|
+
saving on. Language, model/source selections, API keys, native sign-in and client
|
|
1528
|
+
configuration, review/memory choices, image/prediction access, history, usage and
|
|
1529
|
+
network/environment policy are preserved. Environment-controlled effective values
|
|
1530
|
+
remain controlled. Pending drafts are explicitly discarded only after confirmation.
|
|
1531
|
+
|
|
1532
|
+
The private `settings-preferences-backup.json` beside the settings file contains
|
|
1533
|
+
only the six allowlisted service preferences, version, ID and creation time; it
|
|
1534
|
+
contains no credentials or provider settings. Restore backup uses the latest
|
|
1535
|
+
pre-reset snapshot. Backup failure aborts reset; a failed settings write restores
|
|
1536
|
+
the prior settings and prior backup. A repeated reset with its same operation ID
|
|
1537
|
+
cannot overwrite the original snapshot after a lost response. Unreadable settings
|
|
1538
|
+
or backups are preserved and reported.
|
|
1539
|
+
|
|
1540
|
+
Browser appearance has its own origin-local backup linked to the operation ID.
|
|
1541
|
+
At most two entries are held while a reset result is uncertain, reducing to the
|
|
1542
|
+
matching latest backup after a confirmed settings read. Service and browser storage
|
|
1543
|
+
are not one atomic transaction: a browser-storage failure after the service save is
|
|
1544
|
+
reported as partial completion and can be retried. Another browser without the
|
|
1545
|
+
matching appearance backup reports that limitation rather than claiming a complete
|
|
1546
|
+
restore. No periodic backup service, credential export or full configuration reset
|
|
1547
|
+
is added.
|
|
1548
|
+
|
|
1549
|
+
The full `/_ccdx/status` response remains the default CLI/diagnostic contract.
|
|
1550
|
+
Overview and Settings use an explicit `?scope=summary` projection containing service
|
|
1551
|
+
identity, uptime, model activity and current-run usage. The browser keeps summary
|
|
1552
|
+
and full reads in separate resource entries; summary data cannot replace request
|
|
1553
|
+
history or turn missing full fields into zero values. Other pages request full
|
|
1554
|
+
status when opened. Hidden data regions skip DOM work, retaining their last data
|
|
1555
|
+
until a visible full read; native inference and the selected model are unaffected.
|
|
1556
|
+
|
|
1509
1557
|
The usage selector retains current and historical sources. Combined model rows
|
|
1510
1558
|
and daily analytics preserve source identity; old records without a client label
|
|
1511
1559
|
are not guessed into one. Legacy untagged Provider records retain their historical
|
package/package.json
CHANGED
package/src/cli-m365.mjs
CHANGED
|
@@ -40,7 +40,9 @@ export async function fetchActiveProviderModels({ control = providerControl, ...
|
|
|
40
40
|
}
|
|
41
41
|
const address = parseAdapterAddressOptions(options.env || process.env);
|
|
42
42
|
const result = await control({ host: address.adapterHost, port: address.adapterPort, ...options, action: { action: "models", family: "gpt" } });
|
|
43
|
-
|
|
43
|
+
let upstreamHost = "Microsoft 365";
|
|
44
|
+
try { const origin = new URL(result.state?.m365?.service_origin);if (origin.protocol === "https:") upstreamHost = origin.hostname; } catch {}
|
|
45
|
+
return { source: "catalog", upstreamHost, advertised: result.models.length,
|
|
44
46
|
models: result.models.map(model => ({ id: model.id, vendor: model.publisher, endpoints: ["responses"], preview: false })) };
|
|
45
47
|
}
|
|
46
48
|
|
|
@@ -91,6 +91,7 @@
|
|
|
91
91
|
element("save-animation").disabled = selectedAnimation === savedAnimation;
|
|
92
92
|
updateAnimationState();
|
|
93
93
|
syncAnimationPreview();
|
|
94
|
+
globalThis.ccdxSettingsPreferences?.selectAnimation(theme.id);
|
|
94
95
|
});
|
|
95
96
|
const name = document.createElement("span");
|
|
96
97
|
name.className = "theme-name";
|
|
@@ -145,6 +146,7 @@
|
|
|
145
146
|
}
|
|
146
147
|
updateAnimationState();
|
|
147
148
|
text("animation-note", animationNote(data));
|
|
149
|
+
globalThis.ccdxSettingsPreferences?.render();
|
|
148
150
|
}
|
|
149
151
|
|
|
150
152
|
function updateAnimationState() {
|
|
@@ -180,6 +182,12 @@
|
|
|
180
182
|
}
|
|
181
183
|
|
|
182
184
|
return { apply: applyAnimation, load: loadAnimation, save: saveAnimation, sync: syncAnimationPreview, stop: stopAnimationPreview,
|
|
185
|
+
select(theme) {
|
|
186
|
+
if (!animationRows.has(theme) || selectedAnimation === theme) return;
|
|
187
|
+
selectedAnimation = theme;
|
|
188
|
+
for (const [id, row] of animationRows) row.setAttribute("aria-pressed", String(id === theme));
|
|
189
|
+
updateAnimationState();syncAnimationPreview();
|
|
190
|
+
},
|
|
183
191
|
get saving() { return animationSaving; }, get framesLoaded() { return animationFramesLoaded; } };
|
|
184
192
|
}
|
|
185
193
|
globalThis.ccdxDashboardAnimation = { create };
|
package/src/dashboard/console.js
CHANGED
|
@@ -44,6 +44,9 @@
|
|
|
44
44
|
if (next !== "codex") sourceGeneration++;
|
|
45
45
|
if (!["codex", "models"].includes(next) && dashboardRefresh.state("models").pending) dashboardRefresh.invalidate("models");
|
|
46
46
|
for (const view of document.querySelectorAll("[data-view]")) view.hidden = view.dataset.view !== next;
|
|
47
|
+
const snapshot = dashboardRefresh.state(statusResourceKey()).value;
|
|
48
|
+
if (snapshot) render(snapshot);
|
|
49
|
+
void refreshStatus();
|
|
47
50
|
globalThis.ccdxDashboardActivity?.visibilityChanged();
|
|
48
51
|
globalThis.ccdxDashboardFlow?.visibilityChanged();
|
|
49
52
|
for (const item of document.querySelectorAll("[data-route]")) {
|
|
@@ -58,6 +61,7 @@
|
|
|
58
61
|
if (next === "usage") { void dashboardRefresh.refresh("usage");usageView.revealChart(); } else usageView.stopMotion();
|
|
59
62
|
if (next === "requests") renderContext();
|
|
60
63
|
if (next === "system") { void dashboardRefresh.refresh("animation");void dashboardRefresh.refresh("updates"); }
|
|
64
|
+
preferences?.render();
|
|
61
65
|
syncAnimationPreview();
|
|
62
66
|
}
|
|
63
67
|
async function api(body) {
|
|
@@ -66,6 +70,10 @@
|
|
|
66
70
|
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(body?.operation === "account" ? 65000 : 15000) });
|
|
67
71
|
const data = await response.json();if (!response.ok) throw Object.assign(new Error(data.error || `HTTP ${response.status}`), { code: data.code });return data;
|
|
68
72
|
}
|
|
73
|
+
const preferences = globalThis.ccdxDashboardPreferences?.create({ element: el, api, applied: applySettings, time,
|
|
74
|
+
selectAnimation: theme => animationView.select(theme),
|
|
75
|
+
refreshAnimation() { dashboardRefresh.invalidate("animation");if (current === "system") void dashboardRefresh.refresh("animation", { force: true }); } });
|
|
76
|
+
globalThis.ccdxSettingsPreferences = preferences;
|
|
69
77
|
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",
|
|
70
78
|
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" };
|
|
71
79
|
const selectedSource = () => providerEntries.find(source => source.id === el("source-provider").value);
|
|
@@ -103,7 +111,7 @@
|
|
|
103
111
|
syncReviewButton();
|
|
104
112
|
}
|
|
105
113
|
window.addEventListener("ccdx:providers", () => { syncSources();if (current === "codex") void loadSourceModels(); });
|
|
106
|
-
function applySettings(data) {
|
|
114
|
+
function applySettings(data, meta) {
|
|
107
115
|
settings = data;
|
|
108
116
|
const nightly = data.nightly_update;
|
|
109
117
|
el("nightly-update").checked = nightly?.enabled === true;el("nightly-update").disabled = false;
|
|
@@ -164,13 +172,15 @@
|
|
|
164
172
|
}
|
|
165
173
|
}
|
|
166
174
|
el("process-notice").textContent = data.terminal?.last_notice || "";
|
|
175
|
+
preferences?.sync(data, meta);
|
|
167
176
|
}
|
|
168
177
|
async function loadSettings() {
|
|
169
178
|
if (settingsPending) return;
|
|
170
179
|
settingsPending = true;
|
|
171
180
|
el("terminal-color-theme").disabled = true;
|
|
172
181
|
syncAccountControls();
|
|
173
|
-
|
|
182
|
+
const readVersion = preferences?.version;
|
|
183
|
+
try { applySettings(await api(), { readVersion });settingsReadAt = time(Date.now());void globalThis.ccdxConnections?.load(); }
|
|
174
184
|
catch (error) {
|
|
175
185
|
for (const id of ["settings-note", ...(settingsViews.includes(current) ? ["page-settings-note"] : [])]) {
|
|
176
186
|
label(el(id), settingsReadAt ? "showing_previous_data_updated_time" : "could_not_read_settings", { time: settingsReadAt });
|
|
@@ -206,7 +216,7 @@
|
|
|
206
216
|
dashboardRefresh.invalidate("models", { clear: true });
|
|
207
217
|
label(el("m365-account-note"), "company_account_checked");
|
|
208
218
|
}
|
|
209
|
-
if (body.action !== "color_theme") { await
|
|
219
|
+
if (body.action !== "color_theme") { await refreshStatus();await dashboardRefresh.refresh("auth", { force: true }); }
|
|
210
220
|
}
|
|
211
221
|
catch (error) {
|
|
212
222
|
if (settings) applySettings(settings);
|
|
@@ -223,9 +233,10 @@
|
|
|
223
233
|
}
|
|
224
234
|
}
|
|
225
235
|
for (const input of document.querySelectorAll('[role=switch][id^="setting-"]')) input.addEventListener("change", () => {
|
|
236
|
+
if (preferences && input.closest('[data-view="system"]')) return;
|
|
226
237
|
void change({ action: "preference", key: input.id.slice("setting-".length), value: input.checked }, input);
|
|
227
238
|
});
|
|
228
|
-
el("terminal-color-theme").addEventListener("change", () => void change({ action: "color_theme", theme: el("terminal-color-theme").value }, el("terminal-color-theme")));
|
|
239
|
+
if (!preferences) el("terminal-color-theme").addEventListener("change", () => void change({ action: "color_theme", theme: el("terminal-color-theme").value }, el("terminal-color-theme")));
|
|
229
240
|
el("save-history").addEventListener("click", () => void change({ action: "history_limit", mib: Number(el("history-limit").value) }, el("save-history")));
|
|
230
241
|
el("clean-history").addEventListener("click", () => {
|
|
231
242
|
if (window.confirm(globalThis.ccdxLanguage.format("clear_inactive_codex_conversation_data_older_continuation_ids_ma"))) void change({ action: "history_clean" }, el("clean-history"));
|
|
@@ -283,7 +294,7 @@
|
|
|
283
294
|
model: el("source-model").value, ...(settings?.providers?.codex_provider === provider ? {} : {
|
|
284
295
|
auto_review_model: el("source-review").value, auto_review_effort: el("source-review-effort").value || null }) } : {}) }, el("apply-source"));
|
|
285
296
|
});
|
|
286
|
-
el("nightly-update").addEventListener("change", () => void change({ action: "nightly_update", enabled: el("nightly-update").checked }, el("nightly-update")));
|
|
297
|
+
if (!preferences) el("nightly-update").addEventListener("change", () => void change({ action: "nightly_update", enabled: el("nightly-update").checked }, el("nightly-update")));
|
|
287
298
|
el("save-review").addEventListener("click", () => void change({ action: "provider", operation: "auto-review", provider: el("source-provider").value,
|
|
288
299
|
model: el("source-review").value, auto_review_effort: el("source-review-effort").value || null }, el("save-review")));
|
|
289
300
|
// Only the small in-memory status snapshot is read at this cadence. Catalogs
|
|
@@ -292,7 +303,7 @@
|
|
|
292
303
|
clearTimeout(timer);if (stopped || document.visibilityState !== "visible" || !dashboardRefresh.automatic) return;
|
|
293
304
|
timer = setTimeout(async () => {
|
|
294
305
|
if (document.visibilityState === "visible" && dashboardRefresh.automatic) {
|
|
295
|
-
await
|
|
306
|
+
await refreshStatus();
|
|
296
307
|
if (++ticks % 8 === 0) {
|
|
297
308
|
await dashboardRefresh.refresh("auth", { force: true });
|
|
298
309
|
if (settingsViews.includes(current)) await loadSettings();
|
|
@@ -303,7 +314,7 @@
|
|
|
303
314
|
}
|
|
304
315
|
window.addEventListener("hashchange", navigate);
|
|
305
316
|
document.addEventListener("visibilitychange", () => {
|
|
306
|
-
if (!stopped && document.visibilityState === "visible" && dashboardRefresh.automatic) void
|
|
317
|
+
if (!stopped && document.visibilityState === "visible" && dashboardRefresh.automatic) void refreshStatus();
|
|
307
318
|
schedule();
|
|
308
319
|
});
|
|
309
320
|
el("auto-refresh").addEventListener("click", schedule);
|
package/src/dashboard/index.html
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
<script src="/updates.js" defer></script>
|
|
20
20
|
<script src="/animation.js" defer></script>
|
|
21
21
|
<script src="/ui.js" defer></script>
|
|
22
|
+
<script src="/preferences.js" defer></script>
|
|
22
23
|
<script src="/console.js" defer></script>
|
|
23
24
|
<script src="/tools.js" defer></script>
|
|
24
25
|
<script src="/connections.js" defer></script>
|
|
@@ -50,6 +51,7 @@
|
|
|
50
51
|
<section class="intro">
|
|
51
52
|
<h1><span id="page-title" data-i18n="overview">Overview</span></h1>
|
|
52
53
|
<p id="page-settings-note" class="hint" role="status"></p>
|
|
54
|
+
<div id="preferences-status" class="preferences-status" role="status" aria-live="polite" hidden></div>
|
|
53
55
|
</section>
|
|
54
56
|
|
|
55
57
|
|
|
@@ -415,6 +417,19 @@
|
|
|
415
417
|
<p id="install-windows-policy" class="hint" hidden data-i18n="update_windows_policy">If scripts are blocked, use your company’s approved installation method.</p>
|
|
416
418
|
</details><p id="update-copy-note" class="hint" role="status"></p>
|
|
417
419
|
</section>
|
|
420
|
+
<section class="panel dashboard-section" id="settings-preferences" aria-labelledby="preferences-heading">
|
|
421
|
+
<h2 id="preferences-heading" data-i18n="preferences_heading">SAVE & RESTORE</h2>
|
|
422
|
+
<div class="preferences-row"><div><label for="preferences-auto" data-i18n="preferences_auto">Save changes automatically</label><p class="hint" data-i18n="preferences_auto_hint">Valid changes on this page save automatically.</p></div><input id="preferences-auto" type="checkbox" role="switch" disabled checked></div>
|
|
423
|
+
<div class="preferences-row preferences-separator"><div><span data-i18n="preferences_reset_title">Restore default settings</span><p class="hint" data-i18n="preferences_reset_hint">Back up saved settings before restoring.</p></div><button id="preferences-reset" type="button" disabled data-i18n="preferences_reset">Restore defaults</button></div>
|
|
424
|
+
<div id="preferences-backup" class="preferences-row preferences-separator" hidden><div><span data-i18n="preferences_backup">Settings before restore</span><p id="preferences-backup-time" class="hint"></p></div><button id="preferences-restore" type="button" data-i18n="preferences_restore">Restore backup</button></div>
|
|
425
|
+
<div id="preferences-manual" class="preferences-row preferences-separator" hidden><span id="preferences-manual-note" class="hint"></span><div class="connection-actions"><button id="preferences-discard" type="button" data-i18n="preferences_discard">Discard changes</button><button id="preferences-save" type="button" data-i18n="preferences_save">Save changes</button></div></div>
|
|
426
|
+
<div class="section-actions"><button id="preferences-retry" type="button" hidden data-i18n="view_retry">Retry</button><p id="preferences-error" class="hint" role="alert"></p></div>
|
|
427
|
+
</section>
|
|
428
|
+
<dialog id="preferences-dialog" class="preferences-dialog" aria-labelledby="preferences-dialog-title">
|
|
429
|
+
<h2 id="preferences-dialog-title"></h2><p id="preferences-dialog-intro"></p>
|
|
430
|
+
<dl id="preferences-dialog-scope"><div><dt data-i18n="preferences_scope">Restore</dt><dd data-i18n="preferences_scope_value">Web and terminal appearance, animation, startup and update preferences.</dd></div><div><dt data-i18n="preferences_keep">Keep</dt><dd data-i18n="preferences_keep_value">Accounts and keys, models and sources, app connections, chats, usage, image and prediction access.</dd></div></dl>
|
|
431
|
+
<p id="preferences-dialog-note" class="hint"></p><div class="section-actions"><button id="preferences-dialog-cancel" type="button" data-i18n="cancel">Cancel</button><button id="preferences-dialog-confirm" type="button"></button></div>
|
|
432
|
+
</dialog>
|
|
418
433
|
</div>
|
|
419
434
|
</main>
|
|
420
435
|
<footer data-i18n="local_only_visible_page_updates">THIS COMPUTER ONLY / UPDATES WHILE VISIBLE</footer>
|
|
@@ -1,5 +1,45 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"preferences_heading": ["SAVE & RESTORE", "保存与恢复"],
|
|
4
|
+
"preferences_auto": ["Save changes automatically", "自动保存设置"],
|
|
5
|
+
"preferences_auto_hint": ["Valid changes on this page save automatically.", "本页改动有效后自动保存。"],
|
|
6
|
+
"preferences_reset_title": ["Restore default settings", "恢复默认设置"],
|
|
7
|
+
"preferences_reset_hint": ["Back up saved settings before restoring.", "恢复前自动备份已保存设置。"],
|
|
8
|
+
"preferences_reset": ["Restore defaults", "恢复默认"],
|
|
9
|
+
"preferences_backup": ["Settings before restore", "恢复前的设置"],
|
|
10
|
+
"preferences_restore": ["Restore backup", "恢复备份"],
|
|
11
|
+
"preferences_discard": ["Discard changes", "放弃修改"],
|
|
12
|
+
"preferences_save": ["Save changes", "保存修改"],
|
|
13
|
+
"preferences_saved": ["Saved", "已保存"],
|
|
14
|
+
"preferences_manual": ["Manual saving is on", "手动保存已开启"],
|
|
15
|
+
"preferences_unsaved": ["{count} unsaved changes", "{count} 项未保存"],
|
|
16
|
+
"preferences_failed": ["Save failed. Your changes are kept. Try again.", "保存失败,改动已保留。请重试。"],
|
|
17
|
+
"preferences_changed": ["Settings changed elsewhere. Discard your draft to load the current settings.", "设置已在其他窗口修改。请放弃草稿后重试。"],
|
|
18
|
+
"preferences_conflict": ["Settings changed", "设置已变更"],
|
|
19
|
+
"preferences_appearance_preview": ["Preview only. Save to keep this choice.", "仅预览,保存后保留此选择。"],
|
|
20
|
+
"preferences_terminal_preview": ["Preview only. Save to update the terminal.", "仅预览,保存后更新终端。"],
|
|
21
|
+
"preferences_browser_changed": ["Browser appearance changed elsewhere. Discard your draft before saving.", "浏览器外观已在其他窗口修改。请先放弃草稿。"],
|
|
22
|
+
"preferences_browser_failed": ["Service settings saved; browser appearance was not saved. Retry to finish.", "服务设置已保存,浏览器外观未保存。请重试完成。"],
|
|
23
|
+
"preferences_browser_backup_invalid": ["The browser backup could not be saved or read. No restore was requested.", "浏览器备份无法保存或读取,尚未请求恢复。"],
|
|
24
|
+
"preferences_browser_backup_missing": ["This browser has no matching appearance backup. Service settings were kept.", "本浏览器没有对应的外观备份,服务设置已保留。"],
|
|
25
|
+
"preferences_scope": ["Restore", "将恢复"],
|
|
26
|
+
"preferences_scope_value": ["Web and terminal appearance, animation, startup and update preferences.", "网页与终端外观、终端动效、启动偏好和更新偏好。"],
|
|
27
|
+
"preferences_keep": ["Keep", "会保留"],
|
|
28
|
+
"preferences_keep_value": ["Accounts and keys, models and sources, app connections, chats, usage, image and prediction access.", "账号与密钥、模型与来源、应用接入、会话与用量、生图与预测开关。"],
|
|
29
|
+
"preferences_reset_question": ["Restore default settings?", "恢复默认设置?"],
|
|
30
|
+
"preferences_reset_intro": ["Restore settings on this page after backing up saved settings.", "恢复本页设置,并先备份已保存设置。"],
|
|
31
|
+
"preferences_reset_confirm": ["Back up & restore", "备份并恢复"],
|
|
32
|
+
"preferences_restore_question": ["Restore the backup?", "恢复备份设置?"],
|
|
33
|
+
"preferences_restore_intro": ["Replace this page's settings with those saved before the last reset.", "用上次恢复默认前的设置替换本页设置。"],
|
|
34
|
+
"preferences_restore_confirm": ["Restore backup", "恢复备份"],
|
|
35
|
+
"preferences_enable_question": ["Turn on automatic saving?", "开启自动保存?"],
|
|
36
|
+
"preferences_enable_intro": ["This also saves your {count} pending changes.", "同时保存当前 {count} 项修改。"],
|
|
37
|
+
"preferences_enable_confirm": ["Save & turn on", "开启并保存"],
|
|
38
|
+
"preferences_nightly_question": ["Turn on overnight updates?", "开启夜间自动更新?"],
|
|
39
|
+
"preferences_nightly_intro": ["CCDX updates and restarts while idle overnight. Conversations may be affected.", "CCDX 会在夜间空闲时更新并重启,可能影响会话继续。"],
|
|
40
|
+
"preferences_nightly_confirm": ["Turn on", "开启"],
|
|
41
|
+
"preferences_backup_latest": ["Only the latest pre-reset backup is kept.", "只保留最近一次恢复前备份。"],
|
|
42
|
+
"preferences_draft_discard": ["Unsaved changes will be discarded. The backup keeps saved settings.", "未保存的改动将放弃;备份保留已保存设置。"],
|
|
3
43
|
"request_access_blocked": ["Access blocked", "请求已拦截"],
|
|
4
44
|
"access_paused": ["Access paused", "接入已暂停"],
|
|
5
45
|
"not_applicable": ["Not applicable", "不适用"],
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
function create({ element: el, api, applied, refreshAnimation, selectAnimation, time }) {
|
|
3
|
+
const label = (id, key, values) => globalThis.ccdxLanguage.set(el(id), key, values);
|
|
4
|
+
const theme = () => globalThis.ccdxDashboardTheme;
|
|
5
|
+
const backupKey = "ccdx.dashboard.preferences-backup";
|
|
6
|
+
const fields = { terminal_color_theme: "terminal-color-theme", terminal_animation_enabled: "setting-terminal_animation_enabled",
|
|
7
|
+
open_webui: "setting-open_webui", nightly_updates: "nightly-update" };
|
|
8
|
+
let base, draft = {}, appearance, appearanceBase, pending, timer, error = null, conflict = false, version = 0, dialog, dialogRevision, resetting = false, retrying = false, locks = {}, terminalMode;
|
|
9
|
+
const dirty = () => Object.keys(draft).length + (appearance ? 1 : 0);
|
|
10
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
11
|
+
const active = () => !el("settings-preferences").closest("[hidden]");
|
|
12
|
+
function browserBackup() {
|
|
13
|
+
const raw = localStorage.getItem(backupKey);if (raw === null) return { version: 1, entries: [] };
|
|
14
|
+
const value = JSON.parse(raw);
|
|
15
|
+
if (value?.version !== 1 || !Array.isArray(value.entries) || value.entries.length > 2 || value.entries.some(entry => typeof entry.id !== "string"
|
|
16
|
+
|| !["dark", "light"].includes(entry.values?.theme) || !["green", "klein", "pink"].includes(entry.values?.palette))) throw Error("preferences_browser_backup_invalid");
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function render() {
|
|
20
|
+
el("preferences-status").hidden = !active();
|
|
21
|
+
if (!base) return;
|
|
22
|
+
const current = { ...base.values, ...draft }, count = dirty(), busy = Boolean(pending || retrying);
|
|
23
|
+
el("preferences-auto").checked = current.auto_save_settings;el("preferences-auto").disabled = busy || conflict;
|
|
24
|
+
for (const [key, id] of Object.entries(fields)) {
|
|
25
|
+
const node = el(id);if (node.type === "checkbox") node.checked = current[key];else node.value = current[key];
|
|
26
|
+
node.disabled = Boolean(locks[key] || resetting);
|
|
27
|
+
}
|
|
28
|
+
el("web-color-theme").disabled = resetting;
|
|
29
|
+
for (const row of document.querySelectorAll("#animation-options [data-theme]")) row.disabled = resetting;
|
|
30
|
+
el("terminal-color-sample").dataset.terminalPalette = current.terminal_color_theme;
|
|
31
|
+
el("animation-settings").dataset.terminalPalette = current.terminal_color_theme;
|
|
32
|
+
el("preferences-reset").disabled = busy;el("preferences-restore").disabled = busy;
|
|
33
|
+
el("preferences-backup").hidden = !base.backup;
|
|
34
|
+
el("preferences-backup-time").textContent = base.backup ? time(base.backup.created_at, { date: true }) : "";
|
|
35
|
+
el("preferences-manual").hidden = current.auto_save_settings && !conflict;
|
|
36
|
+
el("preferences-save").disabled = !count || busy || conflict;el("preferences-discard").disabled = (!count && !conflict) || busy;
|
|
37
|
+
label("preferences-manual-note", conflict ? "preferences_conflict" : count ? "preferences_unsaved" : "preferences_manual", { count });
|
|
38
|
+
globalThis.ccdxIcons.set(el("preferences-status"), busy ? "saving" : error ? "preferences_failed" : count ? "preferences_unsaved" : "preferences_saved",
|
|
39
|
+
error ? "warning" : busy || count ? "unknown" : "ok", { count });
|
|
40
|
+
el("preferences-retry").hidden = !error || conflict || busy;
|
|
41
|
+
el("preferences-error").parentElement.hidden = !error;
|
|
42
|
+
if (!error) el("preferences-error").textContent = "";
|
|
43
|
+
else label("preferences-error", error);
|
|
44
|
+
el("save-animation").hidden = true;
|
|
45
|
+
if (appearance) theme()?.preview(appearance);
|
|
46
|
+
if (appearance) label("web-color-note", "preferences_appearance_preview");
|
|
47
|
+
else theme()?.sync();
|
|
48
|
+
label("terminal-color-note", Object.hasOwn(draft, "terminal_color_theme") ? "preferences_terminal_preview"
|
|
49
|
+
: terminalMode === "status" ? "terminal_theme_applied" : "terminal_theme_unavailable");
|
|
50
|
+
if (draft.terminal_animation) {
|
|
51
|
+
for (const row of document.querySelectorAll("#animation-options [data-theme]")) row.setAttribute("aria-pressed", String(row.dataset.theme === draft.terminal_animation));
|
|
52
|
+
}
|
|
53
|
+
selectAnimation(current.terminal_animation);
|
|
54
|
+
}
|
|
55
|
+
function sync(data, { readVersion } = {}) {
|
|
56
|
+
if (!data.preferences) return;
|
|
57
|
+
terminalMode = data.terminal?.mode;
|
|
58
|
+
if (readVersion !== undefined && readVersion !== version || pending) { render();return; }
|
|
59
|
+
const next = data.preferences;
|
|
60
|
+
locks.terminal_animation_enabled = data.effective?.terminal_animation_enabled?.locked;
|
|
61
|
+
if (base) for (const key of Object.keys(draft)) {
|
|
62
|
+
if (next.values[key] === draft[key]) delete draft[key];
|
|
63
|
+
else if (next.values[key] !== base.values[key]) { conflict = true;error = "preferences_changed"; }
|
|
64
|
+
}
|
|
65
|
+
base = next;
|
|
66
|
+
if (!appearance) { try { appearanceBase = theme()?.read(); } catch { appearanceBase = theme()?.snapshot(); } }
|
|
67
|
+
try {
|
|
68
|
+
const backup = browserBackup(), retained = backup.entries.filter(entry => entry.id === base.backup?.id);
|
|
69
|
+
if (retained.length && backup.entries.length > 1) localStorage.setItem(backupKey, JSON.stringify({ version: 1, entries: retained }));
|
|
70
|
+
} catch { /* A damaged browser backup is reported if it is used, not erased. */ }
|
|
71
|
+
render();
|
|
72
|
+
}
|
|
73
|
+
function schedule() {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
if (base?.values.auto_save_settings && !error) timer = setTimeout(() => { void save(); }, 300);
|
|
76
|
+
}
|
|
77
|
+
function edit(key, value) {
|
|
78
|
+
if (!base) return;
|
|
79
|
+
if (value === base.values[key]) delete draft[key];else draft[key] = value;
|
|
80
|
+
if (!conflict) error = null;render();schedule();
|
|
81
|
+
}
|
|
82
|
+
async function commit(values, { local = appearance, action = "preferences", backup_id, revision = base?.revision } = {}) {
|
|
83
|
+
if (pending || !base || conflict) return;
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
const captured = { ...values }, capturedLocal = local ? { ...local } : null;
|
|
86
|
+
resetting = action !== "preferences";
|
|
87
|
+
error = null;
|
|
88
|
+
const operation = (async () => {
|
|
89
|
+
try {
|
|
90
|
+
if (capturedLocal && appearanceBase && !same(theme().read(), appearanceBase)) throw Error("preferences_browser_changed");
|
|
91
|
+
const data = action !== "preferences" || Object.keys(captured).length
|
|
92
|
+
? await api({ action, revision, ...(action === "preferences" ? { values: captured } : { backup_id }) }) : null;
|
|
93
|
+
if (data) { base = data.preferences;version++; }
|
|
94
|
+
for (const [key, value] of Object.entries(captured)) if (draft[key] === value) delete draft[key];
|
|
95
|
+
if (capturedLocal) {
|
|
96
|
+
if (!theme().persist(capturedLocal)) throw Error("preferences_browser_failed");
|
|
97
|
+
appearanceBase = capturedLocal;
|
|
98
|
+
if (same(appearance, capturedLocal)) appearance = null;
|
|
99
|
+
}
|
|
100
|
+
if (data) applied(data);
|
|
101
|
+
if (Object.hasOwn(captured, "terminal_animation") || action !== "preferences") refreshAnimation();
|
|
102
|
+
return data || { preferences: base };
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
error = cause.code === "ccdx_settings_changed" ? "preferences_changed"
|
|
105
|
+
: ["preferences_browser_failed", "preferences_browser_changed"].includes(cause.message) ? cause.message : "preferences_failed";
|
|
106
|
+
conflict = error === "preferences_changed" || error === "preferences_browser_changed";
|
|
107
|
+
}
|
|
108
|
+
})();
|
|
109
|
+
pending = operation;render();
|
|
110
|
+
try { return await operation; }
|
|
111
|
+
finally { pending = null;resetting = false;render();if (!error && dirty() && base.values.auto_save_settings) schedule(); }
|
|
112
|
+
}
|
|
113
|
+
function save() { if (dirty()) return commit(draft); }
|
|
114
|
+
async function discard() {
|
|
115
|
+
clearTimeout(timer);if (pending) return;
|
|
116
|
+
try {
|
|
117
|
+
const data = await api();draft = {};appearance = null;error = null;conflict = false;
|
|
118
|
+
appearanceBase = theme().read();theme().preview(appearanceBase);base = data.preferences;version++;applied(data);refreshAnimation();render();
|
|
119
|
+
} catch { error = "preferences_failed";render(); }
|
|
120
|
+
}
|
|
121
|
+
function open(kind) {
|
|
122
|
+
if (!base || pending) return;
|
|
123
|
+
dialog = kind;dialogRevision = base.revision;
|
|
124
|
+
label("preferences-dialog-title", `preferences_${kind}_question`);
|
|
125
|
+
label("preferences-dialog-intro", `preferences_${kind}_intro`, { count: dirty() });
|
|
126
|
+
label("preferences-dialog-confirm", `preferences_${kind}_confirm`);
|
|
127
|
+
el("preferences-dialog-scope").hidden = !["reset", "restore"].includes(kind);
|
|
128
|
+
if (kind === "reset") label("preferences-dialog-note", dirty() ? "preferences_draft_discard" : "preferences_backup_latest");
|
|
129
|
+
else { el("preferences-dialog-note").textContent = "";el("preferences-dialog-note").removeAttribute("data-i18n"); }
|
|
130
|
+
el("preferences-dialog").showModal();
|
|
131
|
+
}
|
|
132
|
+
async function confirmed() {
|
|
133
|
+
const kind = dialog;el("preferences-dialog").close();
|
|
134
|
+
if (kind === "enable") { draft.auto_save_settings = true;await save();return; }
|
|
135
|
+
if (kind === "nightly") { edit("nightly_updates", true);return; }
|
|
136
|
+
if (kind === "restore" || kind === "reset") {
|
|
137
|
+
let local, id = base.backup?.id;
|
|
138
|
+
try {
|
|
139
|
+
const backup = browserBackup();
|
|
140
|
+
if (kind === "reset") {
|
|
141
|
+
id = crypto.randomUUID();local = { theme: "dark", palette: "green" };
|
|
142
|
+
const previous = { id, values: theme().read() };
|
|
143
|
+
localStorage.setItem(backupKey, JSON.stringify({ version: 1, entries: [previous, ...backup.entries].slice(0, 2) }));
|
|
144
|
+
} else {
|
|
145
|
+
local = backup.entries.find(entry => entry.id === id)?.values;
|
|
146
|
+
if (!local) throw Error("preferences_browser_backup_missing");
|
|
147
|
+
}
|
|
148
|
+
} catch (cause) { error = cause.message === "preferences_browser_backup_missing" ? cause.message : "preferences_browser_backup_invalid";render();return; }
|
|
149
|
+
if (conflict) { error = "preferences_changed";render();return; }
|
|
150
|
+
const oldDraft = draft, oldAppearance = appearance;
|
|
151
|
+
draft = {};appearance = local;
|
|
152
|
+
const data = await commit({}, { action: `${kind === "reset" ? "reset" : "restore"}_preferences`, backup_id: id, local, revision: dialogRevision });
|
|
153
|
+
if (data) { theme().preview(local);appearance = null; }
|
|
154
|
+
else if (error === "preferences_browser_failed") appearance = local;
|
|
155
|
+
else { draft = oldDraft;appearance = oldAppearance; }
|
|
156
|
+
render();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const [key, id] of Object.entries(fields)) el(id).addEventListener("change", () => {
|
|
160
|
+
const node = el(id), value = node.type === "checkbox" ? node.checked : node.value;
|
|
161
|
+
if (key === "nightly_updates" && value) { node.checked = false;open("nightly");return; }
|
|
162
|
+
edit(key, value);
|
|
163
|
+
});
|
|
164
|
+
function appearanceChanged() {
|
|
165
|
+
if (!base) return false;
|
|
166
|
+
appearance = same(theme().snapshot(), appearanceBase) ? null : theme().snapshot();
|
|
167
|
+
if (!conflict) error = null;render();schedule();return true;
|
|
168
|
+
}
|
|
169
|
+
el("preferences-auto").addEventListener("change", async () => {
|
|
170
|
+
if (el("preferences-auto").checked && dirty()) { el("preferences-auto").checked = false;open("enable");return; }
|
|
171
|
+
const value = el("preferences-auto").checked;
|
|
172
|
+
draft.auto_save_settings = value;
|
|
173
|
+
const result = await commit({ auto_save_settings: value }, { local: null });
|
|
174
|
+
if (!result) { delete draft.auto_save_settings;render(); }
|
|
175
|
+
});
|
|
176
|
+
el("preferences-save").addEventListener("click", () => { void save(); });
|
|
177
|
+
el("preferences-discard").addEventListener("click", () => { void discard(); });
|
|
178
|
+
el("preferences-retry").addEventListener("click", async () => {
|
|
179
|
+
if (retrying || pending) return;
|
|
180
|
+
const wasError = error;error = null;
|
|
181
|
+
retrying = true;render();
|
|
182
|
+
try { sync(await api());retrying = false;if (!conflict) await save(); } catch { error = wasError; }
|
|
183
|
+
finally { retrying = false;render(); }
|
|
184
|
+
});
|
|
185
|
+
el("preferences-reset").addEventListener("click", () => open("reset"));el("preferences-restore").addEventListener("click", () => open("restore"));
|
|
186
|
+
el("preferences-dialog-cancel").addEventListener("click", () => el("preferences-dialog").close());
|
|
187
|
+
el("preferences-dialog-confirm").addEventListener("click", () => { void confirmed(); });
|
|
188
|
+
globalThis.addEventListener("beforeunload", event => { if (dirty()) { event.preventDefault();event.returnValue = ""; } });
|
|
189
|
+
return { sync, render, appearanceChanged, selectAnimation: value => edit("terminal_animation", value),
|
|
190
|
+
externalAppearance() { if (!appearance) return false;conflict = true;error = "preferences_browser_changed";render();return true; },
|
|
191
|
+
get version() { return version; }, get busy() { return Boolean(pending || retrying); } };
|
|
192
|
+
}
|
|
193
|
+
globalThis.ccdxDashboardPreferences = { create };
|
|
194
|
+
})();
|
package/src/dashboard/status.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator }) {
|
|
3
|
+
const visible = node => !node?.closest?.('[data-view]')?.hidden;
|
|
4
|
+
const writeText = text;
|
|
5
|
+
text = (id, ...args) => { if (visible(element(id))) writeText(id, ...args); };
|
|
3
6
|
let contextRequests = [];
|
|
4
7
|
let contextCompactions = {};
|
|
5
8
|
let failureSignature;
|
|
@@ -87,6 +90,7 @@
|
|
|
87
90
|
}
|
|
88
91
|
|
|
89
92
|
function renderFailures(recent, recentRequests = []) {
|
|
93
|
+
if (!visible(element("failures"))) return;
|
|
90
94
|
const signature = JSON.stringify([element("failure-kind")?.value, recent, recentRequests]);
|
|
91
95
|
if (signature === failureSignature) return;
|
|
92
96
|
failureSignature = signature;
|
|
@@ -200,6 +204,14 @@
|
|
|
200
204
|
}
|
|
201
205
|
|
|
202
206
|
function render(data) {
|
|
207
|
+
if (data.scope === "summary") {
|
|
208
|
+
globalThis.ccdxDashboardActivity?.update(data.model_activity);
|
|
209
|
+
text("version", `v${data.version || "?"}`);
|
|
210
|
+
text("uptime", "pid_pid_uptime_duration", { pid: number(data.pid), duration: duration(data.uptime_ms) });
|
|
211
|
+
renderRuntimeUsage(data);
|
|
212
|
+
text("updated", "snapshot_time", { time: time(Date.now()) });
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
203
215
|
for (const source of data.providers?.connections?.providers || []) sourceNames.set(source.id, source.name);
|
|
204
216
|
globalThis.ccdxConnections?.updateMemory?.(data.providers?.connections);
|
|
205
217
|
globalThis.ccdxDashboardActivity?.update(data.model_activity);
|
|
@@ -237,7 +249,7 @@
|
|
|
237
249
|
const used = Number(history.bytes || 0);
|
|
238
250
|
text("history", `${mib(used)} / ${mib(limit)}`);
|
|
239
251
|
text("history-detail", "entries_entries_trees_trees_misses_misses_evicted_evicted", { entries: number(history.entries), trees: number(history.tree_count), misses: number(history.lookup_misses), evicted: number(history.evicted_lookup_misses) });
|
|
240
|
-
element("history-meter").value = limit > 0 ? Math.min(100, Math.max(0, used / limit * 100)) : 0;
|
|
252
|
+
if (visible(element("history-meter"))) element("history-meter").value = limit > 0 ? Math.min(100, Math.max(0, used / limit * 100)) : 0;
|
|
241
253
|
|
|
242
254
|
const image = data.image_generation;
|
|
243
255
|
text("image", image ? "count_succeeded" : "not_initialized", { count: number(image?.succeeded) });
|
|
@@ -248,7 +260,7 @@
|
|
|
248
260
|
const claude = data.providers?.claude || data.providers?.m365?.claude, claudeMetrics = claude?.requests?.performance;
|
|
249
261
|
percentiles("claude-ttft-percentiles", claudeMetrics?.by_route?.messages?.ttft_ms);
|
|
250
262
|
const sourceBody = element("source-requests-body");
|
|
251
|
-
if (sourceBody) {
|
|
263
|
+
if (sourceBody && visible(sourceBody)) {
|
|
252
264
|
sourceBody.replaceChildren();
|
|
253
265
|
const routes = { ...data.stream_performance?.by_route, ...claudeMetrics?.by_route };
|
|
254
266
|
for (const [protocol, route] of Object.entries(routes)) for (const [source, stats] of Object.entries(route.by_provider || {})) {
|
|
@@ -269,7 +281,7 @@
|
|
|
269
281
|
const kind = element("failure-kind")?.value || "issues";
|
|
270
282
|
renderFailures(issueGroups[kind] || [], kind === "issues" ? recentRequests : []);
|
|
271
283
|
renderContext({ ...data.stream_performance, recent_requests: recentRequests });
|
|
272
|
-
if (element("claude-route")) {
|
|
284
|
+
if (element("claude-route") && visible(element("claude-route"))) {
|
|
273
285
|
element("claude-route").textContent = claude?.base_url || "—";
|
|
274
286
|
const clientState = value => ({ configured: "configured", restored: "settings_restored", preserved: "existing_settings_kept", partially_preserved: "existing_settings_kept",
|
|
275
287
|
not_installed: "not_installed", configuration_unavailable: "setup_unavailable" })[value] || "unknown";
|
|
@@ -280,27 +292,32 @@
|
|
|
280
292
|
text(id, metric?.samples > 0 ? `${Number(metric.avg).toFixed(1)} ${unit} / ${metric.samples}` : "—");
|
|
281
293
|
}
|
|
282
294
|
}
|
|
283
|
-
|
|
295
|
+
renderRuntimeUsage(data);
|
|
296
|
+
if (element("prediction-preference") && visible(element("prediction-preference"))) {
|
|
297
|
+
const prediction = data.client_integrations?.prediction;
|
|
298
|
+
text("prediction-preference", prediction ? prediction.configured ? "configured" : "not_configured" : "unknown");
|
|
299
|
+
text("prediction-bridge", ({ running: "running_f4cca", recovering: "recovering", stopped: "stopped", unavailable: "unavailable_ca184" })[prediction?.bridge] || "unknown");
|
|
300
|
+
text("prediction-route", prediction?.client_route === "observed" ? "observed" : "unknown");
|
|
301
|
+
text("prediction-candidate", "unknown");
|
|
302
|
+
const note = element("prediction-note");
|
|
303
|
+
if (note) note.textContent = prediction?.reason || "";
|
|
304
|
+
}
|
|
305
|
+
text("updated", "snapshot_time", { time: time(Date.now()) });
|
|
306
|
+
}
|
|
307
|
+
function renderRuntimeUsage(data) {
|
|
308
|
+
if (element("runtime-usage") && visible(element("runtime-usage"))) {
|
|
284
309
|
const usage = data.runtime_usage;
|
|
285
310
|
text("runtime-usage", usage ? "records_usage_records_input_input_cache_read_cached_output_outpu" : "—",
|
|
286
311
|
usage ? { records: number(usage.records), input: number(usage.input_tokens), cached: number(usage.cached_input_tokens), output: number(usage.output_tokens), partial: usage.partial_records ? " ~" : "" } : {});
|
|
287
312
|
const rate = usage?.cache_hit_rate;
|
|
288
313
|
text("runtime-cache-hit", Number.isFinite(rate) && rate >= 0 && rate <= 1 ? `${usage.cache_hit_rate_partial ? "~" : ""}${(rate * 100).toFixed(1)}%` : "—");
|
|
314
|
+
}
|
|
315
|
+
if (element("process-state") && visible(element("process-state"))) {
|
|
289
316
|
element("process-state").textContent = `PID ${data.pid || "—"} / ${globalThis.location?.origin || ""}`;
|
|
290
317
|
text("process-memory", "rss_rss_heap_heap", { rss: mib(data.process?.rss_bytes), heap: mib(data.process?.heap_used_bytes) });
|
|
291
318
|
text("process-queues", "codex_body_admission_active_active_queued_queued_queue_limit_lim", {
|
|
292
319
|
active: number(data.admission?.activeRequests), queued: number(data.admission?.queued), limit: number(data.admission?.maxQueued) });
|
|
293
320
|
}
|
|
294
|
-
if (element("prediction-preference")) {
|
|
295
|
-
const prediction = data.client_integrations?.prediction;
|
|
296
|
-
text("prediction-preference", prediction ? prediction.configured ? "configured" : "not_configured" : "unknown");
|
|
297
|
-
text("prediction-bridge", ({ running: "running_f4cca", recovering: "recovering", stopped: "stopped", unavailable: "unavailable_ca184" })[prediction?.bridge] || "unknown");
|
|
298
|
-
text("prediction-route", prediction?.client_route === "observed" ? "observed" : "unknown");
|
|
299
|
-
text("prediction-candidate", "unknown");
|
|
300
|
-
const note = element("prediction-note");
|
|
301
|
-
if (note) note.textContent = prediction?.reason || "";
|
|
302
|
-
}
|
|
303
|
-
text("updated", "snapshot_time", { time: time(Date.now()) });
|
|
304
321
|
}
|
|
305
322
|
|
|
306
323
|
function renderContext(performance) {
|
|
@@ -309,7 +326,7 @@
|
|
|
309
326
|
contextCompactions = performance?.by_route?.responses_compact?.terminal_outcomes?.totals || {};
|
|
310
327
|
}
|
|
311
328
|
const body = element("context-body");
|
|
312
|
-
if (!body) return;
|
|
329
|
+
if (!body || !visible(body)) return;
|
|
313
330
|
text("context-note", "20_latest_finished_requests_compactions_completed_completed_inco", {
|
|
314
331
|
completed: number(contextCompactions.completed), incomplete: number(contextCompactions.incomplete), failed: number(contextCompactions.failed),
|
|
315
332
|
});
|
package/src/dashboard/theme.js
CHANGED
|
@@ -24,10 +24,11 @@
|
|
|
24
24
|
document.getElementById("favicon").href = `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
|
25
25
|
};
|
|
26
26
|
applyTheme();
|
|
27
|
-
function persist() {
|
|
28
|
-
try { localStorage.setItem(key, theme);localStorage.setItem(paletteKey, palette);saved = true; }
|
|
27
|
+
function persist(values = { theme, palette }) {
|
|
28
|
+
try { localStorage.setItem(key, values.theme);localStorage.setItem(paletteKey, values.palette);saved = true; }
|
|
29
29
|
catch { saved = false; }
|
|
30
30
|
sync();
|
|
31
|
+
return saved;
|
|
31
32
|
}
|
|
32
33
|
document.addEventListener("DOMContentLoaded", () => {
|
|
33
34
|
const button = document.getElementById("theme-toggle");
|
|
@@ -47,10 +48,16 @@
|
|
|
47
48
|
document.getElementById("web-color-theme")?.addEventListener("change", event => {
|
|
48
49
|
if (!valid(event.target.value)) return;
|
|
49
50
|
palette = event.target.value;applyTheme();
|
|
50
|
-
persist();
|
|
51
|
+
if (!globalThis.ccdxSettingsPreferences?.appearanceChanged()) persist();
|
|
51
52
|
});
|
|
53
|
+
globalThis.ccdxDashboardTheme = {
|
|
54
|
+
snapshot: () => ({ theme, palette }), persist, sync,
|
|
55
|
+
read: () => ({ theme: localStorage.getItem(key) === "light" ? "light" : "dark", palette: valid(localStorage.getItem(paletteKey)) ? localStorage.getItem(paletteKey) : "green" }),
|
|
56
|
+
preview(values) { if (["light", "dark"].includes(values.theme)) theme = values.theme;if (valid(values.palette)) palette = values.palette;applyTheme();updateLabel();sync(); },
|
|
57
|
+
};
|
|
52
58
|
globalThis.addEventListener?.("storage", event => {
|
|
53
59
|
if (event.key !== paletteKey && event.key !== key) return;
|
|
60
|
+
if (globalThis.ccdxSettingsPreferences?.externalAppearance()) return;
|
|
54
61
|
if (event.key === paletteKey) palette = valid(event.newValue) ? event.newValue : "green";
|
|
55
62
|
else theme = event.newValue === "light" ? "light" : "dark";
|
|
56
63
|
applyTheme();updateLabel();sync();
|
package/src/dashboard/ui.css
CHANGED
|
@@ -553,3 +553,22 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
553
553
|
.memory-model-value .hint { margin:0; }
|
|
554
554
|
.memory-model-value { min-width:0;max-width:100%; }
|
|
555
555
|
.memory-model-value strong { min-width:0;overflow-wrap:anywhere; }
|
|
556
|
+
|
|
557
|
+
/* Settings-page preferences keep their own draft, save and recovery controls. */
|
|
558
|
+
.preferences-status { color:var(--muted); font-size:11px; }
|
|
559
|
+
.preferences-row { display:flex; align-items:center; justify-content:space-between; gap:20px; padding:20px 0; font-size:13px; }
|
|
560
|
+
.preferences-row:last-of-type { padding-bottom:0; }
|
|
561
|
+
.preferences-row .hint { margin-top:5px; }
|
|
562
|
+
.preferences-row input[role="switch"] { flex:none; }
|
|
563
|
+
.preferences-separator { border-top:1px solid var(--border); margin-top:14px; }
|
|
564
|
+
#preferences-backup-time { margin-bottom:0; }
|
|
565
|
+
#preferences-error { margin:0; color:var(--failed); }
|
|
566
|
+
#preferences-save, #preferences-dialog-confirm { background:var(--accent); color:var(--page); border-color:var(--accent); }
|
|
567
|
+
.preferences-dialog { width:480px; max-width:calc(100% - 32px); padding:25px; border:1px solid var(--border); border-radius:2px; background:var(--surface); color:var(--text); font:inherit; }
|
|
568
|
+
.preferences-dialog::backdrop { background:#0007; }
|
|
569
|
+
.preferences-dialog h2 { font-size:19px; margin:0 0 18px; color:var(--strong); }
|
|
570
|
+
.preferences-dialog p, .preferences-dialog dl { font-size:12px; line-height:1.8; }
|
|
571
|
+
.preferences-dialog dl > div { display:grid; grid-template-columns:80px minmax(0,1fr); gap:12px; margin-top:12px; }
|
|
572
|
+
.preferences-dialog dt { color:var(--muted); }.preferences-dialog dd { margin:0; }
|
|
573
|
+
.preferences-dialog .section-actions { justify-content:flex-end; margin-top:24px; }
|
|
574
|
+
@media(max-width:640px) { .preferences-row { gap:14px; flex-wrap:wrap; }.preferences-row > div:first-child { flex:1; min-width:150px; }.preferences-dialog { padding:20px; }.preferences-dialog dl > div { grid-template-columns:1fr; gap:3px; } }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -23,7 +23,9 @@ const usageView = globalThis.ccdxViewBoundary.create("usage-analytics", () => gl
|
|
|
23
23
|
const { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay } = usageView;
|
|
24
24
|
const loadAuth = () => dashboardRefresh.refresh("auth", { force: true });
|
|
25
25
|
|
|
26
|
-
const
|
|
26
|
+
const statusResourceKey = () => ["codex", "claude", "models", "usage", "requests", "checks"].includes((globalThis.location?.hash || "").slice(1)) ? "status" : "status-summary";
|
|
27
|
+
const refreshStatus = () => dashboardRefresh.refresh(statusResourceKey(), { force: true });
|
|
28
|
+
const refresh = refreshStatus;
|
|
27
29
|
|
|
28
30
|
function animateRefresh() {
|
|
29
31
|
const icon = element("status-icon");
|
|
@@ -39,7 +41,7 @@ element("refresh").addEventListener("click", () => {
|
|
|
39
41
|
|
|
40
42
|
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
|
41
43
|
const animationView = globalThis.ccdxViewBoundary.create("animation-settings", () => globalThis.ccdxDashboardAnimation.create({ element, phrase, localize, text, reducedMotion,
|
|
42
|
-
getRefresh: () => dashboardRefresh, document }), ["apply", "load", "save", "sync", "stop"]);
|
|
44
|
+
getRefresh: () => dashboardRefresh, document }), ["apply", "load", "save", "sync", "stop", "select"]);
|
|
43
45
|
const { apply: applyAnimation, load: loadAnimation, save: saveAnimation, sync: syncAnimationPreview, stop: stopAnimationPreview } = animationView;
|
|
44
46
|
reducedMotion.addEventListener("change", () => { if (reducedMotion.matches) usageView.stopMotion(); });
|
|
45
47
|
document.addEventListener("visibilitychange", () => { if (document.visibilityState !== "visible") usageView.stopMotion(); });
|
|
@@ -234,6 +236,16 @@ for (const [key, ids] of [["auth", ["account-authorization", "client-features",
|
|
|
234
236
|
}
|
|
235
237
|
|
|
236
238
|
const updateView = globalThis.ccdxDashboardUpdates.create(viewHelpers);
|
|
239
|
+
function statusState(state) {
|
|
240
|
+
if (state.error || !state.value) globalThis.ccdxDashboardActivity?.unavailable();
|
|
241
|
+
if ((state.error || !state.value) && statusResourceKey() === "status") globalThis.ccdxDashboardFlow?.unavailable();
|
|
242
|
+
text("connection", state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable");
|
|
243
|
+
element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
|
|
244
|
+
globalThis.ccdxIcons?.set(element("connection"), state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable",
|
|
245
|
+
state.pending && !state.value ? "unknown" : state.error ? "unavailable" : "running");
|
|
246
|
+
if (state.error) refreshTime(element("updated"), state);
|
|
247
|
+
for (const node of timestamps.get("status")) refreshTime(node, state);
|
|
248
|
+
}
|
|
237
249
|
const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
238
250
|
visible: () => document.visibilityState === "visible",
|
|
239
251
|
onState: ({ pendingKeys }) => {
|
|
@@ -250,23 +262,24 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
|
250
262
|
state: updateView.state,
|
|
251
263
|
},
|
|
252
264
|
status: {
|
|
253
|
-
visible: () =>
|
|
265
|
+
visible: () => statusResourceKey() === "status",
|
|
254
266
|
load: async ({ signal }) => {
|
|
255
267
|
const data = await readDashboard("/_ccdx/status", { signal, timeout: 5000 });
|
|
256
268
|
if (data.ok !== true || data.name !== "codex-copilot-dx") throw new Error("Unexpected status response");
|
|
257
269
|
return data;
|
|
258
270
|
},
|
|
259
|
-
apply: render,
|
|
260
|
-
state: state => {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
for (const node of timestamps.get("status")) refreshTime(node, state);
|
|
271
|
+
apply: data => { if (statusResourceKey() === "status") render(data); },
|
|
272
|
+
state: state => { if (statusResourceKey() === "status") statusState(state); },
|
|
273
|
+
},
|
|
274
|
+
"status-summary": {
|
|
275
|
+
visible: () => statusResourceKey() === "status-summary",
|
|
276
|
+
load: async ({ signal }) => {
|
|
277
|
+
const data = await readDashboard("/_ccdx/status?scope=summary", { signal, timeout: 5000 });
|
|
278
|
+
if (data.ok !== true || data.name !== "codex-copilot-dx") throw new Error("Unexpected status response");
|
|
279
|
+
return data;
|
|
269
280
|
},
|
|
281
|
+
apply: data => { if (statusResourceKey() === "status-summary") render(data); },
|
|
282
|
+
state: state => { if (statusResourceKey() === "status-summary") statusState(state); },
|
|
270
283
|
},
|
|
271
284
|
auth: {
|
|
272
285
|
visible: () => true,
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -221,7 +221,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
221
221
|
if (!res.destroyed && !res.writableEnded) sendJson(res, 200, data);
|
|
222
222
|
} catch (error) {
|
|
223
223
|
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300),
|
|
224
|
-
...(/^m365_[a-z_]
|
|
224
|
+
...(/^(?:m365_[a-z_]+|ccdx_settings_[a-z_]+)$/.test(error.code || "") ? { code: error.code } : {}) });
|
|
225
225
|
} finally { abort.cleanup(); }
|
|
226
226
|
return;
|
|
227
227
|
}
|
package/src/dashboard.mjs
CHANGED
|
@@ -12,6 +12,7 @@ const ASSETS = new Map([
|
|
|
12
12
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
13
13
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
14
14
|
["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
|
|
15
|
+
["/preferences.js", ["./dashboard/preferences.js", "text/javascript; charset=utf-8"]],
|
|
15
16
|
["/time.js", ["./dashboard/time.js", "text/javascript; charset=utf-8"]],
|
|
16
17
|
["/view-boundary.js", ["./dashboard/view-boundary.js", "text/javascript; charset=utf-8"]],
|
|
17
18
|
["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
|
|
@@ -3,6 +3,7 @@ import { ADAPTER_CACHE_PATH, cacheRuntimeSnapshot, cleanRuntimeCaches, setHistor
|
|
|
3
3
|
import { createRequestAbort, readJsonBody, sendJsonError } from "./http-transport.mjs";
|
|
4
4
|
import { httpError } from "./http-errors.mjs";
|
|
5
5
|
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
6
|
+
import { statusSummary } from "./status-summary.mjs";
|
|
6
7
|
|
|
7
8
|
export function isManagementRoute(method, pathname) {
|
|
8
9
|
return (method === "GET" && [ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname))
|
|
@@ -21,7 +22,8 @@ export function createManagementHandler({ statusSnapshot, nativePredictionPac, f
|
|
|
21
22
|
return;
|
|
22
23
|
}
|
|
23
24
|
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
24
|
-
|
|
25
|
+
const snapshot = statusSnapshot();
|
|
26
|
+
res.end(JSON.stringify(new URL(req.url, "http://localhost").searchParams.get("scope") === "summary" ? statusSummary(snapshot) : snapshot));
|
|
25
27
|
return;
|
|
26
28
|
}
|
|
27
29
|
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/tools.js", "/connections.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", "/_ccdx/ui/connections"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import { m365NetworkMessage } from "./providers/m365-network-diagnostic.mjs";
|
|
|
14
14
|
import { createConnectionRuntime } from "./connection-runtime.mjs";
|
|
15
15
|
import { accessSettingsPath, readAccessSettings } from "./access-settings.mjs";
|
|
16
16
|
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
17
|
+
import { M365_API_HOST } from "./providers/m365-endpoint.mjs";
|
|
17
18
|
|
|
18
19
|
const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
|
|
19
20
|
{ code: reason, statusCode: 503 });
|
|
@@ -250,7 +251,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
250
251
|
if (closed || !enabled || source !== m365 || changingAccount) throw unavailable("m365_refresh_cancelled");
|
|
251
252
|
reason = null;
|
|
252
253
|
const eligible = new Set([...source.models("gpt"), ...source.models("claude")]);
|
|
253
|
-
return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost:
|
|
254
|
+
return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: M365_API_HOST,
|
|
254
255
|
advertised: m365.catalog().length, models: publicModelCatalog(m365.catalog(), {
|
|
255
256
|
selectable: model => eligible.has(model),
|
|
256
257
|
clients: model => !eligible.has(model) ? [] : model.publisher?.toLowerCase() === "anthropic" ? ["claude_code", "claude_app"] : ["codex"],
|
|
@@ -7,16 +7,16 @@ import { createProxyAgent } from "../proxy-tunnel.mjs";
|
|
|
7
7
|
import { loadRuntimeConfig } from "../runtime-config.mjs";
|
|
8
8
|
import { m365HelperEnvironment } from "./m365-auth.mjs";
|
|
9
9
|
import { m365ProxyFailure } from "./m365-network-diagnostic.mjs";
|
|
10
|
+
import { M365_API_HOST as HOST, M365_API_BASE, M365_API_PATH } from "./m365-endpoint.mjs";
|
|
10
11
|
|
|
11
|
-
const
|
|
12
|
-
const targetUrl = new URL(`https://${HOST}/api/v1/llmapi/models`);
|
|
12
|
+
const targetUrl = new URL(`${M365_API_BASE}/models`);
|
|
13
13
|
const fail = code => Object.assign(new Error(`Microsoft 365 network is unavailable (${code})`), { code: `m365_${code}`, statusCode: 503 });
|
|
14
14
|
|
|
15
15
|
export function requestFetch(requestImpl, agent) {
|
|
16
16
|
return (raw, init = {}) => new Promise((resolve, reject) => {
|
|
17
17
|
let url;try { url = new URL(raw); } catch { reject(fail("target_invalid"));return; }
|
|
18
18
|
if (url.protocol !== "https:" || url.hostname !== HOST || url.port || url.username || url.password || url.hash
|
|
19
|
-
|| !url.pathname.startsWith(
|
|
19
|
+
|| !url.pathname.startsWith(`${M365_API_PATH}/`) || !["GET", "POST", "HEAD"].includes(init.method || "GET")) { reject(fail("target_invalid"));return; }
|
|
20
20
|
if (init.signal?.aborted) { reject(init.signal.reason);return; }
|
|
21
21
|
const headers = Object.fromEntries(new Headers(init.headers));
|
|
22
22
|
headers["accept-encoding"] = "identity";
|
package/src/providers/m365.mjs
CHANGED
|
@@ -19,7 +19,8 @@ import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
|
|
|
19
19
|
import { catalogFailure, m365CatalogDiagnostic } from "./m365-catalog-diagnostic.mjs";
|
|
20
20
|
import { m365NetworkDiagnostic } from "./m365-network-diagnostic.mjs";
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
import { M365_API_BASE, M365_API_ORIGIN } from "./m365-endpoint.mjs";
|
|
23
|
+
export { M365_API_BASE } from "./m365-endpoint.mjs";
|
|
23
24
|
const SOFT_TTL_MS = 2 * 60 * 60 * 1000;
|
|
24
25
|
const HARD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
25
26
|
const protocolError = (code, message, statusCode = 400) => Object.assign(new Error(message), {
|
|
@@ -79,7 +80,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
79
80
|
let networkDiagnostic = null, catalogDiagnostic = null;
|
|
80
81
|
const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
|
|
81
82
|
refreshInFlight: false, generation: 0, lastError: null, lastErrorAtMs: null };
|
|
82
|
-
const profile = () => account ? `m365:${m365AccountKey(account)}` : "m365:unavailable";
|
|
83
|
+
const profile = () => account ? `m365:${M365_API_ORIGIN}:${m365AccountKey(account)}` : "m365:unavailable";
|
|
83
84
|
async function transport(signal) {
|
|
84
85
|
if (network?.healthy()) return network.fetch;
|
|
85
86
|
if (!networkFlight) {
|
|
@@ -103,7 +104,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
103
104
|
try {
|
|
104
105
|
account = accountOverride || readM365Account({ home });
|
|
105
106
|
const saved = readM365Json(paths.catalog);
|
|
106
|
-
if (account && saved?.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
|
|
107
|
+
if (account && saved?.service_origin === M365_API_ORIGIN && saved.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
|
|
107
108
|
&& now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at);
|
|
108
109
|
} catch { reason = "m365_cache_unavailable"; }
|
|
109
110
|
|
|
@@ -154,7 +155,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
154
155
|
if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
|
|
155
156
|
const savedAt = now();
|
|
156
157
|
const nextAccount = { ...credential.account, ...(account?.history_isolation ? { history_isolation: true } : {}) };
|
|
157
|
-
if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), saved_at: savedAt, models: value }, { home, expectedAccount: account });
|
|
158
|
+
if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), service_origin: M365_API_ORIGIN, saved_at: savedAt, models: value }, { home, expectedAccount: account });
|
|
158
159
|
account = nextAccount;
|
|
159
160
|
applyCatalog(value, "live", savedAt);catalogDiagnostic = null;state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
|
|
160
161
|
try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
|
|
@@ -252,10 +253,11 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
252
253
|
},
|
|
253
254
|
commitSelection(expectedAccount) {
|
|
254
255
|
if (!catalog || state !== "ready" || !account) throw m365Error("m365_not_ready");
|
|
255
|
-
writeM365Binding(account, { account_key: m365AccountKey(account), saved_at: catalogAt, models: catalog }, { home, expectedAccount });
|
|
256
|
+
writeM365Binding(account, { account_key: m365AccountKey(account), service_origin: M365_API_ORIGIN, saved_at: catalogAt, models: catalog }, { home, expectedAccount });
|
|
256
257
|
persist = true;
|
|
257
258
|
},
|
|
258
259
|
snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
|
|
260
|
+
service_origin: M365_API_ORIGIN,
|
|
259
261
|
network: network?.snapshot() || null,
|
|
260
262
|
network_diagnostic: networkDiagnostic ? { ...networkDiagnostic } : null,
|
|
261
263
|
catalog_diagnostic: m365CatalogDiagnostic(catalogDiagnostic),
|
package/src/service-control.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { readImageProviderConfig } from "./image-provider-config.mjs";
|
|
|
5
5
|
import { readPredictionSettings } from "./native-prediction-profile.mjs";
|
|
6
6
|
import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
|
|
7
7
|
import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
|
|
8
|
+
import { settingsPreferencesSnapshot, writeSettingsPreferences } from "./settings-preferences.mjs";
|
|
8
9
|
|
|
9
10
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
10
11
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
@@ -17,7 +18,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
17
18
|
try { imageConfigured = Boolean(readImages()); } catch {}
|
|
18
19
|
try { predictionConfigured = readPrediction().enabled === true; } catch {}
|
|
19
20
|
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
20
|
-
return { source: "service_settings", saved, theme, color_theme,
|
|
21
|
+
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options),
|
|
21
22
|
nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
|
|
22
23
|
effective: {
|
|
23
24
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
@@ -33,9 +34,16 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
33
34
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
34
35
|
const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
35
36
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
37
|
+
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id"], restore_preferences: ["action", "revision", "backup_id"],
|
|
36
38
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
37
39
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
38
|
-
if (
|
|
40
|
+
if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
|
|
41
|
+
const before = nightlyUpdatePreference(options);
|
|
42
|
+
writeSettingsPreferences(input, options);
|
|
43
|
+
const current = settingsPreferencesSnapshot(options).values;
|
|
44
|
+
terminal?.apply?.({ ...servicePreferences(options), theme: current.terminal_animation, color_theme: current.terminal_color_theme });
|
|
45
|
+
if (before !== current.nightly_updates) nightlyChanged(current.nightly_updates);
|
|
46
|
+
} else if (input.action === "nightly_update") {
|
|
39
47
|
writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
|
|
40
48
|
} else if (input.action === "preference") {
|
|
41
49
|
writeServicePreference(input.key, input.value, options);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readUserSettings, userSettingsPath } from "./user-settings.mjs";
|
|
5
|
+
import { isColorTheme } from "./terminal-colors.mjs";
|
|
6
|
+
import { DEFAULT_TERMINAL_ANIMATION_THEME, isTerminalAnimationTheme } from "./terminal-animation.mjs";
|
|
7
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
8
|
+
import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
9
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
10
|
+
|
|
11
|
+
export const SETTINGS_DEFAULTS = Object.freeze({ terminal_color_theme: "green", terminal_animation: DEFAULT_TERMINAL_ANIMATION_THEME,
|
|
12
|
+
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true });
|
|
13
|
+
const keys = Object.keys(SETTINGS_DEFAULTS);
|
|
14
|
+
const fail = (code, message, statusCode = 409) => Object.assign(new Error(message), { code, statusCode });
|
|
15
|
+
const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
16
|
+
const valuesFor = settings => Object.fromEntries(keys.map(key => [key, key === "terminal_animation" && !isTerminalAnimationTheme(settings[key])
|
|
17
|
+
? SETTINGS_DEFAULTS[key] : settings[key] ?? SETTINGS_DEFAULTS[key]]));
|
|
18
|
+
const revisionFor = values => createHash("sha256").update(JSON.stringify(keys.map(key => values[key]))).digest("hex");
|
|
19
|
+
export const settingsBackupPath = options => path.join(path.dirname(userSettingsPath(options)), "settings-preferences-backup.json");
|
|
20
|
+
|
|
21
|
+
function checkedValues(values) {
|
|
22
|
+
if (!values || typeof values !== "object" || Array.isArray(values) || Object.keys(values).some(key => !keys.includes(key)
|
|
23
|
+
|| (key === "terminal_color_theme" ? !isColorTheme(values[key]) : key === "terminal_animation" ? !isTerminalAnimationTheme(values[key]) : typeof values[key] !== "boolean"))) {
|
|
24
|
+
throw fail("ccdx_settings_values_invalid", "Choose valid settings on this page", 400);
|
|
25
|
+
}
|
|
26
|
+
return values;
|
|
27
|
+
}
|
|
28
|
+
function readBackup(options) {
|
|
29
|
+
try {
|
|
30
|
+
const value = JSON.parse(readBoundedFileSync(settingsBackupPath(options), { encoding: "utf8", maxBytes: 8192 }));
|
|
31
|
+
if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
|
|
32
|
+
|| Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
|
|
33
|
+
|| keys.some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
|
|
34
|
+
checkedValues(value.values);return value;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error.code === "ENOENT") return null;
|
|
37
|
+
throw fail("ccdx_settings_backup_invalid", "The settings backup could not be read; existing files were preserved");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function settingsPreferencesSnapshot(options = {}) {
|
|
41
|
+
const values = valuesFor(readUserSettings({ ...options, strict: true }));
|
|
42
|
+
let backup = null, backup_error = null;
|
|
43
|
+
try { const saved = readBackup(options);if (saved) backup = { id: saved.id, created_at: saved.created_at }; }
|
|
44
|
+
catch (error) { backup_error = error.code; }
|
|
45
|
+
return { values, defaults: SETTINGS_DEFAULTS, revision: revisionFor(values), backup, backup_error };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Only this page's preferences enter its backup. Routing, auth, business flags
|
|
49
|
+
// and unknown settings are retained in the current file, never copied here.
|
|
50
|
+
export function writeSettingsPreferences(input, options = {}) {
|
|
51
|
+
const file = userSettingsPath(options);
|
|
52
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
53
|
+
return withFileLockSync(`${file}.lock`, () => {
|
|
54
|
+
const current = readUserSettings({ ...options, strict: true }), before = valuesFor(current);
|
|
55
|
+
const backup = input.action === "preferences" ? null : readBackup(options);
|
|
56
|
+
if (input.action === "reset_preferences" && backup?.id === input.backup_id && revisionFor(before) === revisionFor(SETTINGS_DEFAULTS)) return;
|
|
57
|
+
if (typeof input.revision !== "string" || input.revision !== revisionFor(before)) {
|
|
58
|
+
throw fail("ccdx_settings_changed", "Settings changed elsewhere. Review the current settings before saving again");
|
|
59
|
+
}
|
|
60
|
+
let values;
|
|
61
|
+
if (input.action === "preferences") values = checkedValues(input.values);
|
|
62
|
+
else {
|
|
63
|
+
if (!idValid(input.backup_id)) throw fail("ccdx_settings_backup_invalid", "Choose the current settings backup", 400);
|
|
64
|
+
if (input.action === "restore_preferences") {
|
|
65
|
+
if (!backup || input.backup_id !== backup.id) throw fail("ccdx_settings_changed", "The settings backup changed. Review it before restoring");
|
|
66
|
+
values = backup.values;
|
|
67
|
+
} else if (input.action === "reset_preferences") values = SETTINGS_DEFAULTS;
|
|
68
|
+
else throw fail("ccdx_settings_action_invalid", "Unknown settings action", 400);
|
|
69
|
+
}
|
|
70
|
+
const next = { ...current, ...values }, data = `${JSON.stringify(next, null, 2)}\n`;
|
|
71
|
+
if (input.action === "reset_preferences") {
|
|
72
|
+
const saved = { version: 1, id: input.backup_id, created_at: new Date().toISOString(), values: before };
|
|
73
|
+
atomicWriteFilePairSync(settingsBackupPath(options), `${JSON.stringify(saved, null, 2)}\n`, file, data);
|
|
74
|
+
} else atomicWriteFileIfChangedSync(file, data, { mode: 0o600 });
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// An explicit projection, never a partial replacement for the full diagnostic
|
|
2
|
+
// snapshot. Old callers keep the complete status contract by default.
|
|
3
|
+
export function statusSummary(snapshot) {
|
|
4
|
+
return Object.fromEntries([...['ok', 'name', 'version', 'pid', 'uptime_ms', 'model_activity', 'runtime_usage']
|
|
5
|
+
.map(key => [key, snapshot[key]]), ['scope', 'summary']]);
|
|
6
|
+
}
|
package/src/user-settings.mjs
CHANGED
|
@@ -51,9 +51,9 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
|
|
|
51
51
|
delete parsed[key];
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
-
if (Object.hasOwn(parsed,
|
|
55
|
-
if (strict) throw invalidSettings(filePath,
|
|
56
|
-
delete parsed
|
|
54
|
+
for (const key of ["nightly_updates", "auto_save_settings"]) if (Object.hasOwn(parsed, key) && typeof parsed[key] !== "boolean") {
|
|
55
|
+
if (strict) throw invalidSettings(filePath, `${key} must be a boolean`);
|
|
56
|
+
delete parsed[key];
|
|
57
57
|
}
|
|
58
58
|
if (Object.hasOwn(parsed, "terminal_color_theme") && !isColorTheme(parsed.terminal_color_theme)) {
|
|
59
59
|
if (strict) throw invalidSettings(filePath, "terminal_color_theme must be green, klein or pink");
|
|
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
|
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
4
|
import { PassThrough, Writable } from "node:stream";
|
|
5
5
|
import { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
6
|
+
import { M365_API_HOST } from "./providers/m365-endpoint.mjs";
|
|
6
7
|
|
|
7
8
|
function failure(code) {
|
|
8
9
|
return Object.assign(new Error(`Windows network failed (${code}); existing company routes were preserved`), { code });
|
|
@@ -16,7 +17,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
|
|
|
16
17
|
if (target === "api" && (!Array.isArray(apiTargets) || !apiTargets.length || apiTargets.length > 8 || apiTargets.some(raw => {
|
|
17
18
|
try { const url = new URL(raw);return url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.href !== raw; } catch { return true; }
|
|
18
19
|
}))) throw failure("proxy_target_invalid");
|
|
19
|
-
const allowedHosts = target === "api" ? apiTargets.map(raw => new URL(raw).hostname) : target === "m365" ? [
|
|
20
|
+
const allowedHosts = target === "api" ? apiTargets.map(raw => new URL(raw).hostname) : target === "m365" ? [M365_API_HOST] : ["chatgpt.com", "ab.chatgpt.com"];
|
|
20
21
|
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
21
22
|
const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
|
|
22
23
|
const child = spawnImpl(command, ["-NoProfile", "-NonInteractive", "-Command",
|
|
@@ -84,7 +84,7 @@ public static class CCDXPredictionNetwork {
|
|
|
84
84
|
IntPtr connection=IntPtr.Zero;
|
|
85
85
|
try {
|
|
86
86
|
var uri=new Uri((string)data["url"]);
|
|
87
|
-
if(uri.Scheme!="https" || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (target=="api" ? !ApiTargetAllowed(uri,(string)data["method"]) : (uri.Port!=443 || (target=="m365" ? (uri.Host!="
|
|
87
|
+
if(uri.Scheme!="https" || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (target=="api" ? !ApiTargetAllowed(uri,(string)data["method"]) : (uri.Port!=443 || (target=="m365" ? (uri.Host!="loki.delve.office.com" || !uri.AbsolutePath.StartsWith("/api/v1/llmapi/",StringComparison.Ordinal)) : (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com"))))) throw new IOException("winhttp_target_invalid");
|
|
88
88
|
var method=(string)data["method"];
|
|
89
89
|
if(method!="GET"&&method!="POST"&&method!="HEAD"&&method!="PUT"&&method!="DELETE"&&method!="OPTIONS"&&method!="PATCH")throw new IOException("winhttp_method_invalid");
|
|
90
90
|
var headers=(string)data["headers"];
|