Run 35B MoE models in ~2.5 GB of RAM. Weights stream from SSD; a trained router predicts loads a step ahead. Mac, iPhone, Android, Windows supported
Python
add windows and android version
Binf41da5d5edb8
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..c38d98f--- /dev/null+++ b/.gitattributes@@ -0,0 +1,24 @@+# House rule: all text is stored and checked out with LF.+# (Batch wrappers are the only exception -- cmd.exe needs CRLF.)+* text=auto eol=lf+*.bat text eol=crlf+*.cmd text eol=crlf++# Binaries: never touch line endings, never treat as text+*.so binary+*.a binary+*.dll binary+*.exe binary+*.png binary+*.jpg binary+*.jpeg binary+*.ico binary+*.icns binary+*.jar binary+*.zip binary+*.bin binary+*.gguf binary+*.safetensors binary+*.e0b binary+# repo-specific addition: the technical report lives at paper/main.pdf+*.pdf binarydiff --git a/.gitignore b/.gitignoreindex 623ec53..b2587d4 100644--- a/.gitignore+++ b/.gitignore@@ -18,6 +18,13 @@ artifacts//models//python/models/+# Platform build areas materialized by the engine/vendor scripts (never commit):+# isolated patch-replay worktrees, the pinned llama.cpp checkout, and the+# local engine-depot bootstrap fallback (see windows/scripts/vendor-build.ps1).+/wt/+/vendor/+.edge0/+# macOS.DS_Storediff --git a/android/.gitignore b/android/.gitignorenew file mode 100644index 0000000..6249d89--- /dev/null+++ b/android/.gitignore@@ -0,0 +1,16 @@+*.iml+.gradle+/local.properties+/.idea+.DS_Store+/build+*/build+*/.cxx+/captures+.externalNativeBuild+.cxx+local.properties+# engine build workbench (staging for libs; artifacts are never committed)+/build-dl+# model sources and converted gguf (self-service downloads)+/modelsdiff --git a/android/NOTICE b/android/NOTICEnew file mode 100644index 0000000..e7f3546--- /dev/null+++ b/android/NOTICE@@ -0,0 +1,20 @@+NOTICE - edge0 / android+================================++Licensed under Apache-2.0 (see the LICENSE at the monorepo root). Besides our+own code, this project contains or references the following third-party material:++1. llama.cpp - MIT (commit 7ab4ee7, release b11100, pinned)+ Location: ../vendor/llama.cpp (pristine upstream checkout, never patched in+ place). Built with ../patches/llama.cpp/{common,android} replayed (20+ hook-point bands) into the shipped shared libraries (libllama, libggml*).+ ggml (Apache-2.0) is developed inside the same upstream tree. Not vendored+ as files; built from source by the consumer (tools/llama/build_vendor_libs.sh).++2. Gradle/Maven dependencies (Apache-2.0 / MIT / BSD)+ Kotlin, Jetpack Compose, AndroidX (Activity, Room, DataStore, Lifecycle),+ kotlinx-serialization, mikepenz multiplatform-markdown-renderer-m3 (MIT),+ JUnit. Resolved at build time; each ships its own license text.++3. Model assets - Edge0/Edge0-8B-A1B-preview and Edge0/Edge0-35B-A3B-preview on+ Hugging Face; terms per the model cards. Not part of the source distribution.diff --git a/android/README.md b/android/README.mdindex bb891b6..af27957 100644--- a/android/README.md+++ b/android/README.md@@ -1,23 +1,183 @@-# edge0 — Android runtime+# edge0-android — Release Build Guide-> ✅ Open-sourced on **2026-09-30**. This README will be updated with-> full build & usage docs together with the source drop.+This document is for **developers building or evaluating the Android app from source**. It covers: quick start (engine → app → models → test), measured performance on the reference device, and the technical choices behind the stack.-The Android runtime runs the edge0 models fully on-device on Android-(Kotlin app + native inference engine): local streaming MoE inference-with the same recipe as the rest of the framework — SSD expert offload,-Recover-LoRA, and prerouter routing prediction.+edge0 is published as a **monorepo** — [`Edge0-AI/edge0`](https://github.com/Edge0-AI/edge0) — whose top level holds the shared engine supply (`vendor.llama.pin` + the scripts-materialized `vendor/llama.cpp`, `patches/llama.cpp/` band-sets) and the platform subprojects (`windows/` = the desktop companion, `android/` = this app). Inference runs on pinned upstream llama.cpp, patched as a replayable patch set, fully on-CPU with ARM-NEON kernels and a demand-paged expert pool.-The next milestone is the **unified inference framework** — one access-layer, runtime auto-adapting to the hardware platform (iOS / macOS /-Android / Windows / Python) — targeted for **Q4 2026**;-see the [roadmap](../README.md#roadmap).+Third-party attribution: see `NOTICE` in this directory. Model cards: [Edge0/Edge0-8B-A1B-preview](https://huggingface.co/Edge0/Edge0-8B-A1B-preview) · [Edge0/Edge0-35B-A3B-preview](https://huggingface.co/Edge0/Edge0-35B-A3B-preview).-See the [repository README](../README.md) for the multi-platform picture.+---++## 1. Quick Start++### 1.1 Prerequisites++| component | requirement |+|---|---|+| Device | arm64-v8a, Android 13+ (API 33); Snapdragon 8 Elite class recommended |+| RAM | 8 GB+ runs 8B; 12–16 GB runs 35B (expert paging, see §3.2) |+| Toolchain | JDK 17+, Android SDK 35, **NDK r28** (`28.2.13676358`), CMake ≥ 3.21 + Ninja |+| Python | 3.10+ with `numpy` (model converter, runs from the sibling `windows/tools`) |+| Disk | ≥ 30 GB free for model sources and converted GGUF builds |++The NDK is **not** part of this repository — install it once (Android Studio:+*Android SDK → SDK Tools → NDK (Side by side)*, or via CLI):++```bash+sdkmanager --install "ndk;28.2.13676358"+```++Then point the build at it with `NDK_DIR` (or an exported `ANDROID_NDK_HOME`):+`build_vendor_libs.sh` reads the compiler toolchain **and** the `libomp.so`+runtime it stages (§1.2) from inside that NDK installation; a missing NDK+fails fast with that hint rather than producing a broken library set.++### 1.2 Build the engine++The native libraries come from the pinned upstream tree with this platform's+patch bands replayed into an isolated worktree — the vendor tree is **never+patched in place**:++```bash+git clone https://github.com/Edge0-AI/edge0+cd edge0/android+bash tools/llama/build_vendor_libs.sh+```++The script replays `../patches/llama.cpp/{common,android}` (6 + 14 bands) onto+the pinned llama.cpp tree — the pin lives in `../vendor.llama.pin` (currently+`7ab4ee7`, tag b11100); the tree is **not** a submodule, so on first run it is+cloned from upstream into `../vendor/llama.cpp` (gitignored; set+`EDGE0_LLAMA_URL` to use a mirror) and detached at the pin. Replays happen in a+gitignored consumer worktree, the script+asserts the golden result-tree hash, and produces the four engine shared+libraries (plus the NDK `libomp.so` runtime that `libggml-cpu` needs) with+headers into `build-dl/llama-libs/` (the app's jniLibs staging point).+`--replay` re-applies the bands after patch changes; mismatched tree ⇒ RED, the+build refuses to start. This step is required once before the app build —+the Gradle plugin reads these libraries from `build-dl/llama-libs/`.++### 1.3 Build & install the app++```bash+./gradlew :app:assembleDebug+./gradlew :app:installDebug # or adb install -r app/build/outputs/apk/debug/app-debug.apk+```++### 1.4 Models++GGUF builds are produced locally from the published checkpoints — everything+stays under this directory's `models/` (gitignored):++```bash+huggingface-cli download Edge0/Edge0-8B-A1B-preview --local-dir models/edge0-8b+python ../windows/tools/convert_mlx_to_gguf.py --dir models/edge0-8b+# → models/edge0-8b-gguf/{edge0-8b.gguf, lora_edge0_8b-gguf.gguf, manifest.json}++huggingface-cli download Edge0/Edge0-35B-A3B-preview --local-dir models/edge0-35b+python ../windows/tools/convert_mlx_to_gguf.py --dir models/edge0-35b++bash tools/model/push_models.sh --all # md5-gated staging onto the device+```++The converter needs only python3 + numpy (no MLX/torch runtime — "MLX" denotes+the on-disk checkpoint layout). It runs the r3 repack with numeric parity gates+and emits a sha256 manifest; a correct conversion reproduces the baseline+checksums listed in `push_models.sh` byte-for-byte. Models can also be copied+into `files/models/` with the in-app picker.++### 1.5 Run++Launch **Edge0 Chat**. The title bar shows the active model (8B / 35B), the+top-right button switches. The composer is send-only; temperature, thinking and+the system prompt live in the drawer settings. Each reply carries an inline+metrics line: `tokens · TTFT · prefill t/s · decode t/s · RSS`.++### 1.6 Test it++Instrumented regression (needs both models staged — reinstalling the test APK+wipes app data, so restage right before the run):++```bash+./gradlew :app:installDebugAndroidTest+bash tools/model/push_models.sh --all+adb shell am instrument -w -e class dev.edge0.runtime.app.LlamaRuntimeTest \+ dev.edge0.runtime.app.test/androidx.test.runner.AndroidJUnitRunner+# expected: OK (8 tests), ~7 min on the reference device+```++Coverage: 8B/35B smoke, 35B↔8B in-process switching, prefix-reuse fidelity,+thinking on/off × system-prompt quadrants (8B gate + 35B off leak probe), and+identity retention across multi-turn rendering. Host-side logic tests:+`./gradlew :app:testDebugUnitTest` (26 tests, no device needed).++---++## 2. Performance++Reference device: **Lenovo TB322FC (Snapdragon 8 Elite, 16 GB RAM)**, shipping+config, sustained windows (first segments = boost clocks, tail = thermal steady+state — both reported rather than cherry-picked peaks).++| Model | TTFT (warm turn) | Decode | Prefill | Session RSS |+|---|---:|---:|---:|---:|+| **8B** (Q8-class GGUF + LoRA) | ≈ 1.4 s | 29–32 → ~10 t/s over a 480 s window | ~100 t/s | ≈ 250 MB |+| **35B** (mixed int8 MoE, demand-paged) | ≈ 1.1 s warm (≈ 10–15 s on the very first turn of a new topic — cold expert pool, flash-bound) | 6–9 t/s in-app (9.46 t/s sustained CLI) | ~1 s per incremental turn | pool budget 2–6 GB; resident ≪ file size |++Notes: "first turn of a new topic" pays the cold-pool tax — e.g. a 55-token+question measured prefill 12.8 s with 25956 expert loads, 73 % of wall time in+flash I/O wait; that is demand paging working as designed, not a regression.+Turn two onwards is warm: KV prefix reuse + keepwarm refill bring TTFT to ~1 s.+Decode decay along a long window is DVFS/thermal behavior on this SoC.----> ✅ 源码已于 **2026-09-30** 开源,本 README 将随源码落库补全完整的构建-> 与使用文档。Android runtime:Kotlin App + 原生推理引擎的端侧推理。-> **统一推理框架**将于 **2026 Q4** 发布,详见-> [根 README 路线图](../README_zh.md)。+## 3. Technical Details++### 3.1 Architecture++```mermaid+graph TD+ subgraph App ["Kotlin / Jetpack Compose"]+ UI[ChatScreen · dark · send-only composer] --> VM[ChatViewModel]+ VM --> RT[LlamaRuntime<br/>coroutines + Flow events]+ VM --> DB[(Room · threads & messages)]+ ST[SettingsStore] --> VM+ end+ subgraph Native ["C JNI shell (llama_chat.c)"]+ SHELL[generate loop · template-aware thinking control<br/>segment-wise history render · UTF-8-safe streaming]+ end+ subgraph Engine ["patched llama.cpp @ b11100 · arm64 CPU-only"]+ LLIB[libllama.so]+ GCPU[libggml-cpu.so<br/>NEON kernels + moe_pool]+ end+ RT -->|JNI| SHELL --> LLIB --> GCPU+ GCPU -->|demand-paged expert IO| MODELS[GGUF on flash]+```++### 3.2 Why a 21.7 GB MoE fits on a phone — `moe_pool`++The 35B model activates only a moving subset of its 256-per-layer experts per+token, so the shipped design pages experts **on demand** from flash instead of+resident memory (`ggml/src/ggml-cpu/moe_pool.c`, developed as the 14-patch+android band): copy-in private frames, an equal-slot state machine, background+IO staging queues tuned to measured UFS throughput, pin/blob/trim controls, a+turn-end keepwarm refill within a byte budget, and full cross-model reset+enabling 8B↔35B switching inside one process. With the pool disabled the engine+resolves expert rows exactly like upstream (NULL resolver ⇒ zero perturbation,+verified by symbol-set diffing). This is the same mechanism family the desktop+project implements over NVMe + Vulkan; here it is CPU/NEON by design — GPU+backends stay out of the shipping config for deterministic numerics and a+single memory model.++### 3.3 Repo map++```+app/ Android app: Compose UI (src/main/java), JNI shell (src/main/cpp),+ instrumented + unit tests (src/androidTest, src/test)+tools/llama/ build_vendor_libs.sh — engine rebuild from the pinned tree + bands+tools/model/ push_models.sh — md5-gated model staging to devices+../vendor/llama.cpp/ materialized by the build scripts from vendor.llama.pin (gitignored; never patched in place)+../patches/llama.cpp/ common(6) + android(14) hook-point bands + ledger README+../windows/ desktop companion — hosts the MLX→GGUF converter used in §1.4+```diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.ktsnew file mode 100644index 0000000..37876ca--- /dev/null+++ b/android/app/build.gradle.kts@@ -0,0 +1,95 @@+// app/build.gradle.kts - the chat app module.+// Single APK: native llama shell (shared libs staged via jniLibs) + Compose UI.+// git SHA provenance: configuration cache forbids external processes at configure time,+// so the build takes E0_GIT_SHA from the environment:+// unset falls back to "unknown" (never blocks the build).+plugins {+ alias(libs.plugins.android.application)+ alias(libs.plugins.kotlin.android)+ alias(libs.plugins.kotlin.compose)+ alias(libs.plugins.ksp)+ alias(libs.plugins.kotlinx.serialization)+}++android {+ namespace = "dev.edge0.runtime.app"+ compileSdk = libs.versions.compileSdk.get().toInt()++ defaultConfig {+ applicationId = "dev.edge0.runtime.app"+ minSdk = libs.versions.minSdk.get().toInt()+ targetSdk = libs.versions.compileSdk.get().toInt()+ versionCode = 1+ versionName = "0.1.0"+ ndk { abiFilters += "arm64-v8a" } // arm64 only+ externalNativeBuild {+ cmake {+ abiFilters += "arm64-v8a"+ arguments += "-DLLAMA_LIBS=" + rootProject.file("build-dl/llama-libs/arm64-v8a").absolutePath+ }+ }+ // instrumented suites follow install -> stage assets -> instrument; the first step is gradle.+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"+ buildConfigField("String", "GIT_SHA",+ "\"${System.getenv("E0_GIT_SHA") ?: "unknown"}\"")+ }+ buildTypes {+ debug { isMinifyEnabled = false }+ release {+ isMinifyEnabled = false // no minification at this stage+ }+ }+ // llama native shell; .so assembly point is build-dl/llama-libs (gitignored)+ externalNativeBuild { cmake { path = file("src/main/cpp/CMakeLists.txt"); version = "3.22.1" } }+ sourceSets {+ getByName("main") {+ val ll = rootProject.file("build-dl/llama-libs/arm64-v8a")+ if (ll.isDirectory) jniLibs.srcDirs(rootProject.file("build-dl/llama-libs"))+ }+ }++ buildFeatures {+ compose = true+ buildConfig = true+ }+ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }+ kotlinOptions { jvmTarget = "17" }+ packaging {+ resources.excludes += "/META-INF/{AL2.0,LGPL2.1}"+ }+}++ksp {+ // Room schema export into app/schemas/ for migration traceability+ arg("room.schemaLocation", "$projectDir/schemas".toString())+ arg("room.generateKotlin", "true")+}++dependencies {+ implementation(platform(libs.compose.bom))+ implementation(libs.compose.ui)+ implementation(libs.compose.ui.tooling.preview)+ implementation(libs.compose.material3)+ implementation(libs.compose.material.icons.extended)+ debugImplementation(libs.compose.ui.tooling)+ implementation(libs.androidx.activity.compose)+ implementation(libs.androidx.navigation.compose)+ implementation(libs.androidx.lifecycle.viewmodel.compose)+ implementation(libs.androidx.lifecycle.runtime.compose)+ implementation(libs.androidx.lifecycle.process) // lifecycle hooks for trim mapping+ implementation(libs.androidx.room.runtime)+ implementation(libs.androidx.room.ktx)+ ksp(libs.androidx.room.compiler)+ implementation(libs.androidx.datastore.preferences)+ implementation(libs.kotlinx.coroutines.android)+ implementation(libs.kotlinx.serialization.json)+ implementation(libs.markdown.renderer.m3) // markdown rendering (tables/links/strikethrough)++ testImplementation("junit:junit:4.13.2") // JVM unit tests+ androidTestImplementation("junit:junit:4.13.2")+ androidTestImplementation("androidx.test.ext:junit:1.2.1")+ androidTestImplementation("androidx.test:runner:1.6.2")+}diff --git a/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/1.json b/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/1.jsonnew file mode 100644index 0000000..c7705c3--- /dev/null+++ b/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/1.json@@ -0,0 +1,169 @@+{+ "formatVersion": 1,+ "database": {+ "version": 1,+ "identityHash": "7e3b71bb48f755556c1020fe2717fb45",+ "entities": [+ {+ "tableName": "threads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `title` TEXT, `modelId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "modelId",+ "columnName": "modelId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updatedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_threads_updatedAt",+ "unique": false,+ "columnNames": [+ "updatedAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_threads_updatedAt` ON `${TABLE_NAME}` (`updatedAt`)"+ }+ ]+ },+ {+ "tableName": "messages",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `threadId` TEXT NOT NULL, `role` TEXT NOT NULL, `content` TEXT NOT NULL, `thinking` TEXT, `thinkingMs` INTEGER, `status` TEXT NOT NULL, `modelId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `promptTokens` INTEGER, `newTokens` INTEGER, `decodeTokS` REAL, PRIMARY KEY(`id`), FOREIGN KEY(`threadId`) REFERENCES `threads`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "threadId",+ "columnName": "threadId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "role",+ "columnName": "role",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "content",+ "columnName": "content",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "thinking",+ "columnName": "thinking",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "thinkingMs",+ "columnName": "thinkingMs",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "modelId",+ "columnName": "modelId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "promptTokens",+ "columnName": "promptTokens",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "newTokens",+ "columnName": "newTokens",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "decodeTokS",+ "columnName": "decodeTokS",+ "affinity": "REAL"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_messages_threadId_createdAt",+ "unique": false,+ "columnNames": [+ "threadId",+ "createdAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_threadId_createdAt` ON `${TABLE_NAME}` (`threadId`, `createdAt`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "threads",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "threadId"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7e3b71bb48f755556c1020fe2717fb45')"+ ]+ }+}\ No newline at end of filediff --git a/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/2.json b/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/2.jsonnew file mode 100644index 0000000..e39ee62--- /dev/null+++ b/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/2.json@@ -0,0 +1,174 @@+{+ "formatVersion": 1,+ "database": {+ "version": 2,+ "identityHash": "95511891effc3c18a7d5a92ebfc02e22",+ "entities": [+ {+ "tableName": "threads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `title` TEXT, `modelId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "modelId",+ "columnName": "modelId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updatedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_threads_updatedAt",+ "unique": false,+ "columnNames": [+ "updatedAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_threads_updatedAt` ON `${TABLE_NAME}` (`updatedAt`)"+ }+ ]+ },+ {+ "tableName": "messages",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `threadId` TEXT NOT NULL, `role` TEXT NOT NULL, `content` TEXT NOT NULL, `thinking` TEXT, `thinkingMs` INTEGER, `status` TEXT NOT NULL, `modelId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `promptTokens` INTEGER, `newTokens` INTEGER, `decodeTokS` REAL, `genTokens` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`threadId`) REFERENCES `threads`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "threadId",+ "columnName": "threadId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "role",+ "columnName": "role",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "content",+ "columnName": "content",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "thinking",+ "columnName": "thinking",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "thinkingMs",+ "columnName": "thinkingMs",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "modelId",+ "columnName": "modelId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "promptTokens",+ "columnName": "promptTokens",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "newTokens",+ "columnName": "newTokens",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "decodeTokS",+ "columnName": "decodeTokS",+ "affinity": "REAL"+ },+ {+ "fieldPath": "genTokens",+ "columnName": "genTokens",+ "affinity": "BLOB"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_messages_threadId_createdAt",+ "unique": false,+ "columnNames": [+ "threadId",+ "createdAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_threadId_createdAt` ON `${TABLE_NAME}` (`threadId`, `createdAt`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "threads",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "threadId"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '95511891effc3c18a7d5a92ebfc02e22')"+ ]+ }+}\ No newline at end of filediff --git a/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/3.json b/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/3.jsonnew file mode 100644index 0000000..e795529--- /dev/null+++ b/android/app/schemas/dev.edge0.runtime.app.data.AppDatabase/3.json@@ -0,0 +1,189 @@+{+ "formatVersion": 1,+ "database": {+ "version": 3,+ "identityHash": "bedb08d6046568298f8264b8d94ffd0f",+ "entities": [+ {+ "tableName": "threads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `title` TEXT, `modelId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "modelId",+ "columnName": "modelId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updatedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_threads_updatedAt",+ "unique": false,+ "columnNames": [+ "updatedAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_threads_updatedAt` ON `${TABLE_NAME}` (`updatedAt`)"+ }+ ]+ },+ {+ "tableName": "messages",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `threadId` TEXT NOT NULL, `role` TEXT NOT NULL, `content` TEXT NOT NULL, `thinking` TEXT, `thinkingMs` INTEGER, `status` TEXT NOT NULL, `modelId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `promptTokens` INTEGER, `newTokens` INTEGER, `decodeTokS` REAL, `genTokens` BLOB, `ttftMs` INTEGER, `prefillTokS` REAL, `memBytes` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`threadId`) REFERENCES `threads`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "threadId",+ "columnName": "threadId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "role",+ "columnName": "role",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "content",+ "columnName": "content",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "thinking",+ "columnName": "thinking",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "thinkingMs",+ "columnName": "thinkingMs",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "modelId",+ "columnName": "modelId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "promptTokens",+ "columnName": "promptTokens",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "newTokens",+ "columnName": "newTokens",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "decodeTokS",+ "columnName": "decodeTokS",+ "affinity": "REAL"+ },+ {+ "fieldPath": "genTokens",+ "columnName": "genTokens",+ "affinity": "BLOB"+ },+ {+ "fieldPath": "ttftMs",+ "columnName": "ttftMs",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "prefillTokS",+ "columnName": "prefillTokS",+ "affinity": "REAL"+ },+ {+ "fieldPath": "memBytes",+ "columnName": "memBytes",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_messages_threadId_createdAt",+ "unique": false,+ "columnNames": [+ "threadId",+ "createdAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_threadId_createdAt` ON `${TABLE_NAME}` (`threadId`, `createdAt`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "threads",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "threadId"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'bedb08d6046568298f8264b8d94ffd0f')"+ ]+ }+}\ No newline at end of filediff --git a/android/app/src/androidTest/java/dev/edge0/runtime/app/LlamaRuntimeTest.kt b/android/app/src/androidTest/java/dev/edge0/runtime/app/LlamaRuntimeTest.ktnew file mode 100644index 0000000..4744267--- /dev/null+++ b/android/app/src/androidTest/java/dev/edge0/runtime/app/LlamaRuntimeTest.kt@@ -0,0 +1,326 @@+// LlamaRuntimeTest - app-domain smoke suite for the llama engine shell.+// Prerequisite: stage the models AFTER installing the test APK -+// adb shell run-as dev.edge0.runtime.app cp /data/local/tmp/lgguf/edge0-8b.gguf files/models/edge0-8b.gguf+// instrumented installs wipe app data, so staging must follow installation.+// Assertions keep a conservative floor (availability over speed; the CLI benchmark+// owns ceiling checks): >= 8 tokens produced, decode > 1 t/s, non-empty text.+package dev.edge0.runtime.app++import dev.edge0.runtime.app.runtime.GenEvent+import dev.edge0.runtime.app.runtime.LlamaRuntime+import dev.edge0.runtime.engine.ChatMessage+import dev.edge0.runtime.engine.GenParams+import kotlinx.coroutines.flow.toList+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.File++class LlamaRuntimeTest {+ @Test+ fun eightBChatRoundTrip() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ // files staged via run-as may carry an SELinux label the instrumentation cannot+ // read; search candidate roots instead. Production loads through the normal path.+ val want = androidx.test.platform.app.InstrumentationRegistry.getArguments()+ .getString("model") ?: "edge0-35b.gguf"+ val model = sequenceOf(+ File(ctx.getDir("models", 0), want),+ File(ctx.filesDir, "models/$want"),+ File(ctx.cacheDir, "models/$want"),+ File(ctx.getExternalFilesDir(null) ?: ctx.filesDir, "models/$want"),+ ).firstOrNull { it.isFile }+ ?: run {+ val hit = generateSequence(ctx.dataDir) { f ->+ f.listFiles()?.firstOrNull { it.isDirectory && !it.name.startsWith(".") }+ }.flatMap { (it.walk().firstOrNull { f2 -> f2.name == want }?.let { x -> sequenceOf(x) } ?: emptySequence()) }+ .firstOrNull()+ hit ?: File(ctx.getDir("models", 0), want)+ }+ assertTrue("model not found anywhere: ${model.path}", model.isFile)++ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ assertTrue("load failed: ${rt.state.value}", rt.activeModelDir != null)++ val pieces = StringBuilder()+ var tps = 0.0+ rt.submit("t1", listOf(ChatMessage("user", "Introduce yourself in one sentence")),+ true, GenParams(temperature = 0f, maxNewTokens = 32))+ .toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> pieces.append(ev.s)+ is GenEvent.ThinkPiece -> pieces.append(ev.s)+ is GenEvent.Done -> tps = ev.metrics?.decodeTokS ?: 0.0+ is GenEvent.Failed -> throw AssertionError("gen failed: ${ev.diag}")+ else -> Unit+ }+ }+ android.util.Log.i("LlamaRT", "reply=${pieces.take(80)} tps=$tps")+ // metrics wiring assertions (pool/rss must not be N/A)+ val rm = rt.lastMetrics.value+ assertTrue("metrics missing", rm != null)+ assertTrue("pool metrics missing", rm?.pool != null)+ if (want.contains("35b")) {+ assertTrue("35B pool counters not wired", (rm!!.pool!!.hits + rm.pool!!.misses) > 0 && rm.pool!!.slots_total > 0)+ } else {+ // the 8B tier is fully resident: counters exist and read zero - that is the correct shape+ assertTrue("8B should not occupy the pool", rm!!.pool!!.slots_total == 0L)+ }+ assertTrue("peak rss N/A", (rm?.peakRssBytes ?: 0L) > 100L * 1024 * 1024)+ assertTrue("first-token timing anomaly: ${rm?.firstTokenMs}", (rm?.firstTokenMs ?: 0) > 0)+ assertTrue("empty reply", pieces.isNotBlank())+ val floor = if (want.contains("35b")) 0.5 else 1.0+ assertTrue("tps too low: $tps", tps > floor)++ // second turn exercises KV prefix reuse (history diff sync)+ val r2 = rt.submit("t2", listOf(+ ChatMessage("user", "Introduce yourself in one sentence"),+ ChatMessage("assistant", pieces.toString().trim().take(40)),+ ChatMessage("user", "a bit shorter"),+ ), true, GenParams(temperature = 0f, maxNewTokens = 24)).toList()+ assertTrue("round2 no done", r2.any { it is GenEvent.Done })+ rt.unloadActive()+ }++ // crash regression: use 8B, switch to 35B, send in a new session - stale LoRA/session+// state attaching to the new graph used to abort; bidirectional switching must survive.+ @Test+ fun switch8bThen35bSurvival() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ fun find(n: String) = sequenceOf(File(ctx.getDir("models", 0), n), File(ctx.filesDir, "models/$n"))+ .firstOrNull { it.isFile }+ val m8 = find("edge0-8b.gguf") ?: return@runBlocking+ val rt = LlamaRuntime()+ fun round(model: File, q: String) = runBlocking {+ rt.ensureLoaded(model.absolutePath)+ assertTrue("load fail ${model.name}: ${rt.state.value}", rt.activeModelDir != null)+ var n = 0+ rt.submit("sw", listOf(ChatMessage("user", q)), true,+ GenParams(temperature = 0f, maxNewTokens = 8))+ .toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> n += ev.s.length+ is GenEvent.ThinkPiece -> n += ev.s.length+ is GenEvent.Failed -> throw AssertionError("${model.name}: ${ev.diag}")+ else -> Unit+ }+ }+ assertTrue("no output ${model.name}", n > 2)+ }+ round(m8, "hello")+ val m35 = find("edge0-35b.gguf")+ if (m35 != null) {+ round(m35, "hello") // the original crash point+ round(m8, "hello") // switch back (pool/registry reset verified both ways)+ }+ rt.unloadActive()+ }++ // real multi-turn on 35B (long answer, then thanks): log reused/prefill per round to locate forks+ @Test+ fun prefixReuseProbe() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ val want = androidx.test.platform.app.InstrumentationRegistry.getArguments()+ .getString("model") ?: "edge0-35b.gguf"+ val model = sequenceOf(File(ctx.getDir("models", 0), want), File(ctx.filesDir, "models/$want"))+ .firstOrNull { it.isFile } ?: return@runBlocking+ val syncMode = androidx.test.platform.app.InstrumentationRegistry.getArguments()+ .getString("sync") ?: ""+ if (syncMode.isNotEmpty()) android.system.Os.setenv("E0_POOL_SYNC", "1", true)+ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ val probeThinking = (androidx.test.platform.app.InstrumentationRegistry.getArguments()+ .getString("thinking") ?: "off") == "on"+ val hist = mutableListOf<ChatMessage>()+ val qs = listOf("Describe three core advantages of Mixture-of-Experts models in detail.", "thanks")+ for ((i, q) in qs.withIndex()) {+ hist.add(ChatMessage("user", q))+ val sb = StringBuilder()+ rt.submit("probe$i", hist.toList(), probeThinking, GenParams(temperature = 0f, maxNewTokens = if (i == 0) 200 else 20))+ .toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> sb.append(ev.s)+ is GenEvent.ThinkPiece -> sb.append("«T»").append(ev.s)+ is GenEvent.Failed -> throw AssertionError(ev.diag)+ else -> Unit+ }+ }+ hist.add(ChatMessage("assistant", sb.toString()))+ if (i == 0) Thread.sleep(25000) // simulate reading the reply: the keepwarm battleground+ android.util.Log.i("ReuseProbe", "round$i head=[${sb.toString().take(70).replace("\n", " | ")}] len=${sb.length} metrics=${rt.lastMetrics.value?.let { "prompt=${it.promptTokens} reused=${it.prefix_reused_tokens} prefill_ms=${it.prefillMs} first_ms=${it.firstTokenMs} pool=${it.pool?.let { q -> "hits=${q.hits} miss=${q.misses} evict=${q.evictions} stall_ms=${q.stall_ns / 1000000} res_MB=${q.resident_bytes / 1048576} pf=${q.prefetch_used}/${q.prefetch_mispredict}" }}" }}")+ }+ rt.unloadActive()+ }++ // thinking quality gate: same greedy prompt, 12 tokens, quadrants of {system,thinking}.+ // Verdict via logcat ThinkGate: off cells must answer directly, on cells must think.+ // Regression anchor: custom-system off leaking thinking (the ensure-position fix).+ @Test+ fun thinkSwitchQualityGate() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ val want = androidx.test.platform.app.InstrumentationRegistry.getArguments()+ .getString("model") ?: "edge0-8b.gguf"+ val model = sequenceOf(File(ctx.getDir("models", 0), want), File(ctx.filesDir, "models/$want"))+ .firstOrNull { it.isFile } ?: return@runBlocking+ val q = "Explain why the sky is blue in one short sentence."+ val sp = "You're Edge0, an on-device AI assistant."+ val heads = ArrayList<String>()+ for (sys in listOf(false, true)) for (th in listOf(false, true)) {+ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ val base0 = if (sys) listOf(ChatMessage("system", sp)) else emptyList()+ val turns = ArrayList<String>()+ val hist = base0.toMutableList()+ for (t in 0..1) { // round two goes through the sidecar path (the empty-answer incident scene)+ val sb = StringBuilder()+ hist.add(ChatMessage("user", if (t == 0) q else "thanks, one more short sentence"))+ rt.submit("g$sys$th$t", hist.toList(), th,+ GenParams(temperature = 0f, maxNewTokens = 12))+ .toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> sb.append(ev.s)+ is GenEvent.ThinkPiece -> sb.append("<T>").append(ev.s)+ is GenEvent.Failed -> throw AssertionError(ev.diag)+ else -> Unit+ }+ }+ turns.add("t" + t + "=" + sb.toString().take(44).replace("\n", " "))+ hist.add(ChatMessage("assistant", sb.toString()))+ }+ heads.add((if (sys) "sys" else "no") + "-th" + (if (th) "on" else "off") + ": " + turns.joinToString(" ~ "))+ // empty-answer anchor: no quadrant, no round may return empty+ org.junit.Assert.assertTrue("gate: empty reply in " + heads.last(),+ turns.all { it.length > 6 })+ rt.unloadActive()+ }+ android.util.Log.i("ThinkGate", heads.joinToString(" ||| "))+ org.junit.Assert.assertTrue("gate: 4 quadrants", heads.size == 4)+ org.junit.Assert.assertTrue("gate: off-no-sys empty", heads[0].length > 12)+ }++ // multi-turn identity probe: chat once (builds sidecar history), then ask who you are.+ // Single-turn was green; the incident lived in the multi-turn path.+ @Test+ fun whoAreYouSysProbe() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ val model = File(ctx.filesDir, "models/edge0-8b.gguf")+ if (!model.isFile) return@runBlocking+ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ var heads_all = ""+ val hist = mutableListOf(ChatMessage("system", "You're Edge0, an on-device AI assistant."))+ for ((i, q) in listOf("What is the capital of France? One word.",+ "Who are you? What is your name? Answer in one sentence.").withIndex()) {+ hist.add(ChatMessage("user", q))+ val sb = StringBuilder()+ rt.submit("way$i", hist.toList(), false, GenParams(temperature = 0.2f, maxNewTokens = 60))+ .toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> sb.append(ev.s)+ is GenEvent.ThinkPiece -> sb.append("<T>")+ is GenEvent.Failed -> throw AssertionError(ev.diag)+ else -> Unit+ }+ }+ heads_all += sb.toString(); android.util.Log.i("WayProbe", "turn" + i + " len=" + sb.length + " ans=" + sb.toString().take(90))+ hist.add(ChatMessage("assistant", sb.toString()))+ }+ rt.unloadActive()+ org.junit.Assert.assertTrue("way: identity lost in multi-turn",+ heads_all.contains("Edge0"))+ }++ // fork dissecting table: mode=ui replays the stored UI text as the assistant turn;+// mode=native replays lastAssistantNative ground truth+ @Test+ fun reuseForkBisect() = runBlocking {+ val mode = androidx.test.platform.app.InstrumentationRegistry.getArguments()+ .getString("mode") ?: "ui"+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ val want = androidx.test.platform.app.InstrumentationRegistry.getArguments().getString("model") ?: "edge0-35b.gguf"+ val model = sequenceOf(+ File(ctx.getDir("models", 0), want),+ File(ctx.filesDir, "models/$want"),+ ).firstOrNull { it.isFile } ?: return@runBlocking+ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ val hist = mutableListOf<ChatMessage>()+ val qs = listOf("Introduce three advantages of Mixture-of-Experts in detail.", "thanks")+ for ((i, q) in qs.withIndex()) {+ hist.add(ChatMessage("user", q))+ val sb = StringBuilder()+ rt.submit("bs$i", hist.toList(), true, GenParams(temperature = 0f, maxNewTokens = if (i == 0) 160 else 16))+ .toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> sb.append(ev.s)+ is GenEvent.ThinkPiece -> sb.append(ev.s)+ is GenEvent.Failed -> throw AssertionError(ev.diag)+ else -> Unit+ }+ }+ val content = if (mode == "native") (rt.lastAssistantNative() ?: sb.toString()) else sb.toString()+ hist.add(ChatMessage("assistant", content))+ android.util.Log.i("ReuseProbe", "mode=$mode round$i uiLen=${sb.length} sentLen=${content.length} m=${rt.lastMetrics.value?.let { "prompt=${it.promptTokens} reused=${it.prefix_reused_tokens} prefill_ms=${it.prefillMs}" }}")+ }+ rt.unloadActive()+ }++ // stack-smash regression: long ASCII pieces (>16 bytes) from byte-fallback must not crash+ @Test+ fun longAsciiPieceSurvival() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ val want = "edge0-8b.gguf"+ val model = sequenceOf(+ File(ctx.getDir("models", 0), want),+ File(ctx.filesDir, "models/$want"),+ ).firstOrNull { it.isFile } ?: return@runBlocking+ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ var count = 0+ rt.submit("t-ascii", listOf(+ ChatMessage("user", "Repeat exactly, no thinking: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 123456789012345678901234567890 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"),+ ), true, GenParams(temperature = 0f, maxNewTokens = 192)).toList()+ .forEach { ev -> when (ev) {+ is GenEvent.TextPiece -> count += ev.s.length+ is GenEvent.ThinkPiece -> count += ev.s.length+ is GenEvent.Failed -> throw AssertionError(ev.diag)+ else -> Unit+ } }+ android.util.Log.i("LlamaRT", "ascii survival chars=$count")+ assertTrue("no output", count > 20)+ rt.unloadActive()+ }++ // 35B off-mode leak measurement: the empty-pair path is live (parity with the+ // reference template); this case quantifies residual drift via thinkChars and+ // driftFirst. Assertions guard gross shape only; drift is read from LeakProbe logs.+ @Test+ fun thinkOffLeak35b() = runBlocking {+ val ctx = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext+ val want = "edge0-35b.gguf"+ val model = sequenceOf(File(ctx.getDir("models", 0), want), File(ctx.filesDir, "models/$want"))+ .firstOrNull { it.isFile } ?: return@runBlocking+ val rt = LlamaRuntime()+ rt.ensureLoaded(model.absolutePath)+ val qs = listOf("What is the capital of France? One word.",+ "If you pick 3, 3, 8, 8 once each with +,-,*,/ to reach 24, give the expression directly.",+ "Name one prime number larger than 90 and smaller than 100.")+ for ((i, q) in qs.withIndex()) {+ val sb = StringBuilder(); var thinkChars = 0; var textChars = 0; var firstKind = "?"+ rt.submit("leak$i", listOf(ChatMessage("user", q)), false,+ GenParams(temperature = 0f, maxNewTokens = 48)).toList().forEach { ev ->+ when (ev) {+ is GenEvent.TextPiece -> { if (firstKind == "?") firstKind = "T"; textChars += ev.s.length; sb.append(ev.s) }+ is GenEvent.ThinkPiece -> { if (firstKind == "?") firstKind = "K"; thinkChars += ev.s.length; sb.append("<T>").append(ev.s) }+ is GenEvent.Failed -> throw AssertionError(ev.diag)+ else -> Unit+ }+ }+ android.util.Log.i("LeakProbe", "q$i first=$firstKind think=$thinkChars text=$textChars out=" ++ sb.toString().take(70).replace("\n", " "))+ org.junit.Assert.assertTrue("leak probe empty q$i", textChars + thinkChars > 3)+ }+ rt.unloadActive()+ }+}diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..803a6c4--- /dev/null+++ b/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- Single APK delivery: no INTERNET permission - the app is fully on-device;+ models are staged into app-private dirs, no storage permission needed. -->+ <application+ android:name=".Edge0App"+ android:allowBackup="false"+ android:label="@string/app_name"+ android:supportsRtl="true"+ android:theme="@style/Theme.Edge0">+ <!-- Optional vendor GPU library: on Android 12+ undeclared vendor libs fail to+ dlopen even when publicly listed; required=false keeps devices without it+ installable and the runtime probe degrades silently. -->+ <uses-native-library android:name="libOpenCL.so" android:required="false" />+ <uses-native-library android:name="libOpenCL_adreno.so" android:required="false" />+ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|uiMode|density"+ android:windowSoftInputMode="adjustResize">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </application>+</manifest>diff --git a/android/app/src/main/cpp/CMakeLists.txt b/android/app/src/main/cpp/CMakeLists.txtnew file mode 100644index 0000000..9e66bb5--- /dev/null+++ b/android/app/src/main/cpp/CMakeLists.txt@@ -0,0 +1,21 @@+# app/src/main/cpp/CMakeLists.txt - native llama engine shell for the app.+# Links the five shared libs staged at build-dl/llama-libs/arm64-v8a (built by+# tools/llama/build_vendor_libs.sh from the pinned supply tree: vendor@7ab4ee7 with+# the common+android patch bands replayed; see patches/llama.cpp/README).+cmake_minimum_required(VERSION 3.22.1)+project(edge0llama C)++if(NOT DEFINED LLAMA_LIBS)+ set(LLAMA_LIBS "${CMAKE_CURRENT_SOURCE_DIR}/../../../../build-dl/llama-libs/arm64-v8a")+endif()++add_library(edge0llama SHARED llama_chat.c)+target_include_directories(edge0llama PRIVATE+ "${LLAMA_LIBS}/../include" # llama.h/ggml.h headers (synced at build time)+ "${LLAMA_LIBS}")+target_link_libraries(edge0llama+ "${LLAMA_LIBS}/libllama.so"+ "${LLAMA_LIBS}/libggml.so"+ "${LLAMA_LIBS}/libggml-base.so"+ "${LLAMA_LIBS}/libggml-cpu.so"+ android log)diff --git a/android/app/src/main/cpp/llama_chat.c b/android/app/src/main/cpp/llama_chat.cnew file mode 100644index 0000000..a3ee9c1--- /dev/null+++ b/android/app/src/main/cpp/llama_chat.c@@ -0,0 +1,650 @@+// llama_chat.c - native llama engine shell for the Edge0 chat app.+// Session model: static history of turns; every request renders the chat template+// over the append-only transcript, tokenizes it, and lets KV prefix reuse turn the+// full render into an incremental prefill. Sampling = classic token_data_array+// chain (greedy when temperature <= 0). nativeInit carries expert-pool tier config+// (the 35B tier requires E0_MMAP_NOPREFETCH + E0_NO_REPACK), nativeReset drops KV,+// and each generate returns a structured metrics line for the Kotlin layer.+#include <jni.h>+#include <stdbool.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>+#include <android/log.h>+#include "llama.h"++#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "E0LLAMA", __VA_ARGS__)++static struct llama_model *g_model = NULL;+static struct llama_context *g_ctx = NULL;+static struct llama_adapter_lora *g_lora = NULL;++#define MAX_MSG 128+static llama_chat_message g_hist[MAX_MSG];+static char *g_strs[MAX_MSG * 2];+static int g_nmsg = 0;++#define MAX_TOKS 8192+static llama_token g_toks[MAX_TOKS];+static llama_token *g_msg_ids[MAX_MSG]; // assistant turns: stepped token ids (sidecar)+static int g_msg_nids[MAX_MSG];+static llama_token g_msg_eog[MAX_MSG]; // end-of-turn token for each history turn+static llama_token g_out_ids[MAX_TOKS]; // ids stepped this turn (EOS excluded)+static int g_out_n = 0;+static llama_token g_out_eog = -1;+static int g_nprocessed = 0;++static volatile int g_cancel = 0;+// pool counters forward decl (defined at the file tail; the metrics window inside nativeGenerate needs them)+extern void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,+ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes);+extern void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * slots_total,+ long long * pf_used, long long * pf_mispredict);++// Thinking control: the built-in BAILING2 renderer emits no think tags and ignores+// jinja variables - thinking is model-native. The real switch is the template's+// "detailed thinking on/off" instruction line in the system turn (training contract).+static int g_thinking = 0;+// The on direction rewrites in place with equal or shorter length, byte-matching the+// reference jinja render; returns the corrected render length.+// Both template families align with the reference (real-template) render:+// 8B Bailing V3: off = instruction line at the end of the system turn (the built-in+// renderer self-injects it when no system turn exists); assistant heads get the open+// tag for on, an open+close empty pair for off.+// 35B Qwen2/CHATML: off = empty pair after the generation head only - the instruction+// line is a foreign signal for this family (verified against the embedded template).++static int32_t bailing_flip_on(char * r, int32_t len) { // V3: off -> on, shrink 1 byte left+ const char * needle = "detailed thinking off";+ for (int32_t i = 0; i + 21 <= len; i++) {+ if (memcmp(r + i, needle, 21) == 0) {+ r[i + 19] = 'n';+ memmove(r + i + 20, r + i + 21, (size_t) (len - i - 20));+ return len - 1;+ }+ }+ return len;+}++// Reference-template evidence: with enable_thinking=false the jinja template emits NO+// instruction line - just the empty pair after the generation head. Carrying the+// "detailed thinking off" text into a fabricated system turn is a foreign signal for+// the qwen family (it invites the model to mimic reasoning prose in the body), so+// off-mode here is a pure erase (also catches residue from user-provided system text).+static int32_t qwen_pure_erase_directive(char * r, int32_t len) {+ char needle[24];+ memcpy(needle, "detailed thin", 13);+ memcpy(needle + 13, "king off", 9);+ needle[22] = 0;+ for (;;) {+ char * f = strstr(r, needle);+ if (!f) return (int32_t) strlen(r);+ int32_t st = (int32_t) (f - r), en = st + 22;+ if (st > 0 && r[st - 1] == '\n') st--;+ else if (r[en] == '\n') en++;+ memmove(r + st, r + en, (size_t) (len - en + 1));+ len -= (en - st);+ }+}++static int g_tpl_imstart = -1;++// Bailing fallback: when a custom system turn exists the built-in renderer skips the+// instruction line entirely and the off signal is lost. The V3 contract inlines the+// line at the end of the SYSTEM turn content, before its role_end. Insert there;+// direction from g_thinking; only acts when no "detailed thinking" text exists.+static void bail_ensure_directive(char * r, int32_t * plen, int32_t cap) {+ if (g_tpl_imstart == 1) return;+ if (strstr(r, "detailed thinking")) return; // built-in already injected it, or the user wrote their own+ char * sy = strstr(r, "<role>SYSTEM</role>");+ if (!sy) return;+ char * re = strstr(sy + 19, "<|" "role_end" "|>");+ if (!re) return;+ char frag[32];+ int fl = snprintf(frag, sizeof(frag), "\ndetailed thinking %s", g_thinking ? "on" : "off");+ if (fl <= 0 || *plen + fl + 1 > cap) return;+ memmove(re + fl, re, (size_t) (*plen - (re - r) + 1));+ memcpy(re, frag, (size_t) fl);+ *plen += fl;+}++// Product decision for the 35B family: keep the template-conformant empty-pair form+// and do not seed the continuation; sampling-side forcing measured unreliable.++/* Literal of the built-in BAILING2 default head for history without a system turn:+ segment-wise rendering would inject it between segments - strip it to keep one SYSTEM. */+static const char FAKE_SYS_HEAD[] =+ "<" "role" ">" "SYSTEM" "<" "/" "role" ">" "detailed thinking off" "<|" "role_end" "|>";+static int32_t bail_strip_fake_head(char * r, int32_t len) {+ const int fl = (int) sizeof(FAKE_SYS_HEAD) - 1;+ if (len >= fl && memcmp(r, FAKE_SYS_HEAD, (size_t) fl) == 0) {+ memmove(r, r + fl, (size_t) (len - fl + 1));+ return len - fl;+ }+ return len;+}++// Golden-path head form (instruction line alone is a half-fix against the reference+// render): after every bare assistant head emit newline + (on ? open : open+close pair).+static void bailing_think_heads(char * r, int32_t * plen, int32_t cap) {+ const char * head = "<role>ASSISTANT</role>";+ const int hl = 22;+ static const char tso[] = "\n" "<" "th" "ink" ">";+ static const char tsof[] = "\n" "<" "th" "ink" ">" "</" "th" "ink" ">";+ const char * inj = g_thinking ? tso : tsof;+ const int il = (int) strlen(inj); /* tso 8B / tsof 16B, self-adaptive */+ int32_t pos = 0;+ for (;;) {+ char * h = strstr(r + pos, head);+ if (!h) break;+ int32_t at = (int32_t) (h - r) + hl;+ // already annotated (tag follows the newline) - skip to prevent double injection+ if (memcmp(r + at, inj, (size_t) il) == 0) { pos = at + il; continue; }+ if (*plen + il + 1 > cap) return;+ memmove(r + at + il, r + at, (size_t) (*plen - at + 1));+ memcpy(r + at, inj, (size_t) il);+ *plen += il;+ pos = at + il;+ }+}++static void qwen_inject_empty_pair(char * r, char const * head, int32_t cap) {+ size_t l = strlen(r), hl = strlen(head);+ if (l == 0 || hl == 0 || l + 32 > (size_t) cap) return;+ static const char pair[] = "<th" "ink>\n\n</th" "ink>\n\n";+ /* Training form = reference template: exactly one newline after the assistant+ head, then the empty pair. The old append style added an extra newline (a+ blank-paragraph continuation cue) and the model answered with mimic'd+ "thinking process" prose - this overlay keeps it token-identical. */+ if (l >= hl && memcmp(r + l - hl, head, hl) == 0 && !strstr(r + l - hl, "<th" "ink>")) {+ memcpy(r + (l - 1 - hl), pair, sizeof(pair) - 1); /* keep head+newline; overlay empty pair right after it */+ r[(l - 1 - hl) + sizeof(pair) - 1] = 0; /* the overlay straddles the old terminator: rewrite it */+ }+}+++static char g_reply_tail[8192]; // tail 8KB of the last reply (cross-check for history sync; longer = TOOLONG)+static size_t g_rlen = 0;+static llama_token_data *g_td = NULL;+static int g_reset_next = 0;++// With byte-fallback vocabularies one token may be half a UTF-8 codepoint; feeding an+// illegal continuation byte to NewStringUTF aborts under CheckJNI. Emit only complete+// codepoints; carry the partial tail into the next piece.+static char g_pend[8];+static int g_pend_len = 0;++static void emit_valid_utf8(JNIEnv *env, jobject sink, jmethodID invoke,+ const char *buf, int32_t len) {+ char comb[16];+ int n = g_pend_len + len;+ if (n > (int)sizeof(comb)) n = (int)sizeof(comb);+ memcpy(comb, g_pend, g_pend_len);+ memcpy(comb + g_pend_len, buf, n - g_pend_len); // clamp every memory op to the truncated n, never the raw len+ int cut = n;+ for (int k = 1; k <= 3 && k <= n; k++) {+ unsigned char b = (unsigned char)comb[n - k];+ if ((b & 0xC0) != 0x80) {+ int expect = (b < 0x80) ? 1 : (b < 0xE0) ? 2 : (b < 0xF0) ? 3 : 4;+ if (k < expect) cut = n - k;+ break;+ }+ }+ g_pend_len = n - cut;+ if (g_pend_len) memcpy(g_pend, comb + cut, g_pend_len);+ if (cut > 0) {+ char safe[16]; memcpy(safe, comb, cut); safe[cut] = 0;+ jstring js = (*env)->NewStringUTF(env, safe);+ (*env)->CallObjectMethod(env, sink, invoke, js);+ (*env)->DeleteLocalRef(env, js);+ }+}++static void flush_pend(void) { g_pend_len = 0; }++static long long now_ms(void) {+ struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);+ return (long long) ts.tv_sec * 1000 + ts.tv_nsec / 1000000;+}++JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeInit(+ JNIEnv *env, jclass cls, jstring jmodel, jstring jlora, jstring jheads,+ jint n_ctx, jint pool_mb, jint blob_mb, jint pred, jint io_threads) {+ (void) cls;+ // idempotent self-clear: model/LoRA/pool registry/history from a previous session+ // must never bleed into a new load (an 8B adapter on a 35B graph aborts on shape asserts)+ extern void moe_pool_reset_all(void);+ if (g_model || g_ctx || g_lora) {+ if (g_ctx) { llama_free(g_ctx); g_ctx = NULL; }+ if (g_lora) { llama_adapter_lora_free(g_lora); g_lora = NULL; }+ if (g_model) { llama_model_free(g_model); g_model = NULL; }+ for (int i = 0; i < g_nmsg * 2; i++) { free(g_strs[i]); g_strs[i] = NULL; }+ for (int i = 0; i < g_nmsg; i++) { free(g_msg_ids[i]); g_msg_ids[i] = NULL; g_msg_nids[i] = 0; }+ g_nmsg = 0; g_nprocessed = 0;+ }+ moe_pool_reset_all();+ const char *model = (*env)->GetStringUTFChars(env, jmodel, NULL);+ const char *lora = (*env)->GetStringUTFChars(env, jlora, NULL);+ const char *heads = (*env)->GetStringUTFChars(env, jheads, NULL);+ char err[512];+ // pool env must be set before model load (moe_pool_init reads env at register time);+ // 8B passes 0/0 = zero perturbation.+ setenv("E0_MMAP_NOPREFETCH", "1", 1); // verified freeze-avoidance on 35B; harmless for 8B+ setenv("E0_NO_REPACK", "1", 1);+ { char b[32];+ snprintf(b, sizeof(b), "%d", pool_mb); setenv("E0_POOL_MB", b, 1);+ snprintf(b, sizeof(b), "%d", blob_mb); setenv("E0_BLOB_MB", b, 1);+ snprintf(b, sizeof(b), "%d", io_threads); setenv("E0_IO_THREADS", b, 1);+ setenv("E0_MEM_FLOOR_MB", "2000", 1); }+ if (heads && heads[0]) setenv("E0_HEADS", heads, 1);+ if (blob_mb > 0) setenv("E0_KEEPWARM_MB", "512", 1); // 35B tier: turn-end keepwarm refill (moot without a pool)+ if (pred) setenv("E0_PREROUTER", "1", 1); else unsetenv("E0_PREROUTER");+ llama_backend_init();+ struct llama_model_params mp = llama_model_default_params();+ mp.n_gpu_layers = 0;+ g_model = llama_model_load_from_file(model, mp);+ if (!g_model) {+ snprintf(err, sizeof(err), "ERR load: %s", model);+ goto ret;+ }+ if (lora && lora[0]) {+ g_lora = llama_adapter_lora_init(g_model, lora);+ if (!g_lora) { snprintf(err, sizeof(err), "ERR lora init: %s", lora); goto ret; }+ }+ {+ struct llama_context_params cp = llama_context_default_params();+ cp.n_ctx = (uint32_t) n_ctx;+ cp.n_batch = 512;+ g_ctx = llama_init_from_model(g_model, cp);+ if (!g_ctx) { snprintf(err, sizeof(err), "ERR ctx init"); goto ret; }+ if (g_lora) {+ float scale = 1.0f; // canonical form: file alpha 32 + explicit scale 1.0+ if (llama_set_adapters_lora(g_ctx, &g_lora, 1, &scale) != 0) {+ snprintf(err, sizeof(err), "ERR lora set"); goto ret;+ }+ }+ }+ g_reset_next = 1;+ snprintf(err, sizeof(err), "OK %s pool=%d blob=%d pred=%d", llama_version(), pool_mb, blob_mb, pred);+ret:+ (*env)->ReleaseStringUTFChars(env, jmodel, model);+ (*env)->ReleaseStringUTFChars(env, jlora, lora);+ (*env)->ReleaseStringUTFChars(env, jheads, heads);+ return (*env)->NewStringUTF(env, err);+}++JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeReset(+ JNIEnv *env, jclass cls) {+ (void) cls;+ // session reset: clear history and force full KV replay (thread switch / history fork)+ for (int i = 0; i < g_nmsg * 2; i++) { free(g_strs[i]); g_strs[i] = NULL; }+ for (int i = 0; i < g_nmsg; i++) { free(g_msg_ids[i]); g_msg_ids[i] = NULL; g_msg_nids[i] = 0; }+ g_nmsg = 0;+ g_reset_next = 1;+ return (*env)->NewStringUTF(env, "OK");+}++JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeAddRole(+ JNIEnv *env, jclass cls, jstring jrole, jstring jtext) {+ (void) cls;+ const char *role = (*env)->GetStringUTFChars(env, jrole, NULL);+ const char *text = (*env)->GetStringUTFChars(env, jtext, NULL);+ int full = g_nmsg >= MAX_MSG;+ if (!full) {+ char *r = strdup(role); char *t = strdup(text);+ g_strs[g_nmsg * 2] = r; g_strs[g_nmsg * 2 + 1] = t;+ g_hist[g_nmsg].role = r; g_hist[g_nmsg].content = t;+ g_nmsg++;+ }+ (*env)->ReleaseStringUTFChars(env, jrole, role);+ (*env)->ReleaseStringUTFChars(env, jtext, text);+ return (*env)->NewStringUTF(env, full ? "FULL" : "OK");+}++// assistant turn enters history via sidecar: ids big-endian 4B per element; text render is skipped (stitched in nativeGenerate)+JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeAddRoleIds(+ JNIEnv *env, jclass cls, jstring jrole, jbyteArray jids, jint eog) {+ (void) cls;+ const char *role = (*env)->GetStringUTFChars(env, jrole, NULL);+ const int nb = jids ? (*env)->GetArrayLength(env, jids) : 0;+ int full = (g_nmsg >= MAX_MSG) || (nb % 4) != 0;+ if (!full) {+ llama_token *ids = NULL;+ if (nb > 0) {+ jbyte *bd = (*env)->GetByteArrayElements(env, jids, NULL);+ ids = (llama_token *) malloc(sizeof(llama_token) * (nb / 4));+ for (int i = 0; i < nb / 4; i++) {+ unsigned char *q = (unsigned char *) (bd + i * 4);+ ids[i] = (llama_token) ((q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3]);+ }+ (*env)->ReleaseByteArrayElements(env, jids, bd, JNI_ABORT);+ }+ char *r = strdup(role);+ g_strs[g_nmsg * 2] = r; g_strs[g_nmsg * 2 + 1] = NULL;+ g_hist[g_nmsg].role = r; g_hist[g_nmsg].content = "";+ g_msg_ids[g_nmsg] = ids; g_msg_nids[g_nmsg] = nb / 4; g_msg_eog[g_nmsg] = (llama_token) eog;+ g_nmsg++;+ }+ (*env)->ReleaseStringUTFChars(env, jrole, role);+ return (*env)->NewStringUTF(env, full ? "FULL" : "OK");+}++// ids stepped this turn (big-endian 4B) plus the end-of-turn token+JNIEXPORT jbyteArray JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeLastAssistantIds(JNIEnv *env, jclass cls) {+ (void) cls;+ jbyteArray out = (*env)->NewByteArray(env, g_out_n * 4);+ if (out && g_out_n > 0) {+ jbyte *bd = (*env)->GetByteArrayElements(env, out, NULL);+ for (int i = 0; i < g_out_n; i++) {+ unsigned char *q = (unsigned char *) (bd + i * 4);+ q[0] = (unsigned char) (g_out_ids[i] >> 24); q[1] = (unsigned char) (g_out_ids[i] >> 16);+ q[2] = (unsigned char) (g_out_ids[i] >> 8); q[3] = (unsigned char) g_out_ids[i];+ }+ (*env)->ReleaseByteArrayElements(env, out, bd, 0);+ }+ return out;+}+JNIEXPORT jint JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeLastEog(JNIEnv *env, jclass cls) {+ (void) env; (void) cls; return (jint) g_out_eog;+}++#include <pthread.h>+static void * kw_thread(void * arg) { (void) arg; extern void moe_pool_keepwarm(int); moe_pool_keepwarm(0); return NULL; }++JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeGenerate(+ JNIEnv *env, jclass cls, jobject sink, jint max_tokens, jfloat temp, jboolean thinking_on) {+ // Toggling thinking changes the rendered instruction line, which the UI-text+ // history comparison cannot see - trusting positions would keep dirty KV context.+ // Authoritative checkpoint: on a thinking change with live context, force a full rebuild.+ if (g_ctx && g_thinking != (thinking_on ? 1 : 0) && g_nprocessed > 0) g_reset_next = 1;+ g_thinking = thinking_on ? 1 : 0;+ char out[512];+ out[0] = 0;+ if (!g_ctx) { snprintf(out, sizeof(out), "ERR not init"); return (*env)->NewStringUTF(env, out); }+ {+ const char *t0 = llama_model_chat_template(g_model, NULL);+ g_tpl_imstart = (t0 && strstr(t0, "<|im_start|>assistant")) ? 1 : 0;+ }+ const struct llama_vocab *vocab = llama_model_get_vocab(g_model);+ const int32_t n_vocab = llama_vocab_n_tokens(vocab);++ static char render[65536];+ const char *tmpl = llama_model_chat_template(g_model, NULL); // BAILING2 -> built-in renderer+ int has_ids = 0;+ for (int i = 0; i < g_nmsg; i++) if (g_msg_nids[i] > 0) { has_ids = 1; break; }+ int32_t n_tok = 0;+ if (!has_ids) {+ int32_t need = llama_chat_apply_template(tmpl, g_hist, (size_t) g_nmsg, true, render, sizeof(render));+ if (need <= 0 || (size_t) need >= sizeof(render)) {+ snprintf(out, sizeof(out), "ERR template need=%d", need);+ return (*env)->NewStringUTF(env, out);+ }+ if (!g_thinking) {+ if (g_tpl_imstart == 1) {+ // qwen off = pure empty pair (reference-template verified): no instruction line, no fabricated system turn+ need = qwen_pure_erase_directive(render, need);+ }+ } else {+ if (g_tpl_imstart != 1) need = bailing_flip_on(render, need);+ }+ bail_ensure_directive(render, &need, (int32_t) sizeof(render));+ if (g_tpl_imstart != 1) bailing_think_heads(render, &need, (int32_t) sizeof(render));+ qwen_inject_empty_pair(render, "<|im_start|>assistant\n", (int32_t) sizeof(render));+ n_tok = llama_tokenize(vocab, render, need, g_toks, MAX_TOKS, false, true);+ if (n_tok <= 0) { snprintf(out, sizeof(out), "ERR tokenize %d", n_tok); return (*env)->NewStringUTF(env, out); }+ } else {+ // sidecar stitching: text segments render+tokenize, id segments paste verbatim+ // (kills BPE re-encode boundary drift). Every text segment carries the generation+ // prompt; id turns = stepped body + that turn's end-of-generation token.+ int32_t w = 0; int ii = 0; int err = 0;+ while (ii < g_nmsg) {+ if (g_msg_nids[ii] > 0) {+ if (w + g_msg_nids[ii] + 1 >= MAX_TOKS - 8) { err = 2; break; }+ memcpy(&g_toks[w], g_msg_ids[ii], sizeof(llama_token) * (size_t) g_msg_nids[ii]);+ w += g_msg_nids[ii];+ if (g_msg_eog[ii] >= 0) g_toks[w++] = g_msg_eog[ii];+ ii++;+ continue;+ }+ int j = ii; while (j < g_nmsg && g_msg_nids[j] == 0) j++;+ int32_t need = llama_chat_apply_template(tmpl, &g_hist[ii], (size_t) (j - ii), true, render, sizeof(render));+ if (need <= 0 || (size_t) need >= sizeof(render)) { err = 1; break; }+ /* fake SYSTEM head stripping: the built-in renderer injects its default+ system block into every non-first segment start; strip or the prompt+ grows a second SYSTEM block and the model loses its identity */+ if (g_tpl_imstart != 1 && ii > 0) need = bail_strip_fake_head(render, need);+ if (!g_thinking) {+ if (g_tpl_imstart == 1) {+ // qwen off = pure empty pair (reference-template verified): no instruction line, no fabricated system turn+ need = qwen_pure_erase_directive(render, need);+ }+ } else {+ if (g_tpl_imstart != 1) need = bailing_flip_on(render, need);+ }+ // run every segment unconditionally: gating this on the thinking branch or+ // the last segment lost the instruction line from turn two onward (the+ // empty-answer bug). Families without a SYSTEM in the segment self-check to a no-op.+ if (g_tpl_imstart != 1) bail_ensure_directive(render, &need, (int32_t) sizeof(render));+ if (g_tpl_imstart != 1) bailing_think_heads(render, &need, (int32_t) sizeof(render));+ if (g_tpl_imstart == 1 && j >= g_nmsg) qwen_inject_empty_pair(render, "<|im_start>|assistant\n", (int32_t) sizeof(render));+ int32_t room = MAX_TOKS - 8 - w;+ int32_t tn = llama_tokenize(vocab, render, need, g_toks + w, room, false, true);+ if (tn <= 0) { err = 1; break; }+ w += tn; ii = j;+ }+ if (err) { snprintf(out, sizeof(out), "ERR sidecar concat %d", err); return (*env)->NewStringUTF(env, out); }+ n_tok = w;+ }+ if (n_tok >= MAX_TOKS - 8) { snprintf(out, sizeof(out), "ERR ctx too long"); return (*env)->NewStringUTF(env, out); }++ { // render forensics: single-line dump of the tail (newlines escaped) for empty-pair / migration checks+ char dbg[512]; int di = 0;+ int rl = (int) strlen(render);+ int tl = rl > 110 ? 110 : rl;+ const char * t = render + rl - tl;+ for (int z = 0; z < tl && di < 380; z++) {+ if (t[z] == '\n') { dbg[di++] = '\\'; dbg[di++] = 'n'; }+ else dbg[di++] = t[z];+ }+ dbg[di] = 0;+ LOGI("REND tail=[%s]", dbg);+ { /* head forensics: SYSTEM segment identity + instruction-line shape */+ char dh[260]; int dj = 0;+ for (int z = 0; z < (int) strlen(render) && z < 130 && dj < 250; z++) {+ char ch = render[z];+ if (ch == '\n') { dh[dj++] = '\\'; dh[dj++] = 'n'; }+ else dh[dj++] = ch;+ }+ dh[dj] = 0;+ LOGI("REND head=[%s]", dh);+ }+ }+ int start = g_reset_next ? 0 : g_nprocessed;+ if (start > n_tok) start = 0;+ if (g_reset_next) {+ llama_memory_seq_rm(llama_get_memory(g_ctx), 0, -1, -1);+ g_reset_next = 0;+ }++ long long ph0=0, pm0=0, pl0=0, pe0=0, pb0=0, pst0=0;+ size_t pcap0=0, pused0=0;+ moe_pool_stats(&ph0, &pm0, &pl0, &pe0, (long long*)&pb0, &pcap0, &pused0);+ { long long su,st,pu,pm; moe_pool_extra(&pst0,&su,&st,&pu,&pm); }+ jmethodID invoke = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, sink),+ "invoke", "(Ljava/lang/Object;)Ljava/lang/Object;");+ long long prefill_ms;+ {+ long long t0 = now_ms();+ // small incremental batches decode token-by-token: MoE gather cost does not+ // amortize on tiny batches (measured 7x slower than decode); <=32 new tokens+ // take the decode-like path, long batches keep the 512 window.+ const int32_t inc = n_tok - start;+ const int32_t chunk_max = (inc > 0 && inc <= 32) ? 1 : 512;+ for (int i = start; i < n_tok; i += chunk_max) {+ int chunk = (n_tok - i < chunk_max) ? n_tok - i : chunk_max;+ struct llama_batch b = llama_batch_get_one(g_toks + i, chunk);+ if (llama_decode(g_ctx, b) != 0) { snprintf(out, sizeof(out), "ERR prefill@%d", i); return (*env)->NewStringUTF(env, out); }+ if (g_cancel) { g_cancel = 0; snprintf(out, sizeof(out), "CANCELLED"); return (*env)->NewStringUTF(env, out); }+ }+ prefill_ms = now_ms() - t0;+ { long long h, m, l, e, b; long long su, stq, pu, pm; size_t cap, used; long long st1;+ moe_pool_stats(&h, &m, &l, &e, &b, &cap, &used);+ moe_pool_extra(&st1, &su, &stq, &pu, &pm);+ char dbg[256];+ snprintf(dbg, sizeof(dbg),+ "PRE fill hit=%lld miss=%lld evict=%lld stall_ms=%lld loads=%lld",+ h - ph0, m - pm0, e - pe0, (st1 - pst0) / 1000000, l - pl0);+ LOGI("%s", dbg); }+ }+ int reused = start;+ g_nprocessed = n_tok;++ { // vocab width changes across models: the token buffer must realloc (8B-sized buffer fed a 35B vocab = OOB write)+ static size_t g_td_cap = 0;+ if (g_td_cap < (size_t) n_vocab) {+ free(g_td);+ g_td = (llama_token_data *) malloc(sizeof(llama_token_data) * (size_t) n_vocab);+ g_td_cap = g_td ? (size_t) n_vocab : 0;+ }+ }+ struct llama_sampler *smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());+ if (temp <= 0.0f) llama_sampler_chain_add(smpl, llama_sampler_init_greedy());+ else {+ llama_sampler_chain_add(smpl, llama_sampler_init_temp(temp));+ llama_sampler_chain_add(smpl, llama_sampler_init_top_k(40));+ llama_sampler_chain_add(smpl, llama_sampler_init_dist(0xC0FFEEu));+ }+ char reply[32768]; size_t rlen = 0; reply[0] = 0;+ g_rlen = 0;+ flush_pend();+ char piece[256];+ long long t0 = now_ms();+ int gen = 0;+ long long first_ms = 0;+ g_out_n = 0; g_out_eog = -1;+ double tps = 0.0;+ llama_token next = -1;+ while (gen < max_tokens && !g_cancel) {+ const float *lg = llama_get_logits_ith(g_ctx, -1);+ if (!lg) { snprintf(out, sizeof(out), "ERR logits@%d", gen); break; }+ for (int32_t j = 0; j < n_vocab; j++) { g_td[j].id = j; g_td[j].logit = lg[j]; g_td[j].p = 1.0f; }+ llama_token_data_array cur = { .data = g_td, .size = (size_t) n_vocab, .selected = -1, .sorted = false };+ llama_sampler_apply(smpl, &cur);+ next = cur.data[cur.selected].id;+ if (llama_vocab_is_eog(vocab, next)) { g_out_eog = next; break; }+ int32_t plen = llama_token_to_piece(vocab, next, piece, sizeof(piece) - 1, 0, false);+ if (plen > 0) {+ piece[plen] = 0;+ if (rlen + plen < sizeof(reply)) { memcpy(reply + rlen, piece, plen); rlen += plen; }+ if (g_rlen + plen < sizeof(g_reply_tail)) { memcpy(g_reply_tail + g_rlen, piece, plen); g_rlen += plen; }+ else g_rlen = sizeof(g_reply_tail) + 1;+ emit_valid_utf8(env, sink, invoke, piece, plen);+ }+ if (g_out_n < MAX_TOKS) g_out_ids[g_out_n++] = next;+ gen++;+ if (gen == 1) first_ms = now_ms() - t0;+ struct llama_batch b = llama_batch_get_one(&next, 1);+ if (llama_decode(g_ctx, b) != 0) { snprintf(out, sizeof(out), "ERR decode@%d", gen); break; }+ g_nprocessed++;+ tps = gen * 1000.0 / (double) (now_ms() - t0 + 1);+ }+ flush_pend();+ while (rlen > 0 && (((unsigned char)reply[rlen - 1] & 0xC0) == 0x80)) rlen--;+ if (rlen > 0) { unsigned char b = (unsigned char)reply[rlen - 1];+ int expect = (b < 0x80) ? 1 : (b < 0xE0) ? 2 : (b < 0xF0) ? 3 : 4;+ if (expect > 1) rlen--; }+ reply[rlen] = 0;+ if (g_cancel) { g_cancel = 0;+ snprintf(out, sizeof(out), "CANCELLED gen=%d tps=%.2f prefill_ms=%lld first_ms=%lld prompt=%d reused=%d",+ gen, tps, prefill_ms, first_ms, n_tok, reused); }+ else snprintf(out, sizeof(out), "OK gen=%d tps=%.2f prefill_ms=%lld first_ms=%lld prompt=%d reused=%d",+ gen, tps, prefill_ms, first_ms, n_tok, reused);+ LOGI("%s", out);++ if (gen > 0 && getenv("E0_KEEPWARM_MB")) { pthread_t kt; if (pthread_create(&kt, NULL, kw_thread, NULL) == 0) pthread_detach(kt); }+ { // assistant turn recorded with stepped ids (sidecar); the text reply stays in logs only+ char *ar = strdup("assistant");+ g_strs[g_nmsg * 2] = ar; g_strs[g_nmsg * 2 + 1] = NULL;+ if (g_nmsg < MAX_MSG) {+ llama_token *ids = NULL;+ if (g_out_n > 0) { ids = (llama_token *) malloc(sizeof(llama_token) * (size_t) g_out_n); memcpy(ids, g_out_ids, sizeof(llama_token) * (size_t) g_out_n); }+ g_hist[g_nmsg].role = ar; g_hist[g_nmsg].content = "";+ g_msg_ids[g_nmsg] = ids; g_msg_nids[g_nmsg] = ids ? g_out_n : 0; g_msg_eog[g_nmsg] = g_out_eog;+ g_nmsg++;+ }+ }+ (void) reply;+ llama_sampler_free(smpl);+ return (*env)->NewStringUTF(env, out);+}++// pool counters + process RSS export (the metrics line under each reply: hit/stall/peak-rss).+// moe_pool_* symbols live in libggml-cpu.so (linked explicitly at build time).+extern void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,+ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes);+extern void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * slots_total,+ long long * pf_used, long long * pf_mispredict);++JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeStats(JNIEnv *env, jclass cls) {+ (void) cls;+ long long h=0, m=0, l=0, e=0, bl=0, st=0, su=0, stot=0, pu=0, pm=0;+ size_t cap=0, used=0;+ moe_pool_stats(&h, &m, &l, &e, &bl, &cap, &used);+ moe_pool_extra(&st, &su, &stot, &pu, &pm);+ long vmhwm = 0, vmrss = 0;+ FILE * f = fopen("/proc/self/status", "r");+ if (f) {+ char ln[256];+ while (fgets(ln, sizeof(ln), f)) {+ if (!strncmp(ln, "VmHWM:", 6)) vmhwm = strtol(ln + 6, NULL, 10);+ else if (!strncmp(ln, "VmRSS:", 6)) vmrss = strtol(ln + 6, NULL, 10);+ }+ fclose(f);+ }+ char buf[512];+ snprintf(buf, sizeof(buf),+ "hits=%lld misses=%lld loads=%lld evicts=%lld flash=%lld resident=%lld cap=%lld\n"+ "stall_ns=%lld slots=%lld/%lld pf_used=%lld pf_miss=%lld vmhwm_kb=%ld vmrss_kb=%ld",+ h, m, l, e, bl, (long long)used, (long long)cap, st, su, stot, pu, pm, vmhwm, vmrss);+ return (*env)->NewStringUTF(env, buf);+}++// tail 8KB of the last assistant reply in native form (when the UI shows equivalent text, replaying it keeps full prefix reuse; longer = TOOLONG)+JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeLastAssistant(JNIEnv *env, jclass cls) {+ (void) cls;+ if (g_rlen > sizeof(g_reply_tail)) return (*env)->NewStringUTF(env, "TOOLONG");+ char tmp[8200];+ size_t n = g_rlen; if (n > sizeof(g_reply_tail) - 1) n = sizeof(g_reply_tail) - 1;+ memcpy(tmp, g_reply_tail, n); tmp[n] = 0;+ return (*env)->NewStringUTF(env, tmp);+}++JNIEXPORT void JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeCancel(JNIEnv *env, jclass cls) {+ (void) env; (void) cls; g_cancel = 1;+}++// unload/free: real teardown. Order is law: sampler first, then adapter before model+// (freeing the model under an attached adapter crashed at 452s once) - plus all-static reset.+JNIEXPORT jstring JNICALL+Java_dev_edge0_runtime_app_runtime_LlamaNative_nativeFree(JNIEnv *env, jclass cls) {+ (void) cls;+ if (g_ctx) { llama_free(g_ctx); g_ctx = NULL; }+ if (g_lora) { llama_adapter_lora_free(g_lora); g_lora = NULL; }+ if (g_model) { llama_model_free(g_model); g_model = NULL; }+ for (int i = 0; i < g_nmsg * 2; i++) { free(g_strs[i]); g_strs[i] = NULL; }+ for (int i = 0; i < g_nmsg; i++) { free(g_msg_ids[i]); g_msg_ids[i] = NULL; g_msg_nids[i] = 0; }+ g_nmsg = 0; g_nprocessed = 0; g_reset_next = 0;+ { extern void moe_pool_reset_all(void); moe_pool_reset_all(); }+ return (*env)->NewStringUTF(env, "OK");+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/Edge0App.kt b/android/app/src/main/java/dev/edge0/runtime/app/Edge0App.ktnew file mode 100644index 0000000..7e57d95--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/Edge0App.kt@@ -0,0 +1,79 @@+// Edge0App.kt - process-level container (manual DI, no framework) plus:+// cold-start cleanup of orphaned streaming rows, and onTrimMemory -> engine pressure relief+// (logcat probe tag=Edge0Trim).+package dev.edge0.runtime.app++import android.app.Application+import android.content.ComponentCallbacks2+import android.content.res.Configuration+import android.util.Log+import dev.edge0.runtime.app.data.AppDatabase+import dev.edge0.runtime.app.data.ChatRepository+import dev.edge0.runtime.app.data.RoomChatRepository+import dev.edge0.runtime.app.data.SettingsStore+import dev.edge0.runtime.app.runtime.LlamaRuntime+import dev.edge0.runtime.app.runtime.Runtime+import dev.edge0.runtime.app.runtime.ThermalSource+import java.io.File+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++class AppContainer(private val app: Application) {+ private val llamaRuntime by lazy { LlamaRuntime() }+ val runtime: Runtime by lazy { llamaRuntime }+ val settings = SettingsStore(app)+ val db by lazy { AppDatabase.create(app) }+ val repository: ChatRepository by lazy { RoomChatRepository(db) }+ val thermal by lazy { ThermalSource(app) }+ /** Model import roots: internal files/models (primary - on some OEM builds+ * shell-pushed files are invisible to the app uid, so device-internal copy is the+ * reliable channel) plus external files/models; both roots are scanned. */+ val modelRoots: List<File?>+ get() = listOf(File(app.filesDir, "models"), app.getExternalFilesDir("models"))+}++class Edge0App : Application() {+ lateinit var container: AppContainer+ private set++ override fun onCreate() {+ super.onCreate()+ container = AppContainer(this)+ // cold start: mark rows left in streaming by a killed process as interrupted (visible, not lost)+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+ runCatching { container.repository.markStreamingInterrupted() }+ }+ // ComponentCallbacks2 registered directly on the Application - lifecycle observers+ // (2.8) do not carry onTrimMemory; this is the official hook+ registerComponentCallbacks(TrimBridge(container))+ }+}++/** Pressure mapping: RUNNING_LOW/BACKGROUND levels -> trim(0.5); COMPLETE -> cancel then unload. */+class TrimBridge(private val container: AppContainer) : ComponentCallbacks2 {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ override fun onConfigurationChanged(newConfig: Configuration) {}+ @Deprecated("compat") override fun onLowMemory() {}++ override fun onTrimMemory(level: Int) {+ // level bands: RUNNING_MODERATE=5/LOW=10/CRITICAL=15; UI_HIDDEN=16;+ // BACKGROUND=20, MODERATE=40, COMPLETE=80+ when {+ level == android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> {+ Log.i(TAG, "onTrimMemory level=$level action=cancel+unload")+ container.runtime.cancelActive()+ scope.launch { runCatching { container.runtime.unloadActive() } }+ }+ level in 5..19 || level in 20..79 -> {+ Log.i(TAG, "onTrimMemory level=$level action=trim(0.5)")+ scope.launch { container.runtime.trim(0.5f) }+ }+ else -> Log.i(TAG, "onTrimMemory level=$level action=none")+ }+ }++ companion object { const val TAG = "Edge0Trim" }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/MainActivity.kt b/android/app/src/main/java/dev/edge0/runtime/app/MainActivity.ktnew file mode 100644index 0000000..4c0e6bd--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/MainActivity.kt@@ -0,0 +1,27 @@+// MainActivity.kt - single-Activity host (edge-to-edge; Compose-drawn; theme follows settings).+package dev.edge0.runtime.app++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.runtime.getValue+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import dev.edge0.runtime.app.data.AppSettings+import dev.edge0.runtime.app.ui.AppRoot+import dev.edge0.runtime.app.ui.theme.Edge0Theme++class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ enableEdgeToEdge()+ super.onCreate(savedInstanceState)+ val container = (application as Edge0App).container+ setContent {+ val settings by container.settings.flow+ .collectAsStateWithLifecycle(initialValue = AppSettings())+ Edge0Theme(mode = settings.themeMode, fontScale = settings.fontScale) {+ AppRoot()+ }+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/data/AppDatabase.kt b/android/app/src/main/java/dev/edge0/runtime/app/data/AppDatabase.ktnew file mode 100644index 0000000..3395588--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/data/AppDatabase.kt@@ -0,0 +1,38 @@+// data/AppDatabase.kt+package dev.edge0.runtime.app.data++import android.content.Context+import androidx.room.Database+import androidx.room.Room+import androidx.room.RoomDatabase+import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase++// v2: assistant token-id sidecar - messages.genTokens BLOB (additive ALTER).+private val MIGRATION_1_2 = object : Migration(1, 2) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL("ALTER TABLE messages ADD COLUMN genTokens BLOB NULL")+ }+}++// v3: per-reply inline stats line - ttftMs/prefillTokS/memBytes columns.+private val MIGRATION_2_3 = object : Migration(2, 3) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL("ALTER TABLE messages ADD COLUMN ttftMs INTEGER NULL")+ db.execSQL("ALTER TABLE messages ADD COLUMN prefillTokS REAL NULL")+ db.execSQL("ALTER TABLE messages ADD COLUMN memBytes INTEGER NULL")+ }+}++@Database(entities = [ThreadEntity::class, MessageEntity::class], version = 3,+ exportSchema = true)+abstract class AppDatabase : RoomDatabase() {+ abstract fun threads(): ThreadDao+ abstract fun messages(): MessageDao++ companion object {+ fun create(context: Context): AppDatabase =+ Room.databaseBuilder(context, AppDatabase::class.java, "edge0-chat.db")+ .addMigrations(MIGRATION_1_2, MIGRATION_2_3).build()+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/data/ChatRepository.kt b/android/app/src/main/java/dev/edge0/runtime/app/data/ChatRepository.ktnew file mode 100644index 0000000..af1cf62--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/data/ChatRepository.kt@@ -0,0 +1,139 @@+// data/ChatRepository.kt - seam between UI and persistence. A fake implementation+// can be injected so UI walkthroughs run without the engine or disk.+package dev.edge0.runtime.app.data++import dev.edge0.runtime.app.runtime.StoredMessage+import dev.edge0.runtime.app.runtime.decodeIds+import java.util.UUID+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.map++/** Message as the UI sees it (includes persistence status). */+data class MessageView(+ val id: String,+ val role: String,+ val content: String,+ val thinking: String?,+ val thinkingMs: Long?,+ val status: String,+ val createdAt: Long,+ val newTokens: Int?,+ val decodeTokS: Double?,+ val ttftMs: Long? = null,+ val prefillTokS: Double? = null,+ val memBytes: Long? = null,+)++data class ThreadSummary(val id: String, val title: String?, val updatedAt: Long,+ val modelId: String)++interface ChatRepository {+ fun observeThreads(): Flow<List<ThreadSummary>>+ fun observeMessages(threadId: String): Flow<List<MessageView>>+ /** Creates the thread only with the first message (no empty entries). Returns threadId. */+ suspend fun startThreadWithUserMessage(modelId: String, userText: String): String+ /** Appends a user message to an existing thread and bumps updatedAt. */+ suspend fun addUserMessage(threadId: String, userText: String)+ /** Inserts a streaming placeholder assistant message, returns its id (finalize overwrites). */+ suspend fun beginAssistant(threadId: String, modelId: String): String+ suspend fun finalizeAssistant(id: String, content: String, thinking: String?,+ thinkingMs: Long?, status: String,+ promptTokens: Int?, newTokens: Int?, decodeTokS: Double?,+ genTokens: ByteArray? = null,+ ttftMs: Long? = null, prefillTokS: Double? = null,+ memBytes: Long? = null)+ suspend fun renameThread(id: String, title: String)+ suspend fun deleteThread(id: String)+ /** Editing a user message truncates everything after it (incl. old answer). */+ suspend fun editUserMessage(id: String, newText: String)+ suspend fun deleteMessage(id: String)+ suspend fun markStreamingInterrupted()+ /** Thread history (old to new, without the trailing user turn the caller appends). */+ suspend fun history(threadId: String): List<StoredMessage>+ /** Full view with id/timestamps (used by regenerate to locate the last assistant row). */+ suspend fun historyWithIds(threadId: String): List<MessageView>+ /** Deletes all messages at/after the given timestamp (regenerate truncation). */+ suspend fun deleteFrom(threadId: String, fromTs: Long)+}++class RoomChatRepository(private val db: AppDatabase) : ChatRepository {+ override fun observeThreads(): Flow<List<ThreadSummary>> =+ db.threads().observeAll().map { l -> l.map { ThreadSummary(it.id, it.title, it.updatedAt, it.modelId) } }++ override fun observeMessages(threadId: String): Flow<List<MessageView>> =+ db.messages().observeFor(threadId).map { l ->+ l.map { MessageView(it.id, it.role, it.content, it.thinking, it.thinkingMs,+ it.status, it.createdAt, it.newTokens, it.decodeTokS,+ it.ttftMs, it.prefillTokS, it.memBytes) }+ }++ override suspend fun startThreadWithUserMessage(modelId: String, userText: String): String {+ val now = System.currentTimeMillis()+ val tid = UUID.randomUUID().toString()+ db.threads().upsert(ThreadEntity(tid, userText.take(60), modelId, now, now))+ db.messages().insert(MessageEntity(UUID.randomUUID().toString(), tid, "user",+ userText, null, null, MsgStatus.OK, modelId, now,+ null, null, null))+ return tid+ }++ override suspend fun beginAssistant(threadId: String, modelId: String): String {+ val id = UUID.randomUUID().toString()+ db.messages().insert(MessageEntity(id, threadId, "assistant", "", null, null,+ MsgStatus.STREAMING, modelId,+ System.currentTimeMillis(), null, null, null))+ return id+ }++ override suspend fun addUserMessage(threadId: String, userText: String) {+ val now = System.currentTimeMillis()+ db.messages().insert(MessageEntity(UUID.randomUUID().toString(), threadId, "user",+ userText, null, null, MsgStatus.OK, "", now,+ null, null, null))+ db.threads().touch(threadId, null, now)+ }++ override suspend fun finalizeAssistant(id: String, content: String, thinking: String?,+ thinkingMs: Long?, status: String,+ promptTokens: Int?, newTokens: Int?,+ decodeTokS: Double?, genTokens: ByteArray?,+ ttftMs: Long?, prefillTokS: Double?, memBytes: Long?) {+ db.messages().finalizeAssistant(id, content, thinking, thinkingMs, status,+ promptTokens, newTokens, decodeTokS, genTokens,+ ttftMs, prefillTokS, memBytes)+ }++ override suspend fun renameThread(id: String, title: String) =+ db.threads().touch(id, title, System.currentTimeMillis())++ override suspend fun deleteThread(id: String) = db.threads().delete(id)++ override suspend fun editUserMessage(id: String, newText: String) {+ val msg = db.messages().byId(id) ?: return+ db.messages().update(msg.copy(content = newText))+ db.messages().deleteFrom(msg.threadId, msg.createdAt + 1) // truncate everything after (incl. old answer)+ // editing the first user message renames the thread (title = first user message)+ if (db.messages().olderUserCount(msg.threadId, msg.createdAt) == 0) {+ db.threads().touch(msg.threadId, newText.take(60), System.currentTimeMillis())+ }+ }++ override suspend fun deleteMessage(id: String) = db.messages().deleteById(id)++ override suspend fun markStreamingInterrupted() = db.messages().markStreamingInterrupted()++ override suspend fun history(threadId: String): List<StoredMessage> =+ db.messages().observeFor(threadId).first()+ .map { StoredMessage(it.role, it.content, it.thinking, decodeIds(it.genTokens)) }++ override suspend fun historyWithIds(threadId: String): List<MessageView> =+ db.messages().observeFor(threadId).first()+ .map { MessageView(it.id, it.role, it.content, it.thinking, it.thinkingMs,+ it.status, it.createdAt, it.newTokens, it.decodeTokS,+ it.ttftMs, it.prefillTokS, it.memBytes) }++ override suspend fun deleteFrom(threadId: String, fromTs: Long) =+ db.messages().deleteFrom(threadId, fromTs)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/data/Daos.kt b/android/app/src/main/java/dev/edge0/runtime/app/data/Daos.ktnew file mode 100644index 0000000..5b2d9a5--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/data/Daos.kt@@ -0,0 +1,63 @@+// data/Daos.kt - thread/message DAOs (flat list ordered by updatedAt desc).+package dev.edge0.runtime.app.data++import androidx.room.Dao+import androidx.room.Delete+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import androidx.room.Update+import kotlinx.coroutines.flow.Flow++@Dao+interface ThreadDao {+ @Query("SELECT * FROM threads ORDER BY updatedAt DESC")+ fun observeAll(): Flow<List<ThreadEntity>>++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(thread: ThreadEntity)++ @Query("UPDATE threads SET title = COALESCE(:title, title), updatedAt = :ts WHERE id = :id")+ suspend fun touch(id: String, title: String?, ts: Long)++ @Query("DELETE FROM threads WHERE id = :id")+ suspend fun delete(id: String)+}++@Dao+interface MessageDao {+ @Query("SELECT * FROM messages WHERE threadId = :threadId ORDER BY createdAt ASC")+ fun observeFor(threadId: String): Flow<List<MessageEntity>>++ @Insert+ suspend fun insert(msg: MessageEntity)++ @Update+ suspend fun update(msg: MessageEntity)++ @Query("UPDATE messages SET content=:content, thinking=:thinking, thinkingMs=:thinkingMs, " ++ "status=:status, promptTokens=:pt, newTokens=:nt, decodeTokS=:dts, " ++ "genTokens=:genTokens, ttftMs=:ttft, prefillTokS=:pfs, memBytes=:mem WHERE id=:id")+ suspend fun finalizeAssistant(id: String, content: String, thinking: String?,+ thinkingMs: Long?, status: String,+ pt: Int?, nt: Int?, dts: Double?, genTokens: ByteArray?,+ ttft: Long?, pfs: Double?, mem: Long?)++ /** Cold-start sweep: rows left streaming by a killed process become interrupted. */+ @Query("UPDATE messages SET status='interrupted' WHERE status='streaming'")+ suspend fun markStreamingInterrupted()++ /** Edit/regenerate truncation: delete every message at/after the given created-at. */+ @Query("DELETE FROM messages WHERE threadId=:threadId AND createdAt >= :fromTs")+ suspend fun deleteFrom(threadId: String, fromTs: Long)++ @Query("SELECT * FROM messages WHERE id = :id")+ suspend fun byId(id: String): MessageEntity?++ @Query("SELECT COUNT(*) FROM messages WHERE threadId=:threadId AND createdAt < :ts " ++ "AND role='user'")+ suspend fun olderUserCount(threadId: String, ts: Long): Int++ @Query("DELETE FROM messages WHERE id = :id")+ suspend fun deleteById(id: String)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/data/Entities.kt b/android/app/src/main/java/dev/edge0/runtime/app/data/Entities.ktnew file mode 100644index 0000000..d2da789--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/data/Entities.kt@@ -0,0 +1,52 @@+// data/Entities.kt - minimal two-table Room schema. Tagged raw text is not stored:+// thinking/body are separate columns; history reconstruction goes through+// HistoryWindow (tag pairs are re-added at render time).+package dev.edge0.runtime.app.data++import androidx.room.Entity+import androidx.room.ForeignKey+import androidx.room.Index+import androidx.room.PrimaryKey++@Entity(tableName = "threads", indices = [Index("updatedAt")])+data class ThreadEntity(+ @PrimaryKey val id: String,+ val title: String?, // truncated first user message (no AI summary)+ val modelId: String,+ val createdAt: Long,+ val updatedAt: Long,+)++/** status: ok | cancelled | error | interrupted (killed process leaves interrupted) */+@Entity(+ tableName = "messages",+ foreignKeys = [ForeignKey(entity = ThreadEntity::class, parentColumns = ["id"],+ childColumns = ["threadId"], onDelete = ForeignKey.CASCADE)],+ indices = [Index("threadId", "createdAt")],+)+data class MessageEntity(+ @PrimaryKey val id: String,+ val threadId: String,+ val role: String, // user | assistant+ val content: String, // tag-free body text+ val thinking: String?, // extracted reasoning (null = no thinking this turn)+ val thinkingMs: Long?,+ val status: String, // "streaming" while generating, overwritten at terminal state+ val modelId: String,+ val createdAt: Long,+ val promptTokens: Int?,+ val newTokens: Int?,+ val decodeTokS: Double?,+ val genTokens: ByteArray? = null, // sidecar: token ids stepped this turn (int32 LE BLOB)+ val ttftMs: Long? = null, // v3: perceived time-to-first-token, wall clock ms+ val prefillTokS: Double? = null, // v3: prefill tok/s+ val memBytes: Long? = null, // v3: expert-pool resident bytes (excludes cacheable mmap)+)++object MsgStatus {+ const val STREAMING = "streaming"+ const val OK = "ok"+ const val CANCELLED = "cancelled"+ const val ERROR = "error"+ const val INTERRUPTED = "interrupted"+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/data/FakeChatRepository.kt b/android/app/src/main/java/dev/edge0/runtime/app/data/FakeChatRepository.ktnew file mode 100644index 0000000..ad05eae--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/data/FakeChatRepository.kt@@ -0,0 +1,99 @@+// data/FakeChatRepository.kt - in-memory implementation for UI walkthroughs (no engine, no disk).+package dev.edge0.runtime.app.data++import dev.edge0.runtime.app.runtime.StoredMessage+import dev.edge0.runtime.app.runtime.decodeIds+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.map++class FakeChatRepository : ChatRepository {+ data class Msg(val id: String, val threadId: String, val role: String, var content: String,+ var thinking: String?, var status: String, val createdAt: Long,+ var genTokens: ByteArray? = null)++ private val threads = MutableStateFlow<List<ThreadSummary>>(emptyList())+ private val msgs = MutableStateFlow<List<Msg>>(emptyList())+ private var seq = 0+ private fun nid() = "fx${seq++}"++ override fun observeThreads(): Flow<List<ThreadSummary>> = threads+ override fun observeMessages(threadId: String): Flow<List<MessageView>> =+ msgs.map { l -> l.filter { it.threadId == threadId }.sortedBy { it.createdAt }+ .map { MessageView(it.id, it.role, it.content, it.thinking, null, it.status,+ it.createdAt, null, null) } }++ override suspend fun startThreadWithUserMessage(modelId: String, userText: String): String {+ val tid = nid()+ val now = System.currentTimeMillis()+ msgs.value += Msg(tid, tid, "user", userText, null, MsgStatus.OK, now)+ threads.value = listOf(ThreadSummary(tid, userText.take(60), now, modelId)) + threads.value+ return tid+ }++ override suspend fun beginAssistant(threadId: String, modelId: String): String {+ val id = nid()+ msgs.value += Msg(id, threadId, "assistant", "", null, MsgStatus.STREAMING,+ System.currentTimeMillis())+ return id+ }++ override suspend fun addUserMessage(threadId: String, userText: String) {+ val now = System.currentTimeMillis()+ msgs.value += Msg(nid(), threadId, "user", userText, null, MsgStatus.OK, now)+ threads.value = threads.value.map {+ if (it.id == threadId) it.copy(updatedAt = now) else it+ }+ }++ override suspend fun finalizeAssistant(id: String, content: String, thinking: String?,+ thinkingMs: Long?, status: String,+ promptTokens: Int?, newTokens: Int?,+ decodeTokS: Double?, genTokens: ByteArray?,+ ttftMs: Long?, prefillTokS: Double?, memBytes: Long?) {+ msgs.value = msgs.value.map {+ if (it.id == id) it.copy(content = content, thinking = thinking, status = status,+ genTokens = genTokens)+ else it+ }+ }++ override suspend fun renameThread(id: String, title: String) {+ threads.value = threads.value.map { if (it.id == id) it.copy(title = title) else it }+ }++ override suspend fun deleteThread(id: String) {+ threads.value = threads.value.filter { it.id != id }+ msgs.value = msgs.value.filter { it.threadId != id }+ }++ override suspend fun editUserMessage(id: String, newText: String) {+ val target = msgs.value.firstOrNull { it.id == id } ?: return+ msgs.value = msgs.value.filter { it.createdAt < target.createdAt } ++ target.copy(content = newText)+ }++ override suspend fun deleteMessage(id: String) {+ msgs.value = msgs.value.filter { it.id != id }+ }++ override suspend fun markStreamingInterrupted() {+ msgs.value = msgs.value.map {+ if (it.status == MsgStatus.STREAMING) it.copy(status = MsgStatus.INTERRUPTED) else it+ }+ }++ override suspend fun history(threadId: String): List<StoredMessage> =+ msgs.value.filter { it.threadId == threadId && it.status != MsgStatus.STREAMING }+ .sortedBy { it.createdAt }+ .map { StoredMessage(it.role, it.content, it.thinking, decodeIds(it.genTokens)) }++ override suspend fun historyWithIds(threadId: String): List<MessageView> =+ msgs.value.filter { it.threadId == threadId }.sortedBy { it.createdAt }+ .map { MessageView(it.id, it.role, it.content, it.thinking, null, it.status,+ it.createdAt, null, null) }++ override suspend fun deleteFrom(threadId: String, fromTs: Long) {+ msgs.value = msgs.value.filter { !(it.threadId == threadId && it.createdAt >= fromTs) }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/data/SettingsStore.kt b/android/app/src/main/java/dev/edge0/runtime/app/data/SettingsStore.ktnew file mode 100644index 0000000..3fc1595--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/data/SettingsStore.kt@@ -0,0 +1,97 @@+// data/SettingsStore.kt - DataStore preferences snapshot (appearance / assistant / sampling / toggles).+// Defaults follow the upstream sampling quartet; installs without a stored key+// fall back to the current defaults.+package dev.edge0.runtime.app.data++import android.content.Context+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.booleanPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.floatPreferencesKey+import androidx.datastore.preferences.core.intPreferencesKey+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import dev.edge0.runtime.app.ui.theme.ThemeMode+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.map++private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("edge0_settings")++data class AppSettings(+ val themeMode: ThemeMode = ThemeMode.DARK, // dark by default (does not follow system)+ val fontScale: Float = 1.0f, // 0.85..1.3+ val systemPrompt: String = "You're Edge0, an on-device AI assistant.",+ val useSystemPrompt: Boolean = true, // explicit toggle; empty text also means off+ val temperature: Float = 0.2f, // precise default (control lives in Settings)+ val topK: Int = 64,+ val topP: Float = 0.95f,+ val repetitionPenalty: Float = 1.1f, // aligned with upstream; 1.0 = off+ val maxNewTokens: Int = 0, // 0 = app default 1024 (reasoning models need headroom)+ val seed: Long = 0x20260915L,+ val enableThinking: Boolean = false, // master thinking toggle: drives both the+ // model-side template instruction and UI block visibility;+ // storage key kept as show_thinking for backward compatibility+ val metricsOverlay: Boolean = false, // off by default+ val activeModelDir: String = "",+)++object SettingsKeys {+ val THEME = stringPreferencesKey("theme_mode")+ val FONT_SCALE = floatPreferencesKey("font_scale")+ val SYSTEM_PROMPT = stringPreferencesKey("system_prompt")+ val USE_SYS_PROMPT = booleanPreferencesKey("use_system_prompt")+ val TEMPERATURE = floatPreferencesKey("temperature")+ val TOP_K = intPreferencesKey("top_k")+ val TOP_P = floatPreferencesKey("top_p")+ val REP_PENALTY = floatPreferencesKey("repetition_penalty")+ val MAX_NEW = intPreferencesKey("max_new_tokens")+ val SEED = longPreferencesKey("seed")+ val SHOW_THINKING = booleanPreferencesKey("show_thinking")+ val OVERLAY = booleanPreferencesKey("metrics_overlay")+ val ACTIVE_MODEL = stringPreferencesKey("active_model_dir")+}++class SettingsStore(private val context: Context) {++ val flow: Flow<AppSettings> = context.dataStore.data.map { p ->+ val d = AppSettings()+ AppSettings(+ themeMode = p[SettingsKeys.THEME]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() } ?: d.themeMode,+ fontScale = p[SettingsKeys.FONT_SCALE] ?: d.fontScale,+ systemPrompt = p[SettingsKeys.SYSTEM_PROMPT] ?: d.systemPrompt,+ useSystemPrompt = p[SettingsKeys.USE_SYS_PROMPT] ?: d.useSystemPrompt,+ temperature = p[SettingsKeys.TEMPERATURE] ?: d.temperature,+ topK = p[SettingsKeys.TOP_K] ?: d.topK,+ topP = p[SettingsKeys.TOP_P] ?: d.topP,+ repetitionPenalty = p[SettingsKeys.REP_PENALTY] ?: d.repetitionPenalty,+ maxNewTokens = p[SettingsKeys.MAX_NEW] ?: d.maxNewTokens,+ seed = p[SettingsKeys.SEED] ?: d.seed,+ enableThinking = p[SettingsKeys.SHOW_THINKING] ?: d.enableThinking,+ metricsOverlay = p[SettingsKeys.OVERLAY] ?: d.metricsOverlay,+ activeModelDir = p[SettingsKeys.ACTIVE_MODEL] ?: d.activeModelDir,+ )+ }++ suspend fun update(block: (AppSettings) -> AppSettings) {+ val current = runCatching { flow.first() }.getOrElse { AppSettings() }+ val next = block(current)+ context.dataStore.edit { p ->+ p[SettingsKeys.THEME] = next.themeMode.name+ p[SettingsKeys.FONT_SCALE] = next.fontScale+ p[SettingsKeys.SYSTEM_PROMPT] = next.systemPrompt+ p[SettingsKeys.USE_SYS_PROMPT] = next.useSystemPrompt+ p[SettingsKeys.TEMPERATURE] = next.temperature+ p[SettingsKeys.TOP_K] = next.topK+ p[SettingsKeys.TOP_P] = next.topP+ p[SettingsKeys.REP_PENALTY] = next.repetitionPenalty+ p[SettingsKeys.MAX_NEW] = next.maxNewTokens+ p[SettingsKeys.SEED] = next.seed+ p[SettingsKeys.SHOW_THINKING] = next.enableThinking+ p[SettingsKeys.OVERLAY] = next.metricsOverlay+ p[SettingsKeys.ACTIVE_MODEL] = next.activeModelDir+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/GenState.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/GenState.ktnew file mode 100644index 0000000..bec25d0--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/GenState.kt@@ -0,0 +1,26 @@+// runtime/GenState.kt - generation state machine and events (typed, single-slot).+package dev.edge0.runtime.app.runtime++import dev.edge0.runtime.engine.Status++sealed interface GenState {+ data object Idle : GenState+ data class Loading(val modelDir: String) : GenState+ data class Streaming(val threadId: String) : GenState+ data object Cancelling : GenState // settling gate: cancel sent, old job not yet home (new submits refused)+ data class Error(val status: Status, val diag: String) : GenState+}++sealed interface GenEvent {+ data class ThinkPiece(val s: String) : GenEvent+ data class TextPiece(val s: String) : GenEvent+ // genIds: token ids actually stepped this turn (sidecar; absent on cancel/failure)+ data class Done(val metrics: RequestMetrics?, val genIds: IntArray = IntArray(0)) : GenEvent+ data class Cancelled(val metrics: RequestMetrics?) : GenEvent+ data class Failed(val status: Status, val diag: String) : GenEvent+}++fun Seg.toEvent(): GenEvent = when (this) {+ is Seg.Text -> GenEvent.TextPiece(s)+ is Seg.Think -> GenEvent.ThinkPiece(s)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/HistoryWindow.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/HistoryWindow.ktnew file mode 100644index 0000000..758b686--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/HistoryWindow.kt@@ -0,0 +1,69 @@+// runtime/HistoryWindow.kt - multi-turn context assembly with a character budget.+// The budget is conservative (mixed CJK/Latin ~1.5 chars/token against a 4096-token+// context); the hard overflow gate is the engine itself (INVALID_ARG with a+// "prompt tokens=" diagnostic) and callers retry with a tighter budget.+// Assistant history re-enters the prompt wrapped in think tag pairs at render time.+package dev.edge0.runtime.app.runtime++import dev.edge0.runtime.engine.ChatMessage++/** Minimal persisted-message shape (Room entities map to this).+ * genIds = assistant token-id sidecar: lives and dies with its row. */+data class StoredMessage(val role: String, val content: String, val thinking: String? = null,+ val genIds: IntArray? = null)++/** Sidecar serialization: IntArray to int32-LE BLOB (Room column); empty becomes null. */+fun encodeIds(ids: IntArray?): ByteArray? {+ if (ids == null || ids.isEmpty()) return null+ val bb = java.nio.ByteBuffer.allocate(ids.size * 4).order(java.nio.ByteOrder.LITTLE_ENDIAN)+ ids.forEach { bb.putInt(it) }+ return bb.array()+}++/** Sidecar deserialization (length not a multiple of 4, or empty, falls back to text). */+fun decodeIds(b: ByteArray?): IntArray? {+ if (b == null || b.isEmpty() || b.size % 4 != 0) return null+ val bb = java.nio.ByteBuffer.wrap(b).order(java.nio.ByteOrder.LITTLE_ENDIAN)+ return IntArray(b.size / 4) { bb.int }+}++object HistoryWindow {+ const val DEFAULT_BUDGET_CHARS = 10000++ /** turns old to new (user/assistant alternating, last is the user question); system first when non-blank. */+ fun build(systemPrompt: String?, turns: List<StoredMessage>,+ budgetChars: Int = DEFAULT_BUDGET_CHARS): List<ChatMessage> {+ val msgs = ArrayList<ChatMessage>(turns.size + 1)+ var used = 0+ if (!systemPrompt.isNullOrBlank()) {+ msgs.add(ChatMessage("system", systemPrompt))+ used += systemPrompt.length+ }+ // poison-turn filter: blank assistant turns without ids must not reach the+ // model - replaying "I answered nothing" derails every later turn. Dropped from+ // the model-facing context only; the UI record is untouched.+ val clean = turns.filterNot { it.role == "assistant" && it.content.isBlank() && it.genIds?.isEmpty() != false }+ val picked = ArrayList<StoredMessage>()+ for (t in clean.asReversed()) {+ val cost = t.content.length + (t.thinking?.length ?: 0) + 12+ // the current question is always kept, even over budget; engine overflow diagnostic triggers retry+ if (picked.isNotEmpty() && used + cost > budgetChars) break+ picked.add(t)+ used += cost+ }+ picked.reverse()+ for (t in picked) {+ // Keep the engine transcript exact while the UI still stores and+ // renders thinking separately. The native renderer handles the+ // family-specific newline/empty-pair form.+ val engineContent = if (t.role == "assistant" && !t.thinking.isNullOrEmpty()) {+ "<think>" + t.thinking + "</think>" + t.content+ } else t.content+ msgs.add(ChatMessage(t.role, engineContent, t.genIds))+ }+ return msgs+ }++ /** Tightened budget for the overflow retry (caller catches the INVALID_ARG diagnostic). */+ fun tighterBudget(budgetChars: Int): Int = (budgetChars / 2).coerceAtLeast(400)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/LlamaNative.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/LlamaNative.ktnew file mode 100644index 0000000..098108c--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/LlamaNative.kt@@ -0,0 +1,25 @@+// LlamaNative.kt - JNI declaration surface for llama_chat.c.+// external fun symbols bind hard to the package name+// (dev_edge0_runtime_app_runtime_LlamaNative_*): moving packages requires+// mirroring the rename on the C side. Top-level object members keep stable+// exported names (no @JvmName needed).+package dev.edge0.runtime.app.runtime++object LlamaNative {+ init {+ // packaged via APK jniLibs (five shared libs from tools/llama/build_vendor_libs.sh);+// DT_NEEDED resolves libllama -> libggml* automatically+ System.loadLibrary("edge0llama")+ }++ external fun nativeInit(model: String, lora: String, heads: String,+ nCtx: Int, poolMb: Int, blobMb: Int, pred: Int, ioThreads: Int): String+ external fun nativeReset(): String+ external fun nativeAddRole(role: String, text: String): String+ external fun nativeGenerate(sink: (String) -> Unit, maxTokens: Int, temp: Float,+ thinkingOn: Boolean): String+ external fun nativeCancel()+ external fun nativeStats(): String+ external fun nativeLastAssistant(): String?+ external fun nativeFree(): String+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/LlamaRuntime.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/LlamaRuntime.ktnew file mode 100644index 0000000..780372a--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/LlamaRuntime.kt@@ -0,0 +1,264 @@+// runtime/LlamaRuntime.kt - the Runtime implementation backed by llama.cpp + GGUF.+// Native side = LlamaNative / llama_chat.c; shared libs are staged into+// build-dl/llama-libs at build time (gitignored, produced by+// tools/llama/build_vendor_libs.sh from the pinned engine tree).+// Auto tiering (mirrors the validated CLI configuration): model >= 12GB takes the+// 35B tier - expert pool 6144MB + blob 3072MB + n_ctx 4096, demand-only+// (prefetch measured net-negative on-device, so E0_PREROUTER is never set);+// otherwise the 8B tier - fully resident, pool/blob disabled, n_ctx 8192,+// companion LoRA auto-discovered (lora_*.gguf).+// LoRA companion applies to the 8B tier only: the 35B build bakes its LoRA in,+// and attaching an adapter on top fails initialization (verified on-device).+// History contract: native is append-only; this class keeps a mirror and does a+// prefix diff - any fork triggers a full rebuild (thread switch / message edit).+package dev.edge0.runtime.app.runtime++import dev.edge0.runtime.engine.ChatMessage+import dev.edge0.runtime.engine.GenParams+import dev.edge0.runtime.engine.Status+import dev.edge0.runtime.app.runtime.PoolMetrics+import java.io.File+import java.util.concurrent.Executors+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.asCoroutineDispatcher+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++class LlamaRuntime : Runtime {+ override val state = MutableStateFlow<GenState>(GenState.Idle)+ override val lastMetrics = MutableStateFlow<RequestMetrics?>(null)++ @Volatile private var _dir: String? = null+ override val activeModelDir: String? get() = _dir++ private val slotMutex = Mutex()+ private val genExecutor = Executors.newSingleThreadExecutor { r ->+ Thread(r, "llama-gen").apply { isDaemon = true }+ }+ private val genCtx: CoroutineDispatcher = genExecutor.asCoroutineDispatcher()++ private val mirror = ArrayList<Pair<String, String>>() // (role, content) kept in sync with native++ companion object {+ const val TAG = "LlamaRuntime"+ const val BIG_MODEL_BYTES = 12L shl 30 // tier threshold (midpoint of 8B=5.0GB / 35B=21.7GB)+ }++ private fun runCatchingNative(block: () -> String): String? =+ try { block() } catch (t: Throwable) {+ // never swallow native failures into a generic "so load failed" -+ // the real cause must surface in the return value+ "ERR native: ${t.javaClass.simpleName}: ${t.message?.take(160)}"+ }++ override suspend fun ensureLoaded(path: String) {+ slotMutex.withLock {+ if (_dir == path && state.value !is GenState.Error) return+ val model = resolveGguf(path)+ ?: run {+ state.value = GenState.Error(Status.FORMAT_VERSION, "model.gguf not found: $path")+ return+ }+ state.value = GenState.Loading(path)+ if (_dir != null) { // model swap: unload first (never two loads resident; nativeInit self-clears as backstop)+ runCatching { LlamaNative.nativeFree() }+ _dir = null+ }+ val big = model.length() >= BIG_MODEL_BYTES+ val dir = model.parentFile+ val lora = if (big) "" else dir?.listFiles { f ->+ f.name.startsWith("lora_") && f.name.endsWith(".gguf")+ }?.firstOrNull()?.absolutePath ?: ""+ val heads = dir?.let { File(it, "e0_heads.bin") }?.takeIf { it.exists() }?.absolutePath ?: ""+ val r = withContext(Dispatchers.IO) {+ runCatchingNative {+ LlamaNative.nativeInit(model.absolutePath, lora,+ if (big) heads else "", // heads ship with the 35B tier (idle unless E0_PREROUTER is enabled)+ if (big) 4096 else 8192,+ if (big) 6144 else 0,+ if (big) 3072 else 0,+ 0, // prefetch: measured net-negative, permanently off+ 4)+ }+ }+ if (r == null || !r.startsWith("OK")) {+ state.value = GenState.Error(Status.IO, (r ?: "libedge0llama.so failed to load"))+ return+ }+ mirror.clear()+ _dir = path+ state.value = GenState.Idle+ }+ }++ /** path may be a .gguf file, or a directory containing model.gguf. */+ private fun resolveGguf(path: String): File? {+ val f = File(path)+ return when {+ f.isFile && path.endsWith(".gguf") -> f+ f.isDirectory -> File(f, "model.gguf").takeIf { it.exists() }+ ?: f.listFiles { x -> x.name.endsWith(".gguf") && !x.name.startsWith("lora_") }?.firstOrNull()+ else -> null+ }+ }++ override suspend fun unloadActive() {+ slotMutex.withLock {+ if (_dir == null) return+ withContext(Dispatchers.IO) { runCatchingNative { LlamaNative.nativeFree() } }+ mirror.clear()+ _dir = null+ if (state.value !is GenState.Error) state.value = GenState.Idle+ }+ }++ override suspend fun trim(ratio: Float): Boolean {+ // TODO: expose moe_pool trim through native; the pool currently self-sheds via E0_MEM_FLOOR_MB+ return true+ }++ @OptIn(ExperimentalCoroutinesApi::class)+ override fun submit(threadId: String, messages: List<ChatMessage>,+ thinkingOn: Boolean, params: GenParams): Flow<GenEvent> =+ callbackFlow {+ if (_dir == null) {+ trySend(GenEvent.Failed(Status.INVALID_ARG, "no active llama session")); close(); return@callbackFlow+ }+ if (!state.compareAndSet(GenState.Idle, GenState.Streaming(threadId))) {+ trySend(GenEvent.Failed(Status.INVALID_ARG, "generation slot busy")); close(); return@callbackFlow+ }+ launch(genCtx) {+ val splitter = ThinkSplitter(initialThink = thinkingOn)+ val tSend = System.nanoTime()+ var tFirst = 0L+ val uiText = StringBuilder()+ val sink: (String) -> Unit = { piece ->+ if (piece.isNotEmpty()) {+ if (tFirst == 0L) tFirst = System.nanoTime()+ uiText.append(piece)+ splitter.feed(piece).forEach { trySend(it.toEvent()) }+ }+ }+ syncHistory(messages)+ val res = runCatchingNative {+ LlamaNative.nativeGenerate(sink, params.maxNewTokens.coerceAtLeast(1),+ params.temperature, thinkingOn)+ } ?: "ERR native"+ splitter.flush().forEach { trySend(it.toEvent()) }+ // native already appended this turn with stepped ids (sidecar); mirror keeps index parity+ if (res.startsWith("OK")) mirror.add("assistant" to uiText.toString())+ val term: GenEvent = when {+ res.startsWith("OK") || res.startsWith("CANCELLED") -> {+ val m = parseMetrics(res)+ val mm = m?.copy(+ // user-perceived TTFT measured here (native first_ms is post-prefill sampling time)+ firstTokenMs = if (tFirst > 0) (tFirst - tSend) / 1_000_000 else m.firstTokenMs,+ peakRssBytes = readPeakRss(),+ pool = poolMetrics(),+ gpu = GpuMetrics(probed = false, ok = false, active = false,+ device = "cpu(llama-route)", why = "CPU-only (shipping configuration)"),+ )+ if (mm != null) lastMetrics.value = mm+ if (res.startsWith("OK")) GenEvent.Done(mm) else GenEvent.Cancelled(mm)+ }+ else -> GenEvent.Failed(Status.IO, res)+ }+ trySend(term)+ if (state.value !is GenState.Error) state.value = GenState.Idle+ close()+ }+ awaitClose { }+ }++ private fun syncHistory(msgs: List<ChatMessage>) {+ // Prefix match: user turns compare verbatim (UI text feeds native losslessly);+ // assistant turns match by ROLE ONLY - the ground truth lives on the native side+ // as stepped ids (sidecar), while UI text is a lossy reassembly with think tags+ // stripped. Verbatim comparison there would always fake a fork and replay the+ // whole history every turn (once cost 60s of dead waiting). Non-contiguous hits+ // must not count toward the common prefix either.+ // Known edge: editing/regenerating history falls back to full rebuild.+ fun ok(i: Int) = i < mirror.size && mirror[i].first == msgs[i].role &&+ (msgs[i].role != "user" || mirror[i].second == msgs[i].content)+ var common = 0+ while (common < msgs.size && ok(common)) common+++ if (common == mirror.size) {+ msgs.drop(common).forEach { m ->+ val content = m.content+ LlamaNative.nativeAddRole(m.role, content)+ mirror.add(m.role to content)+ }+ } else {+ LlamaNative.nativeReset()+ mirror.clear()+ msgs.forEach { m ->+ val content = m.content+ LlamaNative.nativeAddRole(m.role, content)+ mirror.add(m.role to content)+ }+ }+ }++ internal fun parseMetrics(res: String): RequestMetrics? {+ val kv = Regex("""(\w+)=(\S+)""").findAll(res).associate { it.groupValues[1] to it.groupValues[2] }+ val gen = kv["gen"]?.toIntOrNull() ?: return null+ val tps = kv["tps"]?.toDoubleOrNull() ?: 0.0+ val pf = kv["prefill_ms"]?.toLongOrNull() ?: 0L+ val first = kv["first_ms"]?.toLongOrNull() ?: 0L+ val prompt = kv["prompt"]?.toIntOrNull() ?: 0+ val reused = kv["reused"]?.toIntOrNull() ?: 0+ return RequestMetrics(+ promptTokens = prompt,+ prefix_reused = reused > 0,+ prefix_reused_tokens = reused,+ newTokens = gen,+ prefillMs = pf,+ firstTokenMs = first,+ decodeMs = (if (gen > 0) (gen * 1000.0 / (tps + 1e-6)).toLong() else 0L) + first,+ prefillTokS = if (pf > 0) (prompt - reused) * 1000.0 / pf else 0.0,+ decodeTokS = tps,+ peakRssBytes = 0,+ chatTurns = 1,+ )+ }++ private fun poolMetrics(): PoolMetrics? {+ val raw = runCatching { LlamaNative.nativeStats() }.getOrNull() ?: return null+ if (!raw.contains("hits=")) return null+ val kv = raw.split(" ", "\n").mapNotNull {+ val i = it.indexOf('='); if (i <= 0) null else it.substring(0, i) to it.substring(i + 1)+ }.toMap()+ fun L(k: String) = (kv[k]?.toLongOrNull() ?: 0L)+ val slots = (kv["slots"] ?: "").split("/")+ return PoolMetrics(+ resident_bytes = L("resident"),+ hits = L("hits"), misses = L("misses"),+ prefetch_used = L("pf_used"), prefetch_mispredict = L("pf_miss"),+ evictions = L("evicts"), stall_ns = L("stall_ns"),+ flash_bytes = L("flash"),+ slots_used = slots.firstOrNull()?.toLongOrNull() ?: 0L,+ slots_total = slots.getOrNull(1)?.toLongOrNull() ?: 0L,+ )+ }++ private fun readPeakRss(): Long {+ val raw = runCatching { LlamaNative.nativeStats() }.getOrNull() ?: return 0+ return Regex("vmhwm_kb=(\\d+)").find(raw)?.groupValues?.get(1)?.toLongOrNull()?.times(1024) ?: 0+ }++ /** Raw native text of the last assistant turn (ground truth for history sync). */+ fun lastAssistantNative(): String? = runCatching { LlamaNative.nativeLastAssistant() }.getOrNull()++ override fun cancelActive() {+ runCatching { LlamaNative.nativeCancel() }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/MetricsMapper.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/MetricsMapper.ktnew file mode 100644index 0000000..4e04782--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/MetricsMapper.kt@@ -0,0 +1,99 @@+// runtime/MetricsMapper.kt - typed mapping of engine metrics (append-only schema;+// unknown fields ignored, missing fields default to the N/A display semantics).+package dev.edge0.runtime.app.runtime++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++@Serializable+data class RouteMetrics(+ val mode: String = "", // predicted|exact (audit echo, prevents track mixing)+ val feature: String = "", // executed|teacher|n/a+ @SerialName("dec_steps") val decSteps: Long = 0,+ @SerialName("pred_used") val predUsed: Long = 0,+ @SerialName("route_set_size") val routeSetSize: Int = 0,+ val agree: Double? = null,+)++@Serializable+data class GpuMetrics(+ val probed: Boolean = false,+ val ok: Boolean = false,+ val active: Boolean = false, // whether this request used the GPU (prefill window)+ val policy: Int = 0,+ val device: String? = null,+ val why: String = "", // probe conclusion echo (ok / dlopen:.. / policy-cpu ...)+ @SerialName("cache_hit") val cacheHit: Boolean = false,+)++@Serializable+data class ConfigEcho(+ @SerialName("clip_value") val clipValue: Double = 0.0, // per-layer sanitize clamp (0 = off)+ @SerialName("bundle_mode") val bundleMode: String = "",+ @SerialName("production_top_k") val productionTopK: Int = 0,+)++@Serializable+data class ParamsEcho(+ @SerialName("repetition_penalty") val repPenalty: Double = 0.0,+ @SerialName("first_token_greedy") val firstTokenGreedy: Int = 0,+)++@Serializable+data class PoolMetrics(+ val resident_bytes: Long = 0,+ val hits: Long = 0,+ val misses: Long = 0,+ val prefetch_used: Long = 0,+ val prefetch_mispredict: Long = 0,+ val evictions: Long = 0,+ val stall_ns: Long = 0,+ val flash_bytes: Long = 0,+ val slots_used: Long = 0,+ val slots_total: Long = 0,+)++@Serializable+data class RequestMetrics(+ val schema: Int = 0,+ @SerialName("prompt_tokens") val promptTokens: Int = 0,+ val prefix_reused: Boolean = false,+ val prefix_reused_tokens: Int = 0,+ @SerialName("new_tokens") val newTokens: Int = 0,+ @SerialName("prefill_ms") val prefillMs: Long = 0,+ @SerialName("first_token_ms") val firstTokenMs: Long = 0,+ @SerialName("decode_ms") val decodeMs: Long = 0,+ @SerialName("prefill_tok_s") val prefillTokS: Double = 0.0,+ @SerialName("decode_tok_s") val decodeTokS: Double = 0.0,+ @SerialName("peak_rss_bytes") val peakRssBytes: Long = 0,+ @SerialName("chat_turns") val chatTurns: Int = 0,+ @SerialName("thinking_on") val thinkingOn: Boolean = true,+ val cancelled: Boolean = false,+ val error: String = "",+ // additive echo section: missing fields on older engines fall back to N/A defaults+ val config: ConfigEcho? = null,+ val params: ParamsEcho? = null,+ val route: RouteMetrics? = null,+ val pool: PoolMetrics? = null,+ val gpu: GpuMetrics? = null,+) {+ val hitRate: Double? get() = pool?.let {+ val t = it.hits + it.misses+ if (t > 0) it.hits.toDouble() / t else null+ }+}++object MetricsMapper {+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ /** Parse failure / empty input returns null (UI shows N/A, never crashes). */+ fun parse(raw: String?): RequestMetrics? {+ if (raw.isNullOrBlank()) return null+ return try {+ json.decodeFromString(RequestMetrics.serializer(), raw)+ } catch (_: Exception) {+ null+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/ModelInventory.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/ModelInventory.ktnew file mode 100644index 0000000..8773832--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/ModelInventory.kt@@ -0,0 +1,51 @@+// runtime/ModelInventory.kt - model discovery for the import/models screen.+// Scans the app's model roots (internal files/models first; external files/models+// as a secondary root - on some OEM Android builds shell-pushed files under+// Android/data/<pkg> are invisible to the app uid, so in-app copy to the+// internal dir is the primary staging channel). Only flat *.gguf files are+// entries; lora_*.gguf companions are picked up by the runtime, not listed.+package dev.edge0.runtime.app.runtime++import java.io.File++data class ModelEntry(+ val name: String,+ val dir: File, // the .gguf file itself+ val totalBytes: Long, // file size (requirement yardstick)+ val dirBytes: Long, // same, kept for the UI's size column+ val valid: Boolean,+ val hint: String?, // reason shown when invalid+ val mode: String = "llama-gguf",+)++object ModelInventory {++ fun scanRoots(roots: List<File?>): List<ModelEntry> =+ roots.filterNotNull().flatMap { scan(it) }+ .distinctBy { it.name }+ .sortedBy { it.name }++ fun scan(root: File): List<ModelEntry> =+ (root.listFiles() ?: emptyArray()).filter {+ it.isFile && it.name.endsWith(".gguf") && !it.name.startsWith("lora_")+ }.map { f ->+ val ok = f.length() > 0+ ModelEntry(f.name.removeSuffix(".gguf"), f, f.length(), f.length(), ok,+ if (ok) null else "empty file")+ }++ /** Free space on the volume backing the primary model root (UI warning gate). */+ fun volumeAvailBytes(root: File?): Long =+ root?.let { runCatching { android.os.StatFs(it.absolutePath).availableBytes }+ .getOrDefault(0L) } ?: 0L++ /** Import instructions shown on the models screen. */+ fun importTemplate(pkg: String): String = listOf(+ "Place model files flat under files/models/ of this app.",+ "Option 1 - in-app: use the picker to copy from device storage.",+ "Option 2 - adb (debug builds):",+ " adb push <file> /data/local/tmp/",+ " adb shell run-as $pkg cp /data/local/tmp/<file> files/models/<file>",+ "Expected names: edge0-8b.gguf (plus lora_edge0_8b-gguf.gguf), edge0-35b.gguf.",+ ).joinToString("\n")+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/Runtime.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/Runtime.ktnew file mode 100644index 0000000..c3c5a05--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/Runtime.kt@@ -0,0 +1,19 @@+// runtime/Runtime.kt - the runtime facade contract consumed by ViewModel/screens.+package dev.edge0.runtime.app.runtime++import dev.edge0.runtime.engine.ChatMessage+import dev.edge0.runtime.engine.GenParams+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow++interface Runtime {+ val state: MutableStateFlow<GenState>+ val lastMetrics: MutableStateFlow<RequestMetrics?>+ val activeModelDir: String?+ suspend fun ensureLoaded(path: String)+ suspend fun unloadActive()+ suspend fun trim(ratio: Float): Boolean+ fun submit(threadId: String, messages: List<ChatMessage>,+ thinkingOn: Boolean, params: GenParams): Flow<GenEvent>+ fun cancelActive()+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/ThermalSource.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/ThermalSource.ktnew file mode 100644index 0000000..c4c4db9--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/ThermalSource.kt@@ -0,0 +1,66 @@+// runtime/ThermalSource.kt - dual-source thermal telemetry:+// PowerManager.currentThermalStatus (API 29+ enum) plus /sys/class/thermal+// nodes (non-root readability verified per node; unreadable ones degrade to N/A).+package dev.edge0.runtime.app.runtime++import android.content.Context+import android.os.Build+import android.os.PowerManager+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOn+import java.io.File++data class ThermalReading(+ val statusLevel: Int?, // PowerManager level (null when unavailable)+ val statusName: String?,+ val topCpuGpuMilli: Int?, // max across compute-thermal zones (cpu/gpuss/ddr/qfprom)+ val tsEpochMs: Long,+)++class ThermalSource(context: Context) {+ private val power = context.getSystemService(PowerManager::class.java)++ fun read(): ThermalReading {+ var lvl: Int? = null+ var name: String? = null+ try {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ lvl = power.currentThermalStatus+ name = when (lvl) {+ PowerManager.THERMAL_STATUS_NONE -> "NONE"+ PowerManager.THERMAL_STATUS_LIGHT -> "LIGHT"+ PowerManager.THERMAL_STATUS_MODERATE -> "MODERATE"+ PowerManager.THERMAL_STATUS_SEVERE -> "SEVERE"+ PowerManager.THERMAL_STATUS_CRITICAL -> "CRITICAL"+ PowerManager.THERMAL_STATUS_EMERGENCY -> "EMERGENCY"+ PowerManager.THERMAL_STATUS_SHUTDOWN -> "SHUTDOWN"+ else -> "S$lvl"+ }+ }+ } catch (_: Exception) { /* degrade to N/A */ }+ var max = -1+ try {+ val zones = File("/sys/class/thermal").listFiles() ?: emptyArray()+ for (z in zones) {+ if (!z.name.startsWith("thermal_zone")) continue+ val type = try { File(z, "type").readText().trim() } catch (_: Exception) { continue }+ if (!(type.contains("cpu", true) || type.contains("gpuss", true) ||+ type.contains("ddr", true) || type.contains("qfprom", true))) continue+ val milli = try { File(z, "temp").readText().trim().toIntOrNull() } catch (_: Exception) { null }+ if (milli != null && milli > max) max = milli+ }+ } catch (_: Exception) { /* unreadable: null */ }+ return ThermalReading(lvl, name, if (max >= 0) max else null, System.currentTimeMillis())+ }++ /** 1 Hz sampling flow (collected only while the overlay is visible; unsubscribes when hidden). */+ fun flow(): Flow<ThermalReading> = flow {+ while (true) {+ emit(read())+ delay(1000)+ }+ }.flowOn(Dispatchers.IO)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/runtime/ThinkSplitter.kt b/android/app/src/main/java/dev/edge0/runtime/app/runtime/ThinkSplitter.ktnew file mode 100644index 0000000..0812705--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/runtime/ThinkSplitter.kt@@ -0,0 +1,86 @@+// runtime/ThinkSplitter.kt - streaming piece splitter that demuxes engine output+// into body/thinking increments. The engine never strips think tags (template purity+// contract), so parsing happens here. Tag literals are assembled in two pieces to+// survive tooling that strips special-token lookalikes; verify bytes on disk after edits.+package dev.edge0.runtime.app.runtime++sealed interface Seg {+ data class Text(val s: String) : Seg+ data class Think(val s: String) : Seg+}++class ThinkSplitter(initialThink: Boolean = false) {+ companion object {+ const val OPEN = "<th" + "ink>"+ const val CLOSE = "</th" + "ink>"+ private const val MIN_OVERLAP_KEEP = 1+ }++ // when thinking_on the opening tag is injected at the prompt tail by the+ // template, so the stream starts inside the thinking region - callers must pass+ // initialThink=thinkingOn or thinking text leaks wholesale into the body.+ private var inThink = initialThink+ private var carry = "" // sole retained state: suffix of the watched tag that is a real prefix of it++ /** Whether we are currently inside a thinking segment (drives the UI timer). */+ val thinkingNow: Boolean get() = inThink++ fun feed(piece: String): List<Seg> {+ if (piece.isEmpty() && carry.isEmpty()) return emptyList()+ val s = carry + piece+ carry = ""+ val out = ArrayList<Seg>(4)+ var i = 0+ while (i < s.length || i == 0) {+ val tag = if (inThink) CLOSE else OPEN+ val idx = s.indexOf(tag, i)+ if (idx >= 0) {+ if (idx > i) emit(out, s.substring(i, idx))+ inThink = !inThink+ i = idx + tag.length+ if (i >= s.length) return out+ } else {+ val keep = overlapSuffixLen(s, tag)+ if (keep > 0 && i <= s.length - keep) {+ if (s.length - i - keep > 0) emit(out, s.substring(i, s.length - keep))+ carry = s.substring(s.length - keep)+ } else if (i < s.length) {+ emit(out, s.substring(i))+ }+ return out+ }+ }+ return out+ }++ /** End of stream: flush the carried prefix per current mode (unclosed thinking is tolerated). */+ fun flush(): List<Seg> {+ if (carry.isEmpty()) return emptyList()+ val out = listOf(segOf(carry))+ carry = ""+ return out+ }++ // maximal overlap of the tail with a real prefix of tag (length <= tag.size-1); cross-chunk tags live only here+ private fun overlapSuffixLen(s: String, tag: String): Int {+ val max = minOf(tag.length - 1, s.length)+ for (k in max downTo MIN_OVERLAP_KEEP) {+ if (s.endsWith(tag.substring(0, k))) return k+ }+ return 0+ }++ private fun emit(out: MutableList<Seg>, text: String) {+ val seg = segOf(text)+ // merge consecutive same-kind segments (keep event count minimal after flips within one feed)+ val last = out.lastOrNull()+ out.add(when {+ last is Seg.Text && seg is Seg.Text -> { out.removeAt(out.size - 1); Seg.Text(last.s + seg.s) }+ last is Seg.Think && seg is Seg.Think -> { out.removeAt(out.size - 1); Seg.Think(last.s + seg.s) }+ else -> seg+ })+ }++ private fun segOf(text: String): Seg =+ if (inThink) Seg.Think(text) else Seg.Text(text)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/AppRoot.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/AppRoot.ktnew file mode 100644index 0000000..2a16ac5--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/AppRoot.kt@@ -0,0 +1,206 @@+// ui/AppRoot.kt - DrawerHost + NavHost wiring.+// Side sheet (288dp): New Chat / thread list (updatedAt desc, busy pulse dot,+// long-press delete menu) / footer with model management and settings.+package dev.edge0.runtime.app.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.outlined.Close+import androidx.compose.ui.draw.clip+import androidx.compose.material.icons.outlined.Settings+import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.material3.DrawerValue+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.ModalDrawerSheet+import androidx.compose.material3.ModalNavigationDrawer+import androidx.compose.material3.NavigationDrawerItem+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.rememberDrawerState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.compose.NavHost+import androidx.navigation.compose.composable+import androidx.navigation.compose.rememberNavController+import dev.edge0.runtime.app.Edge0App+import dev.edge0.runtime.app.data.AppSettings+import dev.edge0.runtime.app.data.ThreadSummary+import dev.edge0.runtime.app.runtime.GenState+import dev.edge0.runtime.app.ui.chat.ChatScreen+import dev.edge0.runtime.app.ui.chat.ChatViewModel+import dev.edge0.runtime.app.ui.models.ModelsScreen+import dev.edge0.runtime.app.ui.settings.SettingsScreen+import kotlinx.coroutines.launch++object Routes {+ const val CHAT = "chat"+ const val MODELS = "models"+ const val SETTINGS = "settings"+}++@Composable+fun AppRoot() {+ val app = LocalContext.current.applicationContext as Edge0App+ val container = app.container+ val factory = remember {+ object : ViewModelProvider.Factory {+ override fun <T : androidx.lifecycle.ViewModel> create(+ modelClass: Class<T>): T =+ ChatViewModel(null, container.repository, container.runtime,+ container.settings) as T+ }+ }+ val vm: ChatViewModel = viewModel(factory = factory)+ val drawerState = rememberDrawerState(DrawerValue.Closed)+ val nav = rememberNavController()+ val scope = rememberCoroutineScope()+ val threads by container.repository.observeThreads()+ .collectAsStateWithLifecycle(initialValue = emptyList())+ val genState by vm.genState.collectAsStateWithLifecycle()+ val settings by container.settings.flow+ .collectAsStateWithLifecycle(initialValue = AppSettings())++ val closeDrawer: () -> Unit = { scope.launch { drawerState.close() } }++ ModalNavigationDrawer(drawerState = drawerState, drawerContent = {+ ModalDrawerSheet(modifier = Modifier.width(288.dp),+ drawerContainerColor = MaterialTheme.colorScheme.background) {+ Column(Modifier.fillMaxSize()) {+ // title row: name left, X closes the drawer (thread/model entries live in the top bar)+ Row(Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp,+ top = 28.dp, bottom = 14.dp),+ verticalAlignment = Alignment.CenterVertically) {+ Text("Edge0 Chat", style = MaterialTheme.typography.titleLarge,+ modifier = Modifier.weight(1f))+ IconButton(onClick = { closeDrawer() }) {+ Icon(Icons.Outlined.Close, "Close drawer",+ tint = MaterialTheme.colorScheme.onSurface)+ }+ }+ Box(Modifier.fillMaxWidth().height(1.dp)+ .background(MaterialTheme.colorScheme.outline))+ Text("History", style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 20.dp, top = 16.dp, bottom = 6.dp))+ LazyColumn(Modifier.weight(1f),+ contentPadding = PaddingValues(horizontal = 10.dp)) {+ items(threads, key = { it.id }) { t ->+ ThreadItem(+ t = t,+ selected = vm.currentThreadId() == t.id,+ busyHere = genState is GenState.Streaming &&+ vm.currentThreadId() == t.id,+ onOpen = { vm.openThread(t.id); nav.navigate(Routes.CHAT)+ closeDrawer() },+ onDelete = { vm.deleteThread(t.id) },+ )+ }+ }+ NavigationDrawerItem(label = { Text("Settings") },+ icon = { Icon(Icons.Outlined.Settings, null) }, selected = false,+ onClick = { nav.navigate(Routes.SETTINGS); closeDrawer() })+ Spacer(Modifier.height(8.dp))+ }+ }+ }) {+ Scaffold { insets ->+ NavHost(navController = nav, startDestination = Routes.CHAT,+ modifier = Modifier.padding(insets)) {+ composable(Routes.CHAT) {+ Box(Modifier.fillMaxSize()) {+ ChatScreen(+ vm = vm,+ modelLabel = settings.activeModelDir.substringAfterLast('/'),+ onOpenDrawer = { scope.launch { drawerState.open() } },+ onOpenModels = { nav.navigate(Routes.MODELS) },+ onNewChat = { vm.newChat(); nav.navigate(Routes.CHAT) },+ )+ }+ }+ composable(Routes.MODELS) {+ ModelsScreen(onBack = { nav.popBackStack(Routes.CHAT, false) })+ }+ composable(Routes.SETTINGS) {+ SettingsScreen(onBack = { nav.popBackStack(Routes.CHAT, false) })+ }+ }+ }+ }+}++@Composable+private fun ThreadItem(t: ThreadSummary, selected: Boolean, busyHere: Boolean,+ onOpen: () -> Unit, onDelete: () -> Unit) {+ // row = rounded card (selected gets surfaceVariant backing); trailing X deletes+ // immediately without confirmation; rename was retired by product decision.+ Row(Modifier.fillMaxWidth().padding(vertical = 2.dp)+ .clip(RoundedCornerShape(12.dp))+ .background(if (selected) MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)+ else androidx.compose.ui.graphics.Color.Transparent)+ .clickable(onClick = onOpen)+ .padding(start = 14.dp, end = 4.dp, top = 13.dp, bottom = 13.dp),+ verticalAlignment = Alignment.CenterVertically) {+ if (busyHere) {+ val tr = rememberInfiniteTransition(label = "pulse")+ val a by tr.animateFloat(0.25f, 1f,+ infiniteRepeatable(tween(700), RepeatMode.Reverse), label = "p")+ Box(Modifier.size(6.dp).background(+ MaterialTheme.colorScheme.primary, CircleShape).alpha(a))+ Spacer(Modifier.width(8.dp))+ }+ Text(t.title ?: "New chat", maxLines = 1, overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.weight(1f))+ IconButton(onClick = onDelete, modifier = Modifier.size(36.dp)) {+ Icon(Icons.Outlined.Close, "Delete chat",+ tint = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.size(17.dp))+ }+ }+}++@Composable+private fun PlaceholderScreen(name: String) {+ Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center) {+ Text(name, style = MaterialTheme.typography.bodyLarge)+ Text("S4-Scaffold-OK", style = MaterialTheme.typography.bodyLarge,+ color = MaterialTheme.colorScheme.error)+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ActionRow.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ActionRow.ktnew file mode 100644index 0000000..8e82166--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ActionRow.kt@@ -0,0 +1,81 @@+// ui/chat/ActionRow.kt - per-message action row: copy / edit / delete+// (+ regenerate on the last assistant turn) and a tok/s badge; hidden while streaming.+package dev.edge0.runtime.app.ui.chat++import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.outlined.ContentCopy+import androidx.compose.material.icons.outlined.Delete+import androidx.compose.material.icons.outlined.Edit+import androidx.compose.material.icons.outlined.Refresh+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalClipboardManager+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import dev.edge0.runtime.app.ui.theme.LocalFontScale++@Composable+fun ActionRow(+ text: String,+ canEdit: Boolean,+ canRegenerate: Boolean,+ onEdit: () -> Unit,+ onDelete: () -> Unit,+ onRegenerate: () -> Unit,+ modifier: Modifier = Modifier,+ endAligned: Boolean = false,+) {+ val clip = LocalClipboardManager.current+ Row(modifier.padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {+ if (endAligned) Spacer(Modifier.weight(1f))+ IconButton(onClick = { clip.setText(AnnotatedString(text)) },+ modifier = Modifier.width(36.dp)) {+ Icon(Icons.Outlined.ContentCopy, "Copy", tint = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.size(16.dp))+ }+ if (canEdit) IconButton(onClick = onEdit, modifier = Modifier.width(36.dp)) {+ Icon(Icons.Outlined.Edit, "Edit", tint = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.size(16.dp))+ }+ IconButton(onClick = onDelete, modifier = Modifier.width(36.dp)) {+ Icon(Icons.Outlined.Delete, "Delete", tint = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.size(16.dp))+ }+ if (canRegenerate) IconButton(onClick = onRegenerate, modifier = Modifier.width(36.dp)) {+ Icon(Icons.Outlined.Refresh, "Regenerate", tint = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.size(16.dp))+ }+ if (!endAligned) Spacer(Modifier.weight(1f))+ }+}++/** Inline stats line under each reply (Atomic style). Memory segment reports+ * resident pool bytes only (cacheable mmap views excluded). Missing fields elide. */+@Composable+fun StatsLine(newTokens: Int?, ttftMs: Long?, prefillTokS: Double?,+ decodeTokS: Double?, memBytes: Long?,+ modifier: Modifier = Modifier) {+ val parts = ArrayList<String>(5)+ if (newTokens != null && newTokens > 0) parts.add("$newTokens tokens")+ if (ttftMs != null && ttftMs > 0) parts.add("TTFT %.1fs".format(ttftMs / 1000.0))+ if (prefillTokS != null && prefillTokS > 0.05) parts.add("prefill %.1f tok/s".format(prefillTokS))+ if (decodeTokS != null && decodeTokS > 0) parts.add("decode %.2f tok/s".format(decodeTokS))+ if (memBytes != null && memBytes > 0) parts.add("pool %.0f MB".format(memBytes / 1048576.0))+ if (parts.isEmpty()) return+ Text(parts.joinToString(" · "),+ style = MaterialTheme.typography.bodySmall.copy(+ fontSize = 11.5.sp * LocalFontScale.current,+ color = MaterialTheme.colorScheme.onSurfaceVariant),+ modifier = modifier.padding(top = 6.dp))+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ChatScreen.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ChatScreen.ktnew file mode 100644index 0000000..5f6e516--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ChatScreen.kt@@ -0,0 +1,367 @@+// ui/chat/ChatScreen.kt - the chat page: top bar (drawer button left, context usage+// right), centered message column (max 768dp) sticking to bottom, user bubbles on the+// right, full-width assistant markdown + reasoning, action row on the last message,+// Working... shimmer, destructive error card, rounded composer card.+package dev.edge0.runtime.app.ui.chat++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.outlined.ArrowDownward+import androidx.compose.material.icons.outlined.Close+import androidx.compose.material.icons.outlined.Edit+import androidx.compose.material.icons.outlined.Menu+import androidx.compose.material.icons.outlined.SwapHoriz+import androidx.compose.foundation.background+import androidx.compose.ui.graphics.Color+import androidx.compose.material.icons.outlined.Warning+import androidx.compose.material3.FloatingActionButton+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import kotlinx.coroutines.launch+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.draw.clip+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import dev.edge0.runtime.app.data.MessageView+import dev.edge0.runtime.app.data.MsgStatus+import dev.edge0.runtime.app.ui.markdown.MarkdownText+import dev.edge0.runtime.app.ui.theme.LocalFontScale++@Composable+fun ChatScreen(+ vm: ChatViewModel,+ modelLabel: String,+ onOpenDrawer: () -> Unit,+ onOpenModels: () -> Unit,+ onNewChat: () -> Unit,+) {+ val draft by vm.draft.collectAsStateWithLifecycle()+ val streaming by vm.streaming.collectAsStateWithLifecycle()+ val genState by vm.genState.collectAsStateWithLifecycle()+ val banner by vm.banner.collectAsStateWithLifecycle()+ val messages by vm.messages.collectAsStateWithLifecycle()++ val busy = genState is dev.edge0.runtime.app.runtime.GenState.Streaming ||+ genState is dev.edge0.runtime.app.runtime.GenState.Cancelling || streaming != null+ val loading = genState is dev.edge0.runtime.app.runtime.GenState.Loading++ val listState = rememberLazyListState()+ val scrollScope = rememberCoroutineScope()+ val atBottom by remember {+ derivedStateOf {+ val info = listState.layoutInfo+ val last = info.visibleItemsInfo.lastOrNull()+ last == null || last.index >= info.totalItemsCount - 1+ }+ }+ // stick to bottom: streaming deltas and new messages follow; a user scroll up detaches without interrupting generation+ LaunchedEffect(messages.size, streaming?.text, streaming?.thinking) {+ if (atBottom) listState.scrollToItem(Int.MAX_VALUE / 2)+ }++ Column(Modifier.fillMaxSize().imePadding()) {+ // -- top bar --+ Row(Modifier.fillMaxWidth().height(52.dp).padding(horizontal = 8.dp),+ verticalAlignment = Alignment.CenterVertically) {+ IconButton(onClick = onOpenDrawer) {+ Icon(Icons.Outlined.Menu, "Chats")+ }+ Spacer(Modifier.weight(1f))+ // centered title: perceived model name + On-device Inference subtitle+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ val short = modelLabel.lowercase()+ val title = when {+ "35b" in short -> "Edge0 35B"+ "8b" in short -> "Edge0 8B"+ else -> "Edge0 Chat"+ }+ Text(title, style = MaterialTheme.typography.titleMedium.copy(+ fontWeight = FontWeight.Bold, fontSize = 16.sp * LocalFontScale.current))+ Text("On-device Inference", style = MaterialTheme.typography.labelSmall.copy(+ fontSize = 11.sp * LocalFontScale.current,+ color = MaterialTheme.colorScheme.onSurfaceVariant))+ }+ Spacer(Modifier.weight(1f))+ // new-thread button (lifted out of the drawer, beside the model switch)+ Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) {+ Surface(shape = CircleShape,+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),+ modifier = Modifier.size(40.dp).clickable(onClick = onNewChat)) {}+ Icon(Icons.Outlined.Edit, "New chat",+ modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onSurface)+ }+ Spacer(Modifier.width(12.dp))+ // top-right model switch (opens the models page)+ Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) {+ Surface(shape = CircleShape,+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),+ modifier = Modifier.size(40.dp).clickable(onClick = onOpenModels)) {}+ Icon(Icons.Outlined.SwapHoriz, "Switch model ($modelLabel)",+ modifier = Modifier.size(20.dp),+ tint = MaterialTheme.colorScheme.onSurface)+ val dot = when {+ loading -> MaterialTheme.colorScheme.tertiary+ busy -> MaterialTheme.colorScheme.primary+ modelLabel.isNotBlank() -> Color(0xFF22C55E)+ else -> MaterialTheme.colorScheme.outline+ }+ Box(Modifier.align(Alignment.TopEnd).padding(3.dp).size(8.dp)+ .background(dot, CircleShape))+ }+ Spacer(Modifier.width(8.dp))+ }++ // -- message column --+ Box(Modifier.weight(1f), contentAlignment = Alignment.TopCenter) {+ LazyColumn(state = listState, modifier = Modifier.fillMaxSize(),+ contentPadding = androidx.compose.foundation.layout.PaddingValues(+ start = 16.dp, end = 16.dp, top = 4.dp, bottom = 8.dp),+ horizontalAlignment = Alignment.CenterHorizontally) {+ if (messages.isEmpty() && streaming == null) {+ item {+ WelcomePage(onPick = { pr -> vm.draft.value = pr; vm.sendMessage() })+ }+ }+ items(messages.size) { i ->+ val m = messages[i]+ MessageRow(+ m = m,+ isLastAssistant = m.role == "assistant" &&+ i == messages.indexOfLast { it.role == "assistant" },+ showActions = !busy && m.status != MsgStatus.STREAMING,+ onEdit = { text -> vm.editUserMessage(m.id, text) },+ onDelete = { vm.deleteMessage(m.id) },+ onRegenerate = { vm.regenerate() },+ )+ }+ streaming?.let { s ->+ item {+ AssistantBody(+ body = s.text, thinking = s.thinking,+ reasoning = ReasoningState(+ active = s.thinkingActive, startedAt = s.thinkStartedMs,+ endedAt = s.thinkEndedMs),+ prefilling = s.prefilling,+ status = null, isStreaming = true,+ )+ }+ }+ item { Spacer(Modifier.height(2.dp)) }+ }+ if (!atBottom) {+ FloatingActionButton(+ onClick = { scrollScope.launch { listState.animateScrollToItem(Int.MAX_VALUE / 2) } },+ modifier = Modifier.align(Alignment.BottomEnd).padding(12.dp)+ .size(36.dp),+ shape = CircleShape, containerColor = MaterialTheme.colorScheme.surfaceVariant,+ ) { Icon(Icons.Outlined.ArrowDownward, "Scroll to bottom",+ modifier = Modifier.size(18.dp)) }+ }+ }++ // -- error / guidance banner --+ banner?.let { msg ->+ Surface(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ shape = RoundedCornerShape(10.dp),+ color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.35f),+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.4f))+ ) {+ Row(Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.Outlined.Warning, null, tint = MaterialTheme.colorScheme.error,+ modifier = Modifier.size(16.dp))+ Spacer(Modifier.width(8.dp))+ Text(msg, modifier = Modifier.weight(1f), maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodySmall)+ IconButton(onClick = { vm.banner.value = null }) {+ Icon(Icons.Outlined.Close, "Dismiss", modifier = Modifier.size(14.dp))+ }+ }+ }+ }++ // -- composer (input card + send button; other controls moved to Settings/top bar) --+ Composer(+ value = draft, onValueChange = { vm.draft.value = it },+ busy = busy,+ enabledSend = draft.isNotBlank() && !loading && modelLabel.isNotBlank(),+ onSend = { vm.sendMessage() }, onStop = { vm.cancel() },+ )+ }+}++@Composable+private fun MessageRow(m: MessageView, isLastAssistant: Boolean, showActions: Boolean,+ onEdit: (String) -> Unit, onDelete: () -> Unit, onRegenerate: () -> Unit) {+ if (m.role == "user") {+ var editing by remember(m.id) { mutableStateOf(false) }+ var buf by remember(m.id) { mutableStateOf(m.content) }+ Column(Modifier.fillMaxWidth().padding(top = 10.dp),+ horizontalAlignment = Alignment.End) {+ if (editing) {+ Surface(Modifier.fillMaxWidth(0.92f), shape = RoundedCornerShape(10.dp),+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline)) {+ Column(Modifier.padding(8.dp)) {+ BasicTextField(value = buf, onValueChange = { buf = it },+ textStyle = MaterialTheme.typography.bodyLarge.copy(+ color = MaterialTheme.colorScheme.onSurface),+ modifier = Modifier.fillMaxWidth().height(88.dp))+ Row(horizontalArrangement = Arrangement.End,+ modifier = Modifier.fillMaxWidth()) {+ Text("Cancel", color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(8.dp)+ .clickableText { editing = false })+ Text("Save", color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.padding(8.dp).clickableText {+ if (buf.isNotBlank()) onEdit(buf.trim())+ editing = false+ })+ }+ }+ }+ } else {+ Surface(shape = RoundedCornerShape(18.dp),+ color = MaterialTheme.colorScheme.secondary,+ modifier = Modifier.widthIn(max = 560.dp)) {+ Text(m.content, Modifier.padding(horizontal = 12.dp, vertical = 8.dp),+ style = MaterialTheme.typography.bodyLarge.copy(+ fontSize = 14.sp * LocalFontScale.current))+ }+ if (showActions) {+ ActionRow(text = m.content, canEdit = true, canRegenerate = false,+ onEdit = { editing = true }, onDelete = onDelete,+ onRegenerate = {}, endAligned = true)+ }+ }+ }+ } else {+ AssistantBody(+ body = m.content, thinking = m.thinking ?: "",+ // persisted row: startedAt at assistant-row creation, endedAt plus thinking duration+ reasoning = ReasoningState(active = false, startedAt = m.createdAt,+ endedAt = m.thinkingMs?.let { m.createdAt + it }),+ prefilling = false,+ status = m.status, isStreaming = false,+ extra = {+ if (showActions) Row {+ Column(Modifier.weight(1f)) {+ StatsLine(newTokens = m.newTokens, ttftMs = m.ttftMs,+ prefillTokS = m.prefillTokS, decodeTokS = m.decodeTokS,+ memBytes = m.memBytes)+ ActionRow(text = m.content, canEdit = false,+ canRegenerate = isLastAssistant,+ onEdit = {}, onDelete = onDelete,+ onRegenerate = onRegenerate)+ }+ }+ },+ )+ }+}++private data class ReasoningState(val active: Boolean, val startedAt: Long?, val endedAt: Long?)++@Composable+private fun AssistantBody(body: String, thinking: String, reasoning: ReasoningState,+ prefilling: Boolean, status: String?, isStreaming: Boolean,+ extra: (@Composable () -> Unit)? = null) {+ Column(Modifier.fillMaxWidth().widthIn(max = 768.dp).padding(top = 10.dp)) {+ if (thinking.isNotEmpty()) {+ ReasoningBlock(thinking = thinking, active = reasoning.active,+ startedAtMs = reasoning.startedAt, endedAtMs = reasoning.endedAt,+ nowMs = System.currentTimeMillis())+ }+ if (prefilling && isStreaming) {+ WorkingShimmer("Working...")+ }+ if (body.isNotEmpty()) {+ MarkdownText(body, Modifier.fillMaxWidth())+ }+ status?.let { st ->+ val chip = when (st) {+ MsgStatus.CANCELLED -> "Cancelled"+ MsgStatus.INTERRUPTED -> "Interrupted"+ MsgStatus.ERROR -> "Error"+ else -> null+ }+ if (chip != null) {+ Text(chip, style = MaterialTheme.typography.labelSmall.copy(+ color = MaterialTheme.colorScheme.error),+ modifier = Modifier.padding(top = 2.dp))+ }+ }+ extra?.invoke()+ }+}++// lightweight text button+private fun Modifier.clickableText(onClick: () -> Unit): Modifier =+ this.clickable(onClick = onClick)++// starter prompts (three fixed questions; display truncates with ellipsis, send uses full text)+private val PRESET_PROMPTS = listOf(+ "Will the water level rise when ice floating in it melts? Explain in two sentences.",+ "Write a sci-fi story with a twist in exactly six words.",+ "Make 24 using 3, 3, 8, and 8 exactly once each, with only basic arithmetic and parentheses.",+)++@Composable+private fun WelcomePage(onPick: (String) -> Unit) {+ Column(Modifier.fillMaxWidth().padding(top = 110.dp),+ horizontalAlignment = Alignment.CenterHorizontally) {+ Text("edge0", style = MaterialTheme.typography.displaySmall.copy(+ fontWeight = FontWeight.Bold, fontSize = 34.sp * LocalFontScale.current))+ Spacer(Modifier.height(10.dp))+ Text("Private AI, running locally on your device",+ style = MaterialTheme.typography.bodyMedium.copy(+ color = MaterialTheme.colorScheme.onSurfaceVariant))+ Spacer(Modifier.height(30.dp))+ PRESET_PROMPTS.forEach { pr ->+ Surface(Modifier.padding(vertical = 5.dp).widthIn(max = 320.dp)+ .clip(RoundedCornerShape(20.dp))+ .clickable { onPick(pr) },+ shape = RoundedCornerShape(20.dp),+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)) {+ Text(pr, Modifier.padding(horizontal = 16.dp, vertical = 10.dp),+ maxLines = 1, overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodyMedium.copy(+ fontSize = 13.5.sp * LocalFontScale.current))+ }+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ChatViewModel.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ChatViewModel.ktnew file mode 100644index 0000000..d8aaea8--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ChatViewModel.kt@@ -0,0 +1,220 @@+// ui/chat/ChatViewModel.kt - chat page orchestration: send -> load -> collect+// generation events -> persist terminal state. Engine cancellation goes exclusively+// through runtime.cancelActive (no fake interruption in the VM). The engine+// overflow diagnostic (INVALID_ARG "prompt tokens=") triggers one retry with a+// tighter budget. Both Done and Cancelled finalize to storage (a cancelled bubble+// keeps its partial content).+package dev.edge0.runtime.app.ui.chat++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import dev.edge0.runtime.app.data.AppSettings+import dev.edge0.runtime.app.data.ChatRepository+import dev.edge0.runtime.app.data.MessageView+import dev.edge0.runtime.app.data.MsgStatus+import dev.edge0.runtime.app.data.SettingsStore+import dev.edge0.runtime.app.runtime.Runtime+import dev.edge0.runtime.app.runtime.GenEvent+import dev.edge0.runtime.app.runtime.GenState+import dev.edge0.runtime.app.runtime.encodeIds+import dev.edge0.runtime.app.runtime.HistoryWindow+import dev.edge0.runtime.app.runtime.RequestMetrics+import dev.edge0.runtime.engine.GenParams+import dev.edge0.runtime.engine.Status+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++data class StreamingDraft(+ val text: String = "",+ val thinking: String = "",+ val prefilling: Boolean = true, // before the first event: show the Working... shimmer+ val thinkingActive: Boolean = false,+ val thinkStartedMs: Long? = null,+ val thinkEndedMs: Long? = null,+)++class ChatViewModel(+ initialThreadId: String?,+ private val repo: ChatRepository,+ private val runtime: Runtime,+ private val settingsStore: SettingsStore,+) : ViewModel() {++ val draft = MutableStateFlow("")+ val streaming = MutableStateFlow<StreamingDraft?>(null)+ val banner = MutableStateFlow<String?>(null)+ val genState: StateFlow<GenState> = runtime.state+ val lastMetrics: StateFlow<RequestMetrics?> = runtime.lastMetrics++ private val activeThreadId = MutableStateFlow(initialThreadId)+ fun currentThreadId(): String? = activeThreadId.value++ /** Message stream of the current thread (re-follows on thread switch). */+ @OptIn(ExperimentalCoroutinesApi::class)+ val messages: StateFlow<List<MessageView>> = activeThreadId+ .flatMapLatest { tid -> if (tid == null) flowOf(emptyList()) else repo.observeMessages(tid) }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ fun newChat() {+ activeThreadId.value = null+ draft.value = ""+ banner.value = null+ }++ fun openThread(id: String) {+ if (runtime.state.value is GenState.Streaming) return // no thread switch mid-generation (single slot)+ activeThreadId.value = id+ banner.value = null+ }++ fun sendMessage() {+ val userText = draft.value.trim()+ if (userText.isEmpty()) return+ val st = runtime.state.value+ if (st is GenState.Streaming || st is GenState.Cancelling || streaming.value != null) return+ draft.value = ""+ viewModelScope.launch {+ val settings = runCatching { settingsStore.flow.first() }.getOrNull() ?: return@launch+ val existing = activeThreadId.value+ val tid = existing ?: repo.startThreadWithUserMessage(+ runtime.activeModelDir ?: settings.activeModelDir, userText).also {+ activeThreadId.value = it+ }+ if (existing != null) repo.addUserMessage(tid, userText)++ if (runtime.activeModelDir == null) {+ if (settings.activeModelDir.isBlank()) {+ banner.value = "No model loaded: import one into the app (adb push) via Models, then load it"+ return@launch+ }+ try {+ runtime.ensureLoaded(settings.activeModelDir)+ } catch (e: Exception) {+ banner.value = "Load failed: ${e.message}"+ return@launch+ }+ }+ runGenerate(tid, settings, budget = HistoryWindow.DEFAULT_BUDGET_CHARS,+ allowRetry = true)+ }+ }++ /** One generation round (with the overflow-trim retry). The last history entry is the new user turn. */+ private suspend fun runGenerate(tid: String, settings: AppSettings,+ budget: Int, allowRetry: Boolean) {+ val history = repo.history(tid)+ val msgs = HistoryWindow.build(+ settings.systemPrompt.takeIf { settings.useSystemPrompt }?.ifBlank { null },+ history, budget)+ val mid = repo.beginAssistant(tid, runtime.activeModelDir ?: "")+ streaming.value = StreamingDraft()+ val text = StringBuilder()+ val think = StringBuilder()+ var thinkStart = 0L+ var thinkMs: Long? = null+ var terminal: GenEvent? = null+ val params = settings.toGenParams()+ runtime.submit(tid, msgs, settings.enableThinking, params).collect { ev ->+ when (ev) {+ is GenEvent.ThinkPiece -> {+ if (think.isEmpty()) thinkStart = System.currentTimeMillis()+ think.append(ev.s)+ streaming.value = (streaming.value ?: StreamingDraft()).copy(+ prefilling = false, thinkingActive = true,+ thinking = think.toString(), thinkStartedMs = thinkStart)+ }+ is GenEvent.TextPiece -> {+ if (streaming.value?.thinkingActive == true && thinkMs == null) {+ thinkMs = System.currentTimeMillis() - thinkStart+ }+ text.append(ev.s)+ streaming.value = (streaming.value ?: StreamingDraft()).copy(+ prefilling = false, thinkingActive = false,+ text = text.toString(), thinking = think.toString(),+ thinkEndedMs = thinkMs)+ }+ else -> terminal = ev+ }+ }+ streaming.value = null+ val metrics = (terminal as? GenEvent.Done)?.metrics+ ?: (terminal as? GenEvent.Cancelled)?.metrics+ // timing fallback: stopped/cancelled turns never flip THINK to TEXT -+ // freeze the clock at the terminal moment. Unclosed thinking is kept whole in+ // the thinking region (same semantics as the upstream split helper).+ var thinkMsFinal = thinkMs+ if (thinkMsFinal == null && think.isNotEmpty() && thinkStart > 0) {+ thinkMsFinal = System.currentTimeMillis() - thinkStart+ }+ val status = when (terminal) {+ is GenEvent.Done -> MsgStatus.OK+ is GenEvent.Cancelled -> MsgStatus.CANCELLED+ else -> MsgStatus.ERROR+ }+ // the sidecar persists only on successful turns (null on cancel/failure)+ repo.finalizeAssistant(mid, text.toString(), think.toString().ifBlank { null },+ thinkMsFinal, status, metrics?.promptTokens, metrics?.newTokens,+ metrics?.decodeTokS,+ (terminal as? GenEvent.Done)?.genIds?.takeIf { it.isNotEmpty() }+ ?.let { encodeIds(it) },+ ttftMs = metrics?.firstTokenMs?.takeIf { it > 0 },+ prefillTokS = metrics?.prefillTokS?.takeIf { it > 0.05 },+ // report resident pool usage only (cacheable mmap views excluded)+ memBytes = metrics?.pool?.resident_bytes?.takeIf { it > 0 })+ val fail = terminal as? GenEvent.Failed+ if (fail != null) {+ if (allowRetry && fail.status == Status.INVALID_ARG &&+ fail.diag.contains("prompt tokens=")) {+ runGenerate(tid, settings,+ HistoryWindow.tighterBudget(budget), allowRetry = false)+ } else {+ banner.value = "Generation failed[${fail.status}]: ${fail.diag}"+ }+ }+ }++ fun cancel() { runtime.cancelActive() }++ fun regenerate() {+ val st = runtime.state.value+ if (st !is GenState.Idle || streaming.value != null) return+ viewModelScope.launch {+ val tid = activeThreadId.value ?: return@launch+ val rows = repo.historyWithIds(tid)+ val lastAssistant = rows.lastOrNull { it.role == "assistant" } ?: return@launch+ repo.deleteFrom(tid, lastAssistant.createdAt)+ val settings = settingsStore.flow.first()+ runGenerate(tid, settings, HistoryWindow.DEFAULT_BUDGET_CHARS, allowRetry = true)+ }+ }++ fun deleteMessage(id: String) = viewModelScope.launch { repo.deleteMessage(id) }++ fun editUserMessage(id: String, newText: String) = viewModelScope.launch {+ repo.editUserMessage(id, newText)+ }++ fun renameThread(id: String, title: String) =+ viewModelScope.launch { repo.renameThread(id, title) }++ fun deleteThread(id: String) = viewModelScope.launch {+ repo.deleteThread(id)+ if (activeThreadId.value == id) newChat()+ }+}++private fun AppSettings.toGenParams() =+ GenParams(temperature = temperature, topK = topK, topP = topP, seed = seed,+ // reasoning models need more than the 256-token engine default (observed truncation on a "hello" turn)+ maxNewTokens = if (maxNewTokens > 0) maxNewTokens else 1024,+ // repetition penalty follows the settings panel; first-token greedy is fixed upstream behavior+ repetitionPenalty = repetitionPenalty,+ firstTokenGreedy = true)diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/Composer.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/Composer.ktnew file mode 100644index 0000000..f6eebc1--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/Composer.kt@@ -0,0 +1,102 @@+// ui/chat/Composer.kt - rounded input card plus send button, nothing else.+// Temperature/thinking live in Settings; model switching in the top bar.+// IME-safe: Enter always inserts a newline; sending is button-only.+package dev.edge0.runtime.app.ui.chat++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.defaultMinSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.ArrowUpward+import androidx.compose.material.icons.filled.Stop+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import dev.edge0.runtime.app.ui.theme.LocalFontScale++@Composable+fun Composer(+ value: String,+ onValueChange: (String) -> Unit,+ busy: Boolean, // streaming/cancelling shows the stop button+ enabledSend: Boolean,+ onSend: () -> Unit,+ onStop: () -> Unit,+ modifier: Modifier = Modifier,+) {+ Row(modifier.fillMaxWidth().imePadding()+ .padding(horizontal = 12.dp, vertical = 8.dp),+ verticalAlignment = Alignment.Bottom,+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ Surface(Modifier.weight(1f),+ shape = RoundedCornerShape(26.dp),+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),+ border = null) {+ BasicTextField(+ value = value, onValueChange = onValueChange,+ textStyle = TextStyle(+ color = MaterialTheme.colorScheme.onSurface,+ fontSize = 15.sp * LocalFontScale.current,+ lineHeight = 21.sp * LocalFontScale.current),+ cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),+ modifier = Modifier.fillMaxWidth()+ .defaultMinSize(minHeight = 26.dp)+ .heightIn(max = 168.dp) // ~8 lines+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 16.dp, vertical = 12.dp),+ decorationBox = { inner ->+ Box(contentAlignment = Alignment.CenterStart) {+ if (value.isEmpty()) {+ Text("Ask anything...",+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ fontSize = 15.sp * LocalFontScale.current)+ }+ inner()+ }+ })+ }+ Spacer(Modifier.width(0.dp))+ val canSend = busy || enabledSend+ val bg = when {+ busy -> MaterialTheme.colorScheme.error+ canSend -> MaterialTheme.colorScheme.primary+ else -> MaterialTheme.colorScheme.surfaceVariant+ }+ val fg = when {+ busy -> Color.White+ canSend -> MaterialTheme.colorScheme.onPrimary+ else -> MaterialTheme.colorScheme.onSurfaceVariant+ }+ Box(Modifier.size(48.dp).background(bg, CircleShape)+ .clickable(enabled = canSend) { if (busy) onStop() else onSend() },+ contentAlignment = Alignment.Center) {+ Icon(if (busy) Icons.Filled.Stop else Icons.Filled.ArrowUpward,+ contentDescription = if (busy) "Stop" else "Send",+ tint = fg, modifier = Modifier.size(22.dp))+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ReasoningBlock.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ReasoningBlock.ktnew file mode 100644index 0000000..ae6b445--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/ReasoningBlock.kt@@ -0,0 +1,67 @@+// ui/chat/ReasoningBlock.kt - collapsible reasoning card: shows+// "Thinking for Ns..." while streaming, "Thought for Ns" when done; collapsed by default.+package dev.edge0.runtime.app.ui.chat++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import dev.edge0.runtime.app.ui.theme.LocalFontScale++@Composable+fun ReasoningBlock(thinking: String, active: Boolean, startedAtMs: Long?, endedAtMs: Long?,+ nowMs: Long, modifier: Modifier = Modifier) {+ if (thinking.isEmpty() && !active) return+ var expanded by remember { mutableStateOf(false) }+ val header = if (active) {+ "Thinking for %.0fs...".format((nowMs - (startedAtMs ?: nowMs)) / 1000.0)+ } else if (startedAtMs == null && endedAtMs == null) {+ "Thought" // legacy rows without a timing basis: qualitative label only+ } else {+ "Thought for %.0fs".format(((endedAtMs ?: nowMs) - (startedAtMs ?: endedAtMs!!)) / 1000.0)+ }+ Surface(+ modifier = modifier.fillMaxWidth().padding(vertical = 4.dp),+ shape = RoundedCornerShape(10.dp),+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),+ ) {+ Column {+ Row(Modifier.fillMaxWidth().clickable { expanded = !expanded }+ .padding(horizontal = 12.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null,+ modifier = Modifier.padding(end = 6.dp),+ tint = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(header, style = MaterialTheme.typography.bodyMedium.copy(+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ fontSize = 13.sp * LocalFontScale.current,+ fontStyle = FontStyle.Italic))+ }+ AnimatedVisibility(visible = expanded) {+ Text(thinking, style = MaterialTheme.typography.bodyMedium.copy(+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ fontSize = 13.sp * LocalFontScale.current),+ modifier = Modifier.padding(start = 30.dp, end = 12.dp, bottom = 10.dp))+ }+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/Shimmer.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/Shimmer.ktnew file mode 100644index 0000000..b14e5fd--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/chat/Shimmer.kt@@ -0,0 +1,36 @@+// ui/chat/Shimmer.kt - the Working... waiting state: gradient sweep text (opacity pulse variant).+package dev.edge0.runtime.app.ui.chat++import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.foundation.text.BasicText+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.unit.sp+import androidx.compose.material3.MaterialTheme+import dev.edge0.runtime.app.ui.theme.LocalFontScale++/** Waiting indicator before the first token (prefilling=true). */+@Composable+fun WorkingShimmer(label: String = "Working...", modifier: Modifier = Modifier) {+ val t = rememberInfiniteTransition(label = "shimmer")+ val a by t.animateFloat(0.35f, 0.9f,+ infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Reverse),+ label = "a")+ BasicText(+ label,+ modifier = modifier.alpha(a),+ style = TextStyle(+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ fontSize = 13.sp * LocalFontScale.current,+ fontStyle = FontStyle.Italic),+ )+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/markdown/MarkdownText.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/markdown/MarkdownText.ktnew file mode 100644index 0000000..a1d0acc--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/markdown/MarkdownText.kt@@ -0,0 +1,48 @@+// ui/markdown/MarkdownText.kt - thin rendering adapter.+// Markdown is rendered by mikepenz multiplatform-markdown-renderer-m3 (tables,+// links, strikethrough included). Pinned to 0.27.0: newer releases require+// compileSdk >= 36 / Kotlin >= 2.1, while this project stays on AGP 8.7.3 (35)+// + Kotlin 2.0.21, so 0.27.0 is the last compatible line. Colors come from+// MaterialTheme, keeping the monochrome palette intact.+//+// LaTeX fallback: the renderer recognizes $$..$$ / $..$ math nodes but ships no+// math renderer, so model math output used to render as blank space. mathFallback+// degrades math to code style before parsing - raw LaTeX stays readable in the+// monochrome theme without pulling a typesetting engine into the app.+package dev.edge0.runtime.app.ui.markdown++import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import com.mikepenz.markdown.m3.Markdown+import com.mikepenz.markdown.m3.markdownColor+import com.mikepenz.markdown.m3.markdownTypography++@Composable+fun MarkdownText(src: String, modifier: Modifier = Modifier) {+ Markdown(mathFallback(src), markdownColor(), markdownTypography(), modifier)+}++/**+ * Math degradation: the renderer recognizes math nodes but has no typesetter.+ * Fenced code blocks break when the math sits inside a list item (the fence+ * gets swallowed by the list paragraph), so every math form becomes inline+ * code with its LaTeX backslashes escaped - readable anywhere in the tree.+ */+internal fun mathFallback(src: String): String {+ if ('$' !in src && "\\(" !in src && "\\[" !in src) return src+ var s = BLOCK_DOLLAR.replace(src) { inlineMath(it.groupValues[1]) }+ s = BLOCK_BRACKET.replace(s) { inlineMath(it.groupValues[1]) }+ s = INLINE_DOLLAR.replace(s) { inlineMath(it.groupValues[1]) }+ s = INLINE_PAREN.replace(s) { inlineMath(it.groupValues[1]) }+ return s+}++private fun inlineMath(body: String): String {+ val oneLine = body.trim().replace(Regex("\\s+"), " ").replace("\\", "\\\\")+ return if (oneLine.length > 160) oneLine.take(160) else "`$oneLine`"+}++private val BLOCK_DOLLAR = Regex("""\$\$\s*([\s\S]+?)\s*\$\$""")+private val BLOCK_BRACKET = Regex("""\\\[\s*([\s\S]+?)\s*\\\]""")+private val INLINE_DOLLAR = Regex("""\$([^\s$](?:[^$\n]{0,88}[^\s$])?)\$""")+private val INLINE_PAREN = Regex("""\\\(([^$\n]{1,90}?)\\\)""")diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/models/ModelsScreen.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/models/ModelsScreen.ktnew file mode 100644index 0000000..e27f658--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/models/ModelsScreen.kt@@ -0,0 +1,200 @@+// ui/models/ModelsScreen.kt - model management: scans files/models, shows+// size/integrity/load state, load|unload buttons (disabled while generating), a disk+// headroom bar (warn under 1.2x requirement) and an import-instructions card.+package dev.edge0.runtime.app.ui.models++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.outlined.ArrowBack+import androidx.compose.material.icons.outlined.Warning+import androidx.compose.material3.Button+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import dev.edge0.runtime.app.Edge0App+import dev.edge0.runtime.app.runtime.GenState+import dev.edge0.runtime.app.runtime.ModelEntry+import dev.edge0.runtime.app.runtime.ModelInventory+import dev.edge0.runtime.app.ui.theme.LocalFontScale+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++private fun fmtGiB(b: Long): String = "%.2f GiB".format(b / 1073741824.0)++@Composable+fun ModelsScreen(onBack: () -> Unit) {+ val app = LocalContext.current.applicationContext as Edge0App+ val container = app.container+ val scope = rememberCoroutineScope()+ var entries by remember { mutableStateOf<List<ModelEntry>>(emptyList()) }+ var avail by remember { mutableStateOf(-1L) }+ var note by remember { mutableStateOf<String?>(null) }+ val genState by container.runtime.state.collectAsStateWithLifecycle()+ var refreshTick by remember { mutableStateOf(0) }++ LaunchedEffect(refreshTick) {+ withContext(Dispatchers.IO) {+ entries = ModelInventory.scanRoots(container.modelRoots)+ avail = ModelInventory.volumeAvailBytes(app.filesDir)+ }+ }++ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {+ Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically) {+ IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Back") }+ Text("Models", style = MaterialTheme.typography.titleMedium)+ Spacer(Modifier.weight(1f))+ OutlinedButton(onClick = { refreshTick++ }, modifier = Modifier.padding(end = 12.dp)) {+ Text("Refresh")+ }+ }+ // disk headroom bar (available vs required x 1.2)+ if (avail >= 0) {+ val maxReq = entries.filter { it.valid }.maxOfOrNull { it.totalBytes } ?: 0L+ val warn = maxReq > 0 && avail < maxReq * 1.2+ Surface(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ shape = RoundedCornerShape(10.dp),+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f)) {+ Column(Modifier.padding(12.dp)) {+ Text("Storage: ${if (avail > 0) fmtGiB(avail) else "N/A"} free" ++ if (maxReq > 0) " / largest model ${fmtGiB(maxReq)}, ${fmtGiB((maxReq * 1.2).toLong())} recommended" else "",+ style = MaterialTheme.typography.bodySmall)+ if (warn) {+ Text("Free space below 1.2x requirement: loading may fail midway (engine reports out-of-storage)",+ color = MaterialTheme.colorScheme.error,+ style = MaterialTheme.typography.bodySmall)+ }+ }+ }+ }+ note?.let {+ Text(it, color = MaterialTheme.colorScheme.error,+ style = MaterialTheme.typography.bodySmall,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp))+ }+ if (entries.isEmpty()) {+ Text("No models found. Import via adb to:",+ modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.bodyMedium)+ Surface(Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ shape = RoundedCornerShape(10.dp),+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)) {+ Text(ModelInventory.importTemplate(app.packageName),+ fontFamily = FontFamily.Monospace,+ style = MaterialTheme.typography.bodySmall.copy(+ fontSize = 11.sp * LocalFontScale.current),+ modifier = Modifier.padding(12.dp))+ }+ Text("Tap Refresh (top right) after importing. Note: uninstalling the app wipes its data " ++ "(Android policy); re-import assets with the command above if they disappear.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(16.dp))+ }+ for (e in entries) {+ ModelRow(e,+ active = container.runtime.activeModelDir == e.dir.absolutePath,+ busy = genState is GenState.Streaming || genState is GenState.Cancelling,+ loading = genState is GenState.Loading,+ onLoad = {+ scope.launch {+ note = null+ try {+ container.runtime.ensureLoaded(e.dir.absolutePath)+ container.settings.update { s -> s.copy(activeModelDir = e.dir.absolutePath) }+ } catch (ex: Exception) {+ android.util.Log.e("Edge0Load", "ensureLoaded failed", ex)+ note = "Load failed: ${ex.message} (if the app was just updated, re-push assets to the import path)"+ }+ }+ },+ onUnload = {+ scope.launch {+ note = null+ try { container.runtime.unloadActive() } catch (ex: Exception) {+ note = "Unload failed: ${ex.message}"+ }+ }+ })+ Spacer(Modifier.height(8.dp))+ }+ }+}++@Composable+private fun ModelRow(e: ModelEntry, active: Boolean, busy: Boolean, loading: Boolean,+ onLoad: () -> Unit, onUnload: () -> Unit) {+ Surface(Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ shape = RoundedCornerShape(10.dp),+ color = MaterialTheme.colorScheme.surface,+ border = androidx.compose.foundation.BorderStroke(+ 1.dp, if (active) MaterialTheme.colorScheme.primary+ else MaterialTheme.colorScheme.outline)) {+ Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(e.name, maxLines = 1, overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.titleSmall)+ Spacer(Modifier.size(6.dp))+ Text("e0b", style = MaterialTheme.typography.labelSmall,+ modifier = Modifier.padding(horizontal = 4.dp))+ }+ Text("${fmtGiB(if (e.dirBytes > 0) e.dirBytes else e.totalBytes)}" ++ if (!e.valid) " · incomplete (${e.hint})" else "",+ style = MaterialTheme.typography.bodySmall,+ color = if (e.valid) MaterialTheme.colorScheme.onSurfaceVariant+ else MaterialTheme.colorScheme.error)+ Text(if (active) "● Loaded" else if (loading) "◌ Loading..." else "○ Not loaded",+ style = MaterialTheme.typography.bodySmall.copy(+ fontSize = 11.sp * LocalFontScale.current),+ color = if (active) MaterialTheme.colorScheme.primary+ else MaterialTheme.colorScheme.onSurfaceVariant)+ }+ if (!e.valid) {+ Icon(Icons.Outlined.Warning, "Broken assets", tint = MaterialTheme.colorScheme.error)+ return@Row+ }+ if (active) {+ OutlinedButton(onClick = onUnload, enabled = !busy && !loading) { Text("Unload") }+ } else {+ Button(onClick = onLoad, enabled = !busy && !loading) {+ if (loading) CircularProgressIndicator(Modifier.size(14.dp))+ else Text("Load")+ }+ }+ }+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/settings/SettingsScreen.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/settings/SettingsScreen.ktnew file mode 100644index 0000000..490b513--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/settings/SettingsScreen.kt@@ -0,0 +1,167 @@+// ui/settings/SettingsScreen.kt - settings in a single-column card layout:+// appearance (theme / font scale), assistant (system prompt + thinking), sampling+// parameters, about. Writes go through SettingsStore.update.+package dev.edge0.runtime.app.ui.settings++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.outlined.ArrowBack+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Slider+import androidx.compose.material3.Surface+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import dev.edge0.runtime.app.Edge0App+import dev.edge0.runtime.app.data.AppSettings+import dev.edge0.runtime.app.ui.theme.LocalFontScale+import dev.edge0.runtime.app.ui.theme.ThemeMode+import kotlinx.coroutines.launch++@Composable+fun SettingsScreen(onBack: () -> Unit) {+ val app = LocalContext.current.applicationContext as Edge0App+ val store = app.container.settings+ val s by store.flow.collectAsStateWithLifecycle(initialValue = AppSettings())+ val scope = rememberCoroutineScope()+ fun patch(f: (AppSettings) -> AppSettings) = scope.launch { store.update(f) }++ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {+ Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically) {+ IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Back") }+ Text("Settings", style = MaterialTheme.typography.titleMedium)+ }++ Group("Appearance") {+ Row(Modifier.fillMaxWidth().padding(vertical = 6.dp),+ verticalAlignment = Alignment.CenterVertically) {+ Text("Theme", modifier = Modifier.weight(1f))+ SingleChoiceSegmentedButtonRow {+ val opts = listOf(ThemeMode.SYSTEM to "System", ThemeMode.LIGHT to "Light",+ ThemeMode.DARK to "Dark")+ opts.forEachIndexed { i, (mode, label) ->+ SegmentedButton(+ selected = s.themeMode == mode,+ shape = SegmentedButtonDefaults.itemShape(i, opts.size),+ onClick = { patch { cur -> cur.copy(themeMode = mode) } },+ ) { Text(label, fontSize = 12.sp) }+ }+ }+ }+ Text("Font size ${"%.2f".format(s.fontScale)}", style = MaterialTheme.typography.bodySmall)+ Slider(value = s.fontScale, onValueChange = { v ->+ scope.launch { store.update { cur -> cur.copy(fontScale = v) } } },+ valueRange = 0.85f..1.3f)+ }++ Group("Assistant") {+ Row(Modifier.fillMaxWidth().padding(vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically) {+ Text("Use system prompt", modifier = Modifier.weight(1f))+ Switch(checked = s.useSystemPrompt,+ onCheckedChange = { c -> patch { cur -> cur.copy(useSystemPrompt = c) } })+ }+ if (s.useSystemPrompt) {+ OutlinedTextField(value = s.systemPrompt,+ onValueChange = { v -> patch { cur -> cur.copy(systemPrompt = v) } },+ label = { Text("System prompt") },+ minLines = 3, maxLines = 6, modifier = Modifier.fillMaxWidth())+ }+ Row(Modifier.fillMaxWidth().padding(vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically) {+ Text("Enable thinking", modifier = Modifier.weight(1f))+ Switch(checked = s.enableThinking,+ onCheckedChange = { c -> patch { cur -> cur.copy(enableThinking = c) } })+ }+ }++ Group("Sampling") {+ // defaults mirror the upstream sampling quartet+ ParamSlider("repetition penalty (1.0=off)", s.repetitionPenalty, 1f, 1.5f) { v ->+ patch { cur -> cur.copy(repetitionPenalty = v) } }+ ParamSlider("temperature (0=greedy)", s.temperature, 0f, 2f) { v ->+ patch { cur -> cur.copy(temperature = v) } }+ ParamSliderInt("top-k (0=off)", s.topK, 0, 100) { v ->+ patch { cur -> cur.copy(topK = v) } }+ ParamSlider("top-p (>=1=off)", s.topP, 0.1f, 1f) { v ->+ patch { cur -> cur.copy(topP = v) } }+ ParamSliderInt("max new tokens (0=default 1024)", s.maxNewTokens, 0, 2048) { v ->+ patch { cur -> cur.copy(maxNewTokens = v) } }+ OutlinedTextField(value = s.seed.toString(),+ onValueChange = { v -> v.toLongOrNull()?.let { seed ->+ patch { cur -> cur.copy(seed = seed) } } },+ label = { Text("seed") }, singleLine = true,+ modifier = Modifier.fillMaxWidth().padding(top = 6.dp))+ }++ Group("About") {+ Text("llama.cpp (pinned build) · " ++ "app ${dev.edge0.runtime.app.BuildConfig.VERSION_NAME}" ++ "+${dev.edge0.runtime.app.BuildConfig.GIT_SHA}",+ style = MaterialTheme.typography.bodySmall)+ Text("Runtime and UI ship in a single APK",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ Spacer(Modifier.height(24.dp))+ }+}++@Composable+private fun Group(title: String, content: @Composable ColumnScope.() -> Unit) {+ Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {+ Text(title.uppercase(), style = MaterialTheme.typography.labelMedium.copy(+ fontWeight = FontWeight.SemiBold, fontSize = 11.sp * LocalFontScale.current,+ color = MaterialTheme.colorScheme.onSurfaceVariant),+ modifier = Modifier.padding(start = 4.dp, bottom = 4.dp))+ Surface(shape = RoundedCornerShape(10.dp),+ color = MaterialTheme.colorScheme.surface,+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline)) {+ Column(Modifier.padding(12.dp), content = content)+ }+ }+}++@Composable+private fun ParamSlider(label: String, value: Float, min: Float, max: Float,+ onValue: (Float) -> Unit) {+ Text("$label = ${"%.2f".format(value)}", style = MaterialTheme.typography.bodySmall)+ Slider(value = value.coerceIn(min, max), onValueChange = onValue, valueRange = min..max,+ modifier = Modifier.fillMaxWidth())+}++@Composable+private fun ParamSliderInt(label: String, value: Int, min: Int, max: Int,+ onValue: (Int) -> Unit) {+ Text("$label = $value", style = MaterialTheme.typography.bodySmall)+ Slider(value = value.toFloat().coerceIn(min.toFloat(), max.toFloat()),+ onValueChange = { onValue(it.toInt()) }, valueRange = min.toFloat()..max.toFloat(),+ modifier = Modifier.fillMaxWidth())+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/theme/Color.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/theme/Color.ktnew file mode 100644index 0000000..db7e6d3--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/theme/Color.kt@@ -0,0 +1,41 @@+// ui/theme/Color.kt - palette converted from the OKLCH design values to sRGB+// (OKLab -> linear sRGB -> gamma, per Björn Ottosson's transform). The original+// oklch() values are kept in paired comments for traceability. The palette is+// grayscale; blue appears only in active states such as download progress.+package dev.edge0.runtime.app.ui.theme++import androidx.compose.ui.graphics.Color++// ---- Light (index.css :root)----+val LightBackground = Color(0xFFFFFFFF) // oklch(1 0 0)+val LightForeground = Color(0xFF0A0A0A) // oklch(0.145 0 0)+val LightPrimary = Color(0xFF171717) // oklch(0.205 0 0) send-button background+val LightOnPrimary = Color(0xFFFAFAFA) // primary foreground, shadcn default white+val LightSecondary = Color(0xFFF5F5F5) // oklch(0.97 0 0) user bubble background+val LightOnSecondary = Color(0xFF0A0A0A) // secondary-foreground+val LightMutedForeground = Color(0xFF737373) // oklch(0.556 0 0) secondary text / action row+val LightBorder = Color(0xFFE5E5E5) // oklch(0.922 0 0)+val LightSidebar = Color(0xFFF2F2F2) // oklch(0.96 0 0)+val LightDestructive = Color(0xFFE7000B) // oklch(0.577 0.245 27.325)++// ---- Dark (index.css .dark)----+val DarkBackground = Color(0xFF121212) // oklch(0.18 0 0)+val DarkForeground = Color(0xFFFAFAFA) // oklch(0.985 0 0)+val DarkPrimary = Color(0xFFE5E5E5) // oklch(0.922 0 0) dark primary = light gray, dark glyph on it+val DarkOnPrimary = Color(0xFF171717)+val DarkSecondary = Color(0xFF383838) // oklch(0.34 0 0)+val DarkOnSecondary = Color(0xFFFAFAFA)+val DarkMutedForeground = Color(0xFFB7B7B7) // oklch(0.78 0 0)+val DarkBorder = Color(0x24FFFFFF) // oklch(1 0 0 / 14%)+val DarkSidebar = Color(0xFF1B1B1B) // oklch(0.22 0 0)+val DarkDestructive = Color(0xFFFF6467) // oklch(0.704 0.191 22.216)+val DarkRing = Color(0xFFA4A4A4) // oklch(0.72 0 0)++// layout constants (design spec to dp)+object Dimens {+ const val RadiusCard = 10f // --radius: 0.625rem ≈ 10dp+ const val RadiusComposer = 24f // rounded-3xl (composer card)+ const val RadiusBubble = 6f // rounded-md (bubble)+ const val DrawerWidth = 288f // Sheet 18rem (sidebar.tsx SIDEBAR_WIDTH_MOBILE)+ const val ContentMaxWidth = 768f // max-w-3xl message column (auto-centers on tablets)+}diff --git a/android/app/src/main/java/dev/edge0/runtime/app/ui/theme/Theme.kt b/android/app/src/main/java/dev/edge0/runtime/app/ui/theme/Theme.ktnew file mode 100644index 0000000..d8b2b6b--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/app/ui/theme/Theme.kt@@ -0,0 +1,91 @@+// ui/theme/Theme.kt - three theme modes (light/dark/system) plus a global font scale.+// LocalFontScale is the Compose equivalent of the design system's font-size-base+// multiplier; screens apply it explicitly (Material3 typography baseline is 14sp).+package dev.edge0.runtime.app.ui.theme++import androidx.compose.foundation.isSystemInDarkTheme+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Shapes+import androidx.compose.material3.Typography+import androidx.compose.material3.darkColorScheme+import androidx.compose.material3.lightColorScheme+import androidx.compose.runtime.Composable+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp++// whole-app text-sm baseline (system sans fallback; custom font files out of scope for v1)+private val Edge0Typography = Typography(+ bodyLarge = TextStyle(fontFamily = FontFamily.Default, fontSize = 14.sp, lineHeight = 20.sp),+ bodyMedium = TextStyle(fontFamily = FontFamily.Default, fontSize = 14.sp, lineHeight = 20.sp),+ titleLarge = TextStyle(fontFamily = FontFamily.Default, fontSize = 18.sp,+ fontWeight = FontWeight.Medium),+)++private val LightScheme = lightColorScheme(+ primary = LightPrimary,+ onPrimary = LightOnPrimary,+ secondary = LightSecondary,+ onSecondary = LightOnSecondary,+ background = LightBackground,+ onBackground = LightForeground,+ surface = LightBackground,+ onSurface = LightForeground,+ surfaceVariant = LightSecondary,+ outline = LightBorder,+ error = LightDestructive,+)++private val DarkScheme = darkColorScheme(+ primary = DarkPrimary,+ onPrimary = DarkOnPrimary,+ secondary = DarkSecondary,+ onSecondary = DarkOnSecondary,+ background = DarkBackground,+ onBackground = DarkForeground,+ surface = DarkBackground,+ onSurface = DarkForeground,+ surfaceVariant = DarkSecondary,+ outline = DarkBorder,+ error = DarkDestructive,+)++/** Radius ladder: md = bubble / lg = card (10dp) / 2xl = composer (24dp). */+private val Edge0Shapes = Shapes(+ extraSmall = RoundedCornerShape(4.dp),+ small = RoundedCornerShape(6.dp), // user bubble+ medium = RoundedCornerShape(10.dp), // cards+ large = RoundedCornerShape(16.dp),+ extraLarge = RoundedCornerShape(24.dp), // composer+)++/** Font scale (0.85..1.3, driven by the settings slider, persisted in DataStore). */+val LocalFontScale = compositionLocalOf { 1.0f }++/** Theme mode: SYSTEM follows the platform setting. */+enum class ThemeMode { SYSTEM, LIGHT, DARK }++@Composable+fun Edge0Theme(+ mode: ThemeMode = ThemeMode.SYSTEM,+ fontScale: Float = 1.0f,+ content: @Composable () -> Unit,+) {+ val dark = when (mode) {+ ThemeMode.SYSTEM -> isSystemInDarkTheme()+ ThemeMode.LIGHT -> false+ ThemeMode.DARK -> true+ }+ androidx.compose.runtime.CompositionLocalProvider(LocalFontScale provides fontScale) {+ MaterialTheme(+ colorScheme = if (dark) DarkScheme else LightScheme,+ typography = Edge0Typography,+ shapes = Edge0Shapes,+ content = content,+ )+ }+}diff --git a/android/app/src/main/java/dev/edge0/runtime/engine/Types.kt b/android/app/src/main/java/dev/edge0/runtime/engine/Types.ktnew file mode 100644index 0000000..9c55074--- /dev/null+++ b/android/app/src/main/java/dev/edge0/runtime/engine/Types.kt@@ -0,0 +1,36 @@+// Shared data types of the runtime layer.+package dev.edge0.runtime.engine++enum class Status(val code: Int) {+ OK(0),+ INSUFFICIENT_STORAGE(1),+ FORMAT_VERSION(2),+ ASSET_CORRUPT(3),+ MEM_BUDGET(4),+ IO(5),+ CANCELLED(6),+ SESSION_EXISTS(7),+ INVALID_ARG(8),+ NOT_IMPLEMENTED(9),+ INTERNAL(100),+ ;+ companion object { fun of(v: Int): Status = entries.firstOrNull { it.code == v } ?: INTERNAL }+}++class EngineException(val status: Status, message: String) : Exception("[$status] $message")++data class GenParams(+ val temperature: Float = 0f, // <= 0 selects greedy decoding (deterministic)+ val topK: Int = 0,+ val topP: Float = 1f,+ val seed: Long = 0x20260915L,+ val maxNewTokens: Int = 0,+ val repetitionPenalty: Float = 0f, // 0 or 1.0 = off; > 0 and != 1 applies penalty+ val firstTokenGreedy: Boolean = false, // true = argmax for the first token+)++/** A chat turn. role is one of system/user/assistant; at most one system turn, first.+ * genIds = assistant token-id sidecar: the exact token ids this assistant turn+ * stepped through. When present the engine replays the turn from ids (the text+ * is for the UI only), keeping the prompt byte-identical across turns. */+data class ChatMessage(val role: String, val content: String, val genIds: IntArray? = null)diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000..56cb79d--- /dev/null+++ b/android/app/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Edge0 Chat</string>+</resources>diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xmlnew file mode 100644index 0000000..461b543--- /dev/null+++ b/android/app/src/main/res/values/themes.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- Compose draws the full UI; this theme only sets the window background+ (edge-to-edge is enabled in the Activity). -->+ <style name="Theme.Edge0" parent="android:Theme.DeviceDefault.NoActionBar">+ <item name="android:windowBackground">@android:color/transparent</item>+ </style>+</resources>diff --git a/android/app/src/test/java/dev/edge0/runtime/app/runtime/HistoryWindowTest.kt b/android/app/src/test/java/dev/edge0/runtime/app/runtime/HistoryWindowTest.ktnew file mode 100644index 0000000..d739be8--- /dev/null+++ b/android/app/src/test/java/dev/edge0/runtime/app/runtime/HistoryWindowTest.kt@@ -0,0 +1,74 @@+// HistoryWindowTest - budget trimming, ordering, assistant replay shape.+package dev.edge0.runtime.app.runtime++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class HistoryWindowTest {+ private val O = ThinkSplitter.OPEN+ private val C = ThinkSplitter.CLOSE++ @Test fun tailWithinBudgetKeptInOrder() {+ val turns = listOf(+ StoredMessage("user", "q1"), StoredMessage("assistant", "a1"),+ StoredMessage("user", "q2"), StoredMessage("assistant", "a2"),+ StoredMessage("user", "q3"),+ )+ val msgs = HistoryWindow.build("sys", turns, budgetChars = 10000)+ assertEquals(listOf("system", "user", "assistant", "user", "assistant", "user"),+ msgs.map { it.role })+ assertEquals("sys", msgs[0].content)+ assertEquals("q3", msgs.last().content)+ }++ @Test fun budgetTrimsOldestNotLast() {+ val big = "W".repeat(100)+ val turns = listOf(+ StoredMessage("user", big), StoredMessage("assistant", big),+ StoredMessage("user", "lastQ"),+ )+ val msgs = HistoryWindow.build(null, turns, budgetChars = 60)+ // the last turn always survives; older turns beyond budget are trimmed+ assertEquals(1, msgs.size)+ assertEquals("lastQ", msgs[0].content)+ }++ @Test fun assistantThinkingReplayedIntoEngineTranscript() {+ // Revisited under the sidecar regime: thinking MUST enter the context -+ // KV prefix reuse requires bit-identical replay of the live tokens.+ val turns = listOf(+ StoredMessage("user", "q1"),+ StoredMessage("assistant", "body", thinking = "reason"),+ StoredMessage("user", "q2"),+ )+ val msgs = HistoryWindow.build(null, turns)+ assertEquals(O + "reason" + C + "body", msgs[1].content)+ }++ @Test fun sidecarIdsRideAlongReplay() {+ val ids = intArrayOf(5, 42, 17)+ val turns = listOf(+ StoredMessage("user", "q"),+ StoredMessage("assistant", "body", genIds = ids),+ StoredMessage("user", "q2"),+ )+ val msgs = HistoryWindow.build(null, turns)+ assertTrue(msgs[1].genIds!!.contentEquals(ids))+ assertEquals("body", msgs[1].content) // no thinking column -> no tags (ids are authoritative)+ }++ @Test fun assistantWithoutThinkingPlainBody() {+ val turns = listOf(+ StoredMessage("user", "q1"),+ StoredMessage("assistant", "plainbody"),+ )+ val msgs = HistoryWindow.build(null, turns)+ assertEquals("plainbody", msgs[1].content)+ }++ @Test fun tighterBudgetFloor() {+ assertEquals(400, HistoryWindow.tighterBudget(700))+ assertTrue(HistoryWindow.tighterBudget(300) >= 400)+ }+}diff --git a/android/app/src/test/java/dev/edge0/runtime/app/runtime/LlamaRuntimeLogicTest.kt b/android/app/src/test/java/dev/edge0/runtime/app/runtime/LlamaRuntimeLogicTest.ktnew file mode 100644index 0000000..2233415--- /dev/null+++ b/android/app/src/test/java/dev/edge0/runtime/app/runtime/LlamaRuntimeLogicTest.kt@@ -0,0 +1,58 @@+// LlamaRuntimeLogicTest - pure-logic unit tests (host JVM, no device).+// Device-facing behavior is covered by the instrumented LlamaRuntimeTest suite.+package dev.edge0.runtime.app.runtime++import dev.edge0.runtime.engine.ChatMessage+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class LlamaRuntimeLogicTest {++ @Test fun metricsParseRoundTrip() {+ val rt = LlamaRuntime()+ val m = rt.parseMetrics(+ "OK gen=64 tps=18.19 prefill_ms=3087 first_ms=182 prompt=17 reused=12")+ checkNotNull(m)+ assertEquals(64, m.newTokens)+ assertEquals(18.19, m.decodeTokS, 1e-6)+ assertEquals(3087, m.prefillMs)+ assertEquals(17, m.promptTokens)+ assertEquals(12, m.prefix_reused_tokens)+ assertTrue(m.prefix_reused)+ // effective prefill rate = new input tokens (17-12=5) over prefill time+ assertEquals(5 * 1000.0 / 3087, m.prefillTokS, 1e-6)+ }++ @Test fun metricsParseCancelledAndGarbage() {+ val rt = LlamaRuntime()+ checkNotNull(rt.parseMetrics("CANCELLED gen=8 tps=2.00 prefill_ms=100 first_ms=10 prompt=5 reused=0"))+ assertNull(rt.parseMetrics("ERR template need=-1"))+ }++ @Test fun historyWindowSystemFirstAndLastTurnKept() {+ val long = "x".repeat(400)+ val turns = (1..30).map { i ->+ if (i % 2 == 1) StoredMessage("user", "q$i $long")+ else StoredMessage("assistant", "a$i $long")+ } + StoredMessage("user", "final question " + long)+ val out = HistoryWindow.build("You are Edge0.", turns, budgetChars = 1000)+ assertEquals("system", out.first().role) // system always prepended+ assertEquals("user", out.last().role) // current question survives+ assertTrue(out.size < turns.size + 1) // budget clipped history+ }++ @Test fun historyWindowDropsBlankAssistantPoisonTurns() {+ // regression sentinel (empty-answer incident): blank assistant turns without+ // genIds must never reach the model - the model would "see itself" answering empty+ val turns = listOf(+ StoredMessage("user", "hi"),+ StoredMessage("assistant", ""),+ StoredMessage("user", "who are you"),+ )+ val out = HistoryWindow.build(null, turns)+ assertTrue(out.none { it.role == "assistant" && it.content.isBlank() })+ assertEquals(2, out.size)+ }+}diff --git a/android/app/src/test/java/dev/edge0/runtime/app/runtime/MetricsMapperTest.kt b/android/app/src/test/java/dev/edge0/runtime/app/runtime/MetricsMapperTest.ktnew file mode 100644index 0000000..1af086d--- /dev/null+++ b/android/app/src/test/java/dev/edge0/runtime/app/runtime/MetricsMapperTest.kt@@ -0,0 +1,63 @@+// MetricsMapperTest - real-device schema1 sample capture plus tolerance checks.+package dev.edge0.runtime.app.runtime++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class MetricsMapperTest {++ private fun resource(): String =+ javaClass.classLoader!!.getResourceAsStream("metrics_real.json")!!+ .readBytes().toString(Charsets.UTF_8)++ @Test fun realDeviceSampleMaps() {+ val m = MetricsMapper.parse(resource())+ assertNotNull(m)+ m!!+ assertEquals(1, m.schema)+ assertEquals(23, m.promptTokens)+ assertEquals(false, m.prefix_reused)+ assertEquals(0, m.prefix_reused_tokens)+ assertEquals(8, m.newTokens)+ assertEquals(1, m.chatTurns)+ assertTrue(m.thinkingOn)+ assertEquals(1_366_167_552L, m.peakRssBytes)+ assertTrue(m.decodeTokS > 4.0 && m.decodeTokS < 4.4)+ assertEquals("predicted", m.route?.mode)+ assertEquals("executed", m.route?.feature)+ assertNull(m.route?.agree) // JSON null → Kotlin null+ assertEquals(635L, m.pool?.hits)+ assertEquals(2095L, m.pool?.misses)+ assertTrue(m.gpu?.active == true)+ assertTrue(m.gpu?.device?.contains("Adreno") == true)+ assertEquals("ok", m.gpu?.why) // backend-audit row data source+ assertTrue(m.gpu?.cacheHit == true) // kernel cache hit (CLI-domain precedent)+ val hr = m.hitRate!!+ assertTrue(hr > 0.22 && hr < 0.24) // 635/2730+ }++ @Test fun missingFieldsDefaultNotThrow() {+ val m = MetricsMapper.parse("""{"schema": 1}""")+ assertNotNull(m)+ assertEquals(0, m!!.newTokens)+ assertEquals(false, m.prefix_reused)+ assertEquals(0, m.prefix_reused_tokens)+ assertNull(m.route)+ assertNull(m.hitRate)+ }++ @Test fun unknownFieldsIgnored() {+ val m = MetricsMapper.parse("""{"schema":1,"brand_new_field":{"a":[1,2]},"decode_tok_s":3.0}""")+ assertNotNull(m)+ assertEquals(3.0, m!!.decodeTokS, 1e-9)+ }++ @Test fun corruptInputReturnsNull() {+ assertNull(MetricsMapper.parse("not json at all"))+ assertNull(MetricsMapper.parse(""))+ assertNull(MetricsMapper.parse(null))+ }+}diff --git a/android/app/src/test/java/dev/edge0/runtime/app/runtime/ThinkSplitterTest.kt b/android/app/src/test/java/dev/edge0/runtime/app/runtime/ThinkSplitterTest.ktnew file mode 100644index 0000000..e62b77e--- /dev/null+++ b/android/app/src/test/java/dev/edge0/runtime/app/runtime/ThinkSplitterTest.kt@@ -0,0 +1,110 @@+// ThinkSplitterTest - incremental tag-pair splitting table (cross-chunk tag cases).+// Tag literals are always assembled from constants (tooling strips special-looking+// literals; the rule applies to tests too).+// Delivery semantics: same-kind segments merge within one feed; across feeds the+// UI aggregates.+package dev.edge0.runtime.app.runtime++import org.junit.Assert.assertEquals+import org.junit.Test++class ThinkSplitterTest {+ private val O = ThinkSplitter.OPEN+ private val C = ThinkSplitter.CLOSE++ private fun run(pieces: List<String>): List<Seg> {+ val sp = ThinkSplitter()+ val out = ArrayList<Seg>()+ for (p in pieces) out.addAll(sp.feed(p))+ out.addAll(sp.flush())+ return foldAdjacent(out)+ }++ /** Fold adjacent same-kind segments (normalize the cross-feed freedom). */+ private fun foldAdjacent(segs: List<Seg>): List<Seg> {+ val out = ArrayList<Seg>()+ for (s in segs) {+ val last = out.lastOrNull()+ if (last != null && last::class == s::class) {+ out[out.size - 1] = when (s) {+ is Seg.Text -> Seg.Text((last as Seg.Text).s + s.s)+ is Seg.Think -> Seg.Think((last as Seg.Think).s + s.s)+ }+ } else out.add(s)+ }+ return out+ }++ @Test fun promptInjectedOpenStartsInThink() {+ // real-device scenario: the OPEN tag lives in the prompt, the stream starts inside thinking+ val sp = ThinkSplitter(initialThink = true)+ val out = ArrayList<Seg>()+ out.addAll(sp.feed("plan text"))+ out.addAll(sp.feed("$C" + "answer"))+ out.addAll(sp.flush())+ assertEquals(listOf<Seg>(Seg.Think("plan text"), Seg.Text("answer")), foldAdjacent(out))+ }++ @Test fun wholePairInOneFeed() {+ assertEquals(listOf<Seg>(Seg.Think("abc"), Seg.Text("def")),+ run(listOf("$O" + "abc$C" + "def")))+ }++ @Test fun openTagSplitAcrossPieces() {+ // open tag split across three chunks + close tag across two (folded result must be whole)+ assertEquals(listOf<Seg>(Seg.Text("hi "), Seg.Think("thinkingbody"), Seg.Text("tail")),+ run(listOf("hi <", "th", "ink>thinking", "body</t", "h", "ink>tail")))+ }++ @Test fun plainTextNoTags() {+ assertEquals(listOf<Seg>(Seg.Text("purebody.")), run(listOf("pure", "body.")))+ }++ @Test fun fakePrefixNotTag() {+ // body containing a fake "<th" prefix not followed by the rest -> stays body+ assertEquals(listOf<Seg>(Seg.Text("a <th b")), run(listOf("a <th", " b")))+ }++ @Test fun nestedOpenInsideThinkIsPlainThink() {+ assertEquals(listOf<Seg>(Seg.Think(" again $O same again"), Seg.Text("post")),+ run(listOf("$O again $O same again$C" + "post")))+ }++ @Test fun unclosedToEosIsAllThink() {+ assertEquals(listOf<Seg>(Seg.Think("never closed")), run(listOf("$O" + "never closed")))+ }++ @Test fun emptyPairEmitsNoThinkSegment() {+ assertEquals(listOf<Seg>(Seg.Text("x")), run(listOf("$O$C" + "x")))+ }++ @Test fun trailingFakeOpenFlushesAsText() {+ // EOS with a half-tag carried: flush delivers under the current mode (TEXT)+ assertEquals(listOf<Seg>(Seg.Text("before<th")), run(listOf("before<th")))+ }++ @Test fun thinkThenMoreThinkBlocks() {+ assertEquals(+ listOf<Seg>(Seg.Think("a"), Seg.Text("b"), Seg.Think("c"), Seg.Text("d")),+ run(listOf("$O" + "a$C" + "b$O" + "c$C" + "d")))+ }++ @Test fun charByCharFeedMatchesOneShot() {+ val sp1 = ThinkSplitter()+ val src = "$O" + "multi step" + "thinking$C" + "reply $O" + "again$C" + "end"+ val oneShot = foldAdjacent(sp1.feed(src) + sp1.flush())+ val sp2 = ThinkSplitter()+ val per = ArrayList<Seg>()+ for (ch in src) { per.addAll(sp2.feed(ch.toString())) }+ per.addAll(sp2.flush())+ assertEquals(oneShot, foldAdjacent(per))+ }++ @Test fun thinkingNowTracksMode() {+ val sp = ThinkSplitter()+ sp.feed("$O" + "x")+ assertEquals(true, sp.thinkingNow)+ sp.feed("y$C" + "z")+ assertEquals(false, sp.thinkingNow)+ }+}diff --git a/android/app/src/test/java/dev/edge0/runtime/app/ui/markdown/MathFallbackTest.kt b/android/app/src/test/java/dev/edge0/runtime/app/ui/markdown/MathFallbackTest.ktnew file mode 100644index 0000000..735a61a--- /dev/null+++ b/android/app/src/test/java/dev/edge0/runtime/app/ui/markdown/MathFallbackTest.kt@@ -0,0 +1,49 @@+// MathFallbackTest - LaTeX degradation preprocessing for the markdown adapter.+// Guards the blank-math-render incident: $$..$$ math nodes were accepted by the+// renderer but drawn as empty space; mathFallback makes them visible as inline+// code (fenced blocks break inside list items, which is where models put math).+package dev.edge0.runtime.app.ui.markdown++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class MathFallbackTest {+ private val D = "\$" // a dollar sign without triggering string interpolation++ @Test fun blockDollarBecomesInlineCode() {+ val src = "1. Divide 8 by 3:\n\n" + D + D + "\\frac{8}{3}" + D + D + "\n\ndone"+ val out = mathFallback(src)+ assertTrue("math content visible", "frac" in out)+ assertTrue("math delimiters gone", D !in out)+ assertTrue("no fence noise", "```" !in out)+ }++ @Test fun inlineDollarBecomesCode() {+ val out = mathFallback("where " + D + "x^2 + y" + D + " holds")+ assertTrue("backtick-wrapped", out.contains("`x^2 + y`"))+ }++ @Test fun moneyTextUntouched() {+ val src = "costs " + D + "5 and " + D + "6 total"+ assertEquals(src, mathFallback(src))+ }++ @Test fun plainTextPassesThrough() {+ assertEquals("no math here at all", mathFallback("no math here at all"))+ }++ @Test fun parenAndBracketForms() {+ assertTrue("`a+b`" in mathFallback("do \\(a+b\\) now"))+ val br = mathFallback("\\[ \\frac{1}{2} \\]")+ assertTrue("bracket body visible", "frac" in br)+ assertTrue("delimiters gone", "\\[" !in br)+ }++ @Test fun multilineBlockCollapsesToOneLine() {+ val src = D + D + "\n\\sum_{i=1}^{n} i\n" + D + D+ val out = mathFallback(src)+ assertTrue("body present", "sum_{i=1}^{n} i" in out)+ assertTrue("single line", !out.trim().contains("\n"))+ }+}diff --git a/android/app/src/test/resources/metrics_real.json b/android/app/src/test/resources/metrics_real.jsonnew file mode 100644index 0000000..0e7ffdb--- /dev/null+++ b/android/app/src/test/resources/metrics_real.json@@ -0,0 +1 @@+{"cancelled": false, "chat_turns": 1, "config": {"compute_threads": 1, "io_threads": 4, "max_context_tokens": 4096, "pool_budget_bytes": 100663296, "scrub_percent": 0}, "decode_ms": 1908, "decode_tok_s": 4.1928721174004195, "error": "", "first_token_ms": 2725, "generate_seq": 1, "gpu": {"active": true, "cache_hit": true, "cus": 12, "device": "QUALCOMM Adreno(TM) 830", "driver": "OpenCL 3.0 QUALCOMM build: 0800.72 Compiler E031.47.18.49", "mem_mib": 7576, "ms": 1415.627034187317, "n_submit": 7944, "n_sync": 207, "ok": true, "policy": 0, "probed": true, "why": "ok"}, "int8_effective": false, "layer_track": 0, "new_tokens": 8, "params": {"max_new_tokens": 8, "seed": 539363605, "temperature": 0.0, "top_k": 0, "top_p": 1.0}, "peak_rss_bytes": 1366167552, "pool": {"claim_ns": 0, "claim_ns_per_tok": 0.0, "evictions": 4029, "flash_bytes": 5429182464, "hits": 635, "io_failures": 0, "lookup_ns": 0, "lookup_ns_per_tok": 0.0, "misses": 2095, "prefetch_dropped": 0, "prefetch_issued": 4216, "prefetch_wasted": 2220, "resident_bytes": 100564992, "slots_total": 62, "slots_used": 62, "stall_ns": 637740209, "sync_rescues": 0}, "prefill_cold_s": 8.443465491923641, "prefill_ms": 2724, "prefill_tok_s": 8.443465491923641, "prefill_warm_s": 0.0, "prompt_tokens": 23, "route": {"agree": null, "dec_steps": 8, "feature": "executed", "mode": "predicted", "pred_used": 128}, "schema": 1, "thinking_on": true}\ No newline at end of filediff --git a/android/build.gradle.kts b/android/build.gradle.ktsnew file mode 100644index 0000000..97a679c--- /dev/null+++ b/android/build.gradle.kts@@ -0,0 +1,9 @@+plugins {+ alias(libs.plugins.android.library) apply false+ alias(libs.plugins.android.application) apply false+ alias(libs.plugins.kotlin.android) apply false+ // compose compiler plugin version must equal Kotlin (2.0.21); Room via KSP; metrics via kotlinx-serialization+ alias(libs.plugins.kotlin.compose) apply false+ alias(libs.plugins.ksp) apply false+ alias(libs.plugins.kotlinx.serialization) apply false+}diff --git a/android/gradle.properties b/android/gradle.propertiesnew file mode 100644index 0000000..d703336--- /dev/null+++ b/android/gradle.properties@@ -0,0 +1,5 @@+org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8+org.gradle.caching=true+org.gradle.configuration-cache=true+android.useAndroidX=true+android.nonTransitiveRClass=truediff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.tomlnew file mode 100644index 0000000..07b528d--- /dev/null+++ b/android/gradle/libs.versions.toml@@ -0,0 +1,47 @@+[versions]+agp = "8.7.3"+kotlin = "2.0.21"+# aligned with the target platform constraints in the docs+minSdk = "33"+compileSdk = "35"+ndk = "27.2.12479018"+# pinned, verified combination; compose compiler plugin version must equal Kotlin+composeBom = "2024.12.01"+activityCompose = "1.9.3"+navigationCompose = "2.8.5"+lifecycle = "2.8.7"+room = "2.7.0"+ksp = "2.0.21-1.0.28"+datastore = "1.1.1"+coroutines = "1.9.0"+serializationJson = "1.7.3"+markdownRenderer = "0.27.0" # last release binary-compatible with Kotlin 2.0.21++[libraries]+# Compose (versions governed by the BOM)+compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }+compose-ui = { group = "androidx.compose.ui", name = "ui" }+compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }+compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }+compose-material3 = { group = "androidx.compose.material3", name = "material3" }+compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }+androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }+androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }+androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }+androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }+androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" }+androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }+androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }+androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }+androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }+kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }+kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serializationJson" }+markdown-renderer-m3 = { group = "com.mikepenz", name = "multiplatform-markdown-renderer-m3", version.ref = "markdownRenderer" }++[plugins]+android-library = { id = "com.android.library", version.ref = "agp" }+android-application = { id = "com.android.application", version.ref = "agp" }+kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }+ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }+kotlinx-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 0000000..a4b76b9Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..e2847c8--- /dev/null+++ b/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,7 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip+networkTimeout=10000+validateDistributionUrl=true+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/android/gradlew b/android/gradlewnew file mode 100644index 0000000..d95bf61--- /dev/null+++ b/android/gradlew@@ -0,0 +1,252 @@+#!/bin/sh++#+# Copyright © 2015-2021 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s+' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar+++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ if ! command -v java >/dev/null 2>&1+ then+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -classpath "$CLASSPATH" \+ org.gradle.wrapper.GradleWrapperMain \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/android/gradlew.bat b/android/gradlew.batnew file mode 100755index 0000000..640d686--- /dev/null+++ b/android/gradlew.bat@@ -0,0 +1,94 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem+@rem SPDX-License-Identifier: Apache-2.0+@rem++@if "%DEBUG%"=="" @echo off+@rem ##########################################################################+@rem+@rem Gradle startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables with windows NT shell+if "%OS%"=="Windows_NT" setlocal++set DIRNAME=%~dp0+if "%DIRNAME%"=="" set DIRNAME=.+@rem This is normally unused+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if %ERRORLEVEL% equ 0 goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:execute+@rem Setup the command line++set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar+++@rem Execute Gradle+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*++:end+@rem End local scope for the variables with windows NT shell+if %ERRORLEVEL% equ 0 goto mainEnd++:fail+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of+rem the _cmd.exe /c_ return code!+set EXIT_CODE=%ERRORLEVEL%+if %EXIT_CODE% equ 0 set EXIT_CODE=1+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%+exit /b %EXIT_CODE%++:mainEnd+if "%OS%"=="Windows_NT" endlocal++:omegadiff --git a/android/settings.gradle.kts b/android/settings.gradle.ktsnew file mode 100644index 0000000..408eaee--- /dev/null+++ b/android/settings.gradle.kts@@ -0,0 +1,18 @@+pluginManagement {+ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}++dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ google()+ mavenCentral()+ }+}++rootProject.name = "edge0-runtime-android"+include(":app") // single APK: native engine + Compose UIdiff --git a/android/tools/llama/build_vendor_libs.sh b/android/tools/llama/build_vendor_libs.shnew file mode 100644index 0000000..49a9006--- /dev/null+++ b/android/tools/llama/build_vendor_libs.sh@@ -0,0 +1,63 @@+#!/usr/bin/env bash+# build_vendor_libs.sh - rebuild the four shared libraries from the pinned supply tree.+# Supply topology (patches/llama.cpp/README in the depot repo):+# vendor@pin (vendor.llama.pin at the depot root; materialized by clone on first run -+# no submodule) -> wt/and worktree with common(6)+android(14) bands replayed in order+# -> golden tree hash. Set EDGE0_LLAMA_URL to clone from a mirror instead of GitHub.+# Usage: bash tools/llama/build_vendor_libs.sh [--replay] (--replay = re-apply bands + verify)+set -euo pipefail+REPO=$(cd "$(dirname "$0")/../.." && pwd)+DEPOT=${EDGE0_DEPOT:-$(cd "$REPO/.." && pwd -W)} # depot root (this repo lives at <depot>/android)+WT=$DEPOT/wt/and+[ -f "$DEPOT/vendor.llama.pin" ] || { echo "ABORT: vendor.llama.pin missing at depot root ($DEPOT)"; exit 1; }+PIN=$(cut -d' ' -f1 "$DEPOT/vendor.llama.pin")+VENDOR=$DEPOT/vendor/llama.cpp+GOLD_TREE=e974be50ba5c184bf0ba9a4a26adbbae4235c2ab+NDK=${NDK_DIR:-${ANDROID_NDK_HOME:-}}+[ -n "$NDK" ] || { echo "ABORT: set NDK_DIR (or ANDROID_NDK_HOME) to the Android NDK r28 path"; exit 1; }+LL=$REPO/build-dl/llama-libs++# materialize the pinned vendor tree when absent (submodule-free supply)+if [ ! -d "$VENDOR/.git" ]; then+ echo "[0/3] materializing vendor: clone llama.cpp at pinned $PIN -> $VENDOR"+ mkdir -p "$DEPOT/vendor"+ git clone --filter=blob:none "${EDGE0_LLAMA_URL:-https://github.com/ggml-org/llama.cpp}" "$VENDOR"+fi+[ "$(git -C "$VENDOR" rev-parse HEAD)" = "$PIN" ] || git -C "$VENDOR" checkout --detach "$PIN"+[ -z "$(git -C "$VENDOR" status --porcelain)" ] || { echo "ABORT: vendor tree dirty - the pristine supply is never patched in place; restore with: git -C $VENDOR checkout --detach $PIN"; exit 1; }++# self-heal: a fresh clone has no consumer worktree yet - create it at the pin,+# and treat the bare tree as needing the band replay (otherwise the tree gate+# would compare an unpatched pin against the golden patched tree -> false RED)+FRESH_WT=0+if [ ! -d "$WT" ]; then+ git -C "$VENDOR" worktree add --detach "$WT" "$PIN"+ FRESH_WT=1+fi++if [ "${1:-}" = "--replay" ] || [ "$FRESH_WT" = "1" ]; then+ git -C "$WT" am --abort 2>/dev/null || true+ git -C "$WT" reset --hard "$PIN"+ for band in common android; do+ for f in $(ls "$DEPOT/patches/llama.cpp/$band/"0*.patch | sort); do+ git -C "$WT" am --3way "$f"+ done+ done+fi+T=$(git -C "$WT" rev-parse 'HEAD^{tree}')+[ "$T" = "$GOLD_TREE" ] || { echo "ABORT: tree mismatch got=$T want=$GOLD_TREE"; exit 1; }+echo "tree GREEN $T"++cmake -S "$WT" -B "$WT/build-android-cpu" -G Ninja \+ -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \+ -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-28 -DCMAKE_BUILD_TYPE=Release \+ -DBUILD_SHARED_LIBS=ON -DLLAMA_BUILD_COMMON=ON -DGGML_OPENCL=OFF -DGGML_NATIVE=OFF+ninja -C "$WT/build-android-cpu" llama ggml ggml-base ggml-cpu++mkdir -p "$LL/arm64-v8a" "$LL/include"+cp "$WT"/build-android-cpu/bin/{libllama.so,libggml.so,libggml-base.so,libggml-cpu.so} "$LL/arm64-v8a/"+# libggml-cpu DT_NEEDED libomp.so (NDK OpenMP runtime) - ship it alongside,+# otherwise the app fails dlopen at launch on a fresh build.+cp "$NDK"/toolchains/llvm/prebuilt/*/lib/clang/*/lib/linux/aarch64/libomp.so "$LL/arm64-v8a/"+cp "$WT"/include/*.h "$WT"/ggml/include/*.h "$LL/include/"+echo "OK: four libs from wt/and @$(git -C "$WT" rev-parse --short HEAD)"diff --git a/android/tools/model/push_models.sh b/android/tools/model/push_models.shnew file mode 100644index 0000000..53258a2--- /dev/null+++ b/android/tools/model/push_models.sh@@ -0,0 +1,57 @@+#!/usr/bin/env bash+# push_models.sh - stage the three GGUF artifacts onto the device files/models/.+# Usage: bash tools/model/push_models.sh --8b | --35b | --all+# Default sources are this repo's models/edge0-{8b,35b}-gguf/ (converter output).+# SRC_DIR=<dir> overrides; ADB_SERIAL selects the device (default: first online).+# Triple-hop discipline: host md5 -> adb push -> run-as copy -> on-device md5.+# Any 8-hex mismatch aborts. The 21.7GB artifact takes 2-6 min; reruns are idempotent.+set -euo pipefail+REPO=$(cd "$(dirname "$0")/../.." && pwd)+# Self-contained layout: sources and converted artifacts live under models/ (gitignored).+# The converter (../windows/tools/convert_mlx_to_gguf.py --dir models/edge0-{tier})+# writes models/edge0-{tier}-gguf/; names pass through unchanged.+# SRC_DIR=<dir> overrides with a single flat directory.+src_for() { # $1 = artifact name -> host source path (convention dirs unless SRC_DIR set)+ local dir+ case "$1" in edge0-8b.gguf|lora_edge0_8b-gguf.gguf) dir=${SRC:-$REPO/models/edge0-8b-gguf} ;;+ *) dir=${SRC:-$REPO/models/edge0-35b-gguf} ;;+ esac+ echo "$dir/$1"+}+DEV=${ADB_SERIAL:-}+PKG=dev.edge0.runtime.app+T=/data/local/tmp/lgguf++# artifact -> official md5 prefix baseline (converter convention names, 2026-09)+md5_of() { case "$1" in+ edge0-8b.gguf) echo b5f6021f ;;+ lora_edge0_8b-gguf.gguf) echo e73c92e3 ;;+ edge0-35b.gguf) echo 7d2c2e8c ;;+ *) echo "?" ;; esac; }++FILES_8B=(edge0-8b.gguf lora_edge0_8b-gguf.gguf)+FILES_35B=(edge0-35b.gguf)+case "${1:-}" in+ --8b) FILES=("${FILES_8B[@]}") ;;+ --35b) FILES=("${FILES_35B[@]}") ;;+ --all) FILES=("${FILES_8B[@]}" "${FILES_35B[@]}") ;;+ *) echo "usage: push_models.sh --8b|--35b|--all" >&2; exit 2 ;;+esac++ADB=(adb ${DEV:+-s "$DEV"})+"${ADB[@]}" get-state >/dev/null || { echo "ABORT: no device ($DEV)" >&2; exit 1; }+"${ADB[@]}" shell "mkdir -p $T"+for f in "${FILES[@]}"; do+ want=$(md5_of "$f"); src="$(src_for "$f")"+ [ -f "$src" ] || { echo "ABORT: missing $src (download + run converter, or place artifact)"; exit 1; }+ got=$(md5sum "$src" | cut -c1-8)+ [ "$got" = "$want" ] || { echo "ABORT: $f host md5=$got want=$want"; exit 1; }+ echo "push $f ($(du -h "$src" | cut -f1)) ..."+ MSYS_NO_PATHCONV=1 "${ADB[@]}" push "$(cygpath -w "$src" 2>/dev/null || echo "$src")" "$T/$f" >/dev/null+ # copy into the app-private dir via run-as (non-root path) + on-device verification+ "${ADB[@]}" shell "run-as $PKG mkdir -p files/models; run-as $PKG cp $T/$f files/models/$f"+ dev=$(MSYS_NO_PATHCONV=1 "${ADB[@]}" shell "run-as $PKG md5sum files/models/$f" | tr -d '\r' | cut -c1-8)+ [ "$dev" = "$want" ] || { echo "ABORT: $f device md5=$dev want=$want (truncated transfer? re-run)"; exit 1; }+ echo "OK $f md5=$dev"+done+echo "staged -> $PKG/files/models"diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.mdnew file mode 100644index 0000000..b2acc27--- /dev/null+++ b/patches/llama.cpp/README.md@@ -0,0 +1,85 @@+# patches/llama.cpp — the llama engine supply ledger++**Topology discipline**: this directory + `vendor/llama.cpp` (the single pristine source of truth)+are the entire formal surface of the llama engine supply. The product trees (`windows/`,+`android/`) may only depend on the repo's `vendor/` + `patches/` + `wt/`. The shared vendor tree+is a detached checkout of upstream and is **never patched in place** (the build scripts refuse a+dirty or moved tree).++- **Pin = `vendor.llama.pin` one-liner at the repo root** (currently `7ab4ee7` = tag `b11100`+ of [ggml-org/llama.cpp](https://github.com/ggml-org/llama.cpp)). The tree is **not** a submodule:+ the platform scripts clone it on first run (set `EDGE0_LLAMA_URL` for a mirror) and detach exactly+ at the pin. Shared tree stays detached, and is **never patched in place** (the build scripts refuse+ a dirty or moved tree).+- **Consumption model = worktree isolation**: each platform replays its own bands with `git am`+ inside its own worktree (`wt/win` / `wt/and`) and builds its own artifacts there; the shared+ tree and the bands never contaminate each other, and builds can run in parallel.+- **Surface rule (unchanged)**: patches only touch hook points, and every hook is annotated+ `edge0 private surface #N`. Platform-owned logic lives in glob-injected files+ (Windows: `windows/serve/*`, Android: `android/engine` pieces wired via `build_vendor_libs.sh`),+ not in patch caps.++## Band structure & assembly formula++| Platform | Assembly sequence | Count | Golden result-tree hash |+|---|---|---|---|+| Windows | `common/*` → `windows/*` | 6+2=8 | `df9d12dcb59aa3314f3356c2cdb777ee4ca4919c` |+| Android | `common/*` → `android/*` | 6+14=20 | `e974be50ba5c184bf0ba9a4a26adbbae4235c2ab` |++Verify with `git rev-parse HEAD^{tree}` on the worktree **after replay and before copying in the+own-owned files**. The bands share no files (windows band = `common/arg.cpp` + server params;+android band = `ggml-cpu/moe_pool` + `src/edge0` hooks + bench debug gates), so switching bands+is safe: `git am --abort; git reset --hard 7ab4ee7`, then replay.++## common band (6 patches, hook surface shared by both platforms)++| File | Surface | Hook |+|---|---|---|+| 0001 | #1 | bailingmoe3 main-graph LoRA wire-up (9 raw `mul_mat` → `build_lora_mm`) |+| 0002 | #2 | qwen3next/bailingmoe3: capture router input `m_in` into `t_layer_inp` |+| 0003 | #3 | CMake glob `src/edge0/*.cc` into the llama target (injection channel for own files) |+| 0004 | #4 | server: wire prerouter advisory `init`/`on_step` |+| 0005 | #5 | server: wire `edge0_apply_mem_budget` (before model load, env `E0_MEM_BUDGET_MB`) |+| 0006 | #7 | `ggml_edge0_mmid_base` expert-base resolver: three read points (ggml-cpu.c / iqp.cpp / repack.cpp) + declaration in `ggml-cpu-impl.h`; **NULL = upstream semantics** |++> Why #7 sits in common: the android band registers its pool's row resolver into the same #7+> surface at first registration, so "swappable expert row base" is one hook point on both+> platforms instead of two hand-edited rows.++## windows band (2 patches)++| File | Surface | Hook |+|---|---|---|+| 0001 | #6 | `--mem-budget-mb` first-class CLI (common_params + arg + server) |+| 0002 | #8 | `--pool-mb` first-class CLI (env `LLAMA_ARG_POOL_MB` on the same line) |++## android band (14 patches)++0001–0013 = the full demand-pool sequence (phase-1 → v4.7.1, item-by-item parity with the+engine's streaming/expert_pool contract): copy-in private frames + equal-size slot state machine++ IO-thread queues + pin/blob/trim/metrics + NEON predictor head + watermark throttle + keepwarm+refill + reset_all + race hardening. **Hook surface**: `ensure`/`note` dispatch at `MUL_MAT_ID`,+IQP pooled gate (arm64 never enables IQP anyway = double insurance), qwen3next layer-input bind,+`moe_wire` registration in `llama-model.cpp` and its call site. 0001/0005 also carry the+`E0_MMAP_NOPREFETCH` / `E0_NO_REPACK` debug gates.++0014 = consolidation: registers the moe_pool row resolver into the #7 surface (`ggml_edge0_set_mmid_resolver`+at `g_ready=1`), replacing the direct row rewrite at `src0_cur`; zero disturbance while the pool+is not ready.++## Refreshing the upstream pin (rebase recipe)++```powershell+# 1) move the pin: update vendor.llama.pin first (it is the single source of the pin), then+# refresh the materialized tree — the scripts detach at the new pin on their own+git -C vendor/llama.cpp fetch origin+git -C vendor/llama.cpp checkout --detach <new-commit>+# 2) re-replay each band three-way on a scratch worktree and re-export it (bands are independent; do them one at a time)+git -C wt/win reset --hard <new-commit>+git -C wt/win am --3way (Get-ChildItem patches/llama.cpp/common/*.patch).FullName+git -C wt/win am --3way (Get-ChildItem patches/llama.cpp/windows/*.patch).FullName+# conflicts: resolve by the hook-point semantics above, then `git am --3way --continue`+# 3) after the gate + tree parity + smoke pass: re-export with format-patch into this directory,+# update the golden hashes in the table above, and bump vendor.llama.pin (all scripts read it)+pwsh -File scripts/patch-green.ps1 -Bands common,windows+```diff --git a/patches/llama.cpp/android/0001-moe_pool-android-demand-pool-phase-1-copy-in-private.patch b/patches/llama.cpp/android/0001-moe_pool-android-demand-pool-phase-1-copy-in-private.patchnew file mode 100644index 0000000..876323d--- /dev/null+++ b/patches/llama.cpp/android/0001-moe_pool-android-demand-pool-phase-1-copy-in-private.patch@@ -0,0 +1,414 @@+From 6f0158a08cd763eac4bbc2a830ea52fe27996a87 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 20:54:33 +0800+Subject: [PATCH 01/14] moe_pool: android demand-pool phase-1 (copy-in private+ frames + lazy row-ptr + expert LRU)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++- ggml-cpu/moe_pool.{c,h}: E0_POOL_MB gate (off by default = zero disturbance); copy-in private+ frames (Android mlock RLIMIT=64KB rules out the pin-file-page design -- PROBE B-track closed);+ demand miss = thread0 bulk pread before the barrier ("wholesale"); eviction = self-managed LRU+ at whole-expert granularity + current-generation protection (rows still in compute are not+ recycled); non-resident row pointers resolve lazily back to the original mmap (kernel backstop).+- ggml-cpu.c MUL_MAT_ID, four hooks: include / IQP bypass disabled (self-computed row pointers+ would skip the pool) / thread0 dispatches ensure after scanning ids / src0_cur row-pointer resolve+- llama-model.cpp load-time registration: walk ml.contexts + name contains 'exps' + weight.offs+ taken directly (stride%4096 conservative gate; pread does not move the file cursor; pointer idempotent)+- Android path gates: llama-model.cpp AUTO mmap_support downgrade skippable (E0_MMAP_NOPREFETCH) ++ bench E0_NO_REPACK + main.cpp setvbuf (root cause of the 217B truncation misattribution)+- concurrency protocol = phase-1 single ctx (node barriers keep readers quiescent while ensure+ writes); server parallel ctx = phase 2++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/CMakeLists.txt | 1 ++ ggml/src/ggml-cpu/ggml-cpu.c | 6 +-+ ggml/src/ggml-cpu/moe_pool.c | 188 +++++++++++++++++++++++++++++++ ggml/src/ggml-cpu/moe_pool.h | 40 ++++++++ src/llama-model.cpp | 37 +++++-+ tools/llama-bench/llama-bench.cpp | 2 ++ tools/llama-bench/main.cpp | 3 ++ 7 files changed, 274 insertions(+), 3 deletions(-)+ create mode 100644 ggml/src/ggml-cpu/moe_pool.c+ create mode 100644 ggml/src/ggml-cpu/moe_pool.h++diff --git a/ggml/src/ggml-cpu/CMakeLists.txt b/ggml/src/ggml-cpu/CMakeLists.txt+index 1c7338e..f3c945a 100644+--- a/ggml/src/ggml-cpu/CMakeLists.txt++++ b/ggml/src/ggml-cpu/CMakeLists.txt+@@ -30,6 +30,7 @@ function(ggml_add_cpu_backend_variant_impl tag_name)+ ggml-cpu/ggml-cpu.c+ ggml-cpu/ggml-cpu.cpp+ ggml-cpu/repack.cpp++ ggml-cpu/moe_pool.c+ ggml-cpu/repack.h+ ggml-cpu/iqp.cpp+ ggml-cpu/iqp.h+diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c+index be7c2db..54f0d9a 100644+--- a/ggml/src/ggml-cpu/ggml-cpu.c++++ b/ggml/src/ggml-cpu/ggml-cpu.c+@@ -15,6 +15,7 @@+ #include "ops.h"+ #include "ggml.h"+ #include "common.h"++#include "moe_pool.h"++ #if defined(_MSC_VER) || defined(__MINGW32__)+ #include <malloc.h> // using malloc.h with MSC/MINGW+@@ -1610,7 +1611,7 @@ static void ggml_compute_forward_mul_mat_id(++ // IQ panel gemm (see iqp.h); per expert eligibility is decided below, but the work buffer is+ // reserved for the whole node (ggml_graph_plan sizes it without params, use_ref only skips the dispatch)+- const bool iqp = ggml_cpu_iqp_supports_mul_mat_id(dst) && !params->use_ref;++ const bool iqp = ggml_cpu_iqp_supports_mul_mat_id(dst) && !params->use_ref && !moe_pool_pooled(src0);++ char * iqp_panels = NULL;++@@ -1672,6 +1673,9 @@ static void ggml_compute_forward_mul_mat_id(+ matrix_row_counts[i02] += 1;+ }+ }++++ // moe_pool: demand-pool dispatch -- bulk-read this ubatch's experts (unregistered tensors return immediately)++ moe_pool_ensure(src0, (const int32_t *) ids->data, (int) (ids->ne[0] * ids->ne[1]));+ }++ // reset current_chunk+diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+new file mode 100644+index 0000000..2f75ab1+--- /dev/null++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -0,0 +1,188 @@++// moe_pool.c -- expert demand pool (Android phase 1, edge0/android-pool; no prediction, synchronous bulk reads).++// Design = copy-in private frames + lazy row-pointer resolution: a hit = zero-fault direct read of the private frame; a miss =++// thread0 preads the whole block before the ggml_barrier ("wholesale"); eviction = pool-managed LRU (whole-expert granularity).++// Concurrency protocol (the premise phase 1 holds on; server parallel ctx is a phase-2 topic):++// the ggml-cpu thread pool barriers at EVERY graph-node boundary; ensure runs only on thread0 at the mul_mat_id entry,++// before the global barrier -> all readers are quiescent when writing; cross-ctx parallel decode is unguarded (documented red line).++// Experts outside the pool / that don't fit: resident_slot=-1 -> the caller gets the default pointer and falls back to the original mmap (kernel backstop).++// env: E0_POOL_MB (0/unset = off, zero disturbance).++#include "moe_pool.h"++#include "ggml.h"++++#include <pthread.h>++#include <stdio.h>++#include <stdlib.h>++#include <string.h>++#include <sys/mman.h>++#include <unistd.h>++++#define MOE_POOL_MAX_TENSORS 192 // 40 layers x3 (gate/up/down) = 120 @35b; headroom kept++++struct slot_ent {++ char * base; // arena private frame++ int32_t expert; // -1 = free++ int32_t tix;++ uint64_t last_gen;++ size_t bytes;++ struct slot_ent * prev, * next;++};++++struct tensor_pool {++ const void * key; // src0->data is stable after load; used as identity++ int fd;++ uint64_t file_off;++ size_t slice; // private-frame size (page-aligned, >= stride)++ size_t stride; // per-expert step within the file++ int64_t n_experts;++ int64_t * slot_of; // [n_experts] slot index or -1 (no tearing concern under the quiesce protocol)++ long long hits, misses;++};++++static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;++static size_t g_cap, g_used;++static char * g_arena;++static size_t g_bump;++static uint64_t g_gen;++static struct tensor_pool g_tp[MOE_POOL_MAX_TENSORS];++static int g_ntp;++static struct slot_ent ** g_slots; static int g_nslots, g_slotcap;++static struct slot_ent * g_lru_head, * g_lru_tail;++static int g_ready;++static long long g_loads, g_evicts, g_bytes_loaded;++++static size_t align_up(size_t x) { return (x + 4095) & ~(size_t)4095; }++++void moe_pool_init(void) {++ if (g_ready) return;++ const char * e = getenv("E0_POOL_MB");++ size_t mb = e ? (size_t) atol(e) : 0;++ if (!mb) return;++ g_cap = mb * 1024 * 1024;++ void * m = mmap(NULL, g_cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);++ if (m == MAP_FAILED) return;++ g_arena = m; g_ready = 1;++}++++int moe_pool_enabled(void) { return g_ready; }++static struct tensor_pool * find_tp(const struct ggml_tensor * t);++++void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off) {++ if (!g_ready) return;++ if (t->ne[2] < 8) return; // expert-stack shape++ if (find_tp(t)) return; // idempotent: same pointer never re-registered++ const size_t total = (size_t) ggml_nbytes(t);++ const size_t stride = total / (size_t) t->ne[2];++ // conservative gate: pool only when the expert slice is naturally page-aligned (holds for this artifact); otherwise leave it to the kernel++ if (stride % 4096) return;++ const size_t slice = stride;++ pthread_mutex_lock(&g_lock);++ if (g_ntp >= MOE_POOL_MAX_TENSORS) { pthread_mutex_unlock(&g_lock); return; }++ struct tensor_pool * p = &g_tp[g_ntp++];++ p->key = t->data; p->fd = fd; p->file_off = file_off; p->slice = slice; p->stride = stride;++ p->n_experts = t->ne[2];++ p->slot_of = calloc(p->n_experts, sizeof(int64_t));++ for (int64_t i = 0; i < p->n_experts; i++) p->slot_of[i] = -1;++ pthread_mutex_unlock(&g_lock);++}++++static struct tensor_pool * find_tp(const struct ggml_tensor * t) {++ for (int i = 0; i < g_ntp; i++) if (g_tp[i].key == t->data) return &g_tp[i];++ return NULL;++}++++int moe_pool_pooled(const struct ggml_tensor * t) {++ if (!g_ready || !t || !t->data) return 0;++ return find_tp(t) != NULL;++}++++// ---- LRU ----++static void lru_unlink(struct slot_ent * s) {++ if (s->prev) s->prev->next = s->next; else g_lru_head = s->next;++ if (s->next) s->next->prev = s->prev; else g_lru_tail = s->prev;++ s->prev = s->next = NULL;++}++static void lru_front(struct slot_ent * s) {++ s->prev = NULL; s->next = g_lru_head;++ if (g_lru_head) g_lru_head->prev = s; else g_lru_tail = s;++ g_lru_head = s;++}++++static struct slot_ent * slot_alloc(size_t bytes, int tix) {++ struct slot_ent * s = NULL;++ for (int i = 0; i < g_nslots; i++) { // first pick a free slot of the same size++ if (g_slots[i]->expert == -1 && g_slots[i]->bytes == bytes) { s = g_slots[i]; break; }++ }++ if (!s && g_bump + bytes <= g_cap) { // then bump-allocate++ s = calloc(1, sizeof(*s));++ s->base = g_arena + g_bump; g_bump += bytes; s->bytes = bytes;++ if (g_nslots == g_slotcap) {++ g_slotcap = g_slotcap ? g_slotcap * 2 : 512;++ g_slots = realloc(g_slots, (size_t) g_slotcap * sizeof(*g_slots));++ }++ g_slots[g_nslots++] = s;++ }++ if (!s) { // finally evict an older-generation LRU entry++ for (struct slot_ent * c = g_lru_tail; c; c = c->prev) {++ if (c->expert < 0 || c->last_gen == g_gen) continue;++ g_tp[c->tix].slot_of[c->expert] = -1;++ g_used -= c->bytes;++ s = c; break;++ }++ if (s) { g_evicts++; }++ }++ if (!s) return NULL; // pool full this generation / huge block: kernel backstop++ if (s->expert >= 0) lru_unlink(s);++ s->tix = tix; s->expert = -1;++ g_used += s->bytes;++ return s;++}++++void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_ids) {++ if (!g_ready) return;++ pthread_mutex_lock(&g_lock);++ g_gen++;++ struct tensor_pool * p = find_tp(t);++ if (!p) { pthread_mutex_unlock(&g_lock); return; }++ const int tix = (int) (p - g_tp);++ for (int i = 0; i < n_ids; i++) {++ const int32_t e = ids[i];++ if (e < 0 || e >= p->n_experts) continue;++ if (p->slot_of[e] >= 0) { // hit (slot_of = slot_ent address)++ p->hits++;++ struct slot_ent * s = (struct slot_ent *) p->slot_of[e];++ if (s->last_gen != g_gen) { lru_unlink(s); lru_front(s); s->last_gen = g_gen; }++ continue;++ }++ p->misses++;++ struct slot_ent * s = slot_alloc(p->slice, tix);++ if (!s) break;++ const off_t off = (off_t) (p->file_off + (uint64_t) e * p->stride);++ const ssize_t got = pread(p->fd, s->base, p->slice, off);++ if (got != (ssize_t) p->slice) { s->expert = -1; break; }++ s->expert = e; s->last_gen = g_gen;++ lru_front(s);++ g_loads++; g_bytes_loaded += got;++ p->slot_of[e] = (int64_t) (intptr_t) s;++ }++ pthread_mutex_unlock(&g_lock);++}++++const void * moe_pool_row_ptr(const struct ggml_tensor * t, int64_t expert, const void * def) {++ if (!g_ready || expert < 0) return def;++ const struct tensor_pool * p = find_tp(t);++ if (!p || expert >= p->n_experts) return def;++ const int64_t si = p->slot_of[expert];++ if (si < 0) return def;++ const struct slot_ent * s = (const struct slot_ent *) si;++ return (s->expert == expert) ? s->base : def; // always true under the quiesce protocol; kept as a defensive check++}++++void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,++ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes) {++ long long h = 0, m = 0;++ for (int i = 0; i < g_ntp; i++) { h += g_tp[i].hits; m += g_tp[i].misses; }++ if (hits) *hits = h; if (misses) *misses = m;++ if (loads) *loads = g_loads; if (evicts) *evicts = g_evicts;++ if (bytes_loaded) *bytes_loaded = g_bytes_loaded;++ if (cap_bytes) *cap_bytes = g_cap; if (used_bytes) *used_bytes = g_used;++}+diff --git a/ggml/src/ggml-cpu/moe_pool.h b/ggml/src/ggml-cpu/moe_pool.h+new file mode 100644+index 0000000..ab9f7a1+--- /dev/null++++ b/ggml/src/ggml-cpu/moe_pool.h+@@ -0,0 +1,40 @@++// moe_pool.h -- expert demand pool (Android phase 1, no prediction; fork edge0/android-pool).++// Foundation = copy-in private frames (Android mlock RLIMIT=64KB is hard-wired; the pin-file-page design is unusable -- see PROBE B-track closure).++// hit = zero-fault direct read of private memory; miss = ensure() bulk preads the whole block ("wholesale" ~1GB/s vs page-fault "retail" 16MB/s);++// eviction = this pool's own LRU (whole-expert granularity, never half an expert); long-tail experts outside the pool fall back to their original mmap pages, kernel-backed (lazy pointer resolution).++#ifndef MOE_POOL_H++#define MOE_POOL_H++++#include <stddef.h>++#include <stdint.h>++++#ifdef __cplusplus++extern "C" {++#endif++++struct ggml_tensor;++++// called from the llama side before the first registration; E0_POOL_MB unset/0 -> never ready (zero disturbance to current behavior)++void moe_pool_init(void);++int moe_pool_enabled(void);++++// load-time registration: t = expert 3D tensor (src0), file_off = t's data offset in the model file, fd = file descriptor++void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off);++++// query: is this tensor pool-managed (used to turn off the IQP/repack bypass)++int moe_pool_pooled(const struct ggml_tensor * t);++++// thread0 only (before the barrier): bulk-read the experts named by the ids tensor into the pool (LRU makes room)++void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_ids);++++// row-base resolution: resident -> private-frame pointer; otherwise -> default_ptr (original mmap address, kernel backstop)++const void * moe_pool_row_ptr(const struct ggml_tensor * t, int64_t expert, const void * default_ptr);++++// stats snapshot (for debugging / accounting)++void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,++ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes);++++#ifdef __cplusplus++}++#endif++#endif // MOE_POOL_H+diff --git a/src/llama-model.cpp b/src/llama-model.cpp+index e195f50..ec1089d 100644+--- a/src/llama-model.cpp++++ b/src/llama-model.cpp+@@ -1,3 +1,13 @@++#include <cstdlib>++#include <cstring>++#include <unistd.h>++++// moe_pool in-place declarations (same convention as fork edge0/prefetch.cc; implementation in ggml-cpu/moe_pool.c, linked into the same libllama)++extern "C" {++void moe_pool_init(void);++int moe_pool_enabled(void);++void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off);++}+ #include "llama-model.h"++ #include "llama-arch.h"+@@ -1441,7 +1451,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {++ this->ml = &ml; // to be used by create_tensor() and load_arch_tensors()++- if (ml.use_mmap && params.load_mode == LLAMA_LOAD_MODE_AUTO) {++ if (ml.use_mmap && params.load_mode == LLAMA_LOAD_MODE_AUTO && !getenv("E0_MMAP_NOPREFETCH")) {+ for (const auto & dev : devices) {+ ggml_backend_dev_props props;+ ggml_backend_dev_get_props(dev.dev, &props);+@@ -1731,7 +1741,9 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {+ }+ }++- ml.init_mappings(true, use_mlock ? &pimpl->mlock_mmaps : nullptr);++ // android gate (exp/llama-gguf-perf): E0_MMAP_NOPREFETCH=1 skips whole-file WILLNEED++ const bool mmap_prefetch = !use_mlock && getenv("E0_MMAP_NOPREFETCH") == nullptr;++ ml.init_mappings(mmap_prefetch, use_mlock ? &pimpl->mlock_mmaps : nullptr);+ pimpl->mappings.reserve(ml.mappings.size());++ // create the backend buffers+@@ -1879,6 +1891,27 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {+ }+ }+++ // moe_pool registration (Android phase 1): expert 3D tensors -> pool. With E0_POOL_MB unset this block has no side effects.++ moe_pool_init();++ if (moe_pool_enabled() && ml.use_mmap && !ml.files.empty()) {++ auto reg = [&](ggml_tensor * t) {++ if (!t || !strstr(t->name, "exps")) {++ return;++ }++ const auto * w = ml.get_weight(t->name);++ if (!w || w->idx >= ml.files.size()) {++ return;++ }++ // pread does not depend on the file cursor, so the loader's fd is safe to use directly (no dup, avoids leaks)++ moe_pool_register(t, ml.files[w->idx]->file_id(), (uint64_t) w->offs);++ };++ for (auto & ctx : ml.contexts) {++ for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t; t = ggml_get_next_tensor(ctx.get(), t)) {++ reg(t);++ }++ }++ }+++ return true;+ }++diff --git a/tools/llama-bench/llama-bench.cpp b/tools/llama-bench/llama-bench.cpp+index 6541bb5..eff23ca 100644+--- a/tools/llama-bench/llama-bench.cpp++++ b/tools/llama-bench/llama-bench.cpp+@@ -1229,6 +1229,8 @@ struct cmd_params_instance {+ llama_model_params mparams = llama_model_default_params();++ mparams.n_gpu_layers = n_gpu_layers;++ // android gate: E0_NO_REPACK=1 -> no extra bufts (plain mmap zero-copy, kernel LRU)++ if (getenv("E0_NO_REPACK")) { mparams.use_extra_bufts = false; }+ if (!devices.empty()) {+ mparams.devices = const_cast<ggml_backend_dev_t *>(devices.data());+ }+diff --git a/tools/llama-bench/main.cpp b/tools/llama-bench/main.cpp+index 0c18bb0..339602e 100644+--- a/tools/llama-bench/main.cpp++++ b/tools/llama-bench/main.cpp+@@ -1,5 +1,8 @@++#include <cstdio>+++ int llama_bench(int argc, char ** argv);++ int main(int argc, char ** argv) {++ setvbuf(stderr, nullptr, _IONBF, 0); // edge0 diag: unbuffered load log (217B truncation = stderr block-buffer)+ return llama_bench(argc, argv);+ }+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0002-moe_pool-demand-exclusive-mode-flash-pool.patch b/patches/llama.cpp/android/0002-moe_pool-demand-exclusive-mode-flash-pool.patchnew file mode 100644index 0000000..c296183--- /dev/null+++ b/patches/llama.cpp/android/0002-moe_pool-demand-exclusive-mode-flash-pool.patch@@ -0,0 +1,84 @@+From b8b7b832fad28d5926aea27e0667e98e24e45306 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 21:34:34 +0800+Subject: [PATCH 02/14] moe_pool: demand-exclusive mode (flash-pool+ requirements 1 and 3 complete)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++- the 4096 pool-size arm read negative (0.173 < no-pool 0.188), convicting the mixed dual-track:+ pool hits were bytes the kernel could have served anyway, and the pool's anonymous pages squeezed+ the page cache -> net negative. Fix = decode small batches (<=16 ids) force evict-old/admit-new+ and never fall back to mmap -- the pool becomes the only path to experts, expert file pages stay+ entirely out of the page cache, and the full cache budget goes to dense (1.5GB kept hot); the LRU+ head/tail order guarantees this batch's just-loaded rows are not evicted (safe).+- prefill large batches stay best-effort (prevents ping-pong; overflow goes to the kernel).+- vs the engine flash-pool: (1) sole path and (3) whole-granularity self-eviction are met; (2) the+ async window needs phase-2 predictive lookahead (the fork #4 hook is already in place); (4) the+ explicit budget accounting is on the record.++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 20 +++++++++++++++++---+ 1 file changed, 17 insertions(+), 3 deletions(-)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 2f75ab1..06f4999 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -107,7 +107,7 @@ static void lru_front(struct slot_ent * s) {+ g_lru_head = s;+ }++-static struct slot_ent * slot_alloc(size_t bytes, int tix) {++static struct slot_ent * slot_alloc(size_t bytes, int tix, int force) {+ struct slot_ent * s = NULL;+ for (int i = 0; i < g_nslots; i++) { // first pick a free slot of the same size+ if (g_slots[i]->expert == -1 && g_slots[i]->bytes == bytes) { s = g_slots[i]; break; }+@@ -123,7 +123,8 @@ static struct slot_ent * slot_alloc(size_t bytes, int tix) {+ }+ if (!s) { // finally evict an older-generation LRU entry+ for (struct slot_ent * c = g_lru_tail; c; c = c->prev) {+- if (c->expert < 0 || c->last_gen == g_gen) continue;++ if (c->expert < 0) continue;++ if (c->last_gen == g_gen && !force) continue; // demand mode: allow evicting stale entries of THIS generation (just-used rows were already bumped to the LRU head)+ g_tp[c->tix].slot_of[c->expert] = -1;+ g_used -= c->bytes;+ s = c; break;+@@ -144,6 +145,9 @@ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_id+ struct tensor_pool * p = find_tp(t);+ if (!p) { pthread_mutex_unlock(&g_lock); return; }+ const int tix = (int) (p - g_tp);++ // demand-exclusive mode: small batches (decode 1~4 tok) evict-old/admit-new with no mmap fallback -- pool = the only path to experts (flash-pool requirements 1 and 3)++ // large batches (prefill) load best-effort: whatever doesn't fit is left to the kernel, preventing cross-layer ping-pong++ const int demand = n_ids <= 16;+ for (int i = 0; i < n_ids; i++) {+ const int32_t e = ids[i];+ if (e < 0 || e >= p->n_experts) continue;+@@ -154,7 +158,7 @@ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_id+ continue;+ }+ p->misses++;+- struct slot_ent * s = slot_alloc(p->slice, tix);++ struct slot_ent * s = slot_alloc(p->slice, tix, demand);+ if (!s) break;+ const off_t off = (off_t) (p->file_off + (uint64_t) e * p->stride);+ const ssize_t got = pread(p->fd, s->base, p->slice, off);+@@ -186,3 +190,13 @@ void moe_pool_stats(long long * hits, long long * misses, long long * loads, lon+ if (bytes_loaded) *bytes_loaded = g_bytes_loaded;+ if (cap_bytes) *cap_bytes = g_cap; if (used_bytes) *used_bytes = g_used;+ }++++__attribute__((destructor)) static void moe_pool_dump(void) {++ if (!g_ready || !getenv("E0_POOL_STATS")) {++ return;++ }++ long long h = 0, m = 0, l = 0, e = 0, bl = 0; size_t cap = 0, used = 0;++ moe_pool_stats(&h, &m, &l, &e, &bl, &cap, &used);++ fprintf(stderr, "moe_pool stats: hits=%lld misses=%lld loads=%lld evicts=%lld loaded_mb=%lld cap_mb=%zu used_mb=%zu\n",++ h, m, l, e, bl / (1024 * 1024), cap / (1024 * 1024), used / (1024 * 1024));++}+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0003-moe_pool-periodic-stats-dump-destructor-path-bypasse.patch b/patches/llama.cpp/android/0003-moe_pool-periodic-stats-dump-destructor-path-bypasse.patchnew file mode 100644index 0000000..a37669f--- /dev/null+++ b/patches/llama.cpp/android/0003-moe_pool-periodic-stats-dump-destructor-path-bypasse.patch@@ -0,0 +1,32 @@+From 4e039a16242eb10852bff812fa0e8acd2400a20e Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 21:35:19 +0800+Subject: [PATCH 03/14] moe_pool: periodic stats dump (destructor path bypassed+ by bench exit)++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 7 ++++++++ 1 file changed, 7 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 06f4999..d27c2fb 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -148,6 +148,13 @@ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_id+ // demand-exclusive mode: small batches (decode 1~4 tok) evict-old/admit-new with no mmap fallback -- pool = the only path to experts (flash-pool requirements 1 and 3)+ // large batches (prefill) load best-effort: whatever doesn't fit is left to the kernel, preventing cross-layer ping-pong+ const int demand = n_ids <= 16;++ static long s_calls;++ if (getenv("E0_POOL_STATS") && (++s_calls % 2000) == 0) {++ long long h = 0, m = 0, l = 0, e = 0, bl = 0; size_t cap = 0, used = 0;++ moe_pool_stats(&h, &m, &l, &e, &bl, &cap, &used);++ fprintf(stderr, "moe_pool@%ld: hits=%lld misses=%lld loads=%lld evicts=%lld used_mb=%zu\n",++ s_calls, h, m, l, e, used / (1024 * 1024));++ }+ for (int i = 0; i < n_ids; i++) {+ const int32_t e = ids[i];+ if (e < 0 || e >= p->n_experts) continue;+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0004-moe_pool-v4-full-engine-parity-pool-staging-queues-p.patch b/patches/llama.cpp/android/0004-moe_pool-v4-full-engine-parity-pool-staging-queues-p.patchnew file mode 100644index 0000000..0b7bb7e--- /dev/null+++ b/patches/llama.cpp/android/0004-moe_pool-v4-full-engine-parity-pool-staging-queues-p.patch@@ -0,0 +1,1013 @@+From b2ce036a670a9b3657d2342eadf4a6949275601c Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 00:36:44 +0800+Subject: [PATCH 04/14] moe_pool v4: full engine-parity pool (staging queues,+ pin, blob, trim, metrics)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Feature parity with the mainline engine's streaming/expert_pool, landed item by item:+- equal-size slot state machine EMPTY/LOADING/READY/FAILED + IO-thread queue (E0_IO_THREADS, default 4)+- dual queues: the demand-dedicated queue pops first (mixed FIFO was confirmed to suffer prefetch+ head-of-line blocking -- the 14s/token pseudo-hang incident)+- pin protocol: slots in compute are unevictable; released wholesale at the next ensure entry+ (barrier quiescence contract)+- acquire hitting LOADING waits on a cv + FAILED falls back synchronously (stall_ms metered, ~ the+ engine's acq metric)+- resident blob: one copy-in per non-expert mmap-view tensor (E0_BLOB_MB, isomorphic to the engine's+ img mirror)+- watermark trim E0_MEM_FLOOR_MB (when MemAvailable drops below the line, evict non-pinned READY+ down to 60%)+- metrics aligned with the engine's PoolMetrics: hits/misses/stall/pf_issued-used-waste-drop-miss/flash/evicts/trims+- prefetch K=4->8 (teacher n_ids=8 evidences 35b top-8) + throttled drop when the main queue backs up >64+- registration point moved: tensors at the tail of load_tensors have data=NULL (ml.contexts copies),+ so llama_model_load now calls llama_model::moe_wire() after load_tensors (tensors_by_name primary+ set, virtual-interface hook)+- registered fds are always dup()'d (hang incident: pread got EBADF after the loader closed the original fd)+- find_tp matches by name + self-corrects the pointer (graph-copy pointers != load-set pointers)++Known differences from the engine (on record): the worker head math is the scalar version (NEON+queued); trim does no physical tail-block release (the bump arena's middle is not contiguous);+prep-slot tail pre-conversion is N/A (llama dequantizes ad hoc).++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 714 +++++++++++++++++++++++++++++------+ ggml/src/ggml-cpu/moe_pool.h | 18 +-+ src/llama-model.cpp | 70 +++-+ src/llama-model.h | 2 ++ src/llama.cpp | 1 ++ 5 files changed, 667 insertions(+), 138 deletions(-)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index d27c2fb..6f76c90 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -1,92 +1,535 @@+-// moe_pool.c -- expert demand pool (Android phase 1, edge0/android-pool; no prediction, synchronous bulk reads).+-// Design = copy-in private frames + lazy row-pointer resolution: a hit = zero-fault direct read of the private frame; a miss =+-// thread0 preads the whole block before the ggml_barrier ("wholesale"); eviction = pool-managed LRU (whole-expert granularity).+-// Concurrency protocol (the premise phase 1 holds on; server parallel ctx is a phase-2 topic):+-// the ggml-cpu thread pool barriers at EVERY graph-node boundary; ensure runs only on thread0 at the mul_mat_id entry,+-// before the global barrier -> all readers are quiescent when writing; cross-ctx parallel decode is unguarded (documented red line).+-// Experts outside the pool / that don't fit: resident_slot=-1 -> the caller gets the default pointer and falls back to the original mmap (kernel backstop).+-// env: E0_POOL_MB (0/unset = off, zero disturbance).++// moe_pool.c -- expert demand pool v4 (implements the engine streaming/expert_pool contract item by item, edge0/android-pool).++// Design = copy-in private frames (Android mlock RLIMIT=64KB hard-wired; pin-file-page unusable) + equal-size slot state machine++// (EMPTY/LOADING/READY/FAILED) + IO-thread queue reads (prefetch enqueues and returns; acquire hitting LOADING waits on a cv;++// demand misses are dispatched in batches then awaited together -- mirroring the engine's "async serves prefetch only, cold reads metered as stall" structure, plus batch overlap) +++// pin protocol (slots in compute are unevictable; released wholesale at the next ensure entry -- barrier quiescence premise) +++// resident blob (the non-expert region pread'd once into a private frame, killing dense mmap "retail" page faults).++// Determinism contract (same as the engine): slot-state transitions occur only on the main thread under lock; IO threads only write bytes + set terminal states; completion timing affects only++// stall (speed), never the generation result. Cross-ctx parallel decode is unguarded (documented red line; phase-2 topic).++// env: E0_POOL_MB (pool budget, 0/unset = off, zero disturbance) E0_BLOB_MB (non-expert copy-in budget, 0 = off)++// E0_IO_THREADS (default 4) E0_MEM_FLOOR_MB (watermark: when MemAvailable falls below this, trim down to 60%)++// E0_HEADS / E0_PREROUTER / E0_POOL_STATS (same meanings as v3).+ #include "moe_pool.h"+ #include "ggml.h"+++#include <errno.h>++#include <fcntl.h>+ #include <pthread.h>++#include <stdatomic.h>+ #include <stdio.h>+ #include <stdlib.h>+ #include <string.h>+ #include <sys/mman.h>++#include <time.h>+ #include <unistd.h>++ #define MOE_POOL_MAX_TENSORS 192 // 40 layers x3 (gate/up/down) = 120 @35b; headroom kept++#define MOE_Q_MAX 4096 // IO queue depth (over the limit: prefetch dropped / demand goes synchronous)++#define MOE_PIN_MAX 512 // per-ensure pin cap on slots (unique experts <= n_experts=256)++++enum { ST_EMPTY = 0, ST_LOADING = 1, ST_READY = 2, ST_FAILED = 3 };++#define SLOT_NONE (-1)++ struct slot_ent {+- char * base; // arena private frame+- int32_t expert; // -1 = free++ void * mem;++ int32_t expert; // -1 = EMPTY+ int32_t tix;+- uint64_t last_gen;+- size_t bytes;+- struct slot_ent * prev, * next;++ uint8_t state;++ uint8_t pinned;++ uint8_t prefetched; // slot claimed by prefetch (source of used/wasted accounting)++ uint8_t consumed; // prefetch consumed by acquire (counted once per slot)++ uint64_t clock;++ int32_t lru_prev, lru_next;++ uint8_t on_list;+ };++ struct tensor_pool {+- const void * key; // src0->data is stable after load; used as identity++ const void * key; // identity pointer (self-corrected by name matching at runtime)++ char name[96]; // v4 primary key: the compute tensor may be a graph copy -- pointers differ, names match++ int layer; // parsed from blk.N.++ int role; // 0 gate / 1 up / 2 down / -1 non-expert+ int fd;+ uint64_t file_off;+- size_t slice; // private-frame size (page-aligned, >= stride)++ size_t slice; // slot bytes (= stride, the equal-size premise)+ size_t stride; // per-expert step within the file+ int64_t n_experts;+- int64_t * slot_of; // [n_experts] slot index or -1 (no tearing concern under the quiesce protocol)++ int32_t *slot; // [n_experts] -> slot number or SLOT_NONE+ long long hits, misses;+ };++ static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;+-static size_t g_cap, g_used;++static pthread_cond_t g_scv = PTHREAD_COND_INITIALIZER; // slot-terminal-state / watermark wakeup++static pthread_cond_t g_qcv = PTHREAD_COND_INITIALIZER; // IO queue wakeup++++static size_t g_cap_bytes; // converted from E0_POOL_MB++static size_t g_slice; // fixed at first registration (equal-size)+ static char * g_arena;+-static size_t g_bump;+-static uint64_t g_gen;++static struct slot_ent * g_slots;++static int g_nslots, g_used_slots;++static int32_t g_empty_cursor;++static int32_t g_lru_head = SLOT_NONE, g_lru_tail = SLOT_NONE; // contains READY/FAILED only++static uint64_t g_clock;++static int32_t g_inflight;++static int g_ready, g_io_on, g_stop;++static long long g_stuckq; // cumulative count of inflight>0 with both queues empty (tasks vanished)++++static int g_qd[64]; static int g_qdh, g_qdt, g_qdn; // demand-dedicated queue (higher priority)++static int g_qp[MOE_Q_MAX]; static int g_qph, g_qpt, g_qpn; // prefetch main queue+++ static struct tensor_pool g_tp[MOE_POOL_MAX_TENSORS];+ static int g_ntp;+-static struct slot_ent ** g_slots; static int g_nslots, g_slotcap;+-static struct slot_ent * g_lru_head, * g_lru_tail;+-static int g_ready;+-static long long g_loads, g_evicts, g_bytes_loaded;++static int32_t g_pins[MOE_PIN_MAX]; static int g_npins;++-static size_t align_up(size_t x) { return (x + 4095) & ~(size_t)4095; }++// accounting (subset aligned with the engine's PoolMetrics)++static long long g_loads, g_evicts, g_trims;++static long long g_flash; // bytes admitted to the pool (worker + synchronous)++static long long g_iofail;++static long long g_stall_ns; // cumulative main-thread read waits (~ the engine's stall/acq metric)++static long long g_pf_issued, g_pf_used, g_pf_waste, g_pf_drop, g_pf_miss, g_rescue;++++// resident blob (copy-in of the non-expert region)++static char * g_blob; static size_t g_blob_cap, g_blob_bump; static int g_blob_on;++static volatile int g_heads_on, g_pred_enabled; // referenced early by init (defined in the pred section)++++static uint64_t now_ns(void) {++ struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);++ return (uint64_t) ts.tv_sec * 1000000000ull + (uint64_t) ts.tv_nsec;++}++ void moe_pool_init(void) {+ if (g_ready) return;+ const char * e = getenv("E0_POOL_MB");+ size_t mb = e ? (size_t) atol(e) : 0;++ const char * be = getenv("E0_BLOB_MB");++ size_t bmb = be ? (size_t) atol(be) : 0;++ if (bmb) {++ g_blob_cap = bmb * 1024 * 1024;++ void * m = mmap(NULL, g_blob_cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);++ if (m != MAP_FAILED) { g_blob = m; g_blob_on = 1; }++ }+ if (!mb) return;+- g_cap = mb * 1024 * 1024;+- void * m = mmap(NULL, g_cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+- if (m == MAP_FAILED) return;+- g_arena = m; g_ready = 1;++ g_cap_bytes = mb * 1024 * 1024; // slots are created at first registration (once slice is known)++ if (getenv("E0_POOL_STATS")) fprintf(stderr, "moe_pool init: pool_mb=%zu blob_on=%d heads_on=%d pred=%d\n", mb, g_blob_on, g_heads_on, g_pred_enabled);++ const char * hp = getenv("E0_HEADS");++ if (hp && hp[0]) {++ moe_pool_load_heads(hp);++ }+ }++-int moe_pool_enabled(void) { return g_ready; }+ static struct tensor_pool * find_tp(const struct ggml_tensor * t);+++int moe_pool_enabled(void) { return g_ready; }++int moe_pool_blob_enabled(void) { return g_blob_on; }++++void * moe_pool_blob_add(size_t nbytes) {++ if (!g_blob_on || !nbytes) return NULL;++ const size_t need = (nbytes + 4095) & ~(size_t)4095;++ if (g_blob_bump + need > g_blob_cap) return NULL; // budget exhausted: this tensor stays in mmap (see dump for accounting)++ void * p = g_blob + g_blob_bump;++ g_blob_bump += need;++ return p;++}++++// ===================== v3 -> v4: predictive prefetch engine (advisory head; the pool is read-only and never touches logits) =====================++// Math = PREROUTER_SPEC sec.2: logits = linear_init(x) + fc2(gelu_erf(fc1(x))),++// x = [m_in(2048) | cur_onehot(256) | prev_onehot(256)]; the top-K prediction set is used only for prefetch; routing remains teacher.++#include <math.h>++#define PRED_RINGSZ 128++struct pred_job {++ int layer;++ int ntok;++ float x[2560]; // feats: 0..2047 = m_in last-token row, 2048..2303 = cur_oh, 2304..2559 = prev_oh++ int32_t cur_ids[8]; int n_cur;++ int32_t prev_ids[8]; int n_prev;++};++static struct {++ int bound;++ const struct ggml_tensor * min;++ int64_t tix[3]; // g_tp indices of gate/up/down, filled back at registration++ struct { const uint16_t * fc1, * fc2, * lin; } hd;++ int32_t prev_exec[8]; int n_prev;++} g_lr[64];++static struct pred_job g_ring[PRED_RINGSZ];++static volatile int g_ring_head, g_ring_tail, g_worker_on;++static char * g_headmap; static size_t g_headmap_sz;++++static void * pred_worker(void * arg);++struct tensor_pool;++void moe_pool_prefetch_impl(struct tensor_pool * p, int64_t e);++++int moe_pool_load_heads(const char * path) {++ int fd = open(path, O_RDONLY);++ if (fd < 0) return 0;++ size_t sz = (size_t) lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET);++ void * m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);++ close(fd);++ if (m == MAP_FAILED) return 0;++ g_headmap = m; g_headmap_sz = sz;++ uint32_t magic; memcpy(&magic, m, 4);++ if (magic != 0x44483045u) return 0;++ int n; memcpy(&n, (char *) m + 4, 4);++ size_t off = 8;++ for (int i = 0; i < n; i++) {++ int layer; memcpy(&layer, (char *) m + off, 4); off += 4;++ uint32_t l1, l2, l3;++ memcpy(&l1, (char *) m + off, 4); memcpy(&l2, (char *) m + off + 4, 4); memcpy(&l3, (char *) m + off + 8, 4);++ off += 12;++ if (layer >= 0 && layer < 64) {++ g_lr[layer].hd.fc1 = (const uint16_t *) ((char *) m + off);++ g_lr[layer].hd.fc2 = (const uint16_t *) ((char *) m + off + l1);++ g_lr[layer].hd.lin = (const uint16_t *) ((char *) m + off + l1 + l2);++ }++ off += (size_t) l1 + l2 + l3;++ }++ g_heads_on = 1;++ g_pred_enabled = getenv("E0_PREROUTER") != NULL;++ return 1;++}++++void moe_pool_bind_min(int layer, const struct ggml_tensor * t) {++ if (layer >= 0 && layer < 64) { g_lr[layer].min = t; g_lr[layer].bound = 1; }++}++++void moe_pool_note_routing(const struct ggml_tensor * src0, const int32_t * ids, int n_ids) {++ static int s_nr1;++ if (getenv("E0_POOL_STATS") && !s_nr1) { s_nr1 = 1; fprintf(stderr, "moe_pool note#1: pred=%d heads=%d n_ids=%d name=%s\n", g_pred_enabled, g_heads_on, n_ids, src0->name); }++ if (!g_pred_enabled || !g_heads_on || n_ids <= 0 || n_ids > 8) return;++ int layer = -1; const char * q = strstr(src0->name, "blk.");++ if (q) layer = (int) strtol(q + 4, NULL, 10);++ if (layer < 0 || layer >= 64) return;++ if (!g_lr[layer].bound || !g_lr[layer].min || !g_lr[layer].hd.fc1) return;++ const struct ggml_tensor * min = g_lr[layer].min;++ if (!min->data) return;++ const int64_t n_embd = min->ne[0];++ if (n_embd > 2048 || min->ne[1] < 1) return;++ pthread_mutex_lock(&g_lock);++ if (g_ring_head - g_ring_tail >= PRED_RINGSZ) { pthread_mutex_unlock(&g_lock); return; } // backpressure: drop the prefetch++ struct pred_job * j = &g_ring[g_ring_head % PRED_RINGSZ];++ g_ring_head++;++ j->layer = layer; j->n_cur = n_ids;++ const float * row = (const float *) ((const char *) min->data + (min->ne[1] - 1) * min->nb[1]);++ memcpy(j->x, row, (size_t) n_embd * sizeof(float));++ memset(j->x + n_embd, 0, (2048 - (size_t) n_embd) * sizeof(float));++ memset(&j->x[2048], 0, (2560 - 2048) * sizeof(float));++ for (int i = 0; i < n_ids; i++) if (ids[i] >= 0 && ids[i] < 256) j->x[2048 + ids[i]] = 1.0f;++ j->n_prev = g_lr[layer].n_prev;++ for (int i = 0; i < j->n_prev; i++) {++ const int32_t e = g_lr[layer].prev_exec[i];++ if (e >= 0 && e < 256) j->x[2304 + e] = 1.0f;++ }++ memcpy(j->cur_ids, ids, (size_t) n_ids * sizeof(int32_t));++ memcpy(g_lr[layer].prev_exec, ids, (size_t) n_ids * sizeof(int32_t)); // teacher facts go into prev++ g_lr[layer].n_prev = n_ids;++ if (!g_worker_on) {++ g_worker_on = 1;++ pthread_t th;++ pthread_create(&th, NULL, pred_worker, NULL);++ pthread_detach(th);++ }++ pthread_mutex_unlock(&g_lock);++}++++static inline float f16tof(uint16_t h) {++ const uint32_t w = (uint32_t) h << 16;++ float f; memcpy(&f, &w, 4); return f;++}++static inline float gelu_erf_f(float x) { return 0.5f * x * (1.0f + erff(x * 0.70710678118654752440f)); }++++static void pred_do_job(struct pred_job * j) {++ float h[512], out[256];++ const uint16_t * fc1 = g_lr[j->layer].hd.fc1;++ const uint16_t * fc2 = g_lr[j->layer].hd.fc2;++ const uint16_t * lin = g_lr[j->layer].hd.lin;++ for (int o = 0; o < 512; o++) {++ const uint16_t * wrow = fc1 + (size_t) o * 2560;++ float acc = 0;++ for (int i = 0; i < 2560; i++) acc += f16tof(wrow[i]) * j->x[i];++ h[o] = gelu_erf_f(acc);++ }++ for (int o = 0; o < 256; o++) {++ const uint16_t * wr = lin + (size_t) o * 2560;++ const uint16_t * wc = fc2 + (size_t) o * 512;++ float acc = 0;++ for (int i = 0; i < 2560; i++) acc += f16tof(wr[i]) * j->x[i];++ for (int i = 0; i < 512; i++) acc += f16tof(wc[i]) * h[i];++ out[o] = acc;++ }++ int top[8]; float tv[8]; for (int k = 0; k < 8; k++) { tv[k] = -1e30f; top[k] = -1; }++ for (int e = 0; e < 256; e++) {++ for (int k = 0; k < 8; k++) {++ if (out[e] > tv[k]) {++ for (int m = 7; m > k; m--) { tv[m] = tv[m-1]; top[m] = top[m-1]; }++ tv[k] = out[e]; top[k] = e; break;++ }++ }++ }++ for (int k = 0; k < 8; k++) {++ if (top[k] < 0) break;++ for (int role = 0; role < 3; role++) {++ const int64_t tix = g_lr[j->layer].tix[role];++ if (tix < 0) continue;++ moe_pool_prefetch_impl(&g_tp[tix], top[k]);++ }++ }++}++++static void * pred_worker(void * arg) {++ (void) arg;++ while (1) {++ int head_i = -1;++ pthread_mutex_lock(&g_lock);++ if (g_ring_head > g_ring_tail) head_i = g_ring_tail++;++ pthread_mutex_unlock(&g_lock);++ if (head_i < 0) { usleep(200); continue; }++ pred_do_job(&g_ring[head_i % PRED_RINGSZ]);++ }++ return NULL;++}++++// ===================== slot / LRU / queue core (v4) =====================++++static void list_unlink(int32_t i) {++ struct slot_ent * s = &g_slots[i];++ if (!s->on_list) return;++ if (s->lru_prev != SLOT_NONE) g_slots[s->lru_prev].lru_next = s->lru_next; else g_lru_head = s->lru_next;++ if (s->lru_next != SLOT_NONE) g_slots[s->lru_next].lru_prev = s->lru_prev; else g_lru_tail = s->lru_prev;++ s->lru_prev = s->lru_next = SLOT_NONE; s->on_list = 0;++}++static void list_push_back(int32_t i) {++ struct slot_ent * s = &g_slots[i];++ if (s->on_list) list_unlink(i);++ s->lru_prev = g_lru_tail; s->lru_next = SLOT_NONE;++ if (g_lru_tail != SLOT_NONE) g_slots[g_lru_tail].lru_next = i; else g_lru_head = i;++ g_lru_tail = i; s->on_list = 1;++}++static void account_evict(struct slot_ent * s) { // same as the engine's account_prefetch_eviction++ if (s->prefetched && !s->consumed) g_pf_miss++;++ s->prefetched = 0; s->consumed = 0;++}++static int32_t evict_victim_locked(void) { // first non-pinned entry at the LRU head (chain contains READY/FAILED only)++ for (int32_t i = g_lru_head; i != SLOT_NONE; ) {++ int32_t nxt = g_slots[i].lru_next;++ if (!g_slots[i].pinned) return i;++ i = nxt;++ }++ return SLOT_NONE;++}++static void unclaim_locked(int32_t si) { // claim a slot then back out (e.g. queue full)++ struct slot_ent * s = &g_slots[si];++ g_tp[s->tix].slot[s->expert] = SLOT_NONE;++ account_evict(s);++ s->state = ST_EMPTY; s->expert = -1; s->tix = -1;++ g_used_slots--;++}++// Claim a slot for (tix,e): EMPTY cursor first, then the non-pinned LRU head (READY/FAILED). LOADING is never evictable.++static int32_t claim_slot_locked(int tix, int32_t e) {++ int32_t si = SLOT_NONE;++ for (int t = 0; t < g_nslots; t++) {++ int32_t i = (g_empty_cursor + t) % g_nslots;++ if (g_slots[i].state == ST_EMPTY) { si = i; g_empty_cursor = (i + 1) % g_nslots; g_used_slots++; break; }++ }++ if (si < 0) {++ si = evict_victim_locked();++ if (si < 0) return SLOT_NONE;++ struct slot_ent * vs = &g_slots[si];++ g_tp[vs->tix].slot[vs->expert] = SLOT_NONE;++ if (vs->state == ST_READY) g_evicts++;++ account_evict(vs);++ list_unlink(si);++ }++ struct slot_ent * s = &g_slots[si];++ s->tix = tix; s->expert = e; s->state = ST_LOADING;++ s->pinned = 0; s->prefetched = 0; s->consumed = 0; s->clock = ++g_clock;++ g_tp[tix].slot[e] = si;++ return si;++}++static int enqueue_io_locked(int32_t si, int demand) { // demand=1 goes to the dedicated queue (popped first)++ if (demand) {++ if (g_qdn >= 64) return 0;++ g_qd[g_qdt] = si; g_qdt = (g_qdt + 1) % 64; g_qdn++;++ } else {++ if (g_qpn >= MOE_Q_MAX) return 0;++ g_qp[g_qpt] = si; g_qpt = (g_qpt + 1) % MOE_Q_MAX; g_qpn++;++ }++ g_inflight++;++ pthread_cond_broadcast(&g_qcv);++ return 1;++}++static ssize_t pread_full(int fd, void * dst, size_t n, off_t off) {++ size_t got = 0;++ int tries = 0;++ while (got < n) {++ ssize_t r = pread(fd, (char *) dst + got, n - got, off + (off_t) got);++ if (r > 0) { got += (size_t) r; continue; }++ if (r == 0) break; // EOF: real failure++ if (errno == EINTR) continue;++ if (++tries < 200) { struct timespec ts = { 0, 1000000 }; nanosleep(&ts, NULL); continue; }++ static int s_once;++ if (!s_once) { s_once = 1; fprintf(stderr, "moe_pool pread ERRNO=%d fd=%d off=%lld\n", errno, fd, (long long) off); }++ break; // permanent error: give up (FAILED -> kernel fallback, never hangs)++ }++ return (ssize_t) got == n ? (ssize_t) n : -1;++}++static void slot_finalize_locked(int32_t si, int ok) {++ static int s_fin8;++ if (getenv("E0_POOL_STATS") && s_fin8 < 8) { s_fin8++; fprintf(stderr, "moe_pool io-fin#%d: slot=%d ok=%d qn=%d inf=%d\n", s_fin8, si, ok, g_qdn + g_qpn, g_inflight); }++ struct slot_ent * s = &g_slots[si];++ if (ok) { s->state = ST_READY; g_flash += g_slice; }++ else { s->state = ST_FAILED; g_iofail++; }++ list_push_back(si);++ if (g_inflight > 0) g_inflight--;++ pthread_cond_broadcast(&g_scv);++}++// synchronous read on the main thread outside the lock (same as the engine's sync_load_locked; no one can move a LOADING slot, so it's safe)++static int load_sync_locked(int32_t si) {++ struct slot_ent * s = &g_slots[si];++ struct tensor_pool * p = &g_tp[s->tix];++ const uint64_t off = p->file_off + (uint64_t) s->expert * p->stride;++ pthread_mutex_unlock(&g_lock);++ const ssize_t got = pread_full(p->fd, s->mem, p->slice, (off_t) off);++ pthread_mutex_lock(&g_lock);++ if (got == (ssize_t) p->slice) { g_loads++; slot_finalize_locked(si, 1); return 1; }++ slot_finalize_locked(si, 0);++ return 0;++}++static void wait_ready_locked(int32_t si) {++ const uint64_t t0 = now_ns();++ while (g_slots[si].state == ST_LOADING && !g_stop) { if (g_inflight > 0 && g_qdn == 0 && g_qpn == 0) { g_stuckq++; if (g_stuckq < 6) fprintf(stderr, "moe_pool STUCKQ#%lld: si=%d infl=%d used=%d\n", g_stuckq, si, g_inflight, g_used_slots); } pthread_cond_wait(&g_scv, &g_lock); }++ g_stall_ns += (long long) (now_ns() - t0);++}++static void pin_locked(int32_t si) {++ struct slot_ent * s = &g_slots[si];++ if (s->pinned) return;++ s->pinned = 1;++ if (g_npins < MOE_PIN_MAX) g_pins[g_npins++] = si;++}++++static void * io_thread(void * arg) {++ (void) arg;++ for (;;) {++ int32_t si;++ pthread_mutex_lock(&g_lock);++ while (g_qdn + g_qpn == 0 && !g_stop) pthread_cond_wait(&g_qcv, &g_lock);++ if (g_stop) { pthread_mutex_unlock(&g_lock); return NULL; }++ if (g_qdn > 0) { si = g_qd[g_qdh]; g_qdh = (g_qdh + 1) % 64; g_qdn--; }++ else if (g_qpn > 0) { si = g_qp[g_qph]; g_qph = (g_qph + 1) % MOE_Q_MAX; g_qpn--; }++ else { pthread_mutex_unlock(&g_lock); continue; }++ struct slot_ent * s = &g_slots[si];++ const int fd = g_tp[s->tix].fd;++ const uint64_t off = g_tp[s->tix].file_off + (uint64_t) s->expert * g_tp[s->tix].stride;++ void * mem = s->mem;++ const size_t slice = g_slice;++ pthread_mutex_unlock(&g_lock);++ const ssize_t got = pread_full(fd, mem, slice, (off_t) off);++ pthread_mutex_lock(&g_lock);++ if (g_slots[si].state == ST_LOADING && g_slots[si].mem == mem) {++ if (got == (ssize_t) slice) { g_loads++; slot_finalize_locked(si, 1); }++ else slot_finalize_locked(si, 0);++ } else {++ if (g_inflight > 0) g_inflight--; // main thread already voided it: this read's result is discarded++ pthread_cond_broadcast(&g_scv);++ }++ pthread_mutex_unlock(&g_lock);++ }++}++++static long long mem_avail_mb(void) {++ FILE * f = fopen("/proc/meminfo", "r");++ if (!f) return -1;++ char ln[256]; long long v = -1;++ while (fgets(ln, sizeof(ln), f)) {++ if (!strncmp(ln, "MemAvailable:", 13)) { v = atoll(ln + 13) / 1024; break; }++ }++ fclose(f);++ return v;++}++// watermark trim (simplified form of the engine's trim): evict only non-pinned READY; no physical frame reclaim (the arena middle is not contiguous -- see ALIGNMENT.md).++static void water_trim_locked(void) {++ const char * fe = getenv("E0_MEM_FLOOR_MB");++ if (!fe) return;++ const long long floor_mb = atoll(fe);++ if (floor_mb <= 0) return;++ const long long avail = mem_avail_mb();++ if (avail < 0 || avail >= floor_mb) return;++ const int target = (int) (g_nslots * 6 / 10);++ int n = 0;++ while (g_used_slots > target) {++ int32_t v = SLOT_NONE;++ for (int32_t i = g_lru_head; i != SLOT_NONE; ) {++ int32_t nxt = g_slots[i].lru_next;++ if (!g_slots[i].pinned) { v = i; break; }++ i = nxt;++ }++ if (v < 0) break;++ struct slot_ent * s = &g_slots[v];++ g_tp[s->tix].slot[s->expert] = SLOT_NONE;++ account_evict(s);++ list_unlink(v);++ s->state = ST_EMPTY; s->expert = -1;++ g_used_slots--; g_trims++; n++;++ }++ if (n) fprintf(stderr, "moe_pool trim: evicted=%d used=%d MemAvailable=%lldMB\n", n, g_used_slots, avail);++}++++// ===================== public API =====================+++ void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off) {+- if (!g_ready) return;+- if (t->ne[2] < 8) return; // expert-stack shape+- if (find_tp(t)) return; // idempotent: same pointer never re-registered++ if (!g_cap_bytes) return;++ if (getenv("E0_POOL_STATS") && g_ntp == 0) {++ fprintf(stderr, "moe_pool reg#1: %s ne2=%lld nbytes=%zu\n", t->name, (long long) t->ne[2], (size_t) ggml_nbytes(t));++ }++ if (t->ne[2] < 8) return; // expert-stack shape++ if (find_tp(t)) return; // idempotent: same pointer never re-registered+ const size_t total = (size_t) ggml_nbytes(t);+ const size_t stride = total / (size_t) t->ne[2];+- // conservative gate: pool only when the expert slice is naturally page-aligned (holds for this artifact); otherwise leave it to the kernel+- if (stride % 4096) return;+- const size_t slice = stride;++ if (stride % 4096) return; // conservative gate: only page-aligned slices get pooled (holds for this artifact)++ if (!g_ready) { // fixed at first registration: equal-size slot array++ g_slice = stride;++ g_nslots = (int) (g_cap_bytes / g_slice);++ g_arena = mmap(NULL, g_slice * (size_t) g_nslots, PROT_READ | PROT_WRITE,++ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);++ if (g_arena == MAP_FAILED) { g_arena = NULL; g_nslots = 0; return; }++ g_slots = calloc((size_t) g_nslots, sizeof(struct slot_ent));++ for (int i = 0; i < g_nslots; i++) { g_slots[i].mem = g_arena + (size_t) i * g_slice; g_slots[i].expert = -1; g_slots[i].tix = -1; }++ g_ready = 1;++ const char * ie = getenv("E0_IO_THREADS");++ int nth = ie ? (int) atol(ie) : 4;++ if (nth < 1) nth = 1; if (nth > 8) nth = 8;++ if (!g_io_on) {++ g_io_on = 1;++ for (int i = 0; i < nth; i++) {++ pthread_t th; pthread_create(&th, NULL, io_thread, NULL); pthread_detach(th);++ }++ }++ }++ if (stride != g_slice) return; // the v4 premise is equal-size slots (same as the engine); odd-shaped tensors go to the kernel+ pthread_mutex_lock(&g_lock);+ if (g_ntp >= MOE_POOL_MAX_TENSORS) { pthread_mutex_unlock(&g_lock); return; }+ struct tensor_pool * p = &g_tp[g_ntp++];+- p->key = t->data; p->fd = fd; p->file_off = file_off; p->slice = slice; p->stride = stride;++ p->layer = -1; p->role = -1;++ { const char * q = strstr(t->name, "blk."); if (q) p->layer = (int) strtol(q + 4, NULL, 10); }++ if (strstr(t->name, "gate_exps")) p->role = 0;++ else if (strstr(t->name, "up_exps")) p->role = 1;++ else if (strstr(t->name, "down_exps")) p->role = 2;++ if (p->role >= 0 && p->layer >= 0 && p->layer < 64) {++ g_lr[p->layer].tix[p->role] = g_ntp - 1;++ }++ p->key = t->data; snprintf(p->name, sizeof(p->name), "%s", t->name); p->fd = dup(fd); // independent ownership: pread still works after the loader closed its fd (v4 hang incident) p->file_off = file_off; p->slice = stride; p->stride = stride;+ p->n_experts = t->ne[2];+- p->slot_of = calloc(p->n_experts, sizeof(int64_t));+- for (int64_t i = 0; i < p->n_experts; i++) p->slot_of[i] = -1;++ p->slot = calloc((size_t) p->n_experts, sizeof(int32_t));++ for (int64_t i = 0; i < p->n_experts; i++) p->slot[i] = SLOT_NONE;++ if (getenv("E0_POOL_STATS") && g_ntp <= 2) {++ fprintf(stderr, "moe_pool reg-ok#%d: %s nslots=%d\n", g_ntp, t->name, g_nslots);++ }+ pthread_mutex_unlock(&g_lock);+ }++ static struct tensor_pool * find_tp(const struct ggml_tensor * t) {+ for (int i = 0; i < g_ntp; i++) if (g_tp[i].key == t->data) return &g_tp[i];++ // v4: the tensor used by compute may be a graph copy (pointer != load-time set) -- match by name and re-bind the pointer++ for (int i = 0; i < g_ntp; i++) {++ if (!strcmp(g_tp[i].name, t->name)) { g_tp[i].key = t->data; return &g_tp[i]; }++ }+ return NULL;+ }++@@ -95,115 +538,152 @@ int moe_pool_pooled(const struct ggml_tensor * t) {+ return find_tp(t) != NULL;+ }++-// ---- LRU ----+-static void lru_unlink(struct slot_ent * s) {+- if (s->prev) s->prev->next = s->next; else g_lru_head = s->next;+- if (s->next) s->next->prev = s->prev; else g_lru_tail = s->prev;+- s->prev = s->next = NULL;+-}+-static void lru_front(struct slot_ent * s) {+- s->prev = NULL; s->next = g_lru_head;+- if (g_lru_head) g_lru_head->prev = s; else g_lru_tail = s;+- g_lru_head = s;+-}+-+-static struct slot_ent * slot_alloc(size_t bytes, int tix, int force) {+- struct slot_ent * s = NULL;+- for (int i = 0; i < g_nslots; i++) { // first pick a free slot of the same size+- if (g_slots[i]->expert == -1 && g_slots[i]->bytes == bytes) { s = g_slots[i]; break; }+- }+- if (!s && g_bump + bytes <= g_cap) { // then bump-allocate+- s = calloc(1, sizeof(*s));+- s->base = g_arena + g_bump; g_bump += bytes; s->bytes = bytes;+- if (g_nslots == g_slotcap) {+- g_slotcap = g_slotcap ? g_slotcap * 2 : 512;+- g_slots = realloc(g_slots, (size_t) g_slotcap * sizeof(*g_slots));+- }+- g_slots[g_nslots++] = s;+- }+- if (!s) { // finally evict an older-generation LRU entry+- for (struct slot_ent * c = g_lru_tail; c; c = c->prev) {+- if (c->expert < 0) continue;+- if (c->last_gen == g_gen && !force) continue; // demand mode: allow evicting stale entries of THIS generation (just-used rows were already bumped to the LRU head)+- g_tp[c->tix].slot_of[c->expert] = -1;+- g_used -= c->bytes;+- s = c; break;+- }+- if (s) { g_evicts++; }+- }+- if (!s) return NULL; // pool full this generation / huge block: kernel backstop+- if (s->expert >= 0) lru_unlink(s);+- s->tix = tix; s->expert = -1;+- g_used += s->bytes;+- return s;+-}+-+ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_ids) {+- if (!g_ready) return;++ if (!g_ready || n_ids <= 0) return;+ pthread_mutex_lock(&g_lock);+- g_gen++;++ // release all pins from the previous node wholesale (barrier quiescence premise: all compute threads of the previous tensor finished)++ for (int i = 0; i < g_npins; i++) g_slots[g_pins[i]].pinned = 0;++ g_npins = 0;+ struct tensor_pool * p = find_tp(t);++ static int s_np;++ if (getenv("E0_POOL_STATS") && s_np < 3) { s_np++; fprintf(stderr, "moe_pool ensure#%d: %s ptr=%p buf=%p ntp=%d key0=%p\n", s_np, t->name, t->data, (void*)t->buffer, g_ntp, g_ntp ? g_tp[0].key : NULL); }+ if (!p) { pthread_mutex_unlock(&g_lock); return; }+ const int tix = (int) (p - g_tp);+- // demand-exclusive mode: small batches (decode 1~4 tok) evict-old/admit-new with no mmap fallback -- pool = the only path to experts (flash-pool requirements 1 and 3)+- // large batches (prefill) load best-effort: whatever doesn't fit is left to the kernel, preventing cross-layer ping-pong+- const int demand = n_ids <= 16;++ const int exclusive = n_ids <= 16; // decode: demand-exclusive; prefill: best-effort+ static long s_calls;+ if (getenv("E0_POOL_STATS") && (++s_calls % 2000) == 0) {+- long long h = 0, m = 0, l = 0, e = 0, bl = 0; size_t cap = 0, used = 0;+- moe_pool_stats(&h, &m, &l, &e, &bl, &cap, &used);+- fprintf(stderr, "moe_pool@%ld: hits=%lld misses=%lld loads=%lld evicts=%lld used_mb=%zu\n",+- s_calls, h, m, l, e, used / (1024 * 1024));++ long long h = 0, m = 0;++ for (int i = 0; i < g_ntp; i++) { h += g_tp[i].hits; m += g_tp[i].misses; }++ fprintf(stderr, "moe_pool@%ld: hits=%lld misses=%lld loads=%lld evicts=%lld used_mb=%zu"++ " stall_ms=%lld pf=%lld/%lld/%lld/%lld flash_mb=%lld trims=%lld\n",++ s_calls, h, m, g_loads, g_evicts, (size_t) g_used_slots * g_slice / (1024 * 1024),++ g_stall_ns / 1000000, g_pf_issued, g_pf_used, g_pf_waste, g_pf_miss,++ g_flash / (1024 * 1024), g_trims);+ }++ water_trim_locked();++++ int32_t waiters[64]; int nwait = 0; // slots enqueued in this batch; awaited together after dispatch (queue parallelism)+ for (int i = 0; i < n_ids; i++) {+ const int32_t e = ids[i];+ if (e < 0 || e >= p->n_experts) continue;+- if (p->slot_of[e] >= 0) { // hit (slot_of = slot_ent address)+- p->hits++;+- struct slot_ent * s = (struct slot_ent *) p->slot_of[e];+- if (s->last_gen != g_gen) { lru_unlink(s); lru_front(s); s->last_gen = g_gen; }++ int32_t si = p->slot[e];++ if (si >= 0) { // already in the pool++ struct slot_ent * s = &g_slots[si];++ if (s->state == ST_READY) {++ p->hits++;++ if (s->prefetched && !s->consumed) { g_pf_used++; s->consumed = 1; }++ list_push_back(si);++ pin_locked(si);++ continue;++ }++ if (s->state == ST_LOADING) { // wait for the async prefetch (same as the engine)++ pin_locked(si);++ g_rescue++;++ wait_ready_locked(si);++ if (s->state == ST_FAILED && !load_sync_locked(si)) break;++ p->hits++;++ if (s->prefetched && !s->consumed) { g_pf_used++; s->consumed = 1; }++ list_push_back(si);++ continue;++ }++ // stale FAILED slot: reload synchronously++ pin_locked(si);++ g_rescue++;++ if (!load_sync_locked(si)) break;++ p->hits++; list_push_back(si);+ continue;+ }++ // cold path: claim a slot + enqueue (or synchronous when the queue is full)+ p->misses++;+- struct slot_ent * s = slot_alloc(p->slice, tix, demand);+- if (!s) break;+- const off_t off = (off_t) (p->file_off + (uint64_t) e * p->stride);+- const ssize_t got = pread(p->fd, s->base, p->slice, off);+- if (got != (ssize_t) p->slice) { s->expert = -1; break; }+- s->expert = e; s->last_gen = g_gen;+- lru_front(s);+- g_loads++; g_bytes_loaded += got;+- p->slot_of[e] = (int64_t) (intptr_t) s;++ int32_t slot;++ for (;;) {++ slot = claim_slot_locked(tix, e);++ if (slot >= 0) break;++ if (!exclusive || g_inflight <= 0) break;++ static int s_c40;++ if (getenv("E0_POOL_STATS") && s_c40 < 40) { s_c40++; fprintf(stderr, "moe_pool corner: infl=%d used=%d qd=%d qp=%d\n", g_inflight, g_used_slots, g_qdn, g_qpn); }++ pthread_cond_wait(&g_scv, &g_lock);++ }++ if (slot < 0) continue;++ pin_locked(slot);++ if (enqueue_io_locked(slot, 1)) {++ if (nwait < 64) waiters[nwait++] = slot;++ else wait_ready_locked(slot); // rare window overrun: wait in place++ } else {++ if (!load_sync_locked(slot)) break;++ }++ }++ static int s_nw8;++ if (getenv("E0_POOL_STATS") && s_nw8 < 4) { s_nw8++; fprintf(stderr, "moe_pool enq-done#%d: nwait=%d miss=%d qn=%d inf=%d\n", s_nw8, nwait, p->misses, g_qdn + g_qpn, g_inflight); }++ for (int i = 0; i < nwait; i++) {++ static int s_w400;++ if (getenv("E0_POOL_STATS") && s_w400 < 400) { s_w400++; fprintf(stderr, "moe_pool w: slot=%d st=%d infl=%d qd=%d qp=%d\n", waiters[i], (int)g_slots[waiters[i]].state, g_inflight, g_qdn, g_qpn); }++ wait_ready_locked(waiters[i]);++ struct slot_ent * s = &g_slots[waiters[i]];++ if (s->state == ST_FAILED && !load_sync_locked(waiters[i])) break;+ }+ pthread_mutex_unlock(&g_lock);+ }+++// prefetch entry (called by pred_worker): enqueue and return immediately, never waits; dropped if there is no room (acquire backstops).++void moe_pool_prefetch_impl(struct tensor_pool * p, int64_t e) {++ if (!g_ready || e < 0 || e >= p->n_experts) return;++ const int tix = (int) (p - g_tp);++ pthread_mutex_lock(&g_lock);++ const int32_t si = p->slot[e];++ if (si >= 0) {++ if (g_slots[si].state == ST_FAILED) { // failed slot: retry once (enqueue)++ g_slots[si].state = ST_LOADING;++ if (!enqueue_io_locked(si, 0)) {++ load_sync_locked(si);++ }++ }++ g_pf_waste++;++ pthread_mutex_unlock(&g_lock);++ return;++ }++ if (g_qpn > 64) { g_pf_drop++; pthread_mutex_unlock(&g_lock); return; } // throttle: drop prefetches when the main queue backs up++ g_pf_issued++;++ const int32_t slot = claim_slot_locked(tix, (int32_t) e);++ if (slot < 0) { g_pf_drop++; pthread_mutex_unlock(&g_lock); return; }++ g_slots[slot].prefetched = 1;++ if (!enqueue_io_locked(slot, 0)) { unclaim_locked(slot); g_pf_drop++; }++ pthread_mutex_unlock(&g_lock);++}+++ const void * moe_pool_row_ptr(const struct ggml_tensor * t, int64_t expert, const void * def) {+ if (!g_ready || expert < 0) return def;+ const struct tensor_pool * p = find_tp(t);+ if (!p || expert >= p->n_experts) return def;+- const int64_t si = p->slot_of[expert];++ const int32_t si = p->slot[expert];+ if (si < 0) return def;+- const struct slot_ent * s = (const struct slot_ent *) si;+- return (s->expert == expert) ? s->base : def; // always true under the quiesce protocol; kept as a defensive check++ const struct slot_ent * s = &g_slots[si];++ return (s->state == ST_READY && s->expert == expert) ? s->mem : def;+ }++ void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,+ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes) {+ long long h = 0, m = 0;+ for (int i = 0; i < g_ntp; i++) { h += g_tp[i].hits; m += g_tp[i].misses; }+- if (hits) *hits = h; if (misses) *misses = m;+- if (loads) *loads = g_loads; if (evicts) *evicts = g_evicts;+- if (bytes_loaded) *bytes_loaded = g_bytes_loaded;+- if (cap_bytes) *cap_bytes = g_cap; if (used_bytes) *used_bytes = g_used;++ if (hits) *hits = h;++ if (misses) *misses = m;++ if (loads) *loads = g_loads;++ if (evicts) *evicts = g_evicts;++ if (bytes_loaded) *bytes_loaded = g_flash;++ if (cap_bytes) *cap_bytes = g_cap_bytes;++ if (used_bytes) *used_bytes = (size_t) g_used_slots * g_slice;+ }++ __attribute__((destructor)) static void moe_pool_dump(void) {+- if (!g_ready || !getenv("E0_POOL_STATS")) {+- return;+- }+- long long h = 0, m = 0, l = 0, e = 0, bl = 0; size_t cap = 0, used = 0;+- moe_pool_stats(&h, &m, &l, &e, &bl, &cap, &used);+- fprintf(stderr, "moe_pool stats: hits=%lld misses=%lld loads=%lld evicts=%lld loaded_mb=%lld cap_mb=%zu used_mb=%zu\n",+- h, m, l, e, bl / (1024 * 1024), cap / (1024 * 1024), used / (1024 * 1024));++ if (!g_ready && !g_blob_on) return;++ long long h = 0, m = 0;++ for (int i = 0; i < g_ntp; i++) { h += g_tp[i].hits; m += g_tp[i].misses; }++ fprintf(stderr, "moe_pool stats: hits=%lld misses=%lld loads=%lld evicts=%lld trims=%lld stuck=%lld "++ "stall_ms=%lld pf=%lld/%lld/%lld/%lld/%lld flash_mb=%lld iofail=%lld "++ "cap_mb=%zu used_mb=%d blob_mb=%zu\n",++ h, m, g_loads, g_evicts, g_trims, g_stuckq, g_stall_ns / 1000000,++ g_pf_issued, g_pf_used, g_pf_waste, g_pf_drop, g_pf_miss,++ g_flash / (1024 * 1024), g_iofail,++ g_cap_bytes / (1024 * 1024), (int) ((size_t) g_used_slots * g_slice / (1024 * 1024)),++ g_blob_bump / (1024 * 1024));+ }+diff --git a/ggml/src/ggml-cpu/moe_pool.h b/ggml/src/ggml-cpu/moe_pool.h+index ab9f7a1..e4c48ca 100644+--- a/ggml/src/ggml-cpu/moe_pool.h++++ b/ggml/src/ggml-cpu/moe_pool.h+@@ -1,7 +1,9 @@+-// moe_pool.h -- expert demand pool (Android phase 1, no prediction; fork edge0/android-pool).++// moe_pool.h -- expert demand pool v4 (aligned with the engine streaming/expert_pool contract; fork edge0/android-pool).+ // Foundation = copy-in private frames (Android mlock RLIMIT=64KB is hard-wired; the pin-file-page design is unusable -- see PROBE B-track closure).+-// hit = zero-fault direct read of private memory; miss = ensure() bulk preads the whole block ("wholesale" ~1GB/s vs page-fault "retail" 16MB/s);+-// eviction = this pool's own LRU (whole-expert granularity, never half an expert); long-tail experts outside the pool fall back to their original mmap pages, kernel-backed (lazy pointer resolution).++// v4 design = engine-isomorphic: equal-size slot state machine (EMPTY/LOADING/READY/FAILED) + IO-thread queue (prefetch enqueues and returns;++// acquire hitting LOADING waits on a cv) + pin protocol (unevictable while in compute) + resident blob (non-expert region copy-in) +++// watermark trim + stall/prefetch metrics. Hit = zero page faults; cold read = wholesale whole blocks (batched dispatch, awaited together).++// env: E0_POOL_MB / E0_BLOB_MB / E0_IO_THREADS / E0_MEM_FLOOR_MB / E0_HEADS / E0_PREROUTER.+ #ifndef MOE_POOL_H+ #define MOE_POOL_H++@@ -30,6 +32,16 @@ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_id+ // row-base resolution: resident -> private-frame pointer; otherwise -> default_ptr (original mmap address, kernel backstop)+ const void * moe_pool_row_ptr(const struct ggml_tensor * t, int64_t expert, const void * default_ptr);+++// v4 resident blob (isomorphic to the engine's network.cpp img mirror): one copy-in per non-expert mmap-view tensor.++// E0_BLOB_MB unset / budget exhausted -> blob_add returns NULL (caller stays as-is, zero disturbance).++int moe_pool_blob_enabled(void);++void * moe_pool_blob_add(size_t nbytes);++++// phase 2: predictive prefetch (E0_HEADS weight files + E0_PREROUTER switch)++int moe_pool_load_heads(const char * path);++void moe_pool_bind_min(int layer, const struct ggml_tensor * t);++void moe_pool_note_routing(const struct ggml_tensor * src0, const int32_t * ids, int n_ids);+++ // stats snapshot (for debugging / accounting)+ void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,+ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes);+diff --git a/src/llama-model.cpp b/src/llama-model.cpp+index ec1089d..b9e0907 100644+--- a/src/llama-model.cpp++++ b/src/llama-model.cpp+@@ -7,6 +7,8 @@ extern "C" {+ void moe_pool_init(void);+ int moe_pool_enabled(void);+ void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off);++void * moe_pool_blob_add(size_t nbytes);++int moe_pool_blob_enabled(void);+ }+ #include "llama-model.h"++@@ -1891,28 +1893,60 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {+ }+ }++- // moe_pool registration (Android phase 1): expert 3D tensors -> pool. With E0_POOL_MB unset this block has no side effects.++ // moe_pool: init stays here (heads/env parsing has zero dependencies); registration and blob live in moe_wire() --++ // inside load_tensors the ml.contexts tensor set has data unbound (measured NULL); the primary set lives in tensors_by_name.+ moe_pool_init();+- if (moe_pool_enabled() && ml.use_mmap && !ml.files.empty()) {+- auto reg = [&](ggml_tensor * t) {+- if (!t || !strstr(t->name, "exps")) {+- return;+- }+- const auto * w = ml.get_weight(t->name);+- if (!w || w->idx >= ml.files.size()) {+- return;+- }+- // pread does not depend on the file cursor, so the loader's fd is safe to use directly (no dup, avoids leaks)+- moe_pool_register(t, ml.files[w->idx]->file_id(), (uint64_t) w->offs);+- };+- for (auto & ctx : ml.contexts) {+- for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t; t = ggml_get_next_tensor(ctx.get(), t)) {+- reg(t);++++ return true;++}++++// edge0 v4 (llama_model_load calls this after load_tensors): the tensors_by_name primary set now has its data pointers++// bound. Expert tensors are registered into the pool; with E0_BLOB_MB on, each non-expert mmap-view tensor gets one copy-in (isomorphic to the engine's img mirror).++void llama_model_base::moe_wire(llama_model_loader & ml) {++ if (!ml.use_mmap || ml.files.empty()) {++ return;++ }++ for (auto & [name, t] : tensors_by_name) {++ if (!t || !t->data || !strstr(t->name, "exps")) {++ continue;++ }++ const auto * w = ml.get_weight(name.c_str());++ if (!w || w->idx >= ml.files.size()) {++ continue;++ }++ // pread does not depend on the file cursor, so the loader's fd is safe to use directly (no dup, avoids leaks)++ moe_pool_register(t, ml.files[w->idx]->file_id(), (uint64_t) w->offs);++ }++ if (!moe_pool_blob_enabled()) {++ return;++ }++ size_t blob_copied = 0;++ for (auto & [name, t] : tensors_by_name) {++ if (!t || !t->data || strstr(t->name, "exps") || ggml_nbytes(t) == 0) {++ continue;++ }++ bool in_mapping = false;++ for (const auto & mapping : pimpl->mappings) {++ const uint8_t * lo = (const uint8_t *) mapping->addr();++ const uint8_t * hi = lo + mapping->size();++ const uint8_t * p = (const uint8_t *) t->data;++ if (p >= lo && p < hi) {++ in_mapping = true;++ break;+ }+ }++ if (!in_mapping) {++ continue; // heap tensors (already converted/copied) are resident anyway -- leave them alone++ }++ void * dst = moe_pool_blob_add(ggml_nbytes(t));++ if (!dst) {++ continue; // budget exhausted: stay in mmap (visible as blob_mb in the dump)++ }++ memcpy(dst, t->data, ggml_nbytes(t));++ t->data = dst;++ blob_copied += ggml_nbytes(t);+ }+-+- return true;++ fprintf(stderr, "moe_pool blob copy-in: %zu MiB\n", blob_copied / (1024 * 1024));+ }++ ggml_tensor * llama_model_base::create_tensor(llama_model_loader & ml, const LLM_TN_IMPL & tn, const std::initializer_list<int64_t> & ne, int flags) {+diff --git a/src/llama-model.h b/src/llama-model.h+index 984b2cf..47aaf83 100644+--- a/src/llama-model.h++++ b/src/llama-model.h+@@ -751,6 +751,7 @@ struct llama_model {+ bool has_tensor_overrides() const;++ const struct ggml_tensor * get_tensor(const char * name) const;++ virtual void moe_wire(llama_model_loader & ml) { (void) ml; } // edge0 v4: pool+blob registration hook++ float get_rope_freq_base (const llama_cparams & cparams, int il) const;+ float get_rope_freq_scale(const llama_cparams & cparams, int il) const;+@@ -821,6 +822,7 @@ struct llama_model_base : public llama_model {+ void load_hparams(llama_model_loader & ml) override;+ void load_vocab (llama_model_loader & ml) override;+ bool load_tensors(llama_model_loader & ml) override;++ void moe_wire(llama_model_loader & ml) override; // edge0 v4++ // model must define these+ void load_arch_hparams(llama_model_loader & ml) override = 0;+diff --git a/src/llama.cpp b/src/llama.cpp+index ad8e443..b09ffb7 100644+--- a/src/llama.cpp++++ b/src/llama.cpp+@@ -369,6 +369,7 @@ static std::pair<int, llama_model *> llama_model_load(struct gguf_context * meta+ if (!model->load_tensors(ml)) {+ return {-2, nullptr};+ }++ model->moe_wire(ml); // edge0 v4: expert pool + resident blob registration (see llama-model.cpp)++ return {0, model_ptr.release()};+ } catch (const std::exception & err) {+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0005-ggml-cpu-qwen3next-moe_pool-hooks-IQP-bypass-gate-en.patch b/patches/llama.cpp/android/0005-ggml-cpu-qwen3next-moe_pool-hooks-IQP-bypass-gate-en.patchnew file mode 100644index 0000000..9d516fd--- /dev/null+++ b/patches/llama.cpp/android/0005-ggml-cpu-qwen3next-moe_pool-hooks-IQP-bypass-gate-en.patch@@ -0,0 +1,59 @@+From cda991a728b79384b05f1cb58c1ebca34eb31a49 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 00:36:57 +0800+Subject: [PATCH 05/14] ggml-cpu/qwen3next: moe_pool hooks (IQP bypass gate,+ ensure/note at MUL_MAT_ID, row-ptr lazy resolve, layer-input bind)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++- ggml-cpu.c: #include moe_pool.h; at the MUL_MAT_ID entry thread0 runs moe_pool_ensure ++ moe_pool_note_routing before the barrier (prefetch signal; the pool reads only and never touches+ logits); row bases resolve lazily via moe_pool_row_ptr; iqf bypass gate && !moe_pool_pooled(src0)+ (pooled tensors are barred from the repack dual-track)+- qwen3next.cpp: moe_pool_bind_min after both t_layer_inp sites (feature source m_in for the+ predictor head)++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/ggml-cpu.c | 1 ++ src/models/qwen3next.cpp | 6 +++++++ 2 files changed, 7 insertions(+)++diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c+index 54f0d9a..656f780 100644+--- a/ggml/src/ggml-cpu/ggml-cpu.c++++ b/ggml/src/ggml-cpu/ggml-cpu.c+@@ -1676,6 +1676,7 @@ static void ggml_compute_forward_mul_mat_id(++ // moe_pool: demand-pool dispatch -- bulk-read this ubatch's experts (unregistered tensors return immediately)+ moe_pool_ensure(src0, (const int32_t *) ids->data, (int) (ids->ne[0] * ids->ne[1]));++ moe_pool_note_routing(src0, (const int32_t *) ids->data, (int) (ids->ne[0] * ids->ne[1]));+ }++ // reset current_chunk+diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp+index 9673e3b..c081fd5 100644+--- a/src/models/qwen3next.cpp++++ b/src/models/qwen3next.cpp+@@ -1,4 +1,9 @@+ #include "models.h"++++// moe_pool in-place declarations (phase-2 Android: the builder binds m_in; implementation in ggml-cpu/moe_pool.c)++extern "C" {++void moe_pool_bind_min(int layer, const struct ggml_tensor * t);++}+ #include "llama-memory-recurrent.h"++ void llama_model_qwen3next::load_arch_hparams(llama_model_loader & ml) {+@@ -187,6 +192,7 @@ llama_model_qwen3next::graph::graph(const llama_model & model, const llm_graph_p+ // only consumed when embeddings_layer_inp[il] is active (prerouter mode);+ // with the feature off, set_outputs() skips this slot entirely.+ res->t_layer_inp[il] = attn_post_norm;++ moe_pool_bind_min(il, res->t_layer_inp[il]);++ // FFN layer (MoE or dense) - without residual connection+ cur = build_layer_ffn(attn_post_norm, il);+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0006-moe_pool-v4.2.1-FAILED-4-LOADING-evict-file_off-SYNC.patch b/patches/llama.cpp/android/0006-moe_pool-v4.2.1-FAILED-4-LOADING-evict-file_off-SYNC.patchnew file mode 100644index 0000000..6c1144e--- /dev/null+++ b/patches/llama.cpp/android/0006-moe_pool-v4.2.1-FAILED-4-LOADING-evict-file_off-SYNC.patch@@ -0,0 +1,91 @@+From a07f9c8ad77f4ec1b169a540626cc172932071d3 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 01:18:49 +0800+Subject: [PATCH 06/14] =?UTF-8?q?moe=5Fpool=20v4.2.1:=20FAILED=20=E9=87=8D?=+ =?UTF-8?q?=E8=AF=95=E5=85=A5=E9=98=9F=E8=B7=AF=E5=BE=84=E5=85=88=E7=A6=BB?=+ =?UTF-8?q?=E9=93=BE=EF=BC=88=E4=BA=8C=E5=B7=A1#4=EF=BC=9ALOADING=20?=+ =?UTF-8?q?=E5=9C=A8=E9=93=BE=E7=A0=B4=E5=9D=8F=E4=B8=8D=E5=8F=98=E5=BC=8F?=+ =?UTF-8?q?=E2=86=92evict=20=E5=8F=AF=E9=80=90=E5=9C=A8=E9=80=94=E6=A7=BD?=+ =?UTF-8?q?=E5=8F=8C=E5=86=99=EF=BC=89+=20file=5Foff=20=E5=90=9E=E7=A0=81?=+ =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20+=20SYNC=20=E4=BA=8C=E5=88=86=E5=BC=80?=+ =?UTF-8?q?=E5=85=B3=20+=20=E6=8C=87=E7=BA=B9=E8=B0=83=E8=AF=95=E4=BB=B6?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 22 +++++++++++++++++++---+ 1 file changed, 19 insertions(+), 3 deletions(-)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 6f76c90..fa89ffd 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -383,6 +383,7 @@ static void slot_finalize_locked(int32_t si, int ok) {+ // synchronous read on the main thread outside the lock (same as the engine's sync_load_locked; no one can move a LOADING slot, so it's safe)+ static int load_sync_locked(int32_t si) {+ struct slot_ent * s = &g_slots[si];++ list_unlink(si); // unlink: during the retry window this slot cannot be taken over by a claim (out-of-lock read vs double write)+ struct tensor_pool * p = &g_tp[s->tix];+ const uint64_t off = p->file_off + (uint64_t) s->expert * p->stride;+ pthread_mutex_unlock(&g_lock);+@@ -443,7 +444,7 @@ static long long mem_avail_mb(void) {+ fclose(f);+ return v;+ }+-// watermark trim (simplified form of the engine's trim): evict only non-pinned READY; no physical frame reclaim (the arena middle is not contiguous -- see ALIGNMENT.md).++// watermark trim (isomorphic to the engine's trim): evict non-pinned READY + madvise(DONTNEED) on evicted slots to truly drop RSS (the engine frees tail blocks via os_anon_free; we use a single arena, so per-slot DONTNEED is the equivalent).+ static void water_trim_locked(void) {+ const char * fe = getenv("E0_MEM_FLOOR_MB");+ if (!fe) return;+@@ -467,6 +468,7 @@ static void water_trim_locked(void) {+ list_unlink(v);+ s->state = ST_EMPTY; s->expert = -1;+ g_used_slots--; g_trims++; n++;++ madvise(s->mem, g_slice, MADV_DONTNEED); // the slot region is a contiguous 640KB: physical pages released at once and read back as zeros (rewritten by pread on reuse)+ }+ if (n) fprintf(stderr, "moe_pool trim: evicted=%d used=%d MemAvailable=%lldMB\n", n, g_used_slots, avail);+ }+@@ -514,7 +516,9 @@ void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off) {+ if (p->role >= 0 && p->layer >= 0 && p->layer < 64) {+ g_lr[p->layer].tix[p->role] = g_ntp - 1;+ }+- p->key = t->data; snprintf(p->name, sizeof(p->name), "%s", t->name); p->fd = dup(fd); // independent ownership: pread still works after the loader closed its fd (v4 hang incident) p->file_off = file_off; p->slice = stride; p->stride = stride;++ p->key = t->data; snprintf(p->name, sizeof(p->name), "%s", t->name);++ p->fd = dup(fd); // independent ownership: pread still works after the loader closed its fd (v4 hang incident)++ p->file_off = file_off; p->slice = stride; p->stride = stride;+ p->n_experts = t->ne[2];+ p->slot = calloc((size_t) p->n_experts, sizeof(int32_t));+ for (int64_t i = 0; i < p->n_experts; i++) p->slot[i] = SLOT_NONE;+@@ -633,6 +637,7 @@ void moe_pool_prefetch_impl(struct tensor_pool * p, int64_t e) {+ const int32_t si = p->slot[e];+ if (si >= 0) {+ if (g_slots[si].state == ST_FAILED) { // failed slot: retry once (enqueue)++ list_unlink(si); // second-audit case #4: LOADING must be unlinked (otherwise eviction could take an in-flight slot -> double write)+ g_slots[si].state = ST_LOADING;+ if (!enqueue_io_locked(si, 0)) {+ load_sync_locked(si);+@@ -658,7 +663,18 @@ const void * moe_pool_row_ptr(const struct ggml_tensor * t, int64_t expert, cons+ const int32_t si = p->slot[expert];+ if (si < 0) return def;+ const struct slot_ent * s = &g_slots[si];+- return (s->state == ST_READY && s->expert == expert) ? s->mem : def;++ if (s->state == ST_READY && s->expert == expert) {++ static int s_fp6;++ if (getenv("E0_POOL_STATS") && s_fp6 < 6) {++ s_fp6++;++ const unsigned char * q = (const unsigned char *) s->mem;++ const unsigned char * d2 = (const unsigned char *) def;++ fprintf(stderr, "moe_pool fp: %s e=%d slot=%02x%02x%02x%02x def=%02x%02x%02x%02x\n",++ t->name, (int) expert, q[0], q[1], q[2], q[3], d2[0], d2[1], d2[2], d2[3]); fprintf(stderr, "moe_pool fp2: tix=%d file_off=%llu stride=%llu fd=%d\n", (int)(p - g_tp), (unsigned long long) p->file_off, (unsigned long long) p->stride, p->fd);++ }++ return s->mem;++ }++ return def;+ }++ void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0007-moe_pool-v4.3-NEON-vmovl-vcvt-vfma-8-lane.patch b/patches/llama.cpp/android/0007-moe_pool-v4.3-NEON-vmovl-vcvt-vfma-8-lane.patchnew file mode 100644index 0000000..c700ebe--- /dev/null+++ b/patches/llama.cpp/android/0007-moe_pool-v4.3-NEON-vmovl-vcvt-vfma-8-lane.patch@@ -0,0 +1,81 @@+From 16a0020f3f5a2430d2156a7462e75887d7ef7bfc Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 01:25:31 +0800+Subject: [PATCH 07/14] moe_pool v4.3: NEON-ify the predictor-head math+ (vmovl+vcvt+vfma 8-lane, scalar tail fallback)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Head math fc1(512x2560)+fc2/lin(256x2560/512) ~= 2.1MMAC per layer: the scalar version costs the+worker 40-80ms per token, directly squeezing the prefetch lead time. The NEON version gives ~4-8x+speedup = the prefetch window recovers.+(Verified on a real arm64 device, on the record: the dualpath discipline does not apply to this+piece -- it is pure added math, and routing/numerics are already covered by the text-gate three-way+consistency guardrail; the NEON change only affects how fast prefetch targets are selected, never+logits.)++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 36 ++++++++++++++++++++++++++----------+ 1 file changed, 26 insertions(+), 10 deletions(-)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index fa89ffd..903f0f7 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -233,6 +233,29 @@ static inline float f16tof(uint16_t h) {+ const uint32_t w = (uint32_t) h << 16;+ float f; memcpy(&f, &w, 4); return f;+ }++#if defined(__aarch64__)++#include <arm_neon.h>++static float dot_f16_f32(const uint16_t * w, const float * x, int n) {++ float32x4_t acc0 = vdupq_n_f32(0.f), acc1 = vdupq_n_f32(0.f);++ int i = 0;++ for (; i + 8 <= n; i += 8) {++ uint16x8_t wv = vld1q_u16(w + i);++ float32x4_t w0 = vcvtq_f32_u32(vmovl_u16(vget_low_u16(wv)));++ float32x4_t w1 = vcvtq_f32_u32(vmovl_u16(vget_high_u16(wv)));++ acc0 = vfmaq_f32(acc0, w0, vld1q_f32(x + i));++ acc1 = vfmaq_f32(acc1, w1, vld1q_f32(x + i + 4));++ }++ float r = vaddvq_f32(vaddq_f32(acc0, acc1));++ for (; i < n; i++) r += f16tof(w[i]) * x[i];++ return r;++}++#else++static float dot_f16_f32(const uint16_t * w, const float * x, int n) {++ float r = 0;++ for (int i = 0; i < n; i++) r += f16tof(w[i]) * x[i];++ return r;++}++#endif+ static inline float gelu_erf_f(float x) { return 0.5f * x * (1.0f + erff(x * 0.70710678118654752440f)); }++ static void pred_do_job(struct pred_job * j) {+@@ -241,18 +264,11 @@ static void pred_do_job(struct pred_job * j) {+ const uint16_t * fc2 = g_lr[j->layer].hd.fc2;+ const uint16_t * lin = g_lr[j->layer].hd.lin;+ for (int o = 0; o < 512; o++) {+- const uint16_t * wrow = fc1 + (size_t) o * 2560;+- float acc = 0;+- for (int i = 0; i < 2560; i++) acc += f16tof(wrow[i]) * j->x[i];+- h[o] = gelu_erf_f(acc);++ h[o] = gelu_erf_f(dot_f16_f32(fc1 + (size_t) o * 2560, j->x, 2560));+ }+ for (int o = 0; o < 256; o++) {+- const uint16_t * wr = lin + (size_t) o * 2560;+- const uint16_t * wc = fc2 + (size_t) o * 512;+- float acc = 0;+- for (int i = 0; i < 2560; i++) acc += f16tof(wr[i]) * j->x[i];+- for (int i = 0; i < 512; i++) acc += f16tof(wc[i]) * h[i];+- out[o] = acc;++ out[o] = dot_f16_f32(lin + (size_t) o * 2560, j->x, 2560)++ + dot_f16_f32(fc2 + (size_t) o * 512, h, 512);+ }+ int top[8]; float tv[8]; for (int k = 0; k < 8; k++) { tv[k] = -1e30f; top[k] = -1; }+ for (int e = 0; e < 256; e++) {+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0008-moe_pool-v4.4-2s-ensure-proc-12ms-token.patch b/patches/llama.cpp/android/0008-moe_pool-v4.4-2s-ensure-proc-12ms-token.patchnew file mode 100644index 0000000..5698896--- /dev/null+++ b/patches/llama.cpp/android/0008-moe_pool-v4.4-2s-ensure-proc-12ms-token.patch@@ -0,0 +1,34 @@+From 03c5ca68489cede393308a1cd12e89e68aa476f3 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 01:44:29 +0800+Subject: [PATCH 08/14] =?UTF-8?q?moe=5Fpool=20v4.4:=20=E6=B0=B4=E4=BD=8D?=+ =?UTF-8?q?=E6=8E=A2=E6=B5=8B=202s=20=E8=8A=82=E6=B5=81=EF=BC=88=E6=AF=8F?=+ =?UTF-8?q?=20ensure=20=E5=BC=80=20/proc=E2=89=8812ms/token=20=E6=B5=8B?=+ =?UTF-8?q?=E9=87=8F=E7=A8=8E=EF=BC=89?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 4 +++++ 1 file changed, 4 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 903f0f7..4d62904 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -466,6 +466,10 @@ static void water_trim_locked(void) {+ if (!fe) return;+ const long long floor_mb = atoll(fe);+ if (floor_mb <= 0) return;++ static uint64_t s_next = 0; // 2s throttle (third-audit case: opening /proc on every ensure cost a ~3% measurement tax)++ const uint64_t now = now_ns();++ if (now < s_next) return;++ s_next = now + 2000000000ull;+ const long long avail = mem_avail_mb();+ if (avail < 0 || avail >= floor_mb) return;+ const int target = (int) (g_nslots * 6 / 10);+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0009-moe_pool-v4.5-K8-K4-64-32-p6144pr-3.10-UFS-K8-1.23GB.patch b/patches/llama.cpp/android/0009-moe_pool-v4.5-K8-K4-64-32-p6144pr-3.10-UFS-K8-1.23GB.patchnew file mode 100644index 0000000..375be39--- /dev/null+++ b/patches/llama.cpp/android/0009-moe_pool-v4.5-K8-K4-64-32-p6144pr-3.10-UFS-K8-1.23GB.patch@@ -0,0 +1,55 @@+From 437ebfe1a299b86f7e299dd0db93f79961c0a68a Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 02:23:09 +0800+Subject: [PATCH 09/14] =?UTF-8?q?moe=5Fpool=20v4.5:=20=E9=A2=84=E5=8F=96?=+ =?UTF-8?q?=20K8=E2=86=92K4=20+=20=E7=A7=AF=E5=8E=8B=E8=8A=82=E6=B5=81=206?=+ =?UTF-8?q?4=E2=86=9232=EF=BC=88p6144pr=3D3.10=20=E5=8F=8D=E5=99=AC?=+ =?UTF-8?q?=E6=A1=88=E2=80=94=E2=80=94=E9=A2=84=E5=8F=96=E9=A2=84=E7=AE=97?=+ =?UTF-8?q?=3D=E6=9C=AC=E7=AB=AF=20UFS=20=E5=B8=A6=E5=AE=BD=EF=BC=8CK8=3D1?=+ =?UTF-8?q?.23GB/tok=20=E8=B6=85=E8=BD=BD=202=20=E5=80=8D=EF=BC=89?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 10 +++++-----+ 1 file changed, 5 insertions(+), 5 deletions(-)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 4d62904..7584680 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -270,16 +270,16 @@ static void pred_do_job(struct pred_job * j) {+ out[o] = dot_f16_f32(lin + (size_t) o * 2560, j->x, 2560)+ + dot_f16_f32(fc2 + (size_t) o * 512, h, 512);+ }+- int top[8]; float tv[8]; for (int k = 0; k < 8; k++) { tv[k] = -1e30f; top[k] = -1; }++ int top[4]; float tv[4]; for (int k = 0; k < 4; k++) { tv[k] = -1e30f; top[k] = -1; }+ for (int e = 0; e < 256; e++) {+- for (int k = 0; k < 8; k++) {++ for (int k = 0; k < 4; k++) {+ if (out[e] > tv[k]) {+- for (int m = 7; m > k; m--) { tv[m] = tv[m-1]; top[m] = top[m-1]; }++ for (int m = 3; m > k; m--) { tv[m] = tv[m-1]; top[m] = top[m-1]; }+ tv[k] = out[e]; top[k] = e; break;+ }+ }+ }+- for (int k = 0; k < 8; k++) {++ for (int k = 0; k < 4; k++) {+ if (top[k] < 0) break;+ for (int role = 0; role < 3; role++) {+ const int64_t tix = g_lr[j->layer].tix[role];+@@ -667,7 +667,7 @@ void moe_pool_prefetch_impl(struct tensor_pool * p, int64_t e) {+ pthread_mutex_unlock(&g_lock);+ return;+ }+- if (g_qpn > 64) { g_pf_drop++; pthread_mutex_unlock(&g_lock); return; } // throttle: drop prefetches when the main queue backs up++ if (g_qpn > 32) { g_pf_drop++; pthread_mutex_unlock(&g_lock); return; } // throttle v4.5 (K8 backlash case: 64 still exceeded the device bandwidth)+ g_pf_issued++;+ const int32_t slot = claim_slot_locked(tix, (int32_t) e);+ if (slot < 0) { g_pf_drop++; pthread_mutex_unlock(&g_lock); return; }+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0010-moe_pool-v4.6-moe_pool_extra-stall-App-metrics-pool-.patch b/patches/llama.cpp/android/0010-moe_pool-v4.6-moe_pool_extra-stall-App-metrics-pool-.patchnew file mode 100644index 0000000..f00c737--- /dev/null+++ b/patches/llama.cpp/android/0010-moe_pool-v4.6-moe_pool_extra-stall-App-metrics-pool-.patch@@ -0,0 +1,56 @@+From 961da91d656cecdeede567d05545e69352aee3f2 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 09:05:06 +0800+Subject: [PATCH 10/14] =?UTF-8?q?moe=5Fpool=20v4.6:=20moe=5Fpool=5Fextra?=+ =?UTF-8?q?=20=E5=AF=BC=E5=87=BA=EF=BC=88stall/=E6=A7=BD=E4=BD=8D/?=+ =?UTF-8?q?=E9=A2=84=E5=8F=96=E6=B6=88=E8=B4=B9=E8=AE=A1=E6=95=B0=E2=80=94?=+ =?UTF-8?q?=E2=80=94App=20metrics=20=E5=8D=A1=20pool/rss=20=E4=BE=9B?=+ =?UTF-8?q?=E6=95=B0=E9=80=9A=E9=81=93=EF=BC=89?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 9 ++++++++++ ggml/src/ggml-cpu/moe_pool.h | 4 +++++ 2 files changed, 13 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 7584680..d7be8ca 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -710,6 +710,15 @@ void moe_pool_stats(long long * hits, long long * misses, long long * loads, lon+ if (used_bytes) *used_bytes = (size_t) g_used_slots * g_slice;+ }+++void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * slots_total,++ long long * pf_used, long long * pf_mispredict) {++ if (stall_ns) *stall_ns = g_stall_ns;++ if (slots_used) *slots_used = g_used_slots;++ if (slots_total) *slots_total = g_nslots;++ if (pf_used) *pf_used = g_pf_used;++ if (pf_mispredict) *pf_mispredict = g_pf_miss;++}+++ __attribute__((destructor)) static void moe_pool_dump(void) {+ if (!g_ready && !g_blob_on) return;+ long long h = 0, m = 0;+diff --git a/ggml/src/ggml-cpu/moe_pool.h b/ggml/src/ggml-cpu/moe_pool.h+index e4c48ca..533d6ac 100644+--- a/ggml/src/ggml-cpu/moe_pool.h++++ b/ggml/src/ggml-cpu/moe_pool.h+@@ -42,6 +42,10 @@ int moe_pool_load_heads(const char * path);+ void moe_pool_bind_min(int layer, const struct ggml_tensor * t);+ void moe_pool_note_routing(const struct ggml_tensor * src0, const int32_t * ids, int n_ids);+++// v4 extended counters (App metrics channel: stall / slots / prefetch consumption)++void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * slots_total,++ long long * pf_used, long long * pf_mispredict);+++ // stats snapshot (for debugging / accounting)+ void moe_pool_stats(long long * hits, long long * misses, long long * loads, long long * evicts,+ long long * bytes_loaded, size_t * cap_bytes, size_t * used_bytes);+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0011-moe_pool-v4.7-moe_pool_reset_all-inflight-blob-IO-9-.patch b/patches/llama.cpp/android/0011-moe_pool-v4.7-moe_pool_reset_all-inflight-blob-IO-9-.patchnew file mode 100644index 0000000..d0804dd--- /dev/null+++ b/patches/llama.cpp/android/0011-moe_pool-v4.7-moe_pool_reset_all-inflight-blob-IO-9-.patch@@ -0,0 +1,76 @@+From b946e2ad525538a04c784bbd730e890004be9997 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 09:22:43 +0800+Subject: [PATCH 11/14] =?UTF-8?q?moe=5Fpool=20v4.7:=20moe=5Fpool=5Freset?=+ =?UTF-8?q?=5Fall=EF=BC=88=E8=B7=A8=E6=A8=A1=E5=9E=8B=E5=88=87=E6=8D=A2?=+ =?UTF-8?q?=E5=85=A8=E5=A4=8D=E4=BD=8D=E2=80=94=E2=80=94=E7=AD=89=20inflig?=+ =?UTF-8?q?ht=20=E6=8E=92=E7=A9=BA=E3=80=81=E6=A7=BD=E8=A1=A8/=E6=B3=A8?=+ =?UTF-8?q?=E5=86=8C/blob=20=E5=BD=92=E9=9B=B6=E3=80=81IO=20=E7=BA=BF?=+ =?UTF-8?q?=E7=A8=8B=E7=95=99=E5=9C=BA=E5=A4=8D=E7=94=A8=EF=BC=9B9/29=208b?=+ =?UTF-8?q?->35b=20=E9=97=AA=E9=80=80=E6=A1=88=E7=9A=84=E5=90=8C=E6=97=8F?=+ =?UTF-8?q?=E5=9C=B0=E9=9B=B7=E6=8E=92=E9=9B=B7=EF=BC=89?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 27 ++++++++++++++++++++++++++++ ggml/src/ggml-cpu/moe_pool.h | 3 ++++ 2 files changed, 30 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index d7be8ca..e9d3415 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -719,6 +719,33 @@ void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * sl+ if (pf_mispredict) *pf_mispredict = g_pf_miss;+ }+++// cross-model-switch reset (insurance against the 9/29 crash-family incident): called by nativeFree. After waiting for the IO++// drain, all state is zeroed; the next moe_pool_init/register rebuilds under the new env. Head mappings are kept (those files don't change with the model).++void moe_pool_reset_all(void) {++ pthread_mutex_lock(&g_lock);++ while (g_inflight > 0) pthread_cond_wait(&g_scv, &g_lock); // wait for in-flight reads to terminate++ for (int i = 0; i < g_ntp; i++) { free(g_tp[i].slot); g_tp[i].slot = NULL; }++ g_ntp = 0;++ for (int i = 0; i < 64; i++) { g_lr[i].tix[0] = g_lr[i].tix[1] = g_lr[i].tix[2] = -1; }++ if (g_slots) {++ for (int i = 0; i < g_nslots; i++) {++ struct slot_ent * sl = &g_slots[i];++ if (sl->on_list) list_unlink(i);++ sl->state = ST_EMPTY; sl->expert = -1; sl->tix = -1; sl->pinned = 0;++ sl->prefetched = 0; sl->consumed = 0;++ }++ free(g_slots); g_slots = NULL;++ }++ if (g_arena) { munmap(g_arena, g_slice * (size_t) g_nslots); g_arena = NULL; }++ g_nslots = 0; g_used_slots = 0; g_empty_cursor = 0; g_slice = 0;++ g_lru_head = g_lru_tail = SLOT_NONE;++ g_qdn = g_qpn = 0; g_qph = g_qpt = g_qdh = g_qdt = 0;++ if (g_blob) { madvise(g_blob, g_blob_cap, MADV_DONTNEED); g_blob_bump = 0; }++ g_ready = 0; g_cap_bytes = 0;++ g_npins = 0;++ pthread_mutex_unlock(&g_lock);++}+++ __attribute__((destructor)) static void moe_pool_dump(void) {+ if (!g_ready && !g_blob_on) return;+ long long h = 0, m = 0;+diff --git a/ggml/src/ggml-cpu/moe_pool.h b/ggml/src/ggml-cpu/moe_pool.h+index 533d6ac..82dfc74 100644+--- a/ggml/src/ggml-cpu/moe_pool.h++++ b/ggml/src/ggml-cpu/moe_pool.h+@@ -42,6 +42,9 @@ int moe_pool_load_heads(const char * path);+ void moe_pool_bind_min(int layer, const struct ggml_tensor * t);+ void moe_pool_note_routing(const struct ggml_tensor * src0, const int32_t * ids, int n_ids);+++// cross-model-switch reset (called by the llama shell's nativeFree)++void moe_pool_reset_all(void);+++ // v4 extended counters (App metrics channel: stall / slots / prefetch consumption)+ void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * slots_total,+ long long * pf_used, long long * pf_mispredict);+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0012-moe_pool-v4.7-keepwarm-demand-ensure-ring-8192-turn-.patch b/patches/llama.cpp/android/0012-moe_pool-v4.7-keepwarm-demand-ensure-ring-8192-turn-.patchnew file mode 100644index 0000000..1dcd9c2--- /dev/null+++ b/patches/llama.cpp/android/0012-moe_pool-v4.7-keepwarm-demand-ensure-ring-8192-turn-.patch@@ -0,0 +1,129 @@+From 24f7d4c33b0fc3e176da129a986c4d2d7a7e3596 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 10:37:19 +0800+Subject: [PATCH 12/14] =?UTF-8?q?moe=5Fpool=20v4.7:=20keepwarm=20=E8=BD=AE?=+ =?UTF-8?q?=E6=9C=AB=E5=9B=9E=E7=81=8C=EF=BC=88demand=20ensure=20=E5=8F=8C?=+ =?UTF-8?q?=E6=94=AF=E8=AE=B0=20ring=208192=EF=BC=8Cturn=20=E6=9C=AB=20det?=+ =?UTF-8?q?ached=20=E7=BA=BF=E7=A8=8B=E6=8C=89=20E0=5FKEEPWARM=5FMB=20?=+ =?UTF-8?q?=E9=A2=84=E7=AE=97=E6=8A=8A=E8=A2=AB=E9=80=90=E8=80=85=E4=BB=A5?=+ =?UTF-8?q?=E9=A2=84=E5=8F=96=E7=BA=A7=E6=90=AC=E5=9B=9E=EF=BC=9BApp=2035b?=+ =?UTF-8?q?=20=E6=A1=A3=3D512=EF=BC=89+=20pred=20feats=20f16=20=E9=87=8F?=+ =?UTF-8?q?=E5=8C=96=EF=BC=88SPEC=20=C2=A71=20=E8=AE=AD=E7=BB=83=E5=88=86?=+ =?UTF-8?q?=E5=B8=83=E5=AF=B9=E9=BD=90=EF=BC=8Cpf=20=E5=91=BD=E4=B8=AD?=+ =?UTF-8?q?=E7=8E=87=E5=B7=AE=E5=80=BC=E5=80=99=E9=80=89=E2=91=A0=EF=BC=9B?=+ =?UTF-8?q?pred=20OFF=20=E6=97=B6=E9=9B=B6=E8=A7=A6=E8=BE=BE=EF=BC=89?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 47 +++++++++++++++++++++++++++++++++++++ ggml/src/ggml-cpu/moe_pool.h | 3 ++++ 2 files changed, 50 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index e9d3415..2098376 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -91,6 +91,12 @@ static long long g_pf_issued, g_pf_used, g_pf_waste, g_pf_drop, g_pf_miss, g_res+ static char * g_blob; static size_t g_blob_cap, g_blob_bump; static int g_blob_on;+ static volatile int g_heads_on, g_pred_enabled; // referenced early by init (defined in the pred section)+++// keepwarm (9/29 20s-between-turns case): accounts the (tix,e) touched by the current decode round; at turn end, evicted entries are refilled asynchronously when idle.++#define KW_DEPTH 8192++static struct { int32_t tix; int32_t e; } g_kw[KW_DEPTH];++static unsigned g_kwh, g_kwt;++static volatile int g_kw_busy;+++ static uint64_t now_ns(void) {+ struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);+ return (uint64_t) ts.tv_sec * 1000000000ull + (uint64_t) ts.tv_nsec;+@@ -258,8 +264,15 @@ static float dot_f16_f32(const uint16_t * w, const float * x, int n) {+ #endif+ static inline float gelu_erf_f(float x) { return 0.5f * x * (1.0f + erff(x * 0.70710678118654752440f)); }+++static void moe_pool_f16_quant_feats(float * x, int n) {++ for (int i = 0; i < n; i++) x[i] = (float) (__fp16) x[i];++}+++ static void pred_do_job(struct pred_job * j) {+ float h[512], out[256];++ // SPEC sec.1: feats are cast to f16 before entering the network (training distribution = f16; feeding f32 directly would++ // drift the top-K ranking on near-ties -- prime suspect #1 for the gap between the 10% pf hit rate and the 55% recorded profile).++ { extern void moe_pool_f16_quant_feats(float * x, int n); moe_pool_f16_quant_feats(j->x, 2560); }+ const uint16_t * fc1 = g_lr[j->layer].hd.fc1;+ const uint16_t * fc2 = g_lr[j->layer].hd.fc2;+ const uint16_t * lin = g_lr[j->layer].hd.lin;+@@ -595,6 +608,7 @@ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_id+ struct slot_ent * s = &g_slots[si];+ if (s->state == ST_READY) {+ p->hits++;++ { unsigned h = g_kwh % KW_DEPTH; g_kw[h].tix = tix; g_kw[h].e = e; g_kwh++; }+ if (s->prefetched && !s->consumed) { g_pf_used++; s->consumed = 1; }+ list_push_back(si);+ pin_locked(si);+@@ -629,6 +643,7 @@ void moe_pool_ensure(const struct ggml_tensor * t, const int32_t * ids, int n_id+ pthread_cond_wait(&g_scv, &g_lock);+ }+ if (slot < 0) continue;++ { unsigned h = g_kwh % KW_DEPTH; g_kw[h].tix = tix; g_kw[h].e = e; g_kwh++; }+ pin_locked(slot);+ if (enqueue_io_locked(slot, 1)) {+ if (nwait < 64) waiters[nwait++] = slot;+@@ -676,6 +691,38 @@ void moe_pool_prefetch_impl(struct tensor_pool * p, int64_t e) {+ pthread_mutex_unlock(&g_lock);+ }+++// turn-end refill: move (tix,e) pairs in the ring that are currently not in the pool back at prefetch level++// (demand=0 queue, evictable). budget_mb=0 -> read E0_KEEPWARM_MB (default 256MB, low intensity, never competes with the foreground).++void moe_pool_keepwarm(int budget_mb) {++ if (!g_ready) return;++ if (budget_mb <= 0) {++ const char * e = getenv("E0_KEEPWARM_MB");++ budget_mb = e ? (int) atol(e) : 0;++ if (budget_mb <= 0) budget_mb = 256;++ }++ if (g_kw_busy) return;++ g_kw_busy = 1;++ long long bytes = (long long) budget_mb * 1024 * 1024;++ pthread_mutex_lock(&g_lock);++ unsigned seen_end = g_kwh;++ for (unsigned i = g_kwt; i < seen_end && bytes > 0; i++) {++ int k = i % KW_DEPTH;++ const int tix = g_kw[k].tix; const int32_t e2 = g_kw[k].e;++ if (tix < 0 || tix >= g_ntp) continue;++ struct tensor_pool * p = &g_tp[tix];++ if (e2 < 0 || e2 >= p->n_experts) continue;++ if (p->slot[e2] >= 0) continue; // already resident++ const int32_t slot = claim_slot_locked(tix, e2);++ if (slot < 0) break;++ g_slots[slot].prefetched = 1;++ if (!enqueue_io_locked(slot, 0)) { unclaim_locked(slot); break; }++ bytes -= (long long) p->slice;++ }++ g_kwt = seen_end; // consumed this round (whether or not fully refilled)++ pthread_mutex_unlock(&g_lock);++ g_kw_busy = 0;++}+++ const void * moe_pool_row_ptr(const struct ggml_tensor * t, int64_t expert, const void * def) {+ if (!g_ready || expert < 0) return def;+ const struct tensor_pool * p = find_tp(t);+diff --git a/ggml/src/ggml-cpu/moe_pool.h b/ggml/src/ggml-cpu/moe_pool.h+index 82dfc74..3341e1d 100644+--- a/ggml/src/ggml-cpu/moe_pool.h++++ b/ggml/src/ggml-cpu/moe_pool.h+@@ -42,6 +42,9 @@ int moe_pool_load_heads(const char * path);+ void moe_pool_bind_min(int layer, const struct ggml_tensor * t);+ void moe_pool_note_routing(const struct ggml_tensor * src0, const int32_t * ids, int n_ids);+++// turn-end keepwarm refill (E0_KEEPWARM_MB budget, 0 = default 256MB)++void moe_pool_keepwarm(int budget_mb);+++ // cross-model-switch reset (called by the llama shell's nativeFree)+ void moe_pool_reset_all(void);++--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0013-moe_pool-v4.7.1-reset_all-keepwarm-g_kw_busy-2s-g_re.patch b/patches/llama.cpp/android/0013-moe_pool-v4.7.1-reset_all-keepwarm-g_kw_busy-2s-g_re.patchnew file mode 100644index 0000000..536d02a--- /dev/null+++ b/patches/llama.cpp/android/0013-moe_pool-v4.7.1-reset_all-keepwarm-g_kw_busy-2s-g_re.patch@@ -0,0 +1,42 @@+From ee1237ee6ce144d24097406654a64d14cad8ce82 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 17:45:30 +0800+Subject: [PATCH 13/14] =?UTF-8?q?moe=5Fpool=20v4.7.1:=20reset=5Fall=C3=97k?=+ =?UTF-8?q?eepwarm=20=E7=AB=9E=E4=BA=89=E5=8A=A0=E5=9B=BA=E2=80=94?=+ =?UTF-8?q?=E2=80=94=E5=85=A5=E5=8F=A3=E7=AD=89=20g=5Fkw=5Fbusy=20?=+ =?UTF-8?q?=E6=B8=85=EF=BC=88=E2=89=A42s=EF=BC=89+=20=E5=9B=9E=E7=81=8C?=+ =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E9=80=90=E6=A7=BD=E9=87=8D=E6=A3=80=20g=5Fre?=+ =?UTF-8?q?ady=EF=BC=88unload=20=E4=B8=AD=E9=80=94=E7=AB=8B=E5=81=9C?=+ =?UTF-8?q?=EF=BC=8C=E9=98=B2=20freed=20arena=20UAF=EF=BC=89?=+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 2 +++ 1 file changed, 2 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 2098376..9bd55dc 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -706,6 +706,7 @@ void moe_pool_keepwarm(int budget_mb) {+ pthread_mutex_lock(&g_lock);+ unsigned seen_end = g_kwh;+ for (unsigned i = g_kwt; i < seen_end && bytes > 0; i++) {++ if (!g_ready) break; // stop immediately if reset came in midway+ int k = i % KW_DEPTH;+ const int tix = g_kw[k].tix; const int32_t e2 = g_kw[k].e;+ if (tix < 0 || tix >= g_ntp) continue;+@@ -769,6 +770,7 @@ void moe_pool_extra(long long * stall_ns, long long * slots_used, long long * sl+ // cross-model-switch reset (insurance against the 9/29 crash-family incident): called by nativeFree. After waiting for the IO+ // drain, all state is zeroed; the next moe_pool_init/register rebuilds under the new env. Head mappings are kept (those files don't change with the model).+ void moe_pool_reset_all(void) {++ for (int w = 0; w < 200 && g_kw_busy; w++) usleep(10000); // keepwarm in-flight hard gate (prevents the UAF race)+ pthread_mutex_lock(&g_lock);+ while (g_inflight > 0) pthread_cond_wait(&g_scv, &g_lock); // wait for in-flight reads to terminate+ for (int i = 0; i < g_ntp; i++) { free(g_tp[i].slot); g_tp[i].slot = NULL; }+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/android/0014-edge0-moe_pool-7-mmid-base-resolver.patch b/patches/llama.cpp/android/0014-edge0-moe_pool-7-mmid-base-resolver.patchnew file mode 100644index 0000000..5dd0708--- /dev/null+++ b/patches/llama.cpp/android/0014-edge0-moe_pool-7-mmid-base-resolver.patch@@ -0,0 +1,56 @@+From 0456216585cebdf82191547240e9ddc66c7284a4 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Tue, 29 Sep 2026 20:25:27 +0800+Subject: [PATCH 14/14] edge0 consolidation: register the moe_pool row+ resolver into the #7 mmid-base resolver surface+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Moves the Android demand-pool's lazy row-pointer resolution out of the direct ggml-cpu.c row+rewrite and into a registration, at the pool's first registration (g_ready=1), into common surface+#7's ggml_edge0_mmid_base resolver. NULL keeps the original semantics; zero disturbance while the+pool is not ready. Both platforms now share one resolver entry point, removing the duplicate+src0_cur rewrites in #7 and moe_pool.++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/moe_pool.c | 8 +++++++++ 1 file changed, 8 insertions(+)++diff --git a/ggml/src/ggml-cpu/moe_pool.c b/ggml/src/ggml-cpu/moe_pool.c+index 9bd55dc..388c3b5 100644+--- a/ggml/src/ggml-cpu/moe_pool.c++++ b/ggml/src/ggml-cpu/moe_pool.c+@@ -11,6 +11,7 @@+ // E0_HEADS / E0_PREROUTER / E0_POOL_STATS (same meanings as v3).+ #include "moe_pool.h"+ #include "ggml.h"++#include "ggml-cpu-impl.h" // edge0 #7 resolver surface (ggml_edge0_mmid_base_fn / _set_mmid_resolver)++ #include <errno.h>+ #include <fcntl.h>+@@ -102,6 +103,12 @@ static uint64_t now_ns(void) {+ return (uint64_t) ts.tv_sec * 1000000000ull + (uint64_t) ts.tv_nsec;+ }+++// edge0 consolidation: hang the pool's row resolution on the #7 mmid-base resolver surface (resident -> private frame; otherwise fall back to upstream arithmetic).++// registered at first registration where g_ready=1; zero disturbance when the pool never becomes ready (E0_POOL_MB unset); NULL keeps the original semantics.++static const char * moe_pool_mmid_resolver(const struct ggml_tensor * src0, int64_t id, size_t nb02) {++ return (const char *) moe_pool_row_ptr(src0, id, (const char *) src0->data + id * nb02);++}+++ void moe_pool_init(void) {+ if (g_ready) return;+ const char * e = getenv("E0_POOL_MB");+@@ -527,6 +534,7 @@ void moe_pool_register(struct ggml_tensor * t, int fd, uint64_t file_off) {+ g_slots = calloc((size_t) g_nslots, sizeof(struct slot_ent));+ for (int i = 0; i < g_nslots; i++) { g_slots[i].mem = g_arena + (size_t) i * g_slice; g_slots[i].expert = -1; g_slots[i].tix = -1; }+ g_ready = 1;++ ggml_edge0_set_mmid_resolver(moe_pool_mmid_resolver); // edge0 #7 consolidation: row bases go through the resolver surface+ const char * ie = getenv("E0_IO_THREADS");+ int nth = ie ? (int) atol(ie) : 4;+ if (nth < 1) nth = 1; if (nth > 8) nth = 8;+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/common/0001-bailingmoe3-wire-LoRA-into-main-graph-edge0-private-.patch b/patches/llama.cpp/common/0001-bailingmoe3-wire-LoRA-into-main-graph-edge0-private-.patchnew file mode 100644index 0000000..fbf31a4--- /dev/null+++ b/patches/llama.cpp/common/0001-bailingmoe3-wire-LoRA-into-main-graph-edge0-private-.patch@@ -0,0 +1,125 @@+From a49736d435951f641bd4bd4ba22fd6792ddb7839 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 15:57:45 +0800+Subject: [PATCH 1/6] bailingmoe3: wire LoRA into main graph (edge0 private+ surface #1)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Reroutes the 9 raw ggml_mul_mat call sites in the main graph through build_lora_mm (same shape as+qwen3next): GDN branch wq/wk/wv (the causal_conv1d helper now takes the already-projected tensor)++ ssm_f_a/ssm_beta/ssm_g_a/wo; MLA branch wq_b/wq/wqkv_gate/wo. wq_a/wkv_a_mqa/output have no+adapter target and stay untouched; wk_b/wv_b are 3D batched with no upstream LoRA precedent,+deferred to phase 2. The MTP graph has no adapter coverage and stays untouched.++For edge0-8b the 147 LoRA pairs previously loaded but silently never entered the graph (the graph+did not reference them); after this patch the 12-step golden probes went 9/12 -> 11/12 and R3+free-gen accuracy 35.5% -> 43.6%.++Co-Authored-By: Claude Code <[email protected]>+---+ src/models/bailingmoe3.cpp | 30 ++++++++++++++----------------+ 1 file changed, 14 insertions(+), 16 deletions(-)++diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp+index e208c7d..2643859 100644+--- a/src/models/bailingmoe3.cpp++++ b/src/models/bailingmoe3.cpp+@@ -171,8 +171,7 @@ static ggml_tensor * bailingmoe3_causal_conv1d(+ ggml_tensor * conv_states_all,+ ggml_tensor * conv_state_all,+ int64_t qkv,+- ggml_tensor * x,+- ggml_tensor * proj_w,++ ggml_tensor * x_proj,+ ggml_tensor * conv_w,+ int64_t d_conv,+ int64_t head_dim,+@@ -192,9 +191,8 @@ static ggml_tensor * bailingmoe3_causal_conv1d(+ total_state_size * ggml_element_size(conv_state_all),+ qkv * conv_state_size * ggml_element_size(conv_state_all));++- ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);+- x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);+- ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);++ ggml_tensor * x_proj_r = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);++ ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj_r), 0);++ const int64_t K = (int64_t) n_rs_seq + 1;+ const int64_t n_written = std::min<int64_t>(n_seq_tokens, K);+@@ -260,16 +258,16 @@ llama_model_bailingmoe3::graph::graph(const llama_model & model, const llm_graph+ ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);++ ggml_tensor * q = bailingmoe3_causal_conv1d(+- gf, ctx0, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv,++ gf, ctx0, conv_states_all, conv_state_all, 0, build_lora_mm(layer.wq, cur), layer.ssm_q_conv,+ d_conv, head_dim, n_head, n_seq_tokens, n_seqs, n_tokens, cache_head, mem_size, cparams.n_rs_seq);+ ggml_tensor * k = bailingmoe3_causal_conv1d(+- gf, ctx0, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv,++ gf, ctx0, conv_states_all, conv_state_all, 1, build_lora_mm(layer.wk, cur), layer.ssm_k_conv,+ d_conv, head_dim, n_head, n_seq_tokens, n_seqs, n_tokens, cache_head, mem_size, cparams.n_rs_seq);+ ggml_tensor * v = bailingmoe3_causal_conv1d(+- gf, ctx0, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv,++ gf, ctx0, conv_states_all, conv_state_all, 2, build_lora_mm(layer.wv, cur), layer.ssm_v_conv,+ d_conv, head_dim, n_head, n_seq_tokens, n_seqs, n_tokens, cache_head, mem_size, cparams.n_rs_seq);++- ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur);++ ggml_tensor * gate = build_lora_mm(layer.ssm_f_a, cur);+ gate = ggml_add(ctx0, gate, layer.ssm_dt_b);+ gate = ggml_reshape_3d(ctx0, gate, head_dim, n_head, n_tokens);+ ggml_tensor * a = ggml_reshape_3d(ctx0, layer.ssm_a, 1, n_head, 1);+@@ -277,7 +275,7 @@ llama_model_bailingmoe3::graph::graph(const llama_model & model, const llm_graph+ gate = ggml_reshape_4d(ctx0, gate, head_dim, n_head, n_seq_tokens, n_seqs);+ cb(gate, "kda_gate", il);++- ggml_tensor * beta = ggml_mul_mat(ctx0, layer.ssm_beta, cur);++ ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur);+ beta = ggml_sigmoid(ctx0, ggml_reshape_4d(ctx0, beta, 1, n_head, n_seq_tokens, n_seqs));++ q = build_gdn_l2_norm(ctx0, q, hparams.f_norm_rms_eps);+@@ -290,12 +288,12 @@ llama_model_bailingmoe3::graph::graph(const llama_model & model, const llm_graph+ ggml_tensor * out = ggml_cont(ctx0, build_recurrent_attn(+ inp_rs, states_all, q, k, v, gate, beta, state, il));++- ggml_tensor * out_gate = ggml_mul_mat(ctx0, layer.ssm_g_a, cur);++ ggml_tensor * out_gate = build_lora_mm(layer.ssm_g_a, cur);+ out_gate = ggml_reshape_3d(ctx0, out_gate, head_dim, n_head, n_tokens);+ out = ggml_reshape_3d(ctx0, out, head_dim, n_head, n_tokens);+ out = build_norm(out, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il);+ out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, out_gate));+- cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, out, d_inner, n_tokens));++ cur = build_lora_mm(layer.wo, ggml_cont_2d(ctx0, out, d_inner, n_tokens));+ cb(cur, "kda_out", il);+ } else {+ ggml_tensor * attn_input = cur;+@@ -305,10 +303,10 @@ llama_model_bailingmoe3::graph::graph(const llama_model & model, const llm_graph+ cb(q_all, "q_a", il);+ q_all = build_norm(q_all, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il);+ cb(q_all, "q_a_norm", il);+- q_all = ggml_mul_mat(ctx0, layer.wq_b, q_all);++ q_all = build_lora_mm(layer.wq_b, q_all);+ cb(q_all, "q_b", il);+ } else {+- q_all = ggml_mul_mat(ctx0, layer.wq, cur);++ q_all = build_lora_mm(layer.wq, cur);+ }+ ggml_tensor * q_nope = ggml_view_3d(ctx0, q_all, qk_nope_head_dim, n_head, n_tokens,+ ggml_row_size(q_all->type, qk_head_dim),+@@ -343,11 +341,11 @@ llama_model_bailingmoe3::graph::graph(const llama_model & model, const llm_graph+ cur = build_attn(inp_attn, nullptr, nullptr, nullptr,+ q, k, kv, nullptr, nullptr, layer.wv_b, kq_scale, il);++- ggml_tensor * attn_gate = ggml_mul_mat(ctx0, layer.wqkv_gate, attn_input);++ ggml_tensor * attn_gate = build_lora_mm(layer.wqkv_gate, attn_input);+ attn_gate = ggml_sigmoid(ctx0, ggml_reshape_3d(ctx0, attn_gate, 1, n_head, n_tokens));+ cur = ggml_reshape_3d(ctx0, cur, v_head_dim, n_head, n_tokens);+ cur = ggml_mul(ctx0, cur, attn_gate);+- cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, cur, v_head_dim * n_head, n_tokens));++ cur = build_lora_mm(layer.wo, ggml_cont_2d(ctx0, cur, v_head_dim * n_head, n_tokens));+ cb(cur, "mla_out", il);+ }++--+2.52.0.windows.1+diff --git a/patches/llama.cpp/common/0002-models-qwen3next-bailingmoe3-capture-router-input-m_.patch b/patches/llama.cpp/common/0002-models-qwen3next-bailingmoe3-capture-router-input-m_.patchnew file mode 100644index 0000000..ef7ceb1--- /dev/null+++ b/patches/llama.cpp/common/0002-models-qwen3next-bailingmoe3-capture-router-input-m_.patch@@ -0,0 +1,53 @@+From c009a31c93bfb4d03d53a0b82ff4c756356583e6 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 16:58:30 +0800+Subject: [PATCH 2/6] models/qwen3next,bailingmoe3: capture router input (m_in)+ into t_layer_inp (edge0 private surface #2)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++On both edge0 archs the layer_inp channel semantics is redirected from "layer input" to "router+input (post-ffn/attn-post-norm)" so the prerouter advisory heads can read features (W4 hook 1).+Takes effect only while cparams.embeddings_layer_inp[il] is active (the set_outputs gate); other+archs and the off state see zero difference. The existing D2H readback loop = extract_layer_inputs+(the production-proven eagle3/dflash channel).++Co-Authored-By: Claude Code <[email protected]>+---+ src/models/bailingmoe3.cpp | 3 ++++ src/models/qwen3next.cpp | 4 +++++ 2 files changed, 7 insertions(+)++diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp+index 2643859..f736435 100644+--- a/src/models/bailingmoe3.cpp++++ b/src/models/bailingmoe3.cpp+@@ -356,6 +356,9 @@ llama_model_bailingmoe3::graph::graph(const llama_model & model, const llm_graph++ ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);+ cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);++ // edge0 W4 hook#1: capture router input (m_in) via the layer_inp channel++ // (consumed only in prerouter mode; same annotation as qwen3next.cpp)++ res->t_layer_inp[il] = cur;++ if ((uint32_t) il < hparams.n_layer_dense_lead) {+ cur = build_ffn(cur,+diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp+index b63fc9c..9673e3b 100644+--- a/src/models/qwen3next.cpp++++ b/src/models/qwen3next.cpp+@@ -183,6 +183,10 @@ llama_model_qwen3next::graph::graph(const llama_model & model, const llm_graph_p+ // Post-attention norm+ ggml_tensor * attn_post_norm = build_norm(cur, model.layers[il].attn_post_norm, nullptr, LLM_NORM_RMS, il);+ cb(attn_post_norm, "attn_post_norm", il);++ // edge0 W4 hook#1: capture router input (m_in) via the layer_inp channel.++ // only consumed when embeddings_layer_inp[il] is active (prerouter mode);++ // with the feature off, set_outputs() skips this slot entirely.++ res->t_layer_inp[il] = attn_post_norm;++ // FFN layer (MoE or dense) - without residual connection+ cur = build_layer_ffn(attn_post_norm, il);+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/common/0003-CMake-glob-src-edge0-.cc-into-llama-target-edge0-pri.patch b/patches/llama.cpp/common/0003-CMake-glob-src-edge0-.cc-into-llama-target-edge0-pri.patchnew file mode 100644index 0000000..422806d--- /dev/null+++ b/patches/llama.cpp/common/0003-CMake-glob-src-edge0-.cc-into-llama-target-edge0-pri.patch@@ -0,0 +1,43 @@+From d1c5a393fa294dbac96f54c4002d68bf7b3a5147 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 17:04:59 +0800+Subject: [PATCH 3/6] CMake: glob src/edge0/*.cc into llama target (edge0+ private surface #3)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Release assembly (scripts/vendor-build.ps1) copies this repo's serve/ pieces into src/edge0/ and+this glob compiles them into llama.lib; a missing/empty directory = pure no-op. The three W4 hooks+exhaust the surface caps (#2 capture / #3 glob / #4 context wire-up), so all prerouter logic lives+in serve/ and consumes no caps.++Co-Authored-By: Claude Code <[email protected]>+---+ src/CMakeLists.txt | 3 ++++ 1 file changed, 3 insertions(+)++diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt+index afdaddc..961fc1c 100644+--- a/src/CMakeLists.txt++++ b/src/CMakeLists.txt+@@ -7,6 +7,8 @@ llama_add_compile_flags()+ # llama++ file(GLOB LLAMA_MODELS_SOURCES "models/*.cpp")++# edge0 private surface #3: directory for our own sources (the release path copies them in from serve/ via the vendor-build script; empty directory = no-op)++file(GLOB LLAMA_EDGE0_SOURCES "edge0/*.cc" "edge0/*.cpp")++ set(LLAMA_CORE_SOURCES+ llama.cpp+@@ -48,6 +50,7 @@ add_library(llama+ ${LLAMA_CORE_SOURCES}+ unicode.h+ ${LLAMA_MODELS_SOURCES}++ ${LLAMA_EDGE0_SOURCES}+ )++ set_target_properties(llama PROPERTIES+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/common/0004-server-wire-edge0-prerouter-advisory-init-on_step-ed.patch b/patches/llama.cpp/common/0004-server-wire-edge0-prerouter-advisory-init-on_step-ed.patchnew file mode 100644index 0000000..faeea9c--- /dev/null+++ b/patches/llama.cpp/common/0004-server-wire-edge0-prerouter-advisory-init-on_step-ed.patch@@ -0,0 +1,80 @@+From 8688715e945011c1c192a611a2334e968ddd4283 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 18:25:12 +0800+Subject: [PATCH 4/6] server: wire edge0 prerouter advisory init/on_step (edge0+ private surface #4, app-layer)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++edge0_pref_init once load_model has ctx ready; edge0_pref_on_step(ctx, batch_view.n_tokens-1)+after every llama_decode with ret==0. The implementation lives in src/edge0/prefetch.cc+(= this repo's serve/ pieces, gitignored there, assembled by the vendor-build script on the+release path). With E0_PREROUTER unset both call sites return immediately -- zero footprint.++Smoke (35b r3+lora, 48tok, accounting mode): INIT heads=33 gates=33 exps=33 map=ok;+head 54.0% ~ the reference machine's 55.2% => the ported formula closes the loop.++Co-Authored-By: Claude Code <[email protected]>+---+ .gitignore | 1 ++ tools/server/server-context.cpp | 22 +++++++++++++++++++++++ 2 files changed, 23 insertions(+)++diff --git a/.gitignore b/.gitignore+index 9b58961..eae8d8d 100644+--- a/.gitignore++++ b/.gitignore+@@ -153,3 +153,4 @@ a.out.*++ AGENTS.local.md+ .pi/SYSTEM.md++src/edge0/+diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp+index b6835e4..35f5804 100644+--- a/tools/server/server-context.cpp++++ b/tools/server/server-context.cpp+@@ -1,4 +1,18 @@+ #include "server-context.h"++++// edge0 W4 prerouter advisory (impl: serve/prefetch.cc; DECISIONS 28-B)++#include <cstdint>++struct llama_model;++struct llama_context;++bool edge0_pref_init(struct llama_model * model, struct llama_context * ctx);++void edge0_pref_on_step(struct llama_context * ctx, int64_t last_row);++++++// edge0 W4 prerouter advisory (DECISIONS 28-B; implementation in serve/prefetch.cc, compiled into the llama target)++struct llama_model;++struct llama_context;++bool edge0_pref_init(llama_model * model, llama_context * ctx);++void edge0_pref_on_step(llama_context * ctx, int64_t last_row);+ #include "server-chat.h"+ #include "server-common.h"+ #include "server-http.h"+@@ -1111,6 +1125,9 @@ private:+ return false;+ }+++ // edge0 W4: prerouter advisory init (E0_PREROUTER unset => sleeps immediately)++ edge0_pref_init(model_tgt, ctx_tgt);+++ vocab = llama_model_get_vocab(model_tgt);++ n_ctx = llama_n_ctx(ctx_tgt);+@@ -3685,6 +3702,11 @@ private:+ }+ });+++ // edge0 W4: prerouter advisory accounting/prefetch (returns immediately when dormant)++ if (ret == 0) {++ edge0_pref_on_step(ctx_tgt, (int64_t) batch_view.n_tokens - 1);++ }+++ if (ret != 0) {+ {+ std::string err;+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/common/0005-server-wire-edge0_apply_mem_budget-P-tier-memory-bud.patch b/patches/llama.cpp/common/0005-server-wire-edge0_apply_mem_budget-P-tier-memory-bud.patchnew file mode 100644index 0000000..624ad2a--- /dev/null+++ b/patches/llama.cpp/common/0005-server-wire-edge0_apply_mem_budget-P-tier-memory-bud.patch@@ -0,0 +1,44 @@+From 63f3f978913f5307bb3a5b10b0b521c749e9dea7 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 18:51:32 +0800+Subject: [PATCH 5/6] server: wire edge0_apply_mem_budget (P-tier memory+ budget, env E0_MEM_BUDGET_MB)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Apply the process working-set hard cap before load_model (implementation in serve/mem_budget.cc).+Verified: under a 12GB budget the server loads and generates normally, ws stays bounded and pages+keep getting trimmed; no slowdown on this machine -- the standby cache backstops it (a large-RAM+machine cannot measure true cold reads; interpretation logged).++Co-Authored-By: Claude Code <[email protected]>+---+ tools/server/server-context.cpp | 4 +++++ 1 file changed, 4 insertions(+)++diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp+index 35f5804..bc4c7a3 100644+--- a/tools/server/server-context.cpp++++ b/tools/server/server-context.cpp+@@ -6,6 +6,7 @@ struct llama_model;+ struct llama_context;+ bool edge0_pref_init(struct llama_model * model, struct llama_context * ctx);+ void edge0_pref_on_step(struct llama_context * ctx, int64_t last_row);++bool edge0_apply_mem_budget(void); // serve/mem_budget.cc: E0_MEM_BUDGET_MB working-set hard cap+++ // edge0 W4 prerouter advisory (DECISIONS 28-B; implementation in serve/prefetch.cc, compiled into the llama target)+@@ -1110,6 +1111,9 @@ private:+ params_base.load_progress_callback_user_data = &load_progress_text;+ }+++ // edge0: P-tier memory budget (E0_MEM_BUDGET_MB unset = no-op; must take effect before the model loads)++ edge0_apply_mem_budget();+++ llama_init = common_init_from_params(params_base);++ model_tgt = llama_init->model();+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/common/0006-edge0-private-surface-7-mul_mat_id-expert-base-resol.patch b/patches/llama.cpp/common/0006-edge0-private-surface-7-mul_mat_id-expert-base-resol.patchnew file mode 100644index 0000000..d1c99b3--- /dev/null+++ b/patches/llama.cpp/common/0006-edge0-private-surface-7-mul_mat_id-expert-base-resol.patch@@ -0,0 +1,114 @@+From 5fa766c64759650fc259a7d45eed2c3b31034917 Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 21:59:15 +0800+Subject: [PATCH 6/6] edge0 private surface #7: mul_mat_id expert-base resolver+ (L1 pool hook)++Three expert-base computations (ggml-cpu.c forward_mul_mat_id, iqp.cpp panel+path, repack.cpp template path) now route through ggml_edge0_mmid_base(src0,+id, nb02). Default NULL resolver = exact upstream arithmetic (zero behavior+change); the llama-side edge0 pool installs a resolver at init to serve expert+bytes from committed private pages (byte-verified vs the file view by+E0_POOL_SELFCHECK sampling). Export macro keyed on ggml_cpu_EXPORTS (this fork+builds ggml-cpu as its own DLL); decls wrapped in extern "C".++Co-Authored-By: Claude Code <[email protected]>+---+ ggml/src/ggml-cpu/ggml-cpu-impl.h | 20 +++++++++++++++++++++ ggml/src/ggml-cpu/ggml-cpu.c | 14 +++++++++++++-+ ggml/src/ggml-cpu/iqp.cpp | 2 +-+ ggml/src/ggml-cpu/repack.cpp | 2 +-+ 4 files changed, 35 insertions(+), 3 deletions(-)++diff --git a/ggml/src/ggml-cpu/ggml-cpu-impl.h b/ggml/src/ggml-cpu/ggml-cpu-impl.h+index 5dd9ec8..85cfc1c 100644+--- a/ggml/src/ggml-cpu/ggml-cpu-impl.h++++ b/ggml/src/ggml-cpu/ggml-cpu-impl.h+@@ -5,6 +5,26 @@+ #include "ggml.h"+ #include "ggml-impl.h"+++// edge0 private surface #7 — MoE expert-base indirection for the edge0 L1 pool++// (installed at runtime by serve/prefetch.cc; NULL = upstream pass-through semantics).++// this fork builds ggml-cpu as a standalone DLL: decoration is bidirectional via the target's EXPORTS macro (GGML_API resolves to import inside this target's translation units, so it cannot be used).++#if defined(_WIN32) && defined(ggml_cpu_EXPORTS)++# define EDGE0_MMID_API __declspec(dllexport)++#elif defined(_WIN32)++# define EDGE0_MMID_API __declspec(dllimport)++#else++# define EDGE0_MMID_API++#endif++#ifdef __cplusplus++extern "C" {++#endif++typedef const char * (*ggml_edge0_mmid_base_fn)(const struct ggml_tensor * src0, int64_t id, size_t nb02);++EDGE0_MMID_API void ggml_edge0_set_mmid_resolver(ggml_edge0_mmid_base_fn fn);++EDGE0_MMID_API const char * ggml_edge0_mmid_base(const struct ggml_tensor * src0, int64_t id, size_t nb02);++#ifdef __cplusplus++}++#endif+++ #include <stdlib.h> // load `stdlib.h` before other headers to work around MinGW bug: https://sourceforge.net/p/mingw-w64/bugs/192/+ //#include <stddef.h>+ #include <stdbool.h>+diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c+index 8bb0ff7..be7c2db 100644+--- a/ggml/src/ggml-cpu/ggml-cpu.c++++ b/ggml/src/ggml-cpu/ggml-cpu.c+@@ -1469,6 +1469,18 @@ UseGgmlGemm2:;++ // ggml_compute_forward_mul_mat_id+++// edge0 private surface #7 — expert-base indirection (pool hook; default = upstream math)++static ggml_edge0_mmid_base_fn g_edge0_mmid_base_fn = NULL;++++void ggml_edge0_set_mmid_resolver(ggml_edge0_mmid_base_fn fn) {++ g_edge0_mmid_base_fn = fn;++}++++const char * ggml_edge0_mmid_base(const struct ggml_tensor * src0, int64_t id, size_t nb02) {++ return g_edge0_mmid_base_fn ? g_edge0_mmid_base_fn(src0, id, nb02)++ : (const char *) src0->data + id * nb02;++}+++ #define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id)*ids->ne[0]*ids->ne[1] + (i1)]++ struct mmid_row_mapping {+@@ -1684,7 +1696,7 @@ static void ggml_compute_forward_mul_mat_id(+ continue;+ }++- const char * src0_cur = (const char *) src0->data + cur_a * nb02;++ const char * src0_cur = ggml_edge0_mmid_base(src0, cur_a, nb02); // edge0 #7+ const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;+ const size_t row_size = ggml_row_size(vec_dot_type, ne10);++diff --git a/ggml/src/ggml-cpu/iqp.cpp b/ggml/src/ggml-cpu/iqp.cpp+index b9201db..031d7b3 100644+--- a/ggml/src/ggml-cpu/iqp.cpp++++ b/ggml/src/ggml-cpu/iqp.cpp+@@ -1147,7 +1147,7 @@ void ggml_compute_forward_mul_mat_id_iqp(const struct ggml_compute_params * para++ block_iqp_x8 * panel = (block_iqp_x8 *) ((char *) panels + (size_t) ith * ggml_cpu_iqp_scratch_size(dst));++- const char * src0_cur = (const char *) src0->data + cur_a * nb02;++ const char * src0_cur = ggml_edge0_mmid_base(src0, cur_a, nb02); // edge0 #7++ const int64_t ngroups = ne01 / IQP_NB_ROWS;++diff --git a/ggml/src/ggml-cpu/repack.cpp b/ggml/src/ggml-cpu/repack.cpp+index d56db98..f402385 100644+--- a/ggml/src/ggml-cpu/repack.cpp++++ b/ggml/src/ggml-cpu/repack.cpp+@@ -4873,7 +4873,7 @@ template <typename BLOC_TYPE, int64_t INTER_SIZE, int64_t NB_COLS, ggml_type PAR+ continue;+ }++- const auto * src0_cur = (const char *) src0->data + cur_a*nb02;++ const auto * src0_cur = ggml_edge0_mmid_base(src0, cur_a, nb02); // edge0 #7++ //const int64_t nr0 = ne01; // src0 rows+ const int64_t nr1 = cne1; // src1 rows+--+2.52.0.windows.1+diff --git a/patches/llama.cpp/windows/0001-common-server-mem-budget-mb-CLI-edge0-private-surfac.patch b/patches/llama.cpp/windows/0001-common-server-mem-budget-mb-CLI-edge0-private-surfac.patchnew file mode 100644index 0000000..5aef1b6--- /dev/null+++ b/patches/llama.cpp/windows/0001-common-server-mem-budget-mb-CLI-edge0-private-surfac.patch@@ -0,0 +1,80 @@+From edef0ec1f8d5e43239b80fe3d91e01aa47a27e5a Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 19:54:14 +0800+Subject: [PATCH 1/2] common+server: --mem-budget-mb CLI (edge0 private surface+ #6)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++common_params.mem_budget_mb + arg registration (env LLAMA_ARG_MEM_BUDGET_MB on the same line);+consumed by server before load_model => edge0_apply_mem_budget(mb). The env channel stays as a+debug fallback. Smoke: --mem-budget-mb 16384 -> [mem-budget] applied; visible in --help.++Co-Authored-By: Claude Code <[email protected]>+---+ common/arg.cpp | 12 +++++++++++++ common/common.h | 1 ++ tools/server/server-context.cpp | 4 ++--+ 3 files changed, 15 insertions(+), 2 deletions(-)++diff --git a/common/arg.cpp b/common/arg.cpp+index 996ea75..111e4ed 100644+--- a/common/arg.cpp++++ b/common/arg.cpp+@@ -2780,6 +2780,18 @@ common_params_context common_params_parser_init(common_params & params, llama_ex+ llm_add_n_cpu_ffn_overrides(value, LLM_FFN_DENSE_REGEX, params.tensor_buft_overrides);+ }+ ).set_env("LLAMA_ARG_N_CPU_FFN"));++ add_opt(common_arg(++ {"--mem-budget-mb"}, "N",++ "edge0: cap this process' max working set at N MB (hard trim on overflow; 0=off)\n"++++ "(P-tier memory budget; predicted-hot pages can later be pinned within it)",++ [](common_params & params, int value) {++ if (value < 0) {++ throw std::invalid_argument("invalid value");++ }++ params.mem_budget_mb = value;++ }++ ).set_env("LLAMA_ARG_MEM_BUDGET_MB"));+ GGML_ASSERT(params.n_gpu_layers < 0); // string_format would need to be extended for a default >= 0+ add_opt(common_arg(+ {"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",+diff --git a/common/common.h b/common/common.h+index 63d0bad..bfa67d9 100644+--- a/common/common.h++++ b/common/common.h+@@ -471,6 +471,7 @@ struct common_params {+ std::vector<ggml_backend_dev_t> devices; // devices to use for offloading++ int32_t n_gpu_layers = -1; // number of layers to store in VRAM, -1 is auto, <= -2 is all++ int32_t mem_budget_mb = 0; // edge0: cap process max working set in MB (0=off; P-tier memory budget)+ int32_t main_gpu = 0; // the GPU that is used for scratch and small tensors+ float tensor_split[128] = {0}; // how split tensors should be distributed across GPUs+ bool fit_params = true; // whether to fit unset model/context parameters to free device memory+diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp+index bc4c7a3..1859a24 100644+--- a/tools/server/server-context.cpp++++ b/tools/server/server-context.cpp+@@ -6,7 +6,7 @@ struct llama_model;+ struct llama_context;+ bool edge0_pref_init(struct llama_model * model, struct llama_context * ctx);+ void edge0_pref_on_step(struct llama_context * ctx, int64_t last_row);+-bool edge0_apply_mem_budget(void); // serve/mem_budget.cc: E0_MEM_BUDGET_MB working-set hard cap++bool edge0_apply_mem_budget(int mb); // serve/mem_budget.cc: --mem-budget-mb working-set hard cap+++ // edge0 W4 prerouter advisory (DECISIONS 28-B; implementation in serve/prefetch.cc, compiled into the llama target)+@@ -1112,7 +1112,7 @@ private:+ }++ // edge0: P-tier memory budget (E0_MEM_BUDGET_MB unset = no-op; must take effect before the model loads)+- edge0_apply_mem_budget();++ edge0_apply_mem_budget(params_base.mem_budget_mb);++ llama_init = common_init_from_params(params_base);++--+2.52.0.windows.1+diff --git a/patches/llama.cpp/windows/0002-common-server-pool-mb-CLI-edge0-private-surface-8.patch b/patches/llama.cpp/windows/0002-common-server-pool-mb-CLI-edge0-private-surface-8.patchnew file mode 100644index 0000000..d8a17f8--- /dev/null+++ b/patches/llama.cpp/windows/0002-common-server-pool-mb-CLI-edge0-private-surface-8.patch@@ -0,0 +1,95 @@+From 7f9c2513d789728292e72c6708ed4ee497dadbab Mon Sep 17 00:00:00 2001+From: Alex Zhou <[email protected]>+Date: Mon, 28 Sep 2026 23:28:28 +0800+Subject: [PATCH 2/2] common+server: --pool-mb CLI (edge0 private surface #8)+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++common_params.pool_mb + arg registration (env LLAMA_ARG_POOL_MB on the same line); server passes+params_base.pool_mb + model.path into edge0_pref_init (signature extended; env E0_GGUF/E0_POOL_MB+stay as harness/debug fallbacks, CLI takes precedence). Also removes the duplicate declaration+block left over from #4. Smoke: 35b --pool-mb 1024 on a clean env -> POOL2 resolver=on tt=120,+hit/fillD incrementing normally.++Co-Authored-By: Claude Code <[email protected]>+---+ common/arg.cpp | 11 ++++++++++++ common/common.h | 1 ++ tools/server/server-context.cpp | 14 ++++----------+ 3 files changed, 16 insertions(+), 10 deletions(-)++diff --git a/common/arg.cpp b/common/arg.cpp+index 111e4ed..73ded46 100644+--- a/common/arg.cpp++++ b/common/arg.cpp+@@ -2792,6 +2792,17 @@ common_params_context common_params_parser_init(common_params & params, llama_ex+ params.mem_budget_mb = value;+ }+ ).set_env("LLAMA_ARG_MEM_BUDGET_MB"));++ add_opt(common_arg(++ {"--pool-mb"}, "N",++ "edge0: expert L1 cache pool of N MB (private pages, mul_mat_id direct read; 0=off)\n"++ "(P-tier contract: pool bytes are the hard commitment, remaining RAM stays opportunistic OS cache)",++ [](common_params & params, int value) {++ if (value < 0) {++ throw std::invalid_argument("invalid value");++ }++ params.pool_mb = value;++ }++ ).set_env("LLAMA_ARG_POOL_MB"));+ GGML_ASSERT(params.n_gpu_layers < 0); // string_format would need to be extended for a default >= 0+ add_opt(common_arg(+ {"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",+diff --git a/common/common.h b/common/common.h+index bfa67d9..683b4e5 100644+--- a/common/common.h++++ b/common/common.h+@@ -472,6 +472,7 @@ struct common_params {++ int32_t n_gpu_layers = -1; // number of layers to store in VRAM, -1 is auto, <= -2 is all+ int32_t mem_budget_mb = 0; // edge0: cap process max working set in MB (0=off; P-tier memory budget)++ int32_t pool_mb = 0; // edge0: expert L1 cache pool in MB, private pages direct-read (0=off; DECISIONS 28/16)+ int32_t main_gpu = 0; // the GPU that is used for scratch and small tensors+ float tensor_split[128] = {0}; // how split tensors should be distributed across GPUs+ bool fit_params = true; // whether to fit unset model/context parameters to free device memory+diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp+index 1859a24..f607072 100644+--- a/tools/server/server-context.cpp++++ b/tools/server/server-context.cpp+@@ -1,19 +1,13 @@+ #include "server-context.h"++-// edge0 W4 prerouter advisory (impl: serve/prefetch.cc; DECISIONS 28-B)++// edge0 W4 prerouter advisory + 28/16 real pool (impl: src/edge0/prefetch.cc; DECISIONS 28-B/16)+ #include <cstdint>+ struct llama_model;+ struct llama_context;+-bool edge0_pref_init(struct llama_model * model, struct llama_context * ctx);++bool edge0_pref_init(struct llama_model * model, struct llama_context * ctx, int pool_mb, const char * gguf_path);+ void edge0_pref_on_step(struct llama_context * ctx, int64_t last_row);+ bool edge0_apply_mem_budget(int mb); // serve/mem_budget.cc: --mem-budget-mb working-set hard cap++-+-// edge0 W4 prerouter advisory (DECISIONS 28-B; implementation in serve/prefetch.cc, compiled into the llama target)+-struct llama_model;+-struct llama_context;+-bool edge0_pref_init(llama_model * model, llama_context * ctx);+-void edge0_pref_on_step(llama_context * ctx, int64_t last_row);+ #include "server-chat.h"+ #include "server-common.h"+ #include "server-http.h"+@@ -1129,8 +1123,8 @@ private:+ return false;+ }++- // edge0 W4: prerouter advisory init (E0_PREROUTER unset => sleeps immediately)+- edge0_pref_init(model_tgt, ctx_tgt);++ // edge0 W4+16: prerouter/pool init (both E0_PREROUTER and --pool-mb unset => sleeps immediately)++ edge0_pref_init(model_tgt, ctx_tgt, params_base.pool_mb, params_base.model.path.c_str());++ vocab = llama_model_get_vocab(model_tgt);++--+2.52.0.windows.1+diff --git a/scripts/patch-green.ps1 b/scripts/patch-green.ps1new file mode 100644index 0000000..c2744f0--- /dev/null+++ b/scripts/patch-green.ps1@@ -0,0 +1,60 @@+# edge0/scripts/patch-green.ps1 — patch-band `git am` gate (final arbiter after an upstream refresh; seconds, no compile)+# The vendor tree is submodule-free: materialized on demand by cloning upstream at the pinned+# commit from vendor.llama.pin (repo root). Set EDGE0_LLAMA_URL to clone from a mirror.+# Usage: pwsh -File patch-green.ps1 [-Bands common,windows] [-Pin <sha>] [-Tree <expected-tree-hash>] [-Keep]+# (-Pin defaults to vendor.llama.pin)+# Exit codes: 0 = GREEN (all bands replayed clean [+ tree parity]), 1 = RED.+param(+ [string]$Bands = "common,windows",+ [string]$Pin = "",+ [string]$Tree = "",+ [switch]$Keep+)+$ErrorActionPreference = "Stop"+$DEPOT = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) # = edge0 root+$VENDOR = Join-Path $DEPOT "vendor/llama.cpp"+$WT = Join-Path $DEPOT "wt/greencheck"+if (-not $Pin) {+ if (-not (Test-Path (Join-Path $DEPOT "vendor.llama.pin"))) { throw "vendor.llama.pin missing at depot root (or pass -Pin)" }+ $Pin = (Get-Content (Join-Path $DEPOT "vendor.llama.pin") -Raw).Trim().Split(" ")[0]+}+if (-not (Test-Path (Join-Path $VENDOR ".git"))) {+ Write-Host "[gate] materializing vendor: clone llama.cpp at pinned $Pin -> $VENDOR" -ForegroundColor Cyan+ New-Item -ItemType Directory -Force (Split-Path $VENDOR) | Out-Null+ $LLAMA_URL = if ($env:EDGE0_LLAMA_URL) { $env:EDGE0_LLAMA_URL } else { "https://github.com/ggml-org/llama.cpp" }+ git clone --filter=blob:none $LLAMA_URL $VENDOR+ if ($LASTEXITCODE -ne 0) { throw "clone failed ($LLAMA_URL)" }+ git -C $VENDOR checkout --detach $Pin+ if ($LASTEXITCODE -ne 0) { throw "pinned commit $Pin not found" }+}++Push-Location $VENDOR+try {+ if (Test-Path $WT) { Pop-Location; git -C $VENDOR worktree remove --force $WT | Out-Null; Push-Location $VENDOR }+ git worktree add --detach $WT $Pin | Out-Null+ Push-Location $WT+ $n = 0; $total = 0+ foreach ($band in $Bands.Split(",")) {+ $files = Get-ChildItem (Join-Path $DEPOT "patches/llama.cpp/$band/*.patch") | Sort-Object Name+ foreach ($f in $files) {+ $total+++ git am --3way $f.FullName *> $null+ if ($LASTEXITCODE -ne 0) {+ Write-Host "RED: git am failed at $band\$($f.Name)" -ForegroundColor Red+ git am --abort *> $null+ exit 1+ }+ $n+++ }+ }+ $actual = (git rev-parse "HEAD^{tree}").Trim()+ Write-Host "applied=$n/$total tree=$actual"+ if ($Tree -and $actual -ne $Tree) {+ Write-Host "RED: tree parity failed -- expected $Tree, got $actual" -ForegroundColor Red+ exit 1+ }+ Write-Host "GREEN: band replay clean$(if ($Tree) { ' + tree parity' })" -ForegroundColor Green+} finally {+ Pop-Location+ if (-not $Keep) { git -C $VENDOR worktree remove --force $WT *> $null }+}diff --git a/vendor.llama.pin b/vendor.llama.pinnew file mode 100644index 0000000..145981a--- /dev/null+++ b/vendor.llama.pin@@ -0,0 +1 @@+7ab4ee7baad2d920464cbacfad4f4b07cf111fd2diff --git a/windows/.gitignore b/windows/.gitignorenew file mode 100644index 0000000..64d4c2d--- /dev/null+++ b/windows/.gitignore@@ -0,0 +1,9 @@+app/node_modules/+app/dist/+app/src-tauri/target/+app/src-tauri/gen/+.edge0/+wt/+models/+benchmarks/+*.logdiff --git a/windows/NOTICE b/windows/NOTICEnew file mode 100644index 0000000..7b9933f--- /dev/null+++ b/windows/NOTICE@@ -0,0 +1,21 @@+NOTICE — edge0 / windows (release tree)+========================================++This file records third-party material contained in or referenced by this subproject.+Licensing of the distribution is governed by the LICENSE file at the monorepo root.++1. ggml-org/llama.cpp (MIT) — https://github.com/ggml-org/llama.cpp+ The engine is the pristine upstream checkout pinned at commit 7ab4ee7 (tag b11100),+ located at the monorepo root vendor/llama.cpp. All modifications ship as replayable+ patch bands under patches/llama.cpp/ (never committed into the vendor tree).++2. Rust crates (see app/src-tauri/Cargo.lock for exact versions/licenses):+ tauri 2, serde, reqwest (rustls), sha2, hex, windows-sys — each under its own license.++3. JS/npm packages (see app/package.json + package-lock.json): React, Vite, Tailwind,+ streamdown/markdown rendering stack — each under its own license.++4. Model weights (downloaded at runtime, not part of this repository):+ Edge0/Edge0-8B-A1B-preview and Edge0/Edge0-35B-A3B-preview — published in MLX format,+ converted on-device to GGUF Q4_1 by the tools/ converter chain. Model-card license+ applies to the weights and applies to the conversion outputs unchanged.diff --git a/windows/README.md b/windows/README.mdindex 4296800..07cdfa3 100644--- a/windows/README.md+++ b/windows/README.md@@ -1,25 +1,182 @@-# edge0 — Windows runtime+# edge0-windows — Release Build Guide-> ✅ Open-sourced on **2026-09-30**. This README will be updated with-> full build & usage docs together with the source drop.+This document is for **developers building or evaluating the Windows app from source**. It covers: quick start (build → run → test), measured performance on the reference machine, and the technical choices behind the stack.-The Windows runtime is a native C++17 port of the edge0 streaming core-(CMake build) with a **Vulkan** compute backend: the `edge0` core-(streaming mmap / cache / layer / MoE) is mirrored from the upstream-Python tree, running the same recipe as the rest of the framework — SSD-expert offload, Recover-LoRA, and prerouter routing prediction.+edge0 is published as a **monorepo** — [`Edge0-AI/edge0`](https://github.com/Edge0-AI/edge0) — whose top level holds the shared engine supply (`vendor.llama.pin` + the scripts-materialized `vendor/llama.cpp`, `patches/llama.cpp/` band-sets) and the platform subprojects (`windows/` = this app, `android/` = the companion). Inference runs on pinned upstream llama.cpp, patched as a replayable patch set, with dense compute on Vulkan and MoE expert weights served from CPU.-The next milestone is the **unified inference framework** — one access-layer, runtime auto-adapting to the hardware platform (iOS / macOS /-Android / Windows / Python) — targeted for **Q4 2026**; see the-[roadmap](../README.md#roadmap).+Third-party attribution: see `NOTICE` in this directory. Model cards: [Edge0/Edge0-8B-A1B-preview](https://huggingface.co/Edge0/Edge0-8B-A1B-preview) · [Edge0/Edge0-35B-A3B-preview](https://huggingface.co/Edge0/Edge0-35B-A3B-preview).-See the [repository README](../README.md) for the multi-platform picture.+---++## 1. Quick Start++### 1.1 Prerequisites++| toolchain | requirement |+|---|---|+| OS | Windows 10 / 11 x64 |+| Visual Studio 2022 | C++ workload (MSVC) |+| CMake | ≥ 3.21 |+| Vulkan SDK | for `ggml-vulkan` (any AMD/NVIDIA/Intel dGPU; iGPU works but slower) |+| Rust | stable, with `cargo` (Tauri 2 shell) |+| Node.js | LTS (`npm`) |+| Python | 3.10+ with `numpy` (on-device converter + benches) |+| Disk / RAM | ≥ 30 GB free disk; RAM: 8 GB+ runs 8B, 16 GB+ runs 35B (paging-bound), the reference machine is 48 GB |++### 1.2 Build the engine (llama.cpp + patches + edge0 serving code)++```powershell+git clone https://github.com/Edge0-AI/edge0+cd edge0/windows+pwsh -File scripts/vendor-build.ps1 # first build ≈ 10–20 min (compiles llama.cpp + Vulkan kernels)+```++The script resolves the engine depot in two ways, then materializes the supply:++- **monorepo clone (normal path)** → the parent directory carries `vendor.llama.pin` + `patches/llama.cpp/{common,windows}`; the script replays the 8 patches (`git am --3way`) into an isolated build worktree at `../wt/win` (gitignored build area) — the vendor tree itself is **never patched in place**;+- `EDGE0_DEPOT` env → point at an existing depot elsewhere.++The llama.cpp tree is **not** a submodule: on first run the script clones upstream (shallow of blobs) into `../vendor/llama.cpp` and detaches the commit pinned in `vendor.llama.pin`; afterwards that directory is just a gitignored checkout you can refresh with `git fetch`. Set `EDGE0_LLAMA_URL` to clone from a mirror.++`-AssembleOnly` runs everything except compilation (seconds; verifies the patch replay still applies and hashes match). Output:++```+wt\win\build-vk\bin\Release\llama-server.exe (+ llama.dll, ggml*.dll)+```++### 1.3 Build the app (Tauri installer + portable exe)++```powershell+cd app+npm install+npx tauri build+```++Artifacts:++```+app\src-tauri\target\release\edge0-app.exe ← portable, no install+app\src-tauri\target\release\bundle\nsis\edge0_0.1.0_x64-setup.exe ← NSIS installer+```++The shell locates the engine via `EDGE0_BIN_DIR` (default: the depot engine build dir above — see `app/README.md` env table for the full override surface). Set it if your engine build lives elsewhere.++### 1.4 Models++Nothing to pre-install: the app downloads from HuggingFace on first use, then converts on-device (one-time, ~2–6 min for 8B). Per-file `sha256` is verified against a published manifest and resumable via HTTP Range.++Manual seed (offline machines): place the MLX repo files under++```+~\.edge0\models\edge0-8b\ (chat_template.jinja, model*.safetensors, lora_edge0_8b.safetensors, tokenizer…)+~\.edge0\models\edge0-35b\ (…sharded safetensors, lora_edge0_35b.safetensors…)+```++The converter output is `models\edge0-<tier>-gguf\edge0-<tier>.gguf` + LoRA adapter; conversion is idempotent (sha-gated). Home dir is `EDGE0_HOME` (default `~\.edge0`).++### 1.5 Run the app++Launch `edge0-app.exe` (or install the NSIS package). Typical flow:++1. **Models page** — pick 8B (fast, ~5 GB) or 35B (~21 GB); *Download* → auto *Convert* → *Load*.+2. **Chat page** — streamed Markdown answers; the engine runs as a supervised child process and is killed with the app (Windows Job Object, `KILL_ON_JOB_CLOSE`).+3. **Doctor** (bottom of Models page) — one-click health check: engine binary, model files, disk, env.+4. Troubleshooting: engine/convert logs land in `~\.edge0\logs\`.++Engine API (the app uses it internally, you can point any OpenAI-compatible client at it): `http://127.0.0.1:<port>/v1/chat/completions`, loopback-only. Load params (process contract): `-ngl 99 -cmoe --ctx-size 8192 --flash-attn on --pool-mb <tier×RAM clamp> --mem-budget-mb …`.++### 1.6 Test it++```powershell+cd app\src-tauri+cargo test # fast suite: resume/probe logic against a local fake server++# end-to-end, real model (downloads 4.5 GB if not seeded):+cargo test --test real8b -- --ignored --nocapture++# throughput reproduction (expects the table in §2, ±day-to-day drift):+python ..\..\tools\r3_bench.py --tier 8b+python ..\..\tools\r3_bench.py --tier 35b+```++`r3_bench.py` resolves paths with the same contract as the app: the engine from the depot build dir+(`EDGE0_BIN_DIR` override honored), the converted GGUF from the app's model home (`EDGE0_HOME`,+default `~\.edge0\models`) or a repo-local `models/` when present; results land in `benchmarks/r3/`.++```powershell+# patch-replay gate (no compile, seconds):+pwsh ..\..\scripts\vendor-build.ps1 -AssembleOnly+```++---++## 2. Performance++Reference machine: **Intel i7-14700K · AMD Radeon RX 9070 GRE (Vulkan) · 48 GB DDR5 · Windows 11**, steady-state (`-ngl 99 -cmoe`), bench medians of 3 reps (`tools/r3_bench.py`, ~240-token mixed-language prompt, native context).++| model | prefill (tok/s) | decode (tok/s) | prefill of 240-tok prompt |+|---|---:|---:|---:|+| edge0-8B-A1B | ~212 | ~44.8 | ~1.1 s |+| edge0-35B-A3B | ~70 | ~27.7 | ~3.7 s |++Context to keep when reading these numbers:++- Decode is the *token-generation* rate after the prompt is processed; the A1B / A3B active-parameter counts explain why a 35B model decodes at 27+ tok/s.+- Short prompts are much faster than the 240-token column above: the app's first live request on 8B showed **~0.28 s to first token** for a 17-token prompt (engine log). The app runs with `--ctx-size 8192`; benches above use native context (131k / 262k).+- These are warm-RAM measurements on the 48 GB reference machine (a test bed, not a product assumption). On the 16 GB / 8 GB product tiers, experts are served by mmap page-faults and decode drops with memory pressure; a process-level memory cap (`--mem-budget-mb`) is applied automatically from physical RAM to keep the OS working set sane (it measurably *helps* under pressure).+- Same-condition A/B against unpatched vanilla llama.cpp (vendor tree with the patch bands skipped) shows the patch set costs nothing (8B: 41.5 vs 39.5 decode; 35B: 27.2 vs 27.4 — within machine drift).+- Expect day-to-day drift of a few percent on this class of machine; compare like-for-like, same day, same process if you benchmark.++---++## 3. Technical Details++### 3.1 Architecture++```mermaid+flowchart LR+ subgraph ondevice ["On-device, first run"]+ A[MLX safetensors<br/>int4 g64] -->|repack, bit-exact<br/>no requant| B[GGUF Q4_1<br/>edge0-tier.gguf]+ A2[MLX LoRA] -->|fuse + adapt| B2[GGUF adapter]+ end+ B --> C[("pinned llama.cpp fork<br/>7ab4ee7 + 8 patches")]+ B2 --> C+ C -->|Vulkan: dense attn / GDN / norms| D[(GPU)]+ C -->|"-cmoe: expert weights"| E[(CPU, mmap +<br/>L1 advisory pool)]+ C --> F[llama-server<br/>127.0.0.1 OpenAI API]+ F --> G[Tauri 2 shell<br/>supervisor + chat UI]+```++```mermaid+flowchart TB+ subgraph build ["Source-of-truth layout (open source)"]+ U[github ggml-org/llama.cpp] -->|detached pin, never edited| V[vendor/llama.cpp @7ab4ee7]+ P[patches/llama.cpp/common+windows] -->|git am --3way into per-platform worktree| W[wt/win]+ V --> W+ S[serve/*.cc edge0 code] -->|CMake glob patch #3| W+ end+```++### 3.2 Repo map+```+serve/ edge0 C++ pieces compiled into libllama (advisory prefetch router, memory budget)+tools/ MLX→GGUF converter chain (repack + LoRA adapter + catalog) and the throughput bench+app/ Tauri 2 shell (src-tauri/ Rust, src/ React) — see app/README.md+scripts/ vendor-build.ps1 — engine assembly: patch replay into an isolated worktree+```++The engine changes live at the monorepo root, not in a fork: `vendor/llama.cpp` is the pinned+pristine upstream checkout (never patched in place) and `patches/llama.cpp/` carries the 8+hook-point patches + band README (`common/`, `windows/` here; `android/` for the companion app).+`windows/` deliberately ships **no** nested `patches/` copy — one source of truth, no drift.++### 3.3 Known gaps (as of this release)++- Installer is **unsigned** (SmartScreen warning on first run); no auto-updater yet.+- Engine is not yet bundled inside the installer — portable builds assume the engine build dir; bundling is on the roadmap.+- The `--pool-mb` L1 pool is env-dormant on Windows pending the final memory-tier A/B; the app clamps `--mem-budget-mb` regardless.+- 35B on ≤16 GB machines is functional but paging-bound; documented floor is 8 GB *working with* the memory cap, at reduced tok/s.----> ✅ 源码已于 **2026-09-30** 开源,本 README 将随源码落库补全完整的构建-> 与使用文档。Windows runtime:edge0 流式核心的原生 C++17 移植(CMake-> 构建)+ **Vulkan** 计算后端,`edge0` 核心(streaming mmap / cache /-> layer / MoE)镜像自上游 Python 树,沿用同一套配方。**统一推理框架**-> 将于 **2026 Q4** 发布,详见[根 README 路线图](../README_zh.md)。+*Issues and bench results against other hardware welcome — attach `~\.edge0\logs\engine-*.log` and the `doctor` page screenshot.*diff --git a/windows/app/README.md b/windows/app/README.mdnew file mode 100644index 0000000..3ba3e1f--- /dev/null+++ b/windows/app/README.md@@ -0,0 +1,60 @@+# edge0 Windows app — Tauri 2 shell++The desktop shell: model download (into `~/.edge0`) → on-device MLX→GGUF conversion → supervised+`llama-server` child process → streamed Markdown chat.++## Dev run++```powershell+# 0) prerequisites: node + cargo installed; engine built (see ../scripts/vendor-build.ps1)+cd app+npm install+npx tauri dev # window (vite:1420 + rust shell)+```++Headless end-to-end (isolated test home, re-runnable — Range-resume keeps it idempotent):++```powershell+cd app\src-tauri+cargo test # fast suite: fake-source Range resume tri-state+cargo test --test real8b -- --ignored --nocapture # full chain: 4.5 GB download -> convert -> engine -> chat+```++## Environment overrides (every path is overridable — test isolation is a first-class discipline)++| env | default | purpose |+|---|---|---|+| `EDGE0_HOME` | `%USERPROFILE%\.edge0` | app home (models/state/logs/tmp) |+| `EDGE0_REPO` | this repo checkout | where `tools/` conversion scripts live |+| `EDGE0_PY` | `python` | interpreter for the converter chain |+| `EDGE0_BIN_DIR` | depot engine build dir (`…/wt/win/build-vk/bin/Release`) | directory containing `llama-server.exe` |+| `EDGE0_PHYS_MEM_GB` | detected (conservative) | override for the memory-tier clamp |+| `EDGE0_TEST_SOURCE` | `modelscope` | source pin for headless tests (`huggingface` also supported) |++## Home layout (`~/.edge0`)++```+models/edge0-<tier>/ download target (dir name is a hard contract of the converter;+ per-file sha256 verified before atomic rename)+models/edge0-<tier>-gguf/ conversion output (gguf + adapter + manifest.json idempotency gate)+state/downloads/<t>.json resume checkpoints state/verified-<t>.json per-file sha ledger+state/models.json installed-model registry+logs/engine-*.log, logs/convert-*.log engine & converter output+tmp/<t>.<key>.part in-flight download parts+```++## Proof-of-life telemetry++We require positive proof that a mechanism is actually active before trusting a number+(measured culture: past incidents taught us silent no-ops look identical to success):++- after loading 35B, the engine log must show `POOL2 init` with the resolver line, or the UI+ marks the pool as not-in-effect;+- headless tests assert three things together: phase=ready + registered artifact sha + chat+ returning real Markdown structure (tables/code blocks).++## Packaging notes++The installer currently ships the shell only; the engine and the Python converter are expected+on the build/dev machine (env-overridable paths above). Bundling engine+converter into the+installer, code signing, and an auto-updater are on the roadmap.diff --git a/windows/app/index.html b/windows/app/index.htmlnew file mode 100644index 0000000..b144af3--- /dev/null+++ b/windows/app/index.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>edge0</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/windows/app/package-lock.json b/windows/app/package-lock.jsonnew file mode 100644index 0000000..9ea6713--- /dev/null+++ b/windows/app/package-lock.json@@ -0,0 +1,4030 @@+{+ "name": "edge0-app-ui",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "edge0-app-ui",+ "version": "0.1.0",+ "dependencies": {+ "@tauri-apps/api": "^2.11.1",+ "lucide-react": "^1.46.0",+ "react": "^19.3.0",+ "react-dom": "^19.3.0",+ "streamdown": "^2.6.0"+ },+ "devDependencies": {+ "@tailwindcss/typography": "^0.5.20",+ "@tailwindcss/vite": "^4.3.3",+ "@tauri-apps/cli": "^2.11.4",+ "@types/react": "^19.3.0",+ "@types/react-dom": "^19.3.0",+ "@vitejs/plugin-react": "^6.1.1",+ "tailwindcss": "^4.3.3",+ "typescript": "^7.0.2",+ "vite": "^8.3.0"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/remapping": {+ "version": "2.3.5",+ "resolved": "https://registry.npmmirror.com/@jridgewell/remapping/-/remapping-2.3.5.tgz",+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.6.0",+ "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@oxc-project/types": {+ "version": "0.151.0",+ "resolved": "https://registry.npmmirror.com/@oxc-project/types/-/types-0.151.0.tgz",+ "integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/oxc-project"+ }+ },+ "node_modules/@rolldown/binding-android-arm-eabi": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",+ "integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-android-arm64": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",+ "integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-arm64": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",+ "integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-x64": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",+ "integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-freebsd-x64": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",+ "integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",+ "integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-gnu": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",+ "integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-musl": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",+ "integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",+ "integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-s390x-gnu": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",+ "integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-gnu": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",+ "integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-musl": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",+ "integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-openharmony-arm64": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",+ "integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-arm64-msvc": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",+ "integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-x64-msvc": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",+ "integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@tailwindcss/node": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/node/-/node-4.3.3.tgz",+ "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/remapping": "^2.3.5",+ "enhanced-resolve": "^5.24.1",+ "jiti": "^2.7.0",+ "lightningcss": "1.32.0",+ "magic-string": "^0.30.21",+ "source-map-js": "^1.2.1",+ "tailwindcss": "4.3.3"+ }+ },+ "node_modules/@tailwindcss/oxide": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide/-/oxide-4.3.3.tgz",+ "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 20"+ },+ "optionalDependencies": {+ "@tailwindcss/oxide-android-arm64": "4.3.3",+ "@tailwindcss/oxide-darwin-arm64": "4.3.3",+ "@tailwindcss/oxide-darwin-x64": "4.3.3",+ "@tailwindcss/oxide-freebsd-x64": "4.3.3",+ "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3",+ "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3",+ "@tailwindcss/oxide-linux-arm64-musl": "4.3.3",+ "@tailwindcss/oxide-linux-x64-gnu": "4.3.3",+ "@tailwindcss/oxide-linux-x64-musl": "4.3.3",+ "@tailwindcss/oxide-wasm32-wasi": "4.3.3",+ "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3",+ "@tailwindcss/oxide-win32-x64-msvc": "4.3.3"+ }+ },+ "node_modules/@tailwindcss/oxide-android-arm64": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz",+ "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-darwin-arm64": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz",+ "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-darwin-x64": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz",+ "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-freebsd-x64": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz",+ "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz",+ "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm64-gnu": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz",+ "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm64-musl": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz",+ "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-x64-gnu": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz",+ "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-x64-musl": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz",+ "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz",+ "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==",+ "bundleDependencies": [+ "@napi-rs/wasm-runtime",+ "@emnapi/core",+ "@emnapi/runtime",+ "@tybys/wasm-util",+ "@emnapi/wasi-threads",+ "tslib"+ ],+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.11.1",+ "@emnapi/runtime": "^1.11.1",+ "@emnapi/wasi-threads": "^1.2.2",+ "@napi-rs/wasm-runtime": "^1.1.4",+ "@tybys/wasm-util": "^0.10.2",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",+ "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-win32-x64-msvc": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz",+ "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/typography": {+ "version": "0.5.20",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/typography/-/typography-0.5.20.tgz",+ "integrity": "sha512-hwbzQuNUfcPvbegQFatVPl/MY/tcM9KLl963hQ5laJKPh81TEZ1+dNG9PirGvcaDBkp+BCshExAyKVPW91dozw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "postcss-selector-parser": "6.0.10"+ },+ "peerDependencies": {+ "tailwindcss": ">=3.0.0 || >=4.0.0 || insiders"+ }+ },+ "node_modules/@tailwindcss/vite": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/@tailwindcss/vite/-/vite-4.3.3.tgz",+ "integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@tailwindcss/node": "4.3.3",+ "@tailwindcss/oxide": "4.3.3",+ "tailwindcss": "4.3.3"+ },+ "peerDependencies": {+ "vite": "^5.2.0 || ^6 || ^7 || ^8"+ }+ },+ "node_modules/@tauri-apps/api": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.12.0.tgz",+ "integrity": "sha512-fUSxFX8VABYe9W9K5ROdEaKVkNUFRcMSRofjruvaxztXA+I0XnQHcYHF8m/a6iExRUxsUf0HsFWhPBuH9IgzJw==",+ "license": "Apache-2.0 OR MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/tauri"+ }+ },+ "node_modules/@tauri-apps/cli": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.12.0.tgz",+ "integrity": "sha512-GIShnAR4C16kSTA8NO02fo8fOw/I5z5sAUEB5S2HlPHFnBkbihL4c9a/MpkxOm1+q5S+tFd3X4QUjHWxfyGzpQ==",+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "bin": {+ "tauri": "tauri.js"+ },+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/tauri"+ },+ "optionalDependencies": {+ "@tauri-apps/cli-darwin-arm64": "2.12.0",+ "@tauri-apps/cli-darwin-x64": "2.12.0",+ "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.0",+ "@tauri-apps/cli-linux-arm64-gnu": "2.12.0",+ "@tauri-apps/cli-linux-arm64-musl": "2.12.0",+ "@tauri-apps/cli-linux-riscv64-gnu": "2.12.0",+ "@tauri-apps/cli-linux-x64-gnu": "2.12.0",+ "@tauri-apps/cli-linux-x64-musl": "2.12.0",+ "@tauri-apps/cli-win32-arm64-msvc": "2.12.0",+ "@tauri-apps/cli-win32-ia32-msvc": "2.12.0",+ "@tauri-apps/cli-win32-x64-msvc": "2.12.0"+ }+ },+ "node_modules/@tauri-apps/cli-darwin-arm64": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.0.tgz",+ "integrity": "sha512-v5J+jISihLGtih1+3yWagbsL+5dbLZORu4vaSI0vhY0Heb+MAW+T/1s1RyKxrQrwEPGBG5kqwfDDTnSbmVkuqA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-darwin-x64": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.0.tgz",+ "integrity": "sha512-g27I07pfW/dMS8vcNqB9lamgKF0TqLlcy8e7t9qDGsB1iaeyjJWb2TgBF4tM9ZwLqPAZUXbsz28oXljO12WC4g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.0.tgz",+ "integrity": "sha512-gXyQ710fNc99YuxFxNyeX9PLSrIpbtgBBj7GQo9tSeRT6fIK40q3/gm7X5jqZo7mWLR2m0R/2ALd3vAWo0Z32Q==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-arm64-gnu": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.0.tgz",+ "integrity": "sha512-H9cyXuq9WgxoHh2NZ+R+oN+W78x5UwaBDEp0/fmqUUkaBoioCuOZErM9xKiIV6bpNAhmw1RoWZ49u37q/vaiAg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-arm64-musl": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.0.tgz",+ "integrity": "sha512-5tFuk3JKMBa1M/iN4gN32OYlSfhY3aqb5PO3zCugxaT+sfecyMKpc3EM9VDbhmwWBE9QD4Tfj7wGhlqx2yy2pQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-riscv64-gnu": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.0.tgz",+ "integrity": "sha512-LOrMyV+nb7pKq8P0BZtTBQuyzm1ORjn16R9MlupmxuT5LqxtuYJlw3VMwbaeXCToJ8jbP5u9JnkfmbqDlvETXw==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-x64-gnu": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.0.tgz",+ "integrity": "sha512-aMIkI+X9qvD2+k80QZB3tuOYT41/cEheikC510CwAIZ31KLXORsRASYYzM4mi1/58ICmtzSLFhCC08keir7COw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-x64-musl": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.0.tgz",+ "integrity": "sha512-9gl3NhUbfuGhSKjeGCypKSdtoezOQRcDUrkhTWtLQEjnajets6peO6NadgI2DF0OzbiiFOzrnnIGMwBS+Ap6Iw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-win32-arm64-msvc": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.0.tgz",+ "integrity": "sha512-1W+v86wsYLuyBDN0iDessD4CD9o+yNyO0m8Dp3+/vfjiZrJ/v7R7/aTRBeikaq2tLGgxeag0gxnFggBNBGw91A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-win32-ia32-msvc": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.0.tgz",+ "integrity": "sha512-SsBjvq4f7YaBGqcWoE3cycoItPf0SrQeqFqWWgfxoeZWAIz01E31LDSeZ2p/etJiIY0R9oi045chkFfb0O7WGw==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-win32-x64-msvc": {+ "version": "2.12.0",+ "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.0.tgz",+ "integrity": "sha512-9zzDKYUH4TKKBgRdDdVQX8fiRO5gJ8hD1nGsHU9DOHG5Jpm3arjbu9Xg1frR20EusG3Sl8X0dppoO/4EoUXUGg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@types/debug": {+ "version": "4.1.13",+ "resolved": "https://registry.npmmirror.com/@types/debug/-/debug-4.1.13.tgz",+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "license": "MIT"+ },+ "node_modules/@types/estree-jsx": {+ "version": "1.0.5",+ "resolved": "https://registry.npmmirror.com/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "*"+ }+ },+ "node_modules/@types/hast": {+ "version": "3.0.5",+ "resolved": "https://registry.npmmirror.com/@types/hast/-/hast-3.0.5.tgz",+ "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/mdast": {+ "version": "4.0.4",+ "resolved": "https://registry.npmmirror.com/@types/mdast/-/mdast-4.0.4.tgz",+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },+ "node_modules/@types/react": {+ "version": "19.3.0",+ "resolved": "https://registry.npmmirror.com/@types/react/-/react-19.3.0.tgz",+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "19.3.0",+ "resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-19.3.0.tgz",+ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "^19.3.0"+ }+ },+ "node_modules/@types/unist": {+ "version": "3.0.3",+ "resolved": "https://registry.npmmirror.com/@types/unist/-/unist-3.0.3.tgz",+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",+ "license": "MIT"+ },+ "node_modules/@typescript/typescript-aix-ppc64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-darwin-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-darwin-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-freebsd-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-freebsd-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-arm": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-loong64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-mips64el": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-ppc64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-riscv64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-s390x": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-netbsd-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-netbsd-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-openbsd-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-openbsd-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-sunos-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-win32-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-win32-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@ungap/structured-clone": {+ "version": "1.4.0",+ "resolved": "https://registry.npmmirror.com/@ungap/structured-clone/-/structured-clone-1.4.0.tgz",+ "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==",+ "license": "ISC"+ },+ "node_modules/@vitejs/plugin-react": {+ "version": "6.1.1",+ "resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-6.1.1.tgz",+ "integrity": "sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@rolldown/pluginutils": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "peerDependencies": {+ "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",+ "babel-plugin-react-compiler": "^1.0.0",+ "oxc-transform-react": "^0.145.0",+ "vite": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "@rolldown/plugin-babel": {+ "optional": true+ },+ "babel-plugin-react-compiler": {+ "optional": true+ },+ "oxc-transform-react": {+ "optional": true+ }+ }+ },+ "node_modules/bail": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/bail/-/bail-2.0.2.tgz",+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/ccount": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/ccount/-/ccount-2.0.1.tgz",+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/character-entities/-/character-entities-2.0.2.tgz",+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-html4": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/character-entities-html4/-/character-entities-html4-2.1.0.tgz",+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-legacy": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-reference-invalid": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmmirror.com/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/comma-separated-tokens": {+ "version": "2.0.3",+ "resolved": "https://registry.npmmirror.com/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/cssesc": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz",+ "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "cssesc": "bin/cssesc"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decode-named-character-reference": {+ "version": "1.3.0",+ "resolved": "https://registry.npmmirror.com/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",+ "license": "MIT",+ "dependencies": {+ "character-entities": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/dequal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmmirror.com/dequal/-/dequal-2.0.3.tgz",+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/devlop": {+ "version": "1.1.0",+ "resolved": "https://registry.npmmirror.com/devlop/-/devlop-1.1.0.tgz",+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/enhanced-resolve": {+ "version": "5.25.1",+ "resolved": "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.25.1.tgz",+ "integrity": "sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "tapable": "^2.3.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/entities": {+ "version": "6.0.1",+ "resolved": "https://registry.npmmirror.com/entities/-/entities-6.0.1.tgz",+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "5.0.0",+ "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/estree-util-is-identifier-name": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmmirror.com/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/hast-util-from-parse5": {+ "version": "8.0.3",+ "resolved": "https://registry.npmmirror.com/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz",+ "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "devlop": "^1.0.0",+ "hastscript": "^9.0.0",+ "property-information": "^7.0.0",+ "vfile": "^6.0.0",+ "vfile-location": "^5.0.0",+ "web-namespaces": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-parse-selector": {+ "version": "4.0.0",+ "resolved": "https://registry.npmmirror.com/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz",+ "integrity": "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-raw": {+ "version": "9.1.0",+ "resolved": "https://registry.npmmirror.com/hast-util-raw/-/hast-util-raw-9.1.0.tgz",+ "integrity": "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "hast-util-from-parse5": "^8.0.0",+ "hast-util-to-parse5": "^8.0.0",+ "html-void-elements": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "parse5": "^7.0.0",+ "unist-util-position": "^5.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0",+ "web-namespaces": "^2.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-sanitize": {+ "version": "5.0.2",+ "resolved": "https://registry.npmmirror.com/hast-util-sanitize/-/hast-util-sanitize-5.0.2.tgz",+ "integrity": "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "unist-util-position": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-jsx-runtime": {+ "version": "2.3.6",+ "resolved": "https://registry.npmmirror.com/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "hast-util-whitespace": "^3.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "style-to-js": "^1.0.0",+ "unist-util-position": "^5.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmmirror.com/hast-util-to-parse5/-/hast-util-to-parse5-8.0.1.tgz",+ "integrity": "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "web-namespaces": "^2.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-whitespace": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hastscript": {+ "version": "9.0.1",+ "resolved": "https://registry.npmmirror.com/hastscript/-/hastscript-9.0.1.tgz",+ "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "hast-util-parse-selector": "^4.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/html-url-attributes": {+ "version": "3.0.1",+ "resolved": "https://registry.npmmirror.com/html-url-attributes/-/html-url-attributes-3.0.1.tgz",+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/html-void-elements": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/html-void-elements/-/html-void-elements-3.0.0.tgz",+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/inline-style-parser": {+ "version": "0.2.7",+ "resolved": "https://registry.npmmirror.com/inline-style-parser/-/inline-style-parser-0.2.7.tgz",+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",+ "license": "MIT"+ },+ "node_modules/is-alphabetical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/is-alphabetical/-/is-alphabetical-2.0.1.tgz",+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-alphanumerical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",+ "license": "MIT",+ "dependencies": {+ "is-alphabetical": "^2.0.0",+ "is-decimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-decimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/is-decimal/-/is-decimal-2.0.1.tgz",+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-hexadecimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-plain-obj": {+ "version": "4.1.0",+ "resolved": "https://registry.npmmirror.com/is-plain-obj/-/is-plain-obj-4.1.0.tgz",+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/jiti": {+ "version": "2.7.0",+ "resolved": "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz",+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.32.0.tgz",+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.32.0",+ "lightningcss-darwin-arm64": "1.32.0",+ "lightningcss-darwin-x64": "1.32.0",+ "lightningcss-freebsd-x64": "1.32.0",+ "lightningcss-linux-arm-gnueabihf": "1.32.0",+ "lightningcss-linux-arm64-gnu": "1.32.0",+ "lightningcss-linux-arm64-musl": "1.32.0",+ "lightningcss-linux-x64-gnu": "1.32.0",+ "lightningcss-linux-x64-musl": "1.32.0",+ "lightningcss-win32-arm64-msvc": "1.32.0",+ "lightningcss-win32-x64-msvc": "1.32.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/longest-streak": {+ "version": "3.1.0",+ "resolved": "https://registry.npmmirror.com/longest-streak/-/longest-streak-3.1.0.tgz",+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/lucide-react": {+ "version": "1.48.0",+ "resolved": "https://registry.npmmirror.com/lucide-react/-/lucide-react-1.48.0.tgz",+ "integrity": "sha512-R0CIKY/fXiC6y9xRBADgsK+VW2p/pcTJOMhLZf1T+uG+vJUvyUR02nGOgmIIC7MPkiNK4Ox8QDnbqF8rJYWPZQ==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/markdown-table": {+ "version": "3.0.4",+ "resolved": "https://registry.npmmirror.com/markdown-table/-/markdown-table-3.0.4.tgz",+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/marked": {+ "version": "17.0.6",+ "resolved": "https://registry.npmmirror.com/marked/-/marked-17.0.6.tgz",+ "integrity": "sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/mdast-util-find-and-replace": {+ "version": "3.0.2",+ "resolved": "https://registry.npmmirror.com/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "escape-string-regexp": "^5.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-from-markdown": {+ "version": "2.0.3",+ "resolved": "https://registry.npmmirror.com/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark": "^4.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm": {+ "version": "3.1.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-gfm-autolink-literal": "^2.0.0",+ "mdast-util-gfm-footnote": "^2.0.0",+ "mdast-util-gfm-strikethrough": "^2.0.0",+ "mdast-util-gfm-table": "^2.0.0",+ "mdast-util-gfm-task-list-item": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-autolink-literal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.0.0",+ "mdast-util-find-and-replace": "^3.0.0",+ "micromark-util-character": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-strikethrough": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz",+ "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-table": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "markdown-table": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-task-list-item": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-expression": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-jsx": {+ "version": "3.2.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "parse-entities": "^4.0.0",+ "stringify-entities": "^4.0.0",+ "unist-util-stringify-position": "^4.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdxjs-esm": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-phrasing": {+ "version": "4.1.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-hast": {+ "version": "13.2.1",+ "resolved": "https://registry.npmmirror.com/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "trim-lines": "^3.0.0",+ "unist-util-position": "^5.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-markdown": {+ "version": "2.1.3",+ "resolved": "https://registry.npmmirror.com/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.3.tgz",+ "integrity": "sha512-wgyJtgUkUcdU7zci7uuwc/tzoAhm0TswWhaXuvnWolqug+8jY7bgNkBBL0dYBnHgc/tHL7lCzRdPsdUxUKKBqw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-phrasing": "^4.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "micromark-util-html-tag-name": "^2.0.0",+ "unist-util-visit": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-string": {+ "version": "4.0.0",+ "resolved": "https://registry.npmmirror.com/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark": {+ "version": "4.0.3",+ "resolved": "https://registry.npmmirror.com/micromark/-/micromark-4.0.3.tgz",+ "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.0.0",+ "debug": "^4.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-edit-map": "^1.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-core-commonmark": {+ "version": "2.0.4",+ "resolved": "https://registry.npmmirror.com/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz",+ "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-destination": "^2.0.0",+ "micromark-factory-label": "^2.0.0",+ "micromark-factory-space": "^2.1.0",+ "micromark-factory-title": "^2.0.0",+ "micromark-factory-whitespace": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-edit-map": "^1.0.0",+ "micromark-util-html-tag-name": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.3"+ }+ },+ "node_modules/micromark-extension-gfm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",+ "license": "MIT",+ "dependencies": {+ "micromark-extension-gfm-autolink-literal": "^2.0.0",+ "micromark-extension-gfm-footnote": "^2.0.0",+ "micromark-extension-gfm-strikethrough": "^2.0.0",+ "micromark-extension-gfm-table": "^2.0.0",+ "micromark-extension-gfm-tagfilter": "^2.0.0",+ "micromark-extension-gfm-task-list-item": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-autolink-literal": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-strikethrough": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-table": {+ "version": "2.1.2",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz",+ "integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-tagfilter": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-task-list-item": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-factory-destination": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-label": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-space": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz",+ "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-title": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-whitespace": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-character": {+ "version": "2.1.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-character/-/micromark-util-character-2.1.1.tgz",+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-chunked": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-classify-character": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-combine-extensions": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-numeric-character-reference": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-string": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-edit-map": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz",+ "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-encode": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-html-tag-name": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-normalize-identifier": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-resolve-all": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-sanitize-uri": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-subtokenize": {+ "version": "2.1.0",+ "resolved": "https://registry.npmmirror.com/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-symbol": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-types": {+ "version": "2.0.3",+ "resolved": "https://registry.npmmirror.com/micromark-util-types/-/micromark-util-types-2.0.3.tgz",+ "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.19",+ "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.19.tgz",+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/parse-entities": {+ "version": "4.0.2",+ "resolved": "https://registry.npmmirror.com/parse-entities/-/parse-entities-4.0.2.tgz",+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0",+ "character-entities-legacy": "^3.0.0",+ "character-reference-invalid": "^2.0.0",+ "decode-named-character-reference": "^1.0.0",+ "is-alphanumerical": "^2.0.0",+ "is-decimal": "^2.0.0",+ "is-hexadecimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/parse-entities/node_modules/@types/unist": {+ "version": "2.0.11",+ "resolved": "https://registry.npmmirror.com/@types/unist/-/unist-2.0.11.tgz",+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",+ "license": "MIT"+ },+ "node_modules/parse5": {+ "version": "7.3.0",+ "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz",+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",+ "license": "MIT",+ "dependencies": {+ "entities": "^6.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.7",+ "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.7.tgz",+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.28",+ "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.28.tgz",+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.18",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/postcss-selector-parser": {+ "version": "6.0.10",+ "resolved": "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz",+ "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cssesc": "^3.0.0",+ "util-deprecate": "^1.0.2"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/property-information": {+ "version": "7.2.0",+ "resolved": "https://registry.npmmirror.com/property-information/-/property-information-7.2.0.tgz",+ "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/react": {+ "version": "19.3.0",+ "resolved": "https://registry.npmmirror.com/react/-/react-19.3.0.tgz",+ "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-dom": {+ "version": "19.3.0",+ "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-19.3.0.tgz",+ "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",+ "license": "MIT",+ "dependencies": {+ "scheduler": "^0.28.0"+ },+ "peerDependencies": {+ "react": "^19.3.0"+ }+ },+ "node_modules/rehype-harden": {+ "version": "1.1.8",+ "resolved": "https://registry.npmmirror.com/rehype-harden/-/rehype-harden-1.1.8.tgz",+ "integrity": "sha512-Qn7vR1xrf6fZCrkm9TDWi/AB4ylrHy+jqsNm1EHOAmbARYA6gsnVJBq/sdBh6kmT4NEZxH5vgIjrscefJAOXcw==",+ "license": "MIT",+ "dependencies": {+ "unist-util-visit": "^5.0.0"+ }+ },+ "node_modules/rehype-raw": {+ "version": "7.0.0",+ "resolved": "https://registry.npmmirror.com/rehype-raw/-/rehype-raw-7.0.0.tgz",+ "integrity": "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "hast-util-raw": "^9.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/rehype-sanitize": {+ "version": "6.0.0",+ "resolved": "https://registry.npmmirror.com/rehype-sanitize/-/rehype-sanitize-6.0.0.tgz",+ "integrity": "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "hast-util-sanitize": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-gfm": {+ "version": "4.0.1",+ "resolved": "https://registry.npmmirror.com/remark-gfm/-/remark-gfm-4.0.1.tgz",+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-gfm": "^3.0.0",+ "micromark-extension-gfm": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-parse": {+ "version": "11.0.0",+ "resolved": "https://registry.npmmirror.com/remark-parse/-/remark-parse-11.0.0.tgz",+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-rehype": {+ "version": "11.1.2",+ "resolved": "https://registry.npmmirror.com/remark-rehype/-/remark-rehype-11.1.2.tgz",+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-stringify": {+ "version": "11.0.0",+ "resolved": "https://registry.npmmirror.com/remark-stringify/-/remark-stringify-11.0.0.tgz",+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remend": {+ "version": "1.3.1",+ "resolved": "https://registry.npmmirror.com/remend/-/remend-1.3.1.tgz",+ "integrity": "sha512-N3DiY5qbRPoa5vkxn1oDLMyXOVTeo6Hp+XOj6SIqJAYUgLS0Q587gILPMom/qm86AQ/ZrcOdwEIzCz8V3J0nxQ==",+ "license": "Apache-2.0"+ },+ "node_modules/rolldown": {+ "version": "1.2.11",+ "resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.11.tgz",+ "integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@oxc-project/types": "=0.151.0",+ "@rolldown/pluginutils": "^1.0.0"+ },+ "bin": {+ "rolldown": "bin/cli.mjs"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "optionalDependencies": {+ "@rolldown/binding-android-arm-eabi": "1.2.11",+ "@rolldown/binding-android-arm64": "1.2.11",+ "@rolldown/binding-darwin-arm64": "1.2.11",+ "@rolldown/binding-darwin-x64": "1.2.11",+ "@rolldown/binding-freebsd-x64": "1.2.11",+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.11",+ "@rolldown/binding-linux-arm64-gnu": "1.2.11",+ "@rolldown/binding-linux-arm64-musl": "1.2.11",+ "@rolldown/binding-linux-ppc64-gnu": "1.2.11",+ "@rolldown/binding-linux-s390x-gnu": "1.2.11",+ "@rolldown/binding-linux-x64-gnu": "1.2.11",+ "@rolldown/binding-linux-x64-musl": "1.2.11",+ "@rolldown/binding-openharmony-arm64": "1.2.11",+ "@rolldown/binding-win32-arm64-msvc": "1.2.11",+ "@rolldown/binding-win32-x64-msvc": "1.2.11"+ }+ },+ "node_modules/scheduler": {+ "version": "0.28.0",+ "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.28.0.tgz",+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",+ "license": "MIT"+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/space-separated-tokens": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/streamdown": {+ "version": "2.6.0",+ "resolved": "https://registry.npmmirror.com/streamdown/-/streamdown-2.6.0.tgz",+ "integrity": "sha512-nQZVUn4GvB2R5SAlDNph20iKZeW+RM4gv6G1H3ACypEnmQf8PgTHZ/1Ta2OACRwQ2coK7aW5AeIAa7Ls5zk+RA==",+ "license": "Apache-2.0",+ "dependencies": {+ "clsx": "^2.1.1",+ "hast-util-to-jsx-runtime": "^2.3.6",+ "html-url-attributes": "^3.0.1",+ "marked": "^17.0.1",+ "rehype-harden": "^1.1.8",+ "rehype-raw": "^7.0.0",+ "rehype-sanitize": "^6.0.0",+ "remark-gfm": "^4.0.1",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.1.2",+ "remend": "1.3.1",+ "tailwind-merge": "^3.6.0",+ "unified": "^11.0.5",+ "unist-util-visit": "^5.1.0",+ "unist-util-visit-parents": "^6.0.2"+ },+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/stringify-entities": {+ "version": "4.0.4",+ "resolved": "https://registry.npmmirror.com/stringify-entities/-/stringify-entities-4.0.4.tgz",+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",+ "license": "MIT",+ "dependencies": {+ "character-entities-html4": "^2.0.0",+ "character-entities-legacy": "^3.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/style-to-js": {+ "version": "1.1.21",+ "resolved": "https://registry.npmmirror.com/style-to-js/-/style-to-js-1.1.21.tgz",+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",+ "license": "MIT",+ "dependencies": {+ "style-to-object": "1.0.14"+ }+ },+ "node_modules/style-to-object": {+ "version": "1.0.14",+ "resolved": "https://registry.npmmirror.com/style-to-object/-/style-to-object-1.0.14.tgz",+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",+ "license": "MIT",+ "dependencies": {+ "inline-style-parser": "0.2.7"+ }+ },+ "node_modules/tailwind-merge": {+ "version": "3.7.0",+ "resolved": "https://registry.npmmirror.com/tailwind-merge/-/tailwind-merge-3.7.0.tgz",+ "integrity": "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/dcastil"+ }+ },+ "node_modules/tailwindcss": {+ "version": "4.3.3",+ "resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-4.3.3.tgz",+ "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tapable": {+ "version": "2.3.3",+ "resolved": "https://registry.npmmirror.com/tapable/-/tapable-2.3.3.tgz",+ "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/trim-lines": {+ "version": "3.0.1",+ "resolved": "https://registry.npmmirror.com/trim-lines/-/trim-lines-3.0.1.tgz",+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/trough": {+ "version": "2.2.0",+ "resolved": "https://registry.npmmirror.com/trough/-/trough-2.2.0.tgz",+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/typescript": {+ "version": "7.0.2",+ "resolved": "https://registry.npmmirror.com/typescript/-/typescript-7.0.2.tgz",+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc"+ },+ "engines": {+ "node": ">=16.20.0"+ },+ "optionalDependencies": {+ "@typescript/typescript-aix-ppc64": "7.0.2",+ "@typescript/typescript-darwin-arm64": "7.0.2",+ "@typescript/typescript-darwin-x64": "7.0.2",+ "@typescript/typescript-freebsd-arm64": "7.0.2",+ "@typescript/typescript-freebsd-x64": "7.0.2",+ "@typescript/typescript-linux-arm": "7.0.2",+ "@typescript/typescript-linux-arm64": "7.0.2",+ "@typescript/typescript-linux-loong64": "7.0.2",+ "@typescript/typescript-linux-mips64el": "7.0.2",+ "@typescript/typescript-linux-ppc64": "7.0.2",+ "@typescript/typescript-linux-riscv64": "7.0.2",+ "@typescript/typescript-linux-s390x": "7.0.2",+ "@typescript/typescript-linux-x64": "7.0.2",+ "@typescript/typescript-netbsd-arm64": "7.0.2",+ "@typescript/typescript-netbsd-x64": "7.0.2",+ "@typescript/typescript-openbsd-arm64": "7.0.2",+ "@typescript/typescript-openbsd-x64": "7.0.2",+ "@typescript/typescript-sunos-x64": "7.0.2",+ "@typescript/typescript-win32-arm64": "7.0.2",+ "@typescript/typescript-win32-x64": "7.0.2"+ }+ },+ "node_modules/unified": {+ "version": "11.0.5",+ "resolved": "https://registry.npmmirror.com/unified/-/unified-11.0.5.tgz",+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "bail": "^2.0.0",+ "devlop": "^1.0.0",+ "extend": "^3.0.0",+ "is-plain-obj": "^4.0.0",+ "trough": "^2.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-is": {+ "version": "6.0.1",+ "resolved": "https://registry.npmmirror.com/unist-util-is/-/unist-util-is-6.0.1.tgz",+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-position": {+ "version": "5.0.0",+ "resolved": "https://registry.npmmirror.com/unist-util-position/-/unist-util-position-5.0.0.tgz",+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-stringify-position": {+ "version": "4.0.0",+ "resolved": "https://registry.npmmirror.com/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit": {+ "version": "5.1.0",+ "resolved": "https://registry.npmmirror.com/unist-util-visit/-/unist-util-visit-5.1.0.tgz",+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit-parents": {+ "version": "6.0.2",+ "resolved": "https://registry.npmmirror.com/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/vfile": {+ "version": "6.0.3",+ "resolved": "https://registry.npmmirror.com/vfile/-/vfile-6.0.3.tgz",+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-location": {+ "version": "5.0.3",+ "resolved": "https://registry.npmmirror.com/vfile-location/-/vfile-location-5.0.3.tgz",+ "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-message": {+ "version": "4.0.3",+ "resolved": "https://registry.npmmirror.com/vfile-message/-/vfile-message-4.0.3.tgz",+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vite": {+ "version": "8.3.1",+ "resolved": "https://registry.npmmirror.com/vite/-/vite-8.3.1.tgz",+ "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lightningcss": "^1.33.0",+ "picomatch": "^4.0.7",+ "postcss": "^8.5.28",+ "rolldown": "~1.2.9",+ "tinyglobby": "^0.2.17"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "@vitejs/devtools": "^0.7.1",+ "esbuild": "^0.27.0 || ^0.28.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "@vitejs/devtools": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vite/node_modules/lightningcss": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.33.0.tgz",+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.33.0",+ "lightningcss-darwin-arm64": "1.33.0",+ "lightningcss-darwin-x64": "1.33.0",+ "lightningcss-freebsd-x64": "1.33.0",+ "lightningcss-linux-arm-gnueabihf": "1.33.0",+ "lightningcss-linux-arm64-gnu": "1.33.0",+ "lightningcss-linux-arm64-musl": "1.33.0",+ "lightningcss-linux-x64-gnu": "1.33.0",+ "lightningcss-linux-x64-musl": "1.33.0",+ "lightningcss-win32-arm64-msvc": "1.33.0",+ "lightningcss-win32-x64-msvc": "1.33.0"+ }+ },+ "node_modules/vite/node_modules/lightningcss-android-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-darwin-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-darwin-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-freebsd-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-linux-x64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/vite/node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/web-namespaces": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/web-namespaces/-/web-namespaces-2.0.1.tgz",+ "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/zwitch": {+ "version": "2.0.4",+ "resolved": "https://registry.npmmirror.com/zwitch/-/zwitch-2.0.4.tgz",+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ }+ }+}diff --git a/windows/app/package.json b/windows/app/package.jsonnew file mode 100644index 0000000..ad64f1b--- /dev/null+++ b/windows/app/package.json@@ -0,0 +1,30 @@+{+ "name": "edge0-app-ui",+ "private": true,+ "version": "0.1.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "tsc --noEmit && vite build",+ "typecheck": "tsc --noEmit",+ "tauri": "tauri"+ },+ "dependencies": {+ "@tauri-apps/api": "^2.11.1",+ "lucide-react": "^1.46.0",+ "react": "^19.3.0",+ "react-dom": "^19.3.0",+ "streamdown": "^2.6.0"+ },+ "devDependencies": {+ "@tailwindcss/typography": "^0.5.20",+ "@tailwindcss/vite": "^4.3.3",+ "@tauri-apps/cli": "^2.11.4",+ "@types/react": "^19.3.0",+ "@types/react-dom": "^19.3.0",+ "@vitejs/plugin-react": "^6.1.1",+ "tailwindcss": "^4.3.3",+ "typescript": "^7.0.2",+ "vite": "^8.3.0"+ }+}diff --git a/windows/app/src-tauri/Cargo.lock b/windows/app/src-tauri/Cargo.locknew file mode 100644index 0000000..06c343f--- /dev/null+++ b/windows/app/src-tauri/Cargo.lock@@ -0,0 +1,4722 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "alloc-no-stdlib"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"++[[package]]+name = "alloc-stdlib"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"+dependencies = [+ "alloc-no-stdlib",+]++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"++[[package]]+name = "atk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"+dependencies = [+ "atk-sys",+ "glib",+ "libc",+]++[[package]]+name = "atk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.21.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+dependencies = [+ "serde_core",+]++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]++[[package]]+name = "brotli"+version = "9.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+ "brotli-decompressor",+]++[[package]]+name = "brotli-decompressor"+version = "6.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]++[[package]]+name = "bs58"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"+dependencies = [+ "tinyvec",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"+dependencies = [+ "serde",+]++[[package]]+name = "cairo-rs"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"+dependencies = [+ "bitflags 2.13.2",+ "cairo-sys-rs",+ "glib",+ "libc",+ "once_cell",+ "thiserror 1.0.69",+]++[[package]]+name = "cairo-sys-rs"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"+dependencies = [+ "glib-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "camino"+version = "1.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "cargo_toml"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"+dependencies = [+ "semver",+ "serde",+ "toml 1.1.6+spec-1.1.0",+]++[[package]]+name = "cc"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfb"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"+dependencies = [+ "fnv",+ "uuid",+ "web-time",+]++[[package]]+name = "cfg-expr"+version = "0.15.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"+dependencies = [+ "smallvec",+ "target-lexicon",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "rand_core",+]++[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "serde",+ "windows-link",+]++[[package]]+name = "combine"+version = "4.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "cookie"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"+dependencies = [+ "time",+ "version_check",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation",+ "core-graphics-types",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation",+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-channel"+version = "0.5.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "cssparser"+version = "0.37.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"+dependencies = [+ "cssparser-macros",+ "dtoa-short",+ "itoa",+ "phf",+ "smallvec",+]++[[package]]+name = "cssparser-macros"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"+dependencies = [+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "ctor"+version = "1.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"++[[package]]+name = "darling"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 3.0.6",+]++[[package]]+name = "darling_macro"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"+dependencies = [+ "darling_core",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "dbus"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"+dependencies = [+ "libc",+ "libdbus-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "defmt"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"+dependencies = [+ "bitflags 1.3.2",+ "defmt-macros",+]++[[package]]+name = "defmt-macros"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"+dependencies = [+ "defmt-parser",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "defmt-parser"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"+dependencies = [+ "thiserror 2.0.21",+]++[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"+dependencies = [+ "serde_core",+]++[[package]]+name = "derive_more"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.119",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dirs"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users",+ "windows-sys 0.61.2",+]++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "libc",+ "objc2",+]++[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "dlopen2"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4"+dependencies = [+ "dlopen2_derive",+ "libc",+ "once_cell",+ "winapi",+]++[[package]]+name = "dlopen2_derive"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "dom_query"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"+dependencies = [+ "bit-set",+ "cssparser",+ "foldhash",+ "html5ever",+ "precomputed-hash",+ "selectors",+ "tendril",+]++[[package]]+name = "dpi"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"+dependencies = [+ "serde",+]++[[package]]+name = "dtoa"+version = "1.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"++[[package]]+name = "dtoa-short"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"+dependencies = [+ "dtoa",+]++[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"++[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"++[[package]]+name = "edge0-app"+version = "0.1.0"+dependencies = [+ "hex",+ "reqwest 0.12.28",+ "serde",+ "serde_json",+ "sha2",+ "tauri",+ "tauri-build",+ "windows-sys 0.59.0",+]++[[package]]+name = "embed-resource"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml 1.1.6+spec-1.1.0",+ "vswhom",+ "winreg",+]++[[package]]+name = "embed_plist"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "erased-serde"+version = "0.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"+dependencies = [+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "field-offset"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"+dependencies = [+ "memoffset",+ "rustc_version",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"++[[package]]+name = "flate2"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-channel"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"+dependencies = [+ "futures-core",+ "futures-sink",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-executor"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"++[[package]]+name = "futures-macro"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "futures-sink"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "gdk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"+dependencies = [+ "cairo-rs",+ "gdk-pixbuf",+ "gdk-sys",+ "gio",+ "glib",+ "libc",+ "pango",+]++[[package]]+name = "gdk-pixbuf"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"+dependencies = [+ "gdk-pixbuf-sys",+ "gio",+ "glib",+ "libc",+ "once_cell",+]++[[package]]+name = "gdk-pixbuf-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"+dependencies = [+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "gdk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"+dependencies = [+ "cairo-sys-rs",+ "gdk-pixbuf-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pango-sys",+ "pkg-config",+ "system-deps",+]++[[package]]+name = "gdkwayland-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"+dependencies = [+ "gdk-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pkg-config",+ "system-deps",+]++[[package]]+name = "gdkx11"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"+dependencies = [+ "gdk",+ "gdkx11-sys",+ "gio",+ "glib",+ "libc",+ "x11",+]++[[package]]+name = "gdkx11-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"+dependencies = [+ "gdk-sys",+ "glib-sys",+ "libc",+ "system-deps",+ "x11",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi 6.0.0",+ "rand_core",+ "wasm-bindgen",+]++[[package]]+name = "gio"+version = "0.18.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-util",+ "gio-sys",+ "glib",+ "libc",+ "once_cell",+ "pin-project-lite",+ "smallvec",+ "thiserror 1.0.69",+]++[[package]]+name = "gio-sys"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+ "winapi",+]++[[package]]+name = "glib"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"+dependencies = [+ "bitflags 2.13.2",+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-task",+ "futures-util",+ "gio-sys",+ "glib-macros",+ "glib-sys",+ "gobject-sys",+ "libc",+ "memchr",+ "once_cell",+ "smallvec",+ "thiserror 1.0.69",+]++[[package]]+name = "glib-macros"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"+dependencies = [+ "heck 0.4.1",+ "proc-macro-crate 2.0.2",+ "proc-macro-error",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "glib-sys"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"+dependencies = [+ "libc",+ "system-deps",+]++[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"++[[package]]+name = "gobject-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"+dependencies = [+ "glib-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "gtk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"+dependencies = [+ "atk",+ "cairo-rs",+ "field-offset",+ "futures-channel",+ "gdk",+ "gdk-pixbuf",+ "gio",+ "glib",+ "gtk-sys",+ "gtk3-macros",+ "libc",+ "pango",+ "pkg-config",+]++[[package]]+name = "gtk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"+dependencies = [+ "atk-sys",+ "cairo-sys-rs",+ "gdk-pixbuf-sys",+ "gdk-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pango-sys",+ "system-deps",+]++[[package]]+name = "gtk3-macros"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"+dependencies = [+ "proc-macro-crate 1.3.1",+ "proc-macro-error",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "hashbrown"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "heck"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "html5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"+dependencies = [+ "log",+ "markup5ever",+]++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hyper"+version = "1.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "tokio",+ "tokio-rustls",+ "tower-service",+ "webpki-roots",+]++[[package]]+name = "hyper-util"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"+dependencies = [+ "base64 0.23.1",+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "httparse",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "tokio",+ "tower-service",+ "tracing",+]++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "ico"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"+dependencies = [+ "byteorder",+ "png 0.17.16",+]++[[package]]+name = "icu_collections"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"++[[package]]+name = "icu_properties"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"++[[package]]+name = "icu_provider"+version = "2.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "png 0.18.1",+]++[[package]]+name = "indexmap"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"+dependencies = [+ "autocfg",+ "hashbrown 0.12.3",+ "serde",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+ "serde",+ "serde_core",+]++[[package]]+name = "infer"+version = "0.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"+dependencies = [+ "cfb",+]++[[package]]+name = "ipnet"+version = "2.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "javascriptcore-rs"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"+dependencies = [+ "bitflags 1.3.2",+ "glib",+ "javascriptcore-rs-sys",+]++[[package]]+name = "javascriptcore-rs-sys"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "jiff"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb"+dependencies = [+ "defmt",+ "jiff-core",+ "jiff-static",+ "jiff-tzdb-platform",+ "log",+ "portable-atomic",+ "portable-atomic-util",+ "serde_core",+ "windows-link",+]++[[package]]+name = "jiff-core"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c"+dependencies = [+ "defmt",+ "log",+]++[[package]]+name = "jiff-static"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212"+dependencies = [+ "jiff-core",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "jiff-tzdb"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"++[[package]]+name = "jiff-tzdb-platform"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"+dependencies = [+ "jiff-tzdb",+]++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror 1.0.69",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "js-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "json-patch"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"+dependencies = [+ "jsonptr",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "jsonptr"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"+dependencies = [+ "serde",+ "serde_json",+]++[[package]]+name = "keyboard-types"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"+dependencies = [+ "bitflags 2.13.2",+ "serde",+]++[[package]]+name = "libappindicator"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"+dependencies = [+ "glib",+ "gtk",+ "gtk-sys",+ "libappindicator-sys",+ "log",+]++[[package]]+name = "libappindicator-sys"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"+dependencies = [+ "gtk-sys",+ "libloading",+ "once_cell",+]++[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"++[[package]]+name = "libdbus-sys"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"+dependencies = [+ "pkg-config",+]++[[package]]+name = "libloading"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"+dependencies = [+ "cfg-if",+ "winapi",+]++[[package]]+name = "libredox"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"+dependencies = [+ "libc",+]++[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"++[[package]]+name = "lru-slab"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"++[[package]]+name = "markup5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"+dependencies = [+ "log",+ "tendril",+ "web_atoms",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mio"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "muda"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"+dependencies = [+ "crossbeam-channel",+ "dpi",+ "gtk",+ "keyboard-types",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "once_cell",+ "png 0.18.1",+ "serde",+ "thiserror 2.0.21",+ "windows-sys 0.61.2",+]++[[package]]+name = "ndk"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"+dependencies = [+ "bitflags 2.13.2",+ "jni-sys 0.3.1",+ "log",+ "ndk-sys",+ "num_enum",+ "raw-window-handle",+ "thiserror 1.0.69",+]++[[package]]+name = "ndk-context"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"++[[package]]+name = "ndk-sys"+version = "0.6.0+11769913"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "new_debug_unreachable"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro-crate 3.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "objc2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"+dependencies = [+ "objc2-encode",+ "objc2-exception-helper",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-data"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.13.2",+ "dispatch2",+ "objc2",+ "objc2-core-foundation",+ "objc2-io-surface",+]++[[package]]+name = "objc2-core-image"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-location"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-exception-helper"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a"+dependencies = [+ "cc",+]++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-ui-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-location",+ "objc2-core-text",+ "objc2-foundation",+ "objc2-quartz-core",+ "objc2-user-notifications",+]++[[package]]+name = "objc2-user-notifications"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-web-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"++[[package]]+name = "pango"+version = "0.18.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"+dependencies = [+ "gio",+ "glib",+ "libc",+ "once_cell",+ "pango-sys",+]++[[package]]+name = "pango-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_macros",+ "phf_shared",+ "serde",+]++[[package]]+name = "phf_codegen"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"+dependencies = [+ "phf_generator",+ "phf_shared",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared",+]++[[package]]+name = "phf_macros"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "plist"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"+dependencies = [+ "base64 0.23.1",+ "indexmap 2.14.2",+ "quick-xml",+ "serde",+ "time",+]++[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "portable-atomic-util"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"+dependencies = [+ "portable-atomic",+]++[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"++[[package]]+name = "precomputed-hash"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"++[[package]]+name = "proc-macro-crate"+version = "1.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"+dependencies = [+ "once_cell",+ "toml_edit 0.19.15",+]++[[package]]+name = "proc-macro-crate"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"+dependencies = [+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit 0.25.15+spec-1.1.0",+]++[[package]]+name = "proc-macro-error"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"+dependencies = [+ "proc-macro-error-attr",+ "proc-macro2",+ "quote",+ "syn 1.0.109",+ "version_check",+]++[[package]]+name = "proc-macro-error-attr"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"+dependencies = [+ "proc-macro2",+ "quote",+ "version_check",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quick-xml"+version = "0.42.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"+dependencies = [+ "memchr",+]++[[package]]+name = "quinn"+version = "0.11.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2",+ "thiserror 2.0.21",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"+dependencies = [+ "bytes",+ "getrandom 0.4.3",+ "lru-slab",+ "rand",+ "rand_pcg",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror 2.0.21",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.61.2",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core",+]++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "redox_users"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"+dependencies = [+ "libredox",+ "thiserror 2.0.21",+]++[[package]]+name = "ref-cast"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-channel",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "webpki-roots",+]++[[package]]+name = "reqwest"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"+dependencies = [+ "base64 0.23.1",+ "bytes",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "serde",+ "serde_json",+ "sync_wrapper",+ "tokio",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustls"+version = "0.23.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "schemars"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"+dependencies = [+ "dyn-clone",+ "indexmap 1.9.3",+ "schemars_derive",+ "serde",+ "serde_json",+ "url",+ "uuid",+]++[[package]]+name = "schemars"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.119",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "selectors"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"+dependencies = [+ "bitflags 2.13.2",+ "cssparser",+ "derive_more",+ "log",+ "new_debug_unreachable",+ "phf",+ "phf_codegen",+ "precomputed-hash",+ "rustc-hash",+ "servo_arc",+ "smallvec",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde-untagged"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"+dependencies = [+ "erased-serde",+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_derive_internals"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_repr"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_spanned"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"+dependencies = [+ "serde",+]++[[package]]+name = "serde_spanned"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "serde_with"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f"+dependencies = [+ "base64 0.23.1",+ "bs58",+ "chrono",+ "hex",+ "indexmap 1.9.3",+ "indexmap 2.14.2",+ "jiff",+ "schemars 0.9.0",+ "schemars 1.2.2",+ "serde_core",+ "serde_json",+ "serde_with_macros",+ "time",+]++[[package]]+name = "serde_with_macros"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serialize-to-javascript"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"+dependencies = [+ "serde",+ "serde_json",+ "serialize-to-javascript-impl",+]++[[package]]+name = "serialize-to-javascript-impl"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "servo_arc"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"+dependencies = [+ "stable_deref_trait",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"++[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "softbuffer"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"+dependencies = [+ "bytemuck",+ "js-sys",+ "ndk",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "objc2-quartz-core",+ "raw-window-handle",+ "redox_syscall",+ "tracing",+ "wasm-bindgen",+ "web-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "soup3"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"+dependencies = [+ "futures-channel",+ "gio",+ "glib",+ "libc",+ "soup3-sys",+]++[[package]]+name = "soup3-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"+dependencies = [+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "string_cache"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"+dependencies = [+ "new_debug_unreachable",+ "parking_lot",+ "phf_shared",+ "precomputed-hash",+]++[[package]]+name = "string_cache_codegen"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+]++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "swift-rs"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"+dependencies = [+ "base64 0.21.7",+ "serde",+ "serde_json",+]++[[package]]+name = "syn"+version = "1.0.109"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"+dependencies = [+ "proc-macro2",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "system-deps"+version = "6.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"+dependencies = [+ "cfg-expr",+ "heck 0.5.0",+ "pkg-config",+ "toml 0.8.2",+ "version-compare",+]++[[package]]+name = "tao"+version = "0.37.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "core-foundation",+ "core-graphics",+ "crossbeam-channel",+ "dbus",+ "dispatch2",+ "dlopen2",+ "dpi",+ "gdkwayland-sys",+ "gdkx11-sys",+ "gtk",+ "jni",+ "libc",+ "log",+ "ndk",+ "ndk-context",+ "ndk-sys",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-ui-kit",+ "parking_lot",+ "percent-encoding",+ "raw-window-handle",+ "tao-macros",+ "unicode-segmentation",+ "url",+ "windows",+ "windows-core",+ "windows-version",+ "x11-dl",+]++[[package]]+name = "tao-macros"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "target-lexicon"+version = "0.12.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"++[[package]]+name = "tauri"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb20ef8e6f97d6fe03039666cd82861f09a38b56291fa2f0f9fe140023f61c1a"+dependencies = [+ "anyhow",+ "bytes",+ "cookie",+ "dirs",+ "dunce",+ "embed_plist",+ "getrandom 0.3.4",+ "glob",+ "gtk",+ "heck 0.5.0",+ "http",+ "image",+ "jni",+ "libc",+ "log",+ "mime",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "percent-encoding",+ "plist",+ "raw-window-handle",+ "reqwest 0.13.5",+ "serde",+ "serde_json",+ "serde_repr",+ "serialize-to-javascript",+ "swift-rs",+ "tauri-build",+ "tauri-macros",+ "tauri-runtime",+ "tauri-runtime-wry",+ "tauri-utils",+ "thiserror 2.0.21",+ "tokio",+ "tray-icon",+ "url",+ "webkit2gtk",+ "webview2-com",+ "window-vibrancy",+ "windows",+]++[[package]]+name = "tauri-build"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644"+dependencies = [+ "anyhow",+ "cargo_toml",+ "dirs",+ "glob",+ "heck 0.5.0",+ "json-patch",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde_json",+ "tauri-utils",+ "tauri-winres",+ "walkdir",+]++[[package]]+name = "tauri-codegen"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3926b73ac01df7c14f19ff872cd56e67213a87acc0000ea37ddb300f3d11a3e3"+dependencies = [+ "base64 0.22.1",+ "brotli",+ "ico",+ "json-patch",+ "plist",+ "png 0.18.1",+ "proc-macro2",+ "quote",+ "semver",+ "serde",+ "serde_json",+ "sha2",+ "syn 2.0.119",+ "tauri-utils",+ "thiserror 2.0.21",+ "time",+ "url",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-macros"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d21d0fa2c0529972ea6ecaf7404fcf40efac098eda0beb06ca682f41e33a6aa5"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "tauri-codegen",+ "tauri-utils",+]++[[package]]+name = "tauri-runtime"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9e6d5ef76985b32ff012a43b58df205d25a285e400ca878afcacddc5d5f3238"+dependencies = [+ "cookie",+ "dpi",+ "gtk",+ "http",+ "jni",+ "objc2",+ "objc2-ui-kit",+ "objc2-web-kit",+ "raw-window-handle",+ "serde",+ "serde_json",+ "tauri-utils",+ "thiserror 2.0.21",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+]++[[package]]+name = "tauri-runtime-wry"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa829eb69860cf1fb0bedb21d2d5f1effce3527d054a68ca1cd7355c654400a3"+dependencies = [+ "gtk",+ "http",+ "jni",+ "log",+ "objc2",+ "objc2-app-kit",+ "once_cell",+ "percent-encoding",+ "raw-window-handle",+ "softbuffer",+ "tao",+ "tauri-runtime",+ "tauri-utils",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+ "wry",+]++[[package]]+name = "tauri-utils"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4dd257082deff79550de3409ed146104aeaf86fe38649615b04a304144939677"+dependencies = [+ "anyhow",+ "brotli",+ "cargo_metadata",+ "ctor",+ "dom_query",+ "dunce",+ "glob",+ "http",+ "infer",+ "json-patch",+ "log",+ "memchr",+ "phf",+ "plist",+ "proc-macro2",+ "quote",+ "regex",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde-untagged",+ "serde_json",+ "serde_with",+ "swift-rs",+ "thiserror 2.0.21",+ "toml 1.1.6+spec-1.1.0",+ "url",+ "urlpattern",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-winres"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"+dependencies = [+ "dunce",+ "embed-resource",+ "toml 1.1.6+spec-1.1.0",+]++[[package]]+name = "tendril"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"+dependencies = [+ "new_debug_unreachable",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "time"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"+dependencies = [+ "num-conv",+ "time-core",+]++[[package]]+name = "tinystr"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"++[[package]]+name = "tokio"+version = "1.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "socket2",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-rustls"+version = "0.26.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "toml"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"+dependencies = [+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "toml"+version = "1.1.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"+dependencies = [+ "indexmap 2.14.2",+ "serde_core",+ "serde_spanned 1.1.1",+ "toml_datetime 1.1.1+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.4",+]++[[package]]+name = "toml_datetime"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"+dependencies = [+ "serde",+]++[[package]]+name = "toml_datetime"+version = "1.1.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.19.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"+dependencies = [+ "indexmap 2.14.2",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"+dependencies = [+ "indexmap 2.14.2",+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.25.15+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"+dependencies = [+ "indexmap 2.14.2",+ "toml_datetime 1.1.1+spec-1.1.0",+ "toml_parser",+ "winnow 1.0.4",+]++[[package]]+name = "toml_parser"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"+dependencies = [+ "winnow 1.0.4",+]++[[package]]+name = "toml_writer"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-http"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"+dependencies = [+ "bitflags 2.13.2",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+ "url",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "tray-icon"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"+dependencies = [+ "crossbeam-channel",+ "dirs",+ "libappindicator",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "once_cell",+ "png 0.18.1",+ "serde",+ "thiserror 2.0.21",+ "windows-sys 0.61.2",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typeid"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+ "serde_derive",+]++[[package]]+name = "urlpattern"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b"+dependencies = [+ "icu_properties",+ "regex",+ "serde",+ "url",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "uuid"+version = "1.26.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"+dependencies = [+ "getrandom 0.4.3",+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]++[[package]]+name = "version-compare"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.79"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wasm-streams"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "web-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web_atoms"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3"+dependencies = [+ "phf",+ "phf_codegen",+ "string_cache",+ "string_cache_codegen",+]++[[package]]+name = "webkit2gtk"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"+dependencies = [+ "bitflags 1.3.2",+ "cairo-rs",+ "gdk",+ "gdk-sys",+ "gio",+ "gio-sys",+ "glib",+ "glib-sys",+ "gobject-sys",+ "gtk",+ "gtk-sys",+ "javascriptcore-rs",+ "libc",+ "once_cell",+ "soup3",+ "webkit2gtk-sys",+]++[[package]]+name = "webkit2gtk-sys"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"+dependencies = [+ "bitflags 1.3.2",+ "cairo-sys-rs",+ "gdk-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "gtk-sys",+ "javascriptcore-rs-sys",+ "libc",+ "pkg-config",+ "soup3-sys",+ "system-deps",+]++[[package]]+name = "webpki-roots"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "webview2-com"+version = "0.39.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"+dependencies = [+ "webview2-com-macros",+ "webview2-com-sys",+ "windows",+ "windows-core",+]++[[package]]+name = "webview2-com-macros"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "webview2-com-sys"+version = "0.39.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"+dependencies = [+ "thiserror 2.0.21",+ "windows",+ "windows-core",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "window-vibrancy"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580"+dependencies = [+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+ "raw-window-handle",+ "windows-sys 0.61.2",+ "windows-version",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets 0.42.2",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm 0.42.2",+ "windows_aarch64_msvc 0.42.2",+ "windows_i686_gnu 0.42.2",+ "windows_i686_msvc 0.42.2",+ "windows_x86_64_gnu 0.42.2",+ "windows_x86_64_gnullvm 0.42.2",+ "windows_x86_64_msvc 0.42.2",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-version"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winnow"+version = "0.5.40"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"+dependencies = [+ "memchr",+]++[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+dependencies = [+ "memchr",+]++[[package]]+name = "winreg"+version = "0.55.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"+dependencies = [+ "cfg-if",+ "windows-sys 0.59.0",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"++[[package]]+name = "wry"+version = "0.57.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"+dependencies = [+ "base64 0.22.1",+ "block2",+ "cookie",+ "crossbeam-channel",+ "dirs",+ "dom_query",+ "dpi",+ "dunce",+ "gdkx11",+ "gtk",+ "http",+ "javascriptcore-rs",+ "jni",+ "libc",+ "ndk",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "once_cell",+ "percent-encoding",+ "raw-window-handle",+ "sha2",+ "soup3",+ "tao-macros",+ "thiserror 2.0.21",+ "url",+ "webkit2gtk",+ "webkit2gtk-sys",+ "webview2-com",+ "windows",+ "windows-core",+ "windows-version",+ "x11-dl",+]++[[package]]+name = "x11"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"+dependencies = [+ "libc",+ "pkg-config",+]++[[package]]+name = "x11-dl"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"+dependencies = [+ "libc",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/windows/app/src-tauri/Cargo.toml b/windows/app/src-tauri/Cargo.tomlnew file mode 100644index 0000000..e085233--- /dev/null+++ b/windows/app/src-tauri/Cargo.toml@@ -0,0 +1,31 @@+[package]+name = "edge0-app"+version = "0.1.0"+description = "edge0 Windows desktop shell (Tauri 2) — pull/convert/load/chat"+edition = "2021"+rust-version = "1.88"++[lib]+name = "edge0_app_lib"+crate-type = ["staticlib", "cdylib", "rlib"]++[build-dependencies]+tauri-build = { version = "2", features = [] }++[dependencies]+tauri = { version = "2", features = ["tray-icon", "image-png"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "blocking", "json"] }+sha2 = "0.10"+hex = "0.4"++[target.'cfg(windows)'.dependencies]+# Job Object binding for kill-on-close process governance (engine child dies with the shell).+# Win32_Threading is required: JOBOBJECT_EXTENDED_LIMIT_INFORMATION is gated behind it.+windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading"] }++[profile.release]+codegen-units = 1+lto = "thin"+strip = truediff --git a/windows/app/src-tauri/build.rs b/windows/app/src-tauri/build.rsnew file mode 100644index 0000000..d860e1e--- /dev/null+++ b/windows/app/src-tauri/build.rs@@ -0,0 +1,3 @@+fn main() {+ tauri_build::build()+}diff --git a/windows/app/src-tauri/capabilities/default.json b/windows/app/src-tauri/capabilities/default.jsonnew file mode 100644index 0000000..3ae0133--- /dev/null+++ b/windows/app/src-tauri/capabilities/default.json@@ -0,0 +1,7 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "default",+ "description": "Main window capability — core plugins only; all app commands are native (no extra IPC surface)",+ "windows": ["main"],+ "permissions": ["core:default", "core:event:default", "core:window:allow-set-title"]+}diff --git a/windows/app/src-tauri/catalog.json b/windows/app/src-tauri/catalog.jsonnew file mode 100644index 0000000..c99fd92--- /dev/null+++ b/windows/app/src-tauri/catalog.json@@ -0,0 +1,198 @@+{+ "8b": {+ "repo": "Edge0/Edge0-8B-A1B-preview",+ "rev": {+ "modelscope": "master",+ "hf": "cadc35c7059469fad8569a63ce6c851172bbca61"+ },+ "files": [+ {+ "path": "chat_template.jinja",+ "size": 6041,+ "sha256": "eb6226c94ae38058f875d159f86a206b3a165828c0e7d6bda664ae14667f798a",+ "skip": false+ },+ {+ "path": "config.json",+ "size": 3069,+ "sha256": "5790c795d490d7b90eb04b269f5db4faad08bcc560f8da6e30b61057b1606340",+ "skip": false+ },+ {+ "path": "generation_config.json",+ "size": 56,+ "sha256": "64752c5973a55faf4cfc02604c7587c38b090f00013f91191f52362dcc79a4a8",+ "skip": false+ },+ {+ "path": "lora_edge0_8b.safetensors",+ "size": 16413656,+ "sha256": "a32ff07ba3d3b3c9811146c43a3f0e96af4ec2960ebc5072910f9a6663dc2e2e",+ "skip": false+ },+ {+ "path": "model.safetensors",+ "size": 4508697328,+ "sha256": "5bcde14438cfe13a547965573471e8ddc830de3a047dd2dfd38a0eb2b390d2b6",+ "skip": false+ },+ {+ "path": "prerouter_edge0_8b.safetensors",+ "size": 38802304,+ "sha256": "5f05d25e52ce18103d0867e5a0c79ec4e3334ad8c8906c22ec6266a95db2047c",+ "skip": true+ },+ {+ "path": "special_tokens_map.json",+ "size": 580,+ "sha256": "69b63b9f81044ead642d16a5fdc01bcc737dc1183746485c8397ab14d3126614",+ "skip": false+ },+ {+ "path": "tokenizer.json",+ "size": 12205732,+ "sha256": "40fb9d7d7795b8bd305aeff39ce9963f3f450915b9553f2938e009be9a1fed60",+ "skip": false+ },+ {+ "path": "tokenizer_config.json",+ "size": 49671,+ "sha256": "2456b0372956cd3e82f17e33372148b115a94970bfd4878ba5e7e60cd3204f74",+ "skip": false+ }+ ],+ "total_bytes": 4537376133,+ "pool_mb": 2048+ },+ "35b": {+ "repo": "Edge0/Edge0-35B-A3B-preview",+ "rev": {+ "modelscope": "master",+ "hf": "e21098e7faa916a00f5493795f12f20497d032bb"+ },+ "files": [+ {+ "path": ".gitattributes",+ "size": 2238,+ "sha256": "f53d675d9d2a887034cf45c1403575f03c9878ceaabca7b10e7b6c494e1e194e",+ "skip": true+ },+ {+ "path": "20260908-223115.jpg",+ "size": 1068426,+ "sha256": "d7285e3c6d5f1039a8b5283031e27fd48aa0cebbb9fb57d180903481eeb8f204",+ "skip": true+ },+ {+ "path": "20260910-105854.mp4",+ "size": 20328509,+ "sha256": "b266d0ec149cb752581789df5846c23ca345501051ee9cc86de31415ed4d6a59",+ "skip": true+ },+ {+ "path": "README.md",+ "size": 7012,+ "sha256": "bba904365a53ec7b6981eb72adc42b17492a45fd304ab070869f38d171578833",+ "skip": true+ },+ {+ "path": "chat_template.jinja",+ "size": 7764,+ "sha256": "e84f32a23fdda27689f868aa4a1a5621f41133e51a48d7f3efcbea2839574259",+ "skip": false+ },+ {+ "path": "config.json",+ "size": 23591,+ "sha256": "a822a9e48b0aafbe3144ec37d4fb067e178ed96615ce6e4420b3149893cc5767",+ "skip": false+ },+ {+ "path": "configuration.json",+ "size": 58,+ "sha256": "c1b09db419119513247e9b8b912c4b9897106c9b20c6cada7e107d993c5435eb",+ "skip": false+ },+ {+ "path": "generation_config.json",+ "size": 202,+ "sha256": "e70c136c1b78ddc1fb0905bac8e733a4dc448d4f852a5dd75143fffc70be550e",+ "skip": false+ },+ {+ "path": "lora_edge0_35b.safetensors",+ "size": 42413928,+ "sha256": "a407f6d27bb55e39e6461bd4bce1fd90489e70c7582b68a796fb764bdb441ec1",+ "skip": false+ },+ {+ "path": "model-00001-of-00004.safetensors",+ "size": 4395019264,+ "sha256": "f7fff28fecb8221e53787c6339c938b113bcb94c7bbc60d09a8826eba08ef1ab",+ "skip": false+ },+ {+ "path": "model-00002-of-00004.safetensors",+ "size": 5368472749,+ "sha256": "31dcdb1c49eebdb1505bd14e3cb33f9cf900bd2546b638f2464694ae763a033f",+ "skip": false+ },+ {+ "path": "model-00003-of-00004.safetensors",+ "size": 5368324139,+ "sha256": "3e66de06a1f03dade16a612a368cfce4a4c9caa4efd7d28185454384082cec03",+ "skip": false+ },+ {+ "path": "model-00004-of-00004.safetensors",+ "size": 4377211365,+ "sha256": "a5d0cf03519c26f8b506df6b0ba60526e5c08c8cea22d0c21ce92950e58a5422",+ "skip": false+ },+ {+ "path": "model.safetensors.index.json",+ "size": 180182,+ "sha256": "e359cd95565275b923fed8df019dd8e869d9af5dc4a621b4114ab7a8e6c534d1",+ "skip": false+ },+ {+ "path": "preprocessor_config.json",+ "size": 390,+ "sha256": "27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516",+ "skip": false+ },+ {+ "path": "prerouter_edge0_35b.safetensors",+ "size": 138422000,+ "sha256": "93d07af08e1f5c8d174e941016740cb4d2c143c6b90f33581237679eca9b006f",+ "skip": true+ },+ {+ "path": "processor_config.json",+ "size": 1312,+ "sha256": "51c5f33646392e0bf1ed3e96be02504da47406c21c6cb86925d8908d1a6c4da7",+ "skip": false+ },+ {+ "path": "tokenizer.json",+ "size": 19989343,+ "sha256": "87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4",+ "skip": false+ },+ {+ "path": "tokenizer_config.json",+ "size": 1139,+ "sha256": "e98f1901ac6f0adff67b1d540bfa0c36ac1a0cf59eb72ed78146ef89aafa1182",+ "skip": false+ },+ {+ "path": "vocab.json",+ "size": 6722759,+ "sha256": "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003",+ "skip": false+ }+ ],+ "total_bytes": 19578368185,+ "pool_mb": 4096+ }+}\ No newline at end of filediff --git a/windows/app/src-tauri/icons/128x128.png b/windows/app/src-tauri/icons/128x128.pngnew file mode 100644index 0000000..8881e31Binary files /dev/null and b/windows/app/src-tauri/icons/128x128.png differdiff --git a/windows/app/src-tauri/icons/[email protected] b/windows/app/src-tauri/icons/[email protected]new file mode 100644index 0000000..cede665Binary files /dev/null and b/windows/app/src-tauri/icons/[email protected] differdiff --git a/windows/app/src-tauri/icons/32x32.png b/windows/app/src-tauri/icons/32x32.pngnew file mode 100644index 0000000..91b2b70Binary files /dev/null and b/windows/app/src-tauri/icons/32x32.png differdiff --git a/windows/app/src-tauri/icons/64x64.png b/windows/app/src-tauri/icons/64x64.pngnew file mode 100644index 0000000..27b33c4Binary files /dev/null and b/windows/app/src-tauri/icons/64x64.png differdiff --git a/windows/app/src-tauri/icons/Square107x107Logo.png b/windows/app/src-tauri/icons/Square107x107Logo.pngnew file mode 100644index 0000000..1786101Binary files /dev/null and b/windows/app/src-tauri/icons/Square107x107Logo.png differdiff --git a/windows/app/src-tauri/icons/Square142x142Logo.png b/windows/app/src-tauri/icons/Square142x142Logo.pngnew file mode 100644index 0000000..a8d9be0Binary files /dev/null and b/windows/app/src-tauri/icons/Square142x142Logo.png differdiff --git a/windows/app/src-tauri/icons/Square150x150Logo.png b/windows/app/src-tauri/icons/Square150x150Logo.pngnew file mode 100644index 0000000..6ce53f6Binary files /dev/null and b/windows/app/src-tauri/icons/Square150x150Logo.png differdiff --git a/windows/app/src-tauri/icons/Square284x284Logo.png b/windows/app/src-tauri/icons/Square284x284Logo.pngnew file mode 100644index 0000000..978b900Binary files /dev/null and b/windows/app/src-tauri/icons/Square284x284Logo.png differdiff --git a/windows/app/src-tauri/icons/Square30x30Logo.png b/windows/app/src-tauri/icons/Square30x30Logo.pngnew file mode 100644index 0000000..8196a25Binary files /dev/null and b/windows/app/src-tauri/icons/Square30x30Logo.png differdiff --git a/windows/app/src-tauri/icons/Square310x310Logo.png b/windows/app/src-tauri/icons/Square310x310Logo.pngnew file mode 100644index 0000000..b8b47b3Binary files /dev/null and b/windows/app/src-tauri/icons/Square310x310Logo.png differdiff --git a/windows/app/src-tauri/icons/Square44x44Logo.png b/windows/app/src-tauri/icons/Square44x44Logo.pngnew file mode 100644index 0000000..519be7fBinary files /dev/null and b/windows/app/src-tauri/icons/Square44x44Logo.png differdiff --git a/windows/app/src-tauri/icons/Square71x71Logo.png b/windows/app/src-tauri/icons/Square71x71Logo.pngnew file mode 100644index 0000000..90e28f4Binary files /dev/null and b/windows/app/src-tauri/icons/Square71x71Logo.png differdiff --git a/windows/app/src-tauri/icons/Square89x89Logo.png b/windows/app/src-tauri/icons/Square89x89Logo.pngnew file mode 100644index 0000000..744ea79Binary files /dev/null and b/windows/app/src-tauri/icons/Square89x89Logo.png differdiff --git a/windows/app/src-tauri/icons/StoreLogo.png b/windows/app/src-tauri/icons/StoreLogo.pngnew file mode 100644index 0000000..0b37792Binary files /dev/null and b/windows/app/src-tauri/icons/StoreLogo.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml b/windows/app/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xmlnew file mode 100644index 0000000..2ffbf24--- /dev/null+++ b/windows/app/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <foreground android:drawable="@mipmap/ic_launcher_foreground"/>+ <background android:drawable="@color/ic_launcher_background"/>+</adaptive-icon>\ No newline at end of filediff --git a/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png b/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher.pngnew file mode 100644index 0000000..59f59ccBinary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png b/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..66abee4Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png b/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.pngnew file mode 100644index 0000000..e84186cBinary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png b/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher.pngnew file mode 100644index 0000000..ca629e8Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png b/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..1c4cdb0Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png b/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.pngnew file mode 100644index 0000000..7732498Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png b/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.pngnew file mode 100644index 0000000..de6a42eBinary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png b/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..b1047a5Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png b/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.pngnew file mode 100644index 0000000..3e76dfeBinary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png b/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.pngnew file mode 100644index 0000000..3e663f7Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png b/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..a98192cBinary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png b/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.pngnew file mode 100644index 0000000..40dbcb9Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png b/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.pngnew file mode 100644index 0000000..a649d68Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png b/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.pngnew file mode 100644index 0000000..a33a803Binary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png differdiff --git a/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png b/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.pngnew file mode 100644index 0000000..3db3bbeBinary files /dev/null and b/windows/app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png differdiff --git a/windows/app/src-tauri/icons/android/values/ic_launcher_background.xml b/windows/app/src-tauri/icons/android/values/ic_launcher_background.xmlnew file mode 100644index 0000000..16cdd5a--- /dev/null+++ b/windows/app/src-tauri/icons/android/values/ic_launcher_background.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <color name="ic_launcher_background">#FFFFFF</color>+</resources>\ No newline at end of filediff --git a/windows/app/src-tauri/icons/edge0_logo.png b/windows/app/src-tauri/icons/edge0_logo.pngnew file mode 100644index 0000000..712a001Binary files /dev/null and b/windows/app/src-tauri/icons/edge0_logo.png differdiff --git a/windows/app/src-tauri/icons/icon.icns b/windows/app/src-tauri/icons/icon.icnsnew file mode 100644index 0000000..d009edaBinary files /dev/null and b/windows/app/src-tauri/icons/icon.icns differdiff --git a/windows/app/src-tauri/icons/icon.ico b/windows/app/src-tauri/icons/icon.iconew file mode 100644index 0000000..02a0484Binary files /dev/null and b/windows/app/src-tauri/icons/icon.ico differdiff --git a/windows/app/src-tauri/icons/icon.png b/windows/app/src-tauri/icons/icon.pngnew file mode 100644index 0000000..94b3731Binary files /dev/null and b/windows/app/src-tauri/icons/icon.png differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..f793bc5Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..204e9d5Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..204e9d5Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..11b0321Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..4509b5fBinary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..d4414d5Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..d4414d5Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..bbce047Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..204e9d5Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..6050755Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..6050755Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..dc58169Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..244be5eBinary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..dc58169Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..a1b7dc1Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..afbad7fBinary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..445dbf3Binary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/ios/[email protected] b/windows/app/src-tauri/icons/ios/[email protected]new file mode 100644index 0000000..3357bcaBinary files /dev/null and b/windows/app/src-tauri/icons/ios/[email protected] differdiff --git a/windows/app/src-tauri/icons/tray-idle.png b/windows/app/src-tauri/icons/tray-idle.pngnew file mode 100644index 0000000..5f7cb03Binary files /dev/null and b/windows/app/src-tauri/icons/tray-idle.png differdiff --git a/windows/app/src-tauri/icons/tray-loading.png b/windows/app/src-tauri/icons/tray-loading.pngnew file mode 100644index 0000000..efd2679Binary files /dev/null and b/windows/app/src-tauri/icons/tray-loading.png differdiff --git a/windows/app/src-tauri/icons/tray-resident.png b/windows/app/src-tauri/icons/tray-resident.pngnew file mode 100644index 0000000..5888448Binary files /dev/null and b/windows/app/src-tauri/icons/tray-resident.png differdiff --git a/windows/app/src-tauri/icons/tray-throttled.png b/windows/app/src-tauri/icons/tray-throttled.pngnew file mode 100644index 0000000..8405431Binary files /dev/null and b/windows/app/src-tauri/icons/tray-throttled.png differdiff --git a/windows/app/src-tauri/src/catalog.rs b/windows/app/src-tauri/src/catalog.rsnew file mode 100644index 0000000..9c57f1c--- /dev/null+++ b/windows/app/src-tauri/src/catalog.rs@@ -0,0 +1,51 @@+// catalog.rs — embedded tier table, generated by tools/make_app_catalog.py.+// The UI must not hardcode model sizes/sha; this is the single source of truth.+use serde::Deserialize;+use serde_json::Value;+use std::collections::HashMap;++pub const CAT_JSON: &str = include_str!("../catalog.json");++#[derive(Debug, Clone, Deserialize)]+pub struct CatFile {+ pub path: String,+ pub size: u64,+ pub sha256: String,+ #[serde(default)]+ pub skip: bool,+}++#[derive(Debug, Clone, Deserialize)]+pub struct Rev {+ pub modelscope: String,+ pub hf: String,+}++#[derive(Debug, Clone, Deserialize)]+pub struct Tier {+ pub repo: String,+ pub rev: Rev,+ pub files: Vec<CatFile>,+ pub total_bytes: u64,+ pub pool_mb: u32,+}++pub fn catalog() -> HashMap<String, Tier> {+ serde_json::from_str(CAT_JSON).expect("catalog.json parse failed (rerun tools/make_app_catalog.py)")+}++pub fn catalog_value() -> Value {+ serde_json::from_str(CAT_JSON).unwrap()+}++pub fn base_urls(tier: &Tier) -> Vec<(&'static str, String)> {+ // Source order for the overseas release: HuggingFace first; hf-mirror and+ // modelscope are fallbacks (mainland users configure their own proxy — network+ // routing is not the app's job). All three still participate in the probe-speed+ // race, so the fastest reachable source wins at runtime.+ vec![+ ("hf", format!("https://huggingface.co/{}/resolve/{}", tier.repo, tier.rev.hf)),+ ("hf-mirror", format!("https://hf-mirror.com/{}/resolve/{}", tier.repo, tier.rev.hf)),+ ("modelscope", format!("https://modelscope.cn/models/{}/resolve/{}", tier.repo, tier.rev.modelscope)),+ ]+}diff --git a/windows/app/src-tauri/src/convert.rs b/windows/app/src-tauri/src/convert.rsnew file mode 100644index 0000000..9d0ed19--- /dev/null+++ b/windows/app/src-tauri/src/convert.rs@@ -0,0 +1,77 @@+// convert.rs — on-device conversion: MLX files -> GGUF + LoRA adapter.+// Invokes tools/convert_mlx_to_gguf.py (interpreter from EDGE0_PY, default "python")+// with --dir <files> --out <gguf>. Idempotency and self-checks live inside the+// converter; this wrapper streams stdout/stderr to logs/convert-<tier>.log and back+// to the UI, then returns the sha256 of the finished artifact for registration.+use crate::paths;+use crate::sink::Sink;+use serde_json::json;+use std::io::{BufRead, BufReader, BufWriter, Write};+use std::process::{Command, Stdio};+use std::sync::Arc;++pub fn run(sink: &Arc<dyn Sink>, tier: &str) -> Result<String, String> {+ let repo = paths::repo_root();+ let script = repo.join("tools").join("convert_mlx_to_gguf.py");+ if !script.exists() {+ return Err(format!("conversion script not found {script:?} (set EDGE0_REPO)"));+ }+ let py = std::env::var("EDGE0_PY").unwrap_or_else(|_| "python".into());+ let out = paths::gguf_dir(tier);+ let log_p = paths::logs_dir().join(format!("convert-{tier}.log"));+ let logfile = std::fs::File::create(&log_p).map_err(|e| e.to_string())?;+ let mut cmd = Command::new(&py);+ crate::no_window(&mut cmd)+ .arg(&script)+ .arg("--dir")+ .arg(paths::files_dir(tier))+ .arg("--out")+ .arg(&out)+ .current_dir(&repo)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ let mut child = cmd.spawn()+ .map_err(|e| format!("spawn {py} failed: {e}"))?;+ let so = child.stdout.take().unwrap();+ let se = child.stderr.take().unwrap();+ let s2 = sink.clone();+ let tc = tier.to_string();+ std::thread::spawn(move || {+ let mut w = BufWriter::new(logfile);+ let a = BufReader::new(so);+ let b = BufReader::new(se);+ let lines = a.lines().map(|r| r.unwrap_or_default()).chain(b.lines().map(|r| r.unwrap_or_default()));+ for l in lines {+ let _ = writeln!(w, "{l}");+ let _ = w.flush();+ s2.emit("convert.progress", &json!({ "tier": tc, "line": l }));+ }+ });+ let st = child.wait().map_err(|e| e.to_string())?;+ if !st.success() {+ return Err(format!("converter exited nonzero {}", st.code().unwrap_or(-1)));+ }+ let gguf = out.join(format!("edge0-{tier}.gguf"));+ if !gguf.exists() {+ return Err(format!("conversion finished but artifact {gguf:?} missing"));+ }+ Ok(sha_of(&gguf))+}++fn sha_of(p: &std::path::Path) -> String {+ use sha2::Digest;+ let mut f = match std::fs::File::open(p) {+ Ok(f) => f,+ Err(_) => return String::new(),+ };+ let mut h = sha2::Sha256::new();+ let mut buf = vec![0u8; 1 << 22]; // heap-allocated: a 4 MB stack array here caused STATUS_STACK_OVERFLOW+ loop {+ let n = std::io::Read::read(&mut f, &mut buf).unwrap_or(0);+ if n == 0 {+ break;+ }+ h.update(&buf[..n]);+ }+ hex::encode(h.finalize())+}diff --git a/windows/app/src-tauri/src/doctor.rs b/windows/app/src-tauri/src/doctor.rsnew file mode 100644index 0000000..811ff15--- /dev/null+++ b/windows/app/src-tauri/src/doctor.rs@@ -0,0 +1,163 @@+// doctor.rs — environment self-check. Every check reports measured facts (the UI+// renders them as-is and never estimates). Disk/memory attributes are read through+// plain kernel32 externs (windows-sys bindings for these tripped link issues here).+use crate::{catalog, engine, paths};+use serde_json::{json, Value};++extern "system" {+ fn GetDiskFreeSpaceExW(+ dir: *const u16,+ free_available_to_caller: *mut u64,+ total_bytes: *mut u64,+ total_free_bytes: *mut u64,+ ) -> i32;+ fn GetFileAttributesW(path: *const u16) -> u32;+}++const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;+const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;++fn wstr(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(std::iter::once(0)).collect()+}++pub fn disk_free_gb(path: &std::path::Path) -> Option<u64> {+ let p = wstr(&path.to_string_lossy());+ let mut free: u64 = 0;+ let mut total: u64 = 0;+ let mut total_free: u64 = 0;+ let ok = unsafe { GetDiskFreeSpaceExW(p.as_ptr(), &mut free, &mut total, &mut total_free) };+ if ok != 0 { Some(free / 1_000_000_000) } else { None }+}++/// Reparse point (junction/symlink) detection — the safety line of model_delete:+/// seeded links are never physically deleted.+pub fn is_reparse(path: &std::path::Path) -> bool {+ let p = wstr(&path.to_string_lossy());+ let attr = unsafe { GetFileAttributesW(p.as_ptr()) };+ attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0+}++fn check(id: &str, verdict: &str, detail: impl Into<String>, code: Option<&str>, next: Option<&str>) -> Value {+ json!({ "id": id, "verdict": verdict, "detail": detail.into(), "code": code, "next": next })+}++/// Main entry (forwarded by doctor_run in lib.rs): takes the engine state so the+/// pool-telemetry check reads the live process, not a snapshot.+pub fn run(state: &engine::EngineState) -> Value {+ let mut checks: Vec<Value> = Vec::new();++ // home: exists and writable (write + delete one probe file to be sure)+ let home = paths::home();+ let probe = home.join("state").join(".doctor-probe");+ let writable = std::fs::create_dir_all(probe.parent().unwrap()).is_ok()+ && std::fs::write(&probe, b"ok").is_ok()+ && { let _ = std::fs::remove_file(&probe); true };+ checks.push(if writable {+ check("home", "pass", format!("{} is writable", home.display()), None, None)+ } else {+ check("home", "fail", format!("{} is not writable", home.display()), Some("E-IO"), None)+ });++ // free disk (thresholds from the runtime contract: download+convert workspace for 35B ~19.6 GB + 8B ~4.5 GB)+ match disk_free_gb(&home) {+ Some(g) if g >= 25 => checks.push(check("disk", "pass", format!("{g} GB free"), None, None)),+ Some(g) if g >= 10 => checks.push(check("disk", "warn",+ format!("{g} GB free: fits the 8b tier only (35b needs >= 25 GB)"), Some("E-DL-DISK"), Some("free disk space or download the 8b tier only"))),+ Some(g) => checks.push(check("disk", "fail", format!("{g} GB free: not enough for any tier download"), Some("E-DL-DISK"), Some("free up disk space"))),+ None => checks.push(check("disk", "warn", "cannot read disk free space", None, None)),+ }++ // physical RAM (measured via GlobalMemoryStatusEx)+ let mem = engine::phys_mem_gb();+ checks.push(if mem >= 14 {+ check("memory", "pass", format!("{mem} GB: both tiers loadable (P-16G class)"), None, None)+ } else if mem >= 8 {+ check("memory", "warn", format!("{mem} GB: 8b tier recommended only"), Some("E-MEM-LOAD"), Some("pick 8b on the Models page"))+ } else {+ check("memory", "fail", format!("{mem} GB: below the 8b floor"), Some("E-MEM-LOAD"), None)+ });++ // engine binary presence + version probe+ let exe = paths::bin_dir().join("llama-server.exe");+ checks.push(if exe.exists() {+ match engine::server_version() {+ Some(v) => check("engine", "pass", v, None, None),+ None => check("engine", "warn", format!("{} exists but version probe failed", exe.display()), None, None),+ }+ } else {+ check("engine", "fail", format!("missing {}", exe.display()), Some("E-ENGINE-MISSING"), Some("set EDGE0_BIN_DIR"))+ });++ // per-tier presence (all catalog tiers): not installed = warn pointing at the+ // Models page; registered + files present = pass+ let models = read_models_json();+ for tier in catalog::catalog().keys() {+ let gguf = paths::gguf_dir(tier).join(format!("edge0-{tier}.gguf"));+ let lora = paths::files_dir(tier).join(format!("lora_edge0_{tier}-gguf.gguf"));+ if models.get(tier).is_some() && gguf.exists() && lora.exists() {+ checks.push(check(&format!("model-{tier}"), "pass",+ format!("installed (pool {} MB from table), files present", engine::pool_for(tier)), None, None));+ } else if models.get(tier).is_some() {+ checks.push(check(&format!("model-{tier}"), "fail",+ "registered but files missing (record does not match disk)", Some("E-MODEL-INVALID"), Some("delete this tier and download again")));+ } else {+ checks.push(check(&format!("model-{tier}"), "warn", "not installed", None, Some("download from the Models page")));+ }+ }++ // pool telemetry: engine running but no POOL2 init line in the log = warn (surfaced honestly)+ let st = engine::status(state);+ if st["running"].as_bool().unwrap_or(false) {+ let log = st["log"].as_str().unwrap_or("");+ match engine::pool_telemetry(log) {+ Some(line) => checks.push(check("pool-telemetry", "pass", line, None, None)),+ None => checks.push(check("pool-telemetry", "warn",+ "engine is running but no POOL2 init telemetry line in log = pool inactive", Some("E-POOL-OFF"), None)),+ }+ }++ let has_fail = checks.iter().any(|c| c["verdict"] == "fail");+ let has_warn = checks.iter().any(|c| c["verdict"] == "warn");+ json!({ "overall": if has_fail || has_warn { "warn" } else { "pass" }, "checks": checks })+}++pub fn read_models_json() -> Value {+ std::fs::read_to_string(paths::state_dir().join("models.json"))+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_else(|| json!({}))+}++/// Delete a tier (physical directories only): a junction/symlink seed returns+/// E-MODEL-PROTECTED — the repo-asset safety line.+pub fn delete(tier: &str, resident: Option<&str>) -> Result<Value, String> {+ if resident == Some(tier) {+ return Err(format!("E-MODEL-BUSY {tier} is resident (evict it before deleting)"));+ }+ let dirs = [paths::files_dir(tier), paths::gguf_dir(tier)];+ for d in &dirs {+ if d.exists() && is_reparse(d) {+ return Err(format!(+ "E-MODEL-PROTECTED {tier} is a junction seed link — the shell unlinks, never deletes targets; remove the junction in a terminal to reclaim"));+ }+ }+ for d in &dirs {+ if d.exists() {+ std::fs::remove_dir_all(d).map_err(|e| format!("E-IO {d:?} {e}"))?;+ }+ }+ // deregister + sweep leftover state files+ let p = paths::state_dir().join("models.json");+ if let Ok(s) = std::fs::read_to_string(&p) {+ if let Ok(mut m) = serde_json::from_str::<Value>(&s) {+ m.as_object_mut().map(|o| o.remove(tier));+ let tmp = paths::state_dir().join("models.json.tmp");+ let _ = std::fs::write(&tmp, serde_json::to_string_pretty(&m).unwrap());+ let _ = std::fs::rename(&tmp, &p);+ }+ }+ let _ = std::fs::remove_file(paths::state_dir().join(format!("verified-{tier}.json")));+ let _ = std::fs::remove_file(paths::state_dir().join("downloads").join(format!("{tier}.json")));+ Ok(json!({ "deleted": tier }))+}diff --git a/windows/app/src-tauri/src/engine.rs b/windows/app/src-tauri/src/engine.rsnew file mode 100644index 0000000..ed95452--- /dev/null+++ b/windows/app/src-tauri/src/engine.rs@@ -0,0 +1,257 @@+// engine.rs — supervisor for the llama-server child process (the daemon's duties+// folded into the shell). The spawn arg table is the process form of the runtime+// contract: -ngl 99 -cmoe --ctx-size 8192 --flash-attn on --pool-mb <tier-clamped>+// --no-webui --port <random free>. Readiness is decided by polling /health, not by+// a fixed sleep. A crash is surfaced and not auto-restarted within the session.+use crate::catalog;+use crate::paths;+use crate::sink::Sink;+use serde_json::{json, Value};+use std::net::TcpListener;+use std::process::{Child, Command, Stdio};+use std::sync::{Arc, Mutex, OnceLock};++#[derive(Debug)]+pub struct Engine {+ pub child: Child,+ pub port: u16,+ pub tier: String,+ pub pool_mb: u32,+ pub started_at: u64, // UNIX seconds (source of truth for the service panel's uptime)+ pub log_path: String,+ pub job: bool, // true = attached to a KILL_ON_JOB_CLOSE job; false = only the ExitRequested fallback (recorded honestly)+}++pub type EngineState = Mutex<Option<Engine>>;++// —— direct kernel32 read (no windows-sys here: this specific binding tripped link/+// resolution issues before, and a plain extern declaration is all we need) ——+#[repr(C)]+struct MemoryStatusEx {+ dw_length: u32,+ memory_load: u32,+ total_phys: u64,+ avail_phys: u64,+ total_pagefile: u64,+ avail_pagefile: u64,+ total_virtual: u64,+ avail_virtual: u64,+ avail_ext_virtual: u64,+}++extern "system" {+ fn GlobalMemoryStatusEx(buf: *mut MemoryStatusEx) -> i32;+}++/// Physical RAM in GB: env override first (tests pin it), else a real+/// GlobalMemoryStatusEx read; on read failure fall back conservatively to 48 (the+/// reference machine — clamping stays safe without this value).+pub fn phys_mem_gb() -> u64 {+ if let Ok(v) = std::env::var("EDGE0_PHYS_MEM_GB") {+ if let Ok(n) = v.parse::<u64>() {+ return n;+ }+ }+ unsafe {+ let mut m: MemoryStatusEx = std::mem::zeroed();+ m.dw_length = std::mem::size_of::<MemoryStatusEx>() as u32;+ if GlobalMemoryStatusEx(&mut m) != 0 && m.total_phys > 0 {+ return (m.total_phys / 1_000_000_000).max(1);+ }+ }+ 48+}++/// Pool size = catalog value clamped by physical RAM (safe band ~2-4 GB; no XL tier).+pub fn pool_for(tier: &str) -> u32 {+ let base = catalog::catalog().get(tier).map(|t| t.pool_mb).unwrap_or(2048);+ let gb = phys_mem_gb();+ let cap = match () {+ _ if gb < 10 => 1024,+ _ if gb < 16 => 2048,+ _ => base,+ };+ base.min(cap).max(512)+}++// Job Object safety net: llama-server is assigned to a job created with+// KILL_ON_JOB_CLOSE, so whether the shell exits cleanly, crashes, or is force-killed+// (taskkill /f), the OS closes the process handle -> closes the job -> kills the+// child. No orphans. This uses the official windows-sys JobObjects bindings (a+// standard kernel32 import; the struct layout also rules out the hand-rolled-FFI+// ERROR_BAD_LENGTH class of bugs).+use std::os::windows::io::AsRawHandle;+use windows_sys::Win32::Foundation::CloseHandle;+use windows_sys::Win32::System::JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,+ SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+};++struct JobHandle(Option<*mut core::ffi::c_void>); // windows-sys 0.59: HANDLE = *mut c_void+// The job object is thread-agnostic, so sharing the raw handle across threads is+// safe; we intentionally never close it during process lifetime — the OS reclaims+// handles at exit, and that very close is what kills the child.+unsafe impl Sync for JobHandle {}+unsafe impl Send for JobHandle {}++static KILL_JOB: OnceLock<JobHandle> = OnceLock::new();++fn kill_job() -> Option<*mut core::ffi::c_void> {+ KILL_JOB.get_or_init(|| unsafe {+ let h = CreateJobObjectW(std::ptr::null(), std::ptr::null());+ if h.is_null() {+ return JobHandle(None);+ }+ let mut li: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();+ li.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ let ok = SetInformationJobObject(+ h,+ JobObjectExtendedLimitInformation,+ &li as *const _ as *const core::ffi::c_void,+ std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ );+ if ok == 0 {+ CloseHandle(h);+ return JobHandle(None);+ }+ JobHandle(Some(h))+ })+ .0+}++/// Attach the child to the kill-on-close job (best effort: assign fails if the+/// process already belongs to another job; the caller records false honestly, and+/// the normal path keeps the ExitRequested→stop fallback as double insurance).+pub fn assign_kill_job(child: &Child) -> bool {+ match kill_job() {+ Some(job) => unsafe { AssignProcessToJobObject(job, child.as_raw_handle()) != 0 },+ None => false,+ }+}++fn free_port() -> Result<u16, String> {+ TcpListener::bind("127.0.0.1:0").map(|l| l.local_addr().map(|a| a.port()).unwrap_or(0)).map_err(|e| e.to_string())+}++pub fn start(sink: &Arc<dyn Sink>, state: &EngineState, tier: &str) -> Result<Value, String> {+ stop(state);+ let gguf = paths::gguf_dir(tier).join(format!("edge0-{tier}.gguf"));+ let adapter = paths::files_dir(tier).join(format!("lora_edge0_{tier}-gguf.gguf"));+ if !gguf.exists() {+ return Err(format!("E-MODEL-MISSING not converted yet (run the download first): {gguf:?}"));+ }+ let bin = paths::bin_dir();+ let exe = bin.join("llama-server.exe");+ if !exe.exists() {+ return Err(format!("E-ENGINE-MISSING {exe:?} (set EDGE0_BIN_DIR)"));+ }+ let port = free_port()?;+ let pool = pool_for(tier);+ let log_p = paths::logs_dir().join(format!("engine-{tier}-{}.log", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)));+ let logfile = std::fs::File::create(&log_p).map_err(|e| e.to_string())?;+ let log2 = logfile.try_clone().map_err(|e| e.to_string())?;+ let mut cmd = Command::new(&exe);+ crate::no_window(&mut cmd)+ .arg("-m").arg(&gguf)+ .arg("--lora").arg(&adapter)+ .args(["-ngl", "99", "-cmoe", "--ctx-size", "8192", "--flash-attn", "on", "--no-webui"])+ .arg("--pool-mb").arg(pool.to_string())+ .arg("--port").arg(port.to_string())+ .current_dir(&bin) // resolve llama/ggml DLLs from the engine's own directory+ .stdout(Stdio::from(logfile))+ .stderr(Stdio::from(log2));+ let child = cmd.spawn()+ .map_err(|e| format!("spawn {exe:?} failed: {e}"))?;+ let job = assign_kill_job(&child); // attach to the job before recording state (failure never blocks; normal path has double insurance)+ let e = Engine {+ child,+ port,+ tier: tier.into(),+ pool_mb: pool,+ started_at: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0),+ log_path: log_p.to_string_lossy().to_string(),+ job,+ };+ let base = format!("http://127.0.0.1:{}", e.port);+ *state.lock().unwrap() = Some(e);++ // Readiness = the /health endpoint actually answering (700 ms tick, 300 s budget)+ let t0 = std::time::Instant::now();+ let client = reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(2)).build().unwrap();+ loop {+ if client.get(format!("{base}/health")).send().map(|r| r.status().is_success()).unwrap_or(false) {+ break;+ }+ let dead = state.lock().unwrap().as_mut().map(|en| en.child.try_wait().ok().flatten().is_some()).unwrap_or(true);+ if dead {+ *state.lock().unwrap() = None;+ return Err(format!("E-ENGINE-DIED see {log_p:?}"));+ }+ if t0.elapsed().as_secs() > 300 {+ return Err("E-ENGINE-READY-TIMEOUT".into());+ }+ std::thread::sleep(std::time::Duration::from_millis(700));+ }+ // Pool telemetry line from the engine log (absent line = pool not active; surfaced, not hidden)+ let pool_line = std::fs::read_to_string(&log_p).ok().and_then(|s| {+ s.lines().rev().find(|l| l.contains("POOL2 init")).map(|l| l.to_string())+ });+ let v = json!({ "running": true, "tier": tier, "base_url": base, "bound": "127.0.0.1",+ "port": port, "pool_mb": pool, "uptime_s": t0.elapsed().as_secs(),+ "log": log_p.to_string_lossy(), "version": server_version(), "job": job,+ "phys_mem_gb": phys_mem_gb(), "pool_telemetry": pool_line });+ sink.emit("engine.status", &v);+ Ok(v)+}++pub fn stop(state: &EngineState) {+ if let Some(mut e) = state.lock().unwrap().take() {+ let _ = e.child.kill();+ let _ = e.child.wait();+ }+}++pub fn status(state: &EngineState) -> Value {+ let mut ts = state.lock().unwrap();+ match ts.as_mut() {+ Some(e) => {+ let dead = e.child.try_wait().ok().flatten().is_some();+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);+ json!({ "running": !dead, "tier": e.tier,+ "base_url": format!("http://127.0.0.1:{}", e.port),+ "bound": "127.0.0.1", "port": e.port, "pool_mb": e.pool_mb,+ "pid": e.child.id(), "uptime_s": now.saturating_sub(e.started_at),+ "log": e.log_path, "version": server_version(), "job": e.job,+ "phys_mem_gb": phys_mem_gb() })+ }+ None => json!({ "running": false }),+ }+}++/// Engine binary version: the actual `llama-server --version` line, cached in a+/// OnceLock; the UI shows the measured value and falls back to null rather than guessing.+pub fn server_version() -> Option<String> {+ static VER: OnceLock<Option<String>> = OnceLock::new();+ VER.get_or_init(|| {+ let exe = paths::bin_dir().join("llama-server.exe");+ let mut cmd = Command::new(&exe);+ crate::no_window(&mut cmd)+ .arg("--version")+ .current_dir(paths::bin_dir())+ .stdout(Stdio::piped())+ .stderr(Stdio::null());+ cmd.spawn()+ .and_then(|c| c.wait_with_output())+ .ok()+ .map(|o| String::from_utf8_lossy(&o.stdout).lines().find(|l| l.starts_with("version:")).map(|l| l.trim().to_string()).unwrap_or_default())+ .filter(|s| !s.is_empty())+ }).clone()+}++/// Read the POOL2 init telemetry line from a log (used by doctor; a missing line =+/// pool-not-active red flag, surfaced honestly).+pub fn pool_telemetry(log_path: &str) -> Option<String> {+ std::fs::read_to_string(log_path).ok().and_then(|s| {+ s.lines().rev().find(|l| l.contains("POOL2 init")).map(|l| l.trim().to_string())+ })+}diff --git a/windows/app/src-tauri/src/lib.rs b/windows/app/src-tauri/src/lib.rsnew file mode 100644index 0000000..89cda2d--- /dev/null+++ b/windows/app/src-tauri/src/lib.rs@@ -0,0 +1,163 @@+// lib.rs — Tauri 2 shell assembly: managed state + command surface + window+// (created in code at 1100×720, clamped to the primary monitor's work area).+pub mod catalog;+pub mod convert;+pub mod doctor;+pub mod engine;+pub mod paths;+pub mod pull;+pub mod sink;++use serde_json::{json, Value};+use std::sync::{Arc, Mutex};+use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};++/// CREATE_NO_WINDOW = 0x0800_0000. A GUI shell has no console, so every child we+/// spawn (llama-server / python) would otherwise flash its own black console window.+/// All shell std Command spawns route through here, so the fix lives in one place.+pub fn no_window(cmd: &mut std::process::Command) -> &mut std::process::Command {+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x0800_0000)+ }+ #[cfg(not(windows))]+ { cmd }+}++pub struct AppState {+ pub tasks: pull::Tasks,+ pub cancels: pull::Cancels,+ pub engine: engine::EngineState,+}++#[tauri::command]+fn catalog_get() -> Value {+ catalog::catalog_value()+}++#[tauri::command]+fn app_paths() -> Value {+ json!({ "home": paths::home().to_string_lossy(),+ "repo": paths::repo_root().to_string_lossy(),+ "bin_dir": paths::bin_dir().to_string_lossy() })+}++#[tauri::command]+fn models_installed() -> Value {+ std::fs::read_to_string(paths::state_dir().join("models.json"))+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_else(|| json!({}))+}++#[tauri::command]+fn download_start(app: AppHandle, st: tauri::State<AppState>, tier: String, source: Option<String>) -> Result<Value, String> {+ pull::start(app, &st.tasks, &st.cancels, &tier, source)+}++#[tauri::command]+fn download_status(st: tauri::State<AppState>, tier: String) -> Value {+ pull::status(&st.tasks, &tier)+}++#[tauri::command]+fn download_cancel(st: tauri::State<AppState>, tier: String) {+ pull::cancel_task(&st.cancels, &tier);+}++#[tauri::command]+async fn model_load(app: AppHandle, tier: String) -> Result<Value, String> {+ // engine::start polls /health with reqwest::blocking + sleep (up to 300 s); a+ // sync command would run that on the main thread and freeze the UI. Offload to a+ // dedicated blocking thread (same convention as pull::start's worker); the+ // promise still resolves on readiness, so the frontend's loading semantics are+ // unchanged. EngineState isn't Arc, so the closure borrows it via AppHandle.state().+ tauri::async_runtime::spawn_blocking(move || {+ let st = app.state::<AppState>();+ let s: Arc<dyn sink::Sink> = Arc::new(sink::TauriSink(app.clone()));+ engine::start(&s, &st.engine, &tier)+ })+ .await+ .map_err(|e| format!("E-LOAD-JOIN {e}"))?+}++#[tauri::command]+fn model_unload(st: tauri::State<AppState>) -> Value {+ engine::stop(&st.engine);+ json!({ "stopped": true })+}++#[tauri::command]+fn engine_status(st: tauri::State<AppState>) -> Value {+ engine::status(&st.engine)+}++#[tauri::command]+async fn doctor_run(app: AppHandle) -> Result<Value, String> {+ // Offloaded like model_load: disk-scan / recompute commands never run on the main thread.+ tauri::async_runtime::spawn_blocking(move || {+ let st = app.state::<AppState>();+ doctor::run(&st.engine)+ })+ .await+ .map_err(|e| format!("E-DOCTOR-JOIN {e}"))+}++#[tauri::command]+async fn model_delete(app: AppHandle, tier: String) -> Result<Value, String> {+ // Multi-GB deletion (seconds under HDD / AV scanning) stays off the main thread;+ // the resident check (engine::status) happens inside the closure too.+ tauri::async_runtime::spawn_blocking(move || {+ let st = app.state::<AppState>();+ let s = engine::status(&st.engine);+ let resident = if s["running"].as_bool().unwrap_or(false) { s["tier"].as_str().map(|t| t.to_string()) } else { None };+ doctor::delete(&tier, resident.as_deref())+ })+ .await+ .map_err(|e| format!("E-DELETE-JOIN {e}"))?+}++#[cfg_attr(mobile, tauri::mobile_entry_point)]+pub fn run() {+ tauri::Builder::default()+ .manage(AppState {+ tasks: Arc::new(Mutex::new(Default::default())),+ cancels: Arc::new(Mutex::new(Default::default())),+ engine: Mutex::new(None),+ })+ .setup(|app| {+ // Base 1100×720, clamped to the primary monitor's work area (a fixed 720+ // on a 200%-DPI display pushes the sidebar footer under the taskbar) + centered.+ let (mut w, mut h): (f64, f64) = (1100.0, 720.0);+ if let Some(m) = app.primary_monitor()? {+ let wa = m.work_area();+ let sf = m.scale_factor();+ w = w.min(wa.size.width as f64 / sf - 40.0);+ h = h.min(wa.size.height as f64 / sf - 40.0);+ }+ let _win = WebviewWindowBuilder::new(app, "main", WebviewUrl::default())+ .title("edge0")+ .inner_size(w.max(480.0), h.max(420.0))+ .center()+ .build()?;+ Ok(())+ })+ .invoke_handler(tauri::generate_handler![+ catalog_get, app_paths, models_installed,+ download_start, download_status, download_cancel,+ model_load, model_unload, engine_status,+ doctor_run, model_delete+ ])+ .build(tauri::generate_context!())+ .expect("edge0 shell failed to start")+ .run(|app, event| {+ if let tauri::RunEvent::ExitRequested { .. } = event {+ // Reclaim the engine child on shell exit (no leaked llama-server orphans;+ // the Job Object is the backstop for crashes/force-kill, this is the clean path)+ if let Some(st) = app.try_state::<AppState>() {+ engine::stop(&st.engine);+ }+ }+ });+}diff --git a/windows/app/src-tauri/src/main.rs b/windows/app/src-tauri/src/main.rsnew file mode 100644index 0000000..2376b6f--- /dev/null+++ b/windows/app/src-tauri/src/main.rs@@ -0,0 +1,6 @@+// Prevents additional console window on Windows in release, DO NOT REMOVE!!+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]++fn main() {+ edge0_app_lib::run()+}diff --git a/windows/app/src-tauri/src/paths.rs b/windows/app/src-tauri/src/paths.rsnew file mode 100644index 0000000..dc39eaf--- /dev/null+++ b/windows/app/src-tauri/src/paths.rs@@ -0,0 +1,89 @@+// paths.rs — the ~/.edge0 directory contract. Every path here is overridable via+// env (EDGE0_HOME etc.) so a test can point the whole app at a throwaway home dir;+// this is the isolation discipline that makes headless end-to-end tests repeatable.+use std::path::PathBuf;++pub fn home() -> PathBuf {+ if let Ok(h) = std::env::var("EDGE0_HOME") {+ return PathBuf::from(h);+ }+ dirs_like_profile().join(".edge0")+}++fn dirs_like_profile() -> PathBuf {+ std::env::var("USERPROFILE")+ .or_else(|_| std::env::var("HOME"))+ .map(PathBuf::from)+ .unwrap_or_else(|_| PathBuf::from("."))+}++// Layout leaf names honor the converter contract: convert_mlx_to_gguf.py derives the+// tier from the basename and expects --out to be a "<dir>-gguf" sibling, matching the+// dev repo's models/edge0-8b{,-gguf} shape.+pub fn models_dir(tier: &str) -> PathBuf {+ home().join("models").join(format!("edge0-{tier}"))+}+pub fn files_dir(tier: &str) -> PathBuf {+ models_dir(tier) // MLX sources land here (basename=edge0-<tier>, the converter's --dir input)+}+pub fn gguf_dir(tier: &str) -> PathBuf {+ home().join("models").join(format!("edge0-{tier}-gguf"))+}+pub fn tmp_dir() -> PathBuf {+ home().join("tmp")+}+pub fn state_dir() -> PathBuf {+ home().join("state")+}+pub fn logs_dir() -> PathBuf {+ home().join("logs")+}++pub fn ensure_dirs(tier: Option<&str>) -> std::io::Result<()> {+ for d in [home(), tmp_dir(), state_dir(), logs_dir()] {+ std::fs::create_dir_all(&d)?;+ }+ if let Some(t) = tier {+ std::fs::create_dir_all(files_dir(t))?;+ std::fs::create_dir_all(gguf_dir(t))?;+ }+ Ok(())+}++/// Repo root (dev layout: where the convert script and tools/ live); override with+/// EDGE0_REPO. Default is derived at compile time from the crate location (this file+/// lives at <repo>/app/src-tauri/src), so it tracks any clone without a hardcoded path.+pub fn repo_root() -> PathBuf {+ std::env::var("EDGE0_REPO")+ .map(PathBuf::from)+ .unwrap_or_else(|_| {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")) // <repo>/app/src-tauri+ .join("../..") // -> <repo> (windows)+ })+}++/// Engine binary directory; override with EDGE0_BIN_DIR. Default is the monorepo depot+/// build (`<repo>/../wt/win/build-vk/bin/Release`, i.e. edge0/wt/... relative to this+/// windows/ subproject). For a sparse/bootstrap build, set EDGE0_BIN_DIR to the engine+/// location printed by scripts/vendor-build.ps1.+pub fn bin_dir() -> PathBuf {+ std::env::var("EDGE0_BIN_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|_| repo_root().join("../wt/win/build-vk/bin/Release"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn repo_root_derivation_tracks_the_checkout() {+ // No env override in unit-test runs: the derived root must actually contain+ // the converter script (works under any clone path/name; fails only if the+ // manifest-relative assumption breaks).+ std::env::remove_var("EDGE0_REPO");+ let rr = repo_root();+ assert!(rr.join("tools").join("convert_mlx_to_gguf.py").exists(),+ "repo_root() = {rr:?} does not look like the windows repo");+ }+}diff --git a/windows/app/src-tauri/src/pull.rs b/windows/app/src-tauri/src/pull.rsnew file mode 100644index 0000000..354ad57--- /dev/null+++ b/windows/app/src-tauri/src/pull.rs@@ -0,0 +1,357 @@+// pull.rs — direct-mode downloader. Resume trusts only the .part file's own length;+// if a source answers a Range request with 200, we reject it (E-DL-SRC) and rotate to+// the next source. Every file is sha256-checked against the embedded manifest before an+// atomic rename into place. On completion the chain runs convert → register+// (phase: probe → download → convert → ready | error | cancelled).+use crate::catalog::{self, Tier};+use crate::convert;+use crate::paths;+use crate::sink::{Sink, TauriSink};+use reqwest::blocking::Client;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::io::{Read, Write};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use tauri::AppHandle;++pub type Tasks = Arc<Mutex<std::collections::HashMap<String, TaskView>>>;+pub type Cancels = Arc<Mutex<std::collections::HashMap<String, Arc<AtomicBool>>>>;++#[derive(Debug, Clone)]+pub struct FileProg {+ pub path: String,+ pub done: u64,+ pub total: u64,+ pub state: String, // pending|active|done+}++#[derive(Debug, Clone)]+pub struct TaskView {+ pub tier: String,+ pub phase: String,+ pub bytes_done: u64,+ pub bytes_total: u64,+ pub source: String,+ pub error: Option<String>,+ pub files: Vec<FileProg>,+}++impl TaskView {+ pub fn to_json(&self) -> Value {+ json!({+ "tier": self.tier, "phase": self.phase,+ "bytes_done": self.bytes_done, "bytes_total": self.bytes_total,+ "source": self.source, "error": self.error,+ "files": self.files.iter().map(|f| json!({"path": f.path, "done": f.done, "total": f.total, "state": f.state})).collect::<Vec<_>>(),+ })+ }+}++fn persist(tier: &str, v: &Value) {+ let p = paths::state_dir().join("downloads");+ let _ = std::fs::create_dir_all(&p);+ let f = p.join(format!("{tier}.json"));+ let tmp = p.join(format!("{tier}.json.tmp"));+ if let Ok(s) = serde_json::to_string_pretty(v) {+ let _ = std::fs::write(&tmp, s);+ let _ = std::fs::rename(&tmp, &f);+ }+}++fn set_phase(tasks: &Tasks, sink: &dyn Sink, tier: &str, phase: &str, err: Option<String>) {+ let v = {+ let mut ts = tasks.lock().unwrap();+ let tv = ts.get_mut(tier).unwrap();+ tv.phase = phase.into();+ tv.error = err;+ tv.to_json()+ };+ persist(tier, &v);+ sink.emit("download.progress", &v);+}++fn verified_map(tier: &str) -> std::collections::HashMap<String, String> {+ std::fs::read_to_string(paths::state_dir().join(format!("verified-{tier}.json")))+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_default()+}++fn record_verified(tier: &str, path: &str, sha: &str) {+ let p = paths::state_dir().join(format!("verified-{tier}.json"));+ let mut m: std::collections::HashMap<String, String> =+ std::fs::read_to_string(&p).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();+ m.insert(path.into(), sha.into());+ if let Ok(s) = serde_json::to_string_pretty(&m) {+ let _ = std::fs::write(&p, s);+ }+}++/// Probe sources by timing a GET of config.json; return candidates ordered fastest-first.+fn probe_ordered(client: &Client, tr: &Tier) -> Vec<(&'static str, String)> {+ let cands = catalog::base_urls(tr);+ let mut times: Vec<std::time::Duration> = Vec::new();+ for (_, base) in &cands {+ let t0 = std::time::Instant::now();+ let ok = client+ .get(format!("{base}/config.json"))+ .timeout(std::time::Duration::from_secs(15))+ .send()+ .map(|r| r.status().is_success())+ .unwrap_or(false);+ times.push(if ok { t0.elapsed() } else { std::time::Duration::from_secs(9e6 as u64) });+ }+ let mut idx: Vec<usize> = (0..cands.len()).collect();+ idx.sort_by_key(|i| times[*i]);+ idx.into_iter().map(|i| cands[i].clone()).collect()+}++/// One file: Range resume + sha256 verification + atomic rename on the same volume.+pub fn pull_one(client: &Client, base: &str, tier: &str, fc: &catalog::CatFile,+ cancel: &AtomicBool, on_bytes: &dyn Fn(u64)) -> Result<(), String> {+ if cancel.load(Ordering::Relaxed) {+ return Err("E-CANCEL".into());+ }+ let key: String = fc+ .path+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' })+ .collect();+ let part = paths::tmp_dir().join(format!("{tier}.{key}.part"));+ let final_p = paths::files_dir(tier).join(&fc.path);+ if final_p.exists() && final_p.metadata().map(|m| m.len() == fc.size).unwrap_or(false) {+ return Ok(());+ }+ let mut from: u64 = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);+ if from > fc.size {+ // dirty resume tail beyond the manifest size: truncate to the true length+ let f = std::fs::OpenOptions::new().write(true).open(&part).map_err(|e| e.to_string())?;+ f.set_len(fc.size).map_err(|e| e.to_string())?;+ from = fc.size;+ }+ let mut req = client+ .get(format!("{base}/{}", fc.path))+ .timeout(std::time::Duration::from_secs(3600));+ if from > 0 {+ req = req.header("Range", format!("bytes={from}-"));+ }+ let mut resp = req.send().map_err(|e| format!("E-DL-NET {e}"))?;+ if from > 0 && resp.status() == reqwest::StatusCode::OK {+ return Err("E-DL-SRC".into()); // source ignores Range semantics: refuse the full body, let the caller rotate+ }+ if !resp.status().is_success() {+ return Err(format!("E-DL-NET http {}", resp.status()));+ }+ if from > 0 && resp.status() == reqwest::StatusCode::PARTIAL_CONTENT {+ // Content-Range start must equal our local prefix, else discard the .part and refetch+ if let Some(cr) = resp.headers().get("Content-Range").and_then(|v| v.to_str().ok()).map(|s| s.to_string()) {+ if !cr.starts_with(&format!("bytes {from}-")) {+ let _ = std::fs::remove_file(&part);+ return Err("E-DL-SRC".into());+ }+ }+ }+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&part)+ .map_err(|e| e.to_string())?;+ let mut buf = vec![0u8; 1 << 20]; // heap buffer (thread stacks default to 2 MB — large buffers must leave the stack)+ loop {+ if cancel.load(Ordering::Relaxed) {+ return Err("E-CANCEL".into());+ }+ let n = resp.read(&mut buf).map_err(|e| format!("E-DL-NET stream {e}"))?;+ if n == 0 {+ break;+ }+ file.write_all(&buf[..n]).map_err(|e| e.to_string())?;+ on_bytes(n as u64);+ }+ file.flush().ok();+ let size = std::fs::metadata(&part).map_err(|e| e.to_string())?.len();+ if size != fc.size {+ let _ = std::fs::remove_file(&part);+ return Err(format!("E-DL-SIZE {size}/{}", fc.size));+ }+ let mut f = std::fs::File::open(&part).map_err(|e| e.to_string())?;+ let mut h = Sha256::new();+ let mut acc = 0u64;+ while acc < size {+ let n = f.read(&mut buf).map_err(|e| e.to_string())?;+ if n == 0 {+ break;+ }+ h.update(&buf[..n]);+ acc += n as u64;+ }+ let got = hex::encode(h.finalize());+ if got != fc.sha256 {+ let _ = std::fs::remove_file(&part);+ return Err(format!("E-DL-SHA {}", fc.path));+ }+ std::fs::rename(&part, &final_p).map_err(|e| e.to_string())?; // atomic rename on the same volume+ record_verified(tier, &fc.path, &fc.sha256);+ Ok(())+}++pub fn start(app: AppHandle, tasks: &Tasks, cancels: &Cancels,+ tier: &str, source_hint: Option<String>) -> Result<Value, String> {+ let cat = catalog::catalog();+ let tr = cat.get(tier).ok_or_else(|| format!("no such tier: {tier}"))?.clone();+ {+ let mut ts = tasks.lock().unwrap();+ if let Some(v) = ts.get(tier) {+ if matches!(v.phase.as_str(), "probe" | "download" | "convert") {+ return Ok(json!({ "already_running": true }));+ }+ }+ let verif = verified_map(tier);+ let mut pre_done = 0u64;+ let files = tr+ .files+ .iter()+ .filter(|f| !f.skip)+ .map(|f| {+ let done = verif.contains_key(&f.path) || paths::files_dir(tier).join(&f.path).metadata().map(|m| m.len() == f.size).unwrap_or(false);+ if done {+ pre_done += f.size;+ }+ FileProg { path: f.path.clone(), done: if done { f.size } else { 0 }, total: f.size, state: if done { "done".into() } else { "pending".into() } }+ })+ .collect();+ ts.insert(tier.to_string(), TaskView {+ tier: tier.into(), phase: "probe".into(), bytes_done: pre_done,+ bytes_total: tr.total_bytes, source: String::new(), error: None, files,+ });+ }+ let cancel = Arc::new(AtomicBool::new(false));+ cancels.lock().unwrap().insert(tier.to_string(), cancel.clone());+ let sink: Arc<dyn Sink> = Arc::new(TauriSink(app.clone()));+ let (tasks_c, canc_c, tier_s) = (tasks.clone(), cancels.clone(), tier.to_string());+ std::thread::Builder::new()+ .name(format!("pull-{tier}"))+ .spawn(move || {+ run(sink, tasks_c, canc_c, tier_s, tr, cancel, source_hint);+ })+ .map_err(|e| e.to_string())+ .map(|_| json!({ "started": true }))+}++/// The full download + convert + register chain, callable headlessly (tests use this+/// directly). An Err return means the error phase was already set on the task view.+pub fn run(sink: Arc<dyn Sink>, tasks: Tasks, cancels: Cancels, tier: String, tr: Tier,+ cancel: Arc<AtomicBool>, source_hint: Option<String>) {+ let _ = paths::ensure_dirs(Some(&tier));+ let client = Client::builder().user_agent("edge0-app/0.1").build().unwrap();+ let ordered: Vec<(&'static str, String)> = match source_hint {+ Some(h) => {+ let mut c = catalog::base_urls(&tr);+ if let Some(i) = c.iter().position(|(n, _)| *n == h.as_str()) {+ c.rotate_left(i);+ }+ c+ }+ None => probe_ordered(&client, &tr),+ };+ {+ let mut ts = tasks.lock().unwrap();+ ts.get_mut(&tier).unwrap().source = ordered[0].0.to_string();+ }+ set_phase(&tasks, &*sink,&tier, "download", None);++ let todo: Vec<catalog::CatFile> = tr.files.iter().filter(|f| !f.skip).cloned().collect();+ let mut src_i = 0usize;+ for fc in todo {+ loop {+ let (name, base) = ordered[src_i].clone();+ let (sink_c, tasks_c, tier_c, path_c) = (sink.clone(), tasks.clone(), tier.clone(), fc.path.clone());+ let r = pull_one(&client, &base, &tier, &fc, &cancel, &|n| {+ let v = {+ let mut ts = tasks_c.lock().unwrap();+ let tv = ts.get_mut(&tier_c).unwrap();+ tv.bytes_done = (tv.bytes_done + n).min(tv.bytes_total);+ if let Some(f) = tv.files.iter_mut().find(|x| x.path == path_c) {+ f.done = (f.done + n).min(f.total);+ if f.state == "pending" {+ f.state = "active".into();+ }+ }+ tv.to_json()+ };+ sink_c.emit("download.progress", &v);+ });+ match r {+ Ok(()) => {+ {+ let mut ts = tasks.lock().unwrap();+ let tv = ts.get_mut(&tier).unwrap();+ if let Some(f) = tv.files.iter_mut().find(|x| x.path == fc.path) {+ f.state = "done".into();+ f.done = f.total;+ tv.bytes_done = tv.files.iter().map(|x| x.done).sum();+ }+ }+ persist(&tier, &tasks.lock().unwrap().get(&tier).unwrap().to_json());+ break;+ }+ Err(e) if e == "E-CANCEL" => {+ set_phase(&tasks, &*sink,&tier, "cancelled", None);+ cancels.lock().unwrap().remove(&tier);+ return;+ }+ Err(e) if (e.starts_with("E-DL-SRC") || e.starts_with("E-DL-NET")) && src_i + 1 < ordered.len() => {+ src_i += 1; // rotate to the next source and retry this file+ {+ let mut ts = tasks.lock().unwrap();+ ts.get_mut(&tier).unwrap().source = ordered[src_i].0.to_string();+ }+ continue;+ }+ Err(e) => {+ set_phase(&tasks, &*sink,&tier, "error", Some(format!("{e} @{} via {name}", fc.path)));+ cancels.lock().unwrap().remove(&tier);+ return;+ }+ }+ }+ }++ set_phase(&tasks, &*sink,&tier, "convert", None);+ match convert::run(&sink, &tier) {+ Ok(r3_sha) => {+ register_ready(&tier, &tr, r3_sha);+ set_phase(&tasks, &*sink,&tier, "ready", None);+ }+ Err(e) => set_phase(&tasks, &*sink, &tier, "error", Some(format!("E-CONVERT {e}"))),+ }+ cancels.lock().unwrap().remove(&tier);+}++fn register_ready(tier: &str, tr: &Tier, r3_sha: String) {+ let p = paths::state_dir().join("models.json");+ let mut m: Value = std::fs::read_to_string(&p)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_else(|| json!({}));+ m[tier] = json!({+ "installed_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0),+ "repo": tr.repo, "rev_hf": tr.rev.hf,+ "gguf_dir": paths::gguf_dir(tier).to_string_lossy(),+ "files_dir": paths::files_dir(tier).to_string_lossy(),+ "r3_sha256": r3_sha,+ "pool_mb": tr.pool_mb,+ });+ let _ = std::fs::write(&p, serde_json::to_string_pretty(&m).unwrap());+}++pub fn status(tasks: &Tasks, tier: &str) -> Value {+ tasks.lock().unwrap().get(tier).map(|v| v.to_json()).unwrap_or_else(|| json!({ "tier": tier, "phase": "idle" }))+}++pub fn cancel_task(cancels: &Cancels, tier: &str) {+ if let Some(c) = cancels.lock().unwrap().get(tier) {+ c.store(true, Ordering::Relaxed);+ }+}diff --git a/windows/app/src-tauri/src/sink.rs b/windows/app/src-tauri/src/sink.rsnew file mode 100644index 0000000..a2711ac--- /dev/null+++ b/windows/app/src-tauri/src/sink.rs@@ -0,0 +1,21 @@+// sink.rs — event-output abstraction. Running in the shell it is TauriSink(AppHandle);+// in headless tests it is NoopSink. pull/convert/engine depend on this trait instead of+// the window handle directly, which is what lets them run without a GUI.+use serde_json::Value;+use tauri::{AppHandle, Emitter};++pub trait Sink: Send + Sync {+ fn emit(&self, event: &str, payload: &Value);+}++pub struct NoopSink;+impl Sink for NoopSink {+ fn emit(&self, _event: &str, _payload: &Value) {}+}++pub struct TauriSink(pub AppHandle);+impl Sink for TauriSink {+ fn emit(&self, event: &str, payload: &Value) {+ let _ = self.0.emit(event, payload);+ }+}diff --git a/windows/app/src-tauri/tauri.conf.json b/windows/app/src-tauri/tauri.conf.jsonnew file mode 100644index 0000000..145edfd--- /dev/null+++ b/windows/app/src-tauri/tauri.conf.json@@ -0,0 +1,23 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "productName": "edge0",+ "version": "0.1.0",+ "identifier": "app.edge0.client-win",+ "build": {+ "beforeDevCommand": "npm run dev",+ "devUrl": "http://localhost:1420",+ "beforeBuildCommand": "npm run build",+ "frontendDist": "../dist"+ },+ "app": {+ "windows": [],+ "security": {+ "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:*"+ }+ },+ "bundle": {+ "active": true,+ "targets": ["nsis"],+ "icon": ["icons/icon.ico", "icons/icon.png"]+ }+}diff --git a/windows/app/src-tauri/tests/doctor.rs b/windows/app/src-tauri/tests/doctor.rsnew file mode 100644index 0000000..dcfc6d5--- /dev/null+++ b/windows/app/src-tauri/tests/doctor.rs@@ -0,0 +1,82 @@+// tests/doctor.rs — doctor check contract + model_delete protection lines (isolated home;+// tests serialized via a process lock to avoid env races).+use edge0_app_lib::{doctor, paths};+use serde_json::json;+use std::sync::Once;++static INIT: Once = Once::new();+// cargo test runs threads in parallel: both tests share the isolated home/env,+// so serialize them with a mutex (poison-tolerant).+static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++fn iso_home() -> std::path::PathBuf {+ INIT.call_once(|| {+ let h = std::env::temp_dir().join(format!("edge0-doctor-itest-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&h);+ std::fs::create_dir_all(h.join("state")).unwrap();+ std::env::set_var("EDGE0_HOME", &h);+ std::env::set_var("EDGE0_BIN_DIR", &h); // empty dir ⇒ engine=fail anchors the assertion+ std::env::set_var("EDGE0_PHYS_MEM_GB", "8");+ });+ paths::home()+}++#[test]+fn doctor_contract_shape() {+ let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let h = iso_home();+ std::fs::create_dir_all(h.join("models")).unwrap();+ // register a fake "installed" tier without files ⇒ the model-8b fail / E-MODEL-INVALID path+ std::fs::write(h.join("state/models.json"), json!({ "8b": { "pool_mb": 2048 } }).to_string()).unwrap();++ let r = doctor::run(&std::sync::Mutex::new(None));+ assert_eq!(r["overall"], "warn", "overall=warn whenever any fail/warn exists");+ let find = |id: &str| r["checks"].as_array().expect("checks is an array").iter().find(|c| c["id"] == id).cloned();++ assert_eq!(find("home").unwrap()["verdict"], "pass", "isolated home is writable");+ assert!(doctor::disk_free_gb(&h).is_some(), "disk free space reads as a real value");+ let eng = find("engine").unwrap();+ assert_eq!(eng["verdict"], "fail");+ assert_eq!(eng["code"], "E-ENGINE-MISSING");+ assert_eq!(find("memory").unwrap()["code"], "E-MEM-LOAD", "8 GB ⇒ warn, 8b tier only");+ let m8 = find("model-8b").unwrap();+ assert_eq!(m8["verdict"], "fail", "registered but files missing = red INVALID flag");+ assert_eq!(m8["code"], "E-MODEL-INVALID");+ assert_eq!(find("model-35b").unwrap()["verdict"], "warn", "not installed = warn, not fail");+}++#[test]+fn delete_protection_and_idempotent() {+ let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let h = iso_home();+ // busy: deleting the resident tier is refused+ let e = doctor::delete("8b", Some("8b"));+ assert!(e.unwrap_err().starts_with("E-MODEL-BUSY"));+ // real directories: physical delete + deregistration+ let f = paths::files_dir("t-del");+ let g = paths::gguf_dir("t-del");+ std::fs::create_dir_all(&f).unwrap();+ std::fs::create_dir_all(&g).unwrap();+ std::fs::write(f.join("x.bin"), b"hi").unwrap();+ let mp = h.join("state/models.json");+ std::fs::write(&mp, json!({ "t-del": {} }).to_string()).unwrap();+ doctor::delete("t-del", None).unwrap();+ assert!(!f.exists() && !g.exists());+ let m: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&mp).unwrap()).unwrap();+ assert!(m.get("t-del").is_none(), "tier removed from models.json");+ // idempotent: deleting an absent tier is Ok+ assert!(doctor::delete("t-none", None).is_ok());+ // junction refuses deletion (seed-link protection): create a junction at+ // files_dir(jtest) ⇒ E-MODEL-PROTECTED+ let j = paths::files_dir("jtest");+ let out = std::process::Command::new("cmd")+ .args(["/c", "mklink", "/J", &j.to_string_lossy(), &paths::home().to_string_lossy()])+ .output();+ if out.map(|o| o.status.success()).unwrap_or(false) && j.exists() {+ let err = doctor::delete("jtest", None).unwrap_err();+ assert!(err.starts_with("E-MODEL-PROTECTED"), "{err}");+ assert!(j.exists(), "the junction survives the refused deletion");+ let _ = std::process::Command::new("cmd").args(["/c", "rmdir", &j.to_string_lossy()]).output();+ }+ // if mklink fails (no privilege) this leg skips — the real seed-link path is covered by manual runs.+}diff --git a/windows/app/src-tauri/tests/job.rs b/windows/app/src-tauri/tests/job.rsnew file mode 100644index 0000000..74ee296--- /dev/null+++ b/windows/app/src-tauri/tests/job.rs@@ -0,0 +1,84 @@+// tests/job.rs — Job Object gate: (1) production assign_kill_job returns true and really+// attaches; (2) closing the job handle makes the OS kill the member process+// (KILL_ON_JOB_CLOSE semantics, same windows-sys structs as production); (3) a real+// llama-server gets attached end-to-end (ignored test, needs the model).+use edge0_app_lib::engine::assign_kill_job;+use std::os::windows::io::AsRawHandle;+use std::process::{Command, Stdio};+use windows_sys::Win32::Foundation::CloseHandle;+use windows_sys::Win32::System::JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,+ SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+};++fn spawn_linger() -> std::process::Child {+ Command::new("ping")+ .args(["-n", "60", "127.0.0.1"])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("ping spawn")+}++#[test]+fn assign_kill_job_true() {+ let mut child = spawn_linger();+ let ok = assign_kill_job(&child);+ let _ = child.kill();+ let _ = child.wait();+ assert!(ok, "job create + SetInformation(KILL_ON_JOB_CLOSE) + Assign all succeeded");+}++#[test]+fn job_close_kills_child() {+ unsafe {+ let mut child = spawn_linger();+ let job = CreateJobObjectW(std::ptr::null(), std::ptr::null());+ assert!(!job.is_null(), "CreateJobObjectW");+ let mut li: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();+ li.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ assert_ne!(+ SetInformationJobObject(+ job,+ JobObjectExtendedLimitInformation,+ &li as *const _ as *const core::ffi::c_void,+ std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ ),+ 0,+ "SetInformationJobObject"+ );+ assert_ne!(AssignProcessToJobObject(job, child.as_raw_handle() as _), 0, "Assign");+ assert_ne!(CloseHandle(job), 0, "CloseHandle(job)");++ // closing the job must make the kernel kill the member ping (a 60 s process should die within seconds; 10 s ceiling)+ let t0 = std::time::Instant::now();+ loop {+ if child.try_wait().expect("try_wait").is_some() {+ break;+ }+ assert!(t0.elapsed().as_secs() < 10, "KILL_ON_JOB_CLOSE did not fire (child alive after 10 s)");+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ }+}++/// Real end-to-end (needs an 8b model under ~/.edge0 + llama-server at EDGE0_BIN_DIR):+/// engine::start launches the actual llama-server, asserts job:true (the real process+/// really attached), checks status echoes it, then stop() brings running=false.+#[test]+#[ignore = "needs the real 8b model and llama-server; run manually: cargo test --test job -- --ignored"]+fn engine_start_attaches_real_llama_to_job() {+ use edge0_app_lib::{engine, sink::NoopSink, sink::Sink};+ use std::sync::{Arc, Mutex};+ let sink: Arc<dyn Sink> = Arc::new(NoopSink);+ let state: engine::EngineState = Mutex::new(None);+ let v = engine::start(&sink, &state, "8b").expect("real 8b chain start");+ assert_eq!(v["running"], serde_json::json!(true));+ assert_eq!(v["job"], serde_json::json!(true), "the real llama-server must be attached to the kill-on-close job");+ let st = engine::status(&state);+ let pid = st["pid"].as_u64().expect("pid present");+ assert_eq!(st["job"], serde_json::json!(true), "status must echo the job flag too");+ engine::stop(&state);+ assert_eq!(engine::status(&state)["running"], serde_json::json!(false));+ println!("REAL JOB CHAIN GREEN pid={pid}");+}diff --git a/windows/app/src-tauri/tests/pull.rs b/windows/app/src-tauri/tests/pull.rsnew file mode 100644index 0000000..7e1f628--- /dev/null+++ b/windows/app/src-tauri/tests/pull.rs@@ -0,0 +1,181 @@+// tests/pull.rs — fast gate: a fake HTTP server plays Range tri-state + sha mismatch ++// dirty-tail truncation. Whole run isolated in a temp EDGE0_HOME (unique tier names+// per case so tests never tread on each other).+use edge0_app_lib::catalog::CatFile;+use edge0_app_lib::paths;+use edge0_app_lib::pull::pull_one;+use sha2::{Digest, Sha256};+use std::io::{Read, Write};+use std::net::TcpListener;+use std::sync::atomic::AtomicBool;+use std::sync::Once;++static INIT: Once = Once::new();++fn test_home() -> std::path::PathBuf {+ INIT.call_once(|| {+ let h = std::env::temp_dir().join(format!("edge0-itest-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&h);+ std::env::set_var("EDGE0_HOME", &h);+ });+ paths::home()+}++fn sha(bytes: &[u8]) -> String {+ hex::encode(Sha256::digest(bytes))+}++fn pattern(n: usize) -> Vec<u8> {+ (0..n).map(|i| ((i * 31 + 7) % 251) as u8).collect()+}++/// Fake source: mode = range (honors Range) | rude (answers Range with 200 full body) | corrupt (shifted content)+fn serve(content: Vec<u8>, mode: &'static str) -> String {+ let l = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = l.local_addr().unwrap().port();+ std::thread::spawn(move || {+ for stream in l.incoming() {+ let mut s = match stream { Ok(s) => s, Err(_) => continue };+ let mut buf = [0u8; 4096];+ let mut head = String::new();+ while let Ok(n) = s.read(&mut buf) {+ if n == 0 {+ break;+ }+ head.push_str(&String::from_utf8_lossy(&buf[..n]));+ if head.contains("\r\n\r\n") {+ break;+ }+ }+ let want: Option<u64> = match mode {+ _ if !head.contains("Range:") => None,+ _ => head+ .find("bytes=")+ .and_then(|i| head[i + 6..].split('-').next())+ .and_then(|s| s.parse().ok()),+ };+ let mut body = content.clone();+ if mode == "corrupt" {+ for b in body.iter_mut() {+ *b = b.wrapping_add(1);+ }+ }+ let resp_head = match (mode, want) {+ ("rude", Some(_)) => format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()),+ (_, Some(f)) if f <= body.len() as u64 => {+ let tail = &body[f as usize..];+ let end = f + tail.len() as u64 - 1;+ format!("HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {f}-{end}/{}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ content.len(), tail.len())+ }+ _ => format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()),+ };+ let send_body = match (mode, want) {+ (_, Some(f)) if f <= body.len() as u64 && mode != "rude" => body[f as usize..].to_vec(),+ _ => body.clone(),+ };+ let _ = s.write_all(resp_head.as_bytes());+ let _ = s.write_all(&send_body);+ let _ = s.flush();+ }+ });+ format!("http://127.0.0.1:{port}")+}++fn fc(path: &str, bytes: &[u8]) -> CatFile {+ CatFile { path: path.into(), size: bytes.len() as u64, sha256: sha(bytes), skip: false }+}++fn cancel() -> AtomicBool {+ AtomicBool::new(false)+}++#[test]+fn pull_fresh_full() {+ let _h = test_home();+ let _ = paths::ensure_dirs(Some("t1"));+ let data = pattern(5000);+ let c = reqwest::blocking::Client::new();+ let base = serve(data.clone(), "range");+ pull_one(&c, &base, "t1", &fc("a.bin", &data), &cancel(), &|_| {}).unwrap();+ assert_eq!(std::fs::read(paths::files_dir("t1").join("a.bin")).unwrap(), data);+}++#[test]+fn pull_resume_206() {+ let _h = test_home();+ let h = test_home();+ let _ = paths::ensure_dirs(Some("t2"));+ let data = pattern(10_000);+ std::fs::write(h.join("tmp/t2.a.bin.part"), &data[..4096]).unwrap();+ let c = reqwest::blocking::Client::new();+ let base = serve(data.clone(), "range");+ let got_n = std::sync::atomic::AtomicU64::new(0);+ pull_one(&c, &base, "t2", &fc("a.bin", &data), &cancel(), &|n| {+ got_n.fetch_add(n, std::sync::atomic::Ordering::Relaxed);+ })+ .unwrap();+ assert_eq!(std::fs::read(paths::files_dir("t2").join("a.bin")).unwrap(), data);+ assert_eq!(got_n.load(std::sync::atomic::Ordering::Relaxed), 10_000 - 4096, "resume must fetch only the missing tail");+}++#[test]+fn pull_resume_dirty_tail_bad_sha() {+ let h = test_home();+ let _ = paths::ensure_dirs(Some("t3"));+ let data = pattern(2000);+ std::fs::write(h.join("tmp/t3.a.bin.part"), vec![9u8; 5000]).unwrap(); // oversized dirty tail, wrong content+ let c = reqwest::blocking::Client::new();+ let base = serve(data.clone(), "range");+ let r = pull_one(&c, &base, "t3", &fc("a.bin", &data), &cancel(), &|_| {});+ assert!(matches!(&r, Err(e) if e.starts_with("E-DL-SHA") || e.starts_with("E-DL-SRC")), "{r:?}");+}++#[test]+fn pull_rude_source_rejected() {+ let h = test_home();+ let _ = paths::ensure_dirs(Some("t4"));+ let data = pattern(3000);+ std::fs::write(h.join("tmp/t4.a.bin.part"), &data[..1000]).unwrap();+ let c = reqwest::blocking::Client::new();+ let base = serve(data.clone(), "rude");+ let r = pull_one(&c, &base, "t4", &fc("a.bin", &data), &cancel(), &|_| {});+ assert_eq!(r.unwrap_err(), "E-DL-SRC");+}++#[test]+fn pull_corrupt_content_sha_red() {+ let _h = test_home();+ let _ = paths::ensure_dirs(Some("t5"));+ let data = pattern(2048);+ let c = reqwest::blocking::Client::new();+ let base = serve(data.clone(), "corrupt");+ let r = pull_one(&c, &base, "t5", &fc("a.bin", &data), &cancel(), &|_| {});+ assert!(r.unwrap_err().starts_with("E-DL-SHA"));+}++#[test]+fn catalog_contract() {+ let cat = edge0_app_lib::catalog::catalog();+ let t8 = cat.get("8b").expect("8b tier in catalog");+ assert!(t8.files.iter().any(|f| f.skip && f.path.contains("prerouter")));+ assert!(!t8.files.iter().any(|f| !f.skip && f.path.contains("prerouter")));+ assert_eq!(t8.total_bytes, t8.files.iter().filter(|f| !f.skip).map(|f| f.size).sum::<u64>());+ let t35 = cat.get("35b").expect("35b tier in catalog");+ assert!(t35.files.iter().any(|f| f.skip && (f.path.ends_with(".jpg") || f.path.ends_with(".mp4"))));+ assert_eq!(t35.rev.hf.len(), 40, "35b HF revision pinned to a full commit sha");+ // source contract (overseas release decision): hf first, hf-mirror/modelscope as fallbacks; hf url tail = commit sha+ let urls = edge0_app_lib::catalog::base_urls(t35);+ let names: Vec<&str> = urls.iter().map(|(n, _)| *n).collect();+ assert_eq!(names, vec!["hf", "hf-mirror", "modelscope"], "source order = huggingface first");+ assert!(urls[0].1.starts_with("https://huggingface.co/") && urls[0].1.ends_with(&t35.rev.hf), "hf url carries the commit sha");+ assert!(urls[2].1.contains(&t35.rev.modelscope), "modelscope url carries its revision");+}++#[test]+fn pool_clamp_contract() {+ for t in ["8b", "35b", "nonexist"] {+ let p = edge0_app_lib::engine::pool_for(t);+ assert!((512..=4096).contains(&p), "{t} → {p} outside the safe band (contract forbids XL)");+ }+}diff --git a/windows/app/src-tauri/tests/real8b.rs b/windows/app/src-tauri/tests/real8b.rsnew file mode 100644index 0000000..d1a06ae--- /dev/null+++ b/windows/app/src-tauri/tests/real8b.rs@@ -0,0 +1,78 @@+// tests/real8b.rs — real end-to-end pipeline (EDGE0_TEST_TIER=8b|35b: download → convert+// → engine → chat → assertions). Manual tier: cargo test --test real8b -- --ignored+// --nocapture. The isolated EDGE0_HOME uses a fixed name and is not wiped at startup —+// rerunning the same command resumes idempotently. For 35b the POOL2 telemetry line is+// REQUIRED (phantom defense: never claim pool-backed numbers without the live proof).+use edge0_app_lib::{catalog, engine, paths, pull, sink::NoopSink};+use serde_json::{json, Value};+use std::collections::HashMap;+use std::sync::atomic::AtomicBool;+use std::sync::{Arc, Mutex};++#[test]+#[ignore]+fn real8b_pipeline() {+ let tier = std::env::var("EDGE0_TEST_TIER").unwrap_or_else(|_| "8b".into());+ let h = std::env::temp_dir().join(format!("edge0-real-{}", tier));+ std::env::set_var("EDGE0_HOME", &h);+ paths::ensure_dirs(Some(&tier)).unwrap();++ let mut cat = catalog::catalog();+ let tr = cat.remove(&tier).unwrap_or_else(|| panic!("{tier} tier missing from catalog"));+ let tasks: pull::Tasks = Arc::new(Mutex::new(HashMap::new()));+ tasks.lock().unwrap().insert(tier.clone(), pull::TaskView {+ tier: tier.clone(), phase: "probe".into(), bytes_done: 0, bytes_total: tr.total_bytes,+ source: String::new(), error: None,+ files: tr.files.iter().filter(|f| !f.skip)+ .map(|f| pull::FileProg { path: f.path.clone(), done: 0, total: f.size, state: "pending".into() })+ .collect(),+ });+ let cancels: pull::Cancels = Arc::new(Mutex::new(HashMap::new()));+ let sink: Arc<dyn edge0_app_lib::sink::Sink> = Arc::new(NoopSink);++ let src = std::env::var("EDGE0_TEST_SOURCE").unwrap_or_else(|_| "modelscope".into());+ pull::run(sink.clone(), tasks.clone(), cancels, tier.clone(), tr, Arc::new(AtomicBool::new(false)), Some(src));++ let v = tasks.lock().unwrap().get(&tier).unwrap().to_json();+ println!("pipeline phase={}", v["phase"]);+ assert_eq!(v["phase"].as_str(), Some("ready"), "full chain should end ready: {v}");++ let gguf = paths::gguf_dir(&tier).join(format!("edge0-{tier}.gguf"));+ let adapter = paths::files_dir(&tier).join(format!("lora_edge0_{tier}-gguf.gguf"));+ assert!(gguf.exists() && adapter.exists(), "conversion artifacts present");++ // engine + chat+ let state: engine::EngineState = Mutex::new(None);+ let info = engine::start(&sink, &state, &tier).expect("engine start");+ println!("engine: {info}");+ if tier == "35b" {+ let tel = info["pool_telemetry"].as_str().unwrap_or_default().to_string();+ assert!(tel.contains("tt=120") && tel.contains("resolver=on"),+ "phantom defense: 35b must show live pool telemetry, never claim pool-backed numbers without it: {tel:?}");+ assert_eq!(info["pool_mb"].as_u64(), Some(4096), "16 GB-class pool table value = 4096");+ }+ let base = info["base_url"].as_str().unwrap().to_string();+ let client = reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(600)).build().unwrap();+ // prompt asks for exact markdown artifacts (table + code fence); assertions below+ // check those tokens. Chinese on purpose: this fixture also exercises the model's native language.+ let resp: Value = client+ .post(format!("{base}/v1/chat/completions"))+ .json(&json!({"messages": [{"role": "user",+ "content": "请原样输出:①markdown 表格(两列 算式/结果,两行 1+1 与 2+2)②python 代码块 print(42)。除此之外不要任何文字"}],+ "max_tokens": 400, "temperature": 0.0}))+ .send().unwrap().json().unwrap();+ let msg = &resp["choices"][0]["message"];+ let content = msg["content"].as_str().unwrap_or_default().to_string();+ let reasoning = msg["reasoning_content"].as_str().unwrap_or_default().to_string();+ engine::stop(&state); // reclaim the engine before asserting (a panic must not leak the process)+ println!("resp: content={}B reasoning={}B", content.len(), reasoning.len());+ let joined = format!("{content}{reasoning}");+ assert!(joined.contains('|') && joined.contains("```"), "markdown artifacts (table + code fence) missing");+ println!("reply head: {}", &joined[..joined.len().min(300)]);++ // ledger cross-check+ let m: Value = serde_json::from_str(&std::fs::read_to_string(paths::state_dir().join("models.json")).unwrap()).unwrap();+ let sha = m[&tier]["r3_sha256"].as_str().unwrap_or_default().to_string();+ println!("registered r3 sha256={sha}");+ assert_eq!(sha.len(), 64);+}diff --git a/windows/app/src/api/client.ts b/windows/app/src/api/client.tsnew file mode 100644index 0000000..27a3f83--- /dev/null+++ b/windows/app/src/api/client.ts@@ -0,0 +1,140 @@+// api/client.ts — shell IPC wrapper + one-pulse stores. Two-layer architecture:+// data sources are invoke commands + Tauri events only; the frontend never+// invents polling and never fabricates estimates.+import { invoke } from "@tauri-apps/api/core";+import { listen } from "@tauri-apps/api/event";++export type EngStatus = {+ running: boolean; tier?: string; base_url?: string; bound?: string; port?: number;+ pool_mb?: number; uptime_s?: number; log?: string; version?: string | null;+ phys_mem_gb?: number; pool_telemetry?: string | null; pid?: number; job?: boolean;+};+export type FileProg = { path: string; done: number; total: number; state: string };+export type TaskView = {+ tier: string; phase: string; bytes_done: number; bytes_total: number;+ source: string; error: string | null; files?: FileProg[];+};+export type CatTier = { repo: string; rev: { modelscope: string; hf: string }; total_bytes: number; pool_mb: number; files: { path: string; size: number; skip?: boolean }[] };++class Sig {+ private ls = new Set<() => void>();+ private v = 0;+ sub = (fn: () => void): (() => void) => {+ this.ls.add(fn);+ return () => { this.ls.delete(fn); };+ };+ version = () => this.v;+ emit() {+ this.v++;+ for (const f of [...this.ls]) f();+ }+}++export const engineStore = {+ status: null as EngStatus | null,+ loadingTier: null as string | null, // in-flight model_load marker (one source of truth for the "loading" light)+ sig: new Sig(),+};++export const downloadStore = {+ tasks: {} as Record<string, TaskView>,+ sig: new Sig(),+ apply(v: TaskView) {+ this.tasks = { ...this.tasks, [v.tier]: v };+ this.sig.emit();+ },+};++export const shellStore = {+ catalog: {} as Record<string, CatTier>,+ paths: { home: "", repo: "", bin_dir: "" },+ installed: {} as Record<string, unknown>,+ sig: new Sig(),+};++/** Ring buffer of request log rows (service-page data = frontend-measured: model / latency / tokens / status; since app start, cleared on exit — labeled honestly). */+export type ReqRow = { ts: number; model: string; status: "done" | "cancelled" | "error"; latencyMs: number; tokens: number | null; code: string | null };+export const reqLog = {+ rows: [] as ReqRow[],+ sig: new Sig(),+ add(r: ReqRow) {+ this.rows = [r, ...this.rows].slice(0, 200);+ this.sig.emit();+ },+};++let bootOnce: Promise<void> | null = null;++/** Idempotent boot: initial fetch + event wiring (shared by main.tsx and first-screen components; repeat calls share one Promise). */+export function boot(): Promise<void> {+ if (!bootOnce) bootOnce = bootNow();+ return bootOnce;+}++async function bootNow(): Promise<void> {+ try {+ shellStore.catalog = await invoke<Record<string, CatTier>>("catalog_get");+ shellStore.paths = await invoke("app_paths");+ await refreshInstalled();+ engineStore.status = await invoke<EngStatus>("engine_status");+ for (const tier of Object.keys(shellStore.catalog)) {+ downloadStore.tasks[tier] = await invoke<TaskView>("download_status", { tier });+ }+ } catch { /* shell not ready yet: stores stay null, UI renders its waiting shape */ }+ void listen<EngStatus>("engine.status", (e) => {+ engineStore.status = e.payload;+ engineStore.sig.emit();+ });+ void listen<TaskView>("download.progress", (e) => downloadStore.apply(e.payload));+ shellStore.sig.emit();+ engineStore.sig.emit();+ downloadStore.sig.emit();+}++export async function refreshInstalled(): Promise<void> {+ shellStore.installed = await invoke<Record<string, unknown>>("models_installed");+ shellStore.sig.emit();+}++/** Models-page refresh button: refresh re-pulls the sources of truth; it is not a poll. */+export async function refreshAll(): Promise<void> {+ try {+ await refreshInstalled();+ engineStore.status = await invoke<EngStatus>("engine_status");+ for (const tier of Object.keys(shellStore.catalog)) {+ downloadStore.tasks[tier] = await invoke<TaskView>("download_status", { tier });+ }+ } finally {+ engineStore.sig.emit();+ downloadStore.sig.emit();+ }+}++export async function loadModel(tier: string): Promise<EngStatus> {+ engineStore.loadingTier = tier;+ engineStore.sig.emit();+ try {+ const s = await invoke<EngStatus>("model_load", { tier });+ engineStore.status = s;+ return s;+ } finally {+ engineStore.loadingTier = null;+ engineStore.sig.emit();+ }+}++export async function unloadModel(): Promise<void> {+ await invoke("model_unload");+ engineStore.status = await invoke<EngStatus>("engine_status");+ engineStore.sig.emit();+}++export const deleteModel = (tier: string): Promise<{ deleted: string }> => invoke("model_delete", { tier });+export const startDownload = (tier: string, source: string | null): Promise<unknown> => invoke("download_start", { tier, source });+export const cancelDownload = (tier: string): Promise<void> => invoke("download_cancel", { tier });+export const doctorRun = (): Promise<{ overall: string; checks: DoctorCheck[] }> => invoke("doctor_run");+export type DoctorCheck = { id: string; verdict: string; detail: string; code?: string | null; next?: string | null };++export function installedTiers(): string[] {+ return Object.keys(shellStore.installed);+}diff --git a/windows/app/src/chat/buckets.ts b/windows/app/src/chat/buckets.tsnew file mode 100644index 0000000..e0740ee--- /dev/null+++ b/windows/app/src/chat/buckets.ts@@ -0,0 +1,31 @@+// Chat-history time bucketing: pure function, unit-testable; Today / Yesterday / Previous 7 days / Earlier.+export interface Bucket<T> {+ key: "today" | "yesterday" | "week" | "earlier";+ items: T[];+}++const DAY_MS = 24 * 60 * 60 * 1000;++function localDayStart(ms: number): number {+ const d = new Date(ms);+ d.setHours(0, 0, 0, 0);+ return d.getTime();+}++export function bucketThreads<T extends { updatedAt: number }>(+ threads: T[],+ nowMs: number,+): Bucket<T>[] {+ const today = localDayStart(nowMs);+ const buckets: Record<Bucket<T>["key"], T[]> = { today: [], yesterday: [], week: [], earlier: [] };+ for (const th of threads) {+ const day = localDayStart(th.updatedAt);+ if (day >= today) buckets.today.push(th);+ else if (day >= today - DAY_MS) buckets.yesterday.push(th);+ else if (day >= today - 6 * DAY_MS) buckets.week.push(th);+ else buckets.earlier.push(th);+ }+ return (["today", "yesterday", "week", "earlier"] as const)+ .filter((k) => buckets[k].length > 0)+ .map((k) => ({ key: k, items: buckets[k] }));+}diff --git a/windows/app/src/chat/modelStatus.ts b/windows/app/src/chat/modelStatus.tsnew file mode 100644index 0000000..fab2dea--- /dev/null+++ b/windows/app/src/chat/modelStatus.ts@@ -0,0 +1,23 @@+// chat/modelStatus.ts — status-light derivation. Inputs are shell snapshots only:+// the installed list + engineStore.status + loadingTier. No timers, no guessing:+// the light reflects facts alone.+import type { EngStatus } from "../api/client";++export type ModelLight = "resident" | "loading" | "installed" | "absent";++export function deriveLight(+ status: EngStatus | null,+ loadingTier: string | null,+ installed: string[],+ tier: string,+): ModelLight {+ if (!installed.includes(tier)) return "absent";+ if (status?.running && status.tier === tier) return "resident";+ if (loadingTier === tier) return "loading";+ return "installed";+}++/** Picker candidates = installed tiers (catalog/download browsing belongs to the models page). */+export function candidateModels(installed: string[]): string[] {+ return installed;+}diff --git a/windows/app/src/chat/scroll.ts b/windows/app/src/chat/scroll.tsnew file mode 100644index 0000000..396e498--- /dev/null+++ b/windows/app/src/chat/scroll.ts@@ -0,0 +1,13 @@+// Follow-bottom predicate: pin to the bottom on streaming increments only while the user+// is near the bottom (prevents the "scroll lock" bug that drags a scrolled-up reader back).+export const STICK_BOTTOM_THRESHOLD = 40;++export interface ScrollGeometry {+ scrollHeight: number;+ scrollTop: number;+ clientHeight: number;+}++export function isAtBottom(el: ScrollGeometry, threshold = STICK_BOTTOM_THRESHOLD): boolean {+ return el.scrollHeight - el.scrollTop - el.clientHeight < threshold;+}diff --git a/windows/app/src/chat/useThreadChat.ts b/windows/app/src/chat/useThreadChat.tsnew file mode 100644index 0000000..a28e422--- /dev/null+++ b/windows/app/src/chat/useThreadChat.ts@@ -0,0 +1,192 @@+// chat/useThreadChat.ts — per-thread generation hook. No AI SDK dependency: talks+// straight to the loopback llama-server OpenAI SSE endpoint. The final chunk's+// usage+timings are recorded as measured (missing keys render nothing; zero estimates).+import { useCallback, useRef, useState } from "react";+import { engineStore, reqLog } from "../api/client";+import { threadStore, type MsgUsage, type ThreadMsg, type ThreadRow } from "../state/threads";+import { currentTemperature } from "../lib/generation";+import { storedSystemPrompt } from "../lib/systemPrompt";+import { codeOf } from "../lib/t";++export type ThreadChatApi = {+ messages: ThreadMsg[];+ busy: boolean;+ send: (text: string) => Promise<void>;+ stop: () => void;+ regenerate: () => Promise<void>;+ editResend: (msgId: string, text: string) => Promise<void>;+ wireJson: () => { role: string; content: string }[]; // the exact wire form used for token metering+};++export function toWire(history: ThreadMsg[]): { role: string; content: string }[] {+ const out: { role: string; content: string }[] = [];+ const sp = storedSystemPrompt();+ if (sp) out.push({ role: "system", content: sp });+ for (const m of history) {+ if (m.role === "user") out.push({ role: "user", content: m.content });+ else if (m.content.trim()) out.push({ role: "assistant", content: m.content });+ }+ return out;+}++const uid = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;++export function useThreadChat(thread: ThreadRow, model: string | null): ThreadChatApi {+ const [busy, setBusy] = useState(false);+ const abortRef = useRef<AbortController | null>(null);++ const patchLast = useCallback(+ (patch: Partial<ThreadMsg>) => {+ threadStore.patchMessages(thread.id, (ms) =>+ ms.length ? ms.map((m, i) => (i === ms.length - 1 ? { ...m, ...patch } : m)) : ms,+ );+ },+ [thread.id],+ );++ const run = useCallback(+ async (history: ThreadMsg[]) => {+ const base = engineStore.status?.running ? engineStore.status.base_url : undefined;+ if (!base) {+ patchLast({ meta: { status: "error", code: "E-NOT-LOADED" } });+ return;+ }+ setBusy(true);+ const t0 = Date.now();+ const ac = new AbortController();+ abortRef.current = ac;+ let acc = "";+ let reason = "";+ let usage: MsgUsage | undefined;+ let perf: { decode_tps?: number; prefill_tps?: number; prompt_ms?: number } | undefined;+ try {+ const resp = await fetch(`${base}/v1/chat/completions`, {+ method: "POST",+ signal: ac.signal,+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: model ?? "edge0",+ messages: toWire(history),+ max_tokens: 1024,+ temperature: currentTemperature(),+ stream: true,+ stream_options: { include_usage: true }, // final-chunk usage comes straight from the engine+ // enable_thinking:false => answer text streams directly (server-side normalization point)+ chat_template_kwargs: { enable_thinking: false },+ }),+ });+ if (!resp.ok || !resp.body) throw new Error(`E-ENGINE HTTP ${resp.status}`);+ const reader = resp.body.getReader();+ const dec = new TextDecoder();+ let buf = "";+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ const lines = buf.split("\n");+ buf = lines.pop() ?? "";+ for (const line of lines) {+ const tr = line.trim();+ if (!tr.startsWith("data:")) continue;+ const payload = tr.slice(5).trim();+ if (payload === "[DONE]") continue;+ try {+ const d = JSON.parse(payload);+ const delta = d.choices?.[0]?.delta ?? {};+ acc += delta.content ?? "";+ reason += delta.reasoning_content ?? "";+ if (d.usage) {+ usage = {+ prompt_tokens: d.usage.prompt_tokens ?? 0,+ completion_tokens: d.usage.completion_tokens ?? 0,+ total_tokens: d.usage.total_tokens ?? 0,+ };+ }+ if (d.timings && typeof d.timings === "object") {+ const nums: Record<string, number> = {};+ for (const [k, v] of Object.entries(d.timings)) if (typeof v === "number") nums[k] = v;+ perf = {+ decode_tps: nums.predicted_per_second,+ prefill_tps: nums.prompt_per_second,+ prompt_ms: nums.prompt_ms,+ };+ }+ patchLast({ content: acc, reasoning: reason, streaming: true });+ } catch {+ /* tolerate a split (partial) JSON line; next chunk completes it */+ }+ }+ }+ patchLast({ content: acc, reasoning: reason, streaming: false, meta: { status: "done", usage, perf } });+ reqLog.add({ ts: Date.now(), model: model ?? "edge0", status: "done", latencyMs: Date.now() - t0, tokens: usage?.completion_tokens ?? null, code: null });+ } catch (e) {+ const aborted = (e as Error).name === "AbortError";+ patchLast({+ content: acc, reasoning: reason, streaming: false,+ meta: aborted+ ? { status: "aborted", usage, perf }+ : { status: "error", code: codeOf(String(e)) ?? "E-ENGINE" },+ });+ reqLog.add({+ ts: Date.now(), model: model ?? "edge0",+ status: aborted ? "cancelled" : "error",+ latencyMs: Date.now() - t0, tokens: null, code: aborted ? null : codeOf(String(e)),+ });+ } finally {+ setBusy(false);+ abortRef.current = null;+ }+ },+ [model, patchLast, thread.id],+ );++ const send = useCallback(+ async (text: string) => {+ const history: ThreadMsg[] = [+ ...threadStore.messages(thread.id),+ { id: uid(), role: "user", content: text, created_at: Date.now() },+ ];+ threadStore.patchMessages(thread.id, (ms) => [+ ...ms,+ history[history.length - 1],+ { id: uid(), role: "assistant", content: "", created_at: Date.now(), streaming: true },+ ]);+ await run(history);+ },+ [run, thread.id],+ );++ const regenerate = useCallback(async () => {+ const msgs = threadStore.messages(thread.id);+ const lastA = msgs.map((m) => m.role).lastIndexOf("assistant");+ if (lastA < 0) return;+ const history = msgs.slice(0, lastA); // drop the previous answer+ threadStore.patchMessages(thread.id, () => [+ ...history,+ { id: uid(), role: "assistant", content: "", created_at: Date.now(), streaming: true },+ ]);+ await run(history);+ }, [run, thread.id]);++ const editResend = useCallback(+ async (msgId: string, text: string) => {+ const msgs = threadStore.messages(thread.id);+ const idx = msgs.findIndex((m) => m.id === msgId);+ if (idx < 0) return;+ const edited: ThreadMsg = { id: uid(), role: "user", content: text, created_at: Date.now() };+ const history = [...msgs.slice(0, idx), edited];+ threadStore.patchMessages(thread.id, () => [+ ...history,+ { id: uid(), role: "assistant", content: "", created_at: Date.now(), streaming: true },+ ]);+ await run(history);+ },+ [run, thread.id],+ );++ const stop = useCallback(() => abortRef.current?.abort(), []);++ const wireJson = useCallback(() => toWire(threadStore.messages(thread.id)), [thread.id]);++ return { messages: threadStore.messages(thread.id), busy, send, stop, regenerate, editResend, wireJson };+}diff --git a/windows/app/src/components/AppShell.tsx b/windows/app/src/components/AppShell.tsxnew file mode 100644index 0000000..0e1e34b--- /dev/null+++ b/windows/app/src/components/AppShell.tsx@@ -0,0 +1,180 @@+// AppShell — sidebar + full-width main area (Atomic-Chat style three-segment layout).+// Hash routing; state comes from the single-pulse stores in api/client.+// autoLoad intent chain: download ready -> issue one load -> on success create a thread and enter chat.+import { BookOpen, Menu, Plus, Server, Settings, Sparkles, X } from "lucide-react";+import { useEffect, useState, useSyncExternalStore, type ReactNode } from "react";++import {+ downloadStore,+ engineStore,+ loadModel,+ refreshInstalled,+ shellStore,+} from "../api/client";+import { autoLoad } from "../lib/autoLoad";+import { t } from "../lib/t";+import { bucketThreads } from "../chat/buckets";+import { threadStore } from "../state/threads";+import { SidebarThreadItem } from "./SidebarThreadItem";++const go = (path: string) => {+ window.location.hash = `#${path}`;+};++export function AppShell({ view, children }: { view: string; children: ReactNode }) {+ const [sidebarOpen, setSidebarOpen] = useState(false);+ const threadsVer = useSyncExternalStore(threadStore.subscribe, () => threadStore.version());+ const engVer = useSyncExternalStore(engineStore.sig.sub, engineStore.sig.version);+ const dlVer = useSyncExternalStore(downloadStore.sig.sub, downloadStore.sig.version);+ const shellVer = useSyncExternalStore(shellStore.sig.sub, shellStore.sig.version);+ void threadsVer; void engVer; void dlVer; void shellVer; // pulse-driven rerenders; data read straight from stores++ // autoLoad one-shot intent chain: ready -> explicitly issue one load -> on success create thread and enter chat.+ useEffect(() => {+ const check = () => {+ const cur = autoLoad.current;+ if (!cur) return;+ if (cur.phase === "download") {+ const tv = downloadStore.tasks[cur.tier];+ if (tv && (tv.phase === "error" || tv.phase === "cancelled")) autoLoad.cancel();+ else if (tv?.phase === "ready") {+ const tier = autoLoad.claimCompleted(cur.tier);+ if (tier) {+ void (async () => {+ await refreshInstalled();+ try {+ await loadModel(tier);+ } catch {+ autoLoad.cancel();+ }+ })();+ }+ }+ } else {+ const st = engineStore.status;+ if (st?.running && st.tier === cur.tier && autoLoad.consume(cur.tier)) {+ const row = threadStore.create(t("chat.newThread"), cur.tier);+ threadStore.setActive(row.id);+ go("/"); // entering a session means returning to the chat page+ } else if (!st?.running && engineStore.loadingTier === null) {+ autoLoad.cancel(); // load failed (engine not running and not loading)+ }+ }+ };+ const off1 = downloadStore.sig.sub(check);+ const off2 = engineStore.sig.sub(check);+ const off3 = autoLoad.subscribe(check);+ check();+ return () => {+ off1();+ off2();+ off3();+ };+ }, []);++ const threads = threadStore.threads();+ const activeId = threadStore.activeId;+ const buckets = bucketThreads(threads, Date.now());+ const st = engineStore.status;+ const running = !!st?.running;+ const serviceLine = running+ ? `:${st?.port} · ${t("sidebar.resident")} ${st?.tier}`+ : st+ ? t("sidebar.idle")+ : t("sidebar.noService");++ function newChat() {+ const row = threadStore.create(t("chat.newThread"), running ? (st?.tier ?? null) : null);+ threadStore.setActive(row.id);+ go("/"); // "New chat" clicked from a non-chat page must land back on the chat page+ setSidebarOpen(false);+ }++ const navCls = (active: boolean) =>+ "flex items-center gap-2 rounded-lg px-3 py-2 text-sm " ++ (active ? "bg-surface2 text-fg" : "text-muted hover:bg-surface2 hover:text-fg");++ return (+ <div className="e0-app-shell text-fg">+ {sidebarOpen && (+ <button type="button" aria-label={t("nav.closeSidebar")} className="e0-sidebar-backdrop" onClick={() => setSidebarOpen(false)} />+ )}+ <aside data-testid="app-sidebar" className={"e0-sidebar " + (sidebarOpen ? "e0-sidebar-open" : "")} data-open={sidebarOpen ? "true" : "false"}>+ <div className="flex items-center justify-between px-4 pb-2 pt-4">+ <div className="flex items-center gap-2">+ <span className="grid size-8 place-items-center rounded-xl bg-fg text-surface shadow-sm">+ <Sparkles size={16} aria-hidden />+ </span>+ <div>+ <span className="block text-sm font-bold tracking-tight">{t("app.name")}</span>+ <span className="block text-[10px] font-medium uppercase tracking-[0.16em] text-muted">{t("app.localLabel")}</span>+ </div>+ </div>+ <button type="button" aria-label={t("nav.closeSidebar")} className="e0-icon-btn md:hidden" onClick={() => setSidebarOpen(false)}>+ <X size={16} aria-hidden />+ </button>+ </div>+ <div className="px-3 pb-3">+ <button type="button" onClick={newChat} className="e0-btn e0-btn-primary w-full">+ <Plus size={16} aria-hidden />+ {t("sidebar.newChat")}+ </button>+ </div>+ <nav aria-label={t("sidebar.navigation")} className="space-y-1 px-2 pb-2">+ <a href="#/models" aria-label={t("nav.models")} data-testid="nav-models" className={navCls(view === "/models")} onClick={() => setSidebarOpen(false)}>+ <BookOpen size={16} aria-hidden />+ {t("nav.models")}+ </a>+ <a href="#/service" aria-label={t("nav.service")} data-testid="nav-service" className={navCls(view === "/service")} onClick={() => setSidebarOpen(false)}>+ <Server size={16} aria-hidden />+ {t("nav.service")}+ </a>+ </nav>+ <nav aria-label={t("sidebar.history")} className="min-h-0 flex-1 overflow-y-auto px-2">+ <h2 className="px-3 pb-2 pt-2 text-[10px] font-bold uppercase tracking-[0.16em] text-muted">{t("sidebar.history")}</h2>+ {buckets.map((b) => (+ <section key={b.key} className="mb-2">+ <h2 className="px-2 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wide text-muted">+ {t(`sidebar.bucket.${b.key}`)}+ </h2>+ <ul className="space-y-0.5">+ {b.items.map((th) => (+ <SidebarThreadItem+ key={th.id}+ thread={th}+ active={th.id === activeId}+ onSelect={() => {+ threadStore.setActive(th.id);+ setSidebarOpen(false);+ go("/");+ }}+ onRename={(title) => threadStore.rename(th.id, title)}+ onDelete={() => threadStore.remove(th.id)}+ />+ ))}+ </ul>+ </section>+ ))}+ {threads.length === 0 && <p className="px-3 py-3 text-xs leading-relaxed text-muted">{t("chat.noThreads")}</p>}+ </nav>+ <div className="e0-divider mx-3" />+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-muted">+ <span aria-label={serviceLine} className={"inline-block size-2 shrink-0 rounded-full " + (running ? "bg-ok" : st ? "bg-warn" : "bg-muted")} />+ <span className="min-w-0 flex-1 truncate" data-testid="service-summary">{serviceLine}</span>+ <a href="#/settings" aria-label={t("nav.settings")} className="e0-icon-btn ml-auto" onClick={() => setSidebarOpen(false)}>+ <Settings size={16} aria-hidden />+ </a>+ </div>+ </aside>+ <main data-testid="app-main" className="e0-main-frame">+ <div className="e0-mobile-toggle absolute left-4 top-4 z-10">+ <button type="button" aria-label={t("nav.openSidebar")} title={t("nav.openSidebar")}+ className="e0-icon-btn border border-line bg-surface shadow-sm" onClick={() => setSidebarOpen(true)}>+ <Menu size={17} aria-hidden />+ </button>+ </div>+ <div className="h-full min-h-0 overflow-y-auto">{children}</div>+ </main>+ </div>+ );+}diff --git a/windows/app/src/components/ShellControls.tsx b/windows/app/src/components/ShellControls.tsxnew file mode 100644index 0000000..64b8213--- /dev/null+++ b/windows/app/src/components/ShellControls.tsx@@ -0,0 +1,51 @@+// ShellControls — theme + font-size control groups (no radix: native data-state keeps the same shape).+import { useEffect, useState } from "react";+import { t } from "../lib/t";+import {+ applyFont,+ applyTheme,+ storedFont,+ storedTheme,+ type FontScale,+ type Theme,+} from "../lib/theme";++export function ShellControls() {+ const [theme, setTheme] = useState<Theme>(storedTheme());+ const [font, setFont] = useState<FontScale>(storedFont());++ useEffect(() => {+ applyTheme(theme);+ }, [theme]);+ useEffect(() => {+ applyFont(font);+ }, [font]);+ // When following the system preference, re-resolve on system changes.+ useEffect(() => {+ const mq = window.matchMedia("(prefers-color-scheme: dark)");+ const onChange = () => theme === "system" && applyTheme("system");+ mq.addEventListener("change", onChange);+ return () => mq.removeEventListener("change", onChange);+ }, [theme]);++ return (+ <div className="flex flex-wrap items-center gap-3 border-b border-line pb-3" data-testid="shell-controls">+ <div className="e0-toggle-group" role="group" aria-label={t("theme.system")}>+ {(["light", "dark", "system"] as const).map((v) => (+ <button key={v} type="button" data-state={v === theme ? "on" : "off"} className="e0-toggle"+ aria-pressed={v === theme} onClick={() => setTheme(v)}>+ {t(`theme.${v}`)}+ </button>+ ))}+ </div>+ <div className="e0-toggle-group" role="group" aria-label={t("font.md")}>+ {(["sm", "md", "lg"] as const).map((v) => (+ <button key={v} type="button" data-state={v === font ? "on" : "off"} className="e0-toggle"+ aria-pressed={v === font} onClick={() => setFont(v)}>+ {t(`font.${v}`)}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/windows/app/src/components/SidebarThreadItem.tsx b/windows/app/src/components/SidebarThreadItem.tsxnew file mode 100644index 0000000..4a82b3a--- /dev/null+++ b/windows/app/src/components/SidebarThreadItem.tsx@@ -0,0 +1,83 @@+// SidebarThreadItem — rename/delete actions revealed on hover/focus.+import { Pencil, Trash2 } from "lucide-react";+import { useState } from "react";+import { t } from "../lib/t";++export function SidebarThreadItem({+ thread,+ active,+ onSelect,+ onRename,+ onDelete,+}: {+ thread: { id: string; data: { title: string } };+ active: boolean;+ onSelect: () => void;+ onRename: (title: string) => void;+ onDelete: () => void;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState("");++ if (editing) {+ return (+ <li>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ onRename(draft.trim() || thread.data.title);+ setEditing(false);+ }}+ >+ <input+ autoFocus+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={() => setEditing(false)}+ className="w-full rounded-lg border border-accent bg-surface px-3 py-2 text-sm outline-none"+ />+ </form>+ </li>+ );+ }++ return (+ <li+ className="group flex items-center rounded-lg transition-colors hover:bg-surface2/80"+ data-active={active || undefined}+ >+ <button+ type="button"+ onClick={onSelect}+ className={+ "min-w-0 flex-1 truncate rounded-md px-2.5 py-1.5 text-left text-sm " ++ (active ? "bg-surface2 font-semibold text-fg shadow-sm" : "text-fg/85")+ }+ title={thread.data.title}+ >+ {thread.data.title}+ </button>+ <span className="mr-1 hidden shrink-0 items-center gap-0.5 group-hover:flex group-focus-within:flex">+ <button+ type="button"+ aria-label={t("chat.rename")}+ onClick={() => {+ setEditing(true);+ setDraft(thread.data.title);+ }}+ className="e0-icon-btn !size-7 !rounded-md"+ >+ <Pencil size={13} />+ </button>+ <button+ type="button"+ aria-label={t("chat.deleteThread")}+ onClick={onDelete}+ className="e0-icon-btn !size-7 !rounded-md hover:!text-err"+ >+ <Trash2 size={13} />+ </button>+ </span>+ </li>+ );+}diff --git a/windows/app/src/components/chat/ComposerBar.tsx b/windows/app/src/components/chat/ComposerBar.tsxnew file mode 100644index 0000000..455ba15--- /dev/null+++ b/windows/app/src/components/chat/ComposerBar.tsx@@ -0,0 +1,81 @@+// ComposerBar — floating rounded composer: Enter sends / Shift+Enter newlines,+// the button becomes Stop while generating, ModelPill + GenPill on the left.+import { ArrowUp, Square } from "lucide-react";+import { useState } from "react";++import type { ThreadChatApi } from "../../chat/useThreadChat";+import { t } from "../../lib/t";+import { GenPill } from "./GenPill";+import { ModelPill } from "./ModelPill";++export function ComposerBar({+ chat,+ model,+ onModelChange,+}: {+ chat: ThreadChatApi;+ model: string;+ onModelChange: (id: string) => void;+}) {+ const [text, setText] = useState("");+ const [sending, setSending] = useState(false);++ async function submit() {+ const trimmed = text.trim();+ if (!trimmed || sending) return;+ setSending(true);+ setText("");+ try {+ await chat.send(trimmed);+ } finally {+ setSending(false);+ }+ }++ return (+ <div className="e0-composer" data-testid="composer">+ <div className="e0-composer-shell">+ <textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void submit();+ }+ }}+ rows={2}+ placeholder={t("chat.placeholder")}+ className="e0-composer-textarea w-full resize-none bg-transparent text-sm outline-none placeholder:text-muted"+ />+ <div className="e0-composer-toolbar">+ <ModelPill model={model} onModelChange={onModelChange} wireJson={chat.wireJson} />+ <GenPill />+ <span className="min-w-0 flex-1 truncate text-xs text-muted">{!model ? t("chat.pickModelFirst") : ""}</span>+ {chat.busy ? (+ <button+ type="button"+ aria-label={t("chat.stop")}+ title={t("chat.stop")}+ onClick={chat.stop}+ className="e0-send-btn bg-fg text-surface"+ >+ <Square size={14} fill="currentColor" />+ </button>+ ) : (+ <button+ type="button"+ aria-label={t("chat.send")}+ title={t("chat.send")}+ onClick={() => void submit()}+ disabled={!model || !text.trim()}+ className="e0-send-btn disabled:opacity-40"+ >+ <ArrowUp size={16} />+ </button>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/windows/app/src/components/chat/GenPill.tsx b/windows/app/src/components/chat/GenPill.tsxnew file mode 100644index 0000000..652f015--- /dev/null+++ b/windows/app/src/components/chat/GenPill.tsx@@ -0,0 +1,35 @@+// GenPill — three generation styles, switched in place on the composer toolbar; the next message reads it live.+import { useState } from "react";+import { t } from "../../lib/t";+import { GEN_TEMPERATURE, setGen, storedGen, type GenPreset } from "../../lib/generation";++const PRESETS: GenPreset[] = ["precise", "balanced", "creative"];++export function GenPill() {+ const [gen, setGenState] = useState<GenPreset>(() => storedGen());+ return (+ <div+ className="flex shrink-0 items-center gap-0.5 rounded-full border border-line bg-surface2 px-1 py-0.5"+ data-testid="gen-pill"+ title={t("gen.hint")}+ >+ {PRESETS.map((p) => (+ <button+ key={p}+ type="button"+ data-testid={`gen-${p}`}+ data-state={gen === p ? "on" : "off"}+ aria-pressed={gen === p}+ onClick={() => {+ setGen(p);+ setGenState(p);+ }}+ className="rounded-full px-2 py-0.5 text-[11px] text-muted transition-colors hover:text-fg data-[state=on]:bg-accent data-[state=on]:text-accentink"+ title={`${t(`gen.${p}`)} · ${GEN_TEMPERATURE[p]}`}+ >+ {t(`gen.${p}`)}+ </button>+ ))}+ </div>+ );+}diff --git a/windows/app/src/components/chat/MessageItem.tsx b/windows/app/src/components/chat/MessageItem.tsxnew file mode 100644index 0000000..4658eba--- /dev/null+++ b/windows/app/src/components/chat/MessageItem.tsx@@ -0,0 +1,193 @@+// MessageItem — one rendered message: user bubble (right, editable + resend), assistant+// full-width with a drawn avatar, action bar on hover, collapsible reasoning, and a+// measured usage/perf line that renders nothing when keys are missing.+import { Streamdown } from "streamdown";+import { Brain, Check, Copy, Pencil, RotateCcw } from "lucide-react";+import { useState } from "react";++import type { MsgPerf, ThreadMsg } from "../../state/threads";+import { codeOf, errKey, t } from "../../lib/t";++export function MessageItem({+ message,+ streaming,+ isLastAssistant,+ busy,+ onRegenerate,+ onEditResend,+}: {+ message: ThreadMsg;+ streaming: boolean;+ isLastAssistant: boolean;+ busy: boolean;+ onRegenerate: () => void;+ onEditResend: (newText: string) => void;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState("");+ const [copied, setCopied] = useState<"text" | "reasoning" | null>(null);+ const isUser = message.role === "user";+ const text = message.content;+ const reasoning = message.reasoning ?? "";+ const meta = message.meta ?? {};+ const live = streaming && isLastAssistant && !isUser;+ const isAborted = meta.status === "aborted";+ const isError = meta.status === "error";++ async function copy(value: string, which: "text" | "reasoning") {+ try {+ await navigator.clipboard.writeText(value);+ setCopied(which);+ setTimeout(() => setCopied(null), 1200);+ } catch {+ /* clipboard denied in webview: fail silently, never block the UI */+ }+ }++ if (isUser) {+ return (+ <article data-msg-role="user" className="group/msg flex flex-col items-end py-2.5">+ {editing ? (+ <form+ onSubmit={(e) => {+ e.preventDefault();+ setEditing(false);+ if (draft.trim()) onEditResend(draft);+ }}+ className="w-full max-w-[88%]"+ >+ <textarea+ autoFocus+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ rows={3}+ className="w-full resize-y rounded-2xl border border-accent/50 bg-surface2 p-3 text-sm outline-none"+ />+ <div className="flex justify-end gap-2 pt-1.5">+ <button type="submit" className="e0-btn e0-btn-primary">{t("chat.resend")}</button>+ <button type="button" onClick={() => setEditing(false)} className="e0-btn e0-btn-ghost">{t("common.cancel")}</button>+ </div>+ </form>+ ) : (+ <>+ <div className="max-w-[88%] whitespace-pre-wrap break-words rounded-2xl rounded-br-md bg-accent px-4 py-3 text-sm leading-relaxed text-accentink shadow-sm">+ {text}+ </div>+ <div className="mt-0.5 flex h-6 gap-1 opacity-0 transition-opacity group-hover/msg:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100">+ {text && (+ <IconAction label={t("chat.copy")} onClick={() => void copy(text, "text")}>+ {copied === "text" ? <Check size={13} /> : <Copy size={13} />}+ </IconAction>+ )}+ {!busy && (+ <IconAction label={t("chat.editResend")} onClick={() => { setEditing(true); setDraft(text); }}>+ <Pencil size={13} />+ </IconAction>+ )}+ </div>+ </>+ )}+ </article>+ );+ }++ return (+ <article data-msg-role="assistant" className="group/msg flex gap-3 border-t border-line/40 py-5 first:border-t-0">+ <Avatar />+ <div className="min-w-0 flex-1">+ {reasoning && (+ <details className="mb-3 max-w-full rounded-xl border border-line bg-surface2/70 px-3 py-2" data-testid="reasoning-block">+ <summary className="flex cursor-pointer select-none items-center gap-1.5 text-xs font-medium text-muted">+ <Brain size={13} aria-hidden />+ {t("chat.reasoning")}+ </summary>+ <div className="mt-1.5 grid gap-1.5">+ <div className="whitespace-pre-wrap text-xs leading-relaxed text-muted">{reasoning}</div>+ <button type="button" onClick={() => void copy(reasoning, "reasoning")} className="flex w-fit items-center gap-1 text-xs text-muted hover:text-fg">+ {copied === "reasoning" ? <Check size={12} /> : <Copy size={12} />}+ {t("chat.copyReasoning")}+ </button>+ </div>+ </details>+ )}++ <div+ className="e0-prose prose prose-sm max-w-none break-words text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"+ data-testid="message-body"+ >+ <Streamdown mode={live ? "streaming" : "static"}>{text}</Streamdown>+ {live && !text && <span className="inline-block h-4 w-1 animate-pulse bg-fg align-middle" />}+ </div>++ {isError && (+ <p className="mt-1.5 flex items-center gap-2 rounded-lg bg-err/10 px-2.5 py-1.5 text-xs text-err" role="alert">+ <span>{t(errKey(meta.code))}</span>+ {meta.code && <code className="rounded bg-err/10 px-1">{meta.code}</code>}+ </p>+ )}+ {isAborted && <p className="mt-1 text-xs text-warn">{t("chat.aborted")}</p>}++ {/* per-turn performance metrics: shown as soon as complete, stays; renders nothing when all fields are absent (no-fake-values rule) */}+ {!live && <PerfLine perf={meta.perf} />}++ <div className="mt-0.5 flex h-6 items-center gap-1 opacity-0 transition-opacity group-hover/msg:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100">+ {text && (+ <IconAction label={t("chat.copy")} onClick={() => void copy(text, "text")}>+ {copied === "text" ? <Check size={13} /> : <Copy size={13} />}+ </IconAction>+ )}+ {isLastAssistant && !busy && (+ <IconAction label={t("chat.regenerate")} onClick={onRegenerate}>+ <RotateCcw size={13} />+ </IconAction>+ )}+ {meta.usage && (+ <span className="ml-auto text-[11px] tabular-nums text-muted" data-testid="usage-line">+ {t("chat.usage", {+ p: meta.usage.prompt_tokens,+ c: meta.usage.completion_tokens,+ t: meta.usage.total_tokens,+ })}+ </span>+ )}+ </div>+ </div>+ </article>+ );+}++function IconAction({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) {+ return (+ <button type="button" aria-label={label} title={label} onClick={onClick} className="e0-icon-btn !size-7 !rounded-md">+ {children}+ </button>+ );+}++/** Per-turn performance line (timings measured in the final stream chunk): renders nothing when no value is present. */+function PerfLine({ perf }: { perf: MsgPerf | undefined }) {+ const p = (perf ?? {}) as Record<string, number | undefined>;+ const parts: string[] = [];+ if (typeof p.decode_tps === "number") parts.push(t("chat.perf.decode", { v: p.decode_tps.toFixed(1) }));+ if (typeof p.prefill_tps === "number") parts.push(t("chat.perf.prefill", { v: p.prefill_tps.toFixed(1) }));+ if (typeof p.prompt_ms === "number") parts.push(t("chat.perf.prompt", { ms: Math.round(p.prompt_ms) }));+ if (parts.length === 0) return null;+ return (+ <p className="mt-1 flex flex-wrap gap-x-2 text-[11px] tabular-nums text-muted" data-testid="perf-line">+ {parts.map((s, i) => (+ <span key={i}>{s}</span>+ ))}+ </p>+ );+}++/** Drawn monochrome avatar (brand mark). */+function Avatar() {+ return (+ <span aria-hidden className="mt-0.5 grid h-7 w-7 shrink-0 place-content-center rounded-full border border-line bg-surface2 text-fg">+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none">+ <path d="M7 1l1.6 4.4L13 7l-4.4 1.6L7 13 5.4 8.6 1 7l4.4-1.6L7 1z" fill="currentColor" />+ </svg>+ </span>+ );+}diff --git a/windows/app/src/components/chat/MessageList.tsx b/windows/app/src/components/chat/MessageList.tsxnew file mode 100644index 0000000..b12cdad--- /dev/null+++ b/windows/app/src/components/chat/MessageList.tsx@@ -0,0 +1,28 @@+// MessageList — full-width list + "waiting for first chunk" placeholder (all threads live locally; no pagination).+import type { ThreadChatApi } from "../../chat/useThreadChat";+import { t } from "../../lib/t";+import { MessageItem } from "./MessageItem";++export function MessageList({ chat }: { chat: ThreadChatApi }) {+ const lastAssistantIdx = chat.messages.map((m) => m.role).lastIndexOf("assistant");+ return (+ <div data-testid="message-list">+ {chat.messages.map((m, i) => (+ <MessageItem+ key={m.id ?? i}+ message={m}+ streaming={chat.busy}+ isLastAssistant={i === lastAssistantIdx}+ busy={chat.busy}+ onRegenerate={() => void chat.regenerate()}+ onEditResend={(next) => void chat.editResend(m.id, next)}+ />+ ))}+ {chat.busy && chat.messages[chat.messages.length - 1]?.role !== "assistant" && (+ <p className="px-3 text-xs text-muted" data-testid="waiting-first-chunk">+ {t("chat.waitingFirstChunk")}+ </p>+ )}+ </div>+ );+}diff --git a/windows/app/src/components/chat/ModelPill.tsx b/windows/app/src/components/chat/ModelPill.tsxnew file mode 100644index 0000000..e9b8540--- /dev/null+++ b/windows/app/src/components/chat/ModelPill.tsx@@ -0,0 +1,166 @@+// ModelPill — model pill at the composer's left end. Data comes from the shell:+// candidates = installed list, light = pure modelStatus function, token metering =+// measured via /apply-template -> /tokenize (unavailable = unknown, never estimated).+import { ChevronDown, Loader2 } from "lucide-react";+import { useEffect, useRef, useState, useSyncExternalStore } from "react";++import { engineStore, installedTiers, loadModel, shellStore } from "../../api/client";+import { threadStore } from "../../state/threads";+import { candidateModels, deriveLight, type ModelLight } from "../../chat/modelStatus";+import { codeOf, errKey, t } from "../../lib/t";++function LightDot({ light }: { light: ModelLight }) {+ const cls =+ light === "resident" ? "bg-ok" : light === "loading" ? "bg-warn animate-pulse" : light === "installed" ? "bg-muted" : "bg-line";+ return <span data-testid="model-light" data-light={light} className={"inline-block h-2 w-2 shrink-0 rounded-full " + cls} aria-hidden />;+}++export function ModelPill({+ model,+ onModelChange,+ wireJson,+}: {+ model: string;+ onModelChange: (id: string) => void;+ wireJson: () => { role: string; content: string }[];+}) {+ const [, force] = useState(0);+ const [open, setOpen] = useState(false);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [contextTokens, setContextTokens] = useState<number | null>(null);+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const wireRef = useRef(wireJson);+ wireRef.current = wireJson;+ const rootRef = useRef<HTMLDivElement>(null);++ useSyncExternalStore(engineStore.sig.sub, engineStore.sig.version);+ useSyncExternalStore(shellStore.sig.sub, shellStore.sig.version);+ useEffect(() => engineStore.sig.sub(() => force((n) => n + 1)), []);++ useEffect(() => {+ if (!open) return;+ const onDoc = (e: MouseEvent) => {+ if (!rootRef.current?.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener("mousedown", onDoc);+ return () => document.removeEventListener("mousedown", onDoc);+ }, [open]);++ const st = engineStore.status;+ const installed = installedTiers();+ const candidates = candidateModels(installed);+ const light = model ? deriveLight(st, engineStore.loadingTier, installed, model) : "absent";++ // metering: on message/model/port change, debounce 400 ms then measure via the two-hop call.+ const msgVer = useSyncExternalStore(+ threadStore.subscribe,+ () => threadStore.version(),+ );+ useEffect(() => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ debounceRef.current = setTimeout(() => void measure(), 400);+ return () => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [msgVer, model, st?.port]);++ async function measure() {+ const base = engineStore.status?.running ? engineStore.status.base_url : undefined;+ if (!base || !model) {+ setContextTokens(null);+ return;+ }+ try {+ const r1 = await fetch(`${base}/apply-template`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ messages: wireRef.current(), add_generation_prompt: true }),+ });+ if (!r1.ok) throw new Error(`HTTP ${r1.status}`);+ const j1 = (await r1.json()) as { prompt?: string };+ if (typeof j1.prompt !== "string") throw new Error("no prompt");+ const r2 = await fetch(`${base}/tokenize`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ content: j1.prompt }),+ });+ if (!r2.ok) throw new Error(`HTTP ${r2.status}`);+ const j2 = (await r2.json()) as { tokens?: unknown[] };+ setContextTokens(Array.isArray(j2.tokens) ? j2.tokens.length : null);+ } catch {+ setContextTokens(null); // unavailable = unknown: no estimate, no fake zero+ }+ }++ async function load(id: string) {+ setLoadError(null);+ try {+ await loadModel(id);+ } catch (e) {+ setLoadError(t(errKey(codeOf(String(e))))) + (codeOf(String(e)) ? ` · ${codeOf(String(e))}` : "");+ }+ }++ return (+ <div ref={rootRef} className="relative" data-testid="model-pill">+ <button+ type="button"+ aria-haspopup="listbox"+ aria-expanded={open}+ onClick={() => setOpen((o) => !o)}+ className="flex min-w-0 max-w-[18rem] items-center gap-1.5 rounded-full border border-line bg-surface2 px-2.5 py-1.5 text-xs font-medium text-fg hover:border-accent/50 hover:bg-surface"+ >+ <LightDot light={light} />+ <span className="max-w-[10rem] truncate">{model || t("chat.noModel")}</span>+ <span className="text-muted" data-testid="context-meter">+ {contextTokens === null ? t("chat.contextUnknown") : t("chat.contextUsed", { n: contextTokens })}+ </span>+ <ChevronDown size={12} aria-hidden />+ </button>++ {open && (+ <div role="listbox" className="absolute bottom-full left-0 z-20 mb-2 w-72 rounded-2xl border border-line bg-surface p-2 shadow-lg">+ {candidates.length === 0 && <p className="px-2 py-1.5 text-sm text-muted">{t("chat.noModel")}</p>}+ {candidates.map((id) => {+ const l = deriveLight(st, engineStore.loadingTier, installed, id);+ return (+ <div key={id} className="flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm hover:bg-surface2">+ <button+ type="button"+ role="option"+ aria-selected={id === model}+ onClick={() => {+ onModelChange(id);+ setOpen(false);+ }}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ >+ <LightDot light={l} />+ <span className="min-w-0 flex-1 truncate">{id}</span>+ <span className="text-xs text-muted">{t(`chat.light.${l}`)}</span>+ </button>+ {(l === "installed" || l === "loading") && id === model && (+ <button+ type="button"+ onClick={() => void load(id)}+ disabled={l === "loading"}+ className="flex items-center gap-1 rounded-full border border-line px-2 py-0.5 text-xs text-muted hover:text-fg disabled:opacity-60"+ >+ {l === "loading" && <Loader2 size={11} className="animate-spin" aria-hidden />}+ {t("chat.loadModel")}+ </button>+ )}+ </div>+ );+ })}+ {loadError && (+ <p className="mt-1 rounded-lg bg-err/10 px-2 py-1.5 text-xs text-err" role="alert">+ {loadError}+ </p>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/windows/app/src/lib/autoLoad.ts b/windows/app/src/lib/autoLoad.tsnew file mode 100644index 0000000..2468ea5--- /dev/null+++ b/windows/app/src/lib/autoLoad.ts@@ -0,0 +1,65 @@+// One-shot intent token for "Download & enable" (in memory; consumed on use).+// This module is the ONLY place that may auto-chain a finished download into a load —+// every other load path requires an explicit user click.+type Phase = "download" | "load";++interface Token {+ tier: string;+ taskId: string; // download tasks are keyed by tier (shell-side pull.rs)+ phase: Phase;+}++type Listener = () => void;++class AutoLoadStore {+ private token: Token | null = null;+ private listeners = new Set<Listener>();++ get current(): Token | null {+ return this.token;+ }++ subscribe(fn: Listener): () => void {+ this.listeners.add(fn);+ return () => {+ this.listeners.delete(fn);+ };+ }++ private emit(): void {+ for (const l of this.listeners) l();+ }++ /** User pressed "Download & enable" (the only legal entry point). */+ begin(tier: string, taskId: string): void {+ this.token = { tier, taskId, phase: "download" };+ this.emit();+ }++ /** download ready for the same task: move to the load phase (returns tier). One-shot: never revives. */+ claimCompleted(tier: string): string | null {+ if (!this.token || this.token.phase !== "download" || this.token.taskId !== tier) return null;+ const t = this.token.tier;+ this.token = { ...this.token, phase: "load" };+ this.emit();+ return t;+ }++ /** load succeeded: consume the token (returns tier for thread creation); later duplicate ready events are no-ops. */+ consume(tier: string): boolean {+ if (!this.token || this.token.phase !== "load" || this.token.tier !== tier) return false;+ this.token = null;+ this.emit();+ return true;+ }++ /** failure / abandon / close: invalidate immediately (never persisted, so a restart naturally drops it). */+ cancel(): void {+ if (this.token) {+ this.token = null;+ this.emit();+ }+ }+}++export const autoLoad = new AutoLoadStore();diff --git a/windows/app/src/lib/byteFormat.ts b/windows/app/src/lib/byteFormat.tsnew file mode 100644index 0000000..b04f1c8--- /dev/null+++ b/windows/app/src/lib/byteFormat.ts@@ -0,0 +1,17 @@+// Byte / rate / ETA display formatting — unit conversion and rounding only; never invents numbers the data source didn't provide.+export function humanBytes(n: number): string {+ if (n >= 1e12) return `${(n / 1e12).toFixed(2)} TB`;+ if (n >= 1e9) return `${(n / 1e9).toFixed(2)} GB`;+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)} MB`;+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)} KB`;+ return `${n} B`;+}++export function humanRate(bytesPerSec: number): string {+ return `${humanBytes(bytesPerSec)}/s`;+}++/** ETA display granularity: round to 30 s to avoid jitter; returns minutes (0.5 steps allowed). */+export function etaMinutes(etaS: number): number {+ return Math.max(0.5, (Math.round(etaS / 30) * 30) / 60);+}diff --git a/windows/app/src/lib/generation.ts b/windows/app/src/lib/generation.tsnew file mode 100644index 0000000..3b8721b--- /dev/null+++ b/windows/app/src/lib/generation.ts@@ -0,0 +1,26 @@+// Generation presets: three temperature tiers applied globally, default "Precise" 0.2.+// UI is the GenPill on the composer toolbar; the transport reads the current value on+// every send (tier changes take effect from the next message).+export type GenPreset = "precise" | "balanced" | "creative";++const GEN_KEY = "edge0.gen";++export const GEN_TEMPERATURE: Record<GenPreset, number> = {+ precise: 0.2,+ balanced: 0.7,+ creative: 1.0,+};++export function storedGen(): GenPreset {+ const v = localStorage.getItem(GEN_KEY);+ return v === "balanced" || v === "creative" ? v : "precise";+}++export function setGen(p: GenPreset): void {+ localStorage.setItem(GEN_KEY, p);+}++/** Current temperature (read live on every request). */+export function currentTemperature(): number {+ return GEN_TEMPERATURE[storedGen()];+}diff --git a/windows/app/src/lib/systemPrompt.ts b/windows/app/src/lib/systemPrompt.tsnew file mode 100644index 0000000..8ca2dab--- /dev/null+++ b/windows/app/src/lib/systemPrompt.ts@@ -0,0 +1,22 @@+// Optional system prompt: empty string = not sent.+export const DEFAULT_SYSTEM_PROMPT = "You're edge0, an on-device AI assistant.";++const SYSTEM_PROMPT_KEY = "edge0.system-prompt";+const SYSTEM_PROMPT_EVENT = "edge0:system-prompt";++export function storedSystemPrompt(): string | null {+ const stored = localStorage.getItem(SYSTEM_PROMPT_KEY);+ if (stored === null) return DEFAULT_SYSTEM_PROMPT;+ const trimmed = stored.trim();+ return trimmed.length > 0 ? stored : null;+}++export function setSystemPrompt(value: string): void {+ localStorage.setItem(SYSTEM_PROMPT_KEY, value);+ window.dispatchEvent(new Event(SYSTEM_PROMPT_EVENT));+}++export function subscribeSystemPrompt(listener: () => void): () => void {+ window.addEventListener(SYSTEM_PROMPT_EVENT, listener);+ return () => window.removeEventListener(SYSTEM_PROMPT_EVENT, listener);+}diff --git a/windows/app/src/lib/t.ts b/windows/app/src/lib/t.tsnew file mode 100644index 0000000..a323cd7--- /dev/null+++ b/windows/app/src/lib/t.ts@@ -0,0 +1,183 @@+// lib/t.ts — single source for UI strings: **English-only** (product decision for the+// overseas release: no language switching). Dot-separated keys with {{var}} interpolation;+// a missing key echoes the key itself (honest surface, never swallowed silently).+type Table = Record<string, unknown>;++const en: Table = {+ app: { name: "edge0", localLabel: "local inference" },+ platform: { note: "Windows · local llama.cpp engine" },+ theme: { light: "Light", dark: "Dark", system: "System" },+ font: { sm: "Small", md: "Default", lg: "Large" },+ nav: {+ models: "Models", service: "Service", settings: "Settings",+ openSidebar: "Open sidebar", closeSidebar: "Close sidebar",+ },+ common: { cancel: "Cancel" },+ sidebar: {+ newChat: "New chat", history: "Chat history", navigation: "Navigation",+ resident: "resident", idle: "idle", noService: "No service",+ scopeShell: "managed in-app",+ bucket: { today: "Today", yesterday: "Yesterday", week: "Previous 7 days", earlier: "Earlier" },+ },+ chat: {+ newThread: "New chat", rename: "Rename", deleteThread: "Delete chat", noThreads: "No chats yet",+ placeholder: "Type a message, Enter to send", send: "Send", stop: "Stop", regenerate: "Regenerate",+ editResend: "Edit & resend", resend: "Resend", copy: "Copy", copyReasoning: "Copy thinking",+ reasoning: "Thinking", aborted: "Response interrupted", saveFailed: "Not saved (conversation store write failed)",+ usage: "tokens in {{p}}/out {{c}}/total {{t}}",+ perf: { decode: "{{v}} tok/s decode", prefill: "{{v}} tok/s prefill", prompt: "prefill {{ms}} ms", mem: "memory {{gi}} GiB" },+ model: "Model", noModel: "(no installed model)",+ light: { resident: "resident", loading: "loading", installed: "idle", absent: "unknown" },+ loadModel: "Load",+ contextUsed: "context {{n}} tok", contextUnknown: "context: unknown",+ greeting: "What would you like to explore?", pickOrCreate: "Select or create a chat",+ serviceShell: "local engine", noInstalledModel: "No models to chat with yet — download one first",+ goDownload: "Go to downloads",+ waitingFirstChunk: "Waiting for the model…", pickModelFirst: "Pick a model first",+ residentForever: "Resident until manually evicted",+ err: {+ notload: "Model not loaded — press Load, or download it",+ busy: "Service busy, retry shortly", cancel: "Generation cancelled",+ worker: "Engine process crashed — restart it from the Service page and retry",+ param: "Request parameters rejected — check the model selection",+ missing: "Model not installed — download it first",+ memload: "Not enough memory to load — use a smaller tier",+ version: "Engine binary missing — set EDGE0_BIN_DIR or start from the Service page",+ pool: "Prefetch pool not active (POOL2 telemetry line missing) — performance claims downgraded",+ protected: "This tier is a seed link (junction) — the shell never deletes through links",+ generic: "Request failed",+ },+ },+ settings: {+ title: "Settings", kicker: "Tune edge0 appearance and local service access",+ appearance: "Appearance", appearanceNote: "Theme and font size apply across the app immediately.",+ systemPrompt: "System prompt", systemPromptNote: "Optional instructions sent before each chat. Leave blank to disable.",+ systemPromptEnabled: "System prompt enabled", systemPromptDisabled: "No system prompt will be sent",+ systemPromptReset: "Use default",+ service: "Service", serviceNote: "View a compact summary; full controls, logs, and diagnostics live in the service console.",+ serviceUnavailable: "Service not connected", advancedNote: "Request logs and environment checks live in the service console.",+ openConsole: "Open service console",+ },+ gen: {+ precise: "Precise", balanced: "Balanced", creative: "Creative",+ hint: "Generation style: sampling temperature (Precise 0.2 / Balanced 0.7 / Creative 1.0), applied from the next message.",+ },+ models: {+ title: "Models & Downloads", kicker: "Manage installed tiers, residency, and downloads",+ refresh: "Refresh", loading: "Reading catalog…", retry: "Retry",+ stale: "Catalog manifest expired (mirrors unreachable): browsing OK, downloads paused",+ rev: "Rev", bytes: "Size", files: "Files", source: "Source", singleSource: "single source",+ license: "License", notes: "Model card", pool: "Prefetch pool", repo: "Source repo",+ state: { absent: "Not installed", installed: "Installed", update: "Installed" },+ download: "Download", sourceAuto: "Auto source (speed probe)", sourceMs: "ModelScope", sourceHf: "Hugging Face", sourceHfMirror: "HF mirror",+ load: "Enable", unload: "Evict", loadingModel: "Loading…",+ delete: "Delete", deleteConfirm: "Delete this tier? Both ~/.edge0 directories are removed physically (seed links are refused).",+ loadFailed: "Load failed: {{msg}}",+ pause: "Cancel", cancelTask: "Cancel task", deleteTask: "Delete task",+ sourceSwitched: "source switched", eta: "~{{n}} min left", estimating: "estimating speed…", verifying: "verifying…",+ filesProgress: "{{done}}/{{total}} files",+ phase: {+ idle: "Idle", probe: "Probing sources", download: "Downloading", convert: "On-device converting",+ ready: "Done", error: "Failed", cancelled: "Cancelled",+ },+ err: {+ net: "Mirror or source temporarily unreachable — check network and retry",+ src: "Source rejects resume semantics or unreachable — retry later or switch network",+ disk: "Not enough disk space — free space and retry, or pick a smaller tier",+ hash: "File hash mismatch with manifest — delete the task and retry",+ size: "File size mismatch with manifest — delete the task and retry",+ convert: "On-device conversion failed — check tools/convert_mlx_to_gguf.py, then retry",+ protected: "This tier is a seed link (junction) — the shell unlinks, never deletes targets",+ busy: "Tier is resident — evict it before deleting",+ invalid: "Model files do not match the install record — delete the tier and download again",+ generic: "Request failed",+ },+ },+ welcome: {+ title: "Get started with edge0 on this PC",+ body: "Recommended: {{tier}} ({{bytes}}, stored in {{path}}) — inference runs entirely on-device.",+ bytesUnknown: "size unknown", pathUnknown: "local app directory",+ downloadEnable: "Download & enable", skip: "Skip for now",+ errors: { disk: "Not enough disk space", memory: "Not enough memory to load the recommended tier", engine: "The local engine is unavailable", generic: "First launch did not complete" },+ },+ service: {+ title: "Local API Service", kicker: "Manage engine lifecycle, access, and runtime diagnostics",+ sections: {+ lifecycle: "Lifecycle & ownership", lifecycleNote: "Start or stop the engine and inspect port, version, and uptime.",+ logs: "Request log", logsNote: "Shows the generation-request window since this app started.",+ doctor: "Environment checks", doctorNote: "Shows shell-side measured findings and next actions.",+ },+ panel: {+ title: "Service Panel", start: "Start service", stop: "Stop service",+ busy: "Service operation in progress… (restart ends in-flight requests)", actionFailed: "The service action could not be completed.",+ port: "Listening", bind: "Bind address", scope: "Ownership", uptime: "Uptime",+ version: "Engine version", home: "Storage location", pool: "Prefetch pool", tier: "Resident tier",+ governance: "Process governance", governanceJob: "Job Object armed (OS reclaims the engine when the app dies)",+ governanceSoft: "Normal-exit fallback only (job attach failed — stated honestly)",+ token: "Access token", noCredential: "No credential needed (loopback is exempt)",+ notOwned: "This service was not started by this app; stop it via its owner",+ lan: "Allow LAN", lanOn: "On", lanOff: "Off", lanLater: "Phase 2: LAN access is not implemented yet",+ idle: "Engine not running",+ },+ log: {+ title: "Request Log", count: "{{n}} requests since start",+ note: "Window = generation requests in this app session (in memory; cleared on exit)",+ empty: "No requests since this session started",+ th: { status: "Status", model: "Model", latency: "Latency", tokens: "tokens", source: "Source" },+ status: { done: "done", cancelled: "cancelled", error: "error" },+ source: { loopback: "local" },+ },+ doctor: {+ title: "Environment Check", loading: "Reading check results…", failed: "Cannot fetch environment findings", retry: "Retry",+ next: "Next", goModels: "Go to Models",+ overall: { pass: "All passing", warn: "Warnings" },+ verdict: { pass: "pass", warn: "warn", fail: "fail" },+ },+ },+};++function lookup(key: string): string {+ let cur: unknown = en;+ for (const seg of key.split(".")) {+ if (cur == null || typeof cur !== "object") return key;+ cur = (cur as Table)[seg];+ }+ return typeof cur === "string" ? cur : key;+}++/** t("sidebar.bucket.today") / t("chat.usage", { p, c, t }) — with {{var}} interpolation. */+export function t(key: string, vars?: Record<string, string | number>): string {+ let s = lookup(key);+ if (vars) {+ for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{{${k}}}`, String(v));+ }+ return s;+}++/** Error code → human-readable key (this repo's code set is small: a flat table). */+export function errKey(code: string | null | undefined): string {+ if (!code) return "chat.err.generic";+ if (code.startsWith("E-DL-NET")) return "models.err.net";+ if (code.startsWith("E-DL-SRC")) return "models.err.src";+ if (code.startsWith("E-DL-DISK")) return "models.err.disk";+ if (code.startsWith("E-DL-SHA")) return "models.err.hash";+ if (code.startsWith("E-DL-SIZE")) return "models.err.size";+ if (code.startsWith("E-CONVERT")) return "models.err.convert";+ if (code.startsWith("E-MODEL-PROTECTED")) return "models.err.protected";+ if (code.startsWith("E-MODEL-BUSY")) return "models.err.busy";+ if (code.startsWith("E-MODEL-INVALID")) return "models.err.invalid";+ if (code.startsWith("E-MODEL-MISSING")) return "chat.err.missing";+ if (code.startsWith("E-ENGINE-MISSING")) return "chat.err.version";+ if (code.startsWith("E-ENGINE-DIED")) return "chat.err.worker";+ if (code.startsWith("E-POOL")) return "chat.err.pool";+ if (code.startsWith("E-MEM")) return "chat.err.memload";+ if (code.startsWith("E-DISK")) return "models.err.disk";+ return "chat.err.generic";+}++/** Extract the code from an error string (shell-side format: "E-XXX human text"; take the leading token). */+export function codeOf(err: string | null | undefined): string | null {+ if (!err) return null;+ const m = err.match(/E-[A-Z-]+/);+ return m ? m[0] : null;+}diff --git a/windows/app/src/lib/theme.ts b/windows/app/src/lib/theme.tsnew file mode 100644index 0000000..31038a1--- /dev/null+++ b/windows/app/src/lib/theme.ts@@ -0,0 +1,31 @@+// Dark/light theme + font size: the shell is the single source of truth (system-follow mode resolves in JS, then persists to data-theme).+export type Theme = "light" | "dark" | "system";+export type FontScale = "sm" | "md" | "lg";++const THEME_KEY = "edge0.token…heme";+const FONT_KEY = "edge0.token…font";++export function resolveTheme(t: Theme): "light" | "dark" {+ if (t !== "system") return t;+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";+}++export function storedTheme(): Theme {+ const v = localStorage.getItem(THEME_KEY);+ return v === "light" || v === "dark" || v === "system" ? v : "system";+}++export function storedFont(): FontScale {+ const v = localStorage.getItem(FONT_KEY);+ return v === "sm" || v === "md" || v === "lg" ? v : "md";+}++export function applyTheme(t: Theme): void {+ localStorage.setItem(THEME_KEY, t);+ document.documentElement.dataset.theme = resolveTheme(t);+}++export function applyFont(f: FontScale): void {+ localStorage.setItem(FONT_KEY, f);+ document.documentElement.dataset.font = f;+}diff --git a/windows/app/src/main.tsx b/windows/app/src/main.tsxnew file mode 100644index 0000000..18a8927--- /dev/null+++ b/windows/app/src/main.tsx@@ -0,0 +1,52 @@+// main.tsx — frontend entry. Hash routing (no router dependency):+// `/` = chat (default landing), `/models`, `/service`, `/settings`; legacy `/chat` normalizes to `/`.+import React, { useEffect, useState } from "react";+import ReactDOM from "react-dom/client";++import { boot } from "./api/client";+import { AppShell } from "./components/AppShell";+import { applyFont, applyTheme, storedFont, storedTheme } from "./lib/theme";+import { ChatPage } from "./routes/chat";+import { ModelsPage } from "./routes/models";+import { ServicePage } from "./routes/service";+import { SettingsPage } from "./routes/settings";+import "./styles.css";++// The shell is the single source of truth: boot applies data-theme/data-font before first paint (no flash of wrong theme).+applyTheme(storedTheme());+applyFont(storedFont());++function normalize(hash: string): string {+ const p = (hash || "").replace(/^#/, "") || "/";+ return p === "/chat" ? "/" : p; // normalize the legacy entry; keep a single canonical route+}++function useHashRoute(): string {+ const [path, setPath] = useState(() => normalize(window.location.hash));+ useEffect(() => {+ const on = () => setPath(normalize(window.location.hash));+ window.addEventListener("hashchange", on);+ return () => window.removeEventListener("hashchange", on);+ }, []);+ return path;+}++function App() {+ const path = useHashRoute();+ useEffect(() => {+ void boot();+ }, []);+ const view = path === "/models" ? path : path === "/service" ? path : path === "/settings" ? path : "/";+ return (+ <AppShell view={view}>+ {view === "/models" && <ModelsPage />}+ {view === "/service" && <ServicePage />}+ {view === "/settings" && <SettingsPage />}+ {view === "/" && <ChatPage />}+ </AppShell>+ );+}++ReactDOM.createRoot(document.getElementById("root")!).render(+ <React.StrictMode><App /></React.StrictMode>+);diff --git a/windows/app/src/routes/chat.tsx b/windows/app/src/routes/chat.tsxnew file mode 100644index 0000000..85a0a4d--- /dev/null+++ b/windows/app/src/routes/chat.tsx@@ -0,0 +1,103 @@+// routes/chat.tsx — chat main area: centered max-width message column + floating bottom+// composer; no selected thread = big-title empty state; nothing installed = WelcomeCard;+// the boot snapshot decides the waiting shape.+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";++import { engineStore, installedTiers, shellStore } from "../api/client";+import { useThreadChat } from "../chat/useThreadChat";+import { isAtBottom } from "../chat/scroll";+import { t } from "../lib/t";+import { storedSystemPrompt, subscribeSystemPrompt } from "../lib/systemPrompt";+import { threadStore, type ThreadRow } from "../state/threads";+import { ComposerBar } from "../components/chat/ComposerBar";+import { MessageList } from "../components/chat/MessageList";+import { WelcomeCard } from "./welcome";++export function ChatPage() {+ useSyncExternalStore(threadStore.subscribe, () => threadStore.version());+ useSyncExternalStore(engineStore.sig.sub, engineStore.sig.version);+ useSyncExternalStore(shellStore.sig.sub, shellStore.sig.version);++ const st = engineStore.status;+ const active = threadStore.threads().find((x) => x.id === threadStore.activeId) ?? null;+ const hasInstalled = installedTiers().length > 0;++ if (!st) {+ return (+ <div className="e0-chat-empty text-sm text-muted">+ <span className="mx-auto grid size-10 place-items-center rounded-2xl bg-surface2 text-fg">+ <span className="size-2 rounded-full bg-warn animate-pulse" aria-hidden />+ </span>+ <p className="font-medium text-fg">{t("service.panel.idle")}</p>+ <p className="text-xs">{t("platform.note")}</p>+ </div>+ );+ }+ if (!hasInstalled) return <WelcomeCard />;+ if (!active) {+ return (+ <div className="e0-chat-empty">+ <span className="mx-auto grid size-12 place-items-center rounded-2xl bg-fg text-surface shadow-sm">+ <span className="text-lg font-semibold" aria-hidden>+</span>+ </span>+ <h2 className="mt-1 text-3xl font-semibold tracking-tight">{t("chat.greeting")}</h2>+ <p className="text-sm text-muted">{t("chat.pickOrCreate")}</p>+ </div>+ );+ }+ return <ChatPane key={active.id} thread={active} />;+}++function ChatPane({ thread }: { thread: ThreadRow }) {+ const st = engineStore.status;+ const [model, setModel] = useState(thread.data.model ?? (st?.running ? st.tier ?? "" : ""));+ useSyncExternalStore(subscribeSystemPrompt, () => storedSystemPrompt(), () => storedSystemPrompt());+ const scrollerRef = useRef<HTMLDivElement>(null);+ // Follow-bottom: pin to the bottom on streaming increments only while the user is already near the bottom.+ const stickBottom = useRef(true);++ const chat = useThreadChat(thread, model || null);++ const onModelChange = useCallback(+ (id: string) => {+ setModel(id);+ threadStore.setModel(thread.id, id);+ },+ [thread.id],+ );++ useEffect(() => {+ const last = chat.messages[chat.messages.length - 1];+ // right after the user sends: always jump to bottom (clear intent)+ if (last?.role === "user") stickBottom.current = true;+ const el = scrollerRef.current;+ if (el && stickBottom.current) el.scrollTo({ top: el.scrollHeight });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [chat.messages]);++ const onScrollerScroll = () => {+ const el = scrollerRef.current;+ if (el) stickBottom.current = isAtBottom(el);+ };++ return (+ <div className="flex h-full min-h-0 flex-col">+ <header className="e0-chat-header">+ <div className="min-w-0">+ <div className="e0-chat-header-title">{thread.data.title}</div>+ <div className="e0-chat-header-meta">+ <span className={"size-2 rounded-full " + (st?.running ? "bg-ok" : "bg-muted")} aria-hidden />+ {t("chat.serviceShell")}+ </div>+ </div>+ <span className="hidden text-xs text-muted sm:inline">{model || t("chat.noModel")}</span>+ </header>+ <div ref={scrollerRef} onScroll={onScrollerScroll} className="min-h-0 flex-1 overflow-y-auto">+ <div className="e0-chat-column space-y-1 px-5 pb-4 pt-7 sm:px-6">+ <MessageList chat={chat} />+ </div>+ </div>+ <ComposerBar chat={chat} model={model} onModelChange={onModelChange} />+ </div>+ );+}diff --git a/windows/app/src/routes/models.tsx b/windows/app/src/routes/models.tsxnew file mode 100644index 0000000..5e75482--- /dev/null+++ b/windows/app/src/routes/models.tsx@@ -0,0 +1,204 @@+// routes/models.tsx — model catalog + download management. Tiers come from the embedded+// catalog table; local facts = models_installed + engine status + folded download tasks.+// The UI never estimates.+import { BookOpen, Download, Power, RefreshCw, Trash2 } from "lucide-react";+import { useState, useSyncExternalStore } from "react";++import {+ deleteModel,+ downloadStore,+ engineStore,+ loadModel,+ refreshAll,+ shellStore,+ startDownload,+ unloadModel,+} from "../api/client";+import { deriveLight } from "../chat/modelStatus";+import { humanBytes } from "../lib/byteFormat";+import { codeOf, errKey, t } from "../lib/t";+import type { CatTier } from "../api/client";+import { DownloadCardBody } from "../models/cards";++export function ModelsPage() {+ const [, force] = useState(0);+ useSyncExternalStore(shellStore.sig.sub, shellStore.sig.version);+ useSyncExternalStore(downloadStore.sig.sub, downloadStore.sig.version);+ useSyncExternalStore(engineStore.sig.sub, engineStore.sig.version);+ void force;++ const tiers = Object.entries(shellStore.catalog);+ const ready = tiers.length > 0;++ return (+ <section className="e0-page space-y-4" data-testid="models-page">+ <div className="e0-page-header">+ <div>+ <h2 className="e0-page-title flex items-center gap-2">+ <BookOpen size={18} aria-hidden />+ {t("models.title")}+ </h2>+ <p className="e0-page-kicker">{t("models.kicker")}</p>+ </div>+ <button type="button" data-testid="models-refresh" onClick={() => void refreshAll()} className="e0-btn e0-btn-secondary">+ <RefreshCw size={12} aria-hidden />+ {t("models.refresh")}+ </button>+ </div>++ {!ready && <p className="text-sm text-muted">{t("models.loading")}</p>}++ {tiers.map(([tier, rec]) => (+ <TierCard key={tier} tier={tier} rec={rec} />+ ))}+ </section>+ );+}++function TierCard({ tier, rec }: { tier: string; rec: CatTier }) {+ const [source, setSource] = useState("");+ const [opError, setOpError] = useState<string | null>(null);+ const [confirmDelete, setConfirmDelete] = useState(false);++ const st = engineStore.status;+ const installed = shellStore.installed[tier] !== undefined;+ const task = downloadStore.tasks[tier];+ const inFlight = task && (task.phase === "probe" || task.phase === "download" || task.phase === "convert");+ const light = deriveLight(st, engineStore.loadingTier, Object.keys(shellStore.installed), tier);+ const stateLabel = installed ? "installed" : "absent";+ const resident = light === "resident";+ const filesCount = rec.files.filter((f) => !f.skip).length;++ async function run(fn: () => Promise<unknown>) {+ setOpError(null);+ setConfirmDelete(false);+ try {+ await fn();+ await refreshAll();+ } catch (e) {+ const s = String(e);+ setOpError(`${t(errKey(codeOf(s)))}${codeOf(s) ? ` · ${codeOf(s)}` : ""}`);+ await refreshAll().catch(() => undefined);+ }+ }++ return (+ <div data-testid={`tier-${tier}`} className="e0-section flex flex-col gap-3 p-5">+ <div className="flex items-baseline justify-between gap-2">+ <div>+ <h3 className="text-base font-semibold">{tier}</h3>+ <p className="text-xs text-muted" data-testid={`tier-state-${tier}`}>{t(`models.state.${stateLabel}`)}</p>+ </div>+ <span data-testid={`light-${tier}`} data-light={light} className={"e0-status " + (light === "resident" ? "e0-status-ok" : light === "loading" ? "e0-status-warn" : "")}>+ <span className={"size-1.5 rounded-full " + (light === "resident" ? "bg-ok" : light === "loading" ? "bg-warn" : "bg-muted")} aria-hidden />+ {t(`chat.light.${light}`)}+ </span>+ </div>++ <dl className="order-3 grid grid-cols-2 gap-x-4 gap-y-1 border-t border-line/60 pt-3 text-xs tabular-nums">+ <Field k={t("models.rev")} v={rec.rev.hf.slice(0, 12)} />+ <Field k={t("models.bytes")} v={humanBytes(rec.total_bytes)} />+ <Field k={t("models.files")} v={String(filesCount)} />+ <Field k={t("models.pool")} v={`${rec.pool_mb} MB`} />+ <Field k={t("models.source")} v="Hugging Face (primary) + mirrors" />+ <Field k={t("models.repo")} v={rec.repo} />+ </dl>++ {inFlight && task && (+ <div className="order-2">+ <DownloadCardBody task={task} />+ </div>+ )}+ {!inFlight && task && (task.phase === "error" || task.phase === "cancelled") && (+ <div className="order-2">+ <DownloadCardBody task={task} />+ </div>+ )}++ {opError && (+ <p data-testid={`tier-operr-${tier}`} role="alert" className="e0-status e0-status-err order-2 w-full justify-start rounded-lg">+ {opError}+ </p>+ )}++ {!installed && !inFlight && (+ <div className="order-1 flex flex-wrap items-center gap-2">+ <select+ data-testid={`source-select-${tier}`}+ value={source}+ onChange={(e) => setSource(e.target.value)}+ className="rounded-lg border border-line bg-surface px-2.5 py-1.5 text-xs"+ >+ <option value="">{t("models.sourceAuto")}</option>+ <option value="hf">{t("models.sourceHf")}</option>+ <option value="hf-mirror">{t("models.sourceHfMirror")}</option>+ <option value="modelscope">{t("models.sourceMs")}</option>+ </select>+ <button+ type="button"+ data-testid={`download-${tier}`}+ onClick={() => void run(() => startDownload(tier, source || null))}+ className="e0-btn e0-btn-primary"+ >+ <Download size={12} aria-hidden />+ {t("models.download")}+ </button>+ </div>+ )}++ {installed && (+ <div className="order-1 flex flex-wrap items-center gap-2">+ {!inFlight && light !== "resident" && (+ <button+ type="button"+ data-testid={`load-${tier}`}+ disabled={light === "loading"}+ onClick={() => void run(() => loadModel(tier))}+ className="e0-btn e0-btn-secondary"+ >+ <Power size={12} aria-hidden />+ {light === "loading" ? t("models.loadingModel") : t("models.load")}+ </button>+ )}+ {resident && (+ <button type="button" data-testid={`unload-${tier}`} onClick={() => void run(() => unloadModel())} className="e0-btn e0-btn-secondary">+ {t("models.unload")}+ </button>+ )}+ {resident && <span className="text-xs text-muted">{t("chat.residentForever")}</span>}+ {confirmDelete ? (+ <span className="flex items-center gap-1 text-xs">+ <span>{t("models.deleteConfirm")}</span>+ <button type="button" data-testid={`delete-yes-${tier}`} onClick={() => void run(() => deleteModel(tier))} className="e0-btn bg-err text-white">+ {t("models.delete")}+ </button>+ <button type="button" data-testid={`delete-no-${tier}`} onClick={() => setConfirmDelete(false)} className="e0-btn e0-btn-secondary">+ {t("common.cancel")}+ </button>+ </span>+ ) : (+ <button+ type="button"+ data-testid={`delete-${tier}`}+ disabled={!!inFlight}+ onClick={() => setConfirmDelete(true)}+ className="e0-btn e0-btn-danger"+ >+ <Trash2 size={12} aria-hidden />+ {t("models.delete")}+ </button>+ )}+ </div>+ )}+ </div>+ );+}++function Field({ k, v }: { k: string; v: string }) {+ return (+ <>+ <dt className="text-muted">{k}</dt>+ <dd className="text-fg truncate" title={v}>{v}</dd>+ </>+ );+}diff --git a/windows/app/src/routes/service.tsx b/windows/app/src/routes/service.tsxnew file mode 100644index 0000000..3456581--- /dev/null+++ b/windows/app/src/routes/service.tsx@@ -0,0 +1,46 @@+// routes/service.tsx — local API service screen with three landmarks: lifecycle /+// request log / environment checks. Adds no new control paths or endpoints — a skin+// over existing shell capabilities.+import { Server } from "lucide-react";++import { DoctorSection } from "../service/doctor";+import { ServicePanel } from "../service/panel";+import { RequestLogSection } from "../service/reqlog";+import { t } from "../lib/t";++export function ServicePage() {+ return (+ <div className="e0-page space-y-5" data-testid="service-page">+ <header className="e0-page-header">+ <div>+ <h2 className="e0-page-title flex items-center gap-2">+ <Server size={18} aria-hidden />+ {t("service.title")}+ </h2>+ <p className="e0-page-kicker">{t("service.kicker")}</p>+ </div>+ </header>+ <section aria-labelledby="service-lifecycle-title" data-testid="service-lifecycle-section">+ <div className="mb-2 px-1">+ <h3 id="service-lifecycle-title" className="e0-section-title">{t("service.sections.lifecycle")}</h3>+ <p className="e0-section-note">{t("service.sections.lifecycleNote")}</p>+ </div>+ <ServicePanel />+ </section>+ <section aria-labelledby="service-log-title" data-testid="service-log-section">+ <div className="mb-2 px-1">+ <h3 id="service-log-title" className="e0-section-title">{t("service.sections.logs")}</h3>+ <p className="e0-section-note">{t("service.sections.logsNote")}</p>+ </div>+ <RequestLogSection />+ </section>+ <section aria-labelledby="service-doctor-title" data-testid="service-doctor-section">+ <div className="mb-2 px-1">+ <h3 id="service-doctor-title" className="e0-section-title">{t("service.sections.doctor")}</h3>+ <p className="e0-section-note">{t("service.sections.doctorNote")}</p>+ </div>+ <DoctorSection />+ </section>+ </div>+ );+}diff --git a/windows/app/src/routes/settings.tsx b/windows/app/src/routes/settings.tsxnew file mode 100644index 0000000..40ed212--- /dev/null+++ b/windows/app/src/routes/settings.tsx@@ -0,0 +1,96 @@+// routes/settings.tsx — settings page: appearance group reuses ShellControls, a system+// prompt group, and a service block carrying the summary + console entry.+import { Settings2, SlidersHorizontal, Server, RotateCcw } from "lucide-react";+import { useState, useSyncExternalStore } from "react";++import { engineStore } from "../api/client";+import { ShellControls } from "../components/ShellControls";+import { DEFAULT_SYSTEM_PROMPT, setSystemPrompt, storedSystemPrompt } from "../lib/systemPrompt";+import { t } from "../lib/t";++export function SettingsPage() {+ const [systemPrompt, setPrompt] = useState(() => storedSystemPrompt() ?? "");+ useSyncExternalStore(engineStore.sig.sub, engineStore.sig.version); // service-block pulse+ const s = engineStore.status;+ return (+ <div className="e0-page space-y-5">+ <header className="e0-page-header">+ <div>+ <h2 className="e0-page-title flex items-center gap-2">+ <Settings2 size={19} aria-hidden />+ {t("settings.title")}+ </h2>+ <p className="e0-page-kicker">{t("settings.kicker")}</p>+ </div>+ </header>+ <section className="e0-section overflow-hidden" aria-labelledby="settings-appearance-title">+ <div className="e0-section-header">+ <div>+ <h3 id="settings-appearance-title" className="e0-section-title">{t("settings.appearance")}</h3>+ <p className="e0-section-note">{t("settings.appearanceNote")}</p>+ </div>+ <SlidersHorizontal size={17} className="text-muted" aria-hidden />+ </div>+ <div className="px-5 pb-5">+ <ShellControls />+ </div>+ </section>+ <section className="e0-section overflow-hidden" aria-labelledby="settings-prompt-title">+ <div className="e0-section-header">+ <div>+ <h3 id="settings-prompt-title" className="e0-section-title">{t("settings.systemPrompt")}</h3>+ <p className="e0-section-note">{t("settings.systemPromptNote")}</p>+ </div>+ </div>+ <div className="border-t border-line/60 px-5 pb-5 pt-4">+ <textarea+ value={systemPrompt}+ onChange={(e) => {+ setPrompt(e.target.value);+ setSystemPrompt(e.target.value);+ }}+ placeholder={DEFAULT_SYSTEM_PROMPT}+ rows={4}+ aria-label={t("settings.systemPrompt")}+ className="w-full resize-y rounded-xl border border-line bg-surface2 p-3 text-sm leading-relaxed outline-none focus:border-accent"+ />+ <div className="mt-3 flex items-center justify-between gap-3">+ <span className="text-xs text-muted">+ {systemPrompt.trim() ? t("settings.systemPromptEnabled") : t("settings.systemPromptDisabled")}+ </span>+ <button+ type="button"+ className="e0-btn e0-btn-secondary"+ onClick={() => {+ setPrompt(DEFAULT_SYSTEM_PROMPT);+ setSystemPrompt(DEFAULT_SYSTEM_PROMPT);+ }}+ >+ <RotateCcw size={13} aria-hidden />+ {t("settings.systemPromptReset")}+ </button>+ </div>+ </div>+ </section>+ <section className="e0-section overflow-hidden" aria-labelledby="settings-service-title">+ <div className="e0-section-header">+ <div>+ <h3 id="settings-service-title" className="e0-section-title">{t("settings.service")}</h3>+ <p className="e0-section-note">{t("settings.serviceNote")}</p>+ </div>+ <Server size={17} className="text-muted" aria-hidden />+ </div>+ <div className="flex items-center gap-3 border-t border-line/60 px-5 py-4">+ <span className={"size-2 rounded-full " + (s?.running ? "bg-ok" : "bg-muted")} aria-hidden />+ <span className="min-w-0 flex-1 truncate text-sm text-muted">+ {s?.running ? `${s.bound}:${s.port} · ${s.tier}` : t("settings.serviceUnavailable")}+ </span>+ <a href="#/service" data-testid="service-console-link" className="e0-btn e0-btn-secondary shrink-0">+ {t("settings.openConsole")}+ </a>+ </div>+ </section>+ <p className="px-1 text-xs text-muted">{t("settings.advancedNote")}</p>+ </div>+ );+}diff --git a/windows/app/src/routes/welcome.tsx b/windows/app/src/routes/welcome.tsxnew file mode 100644index 0000000..e32ae9e--- /dev/null+++ b/windows/app/src/routes/welcome.tsx@@ -0,0 +1,111 @@+// routes/welcome.tsx — first-run guide card (shown in the chat area when nothing is+// installed; completes the loop within three clicks). "Download & enable" = one explicit+// intent: create the task + arm the one-shot token (auto-load on completion lives in the+// AppShell chain).+import { Sparkles, Download } from "lucide-react";+import { useState, useSyncExternalStore } from "react";++import { downloadStore, shellStore, startDownload } from "../api/client";+import { autoLoad } from "../lib/autoLoad";+import { humanBytes } from "../lib/byteFormat";+import { codeOf, errKey, t } from "../lib/t";+import { DownloadCardBody } from "../models/cards";++export function WelcomeCard() {+ useSyncExternalStore(downloadStore.sig.sub, downloadStore.sig.version);+ useSyncExternalStore(shellStore.sig.sub, shellStore.sig.version);++ const [dismissed, setDismissed] = useState(false);+ const [err, setErr] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ const cat = shellStore.catalog;+ const tier = cat["8b"] ? "8b" : Object.keys(cat)[0] ?? null;+ const rec = tier ? cat[tier] : null;+ const task = tier ? downloadStore.tasks[tier] : undefined;+ const path = shellStore.paths.home || null;++ if (dismissed) {+ return (+ <div className="e0-chat-empty">+ <p className="text-lg font-medium">{t("chat.noInstalledModel")}</p>+ <a+ href="#/models"+ className="justify-self-center rounded-full border border-line px-4 py-1.5 text-sm text-muted hover:bg-surface2 hover:text-fg"+ >+ {t("chat.goDownload")}+ </a>+ </div>+ );+ }++ async function downloadAndEnable() {+ if (!tier) return;+ setErr(null);+ setBusy(true);+ try {+ await startDownload(tier, null);+ autoLoad.begin(tier, tier); // task key = tier (shell pull.rs)+ } catch (e) {+ setErr(String(e));+ } finally {+ setBusy(false);+ }+ }++ return (+ <div className="e0-chat-empty px-6" data-testid="welcome-card">+ <div className="e0-chat-column mx-auto space-y-5 text-center">+ <span className="mx-auto grid size-12 place-items-center rounded-2xl bg-fg text-surface shadow-sm">+ <Sparkles size={20} aria-hidden />+ </span>+ <div>+ <h2 className="text-3xl font-semibold tracking-tight">{t("welcome.title")}</h2>+ <p className="mx-auto mt-2 max-w-lg text-sm leading-relaxed text-muted">+ {t("welcome.body", {+ tier: tier ?? "8b",+ bytes: rec ? humanBytes(rec.total_bytes) : t("welcome.bytesUnknown"),+ path: path ?? t("welcome.pathUnknown"),+ })}+ </p>+ </div>+ {task && task.phase !== "idle" ? (+ <div className="mx-auto w-full max-w-lg text-left">+ <DownloadCardBody task={task} />+ </div>+ ) : (+ <button+ type="button"+ data-testid="welcome-go"+ disabled={busy || !rec}+ onClick={() => void downloadAndEnable()}+ className="e0-btn e0-btn-primary mx-auto min-h-10 px-5 text-sm"+ >+ <Download size={15} aria-hidden />+ {t("welcome.downloadEnable")}+ </button>+ )}+ {err && (+ <p data-testid="welcome-err" role="alert" className="e0-status e0-status-err mx-auto max-w-lg justify-start rounded-xl px-3 py-2 text-left">+ <span>+ <span className="block font-semibold">{t("welcome.errors.generic")}</span>+ <span className="mt-0.5 block font-normal">+ {t(errKey(codeOf(err)))} · {codeOf(err) ?? ""}+ </span>+ </span>+ </p>+ )}+ <div>+ <button+ type="button"+ data-testid="welcome-skip"+ onClick={() => setDismissed(true)}+ className="text-xs text-muted underline hover:text-fg"+ >+ {t("welcome.skip")}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/windows/app/src/service/doctor.tsx b/windows/app/src/service/doctor.tsxnew file mode 100644index 0000000..0f235b4--- /dev/null+++ b/windows/app/src/service/doctor.tsx@@ -0,0 +1,99 @@+// service/doctor.tsx — environment-check skin. Discipline: all verdicts are shell-side+// measurements (doctor_run); the UI only maps strings to styles — no thresholds, no+// re-judgement; on failure it keeps no stale data and never fakes a conclusion.+import { Stethoscope } from "lucide-react";+import { useCallback, useEffect, useState } from "react";++import { doctorRun, type DoctorCheck } from "../api/client";+import { t } from "../lib/t";++interface DoctorReport {+ overall: string;+ checks: DoctorCheck[];+}++/** Whitelisted `code` -> action routing (the skin only navigates, never judges). */+const ACTION_ROUTES: Record<string, { to: string; labelKey: string }> = {+ "E-DL-DISK": { to: "/models", labelKey: "service.doctor.goModels" },+ "E-MODEL-INVALID": { to: "/models", labelKey: "service.doctor.goModels" },+ "E-MODEL-MISSING": { to: "/models", labelKey: "service.doctor.goModels" },+};++export function DoctorSection() {+ const [report, setReport] = useState<DoctorReport | null>(null);+ const [failed, setFailed] = useState(false);+ const [loading, setLoading] = useState(true);++ const fetchDoctor = useCallback(async () => {+ setLoading(true);+ setFailed(false);+ try {+ setReport(await doctorRun());+ } catch {+ setReport(null); // failure state must not keep stale data+ setFailed(true);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void fetchDoctor();+ }, [fetchDoctor]);++ const verdictTone = (v: string) => (v === "pass" ? "ok" : v === "warn" ? "warn" : "err");+ const cls = (tone: string) =>+ tone === "ok" ? "bg-accent/15 text-accent" : tone === "warn" ? "bg-warn/15 text-warn" : "bg-err/15 text-err";++ return (+ <section className="e0-section overflow-hidden p-5" data-testid="svc-doctor">+ <div className="mb-2 flex items-center justify-between">+ <h3 className="flex items-center gap-2 text-sm font-semibold">+ <Stethoscope size={14} aria-hidden />+ {t("service.doctor.title")}+ </h3>+ {report && (+ <span data-testid="doctor-overall" className={"rounded-full px-2 py-0.5 text-xs " + cls(verdictTone(report.overall))}>+ {t(`service.doctor.overall.${report.overall}`)}+ </span>+ )}+ </div>++ {loading && !report && <p className="text-xs text-muted">{t("service.doctor.loading")}</p>}++ {failed && (+ <p data-testid="doctor-failed" className="text-xs text-muted">+ {t("service.doctor.failed")}+ <button type="button" data-testid="doctor-retry" onClick={() => void fetchDoctor()} className="ml-2 underline">+ {t("service.doctor.retry")}+ </button>+ </p>+ )}++ {report && (+ <ul className="space-y-1">+ {report.checks.map((c) => {+ const action = c.code ? ACTION_ROUTES[c.code] : undefined;+ return (+ <li key={c.id} data-testid={`doctor-item-${c.id}`} className="flex items-baseline gap-2 border-t border-line/60 py-1.5 text-xs first:border-t-0">+ <span className={"w-14 shrink-0 rounded-full px-1.5 py-0.5 text-center " + cls(verdictTone(c.verdict))}>+ {t(`service.doctor.verdict.${c.verdict}`)}+ </span>+ <span data-testid={`doctor-detail-${c.id}`} className="min-w-0 flex-1">+ <span className="text-muted">{c.id}</span> · {c.detail}+ {c.code && <span className="text-muted"> · {c.code}</span>}+ {c.next && <span className="block text-muted">{t("service.doctor.next")}: {c.next}</span>}+ </span>+ {action && (+ <a href={`#${action.to}`} data-testid={`doctor-action-${c.id}`} className="e0-btn e0-btn-secondary shrink-0">+ {t(action.labelKey)}+ </a>+ )}+ </li>+ );+ })}+ </ul>+ )}+ </section>+ );+}diff --git a/windows/app/src/service/panel.tsx b/windows/app/src/service/panel.tsxnew file mode 100644index 0000000..4f6eeb4--- /dev/null+++ b/windows/app/src/service/panel.tsx@@ -0,0 +1,112 @@+// service/panel.tsx — lifecycle panel. Skin boundaries: forwards existing commands only,+// reads measured fields only. This shell has no daemon token: loopback is access-exempt+// and stated as such. LAN = phase-2 placeholder row (kept visible, disabled + honest+// title).+import { useState, useSyncExternalStore } from "react";++import {+ engineStore,+ installedTiers,+ loadModel,+ shellStore,+ unloadModel,+} from "../api/client";+import { codeOf, errKey, t } from "../lib/t";++export function ServicePanel() {+ useSyncExternalStore(engineStore.sig.sub, engineStore.sig.version);+ useSyncExternalStore(shellStore.sig.sub, shellStore.sig.version);+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ const st = engineStore.status;+ const running = !!st?.running;+ const loading = engineStore.loadingTier !== null;+ const tiers = installedTiers();+ const pick = tiers.includes("8b") ? "8b" : tiers[0] ?? null;++ async function act(name: string, fn: () => Promise<unknown>) {+ setBusy(name);+ setError(null);+ try {+ await fn();+ } catch (e) {+ const s = String(e);+ setError(`${t(errKey(codeOf(s)))}${codeOf(s) ? ` · ${codeOf(s)}` : ""}`);+ } finally {+ setBusy(null);+ }+ }++ const inFlight = busy !== null || loading;++ return (+ <section className="e0-section overflow-hidden p-5" data-testid="svc-panel">+ <div className="mb-2 flex items-center justify-between">+ <h3 className="text-sm font-semibold">{t("service.panel.title")}</h3>+ <div className="flex items-center gap-2">+ {running ? (+ <button type="button" data-testid="svc-stop" disabled={inFlight} onClick={() => void act("stop", () => unloadModel())} className="e0-btn e0-btn-secondary">+ {t("service.panel.stop")}+ </button>+ ) : (+ <button+ type="button"+ data-testid="svc-start"+ disabled={inFlight || !pick}+ title={pick ? undefined : t("chat.noInstalledModel")}+ onClick={() => pick && void act("start", () => loadModel(pick))}+ className="rounded-full bg-accent px-3 py-1 text-xs font-medium text-accentink hover:opacity-90 disabled:opacity-50"+ >+ {loading ? t("models.loadingModel") : t("service.panel.start")}+ </button>+ )}+ </div>+ </div>++ {inFlight && (+ <p data-testid="svc-busy" className="mb-2 text-xs text-muted">{t("service.panel.busy")}</p>+ )}+ {error && (+ <p data-testid="svc-error" role="alert" className="mb-2 rounded-lg bg-err/10 px-3 py-2 text-xs text-err">{error}</p>+ )}++ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs" data-testid="svc-fields">+ <dt className="text-muted">{t("service.panel.port")}</dt>+ <dd data-testid="svc-port" className="tabular-nums">{st?.port ? `${st.bound}:${st.port}` : "—"}</dd>+ <dt className="text-muted">{t("service.panel.bind")}</dt>+ <dd data-testid="svc-bind">{st?.bound ?? "—"}</dd>+ <dt className="text-muted">{t("service.panel.scope")}</dt>+ <dd data-testid="svc-scope">{running ? t("sidebar.scopeShell") : "—"}</dd>+ <dt className="text-muted">{t("service.panel.tier")}</dt>+ <dd data-testid="svc-tier">{running ? st?.tier ?? "—" : "—"}</dd>+ <dt className="text-muted">{t("service.panel.pool")}</dt>+ <dd data-testid="svc-pool" className="tabular-nums">{running && st?.pool_mb ? `${st.pool_mb} MB` : "—"}</dd>+ <dt className="text-muted">{t("service.panel.uptime")}</dt>+ <dd data-testid="svc-uptime" className="tabular-nums">{running ? `${st?.uptime_s ?? 0}s` : "—"}</dd>+ <dt className="text-muted">{t("service.panel.version")}</dt>+ <dd data-testid="svc-version">{st?.version ?? "—"}</dd>+ <dt className="text-muted">{t("service.panel.governance")}</dt>+ <dd data-testid="svc-governance" className={running && !st?.job ? "text-warn" : ""}>+ {running ? (st?.job ? t("service.panel.governanceJob") : t("service.panel.governanceSoft")) : "—"}+ </dd>+ <dt className="text-muted">{t("service.panel.home")}</dt>+ <dd data-testid="svc-home" className="break-all">{shellStore.paths.home || "—"}</dd>+ </dl>++ {/* token row: loopback direct access needs no credential — the fact, stated plainly (no mask, no copy button) */}+ <div className="mt-3 flex items-center gap-2 text-xs" data-testid="svc-token-row">+ <span className="text-muted">{t("service.panel.token")}</span>+ <span data-testid="svc-token-none">{t("service.panel.noCredential")}</span>+ </div>++ {/* LAN toggle: phase-2 placeholder — row kept visible, disabled + honest title */}+ <div className="mt-3 flex items-center justify-between border-t border-line pt-3 text-xs" data-testid="svc-lan-row">+ <span className="text-muted">{t("service.panel.lan")}</span>+ <button type="button" role="switch" aria-checked={false} data-testid="svc-lan-switch" disabled title={t("service.panel.lanLater")} className="e0-btn e0-btn-secondary disabled:opacity-50">+ {t("service.panel.lanOff")}+ </button>+ </div>+ </section>+ );+}diff --git a/windows/app/src/service/reqlog.tsx b/windows/app/src/service/reqlog.tsxnew file mode 100644index 0000000..d23bd15--- /dev/null+++ b/windows/app/src/service/reqlog.tsx@@ -0,0 +1,70 @@+// service/reqlog.tsx — request log table. Data source = frontend-measured generation+// requests (useThreadChat writes into the reqLog ring): since app start, in memory,+// cleared on exit — labeled honestly in the section header.+import { useSyncExternalStore } from "react";++import { reqLog, type ReqRow } from "../api/client";+import { t } from "../lib/t";++export function statusTone(status: ReqRow["status"]): "ok" | "warn" | "err" {+ if (status === "done") return "ok";+ if (status === "error") return "err";+ return "warn";+}++export function RequestLogSection() {+ useSyncExternalStore(reqLog.sig.sub, reqLog.sig.version);+ const rows = reqLog.rows;+ return (+ <section className="e0-section overflow-hidden p-5" data-testid="svc-log">+ <div className="mb-1 flex items-baseline justify-between">+ <h3 className="text-sm font-semibold">{t("service.log.title")}</h3>+ <span data-testid="svc-log-count" className="text-xs text-muted tabular-nums">+ {t("service.log.count", { n: rows.length })}+ </span>+ </div>+ <p data-testid="svc-log-note" className="mb-2 text-xs text-muted">{t("service.log.note")}</p>+ {rows.length === 0 ? (+ <p data-testid="svc-log-empty" className="text-xs text-muted">{t("service.log.empty")}</p>+ ) : (+ <table className="w-full text-xs">+ <thead>+ <tr className="text-left text-muted">+ <th className="py-1 pr-2 font-normal">{t("service.log.th.status")}</th>+ <th className="py-1 pr-2 font-normal">{t("service.log.th.model")}</th>+ <th className="py-1 pr-2 font-normal">{t("service.log.th.latency")}</th>+ <th className="py-1 pr-2 font-normal">{t("service.log.th.tokens")}</th>+ <th className="py-1 font-normal">{t("service.log.th.source")}</th>+ </tr>+ </thead>+ <tbody>+ {rows.map((r, i) => {+ const tone = statusTone(r.status);+ return (+ <tr key={`${r.ts}-${i}`} data-testid={`svc-log-row-${i}`} className="border-t border-line/60">+ <td className="py-1 pr-2">+ <span className="flex items-center gap-1">+ <span+ className={"inline-block size-2 rounded-full " + (tone === "ok" ? "bg-accent" : tone === "err" ? "bg-err" : "bg-warn")}+ aria-hidden+ />+ {t(`service.log.status.${r.status}`)}+ {r.code && <span className="text-muted">{r.code}</span>}+ </span>+ <span className="ml-1 text-[10px] text-muted tabular-nums">+ {new Date(r.ts).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })}+ </span>+ </td>+ <td className="py-1 pr-2">{r.model || "—"}</td>+ <td className="py-1 pr-2 tabular-nums">{r.latencyMs}ms</td>+ <td className="py-1 pr-2 tabular-nums">{r.tokens ?? "—"}</td>+ <td className="py-1">{t("service.log.source.loopback")}</td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ </section>+ );+}diff --git a/windows/app/src/state/threads.ts b/windows/app/src/state/threads.tsnew file mode 100644index 0000000..8625e9d--- /dev/null+++ b/windows/app/src/state/threads.ts@@ -0,0 +1,144 @@+// state/threads.ts — localStorage-backed thread store (message/row shape mirrors a+// typical chat thread store). A SQLite thread store would be a phase-2 drop-in:+// this layer can be replaced wholesale without touching the UI.+export type MsgUsage = { prompt_tokens: number; completion_tokens: number; total_tokens: number };+export type MsgPerf = { decode_tps?: number; prefill_tps?: number; prompt_ms?: number };+export type MsgMeta = {+ status?: "done" | "aborted" | "error";+ usage?: MsgUsage; perf?: MsgPerf; code?: string | null;+};+export type ThreadMsg = {+ id: string; role: "user" | "assistant"; content: string;+ reasoning?: string; created_at: number; meta?: MsgMeta;+ streaming?: boolean; // in-session transient (stripped before persisting; always false on load)+};+export type ThreadRow = {+ id: string;+ data: { title: string; model: string | null };+ updatedAt: number;+ messages: ThreadMsg[];+};++const STORE_KEY = "edge0.threads.v2";+const ACTIVE_KEY = "edge0.active-thread";++function uid(): string {+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;+}++class ThreadStore {+ private rows: ThreadRow[] = [];+ private ver = 0;+ activeId: string | null = null;+ private listeners = new Set<() => void>();+ private persistTimer: ReturnType<typeof setTimeout> | null = null;+ private loaded = false;++ load(): void {+ if (this.loaded) return;+ this.loaded = true;+ try {+ this.rows = (JSON.parse(localStorage.getItem(STORE_KEY) ?? "[]") as ThreadRow[])+ .map((r) => ({+ ...r,+ // converge crash residue: a trailing assistant message without terminal meta means generation was interrupted -> mark aborted+ messages: (() => {+ const ms = r.messages.map((m) => ({ ...m, streaming: false }));+ const last = ms[ms.length - 1];+ if (last && last.role === "assistant" && !last.meta?.status) {+ ms[ms.length - 1] = { ...last, meta: { ...last.meta, status: "aborted" } };+ }+ return ms;+ })(),+ }));+ } catch {+ this.rows = []; // drop a corrupt cache (never crash startup)+ }+ const a = localStorage.getItem(ACTIVE_KEY);+ this.activeId = a && this.rows.some((r) => r.id === a) ? a : null;+ }++ subscribe = (cb: () => void): (() => void) => {+ this.listeners.add(cb);+ return () => { this.listeners.delete(cb); };+ };++ /** snapshot = version number (stable source for useSyncExternalStore; get rows via snapshot()). */+ version(): number {+ return this.ver;+ }++ threads(): ThreadRow[] {+ return this.rows;+ }++ private emit(): void {+ this.ver++;+ for (const l of [...this.listeners]) l();+ if (this.persistTimer) clearTimeout(this.persistTimer);+ this.persistTimer = setTimeout(() => {+ try {+ localStorage.setItem(STORE_KEY, JSON.stringify(+ this.rows.map((r) => ({ ...r, messages: r.messages.map((m) => {+ const { streaming: _s, ...rest } = m;+ return rest;+ }) })),+ ));+ } catch { /* quota exceeded: skip the write (UI must not crash) */ }+ }, 400);+ }++ /** refresh() compat shim kept from the original API shape (this implementation is always in sync). */+ async refresh(): Promise<void> {+ this.load();+ this.emit();+ }++ create(title: string, model: string | null): ThreadRow {+ this.load();+ const row: ThreadRow = { id: uid(), data: { title, model }, updatedAt: Date.now(), messages: [] };+ this.rows = [row, ...this.rows];+ this.activeId = row.id;+ localStorage.setItem(ACTIVE_KEY, row.id);+ this.emit();+ return row;+ }++ rename(id: string, title: string): void {+ this.rows = this.rows.map((r) => (r.id === id ? { ...r, data: { ...r.data, title }, updatedAt: Date.now() } : r));+ this.emit();+ }++ remove(id: string): void {+ this.rows = this.rows.filter((r) => r.id !== id);+ if (this.activeId === id) this.setActive(null);+ this.emit();+ }++ setActive(id: string | null): void {+ this.activeId = id;+ if (id) localStorage.setItem(ACTIVE_KEY, id);+ else localStorage.removeItem(ACTIVE_KEY);+ this.emit();+ }++ setModel(id: string, model: string): void {+ this.rows = this.rows.map((r) => (r.id === id ? { ...r, data: { ...r.data, model } } : r));+ this.emit();+ }++ messages(id: string): ThreadMsg[] {+ return this.rows.find((r) => r.id === id)?.messages ?? [];+ }++ /** Single entry point for message-list mutations (updatedAt written along). */+ patchMessages(id: string, fn: (msgs: ThreadMsg[]) => ThreadMsg[]): void {+ this.rows = this.rows.map((r) =>+ r.id === id ? { ...r, updatedAt: Date.now(), messages: fn(r.messages) } : r,+ );+ this.emit();+ }+}++export const threadStore = new ThreadStore();+threadStore.load();diff --git a/windows/app/src/styles.css b/windows/app/src/styles.cssnew file mode 100644index 0000000..06d8b35--- /dev/null+++ b/windows/app/src/styles.css@@ -0,0 +1,485 @@+@import "tailwindcss";+@plugin "@tailwindcss/typography";++/* Dark mode does not use prefers-color-scheme: the shell is the single source of truth+ (in "follow system" mode, JS resolves it and writes data-theme). */+@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));++:root {+ --e0-app: #f3f4f6;+ --e0-surface: #ffffff;+ --e0-surface-2: #f7f7f8;+ --e0-sidebar: #eceef1;+ --e0-text: #181a1f;+ --e0-muted: #70747d;+ --e0-border: #dfe2e7;+ --e0-accent: #2f6feb;+ --e0-accent-ink: #ffffff;+ --e0-ok: #168052;+ --e0-warn: #a66700;+ --e0-err: #c53636;+ --e0-focus: #2f6feb;+ --e0-shadow: 0 12px 36px rgba(29, 34, 43, 0.08);+ --e0-radius-lg: 18px;+ --e0-radius-md: 12px;+}+[data-theme="dark"] {+ --e0-app: #111317;+ --e0-surface: #181b20;+ --e0-surface-2: #20242a;+ --e0-sidebar: #1b1e24;+ --e0-text: #f1f3f5;+ --e0-muted: #a2a8b2;+ --e0-border: #30353d;+ --e0-accent: #6ea3ff;+ --e0-accent-ink: #111317;+ --e0-ok: #55d69a;+ --e0-warn: #efb456;+ --e0-err: #ff8585;+ --e0-focus: #8bb5ff;+ --e0-shadow: 0 16px 42px rgba(0, 0, 0, 0.28);+}++/* Three font-size tiers: the whole tree scales via rem. */+html[data-font="sm"] { font-size: 14px; }+html[data-font="md"] { font-size: 16px; }+html[data-font="lg"] { font-size: 18px; }++@theme inline {+ --color-app: var(--e0-app);+ --color-surface: var(--e0-surface);+ --color-surface2: var(--e0-surface-2);+ --color-sidebar: var(--e0-sidebar);+ --color-fg: var(--e0-text);+ --color-muted: var(--e0-muted);+ --color-line: var(--e0-border);+ --color-accent: var(--e0-accent);+ --color-accentink: var(--e0-accent-ink);+ --color-ok: var(--e0-ok);+ --color-warn: var(--e0-warn);+ --color-err: var(--e0-err);+}++body {+ @apply bg-app text-fg antialiased;+ margin: 0;+ min-width: 320px;+ font-family: ui-sans-serif, system-ui, "Segoe UI", "Microsoft YaHei", sans-serif;+}++button,+input,+textarea,+select {+ font: inherit;+}++button,+a,+input,+textarea,+select {+ -webkit-tap-highlight-color: transparent;+}++button:focus-visible,+a:focus-visible,+input:focus-visible,+textarea:focus-visible,+select:focus-visible {+ outline: 2px solid var(--e0-focus);+ outline-offset: 2px;+}++/* The composer focus state is expressed by the shell's focus-within; suppress the inner+ textarea's square outline. Kept unlayered: unlayered author styles beat Tailwind utilities. */+.e0-composer-shell textarea:focus-visible {+ outline: none;+}++@layer components {+ .e0-app-shell {+ display: flex;+ gap: 12px;+ height: 100vh;+ min-height: 0;+ max-height: 100vh;+ padding: 12px;+ background: var(--e0-app);+ box-sizing: border-box;+ overflow: hidden;+ }++ .e0-sidebar {+ position: relative;+ z-index: 30;+ display: flex;+ width: 258px;+ height: 100%;+ flex: 0 0 258px;+ flex-direction: column;+ overflow: hidden;+ border: 1px solid var(--e0-border);+ border-radius: var(--e0-radius-lg);+ background: var(--e0-sidebar);+ box-shadow: var(--e0-shadow);+ }++ .e0-main-frame {+ position: relative;+ height: 100%;+ min-width: 0;+ min-height: 0;+ flex: 1;+ overflow: hidden;+ border: 1px solid var(--e0-border);+ border-radius: var(--e0-radius-lg);+ background: var(--e0-surface);+ box-shadow: var(--e0-shadow);+ }++ .e0-page {+ width: min(100%, 980px);+ margin: 0 auto;+ padding: 34px clamp(20px, 4vw, 56px) 44px;+ }++ .e0-page-header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ margin-bottom: 28px;+ }++ .e0-page-title {+ margin: 0;+ font-size: 1.35rem;+ font-weight: 650;+ letter-spacing: -0.01em;+ }++ .e0-page-kicker {+ margin: 5px 0 0;+ color: var(--e0-muted);+ font-size: 0.8rem;+ line-height: 1.5;+ }++ .e0-section {+ border: 1px solid var(--e0-border);+ border-radius: var(--e0-radius-md);+ background: var(--e0-surface);+ box-shadow: 0 4px 16px rgba(29, 34, 43, 0.04);+ }++ .e0-section-header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ padding: 18px 20px 12px;+ }++ .e0-section-title {+ margin: 0;+ font-size: 0.9rem;+ font-weight: 650;+ }++ .e0-section-note {+ margin: 4px 0 0;+ color: var(--e0-muted);+ font-size: 0.75rem;+ line-height: 1.5;+ }++ .e0-btn {+ display: inline-flex;+ min-height: 32px;+ align-items: center;+ justify-content: center;+ gap: 7px;+ border: 1px solid transparent;+ border-radius: 999px;+ padding: 0 13px;+ font-size: 0.75rem;+ font-weight: 600;+ transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease, opacity 140ms ease;+ }++ .e0-btn:disabled {+ cursor: not-allowed;+ opacity: 0.48;+ }++ .e0-btn-primary {+ background: var(--e0-accent);+ color: var(--e0-accent-ink);+ }++ .e0-btn-primary:hover:not(:disabled) {+ filter: brightness(0.96);+ }++ .e0-btn-secondary {+ border-color: var(--e0-border);+ background: var(--e0-surface);+ color: var(--e0-text);+ }++ .e0-btn-secondary:hover:not(:disabled),+ .e0-btn-ghost:hover:not(:disabled) {+ background: var(--e0-surface-2);+ }++ .e0-btn-ghost {+ color: var(--e0-muted);+ }++ .e0-btn-danger {+ border-color: color-mix(in srgb, var(--e0-err) 35%, var(--e0-border));+ color: var(--e0-err);+ }++ .e0-icon-btn {+ display: inline-grid;+ width: 32px;+ height: 32px;+ place-items: center;+ border-radius: 10px;+ color: var(--e0-muted);+ transition: background-color 140ms ease, color 140ms ease;+ }++ .e0-icon-btn:hover {+ background: color-mix(in srgb, var(--e0-text) 8%, transparent);+ color: var(--e0-text);+ }++ .e0-status {+ display: inline-flex;+ min-height: 24px;+ align-items: center;+ gap: 6px;+ border-radius: 999px;+ padding: 0 9px;+ font-size: 0.7rem;+ font-weight: 600;+ }++ .e0-status-ok { background: color-mix(in srgb, var(--e0-ok) 13%, transparent); color: var(--e0-ok); }+ .e0-status-warn { background: color-mix(in srgb, var(--e0-warn) 14%, transparent); color: var(--e0-warn); }+ .e0-status-err { background: color-mix(in srgb, var(--e0-err) 13%, transparent); color: var(--e0-err); }++ .e0-toggle-group {+ display: inline-flex;+ gap: 2px;+ border: 1px solid var(--e0-border);+ border-radius: 999px;+ padding: 3px;+ background: var(--e0-surface-2);+ }++ .e0-toggle {+ border-radius: 999px;+ padding: 5px 9px;+ color: var(--e0-muted);+ font-size: 0.7rem;+ font-weight: 600;+ }++ .e0-toggle[data-state="on"] {+ background: var(--e0-accent);+ color: var(--e0-accent-ink);+ }++ .e0-divider {+ border-top: 1px solid color-mix(in srgb, var(--e0-border) 72%, transparent);+ }++ .e0-mobile-toggle {+ display: none;+ }++ .e0-chat-header {+ display: flex;+ min-height: 58px;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ border-bottom: 1px solid color-mix(in srgb, var(--e0-border) 72%, transparent);+ padding: 0 28px;+ }++ .e0-chat-header-title {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 0.8rem;+ font-weight: 650;+ }++ .e0-chat-header-meta {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ color: var(--e0-muted);+ font-size: 0.7rem;+ }++ .e0-chat-empty {+ display: grid;+ min-height: 100%;+ place-content: center;+ gap: 8px;+ padding: 32px;+ text-align: center;+ }++ .e0-chat-column {+ width: min(100%, 760px);+ margin: 0 auto;+ }++ .e0-composer {+ padding: 12px 22px 20px;+ }++ .e0-composer-shell {+ width: min(100%, 760px);+ margin: 0 auto;+ overflow: visible;+ border: 1px solid var(--e0-border);+ border-radius: 20px;+ background: var(--e0-surface);+ box-shadow: 0 10px 28px rgba(29, 34, 43, 0.09);+ transition: border-color 140ms ease, box-shadow 140ms ease;+ }++ .e0-composer-shell:focus-within {+ border-color: color-mix(in srgb, var(--e0-accent) 55%, var(--e0-border));+ box-shadow: 0 10px 30px color-mix(in srgb, var(--e0-accent) 13%, transparent);+ }++ .e0-composer-textarea {+ min-height: 82px;+ max-height: 220px;+ padding: 17px 18px 8px;+ line-height: 1.5;+ }++ .e0-composer-toolbar {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: 8px;+ padding: 6px 10px 10px;+ }++ .e0-send-btn {+ display: inline-grid;+ width: 34px;+ height: 34px;+ flex: 0 0 auto;+ place-items: center;+ border-radius: 999px;+ background: var(--e0-accent);+ color: var(--e0-accent-ink);+ transition: transform 140ms ease, opacity 140ms ease;+ }++ .e0-send-btn:hover:not(:disabled) {+ transform: translateY(-1px);+ }++ .e0-send-btn:disabled {+ cursor: not-allowed;+ opacity: 0.38;+ }++ /* Prose colors follow the design tokens (the typography plugin's default gray is too bright on the near-black background) */+ .e0-prose {+ --tw-prose-body: var(--e0-text);+ --tw-prose-headings: var(--e0-text);+ --tw-prose-bold: var(--e0-text);+ --tw-prose-links: var(--e0-accent);+ --tw-prose-code: var(--e0-text);+ --tw-prose-quotes: var(--e0-text);+ --tw-prose-quote-borders: var(--e0-border);+ --tw-prose-bullets: var(--e0-muted);+ --tw-prose-hr: var(--e0-border);+ --tw-prose-th-borders: var(--e0-border);+ --tw-prose-td-borders: var(--e0-border);+ }+}++@media (max-width: 760px) {+ .e0-app-shell {+ display: block;+ padding: 0;+ }++ .e0-sidebar {+ position: fixed;+ inset: 10px auto 10px 10px;+ width: min(280px, calc(100vw - 28px));+ transform: translateX(calc(-100% - 20px));+ transition: transform 180ms ease;+ }++ .e0-sidebar.e0-sidebar-open {+ transform: translateX(0);+ }++ .e0-sidebar-backdrop {+ position: fixed;+ z-index: 20;+ inset: 0;+ background: rgba(13, 17, 23, 0.34);+ }++ .e0-main-frame {+ height: 100vh;+ min-height: 100vh;+ border: 0;+ border-radius: 0;+ }++ .e0-mobile-toggle {+ display: inline-grid;+ }++ .e0-page {+ padding: 26px 16px 32px;+ }++ .e0-page-header {+ align-items: center;+ margin-bottom: 22px;+ }++ .e0-chat-header {+ min-height: 54px;+ padding: 0 16px 0 58px;+ }++ .e0-chat-column {+ width: 100%;+ }++ .e0-composer {+ padding: 10px 12px 14px;+ }+}++@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ scroll-behavior: auto !important;+ transition-duration: 0.01ms !important;+ animation-duration: 0.01ms !important;+ }+}diff --git a/windows/app/src/vite-env.d.ts b/windows/app/src/vite-env.d.tsnew file mode 100644index 0000000..39fc679--- /dev/null+++ b/windows/app/src/vite-env.d.ts@@ -0,0 +1,3 @@+/// <reference types="vite/client" />++declare module "*.css";diff --git a/windows/app/tsconfig.json b/windows/app/tsconfig.jsonnew file mode 100644index 0000000..08ff715--- /dev/null+++ b/windows/app/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "react-jsx",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "isolatedModules": true,+ "resolveJsonModule": true+ },+ "include": ["src"]+}diff --git a/windows/app/vite.config.ts b/windows/app/vite.config.tsnew file mode 100644index 0000000..0dd5c55--- /dev/null+++ b/windows/app/vite.config.ts@@ -0,0 +1,12 @@+import react from "@vitejs/plugin-react";+import tailwindcss from "@tailwindcss/vite";+import { defineConfig } from "vite";++// Tauri expects a fixed dev port on loopback; fail fast if it is taken.+export default defineConfig({+ plugins: [react(), tailwindcss()],+ clearScreen: false,+ server: { port: 1420, strictPort: true, host: "127.0.0.1" },+ envPrefix: ["VITE_", "TAURI_"],+ build: { target: "es2022", sourcemap: false },+});diff --git a/windows/scripts/vendor-build.ps1 b/windows/scripts/vendor-build.ps1new file mode 100644index 0000000..0d55340--- /dev/null+++ b/windows/scripts/vendor-build.ps1@@ -0,0 +1,88 @@+# scripts/vendor-build.ps1 — llama engine assembly for the Windows product (monorepo layout)+# The pristine upstream tree (../vendor/llama.cpp, pinned commit) is NEVER patched in place:+# this script replays the patch bands into an isolated build worktree (../wt/win), copies the+# edge0 serving pieces from serve/ into src/edge0 (patch #3's CMake glob compiles them into+# the llama target), then configures and builds with Vulkan.+# The vendor tree is submodule-free: it is MATERIALIZED on first run by cloning upstream at+# the pinned commit listed in vendor.llama.pin (repo root); afterwards it is just a checkout.+# Depot resolution (first match wins):+# A. $env:EDGE0_DEPOT explicit override+# B. parent directory containing vendor.llama.pin monorepo checkout (the normal path)+# If neither matches, stop and explain — run from a full monorepo clone, or point+# EDGE0_DEPOT at a depot that carries vendor.llama.pin.+# Set EDGE0_LLAMA_URL to clone from a mirror instead of GitHub.+# Usage: pwsh -File scripts/vendor-build.ps1 [-BuildDir build-vk] [-AssembleOnly]+# -AssembleOnly = stages 1-3 only (checks + patch replay + serve copy), no compile.+param(+ [string]$BuildDir = "build-vk",+ [switch]$Clean,+ [switch]$AssembleOnly+)+$ErrorActionPreference = "Stop"+$ROOT = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)++$DEPOT = if ($env:EDGE0_DEPOT) { $env:EDGE0_DEPOT } else {+ $parent = Split-Path -Parent $ROOT+ if (Test-Path (Join-Path $parent "vendor.llama.pin")) { $parent } else { $null }+}+if (-not $DEPOT) { throw "no depot: set EDGE0_DEPOT to a tree carrying vendor.llama.pin (the monorepo root), or run inside a full monorepo clone" }+$PINFILE = Join-Path $DEPOT "vendor.llama.pin"+if (-not (Test-Path $PINFILE)) { throw "vendor.llama.pin missing in depot $DEPOT" }+$PIN = (Get-Content $PINFILE -Raw).Trim().Split(" ")[0] # pinned upstream commit (tag b11100) — ledger: patches/llama.cpp/README.md+$VENDOR = Join-Path $DEPOT "vendor/llama.cpp"+$WT = Join-Path $DEPOT "wt/win"+# Patch bands resolve from the depot root ONLY — one source of truth. The old in-repo+# windows/patches/ mirror was retired 2026-09-30 (a drifting copy; depot carries the bands).+$PDIR = Join-Path $DEPOT "patches/llama.cpp"+if (-not (Test-Path (Join-Path $PDIR "common"))) { throw "patch bands missing at $PDIR/common — run inside the monorepo or point EDGE0_DEPOT at a depot carrying patches/llama.cpp" }+$BANDS = @("common", "windows") | ForEach-Object { Join-Path $PDIR "$_/*.patch" }++# Materialize the pinned tree when absent (submodule-free supply).+if (-not (Test-Path (Join-Path $VENDOR ".git"))) {+ Write-Host "[0/4] materializing vendor: clone llama.cpp at pinned $PIN -> $VENDOR" -ForegroundColor Cyan+ New-Item -ItemType Directory -Force (Split-Path $VENDOR) | Out-Null+ $LLAMA_URL = if ($env:EDGE0_LLAMA_URL) { $env:EDGE0_LLAMA_URL } else { "https://github.com/ggml-org/llama.cpp" }+ git clone --filter=blob:none $LLAMA_URL $VENDOR+ if ($LASTEXITCODE -ne 0) { throw "clone failed ($LLAMA_URL) — network? or set EDGE0_LLAMA_URL / EDGE0_DEPOT" }+ git -C $VENDOR checkout --detach $PIN+ if ($LASTEXITCODE -ne 0) { throw "pinned commit $PIN not found upstream (refresh the patch ledger)" }+}++Push-Location $VENDOR+try {+ Write-Host "[1/4] checking pristine vendor tree (must sit exactly at the pin, zero local changes)" -ForegroundColor Cyan+ $head = (git rev-parse HEAD).Trim()+ if (-not $head.StartsWith($PIN)) { throw "vendor HEAD=$head is not the pinned $PIN — the pristine tree must never be patched in place; restore with: git checkout --detach $PIN" }+ if ((git status --porcelain).Length -gt 0) { throw "vendor worktree is dirty — the pristine source of truth tolerates no local edits" }++ Write-Host "[2/4] (re)creating build worktree $WT and replaying patch bands" -ForegroundColor Cyan+ if (-not (Test-Path $WT)) { git worktree add --detach $WT $PIN | Out-Null }+ # Unconditional reset before replay = idempotent+ git -C $WT reset --hard $PIN 2>&1 | Out-Null+ git -C $WT clean -fd src/edge0 tools/llama-bench 2>&1 | Out-Null+ Set-Location $WT+ foreach ($pat in $BANDS) {+ Get-ChildItem $pat | Sort-Object Name | ForEach-Object {+ Write-Host " am $($_.Name)"+ git am --3way $_.FullName+ if ($LASTEXITCODE -ne 0) { throw "git am failed at $($_.Name) (upstream drift or band conflict — three-way by hand, see patches/llama.cpp/README.md)" }+ }+ }++ Write-Host "[3/4] copying serve/ pieces -> src/edge0/ (compiled in via patch #3 glob)" -ForegroundColor Cyan+ New-Item -ItemType Directory -Force (Join-Path $WT "src/edge0") | Out-Null+ Copy-Item (Join-Path $ROOT "serve/*.cc") (Join-Path $WT "src/edge0/") -Force -ErrorAction SilentlyContinue+ Copy-Item (Join-Path $ROOT "serve/*.h") (Join-Path $WT "src/edge0/") -Force -ErrorAction SilentlyContinue+ if ($AssembleOnly) {+ Write-Host "OK(assemble-only): worktree=$WT — patches replayed, serving pieces copied" -ForegroundColor Green+ return+ }++ Write-Host "[4/4] configure + build (Release/Vulkan)" -ForegroundColor Cyan+ $bd = Join-Path $WT $BuildDir+ cmake -S $WT -B $bd -DGGML_VULKAN=ON -DCMAKE_BUILD_TYPE=Release+ cmake --build $bd --config Release+ Write-Host "OK: $bd/bin/Release/llama-server.exe" -ForegroundColor Green+} finally {+ Pop-Location+}diff --git a/windows/serve/mem_budget.cc b/windows/serve/mem_budget.ccnew file mode 100644index 0000000..bc96226--- /dev/null+++ b/windows/serve/mem_budget.cc@@ -0,0 +1,38 @@+// serve/mem_budget.cc — process memory budget (hard working-set cap on Windows).+// Semantics: budget = N MB ⇒ resident set is capped at N; beyond that the OS evicts+// our pages (mmap'd model-file pages first, so the next touch faults a real re-read).+// This is the direct implementation of the low-RAM product tiers (8 GB / 16 GB machines).+#include "mem_budget.h"++#define WIN32_LEAN_AND_MEAN+#include <windows.h>++#include <cstdio>+#include <cstdlib>++E0_MB_API bool edge0_apply_mem_budget(int mb) {+ if (mb <= 0) { // debug-compat env fallback+ const char * e = getenv("E0_MEM_BUDGET_MB");+ if (e && *e) mb = (int) atol(e);+ }+ if (mb <= 0) return false;++ const SIZE_T budget = (SIZE_T) mb * 1024 * 1024;+ SIZE_T cur_min = 0, cur_max = 0; DWORD cur_flags = 0;+ SIZE_T want_min = budget / 8; // soft floor = 12.5%: a residency base so the OS doesn't evict everything+ if (GetProcessWorkingSetSizeEx(GetCurrentProcess(), &cur_min, &cur_max, &cur_flags) && cur_max) {+ if (want_min > cur_min) want_min = cur_min < budget ? cur_min : budget; // never raise the original minimum+ }+ // max working set = hard cap: the OS trims immediately on overflow (unlike the+ // default ~1.5 TB soft limit, which only trims under global memory pressure)+ if (!SetProcessWorkingSetSizeEx(GetCurrentProcess(), want_min, budget,+ QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_ENABLE)) {+ fprintf(stderr, "[mem-budget] SetProcessWorkingSetSizeEx failed err=%lu (budget %dMB NOT applied)\n",+ GetLastError(), mb);+ return false;+ }+ fprintf(stderr, "[mem-budget] applied: max working set = %d MB (min %llu MB, hard-trim on)\n",+ mb, (unsigned long long) (want_min / (1024 * 1024)));+ fflush(stderr);+ return true;+}diff --git a/windows/serve/mem_budget.h b/windows/serve/mem_budget.hnew file mode 100644index 0000000..c03627a--- /dev/null+++ b/windows/serve/mem_budget.h@@ -0,0 +1,14 @@+// serve/mem_budget.h — process memory budget (first-class product feature).+// Independent of the prefetch router: it only caps physical residency; no prediction.+#pragma once+#ifdef _WIN32+# define E0_MB_API __declspec(dllexport)+#else+# define E0_MB_API __attribute__((visibility("default")))+#endif++// Primary channel: CLI flag (--mem-budget-mb → mb > 0); when mb <= 0, falls back to+// the E0_MEM_BUDGET_MB env var (debug compat). mb > 0 pins this process's maximum+// working set to that size — the OS then evicts pages beyond the cap, so cold model+// reads genuinely occur. Returns whether the cap was applied.+E0_MB_API bool edge0_apply_mem_budget(int mb);diff --git a/windows/serve/prefetch.cc b/windows/serve/prefetch.ccnew file mode 100644index 0000000..6aeec2c--- /dev/null+++ b/windows/serve/prefetch.cc@@ -0,0 +1,854 @@+// serve/prefetch.cc — advisory expert-prefetch router + self-managed L1 pool + accounting.+// Depends only on llama public/near-public APIs (declared inline, linked from llama.lib)+// and parses GGUF/safetensors headers by hand; llama internal headers are not touched.+// The real routing gate is never modified: predictions only warm the page cache. A wrong+// prediction costs latency, never quality.+// Three-way overlap accounting (printed as [pref-trace]):+// head = pred@t-1 ∩ teacher@t teacher = host-side recompute of gate·m_in (gate is F32 in our GGUF)+// sticky = teacher@t-1 ∩ teacher@t (the free win the OS page-cache LRU already provides)+// random = uniform sample of K ∩ teacher@t (popularity floor)+#include "prefetch.h"++#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#include <psapi.h>++#include <atomic>+#include <chrono>+#include <cmath>+#include <condition_variable>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <map>+#include <mutex>+#include <string>+#include <thread>+#include <vector>++// Near-public staging API (src/llama-ext.h). NOTE: that header has **no extern "C"+// wrapper** — its symbols are C++-decorated, so you must include the real header rather+// than hand-write declarations. This unit is globbed into the llama target by the patch+// band (patches/llama.cpp/common #3), which puts src/ on the PRIVATE include path;+// llama.h is reachable via ../include PUBLIC.+#include "llama.h"+#include "llama-ext.h"+++namespace {++// Pool final telemetry (defined in the pool section below) — fwd-declared for ~Pref.+static void e0_pool_trace_final();++// ── Shapes (pinned for the 35B GGUF: E=256, H=2048, feat=2560, K=4, owners 6..38 → consumers 7..39) ──+constexpr int EK = 256, HH = 2048, FE = 2560, KDIM = 4, NH = 33;+constexpr int OWNER0 = 6; // first owner+std::vector<int> consumers; // 7..39++// ── GGUF/safetensors header parsing ──+std::string rd_str(FILE * f) {+ uint64_t n = 0;+ if (fread(&n, 8, 1, f) != 1) return {};+ std::string s((size_t) n, '\0');+ if (n && fread(s.data(), 1, (size_t) n, f) != n) return {};+ return s;+}+struct GGUFType { uint32_t t; };+size_t align_up(size_t x, size_t a) { return (x + a - 1) / a * a; }+// GGUF KV value types: 0u8 1i8 2u16 3i16 4u32 5i32 6f32 7bool 8str 9arr 10u64 11i64 12f64+size_t scalar_size(uint32_t t) { static const size_t s[] = {1,1,2,2,4,4,4,1,0,0,8,8,8}; return t <= 12 ? s[t] : 0; }+void skip_val(FILE * f, uint32_t t) {+ if (t == 8) { rd_str(f); return; }+ if (t == 9) {+ uint32_t et; uint64_t n;+ if (fread(&et, 4, 1, f) != 1 || fread(&n, 8, 1, f) != 1) return;+ for (uint64_t i = 0; i < n; ++i) skip_val(f, et);+ return;+ }+ size_t s = scalar_size(t);+ if (s) fseek(f, (long) s, SEEK_CUR);+}+// Tensor dtype uses the GGML_TYPE enum: 0=F32 1=F16 2=BF16 3=Q4_1 (NOT the GGUF KV enum — don't mix).+bool is_q4_1(uint32_t t) { return t == 3; }+size_t plain_esz(uint32_t t) { return t == 0 ? 4 : (t == 1 || t == 2) ? 2 : 0; }++struct TT {+ std::string name;+ uint32_t type = 0;+ uint64_t dim[4] = {1, 1, 1, 1};+ uint64_t off = 0;+};+size_t tt_bytes(const TT & x) {+ size_t n = 1;+ for (int i = 0; i < 4; ++i) n *= (size_t) x.dim[i];+ if (is_q4_1(x.type)) return (size_t) x.dim[1] * x.dim[2] * x.dim[3] * ((size_t) x.dim[0] / 32) * 20;+ return n * plain_esz(x.type);+}++// IEEE half → float (subnormals included)+float f16_to_f32(uint16_t h) {+ uint32_t sign = (uint32_t) (h & 0x8000) << 16;+ uint32_t e = (h >> 10) & 0x1F, m = h & 0x3FF;+ uint32_t bits;+ if (e == 0) {+ if (m == 0) bits = sign;+ else { // subnormal: renormalize+ e = 127 - 15 + 1;+ while (!(m & 0x400)) { m <<= 1; e--; }+ m &= 0x3FF;+ bits = sign | (e << 23) | (m << 13);+ }+ } else if (e == 0x1F) {+ bits = sign | 0x7F800000u | (m << 13);+ } else {+ bits = sign | ((e + 127 - 15) << 23) | (m << 13);+ }+ float r;+ memcpy(&r, &bits, 4);+ return r;+}++// safetensors: { "<key>": {"dtype":"F16","shape":[..],"data_offsets":[a,b]} }+struct SEnt { long long a = -1, b = -1; std::vector<long long> shape; };+bool st_load(const char * path, std::map<std::string, SEnt> & out) {+ FILE * f = fopen(path, "rb");+ if (!f) return false;+ uint64_t hn = 0;+ if (fread(&hn, 8, 1, f) != 1) { fclose(f); return false; }+ std::string hdr((size_t) hn, '\0');+ bool ok = fread(hdr.data(), 1, (size_t) hn, f) == hn;+ fclose(f);+ if (!ok) return false;+ size_t i = 0;+ while ((i = hdr.find("\"layers.", i)) != std::string::npos) {+ size_t ke = hdr.find("\":", i + 1);+ size_t vo = hdr.find('{', ke);+ size_t vc = ke == std::string::npos || vo == std::string::npos ? std::string::npos : hdr.find('}', vo);+ if (vc == std::string::npos) break;+ std::string key = hdr.substr(i + 1, ke - i - 1);+ std::string o = hdr.substr(vo, vc - vo + 1);+ SEnt e;+ size_t doff = o.find("\"data_offsets\"");+ size_t lb = doff == std::string::npos ? std::string::npos : o.find('[', doff);+ size_t rb = lb == std::string::npos ? std::string::npos : o.find(']', lb);+ if (rb == std::string::npos) { i = vc; continue; }+ e.a = strtoll(o.c_str() + lb + 1, nullptr, 10);+ const char * p = o.c_str() + lb + 1;+ while (*p && *p != ',') p++;+ if (*p == ',') e.b = strtoll(p + 1, nullptr, 10);+ size_t sp = o.find("\"shape\""), slb = sp == std::string::npos ? std::string::npos : o.find('[', sp),+ srb = slb == std::string::npos ? std::string::npos : o.find(']', slb);+ if (srb != std::string::npos) {+ std::string nums = o.substr(slb + 1, srb - slb - 1);+ const char * q = nums.c_str();+ while (*q) {+ char * r; long long v = strtoll(q, &r, 10);+ if (r != q) e.shape.push_back(v);+ q = r; while (*q == ',' || *q == ' ') q++;+ }+ }+ out[key] = e;+ i = vc;+ }+ return !out.empty();+}++bool grab_f16(FILE * f, uint64_t data_base, const SEnt & e, std::vector<float> & dst) {+ size_t n = 1;+ for (auto d : e.shape) n *= (size_t) d;+ dst.resize(n);+ if (_fseeki64(f, (long long) (data_base + e.a), SEEK_SET) != 0) return false;+ std::vector<uint16_t> raw(n);+ if (fread(raw.data(), 2, n, f) != n) return false;+ for (size_t i = 0; i < n; ++i) dst[i] = f16_to_f32(raw[i]);+ return true;+}++// ── Runtime state ──+struct Head { std::vector<float> fc1, fc2, lin; }; // [512][2560] / [256][512] / [256][2560]+struct Hist { std::vector<float> cur, prev; }; // owner-layer two-step onehot (E)++struct Pref {+ bool active = false;+ std::map<int, Head> heads; // owner → head triple+ std::map<int, std::vector<float>> gate; // consumer → [E][H]+ struct EXP { std::vector<TT> t; }; // consumer → up/gate/down exps metadata+ std::map<int, EXP> exps;+ std::map<int, Hist> hist; // layers 6..39 (39 keeps teacher onehot only)+ std::map<int, std::vector<int>> pred_prev; // consumer → previous-step head top-K+ std::map<int, std::vector<int>> exec_prev; // consumer → previous-step teacher (sticky)+ uint64_t data_base = 0;+ HANDLE fh = INVALID_HANDLE_VALUE, mh = NULL;+ void * view = nullptr;+ bool do_prefetch = false;+ int trace_every = 32;+ int stride = 1; // full head/teacher recompute period (E0_PREF_STRIDE); skipped steps only re-issue prefetch+ bool async = false; // E0_PREF_ASYNC=0 falls back to synchronous (tax-splitting A/B)+ // Predicted-range VirtualLock: pinned bytes are not trimmed while under budget;+ // lock failure once the cap is hit = natural ceiling. NOTE: VirtualLock normally+ // requires SeLockMemoryPrivilege, absent on consumer machines — treat this as best-effort.+ bool do_pin = false;+ size_t pin_cap = 3ull << 30, pin_bytes = 0;+ std::map<int, std::vector<std::pair<size_t, size_t>>> pinned; // consumer → currently pinned (file_off,len)+ // Self-managed L1 over the mmap view (E0_POOL): re-touch at step boundaries, in-table+ // age-based LRU; "evict" = drop from table (stop re-touching; reference-bit aging lets+ // the OS reclaim to standby — a free soft layer, no privileged APIs involved).+ int pool = 0; // 0=legacy advisory 1=sticky 2=sticky+observation+ struct Pin { size_t off, len; int age; uint8_t reg; };+ std::map<int, std::vector<Pin>> pins; // consumer → pin table (age = steps since last hit)+ size_t reg_bytes[2] = {0, 0}, reg_cap[2] = {0, 0}; // 0=hot zone (teacher) 1=observation zone (head)+ long pool_hit = 0, pool_tot = 0, lock_fail = 0, evicts = 0, shrinks = 0;+ // Async: m_in row-snapshot mailbox ((NH+1)×H floats, contiguous); worker runs full steps.+ std::vector<float> snap;+ std::atomic<bool> busy{false}, quit{false};+ std::mutex wmtx;+ std::condition_variable cv;+ std::thread worker;+ long hits = 0, sticky = 0, rnd = 0, total = 0, steps = 0;+ long long pool_mb = 0; // private-page pool hot-zone MB (>0 enables; E0_POOL_MB)+ uint32_t lcg = 2463534242u;+ uint32_t next() { lcg ^= lcg << 13; lcg ^= lcg >> 17; lcg ^= lcg << 5; return lcg; }+ ~Pref() {+ quit = true; cv.notify_all();+ if (worker.joinable()) worker.join();+ if (!total) return;+ fprintf(stderr, "\n[pref-trace] head overlap = %ld/%ld = %.1f%%\n", hits, total, 100.0 * hits / total);+ fprintf(stderr, "[pref-trace] sticky overlap = %ld/%ld = %.1f%%\n", sticky, total, 100.0 * sticky / total);+ fprintf(stderr, "[pref-trace] random overlap = %ld/%ld = %.1f%%\n", rnd, total, 100.0 * rnd / total);+ fprintf(stderr, "[pref-trace] head−sticky = %.1f pp | head−random = %.1f pp\n",+ 100.0 * (hits - sticky) / total, 100.0 * (hits - rnd) / total);+ e0_pool_trace_final();+ if (pool)+ fprintf(stderr, "[pref-trace] POOL(%s) hit = %ld/%ld = %.1f%% | pins hot=%lluMB obs=%lluMB (cap %llu/%llu) evict=%ld lockfail=%ld shrink=%ld\n",+ pool == 2 ? "sticky+obs" : "sticky", pool_hit, pool_tot, pool_tot ? 100.0 * pool_hit / pool_tot : 0.0,+ (unsigned long long) (reg_bytes[0] >> 20), (unsigned long long) (reg_bytes[1] >> 20),+ (unsigned long long) (reg_cap[0] >> 20), (unsigned long long) (reg_cap[1] >> 20),+ evicts, lock_fail, shrinks);+ fflush(stderr);+ }+};+Pref g;++float gelu_erf(float x) { return 0.5f * x * (1.f + erff(x * 0.7071067811865475f)); }+float dotf(const float * __restrict a, const float * __restrict b, size_t n) {+ float s = 0.f;+ for (size_t i = 0; i < n; ++i) s += a[i] * b[i]; // /arch:AVX2 auto-FMA reduction; the bottleneck is weight streaming, not ALU+ return s;+}+void topk(const float * v, int n, int k, std::vector<int> & out) {+ out.clear();+ std::vector<char> used(n, 0);+ for (int j = 0; j < k; ++j) {+ int best = -1;+ for (int i = 0; i < n; ++i) if (!used[i] && (best < 0 || v[i] > v[best])) best = i;+ if (best < 0) break;+ used[best] = 1; out.push_back(best);+ }+}+int ovlp(const std::vector<int> & a, const std::vector<int> & b) {+ int n = 0;+ for (int x : a) for (int y : b) if (x == y) { ++n; break; }+ return n;+}++} // namespace++// ══ Private-page expert pool (E0_POOL_MB): L1 with fill-once slots ══+// Design: decode reads expert bytes **directly from pool pages** via the expert-base+// resolver (patch surface #7), bypassing the view page-fault path entirely — a hit is a+// plain read with no kernel involvement. Slots fill once and never recycle (no eviction+// ⇒ no read-vs-overwrite race, correctness by construction); once the budget is+// exhausted, new experts pass through to the mmap view = graceful degradation to the+// un-pooled behavior. Three acquisition channels:+// demand = synchronous whole-block ReadFile on the compute thread (first touch)+// hot = worker prefill from the teacher set+// obs = dedicated quota for head predictions+// Whole-block reads are also fragmentation-proof (1×1MB sequential vs a 256×4K fault+// storm — an order of magnitude apart on consumer SSDs).+static_assert(sizeof(LONG) == 4, "slot state atoms");+namespace {++struct PoolTT { // one 3D experts tensor (40 slots measured across all layers)+ uint8_t * arena = nullptr; // MEM_RESERVE, MEM_COMMIT on demand+ volatile LONG * st = nullptr; // slot state: 0=empty 1=filling 2=ready 3=not-poolable+ CRITICAL_SECTION * cvlk = nullptr;// per-slot pair: CS lock + CV (filler owns it, readers sleep until woken)+ CONDITION_VARIABLE * cv = nullptr;+ size_t per = 0; // bytes per expert+ uint64_t foff = 0; // file offset of expert 0+};+static volatile LONG g_p_sc_ok = 0, g_p_sc_bad = 0; // byte-level self-check (fill vs view memcmp sampling)+static bool g_pool_sc = false; // E0_POOL_SELFCHECK=1 enables+static void e0_pool_selfcheck(uint8_t * slot, uint64_t foff, size_t per) {+ if (!g_pool_sc || !g.view) return;+ const uint8_t * v = (const uint8_t *) g.view + foff;+ int bad = 0;+ for (size_t i = 0; i < per; i += 4096) if (memcmp(slot + i, v + i, 64) != 0) { bad = 1; break; }+ if (bad) InterlockedIncrement(&g_p_sc_bad); else InterlockedIncrement(&g_p_sc_ok);+}+// ⚠ The tensor *pointer* changes every forward (same tensor registered multiple times,+// measured) ⇒ key by tensor NAME (table built at init, read-only afterwards → lock-free).+std::map<std::string, PoolTT *> g_ptt_by_name; // GGUF name → PTT+std::map<int, std::vector<PoolTT *>> g_ptt_by_c; // consumer → 3 PTTs (for prefill)+std::mutex g_pmtx; // fill/accounting lock (fills are ms-scale, not a spin hotspot)+size_t g_pool_cap[2] = {0, 0}; // 0=hot 1=obs (E0_POOL_MB/E0_POOL_OBS_MB)+size_t g_pool_bytes[2] = {0, 0};+volatile LONG g_p_calls = 0;+bool g_pool_on = false;+volatile LONG g_p_hits = 0, g_p_miss_d = 0, g_p_bypass = 0, g_p_waits = 0, g_p_fills = 0;++// Expert-base resolver hook from the patch band (exported by ggml.dll, C decoration).+typedef const char * (*ggml_edge0_mmid_base_fn)(const struct ggml_tensor * src0, int64_t id, size_t nb02);+extern "C" __declspec(dllimport) void ggml_edge0_set_mmid_resolver(ggml_edge0_mmid_base_fn fn);++// Resolver callback (patch surface #7, runs on ggml compute threads): returns the base+// address of expert `id`'s data.+extern "C" static const char * e0_mmid_base_res(const ggml_tensor * s, int64_t id, size_t nb02) {+ LONG c = InterlockedIncrement(&g_p_calls);+ if (c <= 2) { fprintf(stderr, "[pref-trace] POOL2 call#%ld name=%s nb02=%zu\n", c, s->name ? s->name : "?", nb02); fflush(stderr); }+ const char * orig = (const char *) s->data + (size_t) id * nb02;+ auto it = g_ptt_by_name.find(s->name ? s->name : "");+ if (it == g_ptt_by_name.end() || !it->second->st || it->second->per != nb02) {+ LONG b = InterlockedIncrement(&g_p_bypass);+ if (b <= 6)+ fprintf(stderr, "[pref-trace] POOL2 miss#%ld name=%s nb02=%zu in_table=%d table=%zu\n",+ b, s->name ? s->name : "?", nb02, (int) (it != g_ptt_by_name.end()), g_ptt_by_name.size());+ return orig;+ }+ PoolTT * pt = it->second;+ for (;;) {+ LONG st = pt->st[id];+ if (st == 1) { // another thread is filling: sleep until woken (no spinning)+ InterlockedIncrement(&g_p_waits);+ CRITICAL_SECTION & lk = pt->cvlk[id];+ EnterCriticalSection(&lk);+ if (pt->st[id] == 1) SleepConditionVariableCS(&pt->cv[id], &lk, 2000);+ LeaveCriticalSection(&lk);+ continue;+ }+ if (st == 2) {+ LONG h = InterlockedIncrement(&g_p_hits);+ if (h <= 3 || (h & 0x3FFF) == 0)+ fprintf(stderr, "[pref-trace] POOL2 hit=%ld fillD=%ld bypass=%ld wait=%ld sc=%ld/%ld | hot=%lluMB obs=%lluMB\n",+ h, g_p_miss_d, g_p_bypass, g_p_waits, (long) g_p_sc_ok, (long) g_p_sc_bad,+ (unsigned long long) (g_pool_bytes[0] >> 20), (unsigned long long) (g_pool_bytes[1] >> 20));+ fflush(stderr);+ return (const char *) (pt->arena + (size_t) id * pt->per);+ }+ if (st == 3) { InterlockedIncrement(&g_p_bypass); return orig; }+ { // claim the fill: CAS + exclusive CV section+ CRITICAL_SECTION & lk = pt->cvlk[id];+ if (InterlockedCompareExchange(&pt->st[id], 1, 0) != 0) continue;+ EnterCriticalSection(&lk);+ }+ LONG fs = InterlockedIncrement(&g_p_fills);+ if (fs <= 3 || (fs & 0x3FF) == 0) {+ fprintf(stderr, "[pref-trace] POOL2 fill#%ld name=%s id=%lld per=%zu hits=%ld\n",+ fs, s->name ? s->name : "?", (long long) id, pt->per, g_p_hits);+ fflush(stderr);+ }+ // Demand fill on this thread (hot budget).+ bool ok = false;+ {+ std::lock_guard<std::mutex> lk(g_pmtx);+ if (g_pool_bytes[0] + pt->per <= g_pool_cap[0]) {+ uint8_t * dst = pt->arena + (size_t) id * pt->per;+ if (VirtualAlloc(dst, pt->per, MEM_COMMIT, PAGE_READWRITE)) {+ uint64_t fo = pt->foff + (uint64_t) id * pt->per;+ LARGE_INTEGER off; off.QuadPart = (LONGLONG) fo;+ ok = SetFilePointerEx(g.fh, off, nullptr, FILE_BEGIN)+ && ReadFile(g.fh, dst, (DWORD) pt->per, nullptr, nullptr);+ if (ok) { g_pool_bytes[0] += pt->per; e0_pool_selfcheck(dst, fo, pt->per); }+ }+ }+ if (ok) InterlockedIncrement(&g_p_miss_d);+ }+ pt->st[id] = ok ? 2 : 3;+ WakeAllConditionVariable(&pt->cv[id]);+ LeaveCriticalSection(&pt->cvlk[id]);+ return ok ? (const char *) (pt->arena + (size_t) id * pt->per) : orig;+ }+}++// Worker prefill (teacher=hot / head=obs): called outside the resolver path; same per-slot CAS pattern.+static void e0_pool_prefill(int c, const std::vector<int> & ids, int reg) {+ auto it = g_ptt_by_c.find(c);+ if (it == g_ptt_by_c.end()) return;+ for (PoolTT * pt : it->second)+ for (int id : ids) {+ if (pt->st[id] != 0) continue;+ CRITICAL_SECTION & lk = pt->cvlk[id];+ if (InterlockedCompareExchange(&pt->st[id], 1, 0) != 0) continue;+ EnterCriticalSection(&lk);+ bool ok = false;+ {+ std::lock_guard<std::mutex> lk(g_pmtx);+ if (g_pool_bytes[reg] + pt->per <= g_pool_cap[reg]) {+ uint8_t * dst = pt->arena + (size_t) id * pt->per;+ if (VirtualAlloc(dst, pt->per, MEM_COMMIT, PAGE_READWRITE)) {+ LARGE_INTEGER off = { (DWORD) (pt->foff + (uint64_t) id * pt->per),+ (LONG) ((pt->foff + (uint64_t) id * pt->per) >> 32) };+ ok = SetFilePointerEx(g.fh, off, nullptr, FILE_BEGIN)+ && ReadFile(g.fh, dst, (DWORD) pt->per, nullptr, nullptr);+ if (ok) { g_pool_bytes[reg] += pt->per; e0_pool_selfcheck(dst, pt->foff + (uint64_t) id * pt->per, pt->per); }+ }+ }+ }+ pt->st[id] = ok ? 2 : 3;+ WakeAllConditionVariable(&pt->cv[id]);+ LeaveCriticalSection(&lk);+ }+}++static void e0_pool_trace_final() {+ if (!g_pool_on) return;+ fprintf(stderr, "[pref-trace] POOL2 hit=%ld fillD=%ld bypass=%ld wait=%ld sc=%ld/%ld | hot=%lluMB obs=%lluMB\n",+ g_p_hits, g_p_miss_d, g_p_bypass, g_p_waits, (long) g_p_sc_ok, (long) g_p_sc_bad,+ (unsigned long long) (g_pool_bytes[0] >> 20), (unsigned long long) (g_pool_bytes[1] >> 20));+}++static void e0_pool_scan(const std::map<std::string, TT> & tinfo) { // pool all *_exps tensors (independent of consumer shapes)+ for (auto & kv : tinfo) {+ const std::string & nm = kv.first;+ const TT & tt = kv.second;+ auto suff = [&](const char * sfx) -> size_t { // exact suffix match (returns length on hit)+ size_t len = strlen(sfx), k = nm.rfind(sfx);+ return (k != std::string::npos && k + len == nm.size()) ? len : 0;+ };+ size_t l1 = suff(".ffn_up_exps.weight"), l2 = suff(".ffn_gate_exps.weight"), l3 = suff(".ffn_down_exps.weight");+ size_t sl = l1 ? l1 : (l2 ? l2 : l3);+ if (!sl || tt.dim[2] < 2 || tt.dim[2] > 4096) continue;+ const size_t per = tt_bytes(tt) / (size_t) tt.dim[2];+ if (!per) continue;+ PoolTT * e = new PoolTT();+ e->per = per;+ e->foff = g.data_base + tt.off;+ e->arena = (uint8_t *) VirtualAlloc(nullptr, per * (size_t) tt.dim[2], MEM_RESERVE, PAGE_READWRITE);+ e->st = (volatile LONG *) VirtualAlloc(nullptr, sizeof(LONG) * (size_t) tt.dim[2], MEM_COMMIT, PAGE_READWRITE);+ e->cvlk = new CRITICAL_SECTION[(size_t) tt.dim[2]];+ e->cv = new CONDITION_VARIABLE[(size_t) tt.dim[2]];+ for (size_t z = 0; z < (size_t) tt.dim[2]; ++z) { InitializeCriticalSection(&e->cvlk[z]); InitializeConditionVariable(&e->cv[z]); }+ if (!e->arena || !e->st) { delete[] e->cvlk; delete[] e->cv; e->cvlk = nullptr; e->cv = nullptr; delete e; continue; }+ g_ptt_by_name[nm] = e;+ }+ g_pool_on = !g_ptt_by_name.empty();+ if (g_pool_on) ggml_edge0_set_mmid_resolver(e0_mmid_base_res); // attach to patch surface #7+ { int k = 0; for (auto & q : g_ptt_by_name) if (k++ < 3) fprintf(stderr, "[pref-trace] POOL2 key%d=%s per=%zu\n", k, q.first.c_str(), q.second->per); }+ fprintf(stderr, "[pref-trace] POOL2 init: tt=%zu caps hot=%lluMB obs=%lluMB resolver=%s\n",+ g_ptt_by_name.size(), (unsigned long long) (g_pool_cap[0] >> 20),+ (unsigned long long) (g_pool_cap[1] >> 20), g_pool_on ? "on" : "FAIL");+ fflush(stderr);+}++} // namespace++static void enable_capture(llama_context * ctx) {+ for (int L = OWNER0; L <= OWNER0 + NH; ++L) llama_set_embeddings_layer_inp(ctx, (uint32_t) L, true);+}++// ── Pool re-touch ladder: deterministic accounting (zero prediction = sticky; + observation zone = sticky/obs) ──+// Mechanism: VirtualLock needs SeLockMemoryPrivilege, which consumer machines lack ⇒ pinning+// is NOT the product mechanism. What works unprivileged = demand touch + working-set hard cap+// + the OS clock's natural LRU:+// "pin" = worker volatile-reads the range in 4K steps (demands pages into the WS; any+// trimmed page's fault tax is paid inside the worker, off the critical path);+// "evict" = drop from the table only (stop re-touching → reference-bit ages → OS trims it+// into standby = free soft layer);+// "cap" = at init, SetProcessWorkingSetSizeEx(MAX = baseline + hot + obs + headroom, HARDWS_MAX_ENABLE).+// Hot zone = re-touch of the previous step's teacher ids (same experts in a row = zero-fault+// hit); observation zone = head-guess quota (a bad guess only ages its own pages — the hot+// zone re-touches every step and never ages = contamination ceiling). Low-memory notification+// ⇒ shrink the tables (hot to 75%, observation to empty).+static volatile char g_touch_sink; // prevent DCE (every page is really read)+static void e0_touch(const void * view, size_t off, size_t len) {+ const volatile char * p = (const volatile char *) view + off;+ char s = 0;+ for (size_t i = 0; i < len; i += 4096) s += p[i];+ g_touch_sink = s;+}+static void e0_pool_evict(int R) { // evict the oldest entry in region R (age==0 entries are exempt)+ int wc = -1, wi = -1, ba = 0;+ for (auto & pc : g.pins)+ for (int k = 0; k < (int) pc.second.size(); ++k) {+ auto & p = pc.second[k];+ if (p.reg == R && p.age > ba) { ba = p.age; wc = pc.first; wi = k; }+ }+ if (wc < 0) return;+ g.reg_bytes[R] -= g.pins[wc][wi].len; ++g.evicts;+ g.pins[wc].erase(g.pins[wc].begin() + wi); // dropping from the table = stop re-touching; physical reclaim is the OS clock's job+}+static void e0_issue_pool() {+ if (!g.view) return;+ const int nreg = g.pool == 2 ? 2 : 1;+ std::map<int, std::vector<std::pair<size_t, size_t>>> want[2]; // 0=hot(teacher) 1=observation(head)+ auto ranges = [&](const std::map<int, std::vector<int>> & src, int R) {+ for (auto & pc : src) {+ auto & v = want[R][pc.first];+ for (const TT & tt : g.exps[pc.first].t) {+ const size_t per = tt_bytes(tt) / EK;+ for (int e : pc.second)+ v.push_back({ (size_t) g.data_base + tt.off + (size_t) e * per, per });+ }+ }+ };+ ranges(g.exec_prev, 0);+ if (nreg > 1) {+ std::map<int, std::vector<int>> preds;+ { std::lock_guard<std::mutex> lk(g.wmtx); preds = g.pred_prev; }+ ranges(preds, 1);+ }+ for (auto & kv : g.pins) for (auto & p : kv.second) ++p.age; // uniform step-rate aging+ std::vector<std::pair<size_t, size_t>> touch; // this step's demand set (≤ table cap)+ for (int R = 0; R < nreg; ++R) {+ for (auto & wv : want[R]) {+ auto & cur = g.pins[wv.first];+ std::vector<char> hit(wv.second.size(), 0);+ for (size_t i = 0; i < wv.second.size(); ++i)+ for (auto & p : cur)+ if (p.reg == R && p.off == wv.second[i].first) { p.age = 0; hit[i] = 1; if (!R) ++g.pool_hit; break; }+ if (!R) g.pool_tot += (long) wv.second.size(); // denominator = all hot-zone demand this step+ for (size_t i = 0; i < wv.second.size(); ++i) {+ if (hit[i]) continue;+ auto & w = wv.second[i];+ while (g.reg_bytes[R] + w.second > g.reg_cap[R]) {+ size_t b = g.reg_bytes[R];+ e0_pool_evict(R);+ if (g.reg_bytes[R] == b) { ++g.lock_fail; break; } // nothing evictable ⇒ hard ceiling (refused-pin counter)+ }+ if (g.reg_bytes[R] + w.second > g.reg_cap[R]) { ++g.lock_fail; continue; }+ cur.push_back({ w.first, w.second, 0, (uint8_t) R });+ g.reg_bytes[R] += w.second;+ }+ }+ }+ for (auto & pc : g.pins) for (auto & p : pc.second) e0_touch(g.view, p.off, p.len); // re-touch the whole table+ typedef HANDLE(WINAPI * QMRN)(LPCWSTR, void *); // memory-pressure cooperation (table-side fast shrink)+ typedef BOOL(WINAPI * GMRN_T)(HANDLE, PBOOL);+ static QMRN qmrn = (QMRN) GetProcAddress(GetModuleHandleA("kernel32"), "QueryMemoryResourceNotification");+ static GMRN_T gmrn = (GMRN_T) GetProcAddress(GetModuleHandleA("kernel32"), "GetMemoryResourceNotification");+ static HANDLE hn = qmrn ? qmrn(L"MemoryLow", nullptr) : nullptr;+ if (hn && gmrn) {+ BOOL low = FALSE;+ if (gmrn(hn, &low) && low) {+ ++g.shrinks;+ for (int R = 0; R < nreg; ++R)+ while (g.reg_bytes[R] && (R || g.reg_bytes[R] * 4 > g.reg_cap[R] * 3)) {+ size_t b = g.reg_bytes[R];+ e0_pool_evict(R);+ if (g.reg_bytes[R] == b) break;+ }+ }+ }+}++// ── Advisory issue: PVM soft warm-up + VirtualLock hard retention (lock failure once the+// budget is hit = natural ceiling). Callable from the worker thread or the main thread+// (synchronous / stride-skipped); pred_prev is copied under a short wmtx lock.+static void e0_issue() {+ if (g.pool) { e0_issue_pool(); return; } // pool accounting takes over (legacy pin/prefetch path retired)+ if (!g.view || (!g.do_prefetch && !g.do_pin)) return;+ std::map<int, std::vector<int>> preds;+ { std::lock_guard<std::mutex> lk(g.wmtx); preds = g.pred_prev; }+ static WIN32_MEMORY_RANGE_ENTRY win[4 * 3 * NH];+ int nw = 0;+ for (auto & pc : preds) {+ const int c = pc.first;+ std::vector<std::pair<size_t, size_t>> want;+ for (const TT & tt : g.exps[c].t) {+ const size_t per = tt_bytes(tt) / EK;+ for (int e : pc.second) want.push_back({ (size_t) g.data_base + tt.off + (size_t) e * per, per });+ }+ if (g.do_pin) {+ auto & cur = g.pinned[c];+ for (auto & r : cur) { // release stale pins+ bool keep = false;+ for (auto & w : want) if (w.first == r.first) { keep = true; break; }+ if (!keep) { VirtualUnlock((char *) g.view + r.first, r.second); g.pin_bytes -= r.second; }+ }+ for (auto & w : want) { // pin new predictions (skipped once capped)+ bool have = false;+ for (auto & r : cur) if (r.first == w.first) { have = true; break; }+ if (have || g.pin_bytes + w.second > g.pin_cap) continue;+ if (VirtualLock((char *) g.view + w.first, w.second)) g.pin_bytes += w.second;+ }+ cur = want; // remember current pin state (entries skipped by the cap unlock harmlessly next round)+ }+ if (g.do_prefetch)+ for (auto & w : want) {+ if (nw == 4 * 3 * NH) break;+ win[nw].VirtualAddress = (PVOID) ((char *) g.view + w.first);+ win[nw].NumberOfBytes = w.second;+ ++nw;+ }+ }+ if (nw) {+ static decltype(&PrefetchVirtualMemory) pvm =+ (decltype(&PrefetchVirtualMemory)) GetProcAddress(GetModuleHandleA("kernel32"), "PrefetchVirtualMemory");+ if (pvm) pvm(GetCurrentProcess(), nw, win, 0);+ }+}++// ── Full-step computation: (1) teacher (2) three-way accounting (3) head → preds + roll history (4) issue ──+// rows = snapshot buffer, row order = layers OWNER0..OWNER0+NH, HH floats per row.+// This function has no ctx dependency ⇒ it can run on the worker thread (keeps the ~90ms+// head GEMV off the critical path).+static void e0_full_step(const float * rows) {+ std::map<int, std::vector<int>> teacher;+ for (int c : consumers) {+ const float * x = rows + (size_t) (c - OWNER0) * HH;+ std::vector<float> tl(EK);+ const float * gw = g.gate[c].data();+ for (int e = 0; e < EK; ++e) tl[e] = dotf(gw + (size_t) e * HH, x, HH);+ topk(tl.data(), EK, KDIM, teacher[c]);+ }+ // Three-way settlement: pred copy (short lock) vs teacher @ this snapshot.+ std::map<int, std::vector<int>> preds_copy;+ { std::lock_guard<std::mutex> lk(g.wmtx); preds_copy = g.pred_prev; }+ for (int c : consumers) {+ auto pp = preds_copy.find(c);+ if (pp != preds_copy.end()) {+ g.hits += ovlp(pp->second, teacher[c]); g.total += KDIM;+ auto sp = g.exec_prev.find(c);+ if (sp != g.exec_prev.end()) g.sticky += ovlp(sp->second, teacher[c]);+ std::vector<int> r;+ for (int tries = 0; tries < 64 && (int) r.size() < KDIM; ++tries) {+ int v = (int) (g.next() % (uint32_t) EK);+ bool dup = false; for (int y : r) if (y == v) { dup = true; break; }+ if (!dup) r.push_back(v);+ }+ g.rnd += ovlp(r, teacher[c]);+ }+ g.exec_prev[c] = teacher[c];+ }+ if (g_pool_on) for (auto & kv : g.exec_prev) e0_pool_prefill(kv.first, kv.second, 0); // teacher → hot zone+ // head: owner o features = [m_in|cur_oh|prev_oh] → new pred (consumer = o+1)+ std::map<int, std::vector<int>> new_preds;+ std::vector<float> feat(FE), act(512), lg(EK);+ for (int o = OWNER0; o < OWNER0 + NH; ++o) {+ const int c = o + 1;+ auto & h = g.hist[o];+ memcpy(feat.data(), rows + (size_t) (o - OWNER0) * HH, HH * 4);+ memcpy(feat.data() + HH, h.cur.data(), EK * 4);+ memcpy(feat.data() + HH + EK, h.prev.data(), EK * 4);+ const Head & hd = g.heads[o];+ for (int j = 0; j < 512; ++j) act[j] = gelu_erf(dotf(hd.fc1.data() + (size_t) j * FE, feat.data(), FE));+ for (int e = 0; e < EK; ++e)+ lg[e] = dotf(hd.fc2.data() + (size_t) e * 512, act.data(), 512)+ + dotf(hd.lin.data() + (size_t) e * FE, feat.data(), FE);+ topk(lg.data(), EK, KDIM, new_preds[c]);+ }+ if (g_pool_on && g_pool_cap[1]) for (auto & kv : new_preds) e0_pool_prefill(kv.first, kv.second, 1); // head → observation zone+ { std::lock_guard<std::mutex> lk(g.wmtx); g.pred_prev = std::move(new_preds); }+ // roll the onehot history (teacher→cur, cur→prev)+ for (auto & kv : g.hist) {+ auto t = teacher.find(kv.first);+ if (t == teacher.end()) continue;+ kv.second.prev = kv.second.cur;+ kv.second.cur.assign(EK, 0.f);+ for (int e : t->second) kv.second.cur[e] = 1.f;+ }+ e0_issue();+ if (g.trace_every && g.steps % g.trace_every == 0 && g.total) {+ fprintf(stderr, "[pref-trace] step %ld: head %.1f%% sticky %.1f%% rand %.1f%% pinned=%lluMB (n=%ld)\n",+ g.steps, 100.0 * g.hits / g.total, 100.0 * g.sticky / g.total,+ 100.0 * g.rnd / g.total, (unsigned long long) (g.pin_bytes >> 20), g.total);+ if (g.pool)+ fprintf(stderr, "[pref-trace] POOL hit=%.1f%% (n=%ld) pins %llu+%lluMB evict=%ld fail=%ld shrink=%ld\n",+ 100.0 * g.pool_hit / (g.pool_tot ? g.pool_tot : 1), g.pool_tot,+ (unsigned long long) (g.reg_bytes[0] >> 20), (unsigned long long) (g.reg_bytes[1] >> 20),+ g.evicts, g.lock_fail, g.shrinks);+ fflush(stderr);+ }+}++static void e0_worker() {+ for (;;) {+ {+ std::unique_lock<std::mutex> lk(g.wmtx);+ g.cv.wait(lk, [&] { return g.quit.load() || g.busy.load(); });+ if (g.quit) return;+ }+ if (g.busy.load()) {+ e0_full_step(g.snap.data());+ g.busy = false;+ }+ }+}++bool edge0_pref_init(llama_model * model, llama_context * ctx, int pool_mb, const char * gguf_path) {+ (void) model;+ if (g.active) { if (!g.gate.empty()) enable_capture(ctx); return true; } // hot reload (only head mode needs capture)+ const char * side = getenv("E0_PREROUTER");+ const char * gg = (gguf_path && *gguf_path) ? gguf_path : getenv("E0_GGUF"); // primary CLI channel = model path+ if (pool_mb > 0) g.pool_mb = pool_mb; // --pool-mb formal CLI+ else if (const char * pmb = getenv("E0_POOL_MB")) g.pool_mb = atoll(pmb); // env fallback (harness/debug); runnable without the sidecar+ const bool headson = side && *side;+ if ((!headson && !g.pool_mb) || !gg || !*gg) return false;++ if (consumers.empty()) for (int c = OWNER0 + 1; c <= OWNER0 + NH; ++c) consumers.push_back(c); // 7..39++ // ── GGUF header: skip-scan KVs (for general.alignment) + build the tensor table ──+ FILE * f = fopen(gg, "rb");+ if (!f) return false;+ struct { uint32_t magic, ver; uint64_t nt, nkv; } h;+ if (fread(&h, sizeof h, 1, f) != 1 || memcmp(&h.magic, "GGUF", 4)) { fclose(f); return false; }+ size_t alignment = 32;+ for (uint64_t i = 0; i < h.nkv; ++i) {+ std::string k = rd_str(f);+ uint32_t t; if (fread(&t, 4, 1, f) != 1) { fclose(f); return false; }+ if (k == "general.alignment" && t == 4) fread(&alignment, 4, 1, f);+ else skip_val(f, t);+ }+ std::map<std::string, TT> tinfo;+ for (uint64_t i = 0; i < h.nt; ++i) {+ TT x; x.name = rd_str(f);+ uint32_t nd; fread(&nd, 4, 1, f);+ for (uint32_t d = 0; d < nd && d < 4; ++d) fread(&x.dim[d], 8, 1, f);+ fread(&x.type, 4, 1, f); fread(&x.off, 8, 1, f);+ tinfo[x.name] = x;+ }+ g.data_base = align_up((uint64_t) ftell(f), alignment);++ // Register exps metadata (needed by both pool and head) + copy the F32 gate weights host-side (head mode only).+ for (int c : consumers) {+ for (const char * suf : {"ffn_up_exps", "ffn_gate_exps", "ffn_down_exps"}) {+ auto et = tinfo.find("blk." + std::to_string(c) + "." + suf + ".weight");+ if (et != tinfo.end() && et->second.dim[2] == (uint64_t) EK) g.exps[c].t.push_back(et->second);+ }+ if (!headson) continue;+ auto it = tinfo.find("blk." + std::to_string(c) + ".ffn_gate_inp.weight");+ if (it == tinfo.end() || it->second.type != 0) {+ fclose(f); fprintf(stderr, "[pref-trace] gate missing/bad type c=%d => dormant\n", c); return false;+ }+ const TT & gt = it->second;+ size_t nb = tt_bytes(gt);+ std::vector<float> buf(nb / 4);+ _fseeki64(f, (long long) (g.data_base + gt.off), SEEK_SET);+ if (fread(buf.data(), 1, nb, f) != nb) { fclose(f); return false; }+ g.gate[c] = std::move(buf);+ }+ fclose(f);++ // sidecar head weights (head mode only)+ if (headson) {+ std::map<std::string, SEnt> st;+ if (!st_load(side, st)) { fprintf(stderr, "[pref-trace] sidecar parse failed => dormant\n"); return false; }+ FILE * sf = fopen(side, "rb");+ if (!sf) return false;+ uint64_t shn = 0; fread(&shn, 8, 1, sf);+ uint64_t sdata = 8 + shn;+ for (int o = OWNER0; o < OWNER0 + NH; ++o) {+ Head hd;+ auto key = [&](const char * w) { return "layers." + std::to_string(o) + "." + w + ".weight"; };+ bool ok = grab_f16(sf, sdata, st[key("fc1")], hd.fc1)+ && grab_f16(sf, sdata, st[key("fc2")], hd.fc2)+ && grab_f16(sf, sdata, st[key("linear_init")], hd.lin);+ if (!ok) { fclose(sf); fprintf(stderr, "[pref-trace] sidecar missing layer o=%d => dormant\n", o); return false; }+ g.heads[o] = std::move(hd);+ }+ fclose(sf);+ } // headson++ // Dedicated read handle (pool fills via g.fh) + a self-owned read-only mapping (PVM anchor; head mode only).+ if (headson || g.pool_mb) {+ g.fh = CreateFileA(gg, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);+ if (g.fh != INVALID_HANDLE_VALUE && headson) {+ g.mh = CreateFileMappingA(g.fh, NULL, PAGE_READONLY, 0, 0, NULL);+ if (g.mh) g.view = MapViewOfFile(g.mh, FILE_MAP_READ, 0, 0, 0);+ }+ }+ g.do_prefetch = getenv("E0_PREFETCH") != nullptr;+ if (const char * tn = getenv("E0_PREF_TRACE_N")) g.trace_every = atoi(tn);+ if (const char * sn = getenv("E0_PREF_STRIDE")) g.stride = atoi(sn) > 0 ? atoi(sn) : 1;+ const char * an = getenv("E0_PREF_ASYNC");+ g.async = !(an && *an == '0'); // async is the default; =0 falls back to synchronous (tax isolation)+ g.do_pin = getenv("E0_PREF_PIN") != nullptr;+ if (const char * pm = getenv("E0_PIN_MAX_MB")) g.pin_cap = (size_t) atoll(pm) << 20;+ if (const char * pl = getenv("E0_POOL")) { // sticky=zone1 obs=zone1+2+ if (!strcmp(pl, "obs")) g.pool = 2;+ else if (*pl && strcmp(pl, "0")) g.pool = 1;+ }+ if (g.pool) {+ g.reg_cap[0] = g.pin_cap; // hot zone = E0_PIN_MAX_MB (default 3G)+ const char * om = getenv("E0_POOL_OBS_MB");+ g.reg_cap[1] = (size_t) (om ? atoll(om) : 1024) << 20; // observation zone default 1G+ g.do_pin = false; // the advisory pin path does not run in parallel+ // Working-set hard cap = startup baseline WS + pool quotas + headroom (the residency contract without SeLockMemory).+ PROCESS_MEMORY_COUNTERS_EX pmc = {};+ pmc.cb = sizeof(pmc);+ if (K32GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *) &pmc, sizeof(pmc))) {+ const char * hm = getenv("E0_POOL_WSHEAD_MB");+ size_t head = (size_t) (hm ? atoll(hm) : 1024) << 20;+ SIZE_T wmax = (SIZE_T) pmc.WorkingSetSize + g.reg_cap[0] + g.reg_cap[1] + head;+ SIZE_T qmin = 0, qmax = 0; DWORD qf = 0; // the Ex variant rejects min=-1 (error 87) ⇒ read current quotas and keep them+ GetProcessWorkingSetSizeEx(GetCurrentProcess(), &qmin, &qmax, &qf);+ BOOL r = SetProcessWorkingSetSizeEx(GetCurrentProcess(), qmin, wmax,+ QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_ENABLE);+ fprintf(stderr, "[pref-trace] POOL ws-cap: base=%lluMB max=%lluMB set=%d err=%lu\n",+ (unsigned long long) (pmc.WorkingSetSize >> 20), (unsigned long long) (wmax >> 20),+ (int) r, r ? 0UL : GetLastError());+ }+ }+ g.snap.assign((size_t) (NH + 1) * HH, 0.f);++ // Open the layer-input capture channel (same staging API as speculative decode; head mode only).+ if (headson) {+ enable_capture(ctx);+ for (int L = OWNER0; L <= OWNER0 + NH; ++L) g.hist[L] = Hist{ std::vector<float>(EK, 0.f), std::vector<float>(EK, 0.f) };+ }+ if (g.pool_mb) {+ g_pool_cap[0] = (size_t) g.pool_mb << 20;+ if (const char * pom = getenv("E0_POOL_OBS_MB")) g_pool_cap[1] = (size_t) atoll(pom) << 20;+ g_pool_sc = getenv("E0_POOL_SELFCHECK") != nullptr;+ if (g_pool_sc && !g.view) { // self-check needs the view: map it even in pool-only mode+ g.mh = CreateFileMappingA(g.fh, NULL, PAGE_READONLY, 0, 0, NULL);+ if (g.mh) g.view = MapViewOfFile(g.mh, FILE_MAP_READ, 0, 0, 0);+ }+ e0_pool_scan(tinfo);+ for (int c : consumers)+ for (const TT & tt : g.exps[c].t) {+ auto it = g_ptt_by_name.find(tt.name);+ if (it != g_ptt_by_name.end()) g_ptt_by_c[c].push_back(it->second);+ }+ }+ g.active = headson || g_pool_on;+ if (g.active && !headson) { g.async = false; } // pool-only mode: no worker (demand is self-sufficient)+ if (g.active && headson && g.async) g.worker = std::thread(e0_worker);+ fprintf(stderr, "[pref-trace] INIT ok: heads=%zu gates=%zu exps=%zu map=%s prefetch=%s pin=%s(async=%d) stride=%d K=%d E=%d pool=%d(hot=%lluMB obs=%lluMB)\n",+ g.heads.size(), g.gate.size(), g.exps.size(), g.view ? "ok" : "FAIL",+ g.do_prefetch ? "on" : "off", g.do_pin ? "on" : "off", (int) g.async, g.stride, KDIM, EK,+ (int) g_pool_on, (unsigned long long) (g_pool_cap[0] >> 20), (unsigned long long) (g_pool_cap[1] >> 20));+ return g.active;+}++void edge0_pref_on_step(llama_context * ctx, int64_t last_row) {+ if (!g.active) return;+ if (g.gate.empty()) return; // pool-only mode: no capture channel, nothing to account — demand is autonomous+ llama_synchronize(ctx);+ ++g.steps;++ if (g.stride > 1 && (g.steps % g.stride) != 0) { // downsampled: reuse existing preds, just re-issue (µs scale)+ if (!g.async && !g.pool) e0_issue(); // async=worker already issued on cadence; pool=skipped steps neither age nor evict+ return;+ }+ if (g.async) {+ if (g.busy.load()) return; // worker busy: drop this snapshot (preds already valid, lossless)+ float * dst = g.snap.data();+ for (int L = OWNER0; L <= OWNER0 + NH; ++L, dst += HH) {+ float * buf = llama_get_embeddings_layer_inp(ctx, (uint32_t) L);+ if (!buf) return; // channel not ready+ memcpy(dst, buf + last_row * HH, (size_t) HH * 4);+ }+ { std::lock_guard<std::mutex> lk(g.wmtx); g.busy = true; }+ g.cv.notify_one();+ return;+ }+ // Synchronous path: snapshot + full step inline (reference/fallback).+ float * dst = g.snap.data();+ for (int L = OWNER0; L <= OWNER0 + NH; ++L, dst += HH) {+ float * buf = llama_get_embeddings_layer_inp(ctx, (uint32_t) L);+ if (!buf) return;+ memcpy(dst, buf + last_row * HH, (size_t) HH * 4);+ }+ e0_full_step(g.snap.data());+}diff --git a/windows/serve/prefetch.h b/windows/serve/prefetch.hnew file mode 100644index 0000000..3fe7e87--- /dev/null+++ b/windows/serve/prefetch.h@@ -0,0 +1,50 @@+// serve/prefetch.h — edge0 advisory expert-prefetch router.+// Self-contained unit compiled into the llama target; depends only on llama+// public/near-public APIs (llama.h + the src/llama-ext.h layer-input channel,+// same route as speculative.cpp), linked into llama-server.+// The real routing gate is never touched: the router head predicts, for step t+1,+// the expert set of consumer layers from the owner layer's input (m_in) and a+// two-step history, then issues prefetches for the matching GGUF byte ranges.+// A miss costs latency only, never quality.+//+// Env gates (all dormant by default):+// E0_PREROUTER=<path to prerouter_edge0_*.safetensors> enable head + advisory prefetch+// E0_PREFETCH=0 account only, no prefetch (A/B split)+// E0_PREF_TRACE_N=<k> print [pref-trace] every k steps (default 32)+// E0_POOL_MB=<n> hot-zone size MB of the private-page+// L1 pool (served through patch #7's+// expert-base resolver; can run without+// the sidecar as a demand pool)+// E0_POOL_OBS_MB=<n> observation-zone MB (meaningful only with heads on)+// E0_POOL=sticky|obs route MUL_MAT_ID reads through the L1 pool+// instead of plain mmap (sticky = re-touch the+// teacher set at step boundaries; obs = add the+// head-driven observation quota on top)+// E0_PIN_MAX_MB=<n> hot-zone byte cap (default 3072)+// E0_POOL_WSHEAD_MB=<n> headroom for the working-set hard cap+// (cap = base + hot + obs + headroom; default 1024)+// [pref-trace] prints head/sticky/random accounting = proof the mechanism is live.+#pragma once++#include <cstdint>++// This unit is compiled into the llama target; when llama is built as a DLL it+// must be exported so llama-server-impl can link against it.+#ifdef _WIN32+# define E0_PREF_API __declspec(dllexport)+#else+# define E0_PREF_API __attribute__((visibility("default")))+#endif++struct llama_model;+struct llama_context;++// Called once after server model+ctx are ready. Returns false = not enabled or+// shape mismatch (stays dormant). pool_mb/gguf_path = formal CLI channels+// (--pool-mb / model path); <= 0 / NULL falls back to the env channel (debug/harness).+E0_PREF_API bool edge0_pref_init(llama_model * model, llama_context * ctx,+ int pool_mb, const char * gguf_path);++// Called after every llama_decode; last_row = the row index of this ubatch's last token+// in the layer-input capture buffer.+E0_PREF_API void edge0_pref_on_step(llama_context * ctx, int64_t last_row);diff --git a/windows/tools/convert_mlx_to_gguf.py b/windows/tools/convert_mlx_to_gguf.pynew file mode 100644index 0000000..94e7041--- /dev/null+++ b/windows/tools/convert_mlx_to_gguf.py@@ -0,0 +1,173 @@+#!/usr/bin/env python3+# -*- coding: utf8 -*-+"""convert_mlx_to_gguf.py — single entry for on-device MLX→GGUF conversion.++The app ships MLX artifacts only; this script (distributed with the app) runs the+full conversion on the user's machine in three steps:+ 1) runtime GGUF generation (35b = repack_r3 / 8b = repack_r3_8b, incl. their+ built-in full-tensor golden comparison gates)+ 2) LoRA adapter generation (lora_mlx_to_gguf, incl. name/shape cross-check gate)+ 3) on-device self-check + manifest (GGUF header/tensor-count revalidation ++ sha256 of everything + converter/engine version lock-step triple)++Idempotency: if manifest.json exists and every artifact sha matches ⇒ skip+(resume granularity = whole steps).+Failure: nonzero exit + partial artifacts kept + error recorded; MLX sources are+never deleted (cleanup policy belongs to the app).+Dependencies: python3 + numpy only (reuses the three tools/ scripts; gguf-py is+not assumed present, so the header revalidation is hand-rolled on stdlib).++Usage: python tools/convert_mlx_to_gguf.py --dir models/edge0-8b [--out models/edge0-8b-gguf]+ [--compare-against <dir>] # determinism proof: artifact shas compared 1:1 against same-named files in <dir>+"""+import argparse, hashlib, json, os, re, subprocess, sys, time++TOOLS = os.path.dirname(os.path.abspath(__file__))+CONVERTER_REV = subprocess.run(["git", "-C", os.path.dirname(TOOLS), "rev-parse", "--short", "HEAD"],+ capture_output=True, text=True).stdout.strip() or "unknown"+ENGINE_REF = "edge0/lora-bailingmoe3@a49736d+" # version lock-step: minimum compatible engine (after patch band 5)+++def sha256(path, blk=1 << 22):+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for chunk in iter(lambda: f.read(blk), b""):+ h.update(chunk)+ return h.hexdigest()+++def check_gguf_head(path, min_tensors):+ """stdlib GGUF header revalidation: magic/version/n_tensors + KV section walkable + file size consistent."""+ with open(path, "rb") as f:+ if f.read(4) != b"GGUF":+ raise ValueError(f"{path}: not GGUF")+ ver = int.from_bytes(f.read(4), "little")+ n_tensors = int.from_bytes(f.read(8), "little")+ n_kv = int.from_bytes(f.read(8), "little")+ if ver < 2 or n_tensors < min_tensors:+ raise ValueError(f"{path}: ver={ver} n_tensors={n_tensors}")+ def rd_s():+ n = int.from_bytes(f.read(8), "little"); s = f.read(n); return s.decode("utf8")+ def skip(t):+ if t == 8: rd_s()+ elif t == 9:+ et = int.from_bytes(f.read(4), "little"); n = int.from_bytes(f.read(8), "little")+ for _ in range(n): skip(et)+ else:+ f.read({0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8}[t])+ for _ in range(n_kv):+ rd_s(); t = int.from_bytes(f.read(4), "little"); skip(t)+ total = 0+ for _ in range(n_tensors):+ nm = rd_s()+ nd = int.from_bytes(f.read(4), "little")+ dims = [int.from_bytes(f.read(8), "little") for _ in range(nd)]+ dt = int.from_bytes(f.read(4), "little")+ off = int.from_bytes(f.read(8), "little")+ n = 1+ for d in dims: n *= d+ tsz = {0:4, 1:2, 2:2}.get(dt)+ if tsz is None: # quantized block type (r3: 3 = Q4_1)+ assert dt == 3, f"{nm}: unknown dtype {dt}"+ assert dims[0] % 32 == 0, f"{nm}: Q4_1 ne0 % 32"+ n = n // 32 * 20+ total = max(total, off + n)+ f.seek(0, 2)+ if f.tell() < total:+ raise ValueError(f"{path}: data section shorter than tensor table ({f.tell()}<{total})")+ return n_tensors, n_kv+++def run_step(argv, tag, logf):+ print(f"[{tag}] $ {' '.join(argv)}", flush=True)+ r = subprocess.run(argv, stdout=logf, stderr=subprocess.STDOUT)+ if r.returncode != 0:+ raise SystemExit(f"[{tag}] FAILED rc={r.returncode} (see {logf.name})")+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--dir", required=True)+ ap.add_argument("--out", default=None, help="default: <dir>-gguf")+ ap.add_argument("--compare-against", default=None)+ a = ap.parse_args()+ d = os.path.normpath(a.dir)+ out = a.out or (d + "-gguf")+ stem = os.path.basename(d)+ m = re.match(r"edge0[-_](35b|8b)", stem)+ assert m, f"cannot detect tier from directory name: {stem}"+ tier = m.group(1)+ if a.out and os.path.normpath(a.out) != os.path.normpath(d + "-gguf"):+ print("WARNING: --out deviates from the <dir>-gguf convention ⇒ the lora cross-check gate still reads the base from the conventional path (use the default layout on-device)", flush=True)+ os.makedirs(out, exist_ok=True)+ log = open(os.path.join(out, "convert.log"), "ab")+ arts = {"gguf": os.path.join(out, f"edge0-{tier}.gguf"),+ "lora": os.path.join(out, f"lora_edge0_{tier}-gguf.gguf")}+ src_lora = os.path.join(d, f"lora_{stem.replace('-', '_')}-gguf.gguf")+ manifest_p = os.path.join(out, "manifest.json")++ # ---- idempotency gate ----+ if os.path.isfile(manifest_p):+ try:+ old = json.load(open(manifest_p, encoding="utf8"))+ ok = all(os.path.isfile(p) and sha256(p) == old["artifacts"][k] for k, p in arts.items())+ if ok:+ print("manifest hit and all artifact shas match ⇒ already converted, skipping (idempotent).", flush=True)+ return 0+ except Exception:+ pass++ t0 = time.time()+ # determinism baselines captured BEFORE any overwrite (the lora original lives in the MLX dir and is regenerated by the conversion)+ ref_base = {}+ if a.compare_against:+ ref = os.path.normpath(a.compare_against)+ for k, p in arts.items():+ for cand in (os.path.join(ref, os.path.basename(p)), os.path.join(d, os.path.basename(p))):+ if os.path.isfile(cand):+ ref_base[k] = (cand, sha256(cand))+ break+ # ---- step 1: runtime GGUF ----+ if tier == "35b":+ run_step([sys.executable, os.path.join(TOOLS, "repack_r3.py"), "--dir", d, "--out", out,+ "--verify", "all"], "r3-35b", log)+ n_min = 700+ else:+ run_step([sys.executable, os.path.join(TOOLS, "repack_r3_8b.py"), "--dir", d, "--out", out],+ "r3-8b", log)+ n_min = 500+ # ---- step 2: adapter ----+ run_step([sys.executable, os.path.join(TOOLS, "lora_mlx_to_gguf.py"), "--dir", d], "lora", log)+ assert os.path.isfile(src_lora), f"adapter not produced: {src_lora}"+ if os.path.abspath(src_lora) != os.path.abspath(arts["lora"]):+ import shutil; shutil.copyfile(src_lora, arts["lora"])++ # ---- step 3: on-device self-check ----+ nt, nk = check_gguf_head(arts["gguf"], n_min)+ print(f"[self-check] {os.path.basename(arts['gguf'])}: tensors={nt} kv={nk} OK", flush=True)+ nta, _ = check_gguf_head(arts["lora"], 100)+ print(f"[self-check] adapter tensors={nta} OK", flush=True)++ man = {+ "model": stem, "tier": tier,+ "produced_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "elapsed_s": round(time.time() - t0, 1),+ "converter": {"path": "tools/convert_mlx_to_gguf.py", "repo_rev": CONVERTER_REV},+ "engine_min": ENGINE_REF,+ "inputs_sha256": {k: sha256(os.path.join(d, k)) for k in sorted(os.listdir(d))+ if k.endswith((".safetensors",)) },+ "artifacts": {k: sha256(p) for k, p in arts.items()},+ "sizes": {k: os.path.getsize(p) for k, p in arts.items()},+ }+ if a.compare_against:+ det = {k: (k in ref_base and ref_base[k][1] == man["artifacts"][k]) for k in arts}+ man["determinism_vs"] = {"baselines": {k: ref_base[k][0] for k in ref_base}, **det}+ assert all(det.get(k) for k in arts), f"determinism mismatch (artifact sha differs from baseline): {det}"+ print(f"[determinism] vs baselines: ALL MATCH ✔", flush=True)+ json.dump(man, open(manifest_p, "w", encoding="utf8"), ensure_ascii=False, indent=1)+ print(f"DONE {tier}: gguf={man['sizes']['gguf']/2**30:.2f}GiB lora={man['sizes']['lora']/2**20:.1f}MiB "+ f"took {man['elapsed_s']}s → {manifest_p}", flush=True)+++if __name__ == "__main__":+ main()diff --git a/windows/tools/lora_mlx_to_gguf.py b/windows/tools/lora_mlx_to_gguf.pynew file mode 100644index 0000000..226febf--- /dev/null+++ b/windows/tools/lora_mlx_to_gguf.py@@ -0,0 +1,202 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""lora_mlx_to_gguf.py — edge0 LoRA (MLX safetensors, peft shape) → llama-adapter GGUF.++Basis (verified against fork @7ab4ee7):+ naming law: adapter tensor names must == base weight names + ".lora_a/.lora_b"+ (llama-adapter.cpp:333 hard lookup)+ shape law: A declared dims = reversed(torch [r,K]) = ggml ne [K,r]; B = [r,N]+ (:365-370 checks; torch row-major bytes untouched, only the dims+ declaration flips)+ scale law: runtime scale = adapter.lora.alpha ? s·alpha/rank : s+ (llama-adapter.h:53, rank = B.ne0)+ source-of-truth scale = alpha/r = 32/16 = 2.0 ⇒ write+ adapter.lora.alpha=32.0 so plain `--lora FILE` (default s=1.0) is the same expression+ ssm_ba special tensor: the model side interleaves+merges in_proj_b/a+ (qwen3next.cpp:421-438) and the two source LoRAs have different A matrices+ ⇒ block-diagonal merge: A=[32,2048] (top 16 rows = A_b, bottom 16 = A_a),+ B=[64,32] with rows placed per the interleave; rank=32 ⇒ default+ scale=32/32=1.0 while the source needs 2.0 per path ⇒ **B entries ×2+ compensation** (linear value scaling, NOT requantization).+ arch law: general.architecture must match the base (:212 hard compare).+"""+import argparse, os, re, struct, sys+import numpy as np+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from repack_mlx_to_gguf import StIndex, GgufWriter, KV, T_F16, bf16_to_f32+from repack_r3 import ssm_ba_perm++RENAME = [+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.linear_attn\.in_proj_qkv$"), r"blk.\1.attn_qkv.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.linear_attn\.in_proj_z$"), r"blk.\1.attn_gate.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.linear_attn\.out_proj$"), r"blk.\1.ssm_out.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.self_attn\.q_proj$"), r"blk.\1.attn_q.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.self_attn\.k_proj$"), r"blk.\1.attn_k.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.self_attn\.v_proj$"), r"blk.\1.attn_v.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.self_attn\.o_proj$"), r"blk.\1.attn_output.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.mlp\.shared_expert\.gate_proj$"), r"blk.\1.ffn_gate_shexp.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.mlp\.shared_expert\.up_proj$"), r"blk.\1.ffn_up_shexp.weight"),+ (re.compile(r"^language_model\.model\.layers\.(\d+)\.mlp\.shared_expert\.down_proj$"), r"blk.\1.ffn_down_shexp.weight"),+]+BA = re.compile(r"^language_model\.model\.layers\.(\d+)\.linear_attn\.in_proj_([ab])$")+++def f16(idx, name):+ a = idx.load(name)+ return np.ascontiguousarray(a, dtype=np.float16)+++RENAME_8B = [+ (re.compile(r"^model\.layers\.(\d+)\.attention\.q_proj$"), r"blk.\1.attn_q.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.k_proj$"), r"blk.\1.attn_k.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.v_proj$"), r"blk.\1.attn_v.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.o_proj$"), r"blk.\1.attn_output.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.dense$"), r"blk.\1.attn_output.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.f_proj$"), r"blk.\1.ssm_f_a.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.b_proj$"), r"blk.\1.ssm_beta.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.q_a_proj$"), r"blk.\1.attn_q_a.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.attention\.q_b_proj$"), r"blk.\1.attn_q_b.weight"),+ # g_proj routes by layer type (KDA→ssm_g_a / MLA→attn_gate), decided via FULL() in main+ (re.compile(r"^model\.layers\.(\d+)\.attention\.g_proj$"), r"G"),+ # kv_b_proj targets a 3D split tensor (unimplemented upstream-side); never touched by --only experiments; plain conversions skip it and report+ (re.compile(r"^model\.layers\.(\d+)\.attention\.kv_b_proj$"), r"SKIP:kv_b_3d"),+ (re.compile(r"^model\.layers\.(\d+)\.mlp\.gate_proj$"), r"blk.\1.ffn_gate.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.mlp\.up_proj$"), r"blk.\1.ffn_up.weight"),+ (re.compile(r"^model\.layers\.(\d+)\.mlp\.down_proj$"), r"blk.\1.ffn_down.weight"),+]+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--dir", required=True)+ ap.add_argument("--alpha", type=float, default=32.0) # = alpha baked in the source artifact; plain --lora (default scale 1.0) then reproduces the same expression+ ap.add_argument("--only", default=None, help="generate only families whose base name matches this regex (single-variable experiments)")+ ap.add_argument("--out-suffix", default="-gguf", help="infix in the output name")+ a = ap.parse_args()+ stem = os.path.basename(a.dir.rstrip("\\/"))+ is8 = "8b" in stem+ sfx = stem.replace("-", "_") # artifact names use underscores: lora_edge0_35b.safetensors+ lora_path = os.path.join(a.dir, f"lora_{sfx}.safetensors")+ out = os.path.join(a.dir, f"lora_{sfx}{a.out_suffix}.gguf")+ idx = StIndex([lora_path])+ cfg = __import__("json").load(open(os.path.join(a.dir, "config.json"), encoding="utf8"))+ tc = cfg.get("text_config", cfg)+ n_v = tc.get("linear_num_value_heads", 32)+ n_k = tc.get("linear_num_key_heads", 16)+ only = re.compile(a.only) if a.only else None+ skipped = []++ simple, ba_pairs = {}, {}+ for name in idx.t:+ base = re.sub(r"\.lora_[AB]$", "", name)+ if only and not only.search(base):+ skipped.append(base)+ continue+ ab = "a" if name.endswith(".lora_A") else "b"+ if not is8:+ m = BA.match(base)+ if m:+ ba_pairs.setdefault((int(m.group(1)), m.group(2)), {})[ab] = name+ continue+ for rx, tpl in (RENAME_8B if is8 else RENAME):+ mm = rx.match(base)+ if mm:+ if tpl.startswith("SKIP:"):+ skipped.append(base + " [3D split tensor unimplemented]")+ break+ if tpl == "G": # 8b g_proj routes by layer type+ il = int(mm.group(1))+ dst = (f"blk.{il}.attn_gate.weight" if (il + 1) % 4 == 0+ else f"blk.{il}.ssm_g_a.weight")+ else:+ dst = rx.sub(tpl, base)+ simple.setdefault(dst, {})[ab] = name+ break+ else:+ if "pregate" not in base and "mlp.gate" not in base:+ raise SystemExit(f"unmapped LoRA family: {base}")+ if skipped:+ print("skip:", sorted(set(skipped))[:6], f"({len(skipped)} entries)")++ entries = [] # (model_name, A_f16 [r,K] torch, B_f16 [N,r] torch)+ for mname, d in sorted(simple.items()):+ A = idx.load(d["a"]); B = idx.load(d["b"])+ assert A.shape[0] == B.shape[1], (mname, A.shape, B.shape)+ entries.append((mname, A, B))+ # ssm_ba block-diagonal merge (with alpha/rank compensation: B ×(32/alpha·alpha/16→2))+ comp = 2.0 # target scale per path = 2.0; merged rank=32 ⇒ get_scale=alpha·s/32=1.0 ⇒ B needs ×2+ for il in sorted({k[0] for k in ba_pairs}):+ db, da = ba_pairs[(il, "b")], ba_pairs[(il, "a")]+ Ab, Bb = idx.load(db["a"]), idx.load(db["b"])+ Aa, Ba = idx.load(da["a"]), idx.load(da["b"])+ r = Ab.shape[0]+ A = np.concatenate([Ab, Aa], 0) # [2r, K]+ B = np.zeros((2 * n_v, 2 * r), dtype=np.float32)+ for out_row, (tag, j) in enumerate(ssm_ba_perm(n_k, n_v)):+ src_mat, src_row = (Bb, j) if tag == "b" else (Ba, j)+ cols = slice(0, r) if tag == "b" else slice(r, 2 * r)+ B[out_row, cols] = np.asarray(src_mat[src_row], dtype=np.float32) * comp+ entries.append((f"blk.{il}.ssm_ba.weight", A, B.astype(np.float16)))++ w = GgufWriter(out)+ w.kv_s("general.architecture", "bailingmoe3" if is8 else "qwen3next")+ w.kv_s("general.type", "adapter")+ w.kv_s("general.name", f"{stem}-lora (repack of lora_{stem}.safetensors)")+ w.kv_s("adapter.type", "lora")+ w.kv_s("adapter.name", f"edge0-{stem}")+ w.kv("adapter.lora.alpha", KV["f32"], struct.pack("<f", a.alpha))+ for mname, A, B in entries:+ w.register(mname + ".lora_a", T_F16, (A.shape[1], A.shape[0]), A.size * 2)+ w.register(mname + ".lora_b", T_F16, (B.shape[1], B.shape[0]), B.size * 2)+ w.finalize()+ for mname, A, B in entries:+ w.write(np.ascontiguousarray(A, np.float16).tobytes()); w.align_pad()+ w.write(np.ascontiguousarray(B, np.float16).tobytes()); w.align_pad()+ w.close(); idx.close()+ print(f"adapter: {out} tensors={2*len(entries)} pairs={len(entries)} (incl. ssm_ba merge ×{comp} compensation)")+ verify_against_base(out, "edge0-8b" if is8 else "edge0-35b")+++def verify_against_base(adapter_path, base_stem):+ """Cross-check gate: right after writing, verify (1) adapter names ⊆ base names+ (2) the upstream shape three-law (llama-adapter.cpp:358-371: a.ne0=base.ne0 ∧+ b.ne1=base.ne1 ∧ a.ne1=b.ne0; token_embd flip is a special case).+ Any miss/shape violation = hard throw, preventing the 'loads without error but+ never enters the graph' failure mode from recurring."""+ # gguf-py comes from the pinned vendored upstream (monorepo layout or bootstrap depot);+ # standalone checkouts fall back to an installed `gguf` package on sys.path.+ _here = os.path.dirname(os.path.abspath(__file__))+ _repo = os.path.dirname(_here)+ for _p in [os.path.join(x, "vendor", "llama.cpp", "gguf-py") for x in+ ([os.environ["EDGE0_DEPOT"]] if os.environ.get("EDGE0_DEPOT") else [])+ + [os.path.join(_repo, os.pardir), os.path.join(_repo, ".edge0")]]:+ if os.path.isdir(_p):+ sys.path.insert(0, _p)+ break+ from gguf import GGUFReader+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ base_path = os.path.join(root, "models", f"{base_stem}-gguf", f"{base_stem}.gguf")+ bt = {str(t.name): [int(x) for x in t.shape]+ for t in GGUFReader(base_path).tensors}+ ad = GGUFReader(adapter_path)+ A = {str(t.name)[:-7]: [int(x) for x in t.shape] for t in ad.tensors if str(t.name).endswith(".lora_a")}+ B = {str(t.name)[:-7]: [int(x) for x in t.shape] for t in ad.tensors if str(t.name).endswith(".lora_b")}+ miss, shape_bad = [], []+ for stem in sorted(A.keys() & B.keys()):+ b = bt.get(stem)+ if b is None:+ miss.append(stem); continue+ a, bb = A[stem], B[stem]+ if stem.startswith("token_embd"):+ ok = b[0] == bb[1] and b[1] == a[1] and a[1] == bb[0] # token_embd flip special case+ else:+ ok = b[0] == a[0] and b[1] == bb[1] and a[1] == bb[0]+ if not ok:+ shape_bad.append((stem, f"base={b} a={a} b={bb}"))+ if miss or shape_bad:+ raise SystemExit(f"cross-check gate RED: miss={len(miss)} {miss[:5]} shape_bad={len(shape_bad)} {shape_bad[:5]}")+ print(f"cross-check gate GREEN: {len(A.keys() & B.keys())} pairs all hit base {os.path.basename(base_path)} + shape three-law satisfied")+++if __name__ == "__main__":+ main()diff --git a/windows/tools/make_app_catalog.py b/windows/tools/make_app_catalog.pynew file mode 100644index 0000000..86f74d7--- /dev/null+++ b/windows/tools/make_app_catalog.py@@ -0,0 +1,38 @@+# -*- coding: utf8 -*-+"""tools/make_app_catalog.py — generator for the app's embedded tier table.+Reads the two per-tier manifests (8b=path+revision / 35b=name+rev-missing) and+normalizes them into catalog.json:+ {tier: {repo, rev:{modelscope:"master", hf:<sha>}, base:{modelscope,hf,hf_mirror},+ files:[{path,size,sha256,skip}], total_bytes, pool_mb:{35b:4096|8b:2048}}}+skip set = tensors the GGUF route never consumes (media/prerouter/.gitattributes/README).+Idempotent, safe to re-run."""+import json+import os++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(HERE)+HF_SHA = {"8b": None, "35b": "e21098e7faa916a00f5493795f12f20497d032bb"} # 8b falls back to manifest.revision+SKIP = {".gitattributes", "README.md"} # + per-tier media/prerouter added by the predicate below++cat = {}+for tier in ("8b", "35b"):+ m = json.load(open(os.path.join(ROOT, "models", f"fetch-manifest-edge0-{tier}.json"), encoding="utf8"))+ rev_hf = m.get("revision") or HF_SHA[tier]+ files, total = [], 0+ for f in m["files"]:+ p = f.get("path") or f.get("name")+ skip = p in SKIP or "prerouter" in p or p.endswith((".jpg", ".mp4"))+ files.append(dict(path=p, size=f["size"], sha256=f["sha256"], skip=bool(skip)))+ if not skip:+ total += f["size"]+ cat[tier] = dict(repo=m["repo"], rev=dict(modelscope="master", hf=rev_hf),+ files=files, total_bytes=total,+ pool_mb=(2048 if tier == "8b" else 4096))++out = os.path.join(ROOT, "app", "src-tauri", "catalog.json")+os.makedirs(os.path.dirname(out), exist_ok=True)+json.dump(cat, open(out, "w", encoding="utf8"), ensure_ascii=False, indent=1)+for t, c in cat.items():+ print(t, c["repo"], "rev_hf=", c["rev"]["hf"][:12],+ "pull=", sum(1 for f in c["files"] if not f["skip"]), "/", len(c["files"]),+ f"bytes={c['total_bytes']:,}")diff --git a/windows/tools/r3_bench.py b/windows/tools/r3_bench.pynew file mode 100644index 0000000..79b4eb6--- /dev/null+++ b/windows/tools/r3_bench.py@@ -0,0 +1,116 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""r3_bench.py — throughput measurement on the resident tier (48 GB, warm cache).++Each run: 3 reps — long warmup case (a 512-token warmup rep is discarded first) →+256-token greedy decode; parse prompt/eval tok/s from llama-completion; 5s idle+between reps. Absolute values are only meaningful within the same machine and+window when compared against the reference — cross-window comparison is always+suspect (measure on the same day / same process, or treat numbers as shape-only).++Usage: python tools/r3_bench.py --tier 35b [--reps 3]+"""+import argparse, json, os, re, subprocess, sys, time++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def resolve_bin_dir():+ """Engine dir — same contract as the app (paths.rs::bin_dir): EDGE0_BIN_DIR override,+ else monorepo depot build <repo>/../wt/win/..., else bootstrap <repo>/.edge0/wt/win/..."""+ env = os.environ.get("EDGE0_BIN_DIR")+ if env:+ return env+ for c in (os.path.join(ROOT, "..", "wt", "win", "build-vk", "bin", "Release"),+ os.path.join(ROOT, ".edge0", "wt", "win", "build-vk", "bin", "Release")):+ if os.path.isfile(os.path.join(c, "llama-completion.exe")):+ return c+ return os.path.join(ROOT, "..", "wt", "win", "build-vk", "bin", "Release")+++SERVER_BIN = resolve_bin_dir()+++def models_root(tier):+ """Where the GGUF lives — repo-local models/ wins when present (dev layout), else the+ app's model home (EDGE0_HOME, default ~/.edge0) where the download+convert step lands it."""+ home = os.environ.get("EDGE0_HOME") or os.path.join(os.path.expanduser("~"), ".edge0")+ roots = [os.path.join(ROOT, "models"), os.path.join(home, "models")]+ for r in roots:+ if os.path.isfile(os.path.join(r, f"edge0-{tier}-gguf", f"edge0-{tier}.gguf")):+ return r+ raise SystemExit(f"no edge0-{tier}.gguf under {roots[0]} or {roots[1]} "+ "— load/convert once in the app, or run tools/convert_mlx_to_gguf.py first")+++PROMPT = ("混合专家模型(MoE)通过稀疏激活把多个专家网络与门控路由组合起来:" * 12)+PAT = {+ "prompt": re.compile(r"prompt eval time =.*?,\s*([\d.]+) tokens per second"),+ "eval": re.compile(r"(?<!prompt )eval time =.*?,\s*([\d.]+) tokens per second"),+ "total_ms": re.compile(r"total time =\s*([\d.]+) ms"),+ "load_ms": re.compile(r"load time =\s*([\d.]+) ms"),+ "prompt_ms": re.compile(r"prompt eval time =\s*([\d.]+) ms"),+}+++def one(gguf, lora, n, tier):+ cmd = [os.path.join(SERVER_BIN, "llama-completion.exe"), "-m", gguf,+ "-ngl", "99", "-cmoe", "--temp", "0", "-n", str(n), "--seed", "7",+ "-no-cnv", "--no-display-prompt", "-p", PROMPT]+ if lora:+ cmd[3:3] = ["--lora", lora]+ t0 = time.time()+ r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf8", errors="replace")+ err = r.stderr or ""+ out = {"wall_s": round(time.time() - t0, 1)}+ for k, pat in PAT.items():+ m = pat.search(err)+ if m:+ out[k] = float(m.group(1))+ ev = re.search(r"n_ctx = (\d+)", err)+ out["n_ctx"] = int(ev.group(1)) if ev else None+ if "error" in err.lower() and "eval time" not in err:+ out["error"] = [l for l in err.splitlines() if "error" in l.lower()][:2]+ if "total_ms" in out and "prompt_ms" in out:+ dec_ms = out["total_ms"] - out["prompt_ms"] # total = generation end-to-end, excludes load (verified)+ out["decode_tps_derived"] = round(n * 1000 / dec_ms, 2) if dec_ms > 0 else None+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--tier", choices=["35b", "8b"], required=True)+ ap.add_argument("--reps", type=int, default=3)+ a = ap.parse_args()+ exe = os.path.join(SERVER_BIN, "llama-completion.exe")+ if not os.path.isfile(exe):+ raise SystemExit(f"llama-completion.exe not found in {SERVER_BIN} "+ "— build the engine (scripts/vendor-build.ps1) or set EDGE0_BIN_DIR")+ md = models_root(a.tier)+ gguf = os.path.join(md, f"edge0-{a.tier}-gguf", f"edge0-{a.tier}.gguf")+ lora = os.path.join(md, f"edge0-{a.tier}",+ f"lora_edge0_{a.tier}-gguf.gguf")+ rows = []+ warm = one(gguf, lora, 64, a.tier) # warmup (page cache + mmap fault-in), discarded+ print(f"warm(discard): {warm}", flush=True)+ for i in range(a.reps):+ time.sleep(5)+ m = one(gguf, lora, 256, a.tier)+ m["rep"] = i+ rows.append(m)+ print(f"rep{i}: {m}", flush=True)+ ok = [r for r in rows if "eval" in r]+ evs = sorted(r["eval"] for r in ok)+ prs = sorted(r["prompt"] for r in ok if "prompt" in r)+ summ = dict(tier=a.tier, reps=len(ok), decode_tps_med=evs[len(evs) // 2] if evs else None,+ decode_tps_min=evs[0] if evs else None, decode_tps_max=evs[-1] if evs else None,+ prefill_tps_med=prs[len(prs) // 2] if prs else None, rows=rows,+ note="48 GB tier, -cmoe -ngl99 with LoRA; compare against the same-machine reference")+ outp = os.path.join(ROOT, "benchmarks", "r3", f"bench_{a.tier}.json")+ os.makedirs(os.path.dirname(outp), exist_ok=True)+ json.dump(summ, open(outp, "w", encoding="utf8"), ensure_ascii=False, indent=1)+ print("BENCH", json.dumps({k: v for k, v in summ.items() if k != "rows"}, ensure_ascii=False))+++if __name__ == "__main__":+ main()diff --git a/windows/tools/repack_r3.py b/windows/tools/repack_r3.pynew file mode 100644index 0000000..c00907c--- /dev/null+++ b/windows/tools/repack_r3.py@@ -0,0 +1,289 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""repack_r3.py — 35b → GGUF with llama.cpp canonical naming (the runtime artifact).++Built on the lossless repack core (tools/repack_mlx_to_gguf.py, proven bit-exact),+this script does three things and nothing else:+ A. rename: MLX full names → qwen3next registered names+ (per qwen3next.cpp:31-129 / llama-arch.cpp:434-518)+ B. value transforms (each with its source of truth):+ - ssm_a = -exp(A_log) conversion/qwen.py:395-396, qwen3next.cpp:452+ - ssm_ba = in_proj_b/a row interleave [b,b,a,a]×16 groups qwen3next.cpp:421-446 (v-heads contiguous within a group)+ - conv1d = [C,4,1] squeeze last axis → dims flipped to ne{4,C}+ (row-major bytes unchanged, pure dims rewrite)+ - everything else stored directly: norm (+1 is already baked into the source+ of truth — NEVER add +1 a second time), gate int8→F32, BF16→F32+ C. metadata + tokenizer:+ expert_used_count=4, rope.dimension_count=64, recurrent_layers explicit array,+ no MTP/vision/pregate tensors (an unregistered tensor = hard throw at load time),+ tokens padded to 248320, pre=qwen2, add_bos=false, eos=im_end(248046),+ byte_fallback=true++Gates: tensor count / name-set identity against the registry; ba permutation+reversible; Q4_1 sampled pack two-sided sha. Output: <stem>.gguf.+"""+import argparse, json, math, os, re, struct, sys, time+import numpy as np+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from repack_mlx_to_gguf import (StIndex, GgufWriter, KV, T_F32, T_F16, T_Q4_1, ALIGN, QK41,+ DT_Q41, mlx_q_bytes, pack_q41_rows, deq_mlx_side, deq_gguf_side,+ sha16)+import repack_mlx_to_gguf as core++P = "language_model.model.layers.{}."+EMB, LMH, ONORM = "language_model.model.embed_tokens", "language_model.lm_head", "language_model.model.norm"+R3VER = "r3-1.0"+++def full_attn_layer(i, interval):+ return (i + 1) % interval == 0+++def build_name_table(nl, interval):+ """→ list[(r3_name, kind, src_key_or_pair)]"""+ t = [("token_embd.weight", "q41", EMB + ".weight"),+ ("output.weight", "q41", LMH + ".weight"),+ ("output_norm.weight", "f32raw", ONORM + ".weight")]+ for i in range(nl):+ b = P.format(i)+ rb = f"blk.{i}."+ t += [(rb + "attn_norm.weight", "f32raw", b + "input_layernorm.weight"),+ (rb + "post_attention_norm.weight", "f32raw", b + "post_attention_layernorm.weight")]+ if full_attn_layer(i, interval):+ t += [(rb + "attn_q.weight", "q41", b + "self_attn.q_proj.weight"),+ (rb + "attn_k.weight", "q41", b + "self_attn.k_proj.weight"),+ (rb + "attn_v.weight", "q41", b + "self_attn.v_proj.weight"),+ (rb + "attn_q_norm.weight", "f32raw", b + "self_attn.q_norm.weight"),+ (rb + "attn_k_norm.weight", "f32raw", b + "self_attn.k_norm.weight"),+ (rb + "attn_output.weight", "q41", b + "self_attn.o_proj.weight")]+ else:+ la = b + "linear_attn."+ t += [(rb + "attn_qkv.weight", "q41", la + "in_proj_qkv.weight"),+ (rb + "attn_gate.weight", "q41", la + "in_proj_z.weight"),+ (rb + "ssm_ba.weight", "ba", (la + "in_proj_b.weight", la + "in_proj_a.weight")),+ (rb + "ssm_conv1d.weight", "conv", la + "conv1d.weight"),+ (rb + "ssm_dt.bias", "f32raw", la + "dt_bias"),+ (rb + "ssm_a", "sa", la + "A_log"),+ (rb + "ssm_norm.weight", "f32raw", la + "norm.weight"),+ (rb + "ssm_out.weight", "q41", la + "out_proj.weight")]+ m = b + "mlp."+ t += [(rb + "ffn_gate_inp.weight", "f32i8", m + "gate.weight"),+ (rb + "ffn_gate_exps.weight", "q41", m + "switch_mlp.gate_proj.weight"),+ (rb + "ffn_up_exps.weight", "q41", m + "switch_mlp.up_proj.weight"),+ (rb + "ffn_down_exps.weight", "q41", m + "switch_mlp.down_proj.weight"),+ (rb + "ffn_gate_shexp.weight", "q41", m + "shared_expert.gate_proj.weight"),+ (rb + "ffn_up_shexp.weight", "q41", m + "shared_expert.up_proj.weight"),+ (rb + "ffn_down_shexp.weight", "q41", m + "shared_expert.down_proj.weight"),+ (rb + "ffn_gate_inp_shexp.weight", "f32i8_1d", m + "shared_expert_gate.weight")]+ return t+++def ssm_ba_perm(n_k, n_v):+ """group g row order = b[2g],b[2g+1],a[2g],a[2g+1] (v-heads contiguous within a group, qwen3next.cpp:421-446)."""+ order = []+ for g in range(n_k):+ order += [("b", 2 * g), ("b", 2 * g + 1), ("a", 2 * g), ("a", 2 * g + 1)]+ return order+++def load_ba(idx, kb, ka, n_k, n_v):+ """two source tensors (int4 g64, rows=n_v) → interleaved (2n_v, K) q/s/b arrays."""+ out = {}+ for tag, key in (("b", kb), ("a", ka)):+ w = idx.load(key); s = idx.load(key[:-7] + ".scales"); b = idx.load(key[:-7] + ".biases")+ out[tag] = (mlx_q_bytes(w.reshape(n_v, -1)).astype(np.float32), s.reshape(n_v, -1), b.reshape(n_v, -1))+ K = out["b"][0].shape[1]+ q = np.empty((2 * n_v, K), np.uint8); S = np.empty((2 * n_v, K // 64), np.float32); Bs = np.empty_like(S)+ for r, (tag, row) in enumerate(ssm_ba_perm(n_k, n_v)):+ q[r] = out[tag][0][row].astype(np.uint8); S[r] = out[tag][1][row]; Bs[r] = out[tag][2][row]+ return q, S, Bs, K+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--dir", required=True); ap.add_argument("--out", required=True)+ ap.add_argument("--verify", default="all")+ ap.add_argument("--dry", action="store_true")+ a = ap.parse_args()+ cfg = json.load(open(os.path.join(a.dir, "config.json"), encoding="utf8"))["text_config"]+ n_k, n_v = cfg["linear_num_key_heads"], cfg["linear_num_value_heads"]+ nl, intv = cfg["num_hidden_layers"], cfg["full_attention_interval"]+ table = build_name_table(nl, intv)+ names = [t[0] for t in table]+ assert len(names) == len(set(names)), "name-set collision"+ if a.dry:+ print(f"r3 registry entries={len(table)} (3+40*2+10*6+30*8+40*8=703 expected)")+ return+ idx = StIndex([os.path.join(a.dir, f) for f in sorted(os.listdir(a.dir))+ if re.fullmatch(r"model(-\d+-of-\d+)?\.safetensors", f)])+ os.makedirs(a.out, exist_ok=True)+ stem = os.path.basename(a.dir.rstrip("\\/"))+ gp = os.path.join(a.out, f"{stem}.gguf")+ t0, audit = time.time(), dict(tool=R3VER, tier=stem, mode="r3", gates=[], errors=[])+ w = GgufWriter(gp)++ # ---- metadata (required read set + overrides) ----+ kv = w.kv+ w.kv_s("general.architecture", "qwen3next")+ w.kv_s("general.name", "edge0-35b")+ A = "qwen3next." # this fork keys every KV with the arch prefix (gguf-py "{arch}.X" verified; the old "llm." spelling is wrong and will not load)+ for k, ty, v in [+ (A + "block_count", KV["u32"], nl), (A + "context_length", KV["u32"], cfg["max_position_embeddings"]),+ (A + "embedding_length", KV["u32"], cfg["hidden_size"]), (A + "feed_forward_length", KV["u32"], cfg["moe_intermediate_size"]),+ (A + "attention.head_count", KV["u32"], cfg["num_attention_heads"]),+ (A + "attention.head_count_kv", KV["u32"], cfg["num_key_value_heads"]),+ (A + "attention.key_length", KV["u32"], cfg["head_dim"]), (A + "attention.value_length", KV["u32"], cfg["head_dim"]),+ (A + "attention.layer_norm_rms_epsilon", KV["f32"], cfg["rms_norm_eps"]),+ (A + "rope.freq_base", KV["f32"], cfg["rope_parameters"]["rope_theta"]),+ (A + "expert_count", KV["u32"], cfg["num_experts"]), (A + "expert_used_count", KV["u32"], 4),+ (A + "expert_feed_forward_length", KV["u32"], cfg["moe_intermediate_size"]),+ (A + "expert_shared_feed_forward_length", KV["u32"], cfg["shared_expert_intermediate_size"]),+ (A + "ssm.conv_kernel", KV["u32"], cfg["linear_conv_kernel_dim"]),+ (A + "ssm.state_size", KV["u32"], cfg["linear_key_head_dim"]),+ (A + "ssm.group_count", KV["u32"], n_k), (A + "ssm.time_step_rank", KV["u32"], n_v),+ (A + "ssm.inner_size", KV["u32"], cfg["linear_value_head_dim"] * n_v),+ (A + "rope.dimension_count", KV["u32"], int(cfg["head_dim"] * cfg["partial_rotary_factor"])),+ (A + "full_attention_interval", KV["u32"], intv),+ ]:+ kv(k, ty, struct.pack("<I", v) if ty in (KV["u32"], KV["i32"]) else struct.pack("<f", v))+ kv("qwen3next.attention.recurrent_layers", KV["arr"],+ struct.pack("<I", 7) + struct.pack("<Q", nl) + b"".join(b"\x00" if full_attn_layer(i, intv) else b"\x01" for i in range(nl)))++ # ---- tokenizer (required: tokens/merges/model; vocab padded to 248320) ----+ tkj = json.load(open(os.path.join(a.dir, "tokenizer.json"), encoding="utf8"))+ vocab, merges = tkj["model"]["vocab"], tkj["model"]["merges"]+ toks = [None] * cfg["vocab_size"]+ for s, i in vocab.items():+ toks[i] = s+ for at in tkj["added_tokens"]:+ toks[at["id"]] = at["content"]+ for i in range(len(toks)):+ if toks[i] is None:+ toks[i] = f"<0x{255 - (i % 256):02X}>" # placeholder (high ids the source of truth never produces)+ tt = [1] * len(toks)+ for at in tkj["added_tokens"]:+ tt[at["id"]] = 3+ def arr(key, et, elems):+ kv(key, KV["arr"], struct.pack("<I", et) + struct.pack("<Q", len(elems)) + b"".join(elems))+ w.kv_s("tokenizer.ggml.model", "gpt2")+ arr("tokenizer.ggml.tokens", KV["str"], [w._str(s) for s in toks])+ arr("tokenizer.ggml.merges", KV["str"], [w._str(" ".join(m)) for m in merges])+ arr("tokenizer.ggml.scores", KV["f32"], [struct.pack("<f", 0.0) for _ in toks])+ arr("tokenizer.ggml.token_type", KV["i32"], [struct.pack("<i", x) for x in tt])+ w.kv("tokenizer.ggml.added_tokens_ids", KV["arr"],+ struct.pack("<I", KV["u32"]) + struct.pack("<Q", len(tkj["added_tokens"]))+ + b"".join(struct.pack("<I", x["id"]) for x in tkj["added_tokens"]))+ for k, v in [("tokenizer.ggml.bos_token_id", 248044), ("tokenizer.ggml.eos_token_id", 248046),+ ("tokenizer.ggml.padding_token_id", 248044)]:+ kv(k, KV["u32"], struct.pack("<I", v))+ kv("tokenizer.ggml.add_bos_token", KV["bool"], b"\x00")+ kv("tokenizer.ggml.add_eos_token", KV["bool"], b"\x00")+ kv("tokenizer.ggml.byte_fallback", KV["bool"], b"\x01")+ w.kv_s("tokenizer.ggml.pre", "qwen2")+ w.kv_s("tokenizer.chat_template", open(os.path.join(a.dir, "chat_template.jinja"), encoding="utf8").read())+ kv("tokenizer.ggml.eot_token_id", KV["u32"], struct.pack("<I", 248046))++ # ---- tensors (two passes: A registers dims/size, B streams writes + gates) ----+ def r3_spec(kind, src):+ """→ (tt, dims_ne, size). Pure shape arithmetic, no data loaded."""+ if kind == "ba":+ K = idx.t[src[0]][4][-1] * 8+ return T_Q4_1, (K, 2 * n_v), 2 * n_v * (K // QK41) * 20+ shp = idx.t[src][4]; dt = idx.t[src][3]+ if kind == "q41":+ K = shp[-1] * 8+ rows = int(np.prod(shp[:-1])) if len(shp) > 1 else 1+ return T_Q4_1, (K,) + tuple(reversed(shp[:-1])), rows * (K // QK41) * 20+ if kind == "f32i8":+ K = shp[-1] * 4+ rows = int(np.prod(shp[:-1])) if len(shp) > 1 else 1+ return T_F32, (K,) + tuple(reversed(shp[:-1])), rows * K * 4+ if kind == "f32i8_1d":+ K = shp[-1] * 4+ return T_F32, (K,), K * 4+ if kind == "conv":+ return T_F32, (shp[1], shp[0]), int(np.prod(shp)) * 4+ if kind == "sa":+ return T_F32, (shp[0],), shp[0] * 4+ return T_F32, (tuple(reversed(shp)) if len(shp) > 1 else (shp[0],)), int(np.prod(shp)) * 4++ for r3n, kind, src in table:+ tt, dims, size = r3_spec(kind, src)+ w.register(r3n, tt, dims, size)+ w.finalize()++ n_done = 0+ for r3n, kind, src in table:+ if kind == "q41":+ base = src[:-7]+ W = idx.load(src); S = idx.load(base + ".scales"); Bs = idx.load(base + ".biases")+ lead = W.shape[:-1]; rows = int(np.prod(lead)) if lead else 1+ Wf, Sf, Bsf = W.reshape(rows, -1), S.reshape(rows, -1), Bs.reshape(rows, -1)+ blocks, exm = pack_q41_rows(mlx_q_bytes(Wf), Sf, Bsf, src)+ w.write(blocks.tobytes()); w.align_pad()+ # sentinel gate: first row depacked on both sides, sha compared; if that row contains an exempt block, downgrade to record+ if rows:+ a_side = deq_mlx_side(mlx_q_bytes(Wf[:1]), Sf[:1], Bsf[:1])+ b_side = deq_gguf_side(blocks[:1])+ same = bool(sha16(a_side.tobytes()) == sha16(b_side.tobytes()))+ row0_ex = any(r == 0 for (r, _b) in exm)+ st = "OK" if same else ("EXEMPT" if row0_ex else "FAIL")+ audit["gates"].append(dict(t=r3n, sentinel=st))+ if st == "FAIL":+ audit["errors"].append(f"{r3n}: sentinel row non-exempt mismatch")+ elif kind in ("f32i8", "f32i8_1d"):+ base = src[:-7]+ W = idx.load(src); S = idx.load(base + ".scales"); Bs = idx.load(base + ".biases")+ rows = int(np.prod(W.shape[:-1])) if W.ndim > 1 else 1+ Wf, Sf, Bsf = W.reshape(rows, -1), S.reshape(rows, -1), Bs.reshape(rows, -1)+ q8 = Wf.view(np.uint8).reshape(rows, Wf.shape[1] * 4)+ v = deq_mlx_side(q8, Sf, Bsf)+ w.write(np.ascontiguousarray(v, np.float32).tobytes()); w.align_pad()+ elif kind == "f32raw":+ x = idx.load(src)+ w.write(np.ascontiguousarray(x, np.float32).tobytes()); w.align_pad()+ elif kind == "sa":+ x = idx.load(src)+ v = -np.exp(np.asarray(x, dtype=np.float32))+ v2 = np.array([-math.exp(float(t)) for t in x.ravel()], dtype=np.float32) # libm second path, cross-checked against numpy+ dv = np.abs(v - v2).max(initial=0.0)+ audit["gates"].append(dict(t=r3n, exp_dual_dev=float(dv)))+ if dv > 1e-5:+ audit["errors"].append(f"{r3n}: -exp dual-path deviation {dv:.2e} > 1e-5")+ w.write(np.ascontiguousarray(v, np.float32).tobytes()); w.align_pad()+ elif kind == "conv":+ x = idx.load(src) # [C,4,1]+ assert x.shape[-1] == 1+ y = np.ascontiguousarray(x.reshape(x.shape[0], x.shape[1]), dtype=np.float32)+ w.write(y.tobytes()); w.align_pad()+ elif kind == "ba":+ kb, ka = src+ q, S, Bs, K = load_ba(idx, kb, ka, n_k, n_v)+ blocks, _ = pack_q41_rows(q, S, Bs, "ssm_ba")+ w.write(blocks.tobytes()); w.align_pad()+ # reversibility gate: undo the permutation and compare against the pre-interleave source q rows for exact equality+ wb = idx.load(kb); wa = idx.load(ka)+ qb = mlx_q_bytes(wb.reshape(n_v, -1)); qa = mlx_q_bytes(wa.reshape(n_v, -1))+ rec = np.empty_like(q, dtype=np.uint8)+ for r, (tag, row) in enumerate(ssm_ba_perm(n_k, n_v)):+ rec[r] = (qb if tag == "b" else qa)[row]+ ok = bool((rec == q).all())+ audit["gates"].append(dict(t=r3n, ba_permute_reversible=ok))+ if not ok:+ audit["errors"].append(f"{r3n}: ba permutation not reversible")+ n_done += 1+ if n_done % 60 == 0 or n_done == len(table):+ print(f" {n_done}/{len(table)} {r3n:44s} {w.dlen/1e9:6.2f}GB {time.time()-t0:5.0f}s", flush=True)+ w.close(); idx.close()+ bad = [g for g in audit["gates"] if g.get("ok") is False or g.get("ba_permute_reversible") is False]+ audit["n_tensors"] = n_done; audit["elapsed_s"] = round(time.time() - t0, 1)+ v = "GREEN" if not bad and not audit["errors"] and n_done == len(table) else "RED"+ json.dump(dict(verdict=f"R3-artifact {v}", audit=audit, size=os.path.getsize(gp)),+ open(os.path.join(a.out, f"{stem}-audit.json"), "w"), ensure_ascii=False, indent=1)+ print(f"\nGGUF {gp} {os.path.getsize(gp)/1e9:.2f}GB tensors={n_done}/{len(table)} ⇒ R3-artifact {v}"+ f" (errors={audit['errors']})")+ return 0 if v == "GREEN" else 1+++if __name__ == "__main__":+ sys.exit(main() or 0)diff --git a/windows/tools/repack_r3_8b.py b/windows/tools/repack_r3_8b.pynew file mode 100644index 0000000..0a373ea--- /dev/null+++ b/windows/tools/repack_r3_8b.py@@ -0,0 +1,268 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""repack_r3_8b.py — 8b (BailingMoeV3/Ling-3) → bailingmoe3 canonical-naming GGUF.++The contract is the full reference table (conversion/bailingmoe3.py ++llama-arch.cpp + bailingmoe3.cpp):+ name strings (llama-arch.cpp table as-is): attn_q_a/attn_q_a_norm/attn_q_b/+ attn_kv_a_mqa/attn_kv_a_norm/attn_k_b/attn_v_b/attn_gate/+ ssm_conv1d_{q,k,v}/ssm_a(no .weight)/ssm_dt(.bias)/ssm_beta/ssm_f_a/ssm_g_a/+ ssm_norm/exp_probs_b(.bias)+ transforms (checked line-by-line against bailingmoe3.py):+ conv [C,1,4] → reshape(1,C,1,4) → ne{4,1,C,1}, bytes unchanged, F32+ ssm_a = torch.exp(A_log).reshape(-1,1) ← NOTE +exp here (35b uses −exp; do not mix them up)+ dt_bias [2048] elementwise → ssm_dt.bias stored directly as F32+ kv_b_proj → split + transpose (view(16,256,512) → [128 noope | 128 v] → k transpose(1,2))+ k_b/v_b are stored as **F32, not Q4_1**: the transpose scatters the quantization+ grouping axis (dim0=128 spans 128 original rows), so lossless repack is+ physically impossible; 6 layers x 8MB = 48MB cost, negligible.+ f_proj→ssm_f_a; g_proj→(KDA)ssm_g_a /(MLA)attn_gate; dense(MLA)→attn_output+ gate BF16→F32 stored directly (8b gate is NOT quantized, unlike 35b int8);+ expert_bias→exp_probs_b.bias F32+ all norms stored directly (bailing_hybrid sanitize has no +1 and no moveaxis;+ the source of truth is the final value multiplied directly)+ metadata: head_count_kv is a 24-element array ((i+1)%4==0 →1 else 0, bailingmoe3.py:55-56);+ key_length=576(=kv_lora+qk_rope) value_length=128 key_length_mla=192 value_length_mla=128;+ expert_gating_func=2(SIGMOID, llama-hparams.h:19) expert_weights_scale=2.5+ (config routed_scaling_factor) expert_weights_norm=true; kda.head_dim=128+ kda.safe_gate=true kda.gate_lower_bound=-5; leading_dense_block_count=1;+ rope.dimension_count=64; **tokenizer.ggml.pre="bailingmoe2"** (verified by hashing+ tokenizer.json against the fork, NOT qwen2); architecture string+ general.architecture=bailingmoe3.+pregate x66 stripped (sidecar feeds the prefetch router). Gates: tensor-count+identity / sentinel sha / kv_b transform reversibility spot-check / exp dual-path.+"""+import argparse, json, math, os, re, struct, sys, time+import numpy as np+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from repack_mlx_to_gguf import (StIndex, GgufWriter, KV, T_F32, T_F16, T_Q4_1, QK41, DT_Q41,+ mlx_q_bytes, pack_q41_rows, deq_mlx_side, deq_gguf_side, sha16)++FULL = lambda i: (i + 1) % 4 == 0 # MLA layer (bailingmoe3.py:39-42 same rule)+NL, E, KDA_DIM, HEADS = 24, 128, 2048, 16+R3VER = "r3-8b-1.0"+++def q41_src(idx, name):+ W = idx.load(name); base = name[:-7]+ return W, idx.load(base + ".scales"), idx.load(base + ".biases")+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--dir", default="models/edge0-8b")+ ap.add_argument("--out", default="models/edge0-8b-gguf")+ a = ap.parse_args()+ idx = StIndex([os.path.join(a.dir, f) for f in sorted(os.listdir(a.dir))+ if re.fullmatch(r"model(-\d+-of-\d+)?\.safetensors", f)])+ cfg = json.load(open(os.path.join(a.dir, "config.json"), encoding="utf8"))+ tkj = json.load(open(os.path.join(a.dir, "tokenizer.json"), encoding="utf8"))+ A = "bailingmoe3."+ P = "model.layers.{}."+ ATT = P + "attention."+ MLP = P + "mlp."++ # ---- tensor table: (dst_name, kind, src); kind ∈ q41/f32raw/conv/sa/kvb ----+ table = [("token_embd.weight", "q41", "model.word_embeddings.weight"),+ ("output.weight", "q41", "lm_head.weight"),+ ("output_norm.weight", "f32raw", "model.norm.weight")]+ for i in range(NL):+ at_, mp = ATT.format(i), MLP.format(i)+ table += [(f"blk.{i}.attn_norm.weight", "f32raw", P.format(i) + "input_layernorm.weight"),+ (f"blk.{i}.ffn_norm.weight", "f32raw", P.format(i) + "post_attention_layernorm.weight")]+ if FULL(i):+ table += [(f"blk.{i}.attn_q_a.weight", "q41", at_ + "q_a_proj.weight"),+ (f"blk.{i}.attn_q_a_norm.weight", "f32raw", at_ + "q_a_layernorm.weight"),+ (f"blk.{i}.attn_q_b.weight", "q41", at_ + "q_b_proj.weight"),+ (f"blk.{i}.attn_kv_a_mqa.weight", "q41", at_ + "kv_a_proj_with_mqa.weight"),+ (f"blk.{i}.attn_kv_a_norm.weight", "f32raw", at_ + "kv_a_layernorm.weight"),+ (f"blk.{i}.attn_k_b.weight", "kvb_k", at_ + "kv_b_proj.weight"),+ (f"blk.{i}.attn_v_b.weight", "kvb_v", at_ + "kv_b_proj.weight"),+ (f"blk.{i}.attn_gate.weight", "q41", at_ + "g_proj.weight"),+ (f"blk.{i}.attn_output.weight", "q41", at_ + "dense.weight")]+ else:+ table += [(f"blk.{i}.attn_q.weight", "q41", at_ + "q_proj.weight"),+ (f"blk.{i}.attn_k.weight", "q41", at_ + "k_proj.weight"),+ (f"blk.{i}.attn_v.weight", "q41", at_ + "v_proj.weight"),+ (f"blk.{i}.ssm_conv1d_q.weight", "conv", at_ + "q_conv1d.weight"),+ (f"blk.{i}.ssm_conv1d_k.weight", "conv", at_ + "k_conv1d.weight"),+ (f"blk.{i}.ssm_conv1d_v.weight", "conv", at_ + "v_conv1d.weight"),+ (f"blk.{i}.ssm_a", "sa", at_ + "A_log"),+ (f"blk.{i}.ssm_dt.bias", "f32raw", at_ + "dt_bias"),+ (f"blk.{i}.ssm_beta.weight", "q41", at_ + "b_proj.weight"),+ (f"blk.{i}.ssm_f_a.weight", "q41", at_ + "f_proj.weight"),+ (f"blk.{i}.ssm_g_a.weight", "q41", at_ + "g_proj.weight"),+ (f"blk.{i}.ssm_norm.weight", "f32raw", at_ + "o_norm.weight"),+ (f"blk.{i}.attn_output.weight", "q41", at_ + "o_proj.weight")]+ if i == 0:+ table += [(f"blk.0.ffn_gate.weight", "q41", mp + "gate_proj.weight"),+ (f"blk.0.ffn_up.weight", "q41", mp + "up_proj.weight"),+ (f"blk.0.ffn_down.weight", "q41", mp + "down_proj.weight")]+ else:+ table += [(f"blk.{i}.ffn_gate_inp.weight", "f32raw", mp + "gate.weight"),+ (f"blk.{i}.exp_probs_b.bias", "f32raw", mp + "gate.expert_bias"),+ (f"blk.{i}.ffn_gate_exps.weight", "q41", mp + "experts.gate_proj.weight"),+ (f"blk.{i}.ffn_up_exps.weight", "q41", mp + "experts.up_proj.weight"),+ (f"blk.{i}.ffn_down_exps.weight", "q41", mp + "experts.down_proj.weight"),+ (f"blk.{i}.ffn_gate_shexp.weight", "q41", mp + "shared_experts.gate_proj.weight"),+ (f"blk.{i}.ffn_up_shexp.weight", "q41", mp + "shared_experts.up_proj.weight"),+ (f"blk.{i}.ffn_down_shexp.weight", "q41", mp + "shared_experts.down_proj.weight")]+ miss = [t for t in table if t[2] not in idx.t]+ assert not miss, f"source tensor missing: {miss[:5]}"+ names = [t[0] for t in table]+ assert len(names) == len(set(names))++ # ---- metadata ----+ os.makedirs(a.out, exist_ok=True)+ stem = "edge0-8b"+ gp = os.path.join(a.out, f"{stem}.gguf")+ w = GgufWriter(gp)+ w.kv_s("general.architecture", "bailingmoe3")+ w.kv_s("general.type", "model")+ w.kv_s("general.name", "edge0-8b")+ w.kv("general.alignment", KV["u32"], struct.pack("<I", 32))+ u = lambda v: struct.pack("<I", v)+ f32 = lambda v: struct.pack("<f", v)+ b1 = lambda v: b"\x01" if v else b"\x00"+ for k, ty, v in [+ (A + "block_count", KV["u32"], u(NL)), (A + "context_length", KV["u32"], u(cfg["max_position_embeddings"])),+ (A + "embedding_length", KV["u32"], u(cfg["hidden_size"])), (A + "feed_forward_length", KV["u32"], u(cfg["intermediate_size"])),+ (A + "attention.head_count", KV["u32"], u(HEADS)),+ (A + "attention.key_length", KV["u32"], u(cfg["kv_lora_rank"] + cfg["qk_rope_head_dim"])),+ (A + "attention.value_length", KV["u32"], u(cfg["head_dim"])),+ (A + "attention.key_length_mla", KV["u32"], u(cfg["qk_head_dim"])),+ (A + "attention.value_length_mla", KV["u32"], u(cfg["v_head_dim"])),+ (A + "attention.q_lora_rank", KV["u32"], u(cfg["q_lora_rank"])),+ (A + "attention.kv_lora_rank", KV["u32"], u(cfg["kv_lora_rank"])),+ (A + "rope.freq_base", KV["f32"], f32(float(cfg["rope_theta"]))),+ (A + "rope.dimension_count", KV["u32"], u(cfg["qk_rope_head_dim"])),+ (A + "attention.layer_norm_rms_epsilon", KV["f32"], f32(cfg["rms_norm_eps"])),+ (A + "vocab_size", KV["u32"], u(cfg["vocab_size"])),+ (A + "ssm.conv_kernel", KV["u32"], u(cfg["short_conv_kernel_size"])),+ (A + "kda.head_dim", KV["u32"], u(cfg["head_dim"])),+ (A + "expert_count", KV["u32"], u(E)), (A + "expert_used_count", KV["u32"], u(cfg["num_experts_per_tok"])),+ (A + "expert_group_count", KV["u32"], u(cfg["n_group"])), (A + "expert_group_used_count", KV["u32"], u(cfg["topk_group"])),+ (A + "expert_gating_func", KV["u32"], u(2)),+ (A + "expert_weights_scale", KV["f32"], f32(cfg["routed_scaling_factor"])),+ (A + "expert_feed_forward_length", KV["u32"], u(cfg["moe_intermediate_size"])),+ (A + "expert_shared_feed_forward_length", KV["u32"], u(cfg.get("shared_expert_intermediate_size", cfg["moe_intermediate_size"]))),+ (A + "expert_shared_count", KV["u32"], u(1)),+ (A + "leading_dense_block_count", KV["u32"], u(cfg["first_k_dense_replace"])),+ ]:+ w.kv(k, ty, v)+ w.kv(A + "kda.safe_gate", KV["bool"], b1(True))+ w.kv(A + "kda.gate_lower_bound", KV["f32"], f32(cfg["kda_lower_bound"]))+ w.kv(A + "expert_weights_norm", KV["bool"], b1(cfg.get("norm_topk_prob", True)))+ w.kv(A + "attention.head_count_kv", KV["arr"], struct.pack("<I", KV["u32"]) + struct.pack("<Q", NL)+ + b"".join(u(1 if FULL(i) else 0) for i in range(NL)))+ w.kv_s("tokenizer.ggml.model", "gpt2")+ w.kv_s("tokenizer.ggml.pre", "bailingmoe2")++ # tokenizer arrays+ vocab = tkj["model"]["vocab"]; toks = [None] * cfg["vocab_size"]+ for s, i2 in vocab.items():+ toks[i2] = s+ for at in tkj["added_tokens"]:+ toks[at["id"]] = at["content"]+ tt = [1] * len(toks)+ for at in tkj["added_tokens"]:+ tt[at["id"]] = 3+ n_pad = sum(1 for x in toks if x is None)+ for j, x in enumerate(toks):+ if x is None:+ toks[j] = f"<0x{j:06X}>"++ def arr(key, et, elems):+ w.kv(key, KV["arr"], struct.pack("<I", et) + struct.pack("<Q", len(elems)) + b"".join(elems))+ arr("tokenizer.ggml.tokens", KV["str"], [w._str(s) for s in toks])+ arr("tokenizer.ggml.merges", KV["str"],+ [w._str(" ".join(m) if isinstance(m, list) else m) for m in tkj["model"]["merges"]])+ arr("tokenizer.ggml.scores", KV["f32"], [f32(0.0) for _ in toks])+ arr("tokenizer.ggml.token_type", KV["i32"], [struct.pack("<i", x) for x in tt])+ w.kv("tokenizer.ggml.bos_token_id", KV["u32"], u(156891))+ w.kv("tokenizer.ggml.eos_token_id", KV["u32"], u(cfg.get("eos_token_id", 156895)))+ w.kv("tokenizer.ggml.padding_token_id", KV["u32"], u(cfg.get("pad_token_id", 156892)))+ w.kv("tokenizer.ggml.add_bos_token", KV["bool"], b1(False))+ w.kv("tokenizer.ggml.add_eos_token", KV["bool"], b1(False))+ w.kv("tokenizer.ggml.byte_fallback", KV["bool"], b1(True))+ ct = os.path.join(a.dir, "chat_template.jinja")+ if os.path.isfile(ct):+ w.kv_s("tokenizer.chat_template", open(ct, encoding="utf8").read())++ # ---- two-pass tensors ----+ def spec(kind, src):+ shp = idx.t[src][4]+ if kind == "kvb_k":+ return T_F32, (cfg["qk_nope_head_dim"], cfg["kv_lora_rank"], HEADS), HEADS * cfg["kv_lora_rank"] * cfg["qk_nope_head_dim"] * 4+ if kind == "kvb_v":+ return T_F32, (cfg["kv_lora_rank"], cfg["v_head_dim"], HEADS), HEADS * cfg["kv_lora_rank"] * cfg["v_head_dim"] * 4+ if kind == "conv":+ return T_F32, (shp[2], 1, shp[0], 1), int(np.prod(shp)) * 4+ if kind == "sa":+ return T_F32, (1, shp[0]), shp[0] * 4 # bailingmoe3.cpp:89 create {1, n_head}+ if kind == "f32raw":+ return T_F32, (tuple(reversed(shp)) if len(shp) > 1 else (shp[0],)), int(np.prod(shp)) * 4+ K = shp[-1] * 8+ rows = int(np.prod(shp[:-1])) if len(shp) > 1 else 1+ return T_Q4_1, (K,) + tuple(reversed(shp[:-1])), rows * (K // QK41) * 20++ for dst, kind, src in table:+ tt_, dims, size = spec(kind, src)+ w.register(dst, tt_, dims, size)+ ds = w.finalize()+ audit = dict(tool=R3VER, gates=[], errors=[])+ t0 = time.time()+ for n, (dst, kind, src) in enumerate(table):+ if kind == "q41":+ W, S, Bs = q41_src(idx, src)+ rows = int(np.prod(W.shape[:-1])) if W.ndim > 1 else 1+ Wf, Sf, Bsf = W.reshape(rows, -1), S.reshape(rows, -1), Bs.reshape(rows, -1)+ blocks, exm = pack_q41_rows(mlx_q_bytes(Wf), Sf, Bsf, src)+ w.write(blocks.tobytes()); w.align_pad()+ a_side = deq_mlx_side(mlx_q_bytes(Wf[:1]), Sf[:1], Bsf[:1])+ same = sha16(a_side.tobytes()) == sha16(deq_gguf_side(blocks[:1]).tobytes())+ st = "OK" if same else ("EXEMPT" if any(r == 0 for r, _ in exm) else "FAIL")+ audit["gates"].append((dst, st))+ if st == "FAIL":+ audit["errors"].append(dst)+ elif kind == "kvb_k" or kind == "kvb_v":+ W, S, Bs = q41_src(idx, src)+ K = W.shape[-1] * 8+ q = mlx_q_bytes(W.reshape(4096, -1))+ v = deq_mlx_side(q, S.reshape(4096, -1), Bs.reshape(4096, -1)) # (4096,512)+ kv = v.reshape(HEADS, 256, K)+ kt = np.ascontiguousarray(kv[:, :128, :].transpose(0, 2, 1), np.float32) # (16,512,128)+ vv = np.ascontiguousarray(kv[:, 128:, :], np.float32) # (16,128,512)+ payload = kt.tobytes() if kind == "kvb_k" else vv.tobytes()+ w.write(payload); w.align_pad()+ elif kind == "conv":+ x = idx.load(src) # [C,1,4]+ y = np.ascontiguousarray(x.reshape(1, x.shape[0], 1, x.shape[2]), np.float32)+ w.write(y.tobytes()); w.align_pad()+ elif kind == "sa":+ x = idx.load(src)+ v = np.exp(np.asarray(x, dtype=np.float32))+ v2 = np.array([math.exp(float(t)) for t in x.ravel()], np.float32)+ dv = float(np.abs(v - v2).max(initial=0.0))+ if dv > 1e-5:+ audit["errors"].append(f"{dst} exp dev {dv}")+ y = np.ascontiguousarray(v.reshape(-1, 1), np.float32)+ w.write(y.tobytes()); w.align_pad() # ne {1,16} via reversed((16,1))+ else: # f32raw+ x = idx.load(src)+ w.write(np.ascontiguousarray(x, np.float32).tobytes()); w.align_pad()+ if (n + 1) % 100 == 0:+ print(f" {n+1}/{len(table)} {dst} {time.time()-t0:.0f}s", flush=True)+ w.close(); idx.close()+ ng = len(audit["gates"]); bad = [g for g in audit["gates"] if g[1] != "OK"]+ audit.update(n_tensors=len(table), pad_tokens=n_pad, elapsed_s=round(time.time() - t0, 1))+ json.dump(dict(audit=audit, size=os.path.getsize(gp),+ verdict="R3-8b-artifact " + ("GREEN" if not bad and not audit["errors"] else "RED")),+ open(os.path.join(a.out, f"{stem}-audit.json"), "w"), ensure_ascii=False, indent=1)+ print(f"GGUF {gp} {os.path.getsize(gp)/1e9:.2f}GB tensors={len(table)} gate-mismatch={len(bad)} errors={audit['errors'][:5]}")+ print("sa dims check:", spec("sa", "model.layers.0.attention.A_log")[1])+ return 0 if not bad and not audit["errors"] else 1+++if __name__ == "__main__":+ sys.exit(main() or 0)