use super::*;
use axum::{Json, Router, http::HeaderMap, routing::get};
use std::{fs, os::unix::fs::PermissionsExt, process::Command, sync::Arc};
use tokio::net::TcpListener;
#[tokio::test]
async fn device_cursor_survives_reconnect_and_skips_future_event_kinds() {
const TEST: &str =
"auth::notifications::tests::device_cursor_survives_reconnect_and_skips_future_event_kinds";
const FIXTURE: &str = "GENT_TEST_PRIVATE_NOTIFICATION_FIXTURE";
let Some(root) = std::env::var_os(FIXTURE) else {
let scratch = tempfile::tempdir().unwrap();
let sender = scratch.path().join("notify-send");
fs::write(&sender, "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$GENT_TEST_PRIVATE_NOTIFICATION_FIXTURE/banners\"\n").unwrap();
fs::set_permissions(sender, fs::Permissions::from_mode(0o700)).unwrap();
let result = Command::new(std::env::current_exe().unwrap())
.args(["--exact", TEST])
.env(FIXTURE, scratch.path())
.env("PATH", scratch.path())
.output()
.unwrap();
assert!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stdout)
);
return;
};
let root = Path::new(&root);
let home = root.join("node");
let icon = root.join("Gent Desktop icon.png");
fs::write(&icon, include_bytes!("../../../branding/inkling-512.png")).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/", listener.local_addr().unwrap());
let login = Saved {
version: 1,
phase: Phase::Active,
service: url,
token: credential("gent_s1").unwrap(),
session: Some(ServiceSession {
account_id: "fixture".into(),
github_subject: "1".into(),
github_login: "fixture".into(),
created_at: now().unwrap(),
expires_at: now().unwrap() + 7200,
}),
};
let session = source::directory(&home).unwrap().join("session.json");
save(&session, Some(&login)).unwrap();
let token = Arc::new(format!("Bearer {}", login.token));
let app = Router::new().route("/v1/notifications",get(move |headers:HeaderMap| {
let token = token.clone();
async move {
assert_eq!(headers["authorization"].to_str().unwrap(), token.as_str());
let rows = match headers["x-gent-after"].to_str().unwrap() {
"0" => json!([{"sequence":1,"notice":{"event":{"kind":"future_event"}}},
{"sequence":2,"notice":{"event":{"kind":"goal_resumed","reason":"future_reason"}}},
{"sequence":3,"notice":{"id":uuid::Uuid::new_v4(),"created_at":now().unwrap(),
"event":{"kind":"update_installed","node":uuid::Uuid::new_v4(),"commit":"a".repeat(40)}}},
{"sequence":4,"notice":{"id":uuid::Uuid::new_v4(),"created_at":now().unwrap(),
"event":{"kind":"goal_resumed","node":uuid::Uuid::new_v4(),"chat":uuid::Uuid::new_v4(),"reason":"request_payload"}}}]),
"4" => json!([]),
cursor => panic!("unexpected cursor {cursor}"),
};
Json(rows)
}
}));
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
collect(&home, &login, &icon).await.unwrap();
collect(&home, &login, &icon).await.unwrap();
let (cursor, _) = cursor_paths(&home, &login).unwrap();
assert_eq!(fs::read_to_string(&cursor).unwrap(), "4");
let banners = root.join("banners");
let first = fs::read_to_string(&banners).unwrap();
let args: Vec<_> = first.lines().collect();
let (banners_sent, remainder) = args.as_chunks::<7>();
assert!(remainder.is_empty());
assert_eq!(banners_sent.len(), 2);
let hint = format!(
"--hint=string:desktop-entry:{}",
crate::desktop::desktop_entry_id(&home)
);
for (banner, title) in banners_sent
.iter()
.zip(["Gent updated", "Gent Babysitter resumed a goal"])
{
assert_eq!(
banner[..6],
[
"--app-name=Gent",
hint.as_str(),
"--icon",
icon.to_str().unwrap(),
"--",
title
]
);
}
assert!(args[6].ends_with(" updated to aaaaaaaaaaaa."));
save(&session, None).unwrap();
fs::remove_file(&cursor).unwrap();
collect(&home, &login, &icon).await.unwrap();
assert!(!cursor.exists());
assert_eq!(fs::read_to_string(banners).unwrap(), first);
server.abort();
}
#[test]
fn both_hosted_logins_resume_from_the_furthest_existing_cursor() -> Result<()> {
let scratch = tempfile::tempdir()?;
let home = scratch.path().join("node");
gent_daemon::config::initialize(&home, "notifications")?;
let mut login = Saved {
version: 1,
phase: Phase::Active,
service: ACCOUNT.beta.into(),
token: candidate()?,
session: Some(ServiceSession {
account_id: uuid::Uuid::new_v4().to_string(),
github_subject: "1".into(),
github_login: "fixture".into(),
created_at: now()?,
expires_at: now()? + 7200,
}),
};
let (stable, legacy) = cursor_paths(&home, &login)?;
let beta = legacy.context("missing beta cursor")?;
Snapshot::read(&beta)?.write("23")?;
Snapshot::read(&stable)?.write("12")?;
login.service = DEFAULT_SERVICE.into();
assert_eq!(
cursor_paths(&home, &login)?,
(stable.clone(), Some(beta.clone()))
);
assert_eq!(cursor_position(&stable, Some(&beta))?, 23);
Snapshot::read(&stable)?.write("29")?;
assert_eq!(cursor_position(&stable, Some(&beta))?, 29);
login.service = STAGING_SERVICE.into();
let (staging, legacy) = cursor_paths(&home, &login)?;
assert!(legacy.is_none());
assert_eq!(cursor_position(&staging, None)?, 0);
Ok(())
}