import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Db } from '../src/server/db/db.ts' import { Store } from '../src/server/db/store.ts' import { loadLanguageDetector } from '../src/server/bot/engine/language.ts' import { ChannelRuntime, Exec, type IncomingMessage } from '../src/server/bot/runtime.ts' import type { Platform } from '../src/server/bot/platform.ts' const CHANNEL = 'did:plc:streamer' const BOT = 'did:plc:bot' function fakePlatform() { const log: string[] = [] let n = 0 const platform: Platform = { botDid: () => BOT, canSend: () => true, send: async (_c, text, reply) => { log.push(`send${reply ? '(reply)' : ''}: ${text}`) return { uri: `at://${BOT}/place.stream.chat.message/${++n}`, cid: 'c' } }, hide: async (_c, uri) => void log.push(`hide: ${uri}`), block: async (_c, did) => { log.push(`block: ${did}`) return `at://${CHANNEL}/app.bsky.graph.block/${++n}` }, unblock: async (_c, uri) => void log.push(`unblock: ${uri}`), findBlocks: async () => [], pin: async (_c, uri) => void log.push(`pin: ${uri}`), updateStream: async (_c, patch) => void log.push(`stream: ${JSON.stringify(patch)}`), } return { platform, log } } let counter = 0 function msg(text: string, user: Partial = {}): IncomingMessage { counter++ return { uri: `at://${user.did ?? 'did:plc:viewer'}/place.stream.chat.message/${counter}`, cid: `cid${counter}`, text, createdAt: new Date().toISOString(), replyRoot: null, replyParent: null, facetUris: [], user: { did: 'did:plc:viewer', handle: 'viewer.bsky.social', displayName: 'Viewer', badges: [], ...user }, color: null, isBot: false, } } function setup() { const store = new Store(new Db(':memory:')) store.upsertChannel({ did: CHANNEL, handle: 'streamer.bsky.social', displayName: 'Streamer', avatar: '' }) store.setSingleton(CHANNEL, 'settings', { messageGapMs: 250 }) const { platform, log } = fakePlatform() const rt = new ChannelRuntime(store.getChannel(CHANNEL)!, store, platform) const reload = () => rt.reload() return { store, rt, log, reload } } describe('channel runtime', () => { beforeEach(() => { // No network in tests: identity lookups fail fast and the pipeline treats them as unknown. vi.stubGlobal('fetch', async () => { throw new Error('offline') }) }) afterEach(() => vi.unstubAllGlobals()) it('seeds platform roles for new channels', () => { const { store } = setup() expect(store.listDocs(CHANNEL, 'role').map((r) => r.data.platform)).toEqual(['broadcaster', 'moderator', 'vip', 'follower', 'everyone']) }) it('answers custom commands, aliases, and counts uses', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'command', { name: '!Hello', response: 'Hi $(sender)! #$(count)', aliases: ['hey'], globalCooldown: 0, userCooldown: 0 }) reload() await rt.onMessage(msg('!hello')) await rt.onMessage(msg('!hey')) expect(log).toEqual(['send: Hi Viewer! #1', 'send: Hi Viewer! #2']) }) it.each([ { enabled: true, handle: 'dj.bsky.social', account: 'dj.bsky.social' }, { enabled: true, handle: '', account: 'streamer.bsky.social' }, { enabled: false, handle: 'dj.bsky.social', account: null }, ])('routes !song to the enabled music source ($enabled, $handle)', async ({ enabled, handle, account }) => { const { store, rt, log, reload } = setup() store.setSingleton(CHANNEL, 'integrations.tealfm', { enabled, handle }) reload() vi.spyOn(rt.modules.media, 'currentLabel').mockReturnValue('Queued track') const tealfm = vi.fn(async (_actor: string) => ({ track: 'Scrobbled track', artist: 'Artist' })) const services = rt.services.bind(rt) vi.spyOn(rt, 'services').mockImplementation(() => ({ ...services(), tealfm })) await rt.onMessage(msg('!song')) expect(tealfm.mock.calls).toEqual(account ? [[account]] : []) expect(log).toEqual([account ? 'send(reply): Now playing: Scrobbled track by Artist' : 'send(reply): Now playing: Queued track']) }) it('enforces cooldowns but lets moderators bypass them', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'command', { name: 'cd', response: 'ok', globalCooldown: 60, userCooldown: 0 }) reload() await rt.onMessage(msg('!cd')) await rt.onMessage(msg('!cd')) await rt.onMessage(msg('!cd', { did: 'did:plc:mod', badges: ['mod'] })) expect(log).toEqual(['send: ok', 'send: ok']) }) it('respects role conditions', async () => { const { store, rt, log, reload } = setup() const vip = store.listDocs(CHANNEL, 'role').find((r) => r.data.platform === 'vip')! store.createDoc(CHANNEL, 'command', { name: 'vip', response: 'vip only', globalCooldown: 0, userCooldown: 0, conditions: { roles: [vip.id] } }) reload() await rt.onMessage(msg('!vip')) await rt.onMessage(msg('!vip', { did: 'did:plc:v', badges: ['vip'] })) expect(log).toEqual(['send: vip only']) }) it('replies and mentions according to the response type', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'command', { name: 'r', response: 'reply!', responseType: 'reply', globalCooldown: 0, userCooldown: 0 }) store.createDoc(CHANNEL, 'command', { name: 'm', response: 'mention!', responseType: 'mention', globalCooldown: 0, userCooldown: 0 }) reload() await rt.onMessage(msg('!r')) await rt.onMessage(msg('!m')) expect(log).toEqual(['send(reply): reply!', 'send: @viewer.bsky.social mention!']) }) it('fires keywords when every phrase in a group matches', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'keyword', { name: 'schedule', response: 'Streams are Mon/Wed/Fri', globalCooldown: 0, userCooldown: 0, phraseGroups: [[{ text: 'when' }, { text: 'stream', wordBoundary: false }]], }) reload() await rt.onMessage(msg('when is the stream?')) await rt.onMessage(msg('when is dinner?')) expect(log).toEqual(['send: Streams are Mon/Wed/Fri']) }) it('times out blocked terms (after lookalikes) and escalates repeat offenders', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'blocked_term', { phrase: { text: 'free viewers' }, punishment: { action: 'timeout', baseTimeout: 60, maxTimeout: 600, reason: 'No spam', notify: true, repeatOffenders: { enabled: true, multiplier: 2 } }, }) reload() const m1 = msg('get fr33 v1ewers here') await rt.onMessage(m1) expect(log).toEqual([`hide: ${m1.uri}`, 'block: did:plc:viewer', 'send: @viewer.bsky.social, No spam [timeout]']) const p = store.db.get<{ expires_at: number }>('SELECT expires_at FROM punishments WHERE did = ?', 'did:plc:viewer')! expect(Math.round((p.expires_at - Date.now()) / 1000)).toBeGreaterThan(55) // A second offence while still timed out extends the timeout (to 120s) instead of blocking again. await rt.onMessage(msg('free viewers again')) const p2 = store.db.get<{ expires_at: number }>('SELECT expires_at FROM punishments WHERE did = ?', 'did:plc:viewer')! expect(Math.round((p2.expires_at - Date.now()) / 1000)).toBeGreaterThan(115) expect(log.filter((l) => l.startsWith('block')).length).toBe(1) }) it('never moderates the broadcaster or moderators, and honors !permit', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'blocked_term', { phrase: { text: 'badword' }, punishment: { action: 'delete', notify: false } }) reload() await rt.onMessage(msg('badword', { did: CHANNEL, badges: ['streamer'] })) await rt.onMessage(msg('badword', { did: 'did:plc:mod', badges: ['mod'] })) expect(log).toEqual([]) rt.permits.set('did:plc:viewer', Date.now() + 60_000) await rt.onMessage(msg('badword')) expect(log).toEqual([]) }) it('gives warnings before punishing when warnings are on', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'blocked_term', { phrase: { text: 'nope' }, punishment: { action: 'ban', notify: false, warnings: { enabled: true, count: 1, message: 'warning for $(sendername)' } }, }) reload() const first = msg('nope') await rt.onMessage(first) expect(log).toEqual([`hide: ${first.uri}`, 'send: warning for viewer.bsky.social']) log.length = 0 const second = msg('nope') await rt.onMessage(second) expect(log).toEqual([`hide: ${second.uri}`, 'block: did:plc:viewer']) }) it('runs spam filters: caps, links with an allowlist, and one-man spam', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'filter', { type: 'caps', name: 'Caps', punishment: { action: 'delete', notify: false } }) store.createDoc(CHANNEL, 'filter', { type: 'links', name: 'Links', config: { allowedDomains: ['stream.place'] }, punishment: { action: 'delete', notify: false } }) store.createDoc(CHANNEL, 'filter', { type: 'oneman', name: 'Spam', config: { messages: 3, seconds: 30 }, punishment: { action: 'delete', notify: false } }) reload() await rt.onMessage(msg('THIS IS A VERY LOUD MESSAGE')) await rt.onMessage(msg('watch me at https://stream.place/me')) await rt.onMessage(msg('buy at sketchy.example.com')) expect(log.filter((l) => l.startsWith('hide')).length).toBe(2) log.length = 0 const u = { did: 'did:plc:spammer', handle: 'spam.bsky.social' } await rt.onMessage(msg('subscribe to my channel', u)) await rt.onMessage(msg('subscribe to my channel!', u)) await rt.onMessage(msg('subscribe to my channel!!', u)) expect(log.filter((l) => l.startsWith('hide')).length).toBe(1) }) it('runs the language filter on languages, not writing systems', async () => { await loadLanguageDetector() const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'filter', { type: 'language', name: 'English only', config: { allowedLanguages: ['en'] }, punishment: { action: 'delete', notify: false } }) reload() await rt.onMessage(msg('yo whats up chat how is everyone doing')) expect(log.filter((l) => l.startsWith('hide'))).toEqual([]) const spanish = msg('hola que tal como estan todos') await rt.onMessage(spanish) expect(log.filter((l) => l.startsWith('hide'))).toEqual([`hide: ${spanish.uri}`]) }) it('lets moderators add, edit and delete commands from chat', async () => { const { store, rt, log } = setup() const mod = { did: 'did:plc:mod', handle: 'mod.bsky.social', badges: ['mod'] } await rt.onMessage(msg('!addcmd discord Join us at discord.gg/x -g 0 -u 0 --addalias dc', mod)) rt.reload() await rt.onMessage(msg('!dc')) await rt.onMessage(msg('!editcmd discord New link! -t mention', mod)) rt.reload() await rt.onMessage(msg('!discord')) await rt.onMessage(msg('!delcmd discord', mod)) rt.reload() await rt.onMessage(msg('!discord')) expect(log).toEqual(['send(reply): Added !discord.', 'send: Join us at discord.gg/x', 'send(reply): Updated !discord.', 'send: @viewer.bsky.social New link!', 'send(reply): Deleted !discord.']) expect(store.listDocs(CHANNEL, 'command')).toHaveLength(0) }) it('ignores chat-management commands from regular viewers', async () => { const { store, rt, log } = setup() await rt.onMessage(msg('!addcmd hack lol')) expect(log).toEqual([]) expect(store.listDocs(CHANNEL, 'command')).toHaveLength(0) }) it('performs slash actions from responses', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'keyword', { name: 'del', response: '/delete', globalCooldown: 0, userCooldown: 0, phraseGroups: [[{ text: 'delete me' }]] }) reload() const m = msg('please delete me') await rt.onMessage(m) expect(log).toEqual([`hide: ${m.uri}`]) }) it('manages quotes', async () => { const { store, rt, log, reload } = setup() store.setSingleton(CHANNEL, 'default_commands', { quote: { globalCooldown: 0, userCooldown: 0 } }) reload() const mod = { did: 'did:plc:mod', handle: 'mod.bsky.social', badges: ['mod'] } await rt.onMessage(msg('!quote add I am the best', mod)) await rt.onMessage(msg('!quote 1')) expect(log).toEqual(['send(reply): Added quote #1.', 'send(reply): #1: I am the best']) }) it('nukes recent matching messages', async () => { const { rt, log } = setup() const a = msg('buy cheap followers', { did: 'did:plc:a', handle: 'a.bsky.social' }) const b = msg('BUY CHEAP followers today', { did: 'did:plc:b', handle: 'b.bsky.social' }) await rt.onMessage(a) await rt.onMessage(b) await rt.onMessage(msg('hello')) await rt.onMessage(msg('!nuke cheap followers 60 300', { did: 'did:plc:mod', handle: 'mod.bsky.social', badges: ['mod'] })) expect(log.filter((l) => l.startsWith('hide')).sort()).toEqual([`hide: ${a.uri}`, `hide: ${b.uri}`].sort()) expect(log.filter((l) => l.startsWith('block')).length).toBe(2) }) it('rotates timer messages once enough chat lines have passed', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'timer', { name: 'socials', messages: ['one', 'two'], offlineInterval: 1, minLines: 2 }) reload() await rt.tickTimers() // first sight starts the clock const state = (rt as unknown as { timerState: Map }).timerState for (const s of state.values()) s.lastSent -= 61_000 await rt.tickTimers() expect(log).toEqual([]) // not enough lines yet await rt.onMessage(msg('a')) await rt.onMessage(msg('b')) await rt.tickTimers() for (const s of state.values()) s.lastSent -= 61_000 await rt.onMessage(msg('c')) await rt.onMessage(msg('d')) await rt.tickTimers() expect(log).toEqual(['send: one', 'send: two']) }) it('simulates without side effects for the config tester', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'blocked_term', { phrase: { text: 'spam' }, punishment: { action: 'ban' } }) store.createDoc(CHANNEL, 'command', { name: 'hi', response: 'hey $(sender) $(count)', globalCooldown: 0, userCooldown: 0 }) reload() const steps = await rt.simulate({ text: 'spam', handle: 'tester', roles: [] }) expect(steps.some((s) => s.kind === 'moderation')).toBe(true) expect(steps.some((s) => s.kind === 'action' && s.label.startsWith('Ban'))).toBe(true) const steps2 = await rt.simulate({ text: '!hi', handle: 'tester', roles: [] }) expect(steps2.find((s) => s.kind === 'send')?.detail).toBe('hey tester 1') const exempt = await rt.simulate({ text: 'spam', handle: 'tester', roles: ['moderator'] }) expect(exempt.some((s) => s.kind === 'moderation')).toBe(false) expect(log).toEqual([]) expect(store.counterGet(CHANNEL, `cmd:${store.listDocs(CHANNEL, 'command')[0].id}`)).toBe(0) }) it('announces emote combos when they break', async () => { const { store, rt, log, reload } = setup() store.setSingleton(CHANNEL, 'modules.combo', { enabled: true, minCombo: 3, onlineOnly: false }) reload() for (const did of ['did:plc:1', 'did:plc:2', 'did:plc:3']) await rt.onMessage(msg('🔥', { did })) await rt.onMessage(msg('nice')) expect(log).toEqual(['send: 3x 🔥 combo!']) }) it('detects pyramids', async () => { const { store, rt, log, reload } = setup() store.setSingleton(CHANNEL, 'modules.pyramid', { enabled: true, minWidth: 3, onlineOnly: false }) reload() for (const t of ['🐸', '🐸 🐸', '🐸 🐸 🐸', '🐸 🐸', '🐸']) await rt.onMessage(msg(t)) expect(log).toEqual(['send: @viewer.bsky.social built a 3-wide 🐸 pyramid!']) }) it('does nothing while muted, except moderation', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'command', { name: 'x', response: 'y', globalCooldown: 0, userCooldown: 0 }) store.updateChannel(CHANNEL, { bot_muted: 1 }) reload() await rt.onMessage(msg('!x')) expect(log).toEqual([]) expect(new Exec(false).dryRun).toBe(false) }) it('runs commands from the API as the broadcaster, without a chat message to reply to', async () => { const { store, rt, log, reload } = setup() store.createDoc(CHANNEL, 'command', { name: 'death', response: '/pin', globalCooldown: 0, userCooldown: 0 }) store.createDoc(CHANNEL, 'command', { name: 'oops', response: 'Oops #$(count)', responseType: 'reply', globalCooldown: 0, userCooldown: 0 }) reload() expect((await rt.runAsBroadcaster('!count deaths +1')).handled).toBe(true) expect((await rt.runAsBroadcaster('!count deaths +1')).handled).toBe(true) await rt.runAsBroadcaster('!oops') await rt.runAsBroadcaster('!death') expect((await rt.runAsBroadcaster('!nope')).handled).toBe(false) expect(store.counterGet(CHANNEL, 'count:deaths')).toBe(2) // A reply falls back to a plain message, /pin has nothing to pin, and nothing lands in the chat log. expect(log).toEqual(['send: deaths is now 1.', 'send: deaths is now 2.', 'send: Oops #1']) expect(store.db.all('SELECT * FROM chat_messages')).toEqual([]) }) })