Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(autostart): write the startup entry in-process, without spawning PowerShell (#724)
Ruben Lütke9d1415a5baf3
diff --git a/jarvis/autostart/windows.py b/jarvis/autostart/windows.pyindex 276a7eac5e..1e2693383e 100644--- a/jarvis/autostart/windows.py+++ b/jarvis/autostart/windows.py@@ -22,11 +22,19 @@ account's filtered token). *Reading* a task's state does not. So:works (just possibly delayed). The Settings panel surfaces an "enable instantstart" affordance to upgrade the fallback to a task.-Everything shells out to PowerShell (subprocess) exactly like-``scripts/install_shortcuts.py`` — **no ``pywin32`` dependency**. The+The silent paths — the task probe and the fallback ``.lnk`` read/write that the+boot reconcile runs on every start, including the very first one — talk to the+Task Scheduler and ``WScript.Shell`` **in-process** through pywin32 COM. They+used to shell out to ``powershell.exe -ExecutionPolicy Bypass``, and an app that+spawns a hidden PowerShell on its first launch to drop a shortcut into the+Startup folder is exactly the chain behaviour-based antivirus blocks: Bitdefender+quarantined the v3.2.0 install for it (issue #713, ``explorer.exe ->+personaljarvis.exe -> powershell.exe``). PowerShell remains only as a fallback+for a host without pywin32, for a Store Python whose in-process writes would be+redirected into its MSIX container (BUG-138), and for the one-time elevated task+registration the user starts from Settings and confirms in a UAC prompt. Thescript-assembly functions are pure (unit-testable cross-platform); only execution-requires Windows. The ``.lnk`` builders (``build_create_script`` /-``build_read_script``) are unchanged and still used for the fallback.+requires Windows."""from __future__ import annotations@@ -38,9 +46,11 @@ import ntpathimport osimport subprocessimport tempfile-from collections.abc import Callable+from collections.abc import Callable, Iterator+from contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Path+from typing import TypeVarfrom jarvis.core.branding import (WINDOWS_AUTOSTART_DESCRIPTION,@@ -57,6 +67,8 @@ from .protocol import AutostartStatus, LaunchSpeclog = logging.getLogger(__name__)+_T = TypeVar("_T")+# Scheduled-task identity. A stable name so reconcile can find/refresh it.# How long after login the task waits before launching — lets the desktop settle# without the multi-minute Explorer startup throttle.@@ -388,11 +400,12 @@ def _tag_shortcut_aumid(link: Path) -> bool:propsys.PROPVARIANTType(APP_USER_MODEL_ID),)store.Commit()- # The .lnk itself is created by a PowerShell child, which is why it- # reaches the real Startup folder under a Store Python (BUG-138). This- # commit runs IN-PROCESS, so it is redirected: it would leave the real- # shortcut untagged and drop a container copy that masks it from every- # later in-process read. Publishing puts the tagged version back.+ # Under a Store Python the .lnk itself is created by a PowerShell+ # child, which is why it reaches the real Startup folder (BUG-138).+ # This commit runs IN-PROCESS, so there it is redirected: it would+ # leave the real shortcut untagged and drop a container copy that+ # masks it from every later in-process read. Publishing puts the+ # tagged version back (a no-op on an unpackaged interpreter).from jarvis.ui.msix_redirection import publish_out_of_containerif not publish_out_of_container(link):@@ -404,6 +417,170 @@ def _tag_shortcut_aumid(link: Path) -> bool:return False+# --------------------------------------------------------------------------- #+# In-process COM (the silent paths; no child process at all) #+# --------------------------------------------------------------------------- #+++def _win32com() -> tuple[object, object] | None:+ """``(pythoncom, win32com.client)``, or ``None`` when pywin32 is absent.++ Lazy (HN-7): this module is imported on every OS, pywin32 exists only on+ Windows, and only in the ``desktop`` extra. The frozen installer build+ always bundles it (``jarvis.spec`` hidden imports).+ """+ try:+ import pythoncom # type: ignore[import-not-found]+ import win32com.client # type: ignore[import-not-found]+ except Exception: # noqa: BLE001 — absent or broken pywin32 → PowerShell fallback+ return None+ return pythoncom, win32com.client+++@contextmanager+def _com_apartment(pythoncom: object) -> Iterator[None]:+ """Initialise COM on the calling thread for the duration of the block.++ The boot reconcile runs on a worker thread that has never touched COM. A+ thread that already joined a different apartment refuses re-initialisation+ (``RPC_E_CHANGED_MODE``) but can use COM as it is, so that is not an error.+ """+ try:+ pythoncom.CoInitialize() # type: ignore[attr-defined]+ except Exception: # noqa: BLE001 — already initialised in another mode+ yield+ return+ try:+ yield+ finally:+ pythoncom.CoUninitialize() # type: ignore[attr-defined]+++def _shortcut_needs_helper(link: Path) -> bool:+ """Would an in-process write to ``link`` land in an MSIX container?++ Only a Store Python is packaged; its writes under ``%APPDATA%`` are+ redirected where Explorer never looks (BUG-138), which is why the shortcut+ was written by a PowerShell child in the first place. Every other host —+ the installer build above all — writes in-process.+ """+ try:+ from jarvis.ui.msix_redirection import redirects_writes++ return redirects_writes(link)+ except Exception as exc: # noqa: BLE001 — undecidable → the proven helper path+ log.debug("MSIX redirection check failed for %s: %s", link, exc)+ return True+++def _run_com(work: Callable[[object, object], _T]) -> _T:+ """Run ``work(pythoncom, win32com.client)`` inside a COM apartment.++ Raises :class:`LookupError` when pywin32 is unavailable, so a caller can+ fall back to PowerShell. Every COM proxy ``work`` creates lives in its own+ frame and is released when it returns, i.e. BEFORE ``CoUninitialize`` — a+ proxy released after it makes pywin32 complain on every call. For the same+ reason a failure is re-raised as a plain :class:`OSError` once the+ apartment is closed: the original traceback would keep the proxies alive.+ """+ com = _win32com()+ if com is None:+ raise LookupError("pywin32 is not available")+ pythoncom, client = com+ with _com_apartment(pythoncom):+ try:+ return work(pythoncom, client)+ except Exception as exc: # noqa: BLE001 — re-raised below, proxy-free+ error = f"{type(exc).__name__}: {exc}"+ raise OSError(error)+++def _read_task(pythoncom: object, client: object, task_name: str) -> _TaskInfo | None:+ service = client.Dispatch("Schedule.Service") # type: ignore[attr-defined]+ service.Connect()+ try:+ task = service.GetFolder("\\").GetTask(task_name)+ except pythoncom.com_error: # type: ignore[attr-defined]+ return None # not registered+ actions = task.Definition.Actions+ action = actions.Item(1) if actions.Count else None+ return _TaskInfo(+ execute=str(getattr(action, "Path", "") or ""),+ arguments=str(getattr(action, "Arguments", "") or ""),+ working_dir=str(getattr(action, "WorkingDirectory", "") or ""),+ enabled=bool(task.Enabled),+ )+++def _query_task_in_process(task_name: str) -> _TaskInfo | None:+ """Read the logon task through the Task Scheduler COM API.++ Raises :class:`LookupError` when pywin32 is unavailable so the caller can+ fall back; any other failure propagates and the caller treats it as "no+ task", the same rule the PowerShell query follows.+ """+ return _run_com(lambda pythoncom, client: _read_task(pythoncom, client, task_name))+++def _save_shortcut(client: object, link: Path, spec: LaunchSpec, icon: str | None) -> None:+ sc = client.Dispatch("WScript.Shell").CreateShortcut(str(link)) # type: ignore[attr-defined]+ sc.TargetPath = spec.program+ sc.Arguments = " ".join(spec.args)+ sc.WorkingDirectory = spec.working_dir+ sc.Description = WINDOWS_AUTOSTART_DESCRIPTION+ if icon:+ sc.IconLocation = f"{icon},0"+ sc.WindowStyle = 7 if spec.minimized else 1+ sc.Save()+++def _load_shortcut(client: object, link: Path) -> list[str]:+ sc = client.Dispatch("WScript.Shell").CreateShortcut(str(link)) # type: ignore[attr-defined]+ return [+ str(sc.TargetPath or ""),+ str(sc.Arguments or ""),+ str(sc.WorkingDirectory or ""),+ str(sc.IconLocation or ""),+ ]+++def _write_shortcut_in_process(link: Path, spec: LaunchSpec, *, icon: str | None) -> bool:+ """Create/refresh the fallback ``.lnk`` in-process. ``False`` = not possible here.++ Writes the same fields as :func:`build_create_script`.+ """+ if _shortcut_needs_helper(link):+ return False+ try:+ _run_com(lambda _pythoncom, client: _save_shortcut(client, link, spec, icon))+ except LookupError: # no pywin32 here - the caller writes through PowerShell+ return False+ return True+++def _read_shortcut_in_process(link: Path) -> list[str] | None:+ """TargetPath/Arguments/WorkingDirectory/IconLocation; ``None`` = not possible here.++ A Store Python would read its own container copy rather than the shortcut+ Explorer sees, so it keeps reading through the helper.+ """+ if _shortcut_needs_helper(link):+ return None+ try:+ return _run_com(lambda _pythoncom, client: _load_shortcut(client, link))+ except LookupError: # no pywin32 here - the caller reads through PowerShell+ return None+++def _read_shortcut_fields(link: Path) -> list[str]:+ """The shortcut's four read-back fields, in-process when possible."""+ fields = _read_shortcut_in_process(link)+ if fields is not None:+ return fields+ result = _run_powershell(build_read_script(link))+ return _sentinel_fields(result.stdout, _READBACK_SENTINEL)++def _run_powershell(script: str) -> subprocess.CompletedProcess[str]:# encoding/errors are pinned rather than left to the locale: without them# Python decodes the pipe with the ANSI code page while PowerShell wrote it@@ -696,6 +873,13 @@ class WindowsAutostart:# ---- real (live) default operations ------------------------------------def _default_task_probe(self) -> _TaskInfo | None:+ try:+ return _query_task_in_process(self._task_name)+ except LookupError:+ pass # no pywin32 → the PowerShell query below+ except Exception as exc: # noqa: BLE001 — query failure → treat as absent+ log.debug("scheduled-task query failed: %s", exc)+ return Nonetry:result = _run_powershell(build_query_task_script(self._task_name))except Exception as exc: # noqa: BLE001 — query failure → treat as absent@@ -707,11 +891,10 @@ class WindowsAutostart:if not self._path.exists():return Falsetry:- result = _run_powershell(build_read_script(self._path))+ fields = _read_shortcut_fields(self._path)except Exception as exc: # noqa: BLE001 — unreadable → not a matchlog.debug("shortcut read failed: %s", exc)return False- fields = _sentinel_fields(result.stdout, _READBACK_SENTINEL)if len(fields) < 4:# A truncated read-back is "unknown", not "matches". Padding the# missing fields with "" made a half-failed COM read compare equal@@ -744,7 +927,9 @@ class WindowsAutostart:def _default_write_shortcut(self, spec: LaunchSpec) -> None:self._path.parent.mkdir(parents=True, exist_ok=True)self._remove_legacy()- _run_powershell(build_create_script(self._path, spec, icon=_resolve_app_icon()))+ icon = _resolve_app_icon()+ if not _write_shortcut_in_process(self._path, spec, icon=icon):+ _run_powershell(build_create_script(self._path, spec, icon=icon))# Tag the shortcut with the SAME AUMID as the Start-Menu shortcut so the# two same-named .lnk files don't diverge and confuse the shell's taskbar# button resolution (best-effort; a box without pywin32 still gets thediff --git a/tests/unit/autostart/test_windows_task.py b/tests/unit/autostart/test_windows_task.pyindex 01de5e5156..92ac888422 100644--- a/tests/unit/autostart/test_windows_task.py+++ b/tests/unit/autostart/test_windows_task.py@@ -412,6 +412,8 @@ def test_truncated_shortcut_readback_is_drift_not_a_match(monkeypatch) -> None:bare = LaunchSpec(program=r"C:\Python\pythonw.exe", args=(), working_dir="")encoded = base64.b64encode(bare.program.encode("utf-8")).decode("ascii")monkeypatch.setattr(Path, "exists", lambda self: True)+ # Force the PowerShell read-back path: in-process COM is "not possible here".+ monkeypatch.setattr(win_mod, "_read_shortcut_in_process", lambda link: None)monkeypatch.setattr(win_mod,"_run_powershell",@@ -528,3 +530,79 @@ def test_elevated_launcher_fails_safe_on_a_null_exit_code(monkeypatch) -> None:assert "if ($null -eq $p -or $null -eq $p.ExitCode) { exit 1 }" in launcher# The guard must come BEFORE the forwarding exit, or it changes nothing.assert launcher.index("$null -eq $p.ExitCode") < launcher.index("exit $p.ExitCode")+++# --------------------------------------------------------------------------- #+# Silent paths stay in-process (issue #713: Bitdefender blocked the app for #+# spawning powershell.exe on its first launch to write the startup shortcut) #+# --------------------------------------------------------------------------- #+++def _no_powershell(script: str):+ raise AssertionError("the silent autostart path must not spawn PowerShell")+++def test_boot_reconcile_writes_the_shortcut_without_powershell(monkeypatch, tmp_path) -> None:+ from jarvis.autostart import windows as win_mod++ written: list[tuple[object, LaunchSpec, object]] = []+ monkeypatch.setattr(win_mod, "_run_powershell", _no_powershell)+ monkeypatch.setattr(win_mod, "_tag_shortcut_aumid", lambda link: True)+ monkeypatch.setattr(win_mod, "_startup_dir", lambda: tmp_path)+ monkeypatch.setattr(+ win_mod,+ "_write_shortcut_in_process",+ lambda link, spec, icon: written.append((link, spec, icon)) or True,+ )+ mgr = WindowsAutostart(task_probe=lambda: None, run_elevated=lambda s: False)+ mgr.install(_SPEC)+ assert len(written) == 1+ assert written[0][1] == _SPEC+++def test_shortcut_falls_back_to_powershell_only_when_in_process_is_impossible(+ monkeypatch, tmp_path+) -> None:+ from jarvis.autostart import windows as win_mod++ scripts: list[str] = []+ monkeypatch.setattr(win_mod, "_run_powershell", lambda script: scripts.append(script))+ monkeypatch.setattr(win_mod, "_tag_shortcut_aumid", lambda link: True)+ monkeypatch.setattr(win_mod, "_startup_dir", lambda: tmp_path)+ monkeypatch.setattr(win_mod, "_write_shortcut_in_process", lambda link, spec, icon: False)+ WindowsAutostart()._default_write_shortcut(_SPEC)+ assert len(scripts) == 1+ assert "CreateShortcut" in scripts[0]+++def test_task_probe_uses_com_and_skips_powershell(monkeypatch) -> None:+ from jarvis.autostart import windows as win_mod++ monkeypatch.setattr(win_mod, "_run_powershell", _no_powershell)+ monkeypatch.setattr(win_mod, "_query_task_in_process", lambda name: _MATCHING_INFO)+ assert WindowsAutostart()._default_task_probe() == _MATCHING_INFO+++def test_task_probe_com_failure_reads_as_absent_not_powershell(monkeypatch) -> None:+ from jarvis.autostart import windows as win_mod++ def boom(name: str):+ raise OSError("Task Scheduler unavailable")++ monkeypatch.setattr(win_mod, "_run_powershell", _no_powershell)+ monkeypatch.setattr(win_mod, "_query_task_in_process", boom)+ assert WindowsAutostart()._default_task_probe() is None+++def test_task_probe_without_pywin32_falls_back_to_powershell(monkeypatch) -> None:+ import subprocess++ from jarvis.autostart import windows as win_mod++ monkeypatch.setattr(win_mod, "_win32com", lambda: None)+ monkeypatch.setattr(+ win_mod,+ "_run_powershell",+ lambda script: subprocess.CompletedProcess(["powershell"], 0, stdout="", stderr=""),+ )+ assert WindowsAutostart()._default_task_probe() is None