Skip to content

Studio desktop: hide the window as soon as a quit is committed, and exit the backend without finalization - #15723

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:fix/desktop-hide-window-on-quit
Oct 28, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:fix/desktop-hide-window-on-quit

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Quitting the Unsloth desktop app took a few seconds to actually close. The quit path blocks on reaping the backend before app.exit(0) (SIGTERM to the backend process group, then up to 5s before SIGKILL on Unix; about 18s worst case on Windows), and the main window stayed on screen the whole time. Only Windows covered that wait, with a closing overlay; on macOS and Linux the window simply looked stuck.

Two things made up the wait:

  • The window was never hidden during the reap. Typical quits took 1–3s from the user's perspective.
  • The backend took ~1.4s to exit after its own shutdown finished in ~0.3s. No non-daemon threads or slow atexit hooks were involved: the time was CPython interpreter finalization tearing down a large heap after the last atexit hook. Calling os._exit at that point cut SIGTERM-to-exit from 1.42s to 0.34s.

Changes

Desktop: hide the main window as soon as a quit is committed

  • quit_sequence keeps its ordering contract (confirmation dialogs first, then cover, then reap), but the cover step now hides the main window on every platform instead of emitting the Windows-only app-closing overlay events. A guard re-shows the window if the reap unwinds and the app stays up. A window that was already hidden (tray quit, --hidden start) is never popped back.
  • macOS Dock / logout / AppleScript quits: applicationShouldTerminate: now answers NSTerminateNow only when nothing needs confirming and no main window is on screen; otherwise it takes the existing NSTerminateLater quit thread. With NSTerminateNow the reap runs in RunEvent::Exit with the main thread blocked, where a hide is applied but never presented.
  • Unix termination signals: the cleanup thread sends a fire-and-forget hide() before the reap. It deliberately skips the blocking is_visible() round trip so a hung UI thread cannot keep the backend from being reaped.

The saved window state uses SIZE | POSITION | MAXIMIZED only (no VISIBLE), so exiting with the window hidden does not make the next launch start hidden.

Backend: exit without interpreter finalization after shutdown

At the end of the signal / HTTP shutdown path, _exit_without_finalizing() runs the interpreter's own exit steps in its order, then calls os._exit:

  1. threading._shutdown(): join non-daemon threads and thread-pool workers. This stays unbounded so in-process writers (dataset import, LoRA / Q4NX export run via asyncio.to_thread) finish their writes.
  2. atexit._run_exitfuncs(): every Python atexit hook (logging shutdown, child-process sweep, pid-file removal, ...).
  3. Flush stdout/stderr, exiting 120 on a flush failure as CPython does.

Only module/heap teardown is skipped. This covers the desktop quit, the Windows HTTP shutdown, and unsloth studio stop.

Risks / tradeoffs

  • Skipping finalization also skips native Py_AtExit / C atexit handlers and unflushed C stdio buffers, plus __del__ of objects still alive at exit. Children are already reaped at that point, so what is lost is at most native diagnostic output.
  • The Windows closing overlay in the frontend (closing-signal.ts, ClosingScreen) is no longer triggered; removing it is left for a follow-up.
  • Unchanged: a quit within a few seconds of launch can still wait on uvicorn's "Waiting for connections to close" for startup's in-flight model scans until the desktop's 5s SIGKILL, as before. The window is already hidden, so only the process lingers. Bounding it (uvicorn's timeout_graceful_shutdown, or a bounded thread join) was tried and dropped: it cancels or abandons in-flight work that persists state across several steps.

Validation

  • Live app (debug build, macOS), with on-screen window presence sampled every 10ms:

    Quit path Window off screen Before
    Menu "Quit Unsloth" 0.28s stayed until process exit
    NSRunningApplication.terminate() (Dock-style quit) 0.30s stayed until process exit
    SIGTERM 0.44s stayed until process exit
  • Backend SIGTERM → process exit, standalone: 1.42s → 0.34s, exit status 0, all atexit hooks reached.

  • Tests: quit_sequence ordering, unwind re-show, and visibility decisions (Rust). A subprocess exit test checks that a worker outliving any bounded budget finishes before atexit hooks, hooks run, stdout is flushed, finalization is skipped, and an unflushable stdout exits 120. Each new test was checked against targeted mutants of the code it covers.

cd studio/src-tauri && cargo test -- quit reap needs_hiding termination
cd studio/backend && python -m pytest tests/test_exit_without_finalizing.py tests/test_graceful_shutdown_saves_training.py

Quit evidence (Linux, Xvfb)

Debug desktop builds of the merge base and this PR, launched against a stub backend that, like a loaded Studio, takes 3 s to exit after SIGTERM. The app was quit with SIGTERM and window visibility was sampled every 50 ms (xwininfo), 2 rounds per side:

Side Window off screen after quit App process exit
main 3.12 s / 3.10 s (stays up for the whole reap) 3.12 s / 3.10 s
this PR 0.00 s / 0.00 s (first sample) 3.12 s / 3.13 s

Desktop quit before/after: main keeps the window up 0.5 s after quit, this PR has already hidden it

The backend side, measured on the in-process unsloth studio --api-only path the desktop app launches (SIGTERM to process exit, 3 interleaved rounds): main 2.06 / 2.83 / 3.13 s, this PR 0.42 / 0.47 / 0.73 s.

Lyxot added 2 commits October 28, 2026 16:49
Quitting blocks on reaping the backend (SIGTERM, then up to 5s before SIGKILL on Unix; about 18s worst case on Windows), and the main window stayed on screen for all of it, so the app looked stuck for a few seconds. Only Windows had a closing overlay.

Every committed quit now hides the main window before the reap, on all platforms: the quit thread hides it after the confirmation dialogs and re-shows it if the reap unwinds; a macOS Dock, logout, or AppleScript quit takes the NSTerminateLater quit thread whenever a window is on screen, because NSTerminateNow reaps in RunEvent::Exit with the main thread blocked, where a hide is never presented; Unix termination signals hide fire-and-forget before the reap, so a hung UI cannot hold up cleanup. The Windows-only overlay events are no longer emitted.
…shutdown

After a signal or HTTP shutdown the backend finished its own cleanup in about 0.3s but the process took about 1.4s to exit: CPython spent the rest tearing down a large heap after the last atexit hook. The desktop app's quit and `unsloth studio stop` wait on that exit.

The end of the shutdown path now runs the interpreter's own exit steps in order (join threads, run atexit hooks, flush stdio with CPython's 120 status on a flush failure) and then calls os._exit. The thread join stays unbounded so in-process writers finish. Measured SIGTERM to exit: 1.42s to 0.34s.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 28, 2026 08:51
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-28T09:14:10.836733Z
We couldn’t complete this review. Comment @codex review to try again.
1ef41bb Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Lyxot

Lyxot commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@Lyxot

Lyxot commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
The desktop app and an in-venv `unsloth studio` serve the backend in-process from the CLI, never through run.py's __main__, so the fast exit never ran on the desktop quit.
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #15723, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#585.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror f2afebbe97 (this PR's 6ba26f231)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: f2afebbe97

No triage reaction was recorded on the mirror

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: f2afebbe97

View security finding report

Only the user who started this review can view the report in Codex.

No triage reaction was recorded on the mirror

Verdict

The round did not reach a clean review on the mirror before it closed.

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit a7a1a85 into unslothai:main Oct 28, 2026
24 of 85 checks passed
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ugh run_pwsh (#15758)

## Summary

`Repo tests (CPU, studio)` fails on main, so it is red on every recent
staging CI run (#15680, #15696, #15716, #15723 and others). Of its 6
failures, 4 are tests that no longer match intentional changes; this PR
fixes those. The other 2 are real product slips on the login screen and
are fixed separately.

**Media picker contracts (3 failures).** #15726 lined the Images, Audio
and Video model pickers up with Chat:
- The picker now uses `className="ml-1.5 max-w-full overflow-hidden
!pl-2.5 !pr-1.5 !h-[var(--studio-chat-control-height,34px)]"`.
- It no longer sets a `triggerLabelClassName` override.

`tests/studio/test_desktop_reliability_frontend_contract.py` still
pinned the old class string and the old label override, and counted two
scaled `!h-[calc(34px*var(--ui-space-scale,1))]` literals on the Images
and Video pages (and one on Audio) that are now the shared token:

```
images-page.tsx states 1 scaled !h-34px, not 2
assert 'className="!h-[34px] max-w-full gap-1 ...' in header
```

**PowerShell spawn (1 failure).**
`tests/python/test_installer_compile_bytecode.py:271` (from #15646)
starts PowerShell with `subprocess.run`.
`tests/studio/test_pwsh_calls_use_the_shared_runner.py` forbids that,
because direct spawns share one PowerShell startup cache across xdist
workers and can die at startup.

## Change

- **`test_desktop_reliability_frontend_contract.py`:**
- The Images and Audio header contracts assert the new picker class
(`_MEDIA_PICKER_CLASS`), and that the label is not overridden, so the
trigger reads like Chat's.
- The scale table's `!h-34px` counts drop to what the pages still state
literally: Images 1, Audio 0, Video 1. The "no bare `!h-[34px]`" half of
that check is unchanged.
- New test `test_the_media_pickers_take_chats_scaled_control_height`:
all three pages use the picker class, and `index.css` still defines
`--studio-chat-control-height` as `calc(Npx * var(--ui-space-scale,
1))`. This keeps the original point of the scale check, a pill that
grows with the UI scale, attached to the token the height now comes
from.
- **`test_installer_compile_bytecode.py`:** the PowerShell case runs
through `run_pwsh` from `tests/_shared/unsloth_pwsh_runner.py`, with the
same argv and keyword arguments.

## Testing

- These three files: 80 passed (pwsh is installed here, so the
PowerShell cases really ran). On main, the same tests fail 4.
- **Sabotage:** with `--studio-chat-control-height` changed to a bare
`33px`, the new scaling test fails.
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 28, 2026
danielhanchen added a commit that referenced this pull request Oct 28, 2026
Follow-up to #15723: drops comment lines from the desktop quit path that
restated the code or a number already in the PR description.

- `hide_main_window_for_quit`: keeps only the main-thread invariant (the
hide lands once the event loop runs again).
- `quit_sequence`: drops the note that the steps are injected for tests.
- `test_exit_without_finalizing.py`: drops a restatement of the flush
assertion.

Comments only: an AST and tree-sitter check confirms no code changed.
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ady gone (#15764)

## Summary

`AppImage model download E2E` fails intermittently on unrelated PRs, for
example the header-only `chore/desktop-release-agpl-header` run and both
attempts of the #15723 staging run:

```
AssertionError: Timed out waiting for the packaged frontend to render; last result: False
```

The app is fine in every one of these failures. The uploaded
`failure.png` / `failure-webview.json` show it on
`tauri://localhost/chat` with the sidebar rendered (6 `nav-row-*` rows
on the agpl-header run), and `tauri.log` shows the same preflight,
backend start and desktop auth sequence as passing runs.

The first wait in `tests/studio/appimage_model_download_webdriver.py`
demands the transient `Starting Unsloth...` splash:

```python
"return document.body && document.body.innerText.includes('Starting Unsloth')"
```

When the desktop handoff completes before the WebDriver session attaches
and starts polling, the splash is already gone, so this can never become
true, even though the next wait ("the deterministic desktop backend
handoff", splash gone) would pass at once.

## Change

The "rendered" wait now also accepts the app shell
(`[data-testid^="nav-row-"]`, the sidebar rows). The handoff wait after
it is unchanged, so the run still has to see the splash gone before
driving the Model hub.

## Testing

The old and new predicates evaluated in Chromium:

| Page | old | new |
|---|---|---|
| captured failure DOM (app on /chat) | False | True |
| splash only | True | True |
| blank `#root` | False | False |
| an error page with no shell | False | False |

So the wait still fails when nothing rendered, and stops failing on the
healthy page it used to reject.

- `tests/security/test_release_desktop_appimage.py` +
`tests/studio/test_appimage_fixture_cors.py`: 26 passed.
- The E2E itself runs on this PR's desktop workflow (the script path is
in its `paths:` filter).
danielhanchen added a commit that referenced this pull request Oct 28, 2026
## Summary

`Frontend unit tests` fails on main (seen as the Windows leg on #15795;
reproduces locally on `795da3b42a`) with three tests that read
`studio/src-tauri/src/main.rs` and still describe the quit as it was
before #15723:

```
not ok - a quit with no window on screen raises no overlay
    (expects fn quit_raises_the_overlay)
not ok - both sides agree on the event names
    (expects const APP_CLOSING_EVENT / APP_CLOSING_CANCELLED_EVENT in main.rs)
not ok - macOS termination checks unsaved transcripts before allowing exit
    (expects begin_or_attach_termination(quit_requires_confirmation(app)))
```

#15723 changed the quit on purpose: the cover step now hides the main
window on every platform instead of emitting the Windows-only
`app-closing` overlay events, a window that was not on screen is left
hidden, and the macOS terminate path holds on while a window is on
screen (`quit_requires_confirmation(app) ||
main_window_on_screen(app)`). Its description notes the frontend overlay
(`closing-signal.ts`, `ClosingScreen`) is no longer triggered and leaves
removing it to a follow-up. The product is right; these three tests were
not updated with it.

## Change

`studio/frontend/tests/desktop-closing-overlay.test.ts`: the two tests
pinned to the removed Rust emitters are replaced by the contract that
replaced them:

- **a quit with no window on screen leaves it hidden**:
`hide_main_window_for_quit` hides only when `main_window_on_screen(app)`
says the window is visible, read via `window.is_visible()`;
- **the quit hides the window after the confirmations and before the
reap**: in `quit_sequence`, `if !confirm()` comes before `hide()`, which
comes before `reap()`; and `main.rs` does not emit `app-closing`, so if
the overlay is ever wired back the test says to put it back under test
(or remove it).

The store-level overlay tests in the same file still pass and still
cover `closing-signal.ts` until the follow-up removes it.

`studio/frontend/tests/audio-transcript-lifecycle.test.ts`: the macOS
check now matches
`begin_or_attach_termination(quit_requires_confirmation(app)...`, so the
terminate path may hold on for more reasons but never fewer; the `||
renderer.unsaved_transcript` and `confirm_quit_with_unsaved_transcript`
checks are unchanged.

## Testing

- Whole frontend suite (`node --experimental-strip-types --test
"tests/**/*.test.ts"`): 3 failing on main (the three above), 0 with this
change.
- Sabotage on `main.rs`, one at a time:
- reaping before hiding fails "the quit hides the window after the
confirmations and before the reap";
- hiding without asking whether the window is on screen (`let hide =
true;`) fails "a quit with no window on screen leaves it hidden";
- dropping `|| renderer.unsaved_transcript` from
`quit_requires_confirmation` fails the macOS transcript test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants