Skip to content

Commit 5f6d95e

Browse files
committed
fix: address tray and startup review feedback
1 parent 2ce0972 commit 5f6d95e

24 files changed

Lines changed: 591 additions & 133 deletions

‎bin/ocx.mjs‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
1414
import { homedir } from "node:os";
1515
import { dirname, join, resolve } from "node:path";
1616
import { fileURLToPath } from "node:url";
17+
import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../src/update/tray-update-plan.mjs";
1718

1819
const PKG = "@bitkyc08/opencodex";
1920
const require = createRequire(import.meta.url);
@@ -136,7 +137,9 @@ function runNpmSelfUpdate() {
136137
// unloads it permanently, so a successful update must reinstall it afterwards.
137138
const serviceStatePath = join(configDir(), "service-state.json");
138139
const serviceWasInstalled = existsSync(serviceStatePath);
139-
const trayBeforeUpdate = process.platform === "win32" ? trayInstallState() : { installed: false, running: false };
140+
const trayBeforeUpdate = planWindowsTrayUpdate(
141+
process.platform === "win32" ? trayInstallState() : { installed: false, running: false },
142+
);
140143
/** Read the backend from service-state.json so the update reinstalls the same one. */
141144
function serviceReinstallArgs() {
142145
try {
@@ -182,11 +185,17 @@ function runNpmSelfUpdate() {
182185
// and the runtime-port record too: a service-managed or orphaned proxy can be live
183186
// while ocx.pid is stale/missing.
184187
const launcher = fileURLToPath(import.meta.url);
185-
if (trayBeforeUpdate.running) {
188+
if (trayBeforeUpdate.stopBeforeReplacement) {
186189
console.log("⏹ Handing off the Windows tray before updating...");
187-
const stopped = runTrayLifecycle(launcher, "stop");
188-
if (stopped.status !== 0 || trayInstallState().running) {
189-
runTrayLifecycle(launcher, "start");
190+
try {
191+
handoffWindowsTrayForUpdate(trayBeforeUpdate, {
192+
stop: () => {
193+
const stopped = runTrayLifecycle(launcher, "stop");
194+
return { exitStatus: stopped.status, running: trayInstallState().running };
195+
},
196+
start: () => runTrayLifecycle(launcher, "start"),
197+
});
198+
} catch {
190199
console.error("opencodex: could not stop the Windows tray; aborting before package replacement.");
191200
process.exit(1);
192201
}
@@ -199,7 +208,7 @@ function runNpmSelfUpdate() {
199208
const stillHasRuntimeState =
200209
existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json"));
201210
if (stopRes.status !== 0 || stillHasRuntimeState) {
202-
if (trayBeforeUpdate.running) runTrayLifecycle(launcher, "start");
211+
if (trayBeforeUpdate.restoreOnFailure) runTrayLifecycle(launcher, "start");
203212
console.error("opencodex: could not stop the running proxy; aborting the update. Run 'ocx stop' and retry.");
204213
process.exit(1);
205214
}
@@ -222,14 +231,14 @@ function runNpmSelfUpdate() {
222231
if (res.status === 0) {
223232
console.log(`\nUpdated${latest ? ` to v${latest}` : ""}.`);
224233
repairCodexShimIfNeeded();
225-
if (trayBeforeUpdate.installed) {
226-
const tray = spawnSync(process.execPath, [launcher, "tray", "install", ...(!trayBeforeUpdate.running ? ["--no-start"] : [])], {
234+
if (trayBeforeUpdate.refreshAfterReplacement) {
235+
const tray = spawnSync(process.execPath, [launcher, ...trayBeforeUpdate.installArgs], {
227236
stdio: "inherit",
228237
windowsHide: true,
229238
});
230239
if (tray.status !== 0) {
231240
console.warn("opencodex: Windows tray refresh failed. Run: ocx tray install");
232-
if (trayBeforeUpdate.running) runTrayLifecycle(launcher, "start");
241+
if (trayBeforeUpdate.restoreOnFailure) runTrayLifecycle(launcher, "start");
233242
}
234243
}
235244
// The stop above unloaded any managed service; reinstall via the freshly-installed
@@ -268,7 +277,7 @@ function runNpmSelfUpdate() {
268277
}
269278
process.exit(0);
270279
}
271-
if (trayBeforeUpdate.running) runTrayLifecycle(launcher, "start");
280+
if (trayBeforeUpdate.restoreOnFailure) runTrayLifecycle(launcher, "start");
272281
console.error(`\nUpdate failed (${npm} exit ${res.status ?? "?"}). Try manually: ${npm} install -g ${PKG}@${tag}`);
273282
process.exit(1);
274283
}

‎gui/src/i18n/de.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// German — generated from en.ts. Must match TKey set (compile-checked).
22
export const de = {
33
"nav.dashboard": "Übersicht",
4-
"nav.startup": "Autostart",
4+
"nav.startup": "Startsicherheit",
55
"nav.providers": "Anbieter",
66
"nav.models": "Modelle",
77
"nav.combos": "Combos",

‎gui/src/i18n/ja.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export const ja: Record<TKey, string> = {
6868
"startup.shimHint": "対応する Codex スクリプトランチャーの起動時に ocx ensure を実行します。",
6969
"startup.healthy": "正常",
7070
"startup.cliOnly": "CLI のみ",
71-
"startup.stale": "破損",
71+
"startup.stale": "要更新",
7272
"startup.viable": "利用可能",
7373
"startup.unhealthy": "インストール済み・異常",
7474
"startup.conflict": "サービス競合",

‎gui/src/i18n/ko.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export const ko: Record<TKey, string> = {
6363
"startup.shimHint": "지원되는 Codex 스크립트 런처가 시작될 때 ocx ensure를 실행합니다.",
6464
"startup.healthy": "정상",
6565
"startup.cliOnly": "CLI 전용",
66-
"startup.stale": "손상됨",
66+
"startup.stale": "업데이트 필요",
6767
"startup.viable": "사용 가능",
6868
"startup.unhealthy": "설치됐지만 비정상",
6969
"startup.conflict": "서비스 충돌",

‎gui/src/i18n/ru.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { TKey } from "./en";
33
export const ru: Record<TKey, string> = {
44
// sidebar / nav / common
55
"nav.dashboard": "Дашборд",
6-
"nav.startup": "Автозапуск",
6+
"nav.startup": "Безопасность запуска",
77
"nav.providers": "Провайдеры",
88
"nav.models": "Модели",
99
"nav.combos": "Комбо",
@@ -68,7 +68,7 @@ export const ru: Record<TKey, string> = {
6868
"startup.shimHint": "Запускает ocx ensure при запуске поддерживаемого скриптового лаунчера Codex.",
6969
"startup.healthy": "Исправен",
7070
"startup.cliOnly": "Только CLI",
71-
"startup.stale": "Повреждён",
71+
"startup.stale": "Устарел",
7272
"startup.viable": "Готов",
7373
"startup.unhealthy": "Установлен, но неисправен",
7474
"startup.conflict": "Конфликт служб",

‎gui/src/pages/Dashboard.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { formatUptime } from "../formatUptime";
33
import { IconAlert, IconExternal, IconInfo, IconRefresh, IconX } from "../icons";
44
import { Trans } from "../i18n/provider";
55
import { useI18n, type TKey } from "../i18n/shared";
6+
import { startupRiskDetailKey } from "../startup-health-ui";
67
import { formatTokens } from "../format-tokens";
78
import { EmptyState, Select } from "../ui";
89

@@ -632,7 +633,7 @@ export default function Dashboard({ apiBase }: { apiBase: string }) {
632633
<span>
633634
{settings.startupHealth.diagnosticStale
634635
? t("startup.staleData")
635-
: t(settings.startupHealth.routingKind === "custom-local" ? "startup.riskDetailCustomLocal" : settings.startupHealth.shimCoverage === "cli-only" ? "startup.riskDetailWindowsShim" : "startup.riskDetail")}{" "}
636+
: t(startupRiskDetailKey(settings.startupHealth))}{" "}
636637
<a href="#startup">{t("startup.title")}</a>
637638
</span>
638639
</div>

‎gui/src/pages/Startup.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useCallback, useEffect, useState } from "react";
22
import { IconAlert, IconCheck, IconPower, IconRefresh, IconTerminal } from "../icons";
33
import { useI18n, type TKey } from "../i18n/shared";
4+
import { startupRiskDetailKey } from "../startup-health-ui";
45
import { EmptyState } from "../ui";
56

67
type StartupStatus = "native" | "protected" | "at-risk";
@@ -219,7 +220,7 @@ export default function Startup({ apiBase }: { apiBase: string }) {
219220
<p>{failed
220221
? t("startup.staleData")
221222
: data.status === "at-risk"
222-
? t(data.routingKind === "custom-local" ? "startup.riskDetailCustomLocal" : data.shimCoverage === "cli-only" ? "startup.riskDetailWindowsShim" : "startup.riskDetail")
223+
? t(startupRiskDetailKey(data))
223224
: t("startup.safeDetail")}</p>
224225
</div>
225226
</section>

‎gui/src/startup-health-ui.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import type { TKey } from "./i18n/shared";
2+
3+
export interface StartupRiskDetail {
4+
routingKind: "native" | "opencodex-local" | "custom-local" | "custom-remote" | "unknown";
5+
shimCoverage: "full" | "cli-only" | "none";
6+
}
7+
8+
export function startupRiskDetailKey(health: StartupRiskDetail): TKey {
9+
if (health.routingKind === "custom-local") return "startup.riskDetailCustomLocal";
10+
if (health.shimCoverage === "cli-only") return "startup.riskDetailWindowsShim";
11+
return "startup.riskDetail";
12+
}

‎src/cli/doctor.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,8 @@ export async function runDoctor(): Promise<void> {
410410
const anyDrvfs = paths.some(p => detectFsType(p.path, mounts).isDrvfs || detectFsType(p.path, mounts).isMntDrive);
411411
const noProxy = currentProxyEnv.every(p => !p.present) && !configuredProxy.present;
412412
if (!startup.rebootSafe) {
413-
hints.push(`Codex is pinned to the local proxy without persistent startup protection. After restart, requests can reconnect indefinitely. Run '${startup.commands.installService}' or restore native routing with '${startup.commands.restoreNative}'.`);
413+
const command = startup.recommendedCommand ?? startup.commands.restoreNative;
414+
hints.push(`Codex is pinned to the local proxy without persistent startup protection. After restart, requests can reconnect indefinitely. Run '${command}'.`);
414415
}
415416
if (anyDrvfs) {
416417
hints.push("State dir is on a Windows-mounted (/mnt) drive. Prefer the Linux home (~) under WSL for token/lock reliability.");

‎src/cli/index.ts‎

Lines changed: 45 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import {
2020
writeRuntimePort,
2121
} from "../config";
2222
import { collectStatus } from "./status";
23+
import { dispatchInternalCliCommand, type InternalCliCommand } from "./internal-dispatch";
24+
import { runTrayProxyRestart, runTrayProxyStart } from "./tray-proxy";
2325
import { installCrashGuards } from "../lib/crash-guard";
2426
import { hasHelpFlag, printSubcommandUsage, printUsage, printVersion } from "./help";
2527
import { findAvailablePort, isAddrInUse, PortUnavailableError, shouldPersistSelectedPort, waitForPortAvailable } from "../server/ports";
@@ -305,45 +307,43 @@ async function handleEnsure() {
305307

306308
/** Fixed tray action: start the proxy without depending on codexAutoStart. */
307309
async function handleTrayProxyStart(): Promise<void> {
308-
const live = await findLiveProxy();
309-
if (live) {
310-
console.log(`Proxy already running on port ${live.port}.`);
311-
return;
312-
}
313-
const service = diagnoseService();
314-
const serviceStartable = serviceStartableFromTray(service);
315-
if (service.installed && !serviceStartable) {
316-
console.error(`Cannot start from the tray because the installed service is not viable: ${service.summary}`);
317-
console.error("Repair or remove the service before starting a direct proxy.");
318-
process.exitCode = 1;
319-
return;
320-
}
321-
if (serviceStartable) {
322-
await serviceCommand("start");
323-
} else {
324-
const config = loadConfig();
325-
const port = (config.port ?? 10100) > 0 ? (config.port ?? 10100) : 10100;
326-
const child = spawn(process.execPath, startArgv(port), {
327-
detached: true,
328-
stdio: "ignore",
329-
windowsHide: true,
330-
env: { ...process.env, OCX_SERVICE: "1" },
331-
});
332-
child.unref();
333-
}
334-
const started = await waitForProxy();
335-
if (!started) {
336-
console.error("Proxy did not become healthy after the tray start action.");
337-
process.exitCode = 1;
338-
return;
339-
}
340-
console.log(`Proxy running on port ${started.port}.`);
310+
const ok = await runTrayProxyStart({
311+
findLive: findLiveProxy,
312+
diagnoseService: () => {
313+
const service = diagnoseService();
314+
return { installed: service.installed, startable: serviceStartableFromTray(service), summary: service.summary };
315+
},
316+
startService: () => serviceCommand("start"),
317+
startDirect: () => {
318+
const config = loadConfig();
319+
const port = (config.port ?? 10100) > 0 ? (config.port ?? 10100) : 10100;
320+
const child = spawn(process.execPath, startArgv(port), {
321+
detached: true,
322+
stdio: "ignore",
323+
windowsHide: true,
324+
env: { ...process.env, OCX_SERVICE: "1" },
325+
});
326+
child.unref();
327+
},
328+
waitForProxy,
329+
info: message => console.log(message),
330+
error: message => console.error(message),
331+
});
332+
if (!ok) process.exitCode = 1;
341333
}
342334

343335
async function handleTrayProxyRestart(): Promise<void> {
344-
await handleStop();
345-
if (process.exitCode && process.exitCode !== 0) return;
346-
await handleTrayProxyStart();
336+
const ok = await runTrayProxyRestart({
337+
stop: async () => {
338+
await handleStop();
339+
return !process.exitCode || process.exitCode === 0;
340+
},
341+
start: async () => {
342+
await handleTrayProxyStart();
343+
return !process.exitCode || process.exitCode === 0;
344+
},
345+
});
346+
if (!ok) process.exitCode = 1;
347347
}
348348

349349
async function handleStop() {
@@ -696,21 +696,22 @@ switch (command) {
696696
break;
697697
}
698698
case "__tray-start":
699-
await handleTrayProxyStart();
700-
break;
701699
case "__tray-restart":
702-
await handleTrayProxyRestart();
700+
case "__startup-health":
701+
await dispatchInternalCliCommand(command as InternalCliCommand, {
702+
trayStart: handleTrayProxyStart,
703+
trayRestart: handleTrayProxyRestart,
704+
startupHealth: async () => {
705+
const { collectStartupHealth } = await import("../codex/autostart-health");
706+
console.log(JSON.stringify(collectStartupHealth(loadConfig())));
707+
},
708+
});
703709
break;
704710
case "__tray-host": {
705711
const { runWindowsTrayHost } = await import("../tray/windows");
706712
await runWindowsTrayHost();
707713
break;
708714
}
709-
case "__startup-health": {
710-
const { collectStartupHealth } = await import("../codex/autostart-health");
711-
console.log(JSON.stringify(collectStartupHealth(loadConfig())));
712-
break;
713-
}
714715
case "__gui-update-worker": {
715716
const jobId = args[1];
716717
if (!jobId) process.exit(1);

0 commit comments

Comments
 (0)