Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: do not let the raw-bind prompt block a launch nobody is watching

danielhanchen178a73af1554
diff --git a/studio/backend/auth/terminal_prompt.py b/studio/backend/auth/terminal_prompt.py
index 65cb3be44bd..9700bf07530 100644
--- a/studio/backend/auth/terminal_prompt.py
+++ b/studio/backend/auth/terminal_prompt.py
@@ -145,11 +145,55 @@ def _getch_posix() -> str: # pragma: no cover - needs a real tty
_getch: Callable[[], str] = _getch_windows if os.name == "nt" else _getch_posix
-def _read_password(prompt: str, *, out: "TextIO | None" = None) -> str:
+class PromptUnattended(Exception):
+ """A terminal is attached but nobody answered the prompt before the deadline.
+
+ A pty is not a person. ``tmux new -d``, ``screen -dmS`` and ``docker run -dt``
+ all allocate a real, foreground pty that no one is reading, so isatty() is
+ True on both streams and the read simply never returns. Callers that must
+ never block a launch pass a deadline and treat this as a refusal.
+ """
+
+
+def _wait_for_first_key(timeout: float) -> bool:
+ """Whether a keystroke arrived within ``timeout`` seconds.
+
+ Must be called with the terminal already in cbreak mode: in canonical mode
+ the driver holds input until a newline, so the fd would not become readable
+ on the first character. True on any doubt, which is the blocking behaviour.
+ """
+ if os.name == "nt":
+ import time
+
+ try:
+ import msvcrt
+ except ImportError:
+ return True
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if msvcrt.kbhit():
+ return True
+ time.sleep(0.05)
+ return False
+ import select
+
+ try:
+ fd = sys.stdin.fileno()
+ ready, _, _ = select.select([fd], [], [], timeout)
+ except (AttributeError, OSError, ValueError):
+ return True
+ return bool(ready)
+
+
+def _read_password(
+ prompt: str, *, out: "TextIO | None" = None, first_key_timeout: "float | None" = None
+) -> str:
"""Read one masked line: echo ``*`` per char, support backspace editing.
Raises KeyboardInterrupt on Ctrl-C and EOFError on Ctrl-D/Ctrl-Z with an
- empty buffer; the terminal is restored on every exit path.
+ empty buffer; the terminal is restored on every exit path. With
+ ``first_key_timeout`` set, raises PromptUnattended when the FIRST keystroke
+ never arrives; once someone starts typing there is no deadline.
"""
if out is None:
out = sys.stderr
@@ -157,6 +201,10 @@ def _read_password(prompt: str, *, out: "TextIO | None" = None) -> str:
out.flush()
chars: list[str] = []
with _prompt_raw_mode():
+ if first_key_timeout is not None and not _wait_for_first_key(first_key_timeout):
+ out.write("\n")
+ out.flush()
+ raise PromptUnattended
while True:
key = _getch()
if key == "":
@@ -225,6 +273,7 @@ def prompt_for_password_change(
username: str = "unsloth",
out: "TextIO | None" = None,
exposure: str = "on the public internet",
+ first_key_timeout: "float | None" = None,
) -> bool:
"""Force a new admin password before exposure; True on success.
@@ -235,6 +284,12 @@ def prompt_for_password_change(
the public internet; a raw ``-H 0.0.0.0`` bind is every network interface,
which is the LAN behind a NAT router and the internet on a cloud box with a
public address. Claiming the wrong one trains people to ignore the message.
+
+ ``first_key_timeout`` bounds the wait for the FIRST keystroke and returns
+ False if it never comes. Only a caller that must not block a launch passes
+ it: a detached pty (``tmux new -d``, ``docker run -dt``) looks exactly like
+ an attended terminal, so without a deadline such a launch waits forever and
+ never binds its socket. Unset (the tunnel) keeps blocking indefinitely.
"""
if out is None:
out = sys.stderr
@@ -244,9 +299,14 @@ def prompt_for_password_change(
"password now. Ctrl+C to abort.\n\n"
)
out.flush()
+ # Only the first read is deadlined; once a key arrives someone is there.
+ pending_timeout = first_key_timeout
try:
while True:
- new_password = _read_password("New password: ", out = out)
+ new_password = _read_password(
+ "New password: ", out = out, first_key_timeout = pending_timeout
+ )
+ pending_timeout = None
if len(new_password) < min_length:
out.write(f"Password must be at least {min_length} characters; try again.\n")
out.flush()
@@ -270,6 +330,13 @@ def prompt_for_password_change(
out.write(f"Password updated for '{username}'.\n")
out.flush()
return True
+ except PromptUnattended:
+ out.write(
+ "No response at the terminal; leaving the auto-generated admin "
+ "password in place.\n"
+ )
+ out.flush()
+ return False
except (KeyboardInterrupt, EOFError):
out.write("Password change aborted; not exposing Unsloth.\n")
out.flush()
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 3a9712670fc..e5a98de78e9 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -2133,6 +2133,40 @@ def _stream_isatty(stream) -> bool:
return False
+# How long a raw-bind prompt waits for the FIRST keystroke before giving up and
+# launching anyway. Only the first: once someone is typing there is no deadline.
+#
+# 30s, not longer. The launches that reach this with nobody watching are the ones
+# that allocate a pty and then never read it -- `docker run -dt`, `tmux new -d`,
+# `screen -dmS`, some CI runners -- and they want to bind promptly. A container
+# that takes two minutes to answer a healthcheck can be killed and restarted by
+# the orchestrator, which would turn "delayed" into a restart loop; 30s stays
+# inside a default Docker HEALTHCHECK start period. Someone who is actually
+# looking at the prompt starts typing well inside that, and someone who is not
+# gets the refusal path, which warns and launches with the bootstrap deadline
+# armed. Mirrored in the CLI.
+_UNATTENDED_PROMPT_SECONDS = 30.0
+
+
+def _prompt_owns_the_terminal() -> bool:
+ """Whether this process may DRIVE the terminal, not merely see one.
+
+ A backgrounded shell job (`unsloth studio -H 0.0.0.0 &`) inherits the
+ terminal, so isatty() is True, but the masked prompt calls termios.tcsetattr,
+ and POSIX sends SIGTTOU to a background process group that does; the default
+ action stops the process. The launch would freeze before the socket binds
+ instead of starting, which is exactly the "never block a launch that worked"
+ case this gate is careful about everywhere else. Treat it as no terminal.
+
+ True on any doubt: no job control (Windows), no controlling terminal, or a
+ stream with no fileno. Nothing can stop us there, so the isatty answer stands.
+ """
+ try:
+ return os.tcgetpgrp(sys.stdin.fileno()) == os.getpgrp()
+ except (AttributeError, OSError, ValueError):
+ return True
+
+
def _terminal_password_gate(
*,
tunnel_will_start: bool,
@@ -2189,7 +2223,11 @@ def _terminal_password_gate(
# now would move first seeding earlier, open the SQLite file sooner and give a
# read-only or locked home a new place to fail, none of which a container
# operator asked for. Tunnel launches are unaffected: they always came here.
- if not tunnel_will_start and not (_stream_isatty(sys.stdin) and _stream_isatty(sys.stderr)):
+ if not tunnel_will_start and not (
+ _stream_isatty(sys.stdin)
+ and _stream_isatty(sys.stderr)
+ and _prompt_owns_the_terminal()
+ ):
return True, False
from auth import hashing as _auth_hashing
@@ -2285,6 +2323,13 @@ def _terminal_password_gate(
apply_change = _apply_change,
out = sys.stderr,
exposure = ("on the public internet" if tunnel_will_start else "on every network interface"),
+ # A raw bind must never block a launch that used to start. A detached pty
+ # (`tmux new -d`, `screen -dmS`, `docker run -dt`) passes every isatty and
+ # process-group test yet nobody will ever type, so an undeadlined read
+ # waits forever and the socket never binds. No answer is handled below as
+ # a refusal: proceed on the bootstrap deadline, exactly as before. The
+ # tunnel keeps waiting indefinitely; it fails closed rather than proceed.
+ first_key_timeout = None if tunnel_will_start else _UNATTENDED_PROMPT_SECONDS,
)
if changed:
return True, True
diff --git a/studio/backend/tests/test_password_prompt_backstop.py b/studio/backend/tests/test_password_prompt_backstop.py
index 2265c6f5e56..82803caa9b2 100644
--- a/studio/backend/tests/test_password_prompt_backstop.py
+++ b/studio/backend/tests/test_password_prompt_backstop.py
@@ -8,6 +8,7 @@ so run under the Unsloth venv."""
from __future__ import annotations
import io
+import os
import re
import sys
from pathlib import Path
@@ -567,3 +568,190 @@ def test_api_only_and_colab_raw_binds_do_not_prompt(monkeypatch):
frontend_served = True,
is_colab = True,
) == (True, False)
+
+
+# ──────────────────────────────────────────────────────────────────────
+# A backgrounded shell job is not a usable terminal.
+# ──────────────────────────────────────────────────────────────────────
+
+
+class _FdStream(_Stream):
+ def __init__(self):
+ super().__init__(isatty = True)
+
+ def fileno(self):
+ return 0
+
+
+def test_a_backgrounded_raw_bind_does_not_prompt(monkeypatch):
+ """`unsloth studio -H 0.0.0.0 &` must still launch.
+
+ A background job inherits the terminal, so isatty() is True on both streams,
+ but the masked prompt calls termios.tcsetattr; POSIX sends SIGTTOU to a
+ background process group that does, and the default action STOPS the process.
+ The launch would freeze before the socket binds, so it takes the headless
+ path it took before this gate learned about non-tunnel exposure: proceed,
+ protected by the bootstrap deadline, without consulting auth storage.
+ """
+ monkeypatch.setattr(sys, "stdin", _FdStream())
+ monkeypatch.setattr(sys, "stderr", _FdStream())
+ monkeypatch.setattr(run.os, "tcgetpgrp", lambda _fd: 4242)
+ monkeypatch.setattr(run.os, "getpgrp", lambda: 99)
+
+ def _boom(*_a, **_k):
+ raise AssertionError("storage must not be opened for a background job")
+
+ monkeypatch.setattr(auth_storage, "ensure_default_admin", _boom)
+
+ assert run._terminal_password_gate(
+ tunnel_will_start = False, **_RAW_BIND_KWARGS
+ ) == (True, False)
+
+
+def test_a_backgrounded_tunnel_launch_still_fails_closed(monkeypatch):
+ """A tunnel publishes a public URL: it must not quietly proceed unprompted."""
+ monkeypatch.setattr(sys, "stdin", _FdStream())
+ monkeypatch.setattr(sys, "stderr", _FdStream())
+ monkeypatch.setattr(run.os, "tcgetpgrp", lambda _fd: 4242)
+ monkeypatch.setattr(run.os, "getpgrp", lambda: 99)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.setattr(
+ terminal_prompt, "prompt_for_password_change", lambda **_kw: False
+ )
+
+ # The process group check is scoped to the raw-bind branch, so a tunnel
+ # launch still reaches the prompt and still aborts when it is refused.
+ assert run._prompt_owns_the_terminal() is False
+ assert run._terminal_password_gate(
+ tunnel_will_start = True, **_GATE_KWARGS
+ ) == (False, False)
+
+
+def test_a_foreground_raw_bind_still_reaches_the_prompt(monkeypatch):
+ """The ordinary interactive case is untouched."""
+ monkeypatch.setattr(sys, "stdin", _FdStream())
+ monkeypatch.setattr(sys, "stderr", _FdStream())
+ monkeypatch.setattr(run.os, "tcgetpgrp", lambda _fd: 4242)
+ monkeypatch.setattr(run.os, "getpgrp", lambda: 4242)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.setattr(
+ terminal_prompt, "prompt_for_password_change", lambda **_kw: True
+ )
+
+ assert run._terminal_password_gate(
+ tunnel_will_start = False, **_RAW_BIND_KWARGS
+ ) == (True, True)
+
+
+def test_no_job_control_falls_back_to_the_isatty_answer(monkeypatch):
+ """Windows / no controlling terminal: nothing can stop us, so still prompt."""
+ for exc in (OSError("ENOTTY"), AttributeError(), ValueError()):
+ def _boom(_fd, _exc = exc):
+ raise _exc
+
+ monkeypatch.setattr(run.os, "tcgetpgrp", _boom, raising = False)
+ monkeypatch.setattr(sys, "stdin", _FdStream())
+ assert run._prompt_owns_the_terminal() is True
+
+
+# ──────────────────────────────────────────────────────────────────────
+# A pty is not a person: an unattended terminal must not hold the launch.
+# ──────────────────────────────────────────────────────────────────────
+
+
+class _PtyStdin:
+ """sys.stdin standing on a real pty slave, as tmux/screen/docker -t give it."""
+
+ def __init__(self, fd):
+ self._fd = fd
+ self.encoding = "utf-8"
+
+ def fileno(self):
+ return self._fd
+
+ def isatty(self):
+ return True
+
+
+def test_an_unattended_pty_does_not_block_a_raw_bind_forever(monkeypatch):
+ """`tmux new -d 'unsloth studio -H 0.0.0.0'` must still bind its socket.
+
+ A detached pty is a real, foreground terminal that nobody will ever type
+ into: isatty() is True on both streams and the process owns the terminal, so
+ every interactivity test says "prompt". The read then never returns, and
+ because the gate runs BEFORE uvicorn binds, the launch hangs forever instead
+ of starting - a launch that worked before this gate widened to raw binds.
+ """
+ import io
+ import pty
+
+ master, slave = pty.openpty()
+ try:
+ monkeypatch.setattr(sys, "stdin", _PtyStdin(slave))
+ out = io.StringIO()
+ # Nothing is ever written to `master`: the pty exists, the human does not.
+ changed = terminal_prompt.prompt_for_password_change(
+ min_length = 8,
+ is_current_password = lambda _c: False,
+ apply_change = lambda _p: pytest.fail("nothing was typed"),
+ out = out,
+ first_key_timeout = 0.25,
+ )
+ finally:
+ os.close(master)
+ os.close(slave)
+
+ assert changed is False
+ assert "No response at the terminal" in out.getvalue()
+
+
+def test_a_pty_someone_types_into_is_not_treated_as_unattended(monkeypatch):
+ """The deadline is on the FIRST keystroke only, and a real one clears it."""
+ import io
+ import pty
+
+ applied = []
+ master, slave = pty.openpty()
+ try:
+ os.write(master, b"abcdefgh12\rabcdefgh12\r")
+ monkeypatch.setattr(sys, "stdin", _PtyStdin(slave))
+ out = io.StringIO()
+ changed = terminal_prompt.prompt_for_password_change(
+ min_length = 8,
+ is_current_password = lambda _c: False,
+ apply_change = applied.append,
+ out = out,
+ first_key_timeout = 0.25,
+ )
+ finally:
+ os.close(master)
+ os.close(slave)
+
+ assert changed is True
+ assert applied == ["abcdefgh12"]
+
+
+def test_the_gate_deadlines_a_raw_bind_prompt_and_never_the_tunnel(monkeypatch):
+ """Scope: only the launch that must not be blocked gets a deadline.
+
+ A tunnel publishes a public URL, so it keeps waiting indefinitely and fails
+ closed; a raw bind falls back to the protection it already had.
+ """
+ seen = {}
+
+ def _fake_prompt(**kwargs):
+ seen.clear()
+ seen.update(kwargs)
+ return True
+
+ monkeypatch.setattr(terminal_prompt, "prompt_for_password_change", _fake_prompt)
+
+ _patch_streams(monkeypatch, tty = True)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ run._terminal_password_gate(tunnel_will_start = False, **_RAW_BIND_KWARGS)
+ assert seen["first_key_timeout"] == run._UNATTENDED_PROMPT_SECONDS
+
+ _patch_streams(monkeypatch, tty = True)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS)
+ assert seen["first_key_timeout"] is None
diff --git a/unsloth_cli/commands/_password_prompt.py b/unsloth_cli/commands/_password_prompt.py
index 7ec0e042eef..e7d6c28d702 100644
--- a/unsloth_cli/commands/_password_prompt.py
+++ b/unsloth_cli/commands/_password_prompt.py
@@ -28,6 +28,47 @@ _BACKSPACE_CHARS = ("\x7f", "\x08")
_SUBMIT_CHARS = ("\r", "\n")
+class PromptUnattended(Exception):
+ """A terminal is attached but nobody answered before the deadline.
+
+ A pty is not a person: ``tmux new -d``, ``screen -dmS`` and ``docker run -dt``
+ allocate a real, foreground pty nobody reads, so isatty() is True on both
+ streams and the read never returns. Callers that must not block a launch pass
+ a deadline and treat this as a refusal. Mirror of
+ studio/backend/auth/terminal_prompt.py -- keep the two in sync.
+ """
+
+
+def _wait_for_first_key(timeout: float) -> bool:
+ """Whether a keystroke arrived within ``timeout`` seconds.
+
+ Must be called with the terminal already in cbreak mode: in canonical mode
+ the driver holds input until a newline, so the fd would not become readable
+ on the first character. True on any doubt, which is the blocking behaviour.
+ """
+ if os.name == "nt":
+ import time
+
+ try:
+ import msvcrt
+ except ImportError:
+ return True
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if msvcrt.kbhit():
+ return True
+ time.sleep(0.05)
+ return False
+ import select
+
+ try:
+ fd = sys.stdin.fileno()
+ ready, _, _ = select.select([fd], [], [], timeout)
+ except (AttributeError, OSError, ValueError):
+ return True
+ return bool(ready)
+
+
class _RestoreTtyOnSignals:
"""Restore terminal attrs if SIGTERM/SIGHUP kills the prompt mid-read.
@@ -69,7 +110,7 @@ class _RestoreTtyOnSignals:
pass
-def _read_masked_posix(prompt: str, out: TextIO) -> str:
+def _read_masked_posix(prompt: str, out: TextIO, first_key_timeout: "float | None" = None) -> str:
import codecs
import termios
import tty
@@ -87,6 +128,10 @@ def _read_masked_posix(prompt: str, out: TextIO) -> str:
new_attrs = termios.tcgetattr(fd)
new_attrs[3] &= ~termios.ISIG
termios.tcsetattr(fd, termios.TCSADRAIN, new_attrs)
+ # Deadline the FIRST keystroke only: a detached pty is a terminal that
+ # nobody will ever type into, and blocking there never binds the socket.
+ if first_key_timeout is not None and not _wait_for_first_key(first_key_timeout):
+ raise PromptUnattended
# os.read + incremental decoder with errors="replace": text-mode read(1) can raise or yield a lone
# surrogate that later crashes pbkdf2.
# It raises UnicodeDecodeError.
@@ -124,13 +169,15 @@ def _read_masked_posix(prompt: str, out: TextIO) -> str:
return "".join(chars)
-def _read_masked_windows(prompt: str, out: TextIO) -> str:
+def _read_masked_windows(prompt: str, out: TextIO, first_key_timeout: "float | None" = None) -> str:
import msvcrt
out.write(prompt)
out.flush()
chars: list[str] = []
try:
+ if first_key_timeout is not None and not _wait_for_first_key(first_key_timeout):
+ raise PromptUnattended
while True:
ch = msvcrt.getwch()
if ch in _SUBMIT_CHARS:
@@ -161,27 +208,42 @@ def _read_masked_windows(prompt: str, out: TextIO) -> str:
return "".join(chars)
-def read_masked(prompt: str, out: TextIO | None = None) -> str:
+def read_masked(
+ prompt: str, out: TextIO | None = None, *, first_key_timeout: "float | None" = None
+) -> str:
"""Read one line with ``*`` echo. Raises KeyboardInterrupt on Ctrl-C and
- EOFError on Ctrl-D/Ctrl-Z at an empty prompt."""
+ EOFError on Ctrl-D/Ctrl-Z at an empty prompt, and PromptUnattended when
+ ``first_key_timeout`` passes with no keystroke at all."""
if out is None:
out = sys.stderr
if os.name == "nt":
- return _read_masked_windows(prompt, out)
- return _read_masked_posix(prompt, out)
+ return _read_masked_windows(prompt, out, first_key_timeout)
+ return _read_masked_posix(prompt, out, first_key_timeout)
-def prompt_new_password(verify_current: Callable[[str], bool], out: TextIO | None = None) -> str:
+def prompt_new_password(
+ verify_current: Callable[[str], bool],
+ out: TextIO | None = None,
+ *,
+ first_key_timeout: "float | None" = None,
+) -> str:
"""Prompt for a new admin password until a valid, confirmed one is given.
``verify_current`` returns True when the candidate equals the current stored
password; such candidates are rejected. KeyboardInterrupt/EOFError propagate
so the caller can abort the launch.
+
+ ``first_key_timeout`` bounds the wait for the FIRST keystroke and raises
+ PromptUnattended if it never comes; once someone types there is no deadline.
+ Only a caller that must not block a launch passes it -- a detached pty
+ (``tmux new -d``, ``docker run -dt``) is a terminal nobody will answer.
"""
if out is None:
out = sys.stderr
+ pending_timeout = first_key_timeout
while True:
- password = read_masked("New password: ", out)
+ password = read_masked("New password: ", out, first_key_timeout = pending_timeout)
+ pending_timeout = None
if len(password) < MIN_PASSWORD_LENGTH:
out.write(f"Password must be at least {MIN_PASSWORD_LENGTH} characters. Try again.\n")
out.flush()
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index b91e465e8ed..a26220619d6 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -1238,7 +1238,7 @@ def _should_prompt_password_change(
# A tunnel launch prompts regardless of the terminal; the headless
# fallback is handled downstream.
return True
- return is_external_host(host) and _prompt_streams_interactive()
+ return is_external_host(host) and _prompt_streams_interactive() and _prompt_owns_the_terminal()
def _prompt_streams_interactive() -> bool:
@@ -1249,6 +1249,46 @@ def _prompt_streams_interactive() -> bool:
return False
+# How long a raw-bind prompt waits for the first keystroke before giving up and
+# launching anyway. Long enough for someone watching the terminal to react, short
+# enough that an unattended pty is not held hostage. Mirrors run.py.
+# How long a raw-bind prompt waits for the FIRST keystroke before giving up and
+# launching anyway. Only the first: once someone is typing there is no deadline.
+#
+# 30s, not longer. The launches that reach this with nobody watching are the ones
+# that allocate a pty and then never read it -- `docker run -dt`, `tmux new -d`,
+# `screen -dmS`, some CI runners -- and they want to bind promptly. A container
+# that takes two minutes to answer a healthcheck can be killed and restarted by
+# the orchestrator, which would turn "delayed" into a restart loop; 30s stays
+# inside a default Docker HEALTHCHECK start period. Someone who is actually
+# looking at the prompt starts typing well inside that, and someone who is not
+# gets the refusal path, which warns and launches with the bootstrap deadline
+# armed. Mirrored in the CLI.
+_UNATTENDED_PROMPT_SECONDS = 30.0
+
+
+def _prompt_owns_the_terminal() -> bool:
+ """Whether this process may DRIVE the terminal, not merely see one.
+
+ A backgrounded shell job (`unsloth studio -H 0.0.0.0 &`) inherits the
+ terminal, so isatty() is True, but read_masked calls termios.tcsetattr, and
+ POSIX sends SIGTTOU to a background process group that does; the default
+ action stops the process. The launch would freeze at the prompt instead of
+ starting, which is the one thing widening this gate to raw binds must not do
+ -- such a launch started fine before, protected by the bootstrap deadline.
+ Only the raw-bind branch consults this: a tunnel launch is published on the
+ public internet and keeps failing closed rather than quietly proceeding.
+
+ True on any doubt: no job control (Windows), no controlling terminal, or a
+ stream with no fileno. Nothing can stop us there, so the isatty answer stands.
+ Mirror of run.py's _prompt_owns_the_terminal -- keep the two in sync.
+ """
+ try:
+ return os.tcgetpgrp(sys.stdin.fileno()) == os.getpgrp()
+ except (AttributeError, OSError, ValueError):
+ return True
+
+
def _bootstrap_deadline_active() -> bool:
"""Whether the backend's bootstrap shutdown deadline will arm.
@@ -1756,7 +1796,28 @@ def _enforce_password_change_before_exposure(
err = True,
)
try:
- new_password = _password_prompt.prompt_new_password(_is_current_password)
+ new_password = _password_prompt.prompt_new_password(
+ _is_current_password,
+ # A raw bind must never block a launch that used to start. A
+ # detached pty (`tmux new -d`, `screen -dmS`, `docker run -dt`)
+ # passes every isatty and process-group test yet nobody will ever
+ # type, so an undeadlined read waits forever and no server is ever
+ # started. Fall back to the protection that launch already had,
+ # the bootstrap deadline. A tunnel keeps waiting: it publishes a
+ # public URL, so it fails closed rather than proceeding.
+ first_key_timeout = None if tunnel_will_start else _UNATTENDED_PROMPT_SECONDS,
+ )
+ except _password_prompt.PromptUnattended:
+ typer.echo(
+ "Warning: no response at the terminal, so Unsloth is starting with "
+ "the auto-generated admin password on a bind that is reachable from "
+ "the network. Unsloth shuts down after the bootstrap deadline "
+ "(UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT, default 1h) unless the password "
+ "is changed. Change it by logging in, or with `unsloth studio "
+ "reset-password`.",
+ err = True,
+ )
+ return
except (KeyboardInterrupt, EOFError):
typer.echo(
"\nError: password change aborted; refusing to expose Unsloth "
diff --git a/unsloth_cli/tests/test_studio_password_prompt.py b/unsloth_cli/tests/test_studio_password_prompt.py
index e6f562d6b63..6a84774d7ab 100644
--- a/unsloth_cli/tests/test_studio_password_prompt.py
+++ b/unsloth_cli/tests/test_studio_password_prompt.py
@@ -12,6 +12,7 @@ test_studio_cloudflare_flag.py.
from __future__ import annotations
+import io
import sqlite3
import sys
from pathlib import Path
@@ -203,7 +204,7 @@ def _install_prompt_env(
# dedicated test that overrides this.
monkeypatch.setattr(studio_mod, "_tunnel_binary_confirmed_unavailable", lambda: False)
- def fake_prompt(verify_current, out = None):
+ def fake_prompt(verify_current, out = None, **_kw):
events.append(("prompt", verify_current))
if isinstance(scripted, BaseException):
raise scripted
@@ -1832,3 +1833,159 @@ def test_cli_and_backend_agree_on_which_hosts_are_exposed(monkeypatch, host):
f"{host!r}: CLI prompts={cli_prompts} but the backend considers it "
f"exposed={backend_exposed}; the parent gate and the child gate disagree"
)
+
+
+# ── a backgrounded shell job is not a usable terminal ─────────────────
+
+
+def test_a_backgrounded_raw_bind_does_not_prompt(monkeypatch):
+ """`unsloth studio -H 0.0.0.0 &` must still launch.
+
+ A background job inherits the terminal, so isatty() is True on both streams,
+ but the masked prompt calls termios.tcsetattr; POSIX sends SIGTTOU to a
+ background process group that does, and the default action STOPS the process.
+ The launch would freeze at the prompt before the socket binds, i.e. a launch
+ that worked before this gate widened to raw binds stops working. It keeps the
+ protection it already had, the bootstrap deadline.
+ """
+ studio = _studio()
+ monkeypatch.setattr(studio, "_prompt_streams_interactive", lambda: True)
+ monkeypatch.setattr(studio.os, "tcgetpgrp", lambda _fd: 4242)
+ monkeypatch.setattr(studio.os, "getpgrp", lambda: 99)
+ monkeypatch.setattr(studio.sys, "stdin", _FdStream())
+
+ assert studio._should_prompt_password_change(
+ cloudflare = None, host = "0.0.0.0", secure = False, api_only = False
+ ) is False
+ # The tunnel is published on the public internet either way: it must keep
+ # failing closed rather than quietly proceeding.
+ assert studio._should_prompt_password_change(
+ cloudflare = None, host = "0.0.0.0", secure = True, api_only = False
+ ) is True
+
+
+def test_a_foreground_raw_bind_still_prompts(monkeypatch):
+ """The ordinary interactive case is untouched."""
+ studio = _studio()
+ monkeypatch.setattr(studio, "_prompt_streams_interactive", lambda: True)
+ monkeypatch.setattr(studio.os, "tcgetpgrp", lambda _fd: 4242)
+ monkeypatch.setattr(studio.os, "getpgrp", lambda: 4242)
+ monkeypatch.setattr(studio.sys, "stdin", _FdStream())
+
+ assert studio._should_prompt_password_change(
+ cloudflare = None, host = "0.0.0.0", secure = False, api_only = False
+ ) is True
+
+
[email protected]("raised", [OSError("ENOTTY"), AttributeError(), ValueError()])
+def test_no_job_control_falls_back_to_the_isatty_answer(monkeypatch, raised):
+ """Windows / no controlling terminal: nothing can stop us, so still prompt."""
+ studio = _studio()
+ monkeypatch.setattr(studio, "_prompt_streams_interactive", lambda: True)
+
+ def _boom(_fd):
+ raise raised
+
+ monkeypatch.setattr(studio.os, "tcgetpgrp", _boom, raising = False)
+ monkeypatch.setattr(studio.sys, "stdin", _FdStream())
+
+ assert studio._should_prompt_password_change(
+ cloudflare = None, host = "0.0.0.0", secure = False, api_only = False
+ ) is True
+
+
+class _FdStream:
+ def fileno(self): return 0
+ def isatty(self): return True
+
+
+# ── a pty is not a person ────────────────────────────────────────────
+
+
+def test_an_unattended_pty_still_launches_a_raw_bind(monkeypatch, tmp_path):
+ """`tmux new -d 'unsloth studio -H 0.0.0.0'` must still start Unsloth.
+
+ A detached pty (tmux/screen/`docker run -dt`) is a real, foreground terminal
+ that nobody will ever type into: both streams are ttys and the process owns
+ the terminal, so every interactivity test says "prompt" and the read then
+ never returns. The gate runs before any server exists, so without a deadline
+ the launch hangs forever instead of starting. It must fall back to the
+ protection it already had, the bootstrap deadline.
+ """
+ studio_mod = _studio()
+ events = _install_prompt_env(
+ monkeypatch,
+ tmp_path,
+ interactive = True,
+ scripted = studio_mod._password_prompt.PromptUnattended(),
+ )
+ monkeypatch.setattr(studio_mod, "_prompt_owns_the_terminal", lambda: True)
+ _seed_auth(studio_mod)
+
+ result = _invoke_studio_default(monkeypatch, events, ["-H", "0.0.0.0"])
+
+ kinds = [kind for kind, _ in events]
+ assert kinds == ["prompt", "exec"], events
+ assert result.exit_code == 0, result.output
+ # Unchanged password, and the seeded file is kept: a raw bind never strips.
+ assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert (tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE).exists()
+
+
+def test_an_unattended_pty_still_aborts_a_tunnel_launch(monkeypatch, tmp_path):
+ """A tunnel publishes a public URL, so it gets no deadline and no fallback."""
+ studio_mod = _studio()
+ seen = {}
+
+ def _fake_prompt(verify_current, out = None, **kw):
+ seen.update(kw)
+ return _NEW_PW
+
+ events = _install_prompt_env(monkeypatch, tmp_path, interactive = True)
+ monkeypatch.setattr(studio_mod._password_prompt, "prompt_new_password", _fake_prompt)
+ _seed_auth(studio_mod)
+
+ _invoke_studio_default(monkeypatch, events, ["--secure"])
+ assert seen["first_key_timeout"] is None
+
+
+def test_a_raw_bind_prompt_carries_the_unattended_deadline(monkeypatch, tmp_path):
+ """The other half: only the launch that must not be blocked is deadlined."""
+ studio_mod = _studio()
+ seen = {}
+
+ def _fake_prompt(verify_current, out = None, **kw):
+ seen.update(kw)
+ return _NEW_PW
+
+ events = _install_prompt_env(monkeypatch, tmp_path, interactive = True)
+ monkeypatch.setattr(studio_mod._password_prompt, "prompt_new_password", _fake_prompt)
+ monkeypatch.setattr(studio_mod, "_prompt_owns_the_terminal", lambda: True)
+ _seed_auth(studio_mod)
+
+ _invoke_studio_default(monkeypatch, events, ["-H", "0.0.0.0"])
+ assert seen["first_key_timeout"] == studio_mod._UNATTENDED_PROMPT_SECONDS
+
+
+def test_read_masked_gives_up_on_a_pty_nobody_types_into(monkeypatch):
+ """The mechanism itself, against a real pty with no writer."""
+ import os
+ import pty
+
+ from unsloth_cli.commands import _password_prompt
+
+ master, slave = pty.openpty()
+
+ class _PtyStdin:
+ encoding = "utf-8"
+ def fileno(self): return slave
+ def isatty(self): return True
+
+ try:
+ monkeypatch.setattr(_password_prompt.sys, "stdin", _PtyStdin())
+ out = io.StringIO()
+ with pytest.raises(_password_prompt.PromptUnattended):
+ _password_prompt.read_masked("New password: ", out, first_key_timeout = 0.25)
+ finally:
+ os.close(master)
+ os.close(slave)