The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): persist project cwd for new sessions
KoNit-K53aec0e28934
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 3268a250f24..592dca42eb6 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -2159,7 +2159,8 @@ def _final_response_from_result(result: dict, job_id: str, job_name: str, AIAgenreturn final_response-def _finalize_cron_session(session_db, agent, job_id: str, job_name: str, cron_session_id: str) -> None:+def _finalize_cron_session(session_db, agent, job_id: str, job_name: str, cron_session_id: str,+ workdir: Optional[str] = None) -> None:"""Title, classify, end and release the cron session after the agent turn has returned."""# Bound every DB op so storage failure cannot hold the dispatch guard._session_db = _BoundedCronSessionDB(session_db, job_id)@@ -2229,6 +2230,16 @@ def _finalize_cron_session(session_db, agent, job_id: str, job_name: str, cron_sjob_id, _lifecycle, _end_reason)except (Exception, KeyboardInterrupt) as e:logger.debug("Job '%s': session lifecycle classification failed: %s", job_id, e)+ # Stamp the job's workdir on the row BEFORE end_session (same before-close ordering as the+ # title write, #50536): the sidebar groups sessions by cwd prefix, and a NULL cwd filed every+ # cron run under __no_project__ even when the job ran inside a repo (#108205). The workdir is+ # the session's authoritative cwd — _launch_cwd_for_session records none for cron source, so+ # nothing else writes one. Best-effort like every finalize step.+ if workdir:+ try:+ _session_db.update_session_cwd(_final_cron_session_id, workdir)+ except (Exception, KeyboardInterrupt) as e:+ logger.debug("Job '%s': failed to stamp workdir on session row: %s", job_id, e)try:_session_db.end_session(_final_cron_session_id, _end_reason)# The scheduler owns cron-session finalization. AIAgent.close() also@@ -2682,10 +2693,12 @@ def run_job(finally:from cron.scheduler_detached_worker import defer_teardown_to_running_worker_worker_teardown_deferred = defer_teardown_to_running_worker(- _worker_state.get("future"), _session_db, agent, job_id, job_name, _cron_session_id)+ _worker_state.get("future"), _session_db, agent, job_id, job_name, _cron_session_id,+ workdir=scope.workdir)scope.exit()if _session_db and not _worker_teardown_deferred:- _finalize_cron_session(_session_db, agent, job_id, job_name, _cron_session_id)+ _finalize_cron_session(_session_db, agent, job_id, job_name, _cron_session_id,+ workdir=scope.workdir)# Tear down the ephemeral agent or the gateway leaks fds per tick (EMFILE). With deferred# teardown, hand the live agent back: delivery needs a live async client.# Release subprocesses, terminal sandboxes, browser daemons, and the main OpenAI/httpx client helddiff --git a/cron/scheduler_detached_worker.py b/cron/scheduler_detached_worker.pyindex 39cdf723289..db403b4f6cc 100644--- a/cron/scheduler_detached_worker.py+++ b/cron/scheduler_detached_worker.py@@ -16,7 +16,7 @@ from typing import Optionaldef defer_teardown_to_running_worker(future: Optional[concurrent.futures.Future], session_db, agent, job_id: str, job_name: str,- cron_session_id: str,+ cron_session_id: str, workdir: Optional[str] = None,) -> bool:"""Return True when the worker is still running and its Future will finalize the sessionand tear the agent down on completion; False when the caller must do it now."""@@ -27,7 +27,8 @@ def defer_teardown_to_running_worker(def _finish(_future) -> None:try:if session_db:- _finalize_cron_session(session_db, agent, job_id, job_name, cron_session_id)+ _finalize_cron_session(session_db, agent, job_id, job_name, cron_session_id,+ workdir=workdir)finally:_teardown_cron_agent(agent, job_id)diff --git a/tests/cron/test_cleanup_timeout.py b/tests/cron/test_cleanup_timeout.pyindex 9fcc97b43c1..0cd2c92ed15 100644--- a/tests/cron/test_cleanup_timeout.py+++ b/tests/cron/test_cleanup_timeout.py@@ -111,7 +111,8 @@ def test_detached_worker_teardown_waits_for_future():future.set_result({"final_response": "late"})- finalize.assert_called_once_with(fake_db, agent, "detached-worker", "detached worker", "cron_detached-worker")+ finalize.assert_called_once_with(fake_db, agent, "detached-worker", "detached worker",+ "cron_detached-worker", workdir=None)teardown_agent.assert_called_once_with(agent, "detached-worker")assert defer_teardown_to_running_worker(future, fake_db, agent, "detached-worker", "detached worker", "cron_detached-worker") is Falsediff --git a/tests/cron/test_cron_session_workdir.py b/tests/cron/test_cron_session_workdir.pynew file mode 100644index 00000000000..8e178977563--- /dev/null+++ b/tests/cron/test_cron_session_workdir.py@@ -0,0 +1,84 @@+"""Cron sessions stamp the job's workdir on their session row (#108205).++The sidebar groups sessions by cwd prefix; a cron run's row was left NULL even when the+job ran inside a repo workdir (``_launch_cwd_for_session`` records no cwd for cron+source), so every cron session filed under __no_project__. The scheduler — the owner of+cron-session finalization — stamps the job's workdir before closing the session, with the+same before-end_session ordering as the title write (#50536).+"""++from __future__ import annotations++from unittest.mock import patch++from cron.scheduler import run_job+from hermes_state import SessionDB++_RUNTIME = {+ "api_key": "test-key",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+}+++class _FakeCronAgent:+ """Stand-in for the cron AIAgent: creates its session row on the first turn exactly+ like AIAgent's lazy create (source 'cron', no cwd — _launch_cwd_for_session records+ none for cron source)."""++ def __init__(self, *args, session_id=None, session_db=None, **kwargs):+ self.session_id = session_id+ self.session_db = session_db++ def run_conversation(self, user_message, conversation_history=None, task_id=None):+ if self.session_db is not None:+ self.session_db.create_session(self.session_id, source="cron")+ return {"final_response": "ok"}+++def _run_job_with_real_db(job, db, tmp_path):+ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler_delivery._resolve_origin", return_value=None), \+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \+ patch("hermes_state_registry.acquire", return_value=db), \+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", return_value=_RUNTIME), \+ patch("run_agent.AIAgent", _FakeCronAgent):+ return run_job(job)+++def _cron_rows(db):+ return [dict(r) for r in db._read_all("SELECT * FROM sessions WHERE id LIKE 'cron_%'")]+++def test_run_job_stamps_workdir_on_cron_session_row(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ repo = tmp_path / "repo"+ repo.mkdir()+ job = {"id": "workdir-job", "name": "workdir job", "prompt": "hello", "workdir": str(repo)}++ try:+ success, _output, _final, error = _run_job_with_real_db(job, db, tmp_path)++ assert success is True, error+ rows = _cron_rows(db)+ assert len(rows) == 1+ assert rows[0]["cwd"] == str(repo)+ finally:+ db.close()+++def test_run_job_without_workdir_leaves_cron_session_cwd_null(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ job = {"id": "no-workdir-job", "name": "no workdir", "prompt": "hello"}++ try:+ success, _output, _final, error = _run_job_with_real_db(job, db, tmp_path)++ assert success is True, error+ rows = _cron_rows(db)+ assert len(rows) == 1+ assert rows[0]["cwd"] is None+ finally:+ db.close()diff --git a/tests/tui_gateway/test_desktop_session_workspace_persistence.py b/tests/tui_gateway/test_desktop_session_workspace_persistence.pynew file mode 100644index 00000000000..5c2e16f7f61--- /dev/null+++ b/tests/tui_gateway/test_desktop_session_workspace_persistence.py@@ -0,0 +1,111 @@+"""Desktop-provided project workspaces remain durable session metadata (#108205).++A desktop client names a workspace its gateway host cannot ``isdir``-probe (Docker/remote+backend topology). The failed probe is a topology artifact, not a verdict on the path, so a+nonblank desktop-sourced cwd with the client's own provenance (``cwd_explicit``, #52589)+persists to the session row; an inherited workspace only persists when the cwd resolution+actually adopted it, and a launch-dir fallback still persists nothing.+"""++import os++from hermes_state import SessionDB+from tui_gateway import server+++def _gateway_with_db(monkeypatch, tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ monkeypatch.setattr(server, "_get_db", lambda: db)+ monkeypatch.setattr(server, "_schedule_agent_build", lambda _sid: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)+ monkeypatch.setattr(server, "_register_session_cwd", lambda _session: None)+ return db+++def _create_desktop_session(params):+ response = server.handle_request(+ {"id": "create", "method": "session.create",+ "params": {"source": "desktop", **params}}+ )+ assert "result" in response, response+ return response["result"]+++def test_desktop_explicit_cwd_persists_when_local_probe_cannot_see_it(monkeypatch, tmp_path):+ db = _gateway_with_db(monkeypatch, tmp_path)+ workspace = tmp_path / "desktop-only-workspace"+ assert not workspace.exists()++ sid = None+ try:+ result = _create_desktop_session({"cwd": str(workspace), "cwd_explicit": True})+ sid, stored_id = result["session_id"], result["stored_session_id"]++ session = server._sessions[sid]+ assert session["cwd"] == str(workspace)+ assert session["explicit_cwd"] is True++ assert server._persist_session_row_for_submit("rid", session) is None+ assert db.get_session(stored_id)["cwd"] == str(workspace)+ finally:+ if sid:+ server._sessions.pop(sid, None)+ db.close()+++def test_desktop_inherited_cwd_persists_only_when_the_resolution_adopted_it(+ monkeypatch, tmp_path+):+ """An inherited (cwd_explicit=false) workspace under a container backend: the cwd+ resolution adopts the client path (no host isdir on a container path), so it is the+ session's workspace and persists — while still yielding to a named profile's+ configured terminal.cwd inside _completion_cwd (#52589)."""+ db = _gateway_with_db(monkeypatch, tmp_path)+ container_cwd = "/workspace/repo"++ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setattr(server, "_launch_configured_cwd", lambda: None)+ monkeypatch.delenv("TERMINAL_CWD", raising=False)++ sid = None+ try:+ result = _create_desktop_session({"cwd": container_cwd})+ sid, stored_id = result["session_id"], result["stored_session_id"]++ session = server._sessions[sid]+ assert session["cwd"] == container_cwd+ assert session["explicit_cwd"] is True++ assert server._persist_session_row_for_submit("rid", session) is None+ assert db.get_session(stored_id)["cwd"] == container_cwd+ finally:+ if sid:+ server._sessions.pop(sid, None)+ db.close()+++def test_desktop_launch_fallback_cwd_still_persists_nothing(monkeypatch, tmp_path):+ """The inherited cwd resolves to the gateway's launch directory (os.getcwd) — an+ artifact of how the app started, not a picked workspace: the row stays NULL and the+ sidebar keeps filing it under "No workspace" (the #98924 rule)."""+ db = _gateway_with_db(monkeypatch, tmp_path)+ launch_dir = tmp_path / "gateway-launch-dir"+ launch_dir.mkdir()+ monkeypatch.chdir(launch_dir)+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ assert os.path.realpath(server._completion_cwd({})) == os.path.realpath(launch_dir)++ sid = None+ try:+ result = _create_desktop_session({"cwd": "relative-inherited-notebook"})+ sid, stored_id = result["session_id"], result["stored_session_id"]++ session = server._sessions[sid]+ assert session["explicit_cwd"] is False++ assert server._persist_session_row_for_submit("rid", session) is None+ assert db.get_session(stored_id)["cwd"] is None+ finally:+ if sid:+ server._sessions.pop(sid, None)+ db.close()diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex fd2730fbf13..e7abcbcb908 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -400,14 +400,27 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->return _err(rid, 4008, f"nothing to branch — {exc}")history = _visible_branch_history(display_history)if not history:- return _err(rid, 4008, "nothing to branch — send a message first")- # Only an explicitly chosen existing workspace persists as cwd; the launch-dir fallback is "No workspace".- explicit_cwd = False+ return _err(rid, 4008, "send a message first")+ # Only a chosen workspace persists as cwd; the launch-dir fallback is "No workspace".raw_cwd = _str_param(params, "cwd") # unguarded, as on BASE: only the path check is best-effort# An ssh profile's cwd lives on the remote host, where the host isdir check cannot vouch for it.remote_cwd = bool(raw_cwd) and _is_remote_cwd_shape(raw_cwd) and _cwd_is_remote(profile_home)+ explicit_cwd = Falsewith contextlib.suppress(Exception):explicit_cwd = bool(raw_cwd) and (remote_cwd or os.path.isdir(os.path.abspath(os.path.expanduser(raw_cwd))))+ session_cwd = _completion_cwd(params)+ if raw_cwd and not explicit_cwd and source == "desktop":+ # The desktop client names a workspace its gateway host cannot probe (Docker/remote backend+ # topology — #108205): a failed host-side isdir is a topology artifact, not a verdict on the+ # client's path. The CLIENT vouches instead, with #52589 provenance: a deliberate pick+ # (cwd_explicit) adopts the raw path outright; an inherited app-global workspace only marks+ # the workspace explicit when the resolution above actually adopted it, so a launch-dir+ # fallback still persists nothing and a named profile's terminal.cwd keeps winning.+ if _flag(params, "cwd_explicit"):+ explicit_cwd = True+ session_cwd = raw_cwd+ elif session_cwd and session_cwd == os.path.abspath(os.path.expanduser(raw_cwd)):+ explicit_cwd = True_enable_gateway_prompts()from .methods_session_model_guard import create_overridestry:@@ -431,7 +444,7 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->"explicit_cwd": explicit_cwd,"history": history, "history_lock": threading.Lock(), "history_version": 0, "image_counter": 0,"seeded": bool(history), # gates _persist_branch_seed: only create-time history is unpersisted- "cwd": _completion_cwd(params), "inflight_turn": None, "last_active": now,+ "cwd": session_cwd, "inflight_turn": None, "last_active": now,"model_override": session_model_override,"composer_override_profile": composer_override_profile,"create_reasoning_override": create_reasoning_override,