Skip to content

Commit 0be28c4

Browse files
committed
fix(update): skip redundant GUI restart after npm self-update
npm ocx update already restarts the service; a second service install stopped the healthy proxy on 10100 and often failed elevation from the non-interactive worker.
1 parent 58f0fab commit 0be28c4

3 files changed

Lines changed: 181 additions & 24 deletions

File tree

‎docs/adr/0001-gui-update-worker.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ return and remain healthy for a short stability window before marking the job su
2727
keeps `update-job.json` honest on Windows cases where npm leaves the bundled Bun runtime in a bad
2828
state and the restarted proxy dies a few seconds later.
2929

30+
For npm installs specifically, `node ocx.mjs update` already stops the proxy and reinstalls /
31+
starts the managed service (or falls back to a direct start). The worker therefore confirms that
32+
self-update restart first and skips a redundant second `service install`. A second install would
33+
call `stopWindows()` on the healthy listener and often fail elevation from the non-interactive
34+
worker, leaving the captured port (default 10100) dead until a manual restart. Bun global installs
35+
still always take the explicit restart path because `bun add -g` does not restart the proxy.
36+
3037
## Consequences
3138

3239
- The GUI request handler stays responsive and does not overwrite its own running module graph.

‎src/update/job.ts‎

Lines changed: 81 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,12 @@ export interface RestartIo {
306306
bin: string,
307307
args: string[],
308308
) => { status: number | null; signal?: NodeJS.Signals | null };
309+
/** Override the explicit restart path (used by finishGuiUpdateRestart tests). */
310+
restartAfterUpdateFn?: (
311+
job: UpdateJobState,
312+
captured?: { port: number; hostname: string; oldPid?: number },
313+
io?: RestartIo,
314+
) => Promise<void>;
309315
}
310316

311317
async function restartAfterUpdate(
@@ -404,25 +410,19 @@ function restartFailureHint(port: number): string {
404410
+ "reinstall with 'npm install -g --allow-scripts=bun @bitkyc08/opencodex'.";
405411
}
406412

413+
type AwaitHealthyResult =
414+
| { ok: true }
415+
| { ok: false; reason: "timeout" | "flapped" };
416+
407417
/**
408-
* Confirm that the detached/service restart really came back and stayed up. The GUI worker
409-
* used to mark success immediately after spawning the new process, which hid Windows cases
410-
* where npm left the bundled Bun runtime half-updated and the restarted proxy died seconds
411-
* later. A healthy /healthz must appear, then remain healthy for one short stability window.
418+
* Wait for an identity-checked /healthz on the captured listen target, then require a short
419+
* stability window. Soft: never marks the job failed (callers decide whether to fail or retry).
412420
*/
413-
async function confirmRestartedProxy(
421+
async function awaitRestartedProxyHealthy(
414422
job: UpdateJobState,
415423
captured: { port: number; hostname: string },
416424
io: RestartIo = {},
417-
): Promise<boolean> {
418-
/* [Decision Log]
419-
- 목적과 의도: GUI update job이 detached restart 요청만 보고 성공 처리하지 않도록, 실제 프록시 복귀 여부를 확인한다.
420-
- 기존 구현 및 제약 조건: update-job.json은 spawn/service reinstall 직후 `succeeded`로 끝났고, Windows npm/Bun 교체 실패처럼 몇 초 후 죽는 재시작을 잡지 못했다.
421-
- 검토한 주요 대안: (1) 포트 점유만 확인 — 외부 프로세스/죽기 직전 프로세스를 성공으로 오인할 수 있다. (2) 무기한 /healthz 폴링 — UX가 느려지고 worker 종료 시점이 불명확하다. (3) 짧은 healthy 등장 + 안정성 창 확인 — 실제 복귀를 확인하면서도 대기 시간을 제한할 수 있다.
422-
- 선택한 방식: identity-aware /healthz probe가 일정 시간 안에 나타나고, 추가 안정성 창 동안 유지되는지 확인한다.
423-
- 다른 대안 대신 이 방식을 선택한 이유: GUI는 "업데이트가 설치됐지만 재시작은 실패"를 분리해 알려줘야 하며, 이 방식이 가장 적은 오탐으로 그 경계를 만든다.
424-
- 장점, 단점 및 영향: 장점은 silent restart failure가 update-job 상태로 드러난다는 점이다. 단점은 성공 판정이 최대 30초 늦어질 수 있다는 점이며, 대신 실제 복귀를 더 정확히 반영한다.
425-
*/
425+
): Promise<AwaitHealthyResult> {
426426
const probe = io.probeProxy ?? (async (port: number, hostname?: string) => (
427427
!!(await proxyIdentityAt(port, { hostname }))
428428
));
@@ -440,25 +440,50 @@ async function confirmRestartedProxy(
440440
const stableUntil = now() + RESTART_STABILITY_WINDOW_MS;
441441
while (now() < stableUntil) {
442442
if (!(await probe(port, hostname))) {
443-
updateJob(job, {
444-
status: "failed",
445-
restarted: false,
446-
error: `proxy restart became unhealthy on ${hostname}:${port}`,
447-
}, restartFailureHint(port));
448-
return false;
443+
updateJob(job, {}, `Proxy became unhealthy on ${hostname}:${port} during the stability window.`);
444+
return { ok: false, reason: "flapped" };
449445
}
450446
await sleep(500);
451447
}
452448
updateJob(job, {}, `Proxy stayed healthy for ${Math.trunc(RESTART_STABILITY_WINDOW_MS / 1000)}s after restart.`);
453-
return true;
449+
return { ok: true };
454450
}
455451
await sleep(250);
456452
}
457453

454+
return { ok: false, reason: "timeout" };
455+
}
456+
457+
/**
458+
* Confirm that the detached/service restart really came back and stayed up. The GUI worker
459+
* used to mark success immediately after spawning the new process, which hid Windows cases
460+
* where npm left the bundled Bun runtime half-updated and the restarted proxy died seconds
461+
* later. A healthy /healthz must appear, then remain healthy for one short stability window.
462+
*/
463+
async function confirmRestartedProxy(
464+
job: UpdateJobState,
465+
captured: { port: number; hostname: string },
466+
io: RestartIo = {},
467+
): Promise<boolean> {
468+
/* [Decision Log]
469+
- 목적과 의도: GUI update job이 detached restart 요청만 보고 성공 처리하지 않도록, 실제 프록시 복귀 여부를 확인한다.
470+
- 기존 구현 및 제약 조건: update-job.json은 spawn/service reinstall 직후 `succeeded`로 끝났고, Windows npm/Bun 교체 실패처럼 몇 초 후 죽는 재시작을 잡지 못했다.
471+
- 검토한 주요 대안: (1) 포트 점유만 확인 — 외부 프로세스/죽기 직전 프로세스를 성공으로 오인할 수 있다. (2) 무기한 /healthz 폴링 — UX가 느려지고 worker 종료 시점이 불명확하다. (3) 짧은 healthy 등장 + 안정성 창 확인 — 실제 복귀를 확인하면서도 대기 시간을 제한할 수 있다.
472+
- 선택한 방식: identity-aware /healthz probe가 일정 시간 안에 나타나고, 추가 안정성 창 동안 유지되는지 확인한다.
473+
- 다른 대안 대신 이 방식을 선택한 이유: GUI는 "업데이트가 설치됐지만 재시작은 실패"를 분리해 알려줘야 하며, 이 방식이 가장 적은 오탐으로 그 경계를 만든다.
474+
- 장점, 단점 및 영향: 장점은 silent restart failure가 update-job 상태로 드러난다는 점이다. 단점은 성공 판정이 최대 30초 늦어질 수 있다는 점이며, 대신 실제 복귀를 더 정확히 반영한다.
475+
*/
476+
const result = await awaitRestartedProxyHealthy(job, captured, io);
477+
if (result.ok) return true;
478+
const port = captured.port;
479+
const hostname = captured.hostname;
480+
const error = result.reason === "flapped"
481+
? `proxy restart became unhealthy on ${hostname}:${port}`
482+
: `proxy restart never became healthy on ${hostname}:${port}`;
458483
updateJob(job, {
459484
status: "failed",
460485
restarted: false,
461-
error: `proxy restart never became healthy on ${hostname}:${port}`,
486+
error,
462487
}, restartFailureHint(port));
463488
return false;
464489
}
@@ -471,6 +496,39 @@ export function confirmRestartAfterUpdateForTests(
471496
return confirmRestartedProxy(job, captured, io);
472497
}
473498

499+
/**
500+
* Post-install restart for the GUI worker.
501+
*
502+
* npm installs run `node ocx.mjs update`, which already stops the proxy and reinstalls /
503+
* starts the service (or falls back to a direct start). A second `service install` here
504+
* calls `stopWindows()` on that healthy listener, then often fails elevation from the
505+
* non-interactive worker — leaving the captured port (default 10100) dead until a manual
506+
* restart. Prefer confirming the npm self-update's own restart first; only re-run restart
507+
* when that probe fails. Bun/source installs still always take the explicit restart path.
508+
*/
509+
export async function finishGuiUpdateRestart(
510+
job: UpdateJobState,
511+
captured: { port: number; hostname: string; oldPid?: number },
512+
installer: Installer,
513+
io: RestartIo = {},
514+
): Promise<boolean> {
515+
if (installer === "npm") {
516+
const already = await awaitRestartedProxyHealthy(job, captured, io);
517+
if (already.ok) {
518+
updateJob(
519+
job,
520+
{},
521+
`Proxy already healthy on ${captured.hostname}:${captured.port} after npm self-update; skipping redundant restart.`,
522+
);
523+
return true;
524+
}
525+
updateJob(job, {}, "npm self-update did not leave a healthy proxy; performing explicit restart...");
526+
}
527+
const restartFn = io.restartAfterUpdateFn ?? restartAfterUpdate;
528+
await restartFn(job, captured, io);
529+
return confirmRestartedProxy(job, captured, io);
530+
}
531+
474532
export async function runGuiUpdateWorker(jobId: string, channel: Channel, restart: boolean): Promise<void> {
475533
let job = readUpdateJob(jobId);
476534
const check = checkForUpdate(channel);
@@ -590,8 +648,7 @@ export async function runGuiUpdateWorker(jobId: string, channel: Channel, restar
590648

591649
if (restart) {
592650
job = updateJob(job, { status: "restarting" }, "Update installed. Restarting proxy...");
593-
await restartAfterUpdate(job, captured);
594-
if (!(await confirmRestartedProxy(job, captured))) return;
651+
if (!(await finishGuiUpdateRestart(job, captured, check.installer))) return;
595652
updateJob(job, { status: "succeeded", restarted: true }, "Restart requested and proxy is healthy.");
596653
return;
597654
}

‎tests/update-job.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { join } from "node:path";
55
import {
66
checkForUpdate,
77
confirmRestartAfterUpdateForTests,
8+
finishGuiUpdateRestart,
89
readUpdateJob,
910
restartCommand,
1011
restartAfterUpdateForTests,
@@ -366,6 +367,98 @@ describe("GUI update execution decisions", () => {
366367
expect(readUpdateJob(job.id)?.log.some(line => line.includes("stayed healthy for 15s after restart"))).toBe(true);
367368
});
368369

370+
test("npm finish skips redundant restart when self-update already left the proxy healthy", async () => {
371+
let now = 0;
372+
let restartCalls = 0;
373+
const job: UpdateJobState = {
374+
id: "npm-skip-redundant",
375+
status: "restarting",
376+
startedAt: new Date().toISOString(),
377+
updatedAt: new Date().toISOString(),
378+
currentVersion: "2.7.40",
379+
latestVersion: "2.7.41",
380+
channel: "latest",
381+
installer: "npm",
382+
restart: true,
383+
command: "",
384+
log: [],
385+
};
386+
writeFileSync(updateJobPath(job.id), JSON.stringify(job));
387+
const ok = await finishGuiUpdateRestart(job, { port: 10100, hostname: "127.0.0.1" }, "npm", {
388+
probeProxy: async () => true,
389+
now: () => now,
390+
sleepMs: async (ms) => { now += ms; },
391+
restartAfterUpdateFn: async () => { restartCalls += 1; },
392+
});
393+
expect(ok).toBe(true);
394+
expect(restartCalls).toBe(0);
395+
expect(readUpdateJob(job.id)?.log.some(line =>
396+
line.includes("skipping redundant restart") && line.includes("10100"),
397+
)).toBe(true);
398+
});
399+
400+
test("npm finish falls back to explicit restart when self-update left the proxy down", async () => {
401+
let now = 0;
402+
let restartCalls = 0;
403+
const job: UpdateJobState = {
404+
id: "npm-fallback-restart",
405+
status: "restarting",
406+
startedAt: new Date().toISOString(),
407+
updatedAt: new Date().toISOString(),
408+
currentVersion: "2.7.40",
409+
latestVersion: "2.7.41",
410+
channel: "latest",
411+
installer: "npm",
412+
restart: true,
413+
command: "",
414+
log: [],
415+
};
416+
writeFileSync(updateJobPath(job.id), JSON.stringify(job));
417+
const ok = await finishGuiUpdateRestart(job, { port: 10100, hostname: "127.0.0.1" }, "npm", {
418+
// Soft probe times out (proxy down after npm update); confirm after explicit restart succeeds.
419+
probeProxy: async () => restartCalls > 0,
420+
now: () => now,
421+
sleepMs: async (ms) => { now += ms; },
422+
restartAfterUpdateFn: async () => {
423+
restartCalls += 1;
424+
now = 0; // reset clock so post-restart health wait has a fresh window
425+
},
426+
});
427+
expect(ok).toBe(true);
428+
expect(restartCalls).toBe(1);
429+
expect(readUpdateJob(job.id)?.log.some(line =>
430+
line.includes("performing explicit restart"),
431+
)).toBe(true);
432+
});
433+
434+
test("bun finish always runs explicit restart even if a proxy is already healthy", async () => {
435+
let now = 0;
436+
let restartCalls = 0;
437+
const job: UpdateJobState = {
438+
id: "bun-always-restart",
439+
status: "restarting",
440+
startedAt: new Date().toISOString(),
441+
updatedAt: new Date().toISOString(),
442+
currentVersion: "2.7.40",
443+
latestVersion: "2.7.41",
444+
channel: "latest",
445+
installer: "bun",
446+
restart: true,
447+
command: "",
448+
log: [],
449+
};
450+
writeFileSync(updateJobPath(job.id), JSON.stringify(job));
451+
const ok = await finishGuiUpdateRestart(job, { port: 10100, hostname: "127.0.0.1" }, "bun", {
452+
probeProxy: async () => true,
453+
now: () => now,
454+
sleepMs: async (ms) => { now += ms; },
455+
restartAfterUpdateFn: async () => { restartCalls += 1; },
456+
});
457+
expect(ok).toBe(true);
458+
expect(restartCalls).toBe(1);
459+
expect(readUpdateJob(job.id)?.log.some(line => line.includes("skipping redundant restart"))).toBe(false);
460+
});
461+
369462
test("a running job prevents a second update job", () => {
370463
const now = new Date().toISOString();
371464
const job: UpdateJobState = {

0 commit comments

Comments
 (0)