Skip to content

The agent that grows with you

fix(tools): stdin advice reads the recorded PTY fallback; cron notices drop the job pin

Teknium639f97da0e3f
diff --git a/tests/tools/test_cron_run_notice_usage.py b/tests/tools/test_cron_run_notice_usage.py
index 1ebdfd0162c..e2431be6473 100644
--- a/tests/tools/test_cron_run_notice_usage.py
+++ b/tests/tools/test_cron_run_notice_usage.py
@@ -4,7 +4,6 @@ The background ``cronjob(action='run')`` completion used to render ``Model: ?``
whatever the job did: the runner hard-coded ``api_calls: 0`` and the dispatch only knew the job's
model pin (None for a job on the default model). The run's own session in state.db is the record.
"""
-import time
from unittest.mock import patch
import pytest
@@ -28,24 +27,21 @@ def _completion(job, run_one_job):
from tools.process_registry import process_registry
token = _approval_session_key.set("agent:main:telegram:dm:4242")
+ others = []
try:
with patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: dict(job)), \
patch("cron.scheduler.run_one_job", side_effect=run_one_job):
res = _try_dispatch_background_run(dict(job))
assert res["dispatched"] is True
- for _ in range(200):
- try:
- evt = process_registry.completion_queue.get_nowait()
- except Exception:
- time.sleep(0.05)
- continue
+ while True: # a blocking get is the signal; Empty after the deadline fails the test
+ evt = process_registry.completion_queue.get(timeout=10)
if evt.get("delegation_id") == res["delegation_id"]:
return evt
- process_registry.completion_queue.put(evt)
- time.sleep(0.05)
+ others.append(evt)
finally:
+ for evt in others:
+ process_registry.completion_queue.put(evt)
_approval_session_key.reset(token)
- raise AssertionError("completion event never reached the queue")
@pytest.mark.asyncio
@@ -80,3 +76,16 @@ def test_notice_omits_fields_no_run_session_recorded(owner):
text = format_process_notification(evt)
assert "Model: ?" not in text and "API calls" not in text
assert "Role: cron_run" in text
+
+
+def test_refused_fire_of_a_pinned_job_prints_no_model(owner):
+ """The job's model pin is not what ran: a fire with no run session reports no model at all."""
+ job = jobs.create_job(prompt="report", schedule="every 1h", deliver="local", model="vendor/pinned-model")
+
+ def run_one_job(claimed, **kw): # refused before any run session existed
+ jobs.mark_job_run(claimed["id"], False, "refused")
+ return False
+
+ evt = _completion(job, run_one_job)
+ assert not evt.get("model")
+ assert "pinned-model" not in format_process_notification(evt)
diff --git a/tests/tools/test_process_stdin_unavailable_error.py b/tests/tools/test_process_stdin_unavailable_error.py
index 60daddfc5c5..851097f3982 100644
--- a/tests/tools/test_process_stdin_unavailable_error.py
+++ b/tests/tools/test_process_stdin_unavailable_error.py
@@ -3,10 +3,9 @@
A local ``terminal(background=true)`` spawn without ``pty=true`` connects stdin to /dev/null by
design; the old error blamed a "non-local backend or stdin closed", so agents retried blind.
"""
-import time
-
import pytest
+from tests.waiting import wait_until
from tools.process_registry import ProcessRegistry
@@ -18,24 +17,24 @@ def registry():
reg.kill_process(sid)
-def _spawn_reader(registry):
+def _spawn_reader(registry, cwd):
# Alive and waiting; a bare ``read`` would hit EOF on /dev/null and exit before the write.
- return registry.spawn_local("sleep 30", cwd=None, task_id="t-stdin")
+ return registry.spawn_local("sleep 30", cwd=str(cwd), task_id="t-stdin")
@pytest.mark.platforms("posix")
-def test_pipe_mode_write_says_to_relaunch_with_pty(registry):
- session = _spawn_reader(registry)
+def test_pipe_mode_write_says_to_relaunch_with_pty(registry, tmp_path):
+ session = _spawn_reader(registry, tmp_path)
result = registry.write_stdin(session.id, "hello\n")
assert result["status"] == "error"
assert "pty=true" in result["error"] and "non-local" not in result["error"]
@pytest.mark.platforms("posix")
-def test_no_pty_advice_where_a_pty_cannot_be_had(registry, monkeypatch):
+def test_no_pty_advice_where_a_pty_cannot_be_had(registry, monkeypatch, tmp_path):
import tools.process_registry_stdin as stdin_mod
- session = _spawn_reader(registry)
+ session = _spawn_reader(registry, tmp_path)
monkeypatch.setattr(stdin_mod, "_pty_available", lambda: False)
error = stdin_mod.stdin_unavailable_error(session)
assert "pty=true would not help" in error
@@ -54,13 +53,28 @@ def test_non_local_session_keeps_the_backend_explanation():
@pytest.mark.platforms("posix")
-def test_a_reader_that_hit_eof_says_why_it_already_exited(registry):
+def test_a_reader_that_hit_eof_says_why_it_already_exited(registry, tmp_path):
"""``read x`` on /dev/null returns at once, so the write lands on an exited process."""
- session = registry.spawn_local("read x; echo got:$x", cwd=None, task_id="t-stdin-eof")
- for _ in range(100):
- if session.exited:
- break
- time.sleep(0.05)
+ session = registry.spawn_local("read x; echo got:$x", cwd=str(tmp_path), task_id="t-stdin-eof")
+ wait_until(lambda: session.exited, what="the EOF reader to exit")
result = registry.write_stdin(session.id, "hello\n")
assert result["status"] == "already_exited"
assert "without stdin" in result["error"] and "pty=true" in result["error"]
+
+
+def test_a_failed_pty_request_is_not_told_to_retry_pty(registry, monkeypatch, tmp_path):
+ """PTY library installed but the spawn fails: spawn_local falls back to a pipe, and the error
+ names that failure instead of telling the agent to repeat the pty=true that just failed."""
+ import tools.process_registry_stdin as stdin_mod
+
+ monkeypatch.setattr(stdin_mod, "_pty_available", lambda: True)
+
+ def _pty_fails(*args, **kwargs):
+ raise OSError("openpty: out of pseudo-terminals")
+
+ monkeypatch.setattr(registry, "_spawn_local_pty", _pty_fails)
+ session = registry.spawn_local("sleep 30", cwd=str(tmp_path), task_id="t-stdin-ptyfail", use_pty=True)
+ error = registry.write_stdin(session.id, "hello\n")["error"]
+ assert "out of pseudo-terminals" in error and "pty=true would not help" in error
+ assert "Relaunch it with terminal(background=true, pty=true)" not in error
diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.py
index 9563ccfd85d..40bfa88e501 100644
--- a/tools/cronjob_tools.py
+++ b/tools/cronjob_tools.py
@@ -643,7 +643,8 @@ def _try_dispatch_background_run(
goal=f"Manual run of cron job '{job_name}' ({job_id})",
context=("Triggered via cronjob(action='run'). The job executed in its own "
"fresh cron session; this block reports its outcome."),
- toolsets=None, role="cron_run", model=job.get("model"), session_key=session_key,
+ # model=None: the run session (via _runner) is the only source; a pin a refused fire never ran is not.
+ toolsets=None, role="cron_run", model=None, session_key=session_key,
parent_session_id=str(session_id) if session_id else None, runner=_runner,
origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id,
max_async_children=max_async)
diff --git a/tools/process_registry.py b/tools/process_registry.py
index c565ce3c26d..a7054a910be 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -570,6 +570,7 @@ class ProcessSession:
persist_on_release: bool = False # opt out of agent-lifecycle cleanup (release()/turn-abandon kill
# sweeps), per terminal(background=true, persist_on_release=true) (#41225)
output_log: str = "" # file the process writes to (worker spawns; no pipe to lose)
+ pty_fallback: str = "" # why a pty=true local spawn runs in pipe mode instead
# Watcher/notification routing (persisted for crash recovery)
watcher_platform: str = ""
watcher_chat_id: str = ""
@@ -1176,14 +1177,11 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
self, command: str, cwd: str | None = None, task_id: str = "", session_key: str = "",
env_vars: dict | None = None, use_pty: bool = False, owner_task_id: str = "",
persist_on_release: bool = False) -> ProcessSession:
- """Spawn a background process locally (TERMINAL_ENV=local; other backends use
- spawn_via_env()). ``use_pty`` requests a pseudo-terminal via ptyprocess/pywinpty
- for interactive CLIs, falling back to a plain pipe when unavailable or failing.
+ """Spawn a background process locally (TERMINAL_ENV=local; other backends: spawn_via_env()).
+ ``use_pty`` asks ptyprocess/pywinpty for a pseudo-terminal; on failure: pipe + ``pty_fallback``.
``persist_on_release`` keeps the process out of agent-lifecycle kill sweeps (#41225)."""
- # Bash parses ``A && B &`` as ``(A && B) &`` — a subshell that holds our stdout
- # pipe open forever when B is a long-running server. The rewriter turns it into
- # ``A && { B & }``. Lazy import: terminal_tool imports this module.
- # Guard against the `A && B &` subshell-wait trap (issue #68915).
+ # Bash runs ``A && B &`` as a subshell holding our stdout pipe open while a server B lives;
+ # the rewriter makes it ``A && { B & }`` (#68915). Lazy: terminal_tool imports this module.
from tools.terminal_tool_sudo import _rewrite_compound_background as _rewrite_bg
safe_command = _rewrite_bg(command)
@@ -1196,8 +1194,10 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
try:
return self._spawn_local_pty(session, safe_command, env_vars)
except ImportError:
+ session.pty_fallback = "the PTY library (ptyprocess/pywinpty) is not installed"
logger.warning("ptyprocess not installed, falling back to pipe mode")
except Exception as e:
+ session.pty_fallback = f"the PTY spawn failed ({e})"
logger.warning("PTY spawn failed (%s), falling back to pipe mode", e)
if session.systemd_unit:
pty_scope_attempted = True
diff --git a/tools/process_registry_stdin.py b/tools/process_registry_stdin.py
index c2585801fbb..802a29649dc 100644
--- a/tools/process_registry_stdin.py
+++ b/tools/process_registry_stdin.py
@@ -2,20 +2,34 @@
import importlib.util
import sys
+_NON_INTERACTIVE = "Pass input non-interactively instead (arguments, a here-doc, or `printf ... | cmd`)."
+
def _pty_available() -> bool:
return importlib.util.find_spec("winpty" if sys.platform == "win32" else "ptyprocess") is not None
-def _pty_relaunch_helps(session) -> bool:
- """A local pipe-mode spawn (stdin is /dev/null) where ``spawn_local`` could give a PTY instead."""
- return session.process is not None and not session.output_log and _pty_available()
+def _no_pty_reason(session) -> str:
+ """Why a pty=true relaunch of this local pipe-mode session would not help, or "" when it would.
+
+ ``spawn_local`` records a pty=true request that fell back to pipe mode, so the advice never
+ repeats a request that already failed: an installed PTY library is not proof a PTY spawns."""
+ if session.pty_fallback:
+ return f"pty=true was requested but {session.pty_fallback}, so it runs without stdin"
+ if session.output_log:
+ return "background processes here run in an isolated worker that cannot give them a pseudo-terminal"
+ if not _pty_available():
+ return "the PTY library (ptyprocess/pywinpty) is not installed"
+ return ""
def already_exited_error(session) -> str:
"""A pipe-mode process that read stdin got EOF at once and exited: say so, or the agent retries blind."""
- if session.process is None or session.process.stdin is not None or not _pty_relaunch_helps(session):
+ if session.process is None or session.process.stdin is not None:
return "Process has already finished"
+ if reason := _no_pty_reason(session):
+ return (f"Process has already finished. It ran without stdin ({reason}), so anything it read got "
+ f"end-of-file at once. {_NON_INTERACTIVE}")
return ("Process has already finished. It was started without stdin (terminal background=true without "
"pty=true), so anything it read got end-of-file at once. Relaunch it with "
"terminal(background=true, pty=true) to send input.")
@@ -25,15 +39,11 @@ def stdin_unavailable_error(session) -> str:
"""Error for process_manage write/submit on a session without a stdin pipe or PTY.
A local pipe-mode spawn connects stdin to /dev/null by design, so only a PTY relaunch can take
- input; that advice is wrong where ``spawn_local`` cannot give a PTY (an isolated worker writes
- output to a log, or the PTY library is missing), and a non-local backend has no live stdin."""
+ input, and only where ``spawn_local`` can give one; a non-local backend has no live stdin."""
if session.process is None:
return ("Process stdin not available: it runs on a non-local terminal backend (or was recovered "
- "after a restart), which has no live stdin. Pass input non-interactively instead "
- "(arguments, a here-doc, or `printf ... | cmd`).")
- if not _pty_relaunch_helps(session):
- return ("This process was started without stdin, and this session cannot give background "
- "processes a pseudo-terminal, so pty=true would not help. Pass input non-interactively "
- "instead (arguments, a here-doc, or `printf ... | cmd`).")
+ f"after a restart), which has no live stdin. {_NON_INTERACTIVE}")
+ if reason := _no_pty_reason(session):
+ return f"This process has no stdin: {reason}. Relaunching with pty=true would not help. {_NON_INTERACTIVE}"
return ("This process was started without stdin (terminal background=true without pty=true). "
"Relaunch it with terminal(background=true, pty=true) to send input.")