A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(app): gate single-source message hover behind an experiment (#2761)
Hampus128104564855
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.jsonindex 1f975e7d9..429cdb04d 100644--- a/fluxer_admin/openapi-admin.json+++ b/fluxer_admin/openapi-admin.json@@ -10563,6 +10563,7 @@"gateway_rollout": {"$ref": "#/components/schemas/GatewayRolloutConfigResponse"},"voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionConfigResponse"},"experiment_delivery": {"$ref": "#/components/schemas/ExperimentDeliveryConfigResponse"},+ "message_hover_tracking": {"$ref": "#/components/schemas/MessageHoverTrackingConfigResponse"},"registration": {"type": "object","properties": {@@ -10966,6 +10967,7 @@"gateway_rollout","voice_noise_suppression","experiment_delivery",+ "message_hover_tracking","registration","self_hosted","app_public",@@ -11103,6 +11105,10 @@"nullable": true,"allOf": [{"$ref": "#/components/schemas/ExperimentDeliveryConfigUpdateRequest"}]},+ "message_hover_tracking": {+ "nullable": true,+ "allOf": [{"$ref": "#/components/schemas/MessageHoverTrackingConfigUpdateRequest"}]+ },"registration": {"nullable": true,"type": "object",@@ -15159,6 +15165,24 @@"enum": ["open", "approval", "closed"],"type": "string"},+ "MessageHoverTrackingConfigUpdateRequest": {+ "type": "object",+ "properties": {+ "enabled": {"type": "boolean"},+ "rollout_basis_points": {"type": "integer", "minimum": 0, "maximum": 10000},+ "rollout_salt": {"type": "string", "minLength": 1, "maxLength": 64},+ "included_user_ids": {+ "maxItems": 1000,+ "type": "array",+ "items": {"type": "string", "pattern": "^\\d{1,20}$"}+ },+ "excluded_user_ids": {+ "maxItems": 1000,+ "type": "array",+ "items": {"type": "string", "pattern": "^\\d{1,20}$"}+ }+ }+ },"ExperimentDeliveryConfigUpdateRequest": {"type": "object","properties": {@@ -15223,6 +15247,36 @@"type": "string","enum": ["none", "standard", "gate", "speex", "rnnoise", "gtcrn", "deep_filter"]},+ "MessageHoverTrackingConfigResponse": {+ "type": "object",+ "properties": {+ "enabled": {"default": false, "type": "boolean"},+ "config_version": {"default": 0, "type": "integer", "minimum": 0, "maximum": 9007199254740991},+ "rollout_basis_points": {"default": 0, "type": "integer", "minimum": 0, "maximum": 10000},+ "rollout_salt": {"default": "message-hover-tracking-v1", "type": "string", "minLength": 1, "maxLength": 64},+ "included_user_ids": {+ "default": [],+ "maxItems": 1000,+ "type": "array",+ "items": {"type": "string", "pattern": "^\\d{1,20}$"}+ },+ "excluded_user_ids": {+ "default": [],+ "maxItems": 1000,+ "type": "array",+ "items": {"type": "string", "pattern": "^\\d{1,20}$"}+ }+ },+ "required": [+ "enabled",+ "config_version",+ "rollout_basis_points",+ "rollout_salt",+ "included_user_ids",+ "excluded_user_ids"+ ],+ "additionalProperties": false+ },"ExperimentDeliveryConfigResponse": {"type": "object","properties": {diff --git a/fluxer_admin/src/api/types/instance_config.rs b/fluxer_admin/src/api/types/instance_config.rsindex d60227fba..cc0958f44 100644--- a/fluxer_admin/src/api/types/instance_config.rs+++ b/fluxer_admin/src/api/types/instance_config.rs@@ -24,6 +24,8 @@ pub struct InstanceConfigResponse {pub voice_noise_suppression: VoiceNoiseSuppressionConfigResponse,#[serde(default)]pub experiment_delivery: ExperimentDeliveryConfigResponse,+ #[serde(default)]+ pub message_hover_tracking: MessageHoverTrackingConfigResponse,}#[derive(Clone, Debug, Deserialize, Serialize)]@@ -537,6 +539,44 @@ pub struct VoiceNoiseSuppressionConfigUpdateRequest {pub suppression_strength: Option<u32>,}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(default)]+pub struct MessageHoverTrackingConfigResponse {+ pub enabled: bool,+ pub config_version: u64,+ pub rollout_basis_points: u32,+ pub rollout_salt: String,+ pub included_user_ids: Vec<String>,+ pub excluded_user_ids: Vec<String>,+}++impl Default for MessageHoverTrackingConfigResponse {+ fn default() -> Self {+ Self {+ enabled: false,+ config_version: 0,+ rollout_basis_points: 0,+ rollout_salt: "message-hover-tracking-v1".to_owned(),+ included_user_ids: Vec::new(),+ excluded_user_ids: Vec::new(),+ }+ }+}++#[derive(Clone, Debug, Default, Serialize)]+pub struct MessageHoverTrackingConfigUpdateRequest {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub enabled: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rollout_basis_points: Option<u32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rollout_salt: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub included_user_ids: Option<Vec<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub excluded_user_ids: Option<Vec<String>>,+}+#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(default)]pub struct ExperimentDeliveryConfigResponse {@@ -654,6 +694,8 @@ pub struct InstanceConfigUpdateRequest {pub voice_noise_suppression: Option<VoiceNoiseSuppressionConfigUpdateRequest>,#[serde(skip_serializing_if = "Option::is_none")]pub experiment_delivery: Option<ExperimentDeliveryConfigUpdateRequest>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub message_hover_tracking: Option<MessageHoverTrackingConfigUpdateRequest>,}#[derive(Clone, Debug, Default, Serialize)]@@ -988,12 +1030,19 @@ mod tests {.expect("default noise config");let delivery = serde_json::from_value::<ExperimentDeliveryConfigResponse>(json!({})).expect("default delivery config");+ let hover = serde_json::from_value::<MessageHoverTrackingConfigResponse>(json!({}))+ .expect("default message hover tracking config");let noise = serde_json::to_value(noise).expect("serializable noise config");let delivery = serde_json::to_value(delivery).expect("serializable delivery config");+ let hover =+ serde_json::to_value(hover).expect("serializable message hover tracking config");let generated_noise: generated_types::VoiceNoiseSuppressionConfigResponse =serde_json::from_value(noise.clone()).expect("generated noise config contract");let generated_delivery: generated_types::ExperimentDeliveryConfigResponse =serde_json::from_value(delivery.clone()).expect("generated delivery config contract");+ let generated_hover: generated_types::MessageHoverTrackingConfigResponse =+ serde_json::from_value(hover.clone())+ .expect("generated message hover tracking config contract");assert_eq!(serde_json::to_value(generated_noise).expect("serializable generated noise config"),noise@@ -1003,9 +1052,15 @@ mod tests {.expect("serializable generated delivery config"),delivery);+ assert_eq!(+ serde_json::to_value(generated_hover)+ .expect("serializable generated message hover tracking config"),+ hover+ );for (name, value) in [("VoiceNoiseSuppressionConfigResponse", noise),("ExperimentDeliveryConfigResponse", delivery),+ ("MessageHoverTrackingConfigResponse", hover),] {for (field, value) in value.as_object().expect("config object") {assert_eq!(@@ -1016,6 +1071,29 @@ mod tests {}}+ #[test]+ fn message_hover_tracking_update_preserves_empty_lists_and_omitted_fields() {+ let update = MessageHoverTrackingConfigUpdateRequest {+ included_user_ids: Some(Vec::new()),+ excluded_user_ids: Some(Vec::new()),+ ..Default::default()+ };+ let value = serde_json::to_value(update).expect("serializable update");+ serde_json::from_value::<generated_types::MessageHoverTrackingConfigUpdateRequest>(+ value.clone(),+ )+ .expect("generated update contract");+ assert_eq!(+ value,+ json!({"included_user_ids": [], "excluded_user_ids": []})+ );+ assert_eq!(+ serde_json::to_value(MessageHoverTrackingConfigUpdateRequest::default())+ .expect("serializable update"),+ json!({})+ );+ }+#[test]fn noise_suppression_update_preserves_empty_lists_and_omitted_fields() {let update = VoiceNoiseSuppressionConfigUpdateRequest {diff --git a/fluxer_admin/src/routes/system_actions.rs b/fluxer_admin/src/routes/system_actions.rsindex 047f561ee..d86824c8a 100644--- a/fluxer_admin/src/routes/system_actions.rs+++ b/fluxer_admin/src/routes/system_actions.rs@@ -17,9 +17,9 @@ use crate::{InstanceMediaUpdateRequest, InstancePolicyUpdateRequest,InstanceRegistrationConfigUpdateRequest, InstanceServicesUpdateRequest,InstanceYoutubeIntegrationUpdateRequest, LimitConfigUpdateRequest, LimitRule,- LimitRuleFilters, NoiseSuppressionBackend, PremiumMode, RegistrationMode,- SsoConfigUpdateRequest, VOICE_NS_MAX_GUILD_OVERRIDES, VOICE_NS_MAX_TARGETED_USERS,- VoiceE2eeScope, VoiceNoiseSuppressionConfigUpdateRequest,+ LimitRuleFilters, MessageHoverTrackingConfigUpdateRequest, NoiseSuppressionBackend,+ PremiumMode, RegistrationMode, SsoConfigUpdateRequest, VOICE_NS_MAX_GUILD_OVERRIDES,+ VOICE_NS_MAX_TARGETED_USERS, VoiceE2eeScope, VoiceNoiseSuppressionConfigUpdateRequest,VoiceNoiseSuppressionGuildOverride,},},@@ -207,6 +207,10 @@ pub async fn instance_config_post(Ok(update) => instance_config_result(client.update_instance_config(&update).await),Err(message) => FlashData::error(message),},+ "update_message_hover_tracking" => match build_message_hover_tracking_update(&form) {+ Ok(update) => instance_config_result(client.update_instance_config(&update).await),+ Err(message) => FlashData::error(message),+ },"update_experiment_delivery" => match build_experiment_delivery_update(&form) {Ok(update) => instance_config_result(client.update_instance_config(&update).await),Err(message) => FlashData::error(message),@@ -447,10 +451,10 @@ fn build_gateway_rollout_update(form: &MultiValueForm) -> InstanceConfigUpdateRe}}-const VOICE_NS_ROLLOUT_BASIS_POINTS_MAX: u32 = 10_000;+const EXPERIMENT_ROLLOUT_BASIS_POINTS_MAX: u32 = 10_000;const VOICE_NS_SUPPRESSION_STRENGTH_MAX: u32 = 100;-const VOICE_NS_MAX_ROLLOUT_SALT_CHARS: usize = 64;-const VOICE_NS_MAX_SNOWFLAKE_LENGTH: usize = 20;+const EXPERIMENT_MAX_ROLLOUT_SALT_CHARS: usize = 64;+const EXPERIMENT_MAX_SNOWFLAKE_LENGTH: usize = 20;const EXPERIMENT_MIN_POLL_INTERVAL_SECONDS: u64 = 60;const EXPERIMENT_MAX_POLL_INTERVAL_SECONDS: u64 = 86_400;const EXPERIMENT_MAX_POLL_JITTER_PERCENT: u32 = 50;@@ -476,35 +480,36 @@ whereOk(Some(value))}-fn parse_voice_noise_suppression_rollout_salt(+fn parse_experiment_rollout_salt(form: &MultiValueForm,+ key: &str,) -> Result<Option<String>, String> {- let Some(raw) = form.first("voice_ns_rollout_salt") else {+ let Some(raw) = form.first(key) else {return Ok(None);};let salt = raw.trim();- if salt.is_empty() || salt.encode_utf16().count() > VOICE_NS_MAX_ROLLOUT_SALT_CHARS {+ if salt.is_empty() || salt.encode_utf16().count() > EXPERIMENT_MAX_ROLLOUT_SALT_CHARS {return Err(format!(- "Rollout salt must be between 1 and {VOICE_NS_MAX_ROLLOUT_SALT_CHARS} characters"+ "Rollout salt must be between 1 and {EXPERIMENT_MAX_ROLLOUT_SALT_CHARS} characters"));}Ok(Some(salt.to_owned()))}-fn is_voice_noise_suppression_snowflake(value: &str) -> bool {+fn is_experiment_snowflake(value: &str) -> bool {!value.is_empty()- && value.len() <= VOICE_NS_MAX_SNOWFLAKE_LENGTH+ && value.len() <= EXPERIMENT_MAX_SNOWFLAKE_LENGTH&& value.bytes().all(|byte| byte.is_ascii_digit())}-fn parse_voice_noise_suppression_user_ids(value: &str, label: &str) -> Result<Vec<String>, String> {+fn parse_experiment_user_ids(value: &str, label: &str) -> Result<Vec<String>, String> {let mut ids: Vec<String> = Vec::new();for (index, candidate) in value.split([',', '\n', '\r']).enumerate() {let candidate = candidate.trim();if candidate.is_empty() {continue;}- if !is_voice_noise_suppression_snowflake(candidate) {+ if !is_experiment_snowflake(candidate) {return Err(format!("{label} entry {} must contain 1 to 20 decimal digits",index + 1@@ -536,7 +541,7 @@ fn parse_voice_noise_suppression_guild_overrides(format!("Guild overrides line {line_number} must use guild_id=backend")})?;let guild_id = guild_id.trim();- if !is_voice_noise_suppression_snowflake(guild_id) {+ if !is_experiment_snowflake(guild_id) {return Err(format!("Guild overrides line {line_number} must use a guild ID with 1 to 20 decimal digits"));@@ -602,14 +607,14 @@ fn build_voice_noise_suppression_update("voice_ns_rollout_basis_points","Rollout basis points",0,- VOICE_NS_ROLLOUT_BASIS_POINTS_MAX,+ EXPERIMENT_ROLLOUT_BASIS_POINTS_MAX,)?,- rollout_salt: parse_voice_noise_suppression_rollout_salt(form)?,- included_user_ids: Some(parse_voice_noise_suppression_user_ids(+ rollout_salt: parse_experiment_rollout_salt(form, "voice_ns_rollout_salt")?,+ included_user_ids: Some(parse_experiment_user_ids(form.first("voice_ns_included_user_ids").unwrap_or_default(),"Included user IDs",)?),- excluded_user_ids: Some(parse_voice_noise_suppression_user_ids(+ excluded_user_ids: Some(parse_experiment_user_ids(form.first("voice_ns_excluded_user_ids").unwrap_or_default(),"Excluded user IDs",)?),@@ -629,6 +634,35 @@ fn build_voice_noise_suppression_update(})}+fn build_message_hover_tracking_update(+ form: &MultiValueForm,+) -> Result<InstanceConfigUpdateRequest, String> {+ Ok(InstanceConfigUpdateRequest {+ message_hover_tracking: Some(MessageHoverTrackingConfigUpdateRequest {+ enabled: Some(form.bool_value("message_hover_enabled")),+ rollout_basis_points: parse_form_number(+ form,+ "message_hover_rollout_basis_points",+ "Rollout basis points",+ 0,+ EXPERIMENT_ROLLOUT_BASIS_POINTS_MAX,+ )?,+ rollout_salt: parse_experiment_rollout_salt(form, "message_hover_rollout_salt")?,+ included_user_ids: Some(parse_experiment_user_ids(+ form.first("message_hover_included_user_ids")+ .unwrap_or_default(),+ "Included user IDs",+ )?),+ excluded_user_ids: Some(parse_experiment_user_ids(+ form.first("message_hover_excluded_user_ids")+ .unwrap_or_default(),+ "Excluded user IDs",+ )?),+ }),+ ..Default::default()+ })+}+fn build_experiment_delivery_update(form: &MultiValueForm,) -> Result<InstanceConfigUpdateRequest, String> {@@ -1305,9 +1339,9 @@ mod tests {}#[test]- fn parse_voice_noise_suppression_user_ids_splits_newlines_and_commas() {+ fn parse_experiment_user_ids_splits_newlines_and_commas() {assert_eq!(- parse_voice_noise_suppression_user_ids(" 1 ,2\n3\r\n 4 ,, 5 ", "Included user IDs")+ parse_experiment_user_ids(" 1 ,2\n3\r\n 4 ,, 5 ", "Included user IDs").expect("valid IDs"),vec!["1".to_owned(),@@ -1320,16 +1354,15 @@ mod tests {}#[test]- fn parse_voice_noise_suppression_user_ids_dedupes_preserving_order() {+ fn parse_experiment_user_ids_dedupes_preserving_order() {assert_eq!(- parse_voice_noise_suppression_user_ids("20,10,20,10,30", "Included user IDs")- .expect("valid IDs"),+ parse_experiment_user_ids("20,10,20,10,30", "Included user IDs").expect("valid IDs"),vec!["20".to_owned(), "10".to_owned(), "30".to_owned()]);}#[test]- fn parse_voice_noise_suppression_user_ids_rejects_non_digit_and_overlong_values() {+ fn parse_experiment_user_ids_rejects_non_digit_and_overlong_values() {for value in ["abc","12a",@@ -1339,11 +1372,8 @@ mod tests {"<script>",] {assert_eq!(- parse_voice_noise_suppression_user_ids(- &format!("123,{value}"),- "Included user IDs"- )- .expect_err("invalid ID"),+ parse_experiment_user_ids(&format!("123,{value}"), "Included user IDs")+ .expect_err("invalid ID"),"Included user IDs entry 2 must contain 1 to 20 decimal digits","{value}");@@ -1351,18 +1381,17 @@ mod tests {}#[test]- fn parse_voice_noise_suppression_user_ids_rejects_exceeding_the_cap() {+ fn parse_experiment_user_ids_rejects_exceeding_the_cap() {let value = (0..VOICE_NS_MAX_TARGETED_USERS).map(|index| index.to_string()).collect::<Vec<_>>().join("\n");- let ids =- parse_voice_noise_suppression_user_ids(&format!("{value}\n999"), "Included user IDs")- .expect("valid IDs at cap");+ let ids = parse_experiment_user_ids(&format!("{value}\n999"), "Included user IDs")+ .expect("valid IDs at cap");assert_eq!(ids.len(), VOICE_NS_MAX_TARGETED_USERS);assert_eq!(ids.last(), Some(&"999".to_owned()));assert_eq!(- parse_voice_noise_suppression_user_ids(&format!("{value}\n1000"), "Included user IDs")+ parse_experiment_user_ids(&format!("{value}\n1000"), "Included user IDs").expect_err("too many IDs"),"Included user IDs must contain at most 1000 unique IDs");diff --git a/fluxer_admin/src/templates/pages/instance_config.rs b/fluxer_admin/src/templates/pages/instance_config.rsindex 19992bba8..d03aca97c 100644--- a/fluxer_admin/src/templates/pages/instance_config.rs+++ b/fluxer_admin/src/templates/pages/instance_config.rs@@ -5,9 +5,9 @@ use crate::{AppPublicConfigResponse, ExperimentDeliveryConfigResponse, GatewayRolloutConfigResponse,InstanceConfigResponse, InstanceIntegrationsResponse, InstanceMediaResponse,InstancePolicyResponse, InstanceRegistrationResponse, LimitConfigResponse,- NoiseSuppressionBackend, PendingRegistrationResponse, RegistrationUrlResponse,- SsoConfigResponse, VOICE_NS_MAX_GUILD_OVERRIDES, VOICE_NS_MAX_TARGETED_USERS,- VoiceNoiseSuppressionConfigResponse,+ MessageHoverTrackingConfigResponse, NoiseSuppressionBackend, PendingRegistrationResponse,+ RegistrationUrlResponse, SsoConfigResponse, VOICE_NS_MAX_GUILD_OVERRIDES,+ VOICE_NS_MAX_TARGETED_USERS, VoiceNoiseSuppressionConfigResponse,},config::AdminConfig,middleware::auth::AuthContext,@@ -148,6 +148,7 @@ pub fn instance_config_page(html! {(gateway_rollout_section(base, csrf_token, &instance_config.gateway_rollout))(voice_noise_suppression_section(base, csrf_token, &instance_config.voice_noise_suppression))+ (message_hover_tracking_section(base, csrf_token, &instance_config.message_hover_tracking))(experiment_delivery_section(base, csrf_token, &instance_config.experiment_delivery))@if let Some(limit_config) = limit_config {(limit_config_section(base, limit_config))@@ -1175,6 +1176,110 @@ fn voice_noise_suppression_section()}+fn message_hover_tracking_section(+ base: &str,+ csrf_token: &str,+ message_hover_tracking: &MessageHoverTrackingConfigResponse,+) -> Markup {+ let status = if message_hover_tracking.enabled {+ ("Live", BadgeVariant::Success)+ } else {+ ("Inert", BadgeVariant::Default)+ };+ let included_user_ids = message_hover_tracking.included_user_ids.join("\n");+ let excluded_user_ids = message_hover_tracking.excluded_user_ids.join("\n");+ section_card_with_description(+ "Message Hover Tracking",+ "Picks which message hover implementation targeted clients run in the message list. A \+ targeted client resolves the hovered message from one shared pointer oracle and drives \+ the message action bar from that state. While the master switch below is off every \+ client keeps the per-row implementation it ships with, whatever the rest of these \+ fields say.",+ html! {+ form method="post" action={(base) "/instance-config?action=update_message_hover_tracking"} {+ (csrf_input(csrf_token))+ div class="space-y-6" {+ div class="flex flex-wrap items-center gap-2" {+ h3 class="text-sm font-semibold text-neutral-900" { "Master switch" }+ (badge(status.0, status.1))+ span class="text-xs text-neutral-500" {+ "Config version " (message_hover_tracking.config_version)+ }+ }+ (checkbox(+ "message_hover_enabled",+ "true",+ "Serve message hover tracking assignments to clients",+ message_hover_tracking.enabled,+ true,+ ))+ p class="text-xs text-neutral-500" {+ "Off is the safe state. With this unchecked every client is told the \+ rollout is inert and keeps its current hover behavior, so the rollout \+ and targeting fields below have no effect at all."+ }++ h3 class="text-sm font-semibold text-neutral-900" { "Rollout" }+ (number_field(+ "message_hover_rollout_basis_points",+ "Rollout (basis points)",+ &message_hover_tracking.rollout_basis_points.to_string(),+ Some(0), Some(10000), "1",+ Some("Share of users bucketed into the canary, in basis points: 0 is nobody, 100 is 1%, 10000 is everybody."),+ ))+ div class="flex flex-col gap-2" {+ (text_input(+ "message_hover_rollout_salt",+ "Rollout Salt",+ &message_hover_tracking.rollout_salt,+ "message-hover-tracking-v1",+ ))+ p class="text-xs text-neutral-500" {+ "Seeds the bucketing hash. Changing it reshuffles which users fall \+ inside the percentage above. Leave it alone to keep the current \+ cohort stable."+ }+ }+ div class="flex flex-col gap-2" {+ (textarea_input(+ "message_hover_included_user_ids",+ "Always-on User IDs",+ "1500000000000000001\n1500000000000000002",+ &included_user_ids,+ 4,+ false,+ ))+ p class="text-xs text-neutral-500" {+ "One snowflake per line, or comma separated. These users are targeted \+ regardless of the percentage above. IDs must contain 1 to 20 decimal \+ digits. Invalid entries prevent the save; blank entries and duplicate \+ IDs are ignored."+ }+ }+ div class="flex flex-col gap-2" {+ (textarea_input(+ "message_hover_excluded_user_ids",+ "Never-on User IDs",+ "1500000000000000003\n1500000000000000004",+ &excluded_user_ids,+ 4,+ false,+ ))+ p class="text-xs text-neutral-500" {+ "Same format. Exclusion wins over both the always-on list and the \+ percentage, so this is the per-user kill switch."+ }+ }++ (form_actions(html! {+ (submit_button("Save Message Hover Tracking Configuration"))+ }))+ }+ }+ },+ )+}+fn experiment_delivery_section(base: &str,csrf_token: &str,diff --git a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.tsindex f3e3c21a5..94320bbfd 100644--- a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts@@ -32,6 +32,7 @@ import {GatewayRolloutConfigSchema} from '@fluxer/schema/src/domains/admin/Gatewimport {VoiceNoiseSuppressionConfigSchema} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';import {UserIdParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';import {ExperimentDeliveryConfigSchema} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {MessageHoverTrackingConfigSchema} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import type {InstanceBranding} from '@fluxer/schema/src/domains/instance/InstanceSchemas';import {SmtpEmailProvider} from '@pkgs/email/src/SmtpEmailProvider';import type {Context} from 'hono';@@ -58,6 +59,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {gatewayRollout,voiceNoiseSuppression,experimentDelivery,+ messageHoverTracking,registrationConfig,registrationUrls,pendingRegistrations,@@ -66,6 +68,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {instanceConfigRepository.getGatewayRolloutConfig(),instanceConfigRepository.getVoiceNoiseSuppressionConfig(),instanceConfigRepository.getExperimentDeliveryConfig(),+ instanceConfigRepository.getMessageHoverTrackingConfig(),instanceConfigRepository.getRegistrationConfig(),instanceConfigRepository.getRegistrationUrlsForAdmin(),instanceConfigRepository.getPendingRegistrations(),@@ -97,6 +100,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {gateway_rollout: gatewayRollout,voice_noise_suppression: voiceNoiseSuppression,experiment_delivery: experimentDelivery,+ message_hover_tracking: messageHoverTracking,registration: {...registrationConfig,urls: registrationUrls,@@ -240,6 +244,18 @@ export function InstanceConfigAdminController(app: HonoApp) {await instanceConfigRepository.setVoiceNoiseSuppressionConfig(validated);}}+ if (data.message_hover_tracking) {+ const patch = omitUndefinedFields(data.message_hover_tracking);+ if (Object.keys(patch).length > 0) {+ const currentMessageHoverTracking = await instanceConfigRepository.getMessageHoverTrackingConfig();+ const validated = MessageHoverTrackingConfigSchema.parse({+ ...currentMessageHoverTracking,+ ...patch,+ config_version: currentMessageHoverTracking.config_version + 1,+ });+ await instanceConfigRepository.setMessageHoverTrackingConfig(validated);+ }+ }if (data.experiment_delivery) {const currentExperimentDelivery = await instanceConfigRepository.getExperimentDeliveryConfig();const validated = ExperimentDeliveryConfigSchema.parse({diff --git a/fluxer_api/src/api/experiment/ExperimentController.ts b/fluxer_api/src/api/experiment/ExperimentController.tsindex 5b91668cb..01b198fcd 100644--- a/fluxer_api/src/api/experiment/ExperimentController.ts+++ b/fluxer_api/src/api/experiment/ExperimentController.ts@@ -10,6 +10,7 @@ import {entityTagMatches} from '@app/api/utils/EntityTag';import {Headers as HttpHeaders} from '@fluxer/constants/src/Headers';import {resolveVoiceNoiseSuppressionAssignment} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';import {ExperimentAssignmentsResponse} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {resolveMessageHoverTrackingAssignment} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';export function ExperimentController(app: HonoApp) {app.get(@@ -28,15 +29,18 @@ export function ExperimentController(app: HonoApp) {}),async (ctx) => {const instanceConfigRepository = ctx.get('instanceConfigRepository');- const [delivery, voiceConfig] = await Promise.all([+ const [delivery, voiceConfig, messageHoverTrackingConfig] = await Promise.all([instanceConfigRepository.getExperimentDeliveryConfig(),instanceConfigRepository.getVoiceNoiseSuppressionConfig(),+ instanceConfigRepository.getMessageHoverTrackingConfig(),]);+ const userId = ctx.get('user').id.toString();const body: ExperimentAssignmentsResponse = {poll_interval_seconds: delivery.poll_interval_seconds,poll_jitter_percent: delivery.poll_jitter_percent,assignments: {- voice_noise_suppression: resolveVoiceNoiseSuppressionAssignment(voiceConfig, ctx.get('user').id.toString()),+ voice_noise_suppression: resolveVoiceNoiseSuppressionAssignment(voiceConfig, userId),+ message_hover_tracking: resolveMessageHoverTrackingAssignment(messageHoverTrackingConfig, userId),},};const etag = `"${createHash('sha256').update(JSON.stringify(body)).digest('hex')}"`;diff --git a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts b/fluxer_api/src/api/experiment/tests/ExperimentController.test.tsindex b8b5d8a48..379e3019f 100644--- a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts+++ b/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts@@ -15,8 +15,13 @@ import {DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,type ExperimentAssignmentsResponse,type ExperimentDeliveryConfigResponse,+ readMessageHoverTrackingAssignment,readVoiceNoiseSuppressionAssignment,} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {+ DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';const NOT_MODIFIED = 304;@@ -49,7 +54,10 @@ describe('GET /experiments', () => {expect(body).toEqual({poll_interval_seconds: DEFAULT_EXPERIMENT_POLL_INTERVAL_SECONDS,poll_jitter_percent: DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,- assignments: {voice_noise_suppression: INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT},+ assignments: {+ voice_noise_suppression: INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,+ message_hover_tracking: INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT,+ },});});@@ -80,6 +88,66 @@ describe('GET /experiments', () => {expect(readVoiceNoiseSuppressionAssignment(body).enabled).toBe(false);});+ it('populates the message hover tracking key even when the rollout is disabled', async () => {+ const account = await createTestAccount(harness);++ const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();++ expect(Object.hasOwn(body.assignments, 'message_hover_tracking')).toBe(true);+ expect(readMessageHoverTrackingAssignment(body)).toEqual(INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT);+ });++ it('targets an allowlisted account for message hover tracking', async () => {+ const account = await createTestAccount(harness);+ await getInstanceConfigRepository().setMessageHoverTrackingConfig({+ ...DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ enabled: true,+ config_version: 4,+ included_user_ids: [account.userId],+ });++ const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();++ expect(readMessageHoverTrackingAssignment(body)).toEqual({+ enabled: true,+ config_version: 4,+ user_targeted: true,+ source: 'user_rule',+ });+ });++ it('leaves an account outside a zero-width message hover tracking rollout', async () => {+ const account = await createTestAccount(harness);+ await getInstanceConfigRepository().setMessageHoverTrackingConfig({+ ...DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ enabled: true,+ config_version: 2,+ });++ const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();++ expect(readMessageHoverTrackingAssignment(body)).toEqual({+ enabled: true,+ config_version: 2,+ user_targeted: false,+ source: null,+ });+ });++ it('resolves the two experiments independently', async () => {+ const account = await createTestAccount(harness);+ await getInstanceConfigRepository().setMessageHoverTrackingConfig({+ ...DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ enabled: true,+ rollout_basis_points: 10000,+ });++ const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();++ expect(readMessageHoverTrackingAssignment(body).user_targeted).toBe(true);+ expect(readVoiceNoiseSuppressionAssignment(body).enabled).toBe(false);+ });+it('serves the delivery cadence from the delivery config and not from the voice config', async () => {const account = await createTestAccount(harness);await getInstanceConfigRepository().setExperimentDeliveryConfig({diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.test.tsindex 4e863259f..97124827c 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts@@ -17,9 +17,14 @@ import {DEFAULT_EXPERIMENT_DELIVERY_CONFIG,type ExperimentDeliveryConfig,} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {+ DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ type MessageHoverTrackingConfig,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {afterEach, describe, expect, it, vi} from 'vitest';const VOICE_NOISE_SUPPRESSION_CONFIG_KEY = 'voice_noise_suppression_config';+const MESSAGE_HOVER_TRACKING_CONFIG_KEY = 'message_hover_tracking_config';const EXPERIMENT_DELIVERY_CONFIG_KEY = 'experiment_delivery_config';const APP_PUBLIC_CONFIG_KEY = 'app_public_config';const INSTANCE_POLICY_CONFIG_KEY = 'instance_policy_config';@@ -312,6 +317,51 @@ describe('InstanceConfigRepository', () => {await expect(repository.getVoiceNoiseSuppressionConfig()).resolves.toEqual(config);});+ it('returns the default message hover tracking config when the key is absent', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await expect(repository.getMessageHoverTrackingConfig()).resolves.toEqual(DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG);+ });++ it.each([+ {name: 'unparseable text', stored: 'not-json'},+ {name: 'a json array', stored: '[]'},+ {name: 'out-of-range values', stored: '{"rollout_basis_points":99999}'},+ {name: 'a target that is not a snowflake', stored: '{"included_user_ids":["nope"]}'},+ ])('falls back to the default message hover tracking config for $name', async ({stored}) => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig(MESSAGE_HOVER_TRACKING_CONFIG_KEY, stored);++ await expect(repository.getMessageHoverTrackingConfig()).resolves.toEqual(DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG);+ });++ it('round-trips a stored message hover tracking config', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ const config: MessageHoverTrackingConfig = {+ ...DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ enabled: true,+ config_version: 5,+ rollout_basis_points: 2500,+ rollout_salt: 'message-hover-tracking-v2',+ included_user_ids: ['1400000000000000001'],+ excluded_user_ids: ['1400000000000000002'],+ };+ await repository.setMessageHoverTrackingConfig(config);++ await expect(repository.getMessageHoverTrackingConfig()).resolves.toEqual(config);+ });+it('fills newly added voice noise suppression fields from the schema defaults', async () => {const executor = new CountingInMemoryCassandraQueryExecutor();setCassandraQueryExecutorForTesting(executor);diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.tsindex 6843b603e..c8acadf20 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.ts@@ -36,6 +36,10 @@ import {type ExperimentDeliveryConfig,ExperimentDeliveryConfigSchema,} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {+ type MessageHoverTrackingConfig,+ MessageHoverTrackingConfigSchema,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {type InstanceAppPublic,InstanceAppPublicSchema,@@ -55,6 +59,7 @@ import {z} from 'zod';const GATEWAY_ROLLOUT_CONFIG_KEY = 'gateway_rollout_config';const VOICE_NOISE_SUPPRESSION_CONFIG_KEY = 'voice_noise_suppression_config';const EXPERIMENT_DELIVERY_CONFIG_KEY = 'experiment_delivery_config';+const MESSAGE_HOVER_TRACKING_CONFIG_KEY = 'message_hover_tracking_config';const REGISTRATION_CONFIG_KEY = 'registration_config';const REGISTRATION_URLS_KEY = 'registration_urls';const REGISTRATION_PENDING_APPROVALS_KEY = 'registration_pending_approvals';@@ -338,6 +343,7 @@ type StoredConfigSection =| 'gateway rollout'| 'voice noise suppression'| 'experiment delivery'+ | 'message hover tracking'| 'instance policy'| 'integrations'| 'media'@@ -479,6 +485,10 @@ function parseStoredExperimentDeliveryConfig(raw: string | null): ExperimentDelireturn parseStoredConfigOrDefault(ExperimentDeliveryConfigSchema, raw, 'experiment delivery');}+function parseStoredMessageHoverTrackingConfig(raw: string | null): MessageHoverTrackingConfig {+ return parseStoredConfigOrDefault(MessageHoverTrackingConfigSchema, raw, 'message hover tracking');+}+function validateStoredCollection<T>(schema: z.ZodType<T>, value: unknown, section: StoredConfigSection): Array<T> {if (!Array.isArray(value)) {throw new Error(`Stored ${section} configuration must be an array`);@@ -998,6 +1008,7 @@ export class InstanceConfigRepository {);parseStoredVoiceNoiseSuppressionConfig(snapshot.get(VOICE_NOISE_SUPPRESSION_CONFIG_KEY) ?? null);parseStoredExperimentDeliveryConfig(snapshot.get(EXPERIMENT_DELIVERY_CONFIG_KEY) ?? null);+ parseStoredMessageHoverTrackingConfig(snapshot.get(MESSAGE_HOVER_TRACKING_CONFIG_KEY) ?? null);const policy = parseStoredInstancePolicyConfig(snapshot.get(INSTANCE_POLICY_CONFIG_KEY) ?? null);checkStoredConfig('registration', () =>parseStoredRegistrationConfig(snapshot.get(REGISTRATION_CONFIG_KEY) ?? null),@@ -1083,6 +1094,16 @@ export class InstanceConfigRepository {return parseStoredExperimentDeliveryConfig(raw);}+ async getMessageHoverTrackingConfig(): Promise<MessageHoverTrackingConfig> {+ const raw = await this.getConfig(MESSAGE_HOVER_TRACKING_CONFIG_KEY);+ return parseStoredMessageHoverTrackingConfig(raw);+ }++ async setMessageHoverTrackingConfig(config: MessageHoverTrackingConfig): Promise<void> {+ const validated = validateStoredConfig(MessageHoverTrackingConfigSchema, config, 'message hover tracking');+ await this.setConfig(MESSAGE_HOVER_TRACKING_CONFIG_KEY, JSON.stringify(validated));+ }+async setExperimentDeliveryConfig(config: ExperimentDeliveryConfig): Promise<void> {const validated = validateStoredConfig(ExperimentDeliveryConfigSchema, config, 'experiment delivery');await this.setConfig(EXPERIMENT_DELIVERY_CONFIG_KEY, JSON.stringify(validated));diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.jsonindex c755e1d24..c302f5491 100644--- a/fluxer_api/src/api/openapi/openapi.json+++ b/fluxer_api/src/api/openapi/openapi.json@@ -28258,7 +28258,8 @@"assignments": {"type": "object","properties": {- "voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionAssignmentResponse"}+ "voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionAssignmentResponse"},+ "message_hover_tracking": {"$ref": "#/components/schemas/MessageHoverTrackingAssignmentResponse"}},"additionalProperties": false}@@ -31996,6 +31997,17 @@"additionalProperties": false},"DonationCurrency": {"type": "string", "enum": ["usd", "eur", "brl", "inr", "pln", "try"]},+ "MessageHoverTrackingAssignmentResponse": {+ "type": "object",+ "properties": {+ "enabled": {"type": "boolean"},+ "config_version": {"type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991},+ "user_targeted": {"type": "boolean"},+ "source": {"anyOf": [{"type": "string", "enum": ["user_rule", "canary"]}, {"type": "null"}]}+ },+ "required": ["enabled", "config_version", "user_targeted", "source"],+ "additionalProperties": false+ },"VoiceNoiseSuppressionAssignmentResponse": {"type": "object","properties": {diff --git a/fluxer_app/src/app/App.tsx b/fluxer_app/src/app/App.tsxindex 86845a99a..717aeef92 100644--- a/fluxer_app/src/app/App.tsx+++ b/fluxer_app/src/app/App.tsx@@ -21,6 +21,9 @@ import {useServiceWorkerBadge} from '@app/features/app/hooks/useServiceWorkerBadimport {useTabKeyFocusGuard} from '@app/features/app/hooks/useTabKeyFocusGuard';import {type LayoutVariant, LayoutVariantProvider} from '@app/features/app/state/LayoutVariantContext';import RuntimeCrash from '@app/features/app/state/RuntimeCrash';+import MessageHoverTrackingRollout, {+ MESSAGE_HOVER_TRACKING_EXPERIMENT_CLASS,+} from '@app/features/channel/state/MessageHoverTrackingRollout';import {showMyselfTypingHelper} from '@app/features/devtools/utils/ShowMyselfTypingHelper';import GatewayConnection from '@app/features/gateway/transport/GatewayConnection';import {AppI18nProvider} from '@app/features/i18n/components/AppI18nProvider';@@ -154,6 +157,7 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {useDocumentClassToggle('reduced-motion', reducedMotion);useDocumentClassToggle('mobile-layout', MobileLayout.platformMobileDetected || MobileLayout.enabled);useDocumentClassToggle(UNFOCUSED_FULLY_INTERACTIVE_CLASS, stayInteractiveWhenUnfocused);+ useDocumentClassToggle(MESSAGE_HOVER_TRACKING_EXPERIMENT_CLASS, MessageHoverTrackingRollout.enabled);useDesktopAllowTransparency(isNative);useWindowEventListeners({preventDocumentScroll: !isNative});useRemScaleTracking();diff --git a/fluxer_app/src/features/app/hooks/useContextMenuHoverState.ts b/fluxer_app/src/features/app/hooks/useContextMenuHoverState.tsindex bfe0cae32..fbf248057 100644--- a/fluxer_app/src/features/app/hooks/useContextMenuHoverState.ts+++ b/fluxer_app/src/features/app/hooks/useContextMenuHoverState.ts@@ -2,12 +2,11 @@import ContextMenu, {isContextMenuNodeTarget} from '@app/features/ui/state/ContextMenu';import {autorun} from 'mobx';-import {type RefObject, useEffect, useState} from 'react';+import {type RefObject, useEffect, useRef, useState} from 'react';interface ContextMenuHoverSubscriber {readonly elementRef: RefObject<HTMLElement | null>;readonly setContextMenuOpen: (contextMenuOpen: boolean) => void;- contextMenuOpen: boolean;}const contextMenuHoverSubscribers = new Set<ContextMenuHoverSubscriber>();@@ -28,10 +27,7 @@ function syncContextMenuHoverSubscribers(): void {const chain = resolveContextMenuTargetChain();for (const subscriber of Array.from(contextMenuHoverSubscribers)) {const element = subscriber.elementRef.current;- const contextMenuOpen = chain != null && element != null && chain.has(element);- if (subscriber.contextMenuOpen === contextMenuOpen) continue;- subscriber.contextMenuOpen = contextMenuOpen;- subscriber.setContextMenuOpen(contextMenuOpen);+ subscriber.setContextMenuOpen(chain != null && element != null && chain.has(element));}}@@ -52,12 +48,22 @@ function subscribeContextMenuHover(subscriber: ContextMenuHoverSubscriber): () =export function useContextMenuHoverState(elementRef: RefObject<HTMLElement | null>, enabled: boolean = true): boolean {const [contextMenuOpen, setContextMenuOpen] = useState(false);+ const publishedContextMenuOpenRef = useRef(false);useEffect(() => {+ const publishContextMenuOpen = (nextContextMenuOpen: boolean) => {+ if (publishedContextMenuOpenRef.current === nextContextMenuOpen) return;+ publishedContextMenuOpenRef.current = nextContextMenuOpen;+ setContextMenuOpen(nextContextMenuOpen);+ };if (!enabled) {- setContextMenuOpen(false);+ publishContextMenuOpen(false);return;}- return subscribeContextMenuHover({elementRef, setContextMenuOpen, contextMenuOpen: false});+ const unsubscribe = subscribeContextMenuHover({elementRef, setContextMenuOpen: publishContextMenuOpen});+ return () => {+ unsubscribe();+ publishContextMenuOpen(false);+ };}, [elementRef, enabled]);return contextMenuOpen;}diff --git a/fluxer_app/src/features/channel/components/ChannelMessage.tsx b/fluxer_app/src/features/channel/components/ChannelMessage.tsxindex 512691304..db2ff8dfe 100644--- a/fluxer_app/src/features/channel/components/ChannelMessage.tsx+++ b/fluxer_app/src/features/channel/components/ChannelMessage.tsx@@ -6,6 +6,7 @@ import {isMediaOnlyEmbed} from '@app/features/channel/components/embeds/EmbedRenimport {MessageActionBar, MessageActionBarCore} from '@app/features/channel/components/MessageActionBar';import {MessageActionBottomSheet} from '@app/features/channel/components/MessageActionBottomSheet';import {requestDeleteMessage} from '@app/features/channel/components/MessageActionUtils';+import {useMessageHoverState} from '@app/features/channel/components/MessageHoverState';import {MessageViewContextProvider} from '@app/features/channel/components/MessageViewContext';import type {Channel} from '@app/features/channel/models/Channel';import DeveloperOptions from '@app/features/devtools/state/DeveloperOptions';@@ -19,7 +20,6 @@ import {getMessageComponent} from '@app/features/messaging/utils/MessageComponenimport {renderAstToPlaintext} from '@app/features/messaging/utils/markdown/Plaintext';import {NodeType} from '@app/features/messaging/utils/markdown/parser/Enums';import {SystemMessageUtils} from '@app/features/messaging/utils/SystemMessageUtils';-import {subscribeWindowFocus} from '@app/features/platform/utils/WindowFocusBroadcast';import * as ReadStateCommands from '@app/features/read_state/commands/ReadStateCommands';import styles from '@app/features/theme/styles/Message.module.css';import {MessageContextMenu} from '@app/features/ui/action_menu/MessageContextMenu';@@ -38,7 +38,7 @@ import {useLingui} from '@lingui/react/macro';import {clsx} from 'clsx';import {observer} from 'mobx-react-lite';import type React from 'react';-import {useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';const ATTACHMENT_DESCRIPTOR = msg({message: 'attachment',@@ -164,149 +164,6 @@ const truncateAriaLabelText = (text: string): string => {}return `${normalized.slice(0, MAX_ARIA_MESSAGE_TEXT_LENGTH - 1).trimEnd()}...`;};-const isPointInsideMessageTree = (messageElement: HTMLElement, point: {x: number; y: number}): boolean => {- const target = messageElement.ownerDocument.elementFromPoint(point.x, point.y);- return Boolean(target && messageElement.contains(target));-};-const HOVER_SCROLL_IDLE_MS = 150;-let lastPointerPosition: {x: number; y: number} | null = null;-let pointerPositionNotificationFrame: number | null = null;-let pointerPositionSubscriptionCount = 0;-let hoverInvalidationSubscriptionCount = 0;-let pointerHoverSuspendedByScroll = false;-let pointerHoverScrollIdleTimer: ReturnType<typeof setTimeout> | null = null;-const pointerPositionListeners = new Set<() => void>();-const hoverInvalidationListeners = new Set<() => void>();-const notifyPointerPositionListeners = (): void => {- for (const listener of Array.from(pointerPositionListeners)) {- listener();- }-};-const notifyHoverInvalidationListeners = (): void => {- for (const listener of Array.from(hoverInvalidationListeners)) {- listener();- }-};-const clearPointerHoverScrollIdleTimer = (): void => {- if (pointerHoverScrollIdleTimer == null) {- return;- }- clearTimeout(pointerHoverScrollIdleTimer);- pointerHoverScrollIdleTimer = null;-};-const resumePointerHoverAfterScroll = (): void => {- clearPointerHoverScrollIdleTimer();- if (!pointerHoverSuspendedByScroll) {- return;- }- pointerHoverSuspendedByScroll = false;- notifyHoverInvalidationListeners();-};-const suspendPointerHoverForScroll = (): void => {- clearPointerHoverScrollIdleTimer();- pointerHoverScrollIdleTimer = setTimeout(resumePointerHoverAfterScroll, HOVER_SCROLL_IDLE_MS);- if (pointerHoverSuspendedByScroll) {- return;- }- pointerHoverSuspendedByScroll = true;- if (pointerPositionNotificationFrame != null) {- cancelAnimationFrame(pointerPositionNotificationFrame);- pointerPositionNotificationFrame = null;- }- notifyHoverInvalidationListeners();-};-const schedulePointerPositionNotification = (): void => {- if (pointerPositionNotificationFrame != null) {- return;- }- pointerPositionNotificationFrame = requestAnimationFrame(() => {- pointerPositionNotificationFrame = null;- notifyPointerPositionListeners();- });-};-const updateLastPointerPosition = (event: PointerEvent | MouseEvent): void => {- if (lastPointerPosition?.x === event.clientX && lastPointerPosition.y === event.clientY) {- return;- }- lastPointerPosition = {x: event.clientX, y: event.clientY};- resumePointerHoverAfterScroll();- schedulePointerPositionNotification();-};-const clearLastPointerPosition = (): void => {- if (!lastPointerPosition) {- return;- }- lastPointerPosition = null;- schedulePointerPositionNotification();-};-const clearLastPointerPositionOnWindowBlur = (): void => {- clearLastPointerPosition();- notifyHoverInvalidationListeners();-};-const clearLastPointerPositionOnWindowExit = (event: PointerEvent | MouseEvent): void => {- if (event.relatedTarget == null) {- clearLastPointerPosition();- }-};-const supportsPointerPositionEvents = (): boolean => 'PointerEvent' in window;-const subscribePointerPosition = (listener: () => void): (() => void) => {- if (pointerPositionSubscriptionCount === 0) {- if (supportsPointerPositionEvents()) {- window.addEventListener('pointermove', updateLastPointerPosition, true);- window.addEventListener('pointerdown', updateLastPointerPosition, true);- window.addEventListener('pointerout', clearLastPointerPositionOnWindowExit, true);- } else {- window.addEventListener('mousemove', updateLastPointerPosition, true);- window.addEventListener('mousedown', updateLastPointerPosition, true);- window.addEventListener('mouseout', clearLastPointerPositionOnWindowExit, true);- }- }- pointerPositionSubscriptionCount += 1;- pointerPositionListeners.add(listener);- return () => {- pointerPositionListeners.delete(listener);- pointerPositionSubscriptionCount = Math.max(0, pointerPositionSubscriptionCount - 1);- if (pointerPositionSubscriptionCount !== 0) {- return;- }- lastPointerPosition = null;- if (pointerPositionNotificationFrame != null) {- cancelAnimationFrame(pointerPositionNotificationFrame);- pointerPositionNotificationFrame = null;- }- if (supportsPointerPositionEvents()) {- window.removeEventListener('pointermove', updateLastPointerPosition, true);- window.removeEventListener('pointerdown', updateLastPointerPosition, true);- window.removeEventListener('pointerout', clearLastPointerPositionOnWindowExit, true);- } else {- window.removeEventListener('mousemove', updateLastPointerPosition, true);- window.removeEventListener('mousedown', updateLastPointerPosition, true);- window.removeEventListener('mouseout', clearLastPointerPositionOnWindowExit, true);- }- };-};-const subscribeMessageHoverInvalidation = (listener: () => void): (() => void) => {- if (hoverInvalidationSubscriptionCount === 0) {- window.addEventListener('scroll', suspendPointerHoverForScroll, true);- window.addEventListener('resize', notifyHoverInvalidationListeners);- window.addEventListener('blur', clearLastPointerPositionOnWindowBlur);- }- hoverInvalidationSubscriptionCount += 1;- hoverInvalidationListeners.add(listener);- return () => {- hoverInvalidationListeners.delete(listener);- hoverInvalidationSubscriptionCount = Math.max(0, hoverInvalidationSubscriptionCount - 1);- if (hoverInvalidationSubscriptionCount !== 0) {- return;- }- clearPointerHoverScrollIdleTimer();- pointerHoverSuspendedByScroll = false;- window.removeEventListener('scroll', suspendPointerHoverForScroll, true);- window.removeEventListener('resize', notifyHoverInvalidationListeners);- window.removeEventListener('blur', clearLastPointerPositionOnWindowBlur);- };-};-export type MessageBehaviorOverrides = Partial<{mobileLayoutEnabled: boolean;messageGroupSpacing: number;@@ -362,9 +219,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {const {i18n} = useLingui();const [showActionBar, setShowActionBar] = useState(false);const [isLongPressing, setIsLongPressing] = useState(false);- const [isHoveringDesktop, setIsHoveringDesktop] = useState(false);const [isFocusedWithin, setIsFocusedWithin] = useState(false);- const [isPopoutOpen, setIsPopoutOpen] = useState(false);const [mobileLongPressLinkUrl, setMobileLongPressLinkUrl] = useState<string | undefined>(undefined);const messageRef = useRef<HTMLDivElement | null>(null);const disableContextMenuTracking = behaviorOverrides?.disableContextMenuTracking ?? false;@@ -503,15 +358,6 @@ export const Message: React.FC<MessageProps> = observer((props) => {const velocitySamples = useRef<Array<{x: number; y: number; timestamp: number}>>([]);const highlightTimerRef = useRef<NodeJS.Timeout | null>(null);const suppressClickUntilRef = useRef(0);- const popoutCloseRafRef = useRef<number | null>(null);- const isHoveringDesktopRef = useRef(false);- const setDesktopHoverState = useCallback((isHovered: boolean) => {- if (isHoveringDesktopRef.current === isHovered) {- return;- }- isHoveringDesktopRef.current = isHovered;- setIsHoveringDesktop(isHovered);- }, []);const unsubscribeLongPressScrollCancel = useCallback(() => {unsubscribeLongPressScrollCancelRef.current?.();unsubscribeLongPressScrollCancelRef.current = null;@@ -631,50 +477,12 @@ export const Message: React.FC<MessageProps> = observer((props) => {setMobileLongPressLinkUrl(undefined);}, []);const keyboardModeEnabled = KeyboardMode.keyboardModeEnabled;- const isPointerInsideMessage = useCallback((): boolean => {- if (mobileLayoutEnabled) {- return false;- }- if (pointerHoverSuspendedByScroll) {- return false;- }- const element = messageRef.current;- if (!element) {- return false;- }- if (!lastPointerPosition) {- return element.matches(':hover');- }- return isPointInsideMessageTree(element, lastPointerPosition);- }, [mobileLayoutEnabled]);- const syncPointerHoverState = useCallback((): boolean => {- const isHovered = isPointerInsideMessage();- setDesktopHoverState(isHovered);- return isHovered;- }, [isPointerInsideMessage, setDesktopHoverState]);- const cancelScheduledPopoutClose = useCallback(() => {- if (popoutCloseRafRef.current == null) {- return;- }- cancelAnimationFrame(popoutCloseRafRef.current);- popoutCloseRafRef.current = null;- }, []);- const handleMessagePopoutToggle = useCallback(- (isOpen: boolean) => {- if (isOpen) {- cancelScheduledPopoutClose();- setIsPopoutOpen(true);- return;- }- cancelScheduledPopoutClose();- popoutCloseRafRef.current = requestAnimationFrame(() => {- popoutCloseRafRef.current = null;- syncPointerHoverState();- setIsPopoutOpen(false);- });- },- [cancelScheduledPopoutClose, syncPointerHoverState],- );+ const {+ isHovering,+ isPopoutOpen,+ handlePopoutToggle,+ trackingEnabled: hoverTrackingEnabled,+ } = useMessageHoverState({messageRef, mobileLayoutEnabled, keyboardModeEnabled, contextMenuOpen});const handleFocusWithin = useCallback(() => {if (!keyboardModeEnabled) {return;@@ -693,58 +501,6 @@ export const Message: React.FC<MessageProps> = observer((props) => {},[channel.id, message.id],);- useEffect(() => {- if (mobileLayoutEnabled || !messageRef.current) return;- const element = messageRef.current;- const handleMouseEnter = (event: MouseEvent) => {- updateLastPointerPosition(event);- if (pointerHoverSuspendedByScroll) {- return;- }- setDesktopHoverState(true);- };- const handleMouseLeave = (event: MouseEvent) => {- updateLastPointerPosition(event);- setDesktopHoverState(false);- };- element.addEventListener('mouseenter', handleMouseEnter);- element.addEventListener('mouseleave', handleMouseLeave);- const unsubscribeFocus = subscribeWindowFocus(syncPointerHoverState);- const unsubscribeHoverInvalidation = subscribeMessageHoverInvalidation(syncPointerHoverState);- const rafId = requestAnimationFrame(syncPointerHoverState);- return () => {- cancelAnimationFrame(rafId);- element.removeEventListener('mouseenter', handleMouseEnter);- element.removeEventListener('mouseleave', handleMouseLeave);- unsubscribeFocus();- unsubscribeHoverInvalidation();- };- }, [mobileLayoutEnabled, keyboardModeEnabled, syncPointerHoverState]);- const shouldTrackActivePointer = !mobileLayoutEnabled && (isHoveringDesktop || isPopoutOpen || contextMenuOpen);- useEffect(() => {- if (!shouldTrackActivePointer) {- return;- }- const rafId = requestAnimationFrame(syncPointerHoverState);- const unsubscribePointerPosition = subscribePointerPosition(syncPointerHoverState);- return () => {- cancelAnimationFrame(rafId);- unsubscribePointerPosition();- };- }, [shouldTrackActivePointer, syncPointerHoverState]);- const wasContextMenuOpenRef = useRef(false);- useLayoutEffect(() => {- const wasOpen = wasContextMenuOpenRef.current;- wasContextMenuOpenRef.current = contextMenuOpen;- if (wasOpen && !contextMenuOpen) {- syncPointerHoverState();- }- }, [contextMenuOpen, syncPointerHoverState]);- useEffect(() => {- return () => {- cancelScheduledPopoutClose();- };- }, [cancelScheduledPopoutClose]);useEffect(() => {if (!keyboardModeEnabled) return;if (contextMenuOpen) {@@ -775,7 +531,6 @@ export const Message: React.FC<MessageProps> = observer((props) => {}};}, [unsubscribeLongPressScrollCancel]);- const isHovering = mobileLayoutEnabled ? false : isHoveringDesktop;useEffect(() => {if (!keyboardModeEnabled) {setIsFocusedWithin(false);@@ -810,7 +565,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {shouldRenderSuppressEmbeds: false,}: undefined,- onPopoutToggle: handleMessagePopoutToggle,+ onPopoutToggle: handlePopoutToggle,suppressMessageActions,onHeadingActivate,}),@@ -824,7 +579,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {previewContext,previewOverrides,previewMode,- handleMessagePopoutToggle,+ handlePopoutToggle,suppressMessageActions,onHeadingActivate,],@@ -841,7 +596,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {astNodes.length === 1 &&astNodes[0].type === NodeType.Link &&!message.suppressEmbeds;- const shouldDisableHoverBackground = prefersReducedMotion && !isEditing;+ const shouldDisableHoverBackground = !hoverTrackingEnabled && prefersReducedMotion && !isEditing;const isKeyboardFocused = keyboardModeEnabled && isFocusedWithin;const isPreview = previewContext != null;const shouldApplySpacing = !shouldGroup && !removeTopSpacing && previewContext !== MessagePreviewContext.LIST_POPOUT;@@ -961,6 +716,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {data-flx-compact={messageDisplayCompact ? 'true' : undefined}data-flx-grouped={shouldGroup && shouldApplyGroupedLayout(message, prevMessage) ? 'true' : undefined}data-flx-action-bar={shouldShowActionBar ? 'true' : undefined}+ data-flx-action-bar-active={shouldShowActionBar && isActionBarActive ? 'true' : undefined}data-flx-action-bar-forced={shouldShowActionBar && isActionBarForcedVisible ? 'true' : undefined}tabIndex={keyboardModeEnabled ? -1 : undefined}className={messageClasses}@@ -996,7 +752,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {}}developerMode={false}isActive={isActionBarActive}- onPopoutToggle={handleMessagePopoutToggle}+ onPopoutToggle={handlePopoutToggle}data-flx="channel.message.message-action-bar-core"/>) : (@@ -1005,7 +761,7 @@ export const Message: React.FC<MessageProps> = observer((props) => {handleDelete={handleDelete}sourceChannel={channel}isActive={isActionBarActive}- onPopoutToggle={handleMessagePopoutToggle}+ onPopoutToggle={handlePopoutToggle}data-flx="channel.message.message-action-bar"/>))}diff --git a/fluxer_app/src/features/channel/components/MessageActionBar.module.css b/fluxer_app/src/features/channel/components/MessageActionBar.module.cssindex 872071b26..70a029711 100644--- a/fluxer_app/src/features/channel/components/MessageActionBar.module.css+++ b/fluxer_app/src/features/channel/components/MessageActionBar.module.css@@ -11,28 +11,50 @@pointer-events: none;}-:global([data-flx-action-bar]:hover) .actionBarContainer,:global([data-flx-action-bar]) .actionBarContainer:has(:focus-visible) {opacity: 1;visibility: visible;pointer-events: auto;}+:global(html:not(.experiment-message-hover-tracking) [data-flx-action-bar]:hover) .actionBarContainer {+ opacity: 1;+ visibility: visible;+ pointer-events: auto;+}+@media (pointer: coarse) {- :global([data-flx-action-bar]:not([data-flx-action-bar-forced]):hover) .actionBarContainer {+ :global(html:not(.experiment-message-hover-tracking) [data-flx-action-bar]:not([data-flx-action-bar-forced]):hover)+ .actionBarContainer {opacity: 0;visibility: hidden;pointer-events: none;}}-:global([data-flx-action-bar][data-flx-action-bar-forced]) .actionBarContainer,-.actionBarContainer.actionBarPinned {+:global(html:not(.experiment-message-hover-tracking) [data-flx-action-bar][data-flx-action-bar-forced])+ .actionBarContainer,+:global(html:not(.experiment-message-hover-tracking)) .actionBarContainer.actionBarPinned {opacity: 1;visibility: visible;pointer-events: auto;}+:global(html.experiment-message-hover-tracking [data-flx-action-bar][data-flx-action-bar-active]) .actionBarContainer {+ opacity: 1;+ visibility: visible;+ pointer-events: auto;+}++@media (pointer: coarse) {+ :global(html.experiment-message-hover-tracking [data-flx-action-bar]:not([data-flx-action-bar-forced]))+ .actionBarContainer:not(:has(:focus-visible)) {+ opacity: 0;+ visibility: hidden;+ pointer-events: none;+ }+}+:global(html:not(.window-focused):not(.unfocused-fully-interactive)) .actionBarContainer,:global(.window-focus-activation-guard) .actionBarContainer {opacity: 0 !important;diff --git a/fluxer_app/src/features/channel/components/MessageHoverState.ts b/fluxer_app/src/features/channel/components/MessageHoverState.tsnew file mode 100644index 000000000..42a220269--- /dev/null+++ b/fluxer_app/src/features/channel/components/MessageHoverState.ts@@ -0,0 +1,317 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ registerMessageHoverTarget,+ resolveMessageHoverTargetsNow,+} from '@app/features/channel/components/MessageHoverTracking';+import MessageHoverTrackingRollout from '@app/features/channel/state/MessageHoverTrackingRollout';+import {subscribeWindowFocus} from '@app/features/platform/utils/WindowFocusBroadcast';+import type React from 'react';+import {useCallback, useEffect, useLayoutEffect, useRef, useState} from 'react';++const isPointInsideMessageTree = (messageElement: HTMLElement, point: {x: number; y: number}): boolean => {+ const target = messageElement.ownerDocument.elementFromPoint(point.x, point.y);+ return Boolean(target && messageElement.contains(target));+};+const HOVER_SCROLL_IDLE_MS = 150;+let lastPointerPosition: {x: number; y: number} | null = null;+let pointerPositionNotificationFrame: number | null = null;+let pointerPositionSubscriptionCount = 0;+let hoverInvalidationSubscriptionCount = 0;+let pointerHoverSuspendedByScroll = false;+let pointerHoverScrollIdleTimer: ReturnType<typeof setTimeout> | null = null;+const pointerPositionListeners = new Set<() => void>();+const hoverInvalidationListeners = new Set<() => void>();+const notifyPointerPositionListeners = (): void => {+ for (const listener of Array.from(pointerPositionListeners)) {+ listener();+ }+};+const notifyHoverInvalidationListeners = (): void => {+ for (const listener of Array.from(hoverInvalidationListeners)) {+ listener();+ }+};+const clearPointerHoverScrollIdleTimer = (): void => {+ if (pointerHoverScrollIdleTimer == null) {+ return;+ }+ clearTimeout(pointerHoverScrollIdleTimer);+ pointerHoverScrollIdleTimer = null;+};+const resumePointerHoverAfterScroll = (): void => {+ clearPointerHoverScrollIdleTimer();+ if (!pointerHoverSuspendedByScroll) {+ return;+ }+ pointerHoverSuspendedByScroll = false;+ notifyHoverInvalidationListeners();+};+const suspendPointerHoverForScroll = (): void => {+ clearPointerHoverScrollIdleTimer();+ pointerHoverScrollIdleTimer = setTimeout(resumePointerHoverAfterScroll, HOVER_SCROLL_IDLE_MS);+ if (pointerHoverSuspendedByScroll) {+ return;+ }+ pointerHoverSuspendedByScroll = true;+ if (pointerPositionNotificationFrame != null) {+ cancelAnimationFrame(pointerPositionNotificationFrame);+ pointerPositionNotificationFrame = null;+ }+ notifyHoverInvalidationListeners();+};+const schedulePointerPositionNotification = (): void => {+ if (pointerPositionNotificationFrame != null) {+ return;+ }+ pointerPositionNotificationFrame = requestAnimationFrame(() => {+ pointerPositionNotificationFrame = null;+ notifyPointerPositionListeners();+ });+};+const updateLastPointerPosition = (event: PointerEvent | MouseEvent): void => {+ if (lastPointerPosition?.x === event.clientX && lastPointerPosition.y === event.clientY) {+ return;+ }+ lastPointerPosition = {x: event.clientX, y: event.clientY};+ resumePointerHoverAfterScroll();+ schedulePointerPositionNotification();+};+const clearLastPointerPosition = (): void => {+ if (!lastPointerPosition) {+ return;+ }+ lastPointerPosition = null;+ schedulePointerPositionNotification();+};+const clearLastPointerPositionOnWindowBlur = (): void => {+ clearLastPointerPosition();+ notifyHoverInvalidationListeners();+};+const clearLastPointerPositionOnWindowExit = (event: PointerEvent | MouseEvent): void => {+ if (event.relatedTarget == null) {+ clearLastPointerPosition();+ }+};+const supportsPointerPositionEvents = (): boolean => 'PointerEvent' in window;+const subscribePointerPosition = (listener: () => void): (() => void) => {+ if (pointerPositionSubscriptionCount === 0) {+ if (supportsPointerPositionEvents()) {+ window.addEventListener('pointermove', updateLastPointerPosition, true);+ window.addEventListener('pointerdown', updateLastPointerPosition, true);+ window.addEventListener('pointerout', clearLastPointerPositionOnWindowExit, true);+ } else {+ window.addEventListener('mousemove', updateLastPointerPosition, true);+ window.addEventListener('mousedown', updateLastPointerPosition, true);+ window.addEventListener('mouseout', clearLastPointerPositionOnWindowExit, true);+ }+ }+ pointerPositionSubscriptionCount += 1;+ pointerPositionListeners.add(listener);+ return () => {+ pointerPositionListeners.delete(listener);+ pointerPositionSubscriptionCount = Math.max(0, pointerPositionSubscriptionCount - 1);+ if (pointerPositionSubscriptionCount !== 0) {+ return;+ }+ lastPointerPosition = null;+ if (pointerPositionNotificationFrame != null) {+ cancelAnimationFrame(pointerPositionNotificationFrame);+ pointerPositionNotificationFrame = null;+ }+ if (supportsPointerPositionEvents()) {+ window.removeEventListener('pointermove', updateLastPointerPosition, true);+ window.removeEventListener('pointerdown', updateLastPointerPosition, true);+ window.removeEventListener('pointerout', clearLastPointerPositionOnWindowExit, true);+ } else {+ window.removeEventListener('mousemove', updateLastPointerPosition, true);+ window.removeEventListener('mousedown', updateLastPointerPosition, true);+ window.removeEventListener('mouseout', clearLastPointerPositionOnWindowExit, true);+ }+ };+};+const subscribeMessageHoverInvalidation = (listener: () => void): (() => void) => {+ if (hoverInvalidationSubscriptionCount === 0) {+ window.addEventListener('scroll', suspendPointerHoverForScroll, true);+ window.addEventListener('resize', notifyHoverInvalidationListeners);+ window.addEventListener('blur', clearLastPointerPositionOnWindowBlur);+ }+ hoverInvalidationSubscriptionCount += 1;+ hoverInvalidationListeners.add(listener);+ return () => {+ hoverInvalidationListeners.delete(listener);+ hoverInvalidationSubscriptionCount = Math.max(0, hoverInvalidationSubscriptionCount - 1);+ if (hoverInvalidationSubscriptionCount !== 0) {+ return;+ }+ clearPointerHoverScrollIdleTimer();+ pointerHoverSuspendedByScroll = false;+ window.removeEventListener('scroll', suspendPointerHoverForScroll, true);+ window.removeEventListener('resize', notifyHoverInvalidationListeners);+ window.removeEventListener('blur', clearLastPointerPositionOnWindowBlur);+ };+};++interface UseMessageHoverStateParams {+ messageRef: React.RefObject<HTMLDivElement | null>;+ mobileLayoutEnabled: boolean;+ keyboardModeEnabled: boolean;+ contextMenuOpen: boolean;+}++export interface MessageHoverState {+ isHovering: boolean;+ isPopoutOpen: boolean;+ handlePopoutToggle: (isOpen: boolean) => void;+ trackingEnabled: boolean;+}++export function useMessageHoverState({+ messageRef,+ mobileLayoutEnabled,+ keyboardModeEnabled,+ contextMenuOpen,+}: UseMessageHoverStateParams): MessageHoverState {+ const trackingEnabled = MessageHoverTrackingRollout.enabled;+ const [isHoveringDesktop, setIsHoveringDesktop] = useState(false);+ const [isPopoutOpen, setIsPopoutOpen] = useState(false);+ const isHoveringDesktopRef = useRef(false);+ const popoutCloseRafRef = useRef<number | null>(null);+ const setDesktopHoverState = useCallback((isHovered: boolean) => {+ if (isHoveringDesktopRef.current === isHovered) {+ return;+ }+ isHoveringDesktopRef.current = isHovered;+ setIsHoveringDesktop(isHovered);+ }, []);+ const isPointerInsideMessage = useCallback((): boolean => {+ if (mobileLayoutEnabled) {+ return false;+ }+ if (pointerHoverSuspendedByScroll) {+ return false;+ }+ const element = messageRef.current;+ if (!element) {+ return false;+ }+ if (!lastPointerPosition) {+ return element.matches(':hover');+ }+ return isPointInsideMessageTree(element, lastPointerPosition);+ }, [mobileLayoutEnabled, messageRef]);+ const syncPointerHoverState = useCallback((): boolean => {+ const isHovered = isPointerInsideMessage();+ setDesktopHoverState(isHovered);+ return isHovered;+ }, [isPointerInsideMessage, setDesktopHoverState]);+ const cancelScheduledPopoutClose = useCallback(() => {+ if (popoutCloseRafRef.current == null) {+ return;+ }+ cancelAnimationFrame(popoutCloseRafRef.current);+ popoutCloseRafRef.current = null;+ }, []);+ const handlePopoutToggle = useCallback(+ (isOpen: boolean) => {+ if (trackingEnabled) {+ setIsPopoutOpen(isOpen);+ return;+ }+ if (isOpen) {+ cancelScheduledPopoutClose();+ setIsPopoutOpen(true);+ return;+ }+ cancelScheduledPopoutClose();+ popoutCloseRafRef.current = requestAnimationFrame(() => {+ popoutCloseRafRef.current = null;+ syncPointerHoverState();+ setIsPopoutOpen(false);+ });+ },+ [cancelScheduledPopoutClose, syncPointerHoverState, trackingEnabled],+ );+ useEffect(() => {+ if (!trackingEnabled || mobileLayoutEnabled) {+ return;+ }+ const element = messageRef.current;+ if (element == null) {+ return;+ }+ return registerMessageHoverTarget(element, setDesktopHoverState);+ }, [trackingEnabled, mobileLayoutEnabled, messageRef, setDesktopHoverState]);+ useEffect(() => {+ if (trackingEnabled || mobileLayoutEnabled || !messageRef.current) return;+ const element = messageRef.current;+ const handleMouseEnter = (event: MouseEvent) => {+ updateLastPointerPosition(event);+ if (pointerHoverSuspendedByScroll) {+ return;+ }+ setDesktopHoverState(true);+ };+ const handleMouseLeave = (event: MouseEvent) => {+ updateLastPointerPosition(event);+ setDesktopHoverState(false);+ };+ element.addEventListener('mouseenter', handleMouseEnter);+ element.addEventListener('mouseleave', handleMouseLeave);+ const unsubscribeFocus = subscribeWindowFocus(syncPointerHoverState);+ const unsubscribeHoverInvalidation = subscribeMessageHoverInvalidation(syncPointerHoverState);+ const rafId = requestAnimationFrame(syncPointerHoverState);+ return () => {+ cancelAnimationFrame(rafId);+ element.removeEventListener('mouseenter', handleMouseEnter);+ element.removeEventListener('mouseleave', handleMouseLeave);+ unsubscribeFocus();+ unsubscribeHoverInvalidation();+ };+ }, [+ trackingEnabled,+ mobileLayoutEnabled,+ keyboardModeEnabled,+ messageRef,+ setDesktopHoverState,+ syncPointerHoverState,+ ]);+ const shouldTrackActivePointer =+ !trackingEnabled && !mobileLayoutEnabled && (isHoveringDesktop || isPopoutOpen || contextMenuOpen);+ useEffect(() => {+ if (!shouldTrackActivePointer) {+ return;+ }+ const rafId = requestAnimationFrame(syncPointerHoverState);+ const unsubscribePointerPosition = subscribePointerPosition(syncPointerHoverState);+ return () => {+ cancelAnimationFrame(rafId);+ unsubscribePointerPosition();+ };+ }, [shouldTrackActivePointer, syncPointerHoverState]);+ const isOverlayOpen = trackingEnabled ? contextMenuOpen || isPopoutOpen : contextMenuOpen;+ const wasOverlayOpenRef = useRef(false);+ useLayoutEffect(() => {+ const wasOpen = wasOverlayOpenRef.current;+ wasOverlayOpenRef.current = isOverlayOpen;+ if (!wasOpen || isOverlayOpen) {+ return;+ }+ if (trackingEnabled) {+ resolveMessageHoverTargetsNow();+ return;+ }+ syncPointerHoverState();+ }, [isOverlayOpen, syncPointerHoverState, trackingEnabled]);+ useEffect(() => {+ return () => {+ cancelScheduledPopoutClose();+ };+ }, [cancelScheduledPopoutClose]);+ return {+ isHovering: mobileLayoutEnabled ? false : isHoveringDesktop,+ isPopoutOpen,+ handlePopoutToggle,+ trackingEnabled,+ };+}diff --git a/fluxer_app/src/features/channel/components/MessageHoverStyleContract.test.ts b/fluxer_app/src/features/channel/components/MessageHoverStyleContract.test.tsnew file mode 100644index 000000000..fa5606944--- /dev/null+++ b/fluxer_app/src/features/channel/components/MessageHoverStyleContract.test.ts@@ -0,0 +1,115 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {readFileSync} from 'node:fs';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';++interface CssRule {+ readonly selector: string;+ readonly body: string;+}++function readSource(relativePath: string): string {+ return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8');+}++function parseCssRules(css: string): Array<CssRule> {+ const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, '');+ const rules: Array<CssRule> = [];+ for (const match of withoutComments.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {+ rules.push({selector: match[1].replace(/\s+/g, ''), body: match[2].trim()});+ }+ return rules;+}++const EXPERIMENT_CLASS = 'experiment-message-hover-tracking';+const TREATMENT_GATE = `html.${EXPERIMENT_CLASS}`;+const CONTROL_GATE = `:not(.${EXPERIMENT_CLASS})`;++const actionBarCss = readSource('./MessageActionBar.module.css');+const messageCss = readSource('../../theme/styles/Message.module.css');+const actionBarSource = readSource('./MessageActionBar.tsx');+const channelMessageSource = readSource('./ChannelMessage.tsx');+const hoverStateSource = readSource('./MessageHoverState.ts');+const rolloutSource = readSource('../state/MessageHoverTrackingRollout.ts');+const appSource = readSource('../../../app/App.tsx');++const actionBarContainerRules = parseCssRules(actionBarCss).filter((rule) =>+ rule.selector.includes('.actionBarContainer'),+);+const revealingRules = actionBarContainerRules.filter((rule) => /visibility:\s*visible/.test(rule.body));+const treatmentRevealRules = revealingRules.filter((rule) => rule.selector.includes(TREATMENT_GATE));+const controlRevealRules = revealingRules.filter((rule) => rule.selector.includes(CONTROL_GATE));++describe('message hover style contract', () => {+ it('reveals the action bar from the tracked hover state in the experiment arm', () => {+ expect(treatmentRevealRules.length).toBeGreaterThan(0);+ for (const rule of treatmentRevealRules) {+ expect(rule.selector).not.toMatch(/:hover/);+ expect(rule.selector).toMatch(/data-flx-action-bar-active/);+ }+ });++ it('keeps the legacy :hover reveal behind the control arm', () => {+ expect(controlRevealRules.length).toBeGreaterThan(0);+ expect(controlRevealRules.some((rule) => rule.selector.includes(':hover'))).toBe(true);+ for (const rule of controlRevealRules) {+ expect(rule.selector).not.toMatch(/data-flx-action-bar-active/);+ }+ });++ it('gives every action bar reveal rule exactly one arm', () => {+ for (const rule of revealingRules) {+ if (rule.selector.includes(':focus-visible')) continue;+ const treatment = rule.selector.includes(TREATMENT_GATE);+ const control = rule.selector.includes(CONTROL_GATE);+ expect(treatment || control).toBe(true);+ expect(treatment && control).toBe(false);+ }+ });++ it('never reveals the action bar from the message stylesheet in the experiment arm', () => {+ const buttonRevealRules = parseCssRules(messageCss).filter(+ (rule) => /\.buttons\b/.test(rule.selector) && /opacity:\s*1/.test(rule.body),+ );+ expect(buttonRevealRules.length).toBeGreaterThan(0);+ for (const rule of buttonRevealRules) {+ expect(rule.selector).toContain(CONTROL_GATE);+ }+ });++ it('derives the row highlight and the action bar from the same hover state', () => {+ const highlightSource = channelMessageSource.match(/(\w+) && !isPreview && styles\.messageHovered/)?.[1];+ const actionBarSourceState = channelMessageSource.match(/const isActionBarActive = (\w+) \|\|/)?.[1];+ expect(highlightSource).toBeDefined();+ expect(actionBarSourceState).toBe(highlightSource);+ expect(channelMessageSource).toMatch(+ /data-flx-action-bar-active=\{shouldShowActionBar && isActionBarActive \? 'true' : undefined\}/,+ );+ });++ it('resolves the tracked hover state without the retained :hover chain', () => {+ expect(readSource('./MessageHoverTracking.ts')).not.toMatch(/matches\(':hover'\)/);+ const legacyOracle = hoverStateSource.match(/const isPointerInsideMessage[\s\S]*?\n\t\};/)?.[0];+ expect(legacyOracle).toBeDefined();+ expect(legacyOracle).toMatch(/matches\(':hover'\)/);+ expect(hoverStateSource).toMatch(/if \(!trackingEnabled \|\| mobileLayoutEnabled\) \{/);+ expect(hoverStateSource).toMatch(+ /if \(trackingEnabled \|\| mobileLayoutEnabled \|\| !messageRef\.current\) return;/,+ );+ });++ it('drives the stylesheet arm from the rollout assignment', () => {+ expect(rolloutSource).toContain(`'${EXPERIMENT_CLASS}'`);+ expect(actionBarCss).toContain(EXPERIMENT_CLASS);+ expect(messageCss).toContain(EXPERIMENT_CLASS);+ expect(appSource).toMatch(+ /useDocumentClassToggle\(MESSAGE_HOVER_TRACKING_EXPERIMENT_CLASS, MessageHoverTrackingRollout\.enabled\)/,+ );+ });++ it('keeps the control arm reachable from the action bar component', () => {+ expect(actionBarSource).toMatch(/messageStyles\.buttons/);+ expect(actionBarSource).toMatch(/styles\.actionBarPinned/);+ });+});diff --git a/fluxer_app/src/features/channel/components/MessageHoverTracking.test.ts b/fluxer_app/src/features/channel/components/MessageHoverTracking.test.tsnew file mode 100644index 000000000..2d23928db--- /dev/null+++ b/fluxer_app/src/features/channel/components/MessageHoverTracking.test.ts@@ -0,0 +1,309 @@+// @vitest-environment happy-dom+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ refreshMessageHoverTargets,+ registerMessageHoverTarget,+ resetMessageHoverTrackingForTests,+} from '@app/features/channel/components/MessageHoverTracking';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';++let hitTarget: Element | null = null;+let elementFromPointSpy: ReturnType<typeof vi.spyOn>;+let matchesSpy: ReturnType<typeof vi.spyOn>;++function nextFrame(): Promise<void> {+ return new Promise((resolve) => {+ requestAnimationFrame(() => resolve());+ });+}++function createRow(): {row: HTMLElement; content: HTMLElement} {+ const row = document.createElement('div');+ const content = document.createElement('span');+ row.append(content);+ document.body.append(row);+ return {row, content};+}++function movePointerTo(target: Element | null, x = 10, y = 10): void {+ hitTarget = target;+ window.dispatchEvent(new MouseEvent('pointermove', {clientX: x, clientY: y, bubbles: true}));+}++function scrollTo(target: Element | null): void {+ hitTarget = target;+ window.dispatchEvent(new Event('scroll'));+}++beforeEach(() => {+ hitTarget = null;+ elementFromPointSpy = vi.spyOn(document, 'elementFromPoint').mockImplementation(() => hitTarget);+ matchesSpy = vi.spyOn(Element.prototype, 'matches');+});++afterEach(() => {+ vi.useRealTimers();+ resetMessageHoverTrackingForTests();+ elementFromPointSpy.mockRestore();+ matchesSpy.mockRestore();+ document.body.replaceChildren();+});++describe('MessageHoverTracking', () => {+ it('arms the row that owns the element under the pointer', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);+ await nextFrame();+ expect(listener).not.toHaveBeenCalled();++ movePointerTo(content);+ await nextFrame();++ expect(listener).toHaveBeenLastCalledWith(true);+ });++ it('keeps at most one row armed when the pointer moves between adjacent rows', async () => {+ const first = createRow();+ const second = createRow();+ const firstListener = vi.fn();+ const secondListener = vi.fn();+ registerMessageHoverTarget(first.row, firstListener);+ registerMessageHoverTarget(second.row, secondListener);++ movePointerTo(first.content);+ await nextFrame();+ expect(firstListener).toHaveBeenLastCalledWith(true);+ expect(secondListener).not.toHaveBeenCalled();++ movePointerTo(second.content);+ await nextFrame();+ expect(firstListener).toHaveBeenLastCalledWith(false);+ expect(secondListener).toHaveBeenLastCalledWith(true);+ });++ it('does not re-arm a row on window refocus when the pointer left during the blur', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ movePointerTo(content);+ await nextFrame();+ expect(listener).toHaveBeenLastCalledWith(true);++ window.dispatchEvent(new Event('blur'));+ expect(listener).toHaveBeenLastCalledWith(false);++ window.dispatchEvent(new Event('focus'));+ refreshMessageHoverTargets();+ await nextFrame();+ await nextFrame();++ expect(listener).toHaveBeenLastCalledWith(false);+ expect(listener.mock.calls.filter(([isHovered]) => isHovered === true)).toHaveLength(1);+ });++ it('never consults the retained :hover chain as a hover oracle', async () => {+ const {row, content} = createRow();+ registerMessageHoverTarget(row, vi.fn());++ movePointerTo(content);+ await nextFrame();+ window.dispatchEvent(new Event('blur'));+ window.dispatchEvent(new Event('focus'));+ refreshMessageHoverTargets();+ await nextFrame();++ expect(matchesSpy.mock.calls.flat()).not.toContain(':hover');+ });++ it('disarms and does not re-arm while rows scroll under a stationary pointer', async () => {+ const first = createRow();+ const second = createRow();+ const firstListener = vi.fn();+ const secondListener = vi.fn();+ registerMessageHoverTarget(first.row, firstListener);+ registerMessageHoverTarget(second.row, secondListener);++ movePointerTo(first.content);+ await nextFrame();+ expect(firstListener).toHaveBeenLastCalledWith(true);++ scrollTo(second.content);+ await nextFrame();++ expect(firstListener).toHaveBeenLastCalledWith(false);+ expect(secondListener).not.toHaveBeenCalled();+ });++ it('arms the row under the pointer once scrolling settles', async () => {+ vi.useFakeTimers();+ const first = createRow();+ const second = createRow();+ const firstListener = vi.fn();+ const secondListener = vi.fn();+ registerMessageHoverTarget(first.row, firstListener);+ registerMessageHoverTarget(second.row, secondListener);++ hitTarget = first.content;+ window.dispatchEvent(new MouseEvent('pointermove', {clientX: 10, clientY: 10, bubbles: true}));+ await vi.advanceTimersByTimeAsync(20);+ expect(firstListener).toHaveBeenLastCalledWith(true);++ scrollTo(second.content);+ await vi.advanceTimersByTimeAsync(20);+ expect(secondListener).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(200);+ expect(secondListener).toHaveBeenLastCalledWith(true);+ });++ it('stays suspended for as long as momentum keeps firing scroll events', async () => {+ vi.useFakeTimers();+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ hitTarget = content;+ window.dispatchEvent(new MouseEvent('pointermove', {clientX: 10, clientY: 10, bubbles: true}));+ await vi.advanceTimersByTimeAsync(20);+ expect(listener).toHaveBeenLastCalledWith(true);++ scrollTo(content);+ await vi.advanceTimersByTimeAsync(20);+ expect(listener).toHaveBeenLastCalledWith(false);++ for (let i = 0; i < 6; i++) {+ await vi.advanceTimersByTimeAsync(100);+ scrollTo(content);+ }+ expect(listener).toHaveBeenLastCalledWith(false);++ await vi.advanceTimersByTimeAsync(200);+ expect(listener).toHaveBeenLastCalledWith(true);+ });++ it('re-arms immediately when the pointer actually moves during a scroll', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ scrollTo(content);+ await nextFrame();+ expect(listener).not.toHaveBeenCalledWith(true);++ movePointerTo(content);+ await nextFrame();+ expect(listener).toHaveBeenLastCalledWith(true);+ });++ it('does not let a scroll-driven pointerover re-arm a row', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ scrollTo(content);+ await nextFrame();++ hitTarget = content;+ window.dispatchEvent(new MouseEvent('pointerover', {clientX: 10, clientY: 10, bubbles: true}));+ await nextFrame();++ expect(listener).not.toHaveBeenCalledWith(true);+ });++ it('re-arms the row underneath after an overlay that covered it is dismissed', async () => {+ const {row, content} = createRow();+ const overlay = document.createElement('div');+ document.body.append(overlay);+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ movePointerTo(content);+ await nextFrame();+ expect(listener).toHaveBeenLastCalledWith(true);++ hitTarget = overlay;+ refreshMessageHoverTargets();+ await nextFrame();+ expect(listener).toHaveBeenLastCalledWith(false);++ overlay.remove();+ hitTarget = content;+ refreshMessageHoverTargets();+ await nextFrame();++ expect(listener).toHaveBeenLastCalledWith(true);+ });++ it('does not treat a touch contact as hover', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ hitTarget = content;+ window.dispatchEvent(new PointerEvent('pointerdown', {clientX: 10, clientY: 10, pointerType: 'touch'}));+ await nextFrame();++ expect(listener).not.toHaveBeenCalledWith(true);+ });++ it('disarms when the pointer leaves the window', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ registerMessageHoverTarget(row, listener);++ movePointerTo(content);+ await nextFrame();+ expect(listener).toHaveBeenLastCalledWith(true);++ window.dispatchEvent(new MouseEvent('pointerout', {relatedTarget: null}));++ expect(listener).toHaveBeenLastCalledWith(false);+ });++ it('releases ownership when an armed row unregisters', async () => {+ const {row, content} = createRow();+ const listener = vi.fn();+ const unregister = registerMessageHoverTarget(row, listener);+ const other = createRow();+ const otherListener = vi.fn();+ registerMessageHoverTarget(other.row, otherListener);++ movePointerTo(content);+ await nextFrame();+ expect(listener).toHaveBeenLastCalledWith(true);++ unregister();+ hitTarget = other.content;+ await nextFrame();++ expect(otherListener).toHaveBeenLastCalledWith(true);+ expect(listener).not.toHaveBeenLastCalledWith(true);+ });++ it('detaches every global listener once the last row unregisters', () => {+ const addEventListenerSpy = vi.spyOn(window, 'addEventListener');+ const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');+ const {row} = createRow();++ const unregister = registerMessageHoverTarget(row, vi.fn());+ const added = addEventListenerSpy.mock.calls.map(([type, listener]) => ({type, listener}));+ unregister();+ const removed = removeEventListenerSpy.mock.calls.map(([type, listener]) => ({type, listener}));++ expect(added.length).toBeGreaterThan(0);+ for (const addedListener of added) {+ expect(+ removed.some(+ (removedListener) =>+ removedListener.type === addedListener.type && removedListener.listener === addedListener.listener,+ ),+ ).toBe(true);+ }++ addEventListenerSpy.mockRestore();+ removeEventListenerSpy.mockRestore();+ });+});diff --git a/fluxer_app/src/features/channel/components/MessageHoverTracking.ts b/fluxer_app/src/features/channel/components/MessageHoverTracking.tsnew file mode 100644index 000000000..2058e6b47--- /dev/null+++ b/fluxer_app/src/features/channel/components/MessageHoverTracking.ts@@ -0,0 +1,217 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++type MessageHoverListener = (isHovered: boolean) => void;++const SCROLL_IDLE_MS = 150;++const hoverTargets = new Map<HTMLElement, MessageHoverListener>();+let pointerPosition: {x: number; y: number} | null = null;+let hoveredTarget: HTMLElement | null = null;+let resolveFrame: number | null = null;+let globalListenersAttached = false;+let scrollIdleTimer: ReturnType<typeof setTimeout> | null = null;+let suspendedByScroll = false;++const resolveHoveredTarget = (): HTMLElement | null => {+ if (pointerPosition == null) {+ return null;+ }+ let node: Element | null = document.elementFromPoint(pointerPosition.x, pointerPosition.y);+ while (node != null) {+ if (node instanceof HTMLElement && hoverTargets.has(node)) {+ return node;+ }+ node = node.parentElement;+ }+ return null;+};++const setHoveredTarget = (nextHoveredTarget: HTMLElement | null): void => {+ if (hoveredTarget === nextHoveredTarget) {+ return;+ }+ const previousHoveredTarget = hoveredTarget;+ hoveredTarget = nextHoveredTarget;+ if (previousHoveredTarget != null) {+ hoverTargets.get(previousHoveredTarget)?.(false);+ }+ if (nextHoveredTarget != null) {+ hoverTargets.get(nextHoveredTarget)?.(true);+ }+};++const cancelScheduledResolve = (): void => {+ if (resolveFrame == null) {+ return;+ }+ cancelAnimationFrame(resolveFrame);+ resolveFrame = null;+};++const scheduleResolve = (): void => {+ if (suspendedByScroll || resolveFrame != null) {+ return;+ }+ resolveFrame = requestAnimationFrame(() => {+ resolveFrame = null;+ setHoveredTarget(resolveHoveredTarget());+ });+};++const clearScrollIdleTimer = (): void => {+ if (scrollIdleTimer == null) {+ return;+ }+ clearTimeout(scrollIdleTimer);+ scrollIdleTimer = null;+};++const resumeAfterScroll = (): void => {+ clearScrollIdleTimer();+ if (!suspendedByScroll) {+ return;+ }+ suspendedByScroll = false;+ scheduleResolve();+};++const forgetPointerPosition = (): void => {+ pointerPosition = null;+ cancelScheduledResolve();+ clearScrollIdleTimer();+ suspendedByScroll = false;+ setHoveredTarget(null);+};++const isTouchPointerEvent = (event: PointerEvent | MouseEvent): boolean =>+ 'pointerType' in event && event.pointerType === 'touch';++const handlePointerActivity = (event: PointerEvent | MouseEvent): void => {+ if (isTouchPointerEvent(event)) {+ return;+ }+ pointerPosition = {x: event.clientX, y: event.clientY};+ scheduleResolve();+};++const handlePointerWindowExit = (event: PointerEvent | MouseEvent): void => {+ if (isTouchPointerEvent(event) || event.relatedTarget != null) {+ return;+ }+ forgetPointerPosition();+};++const handlePointerMotion = (event: PointerEvent | MouseEvent): void => {+ if (isTouchPointerEvent(event)) {+ return;+ }+ pointerPosition = {x: event.clientX, y: event.clientY};+ if (suspendedByScroll) {+ resumeAfterScroll();+ return;+ }+ scheduleResolve();+};++const handleScroll = (): void => {+ suspendedByScroll = true;+ cancelScheduledResolve();+ setHoveredTarget(null);+ clearScrollIdleTimer();+ scrollIdleTimer = setTimeout(resumeAfterScroll, SCROLL_IDLE_MS);+};++const handleLayoutChange = (): void => {+ scheduleResolve();+};++const supportsPointerEvents = (): boolean => 'PointerEvent' in window;++const attachGlobalListeners = (): void => {+ if (globalListenersAttached) {+ return;+ }+ globalListenersAttached = true;+ if (supportsPointerEvents()) {+ window.addEventListener('pointermove', handlePointerMotion, true);+ window.addEventListener('pointerdown', handlePointerMotion, true);+ window.addEventListener('pointerover', handlePointerActivity, true);+ window.addEventListener('pointerout', handlePointerWindowExit, true);+ } else {+ window.addEventListener('mousemove', handlePointerMotion, true);+ window.addEventListener('mousedown', handlePointerMotion, true);+ window.addEventListener('mouseover', handlePointerActivity, true);+ window.addEventListener('mouseout', handlePointerWindowExit, true);+ }+ window.addEventListener('scroll', handleScroll, true);+ window.addEventListener('resize', handleLayoutChange);+ window.addEventListener('blur', forgetPointerPosition);+};++const detachGlobalListeners = (): void => {+ if (!globalListenersAttached) {+ return;+ }+ globalListenersAttached = false;+ clearScrollIdleTimer();+ suspendedByScroll = false;+ if (supportsPointerEvents()) {+ window.removeEventListener('pointermove', handlePointerMotion, true);+ window.removeEventListener('pointerdown', handlePointerMotion, true);+ window.removeEventListener('pointerover', handlePointerActivity, true);+ window.removeEventListener('pointerout', handlePointerWindowExit, true);+ } else {+ window.removeEventListener('mousemove', handlePointerMotion, true);+ window.removeEventListener('mousedown', handlePointerMotion, true);+ window.removeEventListener('mouseover', handlePointerActivity, true);+ window.removeEventListener('mouseout', handlePointerWindowExit, true);+ }+ window.removeEventListener('scroll', handleScroll, true);+ window.removeEventListener('resize', handleLayoutChange);+ window.removeEventListener('blur', forgetPointerPosition);+};++export function registerMessageHoverTarget(element: HTMLElement, listener: MessageHoverListener): () => void {+ hoverTargets.set(element, listener);+ attachGlobalListeners();+ scheduleResolve();+ return () => {+ if (hoverTargets.get(element) !== listener) {+ return;+ }+ hoverTargets.delete(element);+ if (hoveredTarget === element) {+ hoveredTarget = null;+ listener(false);+ }+ if (hoverTargets.size > 0) {+ scheduleResolve();+ return;+ }+ detachGlobalListeners();+ cancelScheduledResolve();+ hoveredTarget = null;+ };+}++export function refreshMessageHoverTargets(): void {+ scheduleResolve();+}++export function resolveMessageHoverTargetsNow(): void {+ if (suspendedByScroll) {+ return;+ }+ cancelScheduledResolve();+ setHoveredTarget(resolveHoveredTarget());+}++export function resetMessageHoverTrackingForTests(): void {+ detachGlobalListeners();+ cancelScheduledResolve();+ clearScrollIdleTimer();+ suspendedByScroll = false;+ hoverTargets.clear();+ pointerPosition = null;+ hoveredTarget = null;+}diff --git a/fluxer_app/src/features/channel/state/MessageHoverTrackingRollout.test.ts b/fluxer_app/src/features/channel/state/MessageHoverTrackingRollout.test.tsnew file mode 100644index 000000000..23b375763--- /dev/null+++ b/fluxer_app/src/features/channel/state/MessageHoverTrackingRollout.test.ts@@ -0,0 +1,75 @@+// @vitest-environment happy-dom+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ type ExperimentAssignmentsResponse,+ INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE,+} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {+ INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT,+ type MessageHoverTrackingAssignmentResponse,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';+import {runInAction} from 'mobx';+import {afterEach, describe, expect, it, vi} from 'vitest';++vi.mock('@app/features/platform/utils/AppLogger', () => ({+ Logger: class {+ debug = vi.fn();+ info = vi.fn();+ warn = vi.fn();+ error = vi.fn();+ },+}));++vi.mock('@app/features/platform/transport/RestTransport', () => ({+ http: {get: vi.fn(), post: vi.fn()},+}));++const {ExperimentAssignments} = await import('@app/features/experiment/state/ExperimentAssignments');+const {MessageHoverTrackingRollout} = await import('@app/features/channel/state/MessageHoverTrackingRollout');++function publish(assignment: MessageHoverTrackingAssignmentResponse): void {+ const response: ExperimentAssignmentsResponse = {+ poll_interval_seconds: 300,+ poll_jitter_percent: 15,+ assignments: {message_hover_tracking: assignment},+ };+ runInAction(() => {+ ExperimentAssignments.response = response;+ });+}++afterEach(() => {+ runInAction(() => {+ ExperimentAssignments.response = INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE;+ });+});++describe('MessageHoverTrackingRollout', () => {+ it('reads the inert assignment out of the inert envelope', () => {+ expect(MessageHoverTrackingRollout.assignment).toBe(INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT);+ expect(MessageHoverTrackingRollout.enabled).toBe(false);+ });++ it('stays on the control arm while the rollout is disabled', () => {+ publish({enabled: false, config_version: 4, user_targeted: false, source: null});+ expect(MessageHoverTrackingRollout.enabled).toBe(false);+ });++ it('stays on the control arm for an account the rollout did not target', () => {+ publish({enabled: true, config_version: 4, user_targeted: false, source: null});+ expect(MessageHoverTrackingRollout.enabled).toBe(false);+ });++ it('moves to the experiment arm for a targeted account', () => {+ publish({enabled: true, config_version: 4, user_targeted: true, source: 'canary'});+ expect(MessageHoverTrackingRollout.enabled).toBe(true);+ });++ it('follows the envelope back to the control arm when the store is reset', () => {+ publish({enabled: true, config_version: 4, user_targeted: true, source: 'user_rule'});+ expect(MessageHoverTrackingRollout.enabled).toBe(true);+ ExperimentAssignments.reset();+ expect(MessageHoverTrackingRollout.enabled).toBe(false);+ });+});diff --git a/fluxer_app/src/features/channel/state/MessageHoverTrackingRollout.ts b/fluxer_app/src/features/channel/state/MessageHoverTrackingRollout.tsnew file mode 100644index 000000000..ed48ccfeb--- /dev/null+++ b/fluxer_app/src/features/channel/state/MessageHoverTrackingRollout.ts@@ -0,0 +1,22 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import ExperimentAssignments from '@app/features/experiment/state/ExperimentAssignments';+import {readMessageHoverTrackingAssignment} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import type {MessageHoverTrackingAssignmentResponse} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';++export const MESSAGE_HOVER_TRACKING_EXPERIMENT_CLASS = 'experiment-message-hover-tracking';++class MessageHoverTrackingRolloutSelector {+ get assignment(): MessageHoverTrackingAssignmentResponse {+ return readMessageHoverTrackingAssignment(ExperimentAssignments.response);+ }++ get enabled(): boolean {+ const assignment = this.assignment;+ return assignment.enabled && assignment.user_targeted;+ }+}++export const MessageHoverTrackingRollout = new MessageHoverTrackingRolloutSelector();++export default MessageHoverTrackingRollout;diff --git a/fluxer_app/src/features/theme/styles/Message.module.css b/fluxer_app/src/features/theme/styles/Message.module.cssindex ebe2ee340..630964371 100644--- a/fluxer_app/src/features/theme/styles/Message.module.css+++ b/fluxer_app/src/features/theme/styles/Message.module.css@@ -75,18 +75,34 @@}}-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.messageHovered:not(.messageMentioned):not(.messageReplying):not(.messageHighlight):not(.messagePreview),-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.messageHovered:not(.messageMentioned):not(.messageReplying):not(.messageHighlight):not(.messagePreview) {background-color: var(--background-modifier-hover);}-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.messageMentioned.messageHovered,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.messageMentioned.messageHovered {background-color: var(--message-mention-bg-hover);}@@ -98,13 +114,29 @@background-color: var(--message-mention-bg);}-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.messageReplying.messageHovered:not(.messageMentioned),-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.messageHighlight.messageHovered:not(.messageMentioned),-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.messageReplying.messageHovered:not(.messageMentioned),-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.messageHighlight.messageHovered:not(.messageMentioned) {background-color: var(--message-reply-bg);}@@ -127,9 +159,17 @@}@media (pointer: coarse) {- :global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+ :global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message:hover,- :global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+ :global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact:hover {background-color: transparent;}@@ -578,7 +618,11 @@transform: translateX(0.5rem);}-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.messageHovered.messageTimestampHover {opacity: 1;@@ -586,7 +630,11 @@}@media (pointer: coarse) {- :global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+ :global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message:hover.messageTimestampHover {opacity: 0;@@ -650,7 +698,11 @@margin-inline-end: 0;}-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.messageHovered.messageTimestampCompactHover {opacity: 1;@@ -658,7 +710,11 @@}@media (pointer: coarse) {- :global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+ :global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact:hover.messageTimestampCompactHover {opacity: 0;@@ -678,40 +734,80 @@min-inline-size: 0;}-.message .buttons,-.messageCompact .buttons {+:global(html:not(.experiment-message-hover-tracking)) .message .buttons,+:global(html:not(.experiment-message-hover-tracking)) .messageCompact .buttons {opacity: 0;pointer-events: none;}-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.messageHovered.buttons,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.buttons:hover,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.buttons:has(:focus-visible),-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.selected.buttons,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message.buttons.emojiPickerOpen,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.messageHovered.buttons,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.buttons:hover,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.buttons:has(:focus-visible),-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.selected.buttons,-:global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+:global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact.buttons.emojiPickerOpen {opacity: 1;@@ -719,10 +815,18 @@}@media (pointer: coarse) {- :global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+ :global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).message:hover.buttons,- :global(:where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard))+ :global(+ :where(html.window-focused, html.unfocused-fully-interactive):not(.window-focus-activation-guard):not(+ .experiment-message-hover-tracking+ )+ ).messageCompact:hover.buttons {opacity: 0;@@ -1422,15 +1526,21 @@max-inline-size: calc(100% - var(--message-compact-text-start));}-.contextMenuActive {+:global(html:not(.experiment-message-hover-tracking)) .contextMenuActive,+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .contextMenuActive {background-color: var(--background-modifier-hover) !important;}-:global(html.reduced-motion) .contextMenuActive {+:global(html.reduced-motion:not(.experiment-message-hover-tracking)) .contextMenuActive {background-color: transparent !important;}-.contextMenuActive .buttons {+:global(html.reduced-motion.experiment-message-hover-tracking) .contextMenuActive {+ background-color: var(--background-modifier-hover) !important;+}++:global(html:not(.experiment-message-hover-tracking)) .contextMenuActive .buttons {opacity: 1 !important;pointer-events: auto !important;}@@ -1445,7 +1555,9 @@pointer-events: auto !important;}-.contextMenuActive.messageMentioned {+:global(html:not(.experiment-message-hover-tracking)) .contextMenuActive.messageMentioned,+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .contextMenuActive.messageMentioned {background-color: var(--message-mention-bg-hover) !important;}@@ -1453,8 +1565,12 @@background-color: var(--message-mention-bg) !important;}-.contextMenuActive.messageReplying:not(.messageMentioned),-.contextMenuActive.messageHighlight:not(.messageMentioned) {+:global(html:not(.experiment-message-hover-tracking)) .contextMenuActive.messageReplying:not(.messageMentioned),+:global(html:not(.experiment-message-hover-tracking)) .contextMenuActive.messageHighlight:not(.messageMentioned),+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .contextMenuActive.messageReplying:not(.messageMentioned),+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .contextMenuActive.messageHighlight:not(.messageMentioned) {background-color: var(--message-reply-bg) !important;}@@ -1463,20 +1579,27 @@background-color: var(--message-reply-bg) !important;}-.keyboardFocused {+:global(html:not(.experiment-message-hover-tracking)) .keyboardFocused,+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive)) .keyboardFocused {background-color: var(--background-modifier-hover);}-.keyboardFocused.messageMentioned {+:global(html:not(.experiment-message-hover-tracking)) .keyboardFocused.messageMentioned,+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .keyboardFocused.messageMentioned {background-color: var(--message-mention-bg);}-.keyboardFocused.messageReplying:not(.messageMentioned),-.keyboardFocused.messageHighlight:not(.messageMentioned) {+:global(html:not(.experiment-message-hover-tracking)) .keyboardFocused.messageReplying:not(.messageMentioned),+:global(html:not(.experiment-message-hover-tracking)) .keyboardFocused.messageHighlight:not(.messageMentioned),+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .keyboardFocused.messageReplying:not(.messageMentioned),+:global(html.experiment-message-hover-tracking:where(.window-focused, .unfocused-fully-interactive))+ .keyboardFocused.messageHighlight:not(.messageMentioned) {background-color: var(--message-reply-bg);}-.keyboardFocused .buttons {+:global(html:not(.experiment-message-hover-tracking)) .keyboardFocused .buttons {opacity: 1;pointer-events: auto;}diff --git a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.test.ts b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.test.tsnew file mode 100644index 000000000..f7c43eb99--- /dev/null+++ b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.test.ts@@ -0,0 +1,78 @@+// @vitest-environment happy-dom+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ canUseWindowFocusedHoverControls,+ createWindowFocusInteractionGuard,+ isWindowFocusActivationGuardActive,+ subscribeWindowHoverControlsChange,+ WINDOW_FOCUSED_CLASS,+ type WindowFocusInteractionGuard,+} from '@app/features/ui/utils/WindowFocusInteractionGuard';+import {afterEach, describe, expect, it} from 'vitest';++const GUARD_TIMEOUT_MS = 10;++let activeGuard: WindowFocusInteractionGuard | null = null;+let unsubscribe: (() => void) | null = null;++function createFocusedGuard(): {guard: WindowFocusInteractionGuard; root: HTMLElement; observed: Array<boolean>} {+ const root = document.createElement('div');+ root.classList.add(WINDOW_FOCUSED_CLASS);+ document.body.append(root);+ const guard = createWindowFocusInteractionGuard({+ root,+ guardTimeoutMs: GUARD_TIMEOUT_MS,+ releaseClearDelayMs: 5,+ maxGuardTimeoutMs: 200,+ });+ activeGuard = guard;+ const observed: Array<boolean> = [];+ unsubscribe = subscribeWindowHoverControlsChange(() => observed.push(canUseWindowFocusedHoverControls(root)));+ return {guard, root, observed};+}++function wait(ms: number): Promise<void> {+ return new Promise((resolve) => {+ setTimeout(resolve, ms);+ });+}++afterEach(() => {+ unsubscribe?.();+ unsubscribe = null;+ activeGuard?.destroy();+ activeGuard = null;+ document.body.replaceChildren();+});++describe('WindowFocusInteractionGuard', () => {+ it('never publishes an enabled edge between refocus and the activation guard', async () => {+ const {guard, root, observed} = createFocusedGuard();++ guard.setFocused(false);+ guard.setFocused(true);++ expect(observed).toEqual([false]);+ expect(isWindowFocusActivationGuardActive(root)).toBe(true);+ expect(canUseWindowFocusedHoverControls(root)).toBe(false);++ await wait(GUARD_TIMEOUT_MS * 3);++ expect(observed).toEqual([false, true]);+ expect(canUseWindowFocusedHoverControls(root)).toBe(true);+ });++ it('does not publish an enabled edge while tearing down a guarded window', () => {+ const {guard, observed} = createFocusedGuard();++ guard.setFocused(false);+ guard.setFocused(true);+ observed.length = 0;++ guard.destroy();+ activeGuard = null;++ expect(observed).toEqual([]);+ });+});diff --git a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.ts b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.tsindex 6c222f1b1..63069661e 100644--- a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.ts+++ b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.ts@@ -141,14 +141,20 @@ export function createWindowFocusInteractionGuard({return {setFocused(nextFocused: boolean): void {focused = nextFocused;- root.classList.toggle(WINDOW_FOCUSED_CLASS, nextFocused);- notifyHoverControlsChange();if (!nextFocused) {+ root.classList.toggle(WINDOW_FOCUSED_CLASS, false);+ notifyHoverControlsChange();wasBlurred = true;clearActivationGuard();return;}- if (wasBlurred) {+ const shouldGuardActivation = wasBlurred;+ if (shouldGuardActivation) {+ root.classList.add(WINDOW_FOCUS_ACTIVATION_GUARD_CLASS);+ }+ root.classList.toggle(WINDOW_FOCUSED_CLASS, true);+ notifyHoverControlsChange();+ if (shouldGuardActivation) {beginActivationGuard(false);}wasBlurred = false;@@ -162,9 +168,8 @@ export function createWindowFocusInteractionGuard({windowTarget.removeEventListener('pointercancel', handlePointerEnd, true);windowTarget.removeEventListener('click', handlePointerEnd, true);classObserver?.disconnect();- clearActivationGuard();root.classList.remove(WINDOW_FOCUSED_CLASS);- notifyHoverControlsChange();+ clearActivationGuard();},};}diff --git a/fluxer_docs/src/content/docs/admin-api/instance.mdx b/fluxer_docs/src/content/docs/admin-api/instance.mdxindex f34f6d087..1adbd0cc0 100644--- a/fluxer_docs/src/content/docs/admin-api/instance.mdx+++ b/fluxer_docs/src/content/docs/admin-api/instance.mdx@@ -36,6 +36,7 @@ Missing settings use the defaults documented below. Invalid stored configuration| gateway_rollout | [Gateway rollout configuration](#gateway-rollout-configuration-object) object | Gateway admission and dispatch tuning || voice_noise_suppression | [voice noise suppression configuration](#voice-noise-suppression-configuration-object) object | Client-side noise suppression rollout || experiment_delivery | [experiment delivery configuration](#experiment-delivery-configuration-object) object | Cadence every client polls the experiments route on |+| message_hover_tracking | [message hover tracking configuration](#message-hover-tracking-configuration-object) object | Message hover implementation rollout || registration | [registration configuration](#registration-configuration-object) object | Registration policy, issued URLs, and pending registrations || self_hosted | boolean | Whether the deployment runs in self-hosted mode || app_public | [public application configuration](#public-application-configuration-object) object | Branding, legal, setup, and registration field policy |@@ -136,6 +137,27 @@ Every field is present on read. An absent document or missing field uses the defBoth fields are served to every account, whether or not any experiment targets that account, and neither one is versioned by `config_version`. A client that has never received a response from the experiments route uses built-in defaults of 300 seconds and 15 percent, which equal the defaults above. A client that cannot read the route never receives either field.+## Message hover tracking configuration object++The instance rollout of the message hover implementation the client runs in the message list. [Experiments](/http-api/experiments/) defines what a client resolves from it.++### Structure++| Field | Type | Description |+| --- | --- | --- |+| enabled | boolean | Whether the rollout runs at all (default false) |+| config_version | integer | Revision counter, raised by Fluxer and never accepted from a request |+| rollout_basis_points | integer | Share of accounts drawn, in basis points (0-10000, default 0) |+| rollout_salt | string | Salt of the sampling hash (1-64 characters, default `message-hover-tracking-v1`) |+| included_user_ids | array[snowflake] | Accounts always drawn, up to 1000 entries (default empty) |+| excluded_user_ids | array[snowflake] | Accounts never drawn, up to 1000 entries (default empty) |++Every field is present on read. An absent document or missing field uses the defaults above.++`excluded_user_ids` is applied before `included_user_ids`, so an account in both is never drawn. A drawn client resolves the hovered message from one shared pointer oracle, and a client that is not drawn keeps the per-row implementation it ships with. Neither arm changes any response this API produces.++How often a client revalidates this rollout is set once for every experiment in the [experiment delivery configuration](#experiment-delivery-configuration-object) above.+## Registration configuration objectRegistration policy in force, plus every issued registration URL and every account awaiting a decision.@@ -526,6 +548,7 @@ The body has one optional object for each section. Fluxer leaves an absent secti| gateway_rollout? | object | Any subset of the [Gateway rollout configuration](#gateway-rollout-configuration-object) fields, each bound as documented there || voice_noise_suppression? | object | Any subset of the [noise suppression](#voice-noise-suppression-configuration-object) fields || experiment_delivery? | object | Any subset of the [experiment delivery](#experiment-delivery-configuration-object) fields |+| message_hover_tracking? | object | Any subset of the [message hover tracking](#message-hover-tracking-configuration-object) fields || registration? | object | `mode` and `admin_registration_urls_enabled` || app_public?<sup>2</sup> | object | `branding`, `setup`, `legal`, and `registration` sub-objects, each merged field by field || integrations?<sup>3</sup> | object | `gif`, `youtube`, `captcha`, `email`, and `bluesky` sub-objects, the last of which also has the `keys` array |@@ -538,6 +561,8 @@ The body has one optional object for each section. Fluxer leaves an absent secti`voice_noise_suppression` takes every [voice noise suppression configuration](#voice-noise-suppression-configuration-object) field except `config_version`, each bound as documented there. Fluxer raises `config_version` by one on each request that supplies at least one of them. A section that is absent, or present with no field set, writes nothing and leaves `config_version` alone.+`message_hover_tracking` takes every [message hover tracking configuration](#message-hover-tracking-configuration-object) field except `config_version`, each bound as documented there. Fluxer raises that section's own `config_version` by one on each request that supplies at least one of them, independently of the noise suppression revision. A section that is absent, or present with no field set, writes nothing and leaves `config_version` alone.+`experiment_delivery` takes both [experiment delivery configuration](#experiment-delivery-configuration-object) fields, each bound as documented there. It is a section of its own, so a write to it changes no `config_version` and changes no assignment, only the cadence on which clients ask for one.<sup>3</sup> A secret such as `klipy_api_key`, `api_key`, `hcaptcha_secret_key`, `turnstile_secret_key`, or the SMTP `password` is written when supplied and left alone when absent. `integrations.bluesky.keys` is the only way to write the Bluesky signing keys counted as `bluesky.key_count`. It takes up to 8 entries of `kid` (1-255 characters) and nullable `private_key` (up to 10000 characters), and replaces the stored key set outright@@ -574,7 +599,7 @@ Fluxer skips URL validation while the merged configuration leaves single sign-on| 400 | [error response](/admin-api/#error-response) | A policy transition is refused, returned as `INSTANCE_POLICY_TRANSITION_NOT_ALLOWED` |:::caution[Sections are applied one after another]-The order is `gateway_rollout`, `voice_noise_suppression`, `experiment_delivery`, `sso`, `registration`, `app_public` branding, legal, and registration fields, `integrations`, `media`, `policy`, and finally `app_public.setup`. A failure part way through leaves the earlier sections written.+The order is `gateway_rollout`, `voice_noise_suppression`, `message_hover_tracking`, `experiment_delivery`, `sso`, `registration`, `app_public` branding, legal, and registration fields, `integrations`, `media`, `policy`, and finally `app_public.setup`. A failure part way through leaves the earlier sections written.:::### Side effectsdiff --git a/fluxer_docs/src/content/docs/http-api/experiments.mdx b/fluxer_docs/src/content/docs/http-api/experiments.mdxindex 1ae1deacd..383daf92b 100644--- a/fluxer_docs/src/content/docs/http-api/experiments.mdx+++ b/fluxer_docs/src/content/docs/http-api/experiments.mdx@@ -1,12 +1,12 @@---# SPDX-License-Identifier: AGPL-3.0-or-latertitle: Experiments-description: The experiment assignments envelope, the revalidation and polling contract, and the noise suppression experiment.+description: The experiment assignments envelope, the revalidation and polling contract, and the experiments this server defines.---import RouteHeader from '@/components/RouteHeader.astro';-An experiment is an instance-wide rollout that an operator configures. For each account, Fluxer works out from that configuration whether the account is in the rollout and which settings the account receives. The single route on this page resolves every experiment the server defines and returns them in one envelope, together with the polling cadence they share. `voice_noise_suppression` is the only experiment defined today, and [Voice](/voice/) defines the placement protocol its assignment applies to.+An experiment is an instance-wide rollout that an operator configures. For each account, Fluxer works out from that configuration whether the account is in the rollout and which settings the account receives. The single route on this page resolves every experiment the server defines and returns them in one envelope, together with the polling cadence they share. This server defines `voice_noise_suppression`, whose placement protocol [Voice](/voice/) defines, and `message_hover_tracking`, which selects one of two client implementations of the message hover state.Every assignment is advice. A client that ignores one behaves as it does with the rollout off, and no route and no Gateway event reports what a client actually ran.@@ -33,10 +33,11 @@ One entry per experiment. The envelope reports this object even when it is empty| Field | Type | Description || --- | --- | --- || voice_noise_suppression? | [noise suppression assignment](#noise-suppression-assignment-object) object | The caller's noise suppression assignment |+| message_hover_tracking? | [message hover tracking assignment](#message-hover-tracking-assignment-object) object | The caller's message hover tracking assignment |Ignore unknown experiments and treat a missing experiment as off.-This server version writes `voice_noise_suppression` on every response, including while the rollout is disabled. The disabled value is the first [resolution outcome](#resolution-outcomes) below, which reports `enabled` false and the stored `config_version`, so a client that compares `config_version` with the value from its previous response can see that an operator saved the noise suppression configuration, even while the rollout stays disabled, and needs no second request for it.+This server version writes `voice_noise_suppression` and `message_hover_tracking` on every response, including while a rollout is disabled. The disabled value is the first [resolution outcome](#resolution-outcomes) below, which reports `enabled` false and the stored `config_version`, so a client that compares `config_version` with the value from its previous response can see that an operator saved the configuration, even while the rollout stays disabled, and needs no second request for it.## Noise suppression backends@@ -102,6 +103,33 @@ One backend replacement scoped to one guild. While the caller is connected to aAn override naming a backend that is absent from `enabled_backends` is dropped before the response is written, so every entry is runnable.+## Message hover tracking assignment object++One resolution of the instance message hover tracking rollout against one account. Every field is present whenever the key is written.++The rollout selects which implementation of the message hover state a client runs. A drawn client resolves the hovered message from one shared pointer oracle and drives the message action bar from that state. A client that is not drawn keeps the per-row implementation it ships with. Neither arm changes what the API returns, and no route reports which arm a client ran.++### Structure++| Field | Type | Description |+| --- | --- | --- |+| enabled | boolean | Whether the rollout is running on this instance |+| config_version | integer | The revision of the instance configuration this assignment was resolved from |+| user_targeted | boolean | Whether the caller is inside the rollout |+| source | ?string | Which rule targeted the caller, one of `user_rule` or `canary`, and null where the caller is not targeted |++### Hover tracking resolution outcomes++The outcomes below set `user_targeted` to false, and they differ in what else they report.++1. The rollout is off. `enabled` is false and `source` is null.+2. The operator has excluded the caller. `enabled` is true and `source` is null.+3. The caller was not drawn. `enabled` is true and `source` is null.++A caller is drawn either by the operator's allowlist, which sets `source` to `user_rule`, or by the sampled share of the account population, which sets `source` to `canary`. The blocklist is read before the allowlist, so an account named in both is not drawn.++`config_version` reports the stored revision in all outcomes, the rollout being off included. A client branches on `user_targeted` alone.+## Get experiment assignments<RouteHeader method="GET" path="/v1/experiments" bot />diff --git a/packages/schema/src/domains/admin/AdminSchemas.ts b/packages/schema/src/domains/admin/AdminSchemas.tsindex 2ad8e84df..dbfd1f38d 100644--- a/packages/schema/src/domains/admin/AdminSchemas.ts+++ b/packages/schema/src/domains/admin/AdminSchemas.ts@@ -23,6 +23,10 @@ import {ExperimentDeliveryConfigResponse,ExperimentDeliveryConfigUpdateRequest,} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+import {+ MessageHoverTrackingConfigResponse,+ MessageHoverTrackingConfigUpdateRequest,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {GuildMemberResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';import {InstanceCaptchaProviderSchema,@@ -630,6 +634,7 @@ export const InstanceConfigResponse = z.object({gateway_rollout: GatewayRolloutConfigResponse,voice_noise_suppression: VoiceNoiseSuppressionConfigResponse,experiment_delivery: ExperimentDeliveryConfigResponse,+ message_hover_tracking: MessageHoverTrackingConfigResponse,registration: InstanceRegistrationResponse,self_hosted: z.boolean(),app_public: AppPublicConfigResponse,@@ -666,6 +671,7 @@ export const InstanceConfigUpdateRequest = z.object({gateway_rollout: GatewayRolloutConfigUpdateRequest.nullish(),voice_noise_suppression: VoiceNoiseSuppressionConfigUpdateRequest.nullish(),experiment_delivery: ExperimentDeliveryConfigUpdateRequest.nullish(),+ message_hover_tracking: MessageHoverTrackingConfigUpdateRequest.nullish(),registration: z.object({mode: InstanceRegistrationModeSchema.optional(),diff --git a/packages/schema/src/domains/experiment/ClientBehaviorExperiment.ts b/packages/schema/src/domains/experiment/ClientBehaviorExperiment.tsnew file mode 100644index 000000000..1ccd1ce3f--- /dev/null+++ b/packages/schema/src/domains/experiment/ClientBehaviorExperiment.ts@@ -0,0 +1,59 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {EXPERIMENT_BUCKET_RESOLUTION, experimentBucket} from '@fluxer/schema/src/domains/experiment/ExperimentBucket';+import {z} from 'zod';++const CLIENT_BEHAVIOR_MAX_TARGETED_USERS = 1000;+const CLIENT_BEHAVIOR_ASSIGNMENT_SOURCES = ['user_rule', 'canary'] as const;++export function createClientBehaviorExperiment({defaultRolloutSalt}: {defaultRolloutSalt: string}) {+ const targetIdSchema = z.string().regex(/^\d{1,20}$/u);+ const targetedUserIdsSchema = z.array(targetIdSchema).max(CLIENT_BEHAVIOR_MAX_TARGETED_USERS);+ const configFields = {+ enabled: z.boolean(),+ config_version: z.number().int().min(0),+ rollout_basis_points: z.number().int().min(0).max(EXPERIMENT_BUCKET_RESOLUTION),+ rollout_salt: z.string().trim().min(1).max(64),+ included_user_ids: targetedUserIdsSchema,+ excluded_user_ids: targetedUserIdsSchema,+ };+ const ConfigSchema = z.object({+ enabled: configFields.enabled.default(false),+ config_version: configFields.config_version.default(0),+ rollout_basis_points: configFields.rollout_basis_points.default(0),+ rollout_salt: configFields.rollout_salt.default(defaultRolloutSalt),+ included_user_ids: configFields.included_user_ids.default([]),+ excluded_user_ids: configFields.excluded_user_ids.default([]),+ });+ const ConfigUpdateRequest = z.object(configFields).omit({config_version: true}).partial();+ const AssignmentResponse = z.object({+ enabled: configFields.enabled,+ config_version: z.number().int(),+ user_targeted: z.boolean(),+ source: z.enum(CLIENT_BEHAVIOR_ASSIGNMENT_SOURCES).nullable(),+ });+ type Config = z.infer<typeof ConfigSchema>;+ type Assignment = z.infer<typeof AssignmentResponse>;+ const DEFAULT_CONFIG: Config = ConfigSchema.parse({});+ const INERT_ASSIGNMENT: Assignment = {+ enabled: false,+ config_version: 0,+ user_targeted: false,+ source: null,+ };+ const resolveAssignment = (config: Config, userId: string): Assignment => {+ if (!config.enabled) {+ return {...INERT_ASSIGNMENT, config_version: config.config_version};+ }+ const shared = {enabled: true, config_version: config.config_version};+ if (config.excluded_user_ids.includes(userId)) {+ return {...shared, user_targeted: false, source: null};+ }+ if (config.included_user_ids.includes(userId)) {+ return {...shared, user_targeted: true, source: 'user_rule'};+ }+ const inCanary = experimentBucket(userId, config.rollout_salt) < config.rollout_basis_points;+ return {...shared, user_targeted: inCanary, source: inCanary ? 'canary' : null};+ };+ return {ConfigSchema, ConfigUpdateRequest, AssignmentResponse, DEFAULT_CONFIG, INERT_ASSIGNMENT, resolveAssignment};+}diff --git a/packages/schema/src/domains/experiment/ExperimentSchemas.ts b/packages/schema/src/domains/experiment/ExperimentSchemas.tsindex 73c36f9cc..a2f38e1a6 100644--- a/packages/schema/src/domains/experiment/ExperimentSchemas.ts+++ b/packages/schema/src/domains/experiment/ExperimentSchemas.ts@@ -4,6 +4,10 @@ import {INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,VoiceNoiseSuppressionAssignmentResponse,} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';+import {+ INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT,+ MessageHoverTrackingAssignmentResponse,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {z} from 'zod';export const EXPERIMENT_MIN_POLL_INTERVAL_SECONDS = 60;@@ -42,6 +46,7 @@ export type ExperimentDeliveryConfigResponse = z.infer<typeof ExperimentDeliveryconst ExperimentAssignmentsSchema = z.object({voice_noise_suppression: VoiceNoiseSuppressionAssignmentResponse.optional(),+ message_hover_tracking: MessageHoverTrackingAssignmentResponse.optional(),});export const ExperimentAssignmentsResponse = z.object({@@ -63,3 +68,9 @@ export function readVoiceNoiseSuppressionAssignment(): VoiceNoiseSuppressionAssignmentResponse {return response.assignments.voice_noise_suppression ?? INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT;}++export function readMessageHoverTrackingAssignment(+ response: ExperimentAssignmentsResponse,+): MessageHoverTrackingAssignmentResponse {+ return response.assignments.message_hover_tracking ?? INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT;+}diff --git a/packages/schema/src/domains/experiment/MessageHoverTrackingSchemas.ts b/packages/schema/src/domains/experiment/MessageHoverTrackingSchemas.tsnew file mode 100644index 000000000..82f27ebe6--- /dev/null+++ b/packages/schema/src/domains/experiment/MessageHoverTrackingSchemas.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createClientBehaviorExperiment} from '@fluxer/schema/src/domains/experiment/ClientBehaviorExperiment';+import type {z} from 'zod';++const messageHoverTracking = createClientBehaviorExperiment({defaultRolloutSalt: 'message-hover-tracking-v1'});++export const MessageHoverTrackingConfigSchema = messageHoverTracking.ConfigSchema;++export type MessageHoverTrackingConfig = z.infer<typeof MessageHoverTrackingConfigSchema>;++export const DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG: MessageHoverTrackingConfig = messageHoverTracking.DEFAULT_CONFIG;++export const MessageHoverTrackingConfigUpdateRequest = messageHoverTracking.ConfigUpdateRequest;++export type MessageHoverTrackingConfigUpdateRequest = z.infer<typeof MessageHoverTrackingConfigUpdateRequest>;++export const MessageHoverTrackingConfigResponse = messageHoverTracking.ConfigSchema;++export type MessageHoverTrackingConfigResponse = MessageHoverTrackingConfig;++export const MessageHoverTrackingAssignmentResponse = messageHoverTracking.AssignmentResponse;++export type MessageHoverTrackingAssignmentResponse = z.infer<typeof MessageHoverTrackingAssignmentResponse>;++export const INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT: MessageHoverTrackingAssignmentResponse =+ messageHoverTracking.INERT_ASSIGNMENT;++export function resolveMessageHoverTrackingAssignment(+ config: MessageHoverTrackingConfig,+ userId: string,+): MessageHoverTrackingAssignmentResponse {+ return messageHoverTracking.resolveAssignment(config, userId);+}diff --git a/packages/schema/src/domains/tests/MessageHoverTrackingSchemas.test.ts b/packages/schema/src/domains/tests/MessageHoverTrackingSchemas.test.tsnew file mode 100644index 000000000..b76db0f08--- /dev/null+++ b/packages/schema/src/domains/tests/MessageHoverTrackingSchemas.test.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {EXPERIMENT_BUCKET_RESOLUTION, experimentBucket} from '@fluxer/schema/src/domains/experiment/ExperimentBucket';+import {+ DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,+ MessageHoverTrackingConfigSchema,+ resolveMessageHoverTrackingAssignment,+} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';+import {describe, expect, it} from 'vitest';++const USER_ID = '1485064866382176262';+const OTHER_USER_ID = '1485064866382176263';++function config(overrides: Partial<ReturnType<typeof MessageHoverTrackingConfigSchema.parse>> = {}) {+ return MessageHoverTrackingConfigSchema.parse({...overrides});+}++describe('message hover tracking configuration', () => {+ it('defaults to a disabled rollout that targets nobody', () => {+ expect(DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG).toEqual({+ enabled: false,+ config_version: 0,+ rollout_basis_points: 0,+ rollout_salt: 'message-hover-tracking-v1',+ included_user_ids: [],+ excluded_user_ids: [],+ });+ });++ it('refuses a rollout wider than the bucket resolution', () => {+ expect(() => config({rollout_basis_points: EXPERIMENT_BUCKET_RESOLUTION + 1})).toThrow();+ });++ it('refuses a target that is not a snowflake', () => {+ expect(() => config({included_user_ids: ['not-a-snowflake']})).toThrow();+ });+});++describe('message hover tracking resolution', () => {+ it('reports the stored revision while the rollout is disabled', () => {+ const assignment = resolveMessageHoverTrackingAssignment(config({config_version: 3}), USER_ID);+ expect(assignment).toEqual({enabled: false, config_version: 3, user_targeted: false, source: null});+ });++ it('targets an allowlisted account regardless of its bucket', () => {+ const assignment = resolveMessageHoverTrackingAssignment(+ config({enabled: true, included_user_ids: [USER_ID]}),+ USER_ID,+ );+ expect(assignment).toEqual({enabled: true, config_version: 0, user_targeted: true, source: 'user_rule'});+ });++ it('keeps a blocklisted account out of a full rollout', () => {+ const assignment = resolveMessageHoverTrackingAssignment(+ config({+ enabled: true,+ rollout_basis_points: EXPERIMENT_BUCKET_RESOLUTION,+ excluded_user_ids: [USER_ID],+ }),+ USER_ID,+ );+ expect(assignment).toEqual({enabled: true, config_version: 0, user_targeted: false, source: null});+ });++ it('prefers the blocklist over the allowlist', () => {+ const assignment = resolveMessageHoverTrackingAssignment(+ config({enabled: true, included_user_ids: [USER_ID], excluded_user_ids: [USER_ID]}),+ USER_ID,+ );+ expect(assignment.user_targeted).toBe(false);+ });++ it('targets an account whose bucket falls inside the rollout', () => {+ const salt = DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG.rollout_salt;+ const bucket = experimentBucket(USER_ID, salt);+ const inside = resolveMessageHoverTrackingAssignment(+ config({enabled: true, rollout_basis_points: bucket + 1}),+ USER_ID,+ );+ const outside = resolveMessageHoverTrackingAssignment(+ config({enabled: true, rollout_basis_points: bucket}),+ USER_ID,+ );+ expect(inside).toEqual({enabled: true, config_version: 0, user_targeted: true, source: 'canary'});+ expect(outside).toEqual({enabled: true, config_version: 0, user_targeted: false, source: null});+ });++ it('separates two accounts under the same salt', () => {+ const salt = DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG.rollout_salt;+ expect(experimentBucket(USER_ID, salt)).not.toBe(experimentBucket(OTHER_USER_ID, salt));+ });++ it('moves an account when the salt changes', () => {+ expect(experimentBucket(USER_ID, 'message-hover-tracking-v1')).not.toBe(+ experimentBucket(USER_ID, 'message-hover-tracking-v2'),+ );+ });+});