A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(app): gate blocked group rendering behind an experiment (#2763)
Hampused10f9d32367
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.jsonindex 3326d2ece..cc9e3db14 100644--- a/fluxer_admin/openapi-admin.json+++ b/fluxer_admin/openapi-admin.json@@ -10565,6 +10565,7 @@"experiment_delivery": {"$ref": "#/components/schemas/ExperimentDeliveryConfigResponse"},"message_hover_tracking": {"$ref": "#/components/schemas/MessageHoverTrackingConfigResponse"},"message_keyboard_focus": {"$ref": "#/components/schemas/MessageKeyboardFocusConfigResponse"},+ "blocked_message_groups": {"$ref": "#/components/schemas/BlockedMessageGroupsConfigResponse"},"registration": {"type": "object","properties": {@@ -10970,6 +10971,7 @@"experiment_delivery","message_hover_tracking","message_keyboard_focus",+ "blocked_message_groups","registration","self_hosted","app_public",@@ -11115,6 +11117,10 @@"nullable": true,"allOf": [{"$ref": "#/components/schemas/MessageKeyboardFocusConfigUpdateRequest"}]},+ "blocked_message_groups": {+ "nullable": true,+ "allOf": [{"$ref": "#/components/schemas/BlockedMessageGroupsConfigUpdateRequest"}]+ },"registration": {"nullable": true,"type": "object",@@ -15171,6 +15177,24 @@"enum": ["open", "approval", "closed"],"type": "string"},+ "BlockedMessageGroupsConfigUpdateRequest": {+ "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}$"}+ }+ }+ },"MessageKeyboardFocusConfigUpdateRequest": {"type": "object","properties": {@@ -15271,6 +15295,36 @@"type": "string","enum": ["none", "standard", "gate", "speex", "rnnoise", "gtcrn", "deep_filter"]},+ "BlockedMessageGroupsConfigResponse": {+ "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": "blocked-message-groups-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+ },"MessageKeyboardFocusConfigResponse": {"type": "object","properties": {diff --git a/fluxer_admin/src/api/types/instance_config.rs b/fluxer_admin/src/api/types/instance_config.rsindex a9e121733..1842f768d 100644--- a/fluxer_admin/src/api/types/instance_config.rs+++ b/fluxer_admin/src/api/types/instance_config.rs@@ -28,6 +28,8 @@ pub struct InstanceConfigResponse {pub message_hover_tracking: MessageHoverTrackingConfigResponse,#[serde(default)]pub message_keyboard_focus: MessageKeyboardFocusConfigResponse,+ #[serde(default)]+ pub blocked_message_groups: BlockedMessageGroupsConfigResponse,}#[derive(Clone, Debug, Deserialize, Serialize)]@@ -617,6 +619,44 @@ pub struct MessageKeyboardFocusConfigUpdateRequest {pub excluded_user_ids: Option<Vec<String>>,}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(default)]+pub struct BlockedMessageGroupsConfigResponse {+ 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 BlockedMessageGroupsConfigResponse {+ fn default() -> Self {+ Self {+ enabled: false,+ config_version: 0,+ rollout_basis_points: 0,+ rollout_salt: "blocked-message-groups-v1".to_owned(),+ included_user_ids: Vec::new(),+ excluded_user_ids: Vec::new(),+ }+ }+}++#[derive(Clone, Debug, Default, Serialize)]+pub struct BlockedMessageGroupsConfigUpdateRequest {+ #[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 {@@ -738,6 +778,8 @@ pub struct InstanceConfigUpdateRequest {pub message_hover_tracking: Option<MessageHoverTrackingConfigUpdateRequest>,#[serde(skip_serializing_if = "Option::is_none")]pub message_keyboard_focus: Option<MessageKeyboardFocusConfigUpdateRequest>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub blocked_message_groups: Option<BlockedMessageGroupsConfigUpdateRequest>,}#[derive(Clone, Debug, Default, Serialize)]@@ -1076,12 +1118,16 @@ mod tests {.expect("default message hover tracking config");let keyboard = serde_json::from_value::<MessageKeyboardFocusConfigResponse>(json!({})).expect("default message keyboard focus config");+ let blocked = serde_json::from_value::<BlockedMessageGroupsConfigResponse>(json!({}))+ .expect("default blocked message groups 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 keyboard =serde_json::to_value(keyboard).expect("serializable message keyboard focus config");+ let blocked =+ serde_json::to_value(blocked).expect("serializable blocked message groups config");let generated_noise: generated_types::VoiceNoiseSuppressionConfigResponse =serde_json::from_value(noise.clone()).expect("generated noise config contract");let generated_delivery: generated_types::ExperimentDeliveryConfigResponse =@@ -1092,6 +1138,9 @@ mod tests {let generated_keyboard: generated_types::MessageKeyboardFocusConfigResponse =serde_json::from_value(keyboard.clone()).expect("generated message keyboard focus config contract");+ let generated_blocked: generated_types::BlockedMessageGroupsConfigResponse =+ serde_json::from_value(blocked.clone())+ .expect("generated blocked message groups config contract");assert_eq!(serde_json::to_value(generated_noise).expect("serializable generated noise config"),noise@@ -1111,11 +1160,17 @@ mod tests {.expect("serializable generated message keyboard focus config"),keyboard);+ assert_eq!(+ serde_json::to_value(generated_blocked)+ .expect("serializable generated blocked message groups config"),+ blocked+ );for (name, value) in [("VoiceNoiseSuppressionConfigResponse", noise),("ExperimentDeliveryConfigResponse", delivery),("MessageHoverTrackingConfigResponse", hover),("MessageKeyboardFocusConfigResponse", keyboard),+ ("BlockedMessageGroupsConfigResponse", blocked),] {for (field, value) in value.as_object().expect("config object") {assert_eq!(@@ -1172,6 +1227,29 @@ mod tests {);}+ #[test]+ fn blocked_message_groups_update_preserves_empty_lists_and_omitted_fields() {+ let update = BlockedMessageGroupsConfigUpdateRequest {+ 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::BlockedMessageGroupsConfigUpdateRequest>(+ value.clone(),+ )+ .expect("generated update contract");+ assert_eq!(+ value,+ json!({"included_user_ids": [], "excluded_user_ids": []})+ );+ assert_eq!(+ serde_json::to_value(BlockedMessageGroupsConfigUpdateRequest::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 d75d2f208..44c4c8d73 100644--- a/fluxer_admin/src/routes/system_actions.rs+++ b/fluxer_admin/src/routes/system_actions.rs@@ -6,22 +6,22 @@ use crate::{types::{AppBrandingConfigUpdateRequest, AppLegalConfigUpdateRequest,AppPublicConfigUpdateRequest, AppRegistrationConfigUpdateRequest,- AppSetupConfigUpdateRequest, CreateRegistrationUrlRequest,- DeferredPhoneGateUpdateRequest, ExperimentDeliveryConfigUpdateRequest,- GatewayRolloutConfigUpdateRequest, GatewayRolloutMode,- InstanceAttachmentDecayUpdateRequest, InstanceBlueskyIntegrationUpdateRequest,- InstanceBlueskyKeyIntegrationUpdateRequest, InstanceCaptchaIntegrationUpdateRequest,- InstanceConfigUpdateRequest, InstanceEmailIntegrationUpdateRequest,- InstanceEmailSmtpIntegrationUpdateRequest, InstanceEmailSmtpTestRequest,- InstanceGifIntegrationUpdateRequest, InstanceIntegrationsUpdateRequest,- InstanceMediaUpdateRequest, InstancePolicyUpdateRequest,- InstanceRegistrationConfigUpdateRequest, InstanceServicesUpdateRequest,- InstanceYoutubeIntegrationUpdateRequest, LimitConfigUpdateRequest, LimitRule,- LimitRuleFilters, MessageHoverTrackingConfigUpdateRequest,- MessageKeyboardFocusConfigUpdateRequest, NoiseSuppressionBackend, PremiumMode,- RegistrationMode, SsoConfigUpdateRequest, VOICE_NS_MAX_GUILD_OVERRIDES,- VOICE_NS_MAX_TARGETED_USERS, VoiceE2eeScope, VoiceNoiseSuppressionConfigUpdateRequest,- VoiceNoiseSuppressionGuildOverride,+ AppSetupConfigUpdateRequest, BlockedMessageGroupsConfigUpdateRequest,+ CreateRegistrationUrlRequest, DeferredPhoneGateUpdateRequest,+ ExperimentDeliveryConfigUpdateRequest, GatewayRolloutConfigUpdateRequest,+ GatewayRolloutMode, InstanceAttachmentDecayUpdateRequest,+ InstanceBlueskyIntegrationUpdateRequest, InstanceBlueskyKeyIntegrationUpdateRequest,+ InstanceCaptchaIntegrationUpdateRequest, InstanceConfigUpdateRequest,+ InstanceEmailIntegrationUpdateRequest, InstanceEmailSmtpIntegrationUpdateRequest,+ InstanceEmailSmtpTestRequest, InstanceGifIntegrationUpdateRequest,+ InstanceIntegrationsUpdateRequest, InstanceMediaUpdateRequest,+ InstancePolicyUpdateRequest, InstanceRegistrationConfigUpdateRequest,+ InstanceServicesUpdateRequest, InstanceYoutubeIntegrationUpdateRequest,+ LimitConfigUpdateRequest, LimitRule, LimitRuleFilters,+ MessageHoverTrackingConfigUpdateRequest, MessageKeyboardFocusConfigUpdateRequest,+ NoiseSuppressionBackend, PremiumMode, RegistrationMode, SsoConfigUpdateRequest,+ VOICE_NS_MAX_GUILD_OVERRIDES, VOICE_NS_MAX_TARGETED_USERS, VoiceE2eeScope,+ VoiceNoiseSuppressionConfigUpdateRequest, VoiceNoiseSuppressionGuildOverride,},},config::AdminConfig,@@ -216,6 +216,10 @@ pub async fn instance_config_post(Ok(update) => instance_config_result(client.update_instance_config(&update).await),Err(message) => FlashData::error(message),},+ "update_blocked_message_groups" => match build_blocked_message_groups_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),@@ -700,6 +704,35 @@ fn build_message_keyboard_focus_update(})}+fn build_blocked_message_groups_update(+ form: &MultiValueForm,+) -> Result<InstanceConfigUpdateRequest, String> {+ Ok(InstanceConfigUpdateRequest {+ blocked_message_groups: Some(BlockedMessageGroupsConfigUpdateRequest {+ enabled: Some(form.bool_value("blocked_groups_enabled")),+ rollout_basis_points: parse_form_number(+ form,+ "blocked_groups_rollout_basis_points",+ "Rollout basis points",+ 0,+ EXPERIMENT_ROLLOUT_BASIS_POINTS_MAX,+ )?,+ rollout_salt: parse_experiment_rollout_salt(form, "blocked_groups_rollout_salt")?,+ included_user_ids: Some(parse_experiment_user_ids(+ form.first("blocked_groups_included_user_ids")+ .unwrap_or_default(),+ "Included user IDs",+ )?),+ excluded_user_ids: Some(parse_experiment_user_ids(+ form.first("blocked_groups_excluded_user_ids")+ .unwrap_or_default(),+ "Excluded user IDs",+ )?),+ }),+ ..Default::default()+ })+}+fn build_experiment_delivery_update(form: &MultiValueForm,) -> Result<InstanceConfigUpdateRequest, String> {diff --git a/fluxer_admin/src/templates/pages/instance_config.rs b/fluxer_admin/src/templates/pages/instance_config.rsindex 353f1349b..c70ba8b64 100644--- a/fluxer_admin/src/templates/pages/instance_config.rs+++ b/fluxer_admin/src/templates/pages/instance_config.rs@@ -2,13 +2,13 @@use crate::{api::types::{- AppPublicConfigResponse, ExperimentDeliveryConfigResponse, GatewayRolloutConfigResponse,- InstanceConfigResponse, InstanceIntegrationsResponse, InstanceMediaResponse,- InstancePolicyResponse, InstanceRegistrationResponse, LimitConfigResponse,- MessageHoverTrackingConfigResponse, MessageKeyboardFocusConfigResponse,- NoiseSuppressionBackend, PendingRegistrationResponse, RegistrationUrlResponse,- SsoConfigResponse, VOICE_NS_MAX_GUILD_OVERRIDES, VOICE_NS_MAX_TARGETED_USERS,- VoiceNoiseSuppressionConfigResponse,+ AppPublicConfigResponse, BlockedMessageGroupsConfigResponse,+ ExperimentDeliveryConfigResponse, GatewayRolloutConfigResponse, InstanceConfigResponse,+ InstanceIntegrationsResponse, InstanceMediaResponse, InstancePolicyResponse,+ InstanceRegistrationResponse, LimitConfigResponse, MessageHoverTrackingConfigResponse,+ MessageKeyboardFocusConfigResponse, NoiseSuppressionBackend, PendingRegistrationResponse,+ RegistrationUrlResponse, SsoConfigResponse, VOICE_NS_MAX_GUILD_OVERRIDES,+ VOICE_NS_MAX_TARGETED_USERS, VoiceNoiseSuppressionConfigResponse,},config::AdminConfig,middleware::auth::AuthContext,@@ -151,6 +151,7 @@ pub fn instance_config_page((voice_noise_suppression_section(base, csrf_token, &instance_config.voice_noise_suppression))(message_hover_tracking_section(base, csrf_token, &instance_config.message_hover_tracking))(message_keyboard_focus_section(base, csrf_token, &instance_config.message_keyboard_focus))+ (blocked_message_groups_section(base, csrf_token, &instance_config.blocked_message_groups))(experiment_delivery_section(base, csrf_token, &instance_config.experiment_delivery))@if let Some(limit_config) = limit_config {(limit_config_section(base, limit_config))@@ -1386,6 +1387,110 @@ fn message_keyboard_focus_section()}+fn blocked_message_groups_section(+ base: &str,+ csrf_token: &str,+ blocked_message_groups: &BlockedMessageGroupsConfigResponse,+) -> Markup {+ let status = if blocked_message_groups.enabled {+ ("Live", BadgeVariant::Success)+ } else {+ ("Inert", BadgeVariant::Default)+ };+ let included_user_ids = blocked_message_groups.included_user_ids.join("\n");+ let excluded_user_ids = blocked_message_groups.excluded_user_ids.join("\n");+ section_card_with_description(+ "Blocked Message Groups",+ "Picks how targeted clients render a revealed block of blocked or suspected spam \+ messages. A targeted client draws the block full width, spaces consecutive message \+ groups inside it, and keys an unread divider apart from the group below it. While the \+ master switch below is off every client keeps the rendering it ships with, whatever the \+ rest of these fields say.",+ html! {+ form method="post" action={(base) "/instance-config?action=update_blocked_message_groups"} {+ (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 " (blocked_message_groups.config_version)+ }+ }+ (checkbox(+ "blocked_groups_enabled",+ "true",+ "Serve blocked message groups assignments to clients",+ blocked_message_groups.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 rendering, so the rollout \+ and targeting fields below have no effect at all."+ }++ h3 class="text-sm font-semibold text-neutral-900" { "Rollout" }+ (number_field(+ "blocked_groups_rollout_basis_points",+ "Rollout (basis points)",+ &blocked_message_groups.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(+ "blocked_groups_rollout_salt",+ "Rollout Salt",+ &blocked_message_groups.rollout_salt,+ "blocked-message-groups-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(+ "blocked_groups_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(+ "blocked_groups_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 Blocked Message Groups 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 acac8f7a2..7eb5eefbe 100644--- a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts@@ -31,6 +31,7 @@ import {import {GatewayRolloutConfigSchema} from '@fluxer/schema/src/domains/admin/GatewayRolloutSchemas';import {VoiceNoiseSuppressionConfigSchema} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';import {UserIdParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';+import {BlockedMessageGroupsConfigSchema} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {ExperimentDeliveryConfigSchema} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';import {MessageHoverTrackingConfigSchema} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {MessageKeyboardFocusConfigSchema} from '@fluxer/schema/src/domains/experiment/MessageKeyboardFocusSchemas';@@ -62,6 +63,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {experimentDelivery,messageHoverTracking,messageKeyboardFocus,+ blockedMessageGroups,registrationConfig,registrationUrls,pendingRegistrations,@@ -72,6 +74,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {instanceConfigRepository.getExperimentDeliveryConfig(),instanceConfigRepository.getMessageHoverTrackingConfig(),instanceConfigRepository.getMessageKeyboardFocusConfig(),+ instanceConfigRepository.getBlockedMessageGroupsConfig(),instanceConfigRepository.getRegistrationConfig(),instanceConfigRepository.getRegistrationUrlsForAdmin(),instanceConfigRepository.getPendingRegistrations(),@@ -105,6 +108,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {experiment_delivery: experimentDelivery,message_hover_tracking: messageHoverTracking,message_keyboard_focus: messageKeyboardFocus,+ blocked_message_groups: blockedMessageGroups,registration: {...registrationConfig,urls: registrationUrls,@@ -272,6 +276,18 @@ export function InstanceConfigAdminController(app: HonoApp) {await instanceConfigRepository.setMessageKeyboardFocusConfig(validated);}}+ if (data.blocked_message_groups) {+ const patch = omitUndefinedFields(data.blocked_message_groups);+ if (Object.keys(patch).length > 0) {+ const currentBlockedMessageGroups = await instanceConfigRepository.getBlockedMessageGroupsConfig();+ const validated = BlockedMessageGroupsConfigSchema.parse({+ ...currentBlockedMessageGroups,+ ...patch,+ config_version: currentBlockedMessageGroups.config_version + 1,+ });+ await instanceConfigRepository.setBlockedMessageGroupsConfig(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 aa7e9f861..3552a5ff8 100644--- a/fluxer_api/src/api/experiment/ExperimentController.ts+++ b/fluxer_api/src/api/experiment/ExperimentController.ts@@ -9,6 +9,7 @@ import type {HonoApp} from '@app/api/types/HonoEnv';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 {resolveBlockedMessageGroupsAssignment} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {ExperimentAssignmentsResponse} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';import {resolveMessageHoverTrackingAssignment} from '@fluxer/schema/src/domains/experiment/MessageHoverTrackingSchemas';import {resolveMessageKeyboardFocusAssignment} from '@fluxer/schema/src/domains/experiment/MessageKeyboardFocusSchemas';@@ -30,11 +31,18 @@ export function ExperimentController(app: HonoApp) {}),async (ctx) => {const instanceConfigRepository = ctx.get('instanceConfigRepository');- const [delivery, voiceConfig, messageHoverTrackingConfig, messageKeyboardFocusConfig] = await Promise.all([+ const [+ delivery,+ voiceConfig,+ messageHoverTrackingConfig,+ messageKeyboardFocusConfig,+ blockedMessageGroupsConfig,+ ] = await Promise.all([instanceConfigRepository.getExperimentDeliveryConfig(),instanceConfigRepository.getVoiceNoiseSuppressionConfig(),instanceConfigRepository.getMessageHoverTrackingConfig(),instanceConfigRepository.getMessageKeyboardFocusConfig(),+ instanceConfigRepository.getBlockedMessageGroupsConfig(),]);const userId = ctx.get('user').id.toString();const body: ExperimentAssignmentsResponse = {@@ -44,6 +52,7 @@ export function ExperimentController(app: HonoApp) {voice_noise_suppression: resolveVoiceNoiseSuppressionAssignment(voiceConfig, userId),message_hover_tracking: resolveMessageHoverTrackingAssignment(messageHoverTrackingConfig, userId),message_keyboard_focus: resolveMessageKeyboardFocusAssignment(messageKeyboardFocusConfig, userId),+ blocked_message_groups: resolveBlockedMessageGroupsAssignment(blockedMessageGroupsConfig, 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 a1c2ffefd..5d8e236b2 100644--- a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts+++ b/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts@@ -10,11 +10,16 @@ import {DEFAULT_VOICE_NOISE_SUPPRESSION_CONFIG,INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';+import {+ DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG,+ INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {DEFAULT_EXPERIMENT_POLL_INTERVAL_SECONDS,DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,type ExperimentAssignmentsResponse,type ExperimentDeliveryConfigResponse,+ readBlockedMessageGroupsAssignment,readMessageHoverTrackingAssignment,readMessageKeyboardFocusAssignment,readVoiceNoiseSuppressionAssignment,@@ -63,6 +68,7 @@ describe('GET /experiments', () => {voice_noise_suppression: INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,message_hover_tracking: INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT,message_keyboard_focus: INERT_MESSAGE_KEYBOARD_FOCUS_ASSIGNMENT,+ blocked_message_groups: INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT,},});});@@ -186,7 +192,53 @@ describe('GET /experiments', () => {});});- it('resolves all three experiments independently', async () => {+ it('populates the blocked message groups 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, 'blocked_message_groups')).toBe(true);+ expect(readBlockedMessageGroupsAssignment(body)).toEqual(INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT);+ });++ it('targets an allowlisted account for blocked message groups', async () => {+ const account = await createTestAccount(harness);+ await getInstanceConfigRepository().setBlockedMessageGroupsConfig({+ ...DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG,+ enabled: true,+ config_version: 4,+ included_user_ids: [account.userId],+ });++ const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();++ expect(readBlockedMessageGroupsAssignment(body)).toEqual({+ enabled: true,+ config_version: 4,+ user_targeted: true,+ source: 'user_rule',+ });+ });++ it('leaves an account outside a zero-width blocked message groups rollout', async () => {+ const account = await createTestAccount(harness);+ await getInstanceConfigRepository().setBlockedMessageGroupsConfig({+ ...DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG,+ enabled: true,+ config_version: 2,+ });++ const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();++ expect(readBlockedMessageGroupsAssignment(body)).toEqual({+ enabled: true,+ config_version: 2,+ user_targeted: false,+ source: null,+ });+ });++ it('resolves all four experiments independently', async () => {const account = await createTestAccount(harness);await getInstanceConfigRepository().setMessageHoverTrackingConfig({...DEFAULT_MESSAGE_HOVER_TRACKING_CONFIG,@@ -198,11 +250,17 @@ describe('GET /experiments', () => {enabled: true,rollout_basis_points: 10000,});+ await getInstanceConfigRepository().setBlockedMessageGroupsConfig({+ ...DEFAULT_BLOCKED_MESSAGE_GROUPS_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(readMessageKeyboardFocusAssignment(body).user_targeted).toBe(true);+ expect(readBlockedMessageGroupsAssignment(body).user_targeted).toBe(true);expect(readVoiceNoiseSuppressionAssignment(body).enabled).toBe(false);});diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.test.tsindex 32aa27258..a10ecf41c 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts@@ -13,6 +13,10 @@ import {DEFAULT_VOICE_NOISE_SUPPRESSION_CONFIG,type VoiceNoiseSuppressionConfig,} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';+import {+ type BlockedMessageGroupsConfig,+ DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {DEFAULT_EXPERIMENT_DELIVERY_CONFIG,type ExperimentDeliveryConfig,@@ -30,6 +34,7 @@ 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 MESSAGE_KEYBOARD_FOCUS_CONFIG_KEY = 'message_keyboard_focus_config';+const BLOCKED_MESSAGE_GROUPS_CONFIG_KEY = 'blocked_message_groups_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';@@ -412,6 +417,51 @@ describe('InstanceConfigRepository', () => {await expect(repository.getMessageKeyboardFocusConfig()).resolves.toEqual(config);});+ it('returns the default blocked message groups config when the key is absent', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await expect(repository.getBlockedMessageGroupsConfig()).resolves.toEqual(DEFAULT_BLOCKED_MESSAGE_GROUPS_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 blocked message groups config for $name', async ({stored}) => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig(BLOCKED_MESSAGE_GROUPS_CONFIG_KEY, stored);++ await expect(repository.getBlockedMessageGroupsConfig()).resolves.toEqual(DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG);+ });++ it('round-trips a stored blocked message groups config', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ const config: BlockedMessageGroupsConfig = {+ ...DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG,+ enabled: true,+ config_version: 5,+ rollout_basis_points: 2500,+ rollout_salt: 'blocked-message-groups-v2',+ included_user_ids: ['1400000000000000001'],+ excluded_user_ids: ['1400000000000000002'],+ };+ await repository.setBlockedMessageGroupsConfig(config);++ await expect(repository.getBlockedMessageGroupsConfig()).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 5ba9cb5b8..547f54255 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.ts@@ -32,6 +32,10 @@ import {type VoiceNoiseSuppressionConfig,VoiceNoiseSuppressionConfigSchema,} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';+import {+ type BlockedMessageGroupsConfig,+ BlockedMessageGroupsConfigSchema,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {type ExperimentDeliveryConfig,ExperimentDeliveryConfigSchema,@@ -65,6 +69,7 @@ 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 MESSAGE_KEYBOARD_FOCUS_CONFIG_KEY = 'message_keyboard_focus_config';+const BLOCKED_MESSAGE_GROUPS_CONFIG_KEY = 'blocked_message_groups_config';const REGISTRATION_CONFIG_KEY = 'registration_config';const REGISTRATION_URLS_KEY = 'registration_urls';const REGISTRATION_PENDING_APPROVALS_KEY = 'registration_pending_approvals';@@ -350,6 +355,7 @@ type StoredConfigSection =| 'experiment delivery'| 'message hover tracking'| 'message keyboard focus'+ | 'blocked message groups'| 'instance policy'| 'integrations'| 'media'@@ -499,6 +505,10 @@ function parseStoredMessageKeyboardFocusConfig(raw: string | null): MessageKeyboreturn parseStoredConfigOrDefault(MessageKeyboardFocusConfigSchema, raw, 'message keyboard focus');}+function parseStoredBlockedMessageGroupsConfig(raw: string | null): BlockedMessageGroupsConfig {+ return parseStoredConfigOrDefault(BlockedMessageGroupsConfigSchema, raw, 'blocked message groups');+}+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`);@@ -1020,6 +1030,7 @@ export class InstanceConfigRepository {parseStoredExperimentDeliveryConfig(snapshot.get(EXPERIMENT_DELIVERY_CONFIG_KEY) ?? null);parseStoredMessageHoverTrackingConfig(snapshot.get(MESSAGE_HOVER_TRACKING_CONFIG_KEY) ?? null);parseStoredMessageKeyboardFocusConfig(snapshot.get(MESSAGE_KEYBOARD_FOCUS_CONFIG_KEY) ?? null);+ parseStoredBlockedMessageGroupsConfig(snapshot.get(BLOCKED_MESSAGE_GROUPS_CONFIG_KEY) ?? null);const policy = parseStoredInstancePolicyConfig(snapshot.get(INSTANCE_POLICY_CONFIG_KEY) ?? null);checkStoredConfig('registration', () =>parseStoredRegistrationConfig(snapshot.get(REGISTRATION_CONFIG_KEY) ?? null),@@ -1125,6 +1136,16 @@ export class InstanceConfigRepository {await this.setConfig(MESSAGE_KEYBOARD_FOCUS_CONFIG_KEY, JSON.stringify(validated));}+ async getBlockedMessageGroupsConfig(): Promise<BlockedMessageGroupsConfig> {+ const raw = await this.getConfig(BLOCKED_MESSAGE_GROUPS_CONFIG_KEY);+ return parseStoredBlockedMessageGroupsConfig(raw);+ }++ async setBlockedMessageGroupsConfig(config: BlockedMessageGroupsConfig): Promise<void> {+ const validated = validateStoredConfig(BlockedMessageGroupsConfigSchema, config, 'blocked message groups');+ await this.setConfig(BLOCKED_MESSAGE_GROUPS_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 17aa3adfd..fa7f60c0a 100644--- a/fluxer_api/src/api/openapi/openapi.json+++ b/fluxer_api/src/api/openapi/openapi.json@@ -28260,7 +28260,8 @@"properties": {"voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionAssignmentResponse"},"message_hover_tracking": {"$ref": "#/components/schemas/MessageHoverTrackingAssignmentResponse"},- "message_keyboard_focus": {"$ref": "#/components/schemas/MessageKeyboardFocusAssignmentResponse"}+ "message_keyboard_focus": {"$ref": "#/components/schemas/MessageKeyboardFocusAssignmentResponse"},+ "blocked_message_groups": {"$ref": "#/components/schemas/BlockedMessageGroupsAssignmentResponse"}},"additionalProperties": false}@@ -31998,6 +31999,17 @@"additionalProperties": false},"DonationCurrency": {"type": "string", "enum": ["usd", "eur", "brl", "inr", "pln", "try"]},+ "BlockedMessageGroupsAssignmentResponse": {+ "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+ },"MessageKeyboardFocusAssignmentResponse": {"type": "object","properties": {diff --git a/fluxer_app/src/app/App.tsx b/fluxer_app/src/app/App.tsxindex 717aeef92..aea0a8a39 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 BlockedMessageGroupsRollout, {+ BLOCKED_MESSAGE_GROUPS_EXPERIMENT_CLASS,+} from '@app/features/channel/state/BlockedMessageGroupsRollout';import MessageHoverTrackingRollout, {MESSAGE_HOVER_TRACKING_EXPERIMENT_CLASS,} from '@app/features/channel/state/MessageHoverTrackingRollout';@@ -158,6 +161,7 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {useDocumentClassToggle('mobile-layout', MobileLayout.platformMobileDetected || MobileLayout.enabled);useDocumentClassToggle(UNFOCUSED_FULLY_INTERACTIVE_CLASS, stayInteractiveWhenUnfocused);useDocumentClassToggle(MESSAGE_HOVER_TRACKING_EXPERIMENT_CLASS, MessageHoverTrackingRollout.enabled);+ useDocumentClassToggle(BLOCKED_MESSAGE_GROUPS_EXPERIMENT_CLASS, BlockedMessageGroupsRollout.enabled);useDesktopAllowTransparency(isNative);useWindowEventListeners({preventDocumentScroll: !isNative});useRemScaleTracking();diff --git a/fluxer_app/src/features/channel/components/BlockedMessageGroups.module.css b/fluxer_app/src/features/channel/components/BlockedMessageGroups.module.cssindex 195bb2224..5bd889c43 100644--- a/fluxer_app/src/features/channel/components/BlockedMessageGroups.module.css+++ b/fluxer_app/src/features/channel/components/BlockedMessageGroups.module.css@@ -2,9 +2,28 @@.container {background-color: var(--background-secondary);+}++:global(html:not(.experiment-blocked-message-groups)) .container {border-radius: 0.25rem;}+:global(html.experiment-blocked-message-groups) .container {+ margin-left: calc(-1 * var(--chat-mobile-horizontal-padding));+ margin-right: calc(-1 * var(--chat-mobile-horizontal-padding));+ padding-left: var(--chat-mobile-horizontal-padding);+ padding-right: var(--chat-mobile-horizontal-padding);+}++@media (min-width: 768px) {+ :global(html.experiment-blocked-message-groups) .container {+ margin-left: calc(-1 * var(--chat-horizontal-padding));+ margin-right: calc(-1 * var(--chat-horizontal-padding));+ padding-left: var(--chat-horizontal-padding);+ padding-right: var(--chat-horizontal-padding);+ }+}+.toggle {display: flex;width: 100%;diff --git a/fluxer_app/src/features/channel/components/BlockedMessageGroups.test.tsx b/fluxer_app/src/features/channel/components/BlockedMessageGroups.test.tsxnew file mode 100644index 000000000..e2b5b5ef1--- /dev/null+++ b/fluxer_app/src/features/channel/components/BlockedMessageGroups.test.tsx@@ -0,0 +1,129 @@+// @vitest-environment happy-dom+// SPDX-License-Identifier: AGPL-3.0-or-later++import {act, createElement, type ReactNode} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';++const rolloutMock = {enabled: true};+const ChannelStreamType = {+ MESSAGE: 'MESSAGE',+ MESSAGE_GROUP_BLOCKED: 'MESSAGE_GROUP_BLOCKED',+ MESSAGE_GROUP_IGNORED: 'MESSAGE_GROUP_IGNORED',+ MESSAGE_GROUP_SPAMMER: 'MESSAGE_GROUP_SPAMMER',+ DIVIDER: 'DIVIDER',+} as const;++vi.mock('@app/features/messaging/utils/MessageGroupingUtils', () => ({ChannelStreamType}));++vi.mock('@app/features/channel/state/BlockedMessageGroupsRollout', () => ({default: rolloutMock}));+vi.mock('@lingui/core/macro', () => ({msg: (value: unknown) => value}));+vi.mock('@lingui/react/macro', () => ({useLingui: () => ({i18n: {_: () => 'blocked messages'}})}));+vi.mock('@app/features/channel/components/ChannelDivider', () => ({+ Divider: ({children}: {children?: ReactNode}) => createElement('div', {'data-divider': true}, children),+}));+vi.mock('@app/features/channel/components/MessageGroup', () => ({+ MessageGroup: () => createElement('div', {'data-message-group': true}),+}));++const {BlockedMessageGroups} = await import('@app/features/channel/components/BlockedMessageGroups');++(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;++const CHANNEL = {id: 'channel-1', guild_id: null} as never;+const SPACER_SELECTOR = '[data-flx="channel.blocked-message-groups.group-spacer"]';++let container: HTMLDivElement;+let root: Root;+let consoleError: ReturnType<typeof vi.spyOn>;++function message(id: string): Record<string, unknown> {+ return {id, author: {id: 'author-1'}, blocked: true};+}++beforeEach(() => {+ rolloutMock.enabled = true;+ container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+ consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ consoleError.mockRestore();+});++function renderRevealedGroup(messageGroups: Array<unknown>): void {+ act(() => {+ root.render(+ createElement(BlockedMessageGroups, {+ channel: CHANNEL,+ messageGroups: messageGroups as never,+ onReveal: () => undefined,+ revealed: true,+ compact: false,+ messageGroupSpacing: 8,+ variant: 'blocked',+ }),+ );+ });+}++function duplicateKeyWarnings(): Array<unknown> {+ return consoleError.mock.calls.filter((call: Array<unknown>) => String(call[0]).includes('same key'));+}++const DIVIDER_INSIDE_GROUP = [+ {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},+ {type: ChannelStreamType.DIVIDER, content: '', unreadId: '200', contentKey: 'divider-200'},+ {type: ChannelStreamType.MESSAGE, content: message('200'), contentKey: '200', groupId: 'g2'},+];++describe('BlockedMessageGroups experiment arm', () => {+ it('keys an unread divider apart from the message group below it', () => {+ renderRevealedGroup(DIVIDER_INSIDE_GROUP);++ expect(duplicateKeyWarnings()).toEqual([]);+ expect(container.querySelectorAll('[data-message-group]')).toHaveLength(2);+ });++ it('skips a divider that leads the revealed group', () => {+ renderRevealedGroup([+ {type: ChannelStreamType.DIVIDER, content: '', unreadId: '100', contentKey: 'divider-100'},+ {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},+ ]);++ expect(duplicateKeyWarnings()).toEqual([]);+ expect(container.querySelectorAll('[data-message-group]')).toHaveLength(1);+ expect(container.querySelectorAll('[data-divider]')).toHaveLength(0);+ });++ it('spaces consecutive groups apart inside the revealed block', () => {+ renderRevealedGroup([+ {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},+ {type: ChannelStreamType.MESSAGE, content: message('200'), contentKey: '200', groupId: 'g2'},+ {type: ChannelStreamType.MESSAGE, content: message('300'), contentKey: '300', groupId: 'g3'},+ ]);++ expect(container.querySelectorAll('[data-message-group]')).toHaveLength(3);+ expect(container.querySelectorAll(SPACER_SELECTOR)).toHaveLength(2);+ });+});++describe('BlockedMessageGroups control arm', () => {+ beforeEach(() => {+ rolloutMock.enabled = false;+ });++ it('renders no group spacers', () => {+ renderRevealedGroup([+ {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},+ {type: ChannelStreamType.MESSAGE, content: message('200'), contentKey: '200', groupId: 'g2'},+ ]);++ expect(container.querySelectorAll('[data-message-group]')).toHaveLength(2);+ expect(container.querySelectorAll(SPACER_SELECTOR)).toHaveLength(0);+ });+});diff --git a/fluxer_app/src/features/channel/components/BlockedMessageGroups.tsx b/fluxer_app/src/features/channel/components/BlockedMessageGroups.tsxindex dc806f760..bc0e257db 100644--- a/fluxer_app/src/features/channel/components/BlockedMessageGroups.tsx+++ b/fluxer_app/src/features/channel/components/BlockedMessageGroups.tsx@@ -2,12 +2,14 @@import styles from '@app/features/channel/components/BlockedMessageGroups.module.css';import {Divider} from '@app/features/channel/components/ChannelDivider';+import streamStyles from '@app/features/channel/components/ChannelMessages.module.css';import {MessageGroup,type MessageGroupProps,type MessageGroupRenderWrapperProps,} from '@app/features/channel/components/MessageGroup';import type {Channel} from '@app/features/channel/models/Channel';+import BlockedMessageGroupsRollout from '@app/features/channel/state/BlockedMessageGroupsRollout';import type {Message} from '@app/features/messaging/models/MessagingMessage';import MessageKeyboardFocusRollout from '@app/features/messaging/state/MessageKeyboardFocusRollout';import {type ChannelStreamItem, ChannelStreamType} from '@app/features/messaging/utils/MessageGroupingUtils';@@ -100,6 +102,7 @@ export const BlockedMessageGroups = React.memo<BlockedMessageGroupsProps>((propsrenderMessageWrapper,suppressUnreadIndicator,} = props;+ const groupRenderingEnabled = BlockedMessageGroupsRollout.enabled;const {i18n} = useLingui();const containerRef = useRef<HTMLDivElement>(null);const toggleRef = useRef<HTMLButtonElement>(null);@@ -231,8 +234,20 @@ export const BlockedMessageGroups = React.memo<BlockedMessageGroupsProps>((propsconst nodes: Array<React.ReactNode> = [];let currentGroupMessages: Array<Message> = [];let groupId: string | undefined;+ let renderedGroupCount = 0;const flushGroup = () => {if (currentGroupMessages.length > 0) {+ if (groupRenderingEnabled && renderedGroupCount > 0 && messageGroupSpacing > 0) {+ nodes.push(+ <div+ key={`blocked-group-spacer-${currentGroupMessages[0].id}`}+ className={streamStyles.groupSpacer}+ aria-hidden="true"+ data-flx="channel.blocked-message-groups.group-spacer"+ />,+ );+ }+ renderedGroupCount += 1;nodes.push(<MessageGroupkey={currentGroupMessages[0].id}@@ -264,7 +279,13 @@ export const BlockedMessageGroups = React.memo<BlockedMessageGroupsProps>((propsflushGroup();nodes.push(<Divider- key={item.unreadId || item.contentKey || `divider-${itemIndex}`}+ key={+ groupRenderingEnabled+ ? item.unreadId+ ? `unread-divider-${item.unreadId}`+ : item.contentKey || `divider-${itemIndex}`+ : item.unreadId || item.contentKey || `divider-${itemIndex}`+ }spacing={messageGroupSpacing}red={!!item.unreadId}id={item.unreadId ? 'new-messages-bar' : undefined}@@ -298,6 +319,7 @@ export const BlockedMessageGroups = React.memo<BlockedMessageGroupsProps>((propsrenderMessageActions,renderMessageWrapper,suppressUnreadIndicator,+ groupRenderingEnabled,]);const leadingUnreadDivider = messageGroups[0]?.type === ChannelStreamType.DIVIDER && !!messageGroups[0].unreadId;return (diff --git a/fluxer_app/src/features/channel/state/BlockedMessageGroupsRollout.test.ts b/fluxer_app/src/features/channel/state/BlockedMessageGroupsRollout.test.tsnew file mode 100644index 000000000..3f7012040--- /dev/null+++ b/fluxer_app/src/features/channel/state/BlockedMessageGroupsRollout.test.ts@@ -0,0 +1,75 @@+// @vitest-environment happy-dom+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ type BlockedMessageGroupsAssignmentResponse,+ INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';+import {+ type ExperimentAssignmentsResponse,+ INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE,+} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';+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 {BlockedMessageGroupsRollout} = await import('@app/features/channel/state/BlockedMessageGroupsRollout');++function publish(assignment: BlockedMessageGroupsAssignmentResponse): void {+ const response: ExperimentAssignmentsResponse = {+ poll_interval_seconds: 300,+ poll_jitter_percent: 15,+ assignments: {blocked_message_groups: assignment},+ };+ runInAction(() => {+ ExperimentAssignments.response = response;+ });+}++afterEach(() => {+ runInAction(() => {+ ExperimentAssignments.response = INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE;+ });+});++describe('BlockedMessageGroupsRollout', () => {+ it('reads the inert assignment out of the inert envelope', () => {+ expect(BlockedMessageGroupsRollout.assignment).toBe(INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT);+ expect(BlockedMessageGroupsRollout.enabled).toBe(false);+ });++ it('stays on the control arm while the rollout is disabled', () => {+ publish({enabled: false, config_version: 2, user_targeted: false, source: null});+ expect(BlockedMessageGroupsRollout.enabled).toBe(false);+ });++ it('stays on the control arm for an account the rollout did not target', () => {+ publish({enabled: true, config_version: 2, user_targeted: false, source: null});+ expect(BlockedMessageGroupsRollout.enabled).toBe(false);+ });++ it('moves to the experiment arm for a targeted account', () => {+ publish({enabled: true, config_version: 2, user_targeted: true, source: 'canary'});+ expect(BlockedMessageGroupsRollout.enabled).toBe(true);+ });++ it('follows the envelope back to the control arm when the store is reset', () => {+ publish({enabled: true, config_version: 2, user_targeted: true, source: 'user_rule'});+ expect(BlockedMessageGroupsRollout.enabled).toBe(true);+ ExperimentAssignments.reset();+ expect(BlockedMessageGroupsRollout.enabled).toBe(false);+ });+});diff --git a/fluxer_app/src/features/channel/state/BlockedMessageGroupsRollout.ts b/fluxer_app/src/features/channel/state/BlockedMessageGroupsRollout.tsnew file mode 100644index 000000000..6c876ca7c--- /dev/null+++ b/fluxer_app/src/features/channel/state/BlockedMessageGroupsRollout.ts@@ -0,0 +1,22 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import ExperimentAssignments from '@app/features/experiment/state/ExperimentAssignments';+import type {BlockedMessageGroupsAssignmentResponse} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';+import {readBlockedMessageGroupsAssignment} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';++export const BLOCKED_MESSAGE_GROUPS_EXPERIMENT_CLASS = 'experiment-blocked-message-groups';++class BlockedMessageGroupsRolloutSelector {+ get assignment(): BlockedMessageGroupsAssignmentResponse {+ return readBlockedMessageGroupsAssignment(ExperimentAssignments.response);+ }++ get enabled(): boolean {+ const assignment = this.assignment;+ return assignment.enabled && assignment.user_targeted;+ }+}++export const BlockedMessageGroupsRollout = new BlockedMessageGroupsRolloutSelector();++export default BlockedMessageGroupsRollout;diff --git a/fluxer_docs/src/content/docs/admin-api/instance.mdx b/fluxer_docs/src/content/docs/admin-api/instance.mdxindex 6b64a1c3b..226a5d590 100644--- a/fluxer_docs/src/content/docs/admin-api/instance.mdx+++ b/fluxer_docs/src/content/docs/admin-api/instance.mdx@@ -38,6 +38,7 @@ Missing settings use the defaults documented below. Invalid stored configuration| 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 || message_keyboard_focus | [message keyboard focus configuration](#message-keyboard-focus-configuration-object) object | Message list keyboard navigation rollout |+| blocked_message_groups | [blocked message groups configuration](#blocked-message-groups-configuration-object) object | Blocked message block rendering 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 |@@ -180,6 +181,27 @@ Every field is present on read. An absent document or missing field uses the defHow often a client revalidates this rollout is set once for every experiment in the [experiment delivery configuration](#experiment-delivery-configuration-object) above.+## Blocked message groups configuration object++The instance rollout of how a client renders a revealed block of blocked messages. [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 `blocked-message-groups-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 draws a revealed block full width and spaces the message groups inside it, and a client that is not drawn keeps the rendering 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.@@ -572,6 +594,7 @@ The body has one optional object for each section. Fluxer leaves an absent secti| 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 || message_keyboard_focus? | object | Any subset of the [message keyboard focus](#message-keyboard-focus-configuration-object) fields |+| blocked_message_groups? | object | Any subset of the [blocked message groups](#blocked-message-groups-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 |@@ -586,6 +609,7 @@ The body has one optional object for each section. Fluxer leaves an absent secti`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.`message_keyboard_focus` takes every [message keyboard focus configuration](#message-keyboard-focus-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.+`blocked_message_groups` takes every [blocked message groups configuration](#blocked-message-groups-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.@@ -623,7 +647,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`, `message_hover_tracking`, `message_keyboard_focus`, `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`, `message_keyboard_focus`, `blocked_message_groups`, `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 7abef3a88..3c1940a07 100644--- a/fluxer_docs/src/content/docs/http-api/experiments.mdx+++ b/fluxer_docs/src/content/docs/http-api/experiments.mdx@@ -6,7 +6,7 @@ description: The experiment assignments envelope, the revalidation and polling cimport 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. This server defines `voice_noise_suppression`, whose placement protocol [Voice](/voice/) defines, `message_hover_tracking`, which selects one of two client implementations of the message hover state, and `message_keyboard_focus`, which selects one of two client implementations of keyboard navigation in the message list.+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, `message_hover_tracking`, which selects one of two client implementations of the message hover state, `message_keyboard_focus`, which selects one of two client implementations of keyboard navigation in the message list, and `blocked_message_groups`, which selects how a client renders a revealed block of blocked messages.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.@@ -35,10 +35,11 @@ One entry per experiment. The envelope reports this object even when it is empty| 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 || message_keyboard_focus? | [message keyboard focus assignment](#message-keyboard-focus-assignment-object) object | The caller's message keyboard focus assignment |+| blocked_message_groups? | [blocked message groups assignment](#blocked-message-groups-assignment-object) object | The caller's blocked message groups assignment |Ignore unknown experiments and treat a missing experiment as off.-This server version writes `voice_noise_suppression`, `message_hover_tracking`, and `message_keyboard_focus` 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.+This server version writes `voice_noise_suppression`, `message_hover_tracking`, `message_keyboard_focus`, and `blocked_message_groups` 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@@ -158,6 +159,33 @@ A caller is drawn either by the operator's allowlist, which sets `source` to `us`config_version` reports the stored revision in all outcomes, the rollout being off included. A client branches on `user_targeted` alone.+## Blocked message groups assignment object++One resolution of the instance blocked message groups rollout against one account. Every field is present whenever the key is written.++The rollout selects how a client renders a revealed block of blocked or suspected spam messages. A drawn client draws the block full width, spaces consecutive message groups inside it, and keys an unread divider apart from the group below it. A client that is not drawn keeps the rendering 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 |++### Blocked message groups 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 98812a5b9..80649b547 100644--- a/packages/schema/src/domains/admin/AdminSchemas.ts+++ b/packages/schema/src/domains/admin/AdminSchemas.ts@@ -19,6 +19,10 @@ import {VoiceNoiseSuppressionConfigResponse,VoiceNoiseSuppressionConfigUpdateRequest,} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';+import {+ BlockedMessageGroupsConfigResponse,+ BlockedMessageGroupsConfigUpdateRequest,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {ExperimentDeliveryConfigResponse,ExperimentDeliveryConfigUpdateRequest,@@ -640,6 +644,7 @@ export const InstanceConfigResponse = z.object({experiment_delivery: ExperimentDeliveryConfigResponse,message_hover_tracking: MessageHoverTrackingConfigResponse,message_keyboard_focus: MessageKeyboardFocusConfigResponse,+ blocked_message_groups: BlockedMessageGroupsConfigResponse,registration: InstanceRegistrationResponse,self_hosted: z.boolean(),app_public: AppPublicConfigResponse,@@ -678,6 +683,7 @@ export const InstanceConfigUpdateRequest = z.object({experiment_delivery: ExperimentDeliveryConfigUpdateRequest.nullish(),message_hover_tracking: MessageHoverTrackingConfigUpdateRequest.nullish(),message_keyboard_focus: MessageKeyboardFocusConfigUpdateRequest.nullish(),+ blocked_message_groups: BlockedMessageGroupsConfigUpdateRequest.nullish(),registration: z.object({mode: InstanceRegistrationModeSchema.optional(),diff --git a/packages/schema/src/domains/experiment/BlockedMessageGroupsSchemas.ts b/packages/schema/src/domains/experiment/BlockedMessageGroupsSchemas.tsnew file mode 100644index 000000000..5e74b10c4--- /dev/null+++ b/packages/schema/src/domains/experiment/BlockedMessageGroupsSchemas.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 blockedMessageGroups = createClientBehaviorExperiment({defaultRolloutSalt: 'blocked-message-groups-v1'});++export const BlockedMessageGroupsConfigSchema = blockedMessageGroups.ConfigSchema;++export type BlockedMessageGroupsConfig = z.infer<typeof BlockedMessageGroupsConfigSchema>;++export const DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG: BlockedMessageGroupsConfig = blockedMessageGroups.DEFAULT_CONFIG;++export const BlockedMessageGroupsConfigUpdateRequest = blockedMessageGroups.ConfigUpdateRequest;++export type BlockedMessageGroupsConfigUpdateRequest = z.infer<typeof BlockedMessageGroupsConfigUpdateRequest>;++export const BlockedMessageGroupsConfigResponse = blockedMessageGroups.ConfigSchema;++export type BlockedMessageGroupsConfigResponse = BlockedMessageGroupsConfig;++export const BlockedMessageGroupsAssignmentResponse = blockedMessageGroups.AssignmentResponse;++export type BlockedMessageGroupsAssignmentResponse = z.infer<typeof BlockedMessageGroupsAssignmentResponse>;++export const INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT: BlockedMessageGroupsAssignmentResponse =+ blockedMessageGroups.INERT_ASSIGNMENT;++export function resolveBlockedMessageGroupsAssignment(+ config: BlockedMessageGroupsConfig,+ userId: string,+): BlockedMessageGroupsAssignmentResponse {+ return blockedMessageGroups.resolveAssignment(config, userId);+}diff --git a/packages/schema/src/domains/experiment/ExperimentSchemas.ts b/packages/schema/src/domains/experiment/ExperimentSchemas.tsindex c3b54ad25..0896e844e 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 {+ BlockedMessageGroupsAssignmentResponse,+ INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';import {INERT_MESSAGE_HOVER_TRACKING_ASSIGNMENT,MessageHoverTrackingAssignmentResponse,@@ -52,6 +56,7 @@ const ExperimentAssignmentsSchema = z.object({voice_noise_suppression: VoiceNoiseSuppressionAssignmentResponse.optional(),message_hover_tracking: MessageHoverTrackingAssignmentResponse.optional(),message_keyboard_focus: MessageKeyboardFocusAssignmentResponse.optional(),+ blocked_message_groups: BlockedMessageGroupsAssignmentResponse.optional(),});export const ExperimentAssignmentsResponse = z.object({@@ -85,3 +90,9 @@ export function readMessageKeyboardFocusAssignment(): MessageKeyboardFocusAssignmentResponse {return response.assignments.message_keyboard_focus ?? INERT_MESSAGE_KEYBOARD_FOCUS_ASSIGNMENT;}++export function readBlockedMessageGroupsAssignment(+ response: ExperimentAssignmentsResponse,+): BlockedMessageGroupsAssignmentResponse {+ return response.assignments.blocked_message_groups ?? INERT_BLOCKED_MESSAGE_GROUPS_ASSIGNMENT;+}diff --git a/packages/schema/src/domains/tests/BlockedMessageGroupsSchemas.test.ts b/packages/schema/src/domains/tests/BlockedMessageGroupsSchemas.test.tsnew file mode 100644index 000000000..46af76dfc--- /dev/null+++ b/packages/schema/src/domains/tests/BlockedMessageGroupsSchemas.test.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ BlockedMessageGroupsConfigSchema,+ DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG,+ resolveBlockedMessageGroupsAssignment,+} from '@fluxer/schema/src/domains/experiment/BlockedMessageGroupsSchemas';+import {EXPERIMENT_BUCKET_RESOLUTION, experimentBucket} from '@fluxer/schema/src/domains/experiment/ExperimentBucket';+import {describe, expect, it} from 'vitest';++const USER_ID = '1485064866382176262';+const OTHER_USER_ID = '1485064866382176263';++function config(overrides: Partial<ReturnType<typeof BlockedMessageGroupsConfigSchema.parse>> = {}) {+ return BlockedMessageGroupsConfigSchema.parse({...overrides});+}++describe('blocked message groups configuration', () => {+ it('defaults to a disabled rollout that targets nobody', () => {+ expect(DEFAULT_BLOCKED_MESSAGE_GROUPS_CONFIG).toEqual({+ enabled: false,+ config_version: 0,+ rollout_basis_points: 0,+ rollout_salt: 'blocked-message-groups-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('blocked message groups resolution', () => {+ it('reports the stored revision while the rollout is disabled', () => {+ const assignment = resolveBlockedMessageGroupsAssignment(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 = resolveBlockedMessageGroupsAssignment(+ 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 = resolveBlockedMessageGroupsAssignment(+ 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 = resolveBlockedMessageGroupsAssignment(+ 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_BLOCKED_MESSAGE_GROUPS_CONFIG.rollout_salt;+ const bucket = experimentBucket(USER_ID, salt);+ const inside = resolveBlockedMessageGroupsAssignment(+ config({enabled: true, rollout_basis_points: bucket + 1}),+ USER_ID,+ );+ const outside = resolveBlockedMessageGroupsAssignment(+ 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_BLOCKED_MESSAGE_GROUPS_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, 'blocked-message-groups-v1')).not.toBe(+ experimentBucket(USER_ID, 'blocked-message-groups-v2'),+ );+ });+});