Skip to content

feat(dashboard): drain-and-restart from memory observability card (#563) - #580

Merged
Wibias merged 3 commits into
lidge-jun:devfrom
Wibias:feat/563-memory-drain-restart
Jul 28, 2026
Merged

feat(dashboard): drain-and-restart from memory observability card (#563)#580
Wibias merged 3 commits into
lidge-jun:devfrom
Wibias:feat/563-memory-drain-restart

Conversation

@Wibias

@Wibias Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Add confirm-gated Drain & restart on the Memory observability card (EN) / 작업 완료 후 재시작 (KO), with in-flight count and draining/reconnect UI.
  • New POST /api/system/restart accepts immediately (202), runs a fixed 60s drainAndShutdown, then respawns via detached ocx ensure (or service supervisor exit) — not /api/stop teardown.
  • Extend GET /api/system/memory with scalar �ctiveTurnCount + isDraining; i18n (6 locales), docs, and route/GUI regression tests.

Closes #563

Test plan

  • �un run typecheck
  • �un test tests/system-restart.test.ts tests/memory-watchdog.test.ts tests/shutdown-drain.test.ts tests/issue-452-empty-503.test.ts
  • �un test tests/memory-observability-card.test.tsx (from gui/)
  • �un run lint (gui)
  • �un run privacy:scan
  • CI green on Linux/Windows/macOS
  • Manual: open dashboard Memory card → confirm shows in-flight count → drain shows progress → proxy returns on /healthz
  • Confirm /api/stop still restores native Codex; /api/system/restart does not

Summary by CodeRabbit

  • New Features

    • Added a confirmation-gated Drain & restart action to the memory observability dashboard.
    • Displays active requests and clear draining, reconnecting, success, and failure statuses.
    • Automatically waits for in-flight work to finish and reconnects after restart.
    • Added localized messaging across supported languages.
  • Documentation

    • Updated Windows memory troubleshooting guidance with the new restart workflow.

Expose a longer 60s informed recycle on the memory card (POST /api/system/restart) that reuses drainAndShutdown and respawns via ensure/service without Codex teardown (lidge-jun#563).
@github-actions github-actions Bot added the enhancement New feature or request label Jul 28, 2026
@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Wibias, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 10 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 70542235-4f0a-4479-a366-f235d68c5703

📥 Commits

Reviewing files that changed from the base of the PR and between 85ff461 and 190c086.

📒 Files selected for processing (9)
  • docs-site/src/content/docs/troubleshooting/windows-memory.md
  • gui/src/components/MemoryObservabilityCard.tsx
  • gui/tests/memory-observability-card.test.tsx
  • src/cli/index.ts
  • src/server/index.ts
  • src/server/lifecycle.ts
  • src/server/management/system-restart.ts
  • tests/shutdown-drain.test.ts
  • tests/system-restart.test.ts
📝 Walkthrough

Walkthrough

The memory observability card now supports a confirmed 60-second drain-and-restart workflow. Server routes expose active-turn state and restart acceptance, while the UI handles draining, reconnecting, errors, translations, tests, and documentation.

Changes

Memory drain-and-restart flow

Layer / File(s) Summary
Restart lifecycle implementation
src/server/management/system-restart.ts
Adds idempotent restart acceptance, 60-second draining, conditional ensure respawn, process exit, and injectable test I/O.
Management API and lifecycle fields
src/server/management/system-routes.ts, tests/memory-watchdog.test.ts, tests/system-restart.test.ts
Adds activeTurnCount and isDraining to memory responses, introduces POST /api/system/restart, and tests scheduling, duplicate acceptance, supervision, exit, and HTTP 202 responses.
Dashboard restart flow
gui/src/components/MemoryObservabilityCard.tsx, gui/src/i18n/*.ts, gui/tests/memory-observability-card.test.tsx
Adds restart-support detection, confirmation, draining/reconnecting/error states, health polling, localized messages, deterministic request mocking, and interaction coverage.
Workflow documentation
docs-site/src/content/docs/troubleshooting/windows-memory.md
Documents the confirm-gated drain, active-turn wait, existing 503 drain response, and ensure/service-supervisor restart path.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant MemoryCard
  participant SystemRoutes
  participant SystemRestart
  participant ProcessSupervisor
  User->>MemoryCard: Confirm Drain & restart
  MemoryCard->>SystemRoutes: POST /api/system/restart
  SystemRoutes->>SystemRestart: acceptSystemRestart()
  SystemRestart->>ProcessSupervisor: drain, ensure, and exit
  ProcessSupervisor-->>MemoryCard: /healthz becomes available
Loading

Possibly related PRs

  • lidge-jun/opencodex#427: Established the memory observability card and /api/system/memory diagnostics extended by this restart flow.

Suggested labels: enhancement, bug

Suggested reviewers: lidge-jun, ingwannu

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding drain-and-restart from the memory observability card.
Linked Issues check ✅ Passed The PR implements the requested confirm-gated memory-card restart, 60s drain, 503 draining behavior, memory observability fields, i18n, tests, and docs.
Out of Scope Changes check ✅ Passed The changed files stay focused on the restart feature and its supporting UI, API, docs, tests, and translations, with no unrelated subsystem work visible.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 85ff4611d1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (!serviceInstalled) {
(io.spawnEnsure ?? spawnDetachedEnsure)();
}
(io.exitProcess ?? ((code: number) => { process.exit(code); }))(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use a restart path compatible with failure-only supervisors

For the Linux systemd service and both Windows backends inspected, an installed service only restarts failed processes: src/service.ts configures Restart=on-failure, the Task Scheduler wrapper loops only for nonzero %ERRORLEVEL%, and WinSW uses <onfailure>. This branch skips ocx ensure whenever the service is merely installed and then exits with code 0, so Drain & restart leaves the proxy permanently stopped on those standard service installations. Invoke the supervisor's restart operation, use an intentional failure status for these backends, and add coverage against the actual supervisor policies rather than a mock that assumes every installed service respawns.

AGENTS.md reference: AGENTS.md:L93-L95

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 1e20955: supervised service children now exit(1); non-supervised path spawns ocx start.

restartAccepted = true;
schedule(async () => {
const drain = io.drainAndShutdown ?? drainAndShutdown;
await drain(undefined, MEMORY_DRAIN_RESTART_MS);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count turns before waiting on the upstream

When an admitted /v1/responses request is still awaiting upstream headers, it has not yet reached registerTurn()—for example, the passthrough SSE path registers only after upstreamResponse exists in src/server/responses/core.ts. If Drain & restart is clicked during that phase, activeTurns can be empty, so this call completes immediately and the process cuts the request instead of allowing the advertised 60-second drain. Track the turn from request admission through response completion and add a regression test with an upstream whose headers are delayed.

AGENTS.md reference: AGENTS.md:L93-L95

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged — early registration before upstream headers is a pre-existing gap shared with POST /api/stop drain. Out of scope for this recycle-path PR; happy to follow up as a dedicated drain-tracking issue if maintainers want it.

Comment thread src/server/management/system-restart.ts Outdated
const serviceInstalled = (io.isServiceInstalled ?? isServiceInstalled)();
// Service supervisors respawn on exit; spawning ensure would race a second start.
if (!serviceInstalled) {
(io.spawnEnsure ?? spawnDetachedEnsure)();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bypass the autostart gate for an explicit restart

When no service is installed and codexAutoStart is false, this launches ocx ensure, but handleEnsure() explicitly returns without starting anything for that supported configuration. The old process then exits, so the confirm-gated action always shuts the proxy down rather than restarting it; the troubleshooting page's claim that this action restarts via ocx ensure is therefore incorrect for these users. An explicit restart should launch start directly or provide an ensure mode that bypasses the autostart preference.

AGENTS.md reference: AGENTS.md:L96-L97

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 1e20955: non-supervised path now spawns detached ocx start --port (bypasses ensure's codexAutoStart gate).

setData(json);
setUnavailable(false);
setSupportsRestart(typeof json.activeTurnCount === "number");
if (json.isDraining && restartPhase === "idle") setRestartPhase("draining");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Complete the UI state when restart has no observable outage

When a zero-turn restart finishes between the 5-second memory polls, the immediate poll triggered by entering draining can still succeed against the old process and the next poll can already succeed against the new one. Because only a failed poll transitions to reconnecting and a successful non-draining payload never leaves draining, the card then remains disabled and displays “Draining” indefinitely even though the restart completed. Capture the original health pid and poll until it changes, or otherwise recognize a post-acceptance healthy replacement without requiring an observed connection failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 1e20955: capture pre-restart pid and clear draining/reconnect once memory/healthz reports a different pid (or observed outage + healthy replacement).

if (!serviceInstalled) {
(io.spawnEnsure ?? spawnDetachedEnsure)();
}
(io.exitProcess ?? ((code: number) => { process.exit(code); }))(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Suppress teardown cleanup during an interactive recycle

For a proxy launched interactively without OCX_SERVICE, this process.exit(0) still runs the process.on("exit", syncCleanup) handler in src/cli/index.ts, which restores native Codex, strips the Grok fence, and reverts the injected environment. Since the detached ensure child is started immediately before that synchronous cleanup, the old cleanup races the replacement's injection and can leave a healthy restarted proxy whose clients no longer route to it, contrary to this module's stated no-teardown contract. Mark the current process as recycling before exit or complete cleanup before spawning the replacement, and cover preservation of the injected files in an integration test.

AGENTS.md reference: AGENTS.md:L93-L95

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 1e20955: markRecyclingForExit() skips restoreNativeCodex / stripGrokConfig / revertSystemEnv in syncCleanup so the recycle keeps injection intact.

Comment thread src/server/management/system-restart.ts Outdated
}

function spawnDetachedEnsure(): void {
const child = spawn(process.execPath, [process.argv[1], "ensure"], {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the active listen target across restart

When the current proxy was started with an explicit --port or selected a fallback because config.port was occupied, the detached command receives no current-port argument and handleEnsure() instead hard-pins config.port ?? 10100. The restart can therefore fail while waiting on the still-occupied preferred port, or come back on a different port so the dashboard at the original apiBase never reconnects. Capture the live server/runtime port and launch the replacement on that same target, as the update restart flow already does.

AGENTS.md reference: AGENTS.md:L93-L95

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 1e20955: spawn pins the live listen port from the Bun server / runtime record.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs-site/src/content/docs/troubleshooting/windows-memory.md`:
- Around line 55-58: Update the documented proxy restart flow around the
60-second active-turn drain in the Windows memory troubleshooting guidance to
explicitly state that any remaining active turns are aborted when the timeout
expires before restarting. Keep the existing wait-limit and restart behavior
unchanged.
- Around line 53-55: Update the dashboard description near the “Memory
observability” card and “Drain & restart” action to call the displayed value the
current active-turn count, not the in-flight request count. Keep the wording
consistent with the management API’s activeTurnCount semantics; do not imply
broader HTTP request accounting unless a separate request-count field is
actually exposed.

In `@gui/src/components/MemoryObservabilityCard.tsx`:
- Around line 338-368: Update the lifecycle status spans rendered by
MemoryObservabilityCard around restartPhase to use polite live-region semantics,
such as aria-live="polite" or role="status", so draining, reconnecting, and
error transitions are announced to screen readers. Preserve the existing
conditional rendering, text, and styling.
- Around line 217-243: Update the reconnect polling effect in
MemoryObservabilityCard’s useEffect to mirror the sibling polling guard: track
an inFlight state, skip each scheduled tick while a previous request is active,
and always clear the guard after completion. Pass an AbortSignal.timeout(10_000)
to the /healthz fetch so hung requests are bounded, while preserving the
existing cancellation, retry, and give-up behavior.

In `@src/server/management/system-restart.ts`:
- Around line 61-72: Update the restart acceptance path around the scheduled
callback to invoke a lifecycle begin-drain operation synchronously before the
200ms delay. Modify drainAndShutdown to reuse the already-entered draining state
without resetting it, so request rejection and /api/system/memory reporting take
effect immediately. Add a regression test covering a data-plane request being
rejected after restart acceptance but before the scheduled callback executes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7b52943e-4c14-445c-a1c2-aa0c42536581

📥 Commits

Reviewing files that changed from the base of the PR and between de35caa and 85ff461.

📒 Files selected for processing (13)
  • docs-site/src/content/docs/troubleshooting/windows-memory.md
  • gui/src/components/MemoryObservabilityCard.tsx
  • gui/src/i18n/de.ts
  • gui/src/i18n/en.ts
  • gui/src/i18n/ja.ts
  • gui/src/i18n/ko.ts
  • gui/src/i18n/ru.ts
  • gui/src/i18n/zh.ts
  • gui/tests/memory-observability-card.test.tsx
  • src/server/management/system-restart.ts
  • src/server/management/system-routes.ts
  • tests/memory-watchdog.test.ts
  • tests/system-restart.test.ts

Comment thread docs-site/src/content/docs/troubleshooting/windows-memory.md Outdated
Comment thread docs-site/src/content/docs/troubleshooting/windows-memory.md Outdated
Comment thread gui/src/components/MemoryObservabilityCard.tsx Outdated
Comment thread gui/src/components/MemoryObservabilityCard.tsx
Comment thread src/server/management/system-restart.ts
Address Codex review: use failure-exit for supervised service children, spawn start with the live port (not ensure), suppress injection teardown on recycle, and clear the GUI draining state on pid change.
@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Set draining before the 200ms flush delay, bound reconnect /healthz polls, announce restart status to assistive tech, and clarify docs around active-turn drain timeout abort.
@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@Wibias
Wibias merged commit 94a83bc into lidge-jun:dev Jul 28, 2026
12 checks passed
@Wibias
Wibias deleted the feat/563-memory-drain-restart branch July 28, 2026 01:19
@dev-shinyu

Copy link
Copy Markdown
Contributor

Issue author here — thanks for picking this up so quickly, and for implementing
the proposal essentially verbatim (wording table, 60s fixed, 503 reuse,
supervisor-warning default included). The deviation from my sketch — respawning
via detached ocx start / supervisor exit(1) instead of the /api/stop
teardown path, with markRecyclingForExit() keeping the Codex/Grok fences —
is an improvement: a recycle shouldn't tear down routing.

One minor edge: if the detached spawn fails (sync throw, or an 'error'
event before the child actually starts), the scheduled callback can leave the
proxy either stuck with restartAccepted = true or exiting after
markRecyclingForExit() with no replacement. A try/catch + spawn error handler
that still exits cleanly (or resets the latch) would close that.

Happy to see this land — the card finally closes the observe→act gap from #427.

@Wibias

Wibias commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up for the spawn-failure edge you flagged: #594 — wait for spawn success before recycle/exit(0); on sync throw or pre-start error, exit(1) without markRecycling (listen socket is already closed after drain, so a latch reset cannot recover serving).

Wibias added a commit that referenced this pull request Jul 28, 2026
…-up) (#594)

* fix(server): exit cleanly when drain-and-restart spawn fails

Follow-up to #580: wait for detached start spawn success, and on sync throw or pre-start error exit(1) without markRecycling so we never leave a drained process latched or exit(0) with no replacement.

* fix(server): sanitize restart spawn errors and restore fences

Address Codex review on #594: log only errno codes (no pathful messages), and clear inherited OCX_SERVICE on spawn failure so ensure/tray daemons still run syncCleanup restore.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants