Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions libs/code/deepagents_code/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ def _run_startup_auto_update(console: "Console") -> None:
from deepagents_code._version import __version__ as cli_version
from deepagents_code.config import _is_editable_install
from deepagents_code.update_check import (
clear_startup_auto_update_failure,
create_update_log_path,
detect_shadowed_dcode_safe,
format_release_age_parenthetical,
Expand All @@ -285,9 +286,11 @@ def _run_startup_auto_update(console: "Console") -> None:
is_installed_version_at_least,
is_update_check_enabled,
mark_auto_update_default_acknowledged,
mark_startup_auto_update_failed,
perform_upgrade,
release_requires_prereleases,
should_announce_auto_update_default,
should_skip_startup_auto_update_after_failure,
upgrade_command,
)

Expand Down Expand Up @@ -339,6 +342,19 @@ def _run_startup_auto_update(console: "Console") -> None:
highlight=False,
)
return
if should_skip_startup_auto_update_after_failure(latest):
update_needs_prereleases = release_requires_prereleases(latest)
cmd = upgrade_command(
include_prereleases=True if update_needs_prereleases else None,
version=latest if update_needs_prereleases else None,
)
console.print(
f"[bold yellow]Warning:[/bold yellow] Skipping automatic update to "
f"v{latest} after a recent failed attempt. Update manually: "
f"[cyan]{cmd}[/cyan]\nContinuing with v{cli_version}.",
highlight=False,
)
return
if should_announce_auto_update_default():
# First-run consent/migration: auto-update is on only because of the
# opt-out default, not an explicit choice. Announce it once and skip
Expand Down Expand Up @@ -386,6 +402,7 @@ def _run_startup_auto_update(console: "Console") -> None:
perform_upgrade(log_path=log_path, target_version=latest)
)
if success:
clear_startup_auto_update_failure(latest)
# If a stale `dcode` is earlier on PATH, the auto-restart would
# re-exec into the old binary and the user would silently keep
# running the pre-upgrade version. Detect that *before* the
Expand Down Expand Up @@ -434,6 +451,7 @@ def _run_startup_auto_update(console: "Console") -> None:
highlight=False,
)
return
mark_startup_auto_update_failed(latest)
update_needs_prereleases = release_requires_prereleases(latest)
cmd = upgrade_command(
include_prereleases=True if update_needs_prereleases else None,
Expand Down Expand Up @@ -3636,7 +3654,9 @@ def cli_main() -> None:
sys.exit(130)
sys.exit(exit_code)
else:
_run_startup_auto_update(console)
resume_thread = args.resume_thread # "__MOST_RECENT__", "<id>", or None
if resume_thread is None:
_run_startup_auto_update(console)
# Resolve recent-agent fallback only for actual session launches.
assistant_id = _resolve_agent_arg(args)
# Interactive mode - handle thread resume
Expand All @@ -3647,7 +3667,6 @@ def cli_main() -> None:
# Instead of resolving thread_id here with synchronous asyncio.run()
# DB calls, pass the raw resume request to the TUI and let it
# resolve asynchronously during startup.
resume_thread = args.resume_thread # "__MOST_RECENT__", "<id>", or None
thread_id = None if resume_thread else generate_thread_id()

# Validate sandbox provider deps before spawning server subprocess
Expand Down
98 changes: 90 additions & 8 deletions libs/code/deepagents_code/update_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import re
import shlex
import shutil
import signal
import sys
import tempfile
import time
Expand Down Expand Up @@ -150,6 +151,16 @@
UPDATE_LOG_MAX_FILES = 10
"""Keep at most this many newest update logs."""

STARTUP_AUTO_UPDATE_FAILURE_COOLDOWN = CACHE_TTL
"""Seconds to suppress same-version startup auto-update retries after failure."""

_STARTUP_AUTO_UPDATE_FAILED_VERSION_KEY = "startup_auto_update_failed_version"
_STARTUP_AUTO_UPDATE_FAILED_AT_KEY = "startup_auto_update_failed_at"
_STARTUP_AUTO_UPDATE_FAILURE_KEYS: tuple[str, ...] = (
_STARTUP_AUTO_UPDATE_FAILED_VERSION_KEY,
_STARTUP_AUTO_UPDATE_FAILED_AT_KEY,
)

UpgradeProgressCallback = Callable[[str], Awaitable[None] | None]


Expand Down Expand Up @@ -928,6 +939,40 @@ def _write_update_state(
return True


def should_skip_startup_auto_update_after_failure(version: str) -> bool:
"""Return whether startup auto-update should skip a recently failed version."""
data = _read_update_state()
failed_version = data.get(_STARTUP_AUTO_UPDATE_FAILED_VERSION_KEY)
failed_at = data.get(_STARTUP_AUTO_UPDATE_FAILED_AT_KEY)
return bool(
failed_version == version
and isinstance(failed_at, (int, float))
and time.time() - failed_at < STARTUP_AUTO_UPDATE_FAILURE_COOLDOWN
)


def mark_startup_auto_update_failed(version: str) -> bool:
"""Persist a same-version startup auto-update retry cooldown marker.

Returns:
`True` if the marker was written, `False` otherwise.
"""
return _write_update_state(
{
_STARTUP_AUTO_UPDATE_FAILED_VERSION_KEY: version,
_STARTUP_AUTO_UPDATE_FAILED_AT_KEY: time.time(),
}
)


def clear_startup_auto_update_failure(version: str) -> None:
"""Clear a startup auto-update failure marker for `version` if present."""
data = _read_update_state()
if data.get(_STARTUP_AUTO_UPDATE_FAILED_VERSION_KEY) != version:
return
_write_update_state({}, remove_keys=_STARTUP_AUTO_UPDATE_FAILURE_KEYS)


def should_notify_update(latest: str) -> bool:
"""Return whether the user should be notified about version *latest*.

Expand Down Expand Up @@ -1544,6 +1589,25 @@ async def _read_stream(
await _emit_progress(progress, line)


async def _terminate_install_process(proc: asyncio.subprocess.Process) -> None:
"""Terminate an install subprocess and its descendants when possible."""
if proc.returncode is not None:
return
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved
if os.name == "posix":
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
except PermissionError:
with suppress(ProcessLookupError):
proc.kill()
else:
with suppress(ProcessLookupError):
proc.kill()
with suppress(ProcessLookupError):
await proc.wait()


async def _run_install_subprocess(
cmd: str,
*,
Expand All @@ -1568,6 +1632,9 @@ async def _run_install_subprocess(

Returns:
`(success, output)` — *success* is `True` iff the subprocess exited 0.

Raises:
asyncio.CancelledError: If the calling task is cancelled.
"""
timeout = _UPGRADE_TIMEOUT
if log_path is None:
Expand All @@ -1591,12 +1658,21 @@ async def _run_install_subprocess(
log_file = None

try:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.DEVNULL,
)
if os.name == "posix":
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.DEVNULL,
start_new_session=True,
)
else:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.DEVNULL,
)
await asyncio.wait_for(
asyncio.gather(
_read_stream(
Expand All @@ -1617,8 +1693,7 @@ async def _run_install_subprocess(
)
except TimeoutError:
if proc is not None:
proc.kill()
await proc.wait()
await _terminate_install_process(proc)
msg = f"Command timed out after {timeout}s: {cmd}"
if log_file is not None:
with suppress(OSError):
Expand All @@ -1627,6 +1702,13 @@ async def _run_install_subprocess(
await _emit_progress(progress, msg)
logger.warning(msg)
return False, msg
except asyncio.CancelledError:
if proc is not None:
await _terminate_install_process(proc)
if log_file is not None:
with suppress(OSError):
log_file.close()
raise
except OSError as exc:
if log_file is not None:
with suppress(OSError):
Expand Down
52 changes: 50 additions & 2 deletions libs/code/tests/unit_tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ def test_successful_update_restarts_before_launch(self) -> None:
return_value=Path("/tmp/dcode-update.log"),
),
patch("deepagents_code.update_check.perform_upgrade", upgrade),
patch(
"deepagents_code.update_check.clear_startup_auto_update_failure"
) as clear_failure,
patch(
"deepagents_code.main._restart_current_process",
side_effect=SystemExit(0),
Expand All @@ -132,6 +135,7 @@ def test_successful_update_restarts_before_launch(self) -> None:
_run_startup_auto_update(console)

upgrade.assert_awaited_once()
clear_failure.assert_called_once_with("9.9.9")
printed = " ".join(str(c.args[0]) for c in console.print.call_args_list)
assert "tail -f /tmp/dcode-update.log" in printed
restart.assert_called_once_with()
Expand Down Expand Up @@ -292,16 +296,56 @@ def test_failed_update_does_not_restart_and_continues(self) -> None:
return_value="uv tool upgrade deepagents-code",
),
patch("deepagents_code.update_check.perform_upgrade", upgrade),
patch(
"deepagents_code.update_check.mark_startup_auto_update_failed"
) as mark_failed,
patch("deepagents_code.main._restart_current_process") as restart,
):
# Must not raise: a failed upgrade falls through to launch.
_run_startup_auto_update(console)

upgrade.assert_awaited_once()
mark_failed.assert_called_once_with("9.9.9")
restart.assert_not_called()
printed = " ".join(str(c.args[0]) for c in console.print.call_args_list)
assert "Auto-update failed" in printed

def test_recent_failure_cooldown_skips_startup_update(self) -> None:
"""A same-version startup failure cooldown must bypass repeat attempts."""
console = MagicMock()

with (
patch("deepagents_code.config._is_editable_install", return_value=False),
patch(
"deepagents_code.update_check.is_update_check_enabled",
return_value=True,
),
patch(
"deepagents_code.update_check.is_auto_update_enabled",
return_value=True,
),
patch(
"deepagents_code.update_check.get_cached_update_available",
return_value=(True, "9.9.9"),
),
patch(
"deepagents_code.update_check.should_skip_startup_auto_update_after_failure",
return_value=True,
) as should_skip,
patch(
"deepagents_code.update_check.upgrade_command",
return_value="uv tool install -U deepagents-code",
),
patch("deepagents_code.update_check.perform_upgrade") as upgrade,
patch("deepagents_code.main._restart_current_process") as restart,
):
_run_startup_auto_update(console)

should_skip.assert_called_once_with("9.9.9")
upgrade.assert_not_called()
restart.assert_not_called()
printed = " ".join(str(c.args[0]) for c in console.print.call_args_list)
assert "recent failed attempt" in printed

def test_editable_install_skips_update(self) -> None:
"""Editable installs must short-circuit before any PyPI/install work."""
console = MagicMock()
Expand Down Expand Up @@ -801,7 +845,11 @@ def test_startup_auto_update_wired_into_interactive_launch(self) -> None:
no-op.
"""
source = inspect.getsource(cli_main)
assert "_run_startup_auto_update(console)" in source
expected = (
"if resume_thread is None:\n"
" _run_startup_auto_update(console)"
)
assert expected in source


class TestAutoUpdateDefaultMigration:
Expand Down
Loading
Loading