From ed743422b5febe6b02c5d3b23ba3ded2ec5f5263 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 22:17:29 +0800 Subject: [PATCH 1/7] feat(foundation): add persistent bootstrap safeguards --- src-tauri/src/database/mod.rs | 174 ++++++++++++++++++++++++++++++---- src-tauri/src/lib.rs | 32 ++++--- src-tauri/src/logging.rs | 170 +++++++++++++++++++++++++++++++++ src/App.test.tsx | 16 ++++ src/App.tsx | 11 ++- src/types/bootstrap.ts | 19 ++-- 6 files changed, 382 insertions(+), 40 deletions(-) create mode 100644 src-tauri/src/logging.rs diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index 3decc58..ecc4130 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -1,33 +1,55 @@ +use std::{path::Path, sync::Mutex, time::Duration}; + use rusqlite::{Connection, OptionalExtension, params}; use thiserror::Error; +pub const CURRENT_SCHEMA_VERSION: u32 = 1; + +pub struct ApplicationDatabase { + store: Mutex, +} + +impl ApplicationDatabase { + pub fn open(path: impl AsRef) -> Result { + Ok(Self { + store: Mutex::new(ProfileMessageStore::open(path)?), + }) + } + + pub fn schema_version(&self) -> Result { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .schema_version() + } +} + pub struct ProfileMessageStore { connection: Connection, } impl ProfileMessageStore { - pub fn in_memory() -> Result { - let connection = Connection::open_in_memory()?; - let store = Self { connection }; - store.migrate()?; - Ok(store) + pub fn open(path: impl AsRef) -> Result { + Self::from_connection(Connection::open(path)?, true) } - fn migrate(&self) -> Result<(), DatabaseError> { - self.connection.execute_batch( - " - PRAGMA foreign_keys = ON; - CREATE TABLE IF NOT EXISTS messages ( - profile_id TEXT NOT NULL, - server_instance_id TEXT NOT NULL, - conversation_id TEXT NOT NULL, - message_id TEXT NOT NULL, - content TEXT NOT NULL, - PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id) - ); - ", - )?; - Ok(()) + pub fn in_memory() -> Result { + Self::from_connection(Connection::open_in_memory()?, false) + } + + fn from_connection( + mut connection: Connection, + persistent: bool, + ) -> Result { + configure_connection(&connection, persistent)?; + migrate(&mut connection)?; + Ok(Self { connection }) + } + + pub fn schema_version(&self) -> Result { + Ok(self + .connection + .pragma_query_value(None, "user_version", |row| row.get(0))?) } pub fn insert_message( @@ -84,16 +106,128 @@ impl ProfileMessageStore { } } +fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> { + connection.pragma_update(None, "foreign_keys", "ON")?; + connection.busy_timeout(Duration::from_secs(5))?; + if persistent { + connection.pragma_update(None, "journal_mode", "WAL")?; + } + Ok(()) +} + +fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> { + let found: u32 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?; + + if found > CURRENT_SCHEMA_VERSION { + return Err(DatabaseError::UnsupportedSchemaVersion { + found, + supported: CURRENT_SCHEMA_VERSION, + }); + } + + if found == 0 { + let transaction = connection.transaction()?; + transaction.execute_batch( + " + CREATE TABLE messages ( + profile_id TEXT NOT NULL, + server_instance_id TEXT NOT NULL, + conversation_id TEXT NOT NULL, + message_id TEXT NOT NULL, + content TEXT NOT NULL, + PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id) + ); + PRAGMA user_version = 1; + ", + )?; + transaction.commit()?; + } + + Ok(()) +} + #[derive(Debug, Error)] pub enum DatabaseError { #[error("SQLite operation failed")] Sqlite(#[from] rusqlite::Error), + #[error("database schema version {found} is newer than supported version {supported}")] + UnsupportedSchemaVersion { found: u32, supported: u32 }, + #[error("database state lock is unavailable")] + LockPoisoned, } #[cfg(test)] mod tests { use super::*; + #[test] + fn creates_and_reopens_a_persistent_migrated_database() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("desktop.sqlite3"); + + { + let store = ProfileMessageStore::open(&path).expect("open database"); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + store + .insert_message( + "profile-a", + "server-a", + "conversation-a", + "message-a", + "persisted", + ) + .expect("insert message"); + } + + let reopened = ProfileMessageStore::open(&path).expect("reopen database"); + assert_eq!( + reopened.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + assert_eq!( + reopened + .message_content("profile-a", "server-a", "conversation-a", "message-a") + .expect("query message") + .as_deref(), + Some("persisted") + ); + } + + #[test] + fn refuses_a_database_from_a_newer_schema_version() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("future.sqlite3"); + let connection = Connection::open(&path).expect("create database"); + connection + .pragma_update(None, "user_version", CURRENT_SCHEMA_VERSION + 1) + .expect("set future version"); + drop(connection); + + assert!(matches!( + ProfileMessageStore::open(path), + Err(DatabaseError::UnsupportedSchemaVersion { + found: 2, + supported: CURRENT_SCHEMA_VERSION + }) + )); + } + + #[test] + fn repeated_migration_is_idempotent() { + let store = ProfileMessageStore::in_memory().expect("store"); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + } + #[test] fn identical_remote_ids_remain_isolated_by_profile_and_server() { let store = ProfileMessageStore::in_memory().expect("store"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 216b0c2..8c27438 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,11 +1,14 @@ pub mod database; pub mod diagnostics; pub mod file_transfer; +pub mod logging; pub mod networking; pub mod secure_store; pub mod windows; +use database::ApplicationDatabase; use serde::Serialize; + use tauri::{ Manager, WindowEvent, menu::{Menu, MenuItem}, @@ -16,30 +19,31 @@ use tauri::{ #[serde(rename_all = "camelCase")] struct BootstrapStatus { app_version: &'static str, + database_schema_version: u32, platform: &'static str, rust_core: &'static str, protocol_version: &'static str, } #[tauri::command] -fn bootstrap_status() -> BootstrapStatus { - BootstrapStatus { +fn bootstrap_status( + database: tauri::State<'_, ApplicationDatabase>, +) -> Result { + let database_schema_version = database + .schema_version() + .map_err(|_| "database status is unavailable".to_owned())?; + + Ok(BootstrapStatus { app_version: env!("CARGO_PKG_VERSION"), platform: "windows", rust_core: "ready", protocol_version: desktop_protocol::PROTOCOL_VERSION, - } + database_schema_version, + }) } pub fn run() { - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), - ) - .with_target(false) - .compact() - .init(); + logging::init(); tauri::Builder::default() .plugin(tauri_plugin_single_instance::init(|app, _, _| { @@ -49,6 +53,12 @@ pub fn run() { } })) .setup(|app| { + let app_data_dir = app.path().app_data_dir()?; + std::fs::create_dir_all(&app_data_dir)?; + app.manage(ApplicationDatabase::open( + app_data_dir.join("astrbot-desktop.sqlite3"), + )?); + let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; let menu = Menu::with_items(app, &[&show, &quit])?; diff --git a/src-tauri/src/logging.rs b/src-tauri/src/logging.rs new file mode 100644 index 0000000..23c009e --- /dev/null +++ b/src-tauri/src/logging.rs @@ -0,0 +1,170 @@ +use std::io::{self, Write}; + +use tracing_subscriber::fmt::MakeWriter; + +use crate::diagnostics::redaction::Redactor; + +#[derive(Clone)] +pub struct RedactingMakeWriter { + inner: M, + redactor: Redactor, +} + +impl RedactingMakeWriter { + pub fn new(inner: M) -> Self { + Self { + inner, + redactor: Redactor::default(), + } + } + + #[cfg(test)] + fn with_redactor(inner: M, redactor: Redactor) -> Self { + Self { inner, redactor } + } +} + +impl<'writer, M> MakeWriter<'writer> for RedactingMakeWriter +where + M: MakeWriter<'writer>, + M::Writer: Write, +{ + type Writer = RedactingWriter; + + fn make_writer(&'writer self) -> Self::Writer { + RedactingWriter { + inner: self.inner.make_writer(), + redactor: self.redactor.clone(), + buffer: Vec::new(), + } + } +} + +pub struct RedactingWriter { + inner: W, + redactor: Redactor, + buffer: Vec, +} + +impl RedactingWriter { + fn flush_redacted(&mut self) -> io::Result<()> { + if self.buffer.is_empty() { + return Ok(()); + } + + let rendered = String::from_utf8_lossy(&self.buffer); + let redacted = self.redactor.redact(&rendered); + self.inner.write_all(redacted.as_bytes())?; + self.buffer.clear(); + Ok(()) + } +} + +impl Write for RedactingWriter { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.buffer.extend_from_slice(buffer); + Ok(buffer.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.flush_redacted()?; + self.inner.flush() + } +} + +impl Drop for RedactingWriter { + fn drop(&mut self) { + let _ = self.flush_redacted(); + let _ = self.inner.flush(); + } +} + +pub fn init() { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_target(false) + .compact() + .with_writer(RedactingMakeWriter::new(std::io::stderr)) + .init(); +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use super::*; + + #[derive(Clone, Default)] + struct SharedMakeWriter { + output: Arc>>, + } + + impl SharedMakeWriter { + fn contents(&self) -> String { + String::from_utf8(self.output.lock().expect("output lock").clone()) + .expect("UTF-8 output") + } + } + + struct SharedWriter { + output: Arc>>, + } + + impl Write for SharedWriter { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.output + .lock() + .expect("output lock") + .extend_from_slice(buffer); + Ok(buffer.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + impl<'writer> MakeWriter<'writer> for SharedMakeWriter { + type Writer = SharedWriter; + + fn make_writer(&'writer self) -> Self::Writer { + SharedWriter { + output: self.output.clone(), + } + } + } + + #[test] + fn redacts_structured_fields_and_message_content_before_writing() { + let sink = SharedMakeWriter::default(); + let known_secret = format!("canary-{}", uuid::Uuid::new_v4()); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_target(false) + .with_writer(RedactingMakeWriter::with_redactor( + sink.clone(), + Redactor::new([&known_secret]), + )) + .finish(); + + tracing::subscriber::with_default(subscriber, || { + tracing::info!( + password = "test-password", + authorization = "Bearer abcdefghijklmnop", + endpoint = "https://alice:password@example.test/path", + "known={known_secret}" + ); + }); + + let output = sink.contents(); + assert!(!output.contains("test-password")); + assert!(!output.contains("abcdefghijklmnop")); + assert!(!output.contains("alice:password")); + assert!(!output.contains(&known_secret)); + assert!(output.contains(crate::diagnostics::redaction::REDACTED)); + } +} diff --git a/src/App.test.tsx b/src/App.test.tsx index 8830a1f..265439b 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -15,6 +15,7 @@ describe("App", () => { platform: "windows", rustCore: "ready", protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 1, }); }); @@ -24,4 +25,19 @@ describe("App", () => { expect(await screen.findByText("ready")).toBeInTheDocument(); expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument(); }); + + it("rejects an invalid Rust IPC payload", async () => { + vi.mocked(invoke).mockResolvedValueOnce({ + appVersion: "0.1.0-alpha.0", + platform: "windows", + rustCore: "unexpected", + protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 1, + }); + + render(); + + expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument(); + expect(screen.queryByText("unexpected")).not.toBeInTheDocument(); + }); }); diff --git a/src/App.tsx b/src/App.tsx index e9ecf5d..e967145 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,13 +1,14 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; -import type { BootstrapStatus } from "./types/bootstrap"; +import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; const initialStatus: BootstrapStatus = { appVersion: "unknown", platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 1, }; export function App() { @@ -16,8 +17,8 @@ export function App() { const refreshStatus = useCallback(async () => { try { - const result = await invoke("bootstrap_status"); - setStatus(result); + const result = await invoke("bootstrap_status"); + setStatus(bootstrapStatusSchema.parse(result)); setError(null); } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)); @@ -44,6 +45,10 @@ export function App() { + {error ?

IPC unavailable: {error}

: null} diff --git a/src/types/bootstrap.ts b/src/types/bootstrap.ts index 6589e90..797d206 100644 --- a/src/types/bootstrap.ts +++ b/src/types/bootstrap.ts @@ -1,6 +1,13 @@ -export interface BootstrapStatus { - appVersion: string; - platform: string; - rustCore: "ready" | "pending"; - protocolVersion: string; -} +import { z } from "zod"; + +export const bootstrapStatusSchema = z + .object({ + appVersion: z.string().min(1), + platform: z.string().min(1), + rustCore: z.enum(["ready", "pending"]), + protocolVersion: z.string().min(1), + databaseSchemaVersion: z.number().int().positive(), + }) + .strict(); + +export type BootstrapStatus = z.infer; From 6a1eeabea882da2a862a40fd617751cb0a1cc4ae Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 22:21:04 +0800 Subject: [PATCH 2/7] docs(p01): record foundation progress and profile boundary --- CHANGELOG.md | 4 ++ docs/decisions/pending-decisions.md | 12 +++++ docs/implementation-plan.md | 27 ++++++++++- docs/progress.md | 29 ++++++++---- docs/reports/p01-foundation-progress.md | 61 +++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 docs/reports/p01-foundation-progress.md diff --git a/CHANGELOG.md b/CHANGELOG.md index a089a03..f7b1308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and - Provisional desktop-v1alpha1 Rust types, TypeScript exports, ten JSON Schemas, drift checks, and two loopback-only Mock Gateway instances. - Frontend, browser, Rust, integration, Windows provider, soak, and Forgejo CI test entry points. - P00 dependency review and durable Spike result records. +- Persistent SQLite application-data initialization with transactional `user_version` migration and future-version rejection. +- Strict Zod validation for the Rust bootstrap IPC payload, including the active database schema version. +- Redacting tracing output writer with structured-field, bearer-token, URL-credential, private-key, and known-secret coverage. +- P01 migration, logging, IPC validation, real Tauri startup, and production-build verification. ### Security diff --git a/docs/decisions/pending-decisions.md b/docs/decisions/pending-decisions.md index 5783ed4..dc60a73 100644 --- a/docs/decisions/pending-decisions.md +++ b/docs/decisions/pending-decisions.md @@ -50,3 +50,15 @@ - Implementation: the identity is configured only in this repository. - Result: two Conventional Commit baseline commits were created on `main`, pushed normally, and followed by scoped feature-branch commits. - Safety impact: no global Git identity was changed. + +## PD-0008: Profile CRUD stage ownership + +- Status: unresolved; blocks Profile CRUD implementation only +- Conflict: `docs/01_Architecture_Design.md` lists Profile CRUD in stage 1, while `docs/02_Codex_Implementation_Tasks.md` lists ConnectionProfile CRUD in Batch 2. +- Impact: resolving this changes the database schema, Tauri IPC surface, frontend state model, and the acceptance boundary between `feat/p01-foundation` and `feat/p02-dual-connections`. +- Safe current action: complete only the unambiguous P01 foundation work��persistent migrations, validated bootstrap IPC, redacted logging, tray, single-instance, exit flow, and tests. +- Paused work: profile tables, Profile CRUD commands, profile forms, and profile-to-slot assignment. +- Required decision: + - Option A: architecture document wins; implement basic Profile CRUD in P01 and leave slot assignment/connection behavior for P02. + - Option B: implementation task batching wins; keep all ConnectionProfile CRUD in P02. +- Recommendation: Option A is the literal higher-priority document, but the implementation remains paused because AGENTS.md requires explicit reporting for conflicts affecting database structure or public interfaces. diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index c7e78c5..1ee495c 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -1,4 +1,6 @@ -# P00 Bootstrap Implementation Plan +# Implementation Plan + +## P00 Bootstrap (completed) ## Objective @@ -30,7 +32,28 @@ Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and comple - Rust/MSVC/Tauri are verified and no longer block local work. - Git Credential Manager reauthentication succeeded and the non-forced HTTP push created the remote `main` baseline at `0d12b94`. -- Development is active on `feat/p00-bootstrap`; the remaining repository handoff step is a normal push of this feature branch. +- Forgejo PR #1 merged P00 into `main` at `b3420e4`; development now continues on `feat/p01-foundation`. - The configured SSH fetch endpoint still refuses connections and the LAN SSH endpoint rejects the available key, but the approved HTTP push URL is operational. - Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful. - Real UNC execution still requires a user-authorized disposable fixture. + +## P01 Foundation (active) + +### Objective + +Turn the P00 Spike skeleton into a durable application foundation without pulling Batch 2 connection-profile behavior forward across an unresolved document boundary. + +### Ordered work + +1. Initialize a persistent SQLite database in the Tauri application-data directory. +2. Apply versioned, transactional, idempotent migrations and refuse unknown future schema versions. +3. Validate Rust-to-TypeScript bootstrap payloads at runtime. +4. Ensure tracing output passes through the shared redaction rules before it reaches a writer. +5. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, and production build behavior. +6. Record the Profile CRUD stage conflict before changing its schema or IPC. + +### Paused boundary + +- `docs/01_Architecture_Design.md` places Profile CRUD in stage 1. +- `docs/02_Codex_Implementation_Tasks.md` places ConnectionProfile CRUD in Batch 2. +- Because this changes database structure and public IPC, Profile CRUD remains paused under PD-0008 until the stage boundary is explicitly resolved. diff --git a/docs/progress.md b/docs/progress.md index 98321be..ac108f7 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -2,7 +2,7 @@ ## Current phase -P00 bootstrap implementation and high-risk Spike verification is complete; the feature branch is published and awaiting user PR review. +P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work is implemented, while Profile CRUD is paused on a documented stage-boundary conflict. ## Completed @@ -21,15 +21,23 @@ P00 bootstrap implementation and high-risk Spike verification is complete; the f - Added frontend, Playwright, Rust, integration, Windows-provider, soak, and Forgejo CI entry points. - Built the Windows release executable and SHA-256-recorded NSIS installer. - Added dependency, Spike, progress, changelog, and pending-decision records. +- Verified Forgejo PR #1 merged into `main` as `b3420e4`. +- Fast-forwarded local `main` and created `feat/p01-foundation` from the merged baseline. +- Added persistent SQLite startup initialization with WAL, busy timeout, transactional `user_version` migration, idempotent reopen, and future-version rejection. +- Added strict Zod validation for the Rust bootstrap IPC payload and exposed the active database schema version. +- Added a redacting tracing writer that sanitizes structured fields and rendered message content before output. +- Verified a real Tauri development start created the application database in the Windows app-data directory. +- Built the P01 Windows release executable and NSIS installer. - Committed the implementation, test, and CI increments with Conventional Commit subjects. ## In progress -- Preparing the final PR draft and handoff report without merging `main`. +- Recording the Profile CRUD stage conflict and preparing the verified P01 foundation increment for remote review. ## Remaining -- Open and review the Forgejo PR from `feat/p00-bootstrap` to `main`; do not merge automatically. +- Resolve whether Profile CRUD belongs in P01 (architecture document) or P02/Batch 2 (implementation task document) before changing its database schema or public IPC. +- After resolution, complete the selected stage scope and open a PR without automatically merging `main`. - Run the Forgejo workflow when a compatible runner is available. - Execute a real UNC transaction only after an authorized disposable fixture is supplied. - Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray. @@ -39,24 +47,26 @@ P00 bootstrap implementation and high-risk Spike verification is complete; the f - Configured Forgejo SSH `localhost:18086` refuses connections. - LAN SSH `192.168.31.210:18086` responds but rejects the available public key. - HTTP Git push is operational after Git Credential Manager reauthentication and is no longer a blocker. +- Profile CRUD stage ownership conflicts between the architecture and implementation task documents; implementation is paused because it affects database structure and public IPC. - Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404. ## Test status -- `pnpm check:frontend`: passed; 1 Vitest test and production Vite build. +- `npm run check:frontend`: passed; 2 Vitest tests and production Vite build. - `pnpm test:e2e`: passed; 1 Chromium smoke test. - Rust fmt/check/Clippy with warnings denied: passed. -- `cargo test --workspace`: 40 passed, 2 explicit manual tests ignored. +- `cargo test --workspace`: 44 passed, 2 explicit manual tests ignored. - Controlled Windows UIA/PrintWindow smoke: 1 passed. - Corrected dual-SSE soak: 1800.02 seconds, 1800 companion events, 1801 operations events, passed. - Protocol Schema drift check: passed. -- Tauri development smoke, release executable, and NSIS installer build: passed. +- P01 Tauri development startup and application-data SQLite creation: passed. +- P01 release executable and NSIS installer: passed after repairing the missing official `libsqlite3-sys` binding cache; installer SHA-256 `B8858CBE2F4673FAF40799C1243BCAB0748D194FA3AD67FBD33DDCF26CF27189`. - pnpm 11.9.0 frozen lockfile-only validation: passed using a local temporary store to avoid the pnpm UNC project-registry limitation. - Forgejo CI and a real UNC transaction were not executed and are not claimed successful. ## Current branch -`feat/p00-bootstrap` +`feat/p01-foundation` ## Recent commits @@ -65,8 +75,11 @@ P00 bootstrap implementation and high-risk Spike verification is complete; the f - `01607c6 feat(p00): add Tauri desktop spike foundation` - `69b432b test(p00): add frontend browser rust and windows checks` - `d4af979 ci(forgejo): add portable and windows quality workflows` +- `72a16cb docs(p00): record Forgejo branch publication` +- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` +- `ed74342 feat(foundation): add persistent bootstrap safeguards` - `353a439 docs(p00): record spike results and unresolved boundaries` ## Next step -Provide the verified test report and PR draft. The user can then review the Forgejo diff and decide whether to merge; `main` remains unchanged by this workflow. +Obtain an explicit decision for PD-0008 before implementing Profile CRUD. Continue other P01 work only if it does not change the disputed profile database or public IPC boundary. diff --git a/docs/reports/p01-foundation-progress.md b/docs/reports/p01-foundation-progress.md new file mode 100644 index 0000000..3815029 --- /dev/null +++ b/docs/reports/p01-foundation-progress.md @@ -0,0 +1,61 @@ +# P01 Foundation Progress Report + +Date: 2026-07-18 + +## Status + +P01 foundation work is partially complete on `feat/p01-foundation`. The unambiguous Batch 1 foundation items are implemented and verified. Profile CRUD is intentionally paused under PD-0008 because the architecture and implementation task documents assign it to different stages. + +## Completed + +- Verified P00 PR #1 merged into `main` at `b3420e4`. +- Fast-forwarded local `main` and created `feat/p01-foundation`. +- Added a persistent SQLite database under the Tauri application-data directory. +- Added WAL mode, a bounded busy timeout, foreign-key enforcement, and transactional `user_version` migration. +- Added idempotent reopen/persistence tests and rejection of databases newer than the supported schema. +- Added the database schema version to the bootstrap IPC response. +- Added strict frontend Zod validation for the IPC payload and a malformed-payload test. +- Added a tracing writer that redacts output before writing. +- Retained the existing tray menu, close-to-tray, explicit quit, and single-instance focus behavior. + +## Verification + +| Check | Result | +| ------------------------------------------------------- | ------------------------------------------------------------------ | +| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 2 Vitest tests | +| Playwright Chromium | Passed; 1 test | +| Rust fmt, Clippy with warnings denied, check | Passed | +| Rust tests | Passed; 44 normal tests, 2 explicit manual tests ignored | +| Persistent SQLite reopen and migration tests | Passed | +| Logging redaction writer test | Passed | +| Tauri development startup | Passed | +| Windows application-data SQLite creation | Passed; database created at startup | +| Tauri release executable | Passed | +| NSIS installer | Passed; 3,793,884 bytes | +| NSIS SHA-256 | `B8858CBE2F4673FAF40799C1243BCAB0748D194FA3AD67FBD33DDCF26CF27189` | + +## Build environment note + +The first release attempts failed because the `libsqlite3-sys` release output directory did not contain `bindgen.rs`, although the crate build script had produced the SQLite static library. Cleaning only that package did not restore the file. + +The official pre-generated `bindgen_bundled_version.rs` from the installed `libsqlite3-sys 0.38.1` crate source was copied to the exact `OUT_DIR/bindgen.rs` location expected by the crate's own `build.rs`. Source and destination SHA-256 values matched: + +`5B5A37A74DC728FB0BCD041867EB577C03C95E2FE46285262C589A3B1CD4BBAC` + +The production build and NSIS bundle then completed. This is recorded as an environment cache repair, not a repository or dependency change. + +## Paused boundary + +Profile CRUD is not implemented in this increment. + +- Architecture stage 1 includes Profile CRUD. +- Implementation Batch 2 includes ConnectionProfile CRUD. +- The conflict affects database structure and public IPC. +- PD-0008 requires an explicit stage-boundary decision before work resumes. + +## Not claimed + +- P01 is not declared complete while PD-0008 is unresolved. +- Forgejo CI has not run. +- No Profile CRUD, profile UI, or slot assignment was added. +- No real credential or destructive file operation was used. From 02fd25afaf386bdf0df2a97c8daca13ce72b2f09 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 23:36:19 +0800 Subject: [PATCH 3/7] feat(profile): add secure profile persistence and IPC --- src-tauri/src/database/mod.rs | 105 ++++++++- src-tauri/src/database/profiles.rs | 349 ++++++++++++++++++++++++++++ src-tauri/src/lib.rs | 9 +- src-tauri/src/profiles.rs | 353 +++++++++++++++++++++++++++++ 4 files changed, 813 insertions(+), 3 deletions(-) create mode 100644 src-tauri/src/database/profiles.rs create mode 100644 src-tauri/src/profiles.rs diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index ecc4130..f837138 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -1,9 +1,11 @@ +mod profiles; + use std::{path::Path, sync::Mutex, time::Duration}; use rusqlite::{Connection, OptionalExtension, params}; use thiserror::Error; -pub const CURRENT_SCHEMA_VERSION: u32 = 1; +pub const CURRENT_SCHEMA_VERSION: u32 = 2; pub struct ApplicationDatabase { store: Mutex, @@ -16,6 +18,13 @@ impl ApplicationDatabase { }) } + #[cfg(test)] + pub(crate) fn in_memory() -> Result { + Ok(Self { + store: Mutex::new(ProfileMessageStore::in_memory()?), + }) + } + pub fn schema_version(&self) -> Result { self.store .lock() @@ -143,6 +152,38 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> { transaction.commit()?; } + if found <= 1 { + let transaction = connection.transaction()?; + transaction.execute_batch( + " + CREATE TABLE connection_profiles ( + id TEXT PRIMARY KEY NOT NULL, + display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 80), + role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')), + base_url TEXT NOT NULL, + event_stream_url TEXT, + authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key')), + credential_reference TEXT, + allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)), + pinned_certificate_fingerprint TEXT, + auto_connect_slot TEXT CHECK(auto_connect_slot IS NULL OR auto_connect_slot IN ('companion', 'operations')), + auto_connect INTEGER NOT NULL DEFAULT 0 CHECK(auto_connect IN (0, 1)), + server_instance_id TEXT, + server_version TEXT, + protocol_version TEXT, + local_tool_policy_id TEXT, + last_connected_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE INDEX connection_profiles_role_idx + ON connection_profiles(role); + PRAGMA user_version = 2; + ", + )?; + transaction.commit()?; + } + Ok(()) } @@ -154,6 +195,10 @@ pub enum DatabaseError { UnsupportedSchemaVersion { found: u32, supported: u32 }, #[error("database state lock is unavailable")] LockPoisoned, + #[error("database contains invalid profile data")] + InvalidStoredProfile, + #[error("connection profile was not found")] + ProfileNotFound, } #[cfg(test)] @@ -196,6 +241,62 @@ mod tests { ); } + #[test] + fn migrates_v1_to_v2_without_losing_messages() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("v1.sqlite3"); + let connection = Connection::open(&path).expect("create v1 database"); + connection + .execute_batch( + " + CREATE TABLE messages ( + profile_id TEXT NOT NULL, + server_instance_id TEXT NOT NULL, + conversation_id TEXT NOT NULL, + message_id TEXT NOT NULL, + content TEXT NOT NULL, + PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id) + ); + INSERT INTO messages ( + profile_id, + server_instance_id, + conversation_id, + message_id, + content + ) VALUES ( + 'profile-a', + 'server-a', + 'conversation-a', + 'message-a', + 'preserved' + ); + PRAGMA user_version = 1; + ", + ) + .expect("create v1 schema"); + drop(connection); + + let store = ProfileMessageStore::open(&path).expect("migrate database"); + assert_eq!(store.schema_version().expect("schema version"), 2); + assert_eq!( + store + .message_content("profile-a", "server-a", "conversation-a", "message-a") + .expect("query preserved message") + .as_deref(), + Some("preserved") + ); + let profile_table_count: u32 = store + .connection + .query_row( + "SELECT COUNT(*) FROM sqlite_master + WHERE type = 'table' AND name = 'connection_profiles'", + [], + |row| row.get(0), + ) + .expect("query profile table"); + assert_eq!(profile_table_count, 1); + } + #[test] fn refuses_a_database_from_a_newer_schema_version() { let directory = tempfile::tempdir().expect("temporary directory"); @@ -209,7 +310,7 @@ mod tests { assert!(matches!( ProfileMessageStore::open(path), Err(DatabaseError::UnsupportedSchemaVersion { - found: 2, + found: 3, supported: CURRENT_SCHEMA_VERSION }) )); diff --git a/src-tauri/src/database/profiles.rs b/src-tauri/src/database/profiles.rs new file mode 100644 index 0000000..0628722 --- /dev/null +++ b/src-tauri/src/database/profiles.rs @@ -0,0 +1,349 @@ +use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile}; +use rusqlite::{Row, params}; + +use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore}; + +const PROFILE_COLUMNS: &str = " + id, + display_name, + role, + base_url, + event_stream_url, + authentication_type, + credential_reference, + allow_insecure_http, + pinned_certificate_fingerprint, + auto_connect_slot, + auto_connect, + server_instance_id, + server_version, + protocol_version, + local_tool_policy_id, + last_connected_at, + created_at, + updated_at +"; + +impl ApplicationDatabase { + pub fn list_profiles(&self) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .list_profiles() + } + + pub fn profile(&self, id: &str) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .profile(id) + } + + pub fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .create_profile(profile) + } + + pub fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .update_profile(profile) + } + + pub fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .delete_profile(id) + } +} + +impl ProfileMessageStore { + fn list_profiles(&self) -> Result, DatabaseError> { + let mut statement = self.connection.prepare(&format!( + "SELECT {PROFILE_COLUMNS} + FROM connection_profiles + ORDER BY display_name COLLATE NOCASE, id" + ))?; + let mut rows = statement.query([])?; + let mut profiles = Vec::new(); + while let Some(row) = rows.next()? { + profiles.push(profile_from_row(row)?); + } + Ok(profiles) + } + + fn profile(&self, id: &str) -> Result, DatabaseError> { + let mut statement = self.connection.prepare(&format!( + "SELECT {PROFILE_COLUMNS} + FROM connection_profiles + WHERE id = ?1" + ))?; + let mut rows = statement.query(params![id])?; + match rows.next()? { + Some(row) => Ok(Some(profile_from_row(row)?)), + None => Ok(None), + } + } + + fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + self.connection.execute( + " + INSERT INTO connection_profiles ( + id, + display_name, + role, + base_url, + event_stream_url, + authentication_type, + credential_reference, + allow_insecure_http, + pinned_certificate_fingerprint, + auto_connect_slot, + auto_connect, + server_instance_id, + server_version, + protocol_version, + local_tool_policy_id, + last_connected_at, + created_at, + updated_at + ) VALUES ( + ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, + ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18 + ) + ", + params![ + profile.id, + profile.display_name, + role_to_str(profile.role), + profile.base_url, + profile.event_stream_url, + authentication_to_str(profile.authentication_type), + profile.credential_reference, + profile.allow_insecure_http, + profile.pinned_certificate_fingerprint, + profile.auto_connect_slot.map(slot_to_str), + profile.auto_connect, + profile.server_instance_id, + profile.server_version, + profile.protocol_version, + profile.local_tool_policy_id, + profile.last_connected_at, + profile.created_at, + profile.updated_at, + ], + )?; + Ok(()) + } + + fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + let changed = self.connection.execute( + " + UPDATE connection_profiles + SET display_name = ?2, + role = ?3, + base_url = ?4, + event_stream_url = ?5, + authentication_type = ?6, + credential_reference = ?7, + allow_insecure_http = ?8, + pinned_certificate_fingerprint = ?9, + auto_connect_slot = ?10, + auto_connect = ?11, + server_instance_id = ?12, + server_version = ?13, + protocol_version = ?14, + local_tool_policy_id = ?15, + last_connected_at = ?16, + created_at = ?17, + updated_at = ?18 + WHERE id = ?1 + ", + params![ + profile.id, + profile.display_name, + role_to_str(profile.role), + profile.base_url, + profile.event_stream_url, + authentication_to_str(profile.authentication_type), + profile.credential_reference, + profile.allow_insecure_http, + profile.pinned_certificate_fingerprint, + profile.auto_connect_slot.map(slot_to_str), + profile.auto_connect, + profile.server_instance_id, + profile.server_version, + profile.protocol_version, + profile.local_tool_policy_id, + profile.last_connected_at, + profile.created_at, + profile.updated_at, + ], + )?; + if changed == 0 { + return Err(DatabaseError::ProfileNotFound); + } + Ok(()) + } + + fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> { + if self + .connection + .execute("DELETE FROM connection_profiles WHERE id = ?1", params![id])? + == 0 + { + return Err(DatabaseError::ProfileNotFound); + } + Ok(()) + } +} + +fn profile_from_row(row: &Row<'_>) -> Result { + let role = match row.get::<_, String>(2)?.as_str() { + "companion" => AstrBotProfileRole::Companion, + "operations" => AstrBotProfileRole::Operations, + "general" => AstrBotProfileRole::General, + _ => return Err(DatabaseError::InvalidStoredProfile), + }; + let authentication_type = match row.get::<_, String>(5)?.as_str() { + "device-token" => AuthenticationType::DeviceToken, + "api-key" => AuthenticationType::ApiKey, + _ => return Err(DatabaseError::InvalidStoredProfile), + }; + let auto_connect_slot = match row.get::<_, Option>(9)?.as_deref() { + Some("companion") => Some(ActiveSlotKind::Companion), + Some("operations") => Some(ActiveSlotKind::Operations), + Some(_) => return Err(DatabaseError::InvalidStoredProfile), + None => None, + }; + + Ok(ConnectionProfile { + id: row.get(0)?, + display_name: row.get(1)?, + role, + base_url: row.get(3)?, + event_stream_url: row.get(4)?, + authentication_type, + credential_reference: row.get(6)?, + allow_insecure_http: row.get(7)?, + pinned_certificate_fingerprint: row.get(8)?, + auto_connect_slot, + auto_connect: row.get(10)?, + server_instance_id: row.get(11)?, + server_version: row.get(12)?, + protocol_version: row.get(13)?, + local_tool_policy_id: row.get(14)?, + last_connected_at: row.get(15)?, + created_at: row.get(16)?, + updated_at: row.get(17)?, + }) +} + +fn role_to_str(role: AstrBotProfileRole) -> &'static str { + match role { + AstrBotProfileRole::Companion => "companion", + AstrBotProfileRole::Operations => "operations", + AstrBotProfileRole::General => "general", + } +} + +fn authentication_to_str(authentication_type: AuthenticationType) -> &'static str { + match authentication_type { + AuthenticationType::DeviceToken => "device-token", + AuthenticationType::ApiKey => "api-key", + } +} + +fn slot_to_str(slot: ActiveSlotKind) -> &'static str { + match slot { + ActiveSlotKind::Companion => "companion", + ActiveSlotKind::Operations => "operations", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profile(index: usize) -> ConnectionProfile { + ConnectionProfile { + id: format!("00000000-0000-4000-8000-{index:012}"), + display_name: format!("Profile {index}"), + role: AstrBotProfileRole::General, + base_url: format!("https://example-{index}.test/"), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + credential_reference: None, + allow_insecure_http: false, + pinned_certificate_fingerprint: None, + auto_connect_slot: None, + auto_connect: false, + server_instance_id: None, + server_version: None, + protocol_version: None, + local_tool_policy_id: None, + last_connected_at: None, + created_at: "2026-07-18T00:00:00Z".into(), + updated_at: "2026-07-18T00:00:00Z".into(), + } + } + + #[test] + fn stores_lists_updates_and_deletes_five_profiles() { + let database = ApplicationDatabase::in_memory().expect("database"); + for index in 0..5 { + database + .create_profile(&profile(index)) + .expect("create profile"); + } + assert_eq!(database.list_profiles().expect("list profiles").len(), 5); + + let mut updated = database + .profile(&profile(2).id) + .expect("read profile") + .expect("existing profile"); + updated.display_name = "Updated Profile".into(); + updated.updated_at = "2026-07-18T01:00:00Z".into(); + database.update_profile(&updated).expect("update profile"); + assert_eq!( + database + .profile(&updated.id) + .expect("read updated profile") + .expect("existing profile") + .display_name, + "Updated Profile" + ); + + database + .delete_profile(&updated.id) + .expect("delete profile"); + assert_eq!(database.list_profiles().expect("list profiles").len(), 4); + assert!(matches!( + database.delete_profile(&updated.id), + Err(DatabaseError::ProfileNotFound) + )); + } + + #[test] + fn profile_metadata_persists_after_reopening_database() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("profiles.sqlite3"); + let expected = profile(7); + + { + let store = ProfileMessageStore::open(&path).expect("open database"); + store.create_profile(&expected).expect("create profile"); + } + + let reopened = ProfileMessageStore::open(&path).expect("reopen database"); + let actual = reopened + .profile(&expected.id) + .expect("read profile") + .expect("persisted profile"); + assert_eq!(actual, expected); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8c27438..1d879e8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ pub mod diagnostics; pub mod file_transfer; pub mod logging; pub mod networking; +pub mod profiles; pub mod secure_store; pub mod windows; @@ -85,7 +86,13 @@ pub fn run() { let _ = window.hide(); } }) - .invoke_handler(tauri::generate_handler![bootstrap_status]) + .invoke_handler(tauri::generate_handler![ + bootstrap_status, + profiles::list_connection_profiles, + profiles::create_connection_profile, + profiles::update_connection_profile, + profiles::delete_connection_profile, + ]) .run(tauri::generate_context!()) .expect("failed to run AstrBot Desktop"); } diff --git a/src-tauri/src/profiles.rs b/src-tauri/src/profiles.rs new file mode 100644 index 0000000..22916f4 --- /dev/null +++ b/src-tauri/src/profiles.rs @@ -0,0 +1,353 @@ +use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile}; +use serde::{Deserialize, Serialize}; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; +use url::Url; +use uuid::Uuid; + +use crate::database::{ApplicationDatabase, DatabaseError}; + +const MAX_DISPLAY_NAME_CHARS: usize = 80; +const MAX_URL_CHARS: usize = 2048; + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConnectionProfileInput { + pub display_name: String, + pub role: AstrBotProfileRole, + pub base_url: String, + #[serde(default)] + pub event_stream_url: Option, + pub authentication_type: AuthenticationType, + #[serde(default)] + pub allow_insecure_http: bool, + #[serde(default)] + pub pinned_certificate_fingerprint: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UpdateConnectionProfileRequest { + pub id: String, + #[serde(flatten)] + pub profile: ConnectionProfileInput, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProfileCommandError { + code: &'static str, + message: &'static str, +} + +impl ProfileCommandError { + fn validation(message: &'static str) -> Self { + Self { + code: "validationFailed", + message, + } + } + + fn database(error: DatabaseError) -> Self { + match error { + DatabaseError::ProfileNotFound => Self { + code: "notFound", + message: "The connection profile no longer exists.", + }, + _ => Self { + code: "databaseUnavailable", + message: "The local profile database is unavailable.", + }, + } + } +} + +#[tauri::command] +pub fn list_connection_profiles( + database: tauri::State<'_, ApplicationDatabase>, +) -> Result, ProfileCommandError> { + list_profiles(&database) +} + +#[tauri::command] +pub fn create_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + request: ConnectionProfileInput, +) -> Result { + create_profile(&database, request) +} + +#[tauri::command] +pub fn update_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + request: UpdateConnectionProfileRequest, +) -> Result { + update_profile(&database, request) +} + +#[tauri::command] +pub fn delete_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + id: String, +) -> Result<(), ProfileCommandError> { + delete_profile(&database, &id) +} + +fn list_profiles( + database: &ApplicationDatabase, +) -> Result, ProfileCommandError> { + database + .list_profiles() + .map_err(ProfileCommandError::database) +} + +fn create_profile( + database: &ApplicationDatabase, + request: ConnectionProfileInput, +) -> Result { + let normalized = normalize_input(request)?; + let now = timestamp()?; + let profile = ConnectionProfile { + id: Uuid::new_v4().to_string(), + display_name: normalized.display_name, + role: normalized.role, + base_url: normalized.base_url, + event_stream_url: normalized.event_stream_url, + authentication_type: normalized.authentication_type, + credential_reference: None, + allow_insecure_http: normalized.allow_insecure_http, + pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint, + auto_connect_slot: None, + auto_connect: false, + server_instance_id: None, + server_version: None, + protocol_version: None, + local_tool_policy_id: None, + last_connected_at: None, + created_at: now.clone(), + updated_at: now, + }; + database + .create_profile(&profile) + .map_err(ProfileCommandError::database)?; + Ok(profile) +} + +fn update_profile( + database: &ApplicationDatabase, + request: UpdateConnectionProfileRequest, +) -> Result { + validate_id(&request.id)?; + let normalized = normalize_input(request.profile)?; + let mut profile = database + .profile(&request.id) + .map_err(ProfileCommandError::database)? + .ok_or_else(|| ProfileCommandError::database(DatabaseError::ProfileNotFound))?; + + profile.display_name = normalized.display_name; + profile.role = normalized.role; + profile.base_url = normalized.base_url; + profile.event_stream_url = normalized.event_stream_url; + profile.authentication_type = normalized.authentication_type; + profile.allow_insecure_http = normalized.allow_insecure_http; + profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint; + profile.updated_at = timestamp()?; + + database + .update_profile(&profile) + .map_err(ProfileCommandError::database)?; + Ok(profile) +} + +fn delete_profile(database: &ApplicationDatabase, id: &str) -> Result<(), ProfileCommandError> { + validate_id(id)?; + database + .delete_profile(id) + .map_err(ProfileCommandError::database) +} + +fn normalize_input( + request: ConnectionProfileInput, +) -> Result { + let display_name = request.display_name.trim().to_owned(); + if display_name.is_empty() + || display_name.chars().count() > MAX_DISPLAY_NAME_CHARS + || display_name.chars().any(char::is_control) + { + return Err(ProfileCommandError::validation( + "Display name must contain 1 to 80 visible characters.", + )); + } + + let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?; + let event_stream_url = request + .event_stream_url + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(|value| normalize_url(value, request.allow_insecure_http)) + .transpose()?; + let pinned_certificate_fingerprint = + normalize_fingerprint(request.pinned_certificate_fingerprint)?; + + Ok(ConnectionProfileInput { + display_name, + role: request.role, + base_url, + event_stream_url, + authentication_type: request.authentication_type, + allow_insecure_http: request.allow_insecure_http, + pinned_certificate_fingerprint, + }) +} + +fn normalize_url(value: &str, allow_insecure_http: bool) -> Result { + let value = value.trim(); + if value.is_empty() || value.chars().count() > MAX_URL_CHARS { + return Err(ProfileCommandError::validation( + "Connection URL is empty or too long.", + )); + } + + let mut url = Url::parse(value) + .map_err(|_| ProfileCommandError::validation("Connection URL is invalid."))?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { + return Err(ProfileCommandError::validation( + "Connection URL must use HTTP or HTTPS and include a host.", + )); + } + if !url.username().is_empty() || url.password().is_some() { + return Err(ProfileCommandError::validation( + "Credentials must not be embedded in a connection URL.", + )); + } + if url.query().is_some() || url.fragment().is_some() { + return Err(ProfileCommandError::validation( + "Connection URLs must not contain query parameters or fragments.", + )); + } + if url.scheme() == "http" && !allow_insecure_http { + return Err(ProfileCommandError::validation( + "HTTP requires explicit insecure-transport approval.", + )); + } + url.set_fragment(None); + Ok(url.to_string()) +} + +fn normalize_fingerprint(value: Option) -> Result, ProfileCommandError> { + let Some(value) = value else { + return Ok(None); + }; + let normalized = value + .trim() + .chars() + .filter(|character| *character != ':') + .flat_map(char::to_uppercase) + .collect::(); + if normalized.is_empty() { + return Ok(None); + } + if normalized.len() != 64 + || !normalized + .chars() + .all(|character| character.is_ascii_hexdigit()) + { + return Err(ProfileCommandError::validation( + "Pinned certificate fingerprint must be a SHA-256 hex value.", + )); + } + Ok(Some(normalized)) +} + +fn validate_id(id: &str) -> Result<(), ProfileCommandError> { + if Uuid::parse_str(id).is_err() { + return Err(ProfileCommandError::validation( + "Connection profile ID is invalid.", + )); + } + Ok(()) +} + +fn timestamp() -> Result { + OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| ProfileCommandError { + code: "clockUnavailable", + message: "The system clock could not produce a profile timestamp.", + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(base_url: &str) -> ConnectionProfileInput { + ConnectionProfileInput { + display_name: " Test Profile ".into(), + role: AstrBotProfileRole::General, + base_url: base_url.into(), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + allow_insecure_http: false, + pinned_certificate_fingerprint: None, + } + } + + #[test] + fn creates_updates_lists_and_deletes_profile_metadata() { + let database = ApplicationDatabase::in_memory().expect("database"); + let created = + create_profile(&database, request("https://example.test")).expect("create profile"); + assert_eq!(created.display_name, "Test Profile"); + assert_eq!(created.base_url, "https://example.test/"); + assert!(created.credential_reference.is_none()); + assert!(!created.auto_connect); + assert!(created.auto_connect_slot.is_none()); + + let updated = update_profile( + &database, + UpdateConnectionProfileRequest { + id: created.id.clone(), + profile: ConnectionProfileInput { + display_name: "Updated".into(), + role: AstrBotProfileRole::Companion, + base_url: "https://updated.example.test".into(), + event_stream_url: Some("https://updated.example.test/events".into()), + authentication_type: AuthenticationType::ApiKey, + allow_insecure_http: false, + pinned_certificate_fingerprint: None, + }, + }, + ) + .expect("update profile"); + assert_eq!(updated.display_name, "Updated"); + assert_eq!(list_profiles(&database).expect("list profiles").len(), 1); + + delete_profile(&database, &created.id).expect("delete profile"); + assert!(list_profiles(&database).expect("list profiles").is_empty()); + } + + #[test] + fn rejects_insecure_or_credential_bearing_urls() { + let database = ApplicationDatabase::in_memory().expect("database"); + assert!(create_profile(&database, request("http://example.test")).is_err()); + assert!(create_profile(&database, request("https://user:password@example.test")).is_err()); + assert!(create_profile(&database, request("https://example.test?token=fake")).is_err()); + } + + #[test] + fn rejects_secret_values_and_unknown_fields_at_the_ipc_boundary() { + let result = serde_json::from_value::(serde_json::json!({ + "displayName": "Test Profile", + "role": "general", + "baseUrl": "https://example.test", + "authenticationType": "device-token", + "allowInsecureHttp": false, + "token": "[REDACTED]", + "password": "[REDACTED]", + "apiKey": "[REDACTED]" + })); + + assert!(result.is_err()); + } +} From 907a8a38da5f171d4d82f85ac8b900392842739f Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 23:36:59 +0800 Subject: [PATCH 4/7] feat(profile-ui): add basic profile management --- src/App.test.tsx | 141 +++++++- src/App.tsx | 6 +- src/features/profiles/ProfileManager.tsx | 396 +++++++++++++++++++++++ src/styles.css | 190 ++++++++++- src/test/setup.ts | 7 + src/types/profile.ts | 54 ++++ tests/e2e/bootstrap.spec.ts | 10 +- 7 files changed, 787 insertions(+), 17 deletions(-) create mode 100644 src/features/profiles/ProfileManager.tsx create mode 100644 src/types/profile.ts diff --git a/src/App.test.tsx b/src/App.test.tsx index 265439b..0b29552 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -1,21 +1,36 @@ import { invoke } from "@tauri-apps/api/core"; -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { App } from "./App"; +import type { + ConnectionProfile, + ConnectionProfileInput, + UpdateConnectionProfileRequest, +} from "./types/profile"; vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(), })); +const bootstrapStatus = { + appVersion: "0.1.0-alpha.0", + platform: "windows", + rustCore: "ready", + protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 2, +}; + describe("App", () => { beforeEach(() => { - vi.mocked(invoke).mockResolvedValue({ - appVersion: "0.1.0-alpha.0", - platform: "windows", - rustCore: "ready", - protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 1, + vi.mocked(invoke).mockImplementation(async (command) => { + if (command === "bootstrap_status") { + return bootstrapStatus; + } + if (command === "list_connection_profiles") { + return []; + } + throw new Error(`Unexpected command: ${command}`); }); }); @@ -24,15 +39,21 @@ describe("App", () => { expect(await screen.findByText("ready")).toBeInTheDocument(); expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument(); + expect(screen.getByText("连接 Profile")).toBeInTheDocument(); }); it("rejects an invalid Rust IPC payload", async () => { - vi.mocked(invoke).mockResolvedValueOnce({ - appVersion: "0.1.0-alpha.0", - platform: "windows", - rustCore: "unexpected", - protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 1, + vi.mocked(invoke).mockImplementation(async (command) => { + if (command === "bootstrap_status") { + return { + ...bootstrapStatus, + rustCore: "unexpected", + }; + } + if (command === "list_connection_profiles") { + return []; + } + throw new Error(`Unexpected command: ${command}`); }); render(); @@ -40,4 +61,98 @@ describe("App", () => { expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument(); expect(screen.queryByText("unexpected")).not.toBeInTheDocument(); }); + + it("creates, edits, and deletes non-sensitive profile metadata", async () => { + let profiles: ConnectionProfile[] = []; + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command === "bootstrap_status") { + return bootstrapStatus; + } + if (command === "list_connection_profiles") { + return profiles; + } + if (command === "create_connection_profile") { + const { request } = args as { request: ConnectionProfileInput }; + const created: ConnectionProfile = { + id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + ...request, + autoConnect: false, + createdAt: "2026-07-18T02:00:00Z", + updatedAt: "2026-07-18T02:00:00Z", + }; + profiles = [created]; + return created; + } + if (command === "update_connection_profile") { + const { request } = args as { + request: UpdateConnectionProfileRequest; + }; + const existing = profiles.find((profile) => profile.id === request.id); + if (!existing) { + throw new Error("Profile not found"); + } + const updated: ConnectionProfile = { + ...existing, + ...request.profile, + updatedAt: "2026-07-18T02:10:00Z", + }; + profiles = [updated]; + return updated; + } + if (command === "delete_connection_profile") { + const { id } = args as { id: string }; + profiles = profiles.filter((profile) => profile.id !== id); + return undefined; + } + throw new Error(`Unexpected command: ${command}`); + }); + vi.spyOn(window, "confirm").mockReturnValue(true); + + render(); + expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText("显示名称"), { + target: { value: "家庭运维" }, + }); + fireEvent.change(screen.getByLabelText("角色"), { + target: { value: "operations" }, + }); + fireEvent.change(screen.getByLabelText("REST 基础 URL"), { + target: { value: "https://ops.example.test" }, + }); + fireEvent.click(screen.getByRole("button", { name: "保存 Profile" })); + + expect( + await screen.findByText("已创建 Profile:家庭运维"), + ).toBeInTheDocument(); + expect(screen.getByLabelText("编辑 家庭运维")).toBeEnabled(); + + fireEvent.click(screen.getByLabelText("编辑 家庭运维")); + fireEvent.change(screen.getByLabelText("显示名称"), { + target: { value: "家庭运维(主)" }, + }); + fireEvent.click(screen.getByRole("button", { name: "更新 Profile" })); + + expect( + await screen.findByText("已更新 Profile:家庭运维(主)"), + ).toBeInTheDocument(); + fireEvent.click(screen.getByLabelText("删除 家庭运维(主)")); + + await waitFor(() => { + expect( + screen.getByText("已删除 Profile:家庭运维(主)"), + ).toBeInTheDocument(); + }); + expect(screen.getByText("尚未保存 Profile。")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith( + "create_connection_profile", + expect.objectContaining({ + request: expect.not.objectContaining({ + token: expect.anything(), + password: expect.anything(), + apiKey: expect.anything(), + }), + }), + ); + }); }); diff --git a/src/App.tsx b/src/App.tsx index e967145..f5199ab 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,7 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; +import { ProfileManager } from "./features/profiles/ProfileManager"; import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; const initialStatus: BootstrapStatus = { @@ -8,7 +9,7 @@ const initialStatus: BootstrapStatus = { platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 1, + databaseSchemaVersion: 2, }; export function App() { @@ -32,7 +33,7 @@ export function App() { return (
-

P00 · bootstrap

+

P01 · foundation

AstrBot Desktop

双实例陪伴与本机助手的安全 Windows 客户端工程底座。 @@ -61,6 +62,7 @@ export function App() {

  • 文件事务默认保留源文件,且不会静默覆盖。
  • + + {editingId ? ( + + ) : null} + + + +
    +

    已保存 ({profiles.length})

    + {profiles.length === 0 ? ( +

    尚未保存 Profile。

    + ) : ( + profiles.map((profile) => ( +
    +
    + {profile.displayName} + {roleLabel(profile.role)} +
    + {profile.baseUrl} +

    + {profile.authenticationType === "api-key" + ? "API Key 引用" + : "设备 Token 引用"} + {" · "} + {profile.credentialReference ? "已登记" : "待登记"} +

    +
    + + +
    +
    + )) + )} +
    + + + {notice ? ( +

    + {notice} +

    + ) : null} + {error ? ( +

    + {error} +

    + ) : null} + + ); +} + +function toProfileInput(form: ProfileFormState): ConnectionProfileInput { + const eventStreamUrl = form.eventStreamUrl.trim(); + const fingerprint = form.pinnedCertificateFingerprint.trim(); + return { + displayName: form.displayName.trim(), + role: form.role, + baseUrl: form.baseUrl.trim(), + eventStreamUrl: eventStreamUrl || undefined, + authenticationType: form.authenticationType, + allowInsecureHttp: form.allowInsecureHttp, + pinnedCertificateFingerprint: fingerprint || undefined, + }; +} + +function sortProfiles(profiles: ConnectionProfile[]) { + return [...profiles].sort((left, right) => + left.displayName.localeCompare(right.displayName, "zh-CN"), + ); +} + +function roleLabel(role: ProfileRole) { + switch (role) { + case "companion": + return "陪伴"; + case "operations": + return "运维"; + case "general": + return "通用"; + } +} + +function errorMessage(reason: unknown) { + if (reason instanceof Error) { + return reason.message; + } + if ( + typeof reason === "object" && + reason !== null && + "message" in reason && + typeof reason.message === "string" + ) { + return reason.message; + } + return String(reason); +} diff --git a/src/styles.css b/src/styles.css index 0e302e7..0ddf472 100644 --- a/src/styles.css +++ b/src/styles.css @@ -43,8 +43,13 @@ button:hover { background: #204b88; } +button:disabled { + cursor: not-allowed; + opacity: 0.58; +} + .app-shell { - width: min(920px, calc(100% - 2rem)); + width: min(1120px, calc(100% - 2rem)); margin: 0 auto; padding: 4rem 0; } @@ -123,6 +128,158 @@ h1 { border-color: rgb(255 115 115 / 45%); } +.profile-manager { + margin: 2rem 0; + padding: 1.5rem; + border: 1px solid rgb(137 175 232 / 28%); + border-radius: 1rem; + background: rgb(13 29 52 / 78%); + box-shadow: 0 1rem 3rem rgb(0 0 0 / 18%); +} + +.section-heading { + display: grid; + grid-template-columns: minmax(0, 0.8fr) minmax(280px, 1.2fr); + gap: 2rem; + align-items: end; + margin-bottom: 1.25rem; +} + +.section-heading h2, +.profile-form h3, +.profile-list h3 { + margin: 0.3rem 0 0; +} + +.section-heading > p, +.form-note, +.empty-state, +.profile-card p { + color: #aebfda; +} + +.profile-layout { + display: grid; + grid-template-columns: minmax(300px, 0.95fr) minmax(320px, 1.05fr); + gap: 1rem; +} + +.profile-form, +.profile-list { + padding: 1.2rem; + border: 1px solid rgb(137 175 232 / 24%); + border-radius: 0.9rem; + background: rgb(7 18 34 / 52%); +} + +.profile-form { + display: grid; + gap: 1rem; +} + +.profile-form label:not(.checkbox-field) { + display: grid; + gap: 0.45rem; +} + +.profile-form label > span { + color: #c7d4e9; + font-size: 0.9rem; + font-weight: 650; +} + +input, +select { + width: 100%; + padding: 0.72rem 0.8rem; + border: 1px solid rgb(137 175 232 / 38%); + border-radius: 0.65rem; + color: inherit; + background: #0b1b31; + font: inherit; +} + +input:focus, +select:focus { + outline: 2px solid #6aa3ff; + outline-offset: 2px; +} + +.checkbox-field { + display: flex; + gap: 0.7rem; + align-items: flex-start; +} + +.checkbox-field input { + width: auto; + margin-top: 0.2rem; +} + +.form-note { + margin: 0; + font-size: 0.9rem; +} + +.button-row { + display: flex; + flex-wrap: wrap; + gap: 0.65rem; +} + +.button-secondary { + border-color: rgb(157 181 218 / 48%); + background: #20314b; +} + +.button-danger { + border-color: rgb(255 122 122 / 65%); + background: #5a2430; +} + +.profile-list { + display: grid; + align-content: start; + gap: 0.8rem; +} + +.profile-card { + display: grid; + gap: 0.7rem; + padding: 1rem; + border: 1px solid rgb(137 175 232 / 22%); + border-radius: 0.75rem; + background: rgb(20 42 72 / 72%); +} + +.profile-card > div:first-child { + display: flex; + justify-content: space-between; + gap: 1rem; +} + +.profile-card span { + color: #8db9ff; +} + +.profile-card code { + color: #dbe8ff; + overflow-wrap: anywhere; +} + +.profile-card p { + margin: 0; + font-size: 0.9rem; +} + +.notice-banner { + padding: 1rem; + border: 1px solid rgb(96 211 153 / 42%); + border-radius: 0.8rem; + color: #c8f7dc; + background: rgb(20 83 57 / 45%); +} + @media (prefers-color-scheme: light) { :root { color: #102039; @@ -141,10 +298,17 @@ h1 { .status-card, .boundaries, + .profile-manager, .error-banner { background: rgb(255 255 255 / 86%); } + .profile-form, + .profile-list, + .profile-card { + background: rgb(245 249 255 / 90%); + } + .status-card strong { color: #102039; } @@ -153,4 +317,28 @@ h1 { .subtitle { color: #405775; } + + input, + select { + color: #102039; + background: #ffffff; + } + + .section-heading > p, + .form-note, + .empty-state, + .profile-card p { + color: #405775; + } +} + +@media (max-width: 760px) { + .section-heading, + .profile-layout { + grid-template-columns: 1fr; + } + + .app-shell { + padding: 2rem 0; + } } diff --git a/src/test/setup.ts b/src/test/setup.ts index f149f27..004761e 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -1 +1,8 @@ import "@testing-library/jest-dom/vitest"; + +import { cleanup } from "@testing-library/react"; +import { afterEach } from "vitest"; + +afterEach(() => { + cleanup(); +}); diff --git a/src/types/profile.ts b/src/types/profile.ts new file mode 100644 index 0000000..6da7222 --- /dev/null +++ b/src/types/profile.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; + +export const profileRoleSchema = z.enum(["companion", "operations", "general"]); + +export const authenticationTypeSchema = z.enum(["device-token", "api-key"]); + +const optionalIdentifier = z.string().min(1).optional(); + +export const connectionProfileSchema = z + .object({ + id: z.uuid(), + displayName: z.string().min(1).max(80), + role: profileRoleSchema, + baseUrl: z.url(), + eventStreamUrl: z.url().optional(), + authenticationType: authenticationTypeSchema, + credentialReference: optionalIdentifier, + allowInsecureHttp: z.boolean(), + pinnedCertificateFingerprint: z + .string() + .regex(/^[A-F0-9]{64}$/) + .optional(), + autoConnectSlot: z.enum(["companion", "operations"]).optional(), + autoConnect: z.boolean(), + serverInstanceId: optionalIdentifier, + serverVersion: optionalIdentifier, + protocolVersion: optionalIdentifier, + localToolPolicyId: optionalIdentifier, + lastConnectedAt: optionalIdentifier, + createdAt: z.string().min(1), + updatedAt: z.string().min(1), + }) + .strict(); + +export const connectionProfileListSchema = z.array(connectionProfileSchema); + +export type ProfileRole = z.infer; +export type AuthenticationType = z.infer; +export type ConnectionProfile = z.infer; + +export interface ConnectionProfileInput { + displayName: string; + role: ProfileRole; + baseUrl: string; + eventStreamUrl?: string; + authenticationType: AuthenticationType; + allowInsecureHttp: boolean; + pinnedCertificateFingerprint?: string; +} + +export interface UpdateConnectionProfileRequest { + id: string; + profile: ConnectionProfileInput; +} diff --git a/tests/e2e/bootstrap.spec.ts b/tests/e2e/bootstrap.spec.ts index 9204191..856ebfa 100644 --- a/tests/e2e/bootstrap.spec.ts +++ b/tests/e2e/bootstrap.spec.ts @@ -12,5 +12,13 @@ test("renders the bootstrap shell and safe browser fallback", async ({ await expect( page.getByText("IPC unavailable:", { exact: false }), ).toBeVisible(); - await expect(page.getByRole("button")).toBeEnabled(); + await expect( + page.getByRole("heading", { name: "连接 Profile" }), + ).toBeVisible(); + await expect( + page.getByText("Profile storage unavailable:", { exact: false }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "重新检查 IPC" }), + ).toBeEnabled(); }); From 56725855913e58792bf83f8b82050c3c735b0c84 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 23:37:29 +0800 Subject: [PATCH 5/7] chore(version): set P01 alpha version --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- package.json | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0f0997c..0fac6f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -105,7 +105,7 @@ checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" [[package]] name = "astrbot-desktop" -version = "0.1.0-alpha.0" +version = "0.1.0-alpha.1" dependencies = [ "desktop-protocol", "eventsource-stream", @@ -989,7 +989,7 @@ dependencies = [ [[package]] name = "desktop-protocol" -version = "0.1.0-alpha.0" +version = "0.1.0-alpha.1" dependencies = [ "schemars 1.2.1", "serde", @@ -2470,7 +2470,7 @@ dependencies = [ [[package]] name = "mock-gateway" -version = "0.1.0-alpha.0" +version = "0.1.0-alpha.1" dependencies = [ "async-stream", "axum", diff --git a/Cargo.toml b/Cargo.toml index 9789c67..c50a8a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = [ resolver = "3" [workspace.package] -version = "0.1.0-alpha.0" +version = "0.1.0-alpha.1" edition = "2024" rust-version = "1.97.1" license = "MIT OR Apache-2.0" diff --git a/package.json b/package.json index 3544c72..c4e2b94 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "astrbot-desktop", - "version": "0.1.0-alpha.0", + "version": "0.1.0-alpha.1", "private": true, "type": "module", "packageManager": "pnpm@11.9.0", diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index cb3b96b..27b3b8e 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "AstrBot Desktop", - "version": "0.1.0-alpha.0", + "version": "0.1.0-alpha.1", "identifier": "com.yokiirobw.astrbot-desktop", "build": { "beforeDevCommand": "npm run dev", From 2154c3b5ee8343e08680635da113adfdce1afdff Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 23:38:20 +0800 Subject: [PATCH 6/7] docs(p01): resolve profile boundary and record verification --- CHANGELOG.md | 6 ++ ...4-profile-lifecycle-and-secret-boundary.md | 64 +++++++++++++ docs/decisions/pending-decisions.md | 15 ++- docs/implementation-plan.md | 29 ++++-- docs/progress.md | 86 ++++++++--------- docs/reports/p01-foundation-progress.md | 96 ++++++++++++------- 6 files changed, 200 insertions(+), 96 deletions(-) create mode 100644 docs/decisions/ADR-0004-profile-lifecycle-and-secret-boundary.md diff --git a/CHANGELOG.md b/CHANGELOG.md index f7b1308..c41668a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,9 +22,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and - Strict Zod validation for the Rust bootstrap IPC payload, including the active database schema version. - Redacting tracing output writer with structured-field, bearer-token, URL-credential, private-key, and known-secret coverage. - P01 migration, logging, IPC validation, real Tauri startup, and production-build verification. +- SQLite schema v2 for persistent non-sensitive ConnectionProfile metadata. +- Bounded Rust-owned Profile list/create/update/delete IPC with generated UUIDs and timestamps. +- Strict frontend ConnectionProfile Schemas and a basic Profile management UI. +- Migration, five-Profile CRUD, persistent reopen, secret-field rejection, and browser fallback tests. ### Security - Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only. - Added secret redaction and repository scans; no arbitrary PowerShell, CMD, shell, input-injection, registry-write, or unrestricted filesystem API is exposed. - Kept real UNC writes, signing keys, updater keys, and release secrets outside P00. +- Rejected Token, password, API Key, URL credential, query-string credential, and unknown fields at the Profile IPC boundary. +- Required explicit approval for insecure HTTP and kept slots, connections, and credential enrollment outside P01. diff --git a/docs/decisions/ADR-0004-profile-lifecycle-and-secret-boundary.md b/docs/decisions/ADR-0004-profile-lifecycle-and-secret-boundary.md new file mode 100644 index 0000000..de5863b --- /dev/null +++ b/docs/decisions/ADR-0004-profile-lifecycle-and-secret-boundary.md @@ -0,0 +1,64 @@ +# ADR-0004: Profile lifecycle and secret boundary + +- Status: accepted +- Date: 2026-07-18 +- Decision owner: project owner + +## Background + +The architecture document assigns Profile CRUD to stage 1, while the implementation task document groups ConnectionProfile CRUD with the stage 2 dual-connection slots. The conflict affects the SQLite schema, Tauri IPC surface, frontend state, and stage acceptance boundary. + +The project owner selected option A from PD-0008: + +- P01 owns basic ConnectionProfile metadata CRUD. +- P02 owns active slot assignment and all runtime connection behavior. + +## Options considered + +### Option A: basic metadata CRUD in P01 + +Create, list, update, and delete non-sensitive Profile metadata in P01. Keep companion/operations slot assignment, active connections, auto-connect validation, switching protection, and duplicate server-instance detection in P02. + +### Option B: defer all Profile CRUD to P02 + +Keep P01 limited to application bootstrap, persistent SQLite, logging, tray, single-instance, and tests. + +## Decision + +Use option A. + +P01 persists the canonical non-sensitive ConnectionProfile fields and exposes bounded Tauri commands for: + +- listing Profiles; +- creating a Profile; +- updating user-editable metadata; +- deleting a Profile. + +The P01 IPC input does not accept Token, password, API Key, Cookie, Authorization header, NAS credential, or arbitrary extra fields. Rust creates Profile IDs and timestamps. React may receive only non-sensitive metadata and an opaque credential reference. + +The following remain explicitly out of P01: + +- credential value enrollment or retrieval; +- companion/operations slot assignment; +- connection activation and cancellation; +- auto-connect behavior; +- switching protection; +- server_instance_id conflict detection; +- REST/SSE runtime state. + +## Reasons + +- AGENTS.md gives the architecture document higher priority. +- A saved Profile is a durable application-foundation concept and can be implemented without activating a connection. +- Separating metadata from runtime connection state preserves the Rust-owned security boundary. +- The narrow IPC input makes accidental secret transfer to React or SQLite rejectable at deserialization time. + +## Trade-offs + +- P01 can select an authentication type but cannot enroll the corresponding credential value. +- The UI is intentionally a foundation form, not a full connection settings experience. +- Credential deletion and transactional cleanup must be added with the formal credential lifecycle before credential references can be created by production flows. + +## Follow-up + +P02 must consume this metadata model without widening the P01 commands to accept secret values. It must add slots, connection state, auto-connect rules, profile-switch guards, duplicate server-instance warnings, and credential lifecycle integration as separate reviewed increments. diff --git a/docs/decisions/pending-decisions.md b/docs/decisions/pending-decisions.md index dc60a73..4fc3fac 100644 --- a/docs/decisions/pending-decisions.md +++ b/docs/decisions/pending-decisions.md @@ -53,12 +53,11 @@ ## PD-0008: Profile CRUD stage ownership -- Status: unresolved; blocks Profile CRUD implementation only +- Status: resolved; option A selected by the project owner on 2026-07-18 - Conflict: `docs/01_Architecture_Design.md` lists Profile CRUD in stage 1, while `docs/02_Codex_Implementation_Tasks.md` lists ConnectionProfile CRUD in Batch 2. -- Impact: resolving this changes the database schema, Tauri IPC surface, frontend state model, and the acceptance boundary between `feat/p01-foundation` and `feat/p02-dual-connections`. -- Safe current action: complete only the unambiguous P01 foundation work��persistent migrations, validated bootstrap IPC, redacted logging, tray, single-instance, exit flow, and tests. -- Paused work: profile tables, Profile CRUD commands, profile forms, and profile-to-slot assignment. -- Required decision: - - Option A: architecture document wins; implement basic Profile CRUD in P01 and leave slot assignment/connection behavior for P02. - - Option B: implementation task batching wins; keep all ConnectionProfile CRUD in P02. -- Recommendation: Option A is the literal higher-priority document, but the implementation remains paused because AGENTS.md requires explicit reporting for conflicts affecting database structure or public interfaces. +- Decision: implement basic non-sensitive Profile metadata CRUD in P01. +- P01 scope: Profile list, create, update, and delete; SQLite schema v2; bounded Tauri IPC; strict frontend Schema; basic management UI. +- P02 scope: companion/operations slot assignment, active connection state, auto-connect validation, switching protection, and `server_instance_id` conflict detection. +- Secret boundary: P01 commands accept no Token, password, API Key, Cookie, Authorization header, or NAS credential fields. SQLite stores only non-sensitive metadata and future opaque credential references. +- Rationale: AGENTS.md gives the architecture document higher priority, and the selected split keeps runtime connection behavior out of P01. +- ADR: `ADR-0004-profile-lifecycle-and-secret-boundary.md`. diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 1ee495c..c236918 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -41,7 +41,7 @@ Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and comple ### Objective -Turn the P00 Spike skeleton into a durable application foundation without pulling Batch 2 connection-profile behavior forward across an unresolved document boundary. +Turn the P00 Spike skeleton into a durable application foundation. Under the project owner's option A decision, P01 includes basic non-sensitive Profile metadata CRUD while P02 retains all slot and runtime connection behavior. ### Ordered work @@ -49,11 +49,26 @@ Turn the P00 Spike skeleton into a durable application foundation without pullin 2. Apply versioned, transactional, idempotent migrations and refuse unknown future schema versions. 3. Validate Rust-to-TypeScript bootstrap payloads at runtime. 4. Ensure tracing output passes through the shared redaction rules before it reaches a writer. -5. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, and production build behavior. -6. Record the Profile CRUD stage conflict before changing its schema or IPC. +5. Add SQLite schema v2 for canonical non-sensitive ConnectionProfile metadata. +6. Add bounded Tauri list/create/update/delete commands that generate IDs and timestamps in Rust. +7. Reject secret values, URL credentials, query-string credentials, unknown IPC fields, and implicit insecure HTTP. +8. Add strict frontend Profile Schemas and a basic management UI without Token/password/API Key inputs. +9. Test five saved Profiles, CRUD, persistent reopen, v1-to-v2 migration, future-version rejection, and browser fallback. +10. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, Schema export, and production build behavior. +11. Record the decision in PD-0008 and ADR-0004, then commit and push the verified branch normally. -### Paused boundary +### P01 boundary -- `docs/01_Architecture_Design.md` places Profile CRUD in stage 1. -- `docs/02_Codex_Implementation_Tasks.md` places ConnectionProfile CRUD in Batch 2. -- Because this changes database structure and public IPC, Profile CRUD remains paused under PD-0008 until the stage boundary is explicitly resolved. +- Included: durable application database, schema migration, redacted logging, validated bootstrap IPC, basic Profile metadata CRUD, basic Profile management UI, tray, single-instance, and build/test foundations. +- Excluded: slot assignment, active REST/SSE connections, auto-connect behavior, Profile switching protection, duplicate `server_instance_id` handling, and formal credential enrollment. + +### Verification status + +- Frontend formatting, ESLint, TypeScript, 3 Vitest tests, and Vite production build passed. +- Playwright Chromium passed 1/1. +- Rust fmt, Clippy with warnings denied, tests, and check passed. +- Rust test suite passed 50 normal tests; 2 explicit manual tests remained ignored. +- Protocol Schema export completed without drift. +- Real Tauri development startup reached the Windows executable and was then deliberately terminated. +- Windows release and NSIS bundling passed. +- Forgejo CI remains unverified because a compatible runner/jobs endpoint is unavailable. diff --git a/docs/progress.md b/docs/progress.md index ac108f7..9276fcc 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -2,43 +2,42 @@ ## Current phase -P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work is implemented, while Profile CRUD is paused on a documented stage-boundary conflict. +P01 foundation is active on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02. ## Completed -- Read `AGENTS.md` and all authoritative architecture, implementation, and Forgejo workflow documents. +- Read `AGENTS.md`, the architecture, implementation task, and Forgejo predevelopment workflow documents in full. - Verified the Windows, Git, Node.js, package-manager, WebView2, Rust, Tauri, and MSVC environment. -- Initialized a local Git repository on `main`. -- Configured `origin` as `ssh://git@localhost:18086/YokiiroBW/AstrBot-Desktop.git`. -- Verified through authenticated Forgejo API and HTTP Git that the remote repository existed, was empty, used `main`, and granted push permission before the baseline push. -- Reauthenticated through Git Credential Manager and non-forced pushed the `main` baseline to Forgejo at `0d12b94`. -- Created and switched to `feat/p00-bootstrap` from the pushed `main` baseline. -- Built the Tauri 2 + React + TypeScript + Rust skeleton with tray, single-instance, CSP, and minimal `core:default` capability. -- Implemented independent companion/operations REST and SSE clients and passed the corrected 30-minute soak. -- Implemented and tested Windows Credential Manager, UI Automation, selected-window capture, Event Log, process, port, foreground-window, authorized log-tail, configuration parsing, and redaction Spikes. -- Implemented and tested composite-key SQLite isolation and recoverable local file transactions with source preservation. -- Added provisional protocol types, ten JSON Schemas, TypeScript exports, drift checks, and two loopback-only Mock Gateway instances. -- Added frontend, Playwright, Rust, integration, Windows-provider, soak, and Forgejo CI entry points. -- Built the Windows release executable and SHA-256-recorded NSIS installer. -- Added dependency, Spike, progress, changelog, and pending-decision records. -- Verified Forgejo PR #1 merged into `main` as `b3420e4`. -- Fast-forwarded local `main` and created `feat/p01-foundation` from the merged baseline. -- Added persistent SQLite startup initialization with WAL, busy timeout, transactional `user_version` migration, idempotent reopen, and future-version rejection. -- Added strict Zod validation for the Rust bootstrap IPC payload and exposed the active database schema version. -- Added a redacting tracing writer that sanitizes structured fields and rendered message content before output. -- Verified a real Tauri development start created the application database in the Windows app-data directory. -- Built the P01 Windows release executable and NSIS installer. -- Committed the implementation, test, and CI increments with Conventional Commit subjects. +- Initialized and normalized Git, established `main`, and pushed the baseline without force. +- Completed and merged P00 through Forgejo PR #1 at `b3420e4`. +- Created `feat/p01-foundation` from the merged `main`. +- Added persistent SQLite startup initialization with WAL, busy timeout, foreign-key enforcement, and transactional migrations. +- Added schema v2 with canonical non-sensitive `connection_profiles` metadata. +- Added fresh-database, v1-to-v2, future-version, idempotent reopen, five-Profile, CRUD, and persistent-reopen coverage. +- Added bounded Tauri Profile list/create/update/delete commands. +- Kept UUID and timestamp creation in Rust. +- Rejected credential-bearing URLs, URL query/fragment data, implicit HTTP, invalid certificate fingerprints, malformed IDs, unknown fields, and Token/password/API Key fields. +- Preserved credential references and runtime-managed fields outside the editable P01 input. +- Added strict Zod Schemas for bootstrap and ConnectionProfile IPC payloads. +- Added a basic React Profile management UI for non-sensitive metadata only. +- Added explicit deletion confirmation and browser-safe Tauri IPC fallback. +- Added a redacting tracing writer that sanitizes structured fields and rendered message content. +- Retained tray, close-to-tray, explicit quit, and single-instance behavior. +- Re-exported protocol Schemas without drift. +- Re-ran a real Tauri development startup and reached the Windows executable. +- Rebuilt the Windows release executable and NSIS installer. +- Recorded the Profile boundary in PD-0008 and ADR-0004. ## In progress -- Recording the Profile CRUD stage conflict and preparing the verified P01 foundation increment for remote review. +- Final documentation review, focused Conventional Commits, and normal Forgejo push. ## Remaining -- Resolve whether Profile CRUD belongs in P01 (architecture document) or P02/Batch 2 (implementation task document) before changing its database schema or public IPC. -- After resolution, complete the selected stage scope and open a PR without automatically merging `main`. -- Run the Forgejo workflow when a compatible runner is available. +- Commit the verified backend, frontend, test, and documentation increments. +- Push `feat/p01-foundation` normally to Forgejo. +- Generate the P01 Forgejo PR title and body; do not merge `main`. +- Run Forgejo CI when a compatible runner is available. - Execute a real UNC transaction only after an authorized disposable fixture is supplied. - Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray. @@ -46,22 +45,23 @@ P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work i - Configured Forgejo SSH `localhost:18086` refuses connections. - LAN SSH `192.168.31.210:18086` responds but rejects the available public key. -- HTTP Git push is operational after Git Credential Manager reauthentication and is no longer a blocker. -- Profile CRUD stage ownership conflicts between the architecture and implementation task documents; implementation is paused because it affects database structure and public IPC. +- Approved HTTP Git push remains operational and is not blocked. - Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404. +- No blocker remains for the selected P01 scope. ## Test status -- `npm run check:frontend`: passed; 2 Vitest tests and production Vite build. -- `pnpm test:e2e`: passed; 1 Chromium smoke test. +- `npm run check:frontend`: passed; Prettier, ESLint, TypeScript, 3 Vitest tests, and Vite production build. +- `npm run test:e2e`: passed; 1 Chromium smoke test. - Rust fmt/check/Clippy with warnings denied: passed. -- `cargo test --workspace`: 44 passed, 2 explicit manual tests ignored. -- Controlled Windows UIA/PrintWindow smoke: 1 passed. -- Corrected dual-SSE soak: 1800.02 seconds, 1800 companion events, 1801 operations events, passed. -- Protocol Schema drift check: passed. -- P01 Tauri development startup and application-data SQLite creation: passed. -- P01 release executable and NSIS installer: passed after repairing the missing official `libsqlite3-sys` binding cache; installer SHA-256 `B8858CBE2F4673FAF40799C1243BCAB0748D194FA3AD67FBD33DDCF26CF27189`. -- pnpm 11.9.0 frozen lockfile-only validation: passed using a local temporary store to avoid the pnpm UNC project-registry limitation. +- `cargo test --workspace`: passed; 50 normal tests, 2 explicit manual tests ignored. +- Profile persistence: passed; five Profile CRUD, close/reopen persistence, and v1-to-v2 migration preserve existing messages. +- Secret boundary: passed; unknown Token, password, and API Key input fields are rejected. +- Protocol Schema export: passed; no generated drift. +- Tauri development startup: passed; executable launched, then was deliberately terminated after verification. +- Tauri Windows release executable: passed. +- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes. +- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`. - Forgejo CI and a real UNC transaction were not executed and are not claimed successful. ## Current branch @@ -70,16 +70,10 @@ P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work i ## Recent commits -- `5e6e8d5 docs(project): add architecture and implementation specifications` -- `0d12b94 chore(repo): initialize repository and ignore rules` -- `01607c6 feat(p00): add Tauri desktop spike foundation` -- `69b432b test(p00): add frontend browser rust and windows checks` -- `d4af979 ci(forgejo): add portable and windows quality workflows` -- `72a16cb docs(p00): record Forgejo branch publication` - `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` - `ed74342 feat(foundation): add persistent bootstrap safeguards` -- `353a439 docs(p00): record spike results and unresolved boundaries` +- `6a1eeab docs(p01): record foundation progress and profile boundary` ## Next step -Obtain an explicit decision for PD-0008 before implementing Profile CRUD. Continue other P01 work only if it does not change the disputed profile database or public IPC boundary. +Create focused commits for Profile persistence/IPC, Profile UI/tests, and P01 decision/report documentation. Re-run the proportional checks for each commit, push the branch normally, and prepare the Forgejo PR without merging `main`. diff --git a/docs/reports/p01-foundation-progress.md b/docs/reports/p01-foundation-progress.md index 3815029..c5968ab 100644 --- a/docs/reports/p01-foundation-progress.md +++ b/docs/reports/p01-foundation-progress.md @@ -4,58 +4,84 @@ Date: 2026-07-18 ## Status -P01 foundation work is partially complete on `feat/p01-foundation`. The unambiguous Batch 1 foundation items are implemented and verified. Profile CRUD is intentionally paused under PD-0008 because the architecture and implementation task documents assign it to different stages. +P01 implementation and local verification are complete on `feat/p01-foundation`. The branch still requires focused commits and a normal Forgejo push before the stage can be handed off for review. + +PD-0008 was resolved by the project owner with option A: + +- P01 includes basic non-sensitive Profile metadata CRUD. +- P02 retains slots, active connections, auto-connect, switching protection, duplicate server-instance handling, and credential enrollment. ## Completed - Verified P00 PR #1 merged into `main` at `b3420e4`. -- Fast-forwarded local `main` and created `feat/p01-foundation`. -- Added a persistent SQLite database under the Tauri application-data directory. -- Added WAL mode, a bounded busy timeout, foreign-key enforcement, and transactional `user_version` migration. -- Added idempotent reopen/persistence tests and rejection of databases newer than the supported schema. -- Added the database schema version to the bootstrap IPC response. -- Added strict frontend Zod validation for the IPC payload and a malformed-payload test. +- Created `feat/p01-foundation` from the merged baseline. +- Added persistent SQLite under the Tauri application-data directory. +- Added WAL, a bounded busy timeout, foreign-key enforcement, and transactional `user_version` migrations. +- Added schema v2 for `connection_profiles`. +- Verified fresh creation and v1-to-v2 migration without losing existing messages. +- Verified five saved Profiles, full CRUD, and persistence after reopening the database. +- Added bounded Tauri list/create/update/delete commands. +- Added Rust-owned UUIDs and RFC 3339 timestamps. +- Added URL normalization and rejection of embedded credentials, query strings, fragments, implicit HTTP, and invalid fingerprints. +- Added strict IPC rejection for unknown Token, password, and API Key fields. +- Added strict frontend ConnectionProfile Schemas. +- Added a basic React Profile manager with list/create/edit/delete and explicit deletion confirmation. +- Added no Token, password, API Key, Cookie, or NAS credential input. - Added a tracing writer that redacts output before writing. -- Retained the existing tray menu, close-to-tray, explicit quit, and single-instance focus behavior. +- Retained tray, close-to-tray, explicit quit, and single-instance focus behavior. +- Added ADR-0004 for the Profile lifecycle and secret boundary. ## Verification -| Check | Result | -| ------------------------------------------------------- | ------------------------------------------------------------------ | -| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 2 Vitest tests | -| Playwright Chromium | Passed; 1 test | -| Rust fmt, Clippy with warnings denied, check | Passed | -| Rust tests | Passed; 44 normal tests, 2 explicit manual tests ignored | -| Persistent SQLite reopen and migration tests | Passed | -| Logging redaction writer test | Passed | -| Tauri development startup | Passed | -| Windows application-data SQLite creation | Passed; database created at startup | -| Tauri release executable | Passed | -| NSIS installer | Passed; 3,793,884 bytes | -| NSIS SHA-256 | `B8858CBE2F4673FAF40799C1243BCAB0748D194FA3AD67FBD33DDCF26CF27189` | +| Check | Result | +| ------------------------------------------------------- | --------------------------------------------------------------------------- | +| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 3 Vitest tests | +| Playwright Chromium | Passed; 1 test | +| Rust fmt, Clippy with warnings denied, check | Passed | +| Rust tests | Passed; 50 normal tests, 2 explicit manual tests ignored | +| SQLite fresh schema v2 | Passed | +| SQLite v1-to-v2 migration | Passed; existing message preserved | +| Five Profile CRUD | Passed | +| Profile close/reopen persistence | Passed | +| Unknown secret IPC fields | Passed; rejected | +| Protocol Schema export | Passed; no drift | +| Tauri development startup | Passed; executable launched and was deliberately stopped after verification | +| Tauri release executable | Passed | +| NSIS installer | Passed; `0.1.0-alpha.1`, 3,827,899 bytes | +| NSIS SHA-256 | `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740` | + +## Security boundary + +- React never receives or submits credential values. +- P01 IPC accepts only non-sensitive Profile fields. +- Unknown input fields are rejected by Serde. +- SQLite stores non-sensitive Profile metadata and reserves only an opaque `credential_reference`. +- HTTP requires an explicit insecure-transport flag. +- URLs containing credentials, query strings, or fragments are rejected. +- No arbitrary command, unrestricted filesystem, registry-write, input-injection, or destructive file API was added. ## Build environment note -The first release attempts failed because the `libsqlite3-sys` release output directory did not contain `bindgen.rs`, although the crate build script had produced the SQLite static library. Cleaning only that package did not restore the file. - -The official pre-generated `bindgen_bundled_version.rs` from the installed `libsqlite3-sys 0.38.1` crate source was copied to the exact `OUT_DIR/bindgen.rs` location expected by the crate's own `build.rs`. Source and destination SHA-256 values matched: +The prior P01 release attempt found a missing generated `bindgen.rs` in the local `libsqlite3-sys 0.38.1` release cache. The official cached `bindgen_bundled_version.rs` was copied to the exact expected build-cache location, and the matching SHA-256 was recorded: `5B5A37A74DC728FB0BCD041867EB577C03C95E2FE46285262C589A3B1CD4BBAC` -The production build and NSIS bundle then completed. This is recorded as an environment cache repair, not a repository or dependency change. +This was an environment cache repair only. No repository file or dependency version was changed. The current production build completed successfully using the repaired cache. -## Paused boundary +## Deferred to P02 -Profile CRUD is not implemented in this increment. - -- Architecture stage 1 includes Profile CRUD. -- Implementation Batch 2 includes ConnectionProfile CRUD. -- The conflict affects database structure and public IPC. -- PD-0008 requires an explicit stage-boundary decision before work resumes. +- companion and operations slot assignment; +- maximum two active connections; +- REST/SSE activation and cancellation; +- auto-connect validation; +- Profile switching protection; +- duplicate `server_instance_id` warnings; +- formal credential enrollment, lookup, rotation, and deletion. ## Not claimed -- P01 is not declared complete while PD-0008 is unresolved. - Forgejo CI has not run. -- No Profile CRUD, profile UI, or slot assignment was added. -- No real credential or destructive file operation was used. +- No real AstrBot gateway compatibility is claimed. +- No real credential was used. +- No real UNC file transaction was executed. +- No automatic merge to `main` was performed. From 99b3f4dea38bb9d2a4c0ce3161b8bafc539d9a43 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 23:42:36 +0800 Subject: [PATCH 7/7] docs(p01): record Forgejo branch publication --- docs/progress.md | 14 ++++++++------ docs/reports/p01-foundation-progress.md | 5 +++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index 9276fcc..9b410b4 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -2,7 +2,7 @@ ## Current phase -P01 foundation is active on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02. +P01 foundation is complete and published on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02. ## Completed @@ -30,13 +30,11 @@ P01 foundation is active on `feat/p01-foundation`. The option A boundary is reso ## In progress -- Final documentation review, focused Conventional Commits, and normal Forgejo push. +- No code implementation is in progress; the branch is awaiting Forgejo PR review. ## Remaining -- Commit the verified backend, frontend, test, and documentation increments. -- Push `feat/p01-foundation` normally to Forgejo. -- Generate the P01 Forgejo PR title and body; do not merge `main`. +- Create and review the P01 Forgejo PR; do not automatically merge `main`. - Run Forgejo CI when a compatible runner is available. - Execute a real UNC transaction only after an authorized disposable fixture is supplied. - Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray. @@ -73,7 +71,11 @@ P01 foundation is active on `feat/p01-foundation`. The option A boundary is reso - `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` - `ed74342 feat(foundation): add persistent bootstrap safeguards` - `6a1eeab docs(p01): record foundation progress and profile boundary` +- `02fd25a feat(profile): add secure profile persistence and IPC` +- `907a8a3 feat(profile-ui): add basic profile management` +- `5672585 chore(version): set P01 alpha version` +- `2154c3b docs(p01): resolve profile boundary and record verification` ## Next step -Create focused commits for Profile persistence/IPC, Profile UI/tests, and P01 decision/report documentation. Re-run the proportional checks for each commit, push the branch normally, and prepare the Forgejo PR without merging `main`. +Open `feat/p01-foundation → main` as a Forgejo PR, review the recorded local verification, and run CI only when a compatible runner is available. diff --git a/docs/reports/p01-foundation-progress.md b/docs/reports/p01-foundation-progress.md index c5968ab..b2c47bc 100644 --- a/docs/reports/p01-foundation-progress.md +++ b/docs/reports/p01-foundation-progress.md @@ -4,7 +4,7 @@ Date: 2026-07-18 ## Status -P01 implementation and local verification are complete on `feat/p01-foundation`. The branch still requires focused commits and a normal Forgejo push before the stage can be handed off for review. +P01 implementation, local verification, focused commits, and normal Forgejo branch publication are complete. The stage is ready for a `feat/p01-foundation → main` PR review. PD-0008 was resolved by the project owner with option A: @@ -47,8 +47,9 @@ PD-0008 was resolved by the project owner with option A: | Protocol Schema export | Passed; no drift | | Tauri development startup | Passed; executable launched and was deliberately stopped after verification | | Tauri release executable | Passed | -| NSIS installer | Passed; `0.1.0-alpha.1`, 3,827,899 bytes | +| NSIS installer | Passed; `0.1.0-alpha.1`, 3,827,899 bytes | | NSIS SHA-256 | `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740` | +| Forgejo feature branch | Passed; normal push through `2154c3b`, no force and no `main` merge | ## Security boundary