Compare commits

...
3 Commits
Author SHA1 Message Date
jfmonty2 3c06f7e536 add unlock/exit buttons to home screen 2026-11-18 20:12:22 -05:00
jfmonty2 b2a7e5759a add UI tests for welcome and unlock flows 2026-11-18 14:31:00 -05:00
jfmonty2 5999aba0a5 test loading AppSession 2026-11-18 10:14:36 -05:00
13 changed files with 1159 additions and 79 deletions

No files matched your search

Generated
+822 -35
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -23,4 +23,5 @@ testresult = "0.4.2"
thiserror = "2.0.21"
[dev-dependencies]
gpui-kit = { version = "0.7.0", features = ["test-support"] }
tempfile = "3.27.0"
+28
View File
@@ -0,0 +1,28 @@
use std::borrow::Cow;
use gpui_kit::assets::{Assets, icon_assets};
use gpui_kit::{AssetSource, Result, SharedString};
// gpui-kit only embeds the icons its own components use, so anything else has to be listed here
icon_assets!(CreddyIcons, [LogOut, ShieldCheck]);
/// Our extra icons, falling back to gpui-kit's defaults.
pub struct CreddyAssets;
impl AssetSource for CreddyAssets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
match CreddyIcons.load(path)? {
Some(bytes) => Ok(Some(bytes)),
None => Assets.load(path),
}
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths = Assets.list(path)?;
paths.extend(CreddyIcons.list(path)?);
paths.sort();
paths.dedup();
Ok(paths)
}
}
+13
View File
@@ -0,0 +1,13 @@
use gpui_kit::{App, InteractiveElement, IntoElement, Role, SharedString, StatefulInteractiveElement, TestSupportExt};
use gpui_omarchy::{Status, alert};
/// An error alert whose message is also its accessible label,
/// so screen readers announce it and UI tests can find it by its "error" ID.
pub fn error_alert(message: SharedString, cx: &App) -> impl IntoElement {
alert(message.clone(), Status::Error, cx)
.id("error")
.role(Role::Alert)
.aria_label(message)
.test_support()
}
+2
View File
@@ -1,3 +1,5 @@
mod error_alert;
mod passphrase_input;
pub use error_alert::error_alert;
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
+6 -3
View File
@@ -12,6 +12,7 @@ use gpui_omarchy::{ButtonVariant, icon_button, input};
/// The `show` flag is passed in from outside so that it can be shared
/// (e.g. passphrase and confirm-passphrase inputs should share it).
pub struct PassphraseInput {
id: SharedString,
state: Entity<InputState>,
show: Entity<bool>,
_subscriptions: Vec<Subscription>,
@@ -29,7 +30,7 @@ pub enum PassphraseInputEvent {
impl EventEmitter<PassphraseInputEvent> for PassphraseInput {}
impl PassphraseInput {
pub fn new(show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self {
pub fn new(id: impl Into<SharedString>, show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let masked = !*show.read(cx);
let state = cx.new(|cx| {
InputState::new(window, cx)
@@ -56,6 +57,7 @@ impl PassphraseInput {
});
Self {
id: id.into(),
state,
show,
_subscriptions: vec![sync_mask, forward],
@@ -87,10 +89,11 @@ impl Render for PassphraseInput {
(IconName::Eye, "Show passphrase")
};
input("passphrase", &self.state, window, cx)
let toggle_id = SharedString::from(format!("{}-toggle-show", self.id));
input(self.id.clone(), &self.state, window, cx)
.w_full()
.suffix(
icon_button("toggle-show", icon, label, ButtonVariant::Secondary, cx)
icon_button(toggle_id, icon, label, ButtonVariant::Secondary, cx)
.on_click(cx.listener(|this, _, _, cx| this.toggle_show(cx))),
)
}
+2 -1
View File
@@ -13,7 +13,8 @@ impl Db {
pub fn save_private_config(&self, config: &PrivateConfig) -> Result<(), CreddyError> {
let json = serde_json::to_string(&config)?;
let conn = self.connection.lock().unwrap();
conn.execute("INSERT INTO config VALUES (?);", [&json])?;
// the migration seeds the only row, so this is always an update
conn.execute("UPDATE config SET value = ?;", [&json])?;
Ok(())
}
}
+169 -12
View File
@@ -1,8 +1,10 @@
use gpui_kit::{
AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div,
App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowHandle,
WindowOptions, div,
};
use gpui_omarchy::ActiveTheme;
mod assets;
mod components;
mod config;
mod db;
@@ -46,6 +48,20 @@ impl Render for CreddyApp {
}
}
/// Install the globals and open the main window. Tests call this too, so they get the same wiring.
fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHandle<CreddyApp> {
gpui_omarchy::init(cx);
cx.set_global(config);
cx.set_global(session);
// refresh_windows() forces everything to re-render, which is kind of a nuclear solution,
// but these values aren't expected to change very frequently, so it shouldn't be a problem
cx.observe_global::<AppConfig>(|cx| cx.refresh_windows()).detach();
cx.observe_global::<AppSession>(|cx| cx.refresh_windows()).detach();
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
.expect("open window")
}
fn main() {
// todo: replace this with proper error handling
let app_config = AppConfig::load().expect("failed to load config");
@@ -53,18 +69,159 @@ fn main() {
// Icons are read through the asset source, so register the bundle.
gpui_kit::application()
.with_assets(gpui_kit::assets::Assets)
.with_assets(assets::CreddyAssets)
.run(|app| {
gpui_omarchy::init(app);
app.set_global(app_config);
app.set_global(app_session);
// refresh_windows() forces everything to re-render, which is kind of a nuclear solution,
// but these values aren't expected to change very frequently, so it shouldn't be a problem
app.observe_global::<AppConfig>(|app| app.refresh_windows()).detach();
app.observe_global::<AppSession>(|app| app.refresh_windows()).detach();
app.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
.expect("open window");
launch(app, app_config, app_session);
app.activate(true);
});
}
#[cfg(test)]
mod tests {
use gpui_kit::{AnyWindowHandle, TestAppContext};
use gpui_kit::test::TestWindowExt;
use super::*;
use crate::test_data::{TEST_PASSPHRASE, TestEnv};
/// Start the app against the test environment, as `main` would.
fn open_app(env: &TestEnv, cx: &mut TestAppContext) -> AnyWindowHandle {
let window = cx.update(|cx| launch(cx, env.config.clone(), AppSession::load(&env.config)));
// first frame, so that elements exist to be found
cx.update_window(window.into(), |_, window, cx| window.render_frame(cx)).unwrap();
window.into()
}
/// Do something in the window, then let any resulting tasks (e.g. the KDF) finish.
fn act(window: AnyWindowHandle, cx: &mut TestAppContext, f: impl FnOnce(&mut Window, &mut App)) {
cx.update_window(window, |_, window, cx| f(window, cx)).unwrap();
cx.run_until_parked();
cx.update_window(window, |_, window, cx| window.render_frame(cx)).unwrap();
}
/// Click into a field and type.
fn fill(window: AnyWindowHandle, id: &'static str, text: &str, cx: &mut TestAppContext) {
act(window, cx, |window, cx| {
window.click(id, cx);
window.input(text, cx);
});
}
fn click(window: AnyWindowHandle, id: &'static str, cx: &mut TestAppContext) {
act(window, cx, |window, cx| window.click(id, cx));
}
/// The message in the error alert, if one is showing.
fn error_message(window: AnyWindowHandle, cx: &mut TestAppContext) -> Option<String> {
cx.update_window(window, |_, window, _| {
window.try_find("error").and_then(|e| e.label().map(String::from))
}).unwrap()
}
fn is_unlocked(cx: &TestAppContext) -> bool {
cx.read(|cx| matches!(cx.global::<AppSession>(), AppSession::Unlocked(_)))
}
#[gpui_kit::test]
fn test_welcome_success(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
fill(window, "confirm", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx), None);
assert!(is_unlocked(cx));
assert!(env.config.db_path().exists());
}
#[gpui_kit::test]
fn test_welcome_mismatch(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
fill(window, "confirm", "something else", cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx).as_deref(), Some("Passphrases do not match."));
assert!(!is_unlocked(cx));
assert!(!env.config.db_path().exists());
}
#[gpui_kit::test]
fn test_welcome_empty(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let window = open_app(&env, cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx).as_deref(), Some("Passphrase is empty."));
assert!(!is_unlocked(cx));
assert!(!env.config.db_path().exists());
}
#[gpui_kit::test]
fn test_unlock_success(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
env.db().unwrap(); // create the db, then close it again so the app starts out locked
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx), None);
assert!(is_unlocked(cx));
}
#[gpui_kit::test]
fn test_unlock_wrong_passphrase(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
env.db().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", "not the passphrase", cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx).as_deref(), Some("Incorrect passphrase."));
assert!(!is_unlocked(cx));
}
#[gpui_kit::test]
fn test_unlock_restores_private_config(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let mut saved = env.config.clone();
saved.rehide_ms = 5000;
env.db().unwrap().save_private_config(&saved.private_config()).unwrap();
let window = open_app(&env, cx);
// before unlocking, only the defaults are available
assert_eq!(cx.read(|cx| cx.global::<AppConfig>().rehide_ms), env.config.rehide_ms);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert!(is_unlocked(cx));
assert_eq!(cx.read(|cx| cx.global::<AppConfig>().rehide_ms), 5000);
}
#[gpui_kit::test]
fn test_lock(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
env.db().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert!(is_unlocked(cx));
click(window, "lock", cx);
assert!(cx.read(|cx| matches!(cx.global::<AppSession>(), AppSession::Locked)));
// The unlock screen should be a new one, not the old one with the passphrase still in it.
// The masked input doesn't expose its value, so check by submitting it as-is.
click(window, "submit", cx);
assert_eq!(error_message(window, cx).as_deref(), Some("Passphrase is empty."));
assert!(!is_unlocked(cx));
}
}
+63 -5
View File
@@ -1,13 +1,71 @@
use gpui_kit::{div, Render, Window, Context, IntoElement, Styled, ParentElement};
use gpui_kit::base::Button;
use gpui_kit::{
App, Context, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Render,
StatefulInteractiveElement, Styled, Window, div, rems,
};
use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon};
use crate::session::AppSession;
pub struct HomeScreen {}
impl Render for HomeScreen {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let t = cx.omarchy();
let lock = nav_tile("lock", IconName::ShieldCheck, "Lock", "Lock Creddy.", t.warning, cx)
.on_click(|_, _, cx| cx.set_global(AppSession::Locked));
let exit = nav_tile("exit", IconName::LogOut, "Exit", "Close Creddy.", t.accent, cx)
.on_click(|_, _, cx| cx.quit());
focus_scope("home")
.size_full()
.flex()
.justify_center()
.flex_col()
.items_center()
.child("Creddy is unlocked")
.p(rems(0.5))
.child(
div()
.text_size(rems(1.875))
.font_weight(FontWeight::BOLD)
.child("Creddy"),
)
.child(
// fill the rest of the window so the tiles sit in the middle of it
div()
.flex_1()
.flex()
.items_center()
.gap(rems(1.5))
.child(lock)
.child(exit),
)
}
}
/// A big square-ish button with an icon, a title, and a short description.
fn nav_tile(
id: &'static str,
icon_name: IconName,
title: &'static str,
description: &'static str,
color: Hsla,
cx: &App,
) -> Button {
let t = cx.omarchy();
Button::new(id)
.accessibility_label(title)
.flex_col()
.justify_start()
.gap(rems(1.))
.w(rems(14.))
.p(rems(1.))
.border_1()
.border_color(color)
.hover(|s| s.bg(t.hover_fill()))
.focus_visible(|s| s.bg(t.hover_fill()))
.active(|s| s.bg(t.pressed_fill()))
.child(icon(icon_name).size(rems(3.)).text_color(color))
.child(div().text_size(rems(1.125)).font_weight(FontWeight::BOLD).child(title))
.child(div().text_size(rems(0.875)).text_center().child(description))
}
+4 -4
View File
@@ -2,9 +2,9 @@ use gpui_kit::{
AppContext, BorrowAppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
Styled, Subscription, Task, Window, div, rems,
};
use gpui_omarchy::{ButtonVariant, Status, alert, button, focus_scope};
use gpui_omarchy::{ButtonVariant, button, focus_scope};
use crate::components::{PassphraseInput, PassphraseInputEvent};
use crate::components::{PassphraseInput, PassphraseInputEvent, error_alert};
use crate::config::AppConfig;
use crate::db::Db;
use crate::error::CreddyError;
@@ -24,7 +24,7 @@ impl UnlockScreen {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
// nothing else shares the show/hide flag, so it's private to this input
let show = cx.new(|_| false);
let passphrase = cx.new(|cx| PassphraseInput::new(show, window, cx));
let passphrase = cx.new(|cx| PassphraseInput::new("passphrase", show, window, cx));
passphrase.update(cx, |input, cx| input.focus(window, cx));
let submit = cx.subscribe_in(&passphrase, window, |this, _, event, window, cx| {
@@ -125,7 +125,7 @@ impl Render for UnlockScreen {
.font_weight(FontWeight::BOLD)
.child("Please enter your passphrase"),
)
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
.children(self.error.clone().map(|e| error_alert(e, cx)))
.child(self.passphrase.clone())
.child(
button("submit", "Submit", ButtonVariant::Primary, cx)
+5 -5
View File
@@ -2,9 +2,9 @@ use gpui_kit::{
AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
Styled, Subscription, Task,Window, div, rems,
};
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope};
use gpui_omarchy::{ActiveTheme, ButtonVariant, button, focus_scope};
use crate::components::{PassphraseInput, PassphraseInputEvent};
use crate::components::{PassphraseInput, PassphraseInputEvent, error_alert};
use crate::config::AppConfig;
use crate::db::Db;
use crate::session::AppSession;
@@ -26,8 +26,8 @@ pub struct WelcomeScreen {
impl WelcomeScreen {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let show = cx.new(|_| false);
let passphrase = cx.new(|cx| PassphraseInput::new(show.clone(), window, cx));
let confirm = cx.new(|cx| PassphraseInput::new(show, window, cx));
let passphrase = cx.new(|cx| PassphraseInput::new("passphrase", show.clone(), window, cx));
let confirm = cx.new(|cx| PassphraseInput::new("confirm", show, window, cx));
passphrase.update(cx, |input, cx| input.focus(window, cx));
let mut _subscriptions = Vec::new();
@@ -162,7 +162,7 @@ impl Render for WelcomeScreen {
.flex()
.flex_col()
.gap(rems(1.))
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
.children(self.error.clone().map(|e| error_alert(e, cx)))
.child(field("Passphrase", &self.passphrase))
.child(field("Re-enter passphrase", &self.confirm))
.child(
+19 -14
View File
@@ -18,10 +18,6 @@ impl AppSession {
AppSession::Empty
}
}
pub fn unlock(&mut self, passphrase: &str) -> Result<AppSession, CreddyError> {
todo!()
}
}
impl Global for AppSession {}
@@ -29,15 +25,24 @@ impl Global for AppSession {}
#[cfg(test)]
mod tests {
use super::*;
use std::assert_matches;
use testresult::TestResult;
use crate::test_data::TestEnv;
// #[test]
// fn test_new() {
// let passphrase = "correct horse battery staple";
// let salt = AppSession::salt().expect("salt generation failed.");
// let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
// match session {
// AppSession::Unlocked { .. } => (),
// _ => panic!("AppSession::new() should return an unlocked session"),
// }
// }
#[test]
fn test_load_empty() -> TestResult {
let env = TestEnv::new()?;
let session = AppSession::load(&env.config);
assert_matches!(session, AppSession::Empty);
Ok(())
}
#[test]
fn test_load_locked() -> TestResult {
let env = TestEnv::new()?;
let _ = env.db()?; // creates the database in the temp dir
let session = AppSession::load(&env.config);
assert_matches!(session, AppSession::Locked);
Ok(())
}
}
+25
View File
@@ -0,0 +1,25 @@
use tempfile::TempDir;
use crate::config::AppConfig;
use crate::db::Db;
use crate::error::CreddyError;
pub const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
pub struct TestEnv {
// we have to keep this around or the tempdir will be deleted as soon as it's dropped
_dir: TempDir,
pub config: AppConfig,
}
impl TestEnv {
pub fn new() -> Result<TestEnv, CreddyError> {
let dir = tempfile::tempdir()?;
let config = AppConfig::load_from(dir.path().to_path_buf())?;
Ok(TestEnv { _dir: dir, config })
}
pub fn db(&self) -> Result<Db, CreddyError> {
Db::connect(&self.config, TEST_PASSPHRASE)
}
}