Commit Graph
95 Commits
Author SHA1 Message Date
MythEclipse 5c8fa3d254 chore(services): update components based on recent changes
Changes:
 services/frontend/src/App.tsx                                          | 22 ++++++++++++++++++++++
 services/frontend/src/features/live/components/VoiceConnectionCard.tsx |  5 ++++-
 2 files changed, 26 insertions(+), 1 deletion(-)
2026-06-13 16:54:52 +07:00
MythEclipse 5459b13b03 chore(services): update components based on recent changes
Changes:
 services/frontend/src/App.tsx | 37 +++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)
2026-06-13 16:54:29 +07:00
MythEclipse e76a874f11 chore(services): update components based on recent changes
Changes:
 services/frontend/src/shared/api/client.ts | 8 ++++++++
 1 file changed, 8 insertions(+)
2026-06-13 16:53:30 +07:00
MythEclipse fce24278f0 chore(auto): task completed - unknown 2026-06-13 14:49:47 +07:00
MythEclipse e6e34281ff chore(auto): task completed - unknown 2026-06-13 14:24:09 +07:00
MythEclipse 6822cb0bd3 chore(auto): task completed - unknown 2026-06-13 14:10:34 +07:00
MythEclipse 277d982c51 chore(auto): task completed - unknown 2026-06-13 14:05:17 +07:00
MythEclipseandClaude 14c0081f01 feat(discord-gateway): implement voice & push improvements
- Voice disconnect broadcast on stopRecording
- Multi-guild voice support (VoiceController Map<guildId>)
- Session finalization + auto-enqueue muxer job
- Recordings API: duration field, channelId/userId filters
- Transmitter Redis connection reuse (shared conn)
- FFmpeg stderr memory cap (4KB limit)
- 10 new Redis event channels + Redis bridge subscriptions
- New DB tables: message_reactions, message_edits
- Webhook notification module
- Gateway metrics / Prometheus endpoint
- Multi-guild message capture (MONITOR_GUILD_IDS array)
- Thread tracking, presence, channel topic, guild member events
- Edit history snapshot on message update
- Muxer audio post-processing worker

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-13 13:51:21 +07:00
MythEclipseandClaude 4fcab6b003 refactor(frontend): reorder sidebar — messages first, voice below
Default tab is now 'messages'; Voice & Media moved below
Messages in both desktop sidebar and mobile tab bar.
Updated Header titles/subtitles to match new order.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-13 12:50:13 +07:00
MythEclipse 615c23f061 chore(auto): task completed - unknown 2026-06-13 12:24:32 +07:00
MythEclipse dcede1d676 chore(auto): task completed - unknown 2026-06-13 12:11:37 +07:00
MythEclipse 5b04a4637c docs(frontend): add design tokens documentation 2026-06-13 11:54:20 +07:00
MythEclipse 1406ce3585 chore(auto): task completed - unknown 2026-06-13 11:46:15 +07:00
MythEclipseandClaude 30f8d7cce3 feat: replace corrections/tuner with dashboard module
Replace the corrections/adaptive-prompt-tuner feature with a new
dashboard module providing server stats and user profile overview.

Backend:
- Add dashboard module (routes, service, repository) with stats + user list + user detail endpoints
- Remove corrections module entirely
- Wire dashboard router in app.ts

Frontend:
- Add dashboard feature (DashboardStats, UserSummaryList, UserProfileDetail components + useDashboard hook)
- Remove tuner feature (CorrectionStats, CorrectionHistory, SubmitCorrection, useCorrections)
- Update API client from corrections → dashboard types/fns
- Rename tab 'tuner' → 'dashboard'
- Update MobileTabBar, Header, Sidebar links

Tests:
- Expand backend placeholder test with dashboard assertions
- Expand discord-gateway placeholder test with config/channel assertions

AI moderation:
- llmModerationClient: improve status/reply detection, expand safety categories, fix timer reset
- userProfileLearner: fix isReply refinement
- userProfileStore: add pending cache check
- messageMetadata: add crosspost type mapping
- migrate.ts: improve partial-index safety in schema push

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-13 11:24:42 +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
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 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
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 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 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 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
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
MythEclipse e00b23f9b8 fix(concurrency): eliminate all identified double-queue and race conditions
Implements full audit from double_queue_audit.md.

## Critical

fix(backend): reanalyze-batch — per-scope in-flight guard (messages.routes.ts)
  Two concurrent admin sessions clicking 'Retry All Errors' simultaneously now
  get a 409 REANALYZE_BATCH_IN_PROGRESS for the same guildId:channelId scope.
  Prevents the recovery worker from being triggered twice for the same set of
  error messages.

fix(discord-gateway): messageUpdate embed resolution skip (messageCapture.ts)
  Discord fires messageUpdate when link previews resolve 1-2s after send
  even though the message body is unchanged. Compare newContent vs
  existingContent before resetting ai_status to pending and re-queueing LLM.
  Eliminates a spurious duplicate analysis that could overwrite a valid result.

## High

fix(discord-gateway): scheduleAutoDelete idempotency (aiAnalyzer.ts)
  Add autoDeleteInFlight Set. Both processBatch and processIndividualFallback
  call scheduleAutoDelete; without the guard, a message that races through
  both paths launches two concurrent attemptAutoDeleteFlaggedMessage calls,
  producing a duplicate moderation-action log entry and a Discord 10008 error.
  The Set is cleaned up in a .finally() block after each attempt completes.

## Medium

fix(frontend): revert optimistic pending state on HTTP failure (useMessages.ts)
  Capture the prior MessageRecord inside the setMessages functional updater
  (no extra useCallback deps needed). If reanalyzeMessage() throws, restore
  the snapshot so the UI reflects the real DB state instead of lying.

fix(discord-gateway): exclude individual_analysis_exhausted from recovery queries
  Both getConversationKeysWithIncompleteAnalysis and
  getIncompleteMessagesByConversation now add a NOT LIKE guard for
  individual_analysis_exhausted. Prevents an infinite recovery loop if a bug
  ever writes both flags to the same row.

## Low

fix(discord-gateway): unified timer path in scheduleConversationAnalysis
  Remove the separate cooldown-path that created a secondary timer calling
  scheduleConversationAnalysis recursively. Replace with a single
  clear-and-reset pattern where delayMs = max(cooldownRemainder+500, debounce).
  Eliminates the edge case where both timers were live simultaneously.

## Misc

fix(backend): cast req.params.id to String() to satisfy Express typings
  Pre-existing tsc error (string | string[]) exposed by our edit.
  String() is correct; route params are always scalar strings at runtime.
2026-06-05 16:09:23 +07:00
MythEclipse 0a35e83a6c refactor(analytics): replace hardcoded color tokens with theme-aware CSS variables 2026-06-04 14:17:45 +07:00
MythEclipse 3ecb7bd15c chore: session auto-commit 2026-06-04 14:16:59 +07:00
MythEclipse 458f20d5c3 chore: session auto-commit 2026-06-04 14:16:26 +07:00
MythEclipse ad61af54e8 refactor(analytics): replace TrendChart gradient bars with interactive SVG line chart featuring tooltips and grid lines 2026-06-04 14:15:56 +07:00
MythEclipse ceb5fc95ba refactor(analytics): replace gradient bars with interactive SVG donut and horizontal bar charts 2026-06-04 14:15:27 +07:00
MythEclipse 00001973d8 refactor(analytics): replace ActivityChart stacked bars with interactive SVG chart featuring tooltips and grid lines 2026-06-04 14:14:49 +07:00
MythEclipse a24a5e7dfd refactor(messages): remove text channel filter and channel-section grouping 2026-06-03 20:53:47 +07:00
MythEclipse 2a2003e638 fix(messages): hide fallback attachment text when media is already displayed visually 2026-06-03 20:42:57 +07:00
MythEclipse b38f867894 refactor(messages): mark emptyText prop as unused
Rename emptyText to _emptyText to indicate it is currently unused in the
MessageFeed component, preventing linting warnings.
2026-06-03 20:38:01 +07:00
MythEclipse 198d5a6329 feat(messages): group message feed by channel and thread sections 2026-06-03 20:34:58 +07:00
MythEclipse 71801b7f77 feat(messages): show channel and thread location context in message cards 2026-06-03 20:34:06 +07:00
MythEclipse 79c2e31b17 feat(messages): add text channel filtering for message browser 2026-06-03 20:31:23 +07:00
MythEclipse a39c7a91c2 refactor(api): replace URLSearchParams param with structured object in listMessages 2026-06-03 20:29:34 +07:00
MythEclipse 2bf48f6cd0 refactor(ui): remove mascot tooltip from sidebar component
Removes the hardcoded mascot tooltip implementation from the Sidebar
component to clean up the component structure. The tooltip logic is
now handled elsewhere.
2026-06-03 20:09:45 +07:00
MythEclipse 4e12394168 fix: add error handling to analytics getTopics query and fix mascot tooltip positioning 2026-06-03 19:50:26 +07:00
MythEclipse 3c130bf813 fix(ui): adjust mascot tooltip positioning and bubble pointer
Changes the mascot tooltip from a fixed bottom-left position to an absolute
centered position above the sidebar. Updates the decorative pointer
elements to use a downward-pointing triangle clip-path instead of a
side-aligned shape.
2026-06-03 19:41:39 +07:00
MythEclipse 6a8a84fd84 fix(mascot-chat): reposition tooltip to fixed bottom-left and show when sidebar collapsed 2026-06-03 19:39:58 +07:00