feat(app): Tauri window and the Windows build

M5 step 5, first part. app/shell is a Tauri 2 crate (jarvis.exe): one
window over app/ui whose invoke("admin") goes to AdminApi::call. Its
WebView2 data sits next to the location file; closing the window stops
the services and waits for a cancelled start (AdminApi::shutdown).

app/shell/package.sh cross-builds it on Linux (x86_64-pc-windows-gnu)
and lays out Jarvis/ with WebView2Loader.dll and python-src/
(voice_worker, jarvis). The worker's default sources are python-src next
to the executable when present, else the repository's src/.

The bot screen now shows the masked token right after saving.

Checked on the win-ci VM: the window and wizard, PC check, uv and worker
venv installed, a cancel leaving no uv/Python process, the token stored
DPAPI-encrypted, a start failing with its reason, logs, error copy, zip
export, closing the window ending the process, nothing under %APPDATA% or
%LOCALAPPDATA%; the core's unit tests on Windows (156/157, the one
Linux-path assumption fixed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 18:16:02 +09:00
parent 81ba5e3521
commit ac8c30022d
17 changed files with 7752 additions and 7 deletions

View File

@@ -32,7 +32,7 @@ Any code change must either adhere to our spec files perfectly or you should ask
| `src/jarvis/memory/recall_gate.spec.md` | Deterministic skip-enrichment heuristic when the hot window covers a follow-up | Fail-open; language-agnostic via `\w{3,}` + `re.UNICODE`; planner intent always wins |
| `src/voice_worker/voice_worker.spec.md` | v2 voice worker: multi-speaker streaming STT (shared Whisper, batched) and sentence TTS over a local WebSocket | Loopback only with an app token; no transcript text in logs; finals before partials; language-agnostic |
| `app/src/conversation.spec.md` | v2 call detection and response policies in the Rust app: wake words with near matches, call modes, designated people, voice stop, the four response policies with settling, interruption and missed requests | Pure types tested with fake times; language-agnostic matching on normalised letters; nothing dropped silently |
| `app/src/admin.spec.md` | v2 M5 admin backend for the management app: data folder and its location file, settings editing for the screens, stored secrets (DPAPI on Windows), log hub (tabs, daily files, error report, zip export) | One folder; edits keep the user's file (only non-defaults, unknown keys kept, all or nothing); secrets never in a log, copy or export |
| `app/src/admin.spec.md` | v2 M5 admin backend for the management app: data folder and its location file, settings editing for the screens, stored secrets (DPAPI on Windows), log hub (tabs, daily files, error report, zip export), service control and dashboard data, runtime install, the LLM (Strata) the services start, the Tauri window and the Windows build | One folder; edits keep the user's file (only non-defaults, unknown keys kept, all or nothing); secrets never in a log, copy or export |
| `app/src/discord_core.spec.md` | v2 Discord voice core in the Rust app: join/leave, per-speaker receive (own reorder window and Opus decoding after songbird decrypts) to the voice worker, sentence playback and stop, slash command, registered chat channels (read/send), voice worker process | Hears only the channel it is in and reads only registered channels; join notice on every join; chat is data and sent text never pings; no transcript or chat text in logs |
The LLM contexts graph at `docs/llm_contexts.md` maps every LLM call in the app (model, gating, inputs, outputs, limits, flow). Keep it up-to-date at all times: any change that adds, removes, or alters an LLM context (model resolution, timeout, cap, prompt source, gating flag, data-flow edge) must update `docs/llm_contexts.md` in the same PR.

2
app/shell/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
target/
gen/

7531
app/shell/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

26
app/shell/Cargo.toml Normal file
View File

@@ -0,0 +1,26 @@
[package]
name = "jarvis-shell"
version = "0.1.0"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"
license = "MIT"
publish = false
[[bin]]
name = "jarvis"
path = "src/main.rs"
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
jarvis-app = { path = ".." }
tauri = { version = "2", features = [] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
[profile.release]
lto = "thin"
codegen-units = 4
strip = "symbols"

3
app/shell/build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "The management window: core only (the app's own `admin` command needs no permission).",
"windows": ["main"],
"permissions": ["core:default"]
}

BIN
app/shell/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
app/shell/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

20
app/shell/package.sh Executable file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
# Build the Windows management app from Linux and lay it out ready to zip (admin.spec.md, "Windows build"):
# Jarvis/jarvis.exe, Jarvis/WebView2Loader.dll, Jarvis/python-src/{voice_worker,jarvis}
# Needs the x86_64-pc-windows-gnu Rust target, mingw-w64 and cmake (for Opus).
# app/shell/package.sh <output folder>
set -eu
here=$(cd "$(dirname "$0")" && pwd)
out=${1:?output folder}
target=${CARGO_TARGET_DIR:-$here/target}
cargo build --release --locked --target x86_64-pc-windows-gnu --manifest-path "$here/Cargo.toml"
rel="$target/x86_64-pc-windows-gnu/release"
rm -rf "$out/Jarvis"
mkdir -p "$out/Jarvis/python-src"
cp "$rel/jarvis.exe" "$rel/WebView2Loader.dll" "$out/Jarvis/"
# The worker and brain sources only (the worker venv gets its packages from the requirement files).
for pkg in voice_worker jarvis; do
(cd "$here/../../src" && find "$pkg" -name __pycache__ -prune -o -name '*.spec.md' -prune -o -type f -print) |
while read -r f; do mkdir -p "$out/Jarvis/python-src/$(dirname "$f")"; cp "$here/../../src/$f" "$out/Jarvis/python-src/$f"; done
done
echo "$out/Jarvis"

62
app/shell/src/main.rs Normal file
View File

@@ -0,0 +1,62 @@
//! Jarvis management app: one Tauri 2 window over the app core (`app/src/admin.spec.md`, "Screens").
//! The screens (`app/ui`) call `invoke("admin", {command, args})`, passed to the same `AdminApi` the
//! development server uses. Closing the window stops the services the app started.
//!
//! jarvis [--location FILE]
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::path::PathBuf;
use std::sync::Arc;
use jarvis_app::admin_api::AdminApi;
use serde_json::Value;
use tauri::{Manager, RunEvent, WebviewUrl, WebviewWindowBuilder};
struct Api(Arc<AdminApi>);
#[tauri::command]
async fn admin(api: tauri::State<'_, Api>, command: String, args: Option<Value>) -> Result<Value, String> {
api.0.call(&command, args.unwrap_or(Value::Null)).await
}
fn arg(name: &str) -> Option<String> {
let args: Vec<String> = std::env::args().collect();
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}
fn main() {
let location = arg("--location").map(PathBuf::from).or_else(jarvis_app::datadir::default_location_file)
.expect("no location file path: pass --location");
// Log files go to the data folder once there is one; until then memory only.
let logs = jarvis_app::datadir::DataDir::locate(&location).map(|d| d.logs());
let hub = jarvis_app::logs::LogHub::new(logs.as_deref());
jarvis_app::logs::install(hub.clone());
let api = Arc::new(AdminApi::new(&location, hub));
// The window's own browser data sits next to the location file, not in a folder of its own.
let webview_data = location.parent().map(|p| p.join("webview"));
let app = tauri::Builder::default()
.manage(Api(api.clone()))
.invoke_handler(tauri::generate_handler![admin])
.setup(move |app| {
let mut w = WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
.title("Jarvis 관리")
.inner_size(1200.0, 820.0)
.min_inner_size(900.0, 600.0);
if let Some(dir) = webview_data.clone() {
w = w.data_directory(dir);
}
w.build()?;
Ok(())
})
.build(tauri::generate_context!())
.expect("the window did not start");
app.run(move |handle, event| {
if let RunEvent::ExitRequested { .. } = event {
jarvis_app::info_log!("app", "window closed: stopping the services");
let api = handle.state::<Api>().0.clone();
tauri::async_runtime::block_on(api.shutdown());
}
});
}

20
app/shell/tauri.conf.json Normal file
View File

@@ -0,0 +1,20 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Jarvis",
"version": "0.1.0",
"identifier": "kr.jarvis.manager",
"build": {
"frontendDist": "../ui"
},
"app": {
"withGlobalTauri": true,
"windows": [],
"security": {
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ipc: http://ipc.localhost"
}
},
"bundle": {
"active": false,
"icon": ["icons/icon.ico", "icons/icon.png"]
}
}

View File

@@ -255,6 +255,20 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
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.
## Window and Windows build (`app/shell/`)
- `jarvis.exe` (crate `jarvis-shell`, Tauri 2 on the WebView2 Windows already has) opens one window
with the screens (`app/ui`) and passes `invoke("admin", {command, args})` to `AdminApi::call`.
`--location FILE` replaces the default location file (`%APPDATA%\JarvisBot\location.json`).
The window's own browser data goes next to the location file (`webview/`), nothing under
`%LOCALAPPDATA%`. Closing the window stops the services and waits until a start in progress is
cancelled (`AdminApi::shutdown`), so nothing the app started keeps running.
- `app/shell/package.sh <folder>` builds it on Linux (`x86_64-pc-windows-gnu`, mingw-w64) and lays
out `Jarvis/`: `jarvis.exe`, `WebView2Loader.dll` and `python-src/` (the `voice_worker` and
`jarvis` packages, no caches or specs). The worker's default sources are `python-src` next to the
executable when it is there, else the repository's `src/`; the install reads its requirement
files from the same place. The installer (NSIS) comes later; the folder runs as it is.
## Tests
`cargo test`: data folder layout, location file and the environment override, a refused relative
@@ -278,5 +292,9 @@ commands (first run: folder then token, the token never returned whole, the wiza
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.
services (wizard, dashboard start, restart and stop, settings save, chat channels, logs, export). On Windows (the win-ci VM, `x86_64-pc-windows-gnu` build): the unit tests (DPAPI, data folder,
downloads, install steps, logs; the Unix-only process tests excepted), and the window by hand: the
wizard's folder, PC check and install (`uv` and the worker venv installed, a cancel leaving no
`uv` or Python process), the token stored DPAPI-encrypted, a start failing with its reason, the
log screen, error copy, zip export, and closing the window ending the process with nothing written
to `%APPDATA%` or `%LOCALAPPDATA%`.

View File

@@ -92,6 +92,23 @@ impl AdminApi {
Ok(c.get_or_insert_with(|| Controller::new(ServicesHost::new(dir.path().to_path_buf()))).clone())
}
/// Stop the services (and cancel a start) when the app closes, so nothing it started (the
/// worker, Strata) keeps running.
pub async fn shutdown(&self) {
let controller = self.controller.lock().unwrap().clone();
if let Some(c) = controller {
if matches!(c.state(), State::Running | State::Starting) {
let _ = c.stop().await;
}
// A cancelled start finishes in the background: wait for it (Strata's stop takes up to
// two minutes) before the app exits.
let until = std::time::Instant::now() + std::time::Duration::from_secs(150);
while matches!(c.state(), State::Starting | State::Stopping) && std::time::Instant::now() < until {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
pub async fn call(&self, command: &str, args: Value) -> Result<Value, String> {
crate::debug_log!("admin", "command {command}");
match command {
@@ -306,6 +323,16 @@ mod tests {
assert!(a.call("service_stop", json!({})).await.is_err());
}
#[tokio::test]
async fn closing_the_app_while_starting_waits_until_everything_is_stopped() {
let (a, base) = api("api5");
a.shutdown().await; // nothing chosen or started yet
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
a.call("service_start", json!({})).await.unwrap();
a.shutdown().await;
assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped"));
}
#[tokio::test]
async fn a_start_is_starting_when_it_answers_so_a_stop_right_after_it_is_not_refused() {
let (a, base) = api("api4");

View File

@@ -71,7 +71,7 @@ strings (numbers would lose precision).
| `voice.stt` | `{}` | Other worker STT settings (`partials`, `end_silence_ms`, `final_beam`, `language`, ...); the worker validates them. |
| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false), answer ("wakeWord")}` per channel; `answer` is in `conversation.spec.md`. |
| `voiceWorker.python` | `python3` (`python.exe` on Windows) | Python of the worker venv. |
| `voiceWorker.cwd` | the repo's `src/` (development builds) | Folder holding the `voice_worker` package. |
| `voiceWorker.cwd` | `python-src` next to the app's executable when it is there (the Windows build), else the repo's `src/` | Folder holding the `voice_worker` package. |
| `voiceWorker.args` | `[]` | Extra worker arguments, e.g. `["--melo-python", "<MeloTTS venv python>"]`. |
| `memory` | `{}` | The worker's memory settings (`voice_worker.spec.md`, "Memory settings"), sent in its `hello`; the settings screens check them (`admin.spec.md`). |

View File

@@ -129,8 +129,7 @@ impl Default for Settings {
chat_channels: vec![],
voice_worker: WorkerSettings {
python: if cfg!(windows) { "python.exe".into() } else { "python3".into() },
// The repo's src/, next to this crate.
cwd: Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src"),
cwd: worker_cwd_for(std::env::current_exe().ok().as_deref()),
args: vec![],
},
call: CallSettings::default(),
@@ -142,6 +141,18 @@ impl Default for Settings {
}
}
/// Where the worker's Python sources (`voice_worker`, `jarvis`) are by default: `python-src` next to
/// the app's executable (the Windows build ships them there), else the repository's `src/` next to
/// this crate (development and tests).
pub fn worker_cwd_for(exe: Option<&Path>) -> PathBuf {
if let Some(shipped) = exe.and_then(Path::parent).map(|d| d.join("python-src")) {
if shipped.join("voice_worker").is_dir() {
return shipped;
}
}
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src")
}
fn err<T>(msg: impl Into<String>) -> Result<T, SettingsError> {
Err(SettingsError(msg.into()))
}
@@ -456,6 +467,16 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn the_python_sources_shipped_next_to_the_app_win_over_the_repository() {
let dir = crate::datadir::temp_dir("pysrc");
let exe = dir.join("jarvis.exe");
assert!(worker_cwd_for(Some(&exe)).ends_with("src"), "nothing shipped: the repository's src/");
std::fs::create_dir_all(dir.join("python-src").join("voice_worker")).unwrap();
assert_eq!(worker_cwd_for(Some(&exe)), dir.join("python-src"));
assert_eq!(worker_cwd_for(None), Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src"));
}
const ID: &str = "123456789012345678";
const IDN: u64 = 123456789012345678;

View File

@@ -364,6 +364,7 @@ mod tests {
assert!(Path::new(v["db_path"].as_str().unwrap()).starts_with(&l.data));
}
#[cfg(unix)]
/// Default settings on a port nothing listens on (8080 may be taken on a developer's PC).
fn unused_port_settings() -> Settings {
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
@@ -375,6 +376,7 @@ mod tests {
serve(id, delay, None, Arc::new(Mutex::new("list"))).await
}
#[cfg(unix)]
/// The same; once the file `gone` exists (a fake Strata's `--stop` makes it) it stops listening,
/// so a connection is refused.
async fn models_server_until(id: &'static str, delay: Duration, gone: Option<std::path::PathBuf>) -> u16 {
@@ -606,12 +608,15 @@ mod tests {
c.stop().await.unwrap();
}
#[cfg(unix)]
/// The services as the controller sees them, reduced to the LLM.
struct LlmHost {
llm: Arc<Llm>,
settings: Settings,
}
#[cfg(unix)]
struct LlmRunning(Arc<Llm>);
#[cfg(unix)]
#[async_trait::async_trait]
impl crate::control::Running for LlmRunning {
async fn stop(&self) -> Result<(), String> {
@@ -621,6 +626,7 @@ mod tests {
json!({"worker": null, "voiceMembers": [], "missed": []})
}
}
#[cfg(unix)]
#[async_trait::async_trait]
impl crate::control::Host for LlmHost {
async fn start(&self) -> Result<(Arc<dyn crate::control::Running>, tokio::sync::mpsc::UnboundedReceiver<crate::discord::CoreEvent>), String> {

View File

@@ -214,13 +214,15 @@ async function tokenCard() {
const st = await api("token_status");
const input = h("input", { type: "password", placeholder: "새 봇 토큰", autocomplete: "off" });
const out = h("div", { class: "small muted" });
const label = h("span", {}, st.set ? st.masked : "저장된 토큰 없음");
return h("div", { class: "card" }, h("h2", {}, "봇 토큰"),
h("div", { class: "row" }, h("span", {}, st.set ? st.masked : "저장된 토큰 없음"), input,
h("div", { class: "row" }, label, input,
h("button", { class: "btn", onclick: async () => {
try {
const c = await api("token_check", { token: input.value });
await api("token_save", { token: input.value });
input.value = "";
label.textContent = (await api("token_status")).masked;
out.textContent = `${c.botTag} 저장함. Message Content 권한: ${c.messageContent ? "켜짐" : "꺼짐"}`;
} catch (e) { fail(e); }
} }, "확인 후 저장")), out);