fix(terminal): guard os.getcwd() against a deleted CWD

`os.getcwd()` raises FileNotFoundError when the process's working
directory was removed out from under it (e.g. a scratch workspace
cleaned up mid-session), crashing terminal env setup.

Extract a `_safe_getcwd()` helper that falls back to TERMINAL_CWD, then
the user's home, on FileNotFoundError, and route all three `os.getcwd()`
call sites in terminal_tool.py through it (local default_cwd, the Docker
cwd-passthrough source, and the debug-config print) so the same crash
can't resurface at a sibling site. Adds unit tests for the real-cwd path
and both fallback branches.

Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>
This commit is contained in:
Baris Sencan
2026-06-04 19:10:48 -07:00
committed by Teknium
parent b1e399de95
commit ad69d3edc7
2 changed files with 41 additions and 3 deletions

View File

@ -218,3 +218,27 @@ def test_registering_non_cwd_override_leaves_live_env_cwd_untouched(monkeypatch)
terminal_tool.register_task_env_overrides(task_id, {"modal_image": "custom:latest"})
assert fake_env.cwd == "/workspace/keep"
def test_safe_getcwd_returns_real_cwd(monkeypatch):
monkeypatch.setattr(terminal_tool.os, "getcwd", lambda: "/home/user/project")
assert terminal_tool._safe_getcwd() == "/home/user/project"
def test_safe_getcwd_falls_back_to_terminal_cwd_when_cwd_deleted(monkeypatch):
def _boom():
raise FileNotFoundError("[Errno 2] No such file or directory")
monkeypatch.setattr(terminal_tool.os, "getcwd", _boom)
monkeypatch.setenv("TERMINAL_CWD", "/srv/work")
assert terminal_tool._safe_getcwd() == "/srv/work"
def test_safe_getcwd_falls_back_to_home_when_no_terminal_cwd(monkeypatch):
def _boom():
raise FileNotFoundError()
monkeypatch.setattr(terminal_tool.os, "getcwd", _boom)
monkeypatch.delenv("TERMINAL_CWD", raising=False)
monkeypatch.setattr(terminal_tool.os.path, "expanduser", lambda p: "/home/me")
assert terminal_tool._safe_getcwd() == "/home/me"