Files
javis_bot/app/src/admin.spec.md
javis-bot 41026a1eff fix(app): settle the start state before answering and report failed stops
service_start now moves the controller to starting before it returns
(Controller::start_in_background), so a stop right after it cancels the
start and a second start is refused instead of the start running late.
service_restart stops, then starts the same way.

Stopping Strata now confirms the server is gone: `launch --stop` is ended
after 2 minutes with everything it started, then the port must stop
listing a model. A server still answering makes the LLM failed with the
reason, and Services::stop / Running::stop return it, so the controller
shows failed instead of stopped (also for a cancelled start that could
not clear the server). A stop command that fails while nothing answers
counts as stopped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:51:11 +09:00

279 lines
20 KiB
Markdown

# Admin backend spec (v2 M5)
What the management app's screens (`docs/v2/desktop-app.md`) stand on: the data folder, editing the
settings, the stored secrets and the logs. Plain Rust in the app crate, with no window: the Tauri
shell (M5, later step) only calls these, so every rule here is tested on any OS.
## Principles
- **One folder.** Everything the app keeps lives in the data folder the user chose
(`desktop-app.md`, "데이터 폴더 구조"); outside it there is only the file that remembers where it is.
- **The file stays the user's.** Settings edits change only the keys they name, write only values
that differ from the default, keep keys the app does not know, and never leave a half-written file.
- **Secrets never reach a log, a copy or an export.**
- **Logs carry no conversation text** (already the rule for every log line, `discord_core.spec.md`,
`voice_worker.spec.md`); exports still mask secrets.
## Data folder (`app/src/datadir.rs`)
The location file is `%APPDATA%\JarvisBot\location.json` on Windows and
`$XDG_CONFIG_HOME/jarvis-bot/location.json` (else `~/.config/jarvis-bot/location.json`) elsewhere:
`{"dataDir": "<absolute path>"}`. `JARVIS_DATA_DIR` set in the environment wins over it (tests,
development). No location (no file, no variable) means the first-run wizard has not finished.
`DataDir::create(path)` makes the layout below inside an existing or new folder and returns it; it
never deletes anything. `DataDir::choose(path)` creates it and writes the location file (atomically).
```
config/ runtime/ models/llm models/stt models/tts models/vad memory/ browser/ collect/
cache/ logs/ models/hf models/nltk
```
`free_bytes(path)` reports the free space of the disk holding the folder (or its nearest existing
parent); the wizard compares it with `RECOMMENDED_FREE_BYTES` (200 GB) and warns below it. A path
that is not absolute, or is a file, is refused with a message.
## Settings editing (`app/src/settings_edit.rs`)
`config/settings.json` keeps the format of `discord_core.spec.md` and `conversation.spec.md`.
- `fields()` describes every key the screens edit: its dotted path (`call.mode`), screen
(`bot`, `channels`, `chat`, `memory`, `model`), kind (bool, integer with a range, number with a
range, text, text list, choice with its values, Discord ID, Discord ID list, ID to number map,
chat channel list, free object), its default and a Korean label. The screens are built from this
list, so a key is added in one place.
- `view(dir)` returns every field's current value: the file's value, or the default when the file
does not set it. A file that does not parse is reported, not overwritten.
- `apply(dir, changes)` takes `{path: value}`. Each value is checked against its field; a value equal
to the default removes the key (and a section left empty), any other value is set. Keys the app
does not know are kept as they were. The whole result must pass the app's own settings check
(`parse_settings`); only then is it written (temporary file, then rename). A refused change names
the key and changes nothing.
- `memory` (new section): the worker's memory settings (`voice_worker.spec.md`, "Memory settings":
`chat`, `others`, `off`, `since_days`, `recent_minutes`, `recent_records`, `matches`,
`budget_tokens`), sent in the worker `hello` as `memory`. Default `{}` (the worker's defaults).
## Secrets (`app/src/secrets.rs`)
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`). On Windows the bytes are
encrypted with DPAPI for the current Windows user (`CryptProtectData`, no prompt), so the file is
useless copied to another account or PC. Elsewhere (development only) the file is plain JSON with
owner-only permissions (0600). Writes are atomic. `get`, `set`, `remove`; `masked(value)` shows only
the last 4 characters for the screens (`••••abcd`).
The app's token comes from the secrets (`discordToken`), else from `JARVIS_DISCORD_TOKEN` (tests,
headless runs).
## Logs (`app/src/logs.rs`)
`debug_log!` and `error_log!` keep printing to stderr and also feed the log hub once the app
installs one (`logs::install`). Each line has a time, a level (`error`, `warn`, `info`, `debug`), a
service tab and its text. The tab comes from the line's category: `app`, `discord` (`voice`,
`receive`, `play`, `discord`), `chat`, `conversation`, `worker` (the voice worker's own lines; its
STT, LLM and TTS lines go to `stt`, `llm`, `tts` by their worker category), `browser`, `capture`,
`game` (the last three from M6-M7). Unknown categories go to `app`.
- Memory: the last 5,000 lines for the log screen (`query`: tab, lowest level, text to find, and
the lines after a given sequence number, for live follow).
- Files: `logs/<tab>-<YYYY-MM-DD>.log`, one line per entry; files older than 14 days are removed at
start and once a day.
- `recent_error_report()`: the last error with up to 30 lines before and 10 after it (all tabs, in
order), the app version and a short PC summary (OS, CPU count, memory); `None` without an error.
When it is over 2,000 characters (Discord's message limit) the screen offers a download instead.
- `export_zip(from, to, out)`: the log files of those days in a zip, at most 10 MB (Discord's file
limit): when larger, the oldest lines by the time they were logged, across every tab's file, are
left out and a note says how many.
- Every copy and export runs through `redact`: each stored secret's value, and anything shaped like
a Discord bot token (also with sentence dots around it), becomes `[비밀값]`.
- Errors the voice worker reports to the app (`error` messages: code and request id) are always
logged, debug logging or not, so the log screen and the error report show them.
## Service control (`app/src/control.rs`)
The dashboard's start and stop buttons, and the app binary itself, run the services through one
`Controller` for the data folder: states `stopped`, `starting`, `running`, `stopping`, `failed`
(with the error, secrets masked). `start` from stopped or failed only, `stop` from running or
starting; `restart` is stop then start. A start that fails leaves nothing running. A stop while
starting cancels the start (the LLM's model download or load stops and its server is cleared) and
ends in `stopped` without an error; if the start finished anyway, what came up is stopped again.
The screens' `service_start` and `service_restart` return as soon as the state is `starting`
(restart stops first) and the start runs in the background (the first start downloads the model);
the dashboard shows how it goes, a stop right after the answer cancels the start and a second start
is refused. A stop that cannot confirm everything ended (the LLM's server still answers) ends in
`failed` with the reason, not `stopped`; a start (Strata's `--restart`) can follow. The same goes
for a cancelled start that could not clear the server. Starting reads the
settings and the stored token again, so saved changes take effect on the next start. Each start
gets a new dashboard fed by that run's events; `stop` ends the feeding (and waits for it) before
the dashboard is forgotten, so an event queued before the stop, or sent by an earlier run, never
reaches the screen.
## Dashboard data (`app/src/dashboard.rs`)
`Controller::snapshot()` is everything the dashboard shows, as one JSON-ready value:
- `state` and `error` (above); `discord`: the bot's tag once connected; `worker`: connected, STT
and TTS ready (from the worker's `hello_ok`), restarts of its process.
- `voice`: the voice channel Jarvis is in and the people there (ID and display name), as the core
reports them to the worker.
- `captions`: live captions, the last 30 lines: a speaker's partial transcript is replaced by
their next partial and then by the final. A transcript belongs to the voice session its
utterance started in (`Heard.session`, `discord_core.spec.md`): only the current session's are
shown, so one arriving after Jarvis left, or after it moved to another channel, is not. On the screen only: never logged, never written,
cleared when Jarvis leaves the voice channel or the services stop.
- `latency`: the last 20 voice answers, each split into its stages: speech end to final transcript,
the brain (answer asked to answer text), the voice (answer text to the first sound) and the
total; with the median of each. The core's `AnswerAsked { id, user, ended_at, final_at }` event
carries the speech id and the request's own times (when its speech ended, when its final
arrived), so a second question waiting behind the first does not change the first's times.
- `missed`: the conversation's missed requests (`conversation.spec.md`), newest first, at most 20:
who, why and how long ago, never the text.
- `system`: memory in use and total, and per NVIDIA GPU its use and VRAM (from `nvidia-smi`,
missing when there is none); sampled when the snapshot is taken, at most once a second.
- `llm`: the LLM's state (`off`, `starting`, `ready`, `failed`), whether the app runs it
(`managed`), and while starting Strata's last line and last percentage (the model download),
also before the services are up; a failure's reason in `note`.
- `performance`: the performance stage (normal, gaming, paused, and why) comes with game
detection in M7; until then `null`.
The dashboard's state is built from the core's events alone (`Dashboard::on_event` with the time),
so it is tested with made-up events.
## Install (`app/src/install.rs`, `app/src/download.rs`)
The wizard's model step installs the runtime into the data folder with the recipe the M0 kit used
on the game PC (`scripts/m0`). The steps, in order:
| Step | What |
|---|---|
| `uv` | `uv` 0.11.20, downloaded with resume and checked against the release's SHA-256, into `runtime/uv` |
| `worker_env` | Python 3.12 venv `runtime/venvs/worker` with `src/voice_worker/requirements.txt` and `requirements-brain.txt` (the v2 brain only; the repository's `requirements.txt` is v1's desktop app) |
| `melo_env` | Python 3.11 venv `runtime/venvs/melo`: PyTorch 2.11 cu128 (pinned so later installs keep it), MeloTTS at a pinned commit, `python-mecab-ko` instead of the Japanese MeCab |
| `stt_model` | Whisper `large-v3-turbo` (faster-whisper) |
| `tts_model` | the NLTK data MeloTTS's English g2p reads, then the worker's own `melo_child.py` loads the Korean voice once (downloading it) and must say its warm-up sentence |
| `strata` | Strata's own installer (`install.ps1`, `install.sh` elsewhere) with Strata's state, engine and components under `runtime/strata` and no PATH change |
| `settings` | `voiceWorker` in the settings pointed at the worker venv's Python with `--melo-python <melo venv> --history memory/history.sqlite --brain` (other settings kept); the install is done only once this is written |
The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its first start (below).
- A finished step leaves `runtime/.done/<id>` holding its version (the pin; for `worker_env` a hash
of its requirement files), so later runs skip it and a new pin runs it again. Steps run one at a
time; a failure stops the run and the next run starts at that step; cancel stops the running
command and every process it started (one process group, a job tree on Windows) or the download,
also while a server sends nothing (a download's part file stays, so the next try continues it).
- Folders go to commands as arguments or as the working folder, never inside a script's text.
- Every command runs with the layout's environment: `uv`'s cache and Pythons, `HF_HOME`
(`models/hf`), `NLTK_DATA` (`models/nltk`), temp files (`cache/tmp`) and Strata's folders, all
inside the data folder. Python comes from `uv` only. Output lines go to the `install` log tab.
- Downloads go to `<file>.part`, continue with an HTTP range after a break (a server without ranges
starts over), and are checked against the pinned SHA-256; a wrong checksum deletes the part.
- When every step is done, `uv`'s download cache is cleaned (the venvs hold copies).
- With the install complete, the services start the worker with the same environment (models,
caches and temp files in the data folder; on Linux also the CUDA wheels' library folders).
## LLM (`app/src/strata.rs`)
The brain answers with one model, Qwen3.6-35B-A3B UD-Q4_K_XL through Strata (M0). The services
start it first, so nothing answers before the brain can, and stop it last.
- **Strata from the data folder** (the default): `strata launch --family qwen36 --model ud-q4_k_xl
--data-dir models/llm --context <llm.context> --vision off --parallel <n> --access local --port
<llm.port> --no-api-key --restart --yes --no-tui`, run like an install command (the layout's
environment, `runtime/strata` as the working folder, one process group, lines to the `llm` log
tab). It downloads the model on the first start, starts the engine and returns; the app then
waits (up to 30 minutes) until `/v1/models` lists the model and takes its id. `--restart`
replaces a server left with other choices; the same choices are reused. `--parallel` is 1 (faster
on a 16 GB card, M0) and 2 when a chat channel answers every message, so its answers do not wait
behind voice answers. Pictures are off until something in v2 sends one. Stopping the services
runs `strata launch --stop` (ended after 2 minutes, with everything it started) and then checks
that the port no longer lists a model; so does a failed or cancelled start, so nothing
half-started keeps graphics memory. Stopped means nothing answers any more (a stop command that
fails while nothing answers counts as stopped); a server still answering makes the LLM `failed`
with the reason, and the stop or the start reports it. Not installed: the start fails and says to
run the install.
- **A server the app does not start**: with `llm.url` (an OpenAI-compatible `/v1` address, in the
settings file only) the app starts nothing; that server must list a model within 30 seconds.
- **Settings**: `llm.context` (default 32768 tokens per request, 4096-262144) and `llm.port`
(default 8080) on the model screen; `llm.url` (default none).
- **The brain's settings**: on every start the app writes `config/brain.json` (it owns the file):
`ollama_base_url` the LLM's `/v1`, `ollama_chat_model` the listed id, `db_path`
`memory/jarvis.db`; the worker gets it as `JARVIS_CONFIG_PATH`. Loading it writes nothing to the
home folder.
## Admin commands (`app/src/admin_api.rs`)
`AdminApi::call(command, args)` is the one entry point of the screens, JSON in and out; errors come
back as Korean messages for the screen. The Tauri shell passes the screens' `invoke("admin",
{command, args})` to it; the development server (below) does the same over loopback HTTP.
| Command | Does |
|---|---|
| `app_status` | version, data folder, whether a token is stored, `wizardStep`; `firstRun` until the wizard's last step was reached (a stored token alone does not finish it) |
| `wizard_step` `{step}` / `wizard_finish` | remember the wizard step reached / mark it done (needs a stored token); both in `config/setup.json` |
| `folder_check` `{path}` / `folder_choose` `{path}` | free space against the recommendation / create the folder and remember it |
| `pc_check` | OS, CPU threads, RAM, NVIDIA GPUs, the driver version and whether it is 580 or newer, free disk |
| `token_check` `{token}` | the bot's tag and IDs, whether the Message Content intent is on, the invite link (REST only, nothing stored) |
| `token_save` `{token}` / `token_status` | store it (masked from then on in logs) / `set` and the masked form, never the token |
| `discord_guilds` / `discord_channels` `{guildId}` | the bot's servers / a server's voice and text channels, for the pickers |
| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run |
| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start |
| `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it |
| `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back |
The invite link asks for: view channels, send messages, read history, add reactions, manage
messages, manage channels, connect, speak, voice activity, and the slash command scope; never
administrator. The log hub writes to the data folder's `logs/` as soon as a folder is chosen
(`folder_choose` points it there; before that, memory only).
## Screens (`app/ui/`)
Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. All text is Korean.
- **First-run wizard** (while `firstRun`): data folder (free space, warning under 200 GB), PC check,
the model to download, Discord bot (token check with the
Message Content state and the invite link, then save), server and auto-join voice channel
pickers, wake words, then start (which says the first start downloads the LLM). The model step shows the install (each step's state, download
bytes and last line; start, cancel, retry) and goes on only once everything is installed. Each step reached is saved, so a reload or a restart resumes at
that step; only the last step's start finishes it. A stored token lets the bot step go on
without entering it again.
- **Dashboard**: the snapshot every second; while the LLM starts, a card with its percentage and
Strata's last line, and stop in the header; the header with start, restart and stop is rebuilt
only when the state changes, so a click is never lost to the refresh. Every screen change starts
a new generation: an answer that arrives after the user moved to another screen is dropped.
- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델): built from `settings_fields`; only
changed fields are sent; the server and voice channel are pickers (choosing another server clears
the voice channel and lists only that server's channels); the chat channels are a table
with their switches; the bot screen also changes the token.
- **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류
복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days.
`jarvis-admin-dev [--port N] [--ui DIR] [--location FILE]` (development only) serves `app/ui` and
the commands on 127.0.0.1; every command needs the random token it prints (`#token=` in the page
URL), so other local programs cannot drive it.
## Tests
`cargo test`: data folder layout, location file and the environment override, a refused relative
path, free space; settings view with defaults, apply writing only non-defaults, removing a key set
back to its default, keeping unknown keys, refusing a bad value or a result `parse_settings` refuses
without touching the file; secrets round trip, file permissions on Unix, masking; log tabs from
categories, query filters and follow, files per day and retention, error report bounds, zip size
cap, redaction of stored secrets and token-shaped text; the controller's state rules with a fake
service starter, a stop while starting (cancelled, or finished and stopped again); the LLM
(launch arguments from the settings and inside the data folder, the second request slot for a chat
channel answering everything, the download percentage, the brain's settings file, a given server
used without Strata, Strata missing, a fake Strata that reports progress, returns, serves and is
stopped, is cancelled during its download and cleared, or fails with its last line, a stop that
fails or hangs while the server still answers (failed, not off) and one that fails while nothing
answers (off); a background start that is starting at once, so a stop right after it cancels it
and a second start is refused, also through the admin commands; a failed stop reported as failed; the brain's
config loaded without writing to the home folder, `tests/test_config_db_path.py`); the dashboard from made-up events (captions replaced and cleared, latency stages
and medians, an answer matched to its asker's final, missed requests without text); the admin
commands (first run: folder then token, the token never returned whole, the wizard resumed at its
step until finished, log files and the zip from the folder choice on, settings and logs through
their modules, the dashboard before anything runs), the invite link's permissions and the Message
Content flags. The screens are checked in a browser against the development server with the real
services (wizard, dashboard start, restart and stop, settings save, chat channels, logs, export). Windows-only paths (DPAPI, `%APPDATA%`) are
checked on the Windows VM in the Windows build step.