The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): persist project cwd for new sessions (WIP continuation)
Brooklyn Nicholson59a3866ea5a0
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 592dca42eb6..db29cde4415 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -55,21 +55,6 @@ from agent.turn_failure_copy import is_max_iteration_handofflogger = logging.getLogger(__name__)-def _close_late_session_db_result(future: "concurrent.futures.Future") -> None:- """Done-callback: close a SessionDB whose constructor finished after run_job's init timeout- (worker abandoned via ``shutdown(wait=False)``), else its .db/WAL/SHM handles leak to EMFILE.-- If the constructor later completes inside that abandoned worker, the Future's result — an open SessionDB- holding .db / WAL / SHM file handles — would be orphaned and never closed, leaking descriptors until- EMFILE (#72782). This callback retrieves and closes that eventual late result.- """- with contextlib.suppress(Exception):- db = future.result()- if db is not None:- from hermes_state_registry import release_or_close- release_or_close(db)--def _set_cron_session_title(session_db, session_id, base_title):"""Persist a non-blank, unique title for a finished cron session; returns it (None if unset).Runs BEFORE end_session()/close() so no write races the close. Duplicate title (unique-index@@ -1949,6 +1934,7 @@ def _open_cron_session_db(job: dict):# inside it, the future's result would be orphaned and its SQLite FDs (.db, WAL, SHM) leak until# process exit. Register a done-callback that retrieves and closes any eventual late result# (#72782).+ from cron.scheduler_detached_worker import _close_late_session_db_result_session_db_future.add_done_callback(_close_late_session_db_result)raisefinally:@@ -2230,16 +2216,13 @@ 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.+ # Stamp the job's workdir on the row BEFORE end_session (title-write ordering, #50536): the+ # sidebar groups by cwd prefix and nothing else writes a cron row's cwd (#108205).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)+ logger.debug("Job '%s': failed to stamp workdir on session row: %s", job_id, e, exc_info=True)try:_session_db.end_session(_final_cron_session_id, _end_reason)# The scheduler owns cron-session finalization. AIAgent.close() alsodiff --git a/cron/scheduler_detached_worker.py b/cron/scheduler_detached_worker.pyindex db403b4f6cc..66cbbccf47a 100644--- a/cron/scheduler_detached_worker.py+++ b/cron/scheduler_detached_worker.py@@ -9,11 +9,27 @@ overlap behind #102827. The worker's Future owns the teardown instead.from __future__ import annotationsimport concurrent.futures+import contextlibimport subprocessimport threadingfrom typing import Optional+def _close_late_session_db_result(future: "concurrent.futures.Future") -> None:+ """Done-callback: close a SessionDB whose constructor finished after run_job's init timeout+ (worker abandoned via ``shutdown(wait=False)``), else its .db/WAL/SHM handles leak to EMFILE.++ If the constructor later completes inside that abandoned worker, the Future's result — an open+ SessionDB holding .db / WAL / SHM file handles — would be orphaned and never closed, leaking+ descriptors until EMFILE (#72782). This callback retrieves and closes that eventual late result.+ """+ with contextlib.suppress(Exception):+ db = future.result()+ if db is not None:+ from hermes_state_registry import release_or_close+ release_or_close(db)++def defer_teardown_to_running_worker(future: Optional[concurrent.futures.Future], session_db, agent, job_id: str, job_name: str,cron_session_id: str, workdir: Optional[str] = None,diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex e7abcbcb908..c11f7d4575e 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -401,26 +401,9 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->history = _visible_branch_history(display_history)if not history: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 = False- with 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+ # Only a chosen workspace persists as cwd; the launch-dir fallback is "No workspace"+ # (#108205: the desktop arm lets the client vouch for a host-invisible path, #52589 provenance).+ explicit_cwd, session_cwd, remote_cwd = _resolve_create_cwd(params, source, profile_home)_enable_gateway_prompts()from .methods_session_model_guard import create_overridestry:diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 86493462d72..586c199c2af 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -224,6 +224,35 @@ def _context_cwd_is_launch_artifact(session: dict | None) -> bool:return bool(session and not session.get("explicit_cwd") and _session_source(session) in _LAUNCH_CWD_NOT_A_WORKSPACE)+def _resolve_create_cwd(params: dict, source: str, profile_home) -> tuple[bool, str, bool]:+ """``(explicit_cwd, session_cwd, remote_cwd)`` for a freshly created session.++ Only a chosen workspace persists as cwd; the launch-dir fallback is "No workspace". A+ chosen workspace is one the gateway host can ``isdir``-probe, an ssh-shaped cwd on a remote+ profile, or — the #108205 desktop arm — a nonblank desktop-sourced cwd the host probe could+ not vouch for: the client names a workspace its gateway host cannot see (Docker/remote+ backend topology), and 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+ counts once the completion resolution actually adopted it, so a launch-dir fallback still+ persists nothing and a named profile's configured ``terminal.cwd`` keeps winning.+ """+ raw_cwd = str(params.get("cwd") or "").strip()+ remote_cwd = bool(raw_cwd) and _is_remote_cwd_shape(raw_cwd) and _cwd_is_remote(profile_home)+ explicit_cwd = False+ with 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":+ if params.get("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+ return explicit_cwd, session_cwd, remote_cwd++def _persisted_session_cwd(session: dict) -> str | None:"""The cwd to stamp on the session's DB row, or None to leave it unset (launch-dir rule: ``_ensure_session_db_row``)."""if session.get("explicit_cwd"):