Commit Graph
899 Commits
Author SHA1 Message Date
MythEclipseandClaude b508a39ff7 fix(ai-moderation): prevent false positive SARA flag for IMPHNEN project name
- Add explicit system rule that IMPHNEN is the project's own name, not religion
- Rename 'Imphnemia 11:17' example to 'Kitabonia 11:17' to avoid name collision
- Ensures mentioning/promoting the project URL is not flagged as SARA

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 23:28:09 +07:00
MythEclipseandClaude 5c00c9f60b feat(ui): overhaul frontend with IMPHNEN visual identity
- Update CSS foundation: HSL→oklch color tokens, Poppins font, new utilities
- Replace Three.js sakura particles with CSS glow orbs
- Rebrand Header with IMPHNEN logo and gradient text
- Update all UI components (Button, Card, Badge, Input, Select, Tabs, Toast)
- Apply IMPHNEN design patterns (glass, gradient, grid) to layout
- Remove all hardcoded #7EC8E3/#FFB7C5/#FCA5A5 references
- Standardize rounded-xl across all components
- Replace emoji toasts with Lucide icons

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 23:00:52 +07:00
MythEclipseandClaude 7f3eb7b9ac feat(ui): add Adaptive Prompt Tuner tab with correction submission UI
- Add pgCorrectedModerationsTable to shared schema
- Create backend corrections module (stats, list, create endpoints)
- Add TunerPanel with Stats, History, and Submit sub-tabs
- Add AuthOverlay gate for Tuner (admin-only, same as Live)
- Set messages as default tab
- Wire Tuner into sidebar, header, and mobile tab bar

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 21:28:05 +07:00
MythEclipseandClaude fbc2184c6e feat(ai-moderation): add user profile self-learning system
Add user_profiles table, store, and background learner worker
that summarizes user communication style, topics, and personality.

- New user_profiles table (user_id PK, guild_id, profile_summary, last_analyzed_at)
- userProfileStore.ts — CRUD (get/update) following channelCultureStore pattern
- userProfileLearner.ts — background worker: queries 100 recent msgs per user,
  calls LLM for personality summary, updates every 12h
- Inject <user_profile> XML tag per-message in moderation prompt
- Start worker alongside cultureLearner in aiAnalyzer.ts
- Migration 0008 for user_profiles table

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 20:11:34 +07:00
MythEclipseandClaude 6effb51b5d fix(ai-moderation): don't cache text-only results for messages with media
- hasMediaContent now also checks evidence.attachments from metadata
  (not just DB attachment records), catching the race where attachment
  DB rows aren't inserted yet when analysis runs.
- Cache-hit guard: treat cached entries as miss when the message has
  media evidence in metadata, so stale 24h-freezes are avoided.
- Cache-write guard: skip storing text-only analysis results for
  messages whose metadata shows attachments/stickers/embeds. This
  prevents a text-only 'clean' result (from failed vision) being
  frozen for 24h, blocking future re-analysis with full media context.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 18:45:33 +07:00
MythEclipseandClaude 33b787dbd6 fix(migration): make all DDL idempotent with IF NOT EXISTS
- 0000: CREATE TABLE IF NOT EXISTS, CREATE INDEX IF NOT EXISTS,
  FK constraint wrapped in DO 539994 EXCEPTION WHEN duplicate_object
- 0001: ALTER ADD COLUMN wrapped in DO 539994 EXCEPTION WHEN duplicate_column
- 0002: CREATE TABLE IF NOT EXISTS, CREATE INDEX IF NOT EXISTS
- 0003: CREATE TABLE IF NOT EXISTS, CREATE INDEX IF NOT EXISTS
- 0006: ALTER ADD COLUMN wrapped in DO 539994 EXCEPTION,
  DROP COLUMN IF EXISTS

Allows migrations to run cleanly regardless of DB state —
handles fresh DB, partial migration, or wiped __drizzle_migrations.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 18:05:09 +07:00
MythEclipseandClaude fcb199a6ae fix(capture): exclude threads inside excluded channels
- Resolve parent channel ID for threads before checking
  EXCLUDED_CHANNEL_IDS set
- Thread messages now blocked if their parent channel is excluded

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 17:07:34 +07:00
MythEclipseandClaude c91f9f18cc refactor(capture): DRY age-restricted check, use Set for excluded IDs
- Move isAgeRestrictedMessage to messageMetadata.ts alongside
  isAgeRestrictedMetadata — single source of truth for NSFW logic
- Replace || chain of channel IDs with a Set for O(1) lookup
- Import isAgeRestrictedMessage in capture layer instead of inline

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 17:03:01 +07:00
MythEclipseandClaude ebfe942db9 fix(capture): skip age-restricted/NSFW channels entirely
Auto-filter all age-restricted and NSFW channels at capture layer
so messages never enter the database or reach frontend.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 17:00:02 +07:00
MythEclipseandClaude 1efa7b6505 feat(ignore): exclude channel 1323365288447574128 from capture
Add hardcoded channel ID to shouldCaptureMessageLocation so messages
from this channel are not stored, analyzed by AI, or sent to frontend.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-12 16:49:14 +07:00
MythEclipseandClaude Fable 5 906aef1807 fix(database): handle PG15+ public schema CREATE privilege error in seedDrizzleHistory
In PG15+, the CREATE privilege on the public schema is revoked from
non-owner roles by default. The seedDrizzleHistory function's
CREATE TABLE IF NOT EXISTS for __drizzle_migrations fails with 42501,
causing the gateway to crash-loop on startup.

Wrap the CREATE in a try/catch for 42501 — if the table already exists
(created by a prior run), we continue gracefully; otherwise re-throw.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 04:06:11 +07:00
MythEclipseandClaude Fable 5 490aad7704 fix(ci): add build tools to backend Dockerfile for native deps
@discordjs/opus requires Python and C++ build tools for native
compilation. The discord-gateway Dockerfile already had these but
the backend Dockerfile was missing them, causing CI build failure.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 03:58:47 +07:00
MythEclipse 2e5371f3ee fix(discord-gateway): bypass Drizzle PG15 schema creation restrictions 2026-06-11 03:53:48 +07:00
MythEclipseandClaude Fable 5 378f1b6bdc fix(database): use public schema for drizzle migrations to avoid permission error
PostgreSQL error 42501 when Drizzle tries CREATE SCHEMA IF NOT EXISTS
"drizzle" — the DB user lacks schema creation privileges. Configuring
migrationsSchema: "public" keeps __drizzle_migrations in the existing
public schema, matching what seedDrizzleHistory already expects.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 03:34:16 +07:00
MythEclipse 8b114ca278 refactor(ai-moderation): expand SARA and religious blasphemy detection rules
Update the moderation prompt to include high-priority detection categories for:
- Fake scripture/verse parodies
- Claims of divinity or false religious movements
- Misuse of theological terms as internet slang/memes
- Mockery of religious figures and rituals

This change ensures stricter enforcement of SARA (Suku, Agama, Ras, Antargolongan) policies by explicitly defining religious blasphemy and parody as high-severity violations.
2026-06-11 02:40:11 +07:00
MythEclipse 2557a07916 feat(core): implement data retention, metrics, and enhanced media handling
This commit introduces several significant improvements across the backend and gateway services:

- **Data Retention**: Added an automated cleanup scheduler in `discord-gateway` to prune expired messages, attachments, and voice recordings based on configurable retention policies.
- **Observability**: Integrated `prom-client` in the `backend` service to expose Prometheus metrics via `/api/metrics` and added default Node.js runtime metrics.
- **Media Handling**: Enhanced `MediaHandler` in `discord-gateway` to support media URL resolution and improved playback status tracking.
- **API & Config**: Expanded the configuration endpoint to expose more system settings and reorganized `.env.example` for better readability.
- **Refactoring & Cleanup**:
    - Removed unused `better-sqlite3` dependency.
    - Refactored voice channel routing.
    - Improved error handling and testing coverage with comprehensive unit tests for shared utilities and error classes.
- **Documentation**: Added `MEMORY.md` for project context.
2026-06-10 20:56:16 +07:00
MythEclipse f04b0f0b42 refactor(voice): optimize recording pipeline and improve performance
Refactor the voice recording and playback systems to improve efficiency, reduce latency, and enhance Docker build performance.

- **Infrastructure**: Optimize Dockerfiles using build mounts for pnpm cache and reorder layers for better caching of dependencies and build tools.
- **Backend/Gateway**:
  - Refactor `broadcast` module to use a generic event-based system instead of hardcoded functions.
  - Simplify voice recording logic by merging metadata and segment management into a unified `segment.ts`.
  - Optimize audio downsampling in `streamSetup.ts` using `Int16Array` views for better performance.
  - Implement `withFallback` utility for more robust Redis/Database command execution.
- **Frontend**:
  - Optimize audio playback visualization using pre-computed level shapes and efficient RMS calculation.
  - Reduce latency in voice commands by prioritizing WebSocket communication over HTTP.
  - Improve base64 encoding efficiency in audio transmission.
- **General**:
  - Add default value for `ADMIN_PASSWORD` in shared config.
  - Fix Docker healthcheck to use `127.0.0.1` instead of `localhost`.
2026-06-09 22:04:05 +07:00
MythEclipseandClaude Opus 4.8 823b342c2c fix: remove --wait flag from docker compose up
The --wait flag causes the deploy to abort when a container exits
immediately (e.g., due to transient DB connection issue on startup).
With restart: unless-stopped, containers will auto-recover without
blocking the deployment pipeline.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 20:48:39 +07:00
MythEclipseandClaude Opus 4.8 c371317755 fix: add retry logic for docker compose pull transient errors
GitHub Container Registry pulls occasionally fail with 'connection reset
by peer'. Adding a 3-attempt retry loop with 5s backoff between pulls
to handle transient network errors gracefully.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 20:39:32 +07:00
MythEclipseandClaude Opus 4.8 655380dd8d fix: build @bete/shared before frontend in Dockerfile
TypeScript compilation in the frontend Docker build fails with TS2307:
Cannot find module '@bete/shared' because the shared package's .d.ts
files in dist/ were never generated. The backend and discord-gateway
Dockerfiles already have this build step — frontend was missing it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 20:35:35 +07:00
MythEclipseandClaude Opus 4.8 07032ab521 refactor: atomic, DRY, and logging improvements across codebase
- Split llmModerationClient.ts (2170 lines) into 5 focused sub-modules
- Split aiAnalyzer.ts (1282 lines) into 4 modular pipelines
- Split messages.db.ts (826 lines) into 5 domain-specific modules
- Moved shared schema to @bete/shared, eliminated backend duplication
- Added createChildLogger to all voice-recording and AI moderation modules
- Extracted tryCommandThenFallback, normalizeMediaState, DEFAULT_VOICE_STATUS
- Created shared pagination.ts utility, eliminated 5+ cursor-pagination duplications
- Created shared messageMapper.ts for row mapping
- Standardized backend error handling with asyncHandler
- Added frontend createLogger utility and useAsyncAction hook
- Added structured logging to frontend hooks, socket, and API client

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 19:46:08 +07:00
MythEclipseandClaude Opus 4.8 b68789fffc refactor: atomic, DRY, and logging improvements
- Shared Redis channel constants as single source of truth (redis-channels.ts)
- commandHandler.ts split into VoiceHandler, MediaHandler, GuildHandler,
  ModerationHandler with handler-registry.ts dispatch
- messageStore.ts (1322 lines) split into domain-specific DB files:
  messages.db.ts, attachments.db.ts, reviews.db.ts,
  moderation-actions.db.ts, retention.db.ts
- recorder.ts startSpeaking callback extracted into speakingHandler.ts,
  streamSetup.ts, segmentFinalizer.ts
- autoDeleteManager.ts split into autoDeleteEligibility.ts,
  autoDeleteNotify.ts, autoDeleteLogger.ts
- Added createChildLogger() logging across 8 service files
- Backend messages.repository.ts migrated from raw SQL to Drizzle ORM
- Fixed biome.json to exclude packages/**/dist/* from lint
- Fixed config.ts GUILD_ID pre-existing type error

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 17:34:18 +07:00
MythEclipse 7108f6bb47 feat(system): implement graceful shutdown and expand websocket events
Improve system reliability and real-time capabilities by implementing a robust lifecycle management system and adding new broadcast events for attachments and voice recordings.

- Implement asynchronous graceful shutdown in backend to close HTTP, WebSocket, Redis, and database connections.
- Add new WebSocket broadcast events: `attachment_created`, `voice_recording_started`, `voice_recording_stopped`, `voice_recording_uploaded`, and `analysis_queue_status`.
- Refactor media status handling to use boolean `playing` state instead of string-based status.
- Centralize `PageResult` and `VoiceRecording` types to improve consistency between frontend and backend.
- Update frontend API client to include `listRecordings` and handle new WebSocket event types.
- Fix type mismatches in voice command handling and media status reporting.
2026-06-09 16:56:44 +07:00
MythEclipseandClaude Opus 4.8 3a7b005d95 fix: resolve architecture disconnects and codebase weaknesses
- Add TEXT_CHANNEL_ID and TEXT_GUILD_ID to config schema (fix silent channel monitoring)
- Remove dead files: message-capture/broadcaster.ts, voice-recording/index.ts
- Fix WebSocket voice_command payload to forward from frontend
- Implement moderation:action handler in commandHandler
- Fix useMascotChat to use canonical request() wrapper
- Fix useAudioPlayback userId hash collision (use string not parseInt)
- Add catch blocks to useMediaControl.skip/stop
- Add typed broadcast functions (messageAnalyzed, voicePcmData, voiceActiveUser)
- Apply Biome formatting and lint fixes

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 16:36:23 +07:00
MythEclipseandClaude Opus 4.8 30c9e86edc test: add placeholder test files for vitest
Prevents vitest from exiting with code 1 when no test files exist.
Adds minimal test files to backend and discord-gateway services.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 15:40:40 +07:00
MythEclipseandClaude Opus 4.8 7d6612bb2d refactor: resolve architecture disconnects and codebase weaknesses
- Consolidate eventTypes.ts as single source of truth for Redis channels:
  - Remove duplicate DiscordGatewayEvent interface from eventBroadcaster.ts
  - Replace all hardcoded channel strings with EventChannels constants
  - eventTypes.ts is no longer an orphan file

- Remove dangerous moderation action feature (selfbot safety):
  - Remove /messages/:id/moderate endpoint from backend
  - Remove moderation:action handler from commandHandler.ts
  - Remove publishFireAndForgetCommand (wrong envelope format)
  - Verified no remaining references to moderation:action in code

- Remove unused getCommandPublisher import from redis-bridge.ts

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:22:09 +07:00
MythEclipseandClaude Opus 4.8 3614d32701 fix: resolve architecture disconnects and codebase weaknesses
- Standardize MessageRecord types — single source of truth from @bete/shared
- Clean up config: remove unused GUILD_ID/TEXT_GUILD_ID/TEXT_CHANNEL_ID, fix WEBSERVER_PORT default (3001), remove default admin password
- Move mascot_chat_messages table to Drizzle schema with proper migration
- Remove runtime DDL (CREATE TABLE IF NOT EXISTS) from mascot-chat repository
- Remove phantom analytics/ module from documentation
- Add better-sqlite3 dependency to root devDependencies
- Replace 'as any' casts with proper type assertions across AI moderation
- Add error logging to silent catch blocks in LLM client
- Apply Biome formatting and import organization

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:07:01 +07:00
MythEclipse 67d66bb5dd refactor(shared): centralize configuration and types
Migrate configuration validation and core moderation types from individual services to the `@bete/shared` package to ensure consistency across the monorepo.

- Move `AppConfig` and moderation-related interfaces to `packages/shared`.
- Replace service-specific Zod schemas with the centralized shared configuration.
- Refactor `services/backend` and `services/discord-gateway` to consume shared config and types.
- Remove redundant type definitions and local configuration logic in services.
- Update `packages/shared` exports to include new `config` and `moderation-types` modules.
- Clean up unused files and deprecated utility functions in `packages/shared`.
2026-06-09 11:56:03 +07:00
MythEclipse f84b380f4f fix: resolve architecture disconnects and codebase weaknesses
- fix(backend): replace raw .parse() with proper loadConfig() + ConfigError
- fix(gateway): connect voice recording uploader to EventBroadcaster
- fix(gateway): remove dead globalThis.moderationBroadcaster path in AI analyzer
- fix(gateway): eliminate audioStream race condition by attaching handlers before pipe
- fix(gateway): enable inlineVolume by default for setMusicVolume to work
- fix(gateway): reuse persistent redisPub for command replies (no new connection per cmd)
- fix(frontend): add missing voice_active_user/voice_pcm_data to WsEventMap
- fix(frontend): correct onAttachmentUploaded handler signature to accept data
- chore: move @types/pg from dependencies to devDependencies
- chore: translate remaining Indonesian comments to English
- chore: remove stale P3 TODO comment
2026-06-09 11:06:14 +07:00
MythEclipseandClaude Opus 4.8 4becf0d6f1 refactor: comprehensive codebase cleanup and architecture hardening
- Sprint 1 (Quick Wins): Remove dead analytics modules, fix 4 unresolved
  imports, replace 3 console.warn with logger, remove mock-crc import
- Sprint 2 (Architecture): Create MascotChatRepository, AnalysisRepository,
  3 Zod schemas (mascot-chat, analysis, voice), deduplicate error classes,
  move 3 SQL queries from routes to repository
- Sprint 3 (Complexity): Replace 7 any types with proper interfaces,
  extract 6 helpers from prepareMediaMessage (CC 85 -> ~15)
- Sprint 4 (Config): Remove 22 dead env vars from .env, add 30 missing
  vars to .env.example, standardize naming

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 10:16:04 +07:00
MythEclipseandClaude Opus 4.8 d0d9e1669e revert(voice): restore working transmit pipeline
- Rollback frontend latency changes (keep processor.connect(destination))
- Rollback FFmpeg aggressive optimizations (keep 20ms frames)
- Transmit was working before latency optimization; restore stable state

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 01:43:41 +07:00
MythEclipseandClaude Opus 4.8 7b74061788 perf(voice): reduce transmit latency
- FFmpeg: frame_duration 10ms, compression_level 0, nobuffer/low_delay flags, minimal probe
- Frontend: buffer 4096→1024 samples (~170ms→~42ms), faster base64 with chunking
- Remove processor.connect(destination) to avoid audio feedback loop

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 01:07:35 +07:00
MythEclipseandClaude Opus 4.8 a4c2b93314 fix(voice): correct Express route for voice command
Route was POST /api/command (mounted at /api + /command)
Fixed to POST /api/voice/command (mounted at /api + /voice/command)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 00:13:00 +07:00
MythEclipseandClaude Opus 4.8 3252b323d3 fix(voice): correct API URL path for voice command
- Change /voice/command to /api/voice/command
- Nginx proxies /api/* routes; /voice/command returns 405

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 23:54:02 +07:00
MythEclipseandClaude Opus 4.8 fc2bd3baf1 fix(voice): use HTTP-only for transmit commands
Send voice:transmit:start/stop via POST /api/voice/command
instead of WebSocket. The WebSocket approach failed because:
1. Separate WS connections weren't handled by backend
2. HTTP fallback wasn't working correctly

Now uses HTTP API directly which is more reliable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 23:09:19 +07:00
MythEclipseandClaude Opus 4.8 52f2968d8f fix(voice): add HTTP API fallback for transmit commands
- Add POST /api/voice/command endpoint in backend
- Frontend transmit now sends commands via dedicated WebSocket connection
  with HTTP API fallback if WebSocket fails
- Fixes issue where transmit start command was never received by discord-gateway

Previously commands were sent via the existing dashboard WebSocket,
which may not be connected when the Transmit button is pressed.
Now each command opens a fresh WebSocket connection with HTTP fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 22:55:11 +07:00
MythEclipse 218ad2f353 chore(voice): improve ffmpeg error message in transmitter 2026-06-08 22:32:19 +07:00
MythEclipseandClaude Opus 4.8 3fcc727187 fix(docker): add ffmpeg to discord-gateway for voice transmit
Voice transmitter requires FFmpeg to encode PCM to OggOpus.
Previously missing from Alpine image, causing:
  spawn ffmpeg ENOENT

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 22:31:16 +07:00
MythEclipseandClaude Opus 4.8 942605661a fix(voice): use FFmpeg for OggOpus encoding in transmitter
- Replace prism Opus.Encoder + OggLogicalBitstream with FFmpeg
- FFmpeg handles upsampling, encoding, and OGG container in one process
- Input: raw PCM 24kHz mono s16le via stdin
- Output: OggOpus via stdout (StreamType.OggOpus)
- FFmpeg arguments optimized for real-time low-delay streaming

Previous approach failed because:
1. Raw Opus packets without OGG wrapper don't work with @discordjs/voice
2. prism's OggLogicalBitstream has CRC bug with node-crc native bindings
3. Manual upsampling was error-prone

Pipeline:
  Browser Mic → base64 PCM → Redis → FFmpeg → OggOpus → Discord

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 22:11:07 +07:00
MythEclipseandClaude Opus 4.8 25eb3f6353 fix(voice): remove OggDemuxer from transmitter pipeline
Opus.Encoder in prism-media outputs raw Opus packets directly,
no OGG wrapping. OggDemuxer was breaking the stream by
trying to unwrap a non-existent OGG container.

Pipeline was: PCM → Encoder → OggDemuxer → Discord (broken)
Pipeline now:  PCM → Encoder → Discord (correct)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:45:26 +07:00
MythEclipseandClaude Opus 4.8 314d2baec4 feat(voice): implement full voice transmit (Browser → Discord)
Frontend (useAudioTransmit.ts):
- Capture microphone via getUserMedia
- Convert Float32 to Int16 PCM at 24kHz mono
- Base64 encode and send as JSON via WebSocket
- Send voice:transmit:start/stop commands on start/stop

Backend (ws/server.ts):
- Handle voice_transmit messages from browser
- Forward PCM data to Redis channel backend:voice:transmit
- Handle voice_command messages and forward to backend:command
- discord-gateway VoiceTransmitter receives and plays to voice channel

Flow:
   Browser Mic → getUserMedia → ScriptProcessor → Int16 PCM → base64 →
   WebSocket JSON → Backend → Redis → VoiceTransmitter → Discord Voice Channel

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:29:41 +07:00
MythEclipseandClaude Opus 4.8 2e9e9c1a06 fix(frontend): handle voice PCM data as JSON instead of binary
- Add onVoicePcmData and onVoiceActiveUser handlers to WebSocket interface
- Add voice_pcm_data and voice_active_user event cases in socket message handler
- Update useAudioPlayback to decode base64 PCM from JSON format
- Connect onVoicePcmData to audio.handleIncomingPcm in App.tsx

Format change:
- Old: Binary (4 bytes userId + PCM buffer)
- New: JSON {userId: string, pcm: base64string}

This matches the format sent by discord-gateway via Redis.
Now PCM audio will flow correctly: Discord → Gateway → Redis → Backend → WebSocket → Browser!

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:22:00 +07:00
MythEclipseandClaude Opus 4.8 1c7b7e6398 fix(backend): handle voice PCM as JSON instead of binary
- Add discord:voice:pcm to SUBSCRIPTIONS as regular JSON channel
- Remove BINARY_CHANNELS and handleBinaryMessage function
- Discord-gateway sends PCM as JSON with base64, not raw binary
- This fixes PCM data not reaching browser via WebSocket

The issue was backend expected binary format but gateway sends:
{"type":"voice_pcm_data","data":{"userId":"...","pcm":"base64..."}}

Now backend correctly subscribes and broadcasts this to WebSocket clients.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:18:11 +07:00
MythEclipseandClaude Opus 4.8 e8e95f635c fix(voice): add OggDemuxer to transmitter for proper Opus streaming
- Add OggDemuxer to unwrap OGG container from Opus encoder output
- Enable inlineVolume for better audio control
- Discord expects raw Opus packets, not OGG-wrapped stream

This should fix the no-audio issue in voice transmit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:04:57 +07:00
MythEclipseandClaude Opus 4.8 f74252f594 feat(voice): add voice transmit functionality for real-time audio streaming
- Add VoiceTransmitter class to handle PCM audio from backend/browser to Discord
- Implement voice:transmit:start and voice:transmit:stop command handlers
- Upsample 24kHz mono PCM to 48kHz stereo for Discord compatibility
- Encode PCM to Opus and stream via browser-bridge player owner
- Subscribe to Redis channel backend:voice:transmit for real-time PCM data

Features:
- Backend can send PCM audio (24kHz mono s16le base64) via Redis
- Automatic upsampling and encoding to Discord-compatible format
- Clean start/stop lifecycle with resource cleanup

This completes the bidirectional voice streaming:
- Listen: Discord → Backend (already working via voicePcmData broadcast)
- Transmit: Backend → Discord (now implemented)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 20:48:16 +07:00
MythEclipseandClaude Opus 4.8 60edb4576f fix(docker): create recordings directory with proper permissions
- Add recordings directory structure with .gitkeep, .gitignore, and README
- Update deployment script to set chmod 777 on recordings directory
- Fixes ENOENT/EACCES errors when discord-gateway tries to create user subdirectories
- Ensures container app user (UID 100) can write recording files

This resolves the crash on voice channel connection where the service
failed to create user-specific recording directories like:
- recordings/<user-id>/
- recordings/sessions/

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 20:31:43 +07:00
MythEclipse 6f4053c1cc fix(docker): add build tools for native dependencies in discord-gateway
Install python3, make, g++, rust, and cargo in Alpine image to resolve:
- node-crc native build failure (requires cargo)
- @discordjs/opus native build issues (requires build tools)

This fixes the GitHub Actions build failure in the discord-gateway service.
2026-06-08 20:16:47 +07:00
MythEclipse 1565a326d0 build(deps): patch node-crc to resolve native build issues
Add a patch for node-crc@4.0.0 in pnpm-workspace.yaml to address build failures related to native dependency compilation.
2026-06-08 20:11:34 +07:00
MythEclipseandClaude Opus 4.8 0e79ba0d50 fix(voice): disable OGG CRC to avoid node-crc native build failure
- prism-media@2.0.0-alpha.0 OggLogicalBitstream requires node-crc
- node-crc is Rust native addon that fails to build (MSRV compat)
- Setting crc: false makes prism-media skip require('node-crc')
- OGG streams work correctly without CRC checksums
- node-crc kept in package.json

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 19:57:33 +07:00
MythEclipseandClaude Opus 4.8 306ccf58f0 fix(voice): revert to prism-media@2.0.0-alpha.0 to fix production runtime errors
Critical production fix for voice recording failures.

Issue:
- Voice recording failing at runtime with "prism.opus.OpusHead is not a constructor"
- Downgrade to prism-media@1.3.5 broke voice recording (missing OggLogicalBitstream/OpusHead classes)
- Code was written for 2.0.0-alpha.0 API

Root Cause:
- prism-media@1.3.5 lacks OggLogicalBitstream and OpusHead classes
- prism-media@2.0.0-alpha.0 has these classes (code was originally written for this version)
- Downgrade to fix peer dependency warning broke working feature

Solution:
- Reverted to prism-media@2.0.0-alpha.0 (original working version)
- Removed @ts-expect-error comments (no longer needed)
- Accept harmless peer dependency warning with @discordjs/voice

Verification:
- TypeScript compilation: 0 errors
- pnpm install successful
- Both versions coexist (pnpm handles dual versions)

Files Modified (3 surgical edits, <15 lines each):
- package.json: Changed version from ^1.3.5 to 2.0.0-alpha.0
- types.ts: Removed @ts-expect-error comment (line 59)
- segment.ts: Removed 2 @ts-expect-error comments (lines 40, 42)

Impact: Voice recording will now work in production

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 19:42:52 +07:00