Merge origin/main (2145: push gate, T1a repair, batched matcher) into dawn/f1-write-batching

Brings in migrations 0023/0024. Batch-txn interaction reviewed: the batch
holds 0023 push-gate shared locks (per community, insert-time) and 0024
channel-TTL shared locks (per channel, deferred at COMMIT) for all events
in the lane until batch commit. Shared-shared admits concurrent lanes and
direct inserts; no path takes two exclusive advisory locks, so no deadlock
ordering is introduced by multi-key batches. Savepoint rollback of a
poisoned event does not release its already-acquired shared push-gate lock
(held to txn end) - correctness-neutral, slightly extends the window an
exclusive lease activation may wait.

Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com>
Signed-off-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com>
This commit is contained in:
tlongwell-block
2026-07-19 21:45:41 -04:00
co-authored by Dawn
27 changed files with 2470 additions and 523 deletions
+23 -2
View File
@@ -255,7 +255,12 @@ async fn init_session(h: &mut Harness, mcp_servers: Value) -> String {
.await;
r["result"]["sessionId"]
.as_str()
.expect("sessionId")
.unwrap_or_else(|| {
panic!(
"session/new did not return sessionId: response={r}, stderr={}",
h.stderr_text()
)
})
.to_owned()
}
@@ -1570,7 +1575,23 @@ async fn cancel_kills_inflight_tool_via_mcp_notification() {
// the buzz-agent test binary (they share the same target dir).
let self_bin = std::path::PathBuf::from(env!("CARGO_BIN_EXE_buzz-agent"));
let dev_mcp_bin = self_bin.parent().unwrap().join("buzz-dev-mcp");
if !dev_mcp_bin.exists() {
let dev_mcp_is_executable = std::fs::metadata(&dev_mcp_bin)
.map(|metadata| {
if !metadata.is_file() || metadata.len() == 0 {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
metadata.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
{
true
}
})
.unwrap_or(false);
if !dev_mcp_is_executable {
eprintln!(
"SKIP: buzz-dev-mcp not built at {}; run `cargo build -p buzz-dev-mcp` first",
dev_mcp_bin.display()
+53 -3
View File
@@ -538,6 +538,33 @@ pub async fn is_member(
Ok(cnt > 0)
}
/// Return which of the given (channel, pubkey) combinations are active
/// memberships, restricted to non-deleted channels — one statement for any
/// batch size (T2b). Semantics per pair match [`is_member`].
pub async fn membership_pairs(
pool: &PgPool,
community_id: CommunityId,
channel_ids: &[Uuid],
pubkeys: &[Vec<u8>],
) -> Result<Vec<(Uuid, Vec<u8>)>> {
if channel_ids.is_empty() || pubkeys.is_empty() {
return Ok(Vec::new());
}
let rows = sqlx::query(
"SELECT cm.channel_id, cm.pubkey FROM channel_members cm \
JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \
WHERE cm.community_id = $1 AND cm.channel_id = ANY($2) AND cm.pubkey = ANY($3) AND cm.removed_at IS NULL",
)
.bind(community_id.as_uuid())
.bind(channel_ids)
.bind(pubkeys)
.fetch_all(pool)
.await?;
rows.into_iter()
.map(|row| Ok((row.try_get("channel_id")?, row.try_get("pubkey")?)))
.collect()
}
/// Returns all active members of the given channel.
///
/// Returns an empty list if the channel has been soft-deleted.
@@ -1076,9 +1103,32 @@ pub async fn update_channel(
q = q.bind(community_id.as_uuid());
q = q.bind(channel_id);
let result = q.execute(pool).await?;
if result.rows_affected() == 0 {
return Err(DbError::ChannelNotFound(channel_id));
// T1a repair: a TTL change can flip this channel's event-trigger fast
// path (migration 0024 reads ttl_seconds under a SHARED per-channel
// advisory lock). Take the same key EXCLUSIVE before the UPDATE so a
// concurrent event either sees the committed TTL or strictly precedes
// this transition — whose own deadline reset is then the latest word.
// Non-TTL updates don't touch the fast path and skip the lock.
if updates.ttl_seconds.is_some() {
let mut tx = pool.begin().await?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind(format!(
"buzz_channel_ttl:{}:{}",
community_id.as_uuid(),
channel_id
))
.execute(&mut *tx)
.await?;
let result = q.execute(&mut *tx).await?;
if result.rows_affected() == 0 {
return Err(DbError::ChannelNotFound(channel_id));
}
tx.commit().await?;
} else {
let result = q.execute(pool).await?;
if result.rows_affected() == 0 {
return Err(DbError::ChannelNotFound(channel_id));
}
}
get_channel(pool, community_id, channel_id).await
+101
View File
@@ -1561,6 +1561,14 @@ mod tests {
assert_eq!(stale_ttl, None);
let mut activation = pool.begin().await.expect("begin TTL activation");
// Model the repaired update_channel protocol (migration 0024): the
// TTL transition holds the per-channel advisory key EXCLUSIVE, which
// is what the event trigger's shared acquisition now waits on.
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind(format!("buzz_channel_ttl:{community_uuid}:{racing}"))
.execute(&mut *activation)
.await
.expect("acquire exclusive channel TTL key");
let activation_deadline: DateTime<Utc> = sqlx::query_scalar(
"UPDATE channels \
SET ttl_seconds = 60, ttl_deadline = clock_timestamp() + interval '60 seconds' \
@@ -1605,6 +1613,99 @@ mod tests {
);
}
/// T1a repair regression test (migration 0024): permanent-channel event
/// commits must not serialize on the channel row. The 0022 trigger took
/// `FOR UPDATE` on the channel tuple before testing `ttl_seconds`, so
/// concurrent commits into one hot permanent channel queued at commit
/// time (deferred trigger) — invisible to any single-connection test.
/// This holds N insert transactions at a barrier past their INSERTs,
/// then proves (a) while all N sit pre-commit, no transaction holds a
/// row-level lock on the channel tuple, and (b) all N commits succeed
/// with the channel row untouched (permanent ⇒ no deadline write).
#[tokio::test]
#[ignore = "requires Postgres"]
async fn permanent_channel_event_commits_do_not_lock_the_channel_row() {
const N: usize = 8;
// setup_pool's default cap (10) covers N held transactions plus the
// pg_locks inspector connection.
let pool = setup_pool().await;
let community_uuid = make_test_community(&pool).await;
let channel = make_test_channel(&pool, community_uuid, None).await;
// Open N transactions, run the full event INSERT in each (the deferred
// trigger fires at COMMIT), and park them at a barrier.
let mut txs = Vec::new();
for i in 0..N {
let mut tx = pool.begin().await.expect("begin insert txn");
let event = make_text_event(&format!("hot channel event {i}"));
sqlx::query(
"INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,received_at,channel_id) \
VALUES ($1,$2,$3,$4,9,$5,$6,$7,now(),$8)",
)
.bind(community_uuid)
.bind(event.id.as_bytes().as_slice())
.bind(event.pubkey.as_bytes().as_slice())
.bind(DateTime::from_timestamp(event.created_at.as_secs() as i64, 0).unwrap())
.bind(serde_json::to_value(&event.tags).unwrap())
.bind(&event.content)
.bind(event.sig.serialize().as_slice())
.bind(channel)
.execute(&mut *tx)
.await
.expect("insert event inside held txn");
txs.push(tx);
}
// With all N transactions holding completed INSERTs, none may hold a
// row-level lock on the channels tuple. (The 0022 trigger would not
// have taken it yet either — it locks at COMMIT — so also verify the
// commit phase below completes without mutual blocking.)
let tuple_locks: i64 = sqlx::query_scalar(
"SELECT count(*) FROM pg_locks l \
JOIN pg_class c ON c.oid = l.relation \
WHERE c.relname = 'channels' AND l.locktype = 'tuple'",
)
.fetch_one(&pool)
.await
.expect("inspect pg_locks");
assert_eq!(tuple_locks, 0, "no channel tuple locks while txns are held");
// Release all commits concurrently. Under 0022 these serialized on the
// channel row (each holding it across its WAL flush); under 0024 the
// shared advisory key admits them all. Join with a timeout so a
// regression fails fast instead of hanging the suite.
let commits = txs
.into_iter()
.map(|tx| tokio::spawn(async move { tx.commit().await }))
.collect::<Vec<_>>();
for c in commits {
tokio::time::timeout(std::time::Duration::from_secs(10), c)
.await
.expect("concurrent permanent-channel commits must not block")
.expect("join commit task")
.expect("commit succeeds");
}
let deadline: Option<DateTime<Utc>> = sqlx::query_scalar(
"SELECT ttl_deadline FROM channels WHERE community_id = $1 AND id = $2",
)
.bind(community_uuid)
.bind(channel)
.fetch_one(&pool)
.await
.expect("read deadline after commits");
assert_eq!(deadline, None, "permanent channel must remain untouched");
let stored: i64 = sqlx::query_scalar(
"SELECT count(*) FROM events WHERE community_id = $1 AND channel_id = $2",
)
.bind(community_uuid)
.bind(channel)
.fetch_one(&pool)
.await
.expect("count stored events");
assert_eq!(stored as usize, N);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn get_event_by_id_is_scoped_when_event_id_collides_across_communities() {
+48 -13
View File
@@ -1222,12 +1222,13 @@ impl Db {
event::get_events_by_ids(&self.pool, community_id, ids).await
}
/// Exclusively claim the next due event-to-push matcher job.
pub async fn claim_due_push_match(
/// Exclusively claim a batch of due matcher jobs from one community.
pub async fn claim_due_push_match_batch(
&self,
limit: i64,
lease_until: DateTime<Utc>,
) -> Result<Option<push::ClaimedMatch>> {
push::claim_due_match(&self.pool, lease_until).await
) -> Result<Option<push::ClaimedMatchBatch>> {
push::claim_due_match_batch(&self.pool, limit, lease_until).await
}
/// Load active endpoint-enabled leases eligible for push matching.
@@ -1238,18 +1239,30 @@ impl Db {
push::active_match_leases(&self.pool, community).await
}
/// Complete a matcher job if its claim fence is still held.
pub async fn complete_push_match(&self, job: &push::ClaimedMatch) -> Result<bool> {
push::complete_match(&self.pool, job).await
/// Complete matcher jobs from one claimed batch while the fence holds.
pub async fn complete_push_match_batch(
&self,
community: CommunityId,
claim_id: uuid::Uuid,
event_ids: &[Vec<u8>],
) -> Result<u64> {
push::complete_match_batch(&self.pool, community, claim_id, event_ids).await
}
/// Release a matcher claim for retry at the supplied time.
pub async fn retry_push_match(
/// Release fenced matcher claims from one batch for retry.
pub async fn retry_push_match_batch(
&self,
job: &push::ClaimedMatch,
community: CommunityId,
claim_id: uuid::Uuid,
event_ids: &[Vec<u8>],
next: DateTime<Utc>,
) -> Result<bool> {
push::retry_match(&self.pool, job, next).await
) -> Result<u64> {
push::retry_match_batch(&self.pool, community, claim_id, event_ids, next).await
}
/// Delete exhausted matcher jobs (periodic sweep, off the claim path).
pub async fn reap_exhausted_push_matches(&self) -> Result<u64> {
push::reap_exhausted_matches(&self.pool).await
}
/// Idempotently enqueue a wake for a matched lease and event.
@@ -1263,6 +1276,15 @@ impl Db {
push::enqueue_wake(&self.pool, community, author, installation_id, wake).await
}
/// Set-wise [`Self::enqueue_push_wake`]: one transaction per batch.
pub async fn enqueue_push_wakes(
&self,
community: CommunityId,
requests: &[push::WakeRequest],
) -> Result<Vec<push::EnqueueWakeOutcome>> {
push::enqueue_wakes(&self.pool, community, requests).await
}
/// Exclusively claim due wake jobs for one community.
pub async fn claim_due_push_wakes(
&self,
@@ -1536,6 +1558,17 @@ impl Db {
channel::is_member(&self.pool, community_id, channel_id, pubkey).await
}
/// Return the active (channel, pubkey) membership pairs among the given
/// sets, in one statement.
pub async fn membership_pairs(
&self,
community_id: CommunityId,
channel_ids: &[Uuid],
pubkeys: &[Vec<u8>],
) -> Result<Vec<(Uuid, Vec<u8>)>> {
channel::membership_pairs(&self.pool, community_id, channel_ids, pubkeys).await
}
/// Returns all active members of a channel.
pub async fn get_members(
&self,
@@ -4620,9 +4653,11 @@ mod tests {
#[tokio::test]
#[ignore = "requires Postgres"]
async fn test_usage_metrics_lock_has_single_owner_and_releases_on_drop() {
let database_url =
std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.into());
let pool = PgPoolOptions::new()
.max_connections(2)
.connect(TEST_DB_URL)
.connect(&database_url)
.await
.expect("connect to test DB");
let first = Db::from_pool(pool.clone());
+29 -2
View File
@@ -560,7 +560,7 @@ mod tests {
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
migrations.sort_by_key(|migration| migration.version);
assert_eq!(migrations.len(), 22);
assert_eq!(migrations.len(), 24);
assert_eq!(migrations[0].version, 1);
assert_eq!(&*migrations[0].description, "initial schema");
assert!(migrations[0]
@@ -852,6 +852,33 @@ mod tests {
assert!(ttl_refresh.contains("DEFERRABLE INITIALLY DEFERRED"));
assert!(ttl_refresh.contains("clock_timestamp()"));
assert!(ttl_refresh.contains("NEW.kind <> 9007"));
// T1b push gate: the match-queue trigger only enqueues when the
// community has an eligible lease, ordered against lease activations
// through the shared/exclusive per-community advisory lock.
assert_eq!(migrations[22].version, 23);
let push_gate = migrations[22].sql.as_str();
assert!(push_gate.contains("CREATE OR REPLACE FUNCTION enqueue_push_match_job"));
assert!(push_gate.contains("pg_advisory_xact_lock_shared"));
assert!(push_gate.contains("'buzz_push_gate:' || NEW.community_id::text"));
assert!(push_gate.contains("endpoint_enabled"));
// T1a repair: the TTL refresh trigger synchronizes on a shared
// per-channel advisory lock instead of FOR UPDATE on the channel row,
// so permanent-channel commits no longer serialize.
assert_eq!(migrations[23].version, 24);
let ttl_shared = migrations[23].sql.as_str();
assert!(ttl_shared
.contains("CREATE OR REPLACE FUNCTION refresh_channel_ttl_after_event_insert"));
assert!(ttl_shared.contains("pg_advisory_xact_lock_shared"));
assert!(ttl_shared.contains("'buzz_channel_ttl:' || NEW.community_id::text"));
// The row read must be a bare SELECT (comments describe the removed
// FOR UPDATE; the executable body must not reintroduce it).
assert!(ttl_shared.contains("SELECT ttl_seconds INTO channel_ttl"));
assert!(!strip_sql_comments(ttl_shared)
.to_lowercase()
.contains("for update"));
assert!(ttl_shared.contains("NEW.kind <> 9007"));
}
#[test]
@@ -1094,7 +1121,7 @@ mod tests {
run_migrations(&pool)
.await
.expect("retry succeeds after operator repair");
assert_eq!(applied_versions(&pool).await.last().copied(), Some(22));
assert_eq!(applied_versions(&pool).await.last().copied(), Some(24));
}
#[tokio::test]
+826 -137
View File
File diff suppressed because it is too large Load Diff
+194 -43
View File
@@ -15,6 +15,18 @@ use crate::{handlers::push_lease::Subscription, state::AppState};
const CLAIM_SECS: i64 = 30;
const EVENT_USEFUL_SECS: i64 = 3600;
const MAX_ATTEMPTS: i32 = 8;
/// Upper bound on one claimed matcher batch. Bounded well under
/// `get_events_by_ids`' 500-id batch-fetch contract.
const MATCH_BATCH_LIMIT: i64 = 64;
/// Idle poll floor and ceiling. An idle matcher previously issued a claim
/// transaction every 250ms forever; backing off to the ceiling folds that
/// steady-state cost while keeping first-message latency at the floor.
const IDLE_POLL_FLOOR: Duration = Duration::from_millis(250);
const IDLE_POLL_CEILING: Duration = Duration::from_secs(2);
/// Cadence of the poison-job sweep, which lives off the claim path: its scan
/// is not served by the due partial index, so running it inside every claim
/// made claims slower exactly when a backlog needed them fastest.
const REAP_INTERVAL: Duration = Duration::from_secs(30);
#[derive(Serialize)]
struct DeliveryRequest<'a> {
@@ -37,29 +49,37 @@ enum DeliveryResponse {
},
}
/// Continuously claim accepted events and match them against active leases.
/// Continuously claim accepted events in per-community batches and match
/// them against active leases (T2b). One batch costs one claim statement,
/// one event load, one lease scan, one membership scan, and one wake-enqueue
/// transaction — plus one complete/retry statement each — regardless of
/// batch size or how many (event, lease) pairs match.
pub async fn run_matcher(state: Arc<AppState>) {
let mut idle_delay = IDLE_POLL_FLOOR;
let mut last_reap = tokio::time::Instant::now();
loop {
if last_reap.elapsed() >= REAP_INTERVAL {
match state.db.reap_exhausted_push_matches().await {
Ok(reaped) if reaped > 0 => warn!(reaped, "reaped exhausted push match jobs"),
Ok(_) => {}
Err(e) => error!("push match reap failed: {e}"),
}
last_reap = tokio::time::Instant::now();
}
let until = Utc::now() + TimeDelta::seconds(CLAIM_SECS);
match state.db.claim_due_push_match(until).await {
Ok(Some(job)) => {
if let Err(e) = process_match(&state, &job).await {
warn!(event_id=%job.event.event.id, attempt=job.attempt, "push match failed: {e}");
if job.attempt >= buzz_db::push::MAX_MATCH_ATTEMPTS {
// A poison event/lease must not retry forever or pin
// delivered outbox retention through the rematch guard.
let _ = state.db.complete_push_match(&job).await;
} else {
let _ = state
.db
.retry_push_match(&job, Utc::now() + TimeDelta::seconds(2))
.await;
}
} else if let Err(e) = state.db.complete_push_match(&job).await {
warn!(event_id=%job.event.event.id, "push match completion failed: {e}");
}
match state
.db
.claim_due_push_match_batch(MATCH_BATCH_LIMIT, until)
.await
{
Ok(Some(batch)) => {
idle_delay = IDLE_POLL_FLOOR;
process_match_batch(&state, batch).await;
}
Ok(None) => {
tokio::time::sleep(idle_delay).await;
idle_delay = (idle_delay * 2).min(IDLE_POLL_CEILING);
}
Ok(None) => tokio::time::sleep(Duration::from_millis(250)).await,
Err(e) => {
error!("push matcher claim failed: {e}");
tokio::time::sleep(Duration::from_secs(2)).await;
@@ -68,18 +88,149 @@ pub async fn run_matcher(state: Arc<AppState>) {
}
}
async fn process_match(state: &AppState, job: &buzz_db::push::ClaimedMatch) -> anyhow::Result<()> {
let leases = state.db.active_push_match_leases(job.community).await?;
for lease in leases {
/// Per-batch state shared by every job: the community's active leases and
/// the exact (channel, lease author) membership pairs the jobs can consult.
struct MatchContext {
leases: Vec<buzz_db::push::MatchLease>,
memberships: std::collections::HashSet<(uuid::Uuid, Vec<u8>)>,
}
async fn load_match_context(
state: &AppState,
batch: &buzz_db::push::ClaimedMatchBatch,
) -> anyhow::Result<MatchContext> {
let leases = state.db.active_push_match_leases(batch.community).await?;
let mut channels: Vec<uuid::Uuid> = batch
.jobs
.iter()
.filter_map(|job| job.event.channel_id)
.collect();
channels.sort_unstable();
channels.dedup();
let mut authors: Vec<Vec<u8>> = leases.iter().map(|lease| lease.author.clone()).collect();
authors.sort_unstable();
authors.dedup();
let memberships = state
.db
.membership_pairs(batch.community, &channels, &authors)
.await?
.into_iter()
.collect();
Ok(MatchContext {
leases,
memberships,
})
}
async fn process_match_batch(state: &AppState, batch: buzz_db::push::ClaimedMatchBatch) {
let community = batch.community;
let context = match load_match_context(state, &batch).await {
Ok(context) => context,
Err(e) => {
// Shared context failed to load, so no job was evaluated: release
// the whole batch for retry. Jobs that keep failing are reaped by
// the periodic sweep once their attempts are exhausted.
warn!(%community, "push match context load failed: {e}");
let ids: Vec<Vec<u8>> = batch
.jobs
.iter()
.map(|job| job.event.event.id.as_bytes().to_vec())
.collect();
if let Err(e) = state
.db
.retry_push_match_batch(
community,
batch.claim_id,
&ids,
Utc::now() + TimeDelta::seconds(2),
)
.await
{
warn!(%community, "push match batch retry failed: {e}");
}
return;
}
};
let mut completed = Vec::new();
let mut retry = Vec::new();
// Jobs whose wakes are pending the set-wise enqueue below: their
// completion is decided by the flush, not by match evaluation.
let mut pending = Vec::new();
let mut wakes: Vec<buzz_db::push::WakeRequest> = Vec::new();
for job in &batch.jobs {
let event_id = job.event.event.id.as_bytes().to_vec();
match match_job(job, &context) {
Ok(job_wakes) if job_wakes.is_empty() => completed.push(event_id),
Ok(job_wakes) => {
pending.push((event_id, job.attempt));
wakes.extend(job_wakes);
}
Err(e) => {
warn!(event_id=%job.event.event.id, attempt=job.attempt, "push match failed: {e}");
if job.attempt >= buzz_db::push::MAX_MATCH_ATTEMPTS {
// A poison event/lease must not retry forever or pin
// delivered outbox retention through the rematch guard.
completed.push(event_id);
} else {
retry.push(event_id);
}
}
}
}
// One transaction for every wake in the batch (T2b). InactiveLease and
// Duplicate outcomes are per-request non-errors; only a failed enqueue
// transaction sends the contributing jobs back for an idempotent rematch
// (the outbox dedup key absorbs any wakes that did commit elsewhere).
match state.db.enqueue_push_wakes(community, &wakes).await {
Ok(_) => completed.extend(pending.into_iter().map(|(event_id, _)| event_id)),
Err(e) => {
warn!(%community, "push wake batch enqueue failed: {e}");
for (event_id, attempt) in pending {
if attempt >= buzz_db::push::MAX_MATCH_ATTEMPTS {
completed.push(event_id);
} else {
retry.push(event_id);
}
}
}
}
if let Err(e) = state
.db
.complete_push_match_batch(community, batch.claim_id, &completed)
.await
{
warn!(%community, "push match batch completion failed: {e}");
}
if let Err(e) = state
.db
.retry_push_match_batch(
community,
batch.claim_id,
&retry,
Utc::now() + TimeDelta::seconds(2),
)
.await
{
warn!(%community, "push match batch retry failed: {e}");
}
}
/// Pure match evaluation: no DB access. Returns the wake requests this job
/// owes, which the caller flushes set-wise for the whole batch.
fn match_job(
job: &buzz_db::push::BatchedMatch,
context: &MatchContext,
) -> anyhow::Result<Vec<buzz_db::push::WakeRequest>> {
let mut wakes = Vec::new();
for lease in &context.leases {
let author_hex = hex::encode(&lease.author);
if !reader_authorized_for_event(&job.event.event, &author_hex) {
continue;
}
if let Some(channel) = job.event.channel_id {
if !state
.db
.is_member(job.community, channel, &lease.author)
.await?
if !context
.memberships
.contains(&(channel, lease.author.clone()))
{
continue;
}
@@ -123,22 +274,16 @@ async fn process_match(state: &AppState, job: &buzz_db::push::ClaimedMatch) -> a
if expires_at <= Utc::now().timestamp() {
continue;
}
let _ = state
.db
.enqueue_push_wake(
job.community,
&lease.author,
&lease.installation_id,
buzz_db::push::NewWake {
lease_generation: lease.generation,
event_id: job.event.event.id.as_bytes(),
class,
expires_at,
},
)
.await?;
wakes.push(buzz_db::push::WakeRequest {
author: lease.author.clone(),
installation_id: lease.installation_id.clone(),
lease_generation: lease.generation,
event_id: job.event.event.id.as_bytes().to_vec(),
class: class.to_string(),
expires_at,
});
}
Ok(())
Ok(wakes)
}
/// Match-time counterpart of REQ's filter-level `#p` authorization gate.
@@ -169,6 +314,7 @@ pub async fn run_delivery_worker(state: Arc<AppState>) {
.timeout(state.config.push_gateway_timeout)
.build()
.expect("push HTTP client");
let mut idle_delay = Duration::from_millis(500);
loop {
let mut found = false;
match state.db.usage_community_hosts().await {
@@ -189,8 +335,13 @@ pub async fn run_delivery_worker(state: Arc<AppState>) {
}
Err(e) => error!("push worker community scan failed: {e}"),
}
if !found {
tokio::time::sleep(Duration::from_millis(500)).await;
if found {
idle_delay = Duration::from_millis(500);
} else {
// Empty sweeps back off so an idle worker stops paying a full
// per-community claim scan every 500ms forever.
tokio::time::sleep(idle_delay).await;
idle_delay = (idle_delay * 2).min(IDLE_POLL_CEILING);
}
}
}
@@ -61,6 +61,50 @@ const BAKED_STRUCTURED_KEYS = new Set([
BUZZ_AGENT_THINKING_EFFORT,
]);
// Canonical behaviors (PR 2 flag cleanup). These were per-surface props;
// onboarding's values won every call and are now the only behavior:
// - auto-select a valid model when the provider changes
// - keep the model select usable during discovery
// - preserve credential env vars across provider switches (the abandoned
// provider's key stays in env_vars — visible/deletable under Advanced —
// so flipping back never loses a typed key; spawned agents may therefore
// see credentials for providers they don't use)
// - require a provider before model/effort are editable (no saveable
// invalid state — design principle #4). Note: legacy configs saved with
// a model but no provider are cleared by the pre-existing orphan-model
// effect on next edit — deliberate data healing, documented in PR.
const autoSelectModelOnProviderChange = true;
const disableModelSelectDuringDiscovery = false;
const preserveCredentialEnvVarsOnProviderChange = true;
const requireProviderForModelAndEffort = true;
/** The canonical behavior contract, exported for the contract test. */
export const CANONICAL_CONFIG_BEHAVIORS = {
autoSelectModelOnProviderChange,
disableModelSelectDuringDiscovery,
preserveCredentialEnvVarsOnProviderChange,
requireProviderForModelAndEffort,
} as const;
/**
* Disclosure preset → the eight visibility decisions it owns. Effort is
* shown in both presets (onboarding never hid it; the old prop existed but
* was never flipped). Exported for the contract test.
*/
export function resolveDisclosure(disclosure: "full" | "onboarding-essential") {
const full = disclosure === "full";
return {
showAdvancedFields: full,
showCustomModelOption: full,
showCustomProviderOption: full,
showDescriptions: full,
showEffortField: true,
showProviderPlaceholderOption: full,
showRequiredIndicators: full,
showUnavailableEffortOptions: full,
} as const;
}
export type AgentConfigFieldsProps = {
bakedEnv: BakedEnvEntry[];
selectedRuntime: AcpRuntimeCatalogEntry | undefined;
@@ -71,26 +115,29 @@ export type AgentConfigFieldsProps = {
onCustomModelEditingChange: (value: boolean) => void;
onIsCustomProviderChange: (value: boolean) => void;
onValidityChange?: (valid: boolean) => void;
autoSelectModelOnProviderChange?: boolean;
disableModelSelectDuringDiscovery?: boolean;
effortPlaceholderLabel?: string;
effortLabel?: string;
keepSelectedModelValueLabel?: boolean;
modelPlaceholderLabel?: string;
placeholderClassName?: string;
providerLabel?: string;
preserveCredentialEnvVarsOnProviderChange?: boolean;
requireProviderForModelAndEffort?: boolean;
selectClassName?: string;
/**
* Which disclosure preset to render (PR 2 flag cleanup — replaces eight
* independent show* booleans):
* - "full" (default): the evergreen stance — every field, escape hatch
* (custom model/provider), description, required indicator, and
* unavailable option is visible. Settings, defaults modal, dialogs.
* - "onboarding-essential": onboarding page 4's first-run stance — only
* valid forward choices. No advanced section, no custom escape hatches,
* no descriptions (the page copy does that job), no un-choosing via
* placeholder options, no greyed-out effort levels.
* If a second surface wants the trimmed view, rename this value to plain
* "essential" — and have the conversation about whether it should really
* match onboarding.
*/
disclosure?: "full" | "onboarding-essential";
/**
* Harness-conditional, not part of the disclosure preset: provider choice
* only exists for runtimes that support LLM provider selection. PR 3
* derives this internally from selectedRuntime and deletes the prop.
*/
showProviderField?: boolean;
showAdvancedFields?: boolean;
showCustomModelOption?: boolean;
showCustomProviderOption?: boolean;
showDescriptions?: boolean;
showEffortField?: boolean;
showProviderPlaceholderOption?: boolean;
showRequiredIndicators?: boolean;
showUnavailableEffortOptions?: boolean;
unstyled?: boolean;
useCustomSelect?: boolean;
useChevronSelectIcon?: boolean;
@@ -106,30 +153,25 @@ export function AgentConfigFields({
onCustomModelEditingChange,
onIsCustomProviderChange,
onValidityChange,
autoSelectModelOnProviderChange = false,
disableModelSelectDuringDiscovery = true,
effortPlaceholderLabel,
effortLabel = "Thinking/effort",
keepSelectedModelValueLabel = false,
modelPlaceholderLabel = "Select model",
placeholderClassName,
providerLabel = "LLM provider",
preserveCredentialEnvVarsOnProviderChange = false,
requireProviderForModelAndEffort = false,
selectClassName,
disclosure = "full",
showProviderField = true,
showAdvancedFields = true,
showCustomModelOption = true,
showCustomProviderOption = true,
showDescriptions = true,
showEffortField = true,
showProviderPlaceholderOption = true,
showRequiredIndicators = true,
showUnavailableEffortOptions = true,
unstyled = false,
useCustomSelect = false,
useChevronSelectIcon = false,
}: AgentConfigFieldsProps) {
const {
showAdvancedFields,
showCustomModelOption,
showCustomProviderOption,
showDescriptions,
showEffortField,
showProviderPlaceholderOption,
showRequiredIndicators,
showUnavailableEffortOptions,
} = resolveDisclosure(disclosure);
const bakedProvider = React.useMemo(
() => bakedEnv.find((e) => e.key === "BUZZ_AGENT_PROVIDER")?.value ?? null,
[bakedEnv],
@@ -206,9 +248,24 @@ export function AgentConfigFields({
selectedRuntime,
});
// Mount-time healing policy: onboarding page 4 edits the root config during
// first-run (no higher layers to inherit from), so acting on open is safe
// and intentional there — it heals stale state and picks a valid model.
// Evergreen surfaces (Settings, dialogs) edit saved data that may pair with
// higher layers (see PR #2148 review thread), so they only act after the
// user explicitly edits the provider in this session.
const healOnMount = disclosure === "onboarding-essential";
const userEditedProviderRef = React.useRef(false);
// Read inside effects via ref so biome's exhaustive-deps stays honest:
// refs are stable, and healOnMount is captured at declaration.
const mayMutateDependentFieldsRef = React.useRef(false);
mayMutateDependentFieldsRef.current =
healOnMount || userEditedProviderRef.current;
const autoSelectedModelScopeRef = React.useRef<string | null>(null);
React.useEffect(() => {
if (!autoSelectModelOnProviderChange) return;
if (!mayMutateDependentFieldsRef.current) return;
const trimmedProvider = providerForDiscovery.trim();
if (trimmedProvider.length === 0 || isCustomProvider) {
autoSelectedModelScopeRef.current = null;
@@ -228,7 +285,6 @@ export function AgentConfigFields({
onCustomModelEditingChange(false);
onConfigChange({ ...config, model: firstModel.id });
}, [
autoSelectModelOnProviderChange,
config,
discoveredModelOptions,
isCustomProvider,
@@ -241,7 +297,16 @@ export function AgentConfigFields({
const currentEffortForAutoClear =
config.env_vars[BUZZ_AGENT_THINKING_EFFORT] ?? "";
// Orphan-model clearing follows the mount-time healing policy above: the
// backend resolves provider and model independently across layers
// (agent → definition → global), so a saved global model WITHOUT a global
// provider can be a deliberate, working pattern (provider supplied by a
// higher layer). Clearing it on page-open in evergreen surfaces silently
// breaks that agent on its next restart — see PR #2148 review thread.
// Onboarding heals on open by design (discriminating spec: "gates stale
// saved model and effort until provider selection").
React.useEffect(() => {
if (!mayMutateDependentFieldsRef.current) return;
if (!dependentFieldsDisabled) return;
if (
(config.model ?? "").trim().length === 0 &&
@@ -276,6 +341,7 @@ export function AgentConfigFields({
});
function handleProviderChange(value: string) {
userEditedProviderRef.current = true;
const previousApiKey = getProviderApiKeyEnvVar(effectiveProvider);
if (value === CUSTOM_PROVIDER_DROPDOWN_VALUE) {
const nextEnvVars = { ...config.env_vars };
@@ -458,7 +524,7 @@ export function AgentConfigFields({
className={cn("text-sm font-medium", fieldLabelClassName)}
htmlFor="global-agent-provider"
>
{providerLabel}
Provider
</label>
{!useCustomSelect && useChevronSelectIcon ? (
<div className="relative">
@@ -526,7 +592,7 @@ export function AgentConfigFields({
fallbackModel === null &&
!dependentFieldsDisabled
}
keepSelectedModelValueLabel={keepSelectedModelValueLabel}
keepSelectedModelValueLabel
model={dependentFieldsDisabled ? "" : (config.model ?? "")}
modelDiscoveryLoading={
dependentFieldsDisabled ? false : modelDiscoveryLoading
@@ -537,7 +603,7 @@ export function AgentConfigFields({
onIsCustomModelEditingChange={onCustomModelEditingChange}
onModelChange={handleModelChange}
placeholderClassName={placeholderClassName}
placeholder={modelPlaceholderLabel}
placeholder="Select a model"
provider={providerForDiscovery}
fieldClassName={unstyled ? fieldClassName : undefined}
labelClassName={fieldLabelClassName}
@@ -556,7 +622,16 @@ export function AgentConfigFields({
<EffortSelectField
currentEffort={dependentFieldsDisabled ? "" : currentEffort}
disabled={dependentFieldsDisabled}
emptyOptionLabel={effortPlaceholderLabel}
emptyOptionLabel={
// Semantic, not copy: onboarding-essential hides inheritance
// concepts (first-run users pick, they don't inherit), so the
// zero option is a plain placeholder. Full disclosure leaves
// this unset so EffortSelectField computes the inherit/default
// label ("Default (medium)", "Inherit (high)", …).
disclosure === "onboarding-essential"
? "Select effort level"
: undefined
}
effortDefault={effortDefault}
effortValid={effortValid}
fieldClassName={unstyled ? fieldClassName : undefined}
@@ -565,7 +640,7 @@ export function AgentConfigFields({
effortDefault !== null ? `Default (${effortDefault})` : undefined
}
inheritedEffort={bakedEffort ?? undefined}
label={effortLabel}
label="Effort"
labelClassName={fieldLabelClassName}
onChange={(value) => {
const nextEnvVars = { ...config.env_vars };
@@ -0,0 +1,59 @@
/**
* Contract tests for the canonical agent-config behaviors and disclosure
* presets (PR 2 flag cleanup).
*
* Before PR 2, AgentConfigFields exposed 23 optional props and no test pinned
* any surface's behavior — a flag could be flipped or reintroduced and the
* suite would stay green. These tests pin the decided contract:
*
* 1. The four canonical behaviors hold (onboarding's values won every call).
* 2. "full" disclosure shows everything (the evergreen stance).
* 3. "onboarding-essential" hides escape hatches and power tools, but
* NEVER the effort field (onboarding never hid it).
*
* If a future change needs a different behavior or preset, it must edit these
* assertions — which is the conversation the flag cleanup was designed to force.
*/
import assert from "node:assert/strict";
import test from "node:test";
import {
CANONICAL_CONFIG_BEHAVIORS,
resolveDisclosure,
} from "./AgentConfigFields.tsx";
test("canonical behaviors: onboarding's values are the only behavior", () => {
assert.deepEqual(CANONICAL_CONFIG_BEHAVIORS, {
// Changing provider auto-selects a valid model (no dead-end empty model).
autoSelectModelOnProviderChange: true,
// Model select stays usable while discovery loads (no flash-disable).
disableModelSelectDuringDiscovery: false,
// Switching provider keeps the old provider's typed API key in env_vars.
preserveCredentialEnvVarsOnProviderChange: true,
// Model/effort are locked until a provider exists (no saveable invalid state).
requireProviderForModelAndEffort: true,
});
});
test("full disclosure shows every field, escape hatch, and description", () => {
const full = resolveDisclosure("full");
for (const [key, value] of Object.entries(full)) {
assert.equal(value, true, `full preset must show ${key}`);
}
});
test("onboarding-essential hides power tools but never the effort field", () => {
const essential = resolveDisclosure("onboarding-essential");
assert.deepEqual(essential, {
showAdvancedFields: false,
showCustomModelOption: false,
showCustomProviderOption: false,
showDescriptions: false,
// Effort was never hidden by onboarding; both presets show it.
showEffortField: true,
showProviderPlaceholderOption: false,
showRequiredIndicators: false,
showUnavailableEffortOptions: false,
});
});
+50 -9
View File
@@ -23,6 +23,7 @@ import {
toInboxContextMessage,
} from "@/features/home/lib/inboxViewHelpers";
import { useHomeInboxReadState } from "@/features/home/useHomeInboxReadState";
import { useHomeDrafts } from "@/features/home/useHomeDrafts";
import { useInboxThreadContext } from "@/features/home/useInboxThreadContext";
import {
type ProfilePanelTab,
@@ -41,6 +42,7 @@ import {
import { HomeLoadingState } from "@/features/home/ui/HomeLoadingState";
import { InboxDetailPane } from "@/features/home/ui/InboxDetailPane";
import { InboxListPane } from "@/features/home/ui/InboxListPane";
import { DraftDetailPane } from "@/features/messages/ui/DraftDetailPane";
import {
useChannelMessagesQuery,
useToggleReactionMutation,
@@ -52,7 +54,6 @@ import {
import { formatTime } from "@/features/messages/lib/dateFormatters";
import { splitOutgoingTags } from "@/features/messages/lib/imetaMediaMarkdown";
import { getThreadReference } from "@/features/messages/lib/threading";
import { useActiveDraftCount } from "@/features/messages/ui/DraftsPanel";
import { useUsersBatchQuery } from "@/features/profile/hooks";
import { useRelaySelfQuery } from "@/features/moderation/hooks";
import { resolveUserLabel } from "@/features/profile/lib/identity";
@@ -143,10 +144,18 @@ export function HomeView({
const isMessagesMode = !isReminders && !isDrafts;
const remindersQuery = useRemindersQuery(currentPubkey);
const dueReminderCount = countDueReminders(remindersQuery.data ?? []);
// Active draft count for the badge. When the Drafts panel is closed,
// rootStatusMap is empty so orphaned drafts are counted optimistically.
// They drop from the count once the panel opens and relay confirms deletion.
const activeDraftCount = useActiveDraftCount(new Map());
const {
activeCount: activeDraftCount,
deleteDraft: handleDeleteDraft,
items: draftItems,
selectedItem: selectedDraftItem,
selectedKey: selectedDraftKey,
selectDraft: setSelectedDraftKey,
} = useHomeDrafts({
isDrafts,
isNarrowHomeViewport,
viewportWidthPx: homeInboxWidthPx,
});
// `?item=` is Messages-mode-only machinery: a reminder never enters the
// FeedItem selection model, so reload while in Reminders mode keeps a stale
// `?item=` unconsumed and does not snap back to a feed-item detail view.
@@ -645,11 +654,19 @@ export function HomeView({
isNarrowHomeViewport &&
selectedEventId !== null &&
!isSinglePanelAuxiliaryView;
const showListPane = !isSinglePanelDetailView && !isSinglePanelAuxiliaryView;
const isSinglePanelDraftDetailView =
isDrafts &&
isNarrowHomeViewport &&
selectedDraftItem !== null &&
!isSinglePanelAuxiliaryView;
const showListPane =
!isSinglePanelDetailView &&
!isSinglePanelDraftDetailView &&
!isSinglePanelAuxiliaryView;
const showDetailPane =
isMessagesMode &&
!isSinglePanelAuxiliaryView &&
(!isNarrowHomeViewport || isSinglePanelDetailView);
((isMessagesMode && (!isNarrowHomeViewport || isSinglePanelDetailView)) ||
(isDrafts && (!isNarrowHomeViewport || isSinglePanelDraftDetailView)));
const auxiliaryPaneWidthPx = isSinglePanelAuxiliaryView
? homeInboxWidthPx
: threadPanelWidthPx;
@@ -695,15 +712,25 @@ export function HomeView({
} as React.CSSProperties
}
>
{showListPane || showDetailPane ? (
<div
aria-hidden="true"
className="pointer-events-none absolute inset-x-0 top-0 z-30 h-13 bg-background/80 backdrop-blur-md supports-backdrop-filter:bg-background/70 dark:bg-background/70 dark:backdrop-blur-xl dark:supports-backdrop-filter:bg-background/55"
data-testid="home-inbox-shared-header-backdrop"
/>
) : null}
{showListPane ? (
<InboxListPane
activeReminderEventIds={activeReminderEventIds}
agentPubkeys={inboxAgentPubkeys}
activeDraftCount={activeDraftCount}
draftItems={draftItems}
doneSet={effectiveDoneSet}
dueReminderCount={dueReminderCount}
filter={filter}
items={filteredItems}
onDeleteDraft={handleDeleteDraft}
onFilterChange={setFilter}
onMarkRead={markItemRead}
onMarkUnread={markItemUnread}
@@ -734,9 +761,11 @@ export function HomeView({
handleUserSelectItem(itemId);
markItemRead(itemId);
}}
onSelectDraft={setSelectedDraftKey}
onUnreadOnlyChange={setUnreadOnly}
reminderPubkey={currentPubkey}
selectedConversationId={selectedConversationId}
selectedDraftKey={selectedDraftKey}
showRightDivider={showListPane && showDetailPane}
unreadOnly={unreadOnly}
/>
@@ -765,7 +794,7 @@ export function HomeView({
<span className="absolute bottom-0 left-1/2 top-0 w-px -translate-x-1/2 bg-transparent transition-colors group-hover:bg-border/80 group-focus-visible:bg-border/80" />
</button>
{showDetailPane ? (
{showDetailPane && isMessagesMode ? (
<InboxDetailPane
agentPubkeys={inboxAgentPubkeys}
canDelete={canDelete}
@@ -902,6 +931,18 @@ export function HomeView({
replies={selectedItemReplies}
/>
) : null}
{showDetailPane && isDrafts ? (
<DraftDetailPane
item={selectedDraftItem}
key={selectedDraftItem?.entry.key ?? "empty"}
onBack={
isSinglePanelDraftDetailView
? () => setSelectedDraftKey(null)
: undefined
}
onDelete={handleDeleteDraft}
/>
) : null}
{profilePanelPubkey ? (
<RightAuxiliaryPane
canResetWidth={canResetThreadPanelWidth}
@@ -23,6 +23,7 @@ import { getThreadReference } from "@/features/messages/lib/threading";
import { normalizePubkey } from "@/shared/lib/pubkey";
import { MessageComposer } from "@/features/messages/ui/MessageComposer";
import { useAnchoredScroll } from "@/features/messages/ui/useAnchoredScroll";
import { useComposerHeightPadding } from "@/features/messages/ui/useComposerHeightPadding";
import { UpdateIndicator } from "@/features/settings/UpdateIndicator";
import type { Channel, UserProfileSummary } from "@/shared/api/types";
import { resolveMentionProps } from "@/shared/lib/resolveMentionNames";
@@ -130,6 +131,7 @@ export function InboxDetailPane({
// Refs for the shared anchored-scroll hook's container and content roots.
const scrollContainerRef = React.useRef<HTMLDivElement | null>(null);
const contentRef = React.useRef<HTMLDivElement | null>(null);
const composerWrapperRef = React.useRef<HTMLDivElement | null>(null);
const [replyTargetId, setReplyTargetId] = React.useState<string | null>(null);
const [isFocusHighlightVisible, setIsFocusHighlightVisible] =
React.useState(true);
@@ -319,6 +321,12 @@ export function InboxDetailPane({
setCapturedDefaultParentId(fallback);
}, [conversationId, selectedEventId, item, latchedDefaultParentId]);
useComposerHeightPadding(
scrollContainerRef,
composerWrapperRef,
conversationId,
);
if (!item) {
return (
<section
@@ -379,7 +387,7 @@ export function InboxDetailPane({
ref={detailPaneRef}
>
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
<TopChromeInsetHeader flush>
<TopChromeInsetHeader flush transparent>
<div className="px-5 py-2">
<div className="flex min-h-9 min-w-0 items-center justify-between gap-3">
<div
@@ -468,7 +476,8 @@ export function InboxDetailPane({
<div
aria-busy={isThreadContextLoading}
className="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-32 [overflow-anchor:none]"
className="-mt-13 min-h-0 flex-1 overflow-y-auto overscroll-contain pb-32 pt-13 [overflow-anchor:none]"
data-testid="home-inbox-detail-scroll"
onScroll={onScroll}
ref={scrollContainerRef}
>
@@ -488,27 +497,48 @@ export function InboxDetailPane({
);
return (
<React.Fragment key={message.id}>
{isAfterSeparator ? (
<div className="mx-6 my-3 border-t border-border/60" />
) : null}
<InboxMessageRow
agentPubkeys={agentPubkeys}
canReply={canReply}
channelId={item.item.channelId}
isContinuation={isContinuation}
isFocusHighlightVisible={isFocusHighlightVisible}
message={message}
onSelectReplyTarget={handleSelectReplyTarget}
onToggleReaction={onToggleReaction}
/>
</React.Fragment>
<InboxMessageRow
agentPubkeys={agentPubkeys}
canReply={canReply}
channelId={item.item.channelId}
isContinuation={isContinuation}
isFirst={index === 0}
isFocusHighlightVisible={isFocusHighlightVisible}
key={message.id}
message={message}
onSelectReplyTarget={handleSelectReplyTarget}
onToggleReaction={onToggleReaction}
/>
);
})}
</div>
</div>
<div className="pointer-events-none absolute inset-x-0 bottom-0 z-10">
<div
className="pointer-events-none absolute inset-x-0 bottom-0 z-40 isolate before:absolute before:inset-x-0 before:bottom-0 before:h-12 before:bg-gradient-to-b before:from-transparent before:to-background before:content-[''] after:absolute after:inset-x-0 after:bottom-0 after:h-4 after:bg-background after:content-['']"
data-testid="home-inbox-detail-composer-overlay"
ref={composerWrapperRef}
>
<span
aria-hidden="true"
className="absolute bottom-4 left-4 h-4 w-4 bg-background"
style={{
maskImage:
"radial-gradient(circle at top right, transparent 0 1rem, black calc(1rem + 0.5px))",
WebkitMaskImage:
"radial-gradient(circle at top right, transparent 0 1rem, black calc(1rem + 0.5px))",
}}
/>
<span
aria-hidden="true"
className="absolute bottom-4 right-4 h-4 w-4 bg-background"
style={{
maskImage:
"radial-gradient(circle at top left, transparent 0 1rem, black calc(1rem + 0.5px))",
WebkitMaskImage:
"radial-gradient(circle at top left, transparent 0 1rem, black calc(1rem + 0.5px))",
}}
/>
<div className="pointer-events-auto">
<MessageComposer
audienceContext={{
+94 -74
View File
@@ -1,8 +1,8 @@
import {
ChevronDown,
Clock,
Ellipsis,
ExternalLink,
ListFilter,
MailOpen,
} from "lucide-react";
import * as React from "react";
@@ -13,7 +13,10 @@ import {
type InboxItem,
type InboxTypeLabel,
} from "@/features/home/lib/inbox";
import { DraftsPanel } from "@/features/messages/ui/DraftsPanel";
import {
DraftsPanel,
type DraftViewItem,
} from "@/features/messages/ui/DraftsPanel";
import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover";
import { RemindersPanel } from "@/features/reminders/ui/RemindersPanel";
import { TopChromeInsetHeader } from "@/shared/layout/TopChromeInsetHeader";
@@ -102,17 +105,21 @@ type InboxListPaneProps = {
activeReminderEventIds?: ReadonlySet<string>;
agentPubkeys?: ReadonlySet<string>;
activeDraftCount: number;
draftItems: DraftViewItem[];
doneSet: ReadonlySet<string>;
filter: InboxFilter;
items: InboxItem[];
onFilterChange: (filter: InboxFilter) => void;
onDeleteDraft: (draftKey: string) => void;
onMarkRead: (itemId: string) => void;
onMarkUnread: (itemId: string) => void;
onOpenDirect: (item: InboxItem) => void;
onRemindLater: (item: InboxItem) => void;
onSelect: (itemId: string) => void;
onSelectDraft: (draftKey: string) => void;
onUnreadOnlyChange: (checked: boolean) => void;
selectedConversationId: string | null;
selectedDraftKey: string | null;
showRightDivider?: boolean;
dueReminderCount: number;
reminderPubkey?: string;
@@ -123,17 +130,21 @@ export function InboxListPane({
activeReminderEventIds,
agentPubkeys,
activeDraftCount,
draftItems,
doneSet,
filter,
items,
onFilterChange,
onDeleteDraft,
onMarkRead,
onMarkUnread,
onOpenDirect,
onRemindLater,
onSelect,
onSelectDraft,
onUnreadOnlyChange,
selectedConversationId,
selectedDraftKey,
showRightDivider = false,
dueReminderCount,
reminderPubkey,
@@ -142,6 +153,12 @@ export function InboxListPane({
const activeFilter = FILTER_OPTIONS.find((option) => option.value === filter);
const isReminders = filter === "reminders";
const isDrafts = filter === "drafts";
const inboxStatusLabel =
dueReminderCount > 0
? `${dueReminderCount} due reminder${dueReminderCount === 1 ? "" : "s"}`
: activeDraftCount > 0
? `${activeDraftCount} active draft${activeDraftCount === 1 ? "" : "s"}`
: null;
const scrollRef = React.useRef<HTMLDivElement>(null);
const unreadVisibleItemCount = React.useMemo(
() =>
@@ -156,7 +173,7 @@ export function InboxListPane({
}
}, [doneSet, items, onMarkRead]);
const renderItem = (item: InboxItem, index: number) => {
const renderItem = (item: InboxItem) => {
const isSelected = item.conversationId === selectedConversationId;
const isDone = doneSet.has(item.id);
const hasActiveReminder = activeReminderEventIds?.has(item.id) ?? false;
@@ -191,17 +208,14 @@ export function InboxListPane({
>
<button
aria-label={`Open inbox item from ${item.senderLabel}`}
className={cn(
"absolute inset-0 z-0 block w-full border-l border-l-transparent text-left after:pointer-events-none after:absolute after:bottom-0 after:left-[3.625rem] after:right-3 after:h-px after:bg-border/45 after:content-['']",
index === items.length - 1 && "after:hidden",
)}
className="absolute inset-0 z-0 block w-full border-l border-l-transparent text-left"
onClick={() => onSelect(item.id)}
type="button"
>
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-y-0 left-0 right-3 transition-colors",
"pointer-events-none absolute inset-y-0 left-0 right-0 transition-colors",
isSelected
? "bg-[var(--inbox-row-highlight-bg)]"
: "group-hover/inbox-item:bg-[var(--inbox-row-highlight-bg)] group-focus-within/inbox-item:bg-[var(--inbox-row-highlight-bg)] group-active/inbox-item:bg-muted/40",
@@ -387,89 +401,90 @@ export function InboxListPane({
showRightDivider && INBOX_PANE_RIGHT_DIVIDER_CLASS,
)}
>
<TopChromeInsetHeader flush>
<TopChromeInsetHeader flush transparent>
<div className="px-5 py-2">
<div className="flex min-h-9 w-full min-w-0 items-center justify-between gap-3">
<Popover>
<PopoverTrigger asChild>
<button
aria-label="Inbox options"
className={cn(INBOX_HEADER_ICON_BUTTON_CLASS, "-ml-4")}
data-testid="inbox-options-trigger"
type="button"
>
<Ellipsis className="h-4 w-4" />
</button>
</PopoverTrigger>
<PopoverContent align="start" className="w-60 p-2">
<div
className={cn(
"flex min-h-9 items-center justify-between gap-3 rounded-lg px-2 py-1.5",
(isReminders || isDrafts) && "opacity-50",
)}
>
<label
className="text-sm font-medium text-foreground"
htmlFor="inbox-unread-only-switch"
<div className="order-2 ml-auto flex shrink-0 items-center justify-end">
<Popover>
<PopoverTrigger asChild>
<button
aria-label="Inbox options"
className={cn(INBOX_HEADER_ICON_BUTTON_CLASS, "-mr-4")}
data-testid="inbox-options-trigger"
type="button"
>
Show unread
</label>
<Switch
checked={unreadOnly}
className="shadow-none [&>span]:shadow-none"
data-testid="inbox-unread-only-toggle"
disabled={isReminders || isDrafts}
id="inbox-unread-only-switch"
onCheckedChange={onUnreadOnlyChange}
/>
</div>
<Separator className="my-1 bg-muted" />
<button
className="flex min-h-9 w-full items-center rounded-lg px-2 py-2 text-left text-sm transition-colors hover:bg-muted/50 disabled:pointer-events-none disabled:opacity-50"
disabled={unreadVisibleItemCount === 0}
onClick={handleMarkAllRead}
type="button"
>
<span>Mark all as read</span>
{unreadVisibleItemCount > 0 ? (
<span className="ml-auto text-xs text-muted-foreground">
{unreadVisibleItemCount}
</span>
) : null}
</button>
</PopoverContent>
</Popover>
<div className="ml-auto flex shrink-0 items-center justify-end">
<Ellipsis className="h-4 w-4" />
</button>
</PopoverTrigger>
<PopoverContent align="end" className="w-60 p-2">
<div
className={cn(
"flex min-h-9 items-center justify-between gap-3 rounded-lg px-2 py-1.5",
(isReminders || isDrafts) && "opacity-50",
)}
>
<label
className="text-sm font-medium text-foreground"
htmlFor="inbox-unread-only-switch"
>
Show unread
</label>
<Switch
checked={unreadOnly}
className="shadow-none [&>span]:shadow-none"
data-testid="inbox-unread-only-toggle"
disabled={isReminders || isDrafts}
id="inbox-unread-only-switch"
onCheckedChange={onUnreadOnlyChange}
/>
</div>
<Separator className="my-1 bg-muted" />
<button
className="flex min-h-9 w-full items-center rounded-lg px-2 py-2 text-left text-sm transition-colors hover:bg-muted/50 disabled:pointer-events-none disabled:opacity-50"
disabled={unreadVisibleItemCount === 0}
onClick={handleMarkAllRead}
type="button"
>
<span>Mark all as read</span>
{unreadVisibleItemCount > 0 ? (
<span className="ml-auto text-xs text-muted-foreground">
{unreadVisibleItemCount}
</span>
) : null}
</button>
</PopoverContent>
</Popover>
</div>
<div className="order-1 flex shrink-0 items-center justify-start">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
aria-label={`Filter inbox: ${activeFilter?.label ?? "All"}`}
aria-label={`Filter inbox: ${activeFilter?.label ?? "All"}${inboxStatusLabel ? `. ${inboxStatusLabel}` : ""}`}
className={cn(
INBOX_HEADER_ICON_BUTTON_CLASS,
"relative -mr-4",
"relative -ml-2 w-auto gap-1 px-2 text-sm font-medium text-foreground",
)}
data-testid="inbox-filter-trigger"
type="button"
>
<ListFilter className="h-4 w-4" />
<span>{activeFilter?.label ?? "All"}</span>
<ChevronDown className="h-4 w-4 text-muted-foreground" />
{dueReminderCount > 0 ? (
<span
className="absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full border border-background bg-primary px-1 text-2xs font-semibold leading-none text-primary-foreground"
aria-hidden="true"
className="absolute right-1.5 top-0 h-1.5 w-1.5 rounded-full bg-primary ring-2 ring-background"
data-testid="inbox-reminder-badge"
>
{dueReminderCount}
</span>
/>
) : activeDraftCount > 0 ? (
<span
className="absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full border border-background bg-primary px-1 text-2xs font-semibold leading-none text-primary-foreground"
aria-hidden="true"
className="absolute right-1.5 top-0 h-1.5 w-1.5 rounded-full bg-primary ring-2 ring-background"
data-testid="inbox-draft-badge"
>
{activeDraftCount}
</span>
/>
) : null}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuContent align="start" className="w-48">
<DropdownMenuRadioGroup
onValueChange={(value) =>
onFilterChange(value as InboxFilter)
@@ -513,7 +528,7 @@ export function InboxListPane({
{isReminders ? (
<div
className="flex min-h-0 flex-1 flex-col overflow-hidden"
className="-mt-13 flex min-h-0 flex-1 flex-col overflow-hidden pt-13"
data-testid="home-inbox-reminders"
>
{reminderPubkey ? (
@@ -522,14 +537,19 @@ export function InboxListPane({
</div>
) : isDrafts ? (
<div
className="flex min-h-0 flex-1 flex-col overflow-hidden"
className="-mt-13 flex min-h-0 flex-1 flex-col overflow-hidden pt-13"
data-testid="home-inbox-drafts"
>
<DraftsPanel />
<DraftsPanel
items={draftItems}
onDeleteDraft={onDeleteDraft}
onSelectDraft={onSelectDraft}
selectedDraftKey={selectedDraftKey}
/>
</div>
) : (
<div
className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain"
className="-mt-13 min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain pt-13"
data-testid="home-inbox-list"
ref={scrollRef}
>
@@ -27,6 +27,7 @@ type InboxMessageRowProps = {
/** Channel UUID for "Copy link" — passed straight through to MessageActionBar. */
channelId?: string | null;
isContinuation?: boolean;
isFirst?: boolean;
isFocusHighlightVisible: boolean;
message: InboxDisplayMessage;
onSelectReplyTarget: (message: InboxDisplayMessage) => void;
@@ -42,6 +43,7 @@ export function InboxMessageRow({
canReply,
channelId = null,
isContinuation = false,
isFirst = false,
isFocusHighlightVisible,
message,
onSelectReplyTarget,
@@ -111,7 +113,12 @@ export function InboxMessageRow({
}
>
{canReply || canToggleReactions ? (
<div className="absolute right-2 top-1 z-10 sm:top-0 sm:-translate-y-1/2">
<div
className={cn(
"absolute right-2 top-1 z-10",
!isFirst && "sm:top-0 sm:-translate-y-1/2",
)}
>
<MessageActionBar
channelId={channelId}
message={timelineMessage}
@@ -0,0 +1,64 @@
import * as React from "react";
import { clearDraftEntry } from "@/features/messages/lib/useDrafts";
import {
useActiveDraftCount,
useDraftViewItems,
} from "@/features/messages/ui/DraftsPanel";
type UseHomeDraftsOptions = {
isDrafts: boolean;
isNarrowHomeViewport: boolean;
viewportWidthPx: number;
};
export function useHomeDrafts({
isDrafts,
isNarrowHomeViewport,
viewportWidthPx,
}: UseHomeDraftsOptions) {
const items = useDraftViewItems(isDrafts);
const optimisticActiveCount = useActiveDraftCount(new Map());
const activeCount = isDrafts
? items.filter((item) => item.rootStatus !== "deleted").length
: optimisticActiveCount;
const [selectedKey, setSelectedKey] = React.useState<string | null>(null);
const selectedItem =
items.find((item) => item.entry.key === selectedKey) ?? null;
React.useEffect(() => {
if (!isDrafts) {
setSelectedKey(null);
return;
}
if (viewportWidthPx === 0) {
return;
}
if (
selectedKey !== null &&
items.some((item) => item.entry.key === selectedKey)
) {
return;
}
setSelectedKey(isNarrowHomeViewport ? null : (items[0]?.entry.key ?? null));
}, [isDrafts, isNarrowHomeViewport, items, selectedKey, viewportWidthPx]);
const deleteDraft = React.useCallback(
(draftKey: string) => {
clearDraftEntry(draftKey);
if (selectedKey === draftKey) {
setSelectedKey(null);
}
},
[selectedKey],
);
return {
activeCount,
deleteDraft,
items,
selectedItem,
selectedKey,
selectDraft: setSelectedKey,
};
}
@@ -0,0 +1,268 @@
import {
AlertTriangle,
ArrowLeft,
FileText,
Lock,
Pencil,
Send,
Trash2,
} from "lucide-react";
import * as React from "react";
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
import {
canOpenDraft,
canSendDraft,
formatDraftCreatedAt,
getDraftPreview,
openDraftEntry,
SendConfirmDialog,
sendDraftEntry,
type DraftViewItem,
} from "@/features/messages/ui/DraftsPanel";
import { TopChromeInsetHeader } from "@/shared/layout/TopChromeInsetHeader";
import { Button } from "@/shared/ui/button";
import { Markdown } from "@/shared/ui/markdown";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip";
import { UserAvatar } from "@/shared/ui/UserAvatar";
type DraftDetailPaneProps = {
item: DraftViewItem | null;
onBack?: () => void;
onDelete: (draftKey: string) => void;
};
export function DraftDetailPane({
item,
onBack,
onDelete,
}: DraftDetailPaneProps) {
const { goChannel } = useAppNavigation();
const [sendDialogOpen, setSendDialogOpen] = React.useState(false);
if (!item) {
return (
<section
className="flex min-h-0 min-w-0 items-center justify-center bg-background/60 px-6 py-10 pt-20 text-center"
data-testid="home-inbox-draft-detail-empty"
>
<div className="max-w-sm">
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted text-muted-foreground">
<FileText className="h-6 w-6" />
</div>
<p className="mt-4 text-base font-semibold">Select a draft</p>
<p className="mt-1 text-sm text-muted-foreground">
Pick a draft to preview it and choose what to do next.
</p>
</div>
</section>
);
}
const { entry, rootStatus, source } = item;
const isOrphaned = rootStatus === "deleted";
const isPrivate = source.channel?.visibility === "private";
const isDm = source.channel?.channelType === "dm";
const channelLabel = source.channel
? isDm
? source.label
: `#${source.label}`
: "Unknown channel";
const openEnabled = canOpenDraft(entry.draft, source) && !isOrphaned;
const sendEnabled = canSendDraft(entry.draft, source, rootStatus);
const content = entry.draft.content.trim();
const attachmentCount = entry.draft.pendingImeta.length;
return (
<section
className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-background/60"
data-testid="home-inbox-draft-detail"
>
<TopChromeInsetHeader flush transparent>
<div className="px-5 py-2">
<div className="flex min-h-9 min-w-0 items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-1">
{onBack ? (
<Button
aria-label="Back to drafts list"
className="rounded-full text-muted-foreground hover:bg-muted/60 hover:text-foreground"
onClick={onBack}
size="icon"
type="button"
variant="ghost"
>
<ArrowLeft />
</Button>
) : null}
<div className="flex min-w-0 items-center gap-1.5">
{isPrivate ? (
<Lock className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
) : null}
<h2 className="truncate text-sm font-semibold leading-5 tracking-tight text-foreground">
{channelLabel}
</h2>
</div>
</div>
</div>
</div>
</TopChromeInsetHeader>
<div className="-mt-13 min-h-0 flex-1 overflow-y-auto pb-8 pt-15">
{isOrphaned ? (
<div
className="mx-5 mb-3 flex items-start gap-2 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm text-destructive"
data-testid="home-inbox-draft-orphaned-notice"
>
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
<span>
The original thread was deleted. This draft can no longer be
opened or sent.
</span>
</div>
) : null}
<div className="relative px-2">
<article className="group/message relative z-10 mx-1 flex items-start gap-2.5 rounded-2xl px-2 py-1 transition-colors hover:bg-muted/50 focus-within:bg-muted/50">
<DraftActionBar
canOpen={openEnabled}
canSend={sendEnabled}
onDelete={() => onDelete(entry.key)}
onOpen={() => void openDraftEntry(entry, goChannel)}
onSend={() => setSendDialogOpen(true)}
/>
<UserAvatar
avatarUrl={null}
className="h-9 w-9 shrink-0"
displayName="You"
size="md"
/>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0">
<span className="text-sm font-semibold text-foreground">
You
</span>
<span className="text-xs font-medium text-muted-foreground">
Draft
</span>
<span className="shrink-0 text-xs font-normal tabular-nums text-muted-foreground/55">
{formatDraftCreatedAt(entry.draft)}
</span>
</div>
<div className="mt-0.5 text-base leading-6 text-foreground">
<Markdown
className="inbox-preview-markdown text-inherit leading-6"
content={content || getDraftPreview(entry.draft)}
interactive={false}
/>
{attachmentCount > 0 && content ? (
<p className="mt-2 text-sm text-muted-foreground">
{attachmentCount} attachment
{attachmentCount === 1 ? "" : "s"}
</p>
) : null}
</div>
</div>
</article>
</div>
</div>
{sendDialogOpen ? (
<SendConfirmDialog
channelLabel={source.label}
isDm={isDm}
onCancel={() => setSendDialogOpen(false)}
onConfirm={() => {
setSendDialogOpen(false);
void sendDraftEntry(entry, goChannel);
}}
open={true}
/>
) : null}
</section>
);
}
function DraftActionBar({
canOpen,
canSend,
onDelete,
onOpen,
onSend,
}: {
canOpen: boolean;
canSend: boolean;
onDelete: () => void;
onOpen: () => void;
onSend: () => void;
}) {
return (
<div className="absolute right-2 top-1 z-10">
<div
className="-m-1 p-1 opacity-100 transition-opacity duration-150 ease-out sm:pointer-events-none sm:opacity-0 sm:group-hover/message:pointer-events-auto sm:group-hover/message:opacity-100 sm:group-focus-within/message:pointer-events-auto sm:group-focus-within/message:opacity-100"
data-testid="home-inbox-draft-action-bar"
>
<div className="overflow-hidden rounded-full border border-border/70 bg-background/95 shadow-xs backdrop-blur-sm supports-[backdrop-filter]:bg-background/85">
<div className="flex items-center gap-0.5 p-1">
<DraftActionButton
disabled={!canOpen}
label="Open draft"
onClick={onOpen}
>
<Pencil className="h-4 w-4" />
</DraftActionButton>
<DraftActionButton
disabled={!canSend}
label="Send"
onClick={onSend}
>
<Send className="h-4 w-4" />
</DraftActionButton>
<DraftActionButton destructive label="Delete" onClick={onDelete}>
<Trash2 className="h-4 w-4" />
</DraftActionButton>
</div>
</div>
</div>
</div>
);
}
function DraftActionButton({
children,
destructive = false,
disabled = false,
label,
onClick,
}: {
children: React.ReactNode;
destructive?: boolean;
disabled?: boolean;
label: string;
onClick: () => void;
}) {
return (
<Tooltip>
<TooltipTrigger asChild>
<Button
aria-label={label}
className={
destructive
? "h-8 w-8 rounded-full p-0 text-destructive hover:text-destructive"
: "h-8 w-8 rounded-full p-0"
}
disabled={disabled}
onClick={onClick}
size="sm"
type="button"
variant="ghost"
>
{children}
</Button>
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
+145 -144
View File
@@ -4,7 +4,6 @@ import * as React from "react";
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
import { useChannelsQuery } from "@/features/channels/hooks";
import {
clearDraftEntry,
getActiveDraftEntries,
renameDraftEntry,
useDraftsSnapshot,
@@ -45,22 +44,22 @@ const SENT_DRAFT_PREFIX = "sent:";
const THREAD_DRAFT_PREFIX = "thread:";
const UNKNOWN_CHANNEL_LABEL = "Unknown channel";
type DraftListEntry = {
export type DraftListEntry = {
draft: DraftState;
key: string;
};
type DraftSection = {
entries: DraftListEntry[];
label: string;
status: DraftState["status"];
};
type DraftSource = {
export type DraftSource = {
channel: Channel | null;
label: string;
};
export type DraftViewItem = {
entry: DraftListEntry;
rootStatus: RootStatus;
source: DraftSource;
};
const UNKNOWN_DRAFT_SOURCE: DraftSource = {
channel: null,
label: UNKNOWN_CHANNEL_LABEL,
@@ -78,7 +77,7 @@ function parseDraftTime(value: string): number {
return Number.isFinite(time) ? time : 0;
}
function formatDraftCreatedAt(draft: DraftState): string {
export function formatDraftCreatedAt(draft: DraftState): string {
const time = parseDraftTime(draft.createdAt);
return time === 0
? "Unknown time"
@@ -97,7 +96,7 @@ function getOriginalDraftKey(draftKey: string): string {
: sentPayload;
}
function getThreadRootId(draftKey: string): string | null {
export function getThreadRootId(draftKey: string): string | null {
const originalDraftKey = getOriginalDraftKey(draftKey);
if (!originalDraftKey.startsWith(THREAD_DRAFT_PREFIX)) {
return null;
@@ -113,7 +112,7 @@ function isVisibleDraft(entry: DraftListEntry): boolean {
return content.length > 0 || attachmentCount > 0;
}
function getDraftPreview(draft: DraftState): string {
export function getDraftPreview(draft: DraftState): string {
const content = draft.content.trim();
if (content.length > 0) {
return content;
@@ -129,17 +128,6 @@ function getDraftPreview(draft: DraftState): string {
return "Empty draft";
}
function readDraftSections(): DraftSection[] {
const active = getActiveDraftEntries().filter(isVisibleDraft);
const sections: DraftSection[] = [];
if (active.length > 0) {
sections.push({ label: "Drafts", status: "active", entries: active });
}
return sections;
}
function resolveDraftSources({
channels,
currentPubkey,
@@ -236,6 +224,65 @@ export function canSendDraft(
return true;
}
type GoChannel = ReturnType<typeof useAppNavigation>["goChannel"];
export async function openDraftEntry(
entry: DraftListEntry,
goChannel: GoChannel,
): Promise<void> {
if (!entry.draft.channelId) return;
if (entry.key.startsWith(INBOX_REPLY_PREFIX)) {
const migrated = await migrateInboxReplyDraft(entry.key, entry.draft, {
getEventById,
getChannelIdFromTags,
getThreadReference,
renameDraftEntry,
});
if (!migrated) return;
await goChannel(migrated.channelId, {
messageId: migrated.conversationId,
threadRootId: migrated.conversationId,
});
return;
}
const threadRootId = getThreadRootId(entry.key);
await goChannel(
entry.draft.channelId,
threadRootId ? { messageId: threadRootId, threadRootId } : undefined,
);
}
export async function sendDraftEntry(
entry: DraftListEntry,
goChannel: GoChannel,
): Promise<void> {
if (!entry.draft.channelId) return;
if (entry.key.startsWith(INBOX_REPLY_PREFIX)) {
const migrated = await migrateInboxReplyDraft(entry.key, entry.draft, {
getEventById,
getChannelIdFromTags,
getThreadReference,
renameDraftEntry,
});
if (!migrated) return;
await goChannel(migrated.channelId, {
autoSend: migrated.newDraftKey,
messageId: migrated.conversationId,
threadRootId: migrated.conversationId,
});
return;
}
const threadRootId = getThreadRootId(entry.key);
await goChannel(entry.draft.channelId, {
...(threadRootId ? { messageId: threadRootId, threadRootId } : {}),
autoSend: entry.key,
});
}
// ── Send confirmation dialog ──────────────────────────────────────────────────
type SendConfirmDialogProps = {
@@ -246,7 +293,7 @@ type SendConfirmDialogProps = {
open: boolean;
};
function SendConfirmDialog({
export function SendConfirmDialog({
channelLabel,
isDm,
onCancel,
@@ -289,15 +336,19 @@ function DraftRow({
entry,
onDelete,
onOpen,
onSelect,
onSend,
rootStatus,
selected,
source,
}: {
entry: DraftListEntry;
onDelete: (draftKey: string) => void;
onOpen: (entry: DraftListEntry) => void;
onSelect: () => void;
onSend: (entry: DraftListEntry) => void;
rootStatus: RootStatus;
selected: boolean;
source: DraftSource;
}) {
const isSent = entry.draft.status === "sent";
@@ -316,15 +367,15 @@ function DraftRow({
<div
className={cn(
"group/draft-row relative rounded-md border border-border/70 bg-background transition-colors hover:bg-muted/40 focus-within:bg-muted/40",
selected && "border-primary/30 bg-muted/60",
isOrphaned && "opacity-50",
)}
data-testid={`home-draft-item-${entry.key}`}
>
<button
aria-label={`Open draft in ${channelLabel}`}
aria-label={`View draft in ${channelLabel}`}
className="block w-full min-w-0 px-3 py-3 text-left disabled:cursor-default"
disabled={!canOpen}
onClick={() => onOpen(entry)}
onClick={onSelect}
type="button"
>
<div className="min-w-0 pr-0 transition-[padding] group-hover/draft-row:pr-20 group-focus-within/draft-row:pr-20">
@@ -458,41 +509,28 @@ export function useActiveDraftCount(
return deriveActiveDraftCount(activeDrafts, rootStatusMap);
}
// ── DraftsPanel ──────────────────────────────────────────────────────────────
// ── Shared draft view model ──────────────────────────────────────────────────
export function DraftsPanel() {
const { goChannel } = useAppNavigation();
export function useDraftViewItems(enabled: boolean): DraftViewItem[] {
const identityQuery = useIdentityQuery();
const currentPubkey = identityQuery.data?.pubkey;
const channelsQuery = useChannelsQuery();
// Collapse the old `sections` state + `refreshDrafts` pattern onto a
// reactive snapshot: every draft write re-renders via useSyncExternalStore.
useDraftsSnapshot();
const sections = readDraftSections();
const drafts = getActiveDraftEntries().filter(isVisibleDraft);
const drafts = React.useMemo(
() => sections.flatMap((section) => section.entries),
[sections],
);
// Collect unique thread-root IDs from active drafts only (sent drafts cannot
// be sent/orphaned). Deduplicated on root id — multiple drafts can share one.
const threadRootIds = React.useMemo(() => {
const ids = new Set<string>();
for (const entry of sections.flatMap((s) =>
s.status === "active" ? s.entries : [],
)) {
for (const entry of drafts) {
const rootId = getThreadRootId(entry.key);
if (rootId) {
ids.add(rootId);
}
}
return [...ids];
}, [sections]);
}, [drafts]);
// Panel is always mounted when visible; `isOpen=true` enables root queries.
const rootStatusMap = useDraftRootStatus(threadRootIds, true);
const rootStatusMap = useDraftRootStatus(threadRootIds, enabled);
const profilePubkeys = React.useMemo(
() => [
@@ -522,6 +560,36 @@ export function DraftsPanel() {
[channelsQuery.data, currentPubkey, drafts, profiles],
);
return drafts.map((entry) => {
const threadRootId = getThreadRootId(entry.key);
return {
entry,
rootStatus:
threadRootId !== null
? (rootStatusMap.get(threadRootId) ?? "checking")
: "available",
source: sources.get(entry.key) ?? UNKNOWN_DRAFT_SOURCE,
};
});
}
// ── DraftsPanel ──────────────────────────────────────────────────────────────
type DraftsPanelProps = {
items: DraftViewItem[];
onDeleteDraft: (draftKey: string) => void;
onSelectDraft: (draftKey: string) => void;
selectedDraftKey: string | null;
};
export function DraftsPanel({
items,
onDeleteDraft,
onSelectDraft,
selectedDraftKey,
}: DraftsPanelProps) {
const { goChannel } = useAppNavigation();
// Send confirmation dialog state.
const [sendTarget, setSendTarget] = React.useState<DraftListEntry | null>(
null,
@@ -529,52 +597,17 @@ export function DraftsPanel() {
const handleOpen = React.useCallback(
(entry: DraftListEntry) => {
if (!entry.draft.channelId) {
return;
}
// Legacy inbox-reply:<eventId> keys were written by the old InboxDetailPane
// before stable conversation IDs were introduced. Migrate them on open:
// resolve the embedded event to derive the thread root, verify the channel
// tag matches the stored channelId, re-key to thread:<conversationId>, and
// navigate to the correct thread composer with the migrated content.
if (entry.key.startsWith(INBOX_REPLY_PREFIX)) {
void (async () => {
const migrated = await migrateInboxReplyDraft(
entry.key,
entry.draft,
{
getEventById,
getChannelIdFromTags,
getThreadReference,
renameDraftEntry,
},
);
// Navigate only on successful migration; any failure leaves the
// legacy draft untouched and the user in place.
if (!migrated) return;
void goChannel(migrated.channelId, {
messageId: migrated.conversationId,
threadRootId: migrated.conversationId,
});
})();
return;
}
const threadRootId = getThreadRootId(entry.key);
void goChannel(
entry.draft.channelId,
threadRootId ? { messageId: threadRootId, threadRootId } : undefined,
);
void openDraftEntry(entry, goChannel);
},
[goChannel],
);
const handleDelete = React.useCallback((draftKey: string) => {
clearDraftEntry(draftKey);
// No manual refresh needed — clearDraftEntry notifies subscribers and
// useDraftsSnapshot() causes DraftsPanel to re-render automatically.
}, []);
const handleDelete = React.useCallback(
(draftKey: string) => {
onDeleteDraft(draftKey);
},
[onDeleteDraft],
);
const handleSendRequest = React.useCallback((entry: DraftListEntry) => {
setSendTarget(entry);
@@ -588,44 +621,18 @@ export function DraftsPanel() {
if (!sendTarget) return;
const entry = sendTarget;
setSendTarget(null);
if (!entry.draft.channelId) return;
// Legacy inbox-reply: keys: migrate first, then auto-send with new key.
if (entry.key.startsWith(INBOX_REPLY_PREFIX)) {
void (async () => {
const migrated = await migrateInboxReplyDraft(entry.key, entry.draft, {
getEventById,
getChannelIdFromTags,
getThreadReference,
renameDraftEntry,
});
if (!migrated) return;
void goChannel(migrated.channelId, {
messageId: migrated.conversationId,
threadRootId: migrated.conversationId,
autoSend: migrated.newDraftKey,
});
})();
return;
}
const threadRootId = getThreadRootId(entry.key);
void goChannel(entry.draft.channelId, {
...(threadRootId ? { messageId: threadRootId, threadRootId } : {}),
autoSend: entry.key,
});
void sendDraftEntry(entry, goChannel);
}, [sendTarget, goChannel]);
const sendDialogSource = sendTarget
? (sources.get(sendTarget.key) ?? UNKNOWN_DRAFT_SOURCE)
: UNKNOWN_DRAFT_SOURCE;
const sendDialogSource =
items.find((item) => item.entry.key === sendTarget?.key)?.source ??
UNKNOWN_DRAFT_SOURCE;
const sendDialogIsDm = sendDialogSource.channel?.channelType === "dm";
const sendDialogChannelLabel = sendDialogSource.channel
? sendDialogSource.label
: UNKNOWN_CHANNEL_LABEL;
if (sections.length === 0) {
if (items.length === 0) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 p-8 text-center">
<FileText className="h-8 w-8 text-muted-foreground/50" />
@@ -636,31 +643,25 @@ export function DraftsPanel() {
return (
<>
<div className="flex-1 space-y-4 overflow-y-auto p-4">
{sections.map((section) => (
<div className="space-y-2" key={section.status}>
<h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{section.label}
</h3>
{section.entries.map((entry) => {
const threadRootId = getThreadRootId(entry.key);
const rootStatus: RootStatus =
threadRootId !== null
? (rootStatusMap.get(threadRootId) ?? "checking")
: "available";
return (
<DraftRow
entry={entry}
key={entry.key}
onDelete={handleDelete}
onOpen={handleOpen}
onSend={handleSendRequest}
rootStatus={rootStatus}
source={sources.get(entry.key) ?? UNKNOWN_DRAFT_SOURCE}
/>
);
})}
</div>
<div
className="flex-1 space-y-2 overflow-y-auto p-4"
data-testid="home-inbox-drafts-list"
>
<h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Drafts
</h3>
{items.map(({ entry, rootStatus, source }) => (
<DraftRow
entry={entry}
key={entry.key}
onDelete={handleDelete}
onOpen={handleOpen}
onSelect={() => onSelectDraft(entry.key)}
onSend={handleSendRequest}
rootStatus={rootStatus}
selected={entry.key === selectedDraftKey}
source={source}
/>
))}
</div>
@@ -195,11 +195,6 @@ function AgentDefaultsSection({
config={config}
isCustomModelEditing={isCustomModelEditing}
isCustomProvider={isCustomProvider}
autoSelectModelOnProviderChange
disableModelSelectDuringDiscovery={false}
effortPlaceholderLabel="Select effort level"
keepSelectedModelValueLabel
modelPlaceholderLabel="Select a model"
onConfigChange={(next) => {
// Always apply optimistically so the UI never reverts mid-save,
// then enqueue the persist — the coalescer serialises multiple
@@ -209,20 +204,10 @@ function AgentDefaultsSection({
}}
onCustomModelEditingChange={setIsCustomModelEditing}
onIsCustomProviderChange={setIsCustomProvider}
preserveCredentialEnvVarsOnProviderChange
effortLabel="Effort"
placeholderClassName="text-foreground/70"
providerLabel="Provider"
requireProviderForModelAndEffort
selectClassName="h-12 rounded-2xl border-foreground/15 bg-white px-4 py-2 text-sm shadow-none hover:bg-white/95"
showAdvancedFields={false}
showCustomModelOption={false}
showCustomProviderOption={false}
showDescriptions={false}
disclosure="onboarding-essential"
showProviderField={selectedRuntimeSupportsModelProvider}
showRequiredIndicators={false}
showProviderPlaceholderOption={false}
showUnavailableEffortOptions={false}
unstyled
useCustomSelect
/>
@@ -6,6 +6,8 @@ import { cn } from "@/shared/lib/cn";
type TopChromeInsetHeaderProps = React.ComponentProps<"div"> & {
/** Keep the header flush with its parent content row. */
flush?: boolean;
/** Render without a local backdrop when a parent supplies shared chrome. */
transparent?: boolean;
};
/**
@@ -16,12 +18,13 @@ export function TopChromeInsetHeader({
className,
children,
flush = false,
transparent = false,
...props
}: TopChromeInsetHeaderProps) {
return (
<div
className={cn(
topChromeInset.headerBase,
transparent ? "relative z-40 shrink-0" : topChromeInset.headerBase,
!flush && topChromeInset.padding,
!flush && topChromeInset.divider,
className,
+1 -1
View File
@@ -33,7 +33,7 @@ export const topChromeInset = {
"before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:h-px before:bg-border/35 before:content-['']",
/** Shared header backdrop and bottom border below the inset row. */
headerBase:
"relative z-40 shrink-0 bg-background/75 backdrop-blur-md supports-backdrop-filter:bg-background/65 dark:bg-background/45 dark:backdrop-blur-xl dark:supports-backdrop-filter:bg-background/35",
"relative z-40 shrink-0 bg-background/80 backdrop-blur-md supports-backdrop-filter:bg-background/70 dark:bg-background/70 dark:backdrop-blur-xl dark:supports-backdrop-filter:bg-background/55",
/** Vertical pane divider starting at the top of the content row. */
verticalDivider:
"after:pointer-events-none after:absolute after:bottom-0 after:right-0 after:top-0 after:z-40 after:w-px after:bg-border/35 after:content-['']",
+8 -3
View File
@@ -2530,9 +2530,14 @@ test("home inbox manage affordance opens management without leaving home", async
}
expect(detailBox.x + detailBox.width).toBeLessThanOrEqual(sheetBox.x + 1);
expect(sheetBox.width).toBeGreaterThanOrEqual(300);
await page
.getByTestId("home-inbox-list")
.click({ position: { x: 24, y: 80 } });
const inboxList = page.getByTestId("home-inbox-list");
const inboxListBox = await inboxList.boundingBox();
if (!inboxListBox) {
throw new Error("Expected the home inbox list box.");
}
await inboxList.click({
position: { x: 24, y: inboxListBox.height - 24 },
});
await expect(page.getByTestId("channel-management-sheet")).toBeVisible();
await page.keyboard.press("Escape");
await expect(page.getByTestId("channel-management-sheet")).toBeVisible();
+46 -13
View File
@@ -1,5 +1,6 @@
import { expect, test } from "@playwright/test";
import { waitForAnimations } from "../helpers/animations";
import { installMockBridge } from "../helpers/bridge";
const SHOTS = "test-results/drafts";
@@ -164,14 +165,44 @@ test.describe("drafts screenshots", () => {
// Section heading should be "DRAFTS"
await expect(panel.getByText("Drafts", { exact: true })).toBeVisible();
// Small settle before screenshot
await page.waitForTimeout(200);
const detail = page.getByTestId("home-inbox-draft-detail");
await expect(detail).toBeVisible();
await expect(detail.getByText("1 attachment")).toBeVisible();
await expect(detail.getByText("You", { exact: true })).toBeVisible();
await expect(detail.getByText("Draft", { exact: true })).toBeVisible();
await panel.screenshot({
await detail.locator("article").hover();
await expect(
detail.getByTestId("home-inbox-draft-action-bar"),
).toBeVisible();
await waitForAnimations(page);
await page.getByTestId("home-inbox").screenshot({
path: `${SHOTS}/01-drafts-section-populated.png`,
});
});
test("02 — narrow draft list opens the detail view", async ({ page }) => {
await page.setViewportSize({ width: 520, height: 900 });
await installMockBridge(page);
await patchCommunityPubkey(page);
await seedDraftStore(page, ACTIVE_DRAFTS);
const panel = await openDraftsPanel(page);
const draftRow = panel.locator(
`[data-testid='home-draft-item-channel:${GENERAL_CHANNEL_ID}']`,
);
await draftRow.getByRole("button", { name: /View draft/ }).click();
const detail = page.getByTestId("home-inbox-draft-detail");
await expect(detail).toBeVisible();
await expect(panel).not.toBeVisible();
await detail.getByRole("button", { name: "Back to drafts list" }).click();
await expect(panel).toBeVisible();
await expect(detail).not.toBeVisible();
});
test("03 — hover actions visible", async ({ page }) => {
await installMockBridge(page);
await patchCommunityPubkey(page);
@@ -204,8 +235,7 @@ test.describe("drafts screenshots", () => {
await expect(sendMessageBtn).toBeVisible({ timeout: 4_000 });
await expect(deleteDraftBtn).toBeVisible({ timeout: 4_000 });
await page.waitForTimeout(200);
await waitForAnimations(page);
await panel.screenshot({ path: `${SHOTS}/03-hover-actions.png` });
});
@@ -218,8 +248,7 @@ test.describe("drafts screenshots", () => {
// Empty state: FileText icon + "No drafts" text
await expect(panel.getByText("No drafts")).toBeVisible({ timeout: 5_000 });
await page.waitForTimeout(200);
await waitForAnimations(page);
await panel.screenshot({ path: `${SHOTS}/04-empty-state.png` });
});
@@ -286,7 +315,7 @@ test.describe("drafts screenshots", () => {
// Confirm dialog body names the channel.
await expect(dialog.getByText(/general/i)).toBeVisible();
await page.waitForTimeout(200);
await waitForAnimations(page);
await panel.screenshot({
path: `${SHOTS}/05-thread-draft-send-dialog.png`,
});
@@ -320,7 +349,7 @@ test.describe("drafts screenshots", () => {
page,
}) => {
// Captures both badge placements for the PR screenshot:
// 1. The numeric badge on the inbox filter trigger button.
// 1. The status dot on the inbox filter trigger button.
// 2. The badge next to "Drafts" in the filter dropdown.
// Two active drafts are seeded so the count is 2.
await installMockBridge(page);
@@ -332,10 +361,14 @@ test.describe("drafts screenshots", () => {
timeout: 10_000,
});
// Badge should be visible on the filter trigger with count = 2.
// The trigger uses a compact dot while retaining the count accessibly.
const triggerBadge = page.getByTestId("inbox-draft-badge");
await expect(triggerBadge).toBeVisible({ timeout: 6_000 });
await expect(triggerBadge).toHaveText("2");
await expect(triggerBadge).toBeEmpty();
await expect(page.getByTestId("inbox-filter-trigger")).toHaveAttribute(
"aria-label",
"Filter inbox: All. 2 active drafts",
);
// Open the filter dropdown so the badge-option is visible too.
await page.getByTestId("inbox-filter-trigger").click();
@@ -343,7 +376,7 @@ test.describe("drafts screenshots", () => {
await expect(dropdownBadge).toBeVisible({ timeout: 4_000 });
await expect(dropdownBadge).toHaveText("2");
await page.waitForTimeout(200);
await waitForAnimations(page);
// Capture the full inbox header area including the open dropdown.
await page.getByTestId("home-inbox").screenshot({
@@ -406,7 +439,7 @@ test.describe("drafts screenshots", () => {
draftRow.getByRole("button", { name: "Delete draft" }),
).toBeVisible({ timeout: 4_000 });
await page.waitForTimeout(200);
await waitForAnimations(page);
await panel.screenshot({
path: `${SHOTS}/07-thread-deleted-state.png`,
@@ -0,0 +1,100 @@
import { expect, test } from "@playwright/test";
import { waitForAnimations } from "../helpers/animations";
import { installMockBridge } from "../helpers/bridge";
test.describe("home inbox chrome", () => {
test.use({ viewport: { width: 1280, height: 720 } });
test.beforeEach(async ({ page }) => {
await installMockBridge(page);
await page.goto("/");
await expect(page.getByTestId("home-inbox-list")).toBeVisible();
});
test("puts the filter on the left and options on the right", async ({
page,
}) => {
const filter = page.getByTestId("inbox-filter-trigger");
const options = page.getByTestId("inbox-options-trigger");
await expect(filter).toBeVisible();
await expect(filter).toContainText("All");
await expect(options).toBeVisible();
const [filterBox, optionsBox] = await Promise.all([
filter.boundingBox(),
options.boundingBox(),
]);
expect(filterBox).not.toBeNull();
expect(optionsBox).not.toBeNull();
expect(filterBox?.x ?? 0).toBeLessThan(optionsBox?.x ?? 0);
});
test("shares a blurred header backdrop across list and detail", async ({
page,
}) => {
await expect(page.getByTestId("home-inbox-detail")).toBeVisible();
const homeInbox = page.getByTestId("home-inbox");
const listScroller = page.getByTestId("home-inbox-list");
const detailScroller = page.getByTestId("home-inbox-detail-scroll");
const sharedBackdrop = page.getByTestId(
"home-inbox-shared-header-backdrop",
);
const [homeBox, backdropBox, listBox, detailBox, backdropFilter] =
await Promise.all([
homeInbox.boundingBox(),
sharedBackdrop.boundingBox(),
listScroller.boundingBox(),
detailScroller.boundingBox(),
sharedBackdrop.evaluate(
(element) => getComputedStyle(element).backdropFilter,
),
]);
expect(homeBox).not.toBeNull();
expect(backdropBox).not.toBeNull();
expect(listBox).not.toBeNull();
expect(detailBox).not.toBeNull();
expect(Math.round(backdropBox?.x ?? 0)).toBe(Math.round(homeBox?.x ?? 0));
expect(Math.round(backdropBox?.width ?? 0)).toBe(
Math.round(homeBox?.width ?? 0),
);
expect(Math.round(listBox?.y ?? 0)).toBe(Math.round(backdropBox?.y ?? 0));
expect(Math.round(detailBox?.y ?? 0)).toBe(Math.round(backdropBox?.y ?? 0));
expect(backdropFilter).not.toBe("none");
await waitForAnimations(page);
});
test("reserves the measured composer height and masks content behind it", async ({
page,
}) => {
const detailScroller = page.getByTestId("home-inbox-detail-scroll");
const composerOverlay = page.getByTestId(
"home-inbox-detail-composer-overlay",
);
await expect(composerOverlay).toBeVisible();
await expect
.poll(async () => {
const [paddingBottom, overlayBox] = await Promise.all([
detailScroller.evaluate((element) =>
Number.parseFloat(getComputedStyle(element).paddingBottom),
),
composerOverlay.boundingBox(),
]);
return Math.abs(paddingBottom - (overlayBox?.height ?? 0));
})
.toBeLessThanOrEqual(1);
const overlayMaskStyles = await composerOverlay.evaluate((element) => ({
gradient: getComputedStyle(element, "::before").backgroundImage,
solidBackground: getComputedStyle(element, "::after").backgroundColor,
}));
expect(overlayMaskStyles.gradient).not.toBe("none");
expect(overlayMaskStyles.solidBackground).not.toBe("rgba(0, 0, 0, 0)");
});
});
+12
View File
@@ -140,6 +140,18 @@ test("inbox reaction on a thread-reply mention persists after refetch", async ({
await expect(selectedMessage.getByLabel("Toggle ❤️ reaction")).toBeVisible();
await selectedMessage.hover();
const actionBar = page.getByTestId(`message-action-bar-${replyEvent.id}`);
const [actionBarBox, selectedMessageBox] = await Promise.all([
actionBar.boundingBox(),
selectedMessage.boundingBox(),
]);
expect(actionBarBox).not.toBeNull();
expect(selectedMessageBox).not.toBeNull();
if (!actionBarBox || !selectedMessageBox) {
throw new Error("Inbox message action bar bounds were unavailable.");
}
expect(actionBarBox.y).toBeGreaterThanOrEqual(selectedMessageBox.y);
await selectedMessage
.getByRole("button", { name: "React with :+1:" })
.click();
+43
View File
@@ -0,0 +1,43 @@
-- T1b push gate: skip push_match_queue enqueue entirely for communities with
-- no active, endpoint-enabled, unexpired push lease. In lease-less communities
-- (most of them) every durable message currently pays the full matcher cost
-- (enqueue + claim + lease scan + delete) to conclude "notify no one".
--
-- Correctness protocol (write-amp plan rev 3, [R2/R3]):
-- * The gate lives HERE, in the events trigger, so every durable producer is
-- covered — including internal paths that bypass live dispatch.
-- * Lost-wake race: a naive EXISTS check could read "no lease" while a lease
-- activation commits concurrently, silently dropping that user's wake with
-- no retry. Closed with a per-community advisory lock held to transaction
-- end: event inserts take the lock SHARED (concurrent with each other),
-- lease transitions that can make eligibility true take it EXCLUSIVE
-- (crates/buzz-db/src/push.rs: accept_lease_event and replace_lease).
-- The conflict forces a total order: either the event's check sees the
-- committed lease, or the activation strictly follows the event's commit —
-- in which case no lease existed when the event was accepted and no wake
-- was owed. The lease-activation backfill is product recovery coverage
-- only and is not part of this proof.
-- * Lock key domain 'buzz_push_gate:' is distinct from the audit lock
-- ('buzz_audit:') and both lease-address lock families.
CREATE OR REPLACE FUNCTION enqueue_push_match_job() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
-- Keep this allowlist identical to the relay's validated NIP-PL descriptor.
IF NEW.kind IN (7, 9, 1059, 40007, 46010) THEN
PERFORM pg_advisory_xact_lock_shared(
hashtextextended('buzz_push_gate:' || NEW.community_id::text, 0));
IF EXISTS (
SELECT 1 FROM push_leases
WHERE community_id = NEW.community_id
AND active
AND endpoint_enabled
AND expires_at > EXTRACT(EPOCH FROM now())::bigint
) THEN
INSERT INTO push_match_queue (community_id, event_id)
VALUES (NEW.community_id, NEW.id)
ON CONFLICT DO NOTHING;
END IF;
END IF;
RETURN NEW;
END
$$;
@@ -0,0 +1,58 @@
-- T1a repair: the 0022 trigger takes FOR UPDATE on the channel row before
-- testing ttl_seconds, so every durable message in a PERMANENT channel
-- serializes on that tuple at commit time (deferred trigger) — one hot
-- channel means fully serialized commits, each holding the lock across its
-- WAL flush. Observed live at 200 QPS: commit latency 0.07ms -> ~15ms,
-- non-CPU DB load ~9/vCPU with CPU under 45%.
--
-- Repair keeps 0022's stale-prefetch proof but moves the synchronization to
-- a per-channel advisory lock, shared on the hot path:
-- * Event insert: shared channel-key lock -> read ttl_seconds. NULL returns
-- with no tuple lock and no update; shared locks admit each other, so
-- permanent-channel commits proceed concurrently.
-- * Permanent->ephemeral (or TTL-change) transition (update_channel in
-- crates/buzz-db/src/channel.rs) takes the same key EXCLUSIVE before its
-- UPDATE. Either the transition commits first and the event's read sees
-- the TTL (and refreshes), or the event commits first and the
-- transition's own deadline reset is later than anything the event would
-- have written. No stale-NULL hole in either order.
-- * Ephemeral channels still run the conditional UPDATE; their row updates
-- serialize per channel, but only ephemeral channels pay that.
-- Lock key domain 'buzz_channel_ttl:' is distinct from 'buzz_push_gate:'
-- (migration 0023) and the audit/lease lock families. Lock order note: the
-- deferred trigger acquires this key at COMMIT, after any push-gate shared
-- lock taken during insert; no path acquires both domains exclusively.
CREATE OR REPLACE FUNCTION refresh_channel_ttl_after_event_insert() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
channel_ttl INTEGER;
BEGIN
-- Kind 9007 creates the channel and initializes its deadline itself.
IF NEW.channel_id IS NOT NULL AND NEW.kind <> 9007 THEN
BEGIN
PERFORM pg_advisory_xact_lock_shared(hashtextextended(
'buzz_channel_ttl:' || NEW.community_id::text || ':' || NEW.channel_id::text, 0));
SELECT ttl_seconds INTO channel_ttl
FROM channels
WHERE community_id = NEW.community_id AND id = NEW.channel_id;
IF channel_ttl IS NOT NULL THEN
UPDATE channels
SET ttl_deadline = clock_timestamp() + make_interval(secs => ttl_seconds)
WHERE community_id = NEW.community_id
AND id = NEW.channel_id
AND ttl_seconds IS NOT NULL
AND archived_at IS NULL
AND deleted_at IS NULL;
END IF;
EXCEPTION WHEN OTHERS THEN
-- Preserve the existing best-effort contract: a TTL refresh failure
-- must not reject an otherwise valid durable event.
RAISE WARNING 'channel TTL refresh failed for community %, channel %: %',
NEW.community_id, NEW.channel_id, SQLERRM;
END;
END IF;
RETURN NULL;
END
$$;
+64 -3
View File
@@ -818,6 +818,10 @@ CREATE INDEX push_match_queue_due
CREATE INDEX push_match_queue_recovery
ON push_match_queue (lease_until) WHERE state = 'matching';
-- T1b push gate (keep in sync with migrations/0023). Enqueue only when the
-- community has an active, endpoint-enabled, unexpired lease; the shared
-- advisory lock pairs with the exclusive lock taken by lease activations
-- (crates/buzz-db/src/push.rs) to close the lost-wake race.
CREATE FUNCTION enqueue_push_match_job() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
@@ -825,9 +829,19 @@ BEGIN
-- Centralizing it on the events table covers every durable producer,
-- including internal paths that bypass live dispatch.
IF NEW.kind IN (7, 9, 1059, 40007, 46010) THEN
INSERT INTO push_match_queue (community_id, event_id)
VALUES (NEW.community_id, NEW.id)
ON CONFLICT DO NOTHING;
PERFORM pg_advisory_xact_lock_shared(
hashtextextended('buzz_push_gate:' || NEW.community_id::text, 0));
IF EXISTS (
SELECT 1 FROM push_leases
WHERE community_id = NEW.community_id
AND active
AND endpoint_enabled
AND expires_at > EXTRACT(EPOCH FROM now())::bigint
) THEN
INSERT INTO push_match_queue (community_id, event_id)
VALUES (NEW.community_id, NEW.id)
ON CONFLICT DO NOTHING;
END IF;
END IF;
RETURN NEW;
END
@@ -837,6 +851,53 @@ CREATE TRIGGER events_enqueue_push_match
AFTER INSERT ON events
FOR EACH ROW EXECUTE FUNCTION enqueue_push_match_job();
-- Channel TTL refresh (keep in sync with migrations/0024). Runs deferred, in
-- the transaction that makes a channel-scoped event durable, so a TTL
-- transition committed while ingest was in flight is never missed. The
-- per-channel advisory lock is SHARED here — permanent-channel commits admit
-- each other — and taken EXCLUSIVE by TTL transitions (update_channel in
-- crates/buzz-db/src/channel.rs), which forces the same total order the
-- 0022 row lock provided without serializing the hot path.
CREATE FUNCTION refresh_channel_ttl_after_event_insert() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
channel_ttl INTEGER;
BEGIN
-- Kind 9007 creates the channel and initializes its deadline itself.
IF NEW.channel_id IS NOT NULL AND NEW.kind <> 9007 THEN
BEGIN
PERFORM pg_advisory_xact_lock_shared(hashtextextended(
'buzz_channel_ttl:' || NEW.community_id::text || ':' || NEW.channel_id::text, 0));
SELECT ttl_seconds INTO channel_ttl
FROM channels
WHERE community_id = NEW.community_id AND id = NEW.channel_id;
IF channel_ttl IS NOT NULL THEN
UPDATE channels
SET ttl_deadline = clock_timestamp() + make_interval(secs => ttl_seconds)
WHERE community_id = NEW.community_id
AND id = NEW.channel_id
AND ttl_seconds IS NOT NULL
AND archived_at IS NULL
AND deleted_at IS NULL;
END IF;
EXCEPTION WHEN OTHERS THEN
-- Preserve the existing best-effort contract: a TTL refresh failure
-- must not reject an otherwise valid durable event.
RAISE WARNING 'channel TTL refresh failed for community %, channel %: %',
NEW.community_id, NEW.channel_id, SQLERRM;
END;
END IF;
RETURN NULL;
END
$$;
CREATE CONSTRAINT TRIGGER events_refresh_channel_ttl
AFTER INSERT ON events
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION refresh_channel_ttl_after_event_insert();
-- Replica-fence floor guard (keep in sync with migrations/0021). A deferred
-- constraint trigger re-checks, inside COMMIT processing, that channel-bearing
-- event rows are no older than `buzz.created_at_floor` seconds before commit
+8
View File
@@ -19,6 +19,7 @@ BEGIN
-- triggers while attaching and rejects same-named child triggers
-- (both the push-match trigger and the replica-fence floor guard).
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p_past;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p_past;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p_past;
ALTER TABLE events ATTACH PARTITION events_p_past
FOR VALUES FROM (MINVALUE) TO ('2026-01-01');
@@ -30,6 +31,7 @@ BEGIN
AND inhrelid = 'events_p2026_01'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p2026_01;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p2026_01;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_01;
ALTER TABLE events ATTACH PARTITION events_p2026_01
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
@@ -41,6 +43,7 @@ BEGIN
AND inhrelid = 'events_p2026_02'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p2026_02;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p2026_02;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_02;
ALTER TABLE events ATTACH PARTITION events_p2026_02
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
@@ -52,6 +55,7 @@ BEGIN
AND inhrelid = 'events_p2026_03'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p2026_03;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p2026_03;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_03;
ALTER TABLE events ATTACH PARTITION events_p2026_03
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
@@ -63,6 +67,7 @@ BEGIN
AND inhrelid = 'events_p2026_04'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p2026_04;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p2026_04;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_04;
ALTER TABLE events ATTACH PARTITION events_p2026_04
FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');
@@ -74,6 +79,7 @@ BEGIN
AND inhrelid = 'events_p2026_05'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p2026_05;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p2026_05;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_05;
ALTER TABLE events ATTACH PARTITION events_p2026_05
FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
@@ -85,6 +91,7 @@ BEGIN
AND inhrelid = 'events_p2026_06'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p2026_06;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p2026_06;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_06;
ALTER TABLE events ATTACH PARTITION events_p2026_06
FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
@@ -96,6 +103,7 @@ BEGIN
AND inhrelid = 'events_p_future'::regclass
) THEN
DROP TRIGGER IF EXISTS events_enqueue_push_match ON events_p_future;
DROP TRIGGER IF EXISTS events_refresh_channel_ttl ON events_p_future;
DROP TRIGGER IF EXISTS events_created_at_floor ON events_p_future;
ALTER TABLE events ATTACH PARTITION events_p_future
FOR VALUES FROM ('2026-07-01') TO (MAXVALUE);