From e85ba469dd72043925813e89800fe4a6e80658c8 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 5 Sep 2026 21:55:02 +0200 Subject: [PATCH 01/16] feat: Integrate plugin support into RPC context and update route handling --- headless-rust/src/web/mod.rs | 10 ++- headless-rust/src/web/rpc.rs | 169 +++-------------------------------- 2 files changed, 20 insertions(+), 159 deletions(-) diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index 4ce0429..e581992 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -30,6 +30,7 @@ pub fn build_app( violation_tx: broadcast::Sender, armed: Arc, armed_tx: broadcast::Sender, + plugins: Arc, ) -> Router { let (flash_tx, _) = broadcast::channel::(32); @@ -44,6 +45,7 @@ pub fn build_app( violation_tx, armed, armed_tx, + plugins: plugins.clone(), }); // 10 MB payload capacity, 5s keepalive ping interval to keep Wi-Fi sleep-disabled, @@ -72,7 +74,7 @@ pub fn build_app( .allow_methods(Any) .allow_headers(Any); - Router::new() + let mut router = Router::new() .route("/api/health", get(routes::health)) .route("/api/network", get(routes::network)) .route("/image", get(routes::get_image)) @@ -90,7 +92,11 @@ pub fn build_app( .route("/generate_204", get(routes::generate_204_handler)) .route("/gen_204", get(routes::generate_204_handler)) // Apple / macOS captive portal probe - .route("/hotspot-detect.html", get(routes::apple_hotspot_handler)) + .route("/hotspot-detect.html", get(routes::apple_hotspot_handler)); + + router = plugins.register_routes(router); + + router .fallback(routes::static_handler) .layer(layer) .layer(cors) diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 94833a7..1865287 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -42,6 +42,7 @@ pub struct RpcContext { pub violation_tx: broadcast::Sender, pub armed: Arc, pub armed_tx: broadcast::Sender, + pub plugins: Arc, } pub async fn handle_rpc(ctx: &RpcContext, req: RpcRequest) -> RpcResponse { @@ -170,140 +171,10 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul Ok(serde_json::to_value(v).unwrap()) } - // ─── Lap Sessions ───────────────────────────────────────────────────── - "createLapSession" => { - let lap_mode = params["lapMode"].as_str().unwrap_or("single").to_string(); - let db = ctx.db.clone(); - let session = tokio::task::spawn_blocking(move || { - let conn = db.lock(); - crate::db::laps::create_lap_session(&conn, &lap_mode) - }) - .await - .map_err(|e| e.to_string())? - .map_err(|e| e.to_string())?; - Ok(serde_json::to_value(session).unwrap()) - } - - "closeLapSession" => { - let id = params["id"].as_i64().ok_or("Missing id parameter")?; - let db = ctx.db.clone(); - tokio::task::spawn_blocking(move || { - let conn = db.lock(); - crate::db::laps::close_lap_session(&conn, id) - }) - .await - .map_err(|e| e.to_string())? - .map_err(|e| e.to_string())?; - Ok(Value::Null) - } - - "saveLap" => { - let input: SaveLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; - let store = ctx.store.clone(); - let db = ctx.db.clone(); - let lap = tokio::task::spawn_blocking(move || -> Result { - let start_img_path = if let Some(ref b64) = input.start_image_base64 { - store.save_base64_image(b64).ok() - } else { - None - }; - - let end_img_path = if let Some(ref b64) = input.end_image_base64 { - store.save_base64_image(b64).ok() - } else { - None - }; - - let conn = db.lock(); - crate::db::laps::insert_lap( - &conn, - &input, - start_img_path.as_deref(), - end_img_path.as_deref(), - ) - .map_err(|e| e.to_string()) - }) - .await - .map_err(|e| e.to_string())??; - - Ok(serde_json::to_value(lap).unwrap()) - } - - "getLapSessions" => { - let page = params["page"].as_i64().unwrap_or(1); - let limit = params["limit"].as_i64().unwrap_or(20); - let db = ctx.db.clone(); - let (sessions, total) = tokio::task::spawn_blocking(move || { - let conn = db.lock(); - crate::db::laps::get_lap_sessions(&conn, page, limit) - }) - .await - .map_err(|e| e.to_string())? - .map_err(|e| e.to_string())?; - - Ok(json!({ - "sessions": sessions, - "total": total - })) - } - - "getLapSessionById" => { - let id = params["id"].as_i64().ok_or("Missing id parameter")?; - let db = ctx.db.clone(); - let session = tokio::task::spawn_blocking(move || { - let conn = db.lock(); - crate::db::laps::get_lap_session_by_id(&conn, id) - }) - .await - .map_err(|e| e.to_string())? - .map_err(|e| e.to_string())?; - Ok(serde_json::to_value(session).unwrap()) - } - - "deleteLapSession" => { - let id = params["id"].as_i64().ok_or("Missing id parameter")?; - let db = ctx.db.clone(); - let store = ctx.store.clone(); - tokio::task::spawn_blocking(move || -> Result<(), String> { - let img_paths = { - let conn = db.lock(); - crate::db::laps::get_lap_image_paths_for_session(&conn, id).unwrap_or_default() - }; - { - let conn = db.lock(); - crate::db::laps::delete_lap_session(&conn, id).map_err(|e| e.to_string())?; - } - for p in img_paths { - store.delete_image(&p); - } - Ok(()) - }) - .await - .map_err(|e| e.to_string())??; - Ok(Value::Null) - } - - "deleteLap" => { - let id = params["id"].as_i64().ok_or("Missing id parameter")?; - let db = ctx.db.clone(); - let store = ctx.store.clone(); - tokio::task::spawn_blocking(move || -> Result<(), String> { - let img_paths = { - let conn = db.lock(); - crate::db::laps::get_lap_image_paths_for_lap(&conn, id).unwrap_or_default() - }; - { - let conn = db.lock(); - crate::db::laps::delete_lap(&conn, id).map_err(|e| e.to_string())?; - } - for p in img_paths { - store.delete_image(&p); - } - Ok(()) - }) - .await - .map_err(|e| e.to_string())??; - Ok(Value::Null) + // ─── Plugins ────────────────────────────────────────────────────────── + "getPlugins" => { + let plugins = ctx.plugins.list_plugins(); + Ok(serde_json::to_value(plugins).unwrap()) } // ─── Images ─────────────────────────────────────────────────────────── @@ -849,28 +720,6 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul Ok(serde_json::to_value(table).unwrap()) } - "syncLapToTeable" => { - let input: SyncLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; - let db = ctx.db.clone(); - let settings = tokio::task::spawn_blocking(move || { - let conn = db.lock(); - crate::db::settings::get_settings(&conn) - }) - .await - .map_err(|e| e.to_string())? - .map_err(|e| e.to_string())?; - - ctx.teable - .sync_lap( - &settings.teable_url, - &settings.teable_token, - &settings.teable_table_id, - &input, - ) - .await?; - Ok(Value::Null) - } - // ─── Firmware Flasher ───────────────────────────────────────────────── "testGithubToken" => { let token = params["token"].as_str().unwrap_or(""); @@ -942,7 +791,13 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "ok": true })), - _ => Err(format!("Method '{}' not found", method)), + _ => { + if let Some(res) = ctx.plugins.handle_rpc(method, params).await { + res + } else { + Err(format!("Method '{}' not found", method)) + } + } } } From 89cfd24fb9c2699c7c1f5ed8c536d803b9b99655 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 5 Sep 2026 21:55:35 +0200 Subject: [PATCH 02/16] feat: Implement Lap Timer plugin with database integration and RPC methods --- headless-rust/src/main.rs | 21 +- headless-rust/src/plugins/laptimer/db.rs | 251 ++++++++++++++++++++++ headless-rust/src/plugins/laptimer/mod.rs | 35 +++ headless-rust/src/plugins/laptimer/rpc.rs | 188 ++++++++++++++++ headless-rust/src/plugins/mod.rs | 156 ++++++++++++++ 5 files changed, 650 insertions(+), 1 deletion(-) create mode 100644 headless-rust/src/plugins/laptimer/db.rs create mode 100644 headless-rust/src/plugins/laptimer/mod.rs create mode 100644 headless-rust/src/plugins/laptimer/rpc.rs create mode 100644 headless-rust/src/plugins/mod.rs diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index f7a3be1..fb25a1f 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -4,6 +4,7 @@ mod db; mod integrations; mod models; mod network; +mod plugins; mod serial; mod storage; mod web; @@ -105,6 +106,23 @@ async fn main() -> Result<(), Box> { let (armed_tx, _) = tokio::sync::broadcast::channel::(32); let pipeline_armed = armed.clone(); + // ─── Plugin System Initialization ──────────────────────────────────────── + let plugin_ctx = plugins::PluginContext { + config: config.clone(), + db: db.clone(), + store: store.clone(), + camera: camera.clone(), + serial: serial.clone(), + armed: armed.clone(), + armed_tx: armed_tx.clone(), + }; + let mut plugin_reg = plugins::PluginRegistry::new(); + // ponytail: modular lap timer plugin isolated from core daemon + plugin_reg.register(Box::new(plugins::laptimer::LapTimerPlugin::new())); + plugin_reg.init(plugin_ctx)?; + let plugin_registry = std::sync::Arc::new(plugin_reg); + let pipeline_plugins = plugin_registry.clone(); + // ─── Instant Shutter Trigger Pipeline (<10ms latency) ───────────────────── let (violation_tx, _) = tokio::sync::broadcast::channel::(32); let pipeline_violation_tx = violation_tx.clone(); @@ -117,6 +135,7 @@ async fn main() -> Result<(), Box> { loop { match serial_rx.recv().await { Ok(msg) => { + pipeline_plugins.on_serial_event(&msg); if let models::SerialStatusPayload::Speeding { value, direction, .. } = msg { if !pipeline_armed.load(std::sync::atomic::Ordering::SeqCst) { tracing::debug!("[trigger-pipeline] Speeding detected ({} km/h) but system is DISARMED — skipping capture", value); @@ -176,7 +195,7 @@ async fn main() -> Result<(), Box> { // Build and launch Axum web server let bind_addr = format!("{}:{}", config.host, config.port); - let app = web::build_app(config, db, store, camera, serial, violation_tx, armed, armed_tx); + let app = web::build_app(config, db, store, camera, serial, violation_tx, armed, armed_tx, plugin_registry); let listener = tokio::net::TcpListener::bind(&bind_addr).await?; tracing::info!(" 🚀 Server listening on http://{}", bind_addr); axum::serve(listener, app).await?; diff --git a/headless-rust/src/plugins/laptimer/db.rs b/headless-rust/src/plugins/laptimer/db.rs new file mode 100644 index 0000000..ec242d9 --- /dev/null +++ b/headless-rust/src/plugins/laptimer/db.rs @@ -0,0 +1,251 @@ +use super::models::{Lap, LapSession, LapSessionWithLaps, SaveLapInput}; +use chrono::Utc; +use rusqlite::{params, Connection, Result}; + +pub fn init_tables(conn: &Connection) -> Result<()> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS lap_sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + startedAt TEXT NOT NULL, + endedAt TEXT, + lapMode TEXT NOT NULL, + createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + CREATE INDEX IF NOT EXISTS idx_lap_sessions_started ON lap_sessions(startedAt); + + CREATE TABLE IF NOT EXISTS laps ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sessionId INTEGER NOT NULL REFERENCES lap_sessions(id) ON DELETE CASCADE, + lapNumber INTEGER NOT NULL, + startTimestamp INTEGER NOT NULL, + endTimestamp INTEGER NOT NULL, + durationMs INTEGER NOT NULL, + speedAtStart REAL NOT NULL, + speedAtEnd REAL NOT NULL, + startImagePath TEXT, + endImagePath TEXT + ); + CREATE INDEX IF NOT EXISTS idx_laps_session ON laps(sessionId);", + )?; + Ok(()) +} + +pub fn create_lap_session(conn: &Connection, lap_mode: &str) -> Result { + let now = Utc::now().to_rfc3339(); + conn.execute( + "INSERT INTO lap_sessions (startedAt, lapMode, createdAt) VALUES (?, ?, ?)", + params![now, lap_mode, now], + )?; + + let id = conn.last_insert_rowid(); + + Ok(LapSession { + id, + started_at: now.clone(), + ended_at: None, + lap_mode: lap_mode.to_string(), + created_at: now, + }) +} + +pub fn close_lap_session(conn: &Connection, id: i64) -> Result<()> { + let now = Utc::now().to_rfc3339(); + conn.execute( + "UPDATE lap_sessions SET endedAt = ? WHERE id = ?", + params![now, id], + )?; + Ok(()) +} + +pub fn insert_lap( + conn: &Connection, + input: &SaveLapInput, + start_image_path: Option<&str>, + end_image_path: Option<&str>, +) -> Result { + conn.execute( + "INSERT INTO laps ( + sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, startImagePath, endImagePath + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + params![ + input.session_id, + input.lap_number, + input.start_timestamp, + input.end_timestamp, + input.duration_ms, + input.speed_at_start, + input.speed_at_end, + start_image_path, + end_image_path, + ], + )?; + + let id = conn.last_insert_rowid(); + + Ok(Lap { + id, + session_id: input.session_id, + lap_number: input.lap_number, + start_timestamp: input.start_timestamp, + end_timestamp: input.end_timestamp, + duration_ms: input.duration_ms, + speed_at_start: input.speed_at_start, + speed_at_end: input.speed_at_end, + start_image_path: start_image_path.map(|s| s.to_string()), + end_image_path: end_image_path.map(|s| s.to_string()), + }) +} + +pub fn get_lap_sessions( + conn: &Connection, + page: i64, + limit: i64, +) -> Result<(Vec, i64)> { + let mut count_stmt = conn.prepare("SELECT COUNT(*) FROM lap_sessions")?; + let total: i64 = count_stmt.query_row([], |r| r.get(0))?; + + let offset = (page.max(1) - 1) * limit; + let mut session_stmt = conn.prepare( + "SELECT id, startedAt, endedAt, lapMode, createdAt + FROM lap_sessions ORDER BY startedAt DESC LIMIT ? OFFSET ?", + )?; + + let session_rows = session_stmt.query_map(params![limit, offset], |row| { + Ok(LapSession { + id: row.get(0)?, + started_at: row.get(1)?, + ended_at: row.get(2)?, + lap_mode: row.get(3)?, + created_at: row.get(4)?, + }) + })?; + + let mut sessions = Vec::new(); + for s in session_rows { + let session = s?; + let laps = get_laps_for_session(conn, session.id)?; + sessions.push(LapSessionWithLaps { + id: session.id, + started_at: session.started_at, + ended_at: session.ended_at, + lap_mode: session.lap_mode, + created_at: session.created_at, + laps, + }); + } + + Ok((sessions, total)) +} + +pub fn get_lap_session_by_id(conn: &Connection, id: i64) -> Result> { + let mut stmt = conn.prepare( + "SELECT id, startedAt, endedAt, lapMode, createdAt FROM lap_sessions WHERE id = ?", + )?; + + let mut rows = stmt.query_map(params![id], |row| { + Ok(LapSession { + id: row.get(0)?, + started_at: row.get(1)?, + ended_at: row.get(2)?, + lap_mode: row.get(3)?, + created_at: row.get(4)?, + }) + })?; + + if let Some(row) = rows.next() { + let s = row?; + let laps = get_laps_for_session(conn, s.id)?; + Ok(Some(LapSessionWithLaps { + id: s.id, + started_at: s.started_at, + ended_at: s.ended_at, + lap_mode: s.lap_mode, + created_at: s.created_at, + laps, + })) + } else { + Ok(None) + } +} + +fn get_laps_for_session(conn: &Connection, session_id: i64) -> Result> { + let mut stmt = conn.prepare( + "SELECT id, sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, startImagePath, endImagePath + FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC", + )?; + + let rows = stmt.query_map(params![session_id], |row| { + Ok(Lap { + id: row.get(0)?, + session_id: row.get(1)?, + lap_number: row.get(2)?, + start_timestamp: row.get(3)?, + end_timestamp: row.get(4)?, + duration_ms: row.get(5)?, + speed_at_start: row.get(6)?, + speed_at_end: row.get(7)?, + start_image_path: row.get(8)?, + end_image_path: row.get(9)?, + }) + })?; + + let mut laps = Vec::new(); + for l in rows { + laps.push(l?); + } + Ok(laps) +} + +pub fn get_lap_image_paths_for_session(conn: &Connection, session_id: i64) -> Result> { + let mut stmt = conn.prepare("SELECT startImagePath, endImagePath FROM laps WHERE sessionId = ?")?; + let rows = stmt.query_map(params![session_id], |row| { + let start: Option = row.get(0)?; + let end: Option = row.get(1)?; + Ok((start, end)) + })?; + + let mut paths = Vec::new(); + for r in rows { + let (start, end) = r?; + if let Some(s) = start { + paths.push(s); + } + if let Some(e) = end { + paths.push(e); + } + } + Ok(paths) +} + +pub fn get_lap_image_paths_for_lap(conn: &Connection, lap_id: i64) -> Result> { + let mut stmt = conn.prepare("SELECT startImagePath, endImagePath FROM laps WHERE id = ?")?; + let mut rows = stmt.query_map(params![lap_id], |row| { + let start: Option = row.get(0)?; + let end: Option = row.get(1)?; + Ok((start, end)) + })?; + + let mut paths = Vec::new(); + if let Some(r) = rows.next() { + let (start, end) = r?; + if let Some(s) = start { + paths.push(s); + } + if let Some(e) = end { + paths.push(e); + } + } + Ok(paths) +} + +pub fn delete_lap_session(conn: &Connection, id: i64) -> Result<()> { + conn.execute("DELETE FROM lap_sessions WHERE id = ?", params![id])?; + Ok(()) +} + +pub fn delete_lap(conn: &Connection, id: i64) -> Result<()> { + conn.execute("DELETE FROM laps WHERE id = ?", params![id])?; + Ok(()) +} diff --git a/headless-rust/src/plugins/laptimer/mod.rs b/headless-rust/src/plugins/laptimer/mod.rs new file mode 100644 index 0000000..75a877a --- /dev/null +++ b/headless-rust/src/plugins/laptimer/mod.rs @@ -0,0 +1,35 @@ +pub mod db; +pub mod models; +pub mod rpc; + +use crate::plugins::{Plugin, PluginContext, RpcRegistry}; + +pub struct LapTimerPlugin; + +impl LapTimerPlugin { + pub fn new() -> Self { + Self + } +} + +impl Plugin for LapTimerPlugin { + fn id(&self) -> &'static str { + "laptimer" + } + + fn name(&self) -> &'static str { + "Lap Timer" + } + + fn init(&mut self, ctx: &PluginContext) -> Result<(), Box> { + let conn = ctx.db.lock(); + db::init_tables(&conn)?; + tracing::info!("[plugin:laptimer] Initialized database tables"); + Ok(()) + } + + fn register_rpc(&self, registry: &mut RpcRegistry) { + rpc::register_rpc_methods(registry); + tracing::info!("[plugin:laptimer] Registered RPC methods"); + } +} diff --git a/headless-rust/src/plugins/laptimer/rpc.rs b/headless-rust/src/plugins/laptimer/rpc.rs new file mode 100644 index 0000000..a41f840 --- /dev/null +++ b/headless-rust/src/plugins/laptimer/rpc.rs @@ -0,0 +1,188 @@ +use super::db; +use super::models::{Lap, SaveLapInput, SyncLapInput}; +use crate::plugins::RpcRegistry; +use serde_json::{json, Value}; + +// ponytail: register lap timer methods directly without dynamic reflection or macro bloat +pub fn register_rpc_methods(registry: &mut RpcRegistry) { + registry.register("createLapSession", |ctx, params| async move { + let lap_mode = params["lapMode"].as_str().unwrap_or("single").to_string(); + let db = ctx.db.clone(); + let session = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + db::create_lap_session(&conn, &lap_mode) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(session).unwrap()) + }); + + registry.register("closeLapSession", |ctx, params| async move { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + db::close_lap_session(&conn, id) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(Value::Null) + }); + + registry.register("saveLap", |ctx, params| async move { + let input: SaveLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; + let store = ctx.store.clone(); + let db = ctx.db.clone(); + let lap = tokio::task::spawn_blocking(move || -> Result { + let start_img_path = if let Some(ref b64) = input.start_image_base64 { + store.save_base64_image(b64).ok() + } else { + None + }; + + let end_img_path = if let Some(ref b64) = input.end_image_base64 { + store.save_base64_image(b64).ok() + } else { + None + }; + + let conn = db.lock(); + db::insert_lap( + &conn, + &input, + start_img_path.as_deref(), + end_img_path.as_deref(), + ) + .map_err(|e| e.to_string()) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(serde_json::to_value(lap).unwrap()) + }); + + registry.register("getLapSessions", |ctx, params| async move { + let page = params["page"].as_i64().unwrap_or(1); + let limit = params["limit"].as_i64().unwrap_or(20); + let db = ctx.db.clone(); + let (sessions, total) = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + db::get_lap_sessions(&conn, page, limit) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + Ok(json!({ + "sessions": sessions, + "total": total + })) + }); + + registry.register("getLapSessionById", |ctx, params| async move { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let session = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + db::get_lap_session_by_id(&conn, id) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(session).unwrap()) + }); + + registry.register("deleteLapSession", |ctx, params| async move { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let store = ctx.store.clone(); + tokio::task::spawn_blocking(move || -> Result<(), String> { + let img_paths = { + let conn = db.lock(); + db::get_lap_image_paths_for_session(&conn, id).unwrap_or_default() + }; + { + let conn = db.lock(); + db::delete_lap_session(&conn, id).map_err(|e| e.to_string())?; + } + for p in img_paths { + store.delete_image(&p); + } + Ok(()) + }) + .await + .map_err(|e| e.to_string())??; + Ok(Value::Null) + }); + + registry.register("deleteLap", |ctx, params| async move { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let store = ctx.store.clone(); + tokio::task::spawn_blocking(move || -> Result<(), String> { + let img_paths = { + let conn = db.lock(); + db::get_lap_image_paths_for_lap(&conn, id).unwrap_or_default() + }; + { + let conn = db.lock(); + db::delete_lap(&conn, id).map_err(|e| e.to_string())?; + } + for p in img_paths { + store.delete_image(&p); + } + Ok(()) + }) + .await + .map_err(|e| e.to_string())??; + Ok(Value::Null) + }); + + registry.register("syncLapToTeable", |ctx, params| async move { + let input: SyncLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let teable = crate::integrations::teable::TeableClient::new(); + // Convert to core SyncLapInput representation if needed + let core_input = crate::models::SyncLapInput { + lap: crate::models::Lap { + id: input.lap.id, + session_id: input.lap.session_id, + lap_number: input.lap.lap_number, + start_timestamp: input.lap.start_timestamp, + end_timestamp: input.lap.end_timestamp, + duration_ms: input.lap.duration_ms, + speed_at_start: input.lap.speed_at_start, + speed_at_end: input.lap.speed_at_end, + start_image_path: input.lap.start_image_path, + end_image_path: input.lap.end_image_path, + }, + session: crate::models::LapSession { + id: input.session.id, + started_at: input.session.started_at, + ended_at: input.session.ended_at, + lap_mode: input.session.lap_mode, + created_at: input.session.created_at, + }, + }; + + teable + .sync_lap( + &settings.teable_url, + &settings.teable_token, + &settings.teable_table_id, + &core_input, + ) + .await?; + Ok(Value::Null) + }); +} diff --git a/headless-rust/src/plugins/mod.rs b/headless-rust/src/plugins/mod.rs new file mode 100644 index 0000000..edefc3a --- /dev/null +++ b/headless-rust/src/plugins/mod.rs @@ -0,0 +1,156 @@ +pub mod laptimer; + +use crate::camera::CameraService; +use crate::config::AppConfig; +use crate::db::Database; +use crate::models::SerialStatusPayload; +use crate::serial::SerialService; +use crate::storage::FileStore; +use axum::Router; +use serde_json::Value; +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; +use tokio::sync::broadcast; + +// ponytail: minimal context passed to plugins without leaking web server internals +#[derive(Clone)] +#[allow(dead_code)] +pub struct PluginContext { + pub config: AppConfig, + pub db: Database, + pub store: FileStore, + pub camera: Arc, + pub serial: Arc, + pub armed: Arc, + pub armed_tx: broadcast::Sender, +} + +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; +pub type RpcHandler = Box BoxFuture<'static, Result> + Send + Sync>; + +// ponytail: simple rpc method map instead of complex dynamic reflection +#[derive(Default)] +pub struct RpcRegistry { + handlers: HashMap, +} + +impl RpcRegistry { + pub fn new() -> Self { + Self { + handlers: HashMap::new(), + } + } + + pub fn register(&mut self, method: &str, handler: F) + where + F: Fn(PluginContext, Value) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + { + self.handlers.insert( + method.to_string(), + Box::new(move |ctx, params| Box::pin(handler(ctx, params))), + ); + } + + pub async fn dispatch(&self, method: &str, ctx: &PluginContext, params: Value) -> Option> { + if let Some(handler) = self.handlers.get(method) { + Some(handler(ctx.clone(), params).await) + } else { + None + } + } + + #[allow(dead_code)] + pub fn has_method(&self, method: &str) -> bool { + self.handlers.contains_key(method) + } +} + +pub trait Plugin: Send + Sync + 'static { + fn id(&self) -> &'static str; + fn name(&self) -> &'static str; + fn init(&mut self, _ctx: &PluginContext) -> Result<(), Box> { + Ok(()) + } + fn register_rpc(&self, _registry: &mut RpcRegistry) {} + fn register_routes( + &self, + router: Router>, + ) -> Router> { + router + } + fn on_serial_event(&self, _msg: &SerialStatusPayload, _ctx: &PluginContext) {} +} + +pub struct PluginRegistry { + plugins: Vec>, + rpc_registry: Arc, + ctx: Option, +} + +impl PluginRegistry { + pub fn new() -> Self { + Self { + plugins: Vec::new(), + rpc_registry: Arc::new(RpcRegistry::new()), + ctx: None, + } + } + + pub fn register(&mut self, plugin: Box) { + self.plugins.push(plugin); + } + + pub fn init(&mut self, ctx: PluginContext) -> Result<(), Box> { + let mut rpc = RpcRegistry::new(); + for plugin in &mut self.plugins { + plugin.init(&ctx)?; + plugin.register_rpc(&mut rpc); + } + self.rpc_registry = Arc::new(rpc); + self.ctx = Some(ctx); + Ok(()) + } + + pub fn register_routes( + &self, + mut router: Router>, + ) -> Router> { + for plugin in &self.plugins { + router = plugin.register_routes(router); + } + router + } + + pub fn list_plugins(&self) -> Vec { + self.plugins + .iter() + .map(|p| { + serde_json::json!({ + "id": p.id(), + "name": p.name(), + "enabled": true + }) + }) + .collect() + } + + pub async fn handle_rpc(&self, method: &str, params: Value) -> Option> { + if let Some(ref ctx) = self.ctx { + self.rpc_registry.dispatch(method, ctx, params).await + } else { + None + } + } + + pub fn on_serial_event(&self, msg: &SerialStatusPayload) { + if let Some(ref ctx) = self.ctx { + for plugin in &self.plugins { + plugin.on_serial_event(msg, ctx); + } + } + } +} From b769a6ca34f0633e6e581ada99111ef8037cae98 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 5 Sep 2026 21:55:44 +0200 Subject: [PATCH 03/16] feat: Move lap timer data models to plugin module and re-export for use --- headless-rust/src/db/laps.rs | 223 ------------------- headless-rust/src/models.rs | 78 +------ headless-rust/src/plugins/laptimer/models.rs | 75 +++++++ 3 files changed, 80 insertions(+), 296 deletions(-) delete mode 100644 headless-rust/src/db/laps.rs create mode 100644 headless-rust/src/plugins/laptimer/models.rs diff --git a/headless-rust/src/db/laps.rs b/headless-rust/src/db/laps.rs deleted file mode 100644 index ba11eb5..0000000 --- a/headless-rust/src/db/laps.rs +++ /dev/null @@ -1,223 +0,0 @@ -use crate::models::{Lap, LapSession, LapSessionWithLaps, SaveLapInput}; -use chrono::Utc; -use rusqlite::{params, Connection, Result}; - -pub fn create_lap_session(conn: &Connection, lap_mode: &str) -> Result { - let now = Utc::now().to_rfc3339(); - conn.execute( - "INSERT INTO lap_sessions (startedAt, lapMode, createdAt) VALUES (?, ?, ?)", - params![now, lap_mode, now], - )?; - - let id = conn.last_insert_rowid(); - - Ok(LapSession { - id, - started_at: now.clone(), - ended_at: None, - lap_mode: lap_mode.to_string(), - created_at: now, - }) -} - -pub fn close_lap_session(conn: &Connection, id: i64) -> Result<()> { - let now = Utc::now().to_rfc3339(); - conn.execute( - "UPDATE lap_sessions SET endedAt = ? WHERE id = ?", - params![now, id], - )?; - Ok(()) -} - -pub fn insert_lap( - conn: &Connection, - input: &SaveLapInput, - start_image_path: Option<&str>, - end_image_path: Option<&str>, -) -> Result { - conn.execute( - "INSERT INTO laps ( - sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, - speedAtStart, speedAtEnd, startImagePath, endImagePath - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", - params![ - input.session_id, - input.lap_number, - input.start_timestamp, - input.end_timestamp, - input.duration_ms, - input.speed_at_start, - input.speed_at_end, - start_image_path, - end_image_path, - ], - )?; - - let id = conn.last_insert_rowid(); - - Ok(Lap { - id, - session_id: input.session_id, - lap_number: input.lap_number, - start_timestamp: input.start_timestamp, - end_timestamp: input.end_timestamp, - duration_ms: input.duration_ms, - speed_at_start: input.speed_at_start, - speed_at_end: input.speed_at_end, - start_image_path: start_image_path.map(|s| s.to_string()), - end_image_path: end_image_path.map(|s| s.to_string()), - }) -} - -pub fn get_lap_sessions( - conn: &Connection, - page: i64, - limit: i64, -) -> Result<(Vec, i64)> { - let mut count_stmt = conn.prepare("SELECT COUNT(*) FROM lap_sessions")?; - let total: i64 = count_stmt.query_row([], |r| r.get(0))?; - - let offset = (page.max(1) - 1) * limit; - let mut session_stmt = conn.prepare( - "SELECT id, startedAt, endedAt, lapMode, createdAt - FROM lap_sessions ORDER BY startedAt DESC LIMIT ? OFFSET ?", - )?; - - let session_rows = session_stmt.query_map(params![limit, offset], |row| { - Ok(LapSession { - id: row.get(0)?, - started_at: row.get(1)?, - ended_at: row.get(2)?, - lap_mode: row.get(3)?, - created_at: row.get(4)?, - }) - })?; - - let mut sessions = Vec::new(); - for s in session_rows { - let session = s?; - let laps = get_laps_for_session(conn, session.id)?; - sessions.push(LapSessionWithLaps { - id: session.id, - started_at: session.started_at, - ended_at: session.ended_at, - lap_mode: session.lap_mode, - created_at: session.created_at, - laps, - }); - } - - Ok((sessions, total)) -} - -pub fn get_lap_session_by_id(conn: &Connection, id: i64) -> Result> { - let mut stmt = conn.prepare( - "SELECT id, startedAt, endedAt, lapMode, createdAt FROM lap_sessions WHERE id = ?", - )?; - - let mut rows = stmt.query_map(params![id], |row| { - Ok(LapSession { - id: row.get(0)?, - started_at: row.get(1)?, - ended_at: row.get(2)?, - lap_mode: row.get(3)?, - created_at: row.get(4)?, - }) - })?; - - if let Some(row) = rows.next() { - let s = row?; - let laps = get_laps_for_session(conn, s.id)?; - Ok(Some(LapSessionWithLaps { - id: s.id, - started_at: s.started_at, - ended_at: s.ended_at, - lap_mode: s.lap_mode, - created_at: s.created_at, - laps, - })) - } else { - Ok(None) - } -} - -fn get_laps_for_session(conn: &Connection, session_id: i64) -> Result> { - let mut stmt = conn.prepare( - "SELECT id, sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, - speedAtStart, speedAtEnd, startImagePath, endImagePath - FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC", - )?; - - let rows = stmt.query_map(params![session_id], |row| { - Ok(Lap { - id: row.get(0)?, - session_id: row.get(1)?, - lap_number: row.get(2)?, - start_timestamp: row.get(3)?, - end_timestamp: row.get(4)?, - duration_ms: row.get(5)?, - speed_at_start: row.get(6)?, - speed_at_end: row.get(7)?, - start_image_path: row.get(8)?, - end_image_path: row.get(9)?, - }) - })?; - - let mut laps = Vec::new(); - for l in rows { - laps.push(l?); - } - Ok(laps) -} - -pub fn get_lap_image_paths_for_session(conn: &Connection, session_id: i64) -> Result> { - let mut stmt = conn.prepare("SELECT startImagePath, endImagePath FROM laps WHERE sessionId = ?")?; - let rows = stmt.query_map(params![session_id], |row| { - let start: Option = row.get(0)?; - let end: Option = row.get(1)?; - Ok((start, end)) - })?; - - let mut paths = Vec::new(); - for r in rows { - let (start, end) = r?; - if let Some(s) = start { - paths.push(s); - } - if let Some(e) = end { - paths.push(e); - } - } - Ok(paths) -} - -pub fn get_lap_image_paths_for_lap(conn: &Connection, lap_id: i64) -> Result> { - let mut stmt = conn.prepare("SELECT startImagePath, endImagePath FROM laps WHERE id = ?")?; - let mut rows = stmt.query_map(params![lap_id], |row| { - let start: Option = row.get(0)?; - let end: Option = row.get(1)?; - Ok((start, end)) - })?; - - let mut paths = Vec::new(); - if let Some(r) = rows.next() { - let (start, end) = r?; - if let Some(s) = start { - paths.push(s); - } - if let Some(e) = end { - paths.push(e); - } - } - Ok(paths) -} - -pub fn delete_lap_session(conn: &Connection, id: i64) -> Result<()> { - conn.execute("DELETE FROM lap_sessions WHERE id = ?", params![id])?; - Ok(()) -} - -pub fn delete_lap(conn: &Connection, id: i64) -> Result<()> { - conn.execute("DELETE FROM laps WHERE id = ?", params![id])?; - Ok(()) -} diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index 07aaca5..70b2f74 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -254,72 +254,11 @@ pub struct ViolationPage { pub total: i64, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LapSession { - pub id: i64, - pub started_at: String, - pub ended_at: Option, - pub lap_mode: String, - pub created_at: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Lap { - pub id: i64, - pub session_id: i64, - pub lap_number: i64, - pub start_timestamp: i64, - pub end_timestamp: i64, - pub duration_ms: i64, - pub speed_at_start: f64, - pub speed_at_end: f64, - pub start_image_path: Option, - pub end_image_path: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LapSessionWithLaps { - pub id: i64, - pub started_at: String, - pub ended_at: Option, - pub lap_mode: String, - pub created_at: String, - pub laps: Vec, -} - -fn deserialize_duration_ms<'de, D>(deserializer: D) -> Result -where - D: serde::Deserializer<'de>, -{ - #[derive(Deserialize)] - #[serde(untagged)] - enum IntOrFloat { - Int(i64), - Float(f64), - } - match IntOrFloat::deserialize(deserializer)? { - IntOrFloat::Int(i) => Ok(i), - IntOrFloat::Float(f) => Ok(f.round() as i64), - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SaveLapInput { - pub session_id: i64, - pub lap_number: i64, - pub start_timestamp: i64, - pub end_timestamp: i64, - #[serde(deserialize_with = "deserialize_duration_ms")] - pub duration_ms: i64, - pub speed_at_start: f64, - pub speed_at_end: f64, - pub start_image_base64: Option, - pub end_image_base64: Option, -} +// ponytail: lap timer data models re-exported from plugin +#[allow(unused_imports)] +pub use crate::plugins::laptimer::models::{ + Lap, LapSession, LapSessionWithLaps, SaveLapInput, SyncLapInput, +}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -458,13 +397,6 @@ pub struct TeableSchemaCheck { pub missing_fields: Vec, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SyncLapInput { - pub lap: Lap, - pub session: LapSession, -} - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ExportSkinnedResult { pub exported: usize, diff --git a/headless-rust/src/plugins/laptimer/models.rs b/headless-rust/src/plugins/laptimer/models.rs new file mode 100644 index 0000000..e1f7c20 --- /dev/null +++ b/headless-rust/src/plugins/laptimer/models.rs @@ -0,0 +1,75 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LapSession { + pub id: i64, + pub started_at: String, + pub ended_at: Option, + pub lap_mode: String, + pub created_at: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Lap { + pub id: i64, + pub session_id: i64, + pub lap_number: i64, + pub start_timestamp: i64, + pub end_timestamp: i64, + pub duration_ms: i64, + pub speed_at_start: f64, + pub speed_at_end: f64, + pub start_image_path: Option, + pub end_image_path: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LapSessionWithLaps { + pub id: i64, + pub started_at: String, + pub ended_at: Option, + pub lap_mode: String, + pub created_at: String, + pub laps: Vec, +} + +fn deserialize_duration_ms<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + #[derive(Deserialize)] + #[serde(untagged)] + enum IntOrFloat { + Int(i64), + Float(f64), + } + match IntOrFloat::deserialize(deserializer)? { + IntOrFloat::Int(i) => Ok(i), + IntOrFloat::Float(f) => Ok(f.round() as i64), + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SaveLapInput { + pub session_id: i64, + pub lap_number: i64, + pub start_timestamp: i64, + pub end_timestamp: i64, + #[serde(deserialize_with = "deserialize_duration_ms")] + pub duration_ms: i64, + pub speed_at_start: f64, + pub speed_at_end: f64, + pub start_image_base64: Option, + pub end_image_base64: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SyncLapInput { + pub lap: Lap, + pub session: LapSession, +} From 26b8a677fb855d67444122e9212c2d77e1785af9 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 5 Sep 2026 21:55:51 +0200 Subject: [PATCH 04/16] refactor: Remove unused lap-related database tables and clean up comments --- headless-rust/src/db/mod.rs | 28 ++-------------------------- 1 file changed, 2 insertions(+), 26 deletions(-) diff --git a/headless-rust/src/db/mod.rs b/headless-rust/src/db/mod.rs index 4e2152f..1c7a32b 100644 --- a/headless-rust/src/db/mod.rs +++ b/headless-rust/src/db/mod.rs @@ -1,4 +1,3 @@ -pub mod laps; pub mod settings; pub mod violations; @@ -22,7 +21,7 @@ impl Database { PRAGMA busy_timeout = 5000;", )?; - // Tables + // Core tables conn.execute_batch( "CREATE TABLE IF NOT EXISTS speed_violations ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -38,30 +37,7 @@ impl Database { CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS lap_sessions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - startedAt TEXT NOT NULL, - endedAt TEXT, - lapMode TEXT NOT NULL, - createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP - ); - CREATE INDEX IF NOT EXISTS idx_lap_sessions_started ON lap_sessions(startedAt); - - CREATE TABLE IF NOT EXISTS laps ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sessionId INTEGER NOT NULL REFERENCES lap_sessions(id) ON DELETE CASCADE, - lapNumber INTEGER NOT NULL, - startTimestamp INTEGER NOT NULL, - endTimestamp INTEGER NOT NULL, - durationMs INTEGER NOT NULL, - speedAtStart REAL NOT NULL, - speedAtEnd REAL NOT NULL, - startImagePath TEXT, - endImagePath TEXT - ); - CREATE INDEX IF NOT EXISTS idx_laps_session ON laps(sessionId);", + );", )?; // Initialize default settings if not existing From 4135f9d30053cbdf4a3330c9f57c76b9687f95c6 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 5 Sep 2026 21:56:12 +0200 Subject: [PATCH 05/16] feat(laptimer): implement lap timer plugin with session management and UI components - Add LapRow component for displaying individual lap details with delete functionality. - Create LapsPage component to manage live and history lap sessions using tabs. - Implement LiveSessionTab for managing live lap sessions, including start/stop controls and lap display. - Introduce SessionCard component for displaying lap session summaries and details. - Develop a Zustand store for managing lap state, settings, and history. - Register the lap timer plugin in the plugin registry for integration with the app. - Update routing to include lap timer pages and settings. - Modify measurement and system slices to support lap timer functionality. - Enhance test server to validate lap timer plugin RPC methods. --- headless-rust/frontend/src/App.tsx | 4 +- .../src/components/NavigationMenu.tsx | 53 +++++++---- headless-rust/frontend/src/plugins/index.ts | 8 ++ .../components/LapImageThumbnails.tsx | 0 .../laptimer}/components/LapTimerDisplay.tsx | 12 ++- .../components/LapTimerSettingsTab.tsx} | 8 +- .../laptimer/components/LapTimerSidePanel.tsx | 14 +++ .../laptimer}/hooks/useLiveLapTimer.ts | 6 +- .../frontend/src/plugins/laptimer/index.ts | 57 ++++++++++++ .../laptimer/routes}/HistoryTab.tsx | 8 +- .../laptimer/routes}/LapRow.tsx | 6 +- .../laptimer/routes/LapsPage.tsx} | 14 +-- .../laptimer/routes}/LiveSessionTab.tsx | 18 ++-- .../laptimer/routes}/SessionCard.tsx | 0 .../lapSlice.ts => plugins/laptimer/store.ts} | 90 +++++-------------- .../frontend/src/plugins/registry.ts | 88 ++++++++++++++++++ headless-rust/frontend/src/plugins/types.ts | 33 +++++++ headless-rust/frontend/src/routes/__root.tsx | 3 - headless-rust/frontend/src/routes/index.tsx | 14 ++- .../frontend/src/routes/settings.tsx | 50 +++++------ .../src/stores/slices/measurementSlice.ts | 30 +++---- .../frontend/src/stores/slices/systemSlice.ts | 7 +- .../frontend/src/stores/useAppStore.ts | 4 +- headless-rust/scripts/test-server.ts | 18 ++++ 24 files changed, 349 insertions(+), 196 deletions(-) create mode 100644 headless-rust/frontend/src/plugins/index.ts rename headless-rust/frontend/src/{ => plugins/laptimer}/components/LapImageThumbnails.tsx (100%) rename headless-rust/frontend/src/{ => plugins/laptimer}/components/LapTimerDisplay.tsx (89%) rename headless-rust/frontend/src/{routes/settings/LapTimerTab.tsx => plugins/laptimer/components/LapTimerSettingsTab.tsx} (94%) create mode 100644 headless-rust/frontend/src/plugins/laptimer/components/LapTimerSidePanel.tsx rename headless-rust/frontend/src/{ => plugins/laptimer}/hooks/useLiveLapTimer.ts (81%) create mode 100644 headless-rust/frontend/src/plugins/laptimer/index.ts rename headless-rust/frontend/src/{routes/laps => plugins/laptimer/routes}/HistoryTab.tsx (92%) rename headless-rust/frontend/src/{routes/laps => plugins/laptimer/routes}/LapRow.tsx (94%) rename headless-rust/frontend/src/{routes/laps.tsx => plugins/laptimer/routes/LapsPage.tsx} (79%) rename headless-rust/frontend/src/{routes/laps => plugins/laptimer/routes}/LiveSessionTab.tsx (92%) rename headless-rust/frontend/src/{routes/laps => plugins/laptimer/routes}/SessionCard.tsx (100%) rename headless-rust/frontend/src/{stores/slices/lapSlice.ts => plugins/laptimer/store.ts} (60%) create mode 100644 headless-rust/frontend/src/plugins/registry.ts create mode 100644 headless-rust/frontend/src/plugins/types.ts diff --git a/headless-rust/frontend/src/App.tsx b/headless-rust/frontend/src/App.tsx index ffaa34b..4f60073 100644 --- a/headless-rust/frontend/src/App.tsx +++ b/headless-rust/frontend/src/App.tsx @@ -6,9 +6,9 @@ import { IndexRoute } from "@/routes/index"; import { ViolationsRoute } from "@/routes/violations"; import { SettingsRoute } from "@/routes/settings"; import { AboutRoute } from "@/routes/about"; -import { LapsRoute } from "@/routes/laps"; import { TeableRoute } from "@/routes/teable"; import { SetupRoute } from "@/routes/setup"; +import { pluginRegistry } from "@/plugins"; // ─── Router ───────────────────────────────────────────────────────────────────── @@ -17,9 +17,9 @@ const routeTree = RootRoute.addChildren([ ViolationsRoute, SettingsRoute, AboutRoute, - LapsRoute, TeableRoute, SetupRoute, + ...pluginRegistry.getRoutes(RootRoute), ]); const history = createMemoryHistory({ initialEntries: ["/"] }); diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx index 48f56b1..242288e 100644 --- a/headless-rust/frontend/src/components/NavigationMenu.tsx +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -1,14 +1,14 @@ import { Link } from "@tanstack/react-router"; import { HugeiconsIcon } from "@hugeicons/react"; -import { Timer01Icon, DashboardCircleIcon } from "@hugeicons/core-free-icons"; +import { DashboardCircleIcon } from "@hugeicons/core-free-icons"; import { cn } from "@/lib/utils"; import { useAppStore } from "@/stores/useAppStore"; +import { pluginRegistry } from "@/plugins"; import { ConnectionIndicator } from "./ConnectionIndicator"; -const NAV_ITEMS = [ +const CORE_NAV_ITEMS = [ { label: "Home", to: "/" }, { label: "Violations", to: "/violations" }, - { label: "Laps", to: "/laps" }, { label: "Settings", to: "/settings" }, { label: "Setup", to: "/setup" }, { label: "Teable", to: "/teable" }, @@ -23,9 +23,19 @@ export function NavigationMenu({ className }: NavigationMenuProps) { const appMode = useAppStore((s) => s.appMode); const setAppMode = useAppStore((s) => s.setAppMode); + const pluginNavItems = pluginRegistry.getNavItems(); + const pluginModes = pluginRegistry.getModes(); + + const allNavItems = [ + CORE_NAV_ITEMS[0], // Home + CORE_NAV_ITEMS[1], // Violations + ...pluginNavItems, // Dynamic plugin routes (e.g. Laps) + ...CORE_NAV_ITEMS.slice(2), // Settings, Setup, Teable, About + ]; + return (