Skip to content

Studio: update in the background and restart when ready - #9890

Merged
mahiatlinux merged 44 commits into
unslothai:mainfrom
NilayYadav:studio-background-update
Aug 29, 2026
Merged

mahiatlinux merged 44 commits into
unslothai:mainfrom
NilayYadav:studio-background-update

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Right now, updating the desktop app stops the backend and shows a "do not close" screen for a few minutes. With new versions shipping every day or two, that gets old fast.

This change makes updates happen in the background. When a new version is found, the banner shows an Update button. Clicking it downloads the new app and sets up the new backend in a separate copy, while the current one keeps running. You can keep chatting or training in the meantime. A small pill in the corner shows progress, with a toggle to see the log. When everything is ready, the pill says Restart. Restarting takes a few seconds instead of a few minutes.

On the next launch the app switches to the new copy. If the new backend fails to start, the app goes back to the previous copy on its own and will not try that version again. If preparing the update fails for any reason, the old full update still works as before.

What changed:

  • New unsloth studio update --stage command that builds the update in a copy of the environment
  • Setup scripts accept a stage folder so they never touch the live install while staging
  • Desktop app downloads the new bundle itself and keeps it until restart
  • Desktop app swaps in the staged backend at launch, with rollback if it does not come up healthy
  • Update banner turns into a small progress pill with a log view, and only starts when you click Update

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review, GitHub Actions A/B, and UI evidence

Reviewed at 9ed2743 and 8c0e9a7. Four Codex items, all genuine: three fixed here, one deferred with reasoning in its thread.

Fixed

  • _studio_stage.py (P1) — make_relocatable ran only before run_update, so the console script the update reinstalls kept an absolute shebang into .update-stage. Activation moves the venv out of that path and POSIX executes bin/unsloth directly, so the activated backend could never exec and would be rolled back on every release. It now relocates again after the update, and verification probes the launcher itself rather than only python -m unsloth_cli.
  • staged_update.rs (P1) — swap_entries skipped a name the incoming tree lacked. On a legacy install with no tiered sidecars, rollback left the failed update's .venv_t5_* live beside the restored backend. Rollback now evicts them; activation keeps the old behaviour.
  • use-tauri-update.ts (P1) — the idle wait never ended when fetchHealth() returned null, which is exactly the stopped or broken backend the user is trying to update out of, and the pill offers no action while preparing. The wait is bounded at five minutes and falls back to the classic update.

Deferred — the native helpers (llama.cpp, whisper.cpp) sit outside the stage root, so a background preparation does replace them under a live backend. Confirmed, not blocking the above, and it needs its own PR: see the thread on studio/setup.sh.

Also fixed here — the four new settings.about.update.* keys were only in en and pt-BR, and the staged activation broke the setup.ps1 shape tests/studio/test_amd_venv_repair_loop.ps1 pins. A staged run also deleted the live legacy .venv_t5 while building its tiered replacements inside a stage that may never activate.

GitHub Actions A/B — all six jobs green

Same runner, same probe, same command in each pair; only the tree under test changes.

Check BEFORE 3c10a7ae6 AFTER
locale parity --strict fails on the four missing keys passes
test_amd_venv_repair_loop.ps1 (ubuntu + windows) FAIL the activation block was found, FAIL the guard does not delete anything whole suite passes
staged-root guard live legacy .venv_t5 deleted during a staged run live install untouched
staging failure guards both new tests fail all pass

The three remaining reds are already red on main

Proved in the same run against e745043b3 with no PR code present:

  • workflow-trigger lint — playwright_tool_activity.py is named by no workflow.
  • Repo tests (CPU) — studio/backend/tests/test_gpu_init_crash_message.py, 12 failures.
  • Frontend build + bundle sanity — playwright_strip_ansi_smoke.py dies on Cannot access 'CHAT_GPU_MEMORY_MODE_KEY' before initialization.

UI before/after

Merge base 32ba55b57 against head, both rendering the real UpdateBanner/UpdateScreen through the real useTauriUpdate hook behind the same scripted Tauri bridge, the same click on Update, and the same waits.

PR 9890 update banner before/after

Before, one click puts the app on "Updating backend… This may take a few minutes. Do not close the app." and it stays there. After, the same click leaves the app usable and the offer becomes a pill: Preparing update · downloading 30%, then Update ready · v0.1.901 with Restart and the staging log behind the chevron.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 28, 2026
@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 29, 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 ✅ Completed 2026-08-29T08:09:43.154683Z 4b3ba93 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 48ab8c7a4d

ℹ️ 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".

@mahiatlinux

mahiatlinux commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Review and repair results

The PR solves a real updater problem. The old desktop flow stopped the managed backend and held the UI on the update screen. The staged flow copies the managed runtime, updates that copy, and downloads the signed desktop bundle while the live backend remains available.

Confirmed findings and fixes

  1. The staged interpreter could import the live or user environment. A live PYTHONPATH, PYTHONHOME, or console-script shebang could make staging update the wrong install. The stage now scrubs Python variables, prepends only the staged scripts directory, uses isolated Python, and validates the relocated launcher in _studio_stage.py.
  2. An in-flight stage or bundle download could be adopted for another release. Update state now carries the requested backend and shell versions, and adoption requires an exact match in update-preparation.ts and use-tauri-update.ts.
  3. A downloaded desktop bundle existed only in renderer state. Closing or reopening the app lost the verified download and forced the classic updater path. The native updater now persists bundle metadata and SHA-256, revalidates it on use, rejects corrupt or wrong-version files, and removes it after install in desktop_updater.rs.
  4. Repeated Update clicks could start duplicate work. The renderer now adopts matching native downloads and stages, waits for matching in-flight work, and exposes one active preparation state in use-tauri-update.ts.
  5. A withdrawn or superseded release could leave a stale ready stage. Discovery now discards a stage that no longer matches the offered release before presenting restart-ready state in update-preparation.ts.
  6. Activation was not crash-safe. A crash between runtime renames could leave a mixed install, and a second rollback could delete the restored runtime. Activation now writes a durable journal before the first rename, records every previous entry, restores every interrupted boundary, and makes repeated rollback idempotent in staged_update.rs.
  7. Staging could mutate live native helpers. Node, llama.cpp, whisper.cpp, installer cache, and staged setup roots are now isolated and swap with the Python runtime. The activation set is defined in staged_update.rs, with staged roots passed through setup.sh and setup.ps1.
  8. POSIX runtime mutation had no cross-process lock. Terminal update, repair, staging, and activation could race and produce a mixed snapshot. They now share the studio runtime gate for the full mutation or clone lifetime in update.rs and _studio_runtime_gate.py.
  9. Canceling staging killed only the process leader on POSIX. Pip, setup, or compiler descendants could keep writing after cancellation or app close. The updater now owns a process group and waits for the whole group after TERM or KILL in update.rs.
  10. A staged backend was confirmed from process ownership instead of readiness and version. A stale or half-started backend could delete the only known-good copy. Confirmation now requires authenticated health, native path leases, the expected owner, and a backend version at or above the pending version in desktop_backend_owner.rs and staged_update.rs.
  11. A bad staged backend did not recover during the same launch. Spawn failure, early stdout exit, invalid version, missing port, or watchdog timeout left the app down until another manual launch. Those paths now restore the previous runtime and restart in process.rs.
  12. The macOS restart request exited without relaunching after rollback. A packaged-app reproduction restored 2026.8.4 but never started it. macOS now launches a detached post-exit helper, waits for the failed app PID to disappear, and relaunches with the original arguments in main.rs.
  13. The fallback UI called the classic installer action Restart. That action still has to install the desktop bundle. Fast verified staging says Restart; the classic path says Finish update in update-banner.tsx and desktop-update-control.tsx.
  14. An older updater could mark a stage ready with a launcher that broke after activation. The old outer stage relocated before package installation. The nested installation then wrote an absolute .update-stage/.../python shebang, but the already-loaded old outer code never relocated it again. Activation now invokes the newly installed staged finalizer and probes both Python and the console launcher before the first rename in staged_update.rs and _studio_stage.py.
  15. The desktop backend did not inherit an actual runtime lock. Rust passed a boolean handoff, released its lock after spawn, and Python skipped locking. A terminal update could then mutate the venv while the backend imported it. Backend children now wait to acquire and hold the gate through imports and server admission. Updater children keep the parent-lifetime handoff. Rust also removes any stale handoff variable before setting acquire mode in process.rs, _studio_runtime_gate.py, and studio.py.
  16. One transient authenticated probe could roll back a healthy staged backend. The ownership probe already proves that valid liveness followed by a two-second login stall returns Unmanageable. Pending activation treated every such result as permanent. Transport silence, timeouts, and 5xx responses now retry within the 300-second startup budget. Completed protocol, capability, credential, and version failures still roll back immediately in process.rs.
  17. Rollback could forget the bad version after restoring the old runtime. ROLLED_BACK.json was written before .update-failed.json; a crash, full disk, or permission failure between those writes made the next launch delete the rollback journal and allow the bad version to stage again. The failed-version marker is now durable first, and recovery recreates it from an interrupted rollback marker before cleanup in staged_update.rs.
  18. Same-version or repeated staging failed its own integrity check. Initial relocation changed the cloned unsloth launcher before the nested updater ran. When pip correctly skipped the already-installed version, RECORD verification reported 219 bytes instead of 235 and discarded the stage. Initial staging now preserves that package-owned launcher through verification; finalization relocates and probes it afterward in _studio_stage.py and _studio_stage.py.
  19. Activation could confirm the new backend while its torch warmup was still running. The authenticated health response already reports torch_warm_in_progress, but staged validation ignored it and deleted the previous runtime as soon as the version and ownership matched. Validation now keeps retrying while warmup is active and confirms only after the backend reports a completed warmup in desktop_backend_owner.rs and process.rs.
  20. A staged child lost runtime-lock ownership when the desktop app died. Rust held the gate and told Python to inherit it, so a hard app exit released the gate while the surviving staged child kept cloning. A reopened app could then delete or reuse .update-stage underneath it. The staged CLI now owns the gate for its full lifetime, status detects the external owner, and discard holds the gate through deletion in update.rs, update.rs, and commands.rs.
  21. The POSIX whisper.cpp source fallback escaped the staged root. setup.sh launched build_whisper_cpp.sh without the managed root variable that the helper understands, so a forced source build wrote live ~/.unsloth/whisper.cpp. The helper now accepts UNSLOTH_HOME, and staged setup passes it explicitly in build_whisper_cpp.sh and setup.sh.
  22. Windows background staging could mutate the host. It could request UAC to change HKLM long-path policy, install Git through winget, and write the compiler cache to shared C:\tc. Staging now leaves policy unchanged, fails to the foreground updater when a missing Git install is required, and keeps the compiler cache under the stage root in setup.ps1, setup.ps1, and setup.ps1.
  23. The Windows foreground updater could lock and corrupt its own environment. The managed CLI eagerly imported training and chat dependencies before it spawned setup.ps1, so its parent process kept pydantic_core.pyd loaded while uv tried to replace it. Three independent Windows jobs reproduced Access is denied, followed by pip finding a half-removed distribution with no RECORD file. Windows studio setup and studio update entry points now register only the Studio command tree until the mutation ends, including the supported python -m unsloth_cli route, in unsloth_cli/__init__.py and unsloth_cli/__init__.py.
  24. Stage isolation unintentionally changed the foreground Windows install contract. The Git bootstrap was moved behind the source-build predicate, so a normal foreground setup on a Git-less machine stopped attempting the existing winget bootstrap. The upstream masked-winget clean-machine check caught the regression after the install itself succeeded. Setup now suppresses host Git installation only when StageRoot is active and preserves the foreground path in setup.ps1, with the split protected by test_setup_staged_root.sh.

Testing performed

  • Focused local checks: 105 Python updater, runtime-gate, Windows launcher, and staged-helper tests passed with 28 platform skips; 34 staged-root shell checks passed; 26 Rust activation and rollback tests, 31 backend ownership tests, 36 updater tests, and 4 pending-activation tests passed; strict i18n, TypeScript typecheck, 18 update-preparation tests, and 19 banner contracts passed.
  • CI repair checks: 58 Windows launcher transaction tests and the top-level CLI registration test passed locally. Four actual-Windows import probes cover console-script and python -m setup and update entry points without loading pydantic_core.
  • Real mixed-version updater E2E: an older 9ed274308 outer updater staged the fixed 2026.8.22 wheel and wrote the known bad absolute .update-stage shebang. The activation finalizer repaired and probed it before the four Python runtime entries moved. The normal activated launcher started, .update-prev retained the 2026.8.18 runtime entries with PENDING.json, and the wheel remained retained.
  • Real same-version and repeated-update E2E: the exact fixed 2026.8.22 source staged the same wheel with default verification. The integrity scan passed, READY was written, and Python, Node, llama.cpp, and whisper.cpp fingerprints remained identical before, during, and after staging. A seven-entry activation retained the previous Python, T5, Node, and llama.cpp runtimes with PENDING.json; the updater process was live during the sampled stage.
  • Failure E2E: failed update, corrupt stage, interrupted stage, restart during staging, stale stage, insufficient disk, permission failure, repeated Update, duplicate release, wrong-version bundle, corrupt retained bundle, and full-update fallback. Each left the live install usable.
  • Hard-exit E2E: a parent process launched the real POSIX staging CLI and exited with os._exit while staging was blocked in the clone. The orphan retained the runtime gate, a reopened contender was rejected, and the gate recovered after the stage owner exited. A real forced whisper.cpp source-build fixture installed under the staged managed root and left the live home untouched.
  • Packaged macOS app E2E: a deliberately failing 2026.9.2 backend exited with code 42 after activation. The app restored 2026.8.4, relaunched it, returned authenticated health on the new owned port, retained .update-failed.json, removed stage and previous directories, and did not retry the bad version after close and reopen.
  • Real model E2E on physical GPU 1, an RTX A6000: unsloth/Qwen3-1.7B-GGUF:UD-Q4_K_XL generated before and during the original stage. After fixed activation, the normal managed launcher generated again over HTTP 200 in 1.0 seconds while llama-server used 6,010 MiB. Training was not run because the isolated install intentionally used --no-torch; a 170-second real generation covered a long-running backend operation during staging.
  • Focused fork CI covers Windows 2022, Ubuntu 22.04, macOS 14, Python staging, real isolated filesystem staging, Rust activation/rollback/ownership/process tests, frontend i18n/typecheck, and updater state tests. Final results: https://github.com/mahiatlinux/unsloth/actions/runs/33241364653
  • Final-head upstream Windows startup, visible-winget clean-install, and masked-winget clean-install jobs passed. The masked job exercised the restored foreground Git bootstrap.

Playwright UI evidence

All affected states were exercised through Playwright. The checks covered discovery, Update, background progress, progress text, log toggle, fast restart-ready state, failure, retry, duplicate-click suppression, retained download recovery, and classic fallback.

State Before and after
Discovery Discovery
Update click Update click
Background progress Progress
Logs and restart-ready Logs and restart-ready
Failure and retry Failure and retry
Classic fallback Classic fallback

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 299d16b6c9

ℹ️ 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".

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@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: 4b3ba93439

ℹ️ 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".

Comment on lines +29 to +32
fn live_entry(home: &Path, name: &str) -> PathBuf {
if HELPER_RUNTIME_ENTRIES.contains(&name) {
home.parent().unwrap_or(home).join(name)
} else {

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 custom-home helper locations during activation

When staging is run for a custom UNSLOTH_STUDIO_HOME, _studio_stage.managed_helper_root() and both setup scripts place node, llama.cpp, and whisper.cpp directly under that custom home, but this function always treats them as siblings under home.parent(). Activation and rollback therefore replace unrelated sibling directories while leaving the custom installation's helpers untouched, producing a mixed old/new runtime; derive the live helper root using the same default-versus-custom layout rule used while staging.

Useful? React with 👍 / 👎.

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 path is not reachable in the desktop updater. configure_tauri_update_environment removes both UNSLOTH_STUDIO_HOME and STUDIO_HOME, every production activation/reconcile caller passes diagnostics::studio_dir(), and that function is fixed to ~/.unsloth/studio. The hidden CLI --stage can create a custom stage, but no activation caller reads that custom root. live_entry therefore only receives the legacy root in production, where home.parent() matches _studio_stage.managed_helper_root. No code change needed.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 4b3ba93439

ℹ️ 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".

@mahiatlinux

Copy link
Copy Markdown
Contributor

All reviewed and fixed, LGTM. CI results

@mahiatlinux
mahiatlinux merged commit e1653bc into unslothai:main Aug 29, 2026
89 of 100 checks passed
danielhanchen pushed a commit that referenced this pull request Aug 29, 2026
#9890 added staging support to studio/setup.ps1 and put an early
`if ($StageRoot)` return inside Get-ManagedLlamaCppDir, which sits in the block
install.ps1 holds a byte-identical copy of. The copy never got it, so
test_denied_llama_cpp_preflight.py failed on exactly the drift it exists to
catch, taking Repo tests (CPU) down with it.

install.ps1 never assigns $StageRoot, and it runs under Set-StrictMode -Off from
line 25 onwards, so the read is $null there and the branch is inert. Parity is
what the block is for: the copies have to match or the next person edits one of
them and only finds out in production.
danielhanchen added a commit that referenced this pull request Aug 30, 2026
…ordless pip install (#9959)

* Fix three CI regressions: code-span anchor, load-dispatch anchor, recordless pip install

Three unrelated failures, all reproduced locally first.

1. tests/studio/test_update_release_notes.py::test_code_span_closers_ignore_backslashes

   #9796 moved the code-span scanner into scanCodeSpans, which is defined ABOVE
   `export function codeSpans`. The test sliced the file from that export and
   counted `escaped(text` in the remainder, so the count went from 1 to 0 and
   the assertion "only an opener can be escaped" fired on a file where exactly
   one opener is still the only escaped thing. Count over the whole module and
   check the surviving call guards the opening run, so a wrapper moving again
   cannot read as "no opener is escaped either".

2. studio/backend/tests/test_parallel_slots_per_load.py::test_route_resolves_slots_once_before_dedupe_guard_and_load

   The GGUF load moved into _run_gguf_load_attempt, a health-wait helper defined
   above _load_model_impl, so `llama_backend.load_model` left the function body
   and .index() raised ValueError. Every ordering the test guards still holds.
   Anchor on whichever call the body dispatches a load through instead of on one
   backend's method name.

3. startup windows-latest

   pip will not replace a distribution whose .dist-info carries no RECORD, and an
   interrupted install leaves exactly that. The job reuses its venv, so the stub
   is not transient: once written, every later run dies the same way on
   "Cannot uninstall pydantic-core / no RECORD file was found". pip_install now
   retries once after clearing only the distributions pip named as unremovable,
   and only when it named one. pip's own hint is --ignore-installed, which would
   apply to every package in the command and skip real upgrades with it.

run() grows check=False so pip_install can inspect a failure instead of exiting
inside it; every existing caller keeps the old exit-on-failure behaviour.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Mirror the StageRoot branch into install.ps1's shared copy

#9890 added staging support to studio/setup.ps1 and put an early
`if ($StageRoot)` return inside Get-ManagedLlamaCppDir, which sits in the block
install.ps1 holds a byte-identical copy of. The copy never got it, so
test_denied_llama_cpp_preflight.py failed on exactly the drift it exists to
catch, taking Repo tests (CPU) down with it.

install.ps1 never assigns $StageRoot, and it runs under Set-StrictMode -Off from
line 25 onwards, so the read is $null there and the branch is inert. Parity is
what the block is for: the copies have to match or the next person edits one of
them and only finds out in production.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen pushed a commit that referenced this pull request Aug 30, 2026
Second failure in the same job, from the same pull request, and it only became
visible once the pytest step above stopped failing first.

tests/sh/test_studio_home_node_dir.sh lifts the real STUDIO_HOME and NODE_DIR
logic out of studio/setup.sh by content anchor and runs it against a fake HOME.
Block B started grabbing at:

    ^if \[ "\$_STUDIO_HOME_IS_CUSTOM" = true \]; then

#9890 added a staging branch above that one:

    if [ -n "$STAGE_ROOT" ]; then
        _NODE_PARENT="$RUNTIME_ROOT"
    elif [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then

which demoted the anchored line to an elif. The anchor then matched nothing,
block B came out empty, and the file's own extraction guard fired:

    FAIL: blockB extraction broke

setup.sh is right here. A background update has to put its Node under the
staging root, not into the home the running Studio is serving from. The anchor
was the problem: it pinned one branch's text in a conditional that was always
going to grow branches.

Block B is now anchored on the NODE_DIR assignment, the line that actually
matters, and walks back to the top-level `if` feeding it. Branches can be added,
reordered or removed without touching this file. Walking back could in principle
land on an unrelated `if`, so the extraction guard now also requires both
_STUDIO_HOME_IS_CUSTOM and STAGE_ROOT to appear in what it captured.

The staging branch was untested, which is why nothing caught this at the time,
so it gets two checks: a stage root sends Node under it, and it outranks a
custom studio home. Both drive UNSLOTH_STUDIO_STAGE_ROOT, the public knob, since
block A derives STAGE_ROOT and RUNTIME_ROOT from it.

7 checks, all passing. Deleting the staging branch from setup.sh fails the file.
danielhanchen pushed a commit that referenced this pull request Aug 30, 2026
Eleven tests in unsloth_cli/tests have been failing on main, taking Repo tests
(CPU) down with them on every pull request:

  Error: could not coordinate the Unsloth launch:
  [Errno 13] Permission denied: '/fake'

These tests pin STUDIO_HOME to /fake/studio so sys.prefix.startswith() picks the
in-venv branch. /fake was fine while nothing on the path touched the disk. #9890
put _studio_runtime_launch_guard in front of the launch, and
studio_runtime_launch_guard does studio_home.mkdir(parents = True) and then locks
a file inside it, so an unwritable home now aborts the run before run_server is
ever reached. Every one of these failures is the same shape underneath: an empty
captured dict, because the flag under test never got as far as being forwarded.

The guard is right to create the directory it locks in, and right to refuse the
launch when it cannot. What was wrong was a fixture using an unwritable sentinel
path for somewhere that is now genuinely written to, so the tests move to
tmp_path. The tree keeps its shape, so sys.prefix still sits under STUDIO_HOME
and the in-venv branch is still the one exercised: removing the sys.prefix pin
still fails these tests.

unsloth_cli/tests: 1113 passed, 6 skipped.
danielhanchen pushed a commit that referenced this pull request Aug 30, 2026
Second failure in the same job, from the same pull request, and it only became
visible once the pytest step above stopped failing first.

tests/sh/test_studio_home_node_dir.sh lifts the real STUDIO_HOME and NODE_DIR
logic out of studio/setup.sh by content anchor and runs it against a fake HOME.
Block B started grabbing at:

    ^if \[ "\$_STUDIO_HOME_IS_CUSTOM" = true \]; then

#9890 added a staging branch above that one:

    if [ -n "$STAGE_ROOT" ]; then
        _NODE_PARENT="$RUNTIME_ROOT"
    elif [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then

which demoted the anchored line to an elif. The anchor then matched nothing,
block B came out empty, and the file's own extraction guard fired:

    FAIL: blockB extraction broke

setup.sh is right here. A background update has to put its Node under the
staging root, not into the home the running Studio is serving from. The anchor
was the problem: it pinned one branch's text in a conditional that was always
going to grow branches.

Block B is now anchored on the NODE_DIR assignment, the line that actually
matters, and walks back to the top-level `if` feeding it. Branches can be added,
reordered or removed without touching this file. Walking back could in principle
land on an unrelated `if`, so the extraction guard now also requires both
_STUDIO_HOME_IS_CUSTOM and STAGE_ROOT to appear in what it captured.

The staging branch was untested, which is why nothing caught this at the time,
so it gets two checks: a stage root sends Node under it, and it outranks a
custom studio home. Both drive UNSLOTH_STUDIO_STAGE_ROOT, the public knob, since
block A derives STAGE_ROOT and RUNTIME_ROOT from it.

7 checks, all passing. Deleting the staging branch from setup.sh fails the file.
danielhanchen added a commit that referenced this pull request Aug 30, 2026
* Give the in-venv CLI tests a writable STUDIO_HOME

Eleven tests in unsloth_cli/tests have been failing on main, taking Repo tests
(CPU) down with them on every pull request:

  Error: could not coordinate the Unsloth launch:
  [Errno 13] Permission denied: '/fake'

These tests pin STUDIO_HOME to /fake/studio so sys.prefix.startswith() picks the
in-venv branch. /fake was fine while nothing on the path touched the disk. #9890
put _studio_runtime_launch_guard in front of the launch, and
studio_runtime_launch_guard does studio_home.mkdir(parents = True) and then locks
a file inside it, so an unwritable home now aborts the run before run_server is
ever reached. Every one of these failures is the same shape underneath: an empty
captured dict, because the flag under test never got as far as being forwarded.

The guard is right to create the directory it locks in, and right to refuse the
launch when it cannot. What was wrong was a fixture using an unwritable sentinel
path for somewhere that is now genuinely written to, so the tests move to
tmp_path. The tree keeps its shape, so sys.prefix still sits under STUDIO_HOME
and the in-venv branch is still the one exercised: removing the sys.prefix pin
still fails these tests.

unsloth_cli/tests: 1113 passed, 6 skipped.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Anchor the node-dir extraction on NODE_DIR, and cover the staging branch

Second failure in the same job, from the same pull request, and it only became
visible once the pytest step above stopped failing first.

tests/sh/test_studio_home_node_dir.sh lifts the real STUDIO_HOME and NODE_DIR
logic out of studio/setup.sh by content anchor and runs it against a fake HOME.
Block B started grabbing at:

    ^if \[ "\$_STUDIO_HOME_IS_CUSTOM" = true \]; then

#9890 added a staging branch above that one:

    if [ -n "$STAGE_ROOT" ]; then
        _NODE_PARENT="$RUNTIME_ROOT"
    elif [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then

which demoted the anchored line to an elif. The anchor then matched nothing,
block B came out empty, and the file's own extraction guard fired:

    FAIL: blockB extraction broke

setup.sh is right here. A background update has to put its Node under the
staging root, not into the home the running Studio is serving from. The anchor
was the problem: it pinned one branch's text in a conditional that was always
going to grow branches.

Block B is now anchored on the NODE_DIR assignment, the line that actually
matters, and walks back to the top-level `if` feeding it. Branches can be added,
reordered or removed without touching this file. Walking back could in principle
land on an unrelated `if`, so the extraction guard now also requires both
_STUDIO_HOME_IS_CUSTOM and STAGE_ROOT to appear in what it captured.

The staging branch was untested, which is why nothing caught this at the time,
so it gets two checks: a stage root sends Node under it, and it outranks a
custom studio home. Both drive UNSLOTH_STUDIO_STAGE_ROOT, the public knob, since
block A derives STAGE_ROOT and RUNTIME_ROOT from it.

7 checks, all passing. Deleting the staging branch from setup.sh fails the file.

* Pin UNSLOTH_ALLOW_CPU for the child that imports unsloth

Third failure in Repo tests (CPU), and it now runs before the other two, so it
is what the job reports on main today while the eleven unsloth_cli failures and
the setup.sh anchor wait behind it.

test_a_hostile_dtype_field_cannot_reach_an_eval, added by #9777, spawns a fresh
interpreter that imports unsloth. On a host with no torch accelerator that dies
inside unsloth_zoo:

  File "unsloth_zoo/device_type.py", line 389, in get_device_type
    raise NotImplementedError("Unsloth cannot find any torch accelerator? You need a GPU.")

so the child never reaches the module under test and the returncode assertion
fires. The FutureWarning about HF_HUB_ENABLE_HF_TRANSFER that heads the failure
message is unrelated noise from the same stderr.

UNSLOTH_ALLOW_CPU=1 is the documented way to import on such a host, and the test
was getting it by accident: studio/backend/tests/conftest.py sets it with
setdefault at import, so whether the child inherited it depended on whether that
conftest had been loaded, which depends on what else the run collected. In this
job it had not been.

The test copies os.environ and now pins the variable in the copy. It is a test
about the dtype field, and it should read the same on a runner with a card and
on one without.

With no accelerator visible and the variable unset in the parent: 1 failed, 11
passed before, 12 passed after. Unchanged with a card present.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 9, 2026
… classic update (#10604)

* Studio: stop the desktop shell staging updates in the background

Removes the staged-update path #9890 added to the Tauri shell: the staged
UpdateKind and its stage-progress/stage-complete/stage-failed events, the four
staged Tauri commands, the pending-version branches in port validation, the
staged rollback restart and the macOS relaunch helper. The update child now
always runs under the runtime launch guard and always inherits the gate through
STUDIO_RUNTIME_GATE_HANDOFF, which POSIX needs because the shell holds the flock
around the whole child.

staged_update.rs stays as a legacy cleanup module: reconcile_legacy_at_launch
deletes stale rollback trash, the compatibility failure marker and any stage
directory, then restores a runtime an unconfirmed 805-807 activation replaced.
Every step is a rename or a delete, so a second launch is a no-op.

Keeps the independent fixes that shipped in #9890: the POSIX runtime gate and
its ACQUIRE protocol, the stop_update process-group hardening, the unconditional
PYTHONHOME/PYTHONPATH scrub, and the desktop update bundle download with its
three commands.

* Studio: refuse a staged update instead of cloning the environment

An 805-807 desktop shell still spawns `unsloth studio update --stage`. The
hidden flag stays, but it now fails fast: no clone, no gate, no idle scan, no
launcher transaction. It writes the .update-failed.json those shells read, so a
later recheck of the same version returns skip rather than offering to prepare
again, prints the [TAURI:ERROR] line update.rs promotes off stdout, and exits 1,
which drops the shell onto the classic update.

_studio_stage.py keeps only the half an old CLI still calls into: the stage root
helpers, the shebang relocation and finalize_for_activation, stdlib only and
importable under python -I. The cloning, ready marker and uv marker promotion go
with the feature.

* Studio: put the desktop update banner back on the classic flow

The frontend no longer prepares an update in the background: the preparing and
ready statuses, the compact pill, the preparation state and the five staged
wrappers all go, together with lib/update-preparation.ts. Update now runs the
backend update, downloads the shell bundle if an earlier attempt did not leave
one, installs it and relaunches, which is what the classic path always did.

Kept: the periodic check from #9505 with its status ref and focus/visibility
wake-ups, the retained bundle download and install commands, the release notes
panel, and the banner card shapes the Python contract tests pin. The locale keys
the background flow added are removed and desktopAvailableDescription goes back
to describing a restart on completion.

* Apply the repo-pinned ruff formatting to the files this branch touched

* Studio: pin that the legacy cleanup leaves a retained update bundle alone

* Use the shared shell version constant in the staged update refusal

* Studio: wait out a desktop bundle download the update did not start

download_desktop_update refuses a second concurrent download, so a webview
reload during the shell download left the next Update now failing with
"Desktop update download is already running" instead of finishing. Poll the
bundle status until the running one settles, then reuse it or download.

* Studio: keep the legacy update cleanup off the launch path

Both leftovers this reconciler removes are whole runtime trees: .update-stage is
a clone of the managed venv and every native helper, and a confirmed
.update-prev is the runtime it replaced. Unlinking either one inside the Tauri
setup hook holds the runtime gate before the window exists, which on Windows is
minutes for a torch venv, and a complete stage is the common case for exactly
the installs this cleanup targets.

The stage is renamed into the rollback trash namespace, which a later launch
sweeps anyway, and unlinked on a background thread; a confirmed previous runtime
is dropped on one too, keeping its marker-last ordering so an interrupted delete
just repeats.

* Studio: clear a stage an old shell left before refusing to make one

A 805-807 shell reports `partial` for any `.update-stage` directory before it
reads `.update-failed.json`, and its `stagingDecision` maps `partial` straight
back to `stage`. An orphaned stage from an earlier attempt therefore had that
shell re-spawning `studio update --stage` at every periodic recheck, whatever the
refusal marker said. Take the directory out of the way first: renamed into the
`.update-rollback-` namespace the desktop already sweeps at launch, then unlinked
off that path, so the name the shell reads is gone the instant the rename lands
and a delete that fails leaves only trash somebody else collects.

Also spell out two things the marker relies on: `shell_version` is an
`Option<String>` on the other side, so null parses and a placeholder would fail
the version comparison exactly as null does, and the marker lands under the
Python STUDIO_HOME, which matches the shell's studio directory except for a
desktop-configured custom home.

* Studio: pad a relocated launcher back to the size the installer recorded

`make_relocatable` replaces a console script's `#!<venv>/bin/python` line with
the 82-byte relocatable shebang, so every venv path past about 68 characters
leaves the file SHORTER than the size RECORD holds for it. `install_manifest`
reads anything smaller than its recorded size as damage, which makes `setup.sh`
force the full dependency pass at every update and keeps a deep verification from
ever passing, so the whole cost of that check landed on exactly the installs
whose Studio path is long. This is the rewrite an old shell reaches through
`finalize_for_activation`, and `bin/unsloth` is the one launcher it rewrites, so
the deficit is paid back here: a comment line between the shebang and the body,
which `/bin/sh` never reads past the exec on line 2 and Python treats as a
comment, leaving the script still ending in whatever the installer wrote.

Tests cover a rewrite never shrinking a script, a stage finalised under a
100-character path clearing the same size comparison `install_manifest` runs, and
the shell version recorded in the refusal marker for a missing, blank or real
value. `managed_helper_root` goes with its test: the clone step was its only
caller and that step is gone.

* Studio: settle every legacy update leftover before something acts on it

Five things the cleanup module got wrong once a launch was not the only caller.

A rollback the launch deferred outlives the update that follows it. When a
backend still holds the tree, `reconcile_legacy_at_launch` leaves the PENDING
journal for the next launch, which is right at launch and wrong afterwards: a
classic update then installs into a runtime a journal still names as something to
undo, and the next idle launch restores the pre-update trees over all of it.
`reconcile_before_update` settles it inside the runtime guard, after the idle
scan and before the child spawns, and refuses with the one instruction that fixes
it when a backend is holding the tree.

The confirmed backup is quarantined rather than emptied. Deleting in place took
entries out from under the marker that vouches for the live runtime, so an
interrupted delete left a backup with no confirmation, which the next launch
reads as an activation nobody confirmed and rolls back to. The rename is the
whole decision and it is atomic.

The stage discard puts its fallback on a thread too. On Windows the rename fails
exactly when a file inside is still open, which is the multi-gigabyte tree the
background delete exists for, so the in-place unlink held the setup hook for as
long as the clone took.

`roll_back_unconfirmed` stops probing the process table at every launch: an
install with no `.update-prev` has nothing to decide. And a trash name carries a
counter as well as nanos and a pid, so two names in one launch cannot collide.

Tests: a READY stage discarded ahead of a mid-swap PENDING journal, a stage whose
rename fails still swept, distinct trash names, a confirmed backup gone from the
directory on return, and a deferred journal settled or the update refused.

* Studio: report progress while the update waits out a bundle download

A webview reload leaves the native bundle download running with nothing listening
to it, and `download_desktop_update` refuses a second one, so `installUpdate`
waits that download out. It did so silently and forever: the progress bar sat at
zero for the whole of it, and a download that stalled without ever clearing the
flag held the update there with nothing on screen to say why.

`listenDesktopUpdateDownload` comes out of `downloadDesktopUpdate` so the wait can
attach to the same `desktop-update-download` events, once a download really is in
flight and released whichever way the wait ends. The wait is bounded at ten
minutes, after which the attempt falls through to `downloadDesktopUpdate`, which
either takes the download over or reports why it cannot.

The schedule tests grow an event bus and a scripted bundle status so both shapes
are covered, and the failed-install case now pins a rejected
`invoke("start_backend_update")` rather than leaning on a `listen` stub that
happened to throw somewhere earlier in the same path.

* Studio: keep the install test id on the update card action

The revert took `data-testid="tauri-update-install"` off with the compact pill it
also belonged to. The card button is the one an end-to-end test drives, and the
background prefetch built on this branch selects it by that id.

* Studio: tighten the comments in the update path

* Studio: drop the now unused time import from the runtime gate tests

* Studio: align the update module comments with the code they describe
danielhanchen added a commit that referenced this pull request Oct 28, 2026
Three dependencies in `studio/frontend/package.json` are not used by
anything: not by the app, tests, configs, npm scripts, CSS, CI workflows
or the Tauri build.

## What changes

`npm uninstall` of:

- `@tauri-apps/plugin-updater`: nothing in the repo references it. The
last import went away in #9890; the frontend calls the app's own Rust
commands now. The Rust crate is separate and untouched.
- `@radix-ui/[email protected]` and `@radix-ui/[email protected]`:
nothing imports them. The bundle only uses the copies nested under
`radix-ui`, never these top-level ones.

The lockfile loses exactly these 3 entries; nothing is added or changed.

## How it was checked

- Module graph from the repo's own `vite.config.ts` production build,
plus a TypeScript AST pass over every source, test, config file, script
and CSS `@import`, `tsconfig` paths, npm script commands, peer
requirements, and files outside the frontend (workflows, Tauri config).
Transitive dependencies expanded with `npm ls --all`, so packages used
only as peers, config plugins, type-only imports or CLIs in scripts were
not flagged.
- `npm ci` passes and leaves a clean tree. The production `dist/` (871
files) is byte identical to main. `bundle:check`: 6,802.0 KB raw /
2,053.2 KB transfer / 110 chunks on both sides. Typecheck passes on
both; lint gives the identical set of findings on both (main already has
them). Frontend tests: 14,249 passed, 0 failed on both.
`tests/studio/test_frontend_dep_removal.py` and the lockfile audit pass.

This is tidying, not a speed change: none of the three was in the
bundle, and they are 39 KB of `node_modules`.
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.

3 participants