Files
OmniRoute/open-sse/executors/chatgpt-web-codex/doctor.ts
Diego Rodrigues de Sa e Souza f6ccd3cf9f fix(quality): green release/v3.8.50 base-reds round 2 (#9985) (#10131)
* fix(quality): green release/v3.8.50 base-reds round 2 — gateways/conol/deepai corruption, migrations, docs, ratchets, dashboard-typecheck

Base-red fix for issue #9985 after the 2026-08-11 merge storm (99 PRs).

Real defects fixed:
- gateways.ts: close regolo entry (was swallowing naga-ac + chatanywhere from #9421), drop stale duplicate chatanywhere entry (#9594)
- conol-web + deepai registry: correct ../shared import depth + deepai executor:default
- modelSelectModalHelpers: close isProviderModelHidden (#9011)
- driverFactory.test.ts: restore eaten test-closing brace (#9173)
- usageTracking: remove duplicate cache_* props
- modelCapability{Overrides,ResolutionSnapshot,Capabilities}: max_token -> max_output_tokens (#9199 vs #8908) + test align
- videoGeneration: drop duplicate handleFalVideoGeneration import (mediaGeneration/fal canonical, #9982)
- responseSanitizer: cast input_tokens_details before .cached_tokens access
- EditConnectionModal: missing alibaba code fields, hoist validationPsd, providerPageHelpers Badge variant union
- FreeBudgetCard: t() -> labels.noApiKey
- peerRouting + cliRuntime: ProcessEnv typing
- image-combo.test.ts: type any -> unknown
- fal.test.ts: moved to tests/unit/services (collected path) 14 tests green
- remove duplicate 143_job_registry.sql (146 canonical), KNOWN_GAPS fix

Docs/ratchets (owner-authorized rebaselines, annotated):
- CHANGELOG 3.8.50 living section restored + 42 i18n mirrors
- MCP-SERVER.md 104->105 tools + i18n
- ENVIRONMENT.md/.env.example: ADOBE_FIREFLY_CHROME_HEADED + DEBUG_CLAUDE_NONSTREAM
- fabricated-docs allowlist: TELEGRAM proposal env vars
- file-size: 5 grown files + proxyFetch 1207->1220
- dead-code 230->248, codeql 2->9 (drift from merged PRs, not this PR)
- untrack _tasks symlink; agent-skills-sync --apply (config-codex-cli)

* fix(changelog): reformat two feature fragments to the bullet convention (#9239, #9490)

* fix(quality): prune stale ESLint suppressions (base-red)

* fix(quality): resolve open-sse type errors + catalog/build regressions (base-red round 3)

Storm-merge splices repaired in the base-fix PR #10131:
- doctor.ts: AppConfig missing brokerSocketPath
- conol-web.ts: Buffer not assignable to BodyInit (Uint8Array)
- tinycms.ts: TinyCmsExecutor.execute return matches BaseExecutor (response/url/transformedBody)
- tinycmsSigner.ts: encodeInto never-narrowing guard + dead wasm URL fallback (Turbopack)
- virtualFactory.ts: options slot for resolutionSnapshot
- bottleneckPatch.ts: insufficient-overlap casts (as unknown as)
- imageCombo.ts: narrow handleImageGeneration union result
- browser-worker.ts: AppConfig + turn.capabilities splice
- conolDiscovery.ts: getProviderOutboundGuard from Policy module
- catalog.ts: drop removed SWR hooks (getCatalogStaleWhileRevalidateMs + accessors), CatalogCachePolicy -> inline settings, resolve 4-arg call
- catalogCache.ts: remove dead inFlight/promise refs
- chat.ts: add isProviderBreakerFailureStatus import
- model-catalog-cache-swr-8728.test.ts: align to #9199 new API (policy injection removed)

* fix(quality): align UI test fixtures to current component contracts (base-red vitest)

- setup-wizard: provide required serverState prop (component gained it in a merged PR)
- grok-device-oauth-modal: next-intl stub resolves grok flow keys to EN labels
- provider-quota-widget: label now inline (PR #8916 removed AutoRefreshButtonLabel extraction) — test the widget
- use-provider-connections-cursor-refresh + phase1f: match /api/providers?provider=<id> query form; hoist heavy dynamic imports to module scope (timeout flake)
- home-topology: mock next/navigation useRouter (component added node-click navigation)
- cooling/lobe/AutoComboCatalog: raise cold-import describe timeouts to 30-60s
- request-logger-*: align to current detail-view contract

* fix(search): guard params.token undefined in serper headers (typecheck base-red)

* fix(search): guard token headers + non-null providerConfig (typecheck base-red)

* fix(changelog): restore base CHANGELOGs eaten by merge auto-resolve (43 files)

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: backryun <bakryun0718@proton.me>
2026-08-12 16:09:34 -03:00

118 lines
3.9 KiB
TypeScript

import { existsSync, readFileSync } from "node:fs";
import { browserLoginStateExists } from "../../vendor/codex-chatgpt-web/browser-login.ts";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { detectChromeExecutable } from "../chatgpt-web-codex.ts";
import { decodeChatGptWebCodexSecrets } from "./credentials.ts";
import { getChatGptWebCodexRuntimeCounts } from "./runtime.ts";
import {
connectionRuntimePaths,
ensureConnectionStorageStateFromCredential,
} from "./storageState.ts";
import {
getTunnelRuntimeStatus,
tunnelClientPaths,
tunnelSupervisorLeaseStatus,
} from "./tunnelClient.ts";
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
export async function getChatGptWebCodexDoctorStatus(connection: {
id?: unknown;
apiKey?: unknown;
providerSpecificData?: unknown;
lastError?: unknown;
}) {
const connectionId = typeof connection.id === "string" ? connection.id : "";
const data = record(connection.providerSpecificData);
const paths = connectionRuntimePaths(connectionId);
const tunnelPaths = tunnelClientPaths();
const cdpConfigured = Boolean(process.env.CHATGPT_WEB_CODEX_CDP_URL?.trim());
const chrome = detectChromeExecutable(
typeof data.chromeExecutablePath === "string" ? data.chromeExecutablePath : undefined
);
let storageState = false;
let login = false;
let proAvailable = data.proAvailable === true;
let credential = false;
try {
const secrets = decodeChatGptWebCodexSecrets(String(connection.apiKey || ""));
credential = Boolean(secrets.storageState);
if (credential) ensureConnectionStorageStateFromCredential(connectionId, secrets);
storageState = existsSync(paths.storageStatePath);
login = browserLoginStateExists({
mode: "browser-only",
appName: "OmniRoute Codex",
storageStatePath: paths.storageStatePath,
brokerSocketPath: paths.brokerSocketPath,
...(chrome ? { chromeExecutablePath: chrome } : {}),
...(cdpConfigured ? { cdpEndpoint: process.env.CHATGPT_WEB_CODEX_CDP_URL } : {}),
headed: false,
proAvailable,
autoApproveToolCalls: false,
});
if (login) {
try {
const marker = JSON.parse(
readFileSync(`${paths.storageStatePath}.verified.json`, "utf8")
) as Record<string, unknown>;
if (typeof marker.proAvailable === "boolean") proAvailable = marker.proAvailable;
} catch {
// Marker detail is optional.
}
}
} catch {
credential = false;
}
let tunnel = {
ok: false,
processRunning: false,
healthy: false,
ready: false,
detail: "not checked",
};
try {
if (existsSync(tunnelPaths.binary)) tunnel = await getTunnelRuntimeStatus({});
} catch (error) {
tunnel.detail = sanitizeErrorMessage(error instanceof Error ? error.message : error);
}
const runtime = getChatGptWebCodexRuntimeCounts();
const lease = tunnelSupervisorLeaseStatus();
return {
browser: {
ready: Boolean(chrome || cdpConfigured),
mode: cdpConfigured ? "internal-cdp" : chrome ? "local-chromium" : "unavailable",
},
storageState: { ready: storageState && credential },
login: { ready: login },
temporaryChats: { ready: login },
tunnelBinary: { ready: existsSync(tunnelPaths.binary) },
tunnel: {
ready: tunnel.ok,
processRunning: tunnel.processRunning,
healthy: tunnel.healthy,
detail: tunnel.detail,
},
connector: {
ready: typeof data.connectorName === "string" && data.connectorName.trim().length > 0,
},
toolRoundtrip: { ready: tunnel.ok && runtime.brokers > 0 },
runtime,
lease,
proAvailable,
recovery: {
interactiveLoginRequired: storageState && !login,
},
lastError:
typeof connection.lastError === "string" && connection.lastError.trim()
? sanitizeErrorMessage(connection.lastError)
: null,
};
}