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
"""Win32 helper for setting the window icon of a pywebview instance.
Why does Jarvis need this? pywebview's ``create_window`` has no ``icon``
parameter on Windows — the taskbar and titlebar icon therefore inherits from
the process (``python.exe`` / ``pythonw.exe``), i.e. the generic Python logo.
We set it after the ``shown`` event via ``WM_SETICON`` directly against the
window handle.
All functions are no-ops on non-Windows platforms.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
from typing import Any
from loguru import logger
from dodaios.core.branding import (
WINDOWS_BRANDED_LAUNCH_ENV_VAR,
WINDOWS_BRANDED_LAUNCHER_DIR_NAME,
)
from dodaios.core.instance import current_instance
# Every OS-facing identity below follows the *instance* this process runs as
# (``dodaios.core.instance``): the default app keeps the stable branding
# constants, the dev app gets a distinct name, icon, AUMID, shortcut and branded
# exe so the two never group under one taskbar button, never focus each other's
# window and never overwrite each other's Start-Menu entry. Bound at import —
# the launcher pins the instance into the environment before importing this.
_INSTANCE = current_instance()
# The name REGISTERED with the Linux shell (desktop-entry ``Name``). It moves
# together with the entry's file name and the window class below.
APP_DISPLAY_NAME = _INSTANCE.linux_app_name
# The name registered with the Windows shell: toast identity, shortcut
# description, relaunch name. It matches the shortcut's file name, which is the
# name the taskbar and Windows Search show.
WINDOWS_APP_DISPLAY_NAME = _INSTANCE.windows_launcher_entry_name
APP_USER_MODEL_ID = _INSTANCE.windows_aumid
BRANDED_LAUNCHER_EXE_NAME = _INSTANCE.windows_branded_launcher_file_name
#: Earlier names of the branded exe. Never created again, but a copy under
#: one of them is still this app (a pinned taskbar button or a shortcut of an
#: earlier release starts it), so it never re-execs into the current name.
LEGACY_BRANDED_LAUNCHER_EXE_NAMES = _INSTANCE.legacy_windows_branded_launcher_file_names
START_MENU_SHORTCUT_NAME = _INSTANCE.windows_shortcut_file_name
#: Earlier names of the Start-Menu and Desktop shortcut, retired once the
#: current one is in place (``dodaios.setup.desktop_integration``).
LEGACY_START_MENU_SHORTCUT_NAMES = _INSTANCE.legacy_windows_shortcut_file_names
LINUX_DESKTOP_ENTRY_NAME = _INSTANCE.linux_desktop_entry_file_name
#: Earlier names of the applications-menu entry, retired once the current one
#: is in place, and only where they start this install.
LEGACY_LINUX_DESKTOP_ENTRY_NAMES = _INSTANCE.legacy_linux_desktop_entry_file_names
LINUX_WM_CLASS = _INSTANCE.linux_wm_class
#: Launcher argv written into shortcuts / desktop entries so a click reopens
#: THIS instance (``--instance dev`` for the dev app, nothing for the default).
_LAUNCHER_ARGS: tuple[str, ...] = _INSTANCE.launcher_args
_WM_SETICON = 0x0080
_ICON_SMALL = 0
_ICON_BIG = 1
_IMAGE_ICON = 1
_LR_LOADFROMFILE = 0x00000010
_LR_DEFAULTSIZE = 0x00000040
# Class icon slots (negative indices for SetClassLongPtrW). Windows uses the
# class icon for the taskbar entry when no window icon (WM_SETICON) has been
# set yet at first display. Without a class icon, the taskbar
# falls back to the process icon (pythonw.exe → Python logo)
# and caches that mapping for the rest of the session.
_GCLP_HICON = -14
_GCLP_HICONSM = -34
# The friendly name Windows shows on taskbar hover and in the jump-list header.
# This is a *different* layer from the AUMID grouping key above: the key only
# groups the button. The name is resolved by matching the running window's AUMID
# to a **Start-Menu shortcut** carrying the same ``System.AppUserModel.ID`` and
# using that shortcut's file name + icon (see ``ensure_start_menu_shortcut``).
# Without such a shortcut the shell falls back to the process ``FileDescription``
# (``pythonw.exe`` -> "Python"), which is the "taskbar says Python" symptom.
# (The HKCU ``DisplayName`` registered below is the *toast-notification*
# identity, a separate surface — it does NOT name the taskbar button.)
# Start-Menu shortcut whose *file name* becomes the taskbar button name. The
# launcher module is the relaunch target so a fresh click reopens the app.
_LAUNCHER_MODULE = "dodaios.ui.web.launcher"
# IID_IPropertyStore — the COM interface for reading/writing a .lnk's AUMID.
_IID_IPROPERTYSTORE = "{886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99}"
def _installer_owns_shell_registration(artifact: str) -> bool:
"""True when a native installer owns ``artifact`` and this app must not.
Every shell artifact written in this module relaunches Jarvis as
``<interpreter> -m dodaios.ui.web.launcher`` — the source-install shape. A
PyInstaller executable cannot run that command line, and inside an AppImage
the interpreter path points into a mount that disappears when the app
exits, so the entry would be broken twice over. The native installers
(``Setup.exe``, ``.dmg``, ``.deb``/AppImage integration) create the real
launcher and remove it again on uninstall; this app only has to keep its
hands off it. See ``dodaios/setup/desktop_integration.py`` for the same rule
on the registration lifecycle as a whole.
"""
from dodaios.core.frozen import is_frozen
if not is_frozen():
return False
logger.debug(
"{} not written: this is a native-installer build and the installer "
"owns the shell registration.",
artifact,
)
return True
# A per-install copy of ``pythonw.exe`` (next to the interpreter, or in the
# per-user ``%LOCALAPPDATA%\DodaiosApp\bin`` when the base dir is read-only),
# carrying the Jarvis mascot as its EMBEDDED icon. On Windows the taskbar button of
# a running app takes the icon of the LAUNCHING EXECUTABLE — not the window icon,
# class icon, AUMID, Start-Menu shortcut, registry, or icon cache (all verified
# to have no effect on the button). A bare ``pythonw.exe`` launch therefore shows
# the Python logo on the taskbar no matter how much window-icon work we do; the
# ONLY fix is to launch from an exe whose embedded icon is the mascot. See
# ``ensure_branded_launcher_exe`` + ``maybe_reexec_through_branded_launcher``.
# Set in the child's env when we re-exec through the branded exe, so the child
# does not re-exec again (loop guard).
_BRANDED_LAUNCH_ENV = WINDOWS_BRANDED_LAUNCH_ENV_VAR
def register_windows_app_user_model_id(
app_id: str = APP_USER_MODEL_ID,
*,
display_name: str = WINDOWS_APP_DISPLAY_NAME,
icon_path: Path | None = None,
) -> bool:
"""Register the AUMID's ``DisplayName`` (+ icon) under HKCU for *toasts*.
This names the AUMID for the **toast-notification / Action-Center** surface
only. It does NOT name the taskbar button — that is resolved from an
AUMID-tagged Start-Menu shortcut (see ``ensure_start_menu_shortcut``).
Registering the AUMID under
``HKCU\\Software\\Classes\\AppUserModelId\\<app_id>`` with a ``DisplayName``
(and optional ``IconResource``) is the documented way to give a custom AUMID
a friendly toast identity instead of the ``pythonw.exe`` description.
Idempotent (a re-register just rewrites the same values), Windows-only,
best-effort — it never raises and never blocks boot. Returns ``True`` only
when the registration was written.
"""
if sys.platform != "win32":
return False
try:
import winreg
subkey = rf"Software\Classes\AppUserModelId\{app_id}"
with winreg.CreateKeyEx(
winreg.HKEY_CURRENT_USER, subkey, 0, winreg.KEY_SET_VALUE
) as key:
winreg.SetValueEx(key, "DisplayName", 0, winreg.REG_SZ, display_name)
if icon_path is not None:
# "<path>,<index>" lets Explorer pick the icon frame; index 0 is
# the first/largest. REG_EXPAND_SZ matches the shell convention.
winreg.SetValueEx(
key,
"IconResource",
0,
winreg.REG_EXPAND_SZ,
f"{icon_path},0",
)
return True
except Exception as exc: # noqa: BLE001
logger.debug("AUMID DisplayName could not be registered: {}", exc)
return False
def _pythonw_executable() -> Path | None:
"""Best-effort ``pythonw.exe`` next to the running interpreter.
``pythonw`` (GUI subsystem) avoids a console window when the shortcut is
clicked; falls back to ``python.exe`` if the windowless variant is absent.
"""
exe = Path(sys.executable)
cand = exe.with_name("pythonw.exe")
if cand.exists():
return cand
return exe if exe.exists() else None
def _shortcut_launch_target() -> Path | None:
"""What the Start-Menu shortcut should launch — our own exe when we have one.
Windows does not list a shortcut whose target is a GENERIC HOST as an app.
That is not a quirk: the same rule hides the shell's own
``Command Prompt`` (cmd.exe), ``Run`` (rundll32.exe) and ``File Explorer``
entries from the app list, because one host executable cannot stand for the
many different things launched through it. A shortcut aimed at
``pythonw.exe`` falls in that bucket, so the entry exists on disk, opens the
app on a double-click, and is still absent from Windows Search — the exact
report from 2026-08-16, next to an Obsidian and a Discord entry that work
because each points at its own ``.exe``.
``DodaiosApp.exe`` built inside the venv IS our own executable and needs
no environment handed to it, so it is a valid shortcut target and makes the
entry a real app. The other branded homes need ``__PYVENV_LAUNCHER__``,
which a shortcut cannot supply — those keep the historical ``pythonw``
target, where the branded copy is reached through the re-exec in ``main()``
instead. Falls back to ``pythonw`` whenever no branded copy can be built.
"""
branded = ensure_branded_launcher_exe()
if branded is not None and _is_self_contained_branded_exe(branded):
return branded
return _pythonw_executable()
def _interpreter_can_open_a_window() -> bool:
"""Does the RUNNING interpreter have the toolkit the desktop window needs?
The Start-Menu shortcut is written against ``sys.executable``, so it is only
a valid launch target if that interpreter can actually open the window.
Guarding on pywebview is what keeps a foreign interpreter out of the
shortcut: the identity call sits on an import path that headless runs, CLI
commands and stray virtualenvs all reach, and whichever one ran last used to
win. Repoint the shortcut at a python without pywebview and the Start-Menu
entry dies silently — ``pythonw`` has no console, so the ImportError goes
nowhere and the app simply never appears (live forensic 2026-08-16: a
``--headless`` run from an unrelated venv rewrote the entry, after which
Windows Search launched a window-less interpreter and nothing happened).
``find_spec`` only resolves the module, it never imports pywebview — this
runs on the boot critical path (AP-26).
"""
import importlib.util
try:
return importlib.util.find_spec("webview") is not None
except (ImportError, ValueError): # broken/partial install
return False
#: Config value that means "transcribe on this machine". The shortcut guard has
#: to recognise the choice without importing the STT package — that package pulls
#: the whole provider catalogue, and this runs while the app is booting.
_ON_DEVICE_STT_PROVIDER = "faster-whisper"
def _config_wants_on_device_speech() -> bool:
"""Does ``jarvis.toml`` name the on-device recognizer as EITHER role?
Both ``[stt].provider`` and ``[stt].fallback`` count, and the fallback is
not the lesser half: a cloud-first setup that names the local engine as its
floor is relying on it for exactly the case that broke — the cloud account
answering 402 mid-dictation. An interpreter without the engine silently
removes that floor, which is how 24.3 s of speech were lost with no local
recognizer left to catch them.
A direct, BOM-safe TOML read (the idiom
``dodaios.ui.dodaiosbar.interaction._load_jarvisbar_section`` already uses):
one file stat and a parse, no pydantic, no provider catalogue, nothing
initialised (AP-26). An unreadable or absent file answers ``False``, which
the caller treats as "cannot tell" and therefore never as a reason to
refuse — a base install with no config yet must still get its shortcut.
"""
import tomllib
try:
from dodaios.core.config import DEFAULT_CONFIG_FILE
raw = Path(DEFAULT_CONFIG_FILE).read_bytes()
data = tomllib.loads(raw.decode("utf-8-sig"))
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError, ImportError) as exc:
# Silence is correct and load-bearing here (AP-30): every one of these
# means "this build cannot tell what the user chose", and the caller
# reads that as "no reason to refuse". Logging a warning per boot for a
# base install that has no config file yet would be pure noise.
logger.debug("Could not read the configured STT roles: {}", exc)
return False
section = data.get("stt")
if not isinstance(section, dict):
return False
return any(
isinstance(value := section.get(role), str)
and value.strip() == _ON_DEVICE_STT_PROVIDER
for role in ("provider", "fallback")
)
def _interpreter_can_run_the_configured_speech() -> bool:
"""Can the RUNNING interpreter do the speech recognition the config asks for?
The other half of the 2026-08-16 rule, learned the hard way on 2026-08-25.
That rule stopped a window-LESS interpreter from claiming the launcher; this
stops a speech-less one. Python 3.12 on the maintainer's box had pywebview
but not ``faster_whisper``, so it passed the window probe, rewrote the
Start-Menu entry to itself, and every launch after that opened a perfectly
normal window whose local transcription had silently been swapped for a
cloud provider. The swap only surfaced when that cloud account ran out of
credit and a dictation lost 24.3 s of speech.
Deliberately conditional on the CHOICE, not on the package: a cloud-first
install (the default, and what a base download gets) never has the on-device
engine and must still be able to own its own shortcut. Only a user who
picked the on-device recognizer has an interpreter without it refused — for
them, a launcher that cannot transcribe locally is a broken launcher.
``find_spec`` only resolves; nothing is imported (AP-26).
"""
if not _config_wants_on_device_speech():
return True
import importlib.util
try:
return importlib.util.find_spec("faster_whisper") is not None
except (ImportError, ValueError): # broken/partial install
return False
def _interpreter_may_own_the_launcher_shortcut() -> bool:
"""Whether this interpreter is allowed to (re)write the launcher shortcuts.
One gate in front of both entries, because "last run wins" is the failure
mode: whichever interpreter last reached this code used to take the shortcut,
however much less it could do than the one already there. A capability it
lacks is a capability the user loses on their next double-click.
"""
return _interpreter_can_open_a_window() and _interpreter_can_run_the_configured_speech()
def _replace_exe_icon(exe_path: Path, ico_path: Path) -> bool:
"""Overwrite ``exe_path``'s embedded application icon with ``ico_path``.
Rewrites the ``RT_ICON`` images + the primary ``RT_GROUP_ICON`` (id 1, the
group Explorer uses as the app icon for ``pythonw.exe``) via the Win32
``*UpdateResource`` API — no external tool (rcedit/PyInstaller) needed. The
file must not be running. Returns ``True`` on success.
"""
import ctypes
import struct
from ctypes import wintypes
try:
data = ico_path.read_bytes()
_reserved, _itype, count = struct.unpack("<HHH", data[:6])
entries = []
off = 6
for _ in range(count):
w, h, cc, _r, planes, bc, size, imgoff = struct.unpack(
"<BBBBHHII", data[off : off + 16]
)
entries.append(
{
"w": w, "h": h, "cc": cc, "planes": planes, "bc": bc,
"img": data[imgoff : imgoff + size], "size": size,
}
)
off += 16
except Exception as exc: # noqa: BLE001
logger.debug("could not parse .ico for exe branding: {}", exc)
return False
RT_ICON, RT_GROUP_ICON, LANG = 3, 14, 0x0409
# A private WinDLL instance, not ctypes.windll.kernel32: mutating
# argtypes on the shared object corrupts every other caller in the
# process (e.g. pywebview's winforms SetWindowPos calls).
k = ctypes.WinDLL("kernel32", use_last_error=True)
k.BeginUpdateResourceW.restype = wintypes.HANDLE
k.BeginUpdateResourceW.argtypes = [wintypes.LPCWSTR, wintypes.BOOL]
k.UpdateResourceW.argtypes = [
wintypes.HANDLE, wintypes.LPCWSTR, wintypes.LPCWSTR,
wintypes.WORD, wintypes.LPVOID, wintypes.DWORD,
]
k.EndUpdateResourceW.argtypes = [wintypes.HANDLE, wintypes.BOOL]
def _res_id(i: int): # MAKEINTRESOURCE
return ctypes.cast(ctypes.c_void_p(i), wintypes.LPCWSTR)
handle = k.BeginUpdateResourceW(str(exe_path), False)
if not handle:
logger.debug("BeginUpdateResource failed for {}", exe_path)
return False
try:
for i, e in enumerate(entries):
buf = ctypes.create_string_buffer(e["img"], len(e["img"]))
if not k.UpdateResourceW(
handle, _res_id(RT_ICON), _res_id(1 + i), LANG, buf, len(e["img"])
):
logger.debug("UpdateResource RT_ICON {} failed", i)
grp = struct.pack("<HHH", 0, 1, len(entries))
for i, e in enumerate(entries):
grp += struct.pack(
"<BBBBHHIH", e["w"] & 0xFF, e["h"] & 0xFF, e["cc"], 0,
e["planes"] or 1, e["bc"] or 32, e["size"], 1 + i,
)
gbuf = ctypes.create_string_buffer(grp, len(grp))
if not k.UpdateResourceW(
handle, _res_id(RT_GROUP_ICON), _res_id(1), LANG, gbuf, len(grp)
):
logger.debug("UpdateResource RT_GROUP_ICON failed")
return bool(k.EndUpdateResourceW(handle, False))
except Exception as exc: # noqa: BLE001
logger.debug("exe icon resource update failed: {}", exc)
try:
k.EndUpdateResourceW(handle, True) # discard
except Exception: # noqa: BLE001
pass
return False
def _base_pythonw_executable() -> Path | None:
"""The BASE interpreter's ``pythonw.exe`` (``sys.base_prefix``), or ``None``.
This — not the venv ``pythonw.exe`` — is the process that actually OWNS the
window: a venv launcher is a thin redirector that re-spawns the base
interpreter, and Windows takes the taskbar-button icon from that final
window-owning exe. So the mascot must be branded onto a copy of the *base*
pythonw, not the venv stub.
"""
base = Path(sys.base_prefix)
cand = base / "pythonw.exe"
if cand.exists():
return cand
alt = base / "python.exe"
return alt if alt.exists() else None
def _user_launcher_dir() -> Path | None:
"""Per-user home for the branded exe when the base dir is not writable.
``%LOCALAPPDATA%\\DodaiosApp\\bin`` is writable for every account — the
base interpreter dir is NOT on most machines (an all-users install lands in
``Program Files``; only an elevated/admin session can write there, which is
why base-dir-only branding worked on the maintainer's box and silently kept
the Python logo everywhere else).
"""
local = os.environ.get("LOCALAPPDATA")
if not local:
return None
return Path(local) / WINDOWS_BRANDED_LAUNCHER_DIR_NAME / "bin"
def _venv_pythonw_executable() -> Path | None:
"""The venv's OWN ``pythonw.exe``, when this process runs inside a venv.
Unlike the base interpreter this is a real ~250 KB launcher binary even when
the base Python came from the Microsoft Store, and it locates its
environment from ``pyvenv.cfg`` one directory up — by its LOCATION, not its
file name. A renamed copy beside it therefore boots the same venv with no
``__PYVENV_LAUNCHER__`` and no copied runtime DLLs, which is what makes it
the only branding source that survives a Store install (see
``_branded_launcher_candidates``).
"""
exe = Path(sys.executable)
cand = exe.with_name("pythonw.exe")
if not cand.is_file():
return None
if not (cand.parent.parent / "pyvenv.cfg").is_file():
return None # not a venv layout — the copy would not find an environment
try:
if cand.stat().st_size == 0:
return None # an alias, not a launcher
except OSError:
return None
return cand
def _branded_launcher_candidates() -> list[tuple[Path, Path]]:
"""``(source, target)`` pairs for the branded copy, best first.
1. INSIDE THE VENV, copied from the venv's own launcher. Self-contained: the
copy finds its environment from ``pyvenv.cfg`` by location, so it needs
no ``__PYVENV_LAUNCHER__`` and is therefore a valid *shortcut target* —
the others are not. This is also the only home that works on a **Microsoft
Store** Python, where the base "interpreter" is a 0-byte app-execution
alias and its real binary sits in an unwritable ``WindowsApps`` folder
whose copies refuse to run outside their app container (forensic
2026-08-16: that is why branding silently failed on such a machine and
the app never appeared in Windows Search — see
``_shortcut_launch_target``).
2. NEXT TO the base interpreter — finds ``pythonXX.dll`` without any extra
file, but needs a writable base dir (admin-only under ``Program Files``).
3. The per-user dir — always writable, but the interpreter runtime DLLs must
be copied beside the exe (see ``_interpreter_runtime_dlls``).
In homes 2 and 3 the venv/base is re-attached at launch via
``__PYVENV_LAUNCHER__``, so path resolution inside the child is identical.
"""
candidates: list[tuple[Path, Path]] = []
venv = _venv_pythonw_executable()
if venv is not None:
candidates.append((venv, venv.with_name(BRANDED_LAUNCHER_EXE_NAME)))
base = _base_pythonw_executable()
if base is not None:
candidates.append((base, base.with_name(BRANDED_LAUNCHER_EXE_NAME)))
user_dir = _user_launcher_dir()
if user_dir is not None:
candidates.append((base, user_dir / BRANDED_LAUNCHER_EXE_NAME))
return candidates
def _is_self_contained_branded_exe(exe: Path) -> bool:
"""Does this branded copy run the app without ``__PYVENV_LAUNCHER__``?
True only for the in-venv copy (home 1): it resolves its environment from
its own location. That is exactly the property a Start-Menu shortcut needs,
since a shortcut carries no environment of its own.
"""
return (exe.parent.parent / "pyvenv.cfg").is_file()
def _interpreter_runtime_dlls(src_dir: Path) -> list[Path]:
"""The DLLs a *relocated* ``pythonw`` copy needs beside it to start.
``pythonw.exe`` imports ``python3XX.dll`` (and stable-ABI extensions import
``python3.dll``), which the loader resolves from the exe's own directory —
a copy outside the base dir dies at process start without them.
``vcruntime140*.dll`` is python3XX.dll's own dependency and not guaranteed
to be in ``System32``. Everything else (stdlib, ``DLLs/*.pyd``) is resolved
through ``__PYVENV_LAUNCHER__`` path bootstrapping, not the exe location.
"""
return sorted({*src_dir.glob("python3*.dll"), *src_dir.glob("vcruntime140*.dll")})
def _branded_copy_boots(exe: Path) -> bool:
"""One out-of-process start of a freshly built branded copy.
A copy that cannot load its runtime DLLs dies before any window exists — and
the re-exec parent has already exited, so a broken copy would mean NO app at
all (observed during development). Since the in-venv copy is also the
Start-Menu shortcut's target, a broken one there would leave the user with a
Start-Menu entry that does nothing, so every fresh copy is verified.
The start mirrors how that copy is really launched: a self-contained in-venv
copy gets NO ``__PYVENV_LAUNCHER__``, because a shortcut hands it no
environment either; the other homes get the same re-attach ``main()`` uses.
On failure the caller deletes the copy and falls back to bare ``pythonw``.
"""
try:
import subprocess
from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS
env = dict(os.environ)
venv_pythonw = Path(sys.executable).with_name("pythonw.exe")
if _is_self_contained_branded_exe(exe):
env.pop("__PYVENV_LAUNCHER__", None)
elif venv_pythonw.is_file():
env["__PYVENV_LAUNCHER__"] = str(venv_pythonw)
proc = subprocess.run( # noqa: S603 — our own freshly built exe
[str(exe), "-c", "import sys; sys.exit(0)"],
env=env,
timeout=30,
creationflags=NO_WINDOW_CREATIONFLAGS,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return proc.returncode == 0
except Exception as exc: # noqa: BLE001 — an unverifiable copy is a bad copy
logger.debug("branded copy smoke check failed for {}: {}", exe, exc)
return False
def ensure_branded_launcher_exe() -> Path | None:
"""Create/refresh a mascot-icon copy of the BASE ``pythonw`` and return it.
The taskbar button takes its icon from the window-owning executable, which is
the *base* interpreter (the venv ``pythonw`` only redirects to it). So we copy
the base ``pythonw.exe`` to ``DodaiosApp.exe`` and stamp the Jarvis
``.ico`` as its embedded icon. The venv is re-attached at launch via
``__PYVENV_LAUNCHER__`` (see ``maybe_reexec_through_branded_launcher``), so
the branded copy runs the app with the venv's packages while OWNING the
window ⇒ mascot on the taskbar.
Two candidate homes, tried in order (``_branded_launcher_candidates``):
1. next to the base interpreter — zero extra files, but the base dir is
writable only for elevated accounts when Python lives under
``Program Files`` (the common all-users install);
2. ``%LOCALAPPDATA%\\DodaiosApp\\bin`` — writable for EVERY account;
the interpreter runtime DLLs are copied beside the exe and the fresh
copy is smoke-started once before it is trusted.
Idempotent + self-healing (rebuilds only when missing or older than the
icon/source exe). Returns ``None`` — caller falls back to bare ``pythonw``,
taskbar keeps the Python logo — only when NO candidate works, e.g. the
**MS Store Python** base exe (a 0-byte app-execution alias that cannot be
copied; the shipped PyInstaller build is the branded path there).
"""
if sys.platform != "win32":
return None
ico = project_icon_path()
if not ico.is_file():
return None
for src, target in _branded_launcher_candidates():
try:
# A 0-byte app-execution alias (MS Store) copies to an empty husk.
if src.stat().st_size == 0:
logger.debug("{} is a 0-byte alias (MS Store); skipping", src)
continue
except OSError as exc:
logger.debug("{} not statable; skipping: {}", src, exc)
continue
built = _ensure_branded_copy_at(src, target, ico)
if built is not None:
return built
return None
def _ensure_branded_copy_at(src: Path, target: Path, ico: Path) -> Path | None:
"""Build/refresh ONE branded-copy candidate; ``None`` → try the next home.
A relocated copy (target dir ≠ base dir) additionally gets the interpreter
runtime DLLs and must pass a one-time smoke start — a copy that cannot load
``python3XX.dll`` would exit before any window and leave the user with no
app at all (the re-exec parent has already quit by then).
"""
relocated = target.parent != src.parent
try:
dlls = _interpreter_runtime_dlls(src.parent) if relocated else []
newest_input = max(ico.stat().st_mtime, src.stat().st_mtime)
fresh = target.is_file() and target.stat().st_mtime >= newest_input
if fresh and relocated:
fresh = all((target.parent / d.name).is_file() for d in dlls)
if fresh:
return target
# Do not clobber a running copy (best-effort self-heal, not load-bearing).
base_exe = getattr(sys, "_base_executable", "") or ""
if target.is_file() and Path(base_exe).name.lower() == target.name.lower():
return target
import shutil
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, target)
for dll in dlls:
shutil.copy2(dll, target.parent / dll.name)
if not _replace_exe_icon(target, ico):
# A copy without the branded icon is pointless (still shows Python);
# remove it so the caller falls through to the next home / bare pythonw.
_unlink_quietly(target)
return None
# Smoke-start EVERY fresh copy, not just a relocated one. The in-venv
# copy is the Start-Menu shortcut's target, so a broken one would leave
# a Start-Menu entry that does nothing at all — worse than the generic
# pythonw target it replaces. Runs once per rebuild, never per launch.
if not _branded_copy_boots(target):
logger.debug("branded copy does not boot, discarding: {}", target)
_unlink_quietly(target)
return None
logger.debug("Branded launcher exe ready: {}", target)
return target
except PermissionError as exc:
logger.debug("branded home not writable ({}): {}", target.parent, exc)
return None
except Exception as exc: # noqa: BLE001
logger.debug("branded copy could not be built at {}: {}", target, exc)
# A pre-existing SAME-DIR copy is still trustworthy (e.g. the copy step
# failed because the file is held open by a running instance). A
# relocated leftover is not — its DLL set may be incomplete.
if not relocated and target.is_file():
return target
return None
def _unlink_quietly(path: Path) -> None:
try:
path.unlink()
except Exception: # noqa: BLE001 — best-effort cleanup
pass
def maybe_reexec_through_branded_launcher(argv: list[str]) -> int | None:
"""Re-exec the launcher through the mascot-branded exe; return an exit code.
The taskbar button icon is the launching exe's embedded icon, so a bare
``pythonw.exe`` start shows the Python logo regardless of every window-icon /
AUMID / shortcut effort. Relaunching the SAME launcher module through
``DodaiosApp.exe`` (a pythonw copy carrying the mascot icon) is the only
thing that brands the taskbar button — and it covers every entry point at one
chokepoint (``run.bat``, the Start-Menu/pinned shortcut, the autostart task,
the tray self-restart), because they all funnel through ``main()``.
Returns an exit code when it re-exec'd (the caller must return it and let this
process exit), or ``None`` to continue booting in-process (already branded,
non-Windows, a console/debug run, or branding unavailable — graceful
fallback: the app still runs, the taskbar just keeps the Python logo).
"""
if sys.platform != "win32":
return None
# Loop guard: the env marker (set on the re-exec child) is authoritative —
# under ``__PYVENV_LAUNCHER__`` ``sys.executable`` is the venv pythonw, so the
# real running image is ``sys._base_executable`` (our branded copy).
if os.environ.get(_BRANDED_LAUNCH_ENV) == "1":
return None
# Every name the branded exe has had: a copy under an earlier name (a
# pinned taskbar button or a shortcut of an earlier release starts it) is
# the branded app already, not a bare interpreter to brand.
branded_names = {
name.lower() for name in (BRANDED_LAUNCHER_EXE_NAME, *LEGACY_BRANDED_LAUNCHER_EXE_NAMES)
}
base_exe = getattr(sys, "_base_executable", "") or ""
if Path(base_exe).name.lower() in branded_names:
return None
# The in-venv branded copy IS the running image, yet `_base_executable`
# still names the interpreter behind it (a Store alias, say) — so the check
# above cannot see it and the app re-exec'd through the very exe that had
# just started it. Harmless (the child sets the env marker and stops) but a
# wasted process and boot delay on every Start-Menu launch, which is the
# normal way in once the shortcut targets this exe.
if Path(sys.executable).name.lower() in branded_names:
return None
# A visible-console/debug run wants python.exe's console; re-exec'ing through
# a windowless pythonw copy would swallow it. Leave those alone.
if os.environ.get("JARVIS_DEBUG") == "1":
return None
branded = ensure_branded_launcher_exe()
if branded is None:
return None
try:
import subprocess
env = dict(os.environ)
env[_BRANDED_LAUNCH_ENV] = "1"
# Re-attach THIS venv inside the base-python-copy branded exe, so it runs
# the app with the venv's packages while owning the window itself. This is
# exactly the mechanism a venv launcher uses to redirect into the venv.
venv_pythonw = Path(sys.executable).with_name("pythonw.exe")
if venv_pythonw.is_file():
env["__PYVENV_LAUNCHER__"] = str(venv_pythonw)
# DETACHED_PROCESS | CREATE_NO_WINDOW — same idiom as dodaios.ui.relauncher:
# cut the child loose from the parent's console/process group and keep
# pythonw from flashing a console. Redirect all three std streams to
# DEVNULL: DETACHED_PROCESS leaves them as INVALID handles otherwise, and
# a boot-time write to stdout/stderr then crashes the child before its
# window ever appears (observed: the re-exec'd app silently never came up
# until stdio was given valid handles). The app logs to its own file sink.
detached = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
child = subprocess.Popen( # noqa: S603 — fixed argv, no shell, our own exe
[str(branded), "-m", _LAUNCHER_MODULE, *argv],
env=env,
close_fds=True,
creationflags=detached | no_window,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# This process got the foreground right from the user's click; the
# child that does the real boot did not. Without it, the child cannot
# raise an instance that is already running (2026-10-06).
from dodaios.ui.foreground_grant import allow_foreground
allow_foreground(getattr(child, "pid", None))
logger.debug("Re-exec'd launcher through branded exe: {}", branded)
return 0
except Exception as exc: # noqa: BLE001
logger.debug("branded re-exec failed, continuing in-process: {}", exc)
return None
def _default_start_menu_programs_dir() -> Path | None:
appdata = os.environ.get("APPDATA")
if not appdata:
return None
return Path(appdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs"
def _launcher_arguments() -> str:
"""The ``Arguments`` field of every shortcut this module writes."""
return " ".join(("-m", _LAUNCHER_MODULE, *_LAUNCHER_ARGS))
def _same_file_path(actual: str, expected: Path) -> bool:
"""Whether two spellings name the same file, short (8.3) names included.
A shortcut stores the long path; ``sys.executable`` can carry a short one
(``ADMINI~1`` for ``Administrator``), and ``abspath`` keeps it short.
Compared as text they never matched, so every launch rewrote the shortcut.
"""
if not actual:
return False
return os.path.normcase(os.path.realpath(actual)) == os.path.normcase(
os.path.realpath(expected)
)
def _shortcut_matches_install(
lnk: Path,
*,
expected_target: Path,
expected_icon: Path,
expected_arguments: str,
) -> bool:
"""True only when a ``.lnk`` points at this exact live installation.
The taskbar renders an AUMID-grouped button from its Start-Menu shortcut's
icon; a dangling ``IconLocation`` (install moved/renamed) silently degrades
to the target's icon (``pythonw.exe`` -> Python logo). An empty
``IconLocation`` means "use the target's icon", which is exactly the Python
fallback, so that counts as NOT live.
Mere existence is not enough: an old Python installation can remain on disk
after Jarvis rebuilt its venv. The old check accepted that stale executable
forever, leaving Windows search with a launcher for the previous environment.
Compare target, icon, and arguments to the values this process would write.
Best-effort: any read failure returns ``False`` so the caller repairs it.
"""
if sys.platform != "win32":
return False
try:
from win32com.client import Dispatch
except Exception as exc: # noqa: BLE001
logger.debug("pywin32 unavailable; cannot verify shortcut paths: {}", exc)
return False
try:
sc = Dispatch("WScript.Shell").CreateShortcut(str(lnk))
# IconLocation is "<path>,<index>"; an empty path == inherit the target
# icon == the pythonw.exe fallback, so treat it as not-live.
icon_raw = (sc.IconLocation or "").rsplit(",", 1)[0].strip().strip('"')
target_raw = (sc.TargetPath or "").strip().strip('"')
return (
Path(icon_raw).is_file()
and Path(target_raw).is_file()
and _same_file_path(icon_raw, expected_icon)
and _same_file_path(target_raw, expected_target)
and (sc.Arguments or "").strip() == expected_arguments
)
except Exception as exc: # noqa: BLE001
logger.debug("could not read shortcut target/icon, treating as stale: {}", exc)
return False
def ensure_start_menu_shortcut(
*,
aumid: str = APP_USER_MODEL_ID,
display_name: str = WINDOWS_APP_DISPLAY_NAME,
icon_path: Path | None = None,
programs_dir: Path | None = None,
) -> bool:
"""Create/maintain the AUMID-tagged Start-Menu shortcut that NAMES the button.
This — not the HKCU ``DisplayName`` — is the mechanism Windows uses to label
a grouped taskbar button and its jump-list header: it matches the running
window's process AUMID (set by ``SetCurrentProcessExplicitAppUserModelID``)
to a Start-Menu shortcut carrying the same ``System.AppUserModel.ID`` and
shows that shortcut's **file name** ("Dodaios") and **icon**. A
shortcut-less ``pythonw`` app falls back to the process description
("Python") — the exact symptom the user reported. The shortcut only needs to
*exist* in the Start Menu; Windows resolves it regardless of how the app was
launched, and the resolution happens when the taskbar button is created, so
a *fresh* launch picks it up (an already-grouped button is not retroactively
renamed).
Idempotent (an existing shortcut carrying ``aumid`` and pointing at this
exact interpreter is left alone), Windows-only, best-effort - it never
raises and never blocks boot. Returns ``True`` only when a matching shortcut
is present afterwards.
A frozen build writes nothing: the shortcut it would create points at
``<interpreter> -m dodaios.ui.web.launcher``, a command a PyInstaller
executable cannot run, and the native installer already placed a working
one. The self-heal below would otherwise replace the installer's launcher
with a broken one on every boot.
"""
if sys.platform != "win32":
return False
if _installer_owns_shell_registration("Start-Menu shortcut"):
return False
programs = programs_dir or _default_start_menu_programs_dir()
if programs is None:
return False
try:
import pywintypes
from win32com.propsys import propsys, pscon
except Exception as exc: # noqa: BLE001
logger.debug("pywin32 unavailable; Start-Menu shortcut not ensured: {}", exc)
return False
pythonw = _shortcut_launch_target()
if pythonw is None:
return False
ico = icon_path or project_icon_path()
lnk = programs / START_MENU_SHORTCUT_NAME
iid = pywintypes.IID(_IID_IPROPERTYSTORE)
# Every check below asks the file system what is in the Start Menu. Under a
# Store Python those reads are answered from the package container first, so
# a copy trapped there by an older build would look like a healthy entry and
# this function would return True while the shell still sees nothing.
# Dropping the shadow first makes the reads report what the shell reports.
from dodaios.ui.msix_redirection import reveal_real_path
reveal_real_path(lnk)
if not _interpreter_may_own_the_launcher_shortcut():
# This interpreter cannot start the desktop app the way the user
# configured it, so it must not become the shortcut's target. Leave
# whatever is there — a working entry from the installer or from a real
# desktop run — strictly alone.
logger.debug(
"Start-Menu shortcut left untouched: {} cannot open the window or "
"cannot run the configured on-device recognizer, and would be a "
"degraded launch target",
pythonw,
)
return lnk.is_file()
# Idempotent BUT self-healing: leave an existing shortcut alone ONLY if it
# still carries this AUMID *and* its icon + target resolve to real files.
#
# A plain "AUMID matches -> return" check was a latent Python-logo bug: a
# shortcut written against an earlier install location (a moved/renamed repo,
# a throwaway ``.venv``) keeps a **dangling** ``IconLocation``. Windows then
# renders the whole AUMID-grouped taskbar button from the shortcut's target
# icon (``pythonw.exe`` -> the Python logo) even though the live window's
# class icon is the mascot — the button icon is resolved from the shortcut,
# not the window. Re-validating the paths repairs it on the next launch, so
# the fix reaches every machine whose install moved (why it "works on one
# machine, not another"). Verifying the target too keeps a fresh relaunch
# click pointed at a real interpreter.
if lnk.is_file():
try:
ro_store = propsys.SHGetPropertyStoreFromParsingName(
str(lnk), None, 0, iid # GPS_DEFAULT
)
existing = ro_store.GetValue(pscon.PKEY_AppUserModel_ID).GetValue()
if existing == aumid and _shortcut_matches_install(
lnk,
expected_target=pythonw,
expected_icon=ico,
expected_arguments=_launcher_arguments(),
):
return True
logger.debug("stale/broken Start-Menu shortcut, rewriting: {}", lnk)
except Exception as exc: # noqa: BLE001
logger.debug("could not read existing shortcut AUMID, rewriting: {}", exc)
if _write_branded_shortcut(lnk, target=pythonw, ico=ico, aumid=aumid,
display_name=display_name):
logger.debug("Start-Menu shortcut ensured: {}", lnk)
_retire_legacy_start_menu_shortcuts(programs, launch_target=pythonw)
return True
return False
def _retire_legacy_start_menu_shortcuts(programs: Path, *, launch_target: Path) -> None:
"""Drop a Start-Menu entry of the product's earlier name that starts this install.
Runs once the current entry exists, so the app is never left without one.
Best-effort: a failure leaves a second, working entry behind.
"""
try:
import dodaios
from dodaios.setup.desktop_integration import retire_legacy_windows_launchers
install_root = Path(dodaios.__file__).resolve().parent.parent
retire_legacy_windows_launchers(
(programs,), install_root=install_root, launch_target=launch_target
)
except Exception as exc: # noqa: BLE001 — cosmetic cleanup, never load-bearing
logger.debug("earlier Start-Menu shortcut not retired: {}", exc)
def _write_branded_shortcut(
lnk: Path, *, target: Path, ico: Path, aumid: str, display_name: str
) -> bool:
"""Write one AUMID-tagged .lnk pointing at ``target``. Never raises.
Shared by the Start-Menu and Desktop entries so the two can never drift into
different targets, icons or identities — which is exactly how a user ends up
with one working launcher and one dead one.
"""
try:
import pywintypes
from win32com.client import Dispatch
from win32com.propsys import propsys, pscon
lnk.parent.mkdir(parents=True, exist_ok=True)
shell = Dispatch("WScript.Shell")
sc = shell.CreateShortcut(str(lnk))
sc.TargetPath = str(target)
sc.Arguments = _launcher_arguments()
sc.WorkingDirectory = str(Path.home())
if ico.is_file():
sc.IconLocation = f"{ico},0"
sc.Description = display_name
sc.WindowStyle = 1
sc.Save()
# Embed the AUMID so Windows matches the running window to this shortcut.
rw_store = propsys.SHGetPropertyStoreFromParsingName(
str(lnk), None, 2, pywintypes.IID(_IID_IPROPERTYSTORE) # GPS_READWRITE
)
rw_store.SetValue(pscon.PKEY_AppUserModel_ID, propsys.PROPVARIANTType(aumid))
rw_store.Commit()
# Under a Microsoft-Store Python every write above was diverted into the
# package's private container, so the shortcut we just "saved into the
# Start Menu" is invisible to the shell. Publishing it out is what makes
# the entry real; a failure here means the app is NOT installed as far as
# Windows is concerned, so it must not be reported as a success.
from dodaios.ui.msix_redirection import publish_out_of_container
if not publish_out_of_container(lnk):
logger.debug("shortcut stayed trapped in the MSIX container: {}", lnk)
return False
_notify_shell_of_shortcut(lnk)
return True
except Exception as exc: # noqa: BLE001
logger.debug("shortcut could not be written at {}: {}", lnk, exc)
return False
def _default_desktop_dir() -> Path | None:
profile = os.environ.get("USERPROFILE")
return Path(profile) / "Desktop" if profile else None
def ensure_desktop_shortcut(
*,
aumid: str = APP_USER_MODEL_ID,
display_name: str = WINDOWS_APP_DISPLAY_NAME,
icon_path: Path | None = None,
desktop_dir: Path | None = None,
create_if_missing: bool = True,
) -> bool:
"""Install/repair the Desktop launcher — the entry Windows Search can see.
The Start-Menu entry alone is not enough on a real machine. Windows excludes
``%LOCALAPPDATA%``/``%APPDATA%`` from the content index by default, and the
per-user Start Menu lives inside ``%APPDATA%`` — so on a box whose index
lacks the Start-Menu exception rule, NOTHING there is searchable and typing
the app's name finds nothing at all. The Desktop is indexed, which is why
Discord and Obsidian were still findable on the machine that reported this
(forensic 2026-08-16: their Desktop .lnk files were in the index; the
Start-Menu folder had zero entries).
So this is not decoration — for that user it is the only working search
entry, and the icon they expected to see. Everything else (target, icon,
AUMID) is identical to the Start-Menu entry via ``_write_branded_shortcut``.
``create_if_missing=False`` repairs an existing shortcut but never
resurrects a deleted one — a user who threw the icon away keeps their empty
desktop. The installer passes ``True``; incidental callers should not.
A frozen build writes nothing — see :func:`ensure_start_menu_shortcut`; the
native installer owns the Desktop icon too, including the user's choice not
to have one.
"""
if sys.platform != "win32":
return False
if _installer_owns_shell_registration("Desktop shortcut"):
return False
desktop = desktop_dir or _default_desktop_dir()
if desktop is None or not desktop.is_dir():
return False
target = _shortcut_launch_target()
if target is None:
return False
ico = icon_path or project_icon_path()
lnk = desktop / START_MENU_SHORTCUT_NAME
# Normally a no-op — the Desktop is not one of the redirected roots — but a
# profile that relocates it under %LOCALAPPDATA% would hit the same trap as
# the Start Menu, and the check costs a path comparison.
from dodaios.ui.msix_redirection import reveal_real_path
reveal_real_path(lnk)
if not lnk.is_file() and not create_if_missing:
return False
if not _interpreter_may_own_the_launcher_shortcut():
# Same rule as the Start-Menu entry: never aim it at an interpreter that
# can do less than the one it would replace.
return lnk.is_file()
if lnk.is_file() and _shortcut_matches_install(
lnk,
expected_target=target,
expected_icon=ico,
expected_arguments=f"-m {_LAUNCHER_MODULE}",
):
return True
if _write_branded_shortcut(
lnk, target=target, ico=ico, aumid=aumid, display_name=display_name
):
logger.debug("Desktop shortcut ensured: {}", lnk)
return True
return False
def _default_taskbar_pins_dir() -> Path | None:
appdata = os.environ.get("APPDATA")
if not appdata:
return None
return (
Path(appdata)
/ "Microsoft"
/ "Internet Explorer"
/ "Quick Launch"
/ "User Pinned"
/ "TaskBar"
)
def _read_shortcut_aumid(lnk: Path) -> str | None:
try:
import pywintypes
from win32com.propsys import propsys, pscon
store = propsys.SHGetPropertyStoreFromParsingName(
str(lnk), None, 0, pywintypes.IID(_IID_IPROPERTYSTORE) # GPS_DEFAULT
)
value = store.GetValue(pscon.PKEY_AppUserModel_ID).GetValue()
return value if isinstance(value, str) else None
except Exception as exc: # noqa: BLE001
logger.debug("could not read AUMID of {}: {}", lnk, exc)
return None
def repair_taskbar_pins(
*,
aumid: str = APP_USER_MODEL_ID,
display_name: str = WINDOWS_APP_DISPLAY_NAME,
icon_path: Path | None = None,
pins_dir: Path | None = None,
) -> int:
"""Re-aim taskbar pins of this app that point at an old install.
A pinned taskbar button is its own ``.lnk`` in the "User Pinned" folder,
written when the user pinned the app. Nothing ever updated it, so after a
rename or move (``jarvis`` -> ``dodaios``) the pin kept the old icon path and
launcher module. The shell then draws a blank page for the button and a click
starts nothing.
Only pins that carry this app's AUMID are touched, and each is rewritten in
place under its own file name so the pin itself survives. Never creates a
pin. Returns how many pins were rewritten.
"""
if sys.platform != "win32":
return 0
if _installer_owns_shell_registration("taskbar pin"):
return 0
pins = pins_dir or _default_taskbar_pins_dir()
if pins is None or not pins.is_dir():
return 0
if not _interpreter_may_own_the_launcher_shortcut():
return 0
target = _shortcut_launch_target()
if target is None:
return 0
ico = icon_path or project_icon_path()
repaired = 0
for lnk in sorted(pins.glob("*.lnk")):
if _read_shortcut_aumid(lnk) != aumid:
continue
if _shortcut_matches_install(
lnk,
expected_target=target,
expected_icon=ico,
expected_arguments=_launcher_arguments(),
):
continue
if _write_branded_shortcut(
lnk, target=target, ico=ico, aumid=aumid, display_name=display_name
):
logger.info("taskbar pin re-aimed at this install: {}", lnk)
repaired += 1
return repaired
def _notify_shell_of_shortcut(lnk: Path) -> None:
"""Tell the shell the Start-Menu entry changed, so app search can pick it up.
Writing the .lnk is only half the job. Windows answers Start-menu searches
from its own app index (``shell:AppsFolder``), not by reading the folder, and
that index is refreshed from shell change notifications. We finish the file
with an ``IPropertyStore`` commit *after* ``Save()`` — a plain write the
shell is never told about — so nothing announces the final version.
``SHChangeNotify`` is the documented announcement: the item itself, then its
directory. Best-effort by design; it only ever makes the entry appear
SOONER. A machine whose app index has stopped accepting new entries
altogether is a shell-side fault this cannot repair (verified 2026-08-16:
on such a machine a plain ``notepad.exe`` shortcut is refused just the same)
— there the fix is restarting Explorer or signing back in.
"""
if sys.platform != "win32":
return
try:
import ctypes
SHCNE_CREATE, SHCNE_UPDATEDIR, SHCNF_PATHW = 0x0002, 0x1000, 0x0005
shell32 = ctypes.windll.shell32
shell32.SHChangeNotify(
SHCNE_CREATE, SHCNF_PATHW, ctypes.c_wchar_p(str(lnk)), None
)
shell32.SHChangeNotify(
SHCNE_UPDATEDIR, SHCNF_PATHW, ctypes.c_wchar_p(str(lnk.parent)), None
)
except Exception as exc: # noqa: BLE001 — a nicety, never load-bearing
logger.debug("shell change notification skipped: {}", exc)
def ensure_windows_app_identity(
app_id: str = APP_USER_MODEL_ID, *, write_shortcut: bool = True
) -> bool:
"""Pin a stable Windows app identity for taskbar grouping AND name.
Three layers, each a different shell surface:
1. ``SetCurrentProcessExplicitAppUserModelID`` — groups every Jarvis
window under one taskbar button (the grouping *key*) instead of under
"Python".
2. ``ensure_start_menu_shortcut`` — the AUMID-tagged Start-Menu shortcut
that gives that key a *name* + icon, so the button/jump-list header
read "Dodaios" instead of the ``pythonw.exe`` description. This
is the layer that actually fixed the "taskbar says Python" report;
layer 1 alone leaves the button nameless.
3. ``register_windows_app_user_model_id`` — HKCU ``DisplayName`` for the
*toast-notification* identity (a separate surface from the taskbar).
Must run before the first window is created (idempotent across the desktop,
orb and overlay processes, which all call this early). The return value
reflects only step 1; steps 2 and 3 are best-effort side effects.
``write_shortcut=False`` keeps layers 1 and 3 and skips layer 2. Callers on
an import path use it: importing ``dodaios.ui.desktop_app`` (which a headless
boot, a CLI command and the test suite all do) must not rewrite the user's
Start-Menu entry, because at import time nothing yet says this process will
ever show a window. Only a run that really opens one may claim the entry.
"""
if sys.platform != "win32":
return False
ico = project_icon_path()
ico_arg = ico if ico.is_file() else None
# Name the taskbar button (shortcut) + the toast identity (registry). Both
# best-effort and must be in place before the AUMID is set + the window
# appears, so Explorer resolves them on first button creation.
if write_shortcut:
ensure_start_menu_shortcut(aumid=app_id, icon_path=ico_arg)
repair_taskbar_pins(aumid=app_id, icon_path=ico_arg)
register_windows_app_user_model_id(app_id, icon_path=ico_arg)
try:
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)
return True
except Exception as exc: # noqa: BLE001
logger.debug("AppUserModelID could not be set: {}", exc)
return False
# System.AppUserModel.* property keys (fmtid + pid) for the per-WINDOW property
# store. ``RelaunchIconResource`` is THE documented mechanism for an app hosted
# by a shared interpreter exe (pythonw) to give its taskbar button its own icon.
_APPUSERMODEL_FMTID = "{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}"
_PID_RELAUNCH_COMMAND = 2
_PID_RELAUNCH_ICON = 3
_PID_RELAUNCH_NAME = 4
_PID_AUMID = 5
# HWNDs already stamped with relaunch properties this session — the icon-setter
# thread re-polls every 300 ms and the COM property-store dance is not free.
_RELAUNCH_STAMPED: set[int] = set()
def set_window_relaunch_properties(
hwnd: int,
*,
ico_path: Path | None = None,
aumid: str = APP_USER_MODEL_ID,
display_name: str = WINDOWS_APP_DISPLAY_NAME,
) -> bool:
"""Stamp per-window AppUserModel Relaunch* properties → taskbar shows OUR icon.
THE universal taskbar-icon fix, and the one that finally covers every install
(verified live on an MS-Store-Python machine, where exe branding is
impossible): without explicit window properties, the Windows taskbar renders
a button with the icon of the window-owning EXECUTABLE — for a source run
that is ``pythonw.exe`` → the Python logo, no matter what ``WM_SETICON`` /
class icon / AUMID / Start-Menu shortcut say (all verified ineffective on the
button). ``SHGetPropertyStoreForWindow`` +
``System.AppUserModel.RelaunchIconResource`` exists precisely for
interpreter-hosted apps: it tells the shell, per window, which icon (and
name/relaunch command, used when the button is pinned) the button carries.
Takes effect immediately on a live window — no restart, no exe copy.
Idempotent per HWND (session-cached), Windows-only, best-effort: any COM /
pywin32 hiccup returns ``False`` and the window keeps whatever the other
layers achieved. Returns ``True`` when the properties were committed.
"""
if sys.platform != "win32" or not hwnd:
return False
if hwnd in _RELAUNCH_STAMPED:
return True
try:
import pywintypes
from win32com.propsys import propsys
try:
# The icon-setter poll runs on a plain daemon thread with no COM
# apartment; initialize one (idempotent, "already init" is fine).
import pythoncom
pythoncom.CoInitialize()
except Exception: # noqa: BLE001 — already initialized / free-threaded
pass
ico = ico_path or project_icon_path()
fmtid = pywintypes.IID(_APPUSERMODEL_FMTID)
store = propsys.SHGetPropertyStoreForWindow(
hwnd, propsys.IID_IPropertyStore
)
store.SetValue((fmtid, _PID_AUMID), propsys.PROPVARIANTType(aumid))
if ico.is_file():
store.SetValue(
(fmtid, _PID_RELAUNCH_ICON), propsys.PROPVARIANTType(f"{ico},0")
)
store.SetValue(
(fmtid, _PID_RELAUNCH_NAME), propsys.PROPVARIANTType(display_name)
)
# Same target as the Start-Menu shortcut. Pointing this at pythonw.exe
# made the Start recently-used list / a taskbar re-click a generic-host
# launch: Windows either refuses it or pythonw dies with nowhere to print.
target = _shortcut_launch_target()
if target is not None:
store.SetValue(
(fmtid, _PID_RELAUNCH_COMMAND),
propsys.PROPVARIANTType(f'"{target}" -m {_LAUNCHER_MODULE}'),
)
store.Commit()
_RELAUNCH_STAMPED.add(hwnd)
logger.debug("Relaunch properties stamped on hwnd={}", hwnd)
return True
except Exception as exc: # noqa: BLE001 — cosmetic layer, never load-bearing
logger.debug("relaunch properties could not be stamped: {}", exc)
return False
def _apply_icon_to_hwnd(hwnd: int, ico_path: Path) -> bool:
"""Set window + class icon on a known HWND. Returns True on success."""
if sys.platform != "win32":
return False
if not hwnd:
return False
if not ico_path.is_file():
logger.warning("Icon file missing: {}", ico_path)
return False
# Per-window relaunch properties FIRST — the only layer the taskbar button
# honours on every install (incl. MS-Store Python, where the branded-exe
# re-exec cannot run). The class/WM_SETICON work below still covers the
# titlebar + Alt-Tab surfaces.
set_window_relaunch_properties(hwnd, ico_path=ico_path)
try:
import ctypes
from ctypes import wintypes
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("ctypes not available")
return False
# A private WinDLL instance, not ctypes.windll.user32: mutating
# argtypes on the shared object corrupts every other caller in the
# process (e.g. pywebview's winforms SetWindowPos calls).
user32 = ctypes.WinDLL("user32", use_last_error=True)
user32.LoadImageW.restype = wintypes.HANDLE
user32.SendMessageW.restype = ctypes.c_long
# On 64-bit Windows SetClassLongPtrW is the correct variant.
user32.SetClassLongPtrW.argtypes = [
wintypes.HWND, ctypes.c_int, ctypes.c_void_p,
]
user32.SetClassLongPtrW.restype = ctypes.c_void_p
path_str = str(ico_path)
hicon_big = user32.LoadImageW(
None, path_str, _IMAGE_ICON, 32, 32, _LR_LOADFROMFILE | _LR_DEFAULTSIZE
)
hicon_small = user32.LoadImageW(
None, path_str, _IMAGE_ICON, 16, 16, _LR_LOADFROMFILE | _LR_DEFAULTSIZE
)
if not hicon_big or not hicon_small:
logger.warning("LoadImageW failed for {}", path_str)
return False
# WM_SETICON: titlebar + Alt-Tab switcher.
user32.SendMessageW(hwnd, _WM_SETICON, _ICON_BIG, hicon_big)
user32.SendMessageW(hwnd, _WM_SETICON, _ICON_SMALL, hicon_small)
# Class icon: drives the taskbar group. Without it Windows falls back to
# the process icon (pythonw.exe → Python logo). Each Tk/pywebview/Qt
# window registers its own class, so we only affect Jarvis windows.
user32.SetClassLongPtrW(hwnd, _GCLP_HICON, hicon_big)
user32.SetClassLongPtrW(hwnd, _GCLP_HICONSM, hicon_small)
logger.debug("Icon set (window+class): hwnd={} path={}", hwnd, path_str)
return True
def set_window_icon_by_hwnd(hwnd: int, ico_path: Path) -> bool:
"""Set taskbar + titlebar icon for a window whose HWND is already known.
Used by Tkinter (``root.winfo_id()``) and Qt (``window.winId()``) where
the toolkit hands us the HWND directly — no need to scan windows by title.
"""
return _apply_icon_to_hwnd(hwnd, ico_path)
def apply_tk_window_icon(root: Any) -> None:
"""Give a Tkinter root/Toplevel the Jarvis mascot icon on **every** OS.
Tkinter registers its window class *without* a class-icon slot, so a
``python -m …`` launch leaves every Tk window inheriting the interpreter's
process icon: on Windows the taskbar/titlebar falls back to
``pythonw.exe`` → the blue/yellow Python logo, on Linux to the generic
``python3`` interpreter icon. Both are the same "shows Python, not Jarvis"
symptom (BUG #UI-Pin-2026-05-05). Any Tk surface — the JarvisBar, the orb,
any future Tk dialog — must call this once, right after creating its root,
or it will visibly regress to the Python logo.
Two OS-specific paths, because the toolkits read different surfaces:
**Windows** — the taskbar renders the window *class* icon, and the
highest-fidelity source is the multi-resolution ``dodaios.ico``:
1. ``ensure_windows_app_identity`` — group this process under the Jarvis
taskbar button (idempotent across processes).
2. ``iconbitmap(default=.ico)`` — Tk-level icon for all toplevels.
3. ``WM_SETICON`` + ``SetClassLongPtrW`` — the Win32 class-icon override,
the only surface the taskbar actually reads.
``iconphoto`` (the PNG path) is deliberately NOT used on Windows: Tk
re-asserts a ``PhotoImage``-derived class icon on later map/update cycles,
which races and overwrites our ``SetClassLongPtrW`` — the live window ended
up with a blank/greyed class icon. The ``.ico`` + Win32 path is the proven
one (BUG #UI-Pin-2026-05-05).
**Linux / macOS** — Tk exposes no class-icon slot to Win32, but its portable
``root.iconphoto`` sets ``_NET_WM_ICON``, which is exactly what the
dock/taskbar reads. It needs a PNG (most Linux desktops and Tk cannot decode
a Windows ``.ico``). The ``PhotoImage`` is stashed on the root because Tk
keeps no reference — without it Python garbage-collects the image and the
icon silently reverts to the generic ``python3`` interpreter icon.
Every step is wrapped: the bar/orb are cosmetic and must never crash — or
block their Tk mainloop — on an icon hiccup. Must run on the Tk thread that
owns ``root`` (``winfo_id`` / ``PhotoImage`` are thread-affine).
"""
if sys.platform == "win32":
ensure_windows_app_identity()
ico_path = project_icon_path()
if not ico_path.is_file():
return
try:
root.iconbitmap(default=str(ico_path))
except Exception as exc: # noqa: BLE001
logger.debug("Tk iconbitmap could not be applied: {}", exc)
try:
hwnd = int(root.winfo_id())
except Exception as exc: # noqa: BLE001
logger.debug("Tk winfo_id() unavailable; class icon not set: {}", exc)
return
set_window_icon_by_hwnd(hwnd, ico_path)
return
# Linux / macOS — portable Tk icon via the PNG (_NET_WM_ICON).
try:
from dodaios.assets import bundled_app_icon_png
png = bundled_app_icon_png()
except Exception as exc: # noqa: BLE001
logger.debug("bundled PNG icon lookup failed: {}", exc)
png = None
if png is None or not png.is_file():
return
try:
import tkinter as tk
photo = tk.PhotoImage(file=str(png), master=root)
root.iconphoto(True, photo)
# Tk holds no reference to the image; pin it to the root so it is not
# garbage-collected out from under the window icon.
root._jarvis_icon_photo = photo # noqa: SLF001
except Exception as exc: # noqa: BLE001
logger.debug("Tk iconphoto could not be applied: {}", exc)
def set_window_icon_by_title(
title: str,
ico_path: Path,
*,
quiet: bool = False,
expected_pid: int | None = None,
) -> bool:
"""Set the icon only when the titled window belongs to ``expected_pid``.
Needed because pywebview doesn't stably expose the HWND. ``FindWindowW``
against the title is a pragmatic way — the Jarvis window title is
constant (the product name). The title is not globally unique, though: a
terminal opened in the repository commonly has the same title. Never stamp
a title match until its owning PID is verified, or the terminal receives
Jarvis's AUMID/relaunch metadata and gets grouped with the desktop app.
Args:
title: Window title exactly as set by pywebview.
ico_path: Path to the ``.ico`` file.
quiet: If True, "hwnd not found" notices are logged at debug
instead of warning. For polling loops where the window is
expected to appear only after a few iterations.
expected_pid: Required owner of the matched window. Defaults to the
current process.
Returns:
True if both icons could be set.
"""
if sys.platform != "win32":
return False
if not ico_path.is_file():
logger.warning("Icon file missing: {}", ico_path)
return False
try:
import ctypes
from ctypes import wintypes
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("ctypes not available")
return False
# A private WinDLL instance, not ctypes.windll.user32: mutating
# argtypes on the shared object corrupts every other caller in the
# process (e.g. pywebview's winforms SetWindowPos calls).
user32 = ctypes.WinDLL("user32", use_last_error=True)
user32.FindWindowW.restype = wintypes.HWND
user32.GetWindowThreadProcessId.argtypes = [
wintypes.HWND,
ctypes.POINTER(wintypes.DWORD),
]
hwnd = user32.FindWindowW(None, title)
if not hwnd:
if quiet:
logger.debug("Window '{}' not found (yet)", title)
else:
logger.warning("Window '{}' not found — icon not set", title)
return False
owner_pid = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner_pid))
wanted_pid = os.getpid() if expected_pid is None else expected_pid
if owner_pid.value != wanted_pid:
logger.debug(
"Window '{}' belongs to pid={}, not pid={}; icon not set",
title,
owner_pid.value,
wanted_pid,
)
return False
return _apply_icon_to_hwnd(int(hwnd), ico_path)
def set_window_icon_for_pid(pid: int, ico_path: Path) -> bool:
"""Set the icon on the largest visible top-level window owned by ``pid``.
A title-independent companion to :func:`set_window_icon_by_title`. pywebview's
WebView2 host window does not reliably carry ``WINDOW_TITLE`` at the moment the
icon-setter polls (the title is applied late, and ``FindWindowW`` only matches
an *exact* title), so we also locate the window by *our own* process id and pick
its biggest top-level window. Returns True when an icon was applied.
"""
if sys.platform != "win32":
return False
if not ico_path.is_file():
return False
try:
import ctypes
from ctypes import wintypes
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("ctypes not available")
return False
# A private WinDLL instance, not ctypes.windll.user32: mutating
# argtypes on the shared object corrupts every other caller in the
# process (e.g. pywebview's winforms SetWindowPos calls).
user32 = ctypes.WinDLL("user32", use_last_error=True)
user32.GetWindowThreadProcessId.argtypes = [
wintypes.HWND, ctypes.POINTER(wintypes.DWORD)
]
user32.IsWindowVisible.argtypes = [wintypes.HWND]
best = [0, 0] # [hwnd, area]
EnumProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
def _cb(hwnd, _lparam): # noqa: ANN001
wp = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(wp))
if wp.value == pid and user32.IsWindowVisible(hwnd):
rect = wintypes.RECT()
user32.GetWindowRect(hwnd, ctypes.byref(rect))
area = (rect.right - rect.left) * (rect.bottom - rect.top)
if area > best[1]:
best[0], best[1] = int(hwnd), area
return True
user32.EnumWindows(EnumProc(_cb), 0)
if not best[0]:
return False
return _apply_icon_to_hwnd(best[0], ico_path)
# The Linux window-class token the XDG ``.desktop`` pins via ``StartupWMClass``
# (dodaios/autostart/linux.py). Keep the two in lock-step: the desktop maps a
# running window to its launcher entry — and thus shows the entry's ``Icon=`` on
# the taskbar/dock — only when the window's WM_CLASS matches ``StartupWMClass``.
def pin_linux_wm_class(name: str = LINUX_WM_CLASS) -> bool:
"""Pin the X11/Wayland window-class of subsequently-created windows.
Must run BEFORE the GUI toolkit creates its first window. Without it, a
``python3 -m …`` launch leaves the window's WM_CLASS as ``python3`` — so the
Linux taskbar/dock shows the generic interpreter icon even when the
``.desktop`` entry carries the Jarvis ``Icon=`` (they only bind when the
WM_CLASS matches ``StartupWMClass``). Sets GLib's program name, which GTK
(pywebview's default Linux backend) uses to derive WM_CLASS.
No-op on non-Linux and best-effort on Linux (a Qt backend or missing PyGObject
derives its class differently): never raises, so it can never block the
window. Returns ``True`` only when the program name was set.
"""
if sys.platform != "linux":
return False
try:
from gi.repository import GLib # type: ignore[import-not-found]
GLib.set_prgname(name)
return True
except Exception as exc: # noqa: BLE001 — WM-class pin is a nicety, never load-bearing
logger.debug("Linux WM_CLASS could not be pinned: {}", exc)
return False
# The applications-menu .desktop entry (the Linux analog of the AUMID-tagged
# Start-Menu shortcut on Windows): desktop shells map a running window to a
# launcher entry — and render THAT entry's ``Icon=`` on the dock/taskbar — by
# matching the window's WM_CLASS against ``StartupWMClass`` in
# ``$XDG_DATA_HOME/applications``. The autostart entry under
# ``~/.config/autostart`` is a different surface (login launch only) and is
# NOT consulted for icon binding or app search.
def _default_linux_applications_dir() -> Path:
xdg = os.environ.get("XDG_DATA_HOME", "").strip()
base = Path(xdg) if xdg else Path.home() / ".local" / "share"
return base / "applications"
def _refresh_linux_desktop_database(applications_dir: Path) -> bool:
"""Tell the desktop shell a new application entry exists.
Writing the ``.desktop`` file is only half the job, exactly as on Windows:
GNOME, KDE and friends answer app searches from ``mimeinfo.cache`` /
``desktop.<arch>.cache`` built by ``update-desktop-database``, not by reading
the folder on every keystroke. Without this call the entry typically appears
only after the next login — the Linux twin of the Windows Start-Menu index
problem, and the reason a fresh install "isn't in the search" while the file
is demonstrably on disk.
Best-effort by design: ``update-desktop-database`` ships with
``desktop-file-utils``, which is not installed everywhere, and several
desktops watch the directory with inotify and need no prompting at all. A
missing tool therefore degrades to "appears after the next login", never to
an error. Returns ``True`` only when the database was actually rebuilt.
"""
if sys.platform != "linux":
return False
import shutil
tool = shutil.which("update-desktop-database")
if tool is None:
logger.debug(
"update-desktop-database not installed; the menu entry appears "
"once the desktop rescans (usually at next login)"
)
return False
try:
import subprocess
result = subprocess.run( # noqa: S603 — resolved absolute path, no shell
[tool, str(applications_dir)],
timeout=30,
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
logger.debug(
"update-desktop-database failed (rc={}): {}",
result.returncode,
(result.stderr or "").strip()[:300],
)
return False
logger.debug("desktop database refreshed for {}", applications_dir)
return True
except Exception as exc: # noqa: BLE001 — never block the window on a menu refresh
logger.debug("desktop database could not be refreshed: {}", exc)
return False
def _retire_legacy_linux_desktop_entries(applications_dir: Path, install_dir: Path) -> None:
"""Remove the earlier-named menu entries that start this install. Never raises."""
try:
from dodaios.autostart.linux import remove_entries_of_install
remove_entries_of_install(
[applications_dir / name for name in LEGACY_LINUX_DESKTOP_ENTRY_NAMES],
str(install_dir),
)
except Exception as exc: # noqa: BLE001 — a leftover entry is cosmetic, never load-bearing
logger.debug("earlier Linux menu entries not retired: {}", exc)
def ensure_linux_desktop_entry(applications_dir: Path | None = None) -> bool:
"""Install/refresh the applications-menu ``.desktop`` entry (Linux only).
This is what makes (a) "Dodaios" findable in the desktop's app
search/menu and (b) the dock/taskbar show the Jarvis icon for the RUNNING
window: ``pin_linux_wm_class`` pins the window's WM_CLASS, and this entry's
``StartupWMClass`` is the other half of that handshake. Without it the dock
falls back to the generic python3 interpreter icon — the Linux twin of the
Windows "taskbar shows Python" symptom.
Pure ``pathlib`` text I/O, idempotent (rewritten only when the rendered
content changed), best-effort — never raises, never blocks the window.
``applications_dir`` is a test seam; without it, non-Linux is a no-op.
An entry an earlier release wrote under the earlier file name
(``personal-jarvis.desktop``) is removed once the current one is in place,
but only when it starts this install: left behind, the menu would list the
app twice, and its ``StartupWMClass`` no longer matches the window.
A frozen build writes nothing. Inside an AppImage ``sys.executable`` points
into a temporary mount that is gone the moment the app exits, so the entry
would launch nothing at all; the AppImage's own ``.desktop`` (built by
``packaging/linux/build.sh``) and the Debian package are what register the
app there.
"""
if _installer_owns_shell_registration("Linux application-menu entry"):
return False
if applications_dir is None:
if sys.platform != "linux":
return False
applications_dir = _default_linux_applications_dir()
try:
from dodaios.assets import bundled_app_icon_png
from dodaios.core.config import PROJECT_ROOT
from dodaios.core.desktop_entry import escape_value, exec_value
png = bundled_app_icon_png()
icon_line = (
f"Icon={escape_value(str(png))}\n"
if png is not None and png.is_file()
else ""
)
# Both nested Desktop-Entry escaping layers, shared with the autostart
# writer: an install path containing a ``%`` is otherwise read as a field
# code and the desktop discards the whole entry — which takes the dock
# icon down with it, since StartupWMClass binding lives in THIS file.
content = (
"[Desktop Entry]\n"
"Type=Application\n"
f"Name={escape_value(APP_DISPLAY_NAME)}\n"
"Comment=Turn your computer into an AI agent\n"
f"Exec={exec_value(sys.executable, ('-m', _LAUNCHER_MODULE, *_LAUNCHER_ARGS))}\n"
f"Path={escape_value(str(PROJECT_ROOT))}\n"
"Terminal=false\n"
f"{icon_line}"
f"StartupWMClass={escape_value(LINUX_WM_CLASS)}\n"
"Categories=Utility;\n"
# The app search matches Name, and only some shells also match
# Comment. A user typing the name they remember from earlier
# releases ("jarvis"), or what the assistant is FOR, needs these
# to be hit at all. Same role as the Windows Start-Menu file name
# being the searchable token.
"Keywords=jarvis;assistant;voice;agent;automation;\n"
)
entry = applications_dir / LINUX_DESKTOP_ENTRY_NAME
try:
if entry.read_text(encoding="utf-8") == content:
# Content is current, but the menu database may still not know
# the entry — an interrupted earlier run could have written the
# file and never registered it. Re-announcing is cheap and
# idempotent, so a repaired install never needs a re-login.
_retire_legacy_linux_desktop_entries(applications_dir, PROJECT_ROOT)
_refresh_linux_desktop_database(applications_dir)
return True
except OSError:
# No readable entry yet (first install, or an unreadable leftover):
# that is the normal path into the write below, not a fault.
pass
applications_dir.mkdir(parents=True, exist_ok=True)
# Atomic-ish (same idiom as the autostart entry): never leave a
# half-written .desktop the desktop environment would choke on.
tmp = entry.with_name(entry.name + ".tmp")
tmp.write_text(content, encoding="utf-8")
tmp.replace(entry)
try:
# Some shells refuse to offer an entry that is not user-executable.
entry.chmod(0o755)
except OSError as exc:
logger.debug("could not mark {} executable: {}", entry, exc)
_retire_legacy_linux_desktop_entries(applications_dir, PROJECT_ROOT)
_refresh_linux_desktop_database(applications_dir)
logger.debug("Linux applications .desktop entry written: {}", entry)
return True
except Exception as exc: # noqa: BLE001 — menu entry is a nicety, never load-bearing
logger.debug("Linux applications .desktop entry not written: {}", exc)
return False
def apply_macos_dock_icon() -> bool:
"""Give the running app the Jarvis mascot in the macOS Dock.
A ``python -m …`` launch on macOS shows the Python rocket in the Dock —
the process is the interpreter, and only a packaged ``.app`` bundle carries
its own ``CFBundleIconFile``. For source/pip runs the supported override is
``NSApplication.setApplicationIconImage_``, set at runtime before the first
window (pywebview's Cocoa backend uses the same shared NSApplication, so
the icon sticks). Uses the bundled PNG; AppKit (pyobjc, a pywebview macOS
dependency) is probed as a capability, so this is a quiet no-op on any
machine without it. Must run on the main thread. Never raises.
"""
if sys.platform != "darwin":
return False
try:
from AppKit import NSApplication, NSImage # type: ignore[import-not-found]
except Exception as exc: # noqa: BLE001 — no pyobjc → unbranded Dock, never a crash
logger.debug("AppKit unavailable; Dock icon not set: {}", exc)
return False
try:
from dodaios.assets import bundled_app_icon_png
png = bundled_app_icon_png()
if png is None or not png.is_file():
return False
image = NSImage.alloc().initWithContentsOfFile_(str(png))
if image is None:
return False
NSApplication.sharedApplication().setApplicationIconImage_(image)
return True
except Exception as exc: # noqa: BLE001 — Dock icon is a nicety, never load-bearing
logger.debug("macOS Dock icon could not be applied: {}", exc)
return False
def load_ico_as_pil_image(ico_path: Path, size: int = 64) -> Any | None:
"""Loads a ``.ico`` as a ``PIL.Image`` for the pystray tray icon.
pystray needs an Image object, not a file reference. We load the
largest available representation and scale it to ``size``.
"""
if not ico_path.is_file():
return None
try:
from PIL import Image
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("Pillow not available")
return None
try:
img = Image.open(ico_path)
# .ico typically contains multiple sizes — Pillow picks the first,
# we force a clean target size via resize.
if img.mode != "RGBA":
img = img.convert("RGBA")
if img.size != (size, size):
img = img.resize((size, size), Image.LANCZOS)
return img
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("ICO load failed: {}", ico_path)
return None
def project_icon_path() -> Path:
"""Resolve the desktop/taskbar icon (``dodaios.ico``), install-layout agnostic.
Every Win32 icon surface (window class icon, AUMID icon, Start-Menu shortcut,
taskbar name, tray) resolves the icon through this one function — so if it
returns a non-existent path, ALL of them silently fall back to the
``pythonw.exe`` Python logo. That is exactly the "taskbar shows Python on a
fresh machine" symptom: the icon historically lived only at
``<repo-root>/assets/icons/dodaios.ico`` (``parents[2]``), which resolves only
for a run *from the project folder*; a real ``pip install`` relocates the
package to ``site-packages`` where that repo-root ``assets/`` is absent.
Resolution order (first existing wins):
1. the **bundled** in-package copy ``dodaios/assets/icons/dodaios.ico`` — ships
with the code via ``package-data``, so it is present on every install;
2. the legacy ``<repo-root>/assets/icons/dodaios.ico`` — the dev/editable and
build-tool copy (PyInstaller spec, ``install_shortcuts.py``).
Falls back to the bundled path (even if missing) so callers get a stable,
descriptive path in log warnings.
"""
try:
from dodaios.assets import bundled_app_icon
bundled = bundled_app_icon()
if bundled is not None:
return bundled
except Exception as exc: # noqa: BLE001 — never let icon resolution crash boot
logger.debug("bundled_app_icon lookup failed, trying repo-root: {}", exc)
icon_name = _INSTANCE.icon_file_name
repo_icons = Path(__file__).resolve().parents[2] / "assets" / "icons"
for candidate in (repo_icons / icon_name, repo_icons / "dodaios.ico"):
if candidate.is_file():
return candidate
# Nothing found — return the bundled location for a descriptive warning.
return Path(__file__).resolve().parent.parent / "assets" / "icons" / icon_name