Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(api): trim channel, thread, search and read state cases

Hampusf492730ef225
diff --git a/fluxer_api/src/api/channel/PrivateChannelSnapshot.test.ts b/fluxer_api/src/api/channel/PrivateChannelSnapshot.test.ts
index ff72d04af..1921ab323 100644
--- a/fluxer_api/src/api/channel/PrivateChannelSnapshot.test.ts
+++ b/fluxer_api/src/api/channel/PrivateChannelSnapshot.test.ts
@@ -3,9 +3,6 @@
import {createChannelID, createMessageID, createUserID} from '@app/api/BrandedTypes';
import {
channelRowFromPrivateChannelSnapshot,
- privateChannelFanOutTargets,
- privateChannelHydrationPatch,
- privateChannelLastMessageIdPatch,
privateChannelMetadataPatch,
} from '@app/api/channel/PrivateChannelSnapshot';
import type {ChannelRow, PrivateChannelRow} from '@app/api/database/types/ChannelTypes';
@@ -57,21 +54,6 @@ function setValue<T>(op: unknown): T {
return typed.value;
}
-describe('privateChannelFanOutTargets', () => {
- test('returns recipients for a GDM', () => {
- expect(new Set(privateChannelFanOutTargets(gdmRow()))).toEqual(new Set([OWNER, MEMBER_A, MEMBER_B]));
- });
-
- test('includes the owner for personal-notes channels with no recipients', () => {
- const row = gdmRow({type: ChannelTypes.DM_PERSONAL_NOTES, recipient_ids: null, owner_id: OWNER});
- expect(privateChannelFanOutTargets(row)).toEqual([OWNER]);
- });
-
- test('returns nothing for guild channels', () => {
- expect(privateChannelFanOutTargets(gdmRow({type: ChannelTypes.GUILD_TEXT}))).toEqual([]);
- });
-});
-
describe('privateChannelMetadataPatch', () => {
test('writes stable metadata but never the volatile pointer or hydration marker', () => {
const patch = privateChannelMetadataPatch(gdmRow());
@@ -82,30 +64,6 @@ describe('privateChannelMetadataPatch', () => {
expect(patch.channel_last_message_id).toBeUndefined();
expect(patch.snapshot_at).toBeUndefined();
});
-
- test('empty recipient set and nicks map collapse to null', () => {
- const patch = privateChannelMetadataPatch(gdmRow({recipient_ids: new Set(), nicks: new Map()}));
- expect(setValue<Set<unknown> | null>(patch.channel_recipient_ids)).toBeNull();
- expect(setValue<Map<unknown, unknown> | null>(patch.channel_nicks)).toBeNull();
- });
-});
-
-describe('privateChannelHydrationPatch', () => {
- test('adds the authoritative last message id and the snapshot marker', () => {
- const hydratedAt = new Date('2026-06-01T00:00:00.000Z');
- const patch = privateChannelHydrationPatch(gdmRow(), hydratedAt);
- expect(setValue<bigint | null>(patch.channel_last_message_id)).toBe(LAST_MESSAGE);
- expect(setValue<Date>(patch.snapshot_at)).toBe(hydratedAt);
- expect(setValue<number>(patch.channel_type)).toBe(ChannelTypes.GROUP_DM);
- });
-});
-
-describe('privateChannelLastMessageIdPatch', () => {
- test('only writes the last message id column', () => {
- const patch = privateChannelLastMessageIdPatch(LAST_MESSAGE);
- expect(Object.keys(patch)).toEqual(['channel_last_message_id']);
- expect(setValue<bigint | null>(patch.channel_last_message_id)).toBe(LAST_MESSAGE);
- });
});
describe('channelRowFromPrivateChannelSnapshot', () => {
@@ -119,34 +77,4 @@ describe('channelRowFromPrivateChannelSnapshot', () => {
expect(channelRowFromPrivateChannelSnapshot(baseRow)).toBeNull();
expect(channelRowFromPrivateChannelSnapshot({...baseRow, channel_type: ChannelTypes.GROUP_DM})).toBeNull();
});
-
- test('reconstructs a channel row from a hydrated snapshot', () => {
- const row = channelRowFromPrivateChannelSnapshot({
- ...baseRow,
- channel_type: ChannelTypes.GROUP_DM,
- channel_name: 'Squad',
- channel_icon_hash: 'icon123',
- channel_owner_id: OWNER,
- channel_recipient_ids: new Set([OWNER, MEMBER_A, MEMBER_B]),
- channel_last_message_id: LAST_MESSAGE,
- channel_last_pin_timestamp: null,
- channel_nicks: new Map([['2', 'Al']]),
- channel_rate_limit_per_user: 5,
- channel_nsfw: null,
- channel_version: 7,
- snapshot_at: new Date('2026-06-01T00:00:00.000Z'),
- });
- expect(row).not.toBeNull();
- expect(row?.channel_id).toBe(CHANNEL);
- expect(row?.type).toBe(ChannelTypes.GROUP_DM);
- expect(row?.name).toBe('Squad');
- expect(row?.icon_hash).toBe('icon123');
- expect(row?.owner_id).toBe(OWNER);
- expect(row?.recipient_ids).toEqual(new Set([OWNER, MEMBER_A, MEMBER_B]));
- expect(row?.last_message_id).toBe(LAST_MESSAGE);
- expect(row?.rate_limit_per_user).toBe(5);
- expect(row?.version).toBe(7);
- expect(row?.soft_deleted).toBe(false);
- expect(row?.guild_id).toBeNull();
- });
});
diff --git a/fluxer_api/src/api/channel/repositories/ChannelDataRepository.test.ts b/fluxer_api/src/api/channel/repositories/ChannelDataRepository.test.ts
index b9374d84b..d0e01681e 100644
--- a/fluxer_api/src/api/channel/repositories/ChannelDataRepository.test.ts
+++ b/fluxer_api/src/api/channel/repositories/ChannelDataRepository.test.ts
@@ -5,7 +5,6 @@ import {ChannelDataRepository} from '@app/api/channel/repositories/ChannelDataRe
import {setCassandraQueryExecutorForTesting, upsertOne} from '@app/api/database/CassandraQueryExecution';
import type {ChannelRow} from '@app/api/database/types/ChannelTypes';
import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';
-import {Channel} from '@app/api/models/Channel';
import {Channels} from '@app/api/Tables';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
@@ -43,58 +42,17 @@ function makeChannelRow(channelId: ChannelID): ChannelRow {
};
}
-let executor: InMemoryCassandraQueryExecutor;
-
describe('ChannelDataRepository request cache', () => {
beforeEach(() => {
- executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
});
afterEach(() => {
setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
});
- it('reads the channel row once per lookup without a request cache', async () => {
- const channelId = createChannelID(1910000000000000000n);
- await upsertOne(Channels.upsertAll(makeChannelRow(channelId)));
- executor.executed.length = 0;
- const repository = new ChannelDataRepository();
-
- await repository.findUnique(channelId);
- await repository.findUnique(channelId);
-
- expect(executor.countStatements('select:channels')).toBe(2);
- });
- it('serves the prefetched channel once and falls back to the database afterwards', async () => {
- const channelId = createChannelID(1910000000000000000n);
- const row = makeChannelRow(channelId);
- await upsertOne(Channels.upsertAll(row));
- executor.executed.length = 0;
- const requestCache = createRequestCache();
- requestCache.channels.set(channelId, new Channel(row));
- const repository = new ChannelDataRepository(requestCache);
-
- const prefetched = await repository.findUnique(channelId);
- expect(prefetched?.id).toBe(channelId);
- expect(executor.countStatements('select:channels')).toBe(0);
-
- const reread = await repository.findUnique(channelId);
- expect(reread?.id).toBe(channelId);
- expect(executor.countStatements('select:channels')).toBe(1);
- });
- it('keeps a prefetched miss distinguishable from an absent entry', async () => {
- const channelId = createChannelID(1920000000000000000n);
- const requestCache = createRequestCache();
- requestCache.channels.set(channelId, null);
- const repository = new ChannelDataRepository(requestCache);
-
- expect(await repository.findUnique(channelId)).toBeNull();
- expect(executor.countStatements('select:channels')).toBe(0);
- });
it('drops the prefetched channel when the same request writes it', async () => {
const channelId = createChannelID(1930000000000000000n);
const row = makeChannelRow(channelId);
await upsertOne(Channels.upsertAll(row));
- executor.executed.length = 0;
const requestCache = createRequestCache();
requestCache.channels.set(channelId, null);
const repository = new ChannelDataRepository(requestCache);
diff --git a/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.test.ts b/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.test.ts
index c2656fb93..612938088 100644
--- a/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.test.ts
+++ b/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.test.ts
@@ -61,45 +61,22 @@ function makeMessageRow(channelId: ChannelID, messageId: MessageID): MessageRow
};
}
-let executor: InMemoryCassandraQueryExecutor;
-
-describe('MessageDataRepository.upsertMessage round trips', () => {
+describe('MessageDataRepository.upsertMessage channel state', () => {
beforeEach(() => {
- executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
});
afterEach(() => {
setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
});
- it('writes channel_state once and skips the read-before-write when the caller passes no previous row', async () => {
- const channelId = createChannelID(1710000000000000000n);
- const messageId = createMessageID(1720000000000000000n);
- const repository = new MessageDataRepository();
-
- await repository.upsertMessage(makeMessageRow(channelId, messageId), null);
-
- expect(executor.countStatements('select:messages')).toBe(0);
- expect(executor.countStatements('patch:channel_state')).toBe(1);
- expect(executor.batchAtomicity).toEqual([false]);
- expect(await loadChannelState(channelId)).toMatchObject({
- created_bucket: BucketUtils.makeBucket(channelId),
- has_messages: true,
- last_message_id: messageId,
- last_message_bucket: BucketUtils.makeBucket(messageId),
- });
- });
it('keeps the newer last_message_id while still recording channel state for an older message', async () => {
const channelId = createChannelID(1710000000000000000n);
const newerMessageId = createMessageID(1730000000000000000n);
const olderMessageId = createMessageID(1720000000000000000n);
const repository = new MessageDataRepository();
await repository.upsertMessage(makeMessageRow(channelId, newerMessageId), null);
- executor.executed.length = 0;
- executor.batchAtomicity.length = 0;
await repository.upsertMessage(makeMessageRow(channelId, olderMessageId), null);
- expect(executor.countStatements('patch:channel_state')).toBe(1);
expect(await loadChannelState(channelId)).toMatchObject({
created_bucket: BucketUtils.makeBucket(channelId),
has_messages: true,
@@ -111,13 +88,12 @@ describe('MessageDataRepository.upsertMessage round trips', () => {
describe('MessageDataRepository read scans maintain the bucket index', () => {
beforeEach(() => {
- executor = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(executor);
+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
});
afterEach(() => {
setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
});
- it('re-indexes a bucket that still holds messages and keeps the index batch unlogged', async () => {
+ it('re-indexes a bucket that still holds messages', async () => {
const channelId = createChannelID(generateSnowflake());
const messageId = createMessageID(generateSnowflake());
const bucket = BucketUtils.makeBucket(messageId);
@@ -125,33 +101,26 @@ describe('MessageDataRepository read scans maintain the bucket index', () => {
await repository.upsertMessage(makeMessageRow(channelId, messageId), null);
await deleteOneOrMany(ChannelMessageBuckets.deleteByPk({channel_id: channelId, bucket}));
expect(await loadIndexedBuckets(channelId)).toEqual([]);
- executor.executed.length = 0;
- executor.batchAtomicity.length = 0;
const messages = await repository.listMessages(channelId);
expect(messages.map((message) => message.id)).toEqual([messageId]);
expect(await loadIndexedBuckets(channelId)).toEqual([bucket]);
expect(await loadEmptyBuckets(channelId)).toEqual([]);
- expect(executor.countStatements('upsert:channel_message_buckets')).toBe(1);
- expect(executor.batchAtomicity).toEqual([false]);
});
- it('drops a drained bucket from the index and keeps the empty-bucket batch unlogged', async () => {
+ it('drops a drained bucket from the index', async () => {
const channelId = createChannelID(generateSnowflake());
const messageId = createMessageID(generateSnowflake());
const bucket = BucketUtils.makeBucket(messageId);
const repository = new MessageDataRepository();
await repository.upsertMessage(makeMessageRow(channelId, messageId), null);
await deleteOneOrMany(Messages.deleteByPk({channel_id: channelId, bucket, message_id: messageId}));
- executor.executed.length = 0;
- executor.batchAtomicity.length = 0;
const messages = await repository.listMessages(channelId);
expect(messages).toEqual([]);
expect(await loadIndexedBuckets(channelId)).toEqual([]);
expect(await loadEmptyBuckets(channelId)).toEqual([bucket]);
- expect(executor.batchAtomicity).toEqual([false]);
});
});
diff --git a/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts b/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts
index 055d69eb5..2270ebcc1 100644
--- a/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts
+++ b/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts
@@ -129,15 +129,4 @@ describe('MessagePinService.getChannelPins', () => {
.map((message) => message.id.toString()),
);
});
-
- it('reads the pin index once for a caller that can read message history', async () => {
- const pins = Array.from({length: 11}, (_value, index) => makePin(HIDDEN_CREATED_AT, index, index));
- const {calls, listPins} = createPinService({canReadHistory: true, pins});
-
- const page = await listPins(10);
-
- expect(page.items).toHaveLength(10);
- expect(page.has_more).toBe(true);
- expect(calls).toHaveLength(1);
- });
});
diff --git a/fluxer_api/src/api/channel/services/message/MessageActivity.test.ts b/fluxer_api/src/api/channel/services/message/MessageActivity.test.ts
index 59e246afd..b52217117 100644
--- a/fluxer_api/src/api/channel/services/message/MessageActivity.test.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageActivity.test.ts
@@ -1,18 +1,30 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import assert from 'node:assert/strict';
+import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createAttachmentID, createChannelID, createMessageID, createUserID} from '@app/api/BrandedTypes';
-import {emitMessageCreated, emitMessageUpdated} from '@app/api/channel/services/message/MessageActivity';
+import {ChannelRepository} from '@app/api/channel/ChannelRepository';
+import {emitMessageCreated} from '@app/api/channel/services/message/MessageActivity';
+import {createDmChannel} from '@app/api/channel/tests/ChannelTestUtils';
import type {MessageAttachment} from '@app/api/database/types/MessageTypes';
-import {resetActivityEventsForTests, startActivityEvents} from '@app/api/infrastructure/activity/ActivityEvents';
+import {
+ idleActivityEvents,
+ resetActivityEventsForTests,
+ startActivityEvents,
+} from '@app/api/infrastructure/activity/ActivityEvents';
import type {ActivityPublisher} from '@app/api/infrastructure/activity/ActivitySpool';
import type {Channel} from '@app/api/models/Channel';
import {Message} from '@app/api/models/Message';
import type {User} from '@app/api/models/User';
-import {ChannelTypes, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {afterEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const HASH = '3F'.repeat(32);
+const channelRepository = new ChannelRepository();
+const userRepository = new UserRepository();
function attachment(id: bigint, hash: string | null): MessageAttachment {
return {
@@ -63,63 +75,94 @@ function message(attachments: Array<MessageAttachment>, content = ''): Message {
}
class CapturingPublisher implements ActivityPublisher {
- readonly payloads: Array<string> = [];
+ private readonly payloads: Array<unknown> = [];
+ private readonly waiters: Array<(event: unknown) => void> = [];
async publish(_subject: string, payload: string): Promise<void> {
- this.payloads.push(payload);
+ const event: unknown = JSON.parse(payload);
+ const waiter = this.waiters.shift();
+ if (waiter) {
+ waiter(event);
+ } else {
+ this.payloads.push(event);
+ }
+ }
+
+ next(): Promise<unknown> {
+ const event = this.payloads.shift();
+ if (event !== undefined) {
+ return Promise.resolve(event);
+ }
+ return new Promise((resolve) => this.waiters.push(resolve));
}
}
describe('message activity', () => {
- afterEach(() => {
+ let harness: ApiTestHarness;
+ let publisher: CapturingPublisher;
+ let author: TestAccount;
+ let user: User;
+ let channel: Channel;
+ let recipient: TestAccount;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ author = await createTestAccount(harness);
+ recipient = await createTestAccount(harness);
+ const dm = await createDmChannel(harness, author.token, recipient.userId);
+ const storedUser = await userRepository.findUnique(createUserID(BigInt(author.userId)));
+ const storedChannel = await channelRepository.channelData.findUnique(createChannelID(BigInt(dm.id)));
+ assert(storedUser !== null && storedChannel !== null);
+ user = storedUser;
+ channel = storedChannel;
+ publisher = new CapturingPublisher();
+ });
+
+ afterEach(async () => {
+ await idleActivityEvents();
resetActivityEventsForTests();
});
- function params(attachments: Array<MessageAttachment>, content = '') {
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+
+ function params(attachments: Array<MessageAttachment>, content = ''): Parameters<typeof emitMessageCreated>[0] {
return {
- user: {id: createUserID(3n), isBot: false} as unknown as User,
- message: message(attachments, content),
- channel: {id: createChannelID(10n), type: ChannelTypes.DM} as unknown as Channel,
+ user,
+ message: new Message({...message(attachments, content).toRow(), author_id: user.id, channel_id: channel.id}),
+ channel,
guildId: null,
guildOwnerId: null,
- dmRecipientId: createUserID(4n),
+ dmRecipientId: createUserID(BigInt(recipient.userId)),
channelHadMessages: true,
delivered: true,
- userRepository: {getRelationship: async () => null},
+ userRepository,
};
}
it('serializes attachment metadata', async () => {
- const publisher = new CapturingPublisher();
await startActivityEvents({publisher, kv: new MockKVProvider()});
emitMessageCreated(params([attachment(1n, HASH), attachment(2n, null)]));
- await vi.waitFor(() => expect(publisher.payloads).toHaveLength(1));
- const event = JSON.parse(publisher.payloads[0]!);
- expect([event.kind, event.key]).toEqual(['message_created', '3']);
- expect(event.data).toMatchObject({
- attachment_count: 2,
- attachments: [
- {size: 10, content_type: 'image/png', hash: HASH.toLowerCase()},
- {size: 20, content_type: 'image/png', hash: null},
- ],
+ expect(await publisher.next()).toMatchObject({
+ kind: 'message_created',
+ key: author.userId,
+ data: {
+ channel_type: 'dm',
+ attachment_count: 2,
+ attachments: [
+ {size: 10, content_type: 'image/png', hash: '3f'.repeat(32)},
+ {size: 20, content_type: 'image/png', hash: null},
+ ],
+ },
});
});
- it('serializes message updates', async () => {
- const publisher = new CapturingPublisher();
- await startActivityEvents({publisher, kv: new MockKVProvider()});
- emitMessageCreated(params([]));
- emitMessageUpdated(params([attachment(1n, HASH)]));
- await vi.waitFor(() => expect(publisher.payloads).toHaveLength(2));
- const [created, updated] = publisher.payloads.map((payload) => JSON.parse(payload));
- expect(created.kind).toBe('message_created');
- expect(updated.kind).toBe('message_updated');
- expect(updated.data).toMatchObject({message_id: '100', attachments: [{hash: HASH.toLowerCase()}]});
- expect(updated.id).not.toBe(created.id);
- });
-
it('records the link domain of a masked markdown link without its brackets', async () => {
- const publisher = new CapturingPublisher();
await startActivityEvents({publisher, kv: new MockKVProvider()});
emitMessageCreated(
params(
@@ -127,8 +170,8 @@ describe('message activity', () => {
'[OPEN](https://Shop.Example.com) [docs](<https://www.docs.example.org/a>) https://[email protected]:8443/x',
),
);
- await vi.waitFor(() => expect(publisher.payloads).toHaveLength(1));
- const event = JSON.parse(publisher.payloads[0]!);
- expect(event.data.link_domains).toEqual(['shop.example.com', 'docs.example.org', 'cdn.example.net']);
+ expect(await publisher.next()).toMatchObject({
+ data: {link_domains: ['shop.example.com', 'docs.example.org', 'cdn.example.net']},
+ });
});
});
diff --git a/fluxer_api/src/api/channel/services/message/MessageResponseDataService.test.ts b/fluxer_api/src/api/channel/services/message/MessageResponseDataService.test.ts
index 0cf67218a..9ea0ea919 100644
--- a/fluxer_api/src/api/channel/services/message/MessageResponseDataService.test.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageResponseDataService.test.ts
@@ -5,17 +5,11 @@ import {
MESSAGE_BUILD_BATCH_MAX_BYTES,
MessageResponseDataService,
} from '@app/api/channel/services/message/MessageResponseDataService';
-import {
- type InstanceAttachmentDecayEffectiveConfig,
- InstanceConfigRepository,
-} from '@app/api/instance/InstanceConfigRepository';
import {Message} from '@app/api/models/Message';
import {FakeNatsConnectionManager} from '@app/api/test/mocks/FakeNatsConnectionManager';
import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';
import {afterEach, describe, expect, it, vi} from 'vitest';
-const ROUTER_SHARD_REQUEST_TIMEOUT_MS = 5000;
-
function createConnectionManager() {
const orphanedMessageIds = new Set<string>();
return Object.assign(
@@ -114,73 +108,6 @@ describe('MessageResponseDataService', () => {
vi.restoreAllMocks();
});
- it('omits reactions from broadcast message response requests', async () => {
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
-
- await service.buildBroadcastMessage({
- channel: {guildId: null},
- message: makeMessage(),
- });
-
- expect(connectionManager.requests[0]!.body).toMatchObject({
- op: 'BuildResponse',
- include_reactions: false,
- viewer_user_id: '3',
- });
- });
-
- it('tells the shard whether attachment expiry is on', async () => {
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
- const decayConfig = vi.spyOn(InstanceConfigRepository.prototype, 'getEffectiveAttachmentDecayConfig');
-
- for (const enabled of [true, false]) {
- decayConfig.mockResolvedValue({enabled} as InstanceAttachmentDecayEffectiveConfig);
- await service.buildBroadcastMessage({channel: {guildId: null}, message: makeMessage()});
- }
-
- expect(connectionManager.requests.map(({body: payload}) => payload.attachment_decay)).toEqual([true, false]);
- });
-
- it('waits longer than the router shard timeout so the inner hop expires first', async () => {
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
-
- await service.buildBroadcastMessage({
- channel: {guildId: null},
- message: makeMessage(),
- });
-
- expect(connectionManager.requests[0]!.timeout).toBe(6000);
- expect(connectionManager.requests[0]!.timeout).toBeGreaterThan(ROUTER_SHARD_REQUEST_TIMEOUT_MS);
- });
-
- it('sends no request when there are no messages to build', async () => {
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
-
- const responses = await service.buildMessages({userId: VIEWER_ID, messages: [], access: ACCESS});
-
- expect(responses).toEqual([]);
- expect(connectionManager.requests).toEqual([]);
- });
-
- it('keeps a batch that exactly fills the byte budget in one request', async () => {
- const baseBytes = await measureSerializedMessageBytes();
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
- const messages = [
- makeSizedMessage(0, MESSAGE_BUILD_BATCH_MAX_BYTES / 2, baseBytes),
- makeSizedMessage(1, MESSAGE_BUILD_BATCH_MAX_BYTES / 2, baseBytes),
- ];
-
- const responses = await service.buildMessages({userId: VIEWER_ID, messages, access: ACCESS});
-
- expect(batchSizes(connectionManager)).toEqual([2]);
- expect(responses.map((response) => response.id)).toEqual(messages.map((message) => message.id.toString()));
- });
-
it('splits into ordered batches once one more byte would cross the budget', async () => {
const baseBytes = await measureSerializedMessageBytes();
const connectionManager = createConnectionManager();
@@ -197,21 +124,6 @@ describe('MessageResponseDataService', () => {
expect(responses.map((response) => response.id)).toEqual(messages.map((message) => message.id.toString()));
});
- it('sends a single message that exceeds the budget on its own', async () => {
- const baseBytes = await measureSerializedMessageBytes();
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
- const messages = [
- makeSizedMessage(0, MESSAGE_BUILD_BATCH_MAX_BYTES + 1, baseBytes),
- makeSizedMessage(1, baseBytes, baseBytes),
- ];
-
- const responses = await service.buildMessages({userId: VIEWER_ID, messages, access: ACCESS});
-
- expect(batchSizes(connectionManager)).toEqual([1, 1]);
- expect(responses.map((response) => response.id)).toEqual(messages.map((message) => message.id.toString()));
- });
-
it('drops a message the service leaves out instead of shifting later responses', async () => {
const connectionManager = createConnectionManager();
connectionManager.orphanedMessageIds.add(messageId(1));
@@ -276,17 +188,4 @@ describe('MessageResponseDataService', () => {
expect(responses.map((response) => response.id)).toEqual([messageId(1), messageId(2), messageId(3)]);
expect(responses.map((response) => response.channel_id)).toEqual(['20', '10', '10']);
});
-
- it('keeps a full page of ordinary pins in a single request', async () => {
- const connectionManager = createConnectionManager();
- const service = new MessageResponseDataService(connectionManager);
- const messages = Array.from({length: 50}, (_unused, index) =>
- makeMessage(BASE_MESSAGE_ID + BigInt(index), 'a'.repeat(120)),
- );
-
- const responses = await service.buildMessages({userId: VIEWER_ID, messages, access: ACCESS});
-
- expect(batchSizes(connectionManager)).toEqual([50]);
- expect(responses.map((response) => response.id)).toEqual(messages.map((message) => message.id.toString()));
- });
});
diff --git a/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts b/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts
index b6b7833b1..55435ffe2 100644
--- a/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts
+++ b/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts
@@ -5,13 +5,10 @@ import {createChannelID, createGuildID, createUserID, createWebhookID, createWeb
import {disableCrosspostWorker, followRequest, publishRequest} from '@app/api/channel/tests/AnnouncementTestUtils';
import {
createChannel,
- createFriendship,
- createGroupDmChannel,
createGuild,
deleteChannel,
getChannel,
setupTestGuildWithMembers,
- updateChannel,
} from '@app/api/channel/tests/ChannelTestUtils';
import {
copiesOf,
@@ -25,7 +22,6 @@ import {
import {processRecordedGuildDeletions} from '@app/api/guild/tests/GuildDeletionTestUtils';
import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
@@ -77,137 +73,12 @@ describe('Announcement channel conversion', () => {
afterEach(() => {
setInjectedWorkerService(new NoopWorkerService());
- vi.restoreAllMocks();
});
afterAll(async () => {
await harness?.shutdown();
});
- test('converts a text channel to an announcement channel', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Convert Guild');
- const text = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_TEXT);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const converted = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${text.id}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(converted.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- expect((await getChannel(harness, owner.token, text.id)).type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- const channelUpdates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'CHANNEL_UPDATE');
- expect(channelUpdates).toHaveLength(1);
- expect(channelUpdates[0]?.data).toMatchObject({type: ChannelTypes.GUILD_ANNOUNCEMENT});
- const auditLog = await createBuilder<AuditLogResponse>(harness, owner.token)
- .get(`/guilds/${guild.id}/audit-logs?action_type=${AuditLogActionType.CHANNEL_UPDATE}`)
- .expect(HTTP_STATUS.OK)
- .execute();
- const entry = auditLog.audit_log_entries.find((candidate) => candidate.target_id === text.id);
- const typeChange = entry?.changes?.find((change) => change.key === 'type');
- expect(typeChange?.old_value).toBe(ChannelTypes.GUILD_TEXT);
- expect(typeChange?.new_value).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- expect(worker.byTask('removeChannelFollowers')).toHaveLength(0);
- });
-
- test('converts an announcement channel back to text and schedules follower removal', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Revert Guild');
- const announcement = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- const converted = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${announcement.id}`)
- .body({type: ChannelTypes.GUILD_TEXT})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(converted.type).toBe(ChannelTypes.GUILD_TEXT);
- const removals = worker.byTask('removeChannelFollowers');
- expect(removals).toHaveLength(1);
- expect(removals[0]?.payload).toEqual({sourceChannelId: announcement.id, reason: 'converted'});
- expect(removals[0]?.options?.jobKey).toMatch(new RegExp(`^remove-followers:${announcement.id}:converted:\\d+$`));
- expect(removals[0]?.options?.skipLedger).toBeUndefined();
- });
-
- test('keeps the type when the body has no type or repeats the current type', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Keep Guild');
- const announcement = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- const renamed = await updateChannel(harness, owner.token, announcement.id, {topic: 'release notes'});
- expect(renamed.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- expect(renamed.topic).toBe('release notes');
- const repeated = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${announcement.id}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT, topic: 'still news'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(repeated.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- const nulled = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${announcement.id}`)
- .body({type: null, topic: 'null type'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(nulled.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- expect(worker.byTask('removeChannelFollowers')).toHaveLength(0);
- });
-
- test('rejects conversions outside text and announcement', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Reject Guild');
- const text = await createChannel(harness, owner.token, guild.id, 'text', ChannelTypes.GUILD_TEXT);
- const announcement = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- const attempts: Array<{channelId: string; type: number | string}> = [
- {channelId: text.id, type: ChannelTypes.GUILD_VOICE},
- {channelId: text.id, type: ChannelTypes.GUILD_CATEGORY},
- {channelId: text.id, type: 'announcement'},
- {channelId: announcement.id, type: ChannelTypes.GUILD_VOICE},
- {channelId: announcement.id, type: ChannelTypes.GROUP_DM},
- ];
- for (const attempt of attempts) {
- await createBuilder(harness, owner.token)
- .patch(`/channels/${attempt.channelId}`)
- .body({type: attempt.type})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.CHANNEL_TYPE_CONVERSION_NOT_SUPPORTED)
- .execute();
- }
- expect((await getChannel(harness, owner.token, text.id)).type).toBe(ChannelTypes.GUILD_TEXT);
- expect((await getChannel(harness, owner.token, announcement.id)).type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- });
-
- test('ignores a body type on channels that cannot be converted', async () => {
- const owner = await createTestAccount(harness);
- const friend = await createTestAccount(harness);
- await createFriendship(harness, owner, friend);
- const guild = await createGuild(harness, owner.token, 'Ignore Guild');
- const voice = await createChannel(harness, owner.token, guild.id, 'voice', ChannelTypes.GUILD_VOICE);
- const category = await createChannel(harness, owner.token, guild.id, 'category', ChannelTypes.GUILD_CATEGORY);
- const link = await createBuilder<ChannelResponse>(harness, owner.token)
- .post(`/guilds/${guild.id}/channels`)
- .body({name: 'link', type: ChannelTypes.GUILD_LINK, url: 'https://example.com'})
- .execute();
- const groupDm = await createGroupDmChannel(harness, owner.token, [friend.userId]);
- const attempts: Array<{channelId: string; type: number; expected: number}> = [
- {channelId: voice.id, type: ChannelTypes.GUILD_TEXT, expected: ChannelTypes.GUILD_VOICE},
- {channelId: voice.id, type: ChannelTypes.GUILD_ANNOUNCEMENT, expected: ChannelTypes.GUILD_VOICE},
- {channelId: category.id, type: ChannelTypes.GUILD_ANNOUNCEMENT, expected: ChannelTypes.GUILD_CATEGORY},
- {channelId: link.id, type: ChannelTypes.GUILD_TEXT, expected: ChannelTypes.GUILD_LINK},
- {channelId: groupDm.id, type: ChannelTypes.GUILD_ANNOUNCEMENT, expected: ChannelTypes.GROUP_DM},
- ];
- for (const [index, attempt] of attempts.entries()) {
- const name = `renamed-${index}`;
- const updated = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${attempt.channelId}`)
- .body({type: attempt.type, name})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(updated.type).toBe(attempt.expected);
- expect(updated.name).toBe(name);
- const stored = await getChannel(harness, owner.token, attempt.channelId);
- expect(stored.type).toBe(attempt.expected);
- expect(stored.name).toBe(name);
- }
- });
-
test('requires MANAGE_CHANNELS', async () => {
const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
const member = members[0]!;
@@ -258,36 +129,6 @@ describe('Announcement channel conversion', () => {
expect(converted.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
});
- test('an incoming webhook does not block conversion', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Incoming Guild');
- const text = await createChannel(harness, owner.token, guild.id, 'feed', ChannelTypes.GUILD_TEXT);
- await createWebhook(harness, text.id, owner.token, 'Incoming Bot');
- const converted = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${text.id}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(converted.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- });
-
- test('records a distinct job for every conversion back to text', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Flip Guild');
- const announcement = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- for (const type of [ChannelTypes.GUILD_TEXT, ChannelTypes.GUILD_ANNOUNCEMENT, ChannelTypes.GUILD_TEXT]) {
- await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${announcement.id}`)
- .body({type})
- .expect(HTTP_STATUS.OK)
- .execute();
- }
- const removals = worker.byTask('removeChannelFollowers');
- expect(removals).toHaveLength(2);
- const jobKeys = new Set(removals.map((job) => job.options?.jobKey));
- expect(jobKeys.size).toBe(2);
- });
-
test('deleting an announcement channel schedules follower removal with source-deleted copies', async () => {
const owner = await createTestAccount(harness);
const guild = await createGuild(harness, owner.token, 'Delete Guild');
@@ -306,25 +147,6 @@ describe('Announcement channel conversion', () => {
expect(removals[0]?.options?.jobKey).toMatch(new RegExp(`^remove-followers:${announcement.id}:deleted:\\d+$`));
});
- test('deleting a guild schedules follower removal for each announcement channel', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Owner Delete Guild');
- const first = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- const second = await createChannel(harness, owner.token, guild.id, 'updates', ChannelTypes.GUILD_ANNOUNCEMENT);
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guild.id}/delete`)
- .body({password: owner.password})
- .expect(HTTP_STATUS.NO_CONTENT)
- .executeWithResponse();
- await processRecordedGuildDeletions(worker);
- const removals = worker.byTask('removeChannelFollowers');
- expect(removals.map((job) => job.payload.sourceChannelId).sort()).toEqual([first.id, second.id].sort());
- for (const job of removals) {
- expect(job.payload.reason).toBe('deleted');
- expect(job.payload.copyMode).toBe('source_deleted');
- }
- });
-
test('admin guild deletion purges copies', async () => {
const admin = await createTestAccount(harness);
await setUserACLs(harness, admin, ['admin:authenticate', 'guild:lookup', 'guild:delete']);
@@ -361,7 +183,6 @@ describe('Announcement channel conversion with the crosspost worker', () => {
afterEach(() => {
disableCrosspostWorker();
- vi.restoreAllMocks();
});
afterAll(async () => {
@@ -385,7 +206,6 @@ describe('Announcement channel conversion with the crosspost worker', () => {
await followInto(harness, world, world.b.t1.id);
await followInto(harness, world, world.b.t2.id);
const source = await postAndPublish(harness, world, {content: 'before conversion'});
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await convert(ChannelTypes.GUILD_TEXT);
expect(world.worker.byTask('removeChannelFollowers')).toHaveLength(1);
expect(await followerWebhooks(world.b.t1.id)).toHaveLength(1);
@@ -393,12 +213,6 @@ describe('Announcement channel conversion with the crosspost worker', () => {
expect(world.worker.deadLetters).toHaveLength(0);
expect(await followerWebhooks(world.b.t1.id)).toHaveLength(0);
expect(await followerWebhooks(world.b.t2.id)).toHaveLength(0);
- const updates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'WEBHOOKS_UPDATE' && params.guildId.toString() === world.b.guild.id);
- expect(updates.map((params) => (params.data as {channel_id: string}).channel_id).sort()).toEqual(
- [world.b.t1.id, world.b.t2.id].sort(),
- );
const audit = await createBuilder<AuditLogResponse>(harness, world.b.owner.token)
.get(`/guilds/${world.b.guild.id}/audit-logs?action_type=${AuditLogActionType.WEBHOOK_DELETE}`)
.execute();
diff --git a/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts b/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts
index dccf4067d..8c2b14ca5 100644
--- a/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts
+++ b/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts
@@ -1,9 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createChannelID, createGuildID, createMessageID} from '@app/api/BrandedTypes';
+import {createChannelID} from '@app/api/BrandedTypes';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
import {disableCrosspostWorker} from '@app/api/channel/tests/AnnouncementTestUtils';
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {
@@ -16,14 +15,10 @@ import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, MessageFlags} from '@fluxer/constants/src/ChannelConstants';
import {ServerMessageFlags, THREAD_MESSAGE_FLAG_MASK} from '@fluxer/constants/src/ThreadConstants';
import {ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';
-import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
-import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
import type {
ArchivedThreadsResponse,
ThreadChannelResponse,
@@ -57,10 +52,6 @@ describe('announcement threads', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -99,41 +90,7 @@ describe('announcement threads', () => {
return {state: state?.type, channel: channel?.type};
}
- describe('creation', () => {
- it('starts an announcement thread from a message in an announcement channel', async () => {
- const s = await setup();
- const message = await sendMessage(harness, s.owner.token, s.announcementId, 'headline');
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const thread = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
- .post(`/channels/${s.announcementId}/messages/${message.id}/threads`)
- .body({name: 'Discussion'})
- .expect(201)
- .execute();
- expect(thread).toMatchObject({
- id: message.id,
- type: ChannelTypes.ANNOUNCEMENT_THREAD,
- parent_id: s.announcementId,
- });
- expect(thread.thread_metadata?.invitable).toBeUndefined();
- const events = dispatch.mock.calls.map(([params]) => params);
- expect(events.find((params) => params.event === 'THREAD_CREATE')?.data).toMatchObject({
- type: ChannelTypes.ANNOUNCEMENT_THREAD,
- });
- const starter = events.find(
- (params) => params.event === 'MESSAGE_CREATE' && (params.data as MessageResponse).channel_id === message.id,
- )?.data as MessageResponse | undefined;
- expect(starter?.referenced_message?.id).toBe(message.id);
- const stored = await repository.messages.getMessage(
- createChannelID(BigInt(s.announcementId)),
- createMessageID(BigInt(message.id)),
- );
- expect(stored!.flags & ServerMessageFlags.HAS_THREAD).toBe(ServerMessageFlags.HAS_THREAD);
- expect(await storedType(thread.id)).toEqual({
- state: ChannelTypes.ANNOUNCEMENT_THREAD,
- channel: ChannelTypes.ANNOUNCEMENT_THREAD,
- });
- });
-
+ describe('creation and lists', () => {
it('creates an announcement thread for either public type and refuses private threads', async () => {
const s = await setup();
for (const type of [ChannelTypes.ANNOUNCEMENT_THREAD, ChannelTypes.PUBLIC_THREAD]) {
@@ -154,15 +111,6 @@ describe('announcement threads', () => {
expect(text.type).toBe(ChannelTypes.PUBLIC_THREAD);
});
- it('posts a thread created message in the announcement channel', async () => {
- const s = await setup();
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const thread = await startThread(s.owner.token, s.announcementId);
- const created = dispatch.mock.calls.map(([params]) => params).find((params) => params.event === 'MESSAGE_CREATE')
- ?.data as MessageResponse | undefined;
- expect(created).toMatchObject({channel_id: s.announcementId, message_reference: {channel_id: thread.id}});
- });
-
it('derives permissions from the announcement channel', async () => {
const s = await setup();
const thread = await startThread(s.member.token, s.announcementId);
@@ -192,9 +140,7 @@ describe('announcement threads', () => {
.expect(403)
.execute();
});
- });
- describe('lists and members', () => {
it('returns announcement threads from the public archived list and refuses private lists', async () => {
const s = await setup();
const thread = await startThread(s.owner.token, s.announcementId);
@@ -215,83 +161,9 @@ describe('announcement threads', () => {
.execute();
}
});
-
- it('lets members join, chat in, rename and archive an announcement thread', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.announcementId);
- await threadsRequest(harness, s.member.token)
- .put(`/channels/${thread.id}/thread-members/@me`)
- .expect(204)
- .execute();
- const sent = await threadsRequest<MessageResponse>(harness, s.member.token)
- .post(`/channels/${thread.id}/messages`)
- .body({content: 'reply'})
- .expect(200)
- .execute();
- expect(sent.channel_id).toBe(thread.id);
- const renamed = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${thread.id}`)
- .body({name: 'renamed', archived: true, invitable: false})
- .expect(200)
- .execute();
- expect(renamed).toMatchObject({type: ChannelTypes.ANNOUNCEMENT_THREAD, name: 'renamed'});
- expect(renamed.thread_metadata).toMatchObject({archived: true});
- expect(renamed.thread_metadata?.invitable).toBeUndefined();
- });
-
- it('fetches an announcement thread by id', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.announcementId);
- const channel = await threadsRequest<ThreadChannelResponse>(harness, s.member.token)
- .get(`/channels/${thread.id}`)
- .execute();
- expect(channel.type).toBe(ChannelTypes.ANNOUNCEMENT_THREAD);
- });
});
describe('conversion', () => {
- it('turns public threads into announcement threads and back', async () => {
- const s = await setup();
- const active = await startThread(s.owner.token, s.textId, {name: 'live', type: ChannelTypes.PUBLIC_THREAD});
- const archived = await startThread(s.owner.token, s.textId, {name: 'old', type: ChannelTypes.PUBLIC_THREAD});
- await archive(archived.id);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuildMany');
- const single = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const converted = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${s.textId}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(200)
- .execute();
- expect(converted.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- for (const thread of [active, archived]) {
- expect(await storedType(thread.id)).toEqual({
- state: ChannelTypes.ANNOUNCEMENT_THREAD,
- channel: ChannelTypes.ANNOUNCEMENT_THREAD,
- });
- }
- const updates = [
- ...single.mock.calls.map(([params]) => params),
- ...dispatch.mock.calls.flatMap(([params]) => params.events),
- ].filter((params) => params.event === 'THREAD_UPDATE');
- expect(updates.map((params) => (params.data as ThreadChannelResponse).id)).toEqual([active.id]);
- expect(updates[0]!.data).toMatchObject({type: ChannelTypes.ANNOUNCEMENT_THREAD});
- const page = await threadsRequest<ArchivedThreadsResponse>(harness, s.owner.token)
- .get(`/channels/${s.textId}/threads/archived/public`)
- .execute();
- expect(page.threads.map((entry) => entry.type)).toEqual([ChannelTypes.ANNOUNCEMENT_THREAD]);
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.textId}`)
- .body({type: ChannelTypes.GUILD_TEXT})
- .expect(200)
- .execute();
- for (const thread of [active, archived]) {
- expect(await storedType(thread.id)).toEqual({
- state: ChannelTypes.PUBLIC_THREAD,
- channel: ChannelTypes.PUBLIC_THREAD,
- });
- }
- });
-
it('refuses converting a text channel with private threads to announcement', async () => {
const s = await setup();
const secret = await startThread(s.owner.token, s.textId, {name: 'secret', type: ChannelTypes.PRIVATE_THREAD});
@@ -309,45 +181,6 @@ describe('announcement threads', () => {
);
});
- it('rolls back a failed retype and leaves the parent unconverted so a retry converges', async () => {
- const s = await setup();
- const threads = [];
- for (const name of ['a', 'b', 'c']) {
- threads.push(await startThread(s.owner.token, s.textId, {name, type: ChannelTypes.PUBLIC_THREAD}));
- }
- await archive(threads[2]!.id);
- vi.spyOn(ThreadRepository.prototype, 'setThreadType').mockRejectedValueOnce(new ServiceUnavailableError());
- const update = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.textId}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(503)
- .execute();
- expect((await repository.channelData.findUnique(createChannelID(BigInt(s.textId))))?.type).toBe(
- ChannelTypes.GUILD_TEXT,
- );
- expect(update.mock.calls.filter(([params]) => params.event === 'CHANNEL_UPDATE')).toEqual([]);
- vi.restoreAllMocks();
- for (const thread of threads) {
- expect(await storedType(thread.id)).toEqual({
- state: ChannelTypes.PUBLIC_THREAD,
- channel: ChannelTypes.PUBLIC_THREAD,
- });
- }
- const converted = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${s.textId}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(200)
- .execute();
- expect(converted.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- for (const thread of threads) {
- expect(await storedType(thread.id)).toEqual({
- state: ChannelTypes.ANNOUNCEMENT_THREAD,
- channel: ChannelTypes.ANNOUNCEMENT_THREAD,
- });
- }
- });
-
it('refuses converting a parent with retained private threads for incapable callers', async () => {
const s = await setup();
await startThread(s.owner.token, s.textId, {name: 'secret', type: ChannelTypes.PRIVATE_THREAD});
@@ -357,25 +190,6 @@ describe('announcement threads', () => {
.expect(400, APIErrorCodes.CHANNEL_HAS_THREADS)
.execute();
});
-
- it('converts announcement channels while preserving retained threads', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.announcementId);
-
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- await createBuilder(harness, s.owner.token)
- .patch(`/channels/${s.announcementId}`)
- .body({type: ChannelTypes.GUILD_TEXT})
- .expect(200)
- .execute();
- expect(await storedType(thread.id)).toEqual({
- state: ChannelTypes.PUBLIC_THREAD,
- channel: ChannelTypes.PUBLIC_THREAD,
- });
- expect(
- dispatch.mock.calls.filter(([params]) => params.event.startsWith('THREAD_')).map(([params]) => params.data),
- ).toMatchObject([{id: thread.id, type: ChannelTypes.PUBLIC_THREAD}]);
- });
});
describe('announcements', () => {
@@ -428,28 +242,6 @@ describe('announcement threads', () => {
});
describe('control arm', () => {
- it('keeps announcement channels unchanged for clients without the capability', async () => {
- const s = await setup();
- const message = await sendMessage(harness, s.owner.token, s.announcementId, 'headline');
- await threadsRequest(harness, s.owner.token, {capable: false})
- .post(`/channels/${s.announcementId}/messages/${message.id}/threads`)
- .body({name: 'nope'})
- .expect(404)
- .execute();
- const updated = await threadsRequest<Record<string, unknown>>(harness, s.owner.token, {capable: false})
- .patch(`/channels/${s.announcementId}`)
- .body({topic: 'news', default_auto_archive_duration: 60})
- .expect(200)
- .execute();
- expect(updated.topic).toBe('news');
- expect('default_auto_archive_duration' in updated).toBe(false);
- const config = await repository.threads.getParentConfig(
- createGuildID(BigInt(s.guildId)),
- createChannelID(BigInt(s.announcementId)),
- );
- expect(config?.defaultAutoArchiveDuration ?? null).toBeNull();
- });
-
it('masks thread flags in the publish response for clients without the capability', async () => {
const s = await setup();
const message = await sendMessage(harness, s.owner.token, s.announcementId, 'headline');
@@ -466,38 +258,5 @@ describe('announcement threads', () => {
expect(published.flags & THREAD_MESSAGE_FLAG_MASK).toBe(0);
expect('thread' in published).toBe(false);
});
-
- it('stores thread defaults on announcement channels for viewers', async () => {
- const s = await setup();
- const updated = await threadsRequest<Record<string, unknown>>(harness, s.owner.token)
- .patch(`/channels/${s.announcementId}`)
- .body({default_auto_archive_duration: 60, default_thread_rate_limit_per_user: 5})
- .expect(200)
- .execute();
- expect(updated).toMatchObject({default_auto_archive_duration: 60, default_thread_rate_limit_per_user: 5});
- const thread = await startThread(s.owner.token, s.announcementId);
- expect(thread.thread_metadata?.auto_archive_duration).toBe(4320);
- expect(thread.rate_limit_per_user).toBe(5);
- });
-
- it('converts announcement channels when the parent has no threads', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'plain');
- const announcement = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const converted = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${announcement.id}`)
- .body({type: ChannelTypes.GUILD_TEXT})
- .expect(200)
- .execute();
- expect(converted.type).toBe(ChannelTypes.GUILD_TEXT);
- expect(dispatch.mock.calls.filter(([params]) => params.event.startsWith('THREAD_'))).toEqual([]);
- const back = await createBuilder<ChannelResponse>(harness, owner.token)
- .patch(`/channels/${announcement.id}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(200)
- .execute();
- expect(back.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- });
});
});
diff --git a/fluxer_api/src/api/channel/tests/BulkDeleteMessages.test.ts b/fluxer_api/src/api/channel/tests/BulkDeleteMessages.test.ts
index 974efb29c..e5519bfab 100644
--- a/fluxer_api/src/api/channel/tests/BulkDeleteMessages.test.ts
+++ b/fluxer_api/src/api/channel/tests/BulkDeleteMessages.test.ts
@@ -18,23 +18,6 @@ describe('Bulk Delete Messages', () => {
afterAll(async () => {
await harness?.shutdown();
});
- it('rejects bulk delete without MANAGE_MESSAGES permission when channel does not exist', async () => {
- const owner = await createTestAccount(harness);
- const member = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Permissions Test Guild');
- if (!guild.system_channel_id) {
- throw new Error('Guild should have a system channel');
- }
- const messageIds: Array<string> = [];
- for (let i = 0; i < 3; i++) {
- messageIds.push(`${1000000000000000000n + BigInt(i)}`);
- }
- await createBuilder(harness, member.token)
- .post(`/channels/${guild.system_channel_id}/messages/bulk-delete`)
- .body({message_ids: messageIds})
- .expect(403)
- .execute();
- });
it('removes every message when the bulk delete spans more than one batch chunk', async () => {
const owner = await createTestAccount(harness);
const guild = await createGuild(harness, owner.token, 'Bulk Delete Chunk Test Guild');
@@ -61,20 +44,4 @@ describe('Bulk Delete Messages', () => {
}
expect(remainingIds).toContain(survivor.id);
});
- it('accepts bulk delete request with the compat messages alias', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Bulk Delete Alias Test Guild');
- if (!guild.system_channel_id) {
- throw new Error('Guild should have a system channel');
- }
- const messageIds: Array<string> = [];
- for (let i = 0; i < 3; i++) {
- messageIds.push(`${1000000000000000000n + BigInt(i)}`);
- }
- await createBuilder(harness, owner.token)
- .post(`/channels/${guild.system_channel_id}/messages/bulk-delete`)
- .body({messages: messageIds})
- .expect(204)
- .execute();
- });
});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts b/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts
index b811b7e4d..16b2aee04 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {loadFixture, sendMessageWithAttachments} from '@app/api/channel/tests/AttachmentTestUtils';
import {
type AnnouncementWorld,
channelBudgetRemaining,
@@ -9,12 +8,9 @@ import {
editMessage,
postMessage,
publish,
- publishedEditBudgetRemaining,
RecordingWorkerService,
} from '@app/api/channel/tests/CrosspostTestUtils';
-import {createChannel} from '@app/api/guild/tests/GuildTestUtils';
import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
@@ -24,9 +20,7 @@ import {
PUBLISHED_MESSAGE_EDIT_RATE_LIMIT,
} from '@fluxer/constants/src/AnnouncementConstants';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {ChannelTypes, MessageFlags} from '@fluxer/constants/src/ChannelConstants';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {ms} from 'itty-time';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
interface RateLimitBody {
@@ -81,43 +75,6 @@ describe('Publishing and published-edit limits', () => {
expect(worker.byTask('crosspostMessage')).toHaveLength(CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
});
- test('the channel limit is per channel and shared across members', async () => {
- await publishMany(world.announcement.id, CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
- const byMod = await postMessage(harness, world.mod.token, world.announcement.id, 'Moderator news');
- await crosspostRequest(harness, world.mod.token, world.announcement.id, byMod.id)
- .expect(429, APIErrorCodes.MESSAGE_CROSSPOST_RATE_LIMITED)
- .execute();
- const second = await createChannel(
- harness,
- world.owner.token,
- world.guild.id,
- 'news-two',
- ChannelTypes.GUILD_ANNOUNCEMENT,
- );
- const elsewhere = await postMessage(harness, world.author.token, second.id, 'Different channel');
- await publish(harness, world.author.token, second.id, elsewhere.id);
- });
-
- test('a community has no shared publish allowance across its announcement channels', async () => {
- const channels = [
- world.announcement,
- await createChannel(harness, world.owner.token, world.guild.id, 'news-b', ChannelTypes.GUILD_ANNOUNCEMENT),
- await createChannel(harness, world.owner.token, world.guild.id, 'news-c', ChannelTypes.GUILD_ANNOUNCEMENT),
- await createChannel(harness, world.owner.token, world.guild.id, 'news-d', ChannelTypes.GUILD_ANNOUNCEMENT),
- ];
- for (const channel of channels) {
- await publishMany(channel.id, CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
- expect(await channelBudgetRemaining(channel.id)).toBe(0);
- }
- expect(worker.byTask('crosspostMessage')).toHaveLength(channels.length * CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
- const last = channels[3]!;
- const extra = await postMessage(harness, world.author.token, last.id, 'One past the channel allowance');
- const {response} = await crosspostRequest(harness, world.author.token, last.id, extra.id)
- .expect(429, APIErrorCodes.MESSAGE_CROSSPOST_RATE_LIMITED)
- .executeWithResponse();
- expect(response.headers.get('X-RateLimit-Scope')).toBe('shared');
- });
-
test('failed publishes do not consume budget', async () => {
const published = await postMessage(harness, world.author.token, world.announcement.id, 'Published once');
await publish(harness, world.author.token, world.announcement.id, published.id);
@@ -166,59 +123,6 @@ describe('Publishing and published-edit limits', () => {
.execute();
});
- test('edits before publishing do not count toward the published-edit cap', async () => {
- const message = await postMessage(harness, world.author.token, world.announcement.id, 'Draft');
- for (let index = 0; index < 3; index++) {
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: `Draft ${index}`})
- .expect(200)
- .execute();
- }
- expect(worker.syncJobsFor(message.id)).toHaveLength(0);
- await publish(harness, world.author.token, world.announcement.id, message.id);
- expect(await publishedEditBudgetRemaining(message.id)).toBe(PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts);
- for (let index = 0; index < PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts; index++) {
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: `Final ${index}`})
- .expect(200)
- .execute();
- }
- });
-
- test('unpublished messages are never limited by the published-edit cap', async () => {
- const message = await postMessage(harness, world.author.token, world.announcement.id, 'Never published');
- for (let index = 0; index < 6; index++) {
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: `Version ${index}`})
- .expect(200)
- .execute();
- }
- expect(await publishedEditBudgetRemaining(message.id)).toBe(PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts);
- expect(worker.byTask('syncCrosspostedMessage')).toHaveLength(0);
- });
-
- test('a moderator suppress-embeds edit is not limited and still propagates', async () => {
- const message = await postMessage(harness, world.author.token, world.announcement.id, 'Link https://example.com');
- await publish(harness, world.author.token, world.announcement.id, message.id);
- for (let index = 0; index < PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts; index++) {
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: `Link ${index}`})
- .expect(200)
- .execute();
- }
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: 'Blocked'})
- .expect(429, APIErrorCodes.PUBLISHED_MESSAGE_EDIT_RATE_LIMITED)
- .execute();
- const syncsBefore = worker.syncJobsFor(message.id).length;
- const suppressed = await editMessage(harness, world.mod.token, world.announcement.id, message.id, {
- flags: MessageFlags.SUPPRESS_EMBEDS,
- })
- .expect(200)
- .execute();
- expect(suppressed.flags).toBe(MessageFlags.CROSSPOSTED | MessageFlags.SUPPRESS_EMBEDS);
- const restored = await editMessage(harness, world.mod.token, world.announcement.id, message.id, {flags: 0})
- .expect(200)
- .execute();
- expect(restored.flags).toBe(MessageFlags.CROSSPOSTED);
- expect(worker.syncJobsFor(message.id).length).toBe(syncsBefore + 2);
- });
-
test('webhook token edits count toward the published-edit cap', async () => {
const webhook = await createWebhook(harness, world.announcement.id, world.owner.token, 'Changelog');
const executed = await createBuilderWithoutAuth<MessageResponse>(harness)
@@ -242,99 +146,4 @@ describe('Publishing and published-edit limits', () => {
.execute();
expect(worker.syncJobsFor(executed.id)).toHaveLength(PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts);
});
-
- test('published edits that fail validation do not use the edit budget', async () => {
- const missingUpload = {
- attachments: [
- {
- id: 0,
- filename: 'upload.png',
- upload_filename: 'missing-upload-key',
- file_size: 2048,
- content_type: 'image/png',
- },
- ],
- };
- const message = await postMessage(harness, world.author.token, world.announcement.id, 'Edit me');
- await publish(harness, world.author.token, world.announcement.id, message.id);
- for (let index = 0; index < PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts; index++) {
- const {json} = await editMessage(harness, world.author.token, world.announcement.id, message.id, {
- content: `Broken ${index}`,
- ...missingUpload,
- })
- .expect(400)
- .executeWithResponse();
- expect(JSON.stringify(json)).toContain('FILE_NOT_FOUND');
- }
- expect(await publishedEditBudgetRemaining(message.id)).toBe(PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts);
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: 'Valid edit'})
- .expect(200)
- .execute();
- expect(await publishedEditBudgetRemaining(message.id)).toBe(PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts - 1);
- });
-
- test('removing an attachment from a published message counts toward the cap and propagates', async () => {
- const {json} = await sendMessageWithAttachments(
- harness,
- world.author.token,
- world.announcement.id,
- {
- content: 'Two pictures',
- attachments: [
- {id: 0, filename: 'first.png'},
- {id: 1, filename: 'second.png'},
- ],
- },
- [
- {index: 0, filename: 'first.png', data: loadFixture('yeah.png')},
- {index: 1, filename: 'second.png', data: loadFixture('yeah.png')},
- ],
- );
- expect(json.attachments?.length).toBe(2);
- await publish(harness, world.author.token, world.announcement.id, json.id);
- await createBuilder(harness, world.author.token)
- .delete(`/channels/${world.announcement.id}/messages/${json.id}/attachments/${json.attachments![0]!.id}`)
- .expect(204)
- .execute();
- expect(await publishedEditBudgetRemaining(json.id)).toBe(PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts - 1);
- expect(worker.syncJobsFor(json.id)).toHaveLength(1);
- for (let index = 0; index < PUBLISHED_MESSAGE_EDIT_RATE_LIMIT.maxAttempts - 1; index++) {
- await editMessage(harness, world.author.token, world.announcement.id, json.id, {content: `Caption ${index}`})
- .expect(200)
- .execute();
- }
- await createBuilder(harness, world.author.token)
- .delete(`/channels/${world.announcement.id}/messages/${json.id}/attachments/${json.attachments![1]!.id}`)
- .expect(429, APIErrorCodes.PUBLISHED_MESSAGE_EDIT_RATE_LIMITED)
- .execute();
- });
-
- test('the publish and follow route buckets are enforced when route limits are on', async () => {
- expect(RateLimitConfigs.CHANNEL_MESSAGE_CROSSPOST).toEqual({
- bucket: 'channel:message:crosspost::channel_id',
- config: {limit: 5, windowMs: ms('5 seconds')},
- });
- expect(RateLimitConfigs.CHANNEL_FOLLOW).toEqual({
- bucket: 'channel:follow::channel_id',
- config: {limit: 5, windowMs: ms('10 seconds')},
- });
- expect(RateLimitConfigs.CHANNEL_FOLLOWER_STATS).toEqual({
- bucket: 'channel:follower_stats::channel_id',
- config: {limit: 10, windowMs: ms('10 seconds')},
- });
- const statuses: Array<number> = [];
- for (let index = 0; index < 6; index++) {
- const {response} = await crosspostRequest(
- harness,
- world.author.token,
- world.announcement.id,
- `12345678901234567${index}`,
- )
- .header('x-fluxer-test-enable-rate-limits', 'true')
- .executeRaw();
- statuses.push(response.status);
- }
- expect(statuses.slice(0, 5)).toEqual([404, 404, 404, 404, 404]);
- expect(statuses[5]).toBe(429);
- });
});
diff --git a/fluxer_api/src/api/channel/tests/EmbedAttachmentUrlResolution.test.ts b/fluxer_api/src/api/channel/tests/EmbedAttachmentUrlResolution.test.ts
index 0a9fde7a5..fdc338056 100644
--- a/fluxer_api/src/api/channel/tests/EmbedAttachmentUrlResolution.test.ts
+++ b/fluxer_api/src/api/channel/tests/EmbedAttachmentUrlResolution.test.ts
@@ -8,7 +8,6 @@ import {
sendMessageWithAttachments,
} from '@app/api/channel/tests/AttachmentTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('Embed Attachment URL Resolution', () => {
@@ -19,125 +18,7 @@ describe('Embed Attachment URL Resolution', () => {
beforeEach(async () => {
await harness.reset();
});
- describe('Image and Thumbnail Fields', () => {
- it('should handle image and thumbnail in same embed from different files', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'Image And Thumbnail Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const fileData = loadFixture('yeah.png');
- const payload = {
- content: 'Image and thumbnail from different attachments',
- attachments: [
- {id: 0, filename: 'main-image.png'},
- {id: 1, filename: 'thumb-image.png'},
- ],
- embeds: [
- {
- title: 'Dual Image Embed',
- image: {url: 'attachment://main-image.png'},
- thumbnail: {url: 'attachment://thumb-image.png'},
- },
- ],
- };
- const {response, json} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
- {index: 0, filename: 'main-image.png', data: fileData},
- {index: 1, filename: 'thumb-image.png', data: fileData},
- ]);
- expect(response.status).toBe(200);
- expect(json.attachments ?? []).toHaveLength(0);
- expect(json.embeds).toHaveLength(1);
- const embed = json.embeds![0];
- expect(embed.image?.url).not.toContain('attachment://');
- expect(embed.thumbnail?.url).not.toContain('attachment://');
- expect(embed.image?.url).not.toBe(embed.thumbnail?.url);
- });
- it('should resolve attachment:// URL while preserving external thumbnail URL', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'Preserve External URL Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const fileData = loadFixture('yeah.png');
- const payload = {
- content: 'Test with external thumbnail',
- attachments: [{id: 0, filename: 'attached.png'}],
- embeds: [
- {
- title: 'External Thumbnail Test',
- image: {url: 'attachment://attached.png'},
- thumbnail: {url: 'https://cdn.example.com/thumb.jpg'},
- },
- ],
- };
- const {response, json} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
- {index: 0, filename: 'attached.png', data: fileData},
- ]);
- expect(response.status).toBe(200);
- expect(json.embeds).toHaveLength(1);
- const embed = json.embeds![0];
- expect(embed.image?.url).not.toContain('attachment://');
- expect(embed.thumbnail?.url).toBe('https://cdn.example.com/thumb.jpg');
- });
- });
- describe('Filename Matching', () => {
- it('should require exact filename matching', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'Filename Matching Test Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const fileData = loadFixture('yeah.png');
- const payload1 = {
- content: 'Case-sensitive filename test',
- attachments: [{id: 0, filename: 'yeah.png'}],
- embeds: [
- {
- title: 'Exact Match Required',
- image: {url: 'attachment://yeah.png'},
- },
- ],
- };
- const {response: response1} = await sendMessageWithAttachments(harness, account.token, channelId, payload1, [
- {index: 0, filename: 'yeah.png', data: fileData},
- ]);
- expect(response1.status).toBe(200);
- const payload2 = {
- content: 'Case mismatch test',
- attachments: [{id: 0, filename: 'yeah.png'}],
- embeds: [
- {
- title: 'Wrong Case',
- image: {url: 'attachment://Yeah.png'},
- },
- ],
- };
- const {response: response2} = await sendMessageWithAttachments(harness, account.token, channelId, payload2, [
- {index: 0, filename: 'yeah.png', data: fileData},
- ]);
- expect(response2.status).toBe(400);
- });
- });
describe('Error Handling', () => {
- it('should reject embed with attachment:// URL when no files are uploaded', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'No Attachments Test Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const payload = {
- content: 'Embed references attachment but none provided',
- embeds: [
- {
- title: 'Invalid Reference',
- description: 'No attachment uploaded',
- image: {url: 'attachment://image.png'},
- },
- ],
- };
- await createBuilder(harness, account.token)
- .post(`/channels/${channelId}/messages`)
- .body(payload)
- .expect(400)
- .execute();
- });
it('should reject embed referencing non-existent filename', async () => {
const account = await createTestAccount(harness);
const guild = await createGuild(harness, account.token, 'Missing Attachment Test Guild');
@@ -183,122 +64,8 @@ describe('Embed Attachment URL Resolution', () => {
]);
expect(response.status).toBe(400);
});
- it('should reject JSON attachment in embed thumbnail field', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'JSON Rejection Test Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const jsonData = Buffer.from(JSON.stringify({key: 'value'}));
- const payload = {
- content: 'Test message with JSON in embed thumbnail',
- attachments: [{id: 0, filename: 'data.json'}],
- embeds: [
- {
- title: 'JSON Embed Attempt',
- thumbnail: {url: 'attachment://data.json'},
- },
- ],
- };
- const {response} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
- {index: 0, filename: 'data.json', data: jsonData},
- ]);
- expect(response.status).toBe(400);
- });
- it('should accept image and video attachments beyond the legacy image extensions', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'Media Type Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const payload = {
- content: 'Test with jxl and mp4 embed media',
- attachments: [
- {id: 0, filename: 'photo.jxl'},
- {id: 1, filename: 'clip.mp4'},
- ],
- embeds: [
- {
- title: 'Media Embed',
- image: {url: 'attachment://clip.mp4'},
- thumbnail: {url: 'attachment://photo.jxl'},
- },
- ],
- };
- const {response, json} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
- {index: 0, filename: 'photo.jxl', data: Buffer.from('jxl bytes')},
- {index: 1, filename: 'clip.mp4', data: Buffer.from('mp4 bytes')},
- ]);
- expect(response.status).toBe(200);
- expect(json.embeds).toHaveLength(1);
- expect(json.embeds![0].image?.url).not.toContain('attachment://');
- expect(json.embeds![0].thumbnail?.url).not.toContain('attachment://');
- });
});
describe('Multiple Embeds and Files', () => {
- it('should handle multiple embeds each referencing different attachments', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'Multiple Embeds Test Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const file1Data = loadFixture('yeah.png');
- const file2Data = loadFixture('animated.gif');
- const payload = {
- content: 'Multiple embeds with different attachments',
- attachments: [
- {id: 0, filename: 'yeah.png'},
- {id: 1, filename: 'animated.gif'},
- ],
- embeds: [
- {
- title: 'First Embed',
- description: 'Uses PNG',
- image: {url: 'attachment://yeah.png'},
- },
- {
- title: 'Second Embed',
- description: 'Uses GIF',
- image: {url: 'attachment://animated.gif'},
- },
- ],
- };
- const {response, json} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
- {index: 0, filename: 'yeah.png', data: file1Data},
- {index: 1, filename: 'animated.gif', data: file2Data},
- ]);
- expect(response.status).toBe(200);
- expect(json.embeds).toBeDefined();
- expect(json.embeds).toHaveLength(2);
- expect(json.embeds![0].image?.url).toContain('yeah.png');
- expect(json.embeds![1].image?.url).toContain('animated.gif');
- });
- it('should allow same attachment to be used in multiple embeds', async () => {
- const account = await createTestAccount(harness);
- const guild = await createGuild(harness, account.token, 'Reused Attachment Guild');
- const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
- const channelId = guild.system_channel_id ?? channel.id;
- const fileData = loadFixture('yeah.png');
- const payload = {
- content: 'Same attachment in multiple embeds',
- attachments: [{id: 0, filename: 'shared.png'}],
- embeds: [
- {
- title: 'First Use',
- image: {url: 'attachment://shared.png'},
- },
- {
- title: 'Second Use',
- thumbnail: {url: 'attachment://shared.png'},
- },
- ],
- };
- const {response, json} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
- {index: 0, filename: 'shared.png', data: fileData},
- ]);
- expect(response.status).toBe(200);
- expect(json.attachments ?? []).toHaveLength(0);
- expect(json.embeds).toHaveLength(2);
- expect(json.embeds![0].image?.url).not.toContain('attachment://');
- expect(json.embeds![1].thumbnail?.url).not.toContain('attachment://');
- });
it('should preserve embed image metadata when attachment is excluded from standalone list', async () => {
const account = await createTestAccount(harness);
const guild = await createGuild(harness, account.token, 'Metadata Guild');
diff --git a/fluxer_api/src/api/channel/tests/ForumChannels.test.ts b/fluxer_api/src/api/channel/tests/ForumChannels.test.ts
index 31da695e6..8a9d9c64b 100644
--- a/fluxer_api/src/api/channel/tests/ForumChannels.test.ts
+++ b/fluxer_api/src/api/channel/tests/ForumChannels.test.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createMultipartFormData} from '@app/api/channel/tests/AttachmentTestUtils';
import {
acceptInvite,
addMemberRole,
@@ -10,22 +9,15 @@ import {
createGuild,
createRole,
} from '@app/api/channel/tests/ChannelTestUtils';
-import {THREADS_FEATURE, THREADS_FEATURE_HEADER, threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
-import {createEmoji, getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
+import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {ChannelFlags} from '@fluxer/constants/src/ThreadConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import type {
- StartForumThreadResponse,
- ThreadPostDataResponse,
-} from '@fluxer/schema/src/domains/channel/ForumRequestSchemas';
-import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
+import type {StartForumThreadResponse} from '@fluxer/schema/src/domains/channel/ForumRequestSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
interface Setup {
@@ -35,11 +27,6 @@ interface Setup {
forumId: string;
}
-const PNG_1X1 = Buffer.from(
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
- 'base64',
-);
-
describe('forum and media channels', () => {
let harness: ApiTestHarness;
@@ -95,13 +82,6 @@ describe('forum and media channels', () => {
.execute();
}
- async function tags(token: string, forumId: string, names: Array<{name: string; moderated?: boolean}>) {
- return threadsRequest<ChannelResponse>(harness, token)
- .patch(`/channels/${forumId}`)
- .body({available_tags: names})
- .execute();
- }
-
describe('control arm', () => {
it('rejects creating forums without the client capability', async () => {
const owner = await createTestAccount(harness);
@@ -115,189 +95,9 @@ describe('forum and media channels', () => {
});
expect(control.status).toBe(400);
});
-
- it('strips the thread defaults of a text channel for incapable callers', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'control');
- const channel = await threadsRequest<ChannelResponse>(harness, owner.token, {capable: false})
- .post(`/guilds/${guild.id}/channels`)
- .body({name: 'text', type: ChannelTypes.GUILD_TEXT, default_auto_archive_duration: 60})
- .execute();
- expect(channel).not.toHaveProperty('default_auto_archive_duration');
- const patched = await threadsRequest<ChannelResponse>(harness, owner.token, {capable: false})
- .patch(`/channels/${channel.id}`)
- .body({default_thread_rate_limit_per_user: 30})
- .execute();
- expect(patched).not.toHaveProperty('default_thread_rate_limit_per_user');
- });
});
describe('settings', () => {
- it('creates a forum with its settings and serves them on reads', async () => {
- const s = await setup({
- topic: 'x'.repeat(2000),
- available_tags: [
- {name: 'bug', emoji_name: '🐛'},
- {name: 'staff', moderated: true},
- ],
- default_sort_order: 1,
- default_forum_layout: 2,
- default_tag_setting: 'match_all',
- default_thread_rate_limit_per_user: 10,
- default_auto_archive_duration: 1440,
- default_reaction_emoji: {emoji_name: '👍'},
- nsfw: true,
- rate_limit_per_user: 15,
- });
- const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .get(`/channels/${s.forumId}`)
- .execute();
- expect(forum.type).toBe(ChannelTypes.GUILD_FORUM);
- expect(forum.topic).toHaveLength(2000);
- expect(forum.available_tags?.map((tag) => [tag.name, tag.moderated, tag.emoji_name])).toEqual([
- ['bug', false, '🐛'],
- ['staff', true, null],
- ]);
- expect(forum).toMatchObject({
- flags: 0,
- default_sort_order: 1,
- default_forum_layout: 2,
- default_tag_setting: 'match_all',
- default_thread_rate_limit_per_user: 10,
- default_auto_archive_duration: 1440,
- default_reaction_emoji: {emoji_id: null, emoji_name: '👍'},
- nsfw: true,
- rate_limit_per_user: 15,
- });
- expect(forum).not.toHaveProperty('icon');
- expect(forum).not.toHaveProperty('owner_id');
- const listed = await threadsRequest<Array<ChannelResponse>>(harness, s.owner.token)
- .get(`/guilds/${s.guildId}/channels`)
- .execute();
- expect(listed.find((channel) => channel.id === s.forumId)?.available_tags).toHaveLength(2);
- });
-
- it('validates tags and flags', async () => {
- const s = await setup();
- const tooMany = Array.from({length: 21}, (_, index) => ({name: `t${index}`}));
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: tooMany})
- .expect(400, APIErrorCodes.MAX_FORUM_TAGS)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{name: 'a'}, {name: 'a'}]})
- .expect(400, APIErrorCodes.FORUM_TAG_NAMES_MUST_BE_UNIQUE)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{id: '123', name: 'a'}]})
- .expect(404, APIErrorCodes.UNKNOWN_FORUM_TAG)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{name: 'a', emoji_name: 'hello'}]})
- .expect(400, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({default_reaction_emoji: {emoji_name: 'hello'}})
- .expect(400, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{name: 'mods', moderated: true}], flags: ChannelFlags.REQUIRE_TAG})
- .expect(400, APIErrorCodes.NO_TAGS_AVAILABLE_TO_NON_MODERATORS)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({flags: ChannelFlags.HIDE_MEDIA_DOWNLOAD_OPTIONS})
- .expect(400, APIErrorCodes.HIDE_MEDIA_DOWNLOAD_OPTION_MEDIA_ONLY)
- .execute();
- const media = await createForum(s.owner.token, s.guildId, {flags: ChannelFlags.HIDE_MEDIA_DOWNLOAD_OPTIONS}, 16);
- expect(media.flags).toBe(ChannelFlags.HIDE_MEDIA_DOWNLOAD_OPTIONS);
- expect(media).not.toHaveProperty('default_forum_layout');
- });
-
- it('keeps tag ids across edits and exposes the tag routes', async () => {
- const s = await setup();
- const first = await tags(s.owner.token, s.forumId, [{name: 'a'}, {name: 'b'}]);
- const [a, b] = first.available_tags!;
- const kept = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{id: b!.id, name: 'b2'}, {name: 'c'}]})
- .execute();
- expect(kept.available_tags![0]).toMatchObject({id: b!.id, name: 'b2'});
- expect(kept.available_tags!.some((tag) => tag.id === a!.id)).toBe(false);
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({
- available_tags: [
- {id: b!.id, name: 'x'},
- {id: b!.id, name: 'y'},
- ],
- })
- .expect(404, APIErrorCodes.UNKNOWN_FORUM_TAG)
- .execute();
- const created = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .post(`/channels/${s.forumId}/tags`)
- .body({name: 'd', moderated: true})
- .execute();
- const d = created.available_tags!.find((tag) => tag.name === 'd')!;
- const updated = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .put(`/channels/${s.forumId}/tags/${d.id}`)
- .body({name: 'e'})
- .execute();
- expect(updated.available_tags!.find((tag) => tag.id === d.id)).toMatchObject({name: 'e', moderated: false});
- const deleted = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .delete(`/channels/${s.forumId}/tags/${d.id}`)
- .execute();
- expect(deleted.available_tags!.some((tag) => tag.id === d.id)).toBe(false);
- await threadsRequest(harness, s.owner.token)
- .delete(`/channels/${s.forumId}/tags/${d.id}`)
- .expect(404, APIErrorCodes.UNKNOWN_FORUM_TAG)
- .execute();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.forumId}/tags`)
- .body({name: 'x'})
- .expect(403)
- .execute();
- });
-
- it('keeps tag edits working after a tag emoji is deleted', async () => {
- const s = await setup();
- const emoji = await createEmoji(harness, s.owner.token, s.guildId, {name: 'bug', image: getPngDataUrl()});
- const first = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{name: 'bug', emoji_id: emoji.id}, {name: 'other'}]})
- .execute();
- const [bug, other] = first.available_tags!;
- await createBuilder(harness, s.owner.token)
- .delete(`/guilds/${s.guildId}/emojis/${emoji.id}`)
- .expect(204)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .post(`/channels/${s.forumId}/tags`)
- .body({name: 'new'})
- .expect(200)
- .execute();
- await threadsRequest(harness, s.owner.token)
- .delete(`/channels/${s.forumId}/tags/${other!.id}`)
- .expect(200)
- .execute();
- const kept = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({available_tags: [{id: bug!.id, name: 'bug2', emoji_id: emoji.id}]})
- .execute();
- expect(kept.available_tags).toEqual([expect.objectContaining({id: bug!.id, name: 'bug2', emoji_id: emoji.id})]);
- await threadsRequest(harness, s.owner.token)
- .post(`/channels/${s.forumId}/tags`)
- .body({name: 'again', emoji_id: emoji.id})
- .expect(404, APIErrorCodes.UNKNOWN_EMOJI)
- .execute();
- });
-
it('keeps every tag when tag creates race', async () => {
const s = await setup();
const names = ['a', 'b', 'c', 'd', 'e'];
@@ -314,145 +114,26 @@ describe('forum and media channels', () => {
.execute();
expect(forum.available_tags!.map((tag) => tag.name).sort()).toEqual(names);
});
-
- it('stores thread defaults on text channels and copies only the rate limit onto new threads', async () => {
- const s = await setup();
- const text = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .post(`/guilds/${s.guildId}/channels`)
- .body({name: 'text', type: ChannelTypes.GUILD_TEXT, default_auto_archive_duration: 60})
- .execute();
- expect(text.default_auto_archive_duration).toBe(60);
- const patched = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${text.id}`)
- .body({default_thread_rate_limit_per_user: 30})
- .execute();
- expect(patched).toMatchObject({default_auto_archive_duration: 60, default_thread_rate_limit_per_user: 30});
- const thread = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
- .post(`/channels/${text.id}/threads`)
- .body({name: 't', type: ChannelTypes.PUBLIC_THREAD})
- .expect(201)
- .execute();
- expect(thread.rate_limit_per_user).toBe(30);
- expect(thread.thread_metadata?.auto_archive_duration).toBe(4320);
- });
});
describe('posts', () => {
- it('creates a post whose first message shares the thread id', async () => {
- const s = await setup();
- const created = await post(s.member.token, s.forumId);
- expect(created.type).toBe(ChannelTypes.PUBLIC_THREAD);
- expect(created.parent_id).toBe(s.forumId);
- expect(created.message?.id).toBe(created.id);
- expect(created.message?.channel_id).toBe(created.id);
- expect(created.applied_tags).toEqual([]);
- expect(created.message_count).toBe(0);
- const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .get(`/channels/${s.forumId}`)
- .execute();
- expect(forum.last_message_id).toBe(created.id);
- const messages = await threadsRequest<Array<{id: string}>>(harness, s.member.token)
- .get(`/channels/${created.id}/messages`)
- .execute();
- expect(messages.map((message) => message.id)).toEqual([created.id]);
- const media = await createForum(s.owner.token, s.guildId, {}, ChannelTypes.GUILD_MEDIA);
- const mediaPost = await post(s.member.token, media.id);
- expect(mediaPost).toMatchObject({type: ChannelTypes.PUBLIC_THREAD, parent_id: media.id, applied_tags: []});
- expect(mediaPost.message?.id).toBe(mediaPost.id);
- });
-
- it('applies tag rules on create', async () => {
- const s = await setup();
- const forum = await tags(s.owner.token, s.forumId, [{name: 'open'}, {name: 'staff', moderated: true}]);
- const [open, staff] = forum.available_tags!;
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.forumId}`)
- .body({flags: ChannelFlags.REQUIRE_TAG})
- .execute();
- await post(s.member.token, s.forumId, {}, 400);
- await post(s.member.token, s.forumId, {applied_tags: ['1']}, 404);
- await post(s.member.token, s.forumId, {applied_tags: [staff!.id]}, 403);
- const tagged = await post(s.member.token, s.forumId, {applied_tags: [open!.id]});
- expect(tagged.applied_tags).toEqual([open!.id]);
- const moderated = await post(s.owner.token, s.forumId, {applied_tags: [staff!.id]});
- expect(moderated.applied_tags).toEqual([staff!.id]);
- await threadsRequest(harness, s.member.token)
- .patch(`/channels/${tagged.id}`)
- .body({applied_tags: [open!.id, staff!.id]})
- .expect(403)
- .execute();
- const retagged = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${tagged.id}`)
- .body({applied_tags: [staff!.id]})
- .execute();
- expect(retagged.applied_tags).toEqual([staff!.id]);
- });
-
- it('drops a deleted tag when the post tags are sent back unchanged', async () => {
- const s = await setup();
- const forum = await tags(s.owner.token, s.forumId, [{name: 'keep'}, {name: 'gone'}]);
- const [keep, gone] = forum.available_tags!;
- const created = await post(s.member.token, s.forumId, {applied_tags: [keep!.id, gone!.id]});
- await threadsRequest(harness, s.owner.token).delete(`/channels/${s.forumId}/tags/${gone!.id}`).execute();
- const read = await threadsRequest<ThreadChannelResponse>(harness, s.member.token)
- .get(`/channels/${created.id}`)
- .execute();
- expect(read.applied_tags).toEqual([keep!.id]);
- const edited = await threadsRequest<ThreadChannelResponse>(harness, s.member.token)
- .patch(`/channels/${created.id}`)
- .body({applied_tags: [keep!.id, gone!.id]})
- .execute();
- expect(edited.applied_tags).toEqual([keep!.id]);
- await threadsRequest(harness, s.member.token)
- .patch(`/channels/${created.id}`)
- .body({applied_tags: [gone!.id]})
- .expect(404, APIErrorCodes.UNKNOWN_FORUM_TAG)
- .execute();
- });
-
it('refuses a limited account before creating the post', async () => {
const s = await setup();
await createBuilder(harness, '')
.post(`/test/users/${s.member.userId}/security-flags`)
.body({set_flags: ['ACCOUNT_LIMITED']})
.execute();
- const dispatched: Array<string> = [];
- const spy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild').mockImplementation(async (params) => {
- dispatched.push(params.event);
- });
await threadsRequest(harness, s.member.token)
.post(`/channels/${s.forumId}/threads`)
.body({name: 'limited', message: {content: 'hello'}})
.expect(403, APIErrorCodes.ACCOUNT_LIMITED)
.execute();
- spy.mockRestore();
- expect(dispatched.filter((event) => event.startsWith('THREAD_'))).toEqual([]);
const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token)
.get(`/channels/${s.forumId}`)
.execute();
expect(forum.last_message_id ?? null).toBeNull();
});
- it('rejects an invalid starter before creating the post', async () => {
- const s = await setup({rate_limit_per_user: 60});
- const dispatched: Array<string> = [];
- const spy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild').mockImplementation(async (params) => {
- dispatched.push(params.event);
- });
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.forumId}/threads`)
- .body({name: 'empty', message: {}})
- .expect(400, APIErrorCodes.CANNOT_SEND_EMPTY_MESSAGE)
- .execute();
- spy.mockRestore();
- expect(dispatched).not.toContain('THREAD_CREATE');
- const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .get(`/channels/${s.forumId}`)
- .execute();
- expect(forum.last_message_id ?? null).toBeNull();
- await post(s.member.token, s.forumId);
- });
-
it('rolls back a post whose starter fails after the thread exists', async () => {
const s = await setup({rate_limit_per_user: 60});
const first = await post(s.owner.token, s.forumId);
@@ -464,15 +145,6 @@ describe('forum and media channels', () => {
await post(s.member.token, s.forumId);
});
- it('requires a first message on a JSON post', async () => {
- const s = await setup();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.forumId}/threads`)
- .body({name: 'post'})
- .expect(400, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- });
-
it('requires send messages on the forum and refuses private posts', async () => {
const s = await setup();
await post(s.member.token, s.forumId, {type: ChannelTypes.PRIVATE_THREAD}, 400);
@@ -485,133 +157,5 @@ describe('forum and media channels', () => {
.execute();
await post(s.member.token, s.forumId, {}, 403);
});
-
- it('accepts a multipart post with a file', async () => {
- const s = await setup();
- const {body, contentType} = createMultipartFormData(
- {name: 'files', message: {content: 'with file', attachments: [{id: 0, filename: 'a.png'}]}},
- [{index: 0, filename: 'a.png', data: PNG_1X1}],
- );
- const response = await harness.app.request(`/channels/${s.forumId}/threads`, {
- method: 'POST',
- headers: {
- Authorization: s.member.token,
- [THREADS_FEATURE_HEADER]: THREADS_FEATURE,
- 'Content-Type': contentType,
- 'x-forwarded-for': '127.0.0.1',
- },
- body,
- });
- expect(response.status).toBe(201);
- const created = (await response.json()) as StartForumThreadResponse;
- expect(created.message?.id).toBe(created.id);
- expect(created.message?.attachments).toHaveLength(1);
- });
-
- it('allows one pinned post and clears the pin on archive', async () => {
- const s = await setup();
- const first = await post(s.owner.token, s.forumId);
- const second = await post(s.owner.token, s.forumId);
- const pinned = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${first.id}`)
- .body({flags: ChannelFlags.PINNED})
- .execute();
- expect(pinned.flags).toBe(ChannelFlags.PINNED);
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${second.id}`)
- .body({flags: ChannelFlags.PINNED})
- .expect(400, APIErrorCodes.MAX_PINNED_THREADS_IN_FORUM)
- .execute();
- const archived = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
- .patch(`/channels/${first.id}`)
- .body({archived: true})
- .execute();
- expect(archived.flags).toBe(0);
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${second.id}`)
- .body({flags: ChannelFlags.PINNED})
- .execute();
- await threadsRequest(harness, s.member.token)
- .patch(`/channels/${second.id}`)
- .body({flags: 0})
- .expect(403)
- .execute();
- });
-
- it('returns post data', async () => {
- const s = await setup();
- const created = await post(s.member.token, s.forumId);
- const data = await threadsRequest<ThreadPostDataResponse>(harness, s.owner.token)
- .post(`/channels/${s.forumId}/post-data`)
- .body({thread_ids: [created.id, '1']})
- .execute();
- expect(Object.keys(data.threads).sort()).toEqual([created.id, '1'].sort());
- expect(data.threads['1']).toEqual({owner: null, first_message: null});
- expect(data.threads[created.id]?.owner?.user.id).toBe(s.member.userId);
- expect(data.threads[created.id]?.first_message?.id).toBe(created.id);
- });
-
- it('applies the forum slowmode to post creation', async () => {
- const s = await setup({rate_limit_per_user: 60});
- await post(s.member.token, s.forumId);
- const state = await threadsRequest<{retry_after_ms: number}>(harness, s.member.token)
- .get(`/channels/${s.forumId}/slowmode`)
- .execute();
- expect(state.retry_after_ms).toBeGreaterThan(0);
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.forumId}/threads`)
- .body({name: 'again', message: {content: 'x'}})
- .expect(400, APIErrorCodes.SLOWMODE_RATE_LIMITED)
- .execute();
- });
- });
-
- describe('gateway payloads', () => {
- it('carries forum settings on CHANNEL_CREATE and CHANNEL_UPDATE', async () => {
- const s = await setup();
- const dispatches: Array<{event: string; data: unknown}> = [];
- const spy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild').mockImplementation(async (params) => {
- dispatches.push({event: params.event, data: params.data});
- });
- await createForum(s.owner.token, s.guildId, {available_tags: [{name: 'x'}]});
- await threadsRequest(harness, s.owner.token).post(`/channels/${s.forumId}/tags`).body({name: 'y'}).execute();
- spy.mockRestore();
- const created = dispatches.find((entry) => entry.event === 'CHANNEL_CREATE')?.data as ChannelResponse;
- const updated = dispatches.find((entry) => entry.event === 'CHANNEL_UPDATE')?.data as ChannelResponse;
- expect(created.available_tags?.map((tag) => tag.name)).toEqual(['x']);
- expect(updated.available_tags?.map((tag) => tag.name)).toEqual(['y']);
- expect(updated.default_forum_layout).toBe(0);
- });
- });
-
- describe('existing routes on forums', () => {
- it('reports thread search as unavailable without a search provider', async () => {
- const s = await setup();
- await threadsRequest(harness, s.member.token)
- .get(`/channels/${s.forumId}/threads/search`)
- .expect(403, APIErrorCodes.FEATURE_TEMPORARILY_DISABLED)
- .execute();
- });
-
- it('answers with the right errors', async () => {
- const s = await setup();
- await threadsRequest(harness, s.member.token)
- .get(`/channels/${s.forumId}/messages`)
- .expect(400, APIErrorCodes.INVALID_CHANNEL_TYPE)
- .execute();
- await threadsRequest(harness, s.member.token)
- .get(`/channels/${s.forumId}/messages/pins`)
- .expect(400, APIErrorCodes.INVALID_CHANNEL_TYPE)
- .execute();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.forumId}/typing`)
- .expect(400, APIErrorCodes.INVALID_CHANNEL_TYPE)
- .execute();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.forumId}/messages`)
- .body({content: 'x'})
- .expect(400, APIErrorCodes.CANNOT_SEND_MESSAGES_IN_NON_TEXT_CHANNEL)
- .execute();
- });
});
});
diff --git a/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts b/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts
index 6b6f6a5d5..a315a77d8 100644
--- a/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts
+++ b/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts
@@ -1,20 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {ChannelDataRepository} from '@app/api/channel/repositories/ChannelDataRepository';
-import {
- createDmChannel,
- createFriendship,
- createPermissionOverwrite,
- setupTestGuildWithMembers,
-} from '@app/api/channel/tests/ChannelTestUtils';
+import {createPermissionOverwrite, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
-import {getGatewayService} from '@app/api/middleware/ServiceRegistry';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS, TEST_TIMEOUTS, wait} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
@@ -99,100 +90,4 @@ describe('Message send permissions', () => {
.expect(HTTP_STATUS.NOT_FOUND, 'UNKNOWN_MESSAGE')
.execute();
});
-
- it('authenticates the channel once per send and once per edit', async () => {
- const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 1);
- const member = members[0]!;
- await createPermissionOverwrite(harness, owner.token, systemChannel.id, member.userId, {
- type: 1,
- allow: (Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES | Permissions.READ_MESSAGE_HISTORY).toString(),
- deny: '0',
- });
- await ensureSessionStarted(harness, member.token);
- const gatewayService = getGatewayService();
- const getGuildAuthContext = vi.spyOn(gatewayService, 'getGuildAuthContext');
- const getGuildMember = vi.spyOn(gatewayService, 'getGuildMember');
- const getUserPermissions = vi.spyOn(gatewayService, 'getUserPermissions');
-
- try {
- const sentMessage = await createBuilder<MessageResponse>(harness, member.token)
- .post(`/channels/${systemChannel.id}/messages`)
- .body({content: 'authenticate me once'})
- .execute();
- const sendCounts = {
- authContext: getGuildAuthContext.mock.calls.length,
- guildMember: getGuildMember.mock.calls.length,
- userPermissions: getUserPermissions.mock.calls.length,
- };
- getGuildAuthContext.mockClear();
- getGuildMember.mockClear();
- getUserPermissions.mockClear();
- await createBuilder<MessageResponse>(harness, member.token)
- .patch(`/channels/${systemChannel.id}/messages/${sentMessage.id}`)
- .body({content: 'authenticate me once again'})
- .execute();
- const editCounts = {
- authContext: getGuildAuthContext.mock.calls.length,
- guildMember: getGuildMember.mock.calls.length,
- userPermissions: getUserPermissions.mock.calls.length,
- };
-
- expect(sendCounts).toEqual({authContext: 1, guildMember: 1, userPermissions: 1});
- expect(editCounts).toEqual({authContext: 1, guildMember: 1, userPermissions: 1});
- } finally {
- getGuildAuthContext.mockRestore();
- getGuildMember.mockRestore();
- getUserPermissions.mockRestore();
- }
- });
-
- it('resolves the DM channel once for routing and once for authentication when sending', async () => {
- const sender = await createTestAccount(harness);
- const recipient = await createTestAccount(harness);
- await ensureSessionStarted(harness, sender.token);
- await createFriendship(harness, sender, recipient);
- const channel = await createDmChannel(harness, sender.token, recipient.userId);
- const findUnique = vi.spyOn(ChannelDataRepository.prototype, 'findUnique');
-
- try {
- await createBuilder<MessageResponse>(harness, sender.token)
- .post(`/channels/${channel.id}/messages`)
- .body({content: 'no redundant reads'})
- .expect(HTTP_STATUS.OK)
- .execute();
- const channelReads = findUnique.mock.calls.filter((call) => call[0].toString() === channel.id).length;
-
- expect(channelReads).toBe(2);
- } finally {
- findUnique.mockRestore();
- }
- });
-
- it('returns ACCESS_DENIED not UNKNOWN_GUILD when the Gateway has dropped a guild whose record survives', async () => {
- const {owner, systemChannel} = await setupTestGuildWithMembers(harness, 0);
- await ensureSessionStarted(harness, owner.token);
- const gatewayService = getGatewayService();
-
- for (const memberSettlesFirst of [true, false]) {
- const getGuildAuthContext = vi.spyOn(gatewayService, 'getGuildAuthContext').mockImplementation(async () => {
- if (memberSettlesFirst) await wait(TEST_TIMEOUTS.IMMEDIATE);
- throw new UnknownGuildError();
- });
- const getGuildMember = vi.spyOn(gatewayService, 'getGuildMember').mockImplementation(async () => {
- if (!memberSettlesFirst) await wait(TEST_TIMEOUTS.IMMEDIATE);
- throw new UnknownGuildError();
- });
-
- try {
- await createBuilder(harness, owner.token)
- .post(`/channels/${systemChannel.id}/messages`)
- .body({content: 'the gateway forgot this guild'})
- .expect(HTTP_STATUS.FORBIDDEN, 'ACCESS_DENIED')
- .execute();
- } finally {
- getGuildAuthContext.mockRestore();
- getGuildMember.mockRestore();
- }
- }
- });
});
diff --git a/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts b/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts
index a666414e5..ddf31fc08 100644
--- a/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts
@@ -1,17 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import assert from 'node:assert/strict';
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createChannelID, createUserID} from '@app/api/BrandedTypes';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
+import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import {ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {ThreadMemberResponse} from '@fluxer/schema/src/domains/channel/ThreadSchemas';
@@ -31,10 +31,6 @@ describe('thread member settings', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -52,12 +48,18 @@ describe('thread member settings', () => {
const thread = await threadsRequest<ThreadChannelResponse>(harness, owner.token)
.post(`/channels/${channel.id}/threads`)
.body({name: 'topic', type: ChannelTypes.PUBLIC_THREAD})
- .expect(201)
+ .expect(HttpStatus.CREATED)
.execute();
return {owner, member, thread};
}
- function settings(token: string, threadId: string, body: Record<string, unknown>, status = 200, code?: string) {
+ function settings(
+ token: string,
+ threadId: string,
+ body: Record<string, unknown>,
+ status: number = HttpStatus.OK,
+ code?: string,
+ ) {
return threadsRequest<ThreadMemberResponse>(harness, token)
.patch(`/channels/${threadId}/thread-members/@me/settings`)
.body(body)
@@ -65,112 +67,49 @@ describe('thread member settings', () => {
.execute();
}
- it('updates flags and mute, keeps HAS_INTERACTED and tells only the member', async () => {
- const s = await setup();
- const threadId = createChannelID(BigInt(s.thread.id));
- const ownerId = createUserID(BigInt(s.owner.userId));
- const joined = await repository.threads.getMember(threadId, ownerId);
- await repository.threads.updateMemberSettings(joined!, {flags: ThreadMemberFlags.HAS_INTERACTED});
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const updated = await settings(s.owner.token, s.thread.id, {
- flags: ThreadMemberFlags.ONLY_MENTIONS,
- muted: true,
- mute_config: {selected_time_window: 3600, end_time: '2030-01-01T00:00:00.000Z'},
- });
- expect(updated).toMatchObject({
- id: s.thread.id,
- user_id: s.owner.userId,
- flags: ThreadMemberFlags.HAS_INTERACTED | ThreadMemberFlags.ONLY_MENTIONS,
- muted: true,
- mute_config: {selected_time_window: 3600, end_time: '2030-01-01T00:00:00.000Z'},
- });
- const events = dispatch.mock.calls.map(([params]) => params);
- expect(events).toEqual([
- expect.objectContaining({
- event: 'THREAD_MEMBER_UPDATE',
- data: expect.objectContaining({user_id: s.owner.userId, guild_id: s.thread.guild_id}),
- }),
- ]);
- const stored = await repository.threads.getMember(threadId, ownerId);
- expect(stored?.muted).toBe(true);
- });
-
- it('answers 204 without an event when nothing changes', async () => {
- const s = await setup();
- await settings(s.owner.token, s.thread.id, {flags: ThreadMemberFlags.NO_MESSAGES});
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.thread.id}/thread-members/@me/settings`)
- .body({flags: ThreadMemberFlags.NO_MESSAGES})
- .expect(204)
- .execute();
- expect(dispatch).not.toHaveBeenCalled();
- });
-
it('rejects HAS_INTERACTED and more than one notification level', async () => {
const s = await setup();
await settings(
s.owner.token,
s.thread.id,
{flags: ThreadMemberFlags.HAS_INTERACTED},
- 400,
+ HttpStatus.BAD_REQUEST,
APIErrorCodes.INVALID_THREAD_NOTIFICATION_SETTINGS,
);
await settings(
s.owner.token,
s.thread.id,
{flags: ThreadMemberFlags.ALL_MESSAGES | ThreadMemberFlags.NO_MESSAGES},
- 400,
+ HttpStatus.BAD_REQUEST,
APIErrorCodes.INVALID_THREAD_NOTIFICATION_SETTINGS,
);
});
- it('retries a settings write that lost the member race', async () => {
- const s = await setup();
- const write = vi.spyOn(ThreadRepository.prototype, 'updateMemberSettings').mockResolvedValueOnce(null);
- const updated = await settings(s.owner.token, s.thread.id, {muted: true});
- expect(updated.muted).toBe(true);
- expect(write).toHaveBeenCalledTimes(2);
- const stored = await repository.threads.getMember(
- createChannelID(BigInt(s.thread.id)),
- createUserID(BigInt(s.owner.userId)),
- );
- expect(stored?.muted).toBe(true);
- });
-
it('rejects a settings write computed from stale member flags', async () => {
const s = await setup();
const threadId = createChannelID(BigInt(s.thread.id));
const ownerId = createUserID(BigInt(s.owner.userId));
const joined = await repository.threads.getMember(threadId, ownerId);
- const stale = await repository.threads.updateMemberSettings(joined!, {flags: 0});
+ assert(joined !== null);
+ const stale = await repository.threads.updateMemberSettings(joined, {flags: 0});
+ assert(stale !== null);
expect(
- await repository.threads.updateMemberSettings(stale!, {flags: ThreadMemberFlags.HAS_INTERACTED}),
+ await repository.threads.updateMemberSettings(stale, {flags: ThreadMemberFlags.HAS_INTERACTED}),
).not.toBeNull();
- expect(await repository.threads.updateMemberSettings(stale!, {flags: ThreadMemberFlags.ALL_MESSAGES})).toBeNull();
+ expect(await repository.threads.updateMemberSettings(stale, {flags: ThreadMemberFlags.ALL_MESSAGES})).toBeNull();
expect((await repository.threads.getMember(threadId, ownerId))?.flags).toBe(ThreadMemberFlags.HAS_INTERACTED);
const updated = await settings(s.owner.token, s.thread.id, {flags: ThreadMemberFlags.ALL_MESSAGES});
expect(updated.flags).toBe(ThreadMemberFlags.HAS_INTERACTED | ThreadMemberFlags.ALL_MESSAGES);
});
- it('leaves a mute config it was not asked to change to a concurrent writer', async () => {
- const s = await setup();
- const threadId = createChannelID(BigInt(s.thread.id));
- const ownerId = createUserID(BigInt(s.owner.userId));
- const stale = await repository.threads.getMember(threadId, ownerId);
- const muteConfig = {end_time: new Date('2030-01-01T00:00:00.000Z'), selected_time_window: 3600};
- expect(await repository.threads.updateMemberSettings(stale!, {muteConfig})).not.toBeNull();
- const write = vi.spyOn(ThreadRepository.prototype, 'updateMemberSettings');
- vi.spyOn(ThreadRepository.prototype, 'getMember').mockResolvedValueOnce(stale);
- await settings(s.owner.token, s.thread.id, {muted: true});
- expect(write.mock.calls.map(([, patch]) => patch)).toEqual([{flags: stale!.flags, muted: true}]);
- const stored = await repository.threads.getMember(threadId, ownerId);
- expect(stored?.muted).toBe(true);
- expect(stored?.muteConfig?.toMuteConfig()).toEqual(muteConfig);
- });
-
it('requires membership', async () => {
const s = await setup();
- await settings(s.member.token, s.thread.id, {muted: true}, 404, APIErrorCodes.UNKNOWN_THREAD_MEMBER);
+ await settings(
+ s.member.token,
+ s.thread.id,
+ {muted: true},
+ HttpStatus.NOT_FOUND,
+ APIErrorCodes.UNKNOWN_THREAD_MEMBER,
+ );
});
});
diff --git a/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts b/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts
index ed2ca833e..fd2f40fde 100644
--- a/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts
@@ -7,9 +7,7 @@ import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {getReadStateRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {ReadStateFlags} from '@fluxer/constants/src/ThreadConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
@@ -33,10 +31,6 @@ describe('thread pins ack', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -72,25 +66,11 @@ describe('thread pins ack', () => {
return row?.lastPinTimestamp ? row : null;
}
- function pinsAckDispatches(dispatch: {mock: {calls: Array<Array<unknown>>}}) {
- return dispatch.mock.calls.filter(([params]) => (params as {event: string}).event === 'CHANNEL_PINS_ACK');
- }
-
- it('stamps the ack for a thread member', async () => {
- const s = await setup();
- await threadsRequest(harness, s.owner.token).post(`/channels/${s.threadId}/pins/ack`).expect(204).execute();
- const row = await pinAckRow(s.owner, s.threadId);
- expect(row).not.toBeNull();
- expect(row?.flags).toBe(ReadStateFlags.IS_GUILD_CHANNEL | ReadStateFlags.IS_THREAD);
- });
-
it('refuses viewers who cannot see the private thread', async () => {
const s = await setup();
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
await threadsRequest(harness, s.member.token).post(`/channels/${s.threadId}/pins/ack`).expect(403).execute();
await threadsRequest(harness, s.outsider.token).post(`/channels/${s.threadId}/pins/ack`).expect(403).execute();
expect(await pinAckRow(s.member, s.threadId)).toBeNull();
expect(await pinAckRow(s.outsider, s.threadId)).toBeNull();
- expect(pinsAckDispatches(dispatch)).toEqual([]);
});
});
diff --git a/fluxer_api/src/api/channel/threads/tests/ChannelThreadsRouteGuard.test.ts b/fluxer_api/src/api/channel/threads/tests/ChannelThreadsRouteGuard.test.ts
index 2e5403334..5867a3ae5 100644
--- a/fluxer_api/src/api/channel/threads/tests/ChannelThreadsRouteGuard.test.ts
+++ b/fluxer_api/src/api/channel/threads/tests/ChannelThreadsRouteGuard.test.ts
@@ -139,10 +139,6 @@ describe('ChannelThreadsRouteGuard', () => {
const sentinel = () => `/channels/${channelId}/threads-sentinel`;
const unregistered = () => `/channels/${channelId}/threads-unregistered`;
- it('answers like an unregistered path without the client capability', async () => {
- await expectLikeUnregistered(sentinel(), unregistered(), {token: owner.token});
- });
-
it('answers like an unregistered path for an OAuth2 bearer token', async () => {
const bearer = await createBuilder<{token: string}>(harness, '')
.post('/test/oauth2/access-token')
@@ -151,26 +147,6 @@ describe('ChannelThreadsRouteGuard', () => {
await expectLikeUnregistered(sentinel(), unregistered(), {token: `Bearer ${bearer.token}`, headers: CAPABLE});
});
- it('answers like an unregistered path when unauthenticated', async () => {
- await expectLikeUnregistered(sentinel(), unregistered(), {headers: CAPABLE});
- });
-
- it('answers like an unregistered path for a malformed snowflake', async () => {
- await expectLikeUnregistered('/channels/not-a-snowflake/threads-sentinel', '/channels/not-a-snowflake/threads-x', {
- token: owner.token,
- headers: CAPABLE,
- });
- });
-
- it('answers like an unregistered path for a malformed body', async () => {
- await expectLikeUnregistered(sentinel(), unregistered(), {
- method: 'POST',
- token: owner.token,
-
- body: '{"name":',
- });
- });
-
it('answers like an unregistered path for a user token on a bot-only route', async () => {
await expectLikeUnregistered(`/channels/${channelId}/threads-sentinel-bot`, unregistered(), {
token: owner.token,
@@ -178,13 +154,6 @@ describe('ChannelThreadsRouteGuard', () => {
});
});
- it('lets a capable user through on a guild', async () => {
- const channel = await snapshot(sentinel(), {token: owner.token, headers: CAPABLE});
- expect(channel.status).toBe(200);
- const guild = await snapshot(`/guilds/${guildId}/threads-sentinel`, {token: owner.token, headers: CAPABLE});
- expect(guild.status).toBe(200);
- });
-
it('lets an authorized bot through without a client capability header', async () => {
const bot = await createTestBotAccount(harness);
diff --git a/fluxer_api/src/api/read_state/ReadStateRepository.test.ts b/fluxer_api/src/api/read_state/ReadStateRepository.test.ts
index 43f226a63..55b515aa2 100644
--- a/fluxer_api/src/api/read_state/ReadStateRepository.test.ts
+++ b/fluxer_api/src/api/read_state/ReadStateRepository.test.ts
@@ -91,37 +91,6 @@ describe('ReadStateRepository row storage', () => {
mention_count: 0,
});
});
- it('reads every acked channel of a bulk acknowledgement in one query', async () => {
- const recording = new InMemoryCassandraQueryExecutor();
- setCassandraQueryExecutorForTesting(recording);
- const userId = createUserID(1n);
- const seededChannelIds = [createChannelID(10n), createChannelID(20n), createChannelID(30n)];
- for (const channelId of seededChannelIds) {
- await seedReadState(userId, channelId, 100n, 5);
- }
- const missingChannelId = createChannelID(40n);
- recording.executed.length = 0;
- const repository = new ReadStateRepository();
- const readStates = await repository.bulkAckMessages(userId, [
- {channelId: seededChannelIds[0]!, messageId: createMessageID(90n)},
- {channelId: seededChannelIds[1]!, messageId: createMessageID(200n)},
- {channelId: seededChannelIds[2]!, messageId: createMessageID(300n)},
- {channelId: missingChannelId, messageId: createMessageID(400n)},
- ]);
- expect(recording.countStatements('select:read_states')).toBe(1);
- expect(readStates.map((state) => state.channelId)).toEqual([...seededChannelIds, missingChannelId]);
- expect(readStates.map((state) => state.lastMessageId)).toEqual([
- createMessageID(100n),
- createMessageID(200n),
- createMessageID(300n),
- createMessageID(400n),
- ]);
- expect(readStates.map((state) => state.mentionCount)).toEqual([5, 0, 0, 0]);
- expect(await loadReadState(userId, missingChannelId)).toMatchObject({
- message_id: createMessageID(400n),
- mention_count: 0,
- });
- });
it('keeps the last pin timestamp of acked rows and leaves missing rows without one', async () => {
const userId = createUserID(1n);
const pinnedChannelId = createChannelID(10n);
diff --git a/fluxer_api/src/api/read_state/ThreadReadStateMarkers.test.ts b/fluxer_api/src/api/read_state/ThreadReadStateMarkers.test.ts
index 582e898bc..4c890fc98 100644
--- a/fluxer_api/src/api/read_state/ThreadReadStateMarkers.test.ts
+++ b/fluxer_api/src/api/read_state/ThreadReadStateMarkers.test.ts
@@ -2,20 +2,15 @@
import {createChannelID, createGuildID, createMessageID, createUserID} from '@app/api/BrandedTypes';
import {fetchOne, setCassandraQueryExecutorForTesting, upsertOne} from '@app/api/database/CassandraQueryExecution';
-import type {CassandraParams, PreparedQuery} from '@app/api/database/CassandraTypes';
import type {ReadStateRow} from '@app/api/database/types/ChannelTypes';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ReadState} from '@app/api/models/ReadState';
-import {
- clearReadStateChannelMetaCacheForTesting,
- resolveReadStateMarker,
-} from '@app/api/read_state/ReadStateChannelMeta';
+import {clearReadStateChannelMetaCacheForTesting} from '@app/api/read_state/ReadStateChannelMeta';
import {type ReadStateMarker, ReadStateRepository} from '@app/api/read_state/ReadStateRepository';
import {mapReadStateResponse} from '@app/api/read_state/ReadStateResponseMapper';
import {visibleReadStates} from '@app/api/read_state/ReadStateVisibility';
import {ReadStates} from '@app/api/Tables';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import {ReadStateFlags} from '@fluxer/constants/src/ThreadConstants';
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
@@ -31,32 +26,6 @@ const FETCH_READ_STATE = ReadStates.selectCql({
where: [ReadStates.where.eq('user_id'), ReadStates.where.eq('channel_id')],
limit: 1,
});
-const LEGACY_UPSERT_CQL = `UPDATE read_states
-SET message_id = :message_id, mention_count = :mention_count, last_pin_timestamp = :last_pin_timestamp
-WHERE user_id = :user_id AND channel_id = :channel_id;
-`;
-
-class RecordingExecutor extends InMemoryCassandraQueryExecutor {
- readonly writes: Array<string> = [];
-
- override async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(
- query: PreparedQuery<P>,
- ): Promise<Array<T>> {
- if (!query.cql.trimStart().toUpperCase().startsWith('SELECT')) this.writes.push(query.cql);
- return super.executeQuery<T>(query);
- }
-}
-
-class CountingExecutor extends InMemoryCassandraQueryExecutor {
- reads = 0;
-
- override async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(
- query: PreparedQuery<P>,
- ): Promise<Array<T>> {
- if (query.cql.trimStart().toUpperCase().startsWith('SELECT')) this.reads++;
- return super.executeQuery<T>(query);
- }
-}
async function loadRow(channelId = THREAD): Promise<ReadStateRow | null> {
return fetchOne<ReadStateRow>(FETCH_READ_STATE, {user_id: USER, channel_id: channelId});
@@ -75,12 +44,10 @@ async function seed(channelId: typeof THREAD, messageId: bigint, mentionCount: n
}
describe('thread read state markers', () => {
- let executor: RecordingExecutor;
const repository = new ReadStateRepository();
beforeEach(() => {
- executor = new RecordingExecutor();
- setCassandraQueryExecutorForTesting(executor);
+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
clearChannelThreadsTaintCacheForTesting();
clearReadStateChannelMetaCacheForTesting();
});
@@ -90,23 +57,6 @@ describe('thread read state markers', () => {
});
describe('control rows', () => {
- it('creates bulk mention rows with the same full-row CQL as before', async () => {
- executor.writes.length = 0;
- await repository.bulkIncrementMentionCounts([{userId: USER, channelId: TEXT, messageId: createMessageID(20n)}]);
- expect(executor.writes).toEqual([LEGACY_UPSERT_CQL]);
- });
-
- it('never writes marker columns on acks, pins or mention increments', async () => {
- await repository.upsertReadState(USER, TEXT, createMessageID(50n), 0);
- await repository.bulkAckMessages(USER, [{channelId: TEXT, messageId: createMessageID(60n)}]);
- await repository.upsertPinAck(USER, TEXT, new Date('2026-09-01T00:00:00.000Z'));
- await repository.bulkIncrementMentionCounts([{userId: USER, channelId: TEXT, messageId: createMessageID(70n)}]);
- expect(executor.writes.some((cql) => cql.includes('flags') || cql.includes('guild_id'))).toBe(false);
- const readState = new ReadState((await loadRow(TEXT))!);
- expect(readState.isMarked).toBe(false);
- expect(mapReadStateResponse(readState)).not.toHaveProperty('flags');
- });
-
it('keeps the channel id as the mention baseline for unmarked rows', async () => {
await repository.bulkIncrementMentionCounts([
{userId: USER, channelId: THREAD, messageId: createMessageID(1001n)},
@@ -191,27 +141,4 @@ describe('thread read state markers', () => {
expect(visibleReadStates([control, marked], {userId: USER, capable: true})).toEqual([control, marked]);
});
});
-
- describe('marker resolution', () => {
- it('does no IO for incapable sessions', async () => {
- const counting = new CountingExecutor();
- setCassandraQueryExecutorForTesting(counting);
-
- expect(await resolveReadStateMarker({userId: USER, channelId: THREAD, capable: false})).toBeNull();
- expect(counting.reads).toBe(0);
- });
-
- it('stamps threads and forums for viewers and nothing else', async () => {
- const resolve = (type: number, guildId: typeof GUILD | null = GUILD) =>
- resolveReadStateMarker({userId: USER, channelId: THREAD, capable: true, channel: {type, guildId}});
- expect(await resolve(ChannelTypes.PUBLIC_THREAD)).toEqual(THREAD_MARKER);
- expect(await resolve(ChannelTypes.PRIVATE_THREAD)).toEqual(THREAD_MARKER);
- expect(await resolve(ChannelTypes.GUILD_FORUM)).toEqual({flags: ReadStateFlags.IS_GUILD_CHANNEL, guildId: GUILD});
- expect(await resolve(ChannelTypes.GUILD_TEXT)).toBeNull();
- expect(await resolve(ChannelTypes.PUBLIC_THREAD, createGuildID(9n))).toEqual({
- ...THREAD_MARKER,
- guildId: createGuildID(9n),
- });
- });
- });
});
diff --git a/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.test.ts b/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.test.ts
index 3e4db0527..39be32488 100644
--- a/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.test.ts
+++ b/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.test.ts
@@ -3,8 +3,6 @@
import type {MeilisearchClient, MeilisearchTask} from '@app/api/search/meilisearch/MeilisearchClient';
import {MeilisearchTaskError} from '@app/api/search/meilisearch/MeilisearchClient';
import {MeilisearchMessageAdapter} from '@app/api/search/meilisearch/MeilisearchDomainAdapters';
-import {MEILISEARCH_MAX_TRACKED_BULK_TASKS} from '@app/api/search/meilisearch/MeilisearchIndexAdapter';
-import type {SearchableMessage} from '@fluxer/schema/src/contracts/search/SearchDocumentTypes';
import {describe, expect, it} from 'vitest';
interface RecordedMeilisearchRequest {
@@ -128,67 +126,4 @@ describe('MeilisearchMessageAdapter', () => {
},
});
});
-
- it('waits for queued bulk index tasks when refreshed', async () => {
- const client = new FakeMeilisearchClient();
- client.indexExists = true;
- const adapter = new MeilisearchMessageAdapter({client});
- await adapter.initialize();
- client.clear();
-
- await adapter.bulkIndexDocuments([{id: 'message-1'} as SearchableMessage]);
-
- expect(client.waitedTaskUids).toEqual([]);
- await adapter.refreshIndex();
- expect(client.waitedTaskUids).toEqual([5]);
- });
-
- it('does not retain task state for per-document writes', async () => {
- const client = new FakeMeilisearchClient();
- client.indexExists = true;
- const adapter = new MeilisearchMessageAdapter({client});
- await adapter.initialize();
- client.clear();
-
- for (let index = 0; index < 500; index++) {
- await adapter.indexDocument({id: `message-${index}`} as SearchableMessage);
- await adapter.updateDocument({id: `message-${index}`} as SearchableMessage);
- await adapter.deleteDocument(`message-${index}`);
- }
-
- expect(client.requests).toHaveLength(1500);
- await adapter.refreshIndex();
- expect(client.waitedTaskUids).toEqual([]);
- });
-
- it('bounds the tracked bulk task set', async () => {
- const client = new FakeMeilisearchClient();
- client.indexExists = true;
- const adapter = new MeilisearchMessageAdapter({client});
- await adapter.initialize();
- client.clear();
-
- const batches = MEILISEARCH_MAX_TRACKED_BULK_TASKS + 100;
- for (let index = 0; index < batches; index++) {
- await adapter.bulkIndexDocuments([{id: `message-${index}`} as SearchableMessage]);
- }
-
- await adapter.refreshIndex();
- expect(client.waitedTaskUids).toHaveLength(MEILISEARCH_MAX_TRACKED_BULK_TASKS);
- expect(client.waitedTaskUids[0]).toBe(105);
- });
-
- it('drops tracked bulk tasks on shutdown', async () => {
- const client = new FakeMeilisearchClient();
- client.indexExists = true;
- const adapter = new MeilisearchMessageAdapter({client});
- await adapter.initialize();
- client.clear();
-
- await adapter.bulkIndexDocuments([{id: 'message-1'} as SearchableMessage]);
- await adapter.shutdown();
- await adapter.refreshIndex();
-
- expect(client.waitedTaskUids).toEqual([]);
- });
});
diff --git a/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts b/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts
index a8f62708f..7f68f64ef 100644
--- a/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts
+++ b/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
@@ -10,13 +10,10 @@ import {getThreadSearchService} from '@app/api/SearchFactory';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
import refreshSearchIndex from '@app/api/worker/tasks/RefreshSearchIndex';
import {backfillThreadSearch, syncThreadSearchDocument} from '@app/api/worker/tasks/ThreadSearchTasks';
import {clearWorkerDependencies, setWorkerDependencies} from '@app/api/worker/WorkerContext';
import {initializeWorkerDependencies} from '@app/api/worker/WorkerDependencies';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
import type {
@@ -109,55 +106,6 @@ describe('thread search', () => {
.execute();
}
- it('answers 202 until the guild is backfilled, then searches', async () => {
- const s = await setup();
- const created = await post(s, 'first post');
- await settle();
- const response = await harness.requestJson({
- path: `/channels/${s.forumId}/threads/search`,
- headers: {Authorization: s.member.token, 'X-Fluxer-Features': 'channel_threads'},
- });
- expect(response.status).toBe(202);
- expect(await response.json()).toMatchObject({
- code: APIErrorCodes.SEARCH_INDEX_NOT_READY,
- documents_indexed: 0,
- retry_after: 2,
- });
- await settle();
- const result = await search(s, s.forumId);
- expect(result.threads.map((thread) => thread.id)).toEqual([created.id]);
- expect(result.total_results).toBe(1);
- expect(result.has_more).toBe(false);
- expect(result.first_messages?.map((message) => message.id)).toEqual([created.id]);
- expect(result.members.map((member) => member.id)).toEqual([created.id]);
- });
-
- async function refreshThreadsIndex(
- guildId: string,
- status: number,
- code?: string,
- ): Promise<{errors?: Array<{path: string}>}> {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'guild:lookup']);
- return createBuilder<{errors?: Array<{path: string}>}>(harness, admin.token)
- .post('/admin/search/indexes/threads/refreshes')
- .body({guild_id: guildId})
- .expect(status, code)
- .execute();
- }
-
- it('rebuilds a dropped index through the admin threads reindex', async () => {
- const s = await setup();
- const created = await post(s, 'kept post');
- await search(s, s.forumId).catch(() => null);
- await settle();
- await getThreadSearchService()!.deleteAllDocuments();
- expect((await search(s, s.forumId)).threads).toEqual([]);
- await refreshThreadsIndex(s.guildId, HTTP_STATUS.OK);
- await settle();
- expect((await search(s, s.forumId)).threads.map((thread) => thread.id)).toEqual([created.id]);
- });
-
it('keeps documents in sync with renames and deletes', async () => {
const s = await setup();
const created = await post(s, 'old name');
diff --git a/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts b/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts
index c1bcf0598..88b4b1563 100644
--- a/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts
+++ b/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts
@@ -7,7 +7,6 @@ import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtil
import {THREADS_FEATURE, THREADS_FEATURE_HEADER, threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting, insertGuildThreadMarker} from '@app/api/experiment/ChannelThreadsGate';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import {ChannelOverrideFlags} from '@fluxer/constants/src/ThreadConstants';
@@ -32,10 +31,6 @@ describe('thread user settings', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -90,7 +85,6 @@ describe('thread user settings', () => {
{channel_overrides: {[s.channelId]: override({flags: ChannelOverrideFlags.NEW_FORUM_THREADS_OFF})}},
true,
);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
const control = await patchSettings(
s.account,
s.guildId,
@@ -99,9 +93,6 @@ describe('thread user settings', () => {
);
expect(control.channel_overrides?.[s.channelId]).toEqual(expect.not.objectContaining({flags: expect.anything()}));
expect(control.channel_overrides?.[s.channelId]?.muted).toBe(true);
- const updates = dispatch.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'USER_GUILD_SETTINGS_UPDATE');
const viewer = await createBuilder<UserGuildSettingsResponse>(harness, s.account.token)
.header(THREADS_FEATURE_HEADER, THREADS_FEATURE)
.patch(`/users/@me/guilds/${s.guildId}/settings`)
@@ -109,11 +100,6 @@ describe('thread user settings', () => {
.expect(200)
.execute();
expect(viewer.channel_overrides?.[s.channelId]?.flags).toBe(ChannelOverrideFlags.NEW_FORUM_THREADS_OFF);
- expect(updates).toHaveLength(2);
- expect(updates[0]?.data).not.toHaveProperty('__thread_scoped');
- expect(updates[0]?.data).toMatchObject({__thread_unscoped: s.guildId});
- expect(JSON.stringify(updates[0]?.data)).not.toContain('"flags"');
- expect(updates[1]?.data).toMatchObject({__thread_scoped: s.guildId});
});
it('ignores malformed flags from non-viewers and rejects them from viewers', async () => {
@@ -131,16 +117,6 @@ describe('thread user settings', () => {
.expect(400)
.execute();
});
-
- it('sends a single settings update when no override carries thread data', async () => {
- const s = await setup();
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
- await patchSettings(s.account, s.guildId, {channel_overrides: {[s.channelId]: override()}}, true);
- const updates = dispatch.mock.calls.filter(([params]) => params.event === 'USER_GUILD_SETTINGS_UPDATE');
- expect(updates).toHaveLength(1);
- expect(updates[0]?.[0].data).not.toHaveProperty('__thread_scoped');
- expect(updates[0]?.[0].data).not.toHaveProperty('__thread_unscoped');
- });
});
describe('forum override omission', () => {
@@ -165,55 +141,4 @@ describe('thread user settings', () => {
expect(viewer.channel_overrides?.[s.channelId]?.collapsed).toBe(true);
});
});
-
- describe('device capability', () => {
- interface PushSubscriptionsRpc {
- data: Record<string, Array<{subscription_id: string; thread_channels?: boolean}>>;
- }
-
- async function subscriptions(account: TestAccount) {
- const response = await createBuilder<PushSubscriptionsRpc>(harness, '')
- .post('/test/rpc-session-init')
- .body({type: 'get_push_subscriptions', user_ids: [account.userId]})
- .expect(200)
- .execute();
- return response.data[account.userId] ?? [];
- }
-
- it('records the thread capability of a mobile device only when the features header carries it', async () => {
- const account = await createTestAccount(harness);
- const capable = await threadsRequest<{device_id: string}>(harness, account.token)
- .post('/users/@me/mobile-devices')
- .body({platform: 'android_fcm', token: 'capable-device-token'})
- .execute();
- const legacy = await threadsRequest<{device_id: string}>(harness, account.token, {capable: false})
- .post('/users/@me/mobile-devices')
- .body({platform: 'android_fcm', token: 'legacy-device-token'})
- .execute();
- const byId = new Map((await subscriptions(account)).map((sub) => [sub.subscription_id, sub]));
- expect(byId.get(capable.device_id)?.thread_channels).toBe(true);
- expect(byId.get(legacy.device_id)).toBeDefined();
- expect(byId.get(legacy.device_id)).not.toHaveProperty('thread_channels');
- });
-
- it('clears the thread capability on a header-less re-registration', async () => {
- const account = await createTestAccount(harness);
- const register = (capable: boolean) =>
- threadsRequest<{device_id: string}>(harness, account.token, {capable})
- .post('/users/@me/mobile-devices')
- .body({platform: 'android_fcm', token: 'downgraded-device-token'})
- .execute();
- const capability = async (deviceId: string) =>
- (await subscriptions(account)).find((sub) => sub.subscription_id === deviceId)?.thread_channels;
-
- const {device_id} = await register(true);
- await register(false);
- expect(await capability(device_id)).toBeUndefined();
-
- await register(true);
- expect(await capability(device_id)).toBe(true);
- await register(false);
- expect(await capability(device_id)).toBeUndefined();
- });
- });
});