Skip to content

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.

15.1 KB
Raw Blame
"""Which *instance* of the desktop app this process is.

One checkout can run two desktop apps side by side: the **default** instance —
the one that owns the user's day (voice, hotkeys, chat channels, autostart) and
hosts the long-lived Agentic-IDE sessions — and a **dev** instance that is
started and restarted freely to look at the current working tree without
tearing those sessions down. Both load the same ``jarvis.toml``, the same
credentials and the same per-user agent accounts / skills; everything that two
processes cannot share is separated here:

* the runtime data directory (SQLite stores, single-instance lock, WebView
  profile, logs) — ``data/`` vs ``data-dev/`` next to the checkout;
* the listening ports — the dev instance sits ``DEV_PORT_OFFSET`` above every
  configured port;
* the OS identity — window title, taskbar/dock icon (a DEV-badged copy), the
  Windows AppUserModelID / Start-Menu shortcut / branded launcher exe, so the two
  apps never group under one taskbar button and never focus each other's window;
* the *ambient duties* — only the default instance arms the wake word, the
  global hotkeys, the chat channels, reconciles autostart and draws the
  on-screen overlay (Jarvis Bar / orb). Two apps answering "Hey Jarvis" at
  once — or two bars stacked on one spot of the screen — is a defect, not a
  feature.

The instance is chosen by the ``JARVIS_INSTANCE`` environment variable (the
launcher's ``--instance`` flag sets it before anything else is imported). It is
deliberately a *single-underscore* variable: the relauncher drops every
``JARVIS__*`` config override on an in-app restart (``fresh_user_env``), and the
instance must survive exactly that restart — a dev app that came back as the
default app would bounce off the live one's lock.

Standard-library only and free of filesystem / network I/O at import time, like
``dodaios.core.branding``: the fast-boot path, the onboarding state module and
the shortcut installer all read it before the heavy config module loads.
"""

from __future__ import annotations

import os
import re
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path

from dodaios.core.branding import (
    LAUNCHER_ENTRY_NAME,
    LEGACY_LINUX_DESKTOP_ENTRY_FILE_NAMES,
    LEGACY_WINDOWS_BRANDED_LAUNCHER_FILE_NAMES,
    LEGACY_WINDOWS_MUTEX_NAMES,
    LEGACY_WINDOWS_SHORTCUT_FILE_NAMES,
    LINUX_APP_NAME,
    LINUX_DESKTOP_ENTRY_FILE_NAME,
    LINUX_WM_CLASS,
    MACOS_BUNDLE_ID,
    PERSISTENT_COMPACT_NAME,
    PERSISTENT_PRODUCT_NAME,
    PERSISTENT_SLUG,
    PRODUCT_NAME,
    WINDOWS_APP_USER_MODEL_ID,
    WINDOWS_BRANDED_LAUNCHER_FILE_NAME,
    WINDOWS_MUTEX_NAME,
    WINDOWS_SHORTCUT_FILE_NAME,
)

#: Environment variable that relocates the runtime data directory.
DATA_DIR_ENV_VAR = "JARVIS_DATA_DIR"
#: Environment variable naming the instance. Absent / blank = the default app.
INSTANCE_ENV_VAR = "JARVIS_INSTANCE"
DEFAULT_INSTANCE_NAME = "default"
DEV_INSTANCE_NAME = "dev"
#: The dev instance listens this many ports above every configured port.
DEV_PORT_OFFSET = 100
#: Icon file (in ``assets/icons``) each instance shows on taskbar, dock and tray.
DEFAULT_ICON_FILE_NAME = "dodaios.ico"
DEV_ICON_FILE_NAME = "dodaios-dev.ico"
#: Short label appended to the product name ("Dodaios Dev").
DEV_LABEL = "Dev"

KNOWN_INSTANCE_NAMES = (DEFAULT_INSTANCE_NAME, DEV_INSTANCE_NAME)

_NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,23}$")


class InstanceNameError(ValueError):
    """``JARVIS_INSTANCE`` names an instance this build does not know."""


def normalize_instance_name(raw: str | None) -> str:
    """Canonical instance name for a raw env/CLI value.

    ``None``, blank and ``"default"`` (any case) all mean the default instance.
    Anything else must be one of :data:`KNOWN_INSTANCE_NAMES`; a typo must fail
    loudly here rather than silently boot a second *default* app that fights the
    live one over its lock and port.
    """
    name = (raw or "").strip().lower()
    if not name:
        return DEFAULT_INSTANCE_NAME
    if not _NAME_RE.match(name) or name not in KNOWN_INSTANCE_NAMES:
        known = ", ".join(KNOWN_INSTANCE_NAMES)
        raise InstanceNameError(
            f"{INSTANCE_ENV_VAR}={raw!r} is not a known instance (known: {known})"
        )
    return name


@dataclass(frozen=True, slots=True)
class InstanceIdentity:
    """Everything that differs between the instances, resolved once."""

    name: str

    # ---- flags ---------------------------------------------------------
    @property
    def is_default(self) -> bool:
        return self.name == DEFAULT_INSTANCE_NAME

    @property
    def is_dev(self) -> bool:
        return self.name == DEV_INSTANCE_NAME

    @property
    def owns_ambient_duties(self) -> bool:
        """May this instance arm the wake word, global hotkeys, chat channels,
        autostart and the on-screen overlay (Jarvis Bar / orb)? Only the default
        app does; a second listener on the same microphone / bot token / key
        combo — or a second bar on the same spot of the screen — is a collision,
        not redundancy. The overlay is the sharpest case: both instances read
        ONE ``jarvis.toml``, so a dev app that drew its own bar and then had it
        switched off wrote ``orb_style = "none"`` into the shared file and took
        the default app's bar away on its next restart (2026-08-23)."""
        return self.is_default

    # ---- naming ---------------------------------------------------------
    @property
    def label(self) -> str:
        """Short badge text: ``""`` for the default app, ``"Dev"`` for dev."""
        if self.is_default:
            return ""
        return DEV_LABEL if self.is_dev else self.name.title()

    @property
    def display_name(self) -> str:
        """Window title / taskbar name: ``"Dodaios"`` or ``"… Dev"``. Display text only."""
        return PRODUCT_NAME if self.is_default else f"{PRODUCT_NAME} {self.label}"

    @property
    def persistent_name(self) -> str:
        """The name this instance's OS artifacts are registered under.

        A compatibility contract (``dodaios.core.branding``) that never follows
        ``display_name``. The Windows and Linux names moved on with their own
        migrations (``windows_launcher_entry_name``, ``linux_app_name`` and the
        file names beside them); this is the name those earlier releases used.
        """
        if self.is_default:
            return PERSISTENT_PRODUCT_NAME
        return f"{PERSISTENT_PRODUCT_NAME} {self.label}"

    @property
    def compact_name(self) -> str:
        """Persistent: the instance's name without spaces (``PersonalJarvisDev``)."""
        if self.is_default:
            return PERSISTENT_COMPACT_NAME
        return f"{PERSISTENT_COMPACT_NAME}{self.label}"

    @property
    def slug(self) -> str:
        """Persistent: the hyphenated earlier name (``personal-jarvis-dev``).

        Earlier releases named the Linux desktop entry and window class after
        it; ``legacy_linux_desktop_entry_file_names`` still finds those entries.
        """
        return PERSISTENT_SLUG if self.is_default else f"{PERSISTENT_SLUG}-{self.name}"

    # ---- storage / network ----------------------------------------------
    @property
    def data_dir_name(self) -> str:
        """Runtime data directory name next to the checkout (``data`` / ``data-dev``)."""
        return "data" if self.is_default else f"data-{self.name}"

    @property
    def port_offset(self) -> int:
        return 0 if self.is_default else DEV_PORT_OFFSET

    def port(self, base: int) -> int:
        """The port this instance binds for a configured base port."""
        return int(base) + self.port_offset

    @property
    def state_file_suffix(self) -> str:
        """Suffix for per-user state files that must not be shared between the
        instances (``last_session.json`` → ``last_session.dev.json``)."""
        return "" if self.is_default else f".{self.name}"

    # ---- OS identity ----------------------------------------------------
    @property
    def icon_file_name(self) -> str:
        return DEFAULT_ICON_FILE_NAME if self.is_default else DEV_ICON_FILE_NAME

    @property
    def windows_aumid(self) -> str:
        if self.is_default:
            return WINDOWS_APP_USER_MODEL_ID
        return f"{WINDOWS_APP_USER_MODEL_ID}.{self.label}"

    @property
    def windows_launcher_entry_name(self) -> str:
        """The name Windows lists this instance under (shortcut, toast identity)."""
        if self.is_default:
            return LAUNCHER_ENTRY_NAME
        return f"{LAUNCHER_ENTRY_NAME} {self.label}"

    # Each Windows name below has a ``legacy_*`` twin: the names an earlier
    # release registered the same instance under, derived the same way from the
    # branding's ``LEGACY_*`` values. Code that only has to FIND an artifact
    # (a running primary, a launcher to restart through, an old shortcut to
    # retire) looks at both; code that CREATES one uses the current name.
    @property
    def windows_mutex_name(self) -> str:
        return self._mutex_name(WINDOWS_MUTEX_NAME)

    @property
    def legacy_windows_mutex_names(self) -> tuple[str, ...]:
        return tuple(self._mutex_name(base) for base in LEGACY_WINDOWS_MUTEX_NAMES)

    @property
    def windows_shortcut_file_name(self) -> str:
        return self._shortcut_file_name(WINDOWS_SHORTCUT_FILE_NAME)

    @property
    def legacy_windows_shortcut_file_names(self) -> tuple[str, ...]:
        return tuple(self._shortcut_file_name(base) for base in LEGACY_WINDOWS_SHORTCUT_FILE_NAMES)

    @property
    def windows_branded_launcher_file_name(self) -> str:
        return self._launcher_file_name(WINDOWS_BRANDED_LAUNCHER_FILE_NAME)

    @property
    def legacy_windows_branded_launcher_file_names(self) -> tuple[str, ...]:
        return tuple(
            self._launcher_file_name(base) for base in LEGACY_WINDOWS_BRANDED_LAUNCHER_FILE_NAMES
        )

    def _mutex_name(self, base: str) -> str:
        return base if self.is_default else f"{base}_{self.name}"

    def _shortcut_file_name(self, base: str) -> str:
        if self.is_default:
            return base
        stem = base.removesuffix(".lnk")
        return f"{stem} {self.label}.lnk"

    def _launcher_file_name(self, base: str) -> str:
        if self.is_default:
            return base
        stem = base.removesuffix(".exe")
        return f"{stem}{self.label}.exe"

    # The Linux names move together: the desktop binds a running window to the
    # entry whose ``StartupWMClass`` is the window's class, so an entry file,
    # its ``Name`` and the class pinned at runtime always come from one
    # generation of the branding values.
    @property
    def linux_app_name(self) -> str:
        """The name the Linux app menu lists this instance under."""
        return LINUX_APP_NAME if self.is_default else f"{LINUX_APP_NAME} {self.label}"

    @property
    def linux_wm_class(self) -> str:
        return LINUX_WM_CLASS if self.is_default else f"{LINUX_WM_CLASS}-{self.name}"

    @property
    def linux_desktop_entry_file_name(self) -> str:
        return self._linux_entry_file_name(LINUX_DESKTOP_ENTRY_FILE_NAME)

    @property
    def legacy_linux_desktop_entry_file_names(self) -> tuple[str, ...]:
        return tuple(
            self._linux_entry_file_name(base) for base in LEGACY_LINUX_DESKTOP_ENTRY_FILE_NAMES
        )

    def _linux_entry_file_name(self, base: str) -> str:
        if self.is_default:
            return base
        stem = base.removesuffix(".desktop")
        return f"{stem}-{self.name}.desktop"

    @property
    def macos_bundle_id(self) -> str:
        return MACOS_BUNDLE_ID if self.is_default else f"{MACOS_BUNDLE_ID}.{self.name}"

    # ---- launch ---------------------------------------------------------
    @property
    def launcher_args(self) -> tuple[str, ...]:
        """Extra launcher argv that selects this instance (empty for default)."""
        return () if self.is_default else ("--instance", self.name)

    def environ(self, base: Mapping[str, str] | None = None) -> dict[str, str]:
        """``base`` (default ``os.environ``) with this instance pinned in it."""
        env = dict(os.environ if base is None else base)
        if self.is_default:
            env.pop(INSTANCE_ENV_VAR, None)
        else:
            env[INSTANCE_ENV_VAR] = self.name
        return env


def resolve_instance(environ: Mapping[str, str] | None = None) -> InstanceIdentity:
    """The instance named by ``environ`` (default: the process environment)."""
    source = os.environ if environ is None else environ
    return InstanceIdentity(normalize_instance_name(source.get(INSTANCE_ENV_VAR)))


def current_instance() -> InstanceIdentity:
    """The instance THIS process runs as. Cheap; reads the env on every call so a
    test that sets the variable sees the change without any cache to clear."""
    return resolve_instance()


def select_instance(name: str | None) -> InstanceIdentity:
    """Pin ``name`` into the process environment and return its identity.

    The launcher calls this for ``--instance`` before importing anything that
    reads :data:`INSTANCE_ENV_VAR` at import time (``dodaios.core.config``,
    ``dodaios.ui.icon_utils``). Child processes — the relauncher, the branded
    re-exec, the unelevated copy — inherit the variable and come back as the
    same instance.
    """
    identity = InstanceIdentity(normalize_instance_name(name))
    if identity.is_default:
        os.environ.pop(INSTANCE_ENV_VAR, None)
    else:
        os.environ[INSTANCE_ENV_VAR] = identity.name
    return identity


def instance_data_dir(project_root: Path, identity: InstanceIdentity | None = None) -> Path:
    """``<project_root>/data`` or ``<project_root>/data-<name>``."""
    return project_root / (identity or current_instance()).data_dir_name


def resolve_data_dir(project_root: Path) -> Path:
    """The runtime data directory of this process: the one implementation.

    ``JARVIS_DATA_DIR`` (headless hosts, read-only installs, the frozen build's
    runtime hook) wins outright. Otherwise the directory sits next to the
    checkout and is named by the instance. ``dodaios.core.config.DATA_DIR`` and
    the early desktop log both resolve through here, so they cannot disagree.
    """
    env_dir = os.environ.get(DATA_DIR_ENV_VAR)
    if env_dir and env_dir.strip():
        return Path(env_dir.strip())
    return instance_data_dir(project_root)


def data_dir_source() -> str:
    """Where :func:`resolve_data_dir` takes the directory from right now.

    ``"JARVIS_DATA_DIR"`` when the environment variable set it, else
    ``"default"``. Shown at boot and on the diagnostics API so a switched data
    directory (an apparently empty agent roster, issue #1058) is visible.
    """
    env_dir = os.environ.get(DATA_DIR_ENV_VAR)
    return DATA_DIR_ENV_VAR if env_dir and env_dir.strip() else "default"


__all__ = [
    "DATA_DIR_ENV_VAR",
    "DEFAULT_ICON_FILE_NAME",
    "DEFAULT_INSTANCE_NAME",
    "DEV_ICON_FILE_NAME",
    "DEV_INSTANCE_NAME",
    "DEV_LABEL",
    "DEV_PORT_OFFSET",
    "INSTANCE_ENV_VAR",
    "KNOWN_INSTANCE_NAMES",
    "InstanceIdentity",
    "InstanceNameError",
    "current_instance",
    "data_dir_source",
    "instance_data_dir",
    "normalize_instance_name",
    "resolve_data_dir",
    "resolve_instance",
    "select_instance",
]