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.

feat(desktop): a dev instance — two desktop apps from one checkout

rubenluetke10-beepce6cf8262f61
diff --git a/.gitignore b/.gitignore
index c5e884748d..b5ad3bc775 100644
--- a/.gitignore
+++ b/.gitignore
@@ -66,6 +66,8 @@ build/
# Jarvis Runtime-Daten (nie committen)
data/*
data/**/
+# The dev instance's runtime data (jarvis/core/instance.py) — same rule as data/.
+data-dev/
*.db
*.sqlite
*.sqlite3
diff --git a/assets/icons/jarvis-dev.ico b/assets/icons/jarvis-dev.ico
new file mode 100644
index 0000000000..a3d7c72f6e
Binary files /dev/null and b/assets/icons/jarvis-dev.ico differ
diff --git a/assets/icons/jarvis-dev.png b/assets/icons/jarvis-dev.png
new file mode 100644
index 0000000000..014c1abcb3
Binary files /dev/null and b/assets/icons/jarvis-dev.png differ
diff --git a/docs/dev-instance.md b/docs/dev-instance.md
new file mode 100644
index 0000000000..cb4f59c2af
--- /dev/null
+++ b/docs/dev-instance.md
@@ -0,0 +1,73 @@
+# The dev instance — two desktop apps from one checkout
+
+**Problem.** Seeing a backend change means restarting the desktop app, and a
+restart takes the Agentic-IDE panes, their coding-agent sessions and the voice
+stack down with it. Restoring them afterwards is the most annoying part of
+working on the app from inside the app.
+
+**Answer.** Run two desktop apps from the same working tree:
+
+| | **Personal Jarvis** (default instance) | **Personal Jarvis Dev** (dev instance) |
+|---|---|---|
+| Purpose | The app you live in: voice, hotkeys, channels, the Agentic-IDE sessions you vibe-code from. Never restarted for a code change. | A second window you restart as often as you like to look at the current working tree. |
+| Start | `run.bat` / `./run.sh`, the Start-Menu / Desktop shortcut, autostart | `run-dev.bat` / `./run-dev.sh`, the **Personal Jarvis Dev** shortcut, or `python -m jarvis.ui.web.launcher --instance dev` |
+| Frontend | The built bundle; a rebuilt bundle is picked up by the window itself (`bundleWatch`) | Same built bundle, same pick-up — so UI changes show up in BOTH without a restart |
+| Backend (Python) changes | Only after a restart — which you now do on the dev app | Restart from the tray / in-app Restart / the launcher as usual |
+| Data directory | `data/` | `data-dev/` (created on first start, seeded once with `setup_state.json`, `identity_card.json`, `core_memory.json` and a snapshot of `chats.db`) |
+| Ports | `[ui].admin_api_port` etc. as configured (47821 …) | every configured port **+100** (47921 …) |
+| Config, keys, agent accounts, skills | shared (`jarvis.toml`, keyring, `%LOCALAPPDATA%\Jarvis` / `~/.jarvis`) | shared — same providers, same logins, so "everything works" |
+| Window title / taskbar / tray | Personal Jarvis, mascot icon | Personal Jarvis **Dev**, mascot with a yellow **DEV** tag, own taskbar group, own tray entry; the sidebar shows a small **DEV** badge |
+| Wake word, global hotkeys | as configured | **off** — the microphone and the key combos belong to the default app (the in-window mic button and chat still work) |
+| Chat channels (Telegram/Discord), autostart | as configured | **off** — a second poller on the same bot token would collide; the dev app never touches the login autostart entry |
+| Agentic-IDE resume offer | `last_session.json` | `last_session.dev.json` — a restarted dev app never offers to resume panes that are alive in the default app |
+
+## How it is selected
+
+`JARVIS_INSTANCE=dev` in the environment, or `--instance dev` on the launcher
+(which sets the variable before anything else is imported). The variable is a
+*single* underscore on purpose: the relauncher refreshes every `JARVIS__*`
+config override on an in-app restart, and the instance must survive exactly
+that restart. Children — the relauncher, the branded re-exec, the unelevated
+copy, the in-app restart chain — inherit it.
+
+Only `default` and `dev` are known names; anything else fails the boot with a
+sentence, because a typo must not start a second *default* app that fights the
+live one over its lock and port.
+
+`jarvis/core/instance.py` is the one place that knows what differs; everything
+else asks it (`current_instance()`): `jarvis.core.config.DATA_DIR`,
+`load_config` (port offsets, `memory.data_dir`), `jarvis.ui.icon_utils` (AUMID,
+shortcut, branded exe, icon), `jarvis.ui.desktop_app.WINDOW_TITLE`, the tray,
+`jarvis.setup.state`, the Agentic-IDE resume store, `SpeechPipeline` (wake word,
+hotkeys), the Friends stack (channels), and the launcher (autostart).
+
+## Shortcuts
+
+```
+python scripts/install_shortcuts.py --dev
+```
+
+writes `Desktop\Personal Jarvis Dev.lnk` (DEV icon, `--instance dev`, its own
+AppUserModelID). The first dev start also writes the Start-Menu entry
+`Personal Jarvis Dev` through the same code path the default app uses, so the
+taskbar button is named and iconed from the first launch.
+
+The dev icon is rendered by `scripts/make_dev_icon.py` into both icon homes
+(`jarvis/assets/icons/` ships with the package, `assets/icons/` is the
+build-tool copy).
+
+## Known sharing
+
+Two things are deliberately shared and fine: `jarvis.toml` (settings you change
+in the dev app apply to the default app too — same user, same preferences) and
+the per-user directory (agent accounts, skills, board, recents). A few
+CWD-relative paths still point at `data/` from both instances — the flight
+recorder, the wiki curator lock (a cross-process lock, so this is correct), the
+review / self-mod audit logs, computer-use blobs. They are logs and locks, not
+stores; none of them makes the two apps answer for each other.
+
+## Cross-platform
+
+Built OS-neutral; the Windows identity layer is the one verified live. See
+`docs/os-parity.md` P-37 for macOS (no separate bundle, dock icon follows the
+default app) and Linux (own `.desktop` entry, unverified live).
diff --git a/docs/os-parity.md b/docs/os-parity.md
index cb1133280f..b40d884a56 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -254,6 +254,8 @@ experiences today.
| P-35 | Low | Desktop shell | The embedded browser's profile is PERSISTENT (`webview.start(private_mode=False, storage_path=<data>/webview)`) so the frontend's `localStorage` — wallpaper pick, deck/classic surface, pane sizes, favourites, theme cache — survives a restart (2026-08-18: pywebview's default private mode parked the WebView2 profile in a fresh `%TEMP%` folder per launch and the interface forgot every pick). The same call is honoured by every pywebview backend (Edge `UserDataFolder`, WebKitGTK `WebsiteDataManager`, Qt profile path, Cocoa's default persistent data store) but has only been RUN against Windows/WebView2 | `jarvis/ui/desktop_app.py::webview_storage_dir` | Honest everywhere: a checkout without a writable data directory falls back to the per-user directory, then to private mode with a logged warning — the interface still works, it only forgets its cosmetic picks. macOS/Linux live check pending: pick a wallpaper, restart, confirm it is still there |
| P-36 | Low | Coding-CLI panes | DeepSeek Harness is the one registered CLI whose interface is NOT the terminal. Upstream removed its terminal front door and publishes no `@deepseek-ai/dsh-tui*` bundle (checked 2026-08-22), so the two shipped profiles are `web` — a server the pane boots, whose UI opens in the default browser — and `headless`, which answers one task and exits. The pane therefore runs and is detected like every other entry, but declines the keystroke channel (`accepts_typed_prompts=False`), so the prompt bar, voice fan-out and CLI never type into it, and it has no transcript, recap or conversation resume | `jarvis/workspace/agents.py` (the `deepseek-harness` entry), `jarvis/agentic_ide/session.py::accepts_prompts`, upstream `apps/cli/README.md` | Identical on all three OSes — one npm package, one Node entrypoint, no native binary and no OS-specific installer. The one difference is not ours: on a host with no browser (headless Linux, an SSH launch) the harness prints its URL instead of opening it, which is the honest degradation and leaves the pane usable over a forwarded port |
+| P-37 | Low | Dev instance | A second desktop app from the same checkout (`--instance dev` / `JARVIS_INSTANCE=dev`, see `docs/dev-instance.md`) is built OS-neutral — own `data-dev/`, ports +100, own single-instance lock, window title, DEV-badged icon, no wake word / global hotkeys / chat channels / autostart — but only the WINDOWS identity layer has been run live: AUMID `PersonalJarvis.PersonalJarvis.Dev`, Start-Menu shortcut `Personal Jarvis Dev.lnk`, branded `PersonalJarvisDev.exe`, tray tooltip. Linux gets its own `.desktop` entry + `StartupWMClass` through the same code path (unverified live). macOS has NO separate bundle for the dev instance: the dock shows the default app's bundle icon, and an in-app restart of the dev instance re-enters through the interpreter directly (`build_launch_command` skips the LaunchServices bundle for a non-default instance, because `open -a` would not carry `JARVIS_INSTANCE` and would bring it back as a second default app) — so the restarted dev app has no TCC attachment of its own | `jarvis/core/instance.py`, `jarvis/ui/icon_utils.py` (instance-bound constants), `jarvis/ui/relauncher.py::build_launch_command` | Windows: full parity, verified live. Linux desktop: expected parity (title, icon, tray, data, ports), entry unverified. macOS: functional (data, ports, title, ambient duties, in-app restart), dock icon degrades as described — the dev window is still told apart by its title and the DEV tag in the sidebar |
+
## Maintenance
- Fixing a gap: remove its row (git history keeps the record).
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index e80de8c8f4..c8a28f00ab 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -347,9 +347,17 @@ def _as_int(value: Any) -> int:
def _store_path() -> Path:
+ """``last_session.json`` — per instance (``jarvis.core.instance``).
+
+ The default and the dev app run their own registries; a shared offer file
+ would make a restarted dev app propose to resume panes that are alive in the
+ default app's window (and reopen the same agent conversation twice).
+ """
+ from jarvis.core.instance import current_instance
from jarvis.core.paths import user_data_dir
- return user_data_dir() / "agentic_ide" / "last_session.json"
+ suffix = current_instance().state_file_suffix
+ return user_data_dir() / "agentic_ide" / f"last_session{suffix}.json"
def save(snapshot: Snapshot) -> None:
diff --git a/jarvis/assets/__init__.py b/jarvis/assets/__init__.py
index c0c786ed5a..9e8c08692f 100644
--- a/jarvis/assets/__init__.py
+++ b/jarvis/assets/__init__.py
@@ -93,7 +93,27 @@ def bundled_app_icon() -> Path | None:
code (``package-data`` glob ``assets/**/*``). Same fix class as the bundled
Silero VAD model above.
"""
- path = _ICONS_DIR / _APP_ICON_FILE
+ return _instance_icon(_APP_ICON_FILE)
+
+
+def _instance_icon(default_name: str) -> Path | None:
+ """The icon file for the running *instance* (``jarvis.core.instance``).
+
+ The dev app carries a DEV-badged copy (``jarvis-dev.ico`` / ``.png``,
+ rendered by ``scripts/make_dev_icon.py``) so its taskbar, dock and tray
+ entries are told apart from the default app's at a glance. A missing badged
+ file falls back to the default icon rather than to no icon at all.
+ """
+ from jarvis.core.instance import current_instance
+
+ identity = current_instance()
+ if not identity.is_default:
+ badged = _ICONS_DIR / Path(identity.icon_file_name).with_suffix(
+ Path(default_name).suffix
+ )
+ if badged.is_file():
+ return badged
+ path = _ICONS_DIR / default_name
return path if path.is_file() else None
@@ -109,8 +129,7 @@ def bundled_app_icon_png() -> Path | None:
not Jarvis" report. Resolved fresh from the installed package so the absolute
path baked into the ``.desktop`` is correct on any install layout.
"""
- path = _ICONS_DIR / _APP_ICON_PNG_FILE
- return path if path.is_file() else None
+ return _instance_icon(_APP_ICON_PNG_FILE)
_MUSIC_PLAYER_ICON_FILE = "music-player.ico"
diff --git a/jarvis/assets/icons/jarvis-dev.ico b/jarvis/assets/icons/jarvis-dev.ico
new file mode 100644
index 0000000000..a3d7c72f6e
Binary files /dev/null and b/jarvis/assets/icons/jarvis-dev.ico differ
diff --git a/jarvis/assets/icons/jarvis-dev.png b/jarvis/assets/icons/jarvis-dev.png
new file mode 100644
index 0000000000..014c1abcb3
Binary files /dev/null and b/jarvis/assets/icons/jarvis-dev.png differ
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index cee0ce981e..4a22b73b14 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -40,6 +40,7 @@ from jarvis.awareness.config import AwarenessConfig
from jarvis.speech.wake_constants import DEFAULT_WAKE_PHRASE, WAKE_ENGINES
from .branding import CONFIG_FILE_NAME, KEYRING_SERVICE_NAME
+from .instance import current_instance
from .protocols import RiskTier
# AckBrainConfig lives under jarvis.brain.ack_brain.config. We cannot
@@ -58,7 +59,25 @@ if TYPE_CHECKING:
PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_CONFIG_FILE = PROJECT_ROOT / CONFIG_FILE_NAME
PROFILES_DIR = PROJECT_ROOT / "profiles"
-DATA_DIR = PROJECT_ROOT / "data"
+
+
+def _resolve_data_dir() -> Path:
+ """The runtime data directory this process uses.
+
+ ``JARVIS_DATA_DIR`` (headless hosts, read-only installs) wins outright.
+ Otherwise the directory sits next to the checkout and is named by the
+ *instance* (``jarvis.core.instance``): ``data/`` for the default app,
+ ``data-dev/`` for the dev app — two desktop apps from one checkout must not
+ share SQLite stores, the single-instance lock or the WebView profile.
+ Resolved once at import, like every other path constant here.
+ """
+ env_dir = os.environ.get("JARVIS_DATA_DIR")
+ if env_dir and env_dir.strip():
+ return Path(env_dir.strip())
+ return PROJECT_ROOT / current_instance().data_dir_name
+
+
+DATA_DIR = _resolve_data_dir()
ASSETS_DIR = PROJECT_ROOT / "assets"
# Guards _resolve_writable_data_dir()'s lazy writability probe below. Named
@@ -4339,9 +4358,51 @@ def load_config(
# JARVIS__BRAIN__WORKER__* if only the old names are set (process-local).
_migrate_worker_env_vars()
data = _apply_env_overrides(data)
+ data = _apply_instance_overrides(data)
return JarvisConfig(**data)
+# Ports the dev instance shifts by ``InstanceIdentity.port_offset``: every
+# (section, field) a process binds or publishes. The admin port doubles as the
+# fast-boot bind (``launcher._fast_admin_port`` applies the same offset).
+_INSTANCE_PORT_FIELDS: tuple[tuple[str, str, int], ...] = (
+ ("ui", "admin_api_port", 47821),
+ ("mcp_server", "http_port", 47822),
+ ("telemetry", "metrics_port", 9090),
+)
+
+
+def _apply_instance_overrides(data: dict[str, Any]) -> dict[str, Any]:
+ """Pin the non-default instance's ports and data directory AFTER every
+ user layer (TOML, profile, env) has landed.
+
+ These are not preferences but the contract that lets two desktop apps from
+ one checkout coexist, so no layer may undo them: a ``jarvis.toml`` or
+ ``JARVIS__UI__ADMIN_API_PORT`` is read as the *base* the dev app offsets
+ from, and ``memory.data_dir`` (the anchor for sessions / missions / friends
+ / chats / wiki stores) is the instance's own directory. The default
+ instance passes through untouched.
+ """
+ identity = current_instance()
+ if identity.is_default:
+ return data
+ for section, field, default in _INSTANCE_PORT_FIELDS:
+ table = data.get(section)
+ if not isinstance(table, dict):
+ table = {}
+ data[section] = table
+ base = table.get(field, default)
+ if not isinstance(base, int) or isinstance(base, bool):
+ base = default
+ table[field] = identity.port(base)
+ memory = data.get("memory")
+ if not isinstance(memory, dict):
+ memory = {}
+ data["memory"] = memory
+ memory["data_dir"] = str(DATA_DIR)
+ return data
+
+
# ----------------------------------------------------------------------
# Secrets (Windows Credential Manager via keyring)
# ----------------------------------------------------------------------
diff --git a/jarvis/core/instance.py b/jarvis/core/instance.py
new file mode 100644
index 0000000000..fbf1f1d7f8
--- /dev/null
+++ b/jarvis/core/instance.py
@@ -0,0 +1,263 @@
+"""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 and reconciles autostart. Two apps answering
+ "Hey Jarvis" at once 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
+``jarvis.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 jarvis.core.branding import (
+ LINUX_DESKTOP_ENTRY_FILE_NAME,
+ LINUX_WM_CLASS,
+ MACOS_BUNDLE_ID,
+ PRODUCT_COMPACT_NAME,
+ PRODUCT_NAME,
+ PRODUCT_SLUG,
+ WINDOWS_APP_USER_MODEL_ID,
+ WINDOWS_BRANDED_LAUNCHER_FILE_NAME,
+ WINDOWS_MUTEX_NAME,
+ WINDOWS_SHORTCUT_FILE_NAME,
+)
+
+#: 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 = "jarvis.ico"
+DEV_ICON_FILE_NAME = "jarvis-dev.ico"
+#: Short label appended to the product name ("Personal Jarvis 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
+ and autostart? Only the default app does; a second listener on the same
+ microphone / bot token / key combo is a collision, not redundancy."""
+ 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: ``"Personal Jarvis"`` or ``"… Dev"``."""
+ return PRODUCT_NAME if self.is_default else f"{PRODUCT_NAME} {self.label}"
+
+ @property
+ def compact_name(self) -> str:
+ return PRODUCT_COMPACT_NAME if self.is_default else f"{PRODUCT_COMPACT_NAME}{self.label}"
+
+ @property
+ def slug(self) -> str:
+ return PRODUCT_SLUG if self.is_default else f"{PRODUCT_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_mutex_name(self) -> str:
+ return WINDOWS_MUTEX_NAME if self.is_default else f"{WINDOWS_MUTEX_NAME}_{self.name}"
+
+ @property
+ def windows_shortcut_file_name(self) -> str:
+ return WINDOWS_SHORTCUT_FILE_NAME if self.is_default else f"{self.display_name}.lnk"
+
+ @property
+ def windows_branded_launcher_file_name(self) -> str:
+ return (
+ WINDOWS_BRANDED_LAUNCHER_FILE_NAME
+ if self.is_default
+ else f"{self.compact_name}.exe"
+ )
+
+ @property
+ def linux_wm_class(self) -> str:
+ return LINUX_WM_CLASS if self.is_default else self.slug
+
+ @property
+ def linux_desktop_entry_file_name(self) -> str:
+ return LINUX_DESKTOP_ENTRY_FILE_NAME if self.is_default else f"{self.slug}.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 (``jarvis.core.config``,
+ ``jarvis.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
+
+
+__all__ = [
+ "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",
+ "instance_data_dir",
+ "normalize_instance_name",
+ "resolve_instance",
+ "select_instance",
+]
diff --git a/jarvis/core/instance_data.py b/jarvis/core/instance_data.py
new file mode 100644
index 0000000000..543d012d09
--- /dev/null
+++ b/jarvis/core/instance_data.py
@@ -0,0 +1,94 @@
+"""First-start seeding of a non-default instance's data directory.
+
+A dev instance gets its own ``data-dev/`` (see ``jarvis.core.instance``), which
+would otherwise start as a blank install: the first-run guide again, no chats to
+look at, an unnamed assistant. That is not what a second window of the *same*
+product should feel like, so the very first start copies the few files that
+make it recognisably this user's Jarvis — and nothing else. Everything that is
+live state of the running default app (sessions, missions, the wiki, the
+recall store, locks, logs, the WebView profile) starts fresh: it either must not
+be shared between two processes or is simply not worth a snapshot.
+
+The copy happens exactly once — when the directory does not exist yet. A later
+start never re-seeds, so whatever the dev app accumulates stays its own.
+SQLite files are copied through the online backup API so an open WAL on the
+source never yields a torn file.
+"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+import sqlite3
+from pathlib import Path
+
+from jarvis.core.instance import InstanceIdentity, current_instance
+
+log = logging.getLogger(__name__)
+
+#: Files copied from the default instance on the first start of another one.
+SEED_FILES: tuple[str, ...] = (
+ "setup_state.json", # onboarding done — no first-run guide in the dev app
+ "identity_card.json", # the assistant's name / persona as the user set it
+ "core_memory.json", # the core memory the persona is built from
+ "chats.db", # a snapshot of the chat history, so the chat views look real
+)
+
+
+def _copy_sqlite(src: Path, dst: Path) -> None:
+ """Consistent copy of a possibly-open SQLite database (WAL-safe)."""
+ with sqlite3.connect(f"file:{src.as_posix()}?mode=ro", uri=True) as source:
+ with sqlite3.connect(dst) as target:
+ source.backup(target)
+
+
+def ensure_instance_data_dir(
+ project_root: Path,
+ identity: InstanceIdentity | None = None,
+ *,
+ default_data_dir: Path | None = None,
+) -> list[str]:
+ """Create the instance's data dir on its first start, seeded from the default.
+
+ Returns the names of the files that were seeded (empty when the directory
+ already existed, for the default instance, or when there was nothing to copy).
+ Never raises: a failed seed leaves the file out and the app starts without it,
+ which is the blank-install behaviour it would have had anyway.
+ """
+ identity = identity or current_instance()
+ if identity.is_default:
+ return []
+ target_dir = project_root / identity.data_dir_name
+ if target_dir.exists():
+ return []
+ source_dir = default_data_dir or (project_root / "data")
+ target_dir.mkdir(parents=True, exist_ok=True)
+ seeded: list[str] = []
+ for name in SEED_FILES:
+ src = source_dir / name
+ if not src.is_file():
+ continue
+ dst = target_dir / name
+ try:
+ if src.suffix == ".db":
+ _copy_sqlite(src, dst)
+ else:
+ shutil.copyfile(src, dst)
+ except (OSError, sqlite3.Error) as exc:
+ # A missing seed degrades to the blank-install state for that one
+ # file — worth a line, never worth failing the boot over.
+ log.warning("instance %s: could not seed %s: %s", identity.name, name, exc)
+ dst.unlink(missing_ok=True)
+ continue
+ seeded.append(name)
+ log.info(
+ "instance %s: created %s (seeded from %s: %s)",
+ identity.name,
+ target_dir,
+ source_dir,
+ ", ".join(seeded) or "nothing",
+ )
+ return seeded
+
+
+__all__ = ["SEED_FILES", "ensure_instance_data_dir"]
diff --git a/jarvis/setup/state.py b/jarvis/setup/state.py
index d2f1d74861..6d09d30a05 100644
--- a/jarvis/setup/state.py
+++ b/jarvis/setup/state.py
@@ -53,7 +53,19 @@ logger = logging.getLogger(__name__)
# per start method, so the flag written by one start was invisible to the next
# and the first-run setup guide re-appeared on every restart. parents[2] mirrors
# jarvis.core.config.PROJECT_ROOT (this file is jarvis/setup/state.py).
-_DEFAULT_STATE_PATH = Path(__file__).resolve().parents[2] / "data" / "setup_state.json"
+# The data directory follows the *instance* (jarvis.core.instance — a stdlib-only
+# module, so this fast-boot path still never imports the heavy config module):
+# ``data/`` for the default app, ``data-dev/`` for the dev app. ``JARVIS_DATA_DIR``
+# wins when set, mirroring ``jarvis.core.config.DATA_DIR`` exactly.
+def _default_state_path() -> Path:
+ from jarvis.core.instance import instance_data_dir
+
+ env_dir = os.environ.get("JARVIS_DATA_DIR", "").strip()
+ base = Path(env_dir) if env_dir else instance_data_dir(Path(__file__).resolve().parents[2])
+ return base / "setup_state.json"
+
+
+_DEFAULT_STATE_PATH = _default_state_path()
def state_path(override: Path | None = None) -> Path:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 9fd1590ebe..769933bfc3 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -2049,6 +2049,19 @@ def _default_tts_for_pipeline(config: Any) -> Any:
return GeminiFlashTTS()
+def _owns_ambient_duties() -> bool:
+ """May this process arm the wake word and the global hotkeys?
+
+ Only the default instance of the app does (``jarvis.core.instance``); a
+ second instance started beside it for development must not compete for the
+ microphone or the key combos. Lazy import keeps the pipeline's import cost
+ unchanged; the lookup is a dict read.
+ """
+ from jarvis.core.instance import current_instance
+
+ return current_instance().owns_ambient_duties
+
+
class SpeechPipeline:
"""End-to-End Pipeline mit Call/Hangup-Lifecycle + Parallel-Wake."""
@@ -2400,6 +2413,15 @@ class SpeechPipeline:
if configured_wake_enabled is not None
else None
)
+ # A non-default instance of the desktop app (``jarvis.core.instance``,
+ # the "dev" app beside the live one) never listens for the wake word
+ # and never arms a global hotkey — the microphone and the key combos
+ # belong to the default app; two listeners would both answer. The
+ # in-window mic button and the chat still work, so voice can be tested.
+ if not _owns_ambient_duties():
+ self._wake_word_enabled = False
+ enable_openwakeword = False
+ enable_whisper_wake = False
self._openwakeword_enabled = enable_openwakeword
# Custom-wake-word plan (jarvis.speech.wake_phrase.WakeWordPlan) or None.
# When None, the wake path is byte-identical to the legacy "Hey Jarvis"
@@ -3452,7 +3474,7 @@ class SpeechPipeline:
plan, lazily preparing any detector it needs, and both transitions wake
the parked/running wake loop through the existing reload event.
"""
- self._wake_word_enabled = bool(enabled)
+ self._wake_word_enabled = bool(enabled) and _owns_ambient_duties()
plan = getattr(self, "_wake_plan", None)
if self._wake_word_enabled and plan is not None:
self.set_wake_plan(plan)
@@ -3539,11 +3561,14 @@ class SpeechPipeline:
action made that duplication a drift bug waiting to happen — a shortcut
that works at boot but not after a Settings save, or the reverse.
"""
+ edge_events: set[str] = set()
+ if not _owns_ambient_duties():
+ # Global hotkeys are the default app's; see __init__.
+ return {"call": [], "hangup": []}, edge_events
bindings: dict[str, list[str]] = {
"call": list(self._call_hotkeys),
"hangup": list(self._hangup_hotkeys),
}
- edge_events: set[str] = set()
if self._ptt_hotkeys:
bindings["ptt"] = list(self._ptt_hotkeys)
edge_events.add("ptt")
diff --git a/jarvis/state/chat_store.py b/jarvis/state/chat_store.py
index 37e42f9ce4..5e3136537b 100644
--- a/jarvis/state/chat_store.py
+++ b/jarvis/state/chat_store.py
@@ -73,15 +73,17 @@ CREATE INDEX IF NOT EXISTS idx_chat_messages_thread
def default_chats_db_path(data_dir: str = "./data") -> Path:
- """Resolve ``chats.db`` to sit beside ``sessions.db``.
-
- Uses the *identical* formula the session-store bootstrap uses in
- ``server.py`` (``Path(cfg.memory.data_dir).parent / "data" / <name>``), so
- ``chats.db`` is guaranteed to land in the same directory as ``sessions.db``
- regardless of how ``data_dir`` is configured. With the default ``./data``
- that is repo-root ``data/chats.db``.
+ """Resolve ``chats.db`` to sit beside ``sessions.db``: inside ``data_dir``.
+
+ ``data_dir`` is ``cfg.memory.data_dir`` — the one directory every SQLite
+ store of a running app lives in. The formula used to be
+ ``Path(data_dir).parent / "data"``, which silently assumed that directory is
+ *named* ``data``; a second instance of the app (``jarvis.core.instance``,
+ ``data-dev/``) would have written its chats into the default app's folder.
+ The session store (``server.py``) anchors the same way, so the two files stay
+ together. With the default ``./data`` this is still repo-root ``data/chats.db``.
"""
- return Path(data_dir).parent / "data" / "chats.db"
+ return Path(data_dir) / "chats.db"
def _derive_title(text: str) -> str:
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index b35ac8a3a0..3128facc6a 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -30,13 +30,18 @@ from typing import TYPE_CHECKING, Any
from filelock import FileLock, Timeout
-from jarvis.core.branding import PRODUCT_NAME as WINDOW_TITLE
from jarvis.core.config import DATA_DIR, JarvisConfig, load_config
+from jarvis.core.instance import current_instance
from jarvis.core.process_utils import ensure_standard_streams
if TYPE_CHECKING:
from jarvis.ui.web.server import WebServer
+# The main window's title doubles as its focus handle
+# (``_bring_window_to_front_by_title``) and follows the *instance*: the dev app
+# is "Personal Jarvis Dev", so neither instance ever raises the other's window.
+WINDOW_TITLE = current_instance().display_name
+
# Direct ``python -m jarvis.ui.desktop_app`` entry points bypass the launcher,
# so they need the same pythonw/PyInstaller stream repair here as well.
ensure_standard_streams()
diff --git a/jarvis/ui/icon_utils.py b/jarvis/ui/icon_utils.py
index 12b73d700c..65b12f2aad 100644
--- a/jarvis/ui/icon_utils.py
+++ b/jarvis/ui/icon_utils.py
@@ -18,25 +18,27 @@ from typing import Any
from loguru import logger
from jarvis.core.branding import (
- LINUX_DESKTOP_ENTRY_FILE_NAME as LINUX_DESKTOP_ENTRY_NAME,
-)
-from jarvis.core.branding import (
- LINUX_WM_CLASS,
WINDOWS_BRANDED_LAUNCH_ENV_VAR,
WINDOWS_BRANDED_LAUNCHER_DIR_NAME,
)
-from jarvis.core.branding import (
- PRODUCT_NAME as APP_DISPLAY_NAME,
-)
-from jarvis.core.branding import (
- WINDOWS_APP_USER_MODEL_ID as APP_USER_MODEL_ID,
-)
-from jarvis.core.branding import (
- WINDOWS_BRANDED_LAUNCHER_FILE_NAME as BRANDED_LAUNCHER_EXE_NAME,
-)
-from jarvis.core.branding import (
- WINDOWS_SHORTCUT_FILE_NAME as START_MENU_SHORTCUT_NAME,
-)
+from jarvis.core.instance import current_instance
+
+# Every OS-facing identity below follows the *instance* this process runs as
+# (``jarvis.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()
+APP_DISPLAY_NAME = _INSTANCE.display_name
+APP_USER_MODEL_ID = _INSTANCE.windows_aumid
+BRANDED_LAUNCHER_EXE_NAME = _INSTANCE.windows_branded_launcher_file_name
+START_MENU_SHORTCUT_NAME = _INSTANCE.windows_shortcut_file_name
+LINUX_DESKTOP_ENTRY_NAME = _INSTANCE.linux_desktop_entry_file_name
+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
@@ -617,6 +619,11 @@ def _default_start_menu_programs_dir() -> Path | 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 _shortcut_matches_install(
lnk: Path,
*,
@@ -759,7 +766,7 @@ def ensure_start_menu_shortcut(
lnk,
expected_target=pythonw,
expected_icon=ico,
- expected_arguments=f"-m {_LAUNCHER_MODULE}",
+ expected_arguments=_launcher_arguments(),
):
return True
logger.debug("stale/broken Start-Menu shortcut, rewriting: {}", lnk)
@@ -791,7 +798,7 @@ def _write_branded_shortcut(
shell = Dispatch("WScript.Shell")
sc = shell.CreateShortcut(str(lnk))
sc.TargetPath = str(target)
- sc.Arguments = f"-m {_LAUNCHER_MODULE}"
+ sc.Arguments = _launcher_arguments()
sc.WorkingDirectory = str(Path.home())
if ico.is_file():
sc.IconLocation = f"{ico},0"
@@ -1450,7 +1457,7 @@ def ensure_linux_desktop_entry(applications_dir: Path | None = None) -> bool:
"Type=Application\n"
f"Name={escape_value(APP_DISPLAY_NAME)}\n"
"Comment=Voice-driven meta-orchestrator\n"
- f"Exec={exec_value(sys.executable, ('-m', _LAUNCHER_MODULE))}\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}"
@@ -1587,9 +1594,11 @@ def project_icon_path() -> Path:
except Exception as exc: # noqa: BLE001 — never let icon resolution crash boot
logger.debug("bundled_app_icon lookup failed, trying repo-root: {}", exc)
- repo_root = Path(__file__).resolve().parents[2] / "assets" / "icons" / "jarvis.ico"
- if repo_root.is_file():
- return repo_root
+ icon_name = _INSTANCE.icon_file_name
+ repo_icons = Path(__file__).resolve().parents[2] / "assets" / "icons"
+ for candidate in (repo_icons / icon_name, repo_icons / "jarvis.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" / "jarvis.ico"
+ return Path(__file__).resolve().parent.parent / "assets" / "icons" / icon_name
diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.py
index 1c8be1ae8f..4a36121925 100644
--- a/jarvis/ui/relauncher.py
+++ b/jarvis/ui/relauncher.py
@@ -50,7 +50,17 @@ def build_launch_command(executable: str) -> list[str]:
bundle therefore fails closed; the managed installer/repair path owns
recreating it.
"""
- fallback = [executable, "-m", LAUNCHER_MODULE]
+ from jarvis.core.instance import current_instance
+
+ identity = current_instance()
+ fallback = [executable, "-m", LAUNCHER_MODULE, *identity.launcher_args]
+ if sys.platform == "darwin" and not identity.is_default:
+ # The bundle is the DEFAULT app's stable identity and LaunchServices
+ # does not carry ``JARVIS_INSTANCE`` into it — re-entering through it
+ # would bring the dev instance back as a second default app. A dev
+ # instance restarts through the interpreter directly (it never owns the
+ # microphone-bound duties the TCC attachment is for).
+ return fallback
if sys.platform == "darwin":
bundle = Path.home() / "Applications" / MACOS_APP_DIR_NAME
try:
diff --git a/jarvis/ui/shell/single_instance.py b/jarvis/ui/shell/single_instance.py
index 2215adf3d0..444ec64cb7 100644
--- a/jarvis/ui/shell/single_instance.py
+++ b/jarvis/ui/shell/single_instance.py
@@ -33,9 +33,13 @@ from typing import Any
import httpx
-from jarvis.core.branding import WINDOWS_MUTEX_NAME as MUTEX_NAME
+from jarvis.core.instance import current_instance
from jarvis.core.paths import ensure_user_dirs
+# Per instance (``jarvis.core.instance``): the dev app claims its own mutex so
+# it never reads the live app as "already running".
+MUTEX_NAME = current_instance().windows_mutex_name
+
logger = logging.getLogger(__name__)
SESSION_FILENAME = "session.json"
diff --git a/jarvis/ui/tray.py b/jarvis/ui/tray.py
index c5414ca739..903e9ea520 100644
--- a/jarvis/ui/tray.py
+++ b/jarvis/ui/tray.py
@@ -22,8 +22,13 @@ from dataclasses import dataclass
from enum import Enum
from typing import Any
+from jarvis.core.instance import current_instance
from jarvis.platform.probes import display_present
+# Tooltip prefix: "Jarvis" for the default app, "Jarvis Dev" for the dev
+# instance — the tray icon already carries the DEV badge, the hover text says it.
+_TRAY_NAME = " ".join(p for p in ("Jarvis", current_instance().label) if p)
+
log = logging.getLogger("jarvis.ui.tray")
@@ -149,7 +154,7 @@ class JarvisTray:
self._icon = Icon(
"jarvis",
icon=icon_image,
- title="Jarvis — idle",
+ title=f"{_TRAY_NAME} — idle",
menu=self._build_menu(),
)
self._icon.run()
@@ -202,7 +207,7 @@ class JarvisTray:
self._icon = Icon(
"jarvis",
icon=icon_image,
- title="Jarvis — idle",
+ title=f"{_TRAY_NAME} — idle",
menu=self._build_menu(),
darwin_nsapplication=nsapp,
)
@@ -274,7 +279,7 @@ class JarvisTray:
def _apply() -> None:
try:
icon.icon = _make_icon(state)
- icon.title = f"Jarvis — {state.value}"
+ icon.title = f"{_TRAY_NAME} — {state.value}"
except Exception: # noqa: BLE001
pass
@@ -287,7 +292,7 @@ class JarvisTray:
def _apply() -> None:
try:
- icon.title = f"Jarvis — Error: {message[:60]}"
+ icon.title = f"{_TRAY_NAME} — Error: {message[:60]}"
except Exception: # noqa: BLE001
pass
diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.py
index 0bae3e4654..f4f59e29a2 100644
--- a/jarvis/ui/web/fast_bootstrap.py
+++ b/jarvis/ui/web/fast_bootstrap.py
@@ -249,7 +249,13 @@ class FastBootstrap:
@staticmethod
async def _ok_health(send: Any) -> None:
- body = b'{"ok": true, "warming": true}'
+ # Same ``instance`` field the full app's /api/health carries, so the
+ # frontend can badge a dev window from the very first poll.
+ from jarvis.core.instance import current_instance
+
+ body = (
+ '{"ok": true, "warming": true, "instance": "' + current_instance().name + '"}'
+ ).encode("ascii")
await send(
{
"type": "http.response.start",
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 258d720ea4..0d290a19a0 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -27,6 +27,7 @@ import { RecentChats } from "@/components/home/RecentChats";
import { useConversations } from "@/hooks/useConversations";
import { useHomeStore } from "@/store/home";
import { PRODUCT_NAME } from "@/lib/branding";
+import { useAppInstance } from "@/hooks/useAppInstance";
// A logo request that fails once (backend restarting, dist mid-rebuild) would
// otherwise stick as the browser's broken-image glyph forever — an <img> never
@@ -107,6 +108,11 @@ export function Sidebar({
const setActive = useEventStore((s) => s.setActiveSection);
const voiceState = useEventStore((s) => s.voiceState);
const assistantName = useEventStore((s) => s.assistantName);
+ // The dev instance (a second, restartable app beside the live one — see
+ // jarvis.core.instance) shows a small tag so the two windows are never
+ // confused; the default app shows nothing here.
+ const appInstance = useAppInstance();
+ const devTag = appInstance?.isDev ? appInstance.name.toUpperCase() : null;
// "+ New chat" lands on the chat surface of the front page with an empty
// thread — the sidebar owns the history now, so it owns this too.
const { newChat } = useConversations();
@@ -232,10 +238,19 @@ export function Sidebar({
data-variant="logo"
title={railed ? `${assistantName} — ${voiceLabel}` : undefined}
className={cn(
- "flex shrink-0 items-center justify-center",
+ "relative flex shrink-0 items-center justify-center",
railed ? "h-9 w-9" : "h-11 w-11",
)}
>
+ {railed && devTag && (
+ <span
+ data-testid="sidebar-instance-tag"
+ title={t("sidebar.instance_dev_hint")}
+ className="absolute -bottom-1 -right-1 rounded-[3px] bg-primary px-[3px] py-px font-mono text-[7px] font-bold leading-none tracking-wider text-primary-foreground"
+ >
+ {devTag}
+ </span>
+ )}
<img
src={
logoRetry === 0
@@ -258,8 +273,17 @@ export function Sidebar({
</span>
{!railed && (
<div className="flex min-w-0 flex-1 flex-col">
- <span className="font-display text-sm font-semibold tracking-tight">
- {assistantName}
+ <span className="flex min-w-0 items-center gap-1.5 font-display text-sm font-semibold tracking-tight">
+ <span className="truncate">{assistantName}</span>
+ {devTag && (
+ <span
+ data-testid="sidebar-instance-tag"
+ title={t("sidebar.instance_dev_hint")}
+ className="shrink-0 rounded-[4px] bg-primary px-1 py-px font-mono text-[9px] font-bold leading-none tracking-wider text-primary-foreground"
+ >
+ {devTag}
+ </span>
+ )}
</span>
<span className="text-[10px] uppercase tracking-wider text-muted-foreground">
{voiceLabel}
diff --git a/jarvis/ui/web/frontend/src/hooks/useAppInstance.test.ts b/jarvis/ui/web/frontend/src/hooks/useAppInstance.test.ts
new file mode 100644
index 0000000000..98e265b8a8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useAppInstance.test.ts
@@ -0,0 +1,37 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { fetchAppInstance, resetAppInstanceCache } from "./useAppInstance";
+
+function healthResponding(body: unknown, ok = true) {
+ return vi.fn(async () => ({ ok, json: async () => body })) as unknown as typeof fetch;
+}
+
+describe("fetchAppInstance", () => {
+ beforeEach(() => resetAppInstanceCache());
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("reads the instance from /api/health and flags dev", async () => {
+ vi.stubGlobal("fetch", healthResponding({ ok: true, instance: "dev" }));
+ expect(await fetchAppInstance()).toEqual({ name: "dev", isDev: true });
+ });
+
+ it("treats a missing field as the default app (older backend)", async () => {
+ vi.stubGlobal("fetch", healthResponding({ ok: true }));
+ expect(await fetchAppInstance()).toEqual({ name: "default", isDev: false });
+ });
+
+ it("caches the answer — the instance never changes while a process runs", async () => {
+ const f = healthResponding({ ok: true, instance: "dev" });
+ vi.stubGlobal("fetch", f);
+ await fetchAppInstance();
+ await fetchAppInstance();
+ expect(f).toHaveBeenCalledTimes(1);
+ });
+
+ it("stays unknown (null) when the backend cannot be reached, never guesses", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => {
+ throw new Error("offline");
+ }) as unknown as typeof fetch);
+ expect(await fetchAppInstance()).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useAppInstance.ts b/jarvis/ui/web/frontend/src/hooks/useAppInstance.ts
new file mode 100644
index 0000000000..849f622503
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useAppInstance.ts
@@ -0,0 +1,58 @@
+import { useEffect, useState } from "react";
+
+/**
+ * Which *instance* of the desktop app this window belongs to.
+ *
+ * One checkout can run two desktop apps side by side (``jarvis.core.instance``):
+ * the default app and a "dev" app that is restarted freely to look at the
+ * current working tree. They share the same frontend bundle, so the only thing
+ * that can tell a dev window apart from the inside is the backend saying so —
+ * ``/api/health`` carries ``instance`` from the first (warming) poll on.
+ *
+ * Resolved once per page load and shared by every caller; the instance of a
+ * process never changes while it runs. ``null`` until known, and a window whose
+ * backend cannot be reached stays ``null`` rather than guessing "default".
+ */
+export type AppInstance = { name: string; isDev: boolean };
+
+let cached: AppInstance | null = null;
+let inflight: Promise<AppInstance | null> | null = null;
+
+export function resetAppInstanceCache(): void {
+ cached = null;
+ inflight = null;
+}
+
+export async function fetchAppInstance(): Promise<AppInstance | null> {
+ if (cached) return cached;
+ if (!inflight) {
+ inflight = fetch("/api/health", { cache: "no-store", credentials: "same-origin" })
+ .then(async (res) => {
+ if (!res.ok) return null;
+ const body = (await res.json()) as { instance?: unknown };
+ const name = typeof body?.instance === "string" && body.instance ? body.instance : "default";
+ cached = { name, isDev: name !== "default" };
+ return cached;
+ })
+ .catch(() => null)
+ .finally(() => {
+ inflight = null;
+ });
+ }
+ return inflight;
+}
+
+export function useAppInstance(): AppInstance | null {
+ const [instance, setInstance] = useState<AppInstance | null>(cached);
+ useEffect(() => {
+ if (cached) return;
+ let cancelled = false;
+ void fetchAppInstance().then((value) => {
+ if (!cancelled && value) setInstance(value);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ return instance;
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 5f71df7f7c..275936bc94 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -452,6 +452,7 @@
"indicator_label": "Sprachstatus"
},
"sidebar": {
+ "instance_dev_hint": "Dev-Instanz — eine zweite, frei neustartbare Kopie der App mit eigenen Daten, Ports und eigenem Icon. Die normale App läuft daneben weiter.",
"surface_voice": "Voice",
"surface_chat": "Chat",
"surface_hint": "Startseite zwischen Sprache und getipptem Chat umschalten",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 59128890c6..e949f38209 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -452,6 +452,7 @@
"indicator_label": "Voice state"
},
"sidebar": {
+ "instance_dev_hint": "Dev instance — a second, freely restartable copy of the app with its own data, ports and icon. The regular app keeps running beside it.",
"surface_voice": "Voice",
"surface_chat": "Chat",
"surface_hint": "Switch the front page between voice and typed chat",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 64b8731b3f..be764c7554 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -452,6 +452,7 @@
"indicator_label": "Estado de voz"
},
"sidebar": {
+ "instance_dev_hint": "Instancia de desarrollo: una segunda copia de la app que puedes reiniciar libremente, con sus propios datos, puertos e icono. La app normal sigue funcionando al lado.",
"surface_voice": "Voz",
"surface_chat": "Chat",
"surface_hint": "Cambiar la página de inicio entre voz y chat escrito",
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 071534ee15..d9eae05463 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -103,9 +103,52 @@ def _parse_args(argv: list[str]) -> argparse.Namespace:
action="store_true",
help="No single-instance lock (for parallel dev sessions)",
)
+ p.add_argument(
+ "--instance",
+ default=None,
+ metavar="NAME",
+ help=(
+ "Run as a named instance. 'dev' starts a second, freely restartable "
+ "desktop app beside the default one (own data dir, ports, icon, no "
+ "wake word / hotkeys / channels). Same as JARVIS_INSTANCE=NAME."
+ ),
+ )
return p.parse_args(argv)
+def _select_instance_early(argv: list[str]) -> str | None:
+ """Pin ``--instance`` into the environment BEFORE anything reads it.
+
+ ``jarvis.core.config`` binds ``DATA_DIR`` and ``jarvis.ui.icon_utils`` binds
+ the Windows identity at import, so the choice must be in ``os.environ`` before
+ the first of those imports — hence a hand scan of argv here rather than the
+ argparse pass further down (which still accepts the flag). Returns an error
+ sentence when the name is unknown (the caller reports it and exits), else
+ ``None``.
+ """
+ from jarvis.core.instance import (
+ INSTANCE_ENV_VAR,
+ InstanceNameError,
+ resolve_instance,
+ select_instance,
+ )
+
+ name: str | None = None
+ for i, arg in enumerate(argv):
+ if arg == "--instance" and i + 1 < len(argv):
+ name = argv[i + 1]
+ elif arg.startswith("--instance="):
+ name = arg.split("=", 1)[1]
+ try:
+ if name is not None:
+ select_instance(name)
+ else:
+ resolve_instance() # validate an inherited JARVIS_INSTANCE
+ except InstanceNameError as exc:
+ return f"{exc}. Use --instance dev, or unset {INSTANCE_ENV_VAR}."
+ return None
+
+
def _acquire_primary_lock_for_headless(
*, lock_path=None, meta_path=None
):
@@ -210,7 +253,18 @@ def _fast_admin_port() -> int:
"""Read ``[ui].admin_api_port`` from jarvis.toml with a raw tomllib read (a
few ms) so the fast-boot bootstrap can bind the REAL port without paying the
~240 ms full ``load_config`` (which drags pydantic + the brain/awareness
- imports) on the time-to-serving path. Falls back to the packaged default."""
+ imports) on the time-to-serving path. Falls back to the packaged default.
+
+ The configured value is the *base*: a non-default instance (``--instance
+ dev``) binds ``InstanceIdentity.port_offset`` above it, exactly as
+ ``load_config`` resolves it for the full app — the two must agree or the
+ bootstrap and the real server would bind different ports."""
+ from jarvis.core.instance import current_instance
+
+ return current_instance().port(_fast_admin_base_port())
+
+
+def _fast_admin_base_port() -> int:
import contextlib
with contextlib.suppress(Exception): # any failure → packaged default
@@ -467,6 +521,12 @@ async def _run_headless(args) -> int:
def _reconcile_autostart_bg() -> None:
try:
+ from jarvis.core.instance import current_instance
+
+ if not current_instance().owns_ambient_duties:
+ # The login autostart entry belongs to the default app; a dev
+ # instance reconciling it would rewrite (or remove) the real one.
+ return
from jarvis.autostart import reconcile_autostart
reconcile_autostart(cfg)
@@ -1122,6 +1182,10 @@ def _desktop_backend_main(args, port: int, token: str, holder: dict, app_ready)
def _reconcile() -> None:
try:
+ from jarvis.core.instance import current_instance
+
+ if not current_instance().owns_ambient_duties:
+ return # the login autostart entry belongs to the default app
from jarvis.autostart import reconcile_autostart
reconcile_autostart(cfg)
@@ -1228,6 +1292,26 @@ def main(argv: list[str] | None = None) -> int:
print(f"[BOOT_PROFILE] m_{_name}={(_now - _m_last) * 1000.0:.1f}", flush=True)
_m_last = _now
+ _raw_argv = argv if argv is not None else sys.argv[1:]
+
+ # Which instance this process IS — decided first, before any module that
+ # derives a path, a port or an OS identity from it gets imported.
+ _instance_error = _select_instance_early(_raw_argv)
+ if _instance_error is not None:
+ _report_startup_failure(_instance_error)
+ return 2
+ try:
+ from pathlib import Path as _IPath
+
+ import jarvis as _jarvis_pkg
+ from jarvis.core.instance_data import ensure_instance_data_dir
+
+ ensure_instance_data_dir(_IPath(_jarvis_pkg.__file__).resolve().parent.parent)
+ except Exception as exc: # noqa: BLE001 — a missing seed is a blank start, not a failed one
+ import logging as _ilog
+
+ _ilog.getLogger(__name__).warning("instance data dir could not be prepared: %s", exc)
+
# GUI/desktop launches carry a minimal PATH (macOS launchd, Windows tray
# relaunch) — append the well-known CLI install dirs before any provider
# probe or worker spawn resolves binaries (stat-only, AP-26-safe).
@@ -1259,7 +1343,6 @@ def main(argv: list[str] | None = None) -> int:
", ".join(_dropped_colour_claims),
)
- _raw_argv = argv if argv is not None else sys.argv[1:]
args = _parse_args(_raw_argv)
# Refuse a window we cannot build, BEFORE paying for the boot. Everything
@@ -1462,6 +1545,12 @@ def main(argv: list[str] | None = None) -> int:
# finishes, the next boot self-heals the entry.
def _reconcile_autostart_bg() -> None:
try:
+ from jarvis.core.instance import current_instance
+
+ if not current_instance().owns_ambient_duties:
+ # The login autostart entry belongs to the default app; a dev
+ # instance reconciling it would rewrite (or remove) the real one.
+ return
from jarvis.autostart import reconcile_autostart
reconcile_autostart(cfg)
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 76c8d0bb15..62772ba9a7 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -901,12 +901,19 @@ class WebServer:
# ------------------------------------------------------------------
def _register_rest_routes(self, app: FastAPI) -> None:
+ from jarvis.core.instance import current_instance as _ci
+
+ def _instance_name() -> str:
+ return _ci().name
+
cfg = self.cfg
bus = self.bus
@app.get("/api/health")
async def health() -> dict[str, Any]:
- return {"ok": True, "version": __version__}
+ # ``instance`` lets the frontend badge a dev window as such
+ # (``jarvis.core.instance``): "default" or "dev".
+ return {"ok": True, "version": __version__, "instance": _instance_name()}
@app.post("/api/ui/shell-painted", status_code=204, response_model=None)
async def shell_painted() -> Response:
@@ -3317,12 +3324,21 @@ class WebServer:
def _resolve_sessions_db_path(self) -> Path:
"""Absolute path to sessions.db, shared by recorder and board.
- A relative ``[sessions].db_path`` is anchored at the data-dir parent
- (the repo root), never at the process CWD, so every consumer sees the
- SAME database regardless of where the app was launched from.
+ The default lives in ``cfg.memory.data_dir`` itself — the directory
+ every other SQLite store of this app uses (chats, missions, friends) —
+ so a second instance of the app (``jarvis.core.instance``, which points
+ ``memory.data_dir`` at ``data-dev/``) keeps its sessions apart from the
+ default app's. An explicit relative ``[sessions].db_path`` is anchored
+ at the data-dir parent (the repo root, as before), an absolute one is
+ taken as is; neither depends on the process CWD. The shipped default
+ string ``"data/sessions.db"`` (present in every jarvis.toml) IS the
+ default and follows the data dir like an absent key.
"""
section = self._read_sessions_toml_section()
- db_path = Path(str(section.get("db_path", "data/sessions.db")))
+ raw = section.get("db_path")
+ if not raw or Path(str(raw)) == Path("data/sessions.db"):
+ return Path(self.cfg.memory.data_dir) / "sessions.db"
+ db_path = Path(str(raw))
if not db_path.is_absolute():
db_path = Path(self.cfg.memory.data_dir).parent / db_path
return db_path
@@ -3387,7 +3403,19 @@ class WebServer:
tg_cfg = None
dc_cfg = None
integrations = getattr(self.cfg, "integrations", None)
- if integrations is not None:
+ from jarvis.core.instance import current_instance
+
+ if not current_instance().owns_ambient_duties:
+ # A second (dev) instance of the app must not poll the same bot
+ # tokens as the live one — Telegram answers a second getUpdates
+ # poller with 409 and both would answer the user's friends. The
+ # Friends registry still comes up; only the channels stay off.
+ logger.info(
+ "Friends-Stack: chat channels stay off in instance '{}' "
+ "(they belong to the default app)",
+ current_instance().name,
+ )
+ elif integrations is not None:
tg_cfg = getattr(integrations, "telegram", None)
dc_cfg = getattr(integrations, "discord", None)
diff --git a/run-dev.bat b/run-dev.bat
new file mode 100644
index 0000000000..3fd9d263c7
--- /dev/null
+++ b/run-dev.bat
@@ -0,0 +1,34 @@
+@echo off
+REM Personal Jarvis — DEV INSTANCE launcher (Windows).
+REM
+REM Starts a SECOND desktop app beside the regular one, from this same checkout:
+REM "Personal Jarvis Dev" — own data dir (data-dev\), own ports (+100), DEV-badged
+REM icon, no wake word / global hotkeys / chat channels / autostart (those stay
+REM with the regular app). Restart it as often as you like; the regular app and
+REM the coding sessions inside it are never touched.
+REM
+REM Not the same as dev.bat / run.bat --dev (those load the frontend from a Vite
+REM HMR server). This one runs the built frontend exactly like run.bat does.
+REM Same as: set JARVIS_INSTANCE=dev && run.bat
+
+setlocal
+cd /d "%~dp0"
+
+if exist ".venv\Scripts\activate.bat" (
+ call .venv\Scripts\activate.bat
+)
+
+if exist "scripts\check-working-tree.ps1" (
+ powershell -NoProfile -ExecutionPolicy Bypass -File "scripts\check-working-tree.ps1"
+)
+
+if "%1"=="--debug" (
+ set JARVIS_DEBUG=1
+ python -m jarvis.ui.web.launcher --instance dev
+) else if "%1"=="--headless" (
+ python -m jarvis.ui.web.launcher --instance dev --headless
+) else (
+ start "" pythonw -m jarvis.ui.web.launcher --instance dev
+)
+
+endlocal
diff --git a/run-dev.sh b/run-dev.sh
new file mode 100755
index 0000000000..a9b0e6a8fb
--- /dev/null
+++ b/run-dev.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env sh
+# Personal Jarvis - DEV INSTANCE launcher (macOS + Linux). Parity twin of run-dev.bat.
+#
+# Starts a SECOND desktop app beside the regular one, from this same checkout:
+# "Personal Jarvis Dev" - own data dir (data-dev/), own ports (+100), DEV-badged
+# icon, no wake word / global hotkeys / chat channels / autostart (those stay
+# with the regular app). Restart it as often as you like; the regular app and
+# the coding sessions inside it are never touched.
+#
+# Usage: ./run-dev.sh [--debug|--headless]
+# Same as: JARVIS_INSTANCE=dev ./run.sh
+set -u
+cd "$(dirname "$0")" || exit 1
+
+if [ -f ".venv/bin/activate" ]; then
+ # shellcheck disable=SC1091
+ . ".venv/bin/activate"
+fi
+
+if command -v python >/dev/null 2>&1; then
+ PY=python
+elif command -v python3 >/dev/null 2>&1; then
+ PY=python3
+else
+ echo "error: no Python interpreter found on PATH" >&2
+ exit 1
+fi
+
+case "${1:-}" in
+ --debug)
+ JARVIS_DEBUG=1 exec "$PY" -m jarvis.ui.web.launcher --instance dev
+ ;;
+ --headless)
+ exec "$PY" -m jarvis.ui.web.launcher --instance dev --headless
+ ;;
+ *)
+ exec "$PY" -m jarvis.ui.web.launcher --instance dev
+ ;;
+esac
diff --git a/scripts/install_shortcuts.py b/scripts/install_shortcuts.py
index de9ea558c2..75bd13e02e 100644
--- a/scripts/install_shortcuts.py
+++ b/scripts/install_shortcuts.py
@@ -12,8 +12,16 @@ Result:
Both shortcuts point to run.bat in the project folder. run.bat uses
pythonw.exe, so no console window pops up.
+Dev instance (a second, freely restartable desktop app — see
+``jarvis/core/instance.py``):
+
+ python scripts/install_shortcuts.py --dev
+
+ → Desktop\Personal Jarvis Dev.lnk (DEV-badged icon, ``--instance dev``);
+ never touches autostart.
+
Uninstall:
- python scripts/install_shortcuts.py --uninstall
+ python scripts/install_shortcuts.py --uninstall (also removes the Dev link)
"""
from __future__ import annotations
@@ -35,9 +43,17 @@ from jarvis.core.branding import ( # noqa: E402 - script source path above
WINDOWS_APP_USER_MODEL_ID,
WINDOWS_SHORTCUT_FILE_NAME,
)
+from jarvis.core.instance import ( # noqa: E402 - script source path above
+ DEV_INSTANCE_NAME,
+ InstanceIdentity,
+)
ICON_DIR = PROJECT_ROOT / "assets" / "icons"
ICON_PATH = ICON_DIR / "jarvis.ico"
+DEV_INSTANCE = InstanceIdentity(DEV_INSTANCE_NAME)
+DEV_ICON_PATH = ICON_DIR / DEV_INSTANCE.icon_file_name
+DEV_SHORTCUT_NAME = DEV_INSTANCE.windows_shortcut_file_name
+DEV_DESCRIPTION = f"{DEV_INSTANCE.display_name} — second, restartable instance"
RUN_BAT = PROJECT_ROOT / "run.bat"
SHORTCUT_NAME = WINDOWS_SHORTCUT_FILE_NAME
@@ -52,6 +68,10 @@ def desktop_path() -> Path:
return Path(os.environ["USERPROFILE"]) / "Desktop" / SHORTCUT_NAME
+def dev_desktop_path() -> Path:
+ return Path(os.environ["USERPROFILE"]) / "Desktop" / DEV_SHORTCUT_NAME
+
+
def startup_path() -> Path:
return (
Path(os.environ["APPDATA"])
@@ -156,7 +176,7 @@ def _detect_pythonw() -> Path:
)
-def _set_shortcut_app_id(link: Path) -> bool:
+def _set_shortcut_app_id(link: Path, app_id: str = APP_USER_MODEL_ID) -> bool:
"""Best-effort: writes the AppUserModelID into the .lnk property store."""
try:
import pywintypes # type: ignore[import-not-found]
@@ -170,7 +190,7 @@ def _set_shortcut_app_id(link: Path) -> bool:
)
store.SetValue(
pscon.PKEY_AppUserModel_ID,
- propsys.PROPVARIANTType(APP_USER_MODEL_ID),
+ propsys.PROPVARIANTType(app_id),
)
store.Commit()
return True
@@ -188,6 +208,7 @@ def create_shortcut(
icon: Path,
description: str,
window_style: int = 1,
+ app_id: str = APP_USER_MODEL_ID,
) -> None:
"""Creates a .lnk shortcut via PowerShell/WScript.Shell.
@@ -214,7 +235,7 @@ def create_shortcut(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_script],
check=True,
)
- _set_shortcut_app_id(link)
+ _set_shortcut_app_id(link, app_id)
print(f"[ok] Shortcut: {link}")
@@ -255,14 +276,45 @@ def _disable_autostart_via_port() -> None:
make_autostart_manager(detect_capabilities()).uninstall(interactive=True)
+def install_dev_shortcut() -> int:
+ """Desktop shortcut for the DEV instance — icon with the DEV tag, launcher
+ argument ``--instance dev``, its own AUMID; never touches autostart."""
+ try:
+ pythonw = _detect_pythonw()
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 2
+ if not DEV_ICON_PATH.is_file():
+ print(
+ f"Error: {DEV_ICON_PATH} is missing — run scripts/make_dev_icon.py first.",
+ file=sys.stderr,
+ )
+ return 2
+ create_shortcut(
+ dev_desktop_path(),
+ target=pythonw,
+ args=f"-m {LAUNCHER_MODULE} {' '.join(DEV_INSTANCE.launcher_args)}",
+ working_dir=PROJECT_ROOT,
+ icon=DEV_ICON_PATH,
+ description=DEV_DESCRIPTION,
+ window_style=1,
+ app_id=DEV_INSTANCE.windows_aumid,
+ )
+ print(
+ f"\nDouble-clicking '{DEV_SHORTCUT_NAME}' on the desktop starts the dev "
+ "instance beside the regular app (own data dir, ports +100, no wake word)."
+ )
+ return 0
+
+
def uninstall() -> None:
- # Desktop double-click shortcut — this script owns it.
- dp = desktop_path()
- if dp.exists():
- dp.unlink()
- print(f"[rm] {dp}")
- else:
- print(f"[--] not present: {dp}")
+ # Desktop double-click shortcuts — this script owns them.
+ for dp in (desktop_path(), dev_desktop_path()):
+ if dp.exists():
+ dp.unlink()
+ print(f"[rm] {dp}")
+ else:
+ print(f"[--] not present: {dp}")
# Autostart entry — delegate to the port (also clears the persisted toggle
# and any legacy .bat/.lnk names).
_disable_autostart_via_port()
@@ -280,6 +332,14 @@ def main() -> int:
action="store_true",
help="Desktop shortcut only, no autostart",
)
+ parser.add_argument(
+ "--dev",
+ action="store_true",
+ help=(
+ "Create the 'Personal Jarvis Dev' desktop shortcut (second, restartable "
+ "instance) instead of the regular one; never touches autostart"
+ ),
+ )
args = parser.parse_args()
if args.uninstall:
@@ -290,6 +350,9 @@ def main() -> int:
print("Error: only Windows is supported.", file=sys.stderr)
return 1
+ if args.dev:
+ return install_dev_shortcut()
+
try:
pythonw = _detect_pythonw()
except RuntimeError as exc:
diff --git a/scripts/make_dev_icon.py b/scripts/make_dev_icon.py
new file mode 100644
index 0000000000..ffee888f0d
--- /dev/null
+++ b/scripts/make_dev_icon.py
@@ -0,0 +1,102 @@
+"""Render the dev-instance app icon: the mascot with a signal-yellow DEV tag.
+
+ python scripts/make_dev_icon.py
+
+Writes ``jarvis-dev.png`` (256 px) and ``jarvis-dev.ico`` (16…256 px) next to
+the default icon in BOTH icon homes — the in-package copy that ships with the
+code (``jarvis/assets/icons/``) and the build-tool copy (``assets/icons/``).
+``jarvis.core.instance`` names these files; ``jarvis.assets.bundled_app_icon``
+and ``jarvis.ui.icon_utils.project_icon_path`` resolve them for the dev app.
+
+The tag is drawn at 4× and downsampled so it stays crisp at every size. At
+16 px the letters are gone but the yellow corner remains — that is the whole
+point: the two taskbar buttons must be told apart at a glance.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+ROOT = Path(__file__).resolve().parent.parent
+SOURCE_PNG = ROOT / "jarvis" / "assets" / "icons" / "jarvis.png"
+TARGET_DIRS = (ROOT / "jarvis" / "assets" / "icons", ROOT / "assets" / "icons")
+PNG_NAME = "jarvis-dev.png"
+ICO_NAME = "jarvis-dev.ico"
+ICO_SIZES = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
+
+YELLOW = (255, 214, 10, 255)
+INK = (10, 10, 10, 255)
+LABEL = "DEV"
+
+
+def _bold_font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
+ for name in ("segoeuib.ttf", "arialbd.ttf", "DejaVuSans-Bold.ttf", "Arial Bold.ttf"):
+ try:
+ return ImageFont.truetype(name, size)
+ except OSError:
+ continue
+ return ImageFont.load_default()
+
+
+def render(source: Path, size: int = 256) -> Image.Image:
+ scale = 4
+ big = size * scale
+ base = Image.open(source).convert("RGBA").resize((big, big), Image.LANCZOS)
+
+ # Tag geometry (relative to the icon): a rounded pill in the lower-right
+ # corner, wide enough for the word with comfortable padding, on a thin dark
+ # outline so it still separates from a light desktop or a light taskbar.
+ font = _bold_font(int(big * 0.20))
+ probe = ImageDraw.Draw(base)
+ tw = probe.textlength(LABEL, font=font)
+ bbox = font.getbbox(LABEL)
+ th = bbox[3] - bbox[1]
+ pad_x = int(big * 0.045)
+ pad_y = int(big * 0.035)
+ w = int(tw) + 2 * pad_x
+ h = th + 2 * pad_y
+ x1 = big - int(big * 0.03)
+ y1 = big - int(big * 0.03)
+ x0 = x1 - w
+ y0 = y1 - h
+ radius = int(h * 0.28)
+ outline = max(2, int(big * 0.008))
+
+ tag = Image.new("RGBA", (big, big), (0, 0, 0, 0))
+ d = ImageDraw.Draw(tag)
+ d.rounded_rectangle(
+ (x0 - outline, y0 - outline, x1 + outline, y1 + outline),
+ radius=radius + outline,
+ fill=INK,
+ )
+ d.rounded_rectangle((x0, y0, x1, y1), radius=radius, fill=YELLOW)
+ d.text(
+ (x0 + pad_x, y0 + pad_y - bbox[1]),
+ LABEL,
+ font=font,
+ fill=INK,
+ )
+ base.alpha_composite(tag)
+ return base.resize((size, size), Image.LANCZOS)
+
+
+def main() -> int:
+ if not SOURCE_PNG.is_file():
+ print(f"source icon missing: {SOURCE_PNG}", file=sys.stderr)
+ return 1
+ master = render(SOURCE_PNG, 256)
+ for target_dir in TARGET_DIRS:
+ target_dir.mkdir(parents=True, exist_ok=True)
+ png = target_dir / PNG_NAME
+ ico = target_dir / ICO_NAME
+ master.save(png, format="PNG")
+ master.save(ico, format="ICO", sizes=ICO_SIZES)
+ print(f"[ok] {png}\n[ok] {ico}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit/core/test_config_instance.py b/tests/unit/core/test_config_instance.py
new file mode 100644
index 0000000000..dc5a0fdb47
--- /dev/null
+++ b/tests/unit/core/test_config_instance.py
@@ -0,0 +1,62 @@
+"""``load_config`` under a non-default instance: ports shift, the memory data
+dir follows the instance, and the default instance passes through untouched.
+Plus the two store paths that used to assume the data dir is *named* ``data``.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+from jarvis.core import config as cfg
+from jarvis.core.instance import DEV_PORT_OFFSET, INSTANCE_ENV_VAR
+from jarvis.state.chat_store import default_chats_db_path
+
+
+def _toml(tmp_path: Path, body: str) -> Path:
+ path = tmp_path / "jarvis.toml"
+ path.write_text(body, encoding="utf-8")
+ return path
+
+
+def test_default_instance_keeps_configured_ports_and_data_dir(monkeypatch, tmp_path) -> None:
+ monkeypatch.delenv(INSTANCE_ENV_VAR, raising=False)
+ path = _toml(tmp_path, '[ui]\nadmin_api_port = 50000\n[memory]\ndata_dir = "./data"\n')
+ loaded = cfg.load_config(path)
+ assert loaded.ui.admin_api_port == 50000
+ assert loaded.memory.data_dir == "./data"
+
+
+def test_dev_instance_offsets_every_port_from_the_configured_base(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv(INSTANCE_ENV_VAR, "dev")
+ path = _toml(tmp_path, "[ui]\nadmin_api_port = 50000\n[mcp_server]\nhttp_port = 60000\n")
+ loaded = cfg.load_config(path)
+ assert loaded.ui.admin_api_port == 50000 + DEV_PORT_OFFSET
+ assert loaded.mcp_server.http_port == 60000 + DEV_PORT_OFFSET
+ assert loaded.telemetry.metrics_port == 9090 + DEV_PORT_OFFSET
+
+
+def test_dev_instance_offsets_the_packaged_defaults_too(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv(INSTANCE_ENV_VAR, "dev")
+ loaded = cfg.load_config(_toml(tmp_path, ""))
+ assert loaded.ui.admin_api_port == 47821 + DEV_PORT_OFFSET
+
+
+def test_dev_instance_pins_memory_data_dir_to_its_own_directory(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv(INSTANCE_ENV_VAR, "dev")
+ loaded = cfg.load_config(_toml(tmp_path, '[memory]\ndata_dir = "./data"\n'))
+ # DATA_DIR is bound at import (the launcher pins the instance before that);
+ # the override always follows the module's resolved DATA_DIR.
+ assert loaded.memory.data_dir == str(cfg.DATA_DIR)
+
+
+def test_env_override_is_the_base_the_dev_port_offsets_from(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv(INSTANCE_ENV_VAR, "dev")
+ monkeypatch.setenv("JARVIS__UI__ADMIN_API_PORT", "51000")
+ loaded = cfg.load_config(_toml(tmp_path, "[ui]\nadmin_api_port = 50000\n"))
+ assert loaded.ui.admin_api_port == 51000 + DEV_PORT_OFFSET
+
+
+def test_chats_db_lives_inside_the_memory_data_dir() -> None:
+ # Default layout unchanged …
+ assert default_chats_db_path("./data") == Path("./data") / "chats.db"
+ # … and a differently named data dir no longer leaks into ``../data``.
+ assert default_chats_db_path("/x/data-dev") == Path("/x/data-dev") / "chats.db"
diff --git a/tests/unit/core/test_instance.py b/tests/unit/core/test_instance.py
new file mode 100644
index 0000000000..cda41057ee
--- /dev/null
+++ b/tests/unit/core/test_instance.py
@@ -0,0 +1,165 @@
+"""The *instance* contract (``jarvis.core.instance``): two desktop apps from one
+checkout — the default app and a freely restartable ``dev`` app — must never
+collide on data, ports, lock or OS identity, and the dev app must leave the
+ambient duties (wake word, hotkeys, channels, autostart) to the default one.
+"""
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import instance as inst
+from jarvis.core.branding import (
+ PRODUCT_NAME,
+ WINDOWS_APP_USER_MODEL_ID,
+ WINDOWS_BRANDED_LAUNCHER_FILE_NAME,
+ WINDOWS_MUTEX_NAME,
+ WINDOWS_SHORTCUT_FILE_NAME,
+)
+from jarvis.core.instance_data import SEED_FILES, ensure_instance_data_dir
+
+# ---------------------------------------------------------------------------
+# Name resolution
+# ---------------------------------------------------------------------------
+
+
[email protected]("raw", [None, "", " ", "default", "DEFAULT"])
+def test_blank_or_default_means_default(raw) -> None:
+ assert inst.normalize_instance_name(raw) == inst.DEFAULT_INSTANCE_NAME
+
+
[email protected]("raw", ["dev", "Dev", " DEV "])
+def test_dev_is_case_insensitive(raw) -> None:
+ assert inst.normalize_instance_name(raw) == inst.DEV_INSTANCE_NAME
+
+
[email protected]("raw", ["dev2", "prod", "../x", "default app"])
+def test_unknown_name_fails_loudly(raw) -> None:
+ # A typo must not silently boot a second DEFAULT app that fights the live
+ # one over its lock and port.
+ with pytest.raises(inst.InstanceNameError):
+ inst.normalize_instance_name(raw)
+
+
+def test_resolve_reads_the_env_var(monkeypatch) -> None:
+ monkeypatch.delenv(inst.INSTANCE_ENV_VAR, raising=False)
+ assert inst.current_instance().is_default
+ monkeypatch.setenv(inst.INSTANCE_ENV_VAR, "dev")
+ assert inst.current_instance().is_dev
+
+
+def test_select_instance_pins_and_clears_the_env(monkeypatch) -> None:
+ monkeypatch.delenv(inst.INSTANCE_ENV_VAR, raising=False)
+ dev = inst.select_instance("dev")
+ assert dev.is_dev
+ assert inst.resolve_instance().is_dev
+ default = inst.select_instance(None)
+ assert default.is_default
+ assert inst.INSTANCE_ENV_VAR not in __import__("os").environ
+
+
+def test_env_var_is_single_underscore_so_restarts_keep_it() -> None:
+ # The relauncher strips every JARVIS__* (double underscore) config override
+ # on an in-app restart; the instance must survive exactly that restart.
+ assert inst.INSTANCE_ENV_VAR.startswith("JARVIS_")
+ assert not inst.INSTANCE_ENV_VAR.startswith("JARVIS__")
+
+
+# ---------------------------------------------------------------------------
+# Identity
+# ---------------------------------------------------------------------------
+
+
+def test_default_identity_is_the_stable_branding() -> None:
+ d = inst.InstanceIdentity(inst.DEFAULT_INSTANCE_NAME)
+ assert d.display_name == PRODUCT_NAME
+ assert d.windows_aumid == WINDOWS_APP_USER_MODEL_ID
+ assert d.windows_mutex_name == WINDOWS_MUTEX_NAME
+ assert d.windows_shortcut_file_name == WINDOWS_SHORTCUT_FILE_NAME
+ assert d.windows_branded_launcher_file_name == WINDOWS_BRANDED_LAUNCHER_FILE_NAME
+ assert d.data_dir_name == "data"
+ assert d.port_offset == 0 and d.port(47821) == 47821
+ assert d.icon_file_name == inst.DEFAULT_ICON_FILE_NAME
+ assert d.label == "" and d.state_file_suffix == ""
+ assert d.launcher_args == ()
+ assert d.owns_ambient_duties
+
+
+def test_dev_identity_differs_on_every_colliding_surface() -> None:
+ d = inst.InstanceIdentity(inst.DEFAULT_INSTANCE_NAME)
+ v = inst.InstanceIdentity(inst.DEV_INSTANCE_NAME)
+ assert v.display_name == f"{PRODUCT_NAME} Dev"
+ for attr in (
+ "display_name",
+ "compact_name",
+ "slug",
+ "data_dir_name",
+ "icon_file_name",
+ "windows_aumid",
+ "windows_mutex_name",
+ "windows_shortcut_file_name",
+ "windows_branded_launcher_file_name",
+ "linux_wm_class",
+ "linux_desktop_entry_file_name",
+ "macos_bundle_id",
+ "state_file_suffix",
+ ):
+ assert getattr(v, attr) != getattr(d, attr), attr
+ assert v.data_dir_name == "data-dev"
+ assert v.port(47821) == 47821 + inst.DEV_PORT_OFFSET
+ assert v.launcher_args == ("--instance", "dev")
+ assert not v.owns_ambient_duties
+
+
+def test_environ_pins_or_clears_the_variable() -> None:
+ dev = inst.InstanceIdentity("dev")
+ env = dev.environ({"PATH": "x", inst.INSTANCE_ENV_VAR: "stale"})
+ assert env[inst.INSTANCE_ENV_VAR] == "dev" and env["PATH"] == "x"
+ env = inst.InstanceIdentity("default").environ({inst.INSTANCE_ENV_VAR: "dev"})
+ assert inst.INSTANCE_ENV_VAR not in env
+
+
+def test_dev_icons_ship_in_both_icon_homes() -> None:
+ # Rendered by scripts/make_dev_icon.py; the taskbar/tray/dock resolve them.
+ root = Path(inst.__file__).resolve().parents[2]
+ for home in (root / "jarvis" / "assets" / "icons", root / "assets" / "icons"):
+ assert (home / inst.DEV_ICON_FILE_NAME).is_file(), home
+ assert (home / "jarvis-dev.png").is_file(), home
+
+
+# ---------------------------------------------------------------------------
+# Data-dir seeding
+# ---------------------------------------------------------------------------
+
+
+def test_seed_copies_only_the_allowlisted_files(tmp_path: Path) -> None:
+ src = tmp_path / "data"
+ src.mkdir()
+ (src / "setup_state.json").write_text("{}", encoding="utf-8")
+ (src / "identity_card.json").write_text("{}", encoding="utf-8")
+ (src / "sessions.db").write_text("live state, never copied", encoding="utf-8")
+ with sqlite3.connect(src / "chats.db") as db:
+ db.execute("CREATE TABLE t (x)")
+ db.execute("INSERT INTO t VALUES (1)")
+ seeded = ensure_instance_data_dir(tmp_path, inst.InstanceIdentity("dev"))
+ assert sorted(seeded) == ["chats.db", "identity_card.json", "setup_state.json"]
+ dst = tmp_path / "data-dev"
+ assert (dst / "setup_state.json").is_file()
+ assert not (dst / "sessions.db").exists()
+ with sqlite3.connect(dst / "chats.db") as db:
+ assert db.execute("SELECT x FROM t").fetchall() == [(1,)]
+ assert set(seeded) <= set(SEED_FILES)
+
+
+def test_seed_runs_only_once_and_never_for_default(tmp_path: Path) -> None:
+ (tmp_path / "data").mkdir()
+ (tmp_path / "data" / "setup_state.json").write_text("{}", encoding="utf-8")
+ assert ensure_instance_data_dir(tmp_path, inst.InstanceIdentity("default")) == []
+ assert not (tmp_path / "data-default").exists()
+ assert ensure_instance_data_dir(tmp_path, inst.InstanceIdentity("dev")) == ["setup_state.json"]
+ (tmp_path / "data-dev" / "setup_state.json").unlink()
+ # Second start: the directory exists → nothing is re-seeded.
+ assert ensure_instance_data_dir(tmp_path, inst.InstanceIdentity("dev")) == []
+ assert not (tmp_path / "data-dev" / "setup_state.json").exists()
diff --git a/tests/unit/speech/test_pipeline_instance_ambient.py b/tests/unit/speech/test_pipeline_instance_ambient.py
new file mode 100644
index 0000000000..efe000bbd9
--- /dev/null
+++ b/tests/unit/speech/test_pipeline_instance_ambient.py
@@ -0,0 +1,57 @@
+"""A non-default instance of the app (``jarvis.core.instance``) never arms the
+global hotkeys or the wake word — the microphone and the key combos belong to
+the default app. Both arming sites (boot + live keybind change) go through
+``_build_hotkey_bindings``; wake activation goes through ``set_wake_activation``.
+"""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.core.instance import INSTANCE_ENV_VAR
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+def _pipeline() -> SpeechPipeline:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._call_hotkeys = ["f3+f4"]
+ pipe._hangup_hotkeys = ["f1+f2"]
+ pipe._ptt_hotkeys = []
+ pipe._dictate_hotkeys = ["ctrl+alt+d"]
+ pipe._dictate_toggle_hotkeys = []
+ pipe._paste_last_hotkeys = []
+ pipe._dictate_mode = "hold"
+ pipe._wake_plan = None
+ pipe._wake_reload_event = asyncio.Event()
+ return pipe
+
+
+def test_default_instance_arms_the_configured_hotkeys(monkeypatch) -> None:
+ monkeypatch.delenv(INSTANCE_ENV_VAR, raising=False)
+ bindings, edges = _pipeline()._build_hotkey_bindings()
+ assert bindings["call"] == ["f3+f4"]
+ assert bindings["dictate"] == ["ctrl+alt+d"]
+ assert "dictate" in edges
+
+
+def test_dev_instance_arms_no_hotkey_at_all(monkeypatch) -> None:
+ monkeypatch.setenv(INSTANCE_ENV_VAR, "dev")
+ bindings, edges = _pipeline()._build_hotkey_bindings()
+ assert bindings == {"call": [], "hangup": []}
+ assert edges == set()
+
+
+def test_dev_instance_cannot_enable_the_wake_word_live(monkeypatch) -> None:
+ monkeypatch.setenv(INSTANCE_ENV_VAR, "dev")
+ pipe = _pipeline()
+ pipe.set_wake_activation(True)
+ assert pipe._wake_word_enabled is False
+ assert pipe._openwakeword_enabled is False
+ assert pipe._whisper_wake_enabled is False
+
+
+def test_default_instance_wake_activation_is_unchanged(monkeypatch) -> None:
+ monkeypatch.delenv(INSTANCE_ENV_VAR, raising=False)
+ pipe = _pipeline()
+ pipe.set_wake_activation(True)
+ # No plan resident → parks the detectors, but the preference is recorded.
+ assert pipe._wake_word_enabled is True