mattermost-mobile-upstream/app/actions/remote/classification.test.ts
Pablo Vélez 54731fa6ac
Mm 70299 channel labels display phase 1 (#10113)
* MM-70299 - display channel attributes in header, info and banner

* cover and expand channel attributes feature with UI and E2E tests

* Implement channel attributes lock and update related tests and API methods

* Enhance error logging and improve type definitions for channel attributes

* Handle error from setAccessControlGroupId in fetchAccessControlAttributeFields

* Refactor fetchAccessControlAttributeFields to include system ID handling and improve batch record persistence

* Address code review feedback: extract feature-flag constants, move DB-only helpers to query/local layers, refactor attribute chip styles, fix colour spelling, and add test coverage for value pruning and subtitle component

* Fix error handling in removeStoredFields function and delete obsolete end-to-end test file

* Add tests for removeStoredFields function and enhance property queries

* Fix removeStoredFields to recover group ID from classification anchor and clean all owned fields

* Fix batchRecords silently swallowing write errors in fetchAccessControlAttributeFields

* Remove unused visibility check for ChannelAttributeLabels in e2e tests

* Fix classification fetch cache and channel-attributes E2E lock contention

Do not stamp the classification banner cache when both access-control flags
are off, so turning a flag back on after a reload refetches fields.

Share the classification lock with the channel-attributes Detox suite and
stop unsetting ClassificationMarkings. Skip flag-on tests when the server
cannot enable ChannelAttributes.

Co-authored-by: mattermost-code <matty-code@mattermost.com>

* Scope access_control field prune to owned object types

handlePropertyFields(groupId) deletes every field in the group. The fetch
only returns system and channel fields, so same-group user/session rows
were removed on each refresh. Prune only system and channel fields, matching
removeStoredFields.

Co-authored-by: mattermost-code <matty-code@mattermost.com>

* fail channel attributes tests when feature enablement fails instead of silently reporting them as passed

* Compose all channel attribute values in banners with template resolution, mixed field support, and matching web colors

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: mattermost-code <matty-code@mattermost.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
2026-09-17 21:37:43 +02:00

657 lines
30 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Q, type Database} from '@nozbe/watermelondb';
import {DeviceEventEmitter} from 'react-native';
import {setAccessControlGroupId} from '@actions/local/channel_attributes';
import {Events} from '@constants';
import {CLASSIFICATIONS_GROUP_NAME, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID} from '@constants/classification';
import {MM_TABLES} from '@constants/database';
import DatabaseManager from '@database/manager';
import NetworkManager from '@managers/network_manager';
import {getConfigValue} from '@queries/servers/system';
import EphemeralStore from '@store/ephemeral_store';
import {fetchAccessControlAttributeFields, fetchChannelAttributeValues} from './classification';
import type {PropertyFieldModel, PropertyValueModel} from '@database/models/server';
const {PROPERTY_FIELD, PROPERTY_VALUE} = MM_TABLES.SERVER;
jest.mock('@queries/servers/system', () => ({
getConfigValue: jest.fn(),
}));
const mockedGetConfigValue = jest.mocked(getConfigValue);
// Keyed rather than ordered. The action reads two feature flags and the server
// version, and an ordered queue of one-shot values silently mis-answers the
// moment the number or order of reads changes.
type TestConfig = Partial<Record<'FeatureFlagClassificationMarkings' | 'FeatureFlagChannelAttributes' | 'Version', string>>;
const setConfig = (config: TestConfig) => {
mockedGetConfigValue.mockImplementation((_database, key) => Promise.resolve(config[key as keyof TestConfig]));
};
const serverUrl = 'classification.test.com';
const systemField: PropertyField = {
id: 'system-field-id',
group_id: CLASSIFICATIONS_GROUP_NAME,
name: 'classification',
type: 'select',
object_type: 'system',
target_type: 'system',
target_id: '',
delete_at: 0,
create_at: 1000,
update_at: 1000,
attrs: {
actions: ['display_banner_top'],
options: [
{id: 'opt-top-secret', name: 'TOP SECRET', color: '#FCE83A'},
{id: 'opt-secret', name: 'SECRET', color: '#FF0000'},
],
},
};
const channelField: PropertyField = {
id: 'channel-field-id',
group_id: CLASSIFICATIONS_GROUP_NAME,
name: 'classification',
type: 'select',
object_type: 'channel',
target_type: 'system',
target_id: '',
delete_at: 0,
create_at: 1000,
update_at: 1000,
attrs: {
options: [
{id: 'opt-top-secret', name: 'TOP SECRET', color: '#FCE83A'},
{id: 'opt-secret', name: 'SECRET', color: '#FF0000'},
],
},
};
const systemValue: PropertyValue<string> = {
id: 'val-1',
target_id: 'system',
target_type: 'system',
group_id: CLASSIFICATIONS_GROUP_NAME,
field_id: 'system-field-id',
value: 'opt-top-secret',
create_at: 1000,
update_at: 1000,
delete_at: 0,
};
const mockClient = {
getPropertyFields: jest.fn(),
searchPropertyFields: jest.fn(),
getSystemPropertyValues: jest.fn(),
getPropertyValues: jest.fn(),
};
const queryFieldsByGroup = (database: Database, groupId: string) =>
database.get<PropertyFieldModel>(PROPERTY_FIELD).query(Q.where('group_id', groupId)).fetch();
const getStoredFields = async (database: Database) => {
const records = await queryFieldsByGroup(database, CLASSIFICATIONS_GROUP_NAME);
return records.map((r) => r.id).sort();
};
const getStoredValues = async (database: Database, targetId: string) => {
const records = await database.get<PropertyValueModel>(PROPERTY_VALUE).query(Q.where('target_id', targetId)).fetch();
return records;
};
beforeAll(() => {
// @ts-expect-error mock client
NetworkManager.getClient = () => mockClient;
});
beforeEach(async () => {
await DatabaseManager.init([serverUrl]);
jest.clearAllMocks();
setConfig({});
EphemeralStore.clearClassificationCache(serverUrl);
EphemeralStore.clearChannelAttributeValuesSynced(serverUrl);
});
afterEach(async () => {
jest.restoreAllMocks();
await DatabaseManager.destroyServerDatabase(serverUrl);
});
describe('fetchAccessControlAttributeFields', () => {
it('should do nothing when feature flag is not true', async () => {
setConfig({FeatureFlagClassificationMarkings: 'false'});
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(true);
});
it('should clear stale classification data when feature flag is turned off', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField], prepareRecordsOnly: false});
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
setConfig({FeatureFlagClassificationMarkings: 'false'});
await fetchAccessControlAttributeFields(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(0);
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(true);
});
it('should refetch after a flag is turned back on because a disabled fetch is not cached', async () => {
setConfig({FeatureFlagClassificationMarkings: 'false'});
await fetchAccessControlAttributeFields(serverUrl);
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchAccessControlAttributeFields(serverUrl);
expect(mockClient.getPropertyFields).toHaveBeenCalled();
});
it('should clear stale classification data when API returns zero fields', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField], prepareRecordsOnly: false});
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
await fetchAccessControlAttributeFields(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(0);
});
it('should persist fields and values to DB on happy path', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['channel-field-id', 'system-field-id']);
const values = await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID);
expect(values).toHaveLength(1);
expect(values[0].value).toBe('opt-top-secret');
});
it('should persist system field when channel field is missing', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
});
it('should return early when no fields are returned by the API', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should exclude soft-deleted fields from the stored set', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
const deletedSystem = {...systemField, delete_at: 5000};
mockClient.getPropertyFields.mockResolvedValueOnce([deletedSystem]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([]);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['channel-field-id']);
});
it('should return early when fields have mismatched group_ids', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
const differentGroupField = {...channelField, group_id: 'other_group'};
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([differentGroupField]);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should return error when network client throws', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
const networkError = new Error('network failure');
mockClient.getPropertyFields.mockRejectedValueOnce(networkError);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({error: networkError});
});
it('should not write to DB when network client throws', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockRejectedValueOnce(new Error('network failure'));
await fetchAccessControlAttributeFields(serverUrl);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should remove a previously persisted field the API no longer returns', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField, channelField], prepareRecordsOnly: false});
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchAccessControlAttributeFields(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
});
it('should remove soft-deleted fields from DB even when they were previously persisted', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField, channelField], prepareRecordsOnly: false});
const deletedChannel = {...channelField, delete_at: 5000};
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([deletedChannel]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([]);
await fetchAccessControlAttributeFields(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
});
it('should leave fields from other groups untouched', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const otherGroupField = {...systemField, id: 'other-field', group_id: 'other_group', name: 'some_field'};
await operator.handlePropertyFields({fields: [otherGroupField], prepareRecordsOnly: false});
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchAccessControlAttributeFields(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
const otherGroup = await queryFieldsByGroup(database, 'other_group');
expect(otherGroup.map((f) => f.id)).toEqual(['other-field']);
});
it('should leave same-group user fields untouched', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const userField: PropertyField = {
...systemField,
id: 'user-field-id',
name: 'title',
object_type: 'user',
};
await operator.handlePropertyFields({fields: [systemField, channelField, userField], prepareRecordsOnly: false});
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchAccessControlAttributeFields(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id', 'user-field-id']);
});
it('should skip the request when cached and not forced', async () => {
EphemeralStore.setClassificationBannerFetched(serverUrl);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
expect(mockedGetConfigValue).not.toHaveBeenCalled();
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
expect(mockClient.searchPropertyFields).not.toHaveBeenCalled();
});
it('should bypass the cache when forced', async () => {
EphemeralStore.setClassificationBannerFetched(serverUrl);
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchAccessControlAttributeFields(serverUrl, true);
expect(mockClient.getPropertyFields).toHaveBeenCalled();
});
it('should return error and not cache when batch write fails', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const dbError = new Error('disk full');
jest.spyOn(operator.database, 'write').mockRejectedValueOnce(dbError);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({error: dbError});
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(true);
});
it('should retry on a subsequent unforced call after a batch write failure', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.
mockResolvedValueOnce([systemField]).
mockResolvedValueOnce([channelField]).
mockResolvedValueOnce([systemField]).
mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.
mockResolvedValueOnce([systemValue]).
mockResolvedValueOnce([systemValue]);
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
jest.spyOn(operator.database, 'write').mockRejectedValueOnce(new Error('disk full'));
const firstResult = await fetchAccessControlAttributeFields(serverUrl);
expect(firstResult.error).toBeInstanceOf(Error);
const retryResult = await fetchAccessControlAttributeFields(serverUrl);
expect(retryResult).toEqual({});
expect(mockClient.getPropertyFields).toHaveBeenCalledTimes(4);
});
it('should emit database corruption event and propagate when propagateError is true', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const corruptionError = new Error('database disk image is malformed');
// Force the underlying DB write to throw a corruption error.
jest.spyOn(operator.database, 'write').mockRejectedValueOnce(corruptionError);
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit');
// Use a non-empty model list so batchRecords actually calls write().
// A plain object satisfies the call — we only care about the error path.
await expect(
operator.batchRecords([{} as never], 'corruption-test', true),
).rejects.toThrow('database disk image is malformed');
expect(emitSpy).toHaveBeenCalledWith(
Events.DATABASE_CORRUPTION_DETECTED,
expect.objectContaining({source: 'corruption-test'}),
);
});
it('should cache on success so a subsequent unforced call is skipped', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchAccessControlAttributeFields(serverUrl);
await fetchAccessControlAttributeFields(serverUrl);
// Two requests on the first call (system and channel fields); the second
// call is answered from the cache without touching the network.
expect(mockClient.getPropertyFields).toHaveBeenCalledTimes(2);
});
it('should not cache on error so a subsequent unforced call retries', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true'});
// First invocation: two parallel requests (system + channel fields), first rejects.
mockClient.getPropertyFields.mockRejectedValueOnce(new Error('network failure'));
mockClient.getPropertyFields.mockResolvedValueOnce([]);
// Second invocation (the retry): both requests succeed with an empty list.
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
await fetchAccessControlAttributeFields(serverUrl);
// The failure must not have stamped the cache, so an unforced retry makes a second pair of network requests.
await fetchAccessControlAttributeFields(serverUrl);
// Four requests total: two for the failing call (Promise.all initiates both), two for the retry.
expect(mockClient.getPropertyFields).toHaveBeenCalledTimes(4);
expect(mockedGetConfigValue).toHaveBeenCalledWith(expect.anything(), 'FeatureFlagClassificationMarkings');
expect(mockedGetConfigValue).toHaveBeenCalledWith(expect.anything(), 'FeatureFlagChannelAttributes');
});
describe('when the server supports the fields search endpoint', () => {
it('should fetch all fields with a single search request', async () => {
setConfig({FeatureFlagClassificationMarkings: 'true', Version: '11.10.0'});
mockClient.searchPropertyFields.mockResolvedValueOnce([systemField, channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
const result = await fetchAccessControlAttributeFields(serverUrl);
expect(result).toEqual({});
expect(mockClient.searchPropertyFields).toHaveBeenCalledTimes(1);
expect(mockClient.searchPropertyFields).toHaveBeenCalledWith(CLASSIFICATIONS_GROUP_NAME, {
object_types: ['system', 'channel'],
target_type: 'system',
target_id: '',
});
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['channel-field-id', 'system-field-id']);
const values = await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID);
expect(values).toHaveLength(1);
expect(values[0].value).toBe('opt-top-secret');
});
it('should clear stale data when the search returns no fields', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField], prepareRecordsOnly: false});
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
setConfig({FeatureFlagClassificationMarkings: 'true', Version: '11.10.0'});
mockClient.searchPropertyFields.mockResolvedValueOnce([]);
await fetchAccessControlAttributeFields(serverUrl);
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
expect(await getStoredFields(database)).toHaveLength(0);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(0);
});
});
});
describe('batchRecords default behavior (non-throwing)', () => {
it('should not throw when propagateError is not set, even if the write fails', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const writeSpy = jest.spyOn(operator.database, 'write').mockRejectedValueOnce(new Error('write error'));
await expect(operator.batchRecords([{} as never], 'test-description')).resolves.toBeUndefined();
expect(writeSpy).toHaveBeenCalledTimes(1);
});
});
describe('fetchChannelAttributeValues', () => {
const channelId = 'channel-123';
const channelValue: PropertyValue<string> = {
id: 'cv-1',
target_id: channelId,
target_type: 'channel',
group_id: CLASSIFICATIONS_GROUP_NAME,
field_id: 'channel-field-id',
value: 'opt-secret',
create_at: 1000,
update_at: 1000,
delete_at: 0,
};
it('should do nothing when feature flag is not true', async () => {
setConfig({FeatureFlagChannelAttributes: 'false'});
const result = await fetchChannelAttributeValues(serverUrl, channelId);
expect(result).toEqual({});
expect(mockClient.getPropertyValues).not.toHaveBeenCalled();
});
it('should persist channel values to DB on happy path', async () => {
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([channelValue]);
const result = await fetchChannelAttributeValues(serverUrl, channelId);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const values = await getStoredValues(database, channelId);
expect(values).toHaveLength(1);
expect(values[0].value).toBe('opt-secret');
});
it('should clear existing channel values when API returns none', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyValues({values: [channelValue], prepareRecordsOnly: false});
// The group-scoped prune only fires when the group id is known.
await setAccessControlGroupId(serverUrl, CLASSIFICATIONS_GROUP_NAME);
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([]);
const result = await fetchChannelAttributeValues(serverUrl, channelId);
expect(result).toEqual({});
expect(await getStoredValues(database, channelId)).toHaveLength(0);
});
it('should return error when network client throws', async () => {
setConfig({FeatureFlagChannelAttributes: 'true'});
const networkError = new Error('network failure');
mockClient.getPropertyValues.mockRejectedValueOnce(networkError);
const result = await fetchChannelAttributeValues(serverUrl, channelId);
expect(result).toEqual({error: networkError});
});
it('should isolate values across different targets', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([channelValue]);
await operator.handlePropertyFields({fields: [channelField], prepareRecordsOnly: false});
await fetchChannelAttributeValues(serverUrl, channelId);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(1);
expect(await getStoredValues(database, channelId)).toHaveLength(1);
});
it('should force a field refresh when the value references an unknown option', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [channelField], prepareRecordsOnly: false});
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([{...channelValue, value: 'opt-unknown'}]);
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchChannelAttributeValues(serverUrl, channelId);
expect(mockClient.getPropertyFields).toHaveBeenCalled();
// Cache key is fieldId:optionId so the guard is scoped to the field, preventing
// an option with the same short id on a different field from hitting the guard.
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'channel-field-id:opt-unknown')).toBe(true);
});
it('should look the option up on the channel field rather than the system field', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const channelOnly = {...channelField, attrs: {options: [{id: 'opt-channel-only', name: 'CHANNEL ONLY', color: '#00FF00'}]}};
await operator.handlePropertyFields({fields: [systemField, channelOnly], prepareRecordsOnly: false});
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([{...channelValue, value: 'opt-channel-only'}]);
await fetchChannelAttributeValues(serverUrl, channelId);
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
});
it('should not force a field refresh when the value option is already known', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [channelField], prepareRecordsOnly: false});
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([channelValue]); // value opt-secret is a known option
await fetchChannelAttributeValues(serverUrl, channelId);
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'channel-field-id:opt-secret')).toBe(false);
});
it('should not force a field refresh again for an option already attempted this session', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [channelField], prepareRecordsOnly: false});
EphemeralStore.setClassificationFieldSyncAttempted(serverUrl, 'channel-field-id:opt-unknown');
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([{...channelValue, value: 'opt-unknown'}]);
await fetchChannelAttributeValues(serverUrl, channelId);
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
});
it('should not mark the option attempted when the forced refresh fails', async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [channelField], prepareRecordsOnly: false});
setConfig({FeatureFlagChannelAttributes: 'true'});
mockClient.getPropertyValues.mockResolvedValueOnce([{...channelValue, value: 'opt-unknown'}]);
mockClient.getPropertyFields.mockRejectedValueOnce(new Error('network failure'));
await fetchChannelAttributeValues(serverUrl, channelId);
// A transient refresh failure must leave the guard unset so a later update retries.
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'channel-field-id:opt-unknown')).toBe(false);
});
});