Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(init): TUI-style setup wizard with separate embedding/VLM config (#2952)
t0saki7ee826e16590
diff --git a/openviking_cli/server_bootstrap.py b/openviking_cli/server_bootstrap.pyindex 51d96eb69..5ae9a1bda 100644--- a/openviking_cli/server_bootstrap.py+++ b/openviking_cli/server_bootstrap.py@@ -20,6 +20,42 @@ import sysfrom openviking_cli.utils.config import OPENVIKING_CONFIG_ENV+def _config_missing() -> bool:+ """True when no ov.conf resolves through the standard four-level chain."""+ from openviking_cli.utils.config.config_loader import resolve_config_path+ from openviking_cli.utils.config.consts import DEFAULT_OV_CONF++ return resolve_config_path(None, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF) is None+++def _maybe_offer_init() -> None:+ """On an interactive TTY with no config, offer to run the setup wizard.++ Falls through silently in non-interactive contexts (Docker, CI) so the+ server keeps its existing missing-config behavior there.+ """+ try:+ interactive = sys.stdin.isatty() and sys.stdout.isatty()+ except (AttributeError, ValueError):+ interactive = False+ if not interactive or not _config_missing():+ return++ print("No OpenViking configuration found.")+ try:+ answer = input("Run interactive setup now? [Y/n]: ").strip().lower()+ except (EOFError, OSError):+ return+ if answer not in ("", "y", "yes"):+ return++ from openviking_cli.setup_wizard import main as init_main++ code = init_main()+ if code != 0 or _config_missing():+ sys.exit(code or 1)++def main():"""Bootstrap the server while binding a stable execution-level log trace ID."""# Pre-parse --config from sys.argv before any openviking imports,@@ -59,6 +95,9 @@ def main():ingest_app(args=sys.argv[2:], prog_name="openviking-server ingest")return+ if not any(arg in ("-h", "--help", "--version") for arg in sys.argv[1:]):+ _maybe_offer_init()+from openviking.server.bootstrap import main as _real_mainwith bind_log_execution_trace():diff --git a/openviking_cli/setup_wizard.py b/openviking_cli/setup_wizard.pyindex ff9171588..b7a905632 100644--- a/openviking_cli/setup_wizard.py+++ b/openviking_cli/setup_wizard.py@@ -1,7 +1,7 @@"""openviking-server init - interactive setup wizard for OpenViking.Guides users through model selection and configuration, with a focus on-local deployment via Ollama or llama.cpp for macOS / Apple Silicon beginners.+local deployment via Ollama for macOS / Apple Silicon beginners."""from __future__ import annotations@@ -9,6 +9,10 @@ from __future__ import annotationsimport importlibimport jsonimport os+import re+import secrets+import select+import shutilimport subprocessimport sysfrom dataclasses import dataclass@@ -33,6 +37,25 @@ _DEFAULT_CODEX_MODEL = "gpt-5.4"_DEFAULT_KIMI_MODEL = "kimi-code"_DEFAULT_GLM_MODEL = "glm-4.6v"+# Sentinel returned by flows that hand the user off to manual config editing;+# distinguishes "handled elsewhere" from "cancelled" (None).+_CUSTOM_SETUP = object()++# Sentinel for "user chose to skip the VLM" (embedding-only setup).+_SKIP_VLM = object()++# Sentinel for "user navigated back to the previous step" (← key / [0] Back).+_GO_BACK = object()++# rich ships with typer (a core dependency); degrade gracefully without it.+try:+ from rich.console import Console as _RichConsole+ from rich.panel import Panel as _RichPanel++ _console: Any = _RichConsole(highlight=False)+except ImportError: # pragma: no cover+ _console = None+# ---------------------------------------------------------------------------# ANSI helpers (same pattern as doctor.py)# ---------------------------------------------------------------------------@@ -69,8 +92,42 @@ def _cyan(t: str) -> str:# ----------------------------------------------------------------------------def _prompt_choice(prompt: str, options: list[tuple[str, str]], default: int = 1) -> int:- """Display numbered options and return 1-based selection index."""+def _prompt_choice(+ prompt: str,+ options: list[tuple[str, str]],+ default: int = 1,+ *,+ allow_back: bool = False,+) -> int:+ """Display a selectable option list and return the 1-based selection index.++ On an interactive TTY this renders an arrow-key menu (↑/↓ or j/k to move,+ digits to jump, Enter or → to confirm, ← to go back when *allow_back* is+ set). Anywhere else (pipes, tests, dumb terminals) it falls back to the+ classic numbered prompt, where ``0`` means back.++ Returns 0 when *allow_back* is set and the user navigated back.+ """+ if _stdin_stdout_tty() and os.environ.get("TERM", "") != "dumb":+ try:+ import termios+ except ImportError:+ return _prompt_choice_numbered(prompt, options, default, allow_back=allow_back)+ try:+ return _prompt_choice_interactive(prompt, options, default, allow_back=allow_back)+ except (OSError, termios.error):+ pass+ return _prompt_choice_numbered(prompt, options, default, allow_back=allow_back)+++def _prompt_choice_numbered(+ prompt: str,+ options: list[tuple[str, str]],+ default: int = 1,+ *,+ allow_back: bool = False,+) -> int:+ """Numbered fallback selector (non-TTY, pipes, tests)."""print(f"\n {_bold(prompt)}\n")for i, (label, desc) in enumerate(options, 1):marker = " "@@ -78,21 +135,117 @@ def _prompt_choice(prompt: str, options: list[tuple[str, str]], default: int = 1if desc:line += f" {_dim(desc)}"print(line)+ if allow_back:+ print(f" [0] Back {_dim('(previous step)')}")while True:try:raw = input(f"\n Select [{default}]: ").strip()- except EOFError:+ except (EOFError, OSError):return defaultif not raw:return defaulttry:choice = int(raw)+ if allow_back and choice == 0:+ return 0if 1 <= choice <= len(options):return choiceexcept ValueError:pass- print(f" {_red('Please enter a number between 1 and ' + str(len(options)))}")+ low = "0" if allow_back else "1"+ print(f" {_red('Please enter a number between ' + low + ' and ' + str(len(options)))}")+++def _read_menu_key(fd: int) -> str:+ """Read one key press from *fd*, decoding arrow-key escape sequences.++ Reads at the file-descriptor level (``os.read``) — ``sys.stdin`` is+ buffered and its readahead would consume escape-sequence bytes behind+ ``select``'s back.+ """+ data = os.read(fd, 1)+ if data != b"\x1b":+ return data.decode("utf-8", errors="ignore")+ if not select.select([fd], [], [], 0.05)[0]:+ return "\x1b"+ if os.read(fd, 1) != b"[":+ return "\x1b"+ if not select.select([fd], [], [], 0.05)[0]:+ return "\x1b"+ return "\x1b[" + os.read(fd, 1).decode("utf-8", errors="ignore")+++def _prompt_choice_interactive(+ prompt: str,+ options: list[tuple[str, str]],+ default: int = 1,+ *,+ allow_back: bool = False,+) -> int:+ """Arrow-key menu: ↑/↓/j/k move, digits jump, Enter/→ confirm, ← back."""+ import termios+ import tty++ n = len(options)+ idx = max(0, min(n - 1, default - 1))+ out = sys.stdout+ went_back = False++ def render(first: bool) -> None:+ if not first:+ out.write(f"\x1b[{n}A")+ for i, (label, desc) in enumerate(options):+ out.write("\x1b[2K")+ if i == idx:+ line = f" \x1b[1;36m❯ {label}\x1b[0m"+ else:+ line = f" {label}"+ if desc:+ line += f" \x1b[2m{desc}\x1b[0m"+ out.write(line + "\n")+ out.flush()++ hint = "↑/↓ move · enter select"+ if allow_back:+ hint += " · ← back"+ print(f"\n {_bold(prompt)} {_dim(hint)}\n")+ render(True)++ fd = sys.stdin.fileno()+ old_attrs = termios.tcgetattr(fd)+ while True:+ tty.setraw(fd)+ try:+ key = _read_menu_key(fd)+ finally:+ termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)+ if key in ("\r", "\n", "\x04", "\x1b[C"): # Enter / Ctrl-D / → confirm+ break+ if key == "\x03":+ raise KeyboardInterrupt+ if allow_back and key == "\x1b[D": # ← back to previous step+ went_back = True+ break+ if key in ("\x1b[A", "k"):+ idx = (idx - 1) % n+ elif key in ("\x1b[B", "j", "\t"):+ idx = (idx + 1) % n+ elif key.isdigit():+ jump = 9 if key == "0" else int(key) - 1+ if jump < n:+ idx = jump+ render(False)++ # Collapse the menu into a single confirmation line.+ out.write(f"\x1b[{n}A\x1b[0J")+ if went_back:+ out.write(" \x1b[2m← back\x1b[0m\n")+ out.flush()+ return 0+ out.write(f" \x1b[1;36m❯\x1b[0m {options[idx][0]}\n")+ out.flush()+ return idx + 1def _mask_secret(value: str, prefix: int = 7, suffix: int = 4) -> str:@@ -169,7 +322,7 @@ def _prompt_required_input(prompt: str, default: str | None = None, *, mask: bootry:prompt_text = f" {prompt} [{default}]: " if default is not None else f" {prompt}: "raw = reader(prompt_text).strip()- except EOFError:+ except (EOFError, OSError):return default or ""if not raw and default is not None:return default@@ -183,13 +336,45 @@ def _prompt_api_key(prompt: str = "API Key") -> str:return _prompt_required_input(prompt, mask=True)+def _stdin_stdout_tty() -> bool:+ """True when both stdin and stdout are interactive TTYs."""+ try:+ return sys.stdin.isatty() and sys.stdout.isatty()+ except (AttributeError, ValueError):+ return False+++# Environment variables that commonly carry each provider's API key, keyed by+# the internal provider string (BytePlus shares "volcengine").+_PROVIDER_ENV_KEYS: dict[str, list[str]] = {+ "volcengine": ["ARK_API_KEY"],+ "openai": ["OPENAI_API_KEY"],+ "kimi": ["KIMI_API_KEY", "MOONSHOT_API_KEY"],+ "glm": ["GLM_API_KEY", "ZHIPUAI_API_KEY"],+}+++def _prompt_api_key_with_env(env_vars: list[str] | None, prompt: str = "API Key") -> str:+ """Prompt for an API key, offering any matching environment variable first.++ Only engages the env-var shortcut on interactive TTYs so scripted or+ piped runs keep the plain prompt behavior.+ """+ if env_vars and _stdin_stdout_tty():+ for var in env_vars:+ value = os.environ.get(var, "").strip()+ if value and _prompt_confirm(f"Found ${var} ({_mask_secret(value)}). Use it?"):+ return value+ return _prompt_api_key(prompt)++def _prompt_required_int(prompt: str, default: int | None = None) -> int | None:"""Prompt for a required integer value."""while True:try:prompt_text = f" {prompt} [{default}]: " if default is not None else f" {prompt}: "raw = input(prompt_text).strip()- except EOFError:+ except (EOFError, OSError):return defaultif not raw:if default is not None:@@ -207,7 +392,7 @@ def _prompt_confirm(prompt: str, default: bool = True) -> bool:hint = "Y/n" if default else "y/N"try:raw = input(f" {prompt} [{hint}]: ").strip().lower()- except EOFError:+ except (EOFError, OSError):return defaultif not raw:return default@@ -219,6 +404,32 @@ def _configured_hint(enabled: bool) -> str:return "configured" if enabled else _dim("(not configured)")+def _rule(title: str) -> None:+ """Print a section rule (rich when available, plain bold header otherwise)."""+ if _console is not None:+ _console.print()+ _console.rule(f"[bold cyan]{title}[/bold cyan]", style="dim cyan")+ else:+ print(f"\n {_bold(title)}")+++def _print_banner() -> None:+ """Print the wizard banner."""+ if _console is not None:+ _console.print()+ _console.print(+ _RichPanel.fit(+ "[bold cyan]OpenViking[/bold cyan] [bold]Setup[/bold]\n"+ "[dim]Context database for AI agents — data in, context out[/dim]",+ border_style="cyan",+ padding=(0, 2),+ )+ )+ else:+ print(f"\n {_bold('OpenViking Setup')}")+ print(f" {'=' * 16}")++# ---------------------------------------------------------------------------# System info# ---------------------------------------------------------------------------@@ -259,6 +470,35 @@ def _get_system_ram_gb() -> int:return 0+def _parse_size_gb(size_hint: str) -> float:+ """Parse a human size hint like ``~4.7 GB`` or ``~639 MB`` into GB."""+ match = re.search(r"([\d.]+)\s*(GB|MB)", size_hint, re.IGNORECASE)+ if not match:+ return 0.0+ value = float(match.group(1))+ return value / 1024 if match.group(2).upper() == "MB" else value+++def _check_disk_before_pull(required_gb: float) -> bool:+ """Return True when there is enough free disk for a download of *required_gb*.++ When space looks too tight (less than the download plus a 5 GB margin),+ warn and let the user decide.+ """+ if required_gb <= 0:+ return True+ try:+ free_gb = shutil.disk_usage(Path.home()).free / (1024**3)+ except OSError:+ return True+ if free_gb >= required_gb + 5:+ return True+ print(+ f" {_yellow(f'Low disk space: {free_gb:.0f} GB free, download needs ~{required_gb:.0f} GB.')}"+ )+ return _prompt_confirm("Continue anyway?", default=False)++# ---------------------------------------------------------------------------# Ollama interaction (delegates to openviking_cli.utils.ollama)# ---------------------------------------------------------------------------@@ -305,6 +545,33 @@ def _ensure_ollama() -> bool:return result.success+def _ensure_model_pulled(+ model: str,+ size_hint: str,+ ollama_running: bool,+ available_models: list[str],+ *,+ ask: bool = True,+) -> None:+ """Pull *model* via Ollama when missing.++ With ``ask=True`` the user confirms each pull (with a disk-space check);+ ``ask=False`` is for flows where the user already approved the batch.+ """+ if not ollama_running or is_model_available(model, available_models):+ return+ if ask:+ if not _prompt_confirm(f"'{model}' not found locally. Pull now? ({size_hint})"):+ return+ if not _check_disk_before_pull(_parse_size_gb(size_hint)):+ return+ print()+ if not ollama_pull_model(model):+ print(f" {_yellow('Pull failed. You can pull it later: ollama pull ' + model)}")+ else:+ print(f" {_green('OK')} {model} pulled successfully")++def _ensure_codex_auth() -> bool:import importlib@@ -391,8 +658,8 @@ VLM_PRESETS: list[VLMPreset] = [VLMPreset("Qwen 3.5 2B", "qwen3.5:2b", "ollama/qwen3.5:2b", "~2.7 GB", 4),VLMPreset("Qwen 3.5 4B", "qwen3.5:4b", "ollama/qwen3.5:4b", "~3.4 GB", 8),VLMPreset("Qwen 3.5 9B", "qwen3.5:9b", "ollama/qwen3.5:9b", "~6.6 GB", 16),- VLMPreset("Qwen 3.5 27B", "qwen3.5:27b", "ollama/qwen3.5:27b", "~17 GB", 32),- VLMPreset("Qwen 3.5 35B", "qwen3.5:35b", "ollama/qwen3.5:35b", "~24 GB", 48),+ VLMPreset("Qwen 3.6 27B", "qwen3.6:27b", "ollama/qwen3.6:27b", "~17 GB, 256K ctx", 32),+ VLMPreset("Qwen 3.6 35B", "qwen3.6:35b", "ollama/qwen3.6:35b", "~24 GB, 256K ctx", 48),VLMPreset("Qwen 3.5 122B", "qwen3.5:122b", "ollama/qwen3.5:122b", "~81 GB", 128),VLMPreset("Gemma 4 E2B", "gemma4:e2b", "ollama/gemma4:e2b", "~7.2 GB", 16),VLMPreset("Gemma 4 E4B", "gemma4:e4b", "ollama/gemma4:e4b", "~9.6 GB", 16),@@ -418,6 +685,10 @@ QUERY_PLANNER_PRESETS: list[QueryPlannerPreset] = [),]+# Approximate download size of the q8 query-planner models (size_hint above+# carries the parameter count, not the artifact size).+_QUERY_PLANNER_DOWNLOAD_GB = 0.9+# Recommended defaults indexed by RAM tier_RAM_TIERS: list[tuple[int, int, int]] = [# (max_ram_gb, embedding_preset_index, vlm_preset_index)@@ -427,7 +698,7 @@ _RAM_TIERS: list[tuple[int, int, int]] = [(64, 2, 7), # 32-64 GB: qwen3-embedding:8b + gemma4:e4b]_RAM_DEFAULT_EMBED = 2 # ≥64 GB: qwen3-embedding:8b-_RAM_DEFAULT_VLM = 3 # ≥64 GB: qwen3.5:27b+_RAM_DEFAULT_VLM = 3 # ≥64 GB: qwen3.6:27bdef _get_recommended_indices(ram_gb: int) -> tuple[int, int]:@@ -496,8 +767,11 @@ _WIZARD_VLM_OPTIONS: list[tuple[str, str]] = [("Kimi", "(Subscription API Key)"),("GLM", "(Subscription API Key)"),("Custom (OpenAI-compatible)", "(Any OpenAI-compatible endpoint)"),+ ("Local via Ollama", "(no API key, runs on this machine)"),]+_WIZARD_VLM_OLLAMA_CHOICE = 8 # index of "Local via Ollama" in _WIZARD_VLM_OPTIONS+# ---------------------------------------------------------------------------# llama.cpp local embedding presets@@ -572,22 +846,32 @@ def _build_ollama_config(return {"storage": {"workspace": workspace},"embedding": {- "dense": {- "provider": "ollama",- "model": embedding.model,- "api_base": "http://localhost:11434/v1",- "dimension": embedding.dimension,- "input": "text",- },- },- "vlm": {- "provider": "litellm",- "model": vlm.litellm_model,- "api_key": "no-key",- "api_base": "http://localhost:11434",- "temperature": 0.0,- "max_retries": 2,+ "dense": _ollama_dense_config(embedding),},+ "vlm": _ollama_vlm_config(vlm),+ }+++def _ollama_dense_config(embedding: EmbeddingPreset) -> dict[str, Any]:+ """Build the dense-embedding config block for an Ollama-served model."""+ return {+ "provider": "ollama",+ "model": embedding.model,+ "api_base": "http://localhost:11434/v1",+ "dimension": embedding.dimension,+ "input": "text",+ }+++def _ollama_vlm_config(vlm: VLMPreset) -> dict[str, Any]:+ """Build the VLM config block for an Ollama-served model."""+ return {+ "provider": "litellm",+ "model": vlm.litellm_model,+ "api_key": "no-key",+ "api_base": "http://localhost:11434",+ "temperature": 0.0,+ "max_retries": 2,}@@ -727,38 +1011,21 @@ def _write_config(config_dict: dict[str, Any], config_path: Path) -> bool:# ----------------------------------------------------------------------------# Wizard flows+# Shared selection helpers# ----------------------------------------------------------------------------def _wizard_ollama() -> tuple[dict[str, Any] | None, bool]:- """Ollama-based local model setup flow.-- Returns ``(config, ollama_running)`` so later steps (e.g. the query planner)- can reuse the Ollama state instead of re-running the install flow.- """- # Ensure Ollama is installed and running- ollama_running = _ensure_ollama()-- if not ollama_running:- if not _prompt_confirm(- "Continue without Ollama? (config will be generated but models won't be pulled)",- default=False,- ):- return None, ollama_running-- available_models = get_ollama_models() if ollama_running else []-- # System RAM- ram_gb = _get_system_ram_gb()- rec_embed_idx, rec_vlm_idx = _get_recommended_indices(ram_gb)- if ram_gb > 0:- print(f"\n {_dim(f'Detected {ram_gb} GB RAM')}")-- # --- Embedding selection ---+def _select_embedding_preset(+ ollama_running: bool,+ available_models: list[str],+ rec_idx: int,+ *,+ allow_back: bool = False,+) -> EmbeddingPreset | None:+ """Interactive Ollama embedding preset selection. None when the user went back."""embed_options: list[tuple[str, str]] = []for i, p in enumerate(EMBEDDING_PRESETS):- rec = " *" if i == rec_embed_idx else ""+ rec = " *" if i == rec_idx else ""avail = ""if ollama_running and is_model_available(p.model, available_models):avail = _green(" [downloaded]")@@ -769,63 +1036,353 @@ def _wizard_ollama() -> tuple[dict[str, Any] | None, bool]:))- embed_choice = _prompt_choice("Embedding model:", embed_options, default=rec_embed_idx + 1)- embedding = EMBEDDING_PRESETS[embed_choice - 1]+ choice = _prompt_choice(+ "Embedding model — powers semantic search:",+ embed_options,+ default=rec_idx + 1,+ allow_back=allow_back,+ )+ if choice == 0:+ return None+ return EMBEDDING_PRESETS[choice - 1]- # Pull embedding model- if ollama_running and not is_model_available(embedding.model, available_models):- if _prompt_confirm(f"'{embedding.model}' not found locally. Pull now?"):- print()- if not ollama_pull_model(embedding.model):- print(- f" {_yellow('Pull failed. You can pull it later: ollama pull ' + embedding.model)}"- )- else:- print(f" {_green('OK')} {embedding.model} pulled successfully")- # --- VLM selection ---+def _select_vlm_preset(+ ollama_running: bool,+ available_models: list[str],+ rec_idx: int,+ *,+ allow_back: bool = False,+) -> VLMPreset | None:+ """Interactive Ollama VLM preset selection. None when the user went back."""vlm_options: list[tuple[str, str]] = []for i, p in enumerate(VLM_PRESETS):- rec = " *" if i == rec_vlm_idx else ""+ rec = " *" if i == rec_idx else ""avail = ""if ollama_running and is_model_available(p.ollama_model, available_models):avail = _green(" [downloaded]")- vlm_options.append(- (- f"{p.label}",- f"({p.size_hint}){avail}{rec}",- )+ vlm_options.append((f"{p.label}", f"({p.size_hint}){avail}{rec}"))++ choice = _prompt_choice(+ "Vision-language model (VLM) — parses documents & images:",+ vlm_options,+ default=rec_idx + 1,+ allow_back=allow_back,+ )+ if choice == 0:+ return None+ return VLM_PRESETS[choice - 1]+++def _prompt_ollama_vlm(+ *, allow_back: bool = False, current_litellm_model: str | None = None+) -> tuple[dict[str, Any] | None | object, bool | None]:+ """Ollama VLM selection: ensure Ollama, pick a preset, pull it.++ Returns ``(vlm_config, ollama_running)``; ``vlm_config`` is None on cancel+ or ``_GO_BACK`` when the user navigated back from the preset list.+ *current_litellm_model* seeds the preset default when it matches one.+ """+ ollama_running = _ensure_ollama()+ if not ollama_running:+ if not _prompt_confirm("Continue without Ollama?", default=False):+ return None, ollama_running++ available_models = get_ollama_models() if ollama_running else []+ ram_gb = _get_system_ram_gb()+ _, rec_vlm_idx = _get_recommended_indices(ram_gb)+ if current_litellm_model:+ for i, p in enumerate(VLM_PRESETS):+ if p.litellm_model == current_litellm_model:+ rec_vlm_idx = i # default to the currently configured model+ break++ vlm = _select_vlm_preset(ollama_running, available_models, rec_vlm_idx, allow_back=allow_back)+ if vlm is None:+ return _GO_BACK, ollama_running+ _ensure_model_pulled(vlm.ollama_model, vlm.size_hint, ollama_running, available_models)++ return _ollama_vlm_config(vlm), ollama_running+++def _prompt_vlm_api_key(+ provider: str,+ reuse_key: tuple[str, str] | None,+ reuse_prompt: str = "Reuse the embedding API key for the VLM?",+) -> str:+ """Get a VLM API key: offer same-provider reuse first, then env vars, then prompt."""+ if reuse_key and reuse_key[0] == provider and reuse_key[1]:+ if _prompt_confirm(reuse_prompt):+ return reuse_key[1]+ return _prompt_api_key_with_env(_PROVIDER_ENV_KEYS.get(provider))+++def _vlm_option_index_for(current: dict[str, Any]) -> int:+ """1-based ``_WIZARD_VLM_OPTIONS`` index matching an existing VLM config."""+ provider = str(current.get("provider") or "")+ api_base = str(current.get("api_base") or "")+ model = str(current.get("model") or "")+ if provider == "volcengine":+ return 2 if "bytepluses" in api_base else 1+ if provider == "openai-codex":+ return 4+ if provider == "kimi":+ return 5+ if provider == "glm":+ return 6+ if provider == "litellm" and model.startswith("ollama/"):+ return _WIZARD_VLM_OLLAMA_CHOICE+ if provider == "openai":+ return 3 if "api.openai.com" in api_base else 7+ return 1+++def _prompt_cloud_vlm(+ allow_skip: bool = False,+ reuse_key: tuple[str, str] | None = None,+ allow_back: bool = False,+ current: dict[str, Any] | None = None,+) -> tuple[dict[str, Any] | None | object, bool | None]:+ """VLM provider selection (cloud APIs, subscriptions, or local Ollama).++ Returns ``(vlm_config, ollama_running)``; ``vlm_config`` is None on cancel,+ the ``_SKIP_VLM`` sentinel when *allow_skip* is set and taken, or+ ``_GO_BACK`` when *allow_back* is set and the user navigated back.+ ``ollama_running`` is only set when the local Ollama option was taken.+ *reuse_key* is an optional ``(provider, api_key)`` from the embedding step,+ offered for reuse when the VLM provider matches. *current* (the existing+ VLM config, if any) seeds the menu position, model default, and offers to+ keep the existing API key.+ """+ current = current or {}+ options = list(_WIZARD_VLM_OPTIONS)+ if allow_skip:+ options.append(("Skip for now", "(embedding only — add a VLM later)"))+ default_idx = _vlm_option_index_for(current) if current else 1++ # An existing same-provider key takes priority as the reuse candidate.+ if current.get("api_key") and current.get("provider"):+ reuse_key = (str(current["provider"]), str(current["api_key"]))+ reuse_prompt = f"Keep the existing API key ({_mask_secret(str(current['api_key']))})?"+ else:+ reuse_prompt = "Reuse the embedding API key for the VLM?"++ def _default_model(branch_provider: str, fallback: str) -> str:+ if current.get("model") and current.get("provider") == branch_provider:+ return str(current["model"])+ return fallback++ while True:+ vlm_mode = _prompt_choice(+ "VLM provider:", options, default=default_idx, allow_back=allow_back)- vlm_choice = _prompt_choice("Language model (VLM):", vlm_options, default=rec_vlm_idx + 1)- vlm = VLM_PRESETS[vlm_choice - 1]+ if vlm_mode == 0:+ return _GO_BACK, None- # Pull VLM model- if ollama_running and not is_model_available(vlm.ollama_model, available_models):- if _prompt_confirm(f"'{vlm.ollama_model}' not found locally. Pull now?"):- print()- if not ollama_pull_model(vlm.ollama_model):- print(- f" {_yellow('Pull failed. You can pull it later: ollama pull ' + vlm.ollama_model)}"- )- else:- print(f" {_green('OK')} {vlm.ollama_model} pulled successfully")+ if allow_skip and vlm_mode == len(options):+ return _SKIP_VLM, None- return _build_ollama_config(embedding, vlm, _workspace_path()), ollama_running+ if vlm_mode == _WIZARD_VLM_OLLAMA_CHOICE:+ current_ollama_model = (+ str(current["model"])+ if current.get("provider") == "litellm"+ and str(current.get("model", "")).startswith("ollama/")+ else None+ )+ vlm_config, ollama_running = _prompt_ollama_vlm(+ allow_back=True, current_litellm_model=current_ollama_model+ )+ if vlm_config is _GO_BACK:+ continue # back to the provider menu+ return vlm_config, ollama_running+ break-def _wizard_llamacpp() -> tuple[dict[str, Any] | None, bool | None]:- """llama.cpp local embedding setup flow.+ if vlm_mode == 1:+ vlm_choice = _get_cloud_provider_by_label("VolcEngine (火山引擎)")+ print(f"\n {_bold('VolcEngine VLM configuration')}")+ vlm_api_key = _prompt_vlm_api_key(vlm_choice.provider, reuse_key, reuse_prompt)+ if not vlm_api_key:+ print(f" {_red('API key is required')}")+ return None, None+ vlm_model = _prompt_required_input(+ "Model", default=_default_model(vlm_choice.provider, vlm_choice.default_vlm_model)+ )+ vlm_api_base = vlm_choice.default_api_base+ vlm_provider = vlm_choice.provider+ elif vlm_mode == 2:+ vlm_choice = _get_cloud_provider_by_label("BytePlus")+ print(f"\n {_bold('BytePlus VLM configuration')}")+ vlm_api_key = _prompt_vlm_api_key(vlm_choice.provider, reuse_key, reuse_prompt)+ if not vlm_api_key:+ print(f" {_red('API key is required')}")+ return None, None+ vlm_model = _prompt_required_input(+ "Model", default=_default_model(vlm_choice.provider, vlm_choice.default_vlm_model)+ )+ vlm_api_base = vlm_choice.default_api_base+ vlm_provider = vlm_choice.provider+ elif vlm_mode == 3:+ vlm_choice = _get_cloud_provider_by_label("OpenAI")+ print(f"\n {_bold('OpenAI VLM configuration')}")+ vlm_api_key = _prompt_vlm_api_key(vlm_choice.provider, reuse_key, reuse_prompt)+ if not vlm_api_key:+ print(f" {_red('API key is required')}")+ return None, None+ vlm_model = _prompt_required_input(+ "Model", default=_default_model(vlm_choice.provider, vlm_choice.default_vlm_model)+ )+ vlm_api_base = vlm_choice.default_api_base+ vlm_provider = vlm_choice.provider+ elif vlm_mode == 4:+ _ensure_codex_auth()+ print(f"\n {_bold('Codex VLM configuration')}")+ vlm_model = _prompt_required_input(+ "Model", default=_default_model("openai-codex", _DEFAULT_CODEX_MODEL)+ )+ vlm_api_base = _DEFAULT_CODEX_BASE_URL+ vlm_api_key = None+ vlm_provider = "openai-codex"+ elif vlm_mode == 5:+ print(f"\n {_bold('Kimi VLM configuration')}")+ vlm_api_key = _prompt_vlm_api_key("kimi", reuse_key, reuse_prompt)+ if not vlm_api_key:+ print(f" {_red('API key is required')}")+ return None, None+ vlm_model = _prompt_required_input(+ "Model", default=_default_model("kimi", _DEFAULT_KIMI_MODEL)+ )+ vlm_api_base = _DEFAULT_KIMI_BASE_URL+ vlm_provider = "kimi"+ elif vlm_mode == 6:+ print(f"\n {_bold('GLM VLM configuration')}")+ vlm_api_key = _prompt_vlm_api_key("glm", reuse_key, reuse_prompt)+ if not vlm_api_key:+ print(f" {_red('API key is required')}")+ return None, None+ vlm_model = _prompt_required_input(+ "Model", default=_default_model("glm", _DEFAULT_GLM_MODEL)+ )+ vlm_api_base = _DEFAULT_GLM_BASE_URL+ vlm_provider = "glm"+ else:+ print(f"\n {_bold('Custom OpenAI-compatible VLM configuration')}")+ same_openai = current.get("provider") == "openai"+ vlm_api_base = _prompt_required_input(+ "API Base URL",+ default=str(current["api_base"]) if same_openai and current.get("api_base") else None,+ )+ vlm_api_key = _prompt_vlm_api_key("openai", reuse_key, reuse_prompt)+ vlm_model = _prompt_required_input(+ "Model",+ default=str(current["model"]) if same_openai and current.get("model") else None,+ )+ vlm_provider = "openai"- Returns ``(config, ollama_running)``. ``ollama_running`` is ``None`` when the- flow never touched Ollama (cloud or skipped VLM), so the query-planner step- knows it still has to run the install flow itself.+ vlm_config: dict[str, Any] = {+ "provider": vlm_provider,+ "model": vlm_model,+ "api_base": vlm_api_base,+ "temperature": 0.0,+ "max_retries": 2,+ }+ if vlm_api_key:+ vlm_config["api_key"] = vlm_api_key+ return vlm_config, None+++def _cloud_provider_index_for(section: dict[str, Any]) -> int:+ """1-based CLOUD_PROVIDERS index matching an existing config section."""+ provider = str(section.get("provider") or "")+ api_base = str(section.get("api_base") or "")+ for i, p in enumerate(CLOUD_PROVIDERS, 1):+ if p.provider == provider and p.default_api_base == api_base:+ return i+ for i, p in enumerate(CLOUD_PROVIDERS, 1):+ if p.provider == provider:+ return i+ return 1+++def _prompt_cloud_embedding(+ *, allow_back: bool = False, current: dict[str, Any] | None = None+) -> dict[str, Any] | None | object:+ """Cloud embedding provider selection.++ Returns the dense-embedding config dict, ``None`` on cancel,+ ``_CUSTOM_SETUP`` when the user picked manual configuration, or+ ``_GO_BACK`` when *allow_back* is set and the user navigated back.+ *current* (the existing dense config, if any) seeds every default so an+ update run can keep values by just pressing Enter."""- # Ollama is only involved if the user picks an Ollama VLM below; None means- # "not handled yet" so downstream steps can decide whether to ensure it.- ollama_running: bool | None = None+ current = current or {}+ provider_options = [(p.label, "") for p in CLOUD_PROVIDERS]+ provider_options.append(("Other (manual)", ""))+ default_idx = _cloud_provider_index_for(current) if current else 1+ choice = _prompt_choice(+ "Embedding provider:", provider_options, default=default_idx, allow_back=allow_back+ )- # --- Step 1: check / install llama-cpp-python ---+ if choice == 0:+ return _GO_BACK++ if choice > len(CLOUD_PROVIDERS):+ _wizard_custom()+ return _CUSTOM_SETUP++ provider = CLOUD_PROVIDERS[choice - 1]+ same_provider = bool(current) and current.get("provider") == provider.provider++ print(f"\n {_bold('Embedding configuration')}")+ embedding_api_key = ""+ if same_provider and current.get("api_key"):+ masked = _mask_secret(str(current["api_key"]))+ if _prompt_confirm(f"Keep the existing API key ({masked})?"):+ embedding_api_key = str(current["api_key"])+ if not embedding_api_key:+ embedding_api_key = _prompt_api_key_with_env(_PROVIDER_ENV_KEYS.get(provider.provider))+ if not embedding_api_key:+ print(f" {_red('API key is required')}")+ return None++ default_model = (+ str(current["model"])+ if same_provider and current.get("model")+ else provider.default_embedding_model+ )+ embedding_model = _prompt_required_input("Model", default=default_model)+ if (+ same_provider+ and embedding_model == current.get("model")+ and isinstance(current.get("dimension"), int)+ ):+ embedding_dim = current["dimension"]+ print(f" {_dim(f'Dimension: {embedding_dim} (kept from current config)')}")+ elif embedding_model == provider.default_embedding_model:+ embedding_dim = provider.default_embedding_dim+ print(f" {_dim(f'Dimension: {embedding_dim} (auto-filled for {embedding_model})')}")+ else:+ embedding_dim = _prompt_required_int("Dimension", default=provider.default_embedding_dim)+ if embedding_dim is None:+ print(f" {_red('Dimension is required')}")+ return None++ return {+ "provider": provider.provider,+ "model": embedding_model,+ "api_key": embedding_api_key,+ "api_base": (+ str(current["api_base"])+ if same_provider and current.get("api_base")+ else provider.default_api_base+ ),+ "dimension": embedding_dim,+ }+++def _prompt_llamacpp_embedding() -> LocalGGUFPreset | None:+ """llama.cpp embedding setup: ensure runtime, pick a GGUF preset, download it."""print("\n Checking llama-cpp-python...", end=" ", flush=True)if _is_llamacpp_installed():@@ -843,13 +1400,12 @@ def _wizard_llamacpp() -> tuple[dict[str, Any] | None, bool | None]:if not _prompt_confirm("Continue anyway? (config will be generated)", default=False):- return None, ollama_running+ return Noneelse:print(f"\n {_dim('Install later: ' + _PIP_LOCAL_EMBED)}")if not _prompt_confirm("Continue anyway? (config will be generated)", default=False):- return None, ollama_running+ return None- # --- Step 2: select embedding model ---model_options: list[tuple[str, str]] = []for p in LOCAL_GGUF_PRESETS:cached = ""@@ -866,17 +1422,13 @@ def _wizard_llamacpp() -> tuple[dict[str, Any] | None, bool | None]:)model_choice = _prompt_choice("Embedding model:", model_options, default=1)-preset = LOCAL_GGUF_PRESETS[model_choice - 1]- model_name = preset.model_name- dimension = preset.dimension- custom_model_path: str | None = None# Download if not cachedtry:- if not _check_gguf_model_cached(model_name):+ if not _check_gguf_model_cached(preset.model_name):if _prompt_confirm(- f"Model '{model_name}' not downloaded yet. Download now? ({preset.size_hint})"+ f"Model '{preset.model_name}' not downloaded yet. Download now? ({preset.size_hint})"):print(f"\n {_dim('Downloading...')}", end=" ", flush=True)try:@@ -887,8 +1439,8 @@ def _wizard_llamacpp() -> tuple[dict[str, Any] | None, bool | None]:get_local_model_spec,)- spec = get_local_model_spec(model_name)- target = get_local_model_cache_path(model_name)+ spec = get_local_model_spec(preset.model_name)+ target = get_local_model_cache_path(preset.model_name)target.parent.mkdir(parents=True, exist_ok=True)tmp = target.with_suffix(target.suffix + ".part")with requests.get(spec.download_url, stream=True, timeout=(10, 300)) as resp:@@ -917,237 +1469,224 @@ def _wizard_llamacpp() -> tuple[dict[str, Any] | None, bool | None]:except Exception:pass- # --- Step 3: VLM selection ---- print()- vlm_mode = _prompt_choice(- "VLM (language model) setup:",- [- ("Use Ollama for VLM", _dim("(requires Ollama installed)")),- ("Use Cloud API for VLM", _dim("(VolcEngine, BytePlus, OpenAI, etc.)")),- ("Skip VLM", _dim("(embedding only, add VLM later)")),- ],- default=1,- )+ return preset- vlm_config: dict[str, Any] | None = None- if vlm_mode == 1:- # Ollama VLM- ollama_running = _ensure_ollama()- if not ollama_running:- if not _prompt_confirm("Continue without Ollama?", default=False):- return None, ollama_running+# ---------------------------------------------------------------------------+# Wizard flows+# ---------------------------------------------------------------------------- available_models = get_ollama_models() if ollama_running else []- ram_gb = _get_system_ram_gb()- _, rec_vlm_idx = _get_recommended_indices(ram_gb)- vlm_options: list[tuple[str, str]] = []- for i, p in enumerate(VLM_PRESETS):- rec = " *" if i == rec_vlm_idx else ""- avail = ""- if ollama_running and is_model_available(p.ollama_model, available_models):- avail = _green(" [downloaded]")- vlm_options.append((f"{p.label}", f"({p.size_hint}){avail}{rec}"))-- vlm_choice = _prompt_choice("Language model (VLM):", vlm_options, default=rec_vlm_idx + 1)- vlm = VLM_PRESETS[vlm_choice - 1]-- if ollama_running and not is_model_available(vlm.ollama_model, available_models):- if _prompt_confirm(f"'{vlm.ollama_model}' not found locally. Pull now?"):- print()- if not ollama_pull_model(vlm.ollama_model):- print(- f" {_yellow('Pull failed. You can pull it later: ollama pull ' + vlm.ollama_model)}"- )- else:- print(f" {_green('OK')} {vlm.ollama_model} pulled successfully")-- vlm_config = {- "provider": "litellm",- "model": vlm.litellm_model,- "api_key": "no-key",- "api_base": "http://localhost:11434",- "temperature": 0.0,- "max_retries": 2,- }+def _wizard_ollama() -> tuple[dict[str, Any] | None, bool | None]:+ """Ollama-based local model setup flow.- elif vlm_mode == 2:- # Cloud VLM- provider_options = [(p.label, "") for p in CLOUD_PROVIDERS]- provider_options.append(("Custom (OpenAI-compatible)", ""))- choice = _prompt_choice("Cloud provider for VLM:", provider_options, default=1)-- if choice > len(CLOUD_PROVIDERS):- print(f"\n {_bold('Custom OpenAI-compatible VLM configuration')}")- vlm_api_base = _prompt_required_input("API Base URL")- vlm_api_key = _prompt_api_key("VLM API Key")- vlm_model = _prompt_required_input("Vision Model")- vlm_provider = "openai"- else:- provider = CLOUD_PROVIDERS[choice - 1]- vlm_api_key = _prompt_api_key("VLM API Key")- if not vlm_api_key:- print(f" {_red('API key is required')}")- return None, ollama_running- vlm_model = _prompt_required_input("Vision Model")- vlm_api_base = provider.default_api_base- vlm_provider = provider.provider-- vlm_config = {- "provider": vlm_provider,- "model": vlm_model,- "api_base": vlm_api_base,- "temperature": 0.0,- "max_retries": 2,- }- if vlm_api_key:- vlm_config["api_key"] = vlm_api_key-- return (- _build_local_config(- model_name=model_name,- dimension=dimension,- workspace=_workspace_path(),- model_path=custom_model_path,- vlm_config=vlm_config,- ),- ollama_running,+ Returns ``(config, ollama_running)`` so later steps (e.g. the query planner)+ can reuse the Ollama state instead of re-running the install flow.+ """+ # Ensure Ollama is installed and running+ ollama_running = _ensure_ollama()++ if not ollama_running:+ if not _prompt_confirm(+ "Continue without Ollama? (config will be generated but models won't be pulled)",+ default=False,+ ):+ return None, ollama_running++ available_models = get_ollama_models() if ollama_running else []++ # System RAM+ ram_gb = _get_system_ram_gb()+ rec_embed_idx, rec_vlm_idx = _get_recommended_indices(ram_gb)+ if ram_gb > 0:+ print(f"\n {_dim(f'Detected {ram_gb} GB RAM')}")++ # --- Recommended one-shot setup ---+ rec_embed = EMBEDDING_PRESETS[rec_embed_idx]+ rec_vlm = VLM_PRESETS[rec_vlm_idx]+ rec_planner = QUERY_PLANNER_PRESETS[0]+ total_gb = (+ _parse_size_gb(rec_embed.size_hint)+ + _parse_size_gb(rec_vlm.size_hint)+ + _QUERY_PLANNER_DOWNLOAD_GB)+ ram_note = f" (for {ram_gb} GB RAM)" if ram_gb > 0 else ""+ print(f"\n {_bold('Recommended local setup' + ram_note)}")+ print(f" Embedding {rec_embed.model} {_dim('(' + rec_embed.size_hint + ')')}")+ print(f" VLM {rec_vlm.ollama_model} {_dim('(' + rec_vlm.size_hint + ')')}")+ print(f" Query planner {rec_planner.ollama_model} {_dim('(~0.9 GB)')}")+ print(+ f" {_dim(f'Total download ~{total_gb:.0f} GB — already-downloaded models are skipped')}"+ )-def _wizard_cloud() -> dict[str, Any] | None:- """Cloud API model setup flow."""- # Provider selection- provider_options = [(p.label, "") for p in CLOUD_PROVIDERS]- provider_options.append(("Other (manual)", ""))- choice = _prompt_choice("Embedding provider:", provider_options, default=1)+ if _prompt_confirm("Use this recommended setup?"):+ if _check_disk_before_pull(total_gb):+ for model, hint in (+ (rec_embed.model, rec_embed.size_hint),+ (rec_vlm.ollama_model, rec_vlm.size_hint),+ (rec_planner.ollama_model, f"~{_QUERY_PLANNER_DOWNLOAD_GB} GB"),+ ):+ _ensure_model_pulled(model, hint, ollama_running, available_models, ask=False)+ config = _build_ollama_config(rec_embed, rec_vlm, _workspace_path())+ config["query_planner"] = _build_query_planner_config(rec_planner)+ return config, ollama_running+ print(f" {_dim('Pick smaller models below instead.')}")- if choice > len(CLOUD_PROVIDERS):- # Manual / Other- print(f"\n See example config: {_cyan('examples/ov.conf.example')}")- print(f" Edit {_cyan(str(_config_path()))} manually.\n")- return None+ # --- Per-model selection ---+ embedding = _select_embedding_preset(ollama_running, available_models, rec_embed_idx)+ _ensure_model_pulled(embedding.model, embedding.size_hint, ollama_running, available_models)- provider = CLOUD_PROVIDERS[choice - 1]- workspace = _workspace_path()+ vlm = _select_vlm_preset(ollama_running, available_models, rec_vlm_idx)+ _ensure_model_pulled(vlm.ollama_model, vlm.size_hint, ollama_running, available_models)- # Embedding config- print(f"\n {_bold('Embedding configuration')}")- embedding_api_key = _prompt_api_key("API Key")- if not embedding_api_key:- print(f" {_red('API key is required')}")- return None- embedding_model = _prompt_required_input("Model", default=provider.default_embedding_model)- embedding_dim = _prompt_required_int("Dimension", default=provider.default_embedding_dim)- if embedding_dim is None:- print(f" {_red('Dimension is required')}")- return None- embedding_api_base = provider.default_api_base+ return _build_ollama_config(embedding, vlm, _workspace_path()), ollama_running- vlm_mode = _prompt_choice("VLM provider:", _WIZARD_VLM_OPTIONS, default=1)- if vlm_mode == 1:- vlm_choice = _get_cloud_provider_by_label("VolcEngine (火山引擎)")- print(f"\n {_bold('VolcEngine VLM configuration')}")- vlm_api_key = _prompt_api_key("API Key")- if not vlm_api_key:- print(f" {_red('API key is required')}")- return None- vlm_model = _prompt_required_input("Model", default=vlm_choice.default_vlm_model)- vlm_api_base = vlm_choice.default_api_base- vlm_provider = vlm_choice.provider- elif vlm_mode == 2:- vlm_choice = _get_cloud_provider_by_label("BytePlus")- print(f"\n {_bold('BytePlus VLM configuration')}")- vlm_api_key = _prompt_api_key("API Key")- if not vlm_api_key:- print(f" {_red('API key is required')}")- return None- vlm_model = _prompt_required_input("Model", default=vlm_choice.default_vlm_model)- vlm_api_base = vlm_choice.default_api_base- vlm_provider = vlm_choice.provider- elif vlm_mode == 3:- vlm_choice = _get_cloud_provider_by_label("OpenAI")- print(f"\n {_bold('OpenAI VLM configuration')}")- vlm_api_key = _prompt_api_key("API Key")- if not vlm_api_key:- print(f" {_red('API key is required')}")- return None- vlm_model = _prompt_required_input("Model", default=vlm_choice.default_vlm_model)- vlm_api_base = vlm_choice.default_api_base- vlm_provider = vlm_choice.provider- elif vlm_mode == 4:- _ensure_codex_auth()- print(f"\n {_bold('Codex VLM configuration')}")- vlm_model = _prompt_required_input("Model", default=_DEFAULT_CODEX_MODEL)- vlm_api_base = _DEFAULT_CODEX_BASE_URL- vlm_api_key = None- vlm_provider = "openai-codex"- elif vlm_mode == 5:- print(f"\n {_bold('Kimi VLM configuration')}")- vlm_api_key = _prompt_api_key("API Key")- if not vlm_api_key:- print(f" {_red('API key is required')}")- return None- vlm_model = _prompt_required_input("Model", default=_DEFAULT_KIMI_MODEL)- vlm_api_base = _DEFAULT_KIMI_BASE_URL- vlm_provider = "kimi"- elif vlm_mode == 6:- print(f"\n {_bold('GLM VLM configuration')}")- vlm_api_key = _prompt_api_key("API Key")- if not vlm_api_key:- print(f" {_red('API key is required')}")- return None- vlm_model = _prompt_required_input("Model", default=_DEFAULT_GLM_MODEL)- vlm_api_base = _DEFAULT_GLM_BASE_URL- vlm_provider = "glm"- else:- print(f"\n {_bold('Custom OpenAI-compatible VLM configuration')}")- vlm_api_base = _prompt_required_input("API Base URL")- vlm_api_key = _prompt_api_key("API Key")- vlm_model = _prompt_required_input("Model")- vlm_provider = "openai"+def _wizard_two_step() -> tuple[dict[str, Any] | None | object, bool | None]:+ """Step-by-step setup: embedding first, then VLM — each cloud or local.- return _build_cloud_config(- provider,- embedding_api_key,- embedding_model,- embedding_dim,- vlm_model,- workspace,- embedding_api_base=embedding_api_base,- vlm_provider=vlm_provider,- vlm_api_key=vlm_api_key,- vlm_api_base=vlm_api_base,- )+ Returns ``(config, ollama_running)``. ``config`` may also be the+ ``_CUSTOM_SETUP`` sentinel when the user was routed to manual editing, or+ ``_GO_BACK`` when the user backed out to the mode menu.+ """+ while True:+ _rule("Step 1/2 · Embedding — powers semantic search")+ dense, ollama_running = _prompt_embedding_flow(allow_back=True)+ if dense is _GO_BACK:+ return _GO_BACK, None+ if dense is _CUSTOM_SETUP:+ return _CUSTOM_SETUP, None+ if dense is None:+ return None, ollama_running+ print(f"\n {_green('✓')} Embedding: {_summarize_model(dense)}")++ _rule("Step 2/2 · VLM — parses documents & extracts memories")+ reuse_key = None+ if isinstance(dense, dict) and dense.get("api_key"):+ reuse_key = (dense["provider"], dense["api_key"])+ vlm_config, vlm_ollama = _prompt_cloud_vlm(+ allow_skip=True, reuse_key=reuse_key, allow_back=True+ )+ if vlm_config is _GO_BACK:+ continue # back to Step 1+ if vlm_config is None:+ return None, ollama_running+ if vlm_ollama is not None:+ ollama_running = vlm_ollama++ if vlm_config is _SKIP_VLM:+ print(f"\n {_green('✓')} VLM: {_dim('skipped — add one later with init')}")+ else:+ print(f"\n {_green('✓')} VLM: {_summarize_model(vlm_config)}")++ config: dict[str, Any] = {+ "storage": {"workspace": _workspace_path()},+ "embedding": {"dense": dense},+ }+ if vlm_config is not _SKIP_VLM:+ config["vlm"] = vlm_config+ return config, ollama_running-def _wizard_server() -> dict[str, Any] | None:- """Prompt for server host binding and root_api_key (when remote)."""- print(f"\n {_bold('Server binding')}")- print(f" {_dim('Local: only this machine can reach the server.')}")- print(f" {_dim('Remote: bind to 0.0.0.0 — required for Docker / LAN access.')}")+def _wizard_cloud() -> tuple[dict[str, Any] | None | object, bool | None]:+ """Cloud API model setup flow: embedding first, then VLM.+ Returns ``(config, ollama_running)``. ``config`` may also be the+ ``_CUSTOM_SETUP`` sentinel when the user was routed to manual editing.+ """+ dense = _prompt_cloud_embedding()+ if dense is _CUSTOM_SETUP:+ return _CUSTOM_SETUP, None+ if dense is None:+ return None, None++ reuse_key = None+ if isinstance(dense, dict) and dense.get("api_key"):+ reuse_key = (dense["provider"], dense["api_key"])+ vlm_config, ollama_running = _prompt_cloud_vlm(reuse_key=reuse_key)+ if vlm_config is None:+ return None, ollama_running++ config: dict[str, Any] = {+ "storage": {"workspace": _workspace_path()},+ "embedding": {"dense": dense},+ "vlm": vlm_config,+ }+ return config, ollama_running+++def _wizard_server(current: dict[str, Any] | None = None) -> dict[str, Any] | None:+ """Prompt for server binding, port, and auth (root API key when remote).++ Auth mode is auto-detected by the server from ``root_api_key``: setting a+ key switches to ``api_key`` mode, no key means ``dev`` mode (which the+ server only permits on localhost) — so this step never writes+ ``auth_mode`` explicitly. *current* (the existing server config, if any)+ seeds all defaults so an update run can keep values by pressing Enter.+ """+ current = current or {}+ _rule("Server & auth")+ if current:+ print(f" {_dim('Current: ' + _summarize_server(current))}")+ print(f" {_dim('Local: only this machine can reach the server (no auth, dev mode).')}")+ print(f" {_dim('Remote: bind to 0.0.0.0 for Docker / LAN access — requires API-key auth.')}")++ is_remote_now = str(current.get("host") or "127.0.0.1") not in (+ "127.0.0.1",+ "localhost",+ "::1",+ )mode = _prompt_choice("Bind server host to:",[- ("Local (127.0.0.1)", _dim("(default, safer)")),- ("Remote (0.0.0.0)", _dim("(required for Docker / remote access)")),+ ("Local (127.0.0.1)", "(default, safer — no auth needed)"),+ ("Remote (0.0.0.0)", "(Docker / remote access — root API key required)"),],- default=1,+ default=2 if is_remote_now else 1,)+ try:+ port_default = int(current.get("port") or 1933)+ except (TypeError, ValueError):+ port_default = 1933+ port = _prompt_required_int("Port", default=port_default)+ if port is None:+ port = port_default+if mode == 1:- return {"host": "127.0.0.1"}+ return {"host": "127.0.0.1", "port": port}- print(f"\n {_bold('Remote binding requires a root API key.')}")- print(f" {_dim('Clients must send this key as a Bearer token to authenticate.')}")- root_api_key = _prompt_api_key("Root API Key")- if not root_api_key:- print(f" {_red('Root API key is required for remote binding')}")- return None- return {"host": "0.0.0.0", "root_api_key": root_api_key}+ print(f"\n {_dim('Non-local binding switches auth to api_key mode: every client must send')}")+ print(f" {_dim('the root API key as a Bearer token (Authorization: Bearer <key>).')}")++ existing_key = str(current.get("root_api_key") or "")+ key_options: list[tuple[str, str]] = []+ if existing_key:+ key_options.append(("Keep existing key", f"({_mask_secret(existing_key)})"))+ key_options.append(+ ("Generate one for me", "(recommended — 64-char random key, shown once below)")+ )+ key_options.append(("Enter my own", ""))++ key_source = _prompt_choice("Root API key:", key_options, default=1)+ offset = 1 if existing_key else 0++ if existing_key and key_source == 1:+ root_api_key = existing_key+ elif key_source == 1 + offset:+ root_api_key = secrets.token_hex(32)+ print(f"\n {_green('Generated root API key — copy it now, clients need it:')}")+ print(f"\n {_bold(root_api_key)}\n")+ print(f" {_dim('It is also saved in ov.conf (server.root_api_key).')}")+ print(f" {_dim('Clients authenticate with: Authorization: Bearer <this key>')}")+ else:+ root_api_key = _prompt_api_key("Root API Key")+ if not root_api_key:+ print(f" {_red('Root API key is required for remote binding')}")+ return None++ return {"host": "0.0.0.0", "port": port, "root_api_key": root_api_key}def _wizard_query_planner(config_dict: dict[str, Any], ollama_running: bool | None = None) -> None:@@ -1162,7 +1701,10 @@ def _wizard_query_planner(config_dict: dict[str, Any], ollama_running: bool | NoMutates *config_dict* in place to add ``query_planner``. Prompt selection isresolved at retrieval time from the configured model name."""- print(f"\n {_bold('Query planner (optional)')}")+ if "query_planner" in config_dict:+ return # already configured (e.g. by the recommended Ollama setup)++ _rule("Query planner (optional)")print(f" {_dim('A small local model that plans retrieval before search — skips')}")print(f" {_dim('lookups for small talk and emits focused queries otherwise, saving tokens.')}")@@ -1191,14 +1733,12 @@ def _wizard_query_planner(config_dict: dict[str, Any], ollama_running: bool | Nochoice = _prompt_choice("Query planner model:", options, default=1)preset = QUERY_PLANNER_PRESETS[choice - 1]- if ollama_running and not is_model_available(preset.ollama_model, available_models):- if _prompt_confirm(f"'{preset.ollama_model}' not found locally. Pull now?"):- print()- if not ollama_pull_model(preset.ollama_model):- pull_hint = "Pull failed. You can pull it later: ollama pull "- print(f" {_yellow(pull_hint + preset.ollama_model)}")- else:- print(f" {_green('OK')} {preset.ollama_model} pulled successfully")+ _ensure_model_pulled(+ preset.ollama_model,+ f"~{_QUERY_PLANNER_DOWNLOAD_GB} GB",+ bool(ollama_running),+ available_models,+ )config_dict["query_planner"] = _build_query_planner_config(preset)@@ -1227,38 +1767,256 @@ def _wizard_custom() -> dict[str, Any] | None:return None+# ---------------------------------------------------------------------------+# Partial reconfiguration of an existing ov.conf+# ---------------------------------------------------------------------------+++def _prompt_embedding_flow(+ *, allow_back: bool = False, current: dict[str, Any] | None = None+) -> tuple[dict[str, Any] | None | object, bool | None]:+ """Embedding selection across all backends (main flow and section updates).++ Returns ``(dense_config, ollama_running)``; ``dense_config`` is None on+ cancel, the ``_CUSTOM_SETUP`` sentinel for manual editing, or ``_GO_BACK``+ when *allow_back* is set and the user backed out of the backend menu.+ *current* (the existing dense config, if any) seeds all defaults.+ """+ current = current or {}+ backend_default = {"ollama": 2, "local": 3}.get(str(current.get("provider") or ""), 1)+ while True:+ choice = _prompt_choice(+ "Embedding setup:",+ [+ ("Cloud API", "(VolcEngine, BytePlus, OpenAI)"),+ ("Local via Ollama", "(no API key, runs on this machine)"),+ ("Lightweight CPU embedding", "(llama.cpp, ~24 MB, no Ollama needed)"),+ ],+ default=backend_default,+ allow_back=allow_back,+ )++ if choice == 0:+ return _GO_BACK, None++ if choice == 1:+ dense = _prompt_cloud_embedding(allow_back=True, current=current)+ if dense is _GO_BACK:+ continue # back to the backend menu+ return dense, None++ if choice == 2:+ ollama_running = _ensure_ollama()+ if not ollama_running:+ if not _prompt_confirm("Continue without Ollama?", default=False):+ return None, ollama_running+ available_models = get_ollama_models() if ollama_running else []+ ram_gb = _get_system_ram_gb()+ rec_idx, _ = _get_recommended_indices(ram_gb)+ if current.get("provider") == "ollama":+ for i, p in enumerate(EMBEDDING_PRESETS):+ if p.model == current.get("model"):+ rec_idx = i # default to the currently configured model+ break+ preset = _select_embedding_preset(+ ollama_running, available_models, rec_idx, allow_back=True+ )+ if preset is None:+ continue # back to the backend menu+ _ensure_model_pulled(preset.model, preset.size_hint, ollama_running, available_models)+ return _ollama_dense_config(preset), ollama_running++ gguf = _prompt_llamacpp_embedding()+ if gguf is None:+ return None, None+ return {+ "provider": "local",+ "model": gguf.model_name,+ "dimension": gguf.dimension,+ }, None+++def _update_existing_config(config_path: Path, section: str) -> int:+ """Update a single section (vlm / embedding / server) of an existing ov.conf."""+ try:+ data = json.loads(config_path.read_text(encoding="utf-8-sig"))+ except (OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:+ print(f" {_red(f'Cannot read existing config: {exc}')}")+ print(f" {_dim('Fix or remove the file, then re-run `openviking-server init`.')}")+ return 1+ if not isinstance(data, dict):+ print(f" {_red('Existing config is not a JSON object; cannot update in place.')}")+ return 1++ if section == "vlm":+ current_vlm = _config_section(data, "vlm")+ print(f"\n Current VLM: {_summarize_model(current_vlm)}")+ vlm_config, _ = _prompt_cloud_vlm(current=current_vlm)+ if vlm_config is None:+ print("\n Setup cancelled.\n")+ return 0+ old_summary, new_summary = _summarize_model(current_vlm), _summarize_model(vlm_config)+ data["vlm"] = vlm_config+ elif section == "embedding":+ old_dense = _config_section(data, "embedding", "dense")+ old_dim = old_dense.get("dimension")+ print(f"\n Current embedding: {_summarize_model(old_dense)}")+ dense, _ = _prompt_embedding_flow(current=old_dense)+ if dense is _CUSTOM_SETUP:+ return 0+ if dense is None:+ print("\n Setup cancelled.\n")+ return 0+ if old_dim and dense.get("dimension") != old_dim:+ print(+ f"\n {_yellow('Embedding dimension changes from ' + str(old_dim) + ' to ' + str(dense.get('dimension')) + '.')}"+ )+ print(+ f" {_yellow('Existing vector indexes become unusable — data must be re-ingested.')}"+ )+ if not _prompt_confirm("Continue?", default=False):+ print("\n Setup cancelled.\n")+ return 0+ old_summary, new_summary = _summarize_model(old_dense), _summarize_model(dense)+ data.setdefault("embedding", {})["dense"] = dense+ else: # server+ current_server = _config_section(data, "server")+ server_dict = _wizard_server(current=current_server)+ if server_dict is None:+ print("\n Setup cancelled.\n")+ return 0+ old_summary, new_summary = (+ _summarize_server(current_server),+ _summarize_server(server_dict),+ )+ data["server"] = server_dict++ print(f"\n {_bold('Change:')} {old_summary}")+ print(f" {_cyan('→')} {new_summary}")++ if not _prompt_confirm("\n Save configuration?"):+ print("\n Setup cancelled.\n")+ return 0+ if not _write_config(data, config_path):+ return 1++ print(f" {_green('OK')} Configuration updated\n")+ _post_save_actions()+ return 0+++# ---------------------------------------------------------------------------+# Post-save actions+# ---------------------------------------------------------------------------+++def _post_save_actions() -> None:+ """Offer to validate the fresh config and start the server right away."""+ if _prompt_confirm("Validate the setup now? (runs `openviking-server doctor`)"):+ try:+ from openviking_cli.doctor import run_doctor++ run_doctor()+ except Exception as exc:+ print(f" {_yellow(f'doctor failed to run: {exc}')}")++ if _prompt_confirm("Start the server now?", default=False):+ # Replace the wizard process with the server so Ctrl-C etc. behave+ # exactly as a direct `openviking-server` invocation.+ os.execv(sys.executable, [sys.executable, "-m", "openviking_cli.server_bootstrap"])++# ---------------------------------------------------------------------------# Main orchestrator# ---------------------------------------------------------------------------+def _summarize_model(section: dict[str, Any]) -> str:+ """One-line, secret-free description of a model config block."""+ if not section:+ return _dim("(not configured)")+ provider = section.get("provider", "?")+ model = section.get("model", "?")+ text = f"{provider} · {model}"+ if section.get("dimension"):+ text += f" ({section['dimension']}d)"+ return text+++def _summarize_server(server: dict[str, Any]) -> str:+ """One-line, secret-free description of the server config block."""+ if not server:+ return _dim("(defaults: 127.0.0.1:1933 · auth dev)")+ host = server.get("host", "127.0.0.1")+ port = server.get("port", 1933)+ auth = "api_key (root key set)" if server.get("root_api_key") else "dev (no auth)"+ return f"{host}:{port} · auth {auth}"+++def _config_section(data: dict[str, Any], *keys: str) -> dict[str, Any]:+ """Safely walk nested dict keys, returning {} on any non-dict hop."""+ node: Any = data+ for key in keys:+ if not isinstance(node, dict):+ return {}+ node = node.get(key)+ return node if isinstance(node, dict) else {}+++def _load_config_data(config_path: Path) -> dict[str, Any] | None:+ """Best-effort read of the existing ov.conf; None when unreadable."""+ try:+ data = json.loads(config_path.read_text(encoding="utf-8-sig"))+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):+ return None+ return data if isinstance(data, dict) else None+++def _print_current_config(data: dict[str, Any]) -> None:+ """Show the non-secret parts of the existing configuration."""+ print(f"\n {_bold('Current configuration')}")+ print(f" Embedding: {_summarize_model(_config_section(data, 'embedding', 'dense'))}")+ print(f" VLM: {_summarize_model(_config_section(data, 'vlm'))}")+ print(f" Query planner: {_summarize_model(_config_section(data, 'query_planner'))}")+ print(f" Server: {_summarize_server(_config_section(data, 'server'))}")++def run_init() -> int:"""Run the interactive setup wizard."""config_path = _config_path()workspace = _workspace_path()- print(f"\n {_bold('OpenViking Setup')}")- print(f" {'=' * 16}\n")+ _print_banner()print(f" {_dim(f'Data will be stored under {workspace} unless you edit ov.conf later.')}\n")- # Check for existing config+ # Existing config: show what is configured and offer section-level updates+ # instead of forcing a redo.if config_path.exists():print(f" {_yellow('Existing config found:')} {config_path}")- if not _prompt_confirm("Overwrite? (current config will be backed up as .bak)"):+ data = _load_config_data(config_path)+ vlm_now = emb_now = server_now = ""+ if data is not None:+ _print_current_config(data)+ vlm_now = f"(now: {_summarize_model(_config_section(data, 'vlm'))})"+ emb_now = f"(now: {_summarize_model(_config_section(data, 'embedding', 'dense'))})"+ server_now = f"(now: {_summarize_server(_config_section(data, 'server'))})"+ action = _prompt_choice(+ "What would you like to do?",+ [+ ("Start over", "(full setup, current config backed up as .bak)"),+ ("Update VLM", vlm_now),+ ("Update embedding", emb_now),+ ("Update server & auth", server_now),+ ("Cancel", ""),+ ],+ default=1,+ )+ if action == 5:print(" Setup cancelled.\n")return 0-- # Deployment mode- mode = _prompt_choice(- "Choose setup mode:",- [- ("Cloud API", "(VolcEngine, BytePlus, OpenAI, etc.)"),- ("Local embedding via llama.cpp", "(CPU embedding, no GPU required)"),- ("Local models via Ollama", "(recommended for macOS / Apple Silicon)"),- ("Custom", "(manual editing)"),- ],- default=1,- )+ if action in (2, 3, 4):+ section = {2: "vlm", 3: "embedding", 4: "server"}[action]+ return _update_existing_config(config_path, section)config_dict: dict[str, Any] | None = None# Tracks whether Ollama was already set up by the chosen mode, so the query@@ -1266,15 +2024,34 @@ def run_init() -> int:# means the mode never touched Ollama (e.g. Cloud).ollama_running: bool | None = None- if mode == 1:- config_dict = _wizard_cloud()- elif mode == 2:- config_dict, ollama_running = _wizard_llamacpp()- elif mode == 3:- config_dict, ollama_running = _wizard_ollama()- else:- _wizard_custom()- return 0+ # Setup mode; ← inside step-by-step returns here.+ while True:+ mode = _prompt_choice(+ "Choose setup mode:",+ [+ (+ "Step-by-step setup",+ "(pick embedding & VLM separately — cloud, local, or mixed)",+ ),+ ("Recommended local setup", "(all-Ollama, sized to your RAM, one confirm)"),+ ("Manual", "(edit ov.conf directly)"),+ ],+ default=1,+ )++ if mode == 1:+ result, ollama_running = _wizard_two_step()+ if result is _GO_BACK:+ continue # back to the mode menu+ if result is _CUSTOM_SETUP:+ return 0+ config_dict = result # type: ignore[assignment]+ elif mode == 2:+ config_dict, ollama_running = _wizard_ollama()+ else:+ _wizard_custom()+ return 0+ breakif config_dict is None:print("\n Setup cancelled.\n")@@ -1288,18 +2065,18 @@ def run_init() -> int:return 0config_dict["server"] = server_dict- # Summary+ # Summary — providers/models/dimensions are shown, secrets never are.emb = config_dict.get("embedding", {}).get("dense", {})vlm = config_dict.get("vlm", {})- print(f"\n {_bold('Summary:')}")- print(f" Embedding: {_configured_hint(bool(emb))}")+ _rule("Summary")+ print(f" Embedding: {_summarize_model(emb)}")if emb.get("model_path"):print(" Model path: custom local model (hidden)")- vlm_summary = _configured_hint(bool(vlm))- print(f" VLM: {vlm_summary}")- print(f" Query planner: {_configured_hint(bool(config_dict.get('query_planner')))}")- print(f" Server: bound to {server_dict['host']}")+ print(f" VLM: {_summarize_model(vlm)}")+ planner = config_dict.get("query_planner", {})+ print(f" Query planner: {_summarize_model(planner)}")+ print(f" Server: {_summarize_server(server_dict)}")if server_dict.get("root_api_key"):print(" Root API key: configured (hidden)")print(" Workspace: configured (hidden)")@@ -1323,6 +2100,8 @@ def run_init() -> int:print(f" Validate setup: {_cyan('openviking-server doctor')}")print()+ _post_save_actions()+return 0diff --git a/tests/cli/test_setup_wizard.py b/tests/cli/test_setup_wizard.pyindex 8e767ed01..0b9260fd6 100644--- a/tests/cli/test_setup_wizard.py+++ b/tests/cli/test_setup_wizard.py@@ -7,9 +7,12 @@ import osfrom unittest.mock import MagicMock, patchfrom openviking_cli.setup_wizard import (+ _CUSTOM_SETUP,_DEFAULT_CODEX_MODEL,_DEFAULT_GLM_MODEL,_DEFAULT_KIMI_MODEL,+ _GO_BACK,+ _SKIP_VLM,CLOUD_PROVIDERS,EMBEDDING_PRESETS,LOCAL_GGUF_PRESETS,@@ -25,12 +28,17 @@ from openviking_cli.setup_wizard import (_mask_secret,_masked_input,_next_backup_path,+ _parse_size_gb,_prompt_api_key,+ _prompt_api_key_with_env,_prompt_required_input,_prompt_required_int,+ _update_existing_config,_wizard_cloud,+ _wizard_ollama,_wizard_query_planner,_wizard_server,+ _wizard_two_step,_workspace_path,_write_config,run_init,@@ -199,7 +207,7 @@ class TestConfigBuilding:return_value=1024,):with patch("openviking_cli.setup_wizard._ensure_codex_auth", return_value=True):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["storage"]["workspace"] == _workspace_path()@@ -225,7 +233,13 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=1536,):- config = _wizard_cloud()+ # Same provider on both sides → decline the key-reuse offer+ # so the VLM key comes from the prompt sequence.+ with patch(+ "openviking_cli.setup_wizard._prompt_confirm",+ return_value=False,+ ):+ config, _ = _wizard_cloud()assert config is not Noneassert config["storage"]["workspace"] == _workspace_path()@@ -251,7 +265,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=1536,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["storage"]["workspace"] == _workspace_path()@@ -278,7 +292,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=1536,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["storage"]["workspace"] == _workspace_path()@@ -305,7 +319,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=1024,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["vlm"]["provider"] == "kimi"@@ -332,7 +346,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=1024,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["vlm"]["provider"] == "glm"@@ -371,7 +385,7 @@ class TestConfigBuilding:return_value=CLOUD_PROVIDERS[0].default_embedding_dim,) as prompt_int:with patch("openviking_cli.setup_wizard._ensure_codex_auth", return_value=True):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["embedding"]["dense"]["model"] == CLOUD_PROVIDERS[0].default_embedding_model@@ -379,9 +393,8 @@ class TestConfigBuilding:assert config["vlm"]["model"] == _DEFAULT_CODEX_MODELprompt_input.assert_any_call("Model", default=CLOUD_PROVIDERS[0].default_embedding_model)prompt_input.assert_any_call("Model", default=_DEFAULT_CODEX_MODEL)- prompt_int.assert_called_once_with(- "Dimension", default=CLOUD_PROVIDERS[0].default_embedding_dim- )+ # Known default model → dimension auto-filled without prompting.+ prompt_int.assert_not_called()def test_cloud_wizard_kimi_uses_requested_default_model(self):with patch(@@ -401,7 +414,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=CLOUD_PROVIDERS[0].default_embedding_dim,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["vlm"]["model"] == _DEFAULT_KIMI_MODEL@@ -425,7 +438,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=CLOUD_PROVIDERS[0].default_embedding_dim,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["vlm"]["model"] == _DEFAULT_GLM_MODEL@@ -449,7 +462,7 @@ class TestConfigBuilding:"openviking_cli.setup_wizard._prompt_required_int",return_value=CLOUD_PROVIDERS[2].default_embedding_dim,):- config = _wizard_cloud()+ config, _ = _wizard_cloud()assert config is not Noneassert config["vlm"]["provider"] == "volcengine"@@ -670,7 +683,7 @@ class TestConfigWriting:with (patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),- patch("openviking_cli.setup_wizard._prompt_choice", return_value=3),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=2),patch("openviking_cli.setup_wizard._wizard_ollama", return_value=(config, True)),patch("openviking_cli.setup_wizard._wizard_query_planner", return_value=None),patch(@@ -679,6 +692,7 @@ class TestConfigWriting:),patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),patch("openviking_cli.setup_wizard._write_config", return_value=True),+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),patch("builtins.print") as mock_print,):assert run_init() == 0@@ -706,7 +720,7 @@ class TestConfigWriting:}with (patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),- patch("openviking_cli.setup_wizard._prompt_choice", return_value=3),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=2),patch("openviking_cli.setup_wizard._wizard_ollama", return_value=(config, True)),patch("openviking_cli.setup_wizard._wizard_query_planner", return_value=None),patch(@@ -715,6 +729,7 @@ class TestConfigWriting:),patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),patch("openviking_cli.setup_wizard._write_config", return_value=True) as mock_write,+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),patch("builtins.print"),):assert run_init() == 0@@ -918,19 +933,695 @@ class TestApiKeyMasking:class TestServerWizard:- def test_local_mode_returns_loopback_host(self):- with patch("openviking_cli.setup_wizard._prompt_choice", return_value=1):- assert _wizard_server() == {"host": "127.0.0.1"}+ def test_local_mode_returns_loopback_host_and_port(self):+ with (+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=1),+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=1933),+ patch("builtins.print"),+ ):+ assert _wizard_server() == {"host": "127.0.0.1", "port": 1933}- def test_remote_mode_requires_root_api_key(self):+ def test_local_mode_custom_port(self):with (- patch("openviking_cli.setup_wizard._prompt_choice", return_value=2),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=1),+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=8080),+ patch("builtins.print"),+ ):+ assert _wizard_server() == {"host": "127.0.0.1", "port": 8080}++ def test_remote_mode_manual_root_api_key(self):+ with (+ # bind=Remote, key source=Enter my own+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[2, 2]),+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=1933),patch("openviking_cli.setup_wizard._prompt_required_input",return_value="my-secret-key",),+ patch("builtins.print"),):assert _wizard_server() == {"host": "0.0.0.0",+ "port": 1933,"root_api_key": "my-secret-key",}++ def test_remote_mode_generates_and_displays_root_api_key(self):+ with (+ # bind=Remote, key source=Generate one for me+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[2, 1]),+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=1933),+ patch("builtins.print") as mock_print,+ ):+ result = _wizard_server()++ assert result is not None+ key = result["root_api_key"]+ # 64-char hex, matching the repo's root-key convention (token_hex(32)).+ assert len(key) == 64+ int(key, 16) # raises if not hex+ assert result == {"host": "0.0.0.0", "port": 1933, "root_api_key": key}+ # The full key must be displayed to the user exactly once.+ output = "\n".join(+ " ".join(str(arg) for arg in call.args) for call in mock_print.call_args_list+ )+ assert key in output++ def test_remote_mode_empty_manual_key_cancels(self):+ with (+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[2, 2]),+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=1933),+ patch("openviking_cli.setup_wizard._prompt_required_input", return_value=""),+ patch("builtins.print"),+ ):+ assert _wizard_server() is None+++class TestServerWizardCurrentDefaults:+ CURRENT = {"host": "0.0.0.0", "port": 2044, "root_api_key": "k" * 64}++ def test_current_port_seeds_default(self):+ with (+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[1]),+ patch(+ "openviking_cli.setup_wizard._prompt_required_int", return_value=2044+ ) as mock_int,+ patch("builtins.print"),+ ):+ result = _wizard_server(current={"host": "127.0.0.1", "port": 2044})+ assert result == {"host": "127.0.0.1", "port": 2044}+ mock_int.assert_called_once_with("Port", default=2044)++ def test_remote_current_defaults_to_remote_and_keeps_key(self):+ with (+ # bind menu (defaults to Remote), key menu option 1 = Keep existing+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[2, 1]) as mock_choice,+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=2044),+ patch("builtins.print"),+ ):+ result = _wizard_server(current=self.CURRENT)++ assert result == self.CURRENT+ # Bind menu default seeded to Remote (2) because current host is 0.0.0.0.+ bind_call = mock_choice.call_args_list[0]+ assert bind_call.kwargs.get("default") == 2+ # Key menu offers "Keep existing key" as the first, default option.+ key_call = mock_choice.call_args_list[1]+ assert key_call.args[1][0][0] == "Keep existing key"++ def test_remote_current_can_rotate_key(self):+ with (+ # bind=Remote, key menu option 2 = Generate one for me (after Keep)+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[2, 2]),+ patch("openviking_cli.setup_wizard._prompt_required_int", return_value=2044),+ patch("builtins.print"),+ ):+ result = _wizard_server(current=self.CURRENT)++ assert result is not None+ assert result["root_api_key"] != self.CURRENT["root_api_key"]+ assert len(result["root_api_key"]) == 64+++class TestCurrentConfigSeeding:+ def test_cloud_embedding_keeps_existing_key_and_model(self):+ from openviking_cli.setup_wizard import _prompt_cloud_embedding++ current = {+ "provider": "volcengine",+ "model": "doubao-embedding-vision-240000",+ "api_key": "old-key-1234567890",+ "api_base": CLOUD_PROVIDERS[0].default_api_base,+ "dimension": 2048,+ }+ with (+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=1) as mock_choice,+ # Keep the existing API key? -> yes+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ # Model prompt returns its default (the current model)+ patch(+ "openviking_cli.setup_wizard._prompt_required_input",+ side_effect=lambda prompt, default=None, **kw: default,+ ),+ patch("openviking_cli.setup_wizard._prompt_api_key_with_env") as mock_env_key,+ patch("builtins.print"),+ ):+ dense = _prompt_cloud_embedding(current=current)++ assert dense == current+ mock_env_key.assert_not_called() # key kept, never re-prompted+ # Provider menu default seeded to the current provider.+ assert mock_choice.call_args.kwargs.get("default") == 1++ def test_vlm_option_index_mapping(self):+ from openviking_cli.setup_wizard import _vlm_option_index_for++ assert _vlm_option_index_for({"provider": "volcengine", "api_base": "https://ark.cn"}) == 1+ assert (+ _vlm_option_index_for(+ {"provider": "volcengine", "api_base": "https://ark.ap-southeast.bytepluses.com"}+ )+ == 2+ )+ assert (+ _vlm_option_index_for({"provider": "openai", "api_base": "https://api.openai.com/v1"})+ == 3+ )+ assert _vlm_option_index_for({"provider": "openai-codex"}) == 4+ assert _vlm_option_index_for({"provider": "kimi"}) == 5+ assert _vlm_option_index_for({"provider": "glm"}) == 6+ assert _vlm_option_index_for({"provider": "openai", "api_base": "https://my.proxy"}) == 7+ assert _vlm_option_index_for({"provider": "litellm", "model": "ollama/qwen3.6:27b"}) == 8++ def test_run_init_menu_shows_current_values(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(json.dumps(_existing_config()), encoding="utf-8")+ with (+ patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=5) as mock_choice,+ patch("builtins.print") as mock_print,+ ):+ assert run_init() == 0++ # Action menu descriptions carry the current values.+ options = mock_choice.call_args.args[1]+ labels = dict(options)+ assert "openai · old-vlm" in labels["Update VLM"]+ assert "ollama · qwen" in labels["Update embedding"]+ assert "127.0.0.1" in labels["Update server & auth"]+ # And the current-configuration block is printed above the menu.+ output = "\n".join(+ " ".join(str(arg) for arg in call.args) for call in mock_print.call_args_list+ )+ assert "Current configuration" in output++ def test_update_section_shows_change_diff(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(json.dumps(_existing_config()), encoding="utf-8")+ new_vlm = {"provider": "kimi", "model": "kimi-code", "api_base": "https://new"}+ with (+ patch("openviking_cli.setup_wizard._prompt_cloud_vlm", return_value=(new_vlm, None)),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),+ patch("builtins.print") as mock_print,+ ):+ assert _update_existing_config(config_path, "vlm") == 0++ output = "\n".join(+ " ".join(str(arg) for arg in call.args) for call in mock_print.call_args_list+ )+ assert "Change:" in output+ assert "openai · old-vlm" in output+ assert "kimi · kimi-code" in output+++# ---------------------------------------------------------------------------+# VLM presets (qwen3.6 replaces qwen3.5 27B/35B)+# ---------------------------------------------------------------------------+++class TestVLMPresets:+ def test_qwen36_replaces_qwen35_large_tiers(self):+ models = [p.ollama_model for p in VLM_PRESETS]+ assert "qwen3.6:27b" in models+ assert "qwen3.6:35b" in models+ assert "qwen3.5:27b" not in models+ assert "qwen3.5:35b" not in models++ def test_qwen36_litellm_models(self):+ by_ollama = {p.ollama_model: p for p in VLM_PRESETS}+ assert by_ollama["qwen3.6:27b"].litellm_model == "ollama/qwen3.6:27b"+ assert by_ollama["qwen3.6:35b"].litellm_model == "ollama/qwen3.6:35b"++ def test_very_high_ram_recommends_qwen36_27b(self):+ _, vlm_idx = _get_recommended_indices(128)+ assert VLM_PRESETS[vlm_idx].ollama_model == "qwen3.6:27b"+++# ---------------------------------------------------------------------------+# Size-hint parsing+# ---------------------------------------------------------------------------+++class TestSizeParsing:+ def test_parses_gb(self):+ assert _parse_size_gb("~4.7 GB") == 4.7+ assert _parse_size_gb("~17 GB, 256K ctx") == 17.0++ def test_parses_mb(self):+ assert abs(_parse_size_gb("~639 MB") - 639 / 1024) < 1e-9++ def test_unparseable_returns_zero(self):+ assert _parse_size_gb("~0.8B, recommended") == 0.0+ assert _parse_size_gb("") == 0.0+++# ---------------------------------------------------------------------------+# Recommended all-Ollama fast path+# ---------------------------------------------------------------------------+++class TestRecommendedOllamaSetup:+ def test_fast_path_builds_full_config_with_planner(self):+ with (+ patch("openviking_cli.setup_wizard._ensure_ollama", return_value=True),+ patch("openviking_cli.setup_wizard.get_ollama_models", return_value=[]),+ patch("openviking_cli.setup_wizard._get_system_ram_gb", return_value=16),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._check_disk_before_pull", return_value=True),+ patch("openviking_cli.setup_wizard.ollama_pull_model", return_value=True),+ patch("builtins.print"),+ ):+ config, ollama_running = _wizard_ollama()++ assert ollama_running is True+ assert config is not None+ # 16 GB RAM tier: qwen3-embedding:0.6b + qwen3.5:4b+ assert config["embedding"]["dense"]["model"] == "qwen3-embedding:0.6b"+ assert config["vlm"]["model"] == "ollama/qwen3.5:4b"+ assert config["query_planner"]["model"] == QUERY_PLANNER_PRESETS[0].litellm_model++ def test_decline_falls_back_to_per_model_selection(self):+ with (+ patch("openviking_cli.setup_wizard._ensure_ollama", return_value=True),+ patch("openviking_cli.setup_wizard.get_ollama_models", return_value=[]),+ patch("openviking_cli.setup_wizard._get_system_ram_gb", return_value=16),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=False),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=1),+ patch("openviking_cli.setup_wizard.is_model_available", return_value=True),+ patch("builtins.print"),+ ):+ config, _ = _wizard_ollama()++ assert config is not None+ assert config["embedding"]["dense"]["model"] == EMBEDDING_PRESETS[0].model+ assert config["vlm"]["model"] == VLM_PRESETS[0].litellm_model+ assert "query_planner" not in config+++# ---------------------------------------------------------------------------+# Query planner: skip when already configured+# ---------------------------------------------------------------------------+++class TestQueryPlannerAlreadyConfigured:+ def test_early_return_leaves_config_untouched(self):+ planner = _build_query_planner_config(QUERY_PLANNER_PRESETS[0])+ config_dict = {"embedding": {}, "vlm": {}, "query_planner": dict(planner)}+ with patch("openviking_cli.setup_wizard._prompt_confirm") as mock_confirm:+ _wizard_query_planner(config_dict, ollama_running=True)+ mock_confirm.assert_not_called()+ assert config_dict["query_planner"] == planner+++# ---------------------------------------------------------------------------+# Cloud "Other (manual)" routes to custom instead of cancelling+# ---------------------------------------------------------------------------+++class TestCloudOtherRoutesToCustom:+ def test_returns_custom_sentinel(self):+ with (+ patch(+ "openviking_cli.setup_wizard._prompt_choice",+ return_value=len(CLOUD_PROVIDERS) + 1,+ ),+ patch("openviking_cli.setup_wizard._wizard_custom") as mock_custom,+ patch("builtins.print"),+ ):+ result, _ = _wizard_cloud()++ assert result is _CUSTOM_SETUP+ mock_custom.assert_called_once()++ def test_run_init_exits_cleanly_on_custom_sentinel(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ with (+ patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=1),+ patch(+ "openviking_cli.setup_wizard._wizard_two_step",+ return_value=(_CUSTOM_SETUP, None),+ ),+ patch("openviking_cli.setup_wizard._write_config") as mock_write,+ patch("builtins.print"),+ ):+ assert run_init() == 0+ mock_write.assert_not_called()+++# ---------------------------------------------------------------------------+# API key from environment variables+# ---------------------------------------------------------------------------+++class TestEnvApiKey:+ def test_uses_env_var_when_confirmed_on_tty(self):+ with (+ patch.dict(os.environ, {"ARK_API_KEY": "env-key-1234567890"}, clear=False),+ patch("openviking_cli.setup_wizard._stdin_stdout_tty", return_value=True),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._prompt_api_key") as mock_prompt,+ ):+ value = _prompt_api_key_with_env(["ARK_API_KEY"])+ assert value == "env-key-1234567890"+ mock_prompt.assert_not_called()++ def test_falls_back_to_prompt_when_declined(self):+ with (+ patch.dict(os.environ, {"ARK_API_KEY": "env-key-1234567890"}, clear=False),+ patch("openviking_cli.setup_wizard._stdin_stdout_tty", return_value=True),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=False),+ patch("openviking_cli.setup_wizard._prompt_api_key", return_value="typed-key"),+ ):+ assert _prompt_api_key_with_env(["ARK_API_KEY"]) == "typed-key"++ def test_skips_env_shortcut_when_not_tty(self):+ with (+ patch.dict(os.environ, {"ARK_API_KEY": "env-key-1234567890"}, clear=False),+ patch("openviking_cli.setup_wizard._stdin_stdout_tty", return_value=False),+ patch("openviking_cli.setup_wizard._prompt_confirm") as mock_confirm,+ patch("openviking_cli.setup_wizard._prompt_api_key", return_value="typed-key"),+ ):+ assert _prompt_api_key_with_env(["ARK_API_KEY"]) == "typed-key"+ mock_confirm.assert_not_called()+++# ---------------------------------------------------------------------------+# Partial reconfiguration of an existing config+# ---------------------------------------------------------------------------+++def _existing_config() -> dict:+ return {+ "storage": {"workspace": "/tmp/ov"},+ "embedding": {"dense": {"provider": "ollama", "model": "qwen", "dimension": 1024}},+ "vlm": {"provider": "openai", "model": "old-vlm", "api_base": "https://old"},+ "server": {"host": "127.0.0.1"},+ }+++class TestPartialUpdate:+ def test_update_vlm_only(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(json.dumps(_existing_config()), encoding="utf-8")+ new_vlm = {"provider": "kimi", "model": "kimi-code", "api_base": "https://new"}++ with (+ patch("openviking_cli.setup_wizard._prompt_cloud_vlm", return_value=(new_vlm, None)),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),+ patch("builtins.print"),+ ):+ assert _update_existing_config(config_path, "vlm") == 0++ data = json.loads(config_path.read_text(encoding="utf-8"))+ assert data["vlm"] == new_vlm+ assert data["embedding"] == _existing_config()["embedding"] # untouched+ assert (tmp_path / "ov.conf.bak").exists() # old config backed up++ def test_update_server_only(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(json.dumps(_existing_config()), encoding="utf-8")++ with (+ patch(+ "openviking_cli.setup_wizard._wizard_server",+ return_value={"host": "0.0.0.0", "root_api_key": "rk"},+ ),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),+ patch("builtins.print"),+ ):+ assert _update_existing_config(config_path, "server") == 0++ data = json.loads(config_path.read_text(encoding="utf-8"))+ assert data["server"] == {"host": "0.0.0.0", "root_api_key": "rk"}+ assert data["vlm"] == _existing_config()["vlm"]++ def test_embedding_dimension_change_requires_confirmation(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ original = _existing_config()+ config_path.write_text(json.dumps(original), encoding="utf-8")+ new_dense = {"provider": "local", "model": "bge-small-zh-v1.5-f16", "dimension": 512}++ with (+ patch(+ "openviking_cli.setup_wizard._prompt_embedding_flow",+ return_value=(new_dense, None),+ ),+ # Decline the dimension-change warning → nothing written.+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=False),+ patch("builtins.print"),+ ):+ assert _update_existing_config(config_path, "embedding") == 0++ assert json.loads(config_path.read_text(encoding="utf-8")) == original++ def test_unreadable_config_returns_error(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text("{not json", encoding="utf-8")+ with patch("builtins.print"):+ assert _update_existing_config(config_path, "vlm") == 1+++class TestRunInitExistingConfigMenu:+ def test_dispatches_partial_update(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(json.dumps(_existing_config()), encoding="utf-8")+ with (+ patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=2),+ patch(+ "openviking_cli.setup_wizard._update_existing_config", return_value=0+ ) as mock_update,+ patch("builtins.print"),+ ):+ assert run_init() == 0+ mock_update.assert_called_once_with(config_path, "vlm")++ def test_cancel_leaves_config_untouched(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ original = json.dumps(_existing_config())+ config_path.write_text(original, encoding="utf-8")+ with (+ patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=5),+ patch("builtins.print"),+ ):+ assert run_init() == 0+ assert config_path.read_text(encoding="utf-8") == original+++# ---------------------------------------------------------------------------+# Two-step setup: embedding and VLM chosen independently+# ---------------------------------------------------------------------------+++class TestTwoStepWizard:+ def test_mixed_local_embedding_cloud_vlm(self):+ dense = {"provider": "ollama", "model": "qwen3-embedding:0.6b", "dimension": 1024}+ vlm = {"provider": "openai", "model": "gpt-5.4", "api_base": "https://api.openai.com/v1"}+ with (+ patch(+ "openviking_cli.setup_wizard._prompt_embedding_flow",+ return_value=(dense, True),+ ),+ patch("openviking_cli.setup_wizard._prompt_cloud_vlm", return_value=(vlm, None)),+ patch("builtins.print"),+ ):+ config, ollama_running = _wizard_two_step()++ assert config is not None+ assert config["embedding"]["dense"] == dense+ assert config["vlm"] == vlm+ assert config["storage"]["workspace"] == _workspace_path()+ # Ollama state from the embedding step survives a non-Ollama VLM step.+ assert ollama_running is True++ def test_skip_vlm_produces_embedding_only_config(self):+ dense = {"provider": "local", "model": "bge-small-zh-v1.5-f16", "dimension": 512}+ with (+ patch(+ "openviking_cli.setup_wizard._prompt_embedding_flow",+ return_value=(dense, None),+ ),+ patch(+ "openviking_cli.setup_wizard._prompt_cloud_vlm",+ return_value=(_SKIP_VLM, None),+ ),+ patch("builtins.print"),+ ):+ config, _ = _wizard_two_step()++ assert config is not None+ assert config["embedding"]["dense"] == dense+ assert "vlm" not in config++ def test_embedding_key_offered_for_vlm_reuse(self):+ dense = {+ "provider": "volcengine",+ "model": "doubao-embedding-vision-251215",+ "api_key": "ve-key",+ "dimension": 1024,+ }+ with (+ patch(+ "openviking_cli.setup_wizard._prompt_embedding_flow",+ return_value=(dense, None),+ ),+ patch(+ "openviking_cli.setup_wizard._prompt_cloud_vlm",+ return_value=({"provider": "volcengine", "model": "m"}, None),+ ) as mock_vlm,+ patch("builtins.print"),+ ):+ _wizard_two_step()++ mock_vlm.assert_called_once_with(+ allow_skip=True, reuse_key=("volcengine", "ve-key"), allow_back=True+ )++ def test_cancel_in_vlm_step_cancels_setup(self):+ dense = {"provider": "openai", "model": "text-embedding-3-small", "dimension": 1536}+ with (+ patch(+ "openviking_cli.setup_wizard._prompt_embedding_flow",+ return_value=(dense, None),+ ),+ patch("openviking_cli.setup_wizard._prompt_cloud_vlm", return_value=(None, None)),+ patch("builtins.print"),+ ):+ config, _ = _wizard_two_step()+ assert config is None+++class TestVLMKeyReuse:+ def test_reuse_accepted_skips_key_prompt(self):+ from openviking_cli.setup_wizard import _prompt_cloud_vlm++ with (+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=3), # OpenAI+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch(+ "openviking_cli.setup_wizard._prompt_required_input",+ return_value="gpt-5.4",+ ),+ patch("openviking_cli.setup_wizard._prompt_api_key_with_env") as mock_key,+ patch("builtins.print"),+ ):+ vlm_config, _ = _prompt_cloud_vlm(reuse_key=("openai", "shared-key"))++ assert vlm_config["api_key"] == "shared-key"+ mock_key.assert_not_called()++ def test_different_provider_prompts_normally(self):+ from openviking_cli.setup_wizard import _prompt_cloud_vlm++ with (+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=3), # OpenAI+ patch("openviking_cli.setup_wizard._prompt_confirm") as mock_confirm,+ patch(+ "openviking_cli.setup_wizard._prompt_required_input",+ return_value="gpt-5.4",+ ),+ patch(+ "openviking_cli.setup_wizard._prompt_api_key_with_env",+ return_value="typed-key",+ ),+ patch("builtins.print"),+ ):+ vlm_config, _ = _prompt_cloud_vlm(reuse_key=("volcengine", "other-key"))++ assert vlm_config["api_key"] == "typed-key"+ mock_confirm.assert_not_called()+++# ---------------------------------------------------------------------------+# Back navigation (← / [0] Back)+# ---------------------------------------------------------------------------+++class TestBackNavigation:+ def test_numbered_fallback_accepts_zero_as_back(self):+ from openviking_cli.setup_wizard import _prompt_choice_numbered++ with patch("builtins.input", return_value="0"), patch("builtins.print"):+ assert _prompt_choice_numbered("Q:", [("A", ""), ("B", "")], allow_back=True) == 0++ def test_numbered_fallback_rejects_zero_without_back(self):+ with patch("builtins.input", side_effect=["0", "2"]), patch("builtins.print"):+ from openviking_cli.setup_wizard import _prompt_choice_numbered++ assert _prompt_choice_numbered("Q:", [("A", ""), ("B", "")]) == 2++ def test_embedding_flow_backs_out_of_backend_menu(self):+ with (+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=0),+ patch("builtins.print"),+ ):+ from openviking_cli.setup_wizard import _prompt_embedding_flow++ dense, _ = _prompt_embedding_flow(allow_back=True)+ assert dense is _GO_BACK++ def test_vlm_menu_backs_out(self):+ from openviking_cli.setup_wizard import _prompt_cloud_vlm++ with (+ patch("openviking_cli.setup_wizard._prompt_choice", return_value=0),+ patch("builtins.print"),+ ):+ vlm_config, _ = _prompt_cloud_vlm(allow_back=True)+ assert vlm_config is _GO_BACK++ def test_two_step_back_from_vlm_reruns_embedding(self):+ dense1 = {"provider": "ollama", "model": "first", "dimension": 1024}+ dense2 = {"provider": "ollama", "model": "second", "dimension": 1024}+ with (+ patch(+ "openviking_cli.setup_wizard._prompt_embedding_flow",+ side_effect=[(dense1, None), (dense2, None)],+ ),+ patch(+ "openviking_cli.setup_wizard._prompt_cloud_vlm",+ side_effect=[(_GO_BACK, None), (_SKIP_VLM, None)],+ ),+ patch("builtins.print"),+ ):+ config, _ = _wizard_two_step()++ assert config is not None+ assert config["embedding"]["dense"] == dense2++ def test_run_init_back_from_two_step_reshows_mode_menu(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ ollama_config = {+ "embedding": {"dense": {"provider": "ollama", "model": "q", "dimension": 1024}},+ "storage": {"workspace": str(tmp_path / "data")},+ }+ with (+ patch.dict(os.environ, {"OPENVIKING_CONFIG_FILE": str(config_path)}, clear=False),+ # First pass picks step-by-step, which backs out; second pass picks+ # the recommended Ollama mode.+ patch("openviking_cli.setup_wizard._prompt_choice", side_effect=[1, 2]),+ patch(+ "openviking_cli.setup_wizard._wizard_two_step",+ return_value=(_GO_BACK, None),+ ),+ patch(+ "openviking_cli.setup_wizard._wizard_ollama",+ return_value=(ollama_config, True),+ ),+ patch("openviking_cli.setup_wizard._wizard_query_planner", return_value=None),+ patch(+ "openviking_cli.setup_wizard._wizard_server",+ return_value={"host": "127.0.0.1"},+ ),+ patch("openviking_cli.setup_wizard._prompt_confirm", return_value=True),+ patch("openviking_cli.setup_wizard._write_config", return_value=True) as mock_write,+ patch("openviking_cli.setup_wizard._post_save_actions", return_value=None),+ patch("builtins.print"),+ ):+ assert run_init() == 0+ mock_write.assert_called_once()