Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(cli): add --home instance directory selector (#6128)
chengyongru36c36a132466
diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 415131a3c..55c529bbb 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -27,12 +27,15 @@ Use this page when you know what you want to run and need the command shape. For```bashnanobot --helpnanobot --version+nanobot --home ~/.nanobot-work onboardpython -m nanobot --helppython -m nanobot --version````python -m nanobot ...` is useful when the package is installed but the `nanobot` script is not on `PATH`.+`--home <directory>` is a global option; place it before the subcommand. It selects `<directory>/config.json` and the default `<directory>/workspace/`. Explicit `--config` and workspace settings still apply. See [Multiple Instances](./multiple-instances.md) for runtime data locations and port selection. `-h` and `--help` display help.+### Coexisting with Nanobot DesktopThe Python package and Nanobot Desktop keep separate runtimes, configuration,diff --git a/docs/configuration.md b/docs/configuration.mdindex 42b7d3de9..63f21c68a 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -67,7 +67,7 @@ If the WebUI does not expose the option you need, start from the task below. Mos| Add external tools through MCP | `tools.mcpServers.<name>` | Start `nanobot gateway --verbose` and check startup/tool logs | [MCP](#mcp-model-context-protocol) || Tighten tool and network safety | `tools.restrictToWorkspace`, `tools.exec.sandbox`, `tools.ssrfWhitelist`, `channels.*.allowFrom` | Run the same workflow through the channel or CLI you plan to expose | [Security](#security), [Pairing](#pairing) || Tune request timeouts or process concurrency | `NANOBOT_STREAM_IDLE_TIMEOUT_S`, `NANOBOT_MAX_CONCURRENT_REQUESTS` | Start nanobot from the same environment and inspect startup/runtime logs | [Runtime Environment Variables](#runtime-environment-variables) |-| Run multiple isolated bots | separate `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Use the same explicit paths with `nanobot status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |+| Run multiple isolated bots | separate `--home` directories, or `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Place `--home` before the subcommand; use the same instance selectors with `status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) || Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |## Environment Variables for Secretsdiff --git a/docs/multiple-instances.md b/docs/multiple-instances.mdindex 753f1953b..c5a93d5cb 100644--- a/docs/multiple-instances.md+++ b/docs/multiple-instances.md@@ -1,145 +1,52 @@# Multiple Instances-Run multiple nanobot instances simultaneously with separate configs and runtime data. Use `--config` as the main entrypoint. Optionally pass `--workspace` during `onboard` when you want to initialize or update the saved workspace for a specific instance.+Use a separate home directory for each instance. Place `--home` before the subcommand; without it, nanobot uses `~/.nanobot`.## Quick Start-If you want each instance to have its own dedicated workspace from the start, pass both `--config` and `--workspace` during onboarding.--**Initialize instances:**-```bash-# Create separate instance configs and workspaces-nanobot onboard --config ~/.nanobot-telegram/config.json --workspace ~/.nanobot-telegram/workspace-nanobot onboard --config ~/.nanobot-discord/config.json --workspace ~/.nanobot-discord/workspace-nanobot onboard --config ~/.nanobot-feishu/config.json --workspace ~/.nanobot-feishu/workspace+nanobot --home ~/.nanobot-work onboard+nanobot --home ~/.nanobot-work webui --port 8766 --gateway-port 18791```-**Configure each instance:**+Configure this instance's models and channels in WebUI Settings or `~/.nanobot-work/config.json`. Onboarding saves its default workspace as `~/.nanobot-work/workspace`.-Edit `~/.nanobot-telegram/config.json`, `~/.nanobot-discord/config.json`, etc. with different channel settings. The workspace you passed during `onboard` is saved into each config as that instance's default workspace.--**Run instances:**+Use the same home for other commands:```bash-# Check one instance before starting it-nanobot status --config ~/.nanobot-telegram/config.json--# Instance A - Telegram bot-nanobot gateway --config ~/.nanobot-telegram/config.json--# Instance B - Discord bot-nanobot gateway --config ~/.nanobot-discord/config.json--# Instance C - Feishu bot with custom port-nanobot gateway --config ~/.nanobot-feishu/config.json --port 18792+nanobot --home ~/.nanobot-work status+nanobot --home ~/.nanobot-work agent+nanobot --home ~/.nanobot-work gateway --port 18791```-## Path Resolution+Concurrent instances need distinct gateway health ports and WebUI/channel ports. `webui --port` sets the WebUI/WebSocket port; `--gateway-port` sets the health port. For `gateway`, `--port` sets the health port. You can also save these ports in each config. Chat channels should use separate bot credentials.-When using `--config`, nanobot derives its runtime data directory from the config file location. The workspace still comes from `agents.defaults.workspace` unless you override it with `--workspace`.--To open a CLI session against one of these instances locally:--```bash-nanobot agent -c ~/.nanobot-telegram/config.json -m "Hello from Telegram instance"-nanobot agent -c ~/.nanobot-discord/config.json -m "Hello from Discord instance"--# Open the browser workbench for a specific instance-nanobot webui -c ~/.nanobot-telegram/config.json--# Optional one-off workspace override-nanobot agent -c ~/.nanobot-telegram/config.json -w /tmp/nanobot-telegram-test-```+## Path Resolution-> Interactive `nanobot agent` and `nanobot webui` commands with the same `--config` and explicit `--workspace` selectors share one gateway instance. Different selectors produce isolated runtime state and processes. The one-shot and `--classic` agent paths remain direct local executions.--| Component | Resolved From | Example |-|-----------|---------------|---------|-| **Config** | `--config` path | `~/.nanobot-A/config.json` |-| **Workspace** | `--workspace` or config | `~/.nanobot-A/workspace/` |-| **Sessions** | config directory + workspace ID | `~/.nanobot-A/sessions/<workspace-id>/` |-| **Cron Jobs** | workspace directory | `~/.nanobot-A/workspace/cron/` |-| **Media / runtime state** | config directory | `~/.nanobot-A/media/` |--## How It Works--- `--config` selects which config file to load-- By default, the workspace comes from `agents.defaults.workspace` in that config-- If you pass `--workspace`, it overrides the workspace from the config file--## Minimal Setup--1. Copy your base config into a new instance directory.-2. Set a different `agents.defaults.workspace` for that instance.-3. Start the instance with `--config`.--Example config fragment:--```json-{- "agents": {- "defaults": {- "workspace": "~/.nanobot-telegram/workspace"- }- },- "channels": {- "telegram": {- "enabled": true,- "token": "YOUR_TELEGRAM_BOT_TOKEN"- }- },- "gateway": {- "host": "127.0.0.1",- "port": 18790- }-}-```+| Data | Location |+|------|----------|+| Config | `<home>/config.json`, or explicit `--config` |+| Workspace | `<home>/workspace` by default; saved `agents.defaults.workspace` takes precedence; `--workspace` overrides both |+| Sessions | `<config-directory>/sessions/<workspace-id>/` |+| Media, logs, runtime state | Under the config directory |+| Memory, skills, cron jobs | Under the workspace |+| CLI input history | `<home>/history/cli_history` |-The copied base config can keep using the same `modelPresets` and `agents.defaults.modelPreset`. If this instance needs a different model, add another preset and set `agents.defaults.modelPreset` to that preset name.+An explicit `--config` also selects the runtime data directory. Keep each config in its own directory and use separate workspaces to isolate memory, skills, and sessions. Selecting a home does not relocate paths saved in an existing config.-Start separate instances:+For custom config/workspace locations:```bash-nanobot status --config ~/.nanobot-telegram/config.json-nanobot gateway --config ~/.nanobot-telegram/config.json-nanobot gateway --config ~/.nanobot-discord/config.json+nanobot onboard --config ~/bots/work/config.json --workspace ~/work-agent+nanobot webui --config ~/bots/work/config.json --port 8766 --gateway-port 18791```-Each gateway instance also exposes a lightweight HTTP health endpoint on `gateway.host:gateway.port`. By default, the gateway binds to `127.0.0.1`, so the endpoint stays local unless you explicitly set `gateway.host` to a public or LAN-facing address.--`GET /health` reports process liveness and WebSocket channel readiness:--- Returns `200 OK` when the WebSocket channel is disabled or running.-- Returns `503 Service Unavailable` when the WebSocket channel is enabled but not running.--The JSON response includes `status`, `process`, `ready`, and `websocket`.-For example, with the WebSocket channel disabled:--```json-{"status":"ok","process":"alive","ready":true,"websocket":"disabled"}-```--Readiness currently reflects only the WebSocket channel. A successful response does not verify other chat channels, MCP servers, or model provider connectivity.--Other paths return `404`.--Override workspace for one-off runs when needed:--```bash-nanobot gateway --config ~/.nanobot-telegram/config.json --workspace /tmp/nanobot-telegram-test-```+You can also copy an existing config into the new directory and change `agents.defaults.workspace`. Model presets can be reused; select a different `agents.defaults.modelPreset` when needed.-## Common Use Cases+Interactive `agent` and `webui` commands with the same config and explicit workspace selectors share a gateway. Different selectors produce separate runtime state and processes; one-shot and `--classic` agent runs execute directly. Background gateways receive `--home` through their command-line arguments.-- Run separate bots for Telegram, Discord, Feishu, and other platforms-- Keep testing and production instances isolated-- Use different models or providers for different teams-- Serve multiple tenants with separate configs and runtime data+## Health Check-## Notes+Each gateway serves `GET /health` on `gateway.host:gateway.port`, bound to `127.0.0.1` by default. It returns `200` when the WebSocket channel is disabled or running, and `503` when enabled but not running. The JSON fields are `status`, `process`, `ready`, and `websocket`; other paths return `404`.-- Each instance must use a different port if they run at the same time-- Session data follows the active config directory; use a different workspace per instance to isolate memory, skills, and the stable session namespace ID-- `--workspace` overrides the workspace defined in the config file-- Cron jobs are stored in the active workspace; runtime media/state is derived from the config directory+This checks process liveness and WebSocket readiness, not other chat channels, MCP servers, or model connectivity. See [CLI Reference](./cli-reference.md#gateway) for gateway management commands.diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.pyindex 83c2cc795..a361ffb02 100644--- a/nanobot/cli/commands.py+++ b/nanobot/cli/commands.py@@ -111,11 +111,21 @@ def version_callback(value: bool):@app.callback(invoke_without_command=True)def main(ctx: typer.Context,+ home: Path | None = typer.Option(+ None, "--home", help="Instance root directory",+ file_okay=False,+ ),version: bool = typer.Option(None, "--version", "-v", callback=version_callback, is_eager=True),):"""nanobot - Personal AI Assistant."""+ if home is not None:+ from nanobot.config.home import get_selected_home_path, set_home_path++ previous_home = get_selected_home_path()+ set_home_path(home)+ ctx.call_on_close(lambda: set_home_path(previous_home))# Editable/source installs can retain an older generated console script that# imports this Typer app directly instead of ``nanobot.cli.entry``. Keep the# role identity correct until that launcher is regenerated.diff --git a/nanobot/cli/entry.py b/nanobot/cli/entry.pyindex 30fb37b87..860ec48d1 100644--- a/nanobot/cli/entry.py+++ b/nanobot/cli/entry.py@@ -18,6 +18,7 @@ _ROOT_OPTIONS = frozenset("--version","--install-completion","--show-completion",+ "--home",})diff --git a/nanobot/cli/remote.py b/nanobot/cli/remote.pyindex eb765d913..69ea13147 100644--- a/nanobot/cli/remote.py+++ b/nanobot/cli/remote.py@@ -15,6 +15,8 @@ from typing import NoReturnimport typer+from nanobot.config.home import get_home_path+app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.")@@ -190,7 +192,7 @@ def pair(RemoteInspection,)- result = subprocess.run([sys.executable, "-c", _LOCATE, str(Path.home() / ".nanobot/config.json")], capture_output=True, text=True, timeout=8)+ result = subprocess.run([sys.executable, "-c", _LOCATE, str(get_home_path() / "config.json")], capture_output=True, text=True, timeout=8)records = [line.partition("NANOBOT_REMOTE:")[2] for line in result.stdout.splitlines() if "NANOBOT_REMOTE:" in line]candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else []if len(candidates) == 1:diff --git a/nanobot/cli/webui_support.py b/nanobot/cli/webui_support.pyindex 576734439..ce0e3e11b 100644--- a/nanobot/cli/webui_support.py+++ b/nanobot/cli/webui_support.py@@ -368,7 +368,7 @@ def _ensure_local_webui_channel(console.print(" LAN access requires an explicit host change plus a WebUI password in config.")- _confirm_webui_action("Update the local WebUI channel in this config?", yes=yes)+ _confirm_webui_action("Enable the WebUI channel?", yes=yes)if not model.enabled:model.enabled = Truediff --git a/nanobot/config/home.py b/nanobot/config/home.pynew file mode 100644index 000000000..dd862afd5--- /dev/null+++ b/nanobot/config/home.py@@ -0,0 +1,28 @@+"""Default instance paths selected by the global --home option."""++from pathlib import Path++_home_path: Path | None = None+++def set_home_path(path: Path | None) -> None:+ """Select the instance root for the current CLI invocation."""+ global _home_path+ _home_path = path.expanduser().resolve() if path is not None else None+++def get_selected_home_path() -> Path | None:+ """Return the explicit instance root, if one was selected."""+ return _home_path+++def get_home_path() -> Path:+ """Return the selected instance root, or the default ~/.nanobot directory."""+ return _home_path if _home_path is not None else Path.home() / ".nanobot"+++def get_default_workspace() -> str:+ """Keep the portable default unless an instance home was selected."""+ if _home_path is not None:+ return str(get_home_path() / "workspace")+ return "~/.nanobot/workspace"diff --git a/nanobot/config/loader.py b/nanobot/config/loader.pyindex f5bbcefee..ff9a81c84 100644--- a/nanobot/config/loader.py+++ b/nanobot/config/loader.py@@ -10,6 +10,7 @@ from pydantic import BaseModel, ValidationErrorfrom pydantic_settings import SettingsErrorfrom nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issues+from nanobot.config.home import get_home_pathfrom nanobot.config.schema import (Config,_resolve_tool_config_refs, # pyright: ignore[reportPrivateUsage]@@ -36,7 +37,7 @@ def get_config_path() -> Path:"""Get the configuration file path."""if _current_config_path:return _current_config_path- return Path.home() / ".nanobot" / "config.json"+ return get_home_path() / "config.json"def load_config(config_path: Path | None = None) -> Config:diff --git a/nanobot/config/paths.py b/nanobot/config/paths.pyindex 23cafa28d..ec2766697 100644--- a/nanobot/config/paths.py+++ b/nanobot/config/paths.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom pathlib import Path+from nanobot.config.home import get_home_pathfrom nanobot.utils.helpers import ensure_dir@@ -50,22 +51,22 @@ def get_webui_dir() -> Path:def get_workspace_path(workspace: str | Path | None = None) -> Path:"""Resolve and ensure the agent workspace path."""- path = Path(workspace).expanduser() if workspace else Path.home() / ".nanobot" / "workspace"+ path = Path(workspace).expanduser() if workspace else get_home_path() / "workspace"return ensure_dir(path)def is_default_workspace(workspace: str | Path | None) -> bool:"""Return whether a workspace resolves to nanobot's default workspace path."""- current = Path(workspace).expanduser() if workspace is not None else Path.home() / ".nanobot" / "workspace"- default = Path.home() / ".nanobot" / "workspace"+ current = Path(workspace).expanduser() if workspace is not None else get_home_path() / "workspace"+ default = get_home_path() / "workspace"return current.resolve(strict=False) == default.resolve(strict=False)def get_cli_history_path() -> Path:- """Return the shared CLI history file path."""- return Path.home() / ".nanobot" / "history" / "cli_history"+ """Return the selected home's CLI history file path."""+ return get_home_path() / "history" / "cli_history"def get_legacy_sessions_dir() -> Path:- """Return the legacy global session directory used for migration fallback."""- return Path.home() / ".nanobot" / "sessions"+ """Return the selected home's legacy session directory for migration fallback."""+ return get_home_path() / "sessions"diff --git a/nanobot/config/schema.py b/nanobot/config/schema.pyindex 80e42a3ec..c937af5e5 100644--- a/nanobot/config/schema.py+++ b/nanobot/config/schema.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal, castfrom pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict+from nanobot.config.home import get_default_workspacefrom nanobot.config.provider_api_migration import migrate_legacy_provider_apifrom nanobot.config.timezone import detect_system_timezonefrom nanobot.config_base import Base@@ -152,7 +153,7 @@ class ModelPresetConfig(Base):class AgentDefaults(Base):"""Default agent configuration."""- workspace: str = "~/.nanobot/workspace"+ workspace: str = Field(default_factory=get_default_workspace)model_preset: str | None = None # Active preset name — takes precedence over fields belowmodel: str = "anthropic/claude-opus-4-5"provider: str = (diff --git a/nanobot/gateway/runtime.py b/nanobot/gateway/runtime.pyindex 641f5d64f..e6919a185 100644--- a/nanobot/gateway/runtime.py+++ b/nanobot/gateway/runtime.py@@ -22,6 +22,7 @@ from typing import Any, Generator, Literal, castfrom filelock import FileLock+from nanobot.config.home import get_selected_home_pathfrom nanobot.config.paths import get_data_dirfrom nanobot.process_runtime import (ManagedProcessRuntime,@@ -33,7 +34,12 @@ from nanobot.process_runtime import (process_is_running,)-GatewayStartOptions = ProcessStartOptions++@dataclass(frozen=True)+class GatewayStartOptions(ProcessStartOptions):+ """Gateway launch options, including the explicit instance root."""++ home: str | None = NoneGatewayLaunchMode = Literal["foreground", "background", "unknown"]GatewayLifetime = Literal["explicit", "on_demand"]@@ -110,11 +116,15 @@ def build_gateway_command(python_executable: str, options: GatewayStartOptions)python_executable,"-m","nanobot",+ ]+ if options.home is not None:+ command.extend(["--home", options.home])+ command.extend(["gateway","--foreground","--port",str(options.port),- ]+ ])if options.verbose:command.append("--verbose")if options.workspace:@@ -156,6 +166,7 @@ class GatewayInstance:config_path: Pathworkspace: str | Nonepaths: GatewayRuntimePaths+ home: Path | None = None@classmethoddef resolve(@@ -174,6 +185,7 @@ class GatewayInstance:None if resolved_config == _default_config_path() else str(resolved_config))return cls(+ home=get_selected_home_path(),config_path=resolved_config,workspace=resolved_workspace,paths=GatewayRuntimePaths.for_instance(@@ -190,6 +202,7 @@ class GatewayInstance:verbose: bool = False,) -> GatewayStartOptions:return GatewayStartOptions(+ home=str(self.home) if self.home is not None else None,port=port,verbose=verbose,workspace=self.workspace,@@ -199,7 +212,7 @@ class GatewayInstance:)-class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):+class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):"""Manage a background ``nanobot gateway`` process."""service_name = "gateway"@@ -223,14 +236,14 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):sleep=sleep,)- def _build_child_command(self, options: ProcessStartOptions) -> list[str]:+ def _build_child_command(self, options: GatewayStartOptions) -> list[str]:return build_gateway_command(self.python_executable, options)def _transition_lock(self) -> FileLock:"""Serialize long lifecycle transitions without blocking child cleanup."""return FileLock(f"{self.paths.state_path}.transition.lock")- def start_background(self, options: ProcessStartOptions) -> RuntimeResult:+ def start_background(self, options: GatewayStartOptions) -> RuntimeResult:"""Start the gateway detached from the current terminal."""lease = GatewayClientLease(self, kind="gateway-background")while True:@@ -242,7 +255,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):result = self._start_background(options)return RuntimeResult(result.ok, result.message, result.status, promoted)- def start_on_demand(self, options: ProcessStartOptions) -> RuntimeResult:+ def start_on_demand(self, options: GatewayStartOptions) -> RuntimeResult:"""Atomically reuse a gateway or start one owned by local client leases."""lease = GatewayClientLease(self, kind="gateway-start")while True:@@ -256,7 +269,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):lease._mark_ephemeral_locked()return self._start_background(options)- def _start_background(self, options: ProcessStartOptions) -> RuntimeResult:+ def _start_background(self, options: GatewayStartOptions) -> RuntimeResult:result = super()._start_background(options)if not result.ok:return self._result(result)@@ -325,7 +338,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):self._write_state(state)@contextmanager- def foreground_instance(self, options: ProcessStartOptions) -> Generator[None]:+ def foreground_instance(self, options: GatewayStartOptions) -> Generator[None]:"""Publish this foreground gateway while it is available to local clients."""self._claim_current_process(options)try:@@ -333,7 +346,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):finally:self._release_current_process()- def _claim_current_process(self, options: ProcessStartOptions) -> GatewayLaunchMode:+ def _claim_current_process(self, options: GatewayStartOptions) -> GatewayLaunchMode:lease = GatewayClientLease(self, kind="gateway-foreground")pid = os.getpid()while True:@@ -391,7 +404,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):kind="gateway-exit",)._finish_shutdown_locked()- def restart(self, options: ProcessStartOptions, *, timeout_s: int = 20) -> RuntimeResult:+ def restart(self, options: GatewayStartOptions, *, timeout_s: int = 20) -> RuntimeResult:"""Restart an existing gateway without creating a new persistent instance."""with self._transition_lock():with self._lifecycle_lock():diff --git a/tests/cli/test_entry.py b/tests/cli/test_entry.pyindex ca1c1c0f4..8c923cfc1 100644--- a/tests/cli/test_entry.py+++ b/tests/cli/test_entry.py@@ -23,6 +23,8 @@ def test_root_metadata_and_subcommands_keep_the_root_cli() -> None:for args in (["--help"],["--version"],+ ["--home", "./instance", "onboard"],+ ["--home=./instance", "webui"],["--install-completion"],["gateway"],["webui"],diff --git a/tests/cli/test_instance_home.py b/tests/cli/test_instance_home.pynew file mode 100644index 000000000..525698bdb--- /dev/null+++ b/tests/cli/test_instance_home.py@@ -0,0 +1,109 @@+import json+import subprocess+import sys+from pathlib import Path++import pytest+from typer.testing import CliRunner++from nanobot.cli.commands import app+from nanobot.config import home as instance_home+from nanobot.config import loader+from nanobot.config.paths import get_cli_history_path, get_legacy_sessions_dir, get_media_dir+from nanobot.config.schema import Config++[email protected](autouse=True)+def isolate_config(monkeypatch):+ monkeypatch.setattr(loader, "_current_config_path", None)+ monkeypatch.setattr(instance_home, "_home_path", None)+++def test_home_onboard_and_status(tmp_path):+ home = tmp_path / "instance with spaces"+ runner = CliRunner()+ result = runner.invoke(app, ["--home", str(home), "onboard"])+ assert result.exit_code == 0, result.output+ data = json.loads((home / "config.json").read_text(encoding="utf-8"))+ assert Path(data["agents"]["defaults"]["workspace"]) == home / "workspace"+ assert (home / "workspace" / "SOUL.md").is_file()+ result = runner.invoke(app, ["--home", str(home), "status"])+ assert result.exit_code == 0, result.output+ assert str(home) in "".join(result.output.splitlines())+ assert instance_home.get_selected_home_path() is None+++def test_home_explicit_config_and_workspace_take_precedence(tmp_path):+ home = tmp_path / "home"+ config = tmp_path / "other" / "config.json"+ workspace = tmp_path / "project"+ result = CliRunner().invoke(app, [+ "--home", str(home), "onboard", "--config", str(config),+ "--workspace", str(workspace),+ ])+ assert result.exit_code == 0, result.output+ assert not (home / "config.json").exists()+ loaded = loader.load_config(config)+ assert loaded.workspace_path == workspace+ assert loaded.runtime_data_dir == config.parent+++def test_home_paths_and_saved_workspace(tmp_path):+ instance_home.set_home_path(tmp_path)+ assert loader.get_config_path() == tmp_path / "config.json"+ assert Config().workspace_path == tmp_path / "workspace"+ assert get_media_dir() == tmp_path / "media"+ assert get_cli_history_path() == tmp_path / "history" / "cli_history"+ assert get_legacy_sessions_dir() == tmp_path / "sessions"+ config = Config()+ config.agents.defaults.workspace = str(tmp_path / "custom")+ loader.save_config(config)+ assert loader.load_config().workspace_path == tmp_path / "custom"+++def test_installed_entry_dispatch_and_help(tmp_path):+ root = Path(__file__).parents[2]+ for args in (["--home", str(tmp_path), "onboard"], ["-h"], ["--home", str(tmp_path), "status"]):+ result = subprocess.run(+ [sys.executable, "-m", "nanobot", *args], cwd=root,+ capture_output=True, text=True, encoding="utf-8", check=False,+ )+ assert result.returncode == 0, result.stderr+ assert (tmp_path / "config.json").is_file()+++def test_home_rejects_file(tmp_path):+ target = tmp_path / "file"+ target.touch()+ result = CliRunner().invoke(app, ["--home", str(target), "onboard"])+ assert result.exit_code == 2+++def test_home_bare_command_starts_agent_and_restores_selection(monkeypatch, tmp_path):+ from nanobot.cli import entry++ selected = tmp_path / "selected"+ observed = []++ def run_agent(args, *, prog_name):+ observed.append((loader.get_config_path(), Config().workspace_path))++ monkeypatch.setattr(entry, "_run_agent", run_agent)+ result = CliRunner().invoke(app, ["--home", str(selected)])+ assert result.exit_code == 0, result.output+ assert observed == [(selected / "config.json", selected / "workspace")]+ assert instance_home.get_selected_home_path() is None+++def test_gateway_child_receives_home_after_cli_selection_ends(tmp_path):+ from nanobot.gateway import GatewayInstance, build_gateway_command++ home = tmp_path / "instance with spaces"+ instance_home.set_home_path(home)+ instance = GatewayInstance.resolve(config_path=home / "config.json")+ instance_home.set_home_path(None)+ options = instance.start_options(port=18791)+ command = build_gateway_command(sys.executable, options)+ assert command[:5] == [sys.executable, "-m", "nanobot", "--home", str(home)]+ assert command[5] == "gateway"+ assert options.config_path == str(home / "config.json")