Skip to content

Restart the desktop server after Change keys saves - #754

Open
Patriciaath999 wants to merge 3 commits into
sysprog21:mainfrom
Patriciaath999:restart-desktop-after-change-keys
Open

Patriciaath999 wants to merge 3 commits into
sysprog21:mainfrom
Patriciaath999:restart-desktop-after-change-keys

Conversation

@Patriciaath999

@Patriciaath999 Patriciaath999 commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem and behavior

After Change keys saved new keys, the desktop app kept serving on the old
ones until the person quit and reopened it, because only a new launch reads
the config file.

Now, once a save succeeds and no interview is running, the app starts its
server again on the new keys and returns to the lobby, never showing the
failure page. An interview admitted before the save is not cut off: the
server stops admitting new ones, waits for those already running to finish,
report included, and only then asks to be restarted. A server started from
a terminal behaves as before and is restarted by hand. So does a child
without a Google key: the interviews it serves are hosted by an interviewer
running elsewhere, out of its sight, so it cannot tell when none is running.

Approach

The server, when a launcher owns it (AfterSave::Launcher) and it hosts
its interviewer (it has a dispatcher), closes admission after a successful
save, waits until it is idle, and prints one stdout line,
codetrial: keys saved and no interview running: restart now.
The /api/setup summary and the save response say whether the app
restarts the server (appRestarts), and the Setup page's notice says so
instead of asking the person to restart it.
The desktop shell treats that line as a restart request only after the
server has reported it is listening, then stops the child and launches it
again on a thread of its own, since the stop can take up to the grace
period. WebRTC is already known from the launch being replaced, so the
shell goes back to Starting and the ready line alone reopens the window.
The running server and a restart under way have one owner, so a quit
during the restart waits for the old server to stop, and for any server
the restart started, before the app exits.

The line is printed only for a launcher's child, so a terminal server keeps
admitting interviews on the keys it started with. The README and
docs/desktop.md say what a launcher handing over
CODETRIAL_CHANGE_KEYS_CODE has to do once it reads that line. The three commits are
the server side, the Setup page's notice and the desktop side.

Validation

  • The new unit tests (server admission, the wait for an admitted interview,
    who restarts, a launcher's child keeping admission open after a refused
    save, the shell's phase handling, a quit during a restart), the browser test of the
    notice, run on Windows, the CLI tests that a child with a Google key
    prints the line after the save and never prints the code while one without
    never prints the line, and the desktop tests all pass.
  • I broke each piece on purpose (any server restarting, no wait for a
    running interview, a refused save closing admission, a quit that stops
    only the server it finds, a launcher child that never asks, a shell that ignores
    the line, a restart before ready, swapped phases) and a new test failed
    each time, and the browser test fails without the page change.
  • scripts/test.sh exits 0 in WSL at 0073059; its browser, prettier, eslint
    and dependency-audit lanes were skipped for missing tools. The Setup
    page's browser tests ran on Windows with Playwright Chromium and pass, and
    prettier is clean on the changed test file. This change does not touch
    web/.
  • Not checked: a live desktop restart with a real interview and provider.

Close #688

cubic-dev-ai[bot]

This comment was marked as resolved.

jserv

This comment was marked as resolved.

Comment thread desktop/src/server.rs
let status = if !bound && line.starts_with(BOUND_LINE) {
bound = true;
Status::Ready
} else if bound && line == RESTART_LINE {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The doc comment on start still says it reports to report once, Ready and later perhaps Exited, or Exited alone, but this branch now also reports Restart after Ready, once for every restart line the server prints, and never after Exited since the same finished lock guards it. Update that comment to name Restart and its ordering, so a caller does not read report as being called at most twice.

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.

Updated in 0073059: the comment on start now says report gets Ready once, then Restart for every restart line the server prints, then perhaps Exited, or Exited alone, and that neither Ready nor Restart comes after Exited.

@jserv jserv left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Improve git commit messages per https://cbea.ms/git-commit/ and CONTRIBUTING.md; CI applies the same rules. Hint: run make hooks once per clone, so the hooks check every message before you push.

Rebase the current branch onto the upstream default branch and resolve any conflicts. Run /codetrial-review in AI agents (use $codetrial-review in Codex) and resolve all identified issues. Rework the series into minimal, logically coherent commits, squash closely related commits, and ensure all commit messages follow the project’s rules.

@yuuka5555 yuuka5555 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Requesting changes because quitting during a restart can exit the app before the restart worker finishes stopping the old child, leaving its port occupied. Please coordinate restart and quit so the child is stopped and reaped before the app exits.

I also suggest covering refused saves in launcher mode. The current guard is correct, but removing its successful-save check still passes all 11 focused setup tests; the added regression catches that mutation.

Verified at d4a267de on Ubuntu 26.04 under WSL2 with Rust 1.100.0. The 11 focused setup tests and 8 server-control tests pass. The lifecycle issue was reproduced with a headless process-control probe, not the full Tauri UI. Full desktop validation was blocked by missing gdk-3.0.

The attached archive contains the reproduction scripts, proposed regression test, and logs.

review-pr754-evidence.zip

Comment thread desktop/src/main.rs Resolved
#[tokio::test]
async fn only_a_launchers_child_stops_admitting_interviews_once_it_saves() {
let (livekit, _livekit) = livekit().await;
for (after_save, closes) in [(AfterSave::Launcher, true), (AfterSave::Operator, false)] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This loop covers successful saves, but the existing refusal tests use Server::start, which selects AfterSave::Operator. They therefore do not protect the successful-save guard in save_handler.

At d4a267de, I removed only response.status() == StatusCode::OK && from that condition. All 11 focused setup tests still passed. Adding review_refused_launcher_save_keeps_admission_open passed on the original handler and failed on the mutation:

a refused launcher save closed admission: 403 Forbidden

Add refusal cases using AfterSave::Launcher and the existing Closable dispatcher: a wrong code, no changes, and rejected credentials. Assert that admission stays open and the config remains unchanged after the background work has had a chance to run. The current guard is correct; these cases would catch a later change that triggers shutdown after an unsuccessful save.

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.

Added in c1f8932: a_launchers_child_keeps_admitting_interviews_after_a_refused_save in tests/unit/web/setup_edit.rs saves as a launcher's child with the Closable dispatcher and a wrong code (403), nothing to change (400) and keys LiveKit refuses (400), then checks that admission is still open and the config is unchanged after the background work has had time to run. With response.status() == StatusCode::OK && removed from save_handler it fails.

jserv

This comment was marked as resolved.

A save in Change keys rewrites the config file, but the running server
keeps the keys it started with, so the desktop app could not tell when
new ones may take effect (sysprog21#688). When a launcher owns the server and
the server hosts its interviewer, a successful save now stops admitting
new interviews, waits for the ones already running to finish, report
included, and then prints one line saying it is safe to restart. A
server started from a terminal, and a child without a Google key, whose
interviews are hosted elsewhere out of its sight, behave as before and
are restarted by hand.

Change-Id: I4ea7a97d38cfc76cf2c82521758ce6e3cfb5bbeb
After a save, the Setup page told the person to restart the server even
when the desktop app was about to do it, and said so again when the
page was reloaded while the app waited for an interview to end. The
setup summary and the save response now say whether the app restarts
the server, and for such a server the notice says the app does so once
no interview is running and admits none until then. A server restarted
by hand keeps the notice it had.

Change-Id: I0536cfea49e9342f4dc1d599d6c6dc96813a7f10
After Change keys saved new keys, the desktop app kept serving on the
old ones until the person quit and reopened it. The app now reads the
server's restart request, which only counts once the server has
reported it is listening, then stops the server and starts it again.
It goes back to the lobby without showing the failure page, and reopens
the browser when the interview runs there. The running server and a
restart under way have one owner, so a quit during the restart waits
for the old server to stop, and for any it started, instead of exiting
while either still holds the port.

Close sysprog21#688

Change-Id: Ic7f62961821f91886921b0484361b1e71dde822a
@Patriciaath999
Patriciaath999 force-pushed the restart-desktop-after-change-keys branch from d4a267d to 0073059 Compare November 22, 2026 16:26
cubic-dev-ai[bot]

This comment was marked as resolved.

Comment thread src/web/setup_edit.rs
"livekitEndpoint": super::setup::public_endpoint(value("LIVEKIT_URL")),
"googleApiKey": !value("GOOGLE_API_KEY").is_empty() || !value("GOOGLE_API_KEYS").is_empty(),
"restartPending": regular_file(&self.path).as_deref() != Some(self.contents.as_str()),
"appRestarts": self.app_restarts(dispatcher),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In the summary, appRestarts says whether this server would be restarted after a save, not whether a save here scheduled one. So when restartPending comes from a hand edit of the config file, which docs/desktop.md still offers for adding an option, a launcher's child with an interviewer tells the person the app starts the server again and admits no new interview, while no drain runs, no restart line ever comes, interviews are still admitted and Save changes stays disabled. Record in SetupContext that save_handler spawned the drain (an AtomicBool set beside the tokio::spawn, say) and report appRestarts from the summary only once it is set, so a hand edit keeps the restart-by-hand notice.

Comment thread desktop/src/main.rs
let webrtc = match self {
Phase::Serving => true,
Phase::InBrowser => false,
Phase::Starting { .. } | Phase::Failed => return None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The server prints its restart line once. If it arrives while the shell is still Starting (ready, but the starting page has not yet reported WebRTC), it is dropped here: the server has already closed admission, so it then admits nothing until the person quits the app. That needs a save from an external browser in that window, which is narrow but possible. The comment above rules out a second request, not this first one. Record a pending restart and act on it when open_server resolves the phase, instead of returning.

);
let server = start(&launch_of(&dir, program, "127.0.0.1:9".to_string()), |_| {}).unwrap();
let began = Instant::now();
while !pid.exists() && began.elapsed() < Duration::from_secs(10) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

echo $$ > pid creates the file before it writes the id, so pid.exists() can return in between and read_to_string gives "". kill -0 "" then fails, alive returns false, and assert!(!alive(...)) passes whether or not the server is still running, so the quit test can pass vacuously. Write the id atomically (echo $$ > pid.tmp && mv pid.tmp pid), or wait until the file is non-empty and assert the id parses as a number.

Comment thread src/launch.rs
bound,
change_keys_code(&launched_by)?,
match launched_by {
LaunchedBy::Parent(_) => crate::web::AfterSave::Launcher,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LaunchedBy::Parent is any launch with CODETRIAL_EXIT_WITH_STDIN, which the README documents for any program that starts the server as its child. Every such launcher that also hands over CODETRIAL_CHANGE_KEYS_CODE now gets a server that, after Change keys saves, closes admission and waits for a restart the launcher does not know to perform. Until this change that server kept serving on its old keys; after it, the server never admits another interview. Make the restart protocol an explicit opt-in that the desktop app sets (an environment variable beside the other two), and keep AfterSave::Operator for a parent that does not opt in.

Comment thread src/web/setup_edit.rs
"livekitEndpoint": super::setup::public_endpoint(value("LIVEKIT_URL")),
"googleApiKey": !value("GOOGLE_API_KEY").is_empty() || !value("GOOGLE_API_KEYS").is_empty(),
"restartPending": regular_file(&self.path).as_deref() != Some(self.contents.as_str()),
"appRestarts": self.app_restarts(dispatcher),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

appRestarts is true for any launcher's child with a dispatcher, whether or not this process scheduled a drain. restartPending also turns true when someone edits codetrial.env.local on disk, which docs/desktop.md tells people to do to add an option. The page then says the app will restart the server on the new keys, the form stays disabled, and no restart ever comes, because only a save through save_handler spawns the drain. Report appRestarts only once a save here has started it, for example from a flag set where the drain is spawned.

Comment thread src/web/setup_edit.rs
/// Returns once `dispatcher` admits nothing new and runs nothing it admitted,
/// report included.
async fn drain(dispatcher: &dyn RoomDispatcher) {
dispatcher.close_admission();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Closing admission here routes a new interview to DispatchRefusal::Stopping, so a candidate who starts one during the drain is told "The server is shutting down and is not starting new interviews. Try again later." The server is about to come back on new keys within seconds, and the description does not mention this state. Give the drain its own refusal, for example "The server is restarting on new keys; try again in a moment.", and cover it in the token test.

Comment thread desktop/src/main.rs
}
note("Change keys saved: starting the server again");
let relauncher = app.clone();
shell.server.replace(STOP_GRACE, move || {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

server::start starts its reporter threads before launch installs the returned handle with Slot::put. If Ready and Restart arrive before that installation, replace finds no server and launches another child without stopping the first. A headless probe using the unchanged launch/restart functions and actual server module, with a scheduling gate before handle publication, reproduces an occupied port and Phase::Failed without requesting quit. Queue lifecycle events until the handle is installed, or serialize publication and restart, and add a regression for this ordering.

Comment thread src/web/setup_edit.rs
// between that check and this one.
tokio::spawn(async move {
drain(&*dispatcher).await;
let _ = writeln!(std::io::stdout(), "{RESTART_LINE}");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The restart announcement is not ordered after delivery of the successful save response. Using the actual handler with a test-only post-handler transport gate, the launcher receives this line and closes stdin while the response is still pending: the config is saved, but the client receives zero response bytes because the stdin watcher exits the process. Coordinate restart with completion or acknowledgment of the save response, and add an ordering regression rather than a timing delay.

@jserv

jserv commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Some review comments on this pull request are not settled yet. Please refine the change per the review comments listed below, reply on each thread with what you changed or why you did not, and mark each thread resolved yourself once it is settled (Resolve conversation, at the bottom of the thread). The pull request stays blocked while review threads are open.

Not addressed at the current head:

Addressed at the current head; reply with what changed and resolve:

Checked at 0073059.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Restart the desktop server after Change keys saves

4 participants