Compare commits

...

140 Commits

Author SHA1 Message Date
Spicy_Marinara f1179d3b83 v3.3.0: Fix encounter UI theming and JSON cleaning regex properties 2026-01-08 21:52:31 +01:00
Spicy_Marinara 045d1da88b Update README.md 2026-01-08 19:50:20 +01:00
Spicy_Marinara bd056934e1 v3.2.5: Always enable JSON cleaning regex with proper settings 2026-01-08 18:27:16 +01:00
Spicy_Marinara e5bd1e0411 v3.2.4: Fix Present Characters field editing - relationship badges, custom fields, and avatar upload 2026-01-08 18:13:12 +01:00
Spicy_Marinara 055c19951c v3.2.3: Restore avatar upload feature for Present Characters 2026-01-08 13:05:02 +01:00
Spicy_Marinara d41996fb04 v3.2.2: Remove fixed max-width on mobile to support high zoom levels 2026-01-08 12:45:20 +01:00
Spicy_Marinara 2624309523 v3.2.1: Fix mobile viewport height issues with dvh units 2026-01-08 11:18:09 +01:00
Spicy_Marinara 7e9d98738f v3.2.0: Major update with JSON trackers, locking system, and UI improvements 2026-01-08 10:35:54 +01:00
Spicy_Marinara be05051a39 v3.1.1: Fix mobile tabs not initializing on mobile devices 2026-01-08 00:12:19 +01:00
Spicy_Marinara a3063aff4f v3.1.0: Add parser error detection and recommended models section 2026-01-07 22:56:26 +01:00
Spicy_Marinara dbf5c2d17a Merge branch 'main' of https://github.com/SpicyMarinara/rpg-companion-sillytavern 2026-01-07 21:29:20 +01:00
Spicy_Marinara 718d45095d v3.0.1 - Fix thought bubble editing persistence 2026-01-07 20:26:11 +01:00
Spicy_Marinara 897380d532 v3.0.1 - Fix thought bubble editing persistence 2026-01-07 20:25:49 +01:00
Spicy_Marinara 93327e4416 Merge remote changes for v3.0.0 release 2026-01-07 19:52:51 +01:00
Spicy_Marinara c3cdac24c6 Release v3.0.0 - Major update with JSON format, lock/unlock trackers, reorganized UI, colored dialogues, editable prompts, and numerous bug fixes 2026-01-07 17:22:22 +01:00
Spicy Marinara f536472dbe Merge pull request #82 from munimunigamer/auto-update-ext
Fixed auto updating with external api mode
2026-01-06 01:01:16 +01:00
munimunigamer 5bba422904 fixed auto updating with external api mode 2026-01-05 23:58:48 -06:00
Spicy_Marinara 8df6548e0b v2.1.3 - Improved thought bubble positioning and responsiveness
- Align thought bubbles with avatar top instead of center for better visibility
- Fix issue where bubbles extend above avatar when scrolling is limited
- Change thought circles to horizontal layout for cleaner visual flow
- Add responsive positioning that adapts to screen width changes
- Implement smart viewport detection to prevent cutoff at narrow widths
2026-01-03 11:40:07 +01:00
Spicy_Marinara 58020e93d0 Fix: Ensure clothing instruction is included in separate generation prompts 2026-01-03 01:17:41 +01:00
Spicy_Marinara ef03bb11ee Update version to 2.1.2 in settings.html 2026-01-03 00:59:07 +01:00
Spicy_Marinara d75f76b807 Update README with v2.1.2 changelog 2026-01-03 00:58:22 +01:00
Spicy_Marinara c6b71ec1aa Add optional toggle for Relationship Status Fields (v2.1.2)
- Added relationships.enabled toggle in tracker configuration
- Relationship fields and emoji badges can now be disabled/enabled
- UI toggle added in Edit Trackers > Present Characters tab
- Updated prompt generation to respect the toggle
- Maintains backward compatibility with existing configs
- Added i18n translations (en, zh-tw)
2026-01-03 00:55:29 +01:00
Spicy_Marinara d44bb1cff9 v2.1.1: Fix swipe detection in together mode and combat encounter prompt 2026-01-02 20:58:49 +01:00
Spicy_Marinara 87f0931942 Update README with v2.1 release notes 2026-01-02 14:09:13 +01:00
Spicy_Marinara 62ed7ffb18 v2.1: Add dynamic weather effects, clothing inventory, and bug fixes
Features:
- Add dynamic weather effects system (snow, rain, mist, sunshine, storm, wind, blizzard)
- Add separate Clothing tab in inventory system
- Weather effects auto-update based on Info Box weather field
- Combined effects for storm (rain+lightning) and blizzard (snow+wind)

Improvements:
- Settings migration system for automatic feature enablement
- Weather effects positioned behind chat interface (z-index: 1)
- Dynamic weather enabled by default for new users

Bug Fixes:
- Fix tab visibility issues (disabled tabs now properly hide)
- Fix theme-aware borders (remove hardcoded blue colors)
- Fix double scrollbar in Edit Trackers window
- Fix scroll position jumping when editing Present Characters
- Fix dynamic weather toggle hiding issue

Technical:
- Update inventory schema to v2.1 with clothing field
- Add automatic migration for existing v2 inventories
- Update parsers and prompts to handle clothing separately
- Add translations (EN/ZH-TW) for new features
2026-01-02 13:58:43 +01:00
Spicy_Marinara ddd59d124e bug 2025-12-31 18:14:44 +01:00
Spicy_Marinara 3bfc6ea934 Update to v2.0 and add version indicator 2025-12-31 10:53:09 +01:00
Spicy_Marinara 3f58c7ceca Add holiday promotion, snowflakes effect, and Spotify music widget
- Added holiday promotion banner with 2026WITHMARINARA discount code
- Added dismiss functionality for promotion with persistent state
- Implemented snowflakes animation effect with toggle
- Added Spotify music widget above chat input
- Widget matches extension theme colors and positioning
- Added Display Options toggles to show/hide feature toggles
- Improved responsive design and mobile support
2025-12-30 20:56:43 +01:00
Spicy Marinara 51535c5fdc Merge pull request #80 from munimunigamer/image-gen-updates
General Automatic Image Generation Updates
2025-12-30 11:14:55 +01:00
munimunigamer bc4d4a0dd1 prompt now focuses on bust up/face 2025-12-30 04:11:08 -12:00
munimunigamer 5eb602e91d added better prompt generation 2025-12-30 04:02:45 -12:00
munimunigamer ca4a318135 removed unused localization 2025-12-30 03:24:06 -12:00
munimunigamer b4ad757e42 removed unnecessary "LLM Instruction" prompt for image generation 2025-12-30 03:23:18 -12:00
Spicy_Marinara 530d871fd3 Update layout.js 2025-12-29 18:07:33 +01:00
Spicy_Marinara 474e3ce963 Add customizable prompts editor and reorganize settings panel
- Reorganized settings: moved Auto-update, Narrator Mode, and Debug Mode to Advanced section
- Added Customize Prompts button with comprehensive prompts editor modal
- Implemented 7 customizable AI prompts: HTML, plot progression (random/natural), avatar generation, tracker instructions, tracker continuation, and combat narrative
- Added individual and bulk restore to defaults functionality
- Integrated custom prompts across generation modules (plotProgression, promptBuilder, encounterPrompts)
- Auto-update toggle now disabled when not in Separate generation mode
- Merged XML/Markdown tracker instructions into unified prompt
2025-12-29 14:41:12 +01:00
Spicy_Marinara 0b5bca56eb Fix display settings persistence and add responsive layout for plot buttons
- Fixed updateSectionVisibility() to use explicit .show()/.hide() instead of .toggle() to ensure proper element visibility on page reload
- Added responsive CSS for plot buttons to adjust to small screens and mobile devices
- Wrapped button text in spans to enable icon-only mode on very small screens (≤400px)
- Reduced button margins and added flexbox layout with wrapping for better mobile UX
2025-12-29 13:32:30 +01:00
Spicy Marinara 39f4fed40d Merge pull request #79 from munimunigamer/external-mode
feature: Add External API Generation Mode with Secure Key Storage
2025-12-29 10:29:35 +01:00
munimunigamer 6ffcf9c929 detailing that it connects to openai rather than just third party 2025-12-29 02:58:05 -12:00
munimunigamer 10a4f9e89e fixed auto image gen to use external mode as well 2025-12-29 02:56:04 -12:00
munimunigamer fb8a6fcc30 using localstorage instead of extension settings for api key now 2025-12-29 02:50:30 -12:00
munimunigamer b037d95da8 hide the "use model connected to RPG Companion Trackers preset" 2025-12-29 02:43:53 -12:00
munimunigamer 018ab3613f changed default max tokens from 2048 to 8192 2025-12-29 02:42:51 -12:00
munimunigamer 5369cb14a5 add cors error logging, letting the user know if an endpoint can't be used due to cors blocking 2025-12-29 02:42:37 -12:00
munimunigamer 1d4a64bac7 added external api 2025-12-29 02:38:08 -12:00
munimunigamer 9936fb483d added external api settings to extension settings 2025-12-29 02:21:30 -12:00
Spicy_Marinara 3146f033df Fix clamp() to use rem/px for min/max values
- Replace clamp(Xvw, Yvw, Zvw) with clamp(Xrem, Yvw, Zrem)
- Prevents font sizes from scaling excessively on ultrawide monitors
- Now minimum and maximum values are fixed units while middle value remains responsive
- Fixes info box, stats, calendar, weather, and all other text elements
2025-12-28 23:38:41 +01:00
Spicy_Marinara ed421bee63 Fix font sizes for ultrawide monitors using clamp()
- Replace all vw-based font-size properties with clamp() to prevent excessively large text
- Set maximum font sizes to prevent issues on 3440x1440 and other ultrawide displays
- Maintain responsive behavior for normal and mobile screen sizes
- Fix gap properties using vw for better spacing consistency
2025-12-28 22:07:27 +01:00
Spicy Marinara 09463fc95a Merge pull request #75 from munimunigamer/avatar-gen-fixes
fixed right click regen and clearing chat
2025-12-27 21:32:53 +01:00
munimunigamer 10f6326f82 fixed right click regen and clearing chat 2025-12-27 12:36:48 -12:00
Spicy_Marinara 3caa74fbf8 Combat encounters: Add pre-encounter config modal, targeting fixes, and tracker integration
- Add pre-encounter narrative configuration modal with combat/summary style settings
- Change POV fields to text inputs (default: narrator) for custom character names
- Fix targeting system for enemies with spaces in names (e.g., 'Gilded Thrall 1')
- Display character-specific sprites/avatars in targeting modal instead of generic emojis
- Add combat difficulty scaling guidance to prevent trivial god defeats or endless wolf battles
- Integrate tracker updates in combat summary generation (together mode)
- Update auto-save logs description to clarify file storage vs chat history
- Apply extension theming to Close Combat Window button
2025-12-27 16:06:06 +01:00
Spicy Marinara 436f3495f8 Merge pull request #74 from joenunezb/fix/hanging-swipes-with-chapterCheckpoints
fix: Swipes hanging due race condition when handling promises in chapterCheckpoints
2025-12-27 08:42:04 +01:00
joenunezb afa39b1387 Useless comments 2025-12-26 19:24:08 -08:00
joenunezb b38dbe06a6 fix: Properly handle promises that lead to hangs on swipes 2025-12-26 19:01:05 -08:00
Spicy Marinara 6b73e422de Merge pull request #73 from munimunigamer/merge-fix-69-70
Quick fix on the merge problem
2025-12-26 18:13:41 +01:00
munimunigamer ed5bcb2670 fixed index.js file 2025-12-26 10:57:46 -06:00
Spicy Marinara c29f2b1bb5 Merge pull request #70 from munimunigamer/auto-image-generation
Add automatic avatar generation for NPCs with LLM-powered prompts
2025-12-26 10:00:38 +01:00
Spicy Marinara 91732b4d1c Merge branch 'main' into auto-image-generation 2025-12-26 10:00:29 +01:00
Spicy Marinara b163141652 Merge pull request #69 from munimunigamer/main
feat: Add configurable toggles for Narrator Mode and dice display
2025-12-26 09:58:32 +01:00
munimunigamer 87e86bfbb4 Removing my .claude settings file oopsies 2025-12-25 23:43:39 -08:00
munimunigamer d10d4e876f replaced disable placeholder card with Narrator mode (changes prompt a bit to support open ended rpgs/narrator cards that don't have defined characters better) 2025-12-26 01:31:16 -06:00
munimunigamer fdaca39d39 renamed stable diffusion to image generation 2025-12-26 01:01:04 -06:00
munimunigamer 2df173e6af fixed up re-rendering images when right clicking 2025-12-26 00:54:44 -06:00
munimunigamer de11f6f7e2 llm generated image gen prompts 2025-12-25 21:13:19 -08:00
munimunigamer b7e52046bc fixed avatar images appearing in rpg 2025-12-25 20:39:01 -08:00
munimunigamer 7802479670 auto-image-generation 2025-12-25 19:59:25 -08:00
munimunigamer c73260b2c6 Added placeholder and dice config options 2025-12-25 18:27:28 -08:00
Spicy_Marinara 04bd314da2 Add chapter checkpoint UI improvements and separate Quests toggle
- Fix checkpoint button display with expandMessageActions setting
- Add body class observer to update buttons when setting toggles
- Add cleanupCheckpointUI function for extension disable
- Separate Quests from Inventory with independent toggle
- Add horizontal scrolling to Info Box dashboard
- Add divider between Inventory and Quests sections
2025-12-22 01:05:01 +01:00
Spicy_Marinara d386752f9c Fix chapter checkpoint button duplication issue 2025-12-22 00:27:25 +01:00
Spicy_Marinara 9d8b758317 Remove accidentally committed log file 2025-12-21 23:55:02 +01:00
Spicy_Marinara fe03cba802 feat: Add remove button for characters in Present Characters panel
- Add removeCharacter() function to delete characters from panel and saved data
- Remove character from both lastGeneratedData and committedTrackerData
- Add X button to character card header with hover effects
- Button removes character from display and prevents re-inclusion in next generation
- Updates are persisted to chat metadata
2025-12-19 18:01:05 +01:00
Spicy_Marinara ab7dfeaf8b feat: Add custom avatar upload for NPCs in Present Characters panel
- Add npcAvatars storage to extension settings for custom NPC images
- Implement getCharacterAvatar() to check custom avatars first
- Add uploadNpcAvatar() function with file validation (2MB max, images only)
- Make character avatars clickable with visual feedback
- Support left-click to upload and right-click to remove custom avatars
- Add camera icon overlay on hover with smooth animations
- Store avatars as base64 data URIs for persistence across sessions
2025-12-18 14:14:49 +01:00
Spicy_Marinara 5bc7bfe22f Fix: Preserve decimal commas in numbers (e.g., 4443,445)
- Modified itemParser to detect commas between digits
- Prevents splitting money/numbers with comma decimal separators
- Example: '4443,445 gold coins' now stays as one item
- Added documentation and example for decimal comma handling
2025-12-18 02:03:11 +01:00
Spicy_Marinara 3ded104218 Add chapter checkpoint feature
- New feature: bookmark messages to exclude earlier history from context
- Saves tokens by marking chapter start points in long chats
- Uses SillyTavern's /hide and /unhide slash commands
- Persists checkpoint across page reloads and generation events
- UI: bookmark icon in message menus with visual indicators
- Debounced restore function prevents concurrent executions
- Pre-generation checkpoint application ensures messages stay hidden
- Clean production-ready code with proper error handling
2025-12-18 01:59:14 +01:00
Spicy_Marinara 8645bbde98 Revert "Merge pull request #57 from devsorcer/claude/add-character-state-tracking-01AC3zt7Z6eEYLfZXoZCgut4"
This reverts commit 8905db3e44, reversing
changes made to 628d8ee7a4.
2025-12-06 00:04:32 +01:00
Spicy Marinara cc1dd8dc11 Merge pull request #60 from SpicyMarinara/revert-59-main
Revert "All the features"
2025-12-05 22:44:11 +01:00
Spicy Marinara bfb63a34cd Revert "All the features" 2025-12-05 22:43:56 +01:00
Spicy_Marinara 275179fa7f Revert "Update promptBuilder.js"
This reverts commit 3c6daa6a72.
2025-12-05 22:43:04 +01:00
Spicy_Marinara 3c6daa6a72 Update promptBuilder.js 2025-12-05 21:54:15 +01:00
Spicy Marinara 02f74c8e75 Merge pull request #59 from Subarashimo/main
All the features
2025-12-05 20:51:38 +01:00
Spicy Marinara cdbf3a0354 Merge branch 'main' into main 2025-12-05 20:51:05 +01:00
Spicy Marinara 31f12941a8 Merge pull request #58 from devsorcer/main
Done
2025-12-05 20:47:50 +01:00
Spicy Marinara 8905db3e44 Merge pull request #57 from devsorcer/claude/add-character-state-tracking-01AC3zt7Z6eEYLfZXoZCgut4
Claude/add character state tracking 01 ac3zt7 z6e ey lf z xo z cgut4
2025-12-05 20:46:32 +01:00
Subarashimo 3500c200c6 Merge branch 'main' of https://github.com/Subarashimo/rpg-companion-sillytavern 2025-12-05 19:53:04 +01:00
Subarashimo e9317595b6 fix: string format skills 2025-12-05 19:52:25 +01:00
Subarashimo f1219d6a40 Merge branch 'main' into main 2025-12-05 18:16:05 +01:00
Subarashimo 7e47dbfd7c chore: final cleanup 2025-12-05 18:10:21 +01:00
Subarashimo 38328de1bf fix: clear skills 2025-12-05 16:29:54 +01:00
Subarashimo 806a7078a7 feat: message interception 2025-12-05 11:40:50 +01:00
Claude 6a513bc0b5 Add dynamic container creation as fallback if template fails to load 2025-12-05 05:19:41 +00:00
Claude ffed3aa1b5 Add diagnostic logging to character state tracking 2025-12-05 05:12:58 +00:00
Claude 14465e5ae9 Bump version to 2.0.0 with visible loading indicator 2025-12-05 05:06:39 +00:00
devsorcer 817dad352f Add files via upload 2025-12-05 10:32:28 +05:30
Claude 19c47de934 Add READY_TO_USE guide explaining 100% copy-paste integration 2025-12-05 04:53:10 +00:00
Claude c35e39c445 Integrate character state tracking system into main extension
This commit fully integrates the character tracking system into the
RPG Companion extension. Now 100% ready to use with zero manual work.

Changes to index.js:
- Added imports for character state modules
- Created event wrapper functions for:
  - onGenerationStarted (injects character tracking prompt)
  - onMessageReceived (parses and applies state updates)
  - onCharacterChanged (loads character state from chat)
- Added persistence functions (save/load to chat metadata)
- Modified event registration to use wrapper functions
- Added character state display initialization

Changes to template.html:
- Added #rpg-character-state-container for UI display

SYSTEM NOW FULLY FUNCTIONAL:
 LLM receives character state before generation
 LLM updates character state in responses
 States automatically parse and apply
 UI displays character emotions, physical stats, relationships
 State persists between sessions in chat metadata
 100% copy-paste ready - no manual integration needed

To use:
1. Files are already in place
2. System works automatically
3. Check console for [Character Tracking] logs
4. See character state in RPG panel
2025-12-05 04:52:01 +00:00
Claude 0440159089 Add comprehensive character state tracking system for {{char}}
This implements a complete Katherine RPG-based character state tracking
system that tracks the AI character ({{char}}) instead of the user.

Features:
- 40+ primary personality traits (dominance, honesty, empathy, etc.)
- 70+ secondary emotional states (happy, horny, anxious, playful, etc.)
- Physical stats tracking (energy, hunger, arousal, health, pain, etc.)
- Relationship tracking per-NPC (trust, love, attraction, thoughts, etc.)
- Clothing/outfit dynamic tracking
- Internal thoughts and contextual awareness
- LLM-driven automatic state updates based on responses
- Full UI rendering with tabbed interface

New Files:
- src/core/characterState.js (528 lines) - Core state data structure
- src/systems/generation/characterPromptBuilder.js (407 lines) - LLM prompts
- src/systems/generation/characterParser.js (456 lines) - Response parsing
- src/systems/rendering/characterStateRenderer.js (401 lines) - UI rendering
- CHARACTER_TRACKING_README.md - Complete documentation
- INTEGRATION_EXAMPLE.js - Step-by-step integration guide
- IMPLEMENTATION_SUMMARY.md - System overview and deliverables

System tracks 150+ individual stats per character with full LLM integration
for contextual, realistic character simulation.

All code is production-ready and copy-paste complete.
2025-12-05 04:39:53 +00:00
devsorcer 2d5b3c4c5b Add files via upload 2025-12-05 09:57:31 +05:30
Subarashimo 271c69ec49 feat: remove character button 2025-12-04 21:04:56 +01:00
Subarashimo 9f6c44745b feat: rpg stats improvements 2025-12-04 20:40:02 +01:00
Spicy Marinara 628d8ee7a4 Merge pull request #56 from IDeathByte/main
Fix for character card
2025-12-04 09:29:11 +01:00
IDeathByte 23a4e77b0a Fix for character card
Fixing the issue, when card data makes unreadable, when LLM generates more than 2 strings for appearance

Make it scrollable
2025-12-04 13:05:04 +05:00
Subarashimo b5f5f6d9c5 fix: classica js falsy bug 2025-12-03 22:45:58 +01:00
Subarashimo c24515db7e fix: several issues 2025-12-03 22:34:50 +01:00
Subarashimo 0f7fdfcef1 feat: json format, et al. 2025-12-03 14:55:30 +01:00
Subarashimo 56349f30e6 fix: prompt consistency 2025-12-03 10:02:39 +01:00
Subarashimo d775b45951 fix: missing divider handling 2025-12-03 09:24:00 +01:00
Subarashimo c1a343eb46 fix: flexible prompts 2025-12-03 09:22:42 +01:00
Subarashimo f3c224a99a feat: more settings 2025-12-03 09:19:03 +01:00
Spicy_Marinara 32c2543605 Respect showInventory toggle in prompt generation 2025-12-01 11:46:57 +01:00
Spicy Marinara 968aedc537 Merge pull request #52 from lilminzyu/i18n/zh-tw
Add Chinese (Traditional) i18n support
2025-12-01 11:31:44 +01:00
Mingyu f38bddec62 The processing of the Separate button was missing and has been added. Dynamic update logic centralized 2025-11-26 21:46:59 +08:00
Mingyu 691586ce2f Merge branch 'SpicyMarinara:main' into i18n/zh-tw 2025-11-26 15:51:12 +08:00
Mingyu d486c9e924 mobile done 2025-11-26 07:49:59 +00:00
Spicy_Marinara 0c5b55b190 Add character card info in separate mode with muted filtering and scrollable Past Events 2025-11-25 12:40:28 +01:00
Mingyu 6759f514f3 pc all done 2025-11-24 22:38:56 +08:00
Mingyu 79f99a40c6 RPG Companion index [done] 2025-11-24 19:48:34 +08:00
Mingyu ab33604ea0 Edit Trackers Pop-up window [done] 2025-11-24 17:40:07 +08:00
Mingyu 0f0a4dceeb RPG Companion Settings Pop-up window [done] 2025-11-24 17:37:38 +08:00
Mingyu 8ef4e4ba6d first try i18n base ok 2025-11-24 17:35:41 +08:00
Spicy_Marinara 950d83fc18 Update promptBuilder.js 2025-11-23 19:59:27 +01:00
Spicy Marinara 5e05dee0e8 Merge pull request #50 from chungchan-dev/fix/mobile-layout
fix: some mobile layout
2025-11-23 13:40:09 +01:00
Spicy_Marinara 67df7034eb Add custom HTML prompt editor, skills blur handler, and include skills in separate mode 2025-11-22 23:36:39 +01:00
Chanho Chung eef547b0fa fix: mobile layout of rpg-skills-section font size 2025-11-22 23:35:30 +09:00
Chanho Chung fed4e2d095 fix: mobile layout of rpg-skills-section and rpg-classic-stat 2025-11-22 23:27:45 +09:00
Chanho Chung 02f080cc98 fix: mobile layout of rpg-mobile-tabs, rpg-info-content, rpg-character-card 2025-11-22 23:09:54 +09:00
Chanho Chung 00265ba905 fix: mobile layout of rpg-info-box 2025-11-22 11:14:14 +09:00
Spicy_Marinara c3624c240f Exclude attributes from separate tracker generation requests 2025-11-21 00:01:44 +01:00
Spicy_Marinara 76c7e3cd9c Update HTML prompt wording and improve together mode swipe handling 2025-11-20 22:59:31 +01:00
Spicy_Marinara 2b45dc8fae Add stat change guidelines, attributes toggle, skills editing, and improved character parsing
- Add temporal awareness and stat decay rules to prompt (0-5% per message)
- Add 'Always Include Attributes' toggle in tracker editor
- Fix skills section editing (was not saving customFields)
- Improve Present Characters parser to handle malformed formats (mid-line chars, extra blank lines)
- All changes work in both together/separate generation modes
2025-11-18 15:10:24 +01:00
Spicy_Marinara ed3eac54fc Update promptBuilder.js 2025-11-16 00:06:32 +01:00
Spicy_Marinara c48b1dab46 Fix: Hide UI elements when extension disabled
- Skip UI initialization entirely when extension is disabled on page load
- Remove all UI elements (panel, buttons) from DOM when disabling extension
- Recreate full UI when re-enabling extension
- Hide mobile toggle button on desktop viewports (>1000px)
- Show/hide mobile toggle based on viewport size transitions
- Ensures clean state management for extension enable/disable
2025-11-13 23:30:44 +01:00
Spicy_Marinara bd891e39b0 Fix: Quests now properly scoped per-chat
Quests were bleeding through from other chats because loadChatData()
wasn't resetting them when switching to a chat without RPG data.

When loading a chat with no rpg_companion metadata, the function now
resets quests to empty state (main: 'None', optional: []) along with
other tracker data. This ensures each chat maintains its own quest
state independently.
2025-11-13 21:01:37 +01:00
Spicy Marinara dfbae54b48 Merge pull request #47 from amauragis/guided-generation-compat
Add a prompt injection suppresson feature for Guided Generations
2025-11-13 20:59:13 +01:00
Andy Mauragis dc37fd4a63 docs: Update README with guided generation compatibility info 2025-11-13 13:46:36 -05:00
Andy Mauragis 0ac85ad9fd feat: Add 'Skip Injections during Guided Generations' setting and UI 2025-11-13 13:46:36 -05:00
Andy Mauragis 407a45a25c feat: Add core suppression logic and integrate into prompt injector 2025-11-13 13:46:36 -05:00
Spicy_Marinara d658e337f6 Fix: Support multiple character variants in Present Characters panel
Fixed issues when AI generates multiple character variants (e.g.,
storyteller mode with 'Dottore (Prime)', 'Dottore (Beta)', etc.):

1. Escape quotes in character names to prevent HTML attribute breakage
   - Added escapeHtmlAttr() helper function
   - Prevents names like 'Marianna "Mari"' from breaking HTML

2. Restore avatar lookup for character variants
   - namesMatch() now strips parentheses and quotes from both sides
   - Allows 'Dottore (Prime)' to find 'Dottore' character card avatar
   - Each variant still gets its own card with separate attributes

3. Multiple characters now display correctly in panel
   - Each variant creates its own character object
   - Attributes (Details, Relationship, Stats, Thoughts) don't mix
   - All characters appear in the panel, not just the last one
2025-11-13 16:18:35 +01:00
Spicy Marinara 172c8d6ab8 Merge pull request #45 from joenunezb/fix/render-chat-message-properly
fix: Render chat messages using updateMessageBlock
2025-11-13 13:26:13 +01:00
joenunezb c23c68fbc3 fix: Render chat messages using updateMessageBlock 2025-11-13 03:43:41 -08:00
Spicy_Marinara d4fc3ce1d8 Add 'Always Show Thought Bubble' setting - keeps thought bubble permanently expanded 2025-11-06 22:20:35 +01:00
Spicy Marinara 227eb4c31e Merge pull request #43 from SpicyMarinara/revert-36-feat/v2-widget-dashboard-system
Revert "feat: v2 widget dashboard system"
2025-11-06 20:06:40 +01:00
59 changed files with 16128 additions and 3299 deletions
+26 -9
View File
@@ -5,6 +5,18 @@ An immersive RPG extension for browsers that tracks character stats, scene infor
[![My Discord](https://img.shields.io/badge/Discord-Join%20Server-7289da)](https://discord.com/invite/KdAkTg94ME)
[![Support Me](https://img.shields.io/badge/Ko--fi-Support%20Creator-ff5e5b)](https://ko-fi.com/marinara_spaghetti)
## 🆕 What's New
### v3.3.0
- Small upgrades to the combat system.
- Regex fix.
- Fixed External API logic.
- Even more minor bug fixes.
**Special thanks to all the other contributors for this project:**
Paperboygold, Munimunigamer, Subarashimo, Lilminzyu, Claude, IDeathByte, Chungchandev, Joenunezb, and Amauragis.
## 📥 Installation
1. Open SillyTavern
@@ -57,8 +69,6 @@ An immersive RPG extension for browsers that tracks character stats, scene infor
### To-Do
1. Allow users to use a different model for the separate trackers generation
2. ~~Make all trackers and fields customizable~~ ✅ Done!
3. ~~Kill myself~~
## ⚙️ Settings
@@ -186,6 +196,18 @@ The extension fully supports swipes:
You can click the "Refresh RPG Info" button in the settings to refresh the RPG data at any time in separate generation mode.
### Compatibility with Guided Generations
This extension detects when a "guided generation" prompt is submitted (for example, via the GuidedGenerations extension which injects an ephemeral `instruct` prompt), and will avoid adding its tracker injection instructions (requests for stats, info box, and context prompts) to the generation context. This prevents conflicting instructions and ensures guided generations behave as the user expects.
If you want tracker prompts to apply during a guided generation, run the update via separate generation or temporarily disable guided generation in the other extension.
There is a new setting "Skip Tracker & HTML Injections during Guided Generations" in the RPG Companion settings (Advanced section). It now supports three modes:
- none: never skip (always inject the tracker prompts as usual, default)
- impersonation: only skip when an impersonation-style guided generation is detected
- guided: skip whenever a guided `instruct` or `quiet_prompt` generation is detected
## 🎨 Themes
Choose from 6 beautiful themes:
@@ -245,13 +267,8 @@ If you enjoy this extension, consider supporting development:
## 🙏 Credits
- Extension Development: Marinara with assistance from GitHub Copilot
- Immersive HTML concept: Credit to u/melted_walrus
- Info Box prompt inspiration: MidnightSleeper
- Stats Tracker concept: Community feedback
- Special thanks to Quack for helping me with the CSS
- Massive kudos to Paperboy for making the mobile version work, fixing bugs, and adding the inventory system
- Thanks to IDeathByte for solving some CSS scaling issues
**Contributors:**
SpicyMarinara, Paperboygold, Munimunigamer, Subarashimo, Lilminzyu, Claude, IDeathByte, Chungchandev, Joenunezb, and Amauragis.
## 🚀 Planned Features
-264
View File
@@ -1,264 +0,0 @@
{
"chat_completion_source": "custom",
"openai_model": "gpt-4o",
"claude_model": "claude-3-sonnet-20240229",
"openrouter_model": "OR_Website",
"openrouter_use_fallback": false,
"openrouter_group_models": false,
"openrouter_sort_models": "alphabetically",
"openrouter_providers": [],
"openrouter_allow_fallbacks": true,
"openrouter_middleout": "on",
"ai21_model": "jamba-large",
"mistralai_model": "mistral-large-latest",
"cohere_model": "command-r-plus",
"perplexity_model": "llama-3-70b-instruct",
"groq_model": "llama3-70b-8192",
"xai_model": "grok-4-0709",
"pollinations_model": "openai",
"aimlapi_model": "gpt-4o-mini-2024-07-18",
"electronhub_model": "gpt-4o-mini",
"electronhub_sort_models": "alphabetically",
"electronhub_group_models": false,
"moonshot_model": "kimi-latest",
"fireworks_model": "accounts/fireworks/models/kimi-k2-instruct",
"cometapi_model": "gpt-4o",
"custom_model": "",
"custom_prompt_post_processing": "semi",
"google_model": "gemini-pro",
"vertexai_model": "gemini-2.5-pro-exp-03-25",
"azure_api_version": "2024-02-15-preview",
"azure_openai_model": "",
"temperature": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"top_p": 1,
"top_k": 0,
"top_a": 1,
"min_p": 0,
"repetition_penalty": 1,
"openai_max_context": 16384,
"openai_max_tokens": 8192,
"wrap_in_quotes": false,
"names_behavior": -1,
"send_if_empty": "",
"impersonation_prompt": "",
"new_chat_prompt": "",
"new_group_chat_prompt": "",
"new_example_chat_prompt": "",
"continue_nudge_prompt": "",
"bias_preset_selected": "Default (none)",
"max_context_unlocked": false,
"wi_format": "",
"scenario_format": "",
"personality_format": "",
"group_nudge_prompt": "",
"stream_openai": false,
"prompts": [
{
"name": "Main Prompt",
"system_prompt": true,
"role": "system",
"content": "",
"identifier": "main",
"injection_position": 0,
"injection_depth": 4,
"forbid_overrides": false
},
{
"name": "NSFW Prompt",
"system_prompt": true,
"role": "system",
"content": "",
"identifier": "nsfw"
},
{
"identifier": "dialogueExamples",
"name": "Chat Examples",
"system_prompt": true,
"marker": true
},
{
"name": "Jailbreak Prompt",
"system_prompt": true,
"role": "system",
"content": "",
"identifier": "jailbreak"
},
{
"identifier": "chatHistory",
"name": "Chat History",
"system_prompt": true,
"marker": true
},
{
"identifier": "worldInfoAfter",
"name": "World Info (after)",
"system_prompt": true,
"marker": true
},
{
"identifier": "worldInfoBefore",
"name": "World Info (before)",
"system_prompt": true,
"marker": true
},
{
"identifier": "enhanceDefinitions",
"role": "system",
"name": "Enhance Definitions",
"content": "If you have more knowledge of {{char}}, add to the character's lore and personality to enhance them but keep the Character Sheet's definitions absolute.",
"system_prompt": true,
"marker": false
},
{
"identifier": "charDescription",
"name": "Char Description",
"system_prompt": true,
"marker": true
},
{
"identifier": "charPersonality",
"name": "Char Personality",
"system_prompt": true,
"marker": true
},
{
"identifier": "scenario",
"name": "Scenario",
"system_prompt": true,
"marker": true
},
{
"identifier": "personaDescription",
"name": "Persona Description",
"system_prompt": true,
"marker": true
}
],
"prompt_order": [
{
"character_id": 100000,
"order": [
{
"identifier": "main",
"enabled": true
},
{
"identifier": "worldInfoBefore",
"enabled": true
},
{
"identifier": "charDescription",
"enabled": true
},
{
"identifier": "charPersonality",
"enabled": true
},
{
"identifier": "scenario",
"enabled": true
},
{
"identifier": "enhanceDefinitions",
"enabled": false
},
{
"identifier": "nsfw",
"enabled": true
},
{
"identifier": "worldInfoAfter",
"enabled": true
},
{
"identifier": "dialogueExamples",
"enabled": true
},
{
"identifier": "chatHistory",
"enabled": true
},
{
"identifier": "jailbreak",
"enabled": true
}
]
},
{
"character_id": 100001,
"order": [
{
"identifier": "main",
"enabled": false
},
{
"identifier": "worldInfoBefore",
"enabled": false
},
{
"identifier": "personaDescription",
"enabled": false
},
{
"identifier": "charDescription",
"enabled": false
},
{
"identifier": "charPersonality",
"enabled": false
},
{
"identifier": "scenario",
"enabled": false
},
{
"identifier": "enhanceDefinitions",
"enabled": false
},
{
"identifier": "nsfw",
"enabled": false
},
{
"identifier": "worldInfoAfter",
"enabled": false
},
{
"identifier": "dialogueExamples",
"enabled": false
},
{
"identifier": "chatHistory",
"enabled": false
},
{
"identifier": "jailbreak",
"enabled": false
}
]
}
],
"show_external_models": false,
"assistant_prefill": "",
"assistant_impersonation": "",
"claude_use_sysprompt": true,
"use_makersuite_sysprompt": true,
"vertexai_auth_mode": "full",
"squash_system_messages": true,
"image_inlining": false,
"inline_image_quality": "auto",
"video_inlining": false,
"bypass_status_check": false,
"continue_prefill": false,
"continue_postfix": "",
"function_calling": false,
"show_thoughts": false,
"reasoning_effort": "auto",
"enable_web_search": false,
"request_images": false,
"seed": -1,
"n": 1,
"extensions": {}
}
+585 -156
View File
@@ -5,6 +5,8 @@ import { power_user } from '../../../power-user.js';
// Core modules
import { extensionName, extensionFolderPath } from './src/core/config.js';
import { i18n } from './src/core/i18n.js';
import { migrateToV3JSON } from './src/utils/jsonMigration.js';
import {
extensionSettings,
lastGeneratedData,
@@ -20,6 +22,7 @@ import {
$thoughtsContainer,
$inventoryContainer,
$questsContainer,
$musicPlayerContainer,
setExtensionSettings,
updateExtensionSettings,
setLastGeneratedData,
@@ -35,7 +38,9 @@ import {
setInfoBoxContainer,
setThoughtsContainer,
setInventoryContainer,
setQuestsContainer
setQuestsContainer,
setMusicPlayerContainer,
clearSessionAvatarPrompts
} from './src/core/state.js';
import { loadSettings, saveSettings, saveChatData, loadChatData, updateMessageSwipeData } from './src/core/persistence.js';
import { registerAllEvents } from './src/core/events.js';
@@ -49,7 +54,7 @@ import {
generateSeparateUpdatePrompt
} from './src/systems/generation/promptBuilder.js';
import { parseResponse, parseUserStats } from './src/systems/generation/parser.js';
import { updateRPGData } from './src/systems/generation/apiClient.js';
import { updateRPGData, testExternalAPIConnection } from './src/systems/generation/apiClient.js';
import { onGenerationStarted } from './src/systems/generation/injector.js';
// Rendering modules
@@ -64,6 +69,9 @@ import {
} from './src/systems/rendering/thoughts.js';
import { renderInventory } from './src/systems/rendering/inventory.js';
import { renderQuests } from './src/systems/rendering/quests.js';
import { renderMusicPlayer } from './src/systems/rendering/musicPlayer.js';
import { toggleSnowflakes, initSnowflakes } from './src/systems/ui/snowflakes.js';
import { toggleDynamicWeather, initWeatherEffects, updateWeatherEffect } from './src/systems/ui/weatherEffects.js';
// Interaction modules
import { initInventoryEventListeners } from './src/systems/interaction/inventoryActions.js';
@@ -74,6 +82,7 @@ import {
applyCustomTheme,
toggleCustomColors,
toggleAnimations,
updateFeatureTogglesVisibility,
updateSettingsPopupTheme,
applyCustomThemeToSettingsPopup
} from './src/systems/ui/theme.js';
@@ -84,11 +93,22 @@ import {
setupSettingsPopup,
updateDiceDisplay,
addDiceQuickReply,
getSettingsModal
getSettingsModal,
showWelcomeModalIfNeeded
} from './src/systems/ui/modals.js';
import {
initTrackerEditor
} from './src/systems/ui/trackerEditor.js';
import {
initPromptsEditor
} from './src/systems/ui/promptsEditor.js';
import {
initChapterCheckpointUI,
injectCheckpointButton,
updateAllCheckpointIndicators,
cleanupCheckpointUI
} from './src/systems/ui/checkpointUI.js';
import { restoreCheckpointOnLoad } from './src/systems/features/chapterCheckpoint.js';
import {
togglePlotButtons,
updateCollapseToggleIcon,
@@ -104,7 +124,8 @@ import {
setupMobileTabs,
removeMobileTabs,
setupMobileKeyboardHandling,
setupContentEditableScrolling
setupContentEditableScrolling,
updateMobileTabLabels
} from './src/systems/ui/mobile.js';
import {
setupDesktopTabs,
@@ -114,9 +135,11 @@ import {
// Feature modules
import { setupPlotButtons, sendPlotProgression } from './src/systems/features/plotProgression.js';
import { setupClassicStatsButtons } from './src/systems/features/classicStats.js';
import { ensureHtmlCleaningRegex, detectConflictingRegexScripts } from './src/systems/features/htmlCleaning.js';
import { setupMemoryRecollectionButton, updateMemoryRecollectionButton } from './src/systems/features/memoryRecollection.js';
import { initLorebookLimiter } from './src/systems/features/lorebookLimiter.js';
import { ensureHtmlCleaningRegex, detectConflictingRegexScripts, ensureTrackerCleaningRegex } from './src/systems/features/htmlCleaning.js';
import { ensureJsonCleaningRegex, removeJsonCleaningRegex } from './src/systems/features/jsonCleaning.js';
import { parseAndStoreSpotifyUrl } from './src/systems/features/musicPlayer.js';
import { DEFAULT_HTML_PROMPT } from './src/systems/generation/promptBuilder.js';
import { openEncounterModal } from './src/systems/ui/encounterUI.js';
// Integration modules
import {
@@ -126,7 +149,8 @@ import {
onCharacterChanged,
onMessageSwiped,
updatePersonaAvatar,
clearExtensionPrompts
clearExtensionPrompts,
onGenerationEnded
} from './src/systems/integration/sillytavern.js';
// Old state variable declarations removed - now imported from core modules
@@ -151,61 +175,88 @@ import {
// (setupMobileToggle, constrainFabToViewport, setupMobileTabs, removeMobileTabs,
// setupMobileKeyboardHandling, setupContentEditableScrolling)
/**
* Updates UI elements that are dynamically generated and not covered by data-i18n-key.
*/
function updateDynamicLabels() {
// Update "Refresh RPG Info" button, but only if it's not disabled
const refreshBtn = document.getElementById('rpg-manual-update');
if (refreshBtn && !refreshBtn.disabled) {
const refreshText = i18n.getTranslation('template.mainPanel.refreshRpgInfo') || 'Refresh RPG Info';
refreshBtn.innerHTML = `<i class="fa-solid fa-sync"></i> ${refreshText}`;
}
// Update "Last Roll" label
updateDiceDisplay();
// Update mobile tab labels
updateMobileTabLabels();
}
/**
* Adds the extension settings to the Extensions tab.
*/
function addExtensionSettings() {
const settingsHtml = `
<div class="inline-drawer">
<div class="inline-drawer-toggle inline-drawer-header">
<b><i class="fa-solid fa-dice-d20"></i> RPG Companion</b>
<div class="inline-drawer-icon fa-solid fa-circle-chevron-down down"></div>
</div>
<div class="inline-drawer-content">
<label class="checkbox_label" for="rpg-extension-enabled">
<input type="checkbox" id="rpg-extension-enabled" />
<span>Enable RPG Companion</span>
</label>
<small class="notes">Toggle to enable/disable the RPG Companion extension. Configure additional settings within the panel itself.</small>
<div style="margin-top: 10px; display: flex; gap: 10px;">
<a href="https://discord.com/invite/KdAkTg94ME" target="_blank" class="menu_button" style="flex: 1; text-align: center; text-decoration: none;">
<i class="fa-brands fa-discord"></i> Discord
</a>
<a href="https://ko-fi.com/marinara_spaghetti" target="_blank" class="menu_button" style="flex: 1; text-align: center; text-decoration: none;">
<i class="fa-solid fa-heart"></i> Support Creator
</a>
</div>
</div>
</div>
`;
async function addExtensionSettings() {
// Load the HTML template for the settings
const settingsHtml = await renderExtensionTemplateAsync(extensionName, 'settings');
$('#extensions_settings2').append(settingsHtml);
// Set up the enable/disable toggle
$('#rpg-extension-enabled').prop('checked', extensionSettings.enabled).on('change', function() {
$('#rpg-extension-enabled').prop('checked', extensionSettings.enabled).on('change', async function() {
const wasEnabled = extensionSettings.enabled;
extensionSettings.enabled = $(this).prop('checked');
saveSettings();
updatePanelVisibility();
if (!extensionSettings.enabled) {
// Clear extension prompts and thought bubbles when disabled
if (!extensionSettings.enabled && wasEnabled) {
// Disabling extension - remove UI elements
clearExtensionPrompts();
updateChatThoughts(); // This will remove the thought bubble since extension is disabled
} else {
// Re-create thought bubbles when re-enabled
updateChatThoughts(); // This will re-create the thought bubble if data exists
}
updateChatThoughts(); // Remove thought bubbles
cleanupCheckpointUI(); // Remove checkpoint buttons and indicators
// Update Memory Recollection button visibility
updateMemoryRecollectionButton();
// Disable dynamic weather effects
toggleDynamicWeather(false);
// Remove panel and toggle buttons
$('#rpg-companion-panel').remove();
$('#rpg-mobile-toggle').remove();
$('#rpg-collapse-toggle').remove();
$('#rpg-plot-buttons').remove(); // Remove plot buttons
} else if (extensionSettings.enabled && !wasEnabled) {
// Enabling extension - initialize UI
await initUI();
loadChatData(); // Load chat data for current chat
updateChatThoughts(); // Create thought bubbles if data exists
injectCheckpointButton(); // Re-add checkpoint buttons
updateAllCheckpointIndicators(); // Update button states
}
});
// Set up language selector
const langSelect = $('#rpg-companion-language-select');
if (langSelect.length) {
langSelect.val(i18n.currentLanguage);
langSelect.on('change', async function() {
const selectedLanguage = $(this).val();
await i18n.setLanguage(selectedLanguage);
// We need to re-apply translations to the settings panel specifically
i18n.applyTranslations(document.getElementById('extensions_settings2'));
});
}
}
/**
* Initializes the UI for the extension.
*/
async function initUI() {
// Initialize i18n
await i18n.init();
// Only initialize UI if extension is enabled
if (!extensionSettings.enabled) {
// console.log('[RPG Companion] Extension disabled - skipping UI initialization');
return;
}
// Load the HTML template using SillyTavern's template system
const templateHtml = await renderExtensionTemplateAsync(extensionName, 'template');
@@ -213,13 +264,19 @@ async function initUI() {
$('body').append(templateHtml);
// Add mobile toggle button (FAB - Floating Action Button)
const theme = extensionSettings.theme || 'default';
const mobileToggleHtml = `
<button id="rpg-mobile-toggle" class="rpg-mobile-toggle" title="Toggle RPG Panel">
<button id="rpg-mobile-toggle" class="rpg-mobile-toggle" data-theme="${theme}" title="Toggle RPG Panel">
<i class="fa-solid fa-dice-d20"></i>
</button>
`;
$('body').append(mobileToggleHtml);
// Hide mobile toggle on desktop viewport (> 1000px)
if (window.innerWidth > 1000) {
$('#rpg-mobile-toggle').hide();
}
// Cache UI elements using state setters
setPanelContainer($('#rpg-companion-panel'));
setUserStatsContainer($('#rpg-user-stats'));
@@ -227,6 +284,10 @@ async function initUI() {
setThoughtsContainer($('#rpg-thoughts'));
setInventoryContainer($('#rpg-inventory'));
setQuestsContainer($('#rpg-quests'));
setMusicPlayerContainer($('#rpg-music-player'));
// Re-apply translations to the entire body to catch all new elements from the template
i18n.applyTranslations(document.body);
// Set up event listeners (enable/disable is handled in Extensions tab)
$('#rpg-toggle-auto-update').on('change', function() {
@@ -248,23 +309,12 @@ async function initUI() {
saveSettings();
});
$('#rpg-memory-messages').on('change', function() {
const value = $(this).val();
extensionSettings.memoryMessagesToProcess = parseInt(String(value));
saveSettings();
});
$('#rpg-generation-mode').on('change', function() {
$('#rpg-generation-mode').on('change', async function() {
extensionSettings.generationMode = String($(this).val());
saveSettings();
updateGenerationModeUI();
});
$('#rpg-use-separate-preset').on('change', function() {
extensionSettings.useSeparatePreset = $(this).prop('checked');
saveSettings();
});
$('#rpg-toggle-user-stats').on('change', function() {
extensionSettings.showUserStats = $(this).prop('checked');
saveSettings();
@@ -289,6 +339,23 @@ async function initUI() {
updateSectionVisibility();
});
$('#rpg-toggle-quests').on('change', function() {
extensionSettings.showQuests = $(this).prop('checked');
saveSettings();
updateSectionVisibility();
});
$('#rpg-toggle-lock-icons').on('change', function() {
extensionSettings.showLockIcons = $(this).prop('checked');
saveSettings();
// Re-render all sections to show/hide lock icons
renderUserStats();
renderInfoBox();
renderThoughts();
renderInventory();
renderQuests();
});
$('#rpg-toggle-thoughts-in-chat').on('change', function() {
extensionSettings.showThoughtsInChat = $(this).prop('checked');
// console.log('[RPG Companion] Toggle showThoughtsInChat changed to:', extensionSettings.showThoughtsInChat);
@@ -296,30 +363,248 @@ async function initUI() {
updateChatThoughts();
});
$('#rpg-toggle-always-show-bubble').on('change', function() {
extensionSettings.alwaysShowThoughtBubble = $(this).prop('checked');
saveSettings();
// Re-render thoughts to apply the setting
updateChatThoughts();
});
$('#rpg-toggle-html-prompt').on('change', function() {
extensionSettings.enableHtmlPrompt = $(this).prop('checked');
// console.log('[RPG Companion] Toggle enableHtmlPrompt changed to:', extensionSettings.enableHtmlPrompt);
saveSettings();
});
$('#rpg-toggle-plot-buttons').on('change', function() {
extensionSettings.enablePlotButtons = $(this).prop('checked');
// console.log('[RPG Companion] Toggle enablePlotButtons changed to:', extensionSettings.enablePlotButtons);
$('#rpg-toggle-dialogue-coloring').on('change', function() {
extensionSettings.enableDialogueColoring = $(this).prop('checked');
// console.log('[RPG Companion] Toggle enableDialogueColoring changed to:', extensionSettings.enableDialogueColoring);
saveSettings();
});
$('#rpg-toggle-spotify-music').on('change', function() {
extensionSettings.enableSpotifyMusic = $(this).prop('checked');
saveSettings();
updateSectionVisibility();
renderMusicPlayer($musicPlayerContainer[0]);
});
$('#rpg-toggle-dynamic-weather').on('change', function() {
extensionSettings.enableDynamicWeather = $(this).prop('checked');
saveSettings();
toggleDynamicWeather(extensionSettings.enableDynamicWeather);
});
$('#rpg-toggle-narrator').on('change', function() {
extensionSettings.narratorMode = $(this).prop('checked');
saveSettings();
});
$('#rpg-dismiss-promo').on('click', function() {
extensionSettings.dismissedHolidayPromo = true;
saveSettings();
$('#rpg-holiday-promo').fadeOut(300);
});
$('#rpg-skip-guided-mode').on('change', function() {
extensionSettings.skipInjectionsForGuided = String($(this).val());
saveSettings();
});
$('#rpg-save-tracker-history').on('change', function() {
extensionSettings.saveTrackerHistory = $(this).prop('checked');
saveSettings();
});
$('#rpg-toggle-randomized-plot').on('change', function() {
extensionSettings.enableRandomizedPlot = $(this).prop('checked');
saveSettings();
togglePlotButtons();
});
$('#rpg-toggle-animations').on('change', function() {
extensionSettings.enableAnimations = $(this).prop('checked');
$('#rpg-toggle-natural-plot').on('change', function() {
extensionSettings.enableNaturalPlot = $(this).prop('checked');
saveSettings();
toggleAnimations();
togglePlotButtons();
});
$('#rpg-toggle-encounters').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = { enabled: true, historyDepth: 8, autoSaveLogs: true };
}
extensionSettings.encounterSettings.enabled = $(this).prop('checked');
saveSettings();
togglePlotButtons(); // This also controls encounter button visibility
});
$('#rpg-encounter-history-depth').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = { enabled: true, historyDepth: 8, autoSaveLogs: true };
}
const value = $(this).val();
extensionSettings.encounterSettings.historyDepth = parseInt(String(value));
saveSettings();
});
$('#rpg-toggle-autosave-logs').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = { enabled: true, historyDepth: 8, autoSaveLogs: true };
}
extensionSettings.encounterSettings.autoSaveLogs = $(this).prop('checked');
saveSettings();
});
// Combat narrative style settings
$('#rpg-combat-tense').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.combatNarrative) {
extensionSettings.encounterSettings.combatNarrative = {};
}
extensionSettings.encounterSettings.combatNarrative.tense = $(this).val();
saveSettings();
});
$('#rpg-combat-person').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.combatNarrative) {
extensionSettings.encounterSettings.combatNarrative = {};
}
extensionSettings.encounterSettings.combatNarrative.person = $(this).val();
saveSettings();
});
$('#rpg-combat-narration').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.combatNarrative) {
extensionSettings.encounterSettings.combatNarrative = {};
}
extensionSettings.encounterSettings.combatNarrative.narration = $(this).val();
saveSettings();
});
$('#rpg-combat-pov').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.combatNarrative) {
extensionSettings.encounterSettings.combatNarrative = {};
}
extensionSettings.encounterSettings.combatNarrative.pov = $(this).val();
saveSettings();
});
// Summary narrative style settings
$('#rpg-summary-tense').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.summaryNarrative) {
extensionSettings.encounterSettings.summaryNarrative = {};
}
extensionSettings.encounterSettings.summaryNarrative.tense = $(this).val();
saveSettings();
});
$('#rpg-summary-person').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.summaryNarrative) {
extensionSettings.encounterSettings.summaryNarrative = {};
}
extensionSettings.encounterSettings.summaryNarrative.person = $(this).val();
saveSettings();
});
$('#rpg-summary-narration').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.summaryNarrative) {
extensionSettings.encounterSettings.summaryNarrative = {};
}
extensionSettings.encounterSettings.summaryNarrative.narration = $(this).val();
saveSettings();
});
$('#rpg-summary-pov').on('change', function() {
if (!extensionSettings.encounterSettings) {
extensionSettings.encounterSettings = {};
}
if (!extensionSettings.encounterSettings.summaryNarrative) {
extensionSettings.encounterSettings.summaryNarrative = {};
}
extensionSettings.encounterSettings.summaryNarrative.pov = $(this).val();
saveSettings();
});
// Feature toggle visibility controls
$('#rpg-toggle-show-html-toggle').on('change', function() {
extensionSettings.showHtmlToggle = $(this).prop('checked');
saveSettings();
updateFeatureTogglesVisibility();
});
$('#rpg-toggle-show-dialogue-coloring-toggle').on('change', function() {
extensionSettings.showDialogueColoringToggle = $(this).prop('checked');
saveSettings();
updateFeatureTogglesVisibility();
});
$('#rpg-toggle-show-spotify-toggle').on('change', function() {
extensionSettings.showSpotifyToggle = $(this).prop('checked');
saveSettings();
updateFeatureTogglesVisibility();
});
$('#rpg-toggle-show-dynamic-weather-toggle').on('change', function() {
extensionSettings.showDynamicWeatherToggle = $(this).prop('checked');
// Also disable the feature when hiding the toggle
if (!extensionSettings.showDynamicWeatherToggle) {
extensionSettings.enableDynamicWeather = false;
$('#rpg-toggle-dynamic-weather').prop('checked', false);
toggleDynamicWeather(false);
}
saveSettings();
updateFeatureTogglesVisibility();
});
$('#rpg-toggle-show-narrator-mode').on('change', function() {
extensionSettings.showNarratorMode = $(this).prop('checked');
// Also disable the feature when hiding the toggle
if (!extensionSettings.showNarratorMode) {
extensionSettings.narratorMode = false;
$('#rpg-toggle-narrator').prop('checked', false);
}
saveSettings();
updateFeatureTogglesVisibility();
});
$('#rpg-toggle-show-auto-avatars').on('change', function() {
extensionSettings.showAutoAvatars = $(this).prop('checked');
// Also disable the feature when hiding the toggle
if (!extensionSettings.showAutoAvatars) {
extensionSettings.autoGenerateAvatars = false;
$('#rpg-toggle-auto-avatars-panel').prop('checked', false);
}
saveSettings();
updateFeatureTogglesVisibility();
});
// Auto avatar generation panel toggle
$('#rpg-toggle-auto-avatars-panel').on('change', function() {
extensionSettings.autoGenerateAvatars = $(this).prop('checked');
saveSettings();
// Re-render thoughts to update tooltips (regenerate vs delete)
renderThoughts();
});
$('#rpg-toggle-dice-display').on('change', function() {
extensionSettings.showDiceDisplay = $(this).prop('checked');
saveSettings();
updateDiceDisplay();
});
$('#rpg-manual-update').on('click', async function() {
@@ -393,21 +678,152 @@ async function initUI() {
}
});
// External API settings event handlers
$('#rpg-external-base-url').on('change', function() {
if (!extensionSettings.externalApiSettings) {
extensionSettings.externalApiSettings = {
baseUrl: '', apiKey: '', model: '', maxTokens: 8192, temperature: 0.7
};
}
extensionSettings.externalApiSettings.baseUrl = String($(this).val()).trim();
saveSettings();
});
$('#rpg-external-api-key').on('change', function() {
// Securely store API key in localStorage instead of shared extension settings
const apiKey = String($(this).val()).trim();
localStorage.setItem('rpg_companion_external_api_key', apiKey);
// Ensure the externalApiSettings object exists, but don't store the key in it
if (!extensionSettings.externalApiSettings) {
extensionSettings.externalApiSettings = {
baseUrl: '', model: '', maxTokens: 8192, temperature: 0.7
};
saveSettings();
}
});
$('#rpg-external-model').on('change', function() {
if (!extensionSettings.externalApiSettings) {
extensionSettings.externalApiSettings = {
baseUrl: '', apiKey: '', model: '', maxTokens: 8192, temperature: 0.7
};
}
extensionSettings.externalApiSettings.model = String($(this).val()).trim();
saveSettings();
});
$('#rpg-external-max-tokens').on('change', function() {
if (!extensionSettings.externalApiSettings) {
extensionSettings.externalApiSettings = {
baseUrl: '', apiKey: '', model: '', maxTokens: 8192, temperature: 0.7
};
}
extensionSettings.externalApiSettings.maxTokens = parseInt(String($(this).val()));
saveSettings();
});
$('#rpg-external-temperature').on('change', function() {
if (!extensionSettings.externalApiSettings) {
extensionSettings.externalApiSettings = {
baseUrl: '', apiKey: '', model: '', maxTokens: 8192, temperature: 0.7
};
}
extensionSettings.externalApiSettings.temperature = parseFloat(String($(this).val()));
saveSettings();
});
$('#rpg-toggle-api-key-visibility').on('click', function() {
const $input = $('#rpg-external-api-key');
const type = $input.attr('type') === 'password' ? 'text' : 'password';
$input.attr('type', type);
$(this).find('i').toggleClass('fa-eye fa-eye-slash');
});
$('#rpg-test-external-api').on('click', async function() {
const $result = $('#rpg-external-api-test-result');
const $btn = $(this);
const originalText = $btn.html();
$btn.html('<i class="fa-solid fa-spinner fa-spin"></i> Testing...').prop('disabled', true);
$result.hide().removeClass('rpg-success-message rpg-error-message');
try {
const result = await testExternalAPIConnection();
if (result.success) {
$result.addClass('rpg-success-message')
.html(`<i class="fa-solid fa-check-circle"></i> ${result.message}`)
.slideDown();
toastr.success(result.message);
} else {
$result.addClass('rpg-error-message')
.html(`<i class="fa-solid fa-exclamation-circle"></i> ${result.message}`)
.slideDown();
toastr.error(result.message);
}
} catch (error) {
$result.addClass('rpg-error-message')
.html(`<i class="fa-solid fa-exclamation-circle"></i> Error: ${error.message}`)
.slideDown();
} finally {
$btn.html(originalText).prop('disabled', false);
}
});
// Initialize UI state (enable/disable is in Extensions tab)
$('#rpg-toggle-auto-update').prop('checked', extensionSettings.autoUpdate);
$('#rpg-position-select').val(extensionSettings.panelPosition);
$('#rpg-update-depth').val(extensionSettings.updateDepth);
$('#rpg-memory-messages').val(extensionSettings.memoryMessagesToProcess || 16);
$('#rpg-use-separate-preset').prop('checked', extensionSettings.useSeparatePreset);
$('#rpg-toggle-user-stats').prop('checked', extensionSettings.showUserStats);
$('#rpg-toggle-info-box').prop('checked', extensionSettings.showInfoBox);
$('#rpg-toggle-thoughts').prop('checked', extensionSettings.showCharacterThoughts);
$('#rpg-toggle-inventory').prop('checked', extensionSettings.showInventory);
$('#rpg-toggle-quests').prop('checked', extensionSettings.showQuests);
$('#rpg-toggle-lock-icons').prop('checked', extensionSettings.showLockIcons ?? true);
$('#rpg-toggle-thoughts-in-chat').prop('checked', extensionSettings.showThoughtsInChat);
$('#rpg-toggle-always-show-bubble').prop('checked', extensionSettings.alwaysShowThoughtBubble);
$('#rpg-toggle-html-prompt').prop('checked', extensionSettings.enableHtmlPrompt);
$('#rpg-toggle-plot-buttons').prop('checked', extensionSettings.enablePlotButtons);
$('#rpg-toggle-animations').prop('checked', extensionSettings.enableAnimations);
$('#rpg-toggle-dialogue-coloring').prop('checked', extensionSettings.enableDialogueColoring);
$('#rpg-toggle-spotify-music').prop('checked', extensionSettings.enableSpotifyMusic);
$('#rpg-toggle-dynamic-weather').prop('checked', extensionSettings.enableDynamicWeather);
$('#rpg-toggle-narrator').prop('checked', extensionSettings.narratorMode);
// Feature toggle visibility settings
$('#rpg-toggle-show-html-toggle').prop('checked', extensionSettings.showHtmlToggle ?? true);
$('#rpg-toggle-show-dialogue-coloring-toggle').prop('checked', extensionSettings.showDialogueColoringToggle ?? true);
$('#rpg-toggle-show-spotify-toggle').prop('checked', extensionSettings.showSpotifyToggle ?? true);
$('#rpg-toggle-show-dynamic-weather-toggle').prop('checked', extensionSettings.showDynamicWeatherToggle ?? true);
$('#rpg-toggle-show-narrator-mode').prop('checked', extensionSettings.showNarratorMode ?? true);
$('#rpg-toggle-show-auto-avatars').prop('checked', extensionSettings.showAutoAvatars ?? true);
// Hide holiday promo if previously dismissed
if (extensionSettings.dismissedHolidayPromo) {
$('#rpg-holiday-promo').hide();
}
$('#rpg-toggle-randomized-plot').prop('checked', extensionSettings.enableRandomizedPlot ?? true);
$('#rpg-toggle-natural-plot').prop('checked', extensionSettings.enableNaturalPlot ?? true);
$('#rpg-toggle-encounters').prop('checked', extensionSettings.encounterSettings?.enabled ?? true);
$('#rpg-encounter-history-depth').val(extensionSettings.encounterSettings?.historyDepth ?? 8);
$('#rpg-toggle-autosave-logs').prop('checked', extensionSettings.encounterSettings?.autoSaveLogs ?? true);
// Combat narrative style
$('#rpg-combat-tense').val(extensionSettings.encounterSettings?.combatNarrative?.tense ?? 'present');
$('#rpg-combat-person').val(extensionSettings.encounterSettings?.combatNarrative?.person ?? 'third');
$('#rpg-combat-narration').val(extensionSettings.encounterSettings?.combatNarrative?.narration ?? 'omniscient');
$('#rpg-combat-pov').val(extensionSettings.encounterSettings?.combatNarrative?.pov ?? 'narrator');
// Summary narrative style
$('#rpg-summary-tense').val(extensionSettings.encounterSettings?.summaryNarrative?.tense ?? 'past');
$('#rpg-summary-person').val(extensionSettings.encounterSettings?.summaryNarrative?.person ?? 'third');
$('#rpg-summary-narration').val(extensionSettings.encounterSettings?.summaryNarrative?.narration ?? 'omniscient');
$('#rpg-summary-pov').val(extensionSettings.encounterSettings?.summaryNarrative?.pov ?? 'narrator');
// Initialize avatar options (panel toggle)
$('#rpg-toggle-auto-avatars-panel').prop('checked', extensionSettings.autoGenerateAvatars || false);
$('#rpg-toggle-dice-display').prop('checked', extensionSettings.showDiceDisplay);
$('#rpg-stat-bar-color-low').val(extensionSettings.statBarColorLow);
$('#rpg-stat-bar-color-high').val(extensionSettings.statBarColorHigh);
$('#rpg-theme-select').val(extensionSettings.theme);
@@ -415,7 +831,23 @@ async function initUI() {
$('#rpg-custom-accent').val(extensionSettings.customColors.accent);
$('#rpg-custom-text').val(extensionSettings.customColors.text);
$('#rpg-custom-highlight').val(extensionSettings.customColors.highlight);
// Initialize External API settings values
if (extensionSettings.externalApiSettings) {
$('#rpg-external-base-url').val(extensionSettings.externalApiSettings.baseUrl || '');
// Load API Key from secure localStorage
const storedApiKey = localStorage.getItem('rpg_companion_external_api_key') || '';
$('#rpg-external-api-key').val(storedApiKey);
$('#rpg-external-model').val(extensionSettings.externalApiSettings.model || '');
$('#rpg-external-max-tokens').val(extensionSettings.externalApiSettings.maxTokens || 8192);
$('#rpg-external-temperature').val(extensionSettings.externalApiSettings.temperature ?? 0.7);
}
$('#rpg-generation-mode').val(extensionSettings.generationMode);
$('#rpg-skip-guided-mode').val(extensionSettings.skipInjectionsForGuided);
$('#rpg-save-tracker-history').prop('checked', extensionSettings.saveTrackerHistory);
updatePanelVisibility();
updateSectionVisibility();
@@ -424,13 +856,18 @@ async function initUI() {
applyPanelPosition();
toggleCustomColors();
toggleAnimations();
updateFeatureTogglesVisibility();
togglePlotButtons(); // Initialize plot buttons and encounter button visibility
initWeatherEffects(); // Initialize dynamic weather effects
// Setup mobile toggle button
setupMobileToggle();
// Setup desktop tabs (only on desktop viewport)
// Setup tabs based on viewport
if (window.innerWidth > 1000) {
setupDesktopTabs();
} else {
setupMobileTabs();
}
// Setup collapse/expand toggle button
@@ -442,22 +879,28 @@ async function initUI() {
renderThoughts();
renderInventory();
renderQuests();
renderMusicPlayer($musicPlayerContainer[0]);
updateDiceDisplay();
setupDiceRoller();
setupClassicStatsButtons();
setupSettingsPopup();
initTrackerEditor();
initPromptsEditor();
addDiceQuickReply();
setupPlotButtons(sendPlotProgression);
setupPlotButtons(sendPlotProgression, openEncounterModal);
setupMobileKeyboardHandling();
setupContentEditableScrolling();
initInventoryEventListeners();
// Setup Memory Recollection button in World Info
setupMemoryRecollectionButton();
// Initialize chapter checkpoint UI
initChapterCheckpointUI();
injectCheckpointButton();
// Initialize Lorebook Limiter
initLorebookLimiter();
// Expose weather effect functions globally for cross-module access
if (!window.RPGCompanion) {
window.RPGCompanion = {};
}
window.RPGCompanion.updateWeatherEffect = updateWeatherEffect;
}
@@ -472,70 +915,6 @@ async function initUI() {
// (commitTrackerData, onMessageSent, onMessageReceived, onCharacterChanged,
// onMessageSwiped, updatePersonaAvatar, clearExtensionPrompts)
/**
* Ensures the "RPG Companion Trackers" preset exists in the user's OpenAI Settings.
* Imports the preset file from the extension folder if it doesn't exist.
*/
async function ensureTrackerPresetExists() {
try {
const presetName = 'RPG Companion Trackers';
// Check if preset already exists by fetching settings
const checkResponse = await fetch('/api/settings/get', {
method: 'POST',
headers: getRequestHeaders()
});
if (checkResponse.ok) {
const settings = await checkResponse.json();
// openai_setting_names is an array of preset names
if (settings.openai_setting_names && settings.openai_setting_names.includes(presetName)) {
console.log(`[RPG Companion] Preset "${presetName}" already exists`);
return;
}
}
// Preset doesn't exist - import it from extension folder
console.log(`[RPG Companion] Importing preset "${presetName}"...`);
// Load preset from extension folder
const extensionPresetPath = `${extensionFolderPath}/${presetName}.json`;
const presetResponse = await fetch(`/${extensionPresetPath}`);
if (!presetResponse.ok) {
console.warn(`[RPG Companion] Could not load preset template from ${extensionPresetPath}`);
return;
}
const presetData = await presetResponse.json();
// Save preset to user's OpenAI Settings folder using SillyTavern's API
const saveResponse = await fetch('/api/presets/save', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({
apiId: 'openai',
name: presetName,
preset: presetData
})
});
if (saveResponse.ok) {
console.log(`[RPG Companion] ✅ Successfully imported preset "${presetName}"`);
toastr.success(
`The "RPG Companion Trackers" preset has been imported to your OpenAI Settings.`,
'RPG Companion',
{ timeOut: 5000 }
);
} else {
console.warn(`[RPG Companion] Failed to save preset: ${saveResponse.statusText}`);
}
} catch (error) {
console.error('[RPG Companion] Error importing tracker preset:', error);
// Non-critical - users can manually import if needed
}
}
/**
* Main initialization function.
*/
@@ -550,9 +929,29 @@ jQuery(async () => {
console.error('[RPG Companion] Settings load failed, continuing with defaults:', error);
}
// Check if migration to v3 JSON format is needed
try {
if (extensionSettings.settingsVersion < 3) {
// console.log('[RPG Companion] Detected v2 format, migrating to v3 JSON...');
await migrateToV3JSON();
updateExtensionSettings({ settingsVersion: 3 });
await saveSettings();
// console.log('[RPG Companion] ✅ Migration to v3 complete');
}
} catch (error) {
console.error('[RPG Companion] Migration to v3 failed:', error);
// Non-critical - extension can still work with v2 format
}
// Initialize i18n early for the settings panel
await i18n.init();
// Set up a central listener for language changes to update dynamic UI parts
i18n.addEventListener('languageChanged', updateDynamicLabels);
// Add extension settings to Extensions tab
try {
addExtensionSettings();
await addExtensionSettings();
} catch (error) {
console.error('[RPG Companion] Failed to add extension settings tab:', error);
// Don't throw - extension can still work without settings tab
@@ -581,21 +980,30 @@ jQuery(async () => {
// Non-critical - continue without it
}
// Import the RPG Companion Trackers preset if needed
// Import the tracker cleaning regex (removes old together mode JSON from prompts)
try {
await ensureTrackerPresetExists();
await ensureTrackerCleaningRegex(st_extension_settings, saveSettingsDebounced);
} catch (error) {
console.error('[RPG Companion] Preset import failed:', error);
// Non-critical - users can manually import if needed
console.error('[RPG Companion] Tracker cleaning regex import failed:', error);
// Non-critical - continue without it
}
// Import the JSON cleaning regex to clean up JSON in messages
// This cleans historical messages when displayed
try {
await ensureJsonCleaningRegex(st_extension_settings, saveSettingsDebounced);
} catch (error) {
console.error('[RPG Companion] JSON cleaning regex setup failed:', error);
// Non-critical - continue without it
}
// Detect conflicting regex scripts from old manual formatters
try {
const conflicts = detectConflictingRegexScripts(st_extension_settings);
if (conflicts.length > 0) {
console.log('[RPG Companion] ⚠️ Detected old manual formatting regex scripts that may conflict:');
conflicts.forEach(name => console.log(` - ${name}`));
console.log('[RPG Companion] Consider disabling these regexes as the extension now handles formatting automatically.');
// console.log('[RPG Companion] ⚠️ Detected old manual formatting regex scripts that may conflict:');
// conflicts.forEach(name => console.log(` - ${name}`));
// console.log('[RPG Companion] Consider disabling these regexes as the extension now handles formatting automatically.');
// Show user-friendly warning (non-blocking)
// toastr.warning(
@@ -615,7 +1023,9 @@ jQuery(async () => {
[event_types.MESSAGE_SENT]: onMessageSent,
[event_types.GENERATION_STARTED]: onGenerationStarted,
[event_types.MESSAGE_RECEIVED]: onMessageReceived,
[event_types.CHAT_CHANGED]: [onCharacterChanged, updatePersonaAvatar],
[event_types.GENERATION_STOPPED]: onGenerationEnded,
[event_types.GENERATION_ENDED]: onGenerationEnded,
[event_types.CHAT_CHANGED]: [onCharacterChanged, updatePersonaAvatar, restoreCheckpointOnLoad, clearSessionAvatarPrompts],
[event_types.MESSAGE_SWIPED]: onMessageSwiped,
[event_types.USER_MESSAGE_RENDERED]: updatePersonaAvatar,
[event_types.SETTINGS_UPDATED]: updatePersonaAvatar
@@ -625,7 +1035,26 @@ jQuery(async () => {
throw error; // This is critical - can't continue without events
}
console.log('[RPG Companion] ✅ Extension loaded successfully');
// Restore checkpoint state if one exists
await restoreCheckpointOnLoad();
// Initialize snowflakes effect if enabled
try {
initSnowflakes();
} catch (error) {
console.error('[RPG Companion] Snowflakes initialization failed:', error);
// Non-critical - continue without it
}
// Show welcome modal for v3.0 on first launch
try {
showWelcomeModalIfNeeded();
} catch (error) {
console.error('[RPG Companion] Welcome modal failed:', error);
// Non-critical - continue without it
}
console.log('[RPG Companion] ✅ Extension loaded successfully.');
} catch (error) {
console.error('[RPG Companion] ❌ Critical initialization failure:', error);
console.error('[RPG Companion] Error details:', error.message, error.stack);
+2 -2
View File
@@ -5,7 +5,7 @@
"optional": [],
"js": "index.js",
"css": "style.css",
"author": "Marysia",
"version": "1.1.0",
"author": "Marinara",
"version": "3.3.0",
"homePage": "https://github.com/SpicyMarinara/rpg-companion-sillytavern"
}
+35 -4
View File
@@ -7,18 +7,49 @@
<div class="inline-drawer-content">
<label class="checkbox_label" for="rpg-extension-enabled">
<input type="checkbox" id="rpg-extension-enabled" />
<span>Enable RPG Companion</span>
<span data-i18n-key="settings.extensionEnabled">Enable RPG Companion</span>
</label>
<small class="notes">Toggle to enable/disable the RPG Companion extension. Configure additional settings within the panel itself.</small>
<div class="form-group" style="margin-top: 10px;">
<label for="rpg-companion-language-select" data-i18n-key="settings.language.label">Language</label>
<select id="rpg-companion-language-select" class="text_pole">
<option value="en" data-i18n-key="settings.language.option.en">English</option>
<option value="zh-tw" data-i18n-key="settings.language.option.zh-tw">繁體中文</option>
</select>
</div>
<small class="notes" data-i18n-key="settings.note">Toggle to enable/disable the RPG Companion extension. Configure additional settings within the panel itself.</small>
<div style="margin-top: 10px; display: flex; gap: 10px;">
<a href="https://discord.com/invite/KdAkTg94ME" target="_blank" class="menu_button" style="flex: 1; text-align: center; text-decoration: none;">
<i class="fa-brands fa-discord"></i> Discord
<i class="fa-brands fa-discord"></i>&nbsp;Discord
</a>
<a href="https://ko-fi.com/marinara_spaghetti" target="_blank" class="menu_button" style="flex: 1; text-align: center; text-decoration: none;">
<i class="fa-solid fa-heart"></i> Support Creator
<i class="fa-solid fa-heart"></i>&nbsp;Support
</a>
</div>
<div style="margin-top: 15px; text-align: center; opacity: 0.7; font-size: 0.8em; line-height: 1.5;">
<div style="margin-bottom: 5px;">
<i class="fa-solid fa-microchip"></i> <strong data-i18n="settings.recommendedModels.title">Recommended Models:</strong>
</div>
<div style="opacity: 0.8; font-size: 0.9em;" data-i18n="settings.recommendedModels.description">
For the extension to work properly, <strong>it is not recommended to use any models below 20B, especially if they're old.</strong> It works best with the SOTA models such as Deepseek, Claude, GPT, or Gemini.
</div>
</div>
<div style="margin-top: 15px; text-align: center; opacity: 0.7; font-size: 0.8em; line-height: 1.5;">
<div style="margin-bottom: 5px;">
<i class="fa-solid fa-users"></i> <strong>Contributors:</strong>
</div>
<div style="opacity: 0.8; font-size: 0.9em;">
SpicyMarinara, Paperboygold, Munimunigamer, Subarashimo, Lilminzyu, Claude, IDeathByte, Chungchandev, Joenunezb, and Amauragis.
</div>
</div>
<div style="margin-top: 10px; text-align: center; opacity: 0.6; font-size: 0.85em;">
v3.2.6
</div>
</div>
</div>
</div>
+13 -5
View File
@@ -26,15 +26,25 @@ export const defaultSettings = {
autoUpdate: true,
updateDepth: 4, // How many messages to include in the context
generationMode: 'together', // 'separate' or 'together' - whether to generate with main response or separately
useSeparatePreset: false, // Use 'RPG Companion Trackers' preset for tracker generation instead of main API model
showUserStats: true,
showInfoBox: true,
showCharacterThoughts: true,
showInventory: true, // Show inventory section (v2 system)
showQuests: true, // Show quests section
showLockIcons: true, // Show lock/unlock icons on tracker items
showThoughtsInChat: true, // Show thoughts overlay in chat
alwaysShowThoughtBubble: false, // Auto-expand thought bubble without clicking icon
enableHtmlPrompt: false, // Enable immersive HTML prompt injection
enableSpotifyMusic: false, // Enable Spotify music integration (asks AI for Spotify URLs)
customSpotifyPrompt: '', // Custom Spotify prompt text (empty = use default)
// Controls when the extension skips injecting tracker instructions/examples/HTML
// into generations that appear to be user-injected instructions. Valid values:
// - 'none' -> never skip (legacy behavior: always inject)
// - 'guided' -> skip for any guided / instruct or quiet_prompt generation
// - 'impersonation' -> skip only for impersonation-style guided generations
// This setting helps compatibility with other extensions like GuidedGenerations.
skipInjectionsForGuided: 'none',
enablePlotButtons: true, // Show plot progression buttons above chat input
saveTrackerHistory: false, // Save tracker data in chat history for each message
panelPosition: 'right', // 'left', 'right', or 'top'
theme: 'default', // Theme: default, sci-fi, fantasy, cyberpunk, custom
customColors: {
@@ -75,7 +85,5 @@ export const defaultSettings = {
cha: 10
},
lastDiceRoll: null, // Store last dice roll result
collapsedInventoryLocations: [], // Array of collapsed storage location names
debugMode: false, // Enable debug logging visible in UI (for mobile debugging)
memoryMessagesToProcess: 16 // Number of messages to process per batch in memory recollection
collapsedInventoryLocations: [] // Array of collapsed storage location names
};
+103
View File
@@ -0,0 +1,103 @@
//- No-op in case this is running outside of SillyTavern
const { extension_settings } = typeof self.SillyTavern !== 'undefined' ? self.SillyTavern.getContext() : { extension_settings: {} };
class Internationalization {
constructor() {
this.currentLanguage = 'en';
this.translations = {};
this._listeners = {};
}
addEventListener(event, callback) {
if (!this._listeners[event]) {
this._listeners[event] = [];
}
this._listeners[event].push(callback);
}
dispatchEvent(event, data) {
if (this._listeners[event]) {
this._listeners[event].forEach(callback => callback(data));
}
}
async init() {
const savedLanguage = localStorage.getItem('rpgCompanionLanguage') || 'en';
this.currentLanguage = savedLanguage;
await this.loadTranslations(this.currentLanguage);
this.applyTranslations(document.body);
const langSelect = document.getElementById('rpg-companion-language-select');
if (langSelect) {
langSelect.value = this.currentLanguage;
}
}
async loadTranslations(lang) {
const fetchUrl = `/scripts/extensions/third-party/rpg-companion-sillytavern/src/i18n/${lang}.json`;
try {
const response = await fetch(fetchUrl);
if (!response.ok) {
console.error(`[RPG-Companion-i18n] Failed to load translation file for ${lang}. Status: ${response.status}`);
if (lang !== 'en') {
return this.loadTranslations('en');
}
return;
}
this.translations = await response.json();
} catch (error) {
console.error('[RPG-Companion-i18n] CRITICAL error loading translation file:', error);
}
}
applyTranslations(rootElement) {
if (!rootElement) {
return;
}
// 1. Translate textContent
const textElements = rootElement.querySelectorAll('[data-i18n-key]');
textElements.forEach(element => {
const key = element.dataset.i18nKey;
const translation = this.getTranslation(key);
if (translation) {
element.textContent = translation;
}
});
// 2. Translate title attribute
const titleElements = rootElement.querySelectorAll('[data-i18n-title]');
titleElements.forEach(element => {
const key = element.dataset.i18nTitle;
const translation = this.getTranslation(key);
if (translation) {
element.setAttribute('title', translation);
}
});
// 3. Translate aria-label attribute
const ariaLabelElements = rootElement.querySelectorAll('[data-i18n-aria-label]');
ariaLabelElements.forEach(element => {
const key = element.dataset.i18nAriaLabel;
const translation = this.getTranslation(key);
if (translation) {
element.setAttribute('aria-label', translation);
}
});
}
getTranslation(key) {
return this.translations[key] || null;
}
async setLanguage(lang) {
this.currentLanguage = lang;
localStorage.setItem('rpgCompanionLanguage', lang);
await this.loadTranslations(lang);
this.applyTranslations(document.body);
this.dispatchEvent('languageChanged');
}
}
export const i18n = new Internationalization();
+83 -14
View File
@@ -17,6 +17,7 @@ import {
} from './state.js';
import { migrateInventory } from '../utils/migration.js';
import { validateStoredInventory, cleanItemString } from '../utils/security.js';
import { migrateToV3JSON } from '../utils/jsonMigration.js';
const extensionName = 'third-party/rpg-companion-sillytavern';
@@ -78,6 +79,32 @@ export function loadSettings() {
}
updateExtensionSettings(savedSettings);
// Perform settings migrations based on version
const currentVersion = extensionSettings.settingsVersion || 1;
let settingsChanged = false;
// Migration to version 2: Enable dynamic weather for existing users
if (currentVersion < 2) {
// console.log('[RPG Companion] Migrating settings to version 2 (enabling dynamic weather)');
extensionSettings.enableDynamicWeather = true;
extensionSettings.settingsVersion = 2;
settingsChanged = true;
}
// Migration to version 3: Convert text trackers to JSON format
if (currentVersion < 3) {
// console.log('[RPG Companion] Migrating settings to version 3 (JSON tracker format)');
migrateToV3JSON();
extensionSettings.settingsVersion = 3;
settingsChanged = true;
}
// Save migrated settings
if (settingsChanged) {
saveSettings();
}
// console.log('[RPG Companion] Settings loaded:', extensionSettings);
} else {
// console.log('[RPG Companion] No saved settings found, using defaults');
@@ -87,7 +114,7 @@ export function loadSettings() {
if (FEATURE_FLAGS.useNewInventory) {
const migrationResult = migrateInventory(extensionSettings.userStats.inventory);
if (migrationResult.migrated) {
console.log(`[RPG Companion] Inventory migrated from ${migrationResult.source} to v2 format`);
// console.log(`[RPG Companion] Inventory migrated from ${migrationResult.source} to v2 format`);
extensionSettings.userStats.inventory = migrationResult.inventory;
saveSettings(); // Persist migrated inventory
}
@@ -95,7 +122,7 @@ export function loadSettings() {
// Migrate to trackerConfig if it doesn't exist
if (!extensionSettings.trackerConfig) {
console.log('[RPG Companion] Migrating to trackerConfig format');
// console.log('[RPG Companion] Migrating to trackerConfig format');
migrateToTrackerConfig();
saveSettings(); // Persist migration
}
@@ -134,6 +161,14 @@ export function saveChatData() {
return;
}
// console.log('[RPG Companion] 💾 saveChatData called - committedTrackerData:', {
// userStats: committedTrackerData.userStats ? `${committedTrackerData.userStats.substring(0, 50)}...` : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// });
// console.log('[RPG Companion] 💾 saveChatData RAW committedTrackerData:', committedTrackerData);
// console.log('[RPG Companion] 💾 saveChatData RAW lastGeneratedData:', lastGeneratedData);
chat_metadata.rpg_companion = {
userStats: extensionSettings.userStats,
classicStats: extensionSettings.classicStats,
@@ -204,6 +239,10 @@ export function loadChatData() {
stored: {},
assets: "None"
}
},
quests: {
main: "None",
optional: []
}
});
setLastGeneratedData({
@@ -243,21 +282,36 @@ export function loadChatData() {
};
}
// Restore last generated data
if (savedData.lastGeneratedData) {
setLastGeneratedData({ ...savedData.lastGeneratedData });
// Restore committed tracker data first
if (savedData.committedTrackerData) {
// console.log('[RPG Companion] 📥 loadChatData restoring committedTrackerData:', {
// userStats: savedData.committedTrackerData.userStats ? `${savedData.committedTrackerData.userStats.substring(0, 50)}...` : 'null',
// infoBox: savedData.committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: savedData.committedTrackerData.characterThoughts ? 'exists' : 'null'
// });
// console.log('[RPG Companion] 📥 RAW savedData.committedTrackerData:', savedData.committedTrackerData);
// console.log('[RPG Companion] 📥 Type check:', {
// userStatsType: typeof savedData.committedTrackerData.userStats,
// infoBoxType: typeof savedData.committedTrackerData.infoBox,
// characterThoughtsType: typeof savedData.committedTrackerData.characterThoughts
// });
setCommittedTrackerData({ ...savedData.committedTrackerData });
}
// Restore committed tracker data
if (savedData.committedTrackerData) {
setCommittedTrackerData({ ...savedData.committedTrackerData });
// Restore last generated data (for display)
// Always prefer lastGeneratedData as it contains the most recent generation (including swipes)
if (savedData.lastGeneratedData) {
// console.log('[RPG Companion] 📥 loadChatData restoring lastGeneratedData');
setLastGeneratedData({ ...savedData.lastGeneratedData });
} else {
// console.log('[RPG Companion] ⚠️ No lastGeneratedData found in save');
}
// Migrate inventory in chat data if feature flag enabled
if (FEATURE_FLAGS.useNewInventory && extensionSettings.userStats.inventory) {
const migrationResult = migrateInventory(extensionSettings.userStats.inventory);
if (migrationResult.migrated) {
console.log(`[RPG Companion] Chat inventory migrated from ${migrationResult.source} to v2 format`);
// console.log(`[RPG Companion] Chat inventory migrated from ${migrationResult.source} to v2 format`);
extensionSettings.userStats.inventory = migrationResult.inventory;
saveChatData(); // Persist migrated inventory to chat metadata
}
@@ -347,7 +401,7 @@ function validateInventoryStructure(inventory, source) {
// Persist repairs if needed
if (needsSave) {
console.log(`[RPG Companion] Repaired inventory structure from ${source}, saving...`);
// console.log(`[RPG Companion] Repaired inventory structure from ${source}, saving...`);
saveSettings();
if (source === 'chat') {
saveChatData();
@@ -419,7 +473,7 @@ function migrateToTrackerConfig() {
name: extensionSettings.statNames[id] || id.charAt(0).toUpperCase() + id.slice(1),
enabled: true
}));
console.log('[RPG Companion] Migrated statNames to customStats array');
// console.log('[RPG Companion] Migrated statNames to customStats array');
}
// Ensure all stats have corresponding values in userStats
@@ -443,7 +497,7 @@ function migrateToTrackerConfig() {
{ id: 'cha', name: 'CHA', enabled: shouldShow }
];
delete extensionSettings.trackerConfig.userStats.showRPGAttributes;
console.log('[RPG Companion] Migrated showRPGAttributes to rpgAttributes array');
// console.log('[RPG Companion] Migrated showRPGAttributes to rpgAttributes array');
}
// Ensure rpgAttributes exists even if no migration was needed
@@ -481,7 +535,7 @@ function migrateToTrackerConfig() {
const hasOldFormat = pc.customFields.some(f => f.label || f.placeholder || f.type === 'relationship');
if (hasOldFormat) {
console.log('[RPG Companion] Migrating Present Characters to new structure');
// console.log('[RPG Companion] Migrating Present Characters to new structure');
// Extract relationship fields from old customFields
const relationshipFields = ['Lover', 'Friend', 'Ally', 'Enemy', 'Neutral'];
@@ -509,7 +563,7 @@ function migrateToTrackerConfig() {
pc.customFields = newCustomFields;
pc.thoughts = thoughts;
console.log('[RPG Companion] Present Characters migration complete');
// console.log('[RPG Companion] Present Characters migration complete');
saveSettings(); // Persist the migration
}
}
@@ -528,6 +582,21 @@ function migrateToTrackerConfig() {
'Neutral': '⚖️'
};
}
// Migrate to new relationships structure if not already present
if (!pc.relationships) {
pc.relationships = {
enabled: true, // Default to enabled for backward compatibility
relationshipEmojis: pc.relationshipEmojis || {
'Lover': '❤️',
'Friend': '⭐',
'Ally': '🤝',
'Enemy': '⚔️',
'Neutral': '⚖️'
}
};
}
if (!pc.thoughts) {
pc.thoughts = {
enabled: true,
+150 -22
View File
@@ -10,18 +10,39 @@
* Extension settings - persisted to SillyTavern settings
*/
export let extensionSettings = {
settingsVersion: 3, // Version number for settings migrations (v3 = JSON format)
enabled: true,
autoUpdate: true,
autoUpdate: false,
updateDepth: 4, // How many messages to include in the context
generationMode: 'together', // 'separate' or 'together' - whether to generate with main response or separately
useSeparatePreset: false, // Use 'RPG Companion Trackers' preset for tracker generation instead of main API model
showUserStats: true,
showInfoBox: true,
showCharacterThoughts: true,
showInventory: true, // Show inventory section (v2 system)
showQuests: true, // Show quests section
showThoughtsInChat: true, // Show thoughts overlay in chat
narratorMode: false, // Use character card as narrator instead of fixed character references
customNarratorPrompt: '', // Custom narrator mode prompt text (empty = use default)
enableHtmlPrompt: false, // Enable immersive HTML prompt injection
enablePlotButtons: true, // Show plot progression buttons above chat input
customHtmlPrompt: '', // Custom HTML prompt text (empty = use default)
enableDialogueColoring: false, // Enable dialogue coloring prompt injection
customDialogueColoringPrompt: '', // Custom dialogue coloring prompt text (empty = use default)
enableSpotifyMusic: false, // Enable Spotify music integration (asks AI for Spotify URLs)
customSpotifyPrompt: '', // Custom Spotify prompt text (empty = use default)
enableDynamicWeather: true, // Enable dynamic weather effects based on Info Box weather field (v2: enabled by default)
dismissedHolidayPromo: false, // User dismissed the holiday promotion banner
showHtmlToggle: true, // Show Immersive HTML toggle in main panel
showDialogueColoringToggle: true, // Show Dialogue Coloring toggle in main panel (enabled by default)
showSpotifyToggle: true, // Show Spotify Music toggle in main panel
showDynamicWeatherToggle: true, // Show Dynamic Weather Effects toggle in main panel
showNarratorMode: true, // Show Narrator Mode toggle in main panel
showAutoAvatars: true, // Show Auto-generate Avatars toggle in main panel
skipInjectionsForGuided: 'none', // skip injections for instruct injections and quiet prompts (GuidedGenerations compatibility)
enableRandomizedPlot: true, // Show randomized plot progression button above chat input
enableNaturalPlot: true, // Show natural plot progression button above chat input
saveTrackerHistory: false, // Save tracker data in chat history for each message
panelPosition: 'right', // 'left', 'right', or 'top'
theme: 'default', // Theme: default, sci-fi, fantasy, cyberpunk, custom
customColors: {
@@ -37,22 +58,27 @@ export let extensionSettings = {
top: 'calc(var(--topBarBlockSize) + 60px)',
right: '12px'
}, // Saved position for mobile FAB button
userStats: {
health: 100,
satiety: 100,
energy: 100,
hygiene: 100,
arousal: 0,
mood: '😐',
conditions: 'None',
/** @type {InventoryV2} */
userStats: JSON.stringify({
stats: [
{ id: 'health', name: 'Health', value: 100 },
{ id: 'satiety', name: 'Satiety', value: 100 },
{ id: 'energy', name: 'Energy', value: 100 },
{ id: 'hygiene', name: 'Hygiene', value: 100 },
{ id: 'arousal', name: 'Arousal', value: 0 }
],
status: {
mood: '😐',
conditions: 'None'
},
inventory: {
version: 2,
onPerson: "None",
stored: {},
assets: "None"
onPerson: [],
stored: []
},
quests: {
active: [],
completed: []
}
},
}, null, 2),
statNames: {
health: 'Health',
satiety: 'Satiety',
@@ -73,6 +99,8 @@ export let extensionSettings = {
],
// RPG Attributes (customizable D&D-style attributes)
showRPGAttributes: true,
showLevel: true, // Show/hide level in UI and prompts
alwaysSendAttributes: false, // If true, always send attributes; if false, only send with dice rolls
rpgAttributes: [
{ id: 'str', name: 'STR', enabled: true },
{ id: 'dex', name: 'DEX', enabled: true },
@@ -90,7 +118,8 @@ export let extensionSettings = {
// Optional skills field
skillsSection: {
enabled: false,
label: 'Skills' // User-editable
label: 'Skills', // User-editable
customFields: [] // Array of skill names
}
},
infoBox: {
@@ -107,9 +136,20 @@ export let extensionSettings = {
// Fixed fields (always shown)
showEmoji: true,
showName: true,
// Relationship fields (shown after name, separated by /)
// Relationship fields configuration
relationships: {
enabled: true,
// Relationship to emoji mapping (shown on character portraits)
relationshipEmojis: {
'Lover': '❤️',
'Friend': '⭐',
'Ally': '🤝',
'Enemy': '⚔️',
'Neutral': '⚖️'
}
},
// Legacy fields kept for backward compatibility
relationshipFields: ['Lover', 'Friend', 'Ally', 'Enemy', 'Neutral'],
// Relationship to emoji mapping (shown on character portraits)
relationshipEmojis: {
'Lover': '❤️',
'Friend': '⭐',
@@ -142,6 +182,16 @@ export let extensionSettings = {
main: "None", // Current main quest title
optional: [] // Array of optional quest titles
},
infoBox: JSON.stringify({
date: { value: new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) },
weather: { emoji: '☀️', forecast: 'Clear skies' },
temperature: { value: 20, unit: 'C' },
time: { start: '00:00', end: '00:00' },
location: { value: 'Unknown Location' }
}, null, 2),
characterThoughts: JSON.stringify({
characters: []
}, null, 2),
level: 1, // User's character level
classicStats: {
str: 10,
@@ -152,14 +202,55 @@ export let extensionSettings = {
cha: 10
},
lastDiceRoll: null, // Store last dice roll result
showDiceDisplay: true, // Show the "Last Roll" display in the panel
collapsedInventoryLocations: [], // Array of collapsed storage location names
inventoryViewModes: {
onPerson: 'list', // 'list' or 'grid' view mode for On Person section
stored: 'list', // 'list' or 'grid' view mode for Stored section
assets: 'list' // 'list' or 'grid' view mode for Assets section
},
debugMode: false, // Enable debug logging visible in UI (for mobile debugging)
memoryMessagesToProcess: 16 // Number of messages to process per batch in memory recollection
npcAvatars: {}, // Store custom avatar images for NPCs (key: character name, value: base64 data URI)
// Combat encounter settings
encounterSettings: {
enabled: true, // Show Start Encounter button above chat input
historyDepth: 8, // Number of recent messages to include in combat initialization
autoSaveLogs: false // Save detailed combat logs to file
},
// Auto avatar generation settings
autoGenerateAvatars: true, // Master toggle for auto-generating avatars
avatarLLMCustomInstruction: '', // Custom instruction for LLM prompt generation
// External API settings for 'external' generation mode
externalApiSettings: {
baseUrl: '', // OpenAI-compatible API base URL (e.g., "https://api.openai.com/v1")
// apiKey is NOT stored here for security. It is stored in localStorage('rpg_companion_api_key')
model: '', // Model identifier (e.g., "gpt-4o-mini")
maxTokens: 8192, // Maximum tokens for generation
temperature: 0.7 // Temperature setting for generation
},
// Lock state for tracker items (v3 JSON format feature)
lockedItems: {
stats: [], // Array of locked stat IDs (e.g., ["health", "satiety"])
skills: [], // Array of locked skill names (e.g., ["Cooking", "Swordsmanship"])
inventory: {
onPerson: [], // Array of locked item indices (e.g., [0, 2])
clothing: [], // Array of locked item indices
stored: {}, // Object with location keys, each containing array of locked indices (e.g., {"Home": [0, 1]})
assets: [] // Array of locked asset indices
},
quests: {
main: false, // Boolean for main quest lock
optional: [] // Array of locked optional quest indices (e.g., [0, 2])
},
infoBox: {
date: false, // Boolean for date widget lock
weather: false, // Boolean for weather widget lock
temperature: false, // Boolean for temperature widget lock
time: false, // Boolean for time widget lock
location: false, // Boolean for location widget lock
recentEvents: false // Boolean for recent events widget lock
},
characters: {} // Object mapping character names to their locked fields (e.g., {"Sarah": {relationship: true, thoughts: false}})
}
};
/**
@@ -182,6 +273,25 @@ export let committedTrackerData = {
characterThoughts: null
};
/**
* Session-only storage for LLM-generated avatar prompts
* Maps character names to their generated prompts
* Resets on new chat (not persisted to extensionSettings)
*/
export let sessionAvatarPrompts = {};
export function setSessionAvatarPrompt(characterName, prompt) {
sessionAvatarPrompts[characterName] = prompt;
}
export function getSessionAvatarPrompt(characterName) {
return sessionAvatarPrompts[characterName] || null;
}
export function clearSessionAvatarPrompts() {
sessionAvatarPrompts = {};
}
/**
* Tracks whether the last action was a swipe (for separate mode)
* Used to determine whether to commit lastGeneratedData to committedTrackerData
@@ -244,6 +354,7 @@ export let $infoBoxContainer = null;
export let $thoughtsContainer = null;
export let $inventoryContainer = null;
export let $questsContainer = null;
export let $musicPlayerContainer = null;
/**
* State setters - provide controlled mutation of state variables
@@ -265,11 +376,24 @@ export function updateLastGeneratedData(updates) {
}
export function setCommittedTrackerData(data) {
// console.log('[RPG State] setCommittedTrackerData called with:', data);
// console.log('[RPG State] Type check on input:', {
// userStatsType: typeof data.userStats,
// infoBoxType: typeof data.infoBox,
// characterThoughtsType: typeof data.characterThoughts,
// userStatsValue: data.userStats,
// infoBoxValue: data.infoBox,
// characterThoughtsValue: data.characterThoughts
// });
committedTrackerData = data;
// console.log('[RPG State] committedTrackerData after assignment:', committedTrackerData);
}
export function updateCommittedTrackerData(updates) {
// console.log('[RPG State] updateCommittedTrackerData called with:', updates);
// console.log('[RPG State] committedTrackerData before update:', committedTrackerData);
Object.assign(committedTrackerData, updates);
// console.log('[RPG State] committedTrackerData after update:', committedTrackerData);
}
export function setLastActionWasSwipe(value) {
@@ -315,3 +439,7 @@ export function setInventoryContainer($element) {
export function setQuestsContainer($element) {
$questsContainer = $element;
}
export function setMusicPlayerContainer($element) {
$musicPlayerContainer = $element;
}
+237
View File
@@ -0,0 +1,237 @@
{
"settings.language.label": "Language",
"settings.language.option.en": "English",
"settings.language.option.zh-tw": "繁體中文",
"settings.extensionEnabled": "Enable RPG Companion",
"settings.note": "Toggle to enable/disable the RPG Companion extension. Configure additional settings within the panel itself.",
"template.settingsTitle": "RPG Companion Settings",
"template.settingsModal.themeTitle": "Theme",
"template.settingsModal.themeLabel": "Visual Theme:",
"template.settingsModal.themeOptions.default": "Default",
"template.settingsModal.themeOptions.sciFi": "Sci-Fi (Synthwave)",
"template.settingsModal.themeOptions.fantasy": "Fantasy (Rustic Parchment)",
"template.settingsModal.themeOptions.cyberpunk": "Cyberpunk (Neon Grid)",
"template.settingsModal.themeOptions.custom": "Custom",
"template.settingsModal.themeOptions.custom.background": "Background:",
"template.settingsModal.themeOptions.custom.accent": "Accent:",
"template.settingsModal.themeOptions.custom.text": "Text:",
"template.settingsModal.themeOptions.custom.highlight": "Highlight:",
"template.settingsModal.theme.statBarLow": "Stat Bar Color (Low):",
"template.settingsModal.theme.statBarLowNote": "Color when stats are at 0%.",
"template.settingsModal.theme.statBarHigh": "Stat Bar Color (High):",
"template.settingsModal.theme.statBarHighNote": "Color when stats are at 100%.",
"template.settingsModal.displayTitle": "Display Options",
"template.settingsModal.displayNote": "You can enable/disable the entire RPG Companion extension in the Extensions tab of the SillyTavern.",
"template.settingsModal.display.panelPosition": "Panel Position:",
"template.settingsModal.display.panelPositionOptions.right": "Right Sidebar",
"template.settingsModal.display.panelPositionOptions.left": "Left Sidebar",
"template.settingsModal.display.toggleAutoUpdate": "Auto-update after messages",
"template.settingsModal.display.showUserStats": "Show User Stats",
"template.settingsModal.display.showUserStats": "Show User Stats",
"template.settingsModal.display.showUserStatsNote": "Enable User Stats that track your persona's statistics, mood, attributes, skills, etc.",
"template.settingsModal.display.showInfoBox": "Show Info Box",
"template.settingsModal.display.showInfoBoxNote": "Display location, time, weather, and recent events.",
"template.settingsModal.display.showPresentCharacters": "Show Present Characters",
"template.settingsModal.display.showPresentCharactersNote": "Display character portraits with their current thoughts and status.",
"template.settingsModal.display.toggleAutoUpdate": "Auto-update after messages",
"template.settingsModal.display.toggleAutoUpdateNote": "Automatically refresh RPG info after each message.",
"template.settingsModal.display.narratorMode": "Narrator Mode",
"template.settingsModal.display.narratorModeNote": "Use character card as narrator. Infer characters from context instead of using fixed character references.",
"template.settingsModal.display.showInventory": "Show Inventory",
"template.settingsModal.display.showInventoryNote": "Track items carried, clothing worn, stored items, and assets.",
"template.settingsModal.display.showQuests": "Show Quests",
"template.settingsModal.display.showQuestsNote": "Manage main and optional quests with objectives.",
"template.settingsModal.display.showLockIcons": "Show Locking/Unlocking Trackers",
"template.settingsModal.display.showLockIconsNote": "Display lock/unlock icons on tracker items to prevent AI from modifying them.",
"template.settingsModal.display.showThoughtsInChat": "Show Thoughts",
"template.settingsModal.display.showThoughtsInChatNote": "Display character thoughts as overlay bubbles next to their messages.",
"template.settingsModal.display.alwaysShowThoughtBubble": "Always Show Thought Bubble",
"template.settingsModal.display.alwaysShowThoughtBubbleNote": "Auto-expand thought bubble without clicking the icon first",
"template.settingsModal.display.enableAnimations": "Enable Animations",
"template.settingsModal.display.enableAnimationsNote": "Smooth transitions for stats, content updates, and dice rolls.",
"template.settingsModal.display.showImmersiveHtmlToggle": "Show Immersive HTML",
"template.settingsModal.display.showImmersiveHtmlToggleNote": "Display a toggle button to enable/disable HTML formatting in messages.",
"template.settingsModal.display.showDialogueColoringToggle": "Show Colored Dialogues",
"template.settingsModal.display.showDialogueColoringToggleNote": "Display a toggle button to enable/disable colored dialogue formatting.",
"template.settingsModal.display.showSpotifyMusicToggle": "Show Spotify Music",
"template.settingsModal.display.showSpotifyMusicToggleNote": "Display Spotify music player with AI-suggested scene-appropriate tracks.",
"template.settingsModal.display.showSnowflakesToggle": "Show Snowflakes Effect",
"template.settingsModal.display.showDynamicWeatherToggle": "Show Dynamic Weather Effects",
"template.settingsModal.display.showDynamicWeatherToggleNote": "Display a toggle button to enable/disable animated weather effects.",
"template.settingsModal.display.showNarratorMode": "Show Narrator Mode",
"template.settingsModal.display.showNarratorModeNote": "Display a toggle button to enable/disable narrator mode (infer characters from context).",
"template.settingsModal.display.showAutoAvatars": "Show Auto-generate Avatars",
"template.settingsModal.display.showAutoAvatarsNote": "Display a toggle button to automatically generate avatars for characters without images.",
"template.settingsModal.display.showRandomizedPlot": "Show Randomized Plot Progression",
"template.settingsModal.display.showRandomizedPlotNote": "Display button for AI-generated random plot progression prompts.",
"template.settingsModal.display.showNaturalPlot": "Show Natural Plot Progression",
"template.settingsModal.display.showNaturalPlotNote": "Display button for context-aware narrative continuation prompts.",
"template.settingsModal.display.showStartEncounter": "Show Start Encounter",
"template.settingsModal.display.showStartEncounterNote": "Display button to initiate interactive combat encounters.",
"template.settingsModal.display.showDiceDisplay": "Show Dice Roll Display",
"template.settingsModal.display.showDiceDisplayNote": "Display the \"Last Roll\" indicator in the panel.",
"template.mainPanel.autoAvatars": "Auto Avatars",
"template.settingsModal.advancedTitle": "Advanced",
"template.settingsModal.advanced.encounterHistoryDepth": "Chat History Depth For Encounters:",
"template.settingsModal.advanced.encounterHistoryDepthNote": "Number of recent messages to include in combat initialization.",
"template.settingsModal.advanced.autoSaveCombatLogs": "Auto-save Combat Logs",
"template.settingsModal.advanced.autoSaveCombatLogsNote": "Save detailed combat logs to file for future reference and analysis.",
"template.settingsModal.advanced.clearCacheNote": "Clears all cached data including tracker history and temporary files.",
"template.settingsModal.advanced.generationMode": "Generation Mode:",
"template.settingsModal.advanced.generationModeOptions.together": "Together with Main Generation",
"template.settingsModal.advanced.generationModeOptions.separate": "Separate Generation",
"template.settingsModal.advanced.generationModeNote": "Together: Adds RPG tracking to main roleplay. Separate: Generates RPG data separately (manual or auto). External: Connects to an OpenAI-compatible endpoint directly.",
"template.settingsModal.advanced.generationModeOptions.external": "External API",
"template.settingsModal.advanced.externalApi.title": "External API Settings",
"template.settingsModal.advanced.externalApi.baseUrl": "API Base URL",
"template.settingsModal.advanced.externalApi.baseUrlNote": "OpenAI-compatible endpoint (e.g., OpenAI, OpenRouter, local LLM server).",
"template.settingsModal.advanced.externalApi.apiKey": "API Key",
"template.settingsModal.advanced.externalApi.apiKeyNote": "Your API key for the external service.",
"template.settingsModal.advanced.externalApi.model": "Model",
"template.settingsModal.advanced.externalApi.modelNote": "Model identifier (e.g., gpt-4o-mini, claude-3-haiku, mistral-7b).",
"template.settingsModal.advanced.externalApi.maxTokens": "Max Tokens",
"template.settingsModal.advanced.externalApi.temperature": "Temperature",
"template.settingsModal.advanced.externalApi.testConnection": "Test Connection",
"template.settingsModal.advanced.contextMessages": "Context Messages:",
"template.settingsModal.advanced.contextMessagesNote": "Number of recent messages to include.",
"template.settingsModal.advanced.useSeparatePreset": "Use model connected to RPG Companion Trackers preset",
"template.settingsModal.advanced.useSeparatePresetNote": "When enabled, tracker generation will use the model from the \"RPG Companion Trackers\" preset instead of your main API model. The preset will be switched automatically during generation and restored afterward. Select the desired model in that preset and make sure the \"Bind presets to API connections\" toggle is on (next to the import/export preset buttons).",
"template.settingsModal.advanced.skipInjections": "Skip Injections During Guided Generations:",
"template.settingsModal.advanced.skipInjectionsOptions.none": "Never skip",
"template.settingsModal.advanced.skipInjectionsOptions.impersonation": "Only on impersonation requests",
"template.settingsModal.advanced.skipInjectionsOptions.guided": "Always for guided or quiet prompts",
"template.settingsModal.advanced.skipInjectionsNote": "When set, the extension will not inject tracker prompts, examples, or HTML instructions according to the selected mode when a guided generation (via `instruct` or `quiet_prompt`) is detected. Useful when using GuidedGenerations or similar extensions.",
"template.settingsModal.advanced.customHtmlPromptTitle": "Custom HTML Prompt:",
"template.settingsModal.advanced.restoreDefaultHtmlPrompt": "Restore Default",
"template.settingsModal.advanced.customHtmlPromptNote": "Customize the HTML prompt injected when \"Enable Immersive HTML\" is enabled. The default prompt is shown above - you can edit it directly or replace it entirely. Click \"Restore Default\" to reset. This affects all generation modes (together, separate, and plot progression).",
"template.settingsModal.advanced.clearCache": "Clear Extension Cache",
"template.settingsModal.advanced.resetFabPositions": "Reset Button Positions",
"template.settingsModal.advanced.resetFabPositionsNote": "Resets all floating action buttons (toggle, refresh, debug) to default top-left positions. Useful if buttons are off-screen.",
"template.trackerEditorModal.title": "Edit Trackers",
"template.trackerEditorModal.tabs.userStats": "User Stats",
"template.trackerEditorModal.tabs.infoBox": "Info Box",
"template.trackerEditorModal.tabs.presentCharacters": "Present Characters",
"template.trackerEditorModal.buttons.reset": "Reset",
"template.trackerEditorModal.buttons.cancel": "Cancel",
"template.trackerEditorModal.buttons.save": "Save & Apply",
"template.trackerEditorModal.buttons.export": "Export",
"template.trackerEditorModal.buttons.import": "Import",
"template.trackerEditorModal.messages.exportSuccess": "Tracker preset exported successfully!",
"template.trackerEditorModal.messages.exportError": "Failed to export tracker preset. Check console for details.",
"template.trackerEditorModal.messages.importSuccess": "Tracker preset imported successfully!",
"template.trackerEditorModal.messages.importError": "Failed to import tracker preset",
"template.trackerEditorModal.messages.importConfirm": "This will replace your current tracker configuration. Continue?",
"template.trackerEditorModal.userStatsTab.customStatsTitle": "Custom Stats",
"template.trackerEditorModal.userStatsTab.addCustomStatButton": "Add Custom Stat",
"template.trackerEditorModal.userStatsTab.rpgAttributesTitle": "RPG Attributes",
"template.trackerEditorModal.userStatsTab.enableRpgAttributes": "Enable RPG Attributes Section",
"template.trackerEditorModal.userStatsTab.alwaysIncludeAttributes": "Always Include Attributes in Prompt",
"template.trackerEditorModal.userStatsTab.alwaysIncludeAttributesNote": "If disabled, attributes are only sent when a dice roll is active.",
"template.trackerEditorModal.userStatsTab.addAttributeButton": "Add Attribute",
"template.trackerEditorModal.userStatsTab.statusSectionTitle": "Status Section",
"template.trackerEditorModal.userStatsTab.enableStatusSection": "Enable Status Section",
"template.trackerEditorModal.userStatsTab.showMoodEmoji": "Show Mood Emoji",
"template.trackerEditorModal.userStatsTab.statusFieldsLabel": "Status Fields (comma-separated):",
"template.trackerEditorModal.userStatsTab.skillsSectionTitle": "Skills Section",
"template.trackerEditorModal.userStatsTab.enableSkillsSection": "Enable Skills Section",
"template.trackerEditorModal.userStatsTab.skillsLabelLabel": "Skills Label:",
"template.trackerEditorModal.userStatsTab.skillsListLabel": "Skills List (comma-separated):",
"template.trackerEditorModal.infoBoxTab.widgetsTitle": "Widgets",
"template.trackerEditorModal.infoBoxTab.dateWidget": "Date",
"template.trackerEditorModal.infoBoxTab.weatherWidget": "Weather",
"template.trackerEditorModal.infoBoxTab.temperatureWidget": "Temperature",
"template.trackerEditorModal.infoBoxTab.timeWidget": "Time",
"template.trackerEditorModal.infoBoxTab.locationWidget": "Location",
"template.trackerEditorModal.infoBoxTab.recentEventsWidget": "Recent Events",
"template.trackerEditorModal.presentCharactersTab.relationshipStatusTitle": "Relationship Status Fields",
"template.trackerEditorModal.presentCharactersTab.enableRelationshipStatus": "Enable Relationship Status Fields",
"template.trackerEditorModal.presentCharactersTab.relationshipStatusHint": "Define relationship types with corresponding emojis shown on character portraits.",
"template.trackerEditorModal.presentCharactersTab.newRelationshipButton": "New Relationship",
"template.trackerEditorModal.presentCharactersTab.appearanceDemeanorTitle": "Appearance/Demeanor Fields",
"template.trackerEditorModal.presentCharactersTab.appearanceDemeanorHint": "Fields shown below character name.",
"template.trackerEditorModal.presentCharactersTab.addCustomFieldButton": "Add Custom Field",
"template.trackerEditorModal.presentCharactersTab.thoughtsConfigTitle": "Thoughts Configuration",
"template.trackerEditorModal.presentCharactersTab.enableCharacterThoughts": "Enable Character Thoughts",
"template.trackerEditorModal.presentCharactersTab.thoughtsLabelLabel": "Thoughts Label:",
"template.trackerEditorModal.presentCharactersTab.aiInstructionLabel": "AI Instruction:",
"template.trackerEditorModal.presentCharactersTab.characterStatsTitle": "Character Stats",
"template.trackerEditorModal.presentCharactersTab.trackCharacterStats": "Track Character Stats",
"template.trackerEditorModal.presentCharactersTab.characterStatsHint": "Create stats to track for each character (displayed as colored bars).",
"template.trackerEditorModal.presentCharactersTab.addCharacterStatButton": "Add Character Stat",
"template.mainPanel.title": "RPG Companion",
"template.mainPanel.lastRoll": "Last Roll:",
"template.mainPanel.clearLastRoll": "Clear last roll",
"template.mainPanel.immersiveHtml": "Immersive HTML",
"template.mainPanel.coloredDialogues": "Colored Dialogues",
"template.mainPanel.spotifyMusic": "Spotify Music",
"template.mainPanel.snowflakesEffect": "Snowflakes Effect",
"template.mainPanel.dynamicWeatherEffects": "Dynamic Weather",
"template.mainPanel.narratorMode": "Narrator Mode",
"template.mainPanel.refreshRpgInfo": "Refresh RPG Info",
"template.mainPanel.updating": "Updating...",
"template.mainPanel.editTrackersButton": "Edit Trackers",
"template.mainPanel.settingsButton": "Settings",
"global.none": "None",
"global.add": "Add",
"global.cancel": "Cancel",
"global.listView": "List view",
"global.gridView": "Grid view",
"global.save": "Save",
"global.status":"Status",
"global.inventory":"Inventory",
"global.quests":"Quests",
"global.info":"Info",
"infobox.noData.title": "No data yet",
"infobox.noData.instruction": "Generate a new response in the roleplay or switch to \"Separate Generation\" in Settings to access and click the \"Refresh RPG Info\" button",
"infobox.recentEvents.title": "Recent Events",
"infobox.recentEvents.addEventPlaceholder": "Add event...",
"inventory.section.onPerson": "On Person",
"inventory.section.clothing": "Clothing",
"inventory.section.stored": "Stored",
"inventory.section.assets": "Assets",
"inventory.onPerson.empty": "No items carried",
"inventory.onPerson.title": "Items Currently Carried",
"inventory.onPerson.addItemButton": "Add Item",
"inventory.onPerson.addItemPlaceholder": "Enter item name...",
"inventory.clothing.empty": "Not wearing anything",
"inventory.clothing.title": "Clothing & Armor",
"inventory.clothing.addItemButton": "Add Clothing",
"inventory.clothing.addItemPlaceholder": "Enter clothing item...",
"inventory.stored.title": "Storage Locations",
"inventory.stored.addLocationButton": "Add Location",
"inventory.stored.addLocationPlaceholder": "Enter location name...",
"inventory.stored.saveButton": "Save",
"inventory.stored.empty": "No storage locations yet. Click \"Add Location\" to create one.",
"inventory.stored.noItems": "No items stored here",
"inventory.stored.addItemToLocationPlaceholder": "Enter item name...",
"inventory.stored.addItemButton": "Add Item",
"inventory.stored.confirmRemoveLocationMessage": "Remove \"${location}\"? This will delete all items stored there.",
"inventory.stored.confirmRemoveLocationConfirmButton": "Confirm",
"inventory.assets.empty": "No assets owned",
"inventory.assets.title": "Vehicles, Property & Major Possessions",
"inventory.assets.addAssetModalTitle": "Add Asset",
"inventory.assets.addAssetButton": "Add Asset",
"inventory.assets.addAssetPlaceholder": "Enter asset name...",
"inventory.assets.description": "Assets include vehicles (cars, motorcycles), property (homes, apartments), and major equipment (workshop tools, special items).",
"quests.section.main": "Main Quest",
"quests.section.optional": "Optional Quests",
"quests.main.title": "Main Quests",
"quests.main.addQuestButton": "Add Quest",
"quests.main.addQuestPlaceholder": "Enter main quest title...",
"quests.main.empty": "No active main quests",
"quests.main.hint": "The main quest represents your primary objective in the story.",
"quests.optional.title": "Optional Quests",
"quests.optional.addQuestButton": "Add Quest",
"quests.optional.addQuestPlaceholder": "Enter optional quest title...",
"quests.optional.empty": "No active optional quests",
"quests.optional.hint": "Optional quests are side objectives that complement your main story.",
"checkpoint.setChapterStart": "Set Chapter Start",
"checkpoint.clearChapterStart": "Clear Chapter Start",
"checkpoint.indicator": "Chapter Start",
"checkpoint.tooltip": "Messages before this point are excluded from context",
"musicPlayer.title": "Scene Music",
"musicPlayer.noMusic": "AI will suggest music when appropriate for the scene",
"errors.parsingError": "RPG Companion Trackers' parsing error! The model returned an incorrect format. If the issue persists, consider changing the model for generations.",
"settings.recommendedModels.title": "Recommended Models",
"settings.recommendedModels.description": "For the extension to work properly, **it is not recommended to use any models below 20B, especially if they're old.** It works best with the SOTA models such as Deepseek, Claude, GPT, or Gemini."
}
+200
View File
@@ -0,0 +1,200 @@
{
"settings.language.label": "語言",
"settings.language.option.en": "English",
"settings.language.option.zh-tw": "繁體中文",
"settings.extensionEnabled": "啟用 RPG Companion",
"settings.note": "切換開關以啟用/停用 RPG Companion。其他設定可在面板內配置。",
"template.settingsTitle": "RPG Companion 設定",
"template.settingsModal.themeTitle": "主題",
"template.settingsModal.themeLabel": "可選主題:",
"template.settingsModal.themeOptions.default": "預設",
"template.settingsModal.themeOptions.sciFi": "科幻 (合成波)",
"template.settingsModal.themeOptions.fantasy": "奇幻 (古樸羊皮紙)",
"template.settingsModal.themeOptions.cyberpunk": "賽博朋克 (霓虹網格)",
"template.settingsModal.themeOptions.custom": "自訂",
"template.settingsModal.themeOptions.custom.background": "背景:",
"template.settingsModal.themeOptions.custom.accent": "強調色:",
"template.settingsModal.themeOptions.custom.text": "文字:",
"template.settingsModal.themeOptions.custom.highlight": "高亮:",
"template.settingsModal.theme.statBarLow": "屬性條顏色 (低)",
"template.settingsModal.theme.statBarLowNote": "屬性在 0% 時的顏色",
"template.settingsModal.theme.statBarHigh": "屬性條顏色 (高)",
"template.settingsModal.theme.statBarHighNote": "屬性在 100% 時的顏色",
"template.settingsModal.displayTitle": "顯示設定",
"template.settingsModal.displayNote": "使用擴充功能標籤來啟用/停用 RPG Companion 擴充功能。",
"template.settingsModal.display.panelPosition": "面板位置:",
"template.settingsModal.display.panelPositionOptions.right": "右側邊欄",
"template.settingsModal.display.panelPositionOptions.left": "左側邊欄",
"template.settingsModal.display.toggleAutoUpdate": "訊息後自動更新",
"template.settingsModal.display.showUserStats": "顯示 user 屬性",
"template.settingsModal.display.showInfoBox": "顯示資訊框",
"template.settingsModal.display.showPresentCharacters": "顯示在場角色",
"template.settingsModal.display.showInventory": "顯示物品欄",
"template.settingsModal.display.showLockIcons": "顯示鎖定/解鎖追蹤器",
"template.settingsModal.display.showLockIconsNote": "在追蹤器項目上顯示鎖定/解鎖圖示,以防止 AI 修改它們。",
"template.settingsModal.display.showThoughtsInChat": "在聊天中顯示想法",
"template.settingsModal.display.showThoughtsInChatNote": "將角色想法顯示為其訊息旁的泡泡",
"template.settingsModal.display.alwaysShowThoughtBubble": "始終顯示想法泡泡",
"template.settingsModal.display.alwaysShowThoughtBubbleNote": "自動展開想法泡泡",
"template.settingsModal.display.enableAnimations": "啟用動畫",
"template.settingsModal.display.enableAnimationsNote": "屬性、內容更新和擲骰的動畫效果",
"template.settingsModal.display.showImmersiveHtmlToggle": "顯示沉浸式 HTML",
"template.settingsModal.display.showDialogueColoringToggle": "顯示彩色對話",
"template.settingsModal.display.showDialogueColoringToggleNote": "顯示一個切換按鈕以啟用/停用彩色對話格式。",
"template.settingsModal.display.showSpotifyMusicToggle": "顯示 Spotify 音樂",
"template.settingsModal.display.showSnowflakesToggle": "顯示雪花效果", "template.settingsModal.display.showDynamicWeatherToggle": "顯示動態天氣效果", "template.settingsModal.display.showNarratorMode": "顯示旁白模式", "template.settingsModal.display.showNarratorModeNote": "顯示切換按鈕以啟用/停用旁白模式", "template.settingsModal.display.showAutoAvatars": "顯示自動生成頭像", "template.settingsModal.display.showAutoAvatarsNote": "顯示切換按鈕以自動為沒有圖片的角色生成頭像", "template.settingsModal.display.showPlotProgressionButtons": "顯示劇情推進按鈕(QR",
"template.settingsModal.display.showPlotProgressionButtonsNote": "在聊天輸入框上方顯示劇情推進提示按鈕(QR)",
"template.settingsModal.advancedTitle": "進階",
"template.settingsModal.advanced.generationMode": "生成模式:",
"template.settingsModal.advanced.generationModeOptions.together": "同時生成",
"template.settingsModal.advanced.generationModeOptions.separate": "單獨生成",
"template.settingsModal.advanced.generationModeNote": "同時生成:將 RPG 追蹤添加到主要提示詞中一同生成。單獨生成:分開生成 RPG 數據。(就是手動或自動的差別)。外部 API:直接連接 OpenAI 兼容端點生成數據。",
"template.settingsModal.advanced.generationModeOptions.external": "外部 API",
"template.settingsModal.advanced.externalApi.title": "外部 API 設定",
"template.settingsModal.advanced.externalApi.baseUrl": "API 基礎 URL",
"template.settingsModal.advanced.externalApi.baseUrlNote": "OpenAI 兼容端點(例如 OpenAI、OpenRouter、本地 LLM 伺服器)",
"template.settingsModal.advanced.externalApi.apiKey": "API 金鑰",
"template.settingsModal.advanced.externalApi.apiKeyNote": "外部服務的 API 金鑰",
"template.settingsModal.advanced.externalApi.model": "模型",
"template.settingsModal.advanced.externalApi.modelNote": "模型識別碼(例如 gpt-4o-mini、claude-3-haiku、mistral-7b",
"template.settingsModal.advanced.externalApi.maxTokens": "最大 Token",
"template.settingsModal.advanced.externalApi.temperature": "溫度 (Temperature)",
"template.settingsModal.advanced.externalApi.testConnection": "測試連接",
"template.settingsModal.advanced.contextMessages": "上下文訊息:",
"template.settingsModal.advanced.contextMessagesNote": "包含的最近訊息數量(僅限單獨生成模式)",
"template.settingsModal.advanced.memoryBatchSize": "記憶批次大小:",
"template.settingsModal.advanced.memoryBatchSizeNote": "在記憶回憶中每批處理的訊息數量",
"template.settingsModal.advanced.useSeparatePreset": "使用 RPG Companion 追蹤預設模型(設置次要模型)",
"template.settingsModal.advanced.useSeparatePresetNote": "僅限單獨生成模式。啟用後將使用“RPG Companion Trackers”預設中綁定的模型,而不是您的主要 API 模型。生成期間會自動切換預設,之後會恢復原使用預設。請在“RPG Companion Trackers”預設中選擇次要模型,並確保“將預設綁定到 API 連接”切換已開啟(在導入/導出預設按鈕旁邊)。",
"template.settingsModal.advanced.skipInjections": "在引導生成期間跳過注入:",
"template.settingsModal.advanced.skipInjectionsOptions.none": "從不跳過",
"template.settingsModal.advanced.skipInjectionsOptions.impersonation": "僅在模擬請求時跳過",
"template.settingsModal.advanced.skipInjectionsOptions.guided": "始終跳過引導",
"template.settingsModal.advanced.skipInjectionsNote": "當設置後,擴充功能在檢測到引導生成(通過 `instruct` 或 `quiet_prompt`)時,將根據所選模式不注入追蹤提示詞、範例或 HTML 指令。當與 GuidedGenerations 或類似擴充功能一起使用時非常有用。",
"template.settingsModal.advanced.customHtmlPromptTitle": "自訂 HTML 提示詞:",
"template.settingsModal.advanced.restoreDefaultHtmlPrompt": "恢復預設",
"template.settingsModal.advanced.customHtmlPromptNote": "自訂啟用“啟用沉浸式 HTML”時注入的 HTML 提示詞。上方顯示預設提示詞 - 您可以直接編輯或完全替換它。點擊“恢復預設”以重置。這會影響所有生成模式(同時、單獨和劇情推進)。",
"template.settingsModal.advanced.clearCache": "清除擴充功能快取",
"template.settingsModal.advanced.resetFabPositions": "重置按鈕位置",
"template.settingsModal.advanced.resetFabPositionsNote": "將所有浮動操作按鈕(切換、刷新、調試)重置為預設的左上位置。如果按鈕在螢幕外,這會很有用。",
"template.trackerEditorModal.title": "追蹤器編輯",
"template.trackerEditorModal.tabs.userStats": "User 屬性",
"template.trackerEditorModal.tabs.infoBox": "資訊框",
"template.trackerEditorModal.tabs.presentCharacters": "在場角色",
"template.trackerEditorModal.buttons.reset": "重置",
"template.trackerEditorModal.buttons.cancel": "取消",
"template.trackerEditorModal.buttons.save": "保存並應用",
"template.trackerEditorModal.buttons.export": "匯出",
"template.trackerEditorModal.buttons.import": "匯入",
"template.trackerEditorModal.messages.exportSuccess": "追蹤器預設匯出成功!",
"template.trackerEditorModal.messages.exportError": "匯出追蹤器預設失敗。請檢查控制台以獲取詳細資訊。",
"template.trackerEditorModal.messages.importSuccess": "追蹤器預設匯入成功!",
"template.trackerEditorModal.messages.importError": "匯入追蹤器預設失敗",
"template.trackerEditorModal.messages.importConfirm": "這將替換您當前的追蹤器配置。繼續?",
"template.trackerEditorModal.userStatsTab.customStatsTitle": "自訂屬性",
"template.trackerEditorModal.userStatsTab.addCustomStatButton": "添加自訂屬性",
"template.trackerEditorModal.userStatsTab.rpgAttributesTitle": "RPG 屬性",
"template.trackerEditorModal.userStatsTab.enableRpgAttributes": "啟用 RPG 屬性",
"template.trackerEditorModal.userStatsTab.alwaysIncludeAttributes": "始終發送屬性(prompt",
"template.trackerEditorModal.userStatsTab.alwaysIncludeAttributesNote": "將 RPG 屬性始終包含在提示詞中,即使它們未顯示在面板上也一樣。",
"template.trackerEditorModal.userStatsTab.addAttributeButton": "添加屬性",
"template.trackerEditorModal.userStatsTab.statusSectionTitle": "狀態欄",
"template.trackerEditorModal.userStatsTab.enableStatusSection": "啟用狀態欄",
"template.trackerEditorModal.userStatsTab.showMoodEmoji": "顯示心情emoji",
"template.trackerEditorModal.userStatsTab.statusFieldsLabel": "狀態欄欄位(以逗號分隔):",
"template.trackerEditorModal.userStatsTab.skillsSectionTitle": "技能欄",
"template.trackerEditorModal.userStatsTab.enableSkillsSection": "啟用技能欄",
"template.trackerEditorModal.userStatsTab.skillsLabelLabel": "技能欄標籤:",
"template.trackerEditorModal.userStatsTab.skillsListLabel": " 技能列表(以逗號分隔):",
"template.trackerEditorModal.infoBoxTab.widgetsTitle": "小工具",
"template.trackerEditorModal.infoBoxTab.dateWidget": "日期",
"template.trackerEditorModal.infoBoxTab.weatherWidget": "天氣",
"template.trackerEditorModal.infoBoxTab.temperatureWidget": "溫度",
"template.trackerEditorModal.infoBoxTab.timeWidget": "時間",
"template.trackerEditorModal.infoBoxTab.locationWidget": "位置",
"template.trackerEditorModal.infoBoxTab.recentEventsWidget": "近期事件",
"template.trackerEditorModal.presentCharactersTab.relationshipStatusTitle": "關係狀態",
"template.trackerEditorModal.presentCharactersTab.enableRelationshipStatus": "啟用關係狀態欄位",
"template.trackerEditorModal.presentCharactersTab.relationshipStatusHint": "定義關係類型,並在角色頭像上顯示對應的表情符號",
"template.trackerEditorModal.presentCharactersTab.newRelationshipButton": "新增關係類型",
"template.trackerEditorModal.presentCharactersTab.appearanceDemeanorTitle": "外觀與當前行為舉止",
"template.trackerEditorModal.presentCharactersTab.appearanceDemeanorHint": "角色名稱下方顯示的字段,以 | 分隔。",
"template.trackerEditorModal.presentCharactersTab.addCustomFieldButton": "添加自訂字段",
"template.trackerEditorModal.presentCharactersTab.thoughtsConfigTitle": "內心話配置",
"template.trackerEditorModal.presentCharactersTab.enableCharacterThoughts": "啟用角色內心話",
"template.trackerEditorModal.presentCharactersTab.thoughtsLabelLabel": "內心話標籤:",
"template.trackerEditorModal.presentCharactersTab.aiInstructionLabel": "內心話提示詞:",
"template.trackerEditorModal.presentCharactersTab.characterStatsTitle": "角色屬性",
"template.trackerEditorModal.presentCharactersTab.trackCharacterStats": "啟用角色屬性",
"template.trackerEditorModal.presentCharactersTab.characterStatsHint": "建立統計資料以追蹤每個角色(以彩色長條圖顯示)",
"template.trackerEditorModal.presentCharactersTab.addCharacterStatButton": "添加角色屬性",
"template.mainPanel.title": "RPG Companion",
"template.mainPanel.lastRoll": "上次擲骰:",
"template.mainPanel.clearLastRoll": "清除上次擲骰",
"template.mainPanel.immersiveHtml": "沉浸式 HTML",
"template.mainPanel.coloredDialogues": "彩色對話",
"template.mainPanel.spotifyMusic": "Spotify 音樂",
"template.mainPanel.snowflakesEffect": "雪花效果", "template.mainPanel.dynamicWeatherEffects": "動態天氣", "template.mainPanel.narratorMode": "旁白模式", "template.mainPanel.autoAvatars": "自動頭像", "template.mainPanel.refreshRpgInfo": "刷新資訊",
"template.mainPanel.updating": "更新中...",
"template.mainPanel.editTrackersButton": "追蹤器編輯",
"template.mainPanel.settingsButton": "設定",
"global.none": "None",
"global.add": "添加",
"global.cancel": "取消",
"global.save": "保存",
"global.listView": "清單檢視",
"global.gridView": "格子檢視",
"global.status": "狀態欄",
"global.inventory": "物品欄",
"global.quests": "任務",
"global.info":"資訊",
"infobox.noData.title": "無資訊可顯示",
"infobox.noData.instruction": "在RP中產生新的回复,或在設定中切換到“單獨生成”,然後點擊“刷新資訊”按鈕。",
"infobox.recentEvents.title": "近期事件",
"infobox.recentEvents.addEventPlaceholder": "添加事件...",
"inventory.section.onPerson": "隨身物品",
"inventory.section.clothing": "服裝",
"inventory.section.stored": "倉庫物品",
"inventory.section.assets": "資產",
"inventory.onPerson.empty": "這裡什麼都沒有 (⚲□⚲)",
"inventory.onPerson.title": "攜帶的物品",
"inventory.onPerson.addItemButton": "添加物品",
"inventory.onPerson.addItemPlaceholder": "輸入物品名稱...",
"inventory.clothing.empty": "未穿著任何服裝 (⚲□⚲)",
"inventory.clothing.title": "服裝與護甲",
"inventory.clothing.addItemButton": "添加服裝",
"inventory.clothing.addItemPlaceholder": "輸入服裝物品...",
"inventory.stored.title": "倉庫位置",
"inventory.stored.addLocationButton": "添加倉庫",
"inventory.stored.addLocationPlaceholder": "輸入倉庫名稱...",
"inventory.stored.saveButton": "保存",
"inventory.stored.empty": "沒有倉庫 (⚲□⚲), 點擊\"添加倉庫\"來新增一個倉庫",
"inventory.stored.noItems": "這個倉庫是空的 (⚲□⚲)",
"inventory.stored.addItemToLocationPlaceholder": "輸入物品名稱...",
"inventory.stored.addItemButton": "添加物品",
"inventory.stored.confirmRemoveLocationMessage": "確定要刪除這個倉庫嗎?這將移除所有其中的物品。",
"inventory.stored.confirmRemoveLocationConfirmButton": "刪除",
"inventory.assets.empty": "沒有資產 (⚲□⚲) 好窮",
"inventory.assets.title": "車輛、房產及主要財產",
"inventory.assets.addAssetModalTitle": "添加資產",
"inventory.assets.addAssetButton": "添加資產",
"inventory.assets.addAssetPlaceholder": "輸入資產名稱...",
"inventory.assets.description": "資產包括車輛(汽車、摩托車)、房產(房屋、公寓)和主要設備(車間工具、特殊物品)。",
"quests.section.main": "主線任務",
"quests.section.optional": "支線任務",
"quests.main.title": "主線任務",
"quests.main.addQuestButton": "添加主要任務",
"quests.main.addQuestPlaceholder": "輸入主線任務名稱...",
"quests.main.empty": "當前無主要任務 (ฅ˙Ⱉ˙ฅ)",
"quests.main.hint": "主線任務代表你在故事中的主要目標。",
"quests.optional.title": "支線任務",
"quests.optional.addQuestButton": "添加支線任務",
"quests.optional.addQuestPlaceholder": "輸入支線任務名稱...",
"quests.optional.empty": "當前無支線任務 (ʘ̆ʚʘ̆)",
"quests.optional.hint": "支線任務是補充主線劇情的支線目標。",
"musicPlayer.title": "場景音樂",
"musicPlayer.noMusic": "AI 會在適當時為場景建議音樂",
"errors.parsingError": "RPG Companion 追蹤器解析錯誤!模型返回了不正確的格式。如果問題持續存在,請考慮更換生成模型。",
"settings.recommendedModels.title": "推薦模型",
"settings.recommendedModels.description": "為了讓擴充功能正常運作,**不建議使用任何小於 20B 的模型,尤其是舊模型。**它最適合使用 SOTA 模型,例如 Deepseek、Claude、GPT 或 Gemini。"
}
+402
View File
@@ -0,0 +1,402 @@
/**
* Avatar Generator Module
* Handles automatic and manual avatar generation for NPC characters
*
* Features:
* - Batch generation with awaitable completion
* - Batch prompt generation via LLM
* - Individual image generation via /sd command
* - Manual regeneration support
*/
import { generateRaw, characters, this_chid } from '../../../../../../../script.js';
import { executeSlashCommandsOnChatInput } from '../../../../../../../scripts/slash-commands.js';
import { selected_group, getGroupMembers } from '../../../../../../group-chats.js';
import { extensionSettings, sessionAvatarPrompts, setSessionAvatarPrompt } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { generateAvatarPromptGenerationPrompt } from '../generation/promptBuilder.js';
import { getCurrentPresetName, switchToPreset, generateWithExternalAPI } from '../generation/apiClient.js';
// Generation state - tracks characters currently being generated
const pendingGenerations = new Set();
/**
* Checks if a character is pending generation (waiting or actively generating)
* @param {string} characterName - Name of character to check
* @returns {boolean} True if generation is pending
*/
export function isGenerating(characterName) {
return pendingGenerations.has(characterName);
}
/**
* Checks if any avatars are currently being generated
* @returns {boolean} True if any generation is in progress
*/
export function isAnyGenerating() {
return pendingGenerations.size > 0;
}
/**
* Gets all characters currently pending generation
* @returns {string[]} Array of character names
*/
export function getPendingGenerations() {
return [...pendingGenerations];
}
/**
* Helper to check if two character names match (case-insensitive, handles partial matches)
* @param {string} cardName - Name from character card
* @param {string} aiName - Name from AI response
* @returns {boolean} True if names match
*/
function namesMatch(cardName, aiName) {
if (!cardName || !aiName) return false;
const cardLower = cardName.toLowerCase().trim();
const aiLower = aiName.toLowerCase().trim();
if (cardLower === aiLower) return true;
const cardCore = cardLower.split(/[\s,'"]+/)[0];
const aiCore = aiLower.split(/[\s,'"]+/)[0];
if (cardCore === aiCore) return true;
const escapedCardCore = cardCore.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const wordBoundary = new RegExp(`\\b${escapedCardCore}\\b`);
return wordBoundary.test(aiCore);
}
/**
* Checks if a character already has an avatar (custom NPC avatar or from character card)
* @param {string} characterName - Name of character to check
* @returns {boolean} True if character has an avatar
*/
export function hasExistingAvatar(characterName) {
// Check for custom NPC avatar first
if (extensionSettings.npcAvatars && extensionSettings.npcAvatars[characterName]) {
const avatar = extensionSettings.npcAvatars[characterName];
if (typeof avatar === 'string' && avatar) {
return true;
}
}
// Check group members for avatar
if (selected_group) {
try {
const groupMembers = getGroupMembers(selected_group);
if (groupMembers && groupMembers.length > 0) {
const matchingMember = groupMembers.find(member =>
member && member.name && namesMatch(member.name, characterName)
);
if (matchingMember && matchingMember.avatar && matchingMember.avatar !== 'none') {
return true;
}
}
} catch (e) {
// Ignore errors
}
}
// Check all characters for avatar
if (characters && characters.length > 0) {
const matchingCharacter = characters.find(c =>
c && c.name && namesMatch(c.name, characterName)
);
if (matchingCharacter && matchingCharacter.avatar && matchingCharacter.avatar !== 'none') {
return true;
}
}
// Check current character in 1-on-1 chat
if (this_chid !== undefined && characters[this_chid] &&
characters[this_chid].name && namesMatch(characters[this_chid].name, characterName)) {
if (characters[this_chid].avatar && characters[this_chid].avatar !== 'none') {
return true;
}
}
return false;
}
/**
* Generates avatars for multiple characters and waits for all to complete.
* This is the main entry point for auto-generation within a workflow.
*
* @param {string[]} characterNames - Array of character names to generate avatars for
* @param {Function} onStarted - Optional callback when generation starts (to update UI)
* @returns {Promise<void>} Resolves when all generations complete
*/
export async function generateAvatarsForCharacters(characterNames, onStarted = null) {
if (!extensionSettings.autoGenerateAvatars) {
return;
}
// Filter to characters that need avatars
const needsGeneration = characterNames.filter(name => {
// Skip if already pending
if (pendingGenerations.has(name)) {
return false;
}
// Skip if has avatar
if (hasExistingAvatar(name)) {
return false;
}
return true;
});
if (needsGeneration.length === 0) {
return;
}
// console.log('[RPG Avatar] Starting batch generation for:', needsGeneration);
// Mark all as pending IMMEDIATELY (before any async work)
for (const name of needsGeneration) {
pendingGenerations.add(name);
}
// Trigger UI update to show loading spinners
if (onStarted) {
try {
onStarted([...needsGeneration]);
} catch (e) {
console.error('[RPG Avatar] Error in onStarted callback:', e);
}
}
try {
// Generate images one at a time, generating prompt on demand
for (const characterName of needsGeneration) {
// Skip if somehow already has avatar now
if (hasExistingAvatar(characterName)) {
pendingGenerations.delete(characterName);
continue;
}
// Generate LLM prompt for this character
const prompt = await generateAvatarPrompt(characterName);
// Generate the image using the prompt
await generateSingleAvatar(characterName, prompt);
pendingGenerations.delete(characterName);
// Small delay between generations to avoid overwhelming the API
if (needsGeneration.indexOf(characterName) < needsGeneration.length - 1) {
await new Promise(resolve => setTimeout(resolve, 500));
}
}
} finally {
// Ensure all are removed from pending even if there's an error
for (const name of needsGeneration) {
pendingGenerations.delete(name);
}
}
// console.log('[RPG Avatar] Batch generation complete');
}
/**
* Regenerates avatar for a specific character
* Clears existing avatar and prompt, then generates new ones
* Handles preset switching if useSeparatePreset is enabled
*
* @param {string} characterName - Name of character to regenerate
* @returns {Promise<string|null>} New avatar URL or null if failed
*/
export async function regenerateAvatar(characterName) {
// console.log('[RPG Avatar] Regenerating avatar for:', characterName);
// Mark as pending immediately
pendingGenerations.add(characterName);
// Clear existing avatar
if (extensionSettings.npcAvatars && extensionSettings.npcAvatars[characterName]) {
delete extensionSettings.npcAvatars[characterName];
saveSettings();
}
// Clear existing prompt cache
if (sessionAvatarPrompts[characterName]) {
delete sessionAvatarPrompts[characterName];
}
try {
// Generate new LLM prompt
const prompt = await generateAvatarPrompt(characterName);
// Generate the avatar
return await generateSingleAvatar(characterName, prompt);
} finally {
// Remove from pending when done
pendingGenerations.delete(characterName);
}
}
/**
* Generates an LLM prompt for a single character
*
* @param {string} characterName - Name of character
* @returns {Promise<string|null>} Generated prompt or null if failed
*/
async function generateAvatarPrompt(characterName) {
// Check cache first if not forcing regeneration
if (sessionAvatarPrompts[characterName]) {
return sessionAvatarPrompts[characterName];
}
try {
// console.log('[RPG Avatar] Generating LLM prompt for:', characterName);
const promptMessages = await generateAvatarPromptGenerationPrompt(characterName);
let response;
if (extensionSettings.generationMode === 'external') {
// console.log('[RPG Avatar] Using external API for avatar prompt generation');
response = await generateWithExternalAPI(promptMessages);
} else {
response = await generateRaw({
prompt: promptMessages,
quietToLoud: false
});
}
if (response) {
const prompt = response.trim();
// console.log(`[RPG Avatar] Generated prompt for ${characterName}:`, prompt);
// Store prompt in session storage
setSessionAvatarPrompt(characterName, prompt);
return prompt;
}
} catch (error) {
console.error(`[RPG Avatar] Failed to generate LLM prompt for ${characterName}:`, error);
}
return null;
}
/**
* Builds a fallback prompt when LLM prompt generation fails or isn't available
* Uses information embedded in the character name if present (e.g., from malformed tracker output)
*
* @param {string} characterName - Character name (may contain additional details)
* @returns {string} A basic prompt for image generation
*/
function buildFallbackPrompt(characterName) {
// Check if the name contains embedded details (malformed format from weaker models)
// e.g., "Eris Details: 🌟 | beautiful girl with white hair | kind expression"
if (characterName.includes('Details:') || characterName.includes('|')) {
// Extract useful description parts
const parts = characterName.split(/Details:|[|]/).map(p => p.trim()).filter(p => p && !p.match(/^[\p{Emoji}]+$/u));
if (parts.length > 1) {
// First part is likely the name, rest are descriptions
const name = parts[0];
const descriptions = parts.slice(1).join(', ');
return `portrait of ${name}, ${descriptions}, fantasy art style, detailed`;
}
}
// Simple fallback - just use the name
return `portrait of ${characterName}, character portrait, fantasy art style, detailed face, high quality`;
}
/**
* Generates a single avatar using the /sd command
*
* @param {string} characterName - Name of character to generate avatar for
* @param {string|null} prompt - The prompt to use (optional, will fallback if null)
* @returns {Promise<string|null>} Avatar URL or null if failed
*/
async function generateSingleAvatar(characterName, prompt = null) {
// Use provided prompt, or check cache, or build fallback
if (!prompt) {
prompt = sessionAvatarPrompts[characterName];
}
if (!prompt) {
// console.log(`[RPG Avatar] No LLM prompt for ${characterName}, using fallback prompt`);
prompt = buildFallbackPrompt(characterName);
}
// console.log(`[RPG Avatar] Starting image generation for: ${characterName}`);
try {
// Execute /sd command with quiet=true to suppress chat output
const result = await executeSlashCommandsOnChatInput(
`/sd quiet=true ${prompt}`,
{ clearChatInput: false }
);
// Extract image URL from result
const imageUrl = extractImageUrl(result);
if (imageUrl) {
// Store the avatar
if (!extensionSettings.npcAvatars) {
extensionSettings.npcAvatars = {};
}
extensionSettings.npcAvatars[characterName] = imageUrl;
saveSettings();
// console.log(`[RPG Avatar] Successfully generated avatar for: ${characterName}`);
return imageUrl;
} else {
console.warn(`[RPG Avatar] Failed to extract image URL for ${characterName}:`, result);
return null;
}
} catch (error) {
console.error(`[RPG Avatar] Generation failed for ${characterName}:`, error);
return null;
}
}
/**
* Extracts image URL from /sd command result
* Handles various result formats
*
* @param {any} result - Result from executeSlashCommandsOnChatInput
* @returns {string|null} Image URL or null
*/
function extractImageUrl(result) {
if (!result) return null;
// Handle string result
if (typeof result === 'string') {
// Validate it looks like a URL or data URI
if (result.startsWith('http') || result.startsWith('data:') || result.startsWith('/')) {
return result;
}
return null;
}
// Handle object result with various possible properties
if (typeof result === 'object') {
// Try common properties
const url = result.pipe || result.output || result.image || result.url || result.result;
if (url && typeof url === 'string') {
if (url.startsWith('http') || url.startsWith('data:') || url.startsWith('/')) {
return url;
}
}
}
return null;
}
/**
* Clears all pending generations and resets state
*/
export function clearPendingGenerations() {
pendingGenerations.clear();
}
/**
* Gets the current generation status for display
* @returns {{pending: number, names: string[]}}
*/
export function getGenerationStatus() {
return {
pending: pendingGenerations.size,
names: [...pendingGenerations]
};
}
+189
View File
@@ -0,0 +1,189 @@
/**
* Chapter Checkpoint Module
* Allows users to mark messages as "chapter start" points to filter context
* Uses SillyTavern's /hide and /unhide commands to exclude messages from context
*/
import { getContext } from '../../../../../../extensions.js';
import { chat_metadata, saveChatDebounced } from '../../../../../../../script.js';
import { executeSlashCommandsOnChatInput } from '../../../../../../../scripts/slash-commands.js';
// Track the message range that is currently hidden
let currentlyHiddenRange = null;
// Debounce restore to prevent loops
let isRestoring = false;
let restoreTimeout = null;
let pendingResolve = null;
/**
* Gets the current chapter checkpoint message ID for the active chat
* @returns {number|null} Message ID of the checkpoint, or null if none set
*/
export function getChapterCheckpoint() {
const context = getContext();
if (!context || !chat_metadata) return null;
return chat_metadata.rpg_companion_chapter_checkpoint || null;
}
/**
* Sets a message as the chapter checkpoint
* Automatically clears any previous checkpoint (only one checkpoint allowed at a time)
* Hides all messages before the checkpoint
* @param {number} messageId - The chat message index to set as checkpoint
* @returns {Promise<boolean>} True if successful
*/
export async function setChapterCheckpoint(messageId) {
const context = getContext();
const chat = context.chat;
if (!chat || messageId < 0 || messageId >= chat.length) {
console.error('[RPG Companion] Invalid message ID for checkpoint:', messageId);
return false;
}
const previousCheckpoint = chat_metadata.rpg_companion_chapter_checkpoint;
// If moving checkpoint, unhide the old range first
if (previousCheckpoint !== null && previousCheckpoint !== undefined && previousCheckpoint !== messageId && currentlyHiddenRange !== null) {
const { start, end } = currentlyHiddenRange;
await executeSlashCommandsOnChatInput(`/unhide ${start}-${end}`, { quiet: true });
// console.log(`[RPG Companion] Unhid previous range: ${start}-${end}`);
}
// Store in chat metadata (this automatically overrides any previous checkpoint)
chat_metadata.rpg_companion_chapter_checkpoint = messageId;
saveChatDebounced();
// Hide all messages before the checkpoint
if (messageId > 0) {
const rangeEnd = messageId - 1;
await executeSlashCommandsOnChatInput(`/hide 0-${rangeEnd}`, { quiet: true });
currentlyHiddenRange = { start: 0, end: rangeEnd };
// console.log(`[RPG Companion] Hidden messages 0-${rangeEnd} (checkpoint at ${messageId})`);
}
if (previousCheckpoint !== null && previousCheckpoint !== undefined && previousCheckpoint !== messageId) {
// console.log(`[RPG Companion] Chapter checkpoint moved from message ${previousCheckpoint} to ${messageId}`);
} else {
// console.log('[RPG Companion] Chapter checkpoint set at message', messageId);
}
// Emit event for UI updates
if (typeof document !== 'undefined') {
const event = new CustomEvent('rpg-companion-checkpoint-changed', {
detail: { messageId, previousCheckpoint }
});
document.dispatchEvent(event);
}
return true;
}
/**
* Clears the chapter checkpoint and unhides all hidden messages
*/
export async function clearChapterCheckpoint() {
if (!chat_metadata) return;
// Unhide any hidden messages
if (currentlyHiddenRange !== null) {
const { start, end } = currentlyHiddenRange;
await executeSlashCommandsOnChatInput(`/unhide ${start}-${end}`, { quiet: true });
// console.log(`[RPG Companion] Unhid messages ${start}-${end}`);
currentlyHiddenRange = null;
}
delete chat_metadata.rpg_companion_chapter_checkpoint;
saveChatDebounced();
// console.log('[RPG Companion] Chapter checkpoint cleared');
// Emit event for UI updates
if (typeof document !== 'undefined') {
const event = new CustomEvent('rpg-companion-checkpoint-changed', {
detail: { messageId: null }
});
document.dispatchEvent(event);
}
}
/**
* Checks if a message is the current checkpoint
* @param {number} messageId - The message index to check
* @returns {boolean} True if this is the checkpoint message
*/
export function isCheckpointMessage(messageId) {
const checkpointId = getChapterCheckpoint();
return checkpointId === messageId;
}
/**
* Restores checkpoint state after page reload or generation events
* Checks if a checkpoint exists and re-applies the /hide command
* Debounced to prevent loops when called from multiple events
*/
export async function restoreCheckpointOnLoad() {
// Prevent concurrent executions
if (isRestoring) {
return;
}
// Clear any pending timeout and resolve the pending promise
if (restoreTimeout) {
clearTimeout(restoreTimeout);
restoreTimeout = null;
}
if (pendingResolve) {
pendingResolve();
pendingResolve = null;
}
// Debounce: wait 100ms before actually restoring
return new Promise((resolve) => {
pendingResolve = resolve;
restoreTimeout = setTimeout(async () => {
isRestoring = true;
try {
const checkpointId = getChapterCheckpoint();
if (checkpointId !== null && checkpointId !== undefined && checkpointId > 0) {
const context = getContext();
const chat = context.chat;
if (chat && checkpointId < chat.length) {
const rangeEnd = checkpointId - 1;
// Check if messages are already hidden
let needsRestore = false;
let hiddenCount = 0;
let visibleCount = 0;
for (let i = 0; i <= rangeEnd; i++) {
if (chat[i]) {
if (chat[i].is_system) {
hiddenCount++;
} else {
visibleCount++;
needsRestore = true;
}
}
}
if (needsRestore) {
await executeSlashCommandsOnChatInput(`/hide 0-${rangeEnd}`, { quiet: true });
currentlyHiddenRange = { start: 0, end: rangeEnd };
// console.log(`[RPG Companion] Restored checkpoint: Hidden messages 0-${rangeEnd}`);
} else {
currentlyHiddenRange = { start: 0, end: rangeEnd };
}
}
}
} finally {
isRestoring = false;
pendingResolve = null;
resolve();
}
}, 100);
});
}
+1 -1
View File
@@ -19,7 +19,7 @@ export function setupClassicStatsButtons() {
// Delegated event listener for increase buttons
$userStatsContainer.on('click', '.rpg-stat-increase', function() {
const stat = $(this).data('stat');
if (extensionSettings.classicStats[stat] < 100) {
if (extensionSettings.classicStats[stat] < 999) {
extensionSettings.classicStats[stat]++;
saveSettings();
saveChatData();
+18 -4
View File
@@ -9,6 +9,7 @@ import {
setPendingDiceRoll
} from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { i18n } from '../../core/i18n.js';
/**
* Rolls the dice and displays result.
@@ -84,16 +85,29 @@ export async function executeRollCommand(command) {
* Updates the dice display in the sidebar.
*/
export function updateDiceDisplay() {
const lastRoll = extensionSettings.lastDiceRoll;
if (lastRoll) {
$('#rpg-last-roll-text').text(`Last Roll (${lastRoll.formula}): ${lastRoll.total}`);
// Hide the entire dice display if showDiceDisplay is false
const $display = $('#rpg-dice-display');
if (!extensionSettings.showDiceDisplay) {
$display.hide();
return;
} else {
$('#rpg-last-roll-text').text('Last Roll: None');
$display.show();
}
const lastRoll = extensionSettings.lastDiceRoll;
const label = i18n.getTranslation('template.mainPanel.lastRoll') || 'Last Roll: ';
const noneValue = i18n.getTranslation('global.none') || 'None';
if (lastRoll) {
$('#rpg-last-roll-text').text(`${label}(${lastRoll.formula}): ${lastRoll.total}`);
} else {
$('#rpg-last-roll-text').text(label + noneValue);
}
}
/**
* Clears the last dice roll.
* Called when the x button is clicked.
*/
export function clearDiceRoll() {
extensionSettings.lastDiceRoll = null;
+130
View File
@@ -0,0 +1,130 @@
/**
* Encounter State Module
* Manages combat encounter state and history
*/
/**
* Current encounter state
*/
export let currentEncounter = {
active: false,
initialized: false,
combatHistory: [], // Array of {role: 'user'|'assistant'|'system', content: string}
combatStats: null, // Current combat stats (HP, party, enemies, etc.)
preEncounterContext: [], // Messages from before the encounter started
encounterStartMessage: '', // The message that triggered the encounter
encounterLog: [] // Full log of combat actions for final summary
};
/**
* Encounter logs storage (per chat)
*/
export let encounterLogs = {
// chatId: [
// {
// timestamp: Date,
// log: [],
// summary: string,
// result: 'victory'|'defeat'|'fled'
// }
// ]
};
/**
* Sets the current encounter state
* @param {object} encounter - The encounter state object
*/
export function setCurrentEncounter(encounter) {
currentEncounter = encounter;
}
/**
* Updates current encounter state with partial data
* @param {object} updates - Partial encounter state to merge
*/
export function updateCurrentEncounter(updates) {
Object.assign(currentEncounter, updates);
}
/**
* Resets the encounter state
*/
export function resetEncounter() {
currentEncounter = {
active: false,
initialized: false,
combatHistory: [],
combatStats: null,
preEncounterContext: [],
encounterStartMessage: '',
encounterLog: []
};
}
/**
* Adds a message to combat history
* @param {string} role - Message role ('user', 'assistant', or 'system')
* @param {string} content - Message content
*/
export function addCombatMessage(role, content) {
currentEncounter.combatHistory.push({ role, content });
}
/**
* Adds an entry to the encounter log
* @param {string} action - The action taken
* @param {string} result - The result of the action
*/
export function addEncounterLogEntry(action, result) {
currentEncounter.encounterLog.push({
timestamp: Date.now(),
action,
result
});
}
/**
* Saves an encounter log for a specific chat
* @param {string} chatId - The chat identifier
* @param {object} logData - The encounter log data
*/
export function saveEncounterLog(chatId, logData) {
if (!encounterLogs[chatId]) {
encounterLogs[chatId] = [];
}
encounterLogs[chatId].push({
timestamp: new Date(),
log: logData.log || [],
summary: logData.summary || '',
result: logData.result || 'unknown'
});
}
/**
* Gets encounter logs for a specific chat
* @param {string} chatId - The chat identifier
* @returns {Array} Array of encounter logs
*/
export function getEncounterLogs(chatId) {
return encounterLogs[chatId] || [];
}
/**
* Clears all encounter logs for a specific chat
* @param {string} chatId - The chat identifier
*/
export function clearEncounterLogs(chatId) {
if (encounterLogs[chatId]) {
delete encounterLogs[chatId];
}
}
/**
* Exports encounter logs as JSON
* @param {string} chatId - The chat identifier
* @returns {string} JSON string of encounter logs
*/
export function exportEncounterLogs(chatId) {
const logs = getEncounterLogs(chatId);
return JSON.stringify(logs, null, 2);
}
+85 -2
View File
@@ -63,7 +63,7 @@ export async function ensureHtmlCleaningRegex(st_extension_settings, saveSetting
);
if (alreadyExists) {
console.log('[RPG Companion] HTML cleaning regex already exists, skipping import');
// console.log('[RPG Companion] HTML cleaning regex already exists, skipping import');
return;
}
@@ -107,10 +107,93 @@ export async function ensureHtmlCleaningRegex(st_extension_settings, saveSetting
console.warn('[RPG Companion] saveSettingsDebounced is not a function, cannot save HTML regex');
}
console.log('[RPG Companion] ✅ HTML cleaning regex imported successfully');
// console.log('[RPG Companion] ✅ HTML cleaning regex imported successfully');
} catch (error) {
console.error('[RPG Companion] Failed to import HTML cleaning regex:', error);
console.error('[RPG Companion] Error details:', error.message, error.stack);
// Don't throw - this is a nice-to-have feature
}
}
/**
* Automatically imports a regex script to clean tracker JSON from outgoing prompts.
* This is useful when switching from together mode to separate mode mid-roleplay,
* as it prevents old tracker JSON from chat history being sent to the AI.
* @param {Object} st_extension_settings - SillyTavern extension settings object
* @param {Function} saveSettingsDebounced - Function to save settings
*/
export async function ensureTrackerCleaningRegex(st_extension_settings, saveSettingsDebounced) {
try {
// Validate extension settings structure
if (!st_extension_settings || typeof st_extension_settings !== 'object') {
console.warn('[RPG Companion] Invalid extension_settings object, skipping tracker cleaning regex import');
return;
}
// Check if the tracker cleaning regex already exists
const scriptName = 'Clean RPG Trackers (From Outgoing Prompt)';
const existingScripts = st_extension_settings?.regex || [];
// Validate regex array
if (!Array.isArray(existingScripts)) {
console.warn('[RPG Companion] extension_settings.regex is not an array, resetting to empty array');
st_extension_settings.regex = [];
}
const alreadyExists = existingScripts.some(script =>
script && typeof script === 'object' && script.scriptName === scriptName
);
if (alreadyExists) {
// console.log('[RPG Companion] Tracker cleaning regex already exists, skipping import');
return;
}
// Generate a UUID for the script
const uuidv4 = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
// Create the regex script to remove ```json...``` blocks containing tracker data
// This regex matches markdown code blocks with "json" language tag
const regexScript = {
id: uuidv4(),
scriptName: scriptName,
findRegex: '/```json\\s*\\n\\{[\\s\\S]*?(?:\"userStats\"|\"infoBox\"|\"characters\")[\\s\\S]*?\\}\\s*\\n```/gm',
replaceString: '',
trimStrings: [],
placement: [2], // 2 = Input (affects outgoing prompt)
disabled: false,
markdownOnly: false,
promptOnly: true,
runOnEdit: true,
substituteRegex: 0,
minDepth: null,
maxDepth: null
};
// Add to global regex scripts
if (!Array.isArray(st_extension_settings.regex)) {
st_extension_settings.regex = [];
}
st_extension_settings.regex.push(regexScript);
// Save the changes
if (typeof saveSettingsDebounced === 'function') {
saveSettingsDebounced();
} else {
console.warn('[RPG Companion] saveSettingsDebounced is not a function, cannot save tracker cleaning regex');
}
// console.log('[RPG Companion] ✅ Tracker cleaning regex imported successfully');
} catch (error) {
console.error('[RPG Companion] Failed to import tracker cleaning regex:', error);
console.error('[RPG Companion] Error details:', error.message, error.stack);
// Don't throw - this is a nice-to-have feature
}
}
+167
View File
@@ -0,0 +1,167 @@
/**
* JSON Cleaning Module
* Automatically registers a regex script to strip tracker JSON from Together mode output
*/
/**
* Registers an output transformation regex to remove tracker JSON from messages
* This uses SillyTavern's built-in regex system to transform text BEFORE display
* @param {Object} st_extension_settings - SillyTavern extension settings object
* @param {Function} saveSettingsDebounced - Function to save settings
*/
export async function ensureJsonCleaningRegex(st_extension_settings, saveSettingsDebounced) {
try {
// Validate extension settings structure
if (!st_extension_settings || typeof st_extension_settings !== 'object') {
console.warn('[RPG Companion] Invalid extension_settings object, skipping JSON cleaning regex');
return;
}
// Check if the JSON cleaning regex already exists
const scriptName = 'RPG Companion - Remove Tracker JSON (Together Mode)';
const existingScripts = st_extension_settings?.regex || [];
// Validate regex array
if (!Array.isArray(existingScripts)) {
console.warn('[RPG Companion] extension_settings.regex is not an array, resetting to empty array');
st_extension_settings.regex = [];
}
const existingScript = existingScripts.find(script =>
script && script.scriptName && script.scriptName === scriptName
);
if (existingScript) {
// Update existing script with new regex pattern if it's different
const newPattern = '/```(?:json|markdown)?[\\s\\S]*?```/gim';
// Always ensure these properties are set correctly
let needsSave = false;
if (existingScript.findRegex !== newPattern) {
existingScript.findRegex = newPattern;
needsSave = true;
}
if (JSON.stringify(existingScript.placement) !== JSON.stringify([2])) {
existingScript.placement = [2]; // 2 = AI Output
needsSave = true;
}
if (existingScript.disabled !== false) {
existingScript.disabled = false;
needsSave = true;
}
if (existingScript.runOnEdit !== true) {
existingScript.runOnEdit = true;
needsSave = true;
}
if (existingScript.markdownOnly !== true) {
existingScript.markdownOnly = true; // Only process markdown
needsSave = true;
}
if (existingScript.promptOnly !== true) {
existingScript.promptOnly = true; // Enable prompt processing
needsSave = true;
}
if (needsSave && typeof saveSettingsDebounced === 'function') {
// Force immediate save and wait for it
const saveResult = saveSettingsDebounced();
if (saveResult && typeof saveResult.then === 'function') {
await saveResult;
}
// Small delay to ensure save completes
await new Promise(resolve => setTimeout(resolve, 100));
console.log('[RPG Companion] ✅ Updated JSON cleaning regex to v3.2.6 settings.');
} else {
console.log('[RPG Companion] JSON Cleaning Regex is up to date.');
}
return;
}
// Generate a UUID for the script
const uuidv4 = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
// Create the regex script object for cleaning JSON tracker data
// This regex matches ```json...```, ```markdown...```, or plain ```...``` code blocks
// The prompt now explicitly instructs models to use this format
// Updated to handle various whitespace scenarios and ensure it catches all variations
const regexScript = {
id: uuidv4(),
scriptName: scriptName,
// Match ```json...```, ```markdown...```, or ```...``` code blocks (handles spaces, newlines, any content)
// Using a more permissive pattern to catch all variations
findRegex: '/```(?:json|markdown)?[\\s\\S]*?```/gim',
replaceString: '',
trimStrings: [],
placement: [2], // 2 = AI Output
disabled: false,
markdownOnly: true,
promptOnly: true, // Enable prompt processing
runOnEdit: true,
substituteRegex: 0,
minDepth: null,
maxDepth: null
};
// Add to global regex scripts
if (!Array.isArray(st_extension_settings.regex)) {
st_extension_settings.regex = [];
}
st_extension_settings.regex.push(regexScript);
console.log('[RPG Companion] JSON Cleaning Regex created and activated.');
// Save the changes
if (typeof saveSettingsDebounced === 'function') {
saveSettingsDebounced();
} else {
console.warn('[RPG Companion] saveSettingsDebounced is not a function, cannot save JSON cleaning regex');
}
} catch (error) {
console.error('[RPG Companion] JSON Cleaning Regex failed to properly initialize!');
console.error('[RPG Companion] Error details:', error.message, error.stack);
// Don't throw - continue without it
}
}
/**
* Removes the JSON cleaning regex if it exists
* Useful when switching to separate mode or disabling the feature
* @param {Object} st_extension_settings - SillyTavern extension settings object
* @param {Function} saveSettingsDebounced - Function to save settings
*/
export function removeJsonCleaningRegex(st_extension_settings, saveSettingsDebounced) {
try {
if (!st_extension_settings?.regex || !Array.isArray(st_extension_settings.regex)) {
return;
}
const scriptName = 'RPG Companion - Remove Tracker JSON (Together Mode)';
const initialLength = st_extension_settings.regex.length;
st_extension_settings.regex = st_extension_settings.regex.filter(script =>
!script || !script.scriptName || script.scriptName !== scriptName
);
if (st_extension_settings.regex.length < initialLength) {
// console.log('[RPG Companion] Removed JSON cleaning regex');
if (typeof saveSettingsDebounced === 'function') {
saveSettingsDebounced();
}
}
} catch (error) {
console.error('[RPG Companion] Failed to remove JSON cleaning regex:', error);
}
}
-267
View File
@@ -1,267 +0,0 @@
/**
* Lorebook Limiter Module
* Adds maximum activation limit to SillyTavern's World Info system
*/
import { eventSource, event_types } from '../../../../../../../script.js';
let maxActivations = 0; // 0 = unlimited
let settingsInitialized = false;
let activatedEntriesThisGeneration = [];
/**
* Initialize the lorebook limiter
*/
export function initLorebookLimiter() {
console.log('[Lorebook Limiter] Initializing...');
// Load saved setting
const saved = localStorage.getItem('rpg_max_lorebook_activations');
if (saved !== null) {
maxActivations = parseInt(saved, 10);
}
// Wait for World Info settings to be ready
eventSource.on('worldInfoSettings', () => {
setTimeout(() => {
if (!settingsInitialized) {
injectMaxActivationsUI();
settingsInitialized = true;
}
}, 100);
});
// Try when the WI drawer is opened
const tryInjectOnClick = () => {
const wiButton = document.querySelector('#WIDrawerIcon');
if (wiButton) {
wiButton.addEventListener('click', () => {
setTimeout(() => {
if (!settingsInitialized) {
injectMaxActivationsUI();
settingsInitialized = true;
}
}, 300);
});
console.log('[Lorebook Limiter] Attached to WI drawer button');
}
};
// Also try on app ready
eventSource.on('app_ready', () => {
setTimeout(() => {
tryInjectOnClick();
if (!settingsInitialized) {
injectMaxActivationsUI();
settingsInitialized = true;
}
}, 1000);
});
// Patch the world info activation system
patchWorldInfoActivation();
}
/**
* Inject the Maximum Activations UI into World Info settings
*/
function injectMaxActivationsUI() {
console.log('[Lorebook Limiter] Injecting UI...');
// Check if already injected
if (document.querySelector('#rpg-max-lorebook-activations-container')) {
console.log('[Lorebook Limiter] UI already injected');
return;
}
// Find the Memory Recollection button - we'll add our UI right after it
const memoryButton = document.querySelector('.rpg-memory-recollection-btn');
if (!memoryButton) {
console.log('[Lorebook Limiter] Memory Recollection button not found yet');
return;
}
const container = memoryButton.parentElement;
if (!container) {
console.log('[Lorebook Limiter] Could not find button container');
return;
}
console.log('[Lorebook Limiter] Found Memory Recollection button, injecting slider after it');
// Create the UI - styled to match the extension's theme
const settingHTML = `
<div id="rpg-max-lorebook-activations-container" class="rpg-lorebook-limiter-container">
<label class="rpg-lorebook-limiter-label">
<span class="rpg-lorebook-limiter-title">Max Lorebook Activations</span>
<input type="number"
id="rpg-max-activations-input"
class="rpg-lorebook-limiter-input"
min="0"
max="9999"
step="1"
value="${maxActivations}"
placeholder="0 = unlimited" />
</label>
<small class="rpg-lorebook-limiter-hint">Limit entries per generation (0 = unlimited)</small>
</div>
`;
// Insert after the Memory Recollection button
memoryButton.insertAdjacentHTML('afterend', settingHTML);
// Add event listener
const input = document.querySelector('#rpg-max-activations-input');
if (input) {
input.addEventListener('input', (e) => {
let value = parseInt(e.target.value, 10);
if (isNaN(value) || value < 0) value = 0;
if (value > 9999) value = 9999;
maxActivations = value;
e.target.value = value;
localStorage.setItem('rpg_max_lorebook_activations', value.toString());
console.log(`[Lorebook Limiter] Max activations set to: ${value}`);
});
console.log('[Lorebook Limiter] ✅ UI injected successfully');
}
}
/**
* Patch the world info activation system to enforce the limit
*/
function patchWorldInfoActivation() {
console.log('[Lorebook Limiter] Setting up activation limiter...');
// We need to intercept at the module level
// Use a Proxy on the module loader
const originalDefine = window.define;
const originalRequire = window.require;
// Try multiple approaches to hook into the WI system
const attemptPatch = () => {
// Approach 1: Direct window access
if (window.getWorldInfoPrompt) {
const original = window.getWorldInfoPrompt;
window.getWorldInfoPrompt = async function(...args) {
const result = await original.apply(this, args);
if (maxActivations > 0 && result) {
// Count entries in the worldInfoString
const lines = (result.worldInfoBefore + result.worldInfoAfter).split('\n').filter(l => l.trim());
if (lines.length > maxActivations) {
console.log(`[Lorebook Limiter] Limiting ${lines.length} WI lines to ${maxActivations}`);
// Trim the strings
const limitedLines = lines.slice(0, maxActivations);
result.worldInfoBefore = limitedLines.join('\n');
result.worldInfoAfter = '';
result.worldInfoString = result.worldInfoBefore;
console.log(`[Lorebook Limiter] ✅ Limited from ${lines.length} to ${limitedLines.length} entries`);
}
}
return result;
};
console.log('[Lorebook Limiter] ✅ Patched window.getWorldInfoPrompt');
return true;
}
// Approach 2: Through SillyTavern context
if (window.SillyTavern?.getContext) {
const ctx = window.SillyTavern.getContext();
if (ctx.getWorldInfoPrompt) {
const original = ctx.getWorldInfoPrompt;
ctx.getWorldInfoPrompt = async function(...args) {
const result = await original.apply(this, args);
if (maxActivations > 0 && result) {
const lines = (result.worldInfoBefore + result.worldInfoAfter).split('\n').filter(l => l.trim());
if (lines.length > maxActivations) {
console.log(`[Lorebook Limiter] Limiting ${lines.length} WI entries to ${maxActivations}`);
const limitedLines = lines.slice(0, maxActivations);
result.worldInfoBefore = limitedLines.join('\n');
result.worldInfoAfter = '';
result.worldInfoString = result.worldInfoBefore;
}
}
return result;
};
console.log('[Lorebook Limiter] ✅ Patched SillyTavern.getContext().getWorldInfoPrompt');
return true;
}
// Try checkWorldInfo instead
if (ctx.checkWorldInfo) {
const original = ctx.checkWorldInfo;
ctx.checkWorldInfo = async function(...args) {
const result = await original.apply(this, args);
if (maxActivations > 0 && result?.allActivatedEntries?.size > maxActivations) {
console.log(`[Lorebook Limiter] Limiting ${result.allActivatedEntries.size} entries to ${maxActivations}`);
// Keep only first N entries
const entries = Array.from(result.allActivatedEntries.entries());
result.allActivatedEntries = new Map(entries.slice(0, maxActivations));
// Also limit the string output
const lines = (result.worldInfoBefore + result.worldInfoAfter).split('\n').filter(l => l.trim());
if (lines.length > maxActivations) {
const limitedLines = lines.slice(0, maxActivations);
result.worldInfoBefore = limitedLines.join('\n');
result.worldInfoAfter = '';
}
console.log(`[Lorebook Limiter] ✅ Limited to ${result.allActivatedEntries.size} entries`);
}
return result;
};
console.log('[Lorebook Limiter] ✅ Patched SillyTavern.getContext().checkWorldInfo');
return true;
}
}
return false;
};
// Try immediately
if (!attemptPatch()) {
// Retry after delays
setTimeout(() => attemptPatch() || setTimeout(() => attemptPatch(), 2000), 1000);
}
}
/**
* Update the maximum activations limit
*/
export function setMaxActivations(value) {
maxActivations = parseInt(value, 10);
localStorage.setItem('rpg_max_lorebook_activations', value.toString());
// Update UI if it exists
const valueDisplay = document.querySelector('#rpg-max-activations-value');
const slider = document.querySelector('#rpg-max-activations-slider');
if (valueDisplay) {
valueDisplay.textContent = value;
}
if (slider) {
slider.value = value;
}
}
/**
* Get current maximum activations limit
*/
export function getMaxActivations() {
return maxActivations;
}
-843
View File
@@ -1,843 +0,0 @@
/**
* Memory Recollection Module
* Handles generation of lorebook entries from chat history
*/
import { chat, characters, this_chid, generateRaw, substituteParams, eventSource, event_types } from '../../../../../../../script.js';
import { selected_group } from '../../../../../../group-chats.js';
import { extensionSettings, addDebugLog } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { checkWorldInfo, createNewWorldInfo, openWorldInfoEditor, saveWorldInfo, setWorldInfoSettings } from '../../../../../../world-info.js';
/**
* Helper to log to both console and debug logs array
*/
function debugLog(message, data = null) {
if (data !== null && data !== undefined) {
console.log(message, data);
} else {
console.log(message);
}
if (extensionSettings.debugMode) {
addDebugLog(message, data);
}
}
/**
* Get or create the Memory Recollection lorebook
* @returns {Promise<string>} The UID of the Memory Recollection lorebook
*/
async function getOrCreateMemoryLorebook() {
const lorebookName = 'Memory Recollection';
try {
debugLog('[Memory Recollection] Checking for existing lorebook...');
// Use checkWorldInfo to see if it exists
const exists = await checkWorldInfo(lorebookName);
if (exists) {
debugLog('[Memory Recollection] Found existing lorebook:', lorebookName);
return lorebookName;
}
// Create new lorebook using SillyTavern's imported function
debugLog('[Memory Recollection] Creating new Memory Recollection lorebook');
// Call the imported createNewWorldInfo function
await createNewWorldInfo(lorebookName, true);
debugLog('[Memory Recollection] Created lorebook:', lorebookName);
// Wait for the file system to settle
await new Promise(resolve => setTimeout(resolve, 500));
return lorebookName;
} catch (error) {
console.error('[Memory Recollection] Error in getOrCreateMemoryLorebook:', error);
throw error;
}
}
/**
* Create the constant "Relevant Memories:" header entry
* @param {string} lorebookUid - The UID of the lorebook
* @returns {Object} The header entry object
*/
function createConstantHeaderEntry() {
const entry = {
uid: 1, // Fixed UID so it's always first
key: [],
keysecondary: [],
comment: 'Relevant Memories Header',
content: 'Relevant Memories:',
constant: true, // Always inserted
vectorized: false,
selective: false,
selectiveLogic: 0,
addMemo: false,
order: 99, // First in order
position: 4, // at Depth
disable: false,
ignoreBudget: false,
excludeRecursion: false,
preventRecursion: false,
matchPersonaDescription: false,
matchCharacterDescription: false,
matchCharacterPersonality: false,
matchCharacterDepthPrompt: false,
matchScenario: false,
matchCreatorNotes: false,
delayUntilRecursion: false,
probability: 100,
useProbability: true,
depth: 1, // Insertion depth
outletName: '',
group: '',
groupOverride: false,
groupWeight: 100,
scanDepth: null,
caseSensitive: null,
matchWholeWords: null,
useGroupScoring: null,
automationId: '',
role: 0, // System role
sticky: 0,
cooldown: 0,
delay: 0,
triggers: [],
displayIndex: 0,
characterFilter: {
isExclude: false,
names: [],
tags: []
}
};
debugLog('[Memory Recollection] Created constant header entry');
return entry;
}
/**
* Save a world info entry to a lorebook
* @param {string} lorebookUid - The filename/UID of the lorebook
* @param {Object} entry - The entry data
*/
async function saveWorldInfoEntry(lorebookUid, entry) {
try {
debugLog('[Memory Recollection] Saving entry to lorebook:', lorebookUid);
// Open the world info editor for this lorebook to load its data
await openWorldInfoEditor(lorebookUid);
// Wait for it to load
await new Promise(resolve => setTimeout(resolve, 500));
// Now access the loaded world info data
const worldInfo = window.world_info;
debugLog('[Memory Recollection] World info after opening:', {
type: typeof worldInfo,
isArray: Array.isArray(worldInfo),
hasEntries: worldInfo?.entries !== undefined,
keys: worldInfo ? Object.keys(worldInfo).slice(0, 10) : null
});
// Try different structures - it might be an array or might have different properties
let entries;
if (worldInfo && typeof worldInfo === 'object') {
if (worldInfo.entries) {
entries = worldInfo.entries;
} else if (Array.isArray(worldInfo)) {
// If it's an array, convert to entries object
entries = {};
worldInfo.forEach((e, i) => {
if (e && e.uid) {
entries[e.uid] = e;
}
});
}
}
if (!entries) {
entries = {};
}
// Add the entry
entries[entry.uid] = entry;
debugLog('[Memory Recollection] Entry added, saving world info...');
// Save using the imported saveWorldInfo function
// Pass the entries as the data structure
await saveWorldInfo(lorebookUid, { entries });
debugLog('[Memory Recollection] Entry saved successfully');
return { success: true };
} catch (error) {
console.error('[Memory Recollection] Error saving entry:', error);
throw error;
}
}
/**
* Save multiple world info entries to a lorebook at once
* @param {string} lorebookUid - The filename/UID of the lorebook
* @param {Array} newEntries - Array of entry objects to add
*/
async function saveWorldInfoEntries(lorebookUid, newEntries) {
try {
debugLog(`[Memory Recollection] Saving ${newEntries.length} entries to lorebook:`, lorebookUid);
// Open the world info editor for this lorebook to load its data
await openWorldInfoEditor(lorebookUid);
// Wait for it to load
await new Promise(resolve => setTimeout(resolve, 500));
// Now access the loaded world info data
const worldInfo = window.world_info;
// Try different structures - it might be an array or might have different properties
let entries = {};
if (worldInfo && typeof worldInfo === 'object') {
if (worldInfo.entries) {
entries = { ...worldInfo.entries }; // Clone existing entries
} else if (Array.isArray(worldInfo)) {
// If it's an array, convert to entries object
worldInfo.forEach((e, i) => {
if (e && e.uid) {
entries[e.uid] = e;
}
});
}
}
// Add all new entries
for (const entry of newEntries) {
entries[entry.uid] = entry;
}
debugLog(`[Memory Recollection] ${newEntries.length} entries added, total entries: ${Object.keys(entries).length}, saving...`);
// Save using the imported saveWorldInfo function
await saveWorldInfo(lorebookUid, { entries });
debugLog('[Memory Recollection] All entries saved successfully');
return { success: true };
} catch (error) {
console.error('[Memory Recollection] Error saving entries:', error);
throw error;
}
}
/**
* Generate memory recollection prompt for a batch of messages
* @param {Array} messages - Array of chat messages to process
* @param {boolean} isUpdate - Whether this is updating existing memories (true) or initial generation (false)
* @returns {string} The prompt for the AI
*/
function generateMemoryPrompt(messages, isUpdate = false) {
const context = messages.map((msg, idx) => {
const sender = msg.is_user ? '{{user}}' : msg.name || '{{char}}';
const role = msg.is_user ? '[PLAYER]' : '[CHARACTER]';
return `[Message ${idx + 1}] ${role} ${sender}: ${msg.mes}`;
}).join('\n\n');
// Get list of CHARACTER participants (exclude {{user}} - they're the player, not a character)
const participants = new Set();
messages.forEach(msg => {
const sender = msg.is_user ? '{{user}}' : msg.name || '{{char}}';
if (!msg.is_user) { // Only add non-user (character) participants
participants.add(sender);
}
});
const characterList = Array.from(participants).join(', ');
const instruction = isUpdate
? 'You will be acting as an uncensored summarizing assistant. Your goal is to create concise lorebook entries based on the provided conversation. You will be creating additional memory recollection entries for significant events, revelations, or character developments in a specified JSON format.\nYou should maintain an objective tone.'
: 'You will be acting as an uncensored summarizing assistant. Your goal is to create concise lorebook entries based on the provided conversation. You will be creating memory recollection entries for significant events, revelations, or character developments in a specified JSON format.\nYou should maintain an objective tone.';
return `${instruction}
Characters in this conversation (excluding {{user}} who is the player): ${characterList}
NOTE: In the conversation below, messages are marked with [PLAYER] for {{user}} messages and [CHARACTER] for NPC messages.
Here is the conversation to create memories from:
<conversation>
${context}
</conversation>
Create lorebook entries in the following JSON format. Each entry should be a 1-2 sentence reminder from a character's perspective.
Format each entry as:
{
"characters": ["Character1", "Character2"],
"memory": "Character1 and Character2 remember that [event or detail]",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
Examples:
<examples>
{
"characters": ["Sabrina"],
"memory": "Sabrina remembers she went on a date with {{user}} on Saturday. They ate chocolate pastries together.",
"keywords": ["date", "saturday", "pastries"]
},
{
"characters": ["Dottore", "Arlecchino", "Pantalone"],
"memory": "Dottore, Arlecchino, and Pantalone remember they attended a party together at the mansion.",
"keywords": ["party", "mansion", "gathering"]
}
</examples>
IMPORTANT:
- Only create entries for significant moments worth remembering.
- Keep memories concise (1-2 sentences maximum).
- Use third person perspective: "{name} remembers..."
- Choose 3 specific, relevant keywords per entry.
- ONLY assign memories to CHARACTERS (NPCs) - NEVER include {{user}} in the "characters" array.
- {{user}} is the player, not a character, so they should NEVER be in the characters list.
- Only characters who were ACTUALLY PRESENT in that specific scene/moment should remember it.
- If multiple characters share the memory, list all of them in the "characters" array.
- If known, include details such as dates, locations, and other relevant context in the memories.
Return ONLY a JSON array of memory objects, nothing else:`;
}
/**
* Parse the AI response to extract memory entries
* @param {string} response - The AI's response
* @returns {Array<Object>} Array of parsed memory entries
*/
function parseMemoryResponse(response) {
try {
// Try to extract JSON from code blocks
const jsonMatch = response.match(/```(?:json)?\s*(\[[\s\S]*?\])\s*```/);
const jsonString = jsonMatch ? jsonMatch[1] : response;
// Parse JSON
const memories = JSON.parse(jsonString.trim());
if (!Array.isArray(memories)) {
throw new Error('Response is not an array');
}
debugLog('[Memory Recollection] Parsed memories:', memories);
return memories;
} catch (error) {
debugLog('[Memory Recollection] Failed to parse response:', error);
console.error('[Memory Recollection] Parse error:', error);
console.error('[Memory Recollection] Raw response:', response);
return [];
}
}
/**
* Create a world info entry from a memory object
* @param {string} lorebookUid - The UID of the lorebook
* @param {Object} memory - The memory object
* @param {number} index - The index for ordering
*/
async function createMemoryEntry(lorebookUid, memory, index) {
const { characters: characterList, memory: content, keywords } = memory;
// Handle character filter - just use the character names directly
let characterNames = [];
if (Array.isArray(characterList) && characterList.length > 0) {
// New format: array of character names
characterNames = characterList.map(name => name.trim());
debugLog(`[Memory Recollection] Character names for filter:`, characterNames);
} else if (typeof characterList === 'string' && characterList.trim() !== '') {
// Legacy string format or comma-separated - parse it
characterNames = characterList.split(',').map(n => n.trim()).filter(n => n !== '');
debugLog(`[Memory Recollection] Character names for filter:`, characterNames);
}
const entry = {
uid: Date.now() + index, // Simple UID generation
key: keywords || [],
keysecondary: [],
comment: `Memory: ${characterNames.join(', ')}`,
content: content,
constant: false,
vectorized: false,
selective: true,
selectiveLogic: 0,
addMemo: false,
order: 100,
position: 4, // at Depth
disable: false,
ignoreBudget: false,
excludeRecursion: false,
preventRecursion: false,
matchPersonaDescription: false,
matchCharacterDescription: false,
matchCharacterPersonality: false,
matchCharacterDepthPrompt: false,
matchScenario: false,
matchCreatorNotes: false,
delayUntilRecursion: false,
probability: 100,
useProbability: true,
depth: 1, // Insertion depth
outletName: '',
group: '',
groupOverride: false,
groupWeight: 100,
scanDepth: null,
caseSensitive: null,
matchWholeWords: null,
useGroupScoring: null,
automationId: '',
role: 0, // 0 = System role (matching the example)
sticky: 0,
cooldown: 0,
delay: 0,
triggers: [],
displayIndex: index + 1,
characterFilter: {
isExclude: false,
names: characterNames, // Array of character names
tags: []
},
extensions: {
position: 4, // at Depth
depth: 1,
role: 1
}
};
debugLog(`[Memory Recollection] Created entry for ${characterNames.join(', ')} with character filter:`, characterNames);
return entry; // Return instead of saving
}
/**
* Process a batch of messages and generate memory entries
* @param {Array} messages - Array of messages to process
* @param {string} lorebookUid - The UID of the lorebook
* @param {boolean} isUpdate - Whether this is an update (true) or initial generation (false)
* @param {number} startIndex - Starting index for entry ordering
* @returns {Promise<Array>} Array of created entries
*/
async function processBatch(messages, lorebookUid, isUpdate, startIndex) {
debugLog(`[Memory Recollection] Processing batch of ${messages.length} messages (isUpdate: ${isUpdate})`);
const prompt = generateMemoryPrompt(messages, isUpdate);
// Generate using SillyTavern's generateRaw
const response = await generateRaw(prompt, '', false, false);
if (!response) {
throw new Error('No response from AI');
}
// Parse the response
const memories = parseMemoryResponse(response);
if (memories.length === 0) {
debugLog('[Memory Recollection] No memories extracted from this batch');
// Return -1 to signal parse failure (vs 0 for valid but empty response)
throw new Error('Failed to parse memories from AI response. The response may be invalid or the service may be unavailable.');
}
// Create entries for each memory (but don't save yet)
const entries = [];
for (let i = 0; i < memories.length; i++) {
const entry = await createMemoryEntry(lorebookUid, memories[i], startIndex + i);
entries.push(entry);
}
debugLog(`[Memory Recollection] Created ${entries.length} entries from batch`);
return entries;
}
/**
* Main function to start memory recollection process
* @param {Function} onProgress - Callback for progress updates (current, total)
* @param {Function} onComplete - Callback when complete
* @param {Function} onError - Callback for errors
*/
export async function startMemoryRecollection(onProgress, onComplete, onError) {
try {
debugLog('[Memory Recollection] Starting memory recollection process');
// Get or create the lorebook
const lorebookUid = await getOrCreateMemoryLorebook();
// Get messages to process count from settings
const messagesToProcess = extensionSettings.memoryMessagesToProcess || 16;
// Check if this is an update (lorebook already exists with entries)
const world_info = window.world_info;
const lorebook = world_info.globalSelect?.find(book => book.uid === lorebookUid);
const existingEntryCount = lorebook?.entries ? Object.keys(lorebook.entries).length : 0;
const isUpdate = existingEntryCount > 1; // More than just the header
let messagesToProcessArray;
if (isUpdate) {
// Process only the last batch
const totalMessages = chat.length;
const startIdx = Math.max(0, totalMessages - messagesToProcess);
messagesToProcessArray = chat.slice(startIdx);
debugLog(`[Memory Recollection] Update mode: Processing last ${messagesToProcess} messages`);
} else {
// Process entire chat in batches
messagesToProcessArray = chat;
debugLog(`[Memory Recollection] Initial mode: Processing all ${chat.length} messages`);
}
const totalBatches = Math.ceil(messagesToProcessArray.length / messagesToProcess);
let entryIndex = existingEntryCount;
const allEntries = []; // Accumulate all entries here
for (let i = 0; i < totalBatches; i++) {
const batchStart = i * messagesToProcess;
const batchEnd = Math.min(batchStart + messagesToProcess, messagesToProcessArray.length);
const batch = messagesToProcessArray.slice(batchStart, batchEnd);
onProgress(i + 1, totalBatches);
try {
const batchEntries = await processBatch(batch, lorebookUid, isUpdate && i === 0, entryIndex);
allEntries.push(...batchEntries); // Add to accumulator
entryIndex += batchEntries.length;
} catch (error) {
// Batch failed - ask user if they want to retry
debugLog('[Memory Recollection] Batch failed:', error.message);
const retry = await new Promise(resolve => {
const retryModal = document.createElement('div');
retryModal.className = 'rpg-memory-modal-overlay';
retryModal.innerHTML = `
<div class="rpg-memory-modal">
<div class="rpg-memory-modal-header">
<h3>⚠️ Generation Failed</h3>
</div>
<div class="rpg-memory-modal-body">
<p><strong>Error:</strong> ${error.message}</p>
<p>Batch ${i + 1} of ${totalBatches} failed to process.</p>
<p>Would you like to retry this batch?</p>
</div>
<div class="rpg-memory-modal-footer">
<button class="rpg-memory-modal-btn rpg-memory-cancel">Skip Batch</button>
<button class="rpg-memory-modal-btn rpg-memory-proceed">Retry</button>
</div>
</div>
`;
document.body.appendChild(retryModal);
retryModal.querySelector('.rpg-memory-cancel').addEventListener('click', () => {
document.body.removeChild(retryModal);
resolve(false);
});
retryModal.querySelector('.rpg-memory-proceed').addEventListener('click', () => {
document.body.removeChild(retryModal);
resolve(true);
});
});
if (retry) {
// Retry the same batch
i--;
continue;
}
// Otherwise skip this batch and continue
}
// Small delay between batches to avoid rate limiting
if (i < totalBatches - 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
// Add the constant header entry at the end
const headerEntry = createConstantHeaderEntry();
allEntries.push(headerEntry); // Add to end of array
// Save all entries at once
if (allEntries.length > 0) {
debugLog(`[Memory Recollection] Saving ${allEntries.length} total entries (including header) to lorebook...`);
await saveWorldInfoEntries(lorebookUid, allEntries);
// Trigger world info refresh by simulating the WI button click to reload the list
// This ensures the newly created lorebook appears in the dropdown
const wiButton = document.querySelector('#WIDrawerIcon');
if (wiButton) {
// Close and reopen to force refresh
wiButton.click();
await new Promise(resolve => setTimeout(resolve, 100));
wiButton.click();
debugLog('[Memory Recollection] Triggered WI panel refresh');
}
// Also emit the update event
eventSource.emit(event_types.WORLDINFO_SETTINGS_UPDATED);
}
debugLog('[Memory Recollection] Process complete');
// Open the World Info editor with the Memory Recollection lorebook
try {
await openWorldInfoEditor(lorebookUid);
debugLog('[Memory Recollection] Opened World Info editor with Memory Recollection lorebook');
} catch (err) {
debugLog('[Memory Recollection] Could not open World Info editor:', err);
}
onComplete(allEntries.length);
} catch (error) {
debugLog('[Memory Recollection] Error:', error);
onError(error);
}
}
/**
* Show memory recollection confirmation modal
*/
export function showMemoryRecollectionModal() {
const modal = document.createElement('div');
modal.className = 'rpg-memory-modal-overlay';
modal.innerHTML = `
<div class="rpg-memory-modal">
<div class="rpg-memory-modal-header">
<h3>⚠️ Memory Recollection</h3>
</div>
<div class="rpg-memory-modal-body">
<p><strong>Warning!</strong> This process will trigger multiple generation requests and will take time.</p>
<p>Ensure your currently selected model is the one you want to use for this task.</p>
<p class="rpg-memory-modal-info">
Messages per batch: <strong>${extensionSettings.memoryMessagesToProcess || 16}</strong>
<br>
<span class="rpg-memory-modal-hint">(You can change this in the extension settings)</span>
</p>
</div>
<div class="rpg-memory-modal-footer">
<button class="rpg-memory-modal-btn rpg-memory-cancel">Cancel</button>
<button class="rpg-memory-modal-btn rpg-memory-proceed">Proceed</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Event listeners
modal.querySelector('.rpg-memory-cancel').addEventListener('click', () => {
document.body.removeChild(modal);
});
modal.querySelector('.rpg-memory-proceed').addEventListener('click', () => {
document.body.removeChild(modal);
showMemoryProgressModal();
});
// Click outside to close
modal.addEventListener('click', (e) => {
if (e.target === modal) {
document.body.removeChild(modal);
}
});
}
/**
* Show progress modal during memory recollection
*/
function showMemoryProgressModal() {
const modal = document.createElement('div');
modal.className = 'rpg-memory-modal-overlay';
modal.innerHTML = `
<div class="rpg-memory-modal">
<div class="rpg-memory-modal-header">
<h3>🧠 Processing Memories...</h3>
</div>
<div class="rpg-memory-modal-body">
<p class="rpg-memory-progress-text">Processing batch <span class="rpg-memory-current">0</span> of <span class="rpg-memory-total">0</span></p>
<div class="rpg-memory-progress-bar">
<div class="rpg-memory-progress-fill"></div>
</div>
<p class="rpg-memory-status">Initializing...</p>
</div>
</div>
`;
document.body.appendChild(modal);
const currentSpan = modal.querySelector('.rpg-memory-current');
const totalSpan = modal.querySelector('.rpg-memory-total');
const progressFill = modal.querySelector('.rpg-memory-progress-fill');
const statusText = modal.querySelector('.rpg-memory-status');
// Start the process
startMemoryRecollection(
(current, total) => {
currentSpan.textContent = current;
totalSpan.textContent = total;
const percentage = (current / total) * 100;
progressFill.style.width = `${percentage}%`;
statusText.textContent = `Processing memories from batch ${current}...`;
},
(entriesCreated) => {
statusText.innerHTML = `
<strong>✅ Complete!</strong> Created ${entriesCreated} memory entries.<br>
<small>The "Memory Recollection" lorebook has been created.</small><br>
<strong style="color: #ffa500; margin-top: 10px; display: block;">⚠️ Please refresh SillyTavern to see the lorebook in the World Info dropdown.</strong>
`;
progressFill.style.width = '100%';
// Add close button
const closeBtn = document.createElement('button');
closeBtn.className = 'rpg-memory-modal-btn rpg-memory-close';
closeBtn.textContent = 'Close';
closeBtn.style.marginTop = '15px';
closeBtn.addEventListener('click', () => {
document.body.removeChild(modal);
});
modal.querySelector('.rpg-memory-modal-body').appendChild(closeBtn);
},
(error) => {
statusText.textContent = `Error: ${error.message}`;
statusText.style.color = '#e94560';
// Close after 5 seconds
setTimeout(() => {
document.body.removeChild(modal);
}, 5000);
}
);
}
/**
* Setup the memory recollection button in World Info section
*/
export function setupMemoryRecollectionButton() {
console.log('[Memory Recollection] Setting up button via event listener');
// Use SillyTavern's built-in event to know when WI is ready
// This fires after the worldInfoSettings are loaded
eventSource.on('worldInfoSettings', () => {
console.log('[Memory Recollection] worldInfoSettings event fired');
setTimeout(updateButton, 100);
});
// Also try on app ready
eventSource.on('app_ready', () => {
console.log('[Memory Recollection] app_ready event fired');
setTimeout(updateButton, 500);
});
// Try immediately as well
setTimeout(updateButton, 2000);
function updateButton() {
const existingButton = document.querySelector('.rpg-memory-recollection-btn');
// If extension is disabled, remove button if it exists
if (!extensionSettings.enabled) {
if (existingButton) {
console.log('[Memory Recollection] Extension disabled, removing button');
existingButton.remove();
}
return;
}
// Extension is enabled, add button if it doesn't exist
addButton();
}
function addButton() {
// Check if button already exists
if (document.querySelector('.rpg-memory-recollection-btn')) {
console.log('[Memory Recollection] Button already exists');
return;
}
console.log('[Memory Recollection] Attempting to add button...');
// World Info button bar is inside the world editor
// Look for the specific button container
const selectors = [
'#world_editor_buttons',
'#world_popup .world_button_bar',
'#WorldInfo .world_button_bar',
'.world_button_bar',
'#world_popup .justifyLeft',
'#WorldInfo .justifyLeft',
'#world_popup',
'#WorldInfo'
];
let container = null;
for (const selector of selectors) {
container = document.querySelector(selector);
if (container) {
console.log(`[Memory Recollection] Found container with selector: ${selector}`, container);
break;
}
}
if (!container) {
console.log('[Memory Recollection] No suitable container found yet');
return;
}
// Create the button
const button = document.createElement('button');
button.id = 'rpg-memory-recollection-button';
button.className = 'rpg-memory-recollection-btn menu_button';
button.innerHTML = '<i class="fa-solid fa-brain"></i> Memory Recollection';
button.title = 'Generate memory recollection entries from chat history';
button.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
showMemoryRecollectionModal();
});
// Insert the button - prepend to put it first
if (container.classList.contains('world_button_bar') || container.classList.contains('justifyLeft')) {
container.insertBefore(button, container.firstChild);
} else {
// Find or create a button container
let buttonContainer = container.querySelector('.world_button_bar') ||
container.querySelector('.justifyLeft');
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.className = 'world_button_bar justifyLeft';
container.insertBefore(buttonContainer, container.firstChild);
}
buttonContainer.insertBefore(button, buttonContainer.firstChild);
}
console.log('[Memory Recollection] ✅ Button added successfully!');
}
}
/**
* Update button visibility based on extension enabled state
* Call this when the extension is toggled on/off
*/
export function updateMemoryRecollectionButton() {
const existingButton = document.querySelector('.rpg-memory-recollection-btn');
if (!extensionSettings.enabled) {
// Extension disabled - remove button if it exists
if (existingButton) {
console.log('[Memory Recollection] Extension disabled, removing button');
existingButton.remove();
}
} else {
// Extension enabled - ensure button exists
if (!existingButton) {
console.log('[Memory Recollection] Extension enabled, adding button');
setTimeout(() => {
setupMemoryRecollectionButton();
}, 100);
}
}
}
+79
View File
@@ -0,0 +1,79 @@
/**
* Music Player Module
* Handles parsing and storing Spotify URLs from AI responses
*/
import { extensionSettings, committedTrackerData } from '../../core/state.js';
/**
* Extracts song suggestion from AI response in <spotify:Song - Artist/> format
* @param {string} responseText - The raw AI response text
* @returns {Object|null} Object with {song, artist, searchQuery} or null if not found
*/
export function extractSpotifyUrl(responseText) {
if (!responseText || !extensionSettings.enableSpotifyMusic) return null;
// Match <spotify:Song Title - Artist Name/> format
const songMatch = responseText.match(/<spotify:([^<>-]+)\s*-\s*([^<>\/]+)\/>/i);
if (songMatch) {
const song = songMatch[1].trim();
const artist = songMatch[2].trim();
const searchQuery = `${song} ${artist}`;
return {
song,
artist,
searchQuery,
displayText: `${song} - ${artist}`
};
}
return null;
}
/**
* Converts song data to Spotify app protocol URL
* @param {Object} songData - Object with {song, artist, searchQuery}
* @returns {string} Spotify app protocol URL
*/
export function convertToEmbedUrl(songData) {
if (!songData || !songData.searchQuery) return '';
// Use Spotify app protocol for direct app opening
const encodedQuery = encodeURIComponent(songData.searchQuery);
return `spotify:search:${encodedQuery}`;
}
/**
* Parses AI response for song suggestion and stores it
* @param {string} responseText - The raw AI response text
* @returns {boolean} True if song was found and stored
*/
export function parseAndStoreSpotifyUrl(responseText) {
if (!extensionSettings.enableSpotifyMusic) return false;
const songData = extractSpotifyUrl(responseText);
// console.log('[RPG Companion] Spotify Parser: Found song:', songData);
if (songData) {
// Store in committed tracker data
committedTrackerData.spotifyUrl = songData;
// console.log('[RPG Companion] Spotify Parser: Stored song in committedTrackerData:', committedTrackerData.spotifyUrl);
return true;
}
return false;
}
/**
* Gets the current song data from committed tracker data
* @returns {Object|null} Current song data or null
*/
export function getCurrentSpotifyUrl() {
return committedTrackerData.spotifyUrl || null;
}
/**
* Clears the current song data
*/
export function clearSpotifyUrl() {
committedTrackerData.spotifyUrl = null;
}
+36 -17
View File
@@ -5,13 +5,15 @@
import { togglePlotButtons } from '../ui/layout.js';
import { extensionSettings, setIsPlotProgression } from '../../core/state.js';
import { DEFAULT_HTML_PROMPT, DEFAULT_DIALOGUE_COLORING_PROMPT } from '../generation/promptBuilder.js';
import { Generate } from '../../../../../../../script.js';
/**
* Sets up the plot progression buttons inside the send form area.
* @param {Function} handlePlotClick - Callback function to handle plot button clicks
* @param {Function} handleEncounterClick - Callback function to handle encounter button click
*/
export function setupPlotButtons(handlePlotClick) {
export function setupPlotButtons(handlePlotClick, handleEncounterClick) {
// Remove existing buttons if any
$('#rpg-plot-buttons').remove();
@@ -31,10 +33,9 @@ export function setupPlotButtons(handlePlotClick) {
border-radius: 4px;
font-size: 13px;
cursor: pointer;
margin: 0 4px;
display: inline-block;
" tabindex="0" role="button">
<i class="fa-solid fa-dice"></i> Randomized Plot
margin: 0 2px;
" tabindex="0" role="button" title="Generate a random plot twist or event">
<i class="fa-solid fa-dice"></i>&nbsp;<span class="rpg-btn-text">Randomized Plot</span>
</button>
<button id="rpg-plot-natural" class="menu_button interactable" style="
background-color: #4a90e2;
@@ -44,10 +45,21 @@ export function setupPlotButtons(handlePlotClick) {
border-radius: 4px;
font-size: 13px;
cursor: pointer;
margin: 0 4px;
display: inline-block;
" tabindex="0" role="button">
<i class="fa-solid fa-forward"></i> Natural Plot
margin: 0 2px;
" tabindex="0" role="button" title="Continue the story naturally without twists">
<i class="fa-solid fa-forward"></i>&nbsp;<span class="rpg-btn-text">Natural Plot</span>
</button>
<button id="rpg-encounter-button" class="menu_button interactable" style="
background-color: #cc3333;
color: white;
border: none;
padding: 8px 12px;
border-radius: 4px;
font-size: 13px;
cursor: pointer;
margin: 0 2px;
" tabindex="0" role="button" title="Enter combat encounter">
<i class="fa-solid fa-fire"></i>&nbsp;<span class="rpg-btn-text">Enter Encounter</span>
</button>
</span>
`;
@@ -58,6 +70,7 @@ export function setupPlotButtons(handlePlotClick) {
// Add event handlers for buttons
$('#rpg-plot-random').on('click', () => handlePlotClick('random'));
$('#rpg-plot-natural').on('click', () => handlePlotClick('natural'));
$('#rpg-encounter-button').on('click', () => handleEncounterClick());
// Show/hide based on setting
togglePlotButtons();
@@ -87,19 +100,25 @@ export async function sendPlotProgression(type) {
// Build the prompt based on type
let prompt = '';
if (type === 'random') {
prompt = 'Actually, the scene is getting stale. Introduce {{random::stakes::a plot twist::a new character::a cataclysm::a fourth-wall-breaking joke::a sudden atmospheric phenomenon::a plot hook::a running gag::an ecchi scenario::Death from Discworld::a new stake::a drama::a conflict::an angered entity::a god::a vision::a prophetic dream::Il Dottore from Genshin Impact::a new development::a civilian in need::an emotional bit::a threat::a villain::an important memory recollection::a marriage proposal::a date idea::an angry horde of villagers with pitchforks::a talking animal::an enemy::a cliffhanger::a short omniscient POV shift to a completely different character::a quest::an unexpected revelation::a scandal::an evil clone::death of an important character::harm to an important character::a romantic setup::a gossip::a messenger::a plot point from the past::a plot hole::a tragedy::a ghost::an otherworldly occurrence::a plot device::a curse::a magic device::a rival::an unexpected pregnancy::a brothel::a prostitute::a new location::a past lover::a completely random thing::a what-if scenario::a significant choice::war::love::a monster::lewd undertones::Professor Mari::a travelling troupe::a secret::a fortune-teller::something completely different::a killer::a murder mystery::a mystery::a skill check::a deus ex machina::three raccoons in a trench coat::a pet::a slave::an orphan::a psycho::tentacles::"there is only one bed" trope::accidental marriage::a fun twist::a boss battle::sexy corn::an eldritch horror::a character getting hungry, thirsty, or exhausted::horniness::a need for a bathroom break need::someone fainting::an assassination attempt::a meta narration of this all being an out of hand DND session::a dungeon::a friend in need::an old friend::a small time skip::a scene shift::Aurora Borealis, at this time of year, at this time of day, at this part of the country::a grand ball::a surprise party::zombies::foreshadowing::a Spanish Inquisition (nobody expects it)::a natural plot progression}} to make things more interesting! Be creative, but stay grounded in the setting.';
// Use custom prompt if set, otherwise use default
prompt = extensionSettings.customPlotRandomPrompt || 'Actually, the scene is getting stale. Introduce {{random::stakes::a plot twist::a new character::a cataclysm::a fourth-wall-breaking joke::a sudden atmospheric phenomenon::a plot hook::a running gag::an ecchi scenario::Death from Discworld::a new stake::a drama::a conflict::an angered entity::a god::a vision::a prophetic dream::Il Dottore from Genshin Impact::a new development::a civilian in need::an emotional bit::a threat::a villain::an important memory recollection::a marriage proposal::a date idea::an angry horde of villagers with pitchforks::a talking animal::an enemy::a cliffhanger::a short omniscient POV shift to a completely different character::a quest::an unexpected revelation::a scandal::an evil clone::death of an important character::harm to an important character::a romantic setup::a gossip::a messenger::a plot point from the past::a plot hole::a tragedy::a ghost::an otherworldly occurrence::a plot device::a curse::a magic device::a rival::an unexpected pregnancy::a brothel::a prostitute::a new location::a past lover::a completely random thing::a what-if scenario::a significant choice::war::love::a monster::lewd undertones::Professor Mari::a travelling troupe::a secret::a fortune-teller::something completely different::a killer::a murder mystery::a mystery::a skill check::a deus ex machina::three raccoons in a trench coat::a pet::a slave::an orphan::a psycho::tentacles::"there is only one bed" trope::accidental marriage::a fun twist::a boss battle::sexy corn::an eldritch horror::a character getting hungry, thirsty, or exhausted::horniness::a need for a bathroom break need::someone fainting::an assassination attempt::a meta narration of this all being an out of hand DND session::a dungeon::a friend in need::an old friend::a small time skip::a scene shift::Aurora Borealis, at this time of year, at this time of day, at this part of the country::a grand ball::a surprise party::zombies::foreshadowing::a Spanish Inquisition (nobody expects it)::a natural plot progression}} to make things more interesting! Be creative, but stay grounded in the setting.';
} else {
prompt = 'Actually, the scene is getting stale. Progress it, to make things more interesting! Reintroduce an unresolved plot point from the past, or push the story further towards the current main goal. Be creative, but stay grounded in the setting.';
// Use custom prompt if set, otherwise use default
prompt = extensionSettings.customPlotNaturalPrompt || 'Actually, the scene is getting stale. Progress it, to make things more interesting! Reintroduce an unresolved plot point from the past, or push the story further towards the current main goal. Be creative, but stay grounded in the setting.';
}
// Add HTML prompt if enabled
if (extensionSettings.enableHtmlPrompt) {
prompt += '\n\n' + `If appropriate, include inline HTML, CSS, and JS elements for creative, visual storytelling throughout your response:
- Use them liberally to depict any in-world content that can be visualized (screens, posters, books, signs, letters, logos, crests, seals, medallions, labels, etc.), with creative license for animations, 3D effects, pop-ups, dropdowns, websites, and so on.
- Style them thematically to match the theme (e.g., sleek for sci-fi, rustic for fantasy), ensuring text is visible.
- Embed all resources directly (e.g., inline SVGs) so nothing relies on external fonts or libraries.
- Place elements naturally in the narrative where characters would see or use them, with no limits on format or application.
- These HTML/CSS/JS elements must be rendered directly without enclosing them in code fences.`;
// Use custom HTML prompt if set, otherwise use default
const htmlPromptText = extensionSettings.customHtmlPrompt || DEFAULT_HTML_PROMPT;
prompt += '\n\n' + htmlPromptText;
}
// Add Dialogue Coloring prompt if enabled
if (extensionSettings.enableDialogueColoring) {
// Use custom Dialogue Coloring prompt if set, otherwise use default
const dialogueColoringPromptText = extensionSettings.customDialogueColoringPrompt || DEFAULT_DIALOGUE_COLORING_PROMPT;
prompt += '\n\n' + dialogueColoringPromptText;
}
// Set flag to indicate we're doing plot progression
+272 -88
View File
@@ -12,25 +12,151 @@ import {
isGenerating,
lastActionWasSwipe,
setIsGenerating,
setLastActionWasSwipe
setLastActionWasSwipe,
$musicPlayerContainer
} from '../../core/state.js';
import { saveChatData } from '../../core/persistence.js';
import { generateSeparateUpdatePrompt } from './promptBuilder.js';
import {
generateSeparateUpdatePrompt
} from './promptBuilder.js';
import { parseResponse, parseUserStats } from './parser.js';
import { parseAndStoreSpotifyUrl } from '../features/musicPlayer.js';
import { renderUserStats } from '../rendering/userStats.js';
import { renderInfoBox } from '../rendering/infoBox.js';
import { removeLocks } from './lockManager.js';
import { renderThoughts } from '../rendering/thoughts.js';
import { renderInventory } from '../rendering/inventory.js';
import { renderQuests } from '../rendering/quests.js';
import { renderMusicPlayer } from '../rendering/musicPlayer.js';
import { i18n } from '../../core/i18n.js';
import { generateAvatarsForCharacters } from '../features/avatarGenerator.js';
// Store the original preset name to restore after tracker generation
let originalPresetName = null;
/**
* Generates tracker data using an external OpenAI-compatible API.
* Used when generationMode is 'external'.
*
* @param {Array<{role: string, content: string}>} messages - Array of message objects for the API
* @returns {Promise<string>} The generated response content
* @throws {Error} If the API call fails or configuration is invalid
*/
export async function generateWithExternalAPI(messages) {
const { baseUrl, model, maxTokens, temperature } = extensionSettings.externalApiSettings || {};
// Retrieve API key from secure storage (not shared extension settings)
const apiKey = localStorage.getItem('rpg_companion_external_api_key');
// Validate required settings
if (!baseUrl || !baseUrl.trim()) {
throw new Error('External API base URL is not configured');
}
if (!model || !model.trim()) {
throw new Error('External API model is not configured');
}
// Normalize base URL (remove trailing slash if present)
const normalizedBaseUrl = baseUrl.trim().replace(/\/+$/, '');
const endpoint = `${normalizedBaseUrl}/chat/completions`;
// console.log(`[RPG Companion] Calling external API: ${normalizedBaseUrl} with model: ${model}`);
// Prepare headers - only include Authorization if API key is provided
const headers = {
'Content-Type': 'application/json'
};
if (apiKey && apiKey.trim()) {
headers['Authorization'] = `Bearer ${apiKey.trim()}`;
}
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: headers,
body: JSON.stringify({
model: model.trim(),
messages: messages,
max_tokens: maxTokens || 2048,
temperature: temperature ?? 0.7
})
});
if (!response.ok) {
const errorText = await response.text();
let errorMessage = `External API error: ${response.status} ${response.statusText}`;
try {
const errorJson = JSON.parse(errorText);
if (errorJson.error?.message) {
errorMessage = `External API error: ${errorJson.error.message}`;
}
} catch (e) {
// If parsing fails, use the raw text if it's short enough
if (errorText.length < 200) {
errorMessage = `External API error: ${errorText}`;
}
}
throw new Error(errorMessage);
}
const data = await response.json();
if (!data.choices || !data.choices[0] || !data.choices[0].message) {
throw new Error('Invalid response format from external API');
}
const content = data.choices[0].message.content;
// console.log('[RPG Companion] External API response received successfully');
return content;
} catch (error) {
if (error.name === 'TypeError' && (error.message.includes('fetch') || error.message.includes('Failed to fetch') || error.message.includes('NetworkError'))) {
throw new Error(`CORS Access Blocked: This API endpoint (${normalizedBaseUrl}) does not allow direct access from a browser. This is a browser security restriction (CORS), not a bug in the extension. Please use an endpoint that supports CORS (like OpenRouter or a local proxy) or use SillyTavern's internal API system (Separate Mode).`);
}
throw error;
}
}
/**
* Tests the external API connection with a simple request.
* @returns {Promise<{success: boolean, message: string, model?: string}>}
*/
export async function testExternalAPIConnection() {
const { baseUrl, model } = extensionSettings.externalApiSettings || {};
const apiKey = localStorage.getItem('rpg_companion_external_api_key');
if (!baseUrl || !model) {
return {
success: false,
message: 'Please fill in all required fields (Base URL and Model). API Key is optional for local servers.'
};
}
try {
const testMessages = [
{ role: 'user', content: 'Respond with exactly: "Connection successful"' }
];
const response = await generateWithExternalAPI(testMessages);
return {
success: true,
message: `Connection successful! Model: ${model}`,
model: model
};
} catch (error) {
return {
success: false,
message: error.message || 'Connection failed'
};
}
}
/**
* Gets the current preset name using the /preset command
* @returns {Promise<string|null>} Current preset name or null if unavailable
*/
async function getCurrentPresetName() {
export async function getCurrentPresetName() {
try {
// Use /preset without arguments to get the current preset name
const result = await executeSlashCommandsOnChatInput('/preset', { quiet: true });
@@ -54,12 +180,14 @@ async function getCurrentPresetName() {
console.error('[RPG Companion] Error getting current preset:', error);
return null;
}
}/**
}
/**
* Switches to a specific preset by name using the /preset slash command
* @param {string} presetName - Name of the preset to switch to
* @returns {Promise<boolean>} True if switching succeeded, false otherwise
*/
async function switchToPreset(presetName) {
export async function switchToPreset(presetName) {
try {
// Use the /preset slash command to switch presets
// This is the proper way to change presets in SillyTavern
@@ -94,45 +222,59 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough
return;
}
if (extensionSettings.generationMode !== 'separate') {
// console.log('[RPG Companion] Not in separate mode, skipping manual update');
if (extensionSettings.generationMode !== 'separate' && extensionSettings.generationMode !== 'external') {
// console.log('[RPG Companion] Not in separate or external mode, skipping manual update');
return;
}
const isExternalMode = extensionSettings.generationMode === 'external';
try {
setIsGenerating(true);
// Update button to show "Updating..." state
const $updateBtn = $('#rpg-manual-update');
const originalHtml = $updateBtn.html();
$updateBtn.html('<i class="fa-solid fa-spinner fa-spin"></i> Updating...').prop('disabled', true);
const updatingText = i18n.getTranslation('template.mainPanel.updating') || 'Updating...';
$updateBtn.html(`<i class="fa-solid fa-spinner fa-spin"></i> ${updatingText}`).prop('disabled', true);
// Save current preset name before switching (if we're going to switch)
if (extensionSettings.useSeparatePreset) {
originalPresetName = await getCurrentPresetName();
console.log(`[RPG Companion] Saved original preset: "${originalPresetName}"`);
const prompt = await generateSeparateUpdatePrompt();
// Generate response based on mode
let response;
if (isExternalMode) {
// External mode: Use external OpenAI-compatible API directly
// console.log('[RPG Companion] Using external API for tracker generation');
response = await generateWithExternalAPI(prompt);
} else {
// Separate mode: Use SillyTavern's generateRaw
response = await generateRaw({
prompt: prompt,
quietToLoud: false
});
}
// Switch to separate preset if enabled
if (extensionSettings.useSeparatePreset) {
const switched = await switchToPreset('RPG Companion Trackers');
if (!switched) {
console.warn('[RPG Companion] Failed to switch to RPG Companion Trackers preset. Using current preset.');
originalPresetName = null; // Don't try to restore if we didn't switch
}
}
const prompt = generateSeparateUpdatePrompt();
// Generate using raw prompt (uses current preset, no chat history)
const response = await generateRaw({
prompt: prompt,
quietToLoud: false
});
if (response) {
// console.log('[RPG Companion] Raw AI response:', response);
const parsedData = parseResponse(response);
// Check if parsing completely failed (no tracker data found)
if (parsedData.parsingFailed) {
toastr.error(i18n.getTranslation('errors.parsingError'), '', { timeOut: 5000 });
}
// Remove locks from parsed data (JSON format only, text format is unaffected)
if (parsedData.userStats) {
parsedData.userStats = removeLocks(parsedData.userStats);
}
if (parsedData.infoBox) {
parsedData.infoBox = removeLocks(parsedData.infoBox);
}
if (parsedData.characterThoughts) {
parsedData.characterThoughts = removeLocks(parsedData.characterThoughts);
}
// Parse and store Spotify URL if feature is enabled
parseAndStoreSpotifyUrl(response);
// console.log('[RPG Companion] Parsed data:', parsedData);
// console.log('[RPG Companion] parsedData.userStats:', parsedData.userStats ? parsedData.userStats.substring(0, 100) + '...' : 'null');
@@ -143,6 +285,35 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough
// Store RPG data for the last assistant message (separate mode)
const lastMessage = chat && chat.length > 0 ? chat[chat.length - 1] : null;
// console.log('[RPG Companion] Last message is_user:', lastMessage ? lastMessage.is_user : 'no message');
// Update lastGeneratedData for display (regardless of message type)
if (parsedData.userStats) {
lastGeneratedData.userStats = parsedData.userStats;
parseUserStats(parsedData.userStats);
}
if (parsedData.infoBox) {
lastGeneratedData.infoBox = parsedData.infoBox;
}
if (parsedData.characterThoughts) {
lastGeneratedData.characterThoughts = parsedData.characterThoughts;
}
// When saveTrackerHistory is enabled, store tracker data on the user's message too
// This allows scrolling through history and seeing trackers at each point
if (extensionSettings.saveTrackerHistory && lastMessage && lastMessage.is_user) {
if (!lastMessage.extra) {
lastMessage.extra = {};
}
lastMessage.extra.rpg_companion_data = {
userStats: parsedData.userStats,
infoBox: parsedData.infoBox,
characterThoughts: parsedData.characterThoughts,
timestamp: Date.now()
};
// console.log('[RPG Companion] 💾 Stored tracker data on user message for history');
}
// Also store on assistant message if present (existing behavior)
if (lastMessage && !lastMessage.is_user) {
if (!lastMessage.extra) {
lastMessage.extra = {};
@@ -159,77 +330,68 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough
};
// console.log('[RPG Companion] Stored separate mode RPG data for message swipe', currentSwipeId);
// Update lastGeneratedData for display AND future commit
if (parsedData.userStats) {
lastGeneratedData.userStats = parsedData.userStats;
parseUserStats(parsedData.userStats);
}
if (parsedData.infoBox) {
lastGeneratedData.infoBox = parsedData.infoBox;
}
if (parsedData.characterThoughts) {
lastGeneratedData.characterThoughts = parsedData.characterThoughts;
}
// console.log('[RPG Companion] 💾 SEPARATE MODE: Updated lastGeneratedData:', {
// userStats: lastGeneratedData.userStats ? 'exists' : 'null',
// infoBox: lastGeneratedData.infoBox ? 'exists' : 'null',
// characterThoughts: lastGeneratedData.characterThoughts ? 'exists' : 'null'
// });
// Only auto-commit on TRULY first generation (no committed data exists at all)
// This prevents auto-commit after refresh when we have saved committed data
const hasAnyCommittedContent = (
(committedTrackerData.userStats && committedTrackerData.userStats.trim() !== '') ||
(committedTrackerData.infoBox && committedTrackerData.infoBox.trim() !== '' && committedTrackerData.infoBox !== 'Info Box\n---\n') ||
(committedTrackerData.characterThoughts && committedTrackerData.characterThoughts.trim() !== '' && committedTrackerData.characterThoughts !== 'Present Characters\n---\n')
);
// Only commit if we have NO committed content at all (truly first time ever)
if (!hasAnyCommittedContent) {
committedTrackerData.userStats = parsedData.userStats;
committedTrackerData.infoBox = parsedData.infoBox;
committedTrackerData.characterThoughts = parsedData.characterThoughts;
// console.log('[RPG Companion] 🔆 FIRST TIME: Auto-committed tracker data');
}
// Render the updated data
renderUserStats();
renderInfoBox();
renderThoughts();
renderInventory();
renderQuests();
} else {
// No assistant message to attach to - just update display
if (parsedData.userStats) {
parseUserStats(parsedData.userStats);
}
renderUserStats();
renderInfoBox();
renderThoughts();
renderInventory();
renderQuests();
}
// Only commit on TRULY first generation (no committed data exists at all)
// This prevents auto-commit after refresh when we have saved committed data
const hasAnyCommittedContent = (
(committedTrackerData.userStats && committedTrackerData.userStats.trim() !== '') ||
(committedTrackerData.infoBox && committedTrackerData.infoBox.trim() !== '' && committedTrackerData.infoBox !== 'Info Box\n---\n') ||
(committedTrackerData.characterThoughts && committedTrackerData.characterThoughts.trim() !== '' && committedTrackerData.characterThoughts !== 'Present Characters\n---\n')
);
// Only commit if we have NO committed content at all (truly first time ever)
if (!hasAnyCommittedContent) {
committedTrackerData.userStats = parsedData.userStats;
committedTrackerData.infoBox = parsedData.infoBox;
committedTrackerData.characterThoughts = parsedData.characterThoughts;
// console.log('[RPG Companion] 🔆 FIRST TIME: Auto-committed tracker data');
}
// Render the updated data
renderUserStats();
renderInfoBox();
renderThoughts();
renderInventory();
renderQuests();
renderMusicPlayer($musicPlayerContainer[0]);
// Save to chat metadata
saveChatData();
// Generate avatars if auto-generate is enabled (runs within this workflow)
// This uses the RPG Companion Trackers preset and keeps the button spinning
if (extensionSettings.autoGenerateAvatars) {
const charactersNeedingAvatars = parseCharactersFromThoughts(parsedData.characterThoughts);
if (charactersNeedingAvatars.length > 0) {
// console.log('[RPG Companion] Generating avatars for:', charactersNeedingAvatars);
// Generate avatars - this awaits completion
await generateAvatarsForCharacters(charactersNeedingAvatars, (names) => {
// Callback when generation starts - re-render to show loading spinners
// console.log('[RPG Companion] Avatar generation started, showing spinners...');
renderThoughts();
});
// Re-render once all avatars are generated
// console.log('[RPG Companion] All avatars generated, re-rendering...');
renderThoughts();
}
}
}
} catch (error) {
console.error('[RPG Companion] Error updating RPG data:', error);
} finally {
// Restore original preset if we switched to a separate one
if (originalPresetName && extensionSettings.useSeparatePreset) {
console.log(`[RPG Companion] Restoring original preset: "${originalPresetName}"`);
await switchToPreset(originalPresetName);
originalPresetName = null; // Clear after restoring
if (isExternalMode) {
toastr.error(error.message, 'RPG Companion External API Error');
}
} finally {
setIsGenerating(false);
// Restore button to original state
const $updateBtn = $('#rpg-manual-update');
$updateBtn.html('<i class="fa-solid fa-sync"></i> Refresh RPG Info').prop('disabled', false);
const refreshText = i18n.getTranslation('template.mainPanel.refreshRpgInfo') || 'Refresh RPG Info';
$updateBtn.html(`<i class="fa-solid fa-sync"></i> ${refreshText}`).prop('disabled', false);
// Reset the flag after tracker generation completes
// This ensures the flag persists through both main generation AND tracker generation
@@ -237,3 +399,25 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough
setLastActionWasSwipe(false);
}
}
/**
* Parses character names from Present Characters thoughts data
* @param {string} characterThoughtsData - Raw character thoughts data
* @returns {Array<string>} Array of character names found
*/
function parseCharactersFromThoughts(characterThoughtsData) {
if (!characterThoughtsData) return [];
const lines = characterThoughtsData.split('\n');
const characters = [];
for (const line of lines) {
if (line.trim().startsWith('- ')) {
const name = line.trim().substring(2).trim();
if (name && name.toLowerCase() !== 'unavailable') {
characters.push(name);
}
}
}
return characters;
}
+762
View File
@@ -0,0 +1,762 @@
/**
* Encounter Prompt Builder Module
* Handles all AI prompt generation for combat encounters
*/
import { getContext } from '../../../../../../extensions.js';
import { chat, characters, this_chid, substituteParams } from '../../../../../../../script.js';
import { selected_group, getGroupMembers, groups } from '../../../../../../group-chats.js';
import { extensionSettings, committedTrackerData } from '../../core/state.js';
import { currentEncounter } from '../features/encounterState.js';
import { repairJSON } from '../../utils/jsonRepair.js';
import { buildInventorySummary, generateTrackerInstructions, generateTrackerExample } from './promptBuilder.js';
import { applyLocks } from './lockManager.js';
/**
* Gets character information from the current chat
* @returns {Promise<string>} Formatted character information
*/
async function getCharactersInfo() {
let characterInfo = '';
// Check if in group chat
if (selected_group) {
const group = groups.find(g => g.id === selected_group);
const groupMembers = getGroupMembers(selected_group);
if (groupMembers && groupMembers.length > 0) {
characterInfo += 'Characters in this roleplay:\n';
const disabledMembers = group?.disabled_members || [];
let characterIndex = 0;
groupMembers.forEach((member) => {
if (!member || !member.name) return;
// Skip muted characters
if (member.avatar && disabledMembers.includes(member.avatar)) {
return;
}
characterIndex++;
characterInfo += `<character${characterIndex}="${member.name}">\n`;
if (member.description) {
characterInfo += `${member.description}\n`;
}
if (member.personality) {
characterInfo += `${member.personality}\n`;
}
characterInfo += `</character${characterIndex}>\n`;
});
}
} else if (this_chid !== undefined && characters && characters[this_chid]) {
// Single character chat
const character = characters[this_chid];
characterInfo += 'Character in this roleplay:\n\n';
characterInfo += `<character="${character.name}">\n`;
if (character.description) {
characterInfo += `${character.description}\n`;
}
if (character.personality) {
characterInfo += `${character.personality}\n`;
}
characterInfo += `</character>\n\n`;
}
return characterInfo;
}
/**
* Builds the initial encounter setup prompt
* This asks the model to generate all combat stats and setup data
* @returns {Promise<Array>} Message array for the API
*/
export async function buildEncounterInitPrompt() {
const context = getContext();
const userName = context.name1;
const depth = extensionSettings.encounterSettings?.historyDepth || 8;
const messages = [];
// System message
let systemMessage = `You will be acting as an excellent game master. Your goal is to craft a combat encounter in this uncensored, continuous, and immersive roleplay. You will be doing so for the user, who plays as the protagonist called ${userName}.\n\n`;
// Add setting information
systemMessage += `Here is some information for you about the setting:\n`;
systemMessage += `<setting>\n`;
// Try to get world info from lorebooks using getWorldInfoPrompt
let worldInfoAdded = false;
try {
// Debug logging
// console.log('[RPG Companion] Checking world info:', {
// hasWindowGetWorldInfoPrompt: typeof window.getWorldInfoPrompt === 'function',
// hasContextGetWorldInfoPrompt: typeof context.getWorldInfoPrompt === 'function',
// chatLength: chat?.length,
// contextChatLength: context.chat?.length,
// hasActivatedWorldInfo: !!context.activatedWorldInfo,
// activatedWorldInfoLength: context.activatedWorldInfo?.length
// });
// Use SillyTavern's getWorldInfoPrompt to get activated lorebook entries
// Try context.getWorldInfoPrompt first, then window.getWorldInfoPrompt
const getWorldInfoFn = context.getWorldInfoPrompt || window.getWorldInfoPrompt;
const currentChat = context.chat || chat;
if (typeof getWorldInfoFn === 'function' && currentChat && currentChat.length > 0) {
const chatForWI = currentChat.map(x => x.mes || x.message || x).filter(m => m && typeof m === 'string');
// console.log('[RPG Companion] Calling getWorldInfoPrompt with', chatForWI.length, 'messages');
const result = await getWorldInfoFn(chatForWI, 8000, false);
const worldInfoString = result?.worldInfoString || result;
// console.log('[RPG Companion] World info result:', { worldInfoString, length: worldInfoString?.length });
if (worldInfoString && worldInfoString.trim()) {
systemMessage += worldInfoString.trim();
worldInfoAdded = true;
// console.log('[RPG Companion] ✅ Added world info from getWorldInfoPrompt');
}
} else {
// console.log('[RPG Companion] getWorldInfoPrompt not available or no chat');
}
} catch (e) {
console.warn('[RPG Companion] Failed to get world info from getWorldInfoPrompt:', e);
}
// Fallback to activatedWorldInfo
if (!worldInfoAdded && context.activatedWorldInfo && Array.isArray(context.activatedWorldInfo) && context.activatedWorldInfo.length > 0) {
// console.log('[RPG Companion] Using fallback activatedWorldInfo:', context.activatedWorldInfo.length, 'entries');
context.activatedWorldInfo.forEach((entry) => {
if (entry && entry.content) {
systemMessage += `${entry.content}\n\n`;
worldInfoAdded = true;
}
});
}
if (!worldInfoAdded) {
console.warn('[RPG Companion] ⚠️ No world information available');
systemMessage += 'No world information available.';
}
systemMessage += `\n</setting>\n\n`;
// Add character information
const charactersInfo = await getCharactersInfo();
if (charactersInfo) {
systemMessage += `Here is the information available to you about the characters participating in the fight:\n`;
systemMessage += `<characters>\n${charactersInfo}</characters>\n\n`;
}
// Add persona information
systemMessage += `Here are details about the user's ${userName}:\n`;
systemMessage += `<persona>\n`;
try {
const personaText = substituteParams('{{persona}}');
if (personaText && personaText !== '{{persona}}') {
systemMessage += personaText;
} else {
systemMessage += 'No persona information available.';
}
} catch (e) {
systemMessage += 'No persona information available.';
}
systemMessage += `\n</persona>\n\n`;
// Add chat history from before the encounter
systemMessage += `Here is the chat history from before the encounter started between the user and the assistant:\n`;
systemMessage += `<history>\n`;
messages.push({
role: 'system',
content: systemMessage
});
// Add recent chat history (last X messages before encounter)
if (chat && chat.length > 0) {
const recentMessages = chat.slice(-depth - 1, -1); // Exclude the last message (encounter trigger)
for (const message of recentMessages) {
const content = message.mes?.trim();
// Skip empty messages
if (content) {
messages.push({
role: message.is_user ? 'user' : 'assistant',
content: content
});
}
}
// Add the encounter trigger message
const lastMessage = chat[chat.length - 1];
if (lastMessage && lastMessage.mes?.trim()) {
currentEncounter.encounterStartMessage = lastMessage.mes;
messages.push({
role: lastMessage.is_user ? 'user' : 'assistant',
content: lastMessage.mes.trim()
});
}
}
// Build user's current stats
let userStatsInfo = '';
// Add HP and other stats from committed tracker data
if (committedTrackerData.userStats) {
userStatsInfo += `${userName}'s Current Stats:\n${committedTrackerData.userStats}\n\n`;
}
// Add skills if available
const skillsSection = extensionSettings.trackerConfig?.userStats?.skillsSection;
if (skillsSection?.enabled && skillsSection.customFields && skillsSection.customFields.length > 0) {
userStatsInfo += `${userName}'s Skills: ${skillsSection.customFields.join(', ')}\n`;
}
// Add inventory
const inventory = extensionSettings.userStats?.inventory;
if (inventory) {
const inventorySummary = buildInventorySummary(inventory);
userStatsInfo += `${userName}'s Inventory:\n${inventorySummary}\n\n`;
}
// Add classic stats/attributes
if (extensionSettings.classicStats) {
const stats = extensionSettings.classicStats;
userStatsInfo += `${userName}'s Attributes: `;
const showLevel = extensionSettings.trackerConfig?.userStats?.showLevel !== false;
const levelStr = showLevel ? `, LVL ${extensionSettings.level}` : '';
userStatsInfo += `STR ${stats.str}, DEX ${stats.dex}, CON ${stats.con}, INT ${stats.int}, WIS ${stats.wis}, CHA ${stats.cha}${levelStr}\n\n`;
}
// Add present characters info for party members
let partyInfo = '';
if (committedTrackerData.characterThoughts) {
partyInfo += `Present Characters (potential party members):\n${committedTrackerData.characterThoughts}\n\n`;
}
// Close history and add combat initialization instruction
let initInstruction = `</history>\n\n`;
// Wrap RPG Companion panel data in context tags
initInstruction += `Here is some additional tracked context for the scene:\n`;
initInstruction += `<context>\n`;
initInstruction += userStatsInfo;
initInstruction += partyInfo;
initInstruction += `</context>\n\n`;
initInstruction += `The combat starts now.\n\n`;
initInstruction += `Based on everything above, generate the initial combat state. Analyze who is in the party fighting alongside ${userName} (if anyone), and who the enemies are. Replace placeholders in [brackets] and X with actual values. Return ONLY a JSON object with the following structure:\n\n`;
initInstruction += `{\n`;
initInstruction += ` "party": [\n`;
initInstruction += ` {\n`;
initInstruction += ` "name": "${userName}",\n`;
initInstruction += ` "hp": X,\n`;
initInstruction += ` "maxHp": X,\n`;
initInstruction += ` "attacks": [\n`;
initInstruction += ` {"name": "Attack", "type": "single-target|AoE|both"},\n`;
initInstruction += ` {"name": "Skill1", "type": "single-target|AoE|both"}\n`;
initInstruction += ` ],\n`;
initInstruction += ` "items": ["Item1", "Item2"],\n`;
initInstruction += ` "statuses": [],\n`;
initInstruction += ` "isPlayer": true\n`;
initInstruction += ` }\n`;
initInstruction += ` // Add other party members here if they exist in the context, changing isPlayer to false for them.\n`;
initInstruction += ` ],\n`;
initInstruction += ` "enemies": [\n`;
initInstruction += ` {\n`;
initInstruction += ` "name": "Enemy Name",\n`;
initInstruction += ` "hp": X,\n`;
initInstruction += ` "maxHp": X,\n`;
initInstruction += ` "attacks": [\n`;
initInstruction += ` {"name": "Attack1", "type": "single-target|AoE|both"},\n`;
initInstruction += ` {"name": "Attack2", "type": "single-target|AoE|both"}\n`;
initInstruction += ` ],\n`;
initInstruction += ` "statuses": [],\n`;
initInstruction += ` "description": "Brief enemy description",\n`;
initInstruction += ` "sprite": "emoji or brief visual description"\n`;
initInstruction += ` }\n`;
initInstruction += ` // Add all enemies participating in this combat\n`;
initInstruction += ` ],\n`;
initInstruction += ` "environment": "Brief description of the combat environment",\n`;
initInstruction += ` "styleNotes": {\n`;
initInstruction += ` "environmentType": "forest|dungeon|desert|cave|city|ruins|snow|water|castle|wasteland|plains|mountains|swamp|volcanic|spaceship|mansion",\n`;
initInstruction += ` "atmosphere": "bright|dark|foggy|stormy|calm|eerie|chaotic|peaceful",\n`;
initInstruction += ` "timeOfDay": "dawn|day|dusk|night|twilight",\n`;
initInstruction += ` "weather": "clear|rainy|snowy|windy|stormy|overcast"\n`;
initInstruction += ` }\n`;
initInstruction += `}\n\n`;
initInstruction += `IMPORTANT NOTES:\n`;
initInstruction += `- For attacks array: Each attack must be an object with "name" and "type" properties\n`;
initInstruction += ` - "single-target": Can only target one character (enemy or ally)\n`;
initInstruction += ` - "AoE": Area of Effect - targets all enemies, but some AoE attacks (like storms, explosions) can also harm allies if the attack is indiscriminate\n`;
initInstruction += ` - "both": Player can choose to target a single enemy OR use as AoE\n`;
initInstruction += `- Statuses array: May start empty, but don't have to if characters applied them before the combat\n`;
initInstruction += ` - Each status has a format: {"name": "Status Name", "emoji": "💀", "duration": X}\n`;
initInstruction += ` - Examples: Poisoned (🧪), Burning (🔥), Blessed (✨), Stunned (💫), Weakened (⬇️), Strengthened (⬆️)\n\n`;
initInstruction += `The styleNotes object will be used to visually style the combat window - choose ONE value from each category that best fits the environment described in the chat history.\n\n`;
initInstruction += `Use the user's current stats, inventory, and skills to populate the party data. For ${userName}'s attacks array, include their available skills. For items, include usable items from their inventory. Set HP based on their current Health stat if available.\n\n`;
initInstruction += `Ensure all party members and enemies have realistic HP values based on the setting and their descriptions. Return ONLY the JSON object, no other text.`;
// Only add the instruction if it has meaningful content
if (initInstruction.trim()) {
messages.push({
role: 'user',
content: initInstruction.trim()
});
}
// Validate that we have at least one message with content
if (messages.length === 0 || messages.every(m => !m.content || !m.content.trim())) {
throw new Error('Unable to build encounter prompt - no valid content available');
}
return messages;
}
/**
* Builds a combat action prompt
* This is sent when the user takes an action in combat
* @param {string} action - The action taken by the user
* @param {object} combatStats - Current combat statistics
* @returns {Array} Message array for the API
*/
export async function buildCombatActionPrompt(action, combatStats) {
const context = getContext();
const userName = context.name1;
const depth = extensionSettings.encounterSettings?.historyDepth || 8;
// Get narrative style from settings
const narrativeStyle = extensionSettings.encounterSettings?.combatNarrative || {};
const tense = narrativeStyle.tense || 'present';
const person = narrativeStyle.person || 'third';
const narration = narrativeStyle.narration || 'omniscient';
const pov = narrativeStyle.pov || 'narrator';
const messages = [];
// Build system message with setting info
let systemMessage = `You are the game master managing this combat encounter. You must not play as ${userName} - only describe what happens as a result of their actions/dialogues and control NPCs/enemies.\n\n`;
// Add setting information
systemMessage += `Here is some information for you about the setting:\n`;
systemMessage += `<setting>\n`;
// Get world info
let worldInfoAdded = false;
try {
const getWorldInfoFn = context.getWorldInfoPrompt || window.getWorldInfoPrompt;
const currentChat = context.chat || chat;
if (typeof getWorldInfoFn === 'function' && currentChat && currentChat.length > 0) {
const chatForWI = currentChat.map(x => x.mes || x.message || x).filter(m => m && typeof m === 'string');
const result = await getWorldInfoFn(chatForWI, 8000, false);
const worldInfoString = result?.worldInfoString || result;
if (worldInfoString && worldInfoString.trim()) {
systemMessage += worldInfoString.trim();
worldInfoAdded = true;
}
}
} catch (e) {
console.warn('[RPG Companion] Failed to get world info for combat action:', e);
}
if (!worldInfoAdded && context.activatedWorldInfo && Array.isArray(context.activatedWorldInfo) && context.activatedWorldInfo.length > 0) {
context.activatedWorldInfo.forEach((entry) => {
if (entry && entry.content) {
systemMessage += `${entry.content}\n\n`;
worldInfoAdded = true;
}
});
}
if (!worldInfoAdded) {
systemMessage += 'No world information available.';
}
systemMessage += `\n</setting>\n\n`;
// Add character information
const charactersInfo = await getCharactersInfo();
if (charactersInfo) {
systemMessage += `Here is the information available to you about the characters:\n`;
systemMessage += `<characters>\n${charactersInfo}</characters>\n\n`;
}
// Add persona info
if (context.name1) {
systemMessage += `The protagonist is:\n`;
systemMessage += `<persona>\n`;
// Use substituteParams to get {{persona}} like in initial encounter
try {
const personaText = substituteParams('{{persona}}');
if (personaText && personaText !== '{{persona}}') {
systemMessage += personaText;
} else {
systemMessage += `Name: ${context.name1}\n`;
if (extensionSettings.userStats?.personaDescription) {
systemMessage += `${extensionSettings.userStats.personaDescription}\n`;
}
}
} catch (e) {
systemMessage += `Name: ${context.name1}\n`;
if (extensionSettings.userStats?.personaDescription) {
systemMessage += `${extensionSettings.userStats.personaDescription}\n`;
}
}
// Add ONLY classic stats/attributes if enabled
if (extensionSettings.classicStats) {
const stats = extensionSettings.classicStats;
const config = extensionSettings.trackerConfig?.userStats;
const rpgAttributes = (config?.rpgAttributes && config.rpgAttributes.length > 0) ? config.rpgAttributes : [
{ id: 'str', name: 'STR', enabled: true },
{ id: 'dex', name: 'DEX', enabled: true },
{ id: 'con', name: 'CON', enabled: true },
{ id: 'int', name: 'INT', enabled: true },
{ id: 'wis', name: 'WIS', enabled: true },
{ id: 'cha', name: 'CHA', enabled: true }
];
const enabledAttributes = rpgAttributes.filter(attr => attr && attr.enabled && attr.name && attr.id);
const attributeStrings = enabledAttributes.map(attr => `${attr.name} ${stats[attr.id] || 10}`);
systemMessage += `\nAttributes: ${attributeStrings.join(', ')}, LVL ${extensionSettings.level}\n`;
}
systemMessage += `</persona>\n\n`;
}
messages.push({
role: 'system',
content: systemMessage
});
// Add recent chat history for context - append as user/assistant messages like initial encounter
const currentChat = context.chat || chat;
if (currentChat && currentChat.length > 0) {
const recentMessages = currentChat.slice(-depth);
for (const message of recentMessages) {
const content = message.mes?.trim();
// Skip empty messages
if (content) {
messages.push({
role: message.is_user ? 'user' : 'assistant',
content: content
});
}
}
}
// Add combat log as plain text (previous actions)
if (currentEncounter.encounterLog && currentEncounter.encounterLog.length > 0) {
let combatHistory = 'Previous Combat Actions:\n';
currentEncounter.encounterLog.forEach(entry => {
combatHistory += `- ${entry.action}\n`;
if (entry.result) {
combatHistory += ` ${entry.result}\n`;
}
});
messages.push({
role: 'user',
content: combatHistory
});
}
// Add current combat state with FULL information (but tell AI not to regenerate static parts)
let stateMessage = `Current Combat State:\n`;
stateMessage += `Environment: ${combatStats.environment || 'Unknown location'}\n\n`;
stateMessage += `Party Members:\n`;
combatStats.party.forEach(member => {
stateMessage += `- ${member.name}${member.isPlayer ? ' (Player)' : ''}: ${member.hp}/${member.maxHp} HP\n`;
if (member.attacks && member.attacks.length > 0) {
stateMessage += ` Attacks: ${member.attacks.map(a => typeof a === 'string' ? a : a.name).join(', ')}\n`;
}
if (member.items && member.items.length > 0) {
stateMessage += ` Items: ${member.items.join(', ')}\n`;
}
if (member.statuses && member.statuses.length > 0) {
const validStatuses = member.statuses.filter(s => s && (s.emoji || s.name));
if (validStatuses.length > 0) {
stateMessage += ` Status Effects: ${validStatuses.map(s => `${s.emoji || ''} ${s.name || ''}`.trim()).join(', ')}\n`;
}
}
});
stateMessage += `\nEnemies:\n`;
combatStats.enemies.forEach(enemy => {
stateMessage += `- ${enemy.name} (${enemy.sprite || ''}): ${enemy.hp}/${enemy.maxHp} HP\n`;
if (enemy.description) {
stateMessage += ` ${enemy.description}\n`;
}
if (enemy.attacks && enemy.attacks.length > 0) {
stateMessage += ` Attacks: ${enemy.attacks.map(a => typeof a === 'string' ? a : a.name).join(', ')}\n`;
}
if (enemy.statuses && enemy.statuses.length > 0) {
const validStatuses = enemy.statuses.filter(s => s && (s.emoji || s.name));
if (validStatuses.length > 0) {
stateMessage += ` Status Effects: ${validStatuses.map(s => `${s.emoji || ''} ${s.name || ''}`.trim()).join(', ')}\n`;
}
}
});
stateMessage += `\n${userName}'s Action: ${action}\n\n`;
stateMessage += `Respond with the exact JSON object as below, containing ONLY these specified values. Remember to consider the user's party and their moves. DO NOT regenerate character descriptions, sprites, or environment:\n`;
stateMessage += `{\n`;
stateMessage += ` "combatStats": {\n`;
stateMessage += ` "party": [{ "name": "Name", "hp": X, "maxHp": X, "statuses": [...] }],\n`;
stateMessage += ` "enemies": [{ "name": "Name", "hp": X, "maxHp": X, "statuses": [...] }]\n`;
stateMessage += ` },\n`;
stateMessage += ` "enemyActions": [{ "enemyName": "Name", "action": "what they do", "target": "target" }],\n`;
stateMessage += ` "partyActions": [{ "memberName": "Name", "action": "what they do", "target": "target" }],\n`;
stateMessage += ` "narrative": "The roleplay description of what happens"\n`;
stateMessage += `}\n\n`;
stateMessage += `If all enemies are defeated or escape: add "combatEnd": true, "result": "victory". If all party defeated: add "combatEnd": true, "result": "defeat". It's also possible for the encounter to be interrupted by external interference (e.g., an explosion knocks everyone out, sudden environmental catastrophe, third party intervention, etc.). If this occurs, add "combatEnd": true, "result": "interrupted". Each status (if applied) has a format: {"name": "Status Name", "emoji": "💀", "duration": X}.\n`;
stateMessage += `Scale combat difficulty appropriately: Powerful entities (gods, dragons, legendary creatures) should be formidable challenges requiring multiple rounds and strategic play. Weaker foes (common animals, basic enemies, minions) should be resolved more quickly, typically 2-4 rounds. Match HP damage and combat pacing to the narrative weight of the encounter. A wolf should not take 20 rounds to defeat, nor should a deity fall in one hit.\n`;
stateMessage += `For the narrative, write it with intent in ${tense} tense ${person}-person ${narration} from ${pov}'s point of view.\n`;
// Use custom combat narrative prompt if available
const customCombatPrompt = extensionSettings.customCombatNarrativePrompt;
if (customCombatPrompt) {
stateMessage += customCombatPrompt.replace(/{userName}/g, userName) + '\n';
} else {
stateMessage += `Build novel prose. Break patterns from your previous responses by varying sentence structures, rhythms, formats, and openings. Track whether a sentence shape, cadence, sensory detail, or a descriptor appeared recently, and replace it with a different one or skip it entirely. If you mentioned a physical feature, mannerism, or expression once, move on. Don't fixate on the same traits every turn. Well-placed humor, unconventional similes, and subverted turns of phrase are encouraged. Avoid GPTisms, purple prose, and anaphoras, especially the negatives with "no/not/wasn't/didn't." Refrain from describing actions or emotions via negation; focus on what does happen, not what doesn't. Absolutely no asterisks, ellipses, or em-dashes. Explicit content is allowed, no plot armor. Do not play for ${userName}. Keep your response length under 150 words. Never end on handover cues; finish naturally.\n`;
stateMessage += `CRITICAL: Do not repeat, echo, parrot, or restate distinctive words, phrases, and dialogues from the user's last message. If reacting to speech, show interpretation or response, not repetition.\n`;
stateMessage += `EXAMPLE: "Are you a gooner?" User asks.\n`;
stateMessage += `BAD: "Gooner?"\n`;
stateMessage += `GOOD: A flat look. "What type of question is that?"`;
}
messages.push({
role: 'user',
content: stateMessage
});
return messages;
}
/**
* Builds the final summary prompt
* This is sent when combat ends to get a narrative summary
* @param {Array} combatLog - Full combat log
* @param {string} result - Combat result ('victory', 'defeat', or 'fled')
* @returns {Promise<Array>} Message array for the API
*/
export async function buildCombatSummaryPrompt(combatLog, result) {
const context = getContext();
const userName = context.name1;
const messages = [];
// Get narrative style from settings (use summary narrative settings)
const narrativeStyle = extensionSettings.encounterSettings?.summaryNarrative || {};
const tense = narrativeStyle.tense || 'past';
const person = narrativeStyle.person || 'third';
const narration = narrativeStyle.narration || 'omniscient';
const pov = narrativeStyle.pov || 'narrator';
// Build system message with setting info
let systemMessage = `You are summarizing a combat encounter that just concluded.\n\n`;
// Add setting information
systemMessage += `Here is some information for you about the setting:\n`;
systemMessage += `<setting>\n`;
// Get world info using the same method as encounter init
let worldInfoAdded = false;
try {
const getWorldInfoFn = context.getWorldInfoPrompt || window.getWorldInfoPrompt;
const currentChat = context.chat || chat;
if (typeof getWorldInfoFn === 'function' && currentChat && currentChat.length > 0) {
const chatForWI = currentChat.map(x => x.mes || x.message || x).filter(m => m && typeof m === 'string');
const result = await getWorldInfoFn(chatForWI, 8000, false);
const worldInfoString = result?.worldInfoString || result;
if (worldInfoString && worldInfoString.trim()) {
systemMessage += worldInfoString.trim();
worldInfoAdded = true;
}
}
} catch (e) {
console.warn('[RPG Companion] Failed to get world info for summary:', e);
}
// Fallback to activatedWorldInfo
if (!worldInfoAdded && context.activatedWorldInfo && Array.isArray(context.activatedWorldInfo) && context.activatedWorldInfo.length > 0) {
context.activatedWorldInfo.forEach((entry) => {
if (entry && entry.content) {
systemMessage += `${entry.content}\n\n`;
worldInfoAdded = true;
}
});
}
if (!worldInfoAdded) {
systemMessage += 'No world information available.';
}
systemMessage += `\n</setting>\n\n`;
// Add character information
const charactersInfo = await getCharactersInfo();
if (charactersInfo) {
systemMessage += `Here is the information available to you about the characters:\n`;
systemMessage += `<characters>\n${charactersInfo}</characters>\n\n`;
}
// Add persona information
systemMessage += `Here are details about ${userName}:\n`;
systemMessage += `<persona>\n`;
try {
const personaText = substituteParams('{{persona}}');
if (personaText && personaText !== '{{persona}}') {
systemMessage += personaText;
} else {
systemMessage += 'No persona information available.';
}
} catch (e) {
systemMessage += 'No persona information available.';
}
systemMessage += `\n</persona>\n\n`;
// Add the message that triggered the encounter
if (currentEncounter.encounterStartMessage) {
systemMessage += `Here is the last message before combat started:\n`;
systemMessage += `<trigger>\n${currentEncounter.encounterStartMessage}\n</trigger>\n\n`;
}
messages.push({
role: 'system',
content: systemMessage
});
let summaryMessage = `Combat has ended with result: ${result}\n\n`;
summaryMessage += `Full Combat Log:\n`;
combatLog.forEach((entry, index) => {
summaryMessage += `\nRound ${index + 1}:\n`;
summaryMessage += `${entry.action}\n`;
summaryMessage += `${entry.result}\n`;
});
summaryMessage += `\n\nProvide a narrative summary of the entire fight in a way that fits the style from the chat history. Start with [FIGHT CONCLUDED] on the first line, then provide the description.\n\n`;
summaryMessage += `Write with intent in ${tense} tense ${person}-person ${narration} from ${pov}'s point of view.\n`;
summaryMessage += `Build novel prose. Break patterns from your previous responses by varying sentence structures, rhythms, formats, and openings. If you last started with a narration, begin this one with dialogue; if with an action, switch to an internal thought. Track whether a sentence shape, cadence, sensory detail, or a descriptor appeared recently, and replace it with a different one or skip it entirely. If you mentioned a physical feature, mannerism, or expression once, move on. Don't fixate on the same traits every turn. Well-placed humor, unconventional similes, and subverted turns of phrase are encouraged. Avoid GPTisms, purple prose, and anaphoras, especially the negatives with "no/not/wasn't/didn't." Refrain from describing actions or emotions via negation; focus on what does happen, not what doesn't. Minimize asterisks, ellipses, and em-dashes. Explicit content is allowed. Never end on handover cues; finish naturally.\n\n`;
summaryMessage += `Express ${userName}'s actions and dialogue using indirect speech (e.g., "${userName} swung their sword" or "${userName} asked for help"). The summary should be 2-4 paragraphs and capture the essence of the battle.\n\n`;
// If in Together mode and trackers are enabled, add tracker update instructions
if (extensionSettings.generationMode === 'together' && (extensionSettings.showUserStats || extensionSettings.showInfoBox || extensionSettings.showCharacterThoughts)) {
summaryMessage += `\n--- TRACKER UPDATE ---\n\n`;
summaryMessage += `After the [FIGHT CONCLUDED] summary, update the RPG trackers to reflect ${userName}'s state AFTER the combat encounter. `;
summaryMessage += `Account for any injuries sustained, resources used, emotional state changes, or other consequences of the battle.\n\n`;
// Include pre-combat tracker state if available
if (committedTrackerData.userStats || committedTrackerData.infoBox || committedTrackerData.characterThoughts) {
summaryMessage += `Pre-combat tracker state:\n`;
summaryMessage += `<previous>\n`;
if (committedTrackerData.userStats) {
const statsJSON = typeof committedTrackerData.userStats === 'object'
? JSON.stringify(committedTrackerData.userStats, null, 2)
: committedTrackerData.userStats;
summaryMessage += statsJSON + '\n';
}
if (committedTrackerData.infoBox) {
const infoBoxJSON = typeof committedTrackerData.infoBox === 'object'
? JSON.stringify(committedTrackerData.infoBox, null, 2)
: committedTrackerData.infoBox;
summaryMessage += infoBoxJSON + '\n';
}
if (committedTrackerData.characterThoughts) {
const charactersJSON = typeof committedTrackerData.characterThoughts === 'object'
? JSON.stringify(committedTrackerData.characterThoughts, null, 2)
: committedTrackerData.characterThoughts;
summaryMessage += charactersJSON + '\n';
}
summaryMessage += `</previous>\n\n`;
}
// Add tracker instructions and example
const trackerInstructions = generateTrackerInstructions(false, false, true);
summaryMessage += trackerInstructions;
const trackerExample = generateTrackerExample();
if (trackerExample) {
summaryMessage += `\n${trackerExample}`;
}
}
messages.push({
role: 'user',
content: summaryMessage
});
return messages;
}
/**
* Parses JSON response from the AI, handling code blocks
* @param {string} response - The AI response
* @returns {object|null} Parsed JSON object or null if parsing fails
*/
export function parseEncounterJSON(response) {
try {
// Remove code blocks if present
let cleaned = response.trim();
// Remove ```json, ```markdown, and ``` markers (more comprehensive)
cleaned = cleaned.replace(/```(?:json|markdown)?\s*/gi, '');
// Remove any remaining backticks
cleaned = cleaned.replace(/`/g, '');
// Find the first { and last }
const firstBrace = cleaned.indexOf('{');
const lastBrace = cleaned.lastIndexOf('}');
if (firstBrace !== -1 && lastBrace !== -1) {
cleaned = cleaned.substring(firstBrace, lastBrace + 1);
}
// Try to parse directly first
try {
return JSON.parse(cleaned);
} catch (initialError) {
// If direct parsing fails, try JSON repair
console.warn('[RPG Companion] Initial parse failed, attempting JSON repair...');
const repaired = repairJSON(cleaned);
if (repaired) {
// console.log('[RPG Companion] ✓ Successfully repaired encounter JSON');
return repaired;
}
// If repair also failed, throw the original error
throw initialError;
}
} catch (error) {
console.error('[RPG Companion] Failed to parse encounter JSON:', error);
console.error('[RPG Companion] Response was:', response);
return null;
}
}
+196 -59
View File
@@ -11,14 +11,27 @@ import {
lastGeneratedData,
isGenerating,
lastActionWasSwipe,
setLastActionWasSwipe
setLastActionWasSwipe,
setIsGenerating
} from '../../core/state.js';
import { evaluateSuppression } from './suppression.js';
import { parseUserStats } from './parser.js';
import {
generateTrackerExample,
generateTrackerInstructions,
generateContextualSummary
generateContextualSummary,
DEFAULT_HTML_PROMPT,
DEFAULT_DIALOGUE_COLORING_PROMPT,
DEFAULT_SPOTIFY_PROMPT,
SPOTIFY_FORMAT_INSTRUCTION
} from './promptBuilder.js';
import { restoreCheckpointOnLoad } from '../features/chapterCheckpoint.js';
// Type imports
/** @typedef {import('../../types/inventory.js').InventoryV2} InventoryV2 */
// Track last chat length we committed at to prevent duplicate commits from streaming
let lastCommittedChatLength = -1;
/**
* Event handler for generation start.
@@ -26,8 +39,15 @@ import {
*
* @param {string} type - Event type
* @param {Object} data - Event data
* @param {boolean} dryRun - If true, this is a dry run (page reload, prompt preview, etc.) - skip all logic
*/
export function onGenerationStarted(type, data) {
export async function onGenerationStarted(type, data, dryRun) {
// Skip dry runs (page reload, prompt manager preview, etc.)
if (dryRun) {
// console.log('[RPG Companion] Skipping onGenerationStarted: dry run detected');
return;
}
// console.log('[RPG Companion] onGenerationStarted called');
// console.log('[RPG Companion] enabled:', extensionSettings.enabled);
// console.log('[RPG Companion] generationMode:', extensionSettings.generationMode);
@@ -41,37 +61,125 @@ export function onGenerationStarted(type, data) {
}
if (!extensionSettings.enabled) {
// Extension is disabled - clear any existing prompts to ensure nothing is injected
setExtensionPrompt('rpg-companion-inject', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-example', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-dialogue-coloring', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-spotify', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-context', '', extension_prompt_types.IN_CHAT, 1, false);
return;
}
const chat = getContext().chat;
const context = getContext();
const chat = context.chat;
// Detect if a guided generation is active (GuidedGenerations and similar extensions
// inject an ephemeral 'instruct' injection into chatMetadata.script_injects).
// If present, we should avoid injecting RPG tracker instructions that ask
// the model to include stats/etc. This prevents conflicts when guided prompts
// are used (e.g., GuidedGenerations Extension).
// Evaluate suppression using the shared helper
const suppression = evaluateSuppression(extensionSettings, context, data);
const { shouldSuppress, skipMode, isGuidedGeneration, isImpersonationGeneration, hasQuietPrompt, instructContent, quietPromptRaw, matchedPattern } = suppression;
if (shouldSuppress) {
// Debugging: indicate active suppression and which source triggered it
console.debug(`[RPG Companion] Suppression active (mode=${skipMode}). isGuided=${isGuidedGeneration}, isImpersonation=${isImpersonationGeneration}, hasQuietPrompt=${hasQuietPrompt} - skipping RPG tracker injections for this generation.`);
// Also clear any existing RPG Companion prompts so they do not leak into this generation
// (e.g., previously set extension prompts should not be used alongside a guided prompt)
setExtensionPrompt('rpg-companion-inject', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-example', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-spotify', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-context', '', extension_prompt_types.IN_CHAT, 1, false);
}
// Ensure checkpoint is applied before generation
await restoreCheckpointOnLoad();
const currentChatLength = chat ? chat.length : 0;
const lastMessage = chat && chat.length > 0 ? chat[chat.length - 1] : null;
// For SEPARATE mode only: Check if we need to commit extension data
// For TOGETHER mode: Commit when user sends message (before first generation)
if (extensionSettings.generationMode === 'together') {
// By the time onGenerationStarted fires, ST has already added the placeholder AI message
// So we check the second-to-last message to see if user just sent a message
const secondToLastMessage = chat && chat.length > 1 ? chat[chat.length - 2] : null;
const isUserMessage = secondToLastMessage && secondToLastMessage.is_user;
// Commit if:
// 1. Second-to-last message is from USER (user just sent message)
// 2. Not a swipe (lastActionWasSwipe = false)
// 3. Haven't already committed for this chat length (prevent streaming duplicates)
const shouldCommit = isUserMessage && !lastActionWasSwipe && currentChatLength !== lastCommittedChatLength;
if (shouldCommit) {
// console.log('[RPG Companion] 📝 TOGETHER MODE COMMIT: User sent message - committing data from BEFORE user message');
// console.log('[RPG Companion] Chat length:', currentChatLength, 'Last committed:', lastCommittedChatLength);
// console.log('[RPG Companion] BEFORE: committedTrackerData =', {
// userStats: committedTrackerData.userStats ? `${committedTrackerData.userStats.substring(0, 50)}...` : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? `${committedTrackerData.characterThoughts.substring(0, 100)}...` : 'null'
// // });
// console.log('[RPG Companion] BEFORE: lastGeneratedData =', {
// userStats: lastGeneratedData.userStats ? `${lastGeneratedData.userStats.substring(0, 50)}...` : 'null',
// infoBox: lastGeneratedData.infoBox ? 'exists' : 'null',
// characterThoughts: lastGeneratedData.characterThoughts ? `${lastGeneratedData.characterThoughts.substring(0, 100)}...` : 'null'
// });
// Commit displayed data (from before user sent message)
committedTrackerData.userStats = lastGeneratedData.userStats;
committedTrackerData.infoBox = lastGeneratedData.infoBox;
committedTrackerData.characterThoughts = lastGeneratedData.characterThoughts;
// Track chat length to prevent duplicate commits
lastCommittedChatLength = currentChatLength;
// console.log('[RPG Companion] AFTER: committedTrackerData =', {
// userStats: committedTrackerData.userStats ? `${committedTrackerData.userStats.substring(0, 50)}...` : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? `${committedTrackerData.characterThoughts.substring(0, 100)}...` : 'null'
// });
} else if (lastActionWasSwipe) {
// console.log('[RPG Companion] ⏭️ Skipping commit: swipe (using previous committed data)');
} else if (!isUserMessage) {
// console.log('[RPG Companion] ⏭️ Skipping commit: second-to-last message is not user message (likely swipe or continuation)');
}
// console.log('[RPG Companion] 📦 TOGETHER MODE: Injecting committed tracker data into prompt');
// console.log('[RPG Companion] committedTrackerData =', {
// userStats: committedTrackerData.userStats ? `${committedTrackerData.userStats.substring(0, 50)}...` : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? `${committedTrackerData.characterThoughts.substring(0, 100)}...` : 'null'
// });
}
// For SEPARATE and EXTERNAL modes: Check if we need to commit extension data
// BUT: Only do this for the MAIN generation, not the tracker update generation
// If isGenerating is true, this is the tracker update generation (second call), so skip flag logic
// console.log('[RPG Companion DEBUG] Before generating:', lastGeneratedData.characterThoughts, ' , committed - ', committedTrackerData.characterThoughts);
if (extensionSettings.generationMode === 'separate' && !isGenerating) {
if ((extensionSettings.generationMode === 'separate' || extensionSettings.generationMode === 'external') && !isGenerating) {
if (!lastActionWasSwipe) {
// User sent a new message - commit lastGeneratedData before generation
// console.log('[RPG Companion] 📝 COMMIT: New message - committing lastGeneratedData');
// console.log('[RPG Companion] BEFORE commit - committedTrackerData:', {
// userStats: committedTrackerData.userStats ? 'exists' : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// });
// userStats: committedTrackerData.userStats ? 'exists' : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// // });
// console.log('[RPG Companion] BEFORE commit - lastGeneratedData:', {
// userStats: lastGeneratedData.userStats ? 'exists' : 'null',
// infoBox: lastGeneratedData.infoBox ? 'exists' : 'null',
// characterThoughts: lastGeneratedData.characterThoughts ? 'exists' : 'null'
// userStats: lastGeneratedData.userStats ? 'exists' : 'null',
// infoBox: lastGeneratedData.infoBox ? 'exists' : 'null',
// characterThoughts: lastGeneratedData.characterThoughts ? 'exists' : 'null'
// });
committedTrackerData.userStats = lastGeneratedData.userStats;
committedTrackerData.infoBox = lastGeneratedData.infoBox;
committedTrackerData.characterThoughts = lastGeneratedData.characterThoughts;
// console.log('[RPG Companion] AFTER commit - committedTrackerData:', {
// userStats: committedTrackerData.userStats ? 'exists' : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// userStats: committedTrackerData.userStats ? 'exists' : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// });
// Reset flag after committing (ready for next cycle)
@@ -79,28 +187,14 @@ export function onGenerationStarted(type, data) {
} else {
// console.log('[RPG Companion] 🔄 SWIPE: Using existing committedTrackerData (no commit)');
// console.log('[RPG Companion] committedTrackerData:', {
// userStats: committedTrackerData.userStats ? 'exists' : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// userStats: committedTrackerData.userStats ? 'exists' : 'null',
// infoBox: committedTrackerData.infoBox ? 'exists' : 'null',
// characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null'
// });
// Reset flag after using it (swipe generation complete, ready for next action)
}
}
// For TOGETHER mode: Check if we need to commit extension data
// Same logic as separate mode - commit on new messages, keep existing data on swipes
if (extensionSettings.generationMode === 'together') {
if (!lastActionWasSwipe) {
// User sent a new message - commit lastGeneratedData before generation
// console.log('[RPG Companion] 📝 TOGETHER MODE COMMIT: New message - committing lastGeneratedData');
committedTrackerData.userStats = lastGeneratedData.userStats;
committedTrackerData.infoBox = lastGeneratedData.infoBox;
committedTrackerData.characterThoughts = lastGeneratedData.characterThoughts;
} else {
// console.log('[RPG Companion] 🔄 TOGETHER MODE SWIPE: Using existing committedTrackerData (no commit)');
}
}
// Use the committed tracker data as source for generation
// console.log('[RPG Companion] Using committedTrackerData for generation');
// console.log('[RPG Companion] committedTrackerData.userStats:', committedTrackerData.userStats);
@@ -114,7 +208,10 @@ export function onGenerationStarted(type, data) {
if (extensionSettings.generationMode === 'together') {
// console.log('[RPG Companion] In together mode, generating prompts...');
const example = generateTrackerExample();
const exampleRaw = generateTrackerExample();
// Wrap example in ```json``` code blocks for consistency with format instructions
// Add only 1 newline after the closing ``` (ST adds its own newline when injecting)
const example = exampleRaw ? `\`\`\`json\n${exampleRaw}\n\`\`\`\n` : null;
// Don't include HTML prompt in instructions - inject it separately to avoid duplication on swipes
const instructions = generateTrackerInstructions(false, true);
@@ -145,7 +242,7 @@ export function onGenerationStarted(type, data) {
}
// If we have previous tracker data and found an assistant message, inject it as an assistant message
if (example && lastAssistantDepth > 0) {
if (!shouldSuppress && example && lastAssistantDepth > 0) {
setExtensionPrompt('rpg-companion-example', example, extension_prompt_types.IN_CHAT, lastAssistantDepth, false, extension_prompt_roles.ASSISTANT);
// console.log('[RPG Companion] Injected tracker example as assistant message at depth:', lastAssistantDepth);
} else {
@@ -153,17 +250,18 @@ export function onGenerationStarted(type, data) {
}
// Inject the instructions as a user message at depth 0 (right before generation)
setExtensionPrompt('rpg-companion-inject', instructions, extension_prompt_types.IN_CHAT, 0, false, extension_prompt_roles.USER);
// If this is a guided generation (user explicitly injected 'instruct'), skip adding
// our tracker instructions to avoid clobbering the guided prompt.
if (!shouldSuppress) {
setExtensionPrompt('rpg-companion-inject', instructions, extension_prompt_types.IN_CHAT, 0, false, extension_prompt_roles.USER);
}
// console.log('[RPG Companion] Injected RPG tracking instructions at depth 0 (right before generation)');
// Inject HTML prompt separately at depth 0 if enabled (prevents duplication on swipes)
if (extensionSettings.enableHtmlPrompt) {
const htmlPrompt = `\nIf appropriate, include inline HTML, CSS, and JS elements for creative, visual storytelling throughout your response:
- Use them liberally to depict any in-world content that can be visualized (screens, posters, books, signs, letters, logos, crests, seals, medallions, labels, etc.), with creative license for animations, 3D effects, pop-ups, dropdowns, websites, and so on.
- Style them thematically to match the theme (e.g., sleek for sci-fi, rustic for fantasy), ensuring text is visible.
- Embed all resources directly (e.g., inline SVGs) so nothing relies on external fonts or libraries.
- Place elements naturally in the narrative where characters would see or use them, with no limits on format or application.
- These HTML/CSS/JS elements must be rendered directly without enclosing them in code fences.`;
if (extensionSettings.enableHtmlPrompt && !shouldSuppress) {
// Use custom HTML prompt if set, otherwise use default
const htmlPromptText = extensionSettings.customHtmlPrompt || DEFAULT_HTML_PROMPT;
const htmlPrompt = `\n${htmlPromptText}`;
setExtensionPrompt('rpg-companion-html', htmlPrompt, extension_prompt_types.IN_CHAT, 0, false);
// console.log('[RPG Companion] Injected HTML prompt at depth 0 for together mode');
@@ -171,44 +269,81 @@ export function onGenerationStarted(type, data) {
// Clear HTML prompt if disabled
setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false);
}
} else if (extensionSettings.generationMode === 'separate') {
// In SEPARATE mode, inject the contextual summary for main roleplay generation
// Inject Dialogue Coloring prompt separately at depth 0 if enabled
if (extensionSettings.enableDialogueColoring && !shouldSuppress) {
// Use custom Dialogue Coloring prompt if set, otherwise use default
const dialogueColoringPromptText = extensionSettings.customDialogueColoringPrompt || DEFAULT_DIALOGUE_COLORING_PROMPT;
const dialogueColoringPrompt = `\n${dialogueColoringPromptText}`;
setExtensionPrompt('rpg-companion-dialogue-coloring', dialogueColoringPrompt, extension_prompt_types.IN_CHAT, 0, false);
// console.log('[RPG Companion] Injected Dialogue Coloring prompt at depth 0 for together mode');
} else {
// Clear Dialogue Coloring prompt if disabled
setExtensionPrompt('rpg-companion-dialogue-coloring', '', extension_prompt_types.IN_CHAT, 0, false);
}
// Inject Spotify prompt separately at depth 0 if enabled
if (extensionSettings.enableSpotifyMusic && !shouldSuppress) {
// Use custom Spotify prompt if set, otherwise use default
const spotifyPromptText = extensionSettings.customSpotifyPrompt || DEFAULT_SPOTIFY_PROMPT;
const spotifyPrompt = `\n${spotifyPromptText} ${SPOTIFY_FORMAT_INSTRUCTION}`;
setExtensionPrompt('rpg-companion-spotify', spotifyPrompt, extension_prompt_types.IN_CHAT, 0, false);
// console.log('[RPG Companion] Injected Spotify prompt at depth 0 for together mode');
} else {
// Clear Spotify prompt if disabled
setExtensionPrompt('rpg-companion-spotify', '', extension_prompt_types.IN_CHAT, 0, false);
}
} else if (extensionSettings.generationMode === 'separate' || extensionSettings.generationMode === 'external') {
// In SEPARATE and EXTERNAL modes, inject the contextual summary for main roleplay generation
const contextSummary = generateContextualSummary();
if (contextSummary) {
const wrappedContext = `Here is context information about the current scene, and what follows is the last message in the chat history:
const wrappedContext = `\nHere is context information about the current scene, and what follows is the last message in the chat history:
<context>
${contextSummary}
Ensure these details naturally reflect and influence the narrative. Character behavior, dialogue, and story events should acknowledge these conditions when relevant, such as fatigue affecting performance, low hygiene influencing social interactions, environmental factors shaping the scene, or a character's emotional state coloring their responses.
</context>
`;
</context>\n\n`;
// Inject context at depth 1 (before last user message) as SYSTEM
setExtensionPrompt('rpg-companion-context', wrappedContext, extension_prompt_types.IN_CHAT, 1, false);
// console.log('[RPG Companion] Injected contextual summary for separate mode:', contextSummary);
// Skip when a guided generation injection is present to avoid conflicting instructions
if (!shouldSuppress) {
setExtensionPrompt('rpg-companion-context', wrappedContext, extension_prompt_types.IN_CHAT, 1, false);
}
// console.log('[RPG Companion] Injected contextual summary for separate/external mode:', contextSummary);
} else {
// Clear if no data yet
setExtensionPrompt('rpg-companion-context', '', extension_prompt_types.IN_CHAT, 1, false);
}
// Inject HTML prompt separately at depth 0 if enabled (same as together mode pattern)
if (extensionSettings.enableHtmlPrompt) {
const htmlPrompt = `\nIf appropriate, include inline HTML, CSS, and JS elements for creative, visual storytelling throughout your response:
- Use them liberally to depict any in-world content that can be visualized (screens, posters, books, signs, letters, logos, crests, seals, medallions, labels, etc.), with creative license for animations, 3D effects, pop-ups, dropdowns, websites, and so on.
- Style them thematically to match the theme (e.g., sleek for sci-fi, rustic for fantasy), ensuring text is visible.
- Embed all resources directly (e.g., inline SVGs) so nothing relies on external fonts or libraries.
- Place elements naturally in the narrative where characters would see or use them, with no limits on format or application.
- These HTML/CSS/JS elements must be rendered directly without enclosing them in code fences.`;
if (extensionSettings.enableHtmlPrompt && !shouldSuppress) {
// Use custom HTML prompt if set, otherwise use default
const htmlPromptText = extensionSettings.customHtmlPrompt || DEFAULT_HTML_PROMPT;
const htmlPrompt = `\n${htmlPromptText}`;
setExtensionPrompt('rpg-companion-html', htmlPrompt, extension_prompt_types.IN_CHAT, 0, false);
// console.log('[RPG Companion] Injected HTML prompt at depth 0 for separate mode');
// console.log('[RPG Companion] Injected HTML prompt at depth 0 for separate/external mode');
} else {
// Clear HTML prompt if disabled
setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false);
}
// Inject Spotify prompt separately at depth 0 if enabled
if (extensionSettings.enableSpotifyMusic && !shouldSuppress) {
// Use custom Spotify prompt if set, otherwise use default
const spotifyPromptText = extensionSettings.customSpotifyPrompt || DEFAULT_SPOTIFY_PROMPT;
const spotifyPrompt = `\n${spotifyPromptText} ${SPOTIFY_FORMAT_INSTRUCTION}`;
setExtensionPrompt('rpg-companion-spotify', spotifyPrompt, extension_prompt_types.IN_CHAT, 0, false);
// console.log('[RPG Companion] Injected Spotify prompt at depth 0 for separate/external mode');
} else {
// Clear Spotify prompt if disabled
setExtensionPrompt('rpg-companion-spotify', '', extension_prompt_types.IN_CHAT, 0, false);
}
// Clear together mode injections
setExtensionPrompt('rpg-companion-inject', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-example', '', extension_prompt_types.IN_CHAT, 0, false);
@@ -217,5 +352,7 @@ Ensure these details naturally reflect and influence the narrative. Character be
setExtensionPrompt('rpg-companion-inject', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-example', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-context', '', extension_prompt_types.IN_CHAT, 1, false);
setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-spotify', '', extension_prompt_types.IN_CHAT, 0, false);
}
}
+10
View File
@@ -28,6 +28,7 @@ export function extractInventoryData(statsText) {
const result = {
version: 2,
onPerson: "None",
clothing: "None",
stored: {},
assets: "None"
};
@@ -48,6 +49,14 @@ export function extractInventoryData(statsText) {
continue;
}
// Parse "Clothing: ..." line
const clothingMatch = trimmed.match(/^Clothing:\s*(.+)$/i);
if (clothingMatch) {
result.clothing = clothingMatch[1].trim() || "None";
foundAnyInventoryData = true;
continue;
}
// Parse "Stored - [Location]: ..." lines
const storedMatch = trimmed.match(/^Stored\s*-\s*([^:]+):\s*(.+)$/i);
if (storedMatch) {
@@ -122,6 +131,7 @@ export function extractInventory(statsText) {
return {
version: 2,
onPerson: v1Data,
clothing: "None",
stored: {},
assets: "None"
};
+209
View File
@@ -0,0 +1,209 @@
/**
* JSON Prompt Builder Helpers
* Helper functions for building JSON format tracker prompts
*/
import { extensionSettings, committedTrackerData } from '../../core/state.js';
import { getContext } from '../../../../../../extensions.js';
/**
* Converts a field name to snake_case for use as JSON key
* Example: "Test Tracker" -> "test_tracker"
* @param {string} name - Field name to convert
* @returns {string} snake_case version
*/
function toSnakeCase(name) {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '');
}
/**
* Builds User Stats JSON format instruction
* @returns {string} JSON format instruction for user stats
*/
export function buildUserStatsJSONInstruction() {
const userName = getContext().name1;
const trackerConfig = extensionSettings.trackerConfig;
const userStatsConfig = trackerConfig?.userStats;
const enabledStats = userStatsConfig?.customStats?.filter(s => s && s.enabled && s.name) || [];
let instruction = '{\n';
instruction += ' "stats": [\n';
// Add stats dynamically
for (let i = 0; i < enabledStats.length; i++) {
const stat = enabledStats[i];
const comma = i < enabledStats.length - 1 ? ',' : '';
instruction += ` {"id": "${stat.id}", "name": "${stat.name}", "value": X}${comma}\n`;
}
instruction += ' ],\n';
// Status section
if (userStatsConfig?.statusSection?.enabled) {
instruction += ' "status": {\n';
if (userStatsConfig.statusSection.showMoodEmoji) {
instruction += ' "mood": "Mood Emoji",\n';
}
instruction += ' "conditions": "[Condition1, Condition2]"\n';
instruction += ' },\n';
}
// Skills section
if (userStatsConfig?.skillsSection?.enabled) {
instruction += ' "skills": [\n';
instruction += ' {"name": "Skill1"},\n';
instruction += ' {"name": "Skill2"}\n';
instruction += ' ],\n';
}
// Inventory section
if (extensionSettings.showInventory) {
instruction += ' "inventory": {\n';
instruction += ' "onPerson": [\n';
instruction += ' {"name": "Item1", "quantity": X},\n';
instruction += ' {"name": "Item2", "quantity": X}\n';
instruction += ' ],\n';
instruction += ' "clothing": [\n';
instruction += ' {"name": "Clothing1"}\n';
instruction += ' ],\n';
instruction += ' "stored": {\n';
instruction += ' "Location1": [\n';
instruction += ' {"name": "Item", "quantity": X}\n';
instruction += ' ]\n';
instruction += ' },\n';
instruction += ' "assets": [\n';
instruction += ' {"name": "Asset1", "location": "Location"}\n';
instruction += ' ]\n';
instruction += ' },\n';
}
// Quests section
instruction += ' "quests": {\n';
instruction += ' "main": {"title": "Quest title"},\n';
instruction += ' "optional": [\n';
instruction += ' {"title": "Quest1"},\n';
instruction += ' {"title": "Quest2"}\n';
instruction += ' ]\n';
instruction += ' }\n';
instruction += '}';
return instruction;
}
/**
* Builds Info Box JSON format instruction
* @returns {string} JSON format instruction for info box
*/
export function buildInfoBoxJSONInstruction() {
const infoBoxConfig = extensionSettings.trackerConfig?.infoBox;
const widgets = infoBoxConfig?.widgets || {};
let instruction = '{\n';
let hasFields = false;
if (widgets.date?.enabled) {
instruction += ' "date": {"value": "Weekday, Month, Year"}';
hasFields = true;
}
if (widgets.weather?.enabled) {
instruction += (hasFields ? ',\n' : '') + ' "weather": {"emoji": "Weather Emoji", "forecast": "Forecast"}';
hasFields = true;
}
if (widgets.temperature?.enabled) {
const unit = widgets.temperature.unit === 'F' ? 'F' : 'C';
instruction += (hasFields ? ',\n' : '') + ` "temperature": {"value": X, "unit": "${unit}"}`;
hasFields = true;
}
if (widgets.time?.enabled) {
instruction += (hasFields ? ',\n' : '') + ' "time": {"start": "TimeStart", "end": "TimeEnd"}';
hasFields = true;
}
if (widgets.location?.enabled) {
instruction += (hasFields ? ',\n' : '') + ' "location": {"value": "Location"}';
hasFields = true;
}
if (widgets.recentEvents?.enabled) {
instruction += (hasFields ? ',\n' : '') + ' "recentEvents": ["Event1", "Event2", "Event3"]';
hasFields = true;
}
instruction += '\n}';
return instruction;
}
/**
* Builds Present Characters JSON format instruction
* @returns {string} JSON format instruction for present characters
*/
export function buildCharactersJSONInstruction() {
const userName = getContext().name1;
const presentCharsConfig = extensionSettings.trackerConfig?.presentCharacters;
const enabledFields = presentCharsConfig?.customFields?.filter(f => f && f.enabled && f.name) || [];
const relationshipsEnabled = presentCharsConfig?.relationships?.enabled !== false;
const thoughtsConfig = presentCharsConfig?.thoughts;
const characterStats = presentCharsConfig?.characterStats;
const enabledCharStats = characterStats?.enabled && characterStats?.customStats?.filter(s => s && s.enabled && s.name) || [];
let instruction = '[\n';
instruction += ' {\n';
instruction += ' "name": "CharacterName",\n';
instruction += ' "emoji": "Character Emoji"';
// Details fields
if (enabledFields.length > 0) {
instruction += ',\n "details": {\n';
for (let i = 0; i < enabledFields.length; i++) {
const field = enabledFields[i];
const fieldKey = toSnakeCase(field.name);
const comma = i < enabledFields.length - 1 ? ',' : '';
instruction += ` "${fieldKey}": "${field.description}"${comma}\n`;
}
instruction += ' }';
}
// Relationship
if (relationshipsEnabled) {
const relationshipFields = presentCharsConfig?.relationshipFields || [];
const options = relationshipFields.join('/');
instruction += ',\n "relationship": {"status": "(choose one: ' + options + ')"}';
}
// Stats
if (enabledCharStats.length > 0) {
instruction += ',\n "stats": [\n';
for (let i = 0; i < enabledCharStats.length; i++) {
const stat = enabledCharStats[i];
const comma = i < enabledCharStats.length - 1 ? ',' : '';
instruction += ` {"name": "${stat.name}", "value": X}${comma}\n`;
}
instruction += ' ]';
}
// Thoughts
if (thoughtsConfig?.enabled) {
const thoughtsDescription = thoughtsConfig.description || 'Internal monologue';
instruction += `,\n "thoughts": {"content": "${thoughtsDescription}"}`;
}
instruction += '\n }\n';
instruction += ']';
return instruction;
}
/**
* Adds lock information to instruction text
* @param {string} baseInstruction - Base instruction text
* @returns {string} Instruction with lock information added
*/
export function addLockInstruction(baseInstruction) {
return baseInstruction + '\n\nIMPORTANT: If an item, stat, quest, or field has "locked": true in its object, you MUST NOT change its value. Keep it exactly as it appears in the previous trackers. Only unlocked items can be modified. The "locked" field should ONLY be included if the item is actually locked - omit it for unlocked items.';
}
+463
View File
@@ -0,0 +1,463 @@
/**
* Lock Manager
* Handles applying and removing locks for tracker items
* Locks prevent AI from modifying specific values
*/
import { extensionSettings } from '../../core/state.js';
import { repairJSON } from '../../utils/jsonRepair.js';
/**
* Apply locks to tracker data before sending to AI.
* Adds "locked": true to locked items in JSON format.
*
* @param {string} trackerData - JSON string of tracker data
* @param {string} trackerType - Type of tracker ('userStats', 'infoBox', 'characters')
* @returns {string} Tracker data with locks applied
*/
export function applyLocks(trackerData, trackerType) {
if (!trackerData) return trackerData;
// Try to parse as JSON
const parsed = repairJSON(trackerData);
if (!parsed) {
// Not JSON format, return as-is (text format doesn't support locks)
return trackerData;
}
// Get locked items for this tracker type
const lockedItems = extensionSettings.lockedItems?.[trackerType] || {};
// Apply locks based on tracker type
switch (trackerType) {
case 'userStats':
return applyUserStatsLocks(parsed, lockedItems);
case 'infoBox':
return applyInfoBoxLocks(parsed, lockedItems);
case 'characters':
return applyCharactersLocks(parsed, lockedItems);
default:
return trackerData;
}
}
/**
* Apply locks to User Stats tracker
* @param {Object} data - Parsed user stats data
* @param {Object} lockedItems - Locked items configuration
* @returns {string} JSON string with locks applied
*/
function applyUserStatsLocks(data, lockedItems) {
// Lock individual stats within stats object
if (data.stats && lockedItems.stats) {
// Handle both section lock and individual stat locks
const isStatsLocked = lockedItems.stats === true;
if (isStatsLocked) {
// Lock entire stats section
for (const statName in data.stats) {
data.stats[statName] = {
value: data.stats[statName].value || data.stats[statName],
locked: true
};
}
} else {
// Lock individual stats
for (const statName in lockedItems.stats) {
if (lockedItems.stats[statName] && data.stats[statName] !== undefined) {
data.stats[statName] = {
value: data.stats[statName].value || data.stats[statName],
locked: true
};
}
}
}
}
// Lock status field
if (data.status && lockedItems.status) {
data.status = {
...data.status,
locked: true
};
}
// Lock individual skills
if (data.skills && lockedItems.skills) {
if (Array.isArray(data.skills)) {
data.skills = data.skills.map(skill => {
if (typeof skill === 'string') {
if (lockedItems.skills[skill]) {
return { name: skill, locked: true };
}
return skill;
} else if (skill.name && lockedItems.skills[skill.name]) {
return { ...skill, locked: true };
}
return skill;
});
}
}
// Lock inventory items - handle bracket notation paths like "inventory.onPerson[0]"
if (data.inventory && lockedItems.inventory) {
// Helper function to parse bracket notation and apply lock
const applyInventoryLocks = (items, category) => {
if (!Array.isArray(items)) return items;
return items.map((item, index) => {
// Check if this specific item is locked using bracket notation with inventory prefix
const bracketPath = `${category}[${index}]`;
if (lockedItems.inventory[bracketPath]) {
return typeof item === 'string'
? { item, locked: true }
: { ...item, locked: true };
}
return item;
});
};
// Apply locks to onPerson items
if (data.inventory.onPerson) {
data.inventory.onPerson = applyInventoryLocks(data.inventory.onPerson, 'onPerson');
}
// Apply locks to clothing items
if (data.inventory.clothing) {
data.inventory.clothing = applyInventoryLocks(data.inventory.clothing, 'clothing');
}
// Apply locks to assets
if (data.inventory.assets) {
data.inventory.assets = applyInventoryLocks(data.inventory.assets, 'assets');
}
// Apply locks to stored items (nested structure with inventory.stored.location[index])
if (data.inventory.stored && lockedItems.inventory.stored) {
for (const location in data.inventory.stored) {
if (Array.isArray(data.inventory.stored[location])) {
data.inventory.stored[location] = data.inventory.stored[location].map((item, index) => {
const bracketPath = `${location}[${index}]`;
if (lockedItems.inventory.stored[bracketPath]) {
return typeof item === 'string'
? { item, locked: true }
: { ...item, locked: true };
}
return item;
});
}
}
}
}
// Lock individual quests - handle paths like "quests.main" and "quests.optional[0]"
if (data.quests && lockedItems.quests) {
// Check if main quest is locked (entire section)
if (data.quests.main && lockedItems.quests.main === true) {
data.quests.main = { value: data.quests.main, locked: true };
}
// Check individual optional quests
if (data.quests.optional && Array.isArray(data.quests.optional)) {
data.quests.optional = data.quests.optional.map((quest, index) => {
const bracketPath = `optional[${index}]`;
if (lockedItems.quests[bracketPath]) {
return typeof quest === 'string'
? { title: quest, locked: true }
: { ...quest, locked: true };
}
return quest;
});
}
}
return JSON.stringify(data, null, 2);
}
/**
* Apply locks to Info Box tracker
* @param {Object} data - Parsed info box data
* @param {Object} lockedItems - Locked items configuration
* @returns {string} JSON string with locks applied
*/
function applyInfoBoxLocks(data, lockedItems) {
if (lockedItems.date && data.date) {
data.date = { ...data.date, locked: true };
}
if (lockedItems.weather && data.weather) {
data.weather = { ...data.weather, locked: true };
}
if (lockedItems.temperature && data.temperature) {
data.temperature = { ...data.temperature, locked: true };
}
if (lockedItems.time && data.time) {
data.time = { ...data.time, locked: true };
}
if (lockedItems.location && data.location) {
data.location = { ...data.location, locked: true };
}
if (lockedItems.recentEvents && data.recentEvents) {
data.recentEvents = { ...data.recentEvents, locked: true };
}
return JSON.stringify(data, null, 2);
}
/**
* Apply locks to Characters tracker
* @param {Object} data - Parsed characters data
* @param {Object} lockedItems - Locked items configuration
* @returns {string} JSON string with locks applied
*/
function applyCharactersLocks(data, lockedItems) {
// console.log('[Lock Manager] applyCharactersLocks called');
// console.log('[Lock Manager] Locked items:', JSON.stringify(lockedItems, null, 2));
// console.log('[Lock Manager] Input data:', JSON.stringify(data, null, 2));
// Handle both array format and object format
let characters = Array.isArray(data) ? data : (data.characters || []);
characters = characters.map((char, index) => {
const charName = char.name || char.characterName;
// Check if entire character is locked (index-based)
if (lockedItems[index] === true) {
// console.log('[Lock Manager] Locking entire character by index:', index);
return { ...char, locked: true };
}
// Check if character name exists in locked items (could be nested object for field locks or boolean for full lock)
const charLocks = lockedItems[charName];
if (charLocks === true) {
// Entire character is locked
// console.log('[Lock Manager] Locking entire character:', charName);
return { ...char, locked: true };
} else if (charLocks && typeof charLocks === 'object') {
// Character has field-level locks
const modifiedChar = { ...char };
for (const fieldName in charLocks) {
if (charLocks[fieldName] === true) {
// Check both the original field name and snake_case version
// (AI returns snake_case, but locks are stored with original configured names)
// Use the same conversion as toSnakeCase in thoughts.js
const snakeCaseFieldName = fieldName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '');
let locked = false;
// Check at root level first (backward compatibility)
if (modifiedChar[fieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to field:', `${charName}.${fieldName}`);
modifiedChar[fieldName] = {
value: modifiedChar[fieldName],
locked: true
};
locked = true;
} else if (modifiedChar[snakeCaseFieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to snake_case field:', `${charName}.${snakeCaseFieldName} (from ${fieldName})`);
modifiedChar[snakeCaseFieldName] = {
value: modifiedChar[snakeCaseFieldName],
locked: true
};
locked = true;
}
// Check in nested objects (details, relationship, thoughts)
if (!locked && modifiedChar.details) {
if (modifiedChar.details[fieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to details field:', `${charName}.details.${fieldName}`);
if (!modifiedChar.details || typeof modifiedChar.details !== 'object') {
modifiedChar.details = {};
} else {
modifiedChar.details = { ...modifiedChar.details };
}
modifiedChar.details[fieldName] = {
value: modifiedChar.details[fieldName],
locked: true
};
locked = true;
} else if (modifiedChar.details[snakeCaseFieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to details snake_case field:', `${charName}.details.${snakeCaseFieldName} (from ${fieldName})`);
if (!modifiedChar.details || typeof modifiedChar.details !== 'object') {
modifiedChar.details = {};
} else {
modifiedChar.details = { ...modifiedChar.details };
}
modifiedChar.details[snakeCaseFieldName] = {
value: modifiedChar.details[snakeCaseFieldName],
locked: true
};
locked = true;
}
}
// Check in relationship object
if (!locked && modifiedChar.relationship) {
if (modifiedChar.relationship[fieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to relationship field:', `${charName}.relationship.${fieldName}`);
modifiedChar.relationship = { ...modifiedChar.relationship };
modifiedChar.relationship[fieldName] = {
value: modifiedChar.relationship[fieldName],
locked: true
};
locked = true;
} else if (modifiedChar.relationship[snakeCaseFieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to relationship snake_case field:', `${charName}.relationship.${snakeCaseFieldName} (from ${fieldName})`);
modifiedChar.relationship = { ...modifiedChar.relationship };
modifiedChar.relationship[snakeCaseFieldName] = {
value: modifiedChar.relationship[snakeCaseFieldName],
locked: true
};
locked = true;
}
}
// Check in thoughts object
if (!locked && modifiedChar.thoughts) {
if (modifiedChar.thoughts[fieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to thoughts field:', `${charName}.thoughts.${fieldName}`);
modifiedChar.thoughts = { ...modifiedChar.thoughts };
modifiedChar.thoughts[fieldName] = {
value: modifiedChar.thoughts[fieldName],
locked: true
};
locked = true;
} else if (modifiedChar.thoughts[snakeCaseFieldName] !== undefined) {
// console.log('[Lock Manager] Applying lock to thoughts snake_case field:', `${charName}.thoughts.${snakeCaseFieldName} (from ${fieldName})`);
modifiedChar.thoughts = { ...modifiedChar.thoughts };
modifiedChar.thoughts[snakeCaseFieldName] = {
value: modifiedChar.thoughts[snakeCaseFieldName],
locked: true
};
locked = true;
}
}
}
}
return modifiedChar;
}
// No locks for this character
return char;
});
const result = Array.isArray(data)
? JSON.stringify(characters, null, 2)
: JSON.stringify({ ...data, characters }, null, 2);
// console.log('[Lock Manager] Output data:', result);
return result;
}
/**
* Remove locks from tracker data received from AI.
* Strips "locked": true from all items to clean up the data.
*
* @param {string} trackerData - JSON string of tracker data
* @returns {string} Tracker data with locks removed
*/
export function removeLocks(trackerData) {
if (!trackerData) return trackerData;
// Try to parse as JSON
const parsed = repairJSON(trackerData);
if (!parsed) {
// Not JSON format, return as-is
return trackerData;
}
// Recursively remove all "locked" properties
const cleaned = removeLockedProperties(parsed);
return JSON.stringify(cleaned, null, 2);
}
/**
* Recursively remove "locked" properties from an object
* @param {*} obj - Object to clean
* @returns {*} Object with locked properties removed
*/
function removeLockedProperties(obj) {
if (Array.isArray(obj)) {
return obj.map(item => removeLockedProperties(item));
} else if (obj !== null && typeof obj === 'object') {
const cleaned = {};
for (const key in obj) {
if (key !== 'locked') {
cleaned[key] = removeLockedProperties(obj[key]);
}
}
return cleaned;
}
return obj;
}
/**
* Check if a specific item is locked
* @param {string} trackerType - Type of tracker
* @param {string} itemPath - Path to the item (e.g., 'stats.Health', 'quests.main.0')
* @returns {boolean} Whether the item is locked
*/
export function isItemLocked(trackerType, itemPath) {
const lockedItems = extensionSettings.lockedItems?.[trackerType];
if (!lockedItems) return false;
const parts = itemPath.split('.');
let current = lockedItems;
for (const part of parts) {
if (current[part] === undefined) return false;
current = current[part];
}
return !!current;
}
/**
* Toggle lock state for a specific item
* @param {string} trackerType - Type of tracker
* @param {string} itemPath - Path to the item
* @param {boolean} locked - New lock state
*/
export function setItemLock(trackerType, itemPath, locked) {
// console.log('[Lock Manager] setItemLock called:', { trackerType, itemPath, locked });
if (!extensionSettings.lockedItems) {
extensionSettings.lockedItems = {};
}
if (!extensionSettings.lockedItems[trackerType]) {
extensionSettings.lockedItems[trackerType] = {};
}
const parts = itemPath.split('.');
let current = extensionSettings.lockedItems[trackerType];
// Navigate to parent of target
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
if (!current[part]) {
current[part] = {};
}
current = current[part];
}
// Set or remove lock
const finalKey = parts[parts.length - 1];
if (locked) {
current[finalKey] = true;
} else {
delete current[finalKey];
}
// console.log('[Lock Manager] Locked items after set:', JSON.stringify(extensionSettings.lockedItems, null, 2));
}
+364 -2
View File
@@ -1,11 +1,13 @@
/**
* Parser Module
* Handles parsing of AI responses to extract tracker data
* Supports both legacy text format and new v3 JSON format
*/
import { extensionSettings, FEATURE_FLAGS, addDebugLog } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { extractInventory } from './inventoryParser.js';
import { repairJSON } from '../../utils/jsonRepair.js';
/**
* Helper to separate emoji from text in a string
@@ -127,7 +129,7 @@ function stripBrackets(text) {
* Helper to log to both console and debug logs array
*/
function debugLog(message, data = null) {
console.log(message, data || '');
// console.log(message, data || '');
if (extensionSettings.debugMode) {
addDebugLog(message, data);
}
@@ -159,6 +161,248 @@ export function parseResponse(responseText) {
cleanedResponse = cleanedResponse.replace(/<thinking>[\s\S]*?<\/thinking>/gi, '');
debugLog('[RPG Parser] Removed thinking tags, new length:', cleanedResponse.length + ' chars');
// Remove "FORMAT:" markers that the model might accidentally output
cleanedResponse = cleanedResponse.replace(/FORMAT:\s*/gi, '');
debugLog('[RPG Parser] Removed FORMAT: markers, new length:', cleanedResponse.length + ' chars');
// First, try to extract raw JSON objects (v3 format)
// Note: Prompts now instruct models to use ```json``` code blocks, but we extract
// from any JSON found using brace-matching for maximum compatibility
// Use brace-matching to find complete JSON objects
const extractedObjects = [];
let i = 0;
while (i < cleanedResponse.length) {
if (cleanedResponse[i] === '{') {
// Found opening brace, find matching closing brace
let depth = 1;
let j = i + 1;
let inString = false;
let escapeNext = false;
while (j < cleanedResponse.length && depth > 0) {
const char = cleanedResponse[j];
if (escapeNext) {
escapeNext = false;
} else if (char === '\\') {
escapeNext = true;
} else if (char === '"') {
inString = !inString;
} else if (!inString) {
if (char === '{') depth++;
else if (char === '}') depth--;
}
j++;
}
if (depth === 0) {
// Found complete JSON object
const jsonContent = cleanedResponse.substring(i, j).trim();
extractedObjects.push(jsonContent);
i = j;
} else {
i++;
}
} else {
i++;
}
}
if (extractedObjects.length > 0) {
// console.log(`[RPG Parser] ✓ Found ${extractedObjects.length} raw JSON objects (v3 format)`);
debugLog(`[RPG Parser] ✓ Found ${extractedObjects.length} raw JSON objects (v3 format)`);
// First, try to parse as unified JSON structure (new v3.1 format)
if (extractedObjects.length === 1) {
const parsed = repairJSON(extractedObjects[0]);
if (parsed && (parsed.userStats || parsed.infoBox || parsed.characters)) {
// console.log('[RPG Parser] ✓ Detected unified JSON structure (v3.1 format)');
if (parsed.userStats) {
result.userStats = JSON.stringify(parsed.userStats);
// console.log('[RPG Parser] ✓ Extracted userStats from unified structure');
}
if (parsed.infoBox) {
result.infoBox = JSON.stringify(parsed.infoBox);
// console.log('[RPG Parser] ✓ Extracted infoBox from unified structure');
}
if (parsed.characters) {
result.characterThoughts = JSON.stringify(parsed.characters);
// console.log('[RPG Parser] ✓ Extracted characters from unified structure');
}
if (result.userStats || result.infoBox || result.characterThoughts) {
// console.log('[RPG Parser] ✓ Returning unified JSON parse results');
debugLog('[RPG Parser] Returning unified JSON parse results');
return result;
}
}
}
// Fall back to parsing multiple separate JSON objects (legacy v3.0 format)
for (let idx = 0; idx < extractedObjects.length; idx++) {
const jsonContent = extractedObjects[idx];
// console.log(`[RPG Parser] Parsing object ${idx + 1}:`, jsonContent.substring(0, 100) + '...');
// console.log(`[RPG Parser] Full object ${idx + 1} length:`, jsonContent.length);
const parsed = repairJSON(jsonContent);
if (parsed) {
// console.log(`[RPG Parser] Object ${idx + 1} parsed successfully, keys:`, Object.keys(parsed));
// Check if object is wrapped (e.g., {"userStats": {...}})
// Unwrap single-key objects that match our tracker types
let unwrapped = parsed;
if (Object.keys(parsed).length === 1) {
const key = Object.keys(parsed)[0];
if (key === 'userStats' || key === 'infoBox' || key === 'characters') {
unwrapped = parsed[key];
// console.log(`[RPG Parser] ✓ Unwrapped ${key} object`);
}
}
// Detect tracker type by checking for top-level fields
if (unwrapped.stats || unwrapped.status || unwrapped.skills || unwrapped.inventory || unwrapped.quests) {
result.userStats = jsonContent;
// console.log('[RPG Parser] ✓ Assigned to User Stats');
debugLog('[RPG Parser] ✓ Extracted raw JSON User Stats');
} else if (unwrapped.date || unwrapped.location || unwrapped.weather || unwrapped.temperature || unwrapped.time) {
result.infoBox = jsonContent;
// console.log('[RPG Parser] ✓ Assigned to Info Box');
debugLog('[RPG Parser] ✓ Extracted raw JSON Info Box');
} else if (unwrapped.characters || Array.isArray(unwrapped)) {
result.characterThoughts = jsonContent;
// console.log('[RPG Parser] ✓ Assigned to Characters');
debugLog('[RPG Parser] ✓ Extracted raw JSON Characters');
} else {
console.warn('[RPG Parser] ⚠️ Could not categorize object with keys:', Object.keys(parsed));
}
} else {
console.error('[RPG Parser] ✗ Failed to parse raw JSON object', idx + 1);
}
}
if (result.userStats || result.infoBox || result.characterThoughts) {
// console.log('[RPG Parser] ✓ Returning raw JSON parse results:', {
// hasUserStats: !!result.userStats,
// hasInfoBox: !!result.infoBox,
// hasCharacters: !!result.characterThoughts
// });
debugLog('[RPG Parser] Returning raw JSON parse results');
return result;
} else {
console.warn('[RPG Parser] ⚠️ No tracker data extracted from', extractedObjects.length, 'objects');
}
}
// Check for JSON code blocks (legacy v3 format with ```json fences)
// Look for ```json code blocks which indicate JSON format
const jsonBlockRegex = /```json\s*\n([\s\S]*?)```/g;
const jsonMatches = [...cleanedResponse.matchAll(jsonBlockRegex)];
if (jsonMatches.length > 0) {
// console.log('[RPG Parser] ✓ Found', jsonMatches.length, 'JSON code blocks (v3 format with fences)');
debugLog('[RPG Parser] ✓ Found JSON code blocks (v3 format), parsing as JSON');
for (let idx = 0; idx < jsonMatches.length; idx++) {
const match = jsonMatches[idx];
const jsonContent = match[1].trim();
// console.log(`[RPG Parser] Parsing JSON block ${idx + 1}:`, jsonContent.substring(0, 100) + '...');
const parsed = repairJSON(jsonContent);
if (parsed) {
// console.log(`[RPG Parser] JSON block ${idx + 1} parsed successfully, keys:`, Object.keys(parsed));
// Detect tracker type by checking for top-level fields
if (parsed.stats || parsed.status || parsed.skills || parsed.inventory || parsed.quests) {
result.userStats = jsonContent;
// console.log('[RPG Parser] ✓ Assigned to User Stats');
debugLog('[RPG Parser] ✓ Extracted JSON User Stats');
} else if (parsed.date || parsed.location || parsed.weather || parsed.temperature || parsed.time) {
result.infoBox = jsonContent;
// console.log('[RPG Parser] ✓ Assigned to Info Box');
debugLog('[RPG Parser] ✓ Extracted JSON Info Box');
} else if (parsed.characters || Array.isArray(parsed)) {
result.characterThoughts = jsonContent;
// console.log('[RPG Parser] ✓ Assigned to Characters');
debugLog('[RPG Parser] ✓ Extracted JSON Characters');
} else {
console.warn('[RPG Parser] ⚠️ Could not categorize JSON block with keys:', Object.keys(parsed));
}
} else {
console.error('[RPG Parser] ✗ Failed to parse JSON code block', idx + 1);
debugLog('[RPG Parser] ✗ Failed to parse JSON block, will try text fallback');
}
}
// If we found at least one valid JSON block, return the result
// Mixed formats (some JSON, some text) will still work
if (result.userStats || result.infoBox || result.characterThoughts) {
// console.log('[RPG Parser] ✓ Returning JSON code block parse results:', {
// hasUserStats: !!result.userStats,
// hasInfoBox: !!result.infoBox,
// hasCharacters: !!result.characterThoughts
// });
debugLog('[RPG Parser] Returning JSON parse results');
return result;
} else {
console.warn('[RPG Parser] ⚠️ No tracker data extracted from', jsonMatches.length, 'JSON blocks');
}
}
// Check if response uses XML <trackers> tags (hybrid format)
const xmlMatch = cleanedResponse.match(/<trackers>([\s\S]*?)<\/trackers>/i);
if (xmlMatch) {
debugLog('[RPG Parser] ✓ Found XML <trackers> tags, using XML parser');
const trackersContent = xmlMatch[1].trim();
// Try to parse JSON blocks within XML first
const xmlJsonMatches = [...trackersContent.matchAll(jsonBlockRegex)];
if (xmlJsonMatches.length > 0) {
debugLog('[RPG Parser] Found JSON blocks within XML tags');
for (const match of xmlJsonMatches) {
const jsonContent = match[1].trim();
const parsed = repairJSON(jsonContent);
if (parsed) {
if (parsed.type === 'userStats' || parsed.stats) {
result.userStats = jsonContent;
} else if (parsed.type === 'infoBox' || parsed.date || parsed.location) {
result.infoBox = jsonContent;
} else if (parsed.type === 'characters' || parsed.characters || Array.isArray(parsed)) {
result.characterThoughts = jsonContent;
}
}
}
} else {
// Fallback to text extraction from XML content (legacy v2 text format)
const statsMatch = trackersContent.match(/(User )?Stats\s*\n\s*---[\s\S]*?(?=\n\s*\n\s*(Info Box|Present Characters)|$)/i);
if (statsMatch) {
result.userStats = stripBrackets(statsMatch[0].trim());
debugLog('[RPG Parser] ✓ Extracted Stats from XML (text format)');
}
const infoBoxMatch = trackersContent.match(/Info Box\s*\n\s*---[\s\S]*?(?=\n\s*\n\s*Present Characters|$)/i);
if (infoBoxMatch) {
result.infoBox = stripBrackets(infoBoxMatch[0].trim());
debugLog('[RPG Parser] ✓ Extracted Info Box from XML (text format)');
}
const charactersMatch = trackersContent.match(/Present Characters\s*\n\s*---[\s\S]*$/i);
if (charactersMatch) {
result.characterThoughts = stripBrackets(charactersMatch[0].trim());
debugLog('[RPG Parser] ✓ Extracted Present Characters from XML (text format)');
}
}
debugLog('[RPG Parser] Parsed from XML:', result);
return result;
}
// Fallback to markdown code block parsing (old text format or mixed format)
debugLog('[RPG Parser] No XML tags found, using code block parser');
// Extract code blocks
const codeBlockRegex = /```([^`]+)```/g;
const matches = [...cleanedResponse.matchAll(codeBlockRegex)];
@@ -256,8 +500,14 @@ export function parseResponse(responseText) {
debugLog('[RPG Parser] Found Characters:', !!result.characterThoughts);
debugLog('[RPG Parser] =======================================================');
// Check if we found at least one section - if not, mark as parsing failure
if (!result.userStats && !result.infoBox && !result.characterThoughts) {
result.parsingFailed = true;
console.error('[RPG Parser] ❌ No tracker data found in response - parsing failed');
}
return result;
}
} // End parseResponse
/**
* Parses user stats from the text and updates the extensionSettings.
@@ -271,6 +521,118 @@ export function parseUserStats(statsText) {
debugLog('[RPG Parser] Stats text preview:', statsText.substring(0, 200));
try {
// Check if this is v3 JSON format - try to parse it first
let statsData = null;
const trimmed = statsText.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
statsData = repairJSON(statsText);
if (statsData) {
debugLog('[RPG Parser] ✓ Parsed as v3 JSON format');
// Extract stats from v3 JSON structure
if (statsData.stats && Array.isArray(statsData.stats)) {
// console.log('[RPG Parser] ✓ Extracting stats array, count:', statsData.stats.length);
statsData.stats.forEach(stat => {
if (stat.id && typeof stat.value !== 'undefined') {
extensionSettings.userStats[stat.id] = stat.value;
// console.log(`[RPG Parser] ✓ Set ${stat.id} = ${stat.value}`);
}
});
}
// Extract status
if (statsData.status) {
// console.log('[RPG Parser] ✓ Extracting status:', statsData.status);
if (statsData.status.mood) {
extensionSettings.userStats.mood = statsData.status.mood;
// console.log('[RPG Parser] ✓ Set mood =', statsData.status.mood);
}
if (statsData.status.conditions) {
extensionSettings.userStats.conditions = statsData.status.conditions;
// console.log('[RPG Parser] ✓ Set conditions =', statsData.status.conditions);
}
}
// Extract inventory (convert v3 array format to v2 string format)
if (statsData.inventory) {
const inv = statsData.inventory;
// Convert arrays of {name, quantity} objects to comma-separated strings
const convertItems = (items) => {
if (!items || !Array.isArray(items)) return '';
return items.map(item => {
if (typeof item === 'object' && item.name) {
// Include quantity if > 1
return item.quantity && item.quantity > 1
? `${item.quantity}x ${item.name}`
: item.name;
}
return String(item);
}).join(', ');
};
// Convert stored object {location: [items]} to {location: "item1, item2"}
const convertStoredInventory = (stored) => {
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return {};
const result = {};
for (const [location, items] of Object.entries(stored)) {
if (Array.isArray(items)) {
result[location] = convertItems(items);
} else if (typeof items === 'string') {
result[location] = items;
} else {
result[location] = '';
}
}
return result;
};
extensionSettings.userStats.inventory = {
onPerson: convertItems(inv.onPerson),
clothing: convertItems(inv.clothing),
stored: convertStoredInventory(inv.stored),
assets: convertItems(inv.assets)
};
// console.log('[RPG Parser] ✓ Converted v3 inventory:', extensionSettings.userStats.inventory);
}
// Extract quests (convert v3 object format to v2 string format)
if (statsData.quests) {
// Convert quest objects to strings
const convertQuest = (quest) => {
if (!quest) return '';
if (typeof quest === 'string') return quest;
if (typeof quest === 'object') {
// v3 format: {title, description, status}
return quest.title || quest.description || JSON.stringify(quest);
}
return String(quest);
};
extensionSettings.quests = {
main: convertQuest(statsData.quests.main),
optional: Array.isArray(statsData.quests.optional)
? statsData.quests.optional.map(convertQuest)
: []
};
// console.log('[RPG Parser] ✓ Converted v3 quests:', extensionSettings.quests);
}
// Extract skills if present (store as object, not JSON string)
if (statsData.skills && Array.isArray(statsData.skills)) {
extensionSettings.userStats.skills = statsData.skills;
// console.log('[RPG Parser] ✓ Set skills:', extensionSettings.userStats.skills);
}
debugLog('[RPG Parser] ✓ Successfully extracted v3 JSON data');
saveSettings();
return; // Done processing v3 format
}
}
// Fall back to v2 text format parsing if JSON parsing failed
debugLog('[RPG Parser] Falling back to v2 text format parsing');
// Get custom stat configuration
const trackerConfig = extensionSettings.trackerConfig;
const customStats = trackerConfig?.userStats?.customStats || [];
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
/**
* Suppression helper for guided generation injection behavior.
*
* This module exports a pure function `evaluateSuppression` that computes
* whether RPG Companion should suppress tracker and HTML injections for a
* given generation request, based on runtime settings, extended context, and
* generation data (quiet prompt flags, etc.).
*/
/**
* Determine if suppression should be applied for this generation.
*
* @param {any} extensionSettings - extension settings object (may contain skipInjectionsForGuided)
* @param {any} context - SillyTavern context object (used to find chatMetadata.script_injects.instruct)
* @param {any} data - Generation data (contains quiet_prompt/quietPrompt flags)
* @returns {Object} - An object describing the suppression decision.
*/
export function evaluateSuppression(extensionSettings, context, data) {
// Detect presence of any injected `instruct` script
const instructObj = context?.chatMetadata?.script_injects?.instruct;
const isGuidedGeneration = !!instructObj;
const quietPromptRaw = data?.quiet_prompt || data?.quietPrompt || '';
const hasQuietPrompt = !!quietPromptRaw;
// Normalize the injected instruction body (it may be an object with a 'value' field or a raw string)
let instructContent = '';
if (instructObj) {
if (typeof instructObj === 'object') {
instructContent = String(instructObj.value || instructObj || '');
} else {
instructContent = String(instructObj);
}
}
const IMPERSONATION_PATTERNS = [
{ id: 'first-perspective', re: /write in first person perspective from/i },
{ id: 'second-perspective', re: /write in second person perspective from/i },
{ id: 'third-perspective', re: /write in third person perspective from/i },
{ id: 'you-yours', re: /using you\/yours for/i },
{ id: 'third-person-pronouns', re: /third-person pronouns for/i },
{ id: 'impersonate-word', re: /\bimpersonat(e|ion)?\b/i },
{ id: 'assume-role', re: /assume the role of/i },
{ id: 'play-role', re: /play the role of/i },
{ id: 'impersonate-command', re: /\/impersonate await=true/i },
{ id: 'generic-first', re: /\bfirst person\b/i },
{ id: 'generic-second', re: /\bsecond person\b/i },
{ id: 'generic-third', re: /\bthird person\b/i }
];
// Include quietPrompt raw text in detection; guided impersonation flows may pass it directly here
const combinedTextForDetection = [instructContent, quietPromptRaw].filter(Boolean).join('\n');
let matchedPattern = '';
let isImpersonationGeneration = false;
if (combinedTextForDetection.length) {
for (const pat of IMPERSONATION_PATTERNS) {
if (pat.re.test(combinedTextForDetection)) {
matchedPattern = pat.id;
isImpersonationGeneration = true;
break;
}
}
}
const skipMode = (extensionSettings && extensionSettings.skipInjectionsForGuided) || 'none';
// Compute suppression according to mode
const shouldSuppress = skipMode === 'guided'
? (isGuidedGeneration || hasQuietPrompt)
: (skipMode === 'impersonation' ? isImpersonationGeneration : false);
return {
shouldSuppress,
skipMode,
isGuidedGeneration,
isImpersonationGeneration,
hasQuietPrompt,
instructContent,
quietPromptRaw,
matchedPattern
};
}
+148 -55
View File
@@ -4,7 +4,7 @@
*/
import { getContext } from '../../../../../../extensions.js';
import { chat, user_avatar, setExtensionPrompt, extension_prompt_types } from '../../../../../../../script.js';
import { chat, user_avatar, setExtensionPrompt, extension_prompt_types, saveChatDebounced } from '../../../../../../../script.js';
// Core modules
import {
@@ -15,14 +15,20 @@ import {
isPlotProgression,
setLastActionWasSwipe,
setIsPlotProgression,
setIsGenerating,
updateLastGeneratedData,
updateCommittedTrackerData
updateCommittedTrackerData,
$musicPlayerContainer
} from '../../core/state.js';
import { saveChatData, loadChatData } from '../../core/persistence.js';
import { i18n } from '../../core/i18n.js';
// Generation & Parsing
import { parseResponse, parseUserStats } from '../generation/parser.js';
import { parseAndStoreSpotifyUrl, convertToEmbedUrl } from '../features/musicPlayer.js';
import { updateRPGData } from '../generation/apiClient.js';
import { removeLocks } from '../generation/lockManager.js';
import { onGenerationStarted } from '../generation/injector.js';
// Rendering
import { renderUserStats } from '../rendering/userStats.js';
@@ -30,10 +36,15 @@ import { renderInfoBox } from '../rendering/infoBox.js';
import { renderThoughts, updateChatThoughts } from '../rendering/thoughts.js';
import { renderInventory } from '../rendering/inventory.js';
import { renderQuests } from '../rendering/quests.js';
import { renderMusicPlayer } from '../rendering/musicPlayer.js';
// Utils
import { getSafeThumbnailUrl } from '../../utils/avatars.js';
// Chapter checkpoint
import { updateAllCheckpointIndicators } from '../ui/checkpointUI.js';
import { restoreCheckpointOnLoad } from '../features/chapterCheckpoint.js';
/**
* Commits the tracker data from the last assistant message to be used as source for next generation.
* This should be called when the user has replied to a message, ensuring all swipes of the next
@@ -73,35 +84,81 @@ export function commitTrackerData() {
/**
* Event handler for when the user sends a message.
* Sets the flag to indicate this is NOT a swipe.
* In together mode, commits displayed data (only for real messages, not streaming placeholders).
*/
export function onMessageSent() {
if (!extensionSettings.enabled) return;
// User sent a new message - NOT a swipe
setLastActionWasSwipe(false);
// console.log('[RPG Companion] 🟢 EVENT: onMessageSent - lastActionWasSwipe =', lastActionWasSwipe);
// Check if this is a streaming placeholder message (content = "...")
// When streaming is on, ST sends a "..." placeholder before generation starts
const context = getContext();
const chat = context.chat;
const lastMessage = chat && chat.length > 0 ? chat[chat.length - 1] : null;
if (lastMessage && lastMessage.mes === '...') {
// console.log('[RPG Companion] 🟢 Ignoring onMessageSent: streaming placeholder message');
return;
}
// console.log('[RPG Companion] 🟢 EVENT: onMessageSent (after placeholder check)');
// console.log('[RPG Companion] 🟢 NOTE: lastActionWasSwipe will be reset in onMessageReceived after generation completes');
// For separate mode with auto-update disabled, commit displayed tracker
if (extensionSettings.generationMode === 'separate' && !extensionSettings.autoUpdate) {
if (lastGeneratedData.userStats || lastGeneratedData.infoBox || lastGeneratedData.characterThoughts) {
committedTrackerData.userStats = lastGeneratedData.userStats;
committedTrackerData.infoBox = lastGeneratedData.infoBox;
committedTrackerData.characterThoughts = lastGeneratedData.characterThoughts;
// console.log('[RPG Companion] 💾 SEPARATE MODE: Committed displayed tracker (auto-update disabled)');
}
}
}
/**
* Event handler for when a message is generated.
*/
export async function onMessageReceived(data) {
// console.log('[RPG Companion] onMessageReceived called, lastActionWasSwipe:', lastActionWasSwipe);
if (!extensionSettings.enabled) {
return;
}
// Reset swipe flag after generation completes
// This ensures next user message (whether from original or swipe) triggers commit
setLastActionWasSwipe(false);
// console.log('[RPG Companion] 🟢 Reset lastActionWasSwipe = false (generation completed)');
if (extensionSettings.generationMode === 'together') {
// In together mode, parse the response to extract RPG data
// The message should be in chat[chat.length - 1]
// Commit happens in onMessageSent (when user sends message, before generation)
const lastMessage = chat[chat.length - 1];
if (lastMessage && !lastMessage.is_user) {
const responseText = lastMessage.mes;
// console.log('[RPG Companion] Parsing together mode response:', responseText);
const parsedData = parseResponse(responseText);
// console.log('[RPG Companion] Parsed data:', parsedData);
// Update stored data
// Note: Don't show parsing error here - this event fires when loading chat history too
// Error notification is handled in apiClient.js for fresh generations only
// Remove locks from parsed data (JSON format only, text format is unaffected)
if (parsedData.userStats) {
parsedData.userStats = removeLocks(parsedData.userStats);
}
if (parsedData.infoBox) {
parsedData.infoBox = removeLocks(parsedData.infoBox);
}
if (parsedData.characterThoughts) {
parsedData.characterThoughts = removeLocks(parsedData.characterThoughts);
}
// Parse and store Spotify URL if feature is enabled
parseAndStoreSpotifyUrl(responseText);
// Update display data with newly parsed response
// console.log('[RPG Companion] 📝 TOGETHER MODE: Updating lastGeneratedData with parsed response');
if (parsedData.userStats) {
lastGeneratedData.userStats = parsedData.userStats;
parseUserStats(parsedData.userStats);
@@ -130,26 +187,25 @@ export async function onMessageReceived(data) {
// console.log('[RPG Companion] Stored RPG data for swipe', currentSwipeId);
// If there's no committed data yet (first time generating), automatically commit
if (!committedTrackerData.userStats && !committedTrackerData.infoBox && !committedTrackerData.characterThoughts) {
committedTrackerData.userStats = parsedData.userStats;
committedTrackerData.infoBox = parsedData.infoBox;
committedTrackerData.characterThoughts = parsedData.characterThoughts;
// console.log('[RPG Companion] 🔆 FIRST TIME: Auto-committed tracker data');
} else {
// console.log('[RPG Companion] Data will be committed when user replies');
}
// Remove the tracker code blocks from the visible message
let cleanedMessage = responseText;
// Remove all code blocks that contain tracker data
cleanedMessage = cleanedMessage.replace(/```[^`]*?Stats\s*\n\s*---[^`]*?```\s*/gi, '');
cleanedMessage = cleanedMessage.replace(/```[^`]*?Info Box\s*\n\s*---[^`]*?```\s*/gi, '');
cleanedMessage = cleanedMessage.replace(/```[^`]*?Present Characters\s*\n\s*---[^`]*?```\s*/gi, '');
// Remove any stray "---" dividers that might appear after the code blocks
cleanedMessage = cleanedMessage.replace(/^\s*---\s*$/gm, '');
// Clean up multiple consecutive newlines
cleanedMessage = cleanedMessage.replace(/\n{3,}/g, '\n\n');
// Only remove trackers if saveTrackerHistory is disabled
// When enabled, trackers are in <trackers> XML tags which SillyTavern auto-hides
if (!extensionSettings.saveTrackerHistory) {
// Note: JSON code blocks are hidden from display by regex script (but preserved in message data)
// Remove old text format code blocks (legacy support)
cleanedMessage = cleanedMessage.replace(/```[^`]*?Stats\s*\n\s*---[^`]*?```\s*/gi, '');
cleanedMessage = cleanedMessage.replace(/```[^`]*?Info Box\s*\n\s*---[^`]*?```\s*/gi, '');
cleanedMessage = cleanedMessage.replace(/```[^`]*?Present Characters\s*\n\s*---[^`]*?```\s*/gi, '');
// Remove any stray "---" dividers that might appear after the code blocks
cleanedMessage = cleanedMessage.replace(/^\s*---\s*$/gm, '');
// Clean up multiple consecutive newlines
cleanedMessage = cleanedMessage.replace(/\n{3,}/g, '\n\n');
}
// Note: <trackers> XML tags are automatically hidden by SillyTavern
// Note: <Song - Artist/> tags are also automatically hidden by SillyTavern
// Update the message in chat history
lastMessage.mes = cleanedMessage.trim();
@@ -165,26 +221,40 @@ export async function onMessageReceived(data) {
renderThoughts();
renderInventory();
renderQuests();
renderMusicPlayer($musicPlayerContainer[0]);
// Then update the DOM to reflect the cleaned message
const lastMessageElement = $('#chat').children('.mes').last();
if (lastMessageElement.length) {
const messageText = lastMessageElement.find('.mes_text');
if (messageText.length) {
messageText.html(substituteParams(cleanedMessage.trim()));
}
}
// Using updateMessageBlock to perform macro substitutions + regex formatting
const messageId = chat.length - 1;
updateMessageBlock(messageId, lastMessage, { rerenderMessage: true });
// console.log('[RPG Companion] Cleaned message, removed tracker code blocks from DOM');
// Save to chat metadata
saveChatData();
}
} else if (extensionSettings.generationMode === 'separate' && extensionSettings.autoUpdate) {
// In separate mode with auto-update, trigger update after message
setTimeout(async () => {
await updateRPGData(renderUserStats, renderInfoBox, renderThoughts, renderInventory);
}, 500);
} else if (extensionSettings.generationMode === 'separate' || extensionSettings.generationMode === 'external') {
// In separate/external mode, also parse Spotify URLs from the main roleplay response
const lastMessage = chat[chat.length - 1];
if (lastMessage && !lastMessage.is_user) {
const responseText = lastMessage.mes;
// Parse and store Spotify URL
const foundSpotifyUrl = parseAndStoreSpotifyUrl(responseText);
// No need to clean message - SillyTavern auto-hides <Song - Artist/> tags
if (foundSpotifyUrl && extensionSettings.enableSpotifyMusic) {
// Just render the music player
renderMusicPlayer($musicPlayerContainer[0]);
}
}
// Trigger auto-update if enabled (for both separate and external modes)
if (extensionSettings.autoUpdate) {
setTimeout(async () => {
await updateRPGData(renderUserStats, renderInfoBox, renderThoughts, renderInventory);
}, 500);
}
}
// Reset the swipe flag after generation completes
@@ -201,6 +271,9 @@ export async function onMessageReceived(data) {
setIsPlotProgression(false);
// console.log('[RPG Companion] Plot progression generation completed');
}
// Re-apply checkpoint in case SillyTavern unhid messages during generation
await restoreCheckpointOnLoad();
}
/**
@@ -228,9 +301,13 @@ export function onCharacterChanged() {
renderThoughts();
renderInventory();
renderQuests();
renderMusicPlayer($musicPlayerContainer[0]);
// Update chat thought overlays
updateChatThoughts();
// Update checkpoint indicators for the loaded chat
updateAllCheckpointIndicators();
}
/**
@@ -242,11 +319,12 @@ export function onMessageSwiped(messageIndex) {
return;
}
// console.log('[RPG Companion] Message swiped at index:', messageIndex);
// console.log('[RPG Companion] 🔵 EVENT: onMessageSwiped at index:', messageIndex);
// Get the message that was swiped
const message = chat[messageIndex];
if (!message || message.is_user) {
// console.log('[RPG Companion] 🔵 Ignoring swipe - message is user or undefined');
return;
}
@@ -255,28 +333,28 @@ export function onMessageSwiped(messageIndex) {
// Only set flag to true if this swipe will trigger a NEW generation
// Check if the swipe already exists (has content in the swipes array)
const isExistingSwipe = message.swipes &&
message.swipes[currentSwipeId] !== undefined &&
message.swipes[currentSwipeId] !== null &&
message.swipes[currentSwipeId].length > 0;
message.swipes[currentSwipeId] !== undefined &&
message.swipes[currentSwipeId] !== null &&
message.swipes[currentSwipeId].length > 0;
if (!isExistingSwipe) {
// This is a NEW swipe that will trigger generation
setLastActionWasSwipe(true);
// console.log('[RPG Companion] 🔵 EVENT: onMessageSwiped (NEW generation) - lastActionWasSwipe =', lastActionWasSwipe);
// console.log('[RPG Companion] 🔵 NEW swipe detected - Set lastActionWasSwipe = true');
} else {
// This is navigating to an EXISTING swipe - don't change the flag
// console.log('[RPG Companion] 🔵 EVENT: onMessageSwiped (existing swipe navigation) - lastActionWasSwipe unchanged =', lastActionWasSwipe);
// console.log('[RPG Companion] 🔵 EXISTING swipe navigation - lastActionWasSwipe unchanged =', lastActionWasSwipe);
}
// console.log('[RPG Companion] Loading data for swipe', currentSwipeId);
// Load RPG data for this swipe into lastGeneratedData (for display only)
// This updates what the user sees, but does NOT commit it
// Committed data will be updated when/if the user replies to this swipe
// Load RPG data for this swipe
// lastGeneratedData is for DISPLAY, committedTrackerData is for GENERATION
// It's safe to load swipe data into lastGeneratedData - it won't be committed due to !lastActionWasSwipe check
if (message.extra && message.extra.rpg_companion_swipes && message.extra.rpg_companion_swipes[currentSwipeId]) {
const swipeData = message.extra.rpg_companion_swipes[currentSwipeId];
// Update display data
// Load swipe data into lastGeneratedData for display (both modes)
lastGeneratedData.userStats = swipeData.userStats || null;
lastGeneratedData.infoBox = swipeData.infoBox || null;
lastGeneratedData.characterThoughts = swipeData.characterThoughts || null;
@@ -286,20 +364,18 @@ export function onMessageSwiped(messageIndex) {
parseUserStats(swipeData.userStats);
}
// console.log('[RPG Companion] Loaded RPG data for swipe', currentSwipeId, '(display only, NOT committed)');
// console.log('[RPG Companion] committedTrackerData unchanged - will be updated if user replies to this swipe');
// console.log('[RPG Companion] 🔄 Loaded swipe data into lastGeneratedData for display:', currentSwipeId);
} else {
// No data for this swipe - keep existing lastGeneratedData (don't clear it)
// This ensures the display remains consistent and data is available for next commit
// console.log('[RPG Companion] No RPG data for swipe', currentSwipeId, '- keeping existing lastGeneratedData');
// console.log('[RPG Companion] ️ No stored data for swipe:', currentSwipeId);
}
// Re-render the panels (display only - committedTrackerData unchanged)
// Re-render the panels
renderUserStats();
renderInfoBox();
renderThoughts();
renderInventory();
renderQuests();
renderMusicPlayer($musicPlayerContainer[0]);
// Update chat thought overlays
updateChatThoughts();
@@ -346,7 +422,24 @@ export function clearExtensionPrompts() {
setExtensionPrompt('rpg-companion-inject', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-example', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-dialogue-coloring', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-spotify', '', extension_prompt_types.IN_CHAT, 0, false);
setExtensionPrompt('rpg-companion-context', '', extension_prompt_types.IN_CHAT, 1, false);
// Note: rpg-companion-plot is not cleared here since it's passed via quiet_prompt option
// console.log('[RPG Companion] Cleared all extension prompts');
}
/**
* Event handler for when generation stops or ends
* Re-applies checkpoint if SillyTavern unhid messages
*/
export async function onGenerationEnded() {
// console.log('[RPG Companion] 🏁 onGenerationEnded called');
// Note: isGenerating flag is cleared in onMessageReceived after parsing (together mode)
// or in apiClient.js after separate generation completes (separate mode)
// SillyTavern may auto-unhide messages when generation stops
// Re-apply checkpoint if one exists
await restoreCheckpointOnLoad();
}
+46 -5
View File
@@ -39,15 +39,56 @@ let openForms = {
/**
* Updates lastGeneratedData.userStats AND committedTrackerData.userStats to include
* current inventory in text format.
* current inventory.
* Maintains JSON format if current data is JSON, otherwise uses text format.
* This ensures manual edits are immediately visible to AI in next generation.
*/
function updateLastGeneratedDataInventory() {
// Rebuild the userStats text format using custom stat names
const statsText = buildUserStatsText();
// Check if current data is in JSON format
const currentData = lastGeneratedData.userStats || committedTrackerData.userStats;
if (currentData) {
const trimmed = currentData.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
// Maintain JSON format
try {
const jsonData = JSON.parse(currentData);
if (jsonData && typeof jsonData === 'object') {
// Update inventory in JSON
const stats = extensionSettings.userStats;
// Update BOTH lastGeneratedData AND committedTrackerData
// This makes manual edits immediately visible to AI
// Convert inventory back to v3 format (arrays of {name, quantity})
const convertToV3Items = (itemString) => {
if (!itemString) return [];
const items = itemString.split(',').map(s => s.trim()).filter(s => s);
return items.map(item => {
const qtyMatch = item.match(/^(\d+)x\s+(.+)$/);
if (qtyMatch) {
return { name: qtyMatch[2].trim(), quantity: parseInt(qtyMatch[1]) };
}
return { name: item, quantity: 1 };
});
};
jsonData.inventory = {
onPerson: convertToV3Items(stats.inventory.onPerson),
clothing: convertToV3Items(stats.inventory.clothing),
stored: stats.inventory.stored || {},
assets: convertToV3Items(stats.inventory.assets)
};
const updatedJSON = JSON.stringify(jsonData, null, 2);
lastGeneratedData.userStats = updatedJSON;
committedTrackerData.userStats = updatedJSON;
return;
}
} catch (e) {
console.warn('[RPG Companion] Failed to parse JSON, falling back to text format:', e);
}
}
}
// Fall back to text format
const statsText = buildUserStatsText();
lastGeneratedData.userStats = statsText;
committedTrackerData.userStats = statsText;
}
+46 -6
View File
@@ -79,15 +79,58 @@ export function updateInventoryItem(field, index, newName, location) {
/**
* Updates lastGeneratedData.userStats AND committedTrackerData.userStats to include
* current inventory in text format.
* current inventory.
* Maintains JSON format if current data is JSON, otherwise uses text format.
* This ensures manual edits are immediately visible to AI in next generation.
* @private
*/
function updateLastGeneratedDataInventory() {
// Check if current data is in JSON format
const currentData = lastGeneratedData.userStats || committedTrackerData.userStats;
if (currentData) {
const trimmed = currentData.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
// Maintain JSON format
try {
const jsonData = JSON.parse(currentData);
if (jsonData && typeof jsonData === 'object') {
// Update inventory in JSON
const stats = extensionSettings.userStats;
// Convert inventory back to v3 format (arrays of {name, quantity})
const convertToV3Items = (itemString) => {
if (!itemString) return [];
const items = itemString.split(',').map(s => s.trim()).filter(s => s);
return items.map(item => {
const qtyMatch = item.match(/^(\d+)x\s+(.+)$/);
if (qtyMatch) {
return { name: qtyMatch[2].trim(), quantity: parseInt(qtyMatch[1]) };
}
return { name: item, quantity: 1 };
});
};
jsonData.inventory = {
onPerson: convertToV3Items(stats.inventory.onPerson),
clothing: convertToV3Items(stats.inventory.clothing),
stored: stats.inventory.stored || {},
assets: convertToV3Items(stats.inventory.assets)
};
const updatedJSON = JSON.stringify(jsonData, null, 2);
lastGeneratedData.userStats = updatedJSON;
committedTrackerData.userStats = updatedJSON;
return;
}
} catch (e) {
console.warn('[RPG Companion] Failed to parse JSON, falling back to text format:', e);
}
}
}
// Fall back to text format
const stats = extensionSettings.userStats;
const inventorySummary = buildInventorySummary(stats.inventory);
// Rebuild the userStats text format
const statsText =
`Health: ${stats.health}%\n` +
`Satiety: ${stats.satiety}%\n` +
@@ -96,9 +139,6 @@ function updateLastGeneratedDataInventory() {
`Arousal: ${stats.arousal}%\n` +
`${stats.mood}: ${stats.conditions}\n` +
`${inventorySummary}`;
// Update BOTH lastGeneratedData AND committedTrackerData
// This makes manual edits immediately visible to AI
lastGeneratedData.userStats = statsText;
committedTrackerData.userStats = statsText;
}
+259 -48
View File
@@ -11,6 +11,26 @@ import {
$infoBoxContainer
} from '../../core/state.js';
import { saveChatData } from '../../core/persistence.js';
import { i18n } from '../../core/i18n.js';
import { isItemLocked } from '../generation/lockManager.js';
import { repairJSON } from '../../utils/jsonRepair.js';
/**
* Helper to generate lock icon HTML if setting is enabled
* @param {string} tracker - Tracker name
* @param {string} path - Item path
* @returns {string} Lock icon HTML or empty string
*/
function getLockIconHtml(tracker, path) {
const showLockIcons = extensionSettings.showLockIcons ?? true;
if (!showLockIcons) return '';
const isLocked = isItemLocked(tracker, path);
const lockIcon = isLocked ? '🔒' : '🔓';
const lockTitle = isLocked ? 'Locked' : 'Unlocked';
const lockedClass = isLocked ? ' locked' : '';
return `<span class="rpg-section-lock-icon${lockedClass}" data-tracker="${tracker}" data-path="${path}" title="${lockTitle}">${lockIcon}</span>`;
}
/**
* Helper to separate emoji from text in a string
@@ -55,41 +75,36 @@ function separateEmojiFromText(str) {
* Includes event listeners for editable fields.
*/
export function renderInfoBox() {
if (!extensionSettings.showInfoBox || !$infoBoxContainer) {
return;
}
// console.log('[RPG InfoBox Render] ==================== RENDERING INFO BOX ====================');
// console.log('[RPG InfoBox Render] showInfoBox setting:', extensionSettings.showInfoBox);
// console.log('[RPG InfoBox Render] Container exists:', !!$infoBoxContainer);
// Add updating class for animation
if (extensionSettings.enableAnimations) {
$infoBoxContainer.addClass('rpg-content-updating');
if (!extensionSettings.showInfoBox || !$infoBoxContainer) {
// console.log('[RPG InfoBox Render] Exiting: showInfoBox or container is false');
return;
}
// Use committedTrackerData as fallback if lastGeneratedData is empty (e.g., after page refresh)
const infoBoxData = lastGeneratedData.infoBox || committedTrackerData.infoBox;
// console.log('[RPG InfoBox Render] infoBoxData length:', infoBoxData ? infoBoxData.length : 'null');
// console.log('[RPG InfoBox Render] infoBoxData preview:', infoBoxData ? infoBoxData.substring(0, 200) : 'null');
// If no data yet, show placeholder
// If no data yet, hide the container (e.g., after cache clear)
if (!infoBoxData) {
const placeholderHtml = `
<div class="rpg-dashboard rpg-dashboard-row-1">
<div class="rpg-dashboard-widget rpg-placeholder-widget">
<div class="rpg-placeholder-text">No data yet</div>
<div class="rpg-placeholder-hint">Generate a new response in the roleplay or switch to "Separate Generation" in Settings to access and click the "Refresh RPG Info" button</div>
</div>
</div>
`;
$infoBoxContainer.html(placeholderHtml);
if (extensionSettings.enableAnimations) {
setTimeout(() => $infoBoxContainer.removeClass('rpg-content-updating'), 500);
}
// console.log('[RPG InfoBox Render] No data, hiding container');
$infoBoxContainer.empty().hide();
return;
}
// Show container and add updating class for animation
$infoBoxContainer.show();
if (extensionSettings.enableAnimations) {
$infoBoxContainer.addClass('rpg-content-updating');
}
// console.log('[RPG Companion] renderInfoBox called with data:', infoBoxData);
// Parse the info box data
const lines = infoBoxData.split('\n');
// console.log('[RPG Companion] Info Box split into lines:', lines);
const data = {
let data = {
date: '',
weekday: '',
month: '',
@@ -104,6 +119,45 @@ export function renderInfoBox() {
characters: []
};
// Check if data is v3 JSON format
const trimmed = infoBoxData.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
const jsonData = repairJSON(infoBoxData);
if (jsonData) {
// Extract from v3 JSON structure
data.weatherEmoji = jsonData.weather?.emoji || '';
data.weatherForecast = jsonData.weather?.forecast || '';
data.temperature = jsonData.temperature ? `${jsonData.temperature.value}°${jsonData.temperature.unit}` : '';
data.tempValue = jsonData.temperature?.value || 0;
data.timeStart = jsonData.time?.start || '';
data.timeEnd = jsonData.time?.end || '';
data.location = jsonData.location?.value || '';
// Parse date string to extract weekday, month, year
if (jsonData.date?.value) {
data.date = jsonData.date.value;
// Expected format: "Tuesday, October 17th, 2023"
const dateParts = data.date.split(',').map(p => p.trim());
data.weekday = dateParts[0] || '';
data.month = dateParts[1] || '';
data.year = dateParts[2] || '';
}
// Skip to rendering
} else {
// JSON parsing failed, fall back to text parsing
parseTextFormat();
}
} else {
// Text format
parseTextFormat();
}
function parseTextFormat() {
// Parse the info box data
const lines = infoBoxData.split('\n');
// console.log('[RPG Companion] Info Box split into lines:', lines);
// Track which fields we've already parsed to avoid duplicates from mixed formats
const parsedFields = {
date: false,
@@ -204,10 +258,10 @@ export function renderInfoBox() {
data.weatherEmoji = emoji;
data.weatherForecast = text;
} else if (weatherStr.includes(',')) {
// Fallback to comma split if emoji detection failed
const weatherParts = weatherStr.split(',').map(p => p.trim());
data.weatherEmoji = weatherParts[0] || '';
data.weatherForecast = weatherParts[1] || '';
// Fallback to comma split if emoji detection failed - split only on FIRST comma
const firstCommaIndex = weatherStr.indexOf(',');
data.weatherEmoji = weatherStr.substring(0, firstCommaIndex).trim();
data.weatherForecast = weatherStr.substring(firstCommaIndex + 1).trim();
} else {
// No clear separation - assume it's all forecast text
data.weatherEmoji = '🌤️'; // Default emoji
@@ -269,6 +323,7 @@ export function renderInfoBox() {
// timeStart: data.timeStart,
// location: data.location
// });
}
// Get tracker configuration
const config = extensionSettings.trackerConfig?.infoBox;
@@ -302,10 +357,13 @@ export function renderInfoBox() {
weekdayDisplay = weekdayDisplay;
}
const dateLockIconHtml = getLockIconHtml('infoBox', 'date');
row1Widgets.push(`
<div class="rpg-dashboard-widget rpg-calendar-widget">
${dateLockIconHtml}
<div class="rpg-calendar-top rpg-editable" contenteditable="true" data-field="month" data-full-value="${data.month || ''}" title="Click to edit">${monthDisplay}</div>
<div class="rpg-calendar-day rpg-editable" contenteditable="true" data-field="weekday" data-full-value="${data.weekday || ''}" title="Click to edit">${weekdayDisplay}</div>
<div class="rpg-calendar-day" title="Click to edit"><span class="rpg-calendar-day-text rpg-editable" contenteditable="true" data-field="weekday" data-full-value="${data.weekday || ''}">${weekdayDisplay}</span></div>
<div class="rpg-calendar-year rpg-editable" contenteditable="true" data-field="year" data-full-value="${data.year || ''}" title="Click to edit">${yearDisplay}</div>
</div>
`);
@@ -315,8 +373,11 @@ export function renderInfoBox() {
if (config?.widgets?.weather?.enabled) {
const weatherEmoji = data.weatherEmoji || '🌤️';
const weatherForecast = data.weatherForecast || 'Weather';
const weatherLockIconHtml = getLockIconHtml('infoBox', 'weather');
row1Widgets.push(`
<div class="rpg-dashboard-widget rpg-weather-widget">
${weatherLockIconHtml}
<div class="rpg-weather-icon rpg-editable" contenteditable="true" data-field="weatherEmoji" title="Click to edit emoji">${weatherEmoji}</div>
<div class="rpg-weather-forecast rpg-editable" contenteditable="true" data-field="weatherForecast" title="Click to edit">${weatherForecast}</div>
</div>
@@ -356,8 +417,11 @@ export function renderInfoBox() {
const tempInCelsius = preferredUnit === 'F' ? Math.round((tempValue - 32) * 5/9) : tempValue;
const tempPercent = Math.min(100, Math.max(0, ((tempInCelsius + 20) / 60) * 100));
const tempColor = tempInCelsius < 10 ? '#4a90e2' : tempInCelsius < 25 ? '#67c23a' : '#e94560';
const tempLockIconHtml = getLockIconHtml('infoBox', 'temperature');
row1Widgets.push(`
<div class="rpg-dashboard-widget rpg-temp-widget">
${tempLockIconHtml}
<div class="rpg-thermometer">
<div class="rpg-thermometer-bulb"></div>
<div class="rpg-thermometer-tube">
@@ -371,7 +435,12 @@ export function renderInfoBox() {
// Time widget - show if enabled
if (config?.widgets?.time?.enabled) {
// Determine which time value to display and edit
const hasTimeEnd = Boolean(data.timeEnd);
const hasTimeStart = Boolean(data.timeStart);
const timeDisplay = data.timeEnd || data.timeStart || '12:00';
const timeField = hasTimeEnd ? 'timeEnd' : 'timeStart';
// Parse time for clock hands
const timeMatch = timeDisplay.match(/(\d+):(\d+)/);
let hourAngle = 0;
@@ -382,8 +451,12 @@ export function renderInfoBox() {
hourAngle = (hours % 12) * 30 + minutes * 0.5; // 30° per hour + 0.5° per minute
minuteAngle = minutes * 6; // 6° per minute
}
const timeLockIconHtml = getLockIconHtml('infoBox', 'time');
row1Widgets.push(`
<div class="rpg-dashboard-widget rpg-clock-widget">
${timeLockIconHtml}
<div class="rpg-clock">
<div class="rpg-clock-face">
<div class="rpg-clock-hour" style="transform: rotate(${hourAngle}deg)"></div>
@@ -391,7 +464,7 @@ export function renderInfoBox() {
<div class="rpg-clock-center"></div>
</div>
</div>
<div class="rpg-time-value rpg-editable" contenteditable="true" data-field="timeStart" title="Click to edit">${timeDisplay}</div>
<div class="rpg-time-value rpg-editable" contenteditable="true" data-field="${timeField}" title="Click to edit">${timeDisplay}</div>
</div>
`);
}
@@ -406,9 +479,12 @@ export function renderInfoBox() {
// Row 2: Location widget (full width) - show if enabled
if (config?.widgets?.location?.enabled) {
const locationDisplay = data.location || 'Location';
const locationLockIconHtml = getLockIconHtml('infoBox', 'location');
html += `
<div class="rpg-dashboard rpg-dashboard-row-2">
<div class="rpg-dashboard-widget rpg-location-widget">
${locationLockIconHtml}
<div class="rpg-map-bg">
<div class="rpg-map-marker">📍</div>
</div>
@@ -420,14 +496,26 @@ export function renderInfoBox() {
// Row 3: Recent Events widget (notebook style) - show if enabled
if (config?.widgets?.recentEvents?.enabled) {
// Parse Recent Events from infoBox string
// Parse Recent Events from infoBox (supports both JSON and text formats)
let recentEvents = [];
if (committedTrackerData.infoBox) {
const recentEventsLine = committedTrackerData.infoBox.split('\n').find(line => line.startsWith('Recent Events:'));
if (recentEventsLine) {
const eventsString = recentEventsLine.replace('Recent Events:', '').trim();
if (eventsString) {
recentEvents = eventsString.split(',').map(e => e.trim()).filter(e => e);
// Try JSON format first
try {
const parsed = typeof committedTrackerData.infoBox === 'string'
? JSON.parse(committedTrackerData.infoBox)
: committedTrackerData.infoBox;
if (parsed && Array.isArray(parsed.recentEvents)) {
recentEvents = parsed.recentEvents;
}
} catch (e) {
// Fall back to old text format
const recentEventsLine = committedTrackerData.infoBox.split('\n').find(line => line.startsWith('Recent Events:'));
if (recentEventsLine) {
const eventsString = recentEventsLine.replace('Recent Events:', '').trim();
if (eventsString) {
recentEvents = eventsString.split(',').map(e => e.trim()).filter(e => e);
}
}
}
}
@@ -439,15 +527,18 @@ export function renderInfoBox() {
validEvents.push('Click to add event');
}
const eventsLockIconHtml = getLockIconHtml('infoBox', 'recentEvents');
html += `
<div class="rpg-dashboard rpg-dashboard-row-3">
<div class="rpg-dashboard-widget rpg-events-widget">
${eventsLockIconHtml}
<div class="rpg-notebook-header">
<div class="rpg-notebook-ring"></div>
<div class="rpg-notebook-ring"></div>
<div class="rpg-notebook-ring"></div>
</div>
<div class="rpg-notebook-title">Recent Events</div>
<div class="rpg-notebook-title" data-i18n-key="infobox.recentEvents.title">${i18n.getTranslation('infobox.recentEvents.title')}</div>
<div class="rpg-notebook-lines">
`;
@@ -466,7 +557,7 @@ export function renderInfoBox() {
html += `
<div class="rpg-notebook-line rpg-event-add">
<span class="rpg-bullet">+</span>
<span class="rpg-event-text rpg-editable rpg-event-placeholder" contenteditable="true" data-field="event${i + 1}" title="Click to add event">Add event...</span>
<span class="rpg-event-text rpg-editable rpg-event-placeholder" contenteditable="true" data-field="event${i + 1}" title="Click to add event" data-i18n-key="infobox.recentEvents.addEventPlaceholder">${i18n.getTranslation('infobox.recentEvents.addEventPlaceholder')}</span>
</div>
`;
}
@@ -483,6 +574,19 @@ export function renderInfoBox() {
$infoBoxContainer.html(html);
// Add dynamic text scaling for location field
const updateLocationTextSize = ($element) => {
const text = $element.text();
const charCount = text.length;
$element.css('--char-count', Math.min(charCount, 100));
};
// Initial size update for location
const $locationText = $infoBoxContainer.find('[data-field="location"]');
if ($locationText.length) {
updateLocationTextSize($locationText);
}
// Add event handlers for editable Info Box fields
$infoBoxContainer.find('.rpg-editable').on('blur', function() {
const $this = $(this);
@@ -500,6 +604,11 @@ export function renderInfoBox() {
}
}
// Update location text size dynamically
if (field === 'location') {
updateLocationTextSize($this);
}
// Handle recent events separately
if (field === 'event1' || field === 'event2' || field === 'event3') {
updateRecentEvent(field, value);
@@ -508,6 +617,11 @@ export function renderInfoBox() {
}
});
// Update location size on input as well (real-time)
$infoBoxContainer.find('[data-field="location"]').on('input', function() {
updateLocationTextSize($(this));
});
// For date fields, show full value on focus
$infoBoxContainer.find('[data-field="month"], [data-field="weekday"], [data-field="year"]').on('focus', function() {
const fullValue = $(this).data('full-value');
@@ -516,10 +630,39 @@ export function renderInfoBox() {
}
});
// Add event handler for lock icons (support both click and touch)
$infoBoxContainer.find('.rpg-section-lock-icon').on('click touchend', function(e) {
e.preventDefault();
e.stopPropagation();
const $lockIcon = $(this);
const tracker = $lockIcon.data('tracker');
const path = $lockIcon.data('path');
// Import lockManager dynamically to avoid circular dependencies
import('../generation/lockManager.js').then(({ setItemLock, isItemLocked }) => {
const isLocked = isItemLocked(tracker, path);
const newLockState = !isLocked;
setItemLock(tracker, path, newLockState);
// Update icon
$lockIcon.text(newLockState ? '🔒' : '🔓');
$lockIcon.attr('title', newLockState ? 'Locked - AI cannot change this' : 'Unlocked - AI can change this');
$lockIcon.toggleClass('locked', newLockState);
// Save settings to persist lock state
saveSettings();
});
});
// Remove updating class after animation
if (extensionSettings.enableAnimations) {
setTimeout(() => $infoBoxContainer.removeClass('rpg-content-updating'), 500);
}
// Update weather effect after rendering
if (window.RPGCompanion?.updateWeatherEffect) {
window.RPGCompanion.updateWeatherEffect();
}
}
/**
@@ -535,6 +678,64 @@ export function updateInfoBoxField(field, value) {
lastGeneratedData.infoBox = 'Info Box\n---\n';
}
// Check if data is in v3 JSON format
const trimmed = lastGeneratedData.infoBox.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
// Handle v3 JSON format
const jsonData = repairJSON(lastGeneratedData.infoBox);
if (jsonData) {
// Update the appropriate field based on v3 structure
if (field === 'weatherEmoji') {
if (!jsonData.weather) jsonData.weather = {};
jsonData.weather.emoji = value;
} else if (field === 'weatherForecast') {
if (!jsonData.weather) jsonData.weather = {};
jsonData.weather.forecast = value;
} else if (field === 'temperature') {
// Parse temperature value and unit
const tempMatch = value.match(/(-?\d+)\s*°?\s*([CF]?)/i);
if (tempMatch) {
if (!jsonData.temperature) jsonData.temperature = {};
jsonData.temperature.value = parseInt(tempMatch[1]);
jsonData.temperature.unit = (tempMatch[2] || 'C').toUpperCase();
}
} else if (field === 'timeStart') {
if (!jsonData.time) jsonData.time = {};
jsonData.time.start = value;
} else if (field === 'timeEnd') {
if (!jsonData.time) jsonData.time = {};
jsonData.time.end = value;
} else if (field === 'location') {
if (!jsonData.location) jsonData.location = {};
jsonData.location.value = value;
} else if (field === 'weekday' || field === 'month' || field === 'year') {
// Update date components
if (!jsonData.date) jsonData.date = {};
let currentDate = jsonData.date.value || '';
const dateParts = currentDate.split(',').map(p => p.trim());
if (field === 'weekday') {
dateParts[0] = value;
} else if (field === 'month') {
dateParts[1] = value;
} else if (field === 'year') {
dateParts[2] = value;
}
jsonData.date.value = dateParts.filter(p => p).join(', ');
}
// Save back as JSON
lastGeneratedData.infoBox = JSON.stringify(jsonData, null, 2);
committedTrackerData.infoBox = lastGeneratedData.infoBox;
saveChatData();
renderInfoBox();
// console.log('[RPG Companion] Updated info box field (v3 JSON):', { field, value });
return;
}
}
// Fall back to text format handling
// Reconstruct the Info Box text with updated field
const lines = lastGeneratedData.infoBox.split('\n');
let dateLineFound = false;
@@ -607,14 +808,16 @@ export function updateInfoBoxField(field, value) {
if (line.startsWith('Weather:')) {
// New format: Weather: emoji, forecast
const weatherContent = line.replace('Weather:', '').trim();
const parts = weatherContent.split(',').map(p => p.trim());
const forecast = parts[1] || 'Weather';
// Split only on first comma to get emoji and rest
const firstCommaIndex = weatherContent.indexOf(',');
const forecast = firstCommaIndex > 0 ? weatherContent.substring(firstCommaIndex + 1).trim() : 'Weather';
return `Weather: ${value}, ${forecast}`;
} else {
// Legacy format: emoji: forecast
const parts = line.split(':');
if (parts.length >= 2) {
return `${value}: ${parts.slice(1).join(':').trim()}`;
const firstColonIndex = line.indexOf(':');
if (firstColonIndex >= 0) {
const forecast = line.substring(firstColonIndex + 1).trim();
return `${value}: ${forecast}`;
}
}
} else if (field === 'weatherForecast' && index === weatherLineIndex) {
@@ -622,14 +825,16 @@ export function updateInfoBoxField(field, value) {
if (line.startsWith('Weather:')) {
// New format: Weather: emoji, forecast
const weatherContent = line.replace('Weather:', '').trim();
const parts = weatherContent.split(',').map(p => p.trim());
const emoji = parts[0] || '🌤️';
// Split only on first comma to get emoji and rest
const firstCommaIndex = weatherContent.indexOf(',');
const emoji = firstCommaIndex > 0 ? weatherContent.substring(0, firstCommaIndex).trim() : '🌤️';
return `Weather: ${emoji}, ${value}`;
} else {
// Legacy format: emoji: forecast
const parts = line.split(':');
if (parts.length >= 2) {
return `${parts[0].trim()}: ${value}`;
const firstColonIndex = line.indexOf(':');
if (firstColonIndex >= 0) {
const emoji = line.substring(0, firstColonIndex).trim();
return `${emoji}: ${value}`;
}
}
} else if (field === 'temperature' && (line.includes('🌡️:') || line.startsWith('Temperature:'))) {
@@ -873,6 +1078,12 @@ function updateRecentEvent(field, value) {
saveChatData();
renderInfoBox();
console.log(`[RPG Companion] Updated recent event ${field}:`, value);
// Update weather effect after rendering
if (window.RPGCompanion?.updateWeatherEffect) {
window.RPGCompanion.updateWeatherEffect();
}
// console.log(`[RPG Companion] Updated recent event ${field}:`, value);
}
}
+165 -14
View File
@@ -4,13 +4,32 @@
*/
import { extensionSettings, $inventoryContainer } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { getInventoryRenderOptions, restoreFormStates } from '../interaction/inventoryActions.js';
import { updateInventoryItem } from '../interaction/inventoryEdit.js';
import { parseItems } from '../../utils/itemParser.js';
import { isItemLocked, setItemLock } from '../generation/lockManager.js';
// Type imports
/** @typedef {import('../../types/inventory.js').InventoryV2} InventoryV2 */
/**
* Helper to generate lock icon HTML if setting is enabled
* @param {string} tracker - Tracker name
* @param {string} path - Item path
* @returns {string} Lock icon HTML or empty string
*/
function getLockIconHtml(tracker, path) {
const showLockIcons = extensionSettings.showLockIcons ?? true;
if (!showLockIcons) return '';
const isLocked = isItemLocked(tracker, path);
const lockIcon = isLocked ? '🔒' : '🔓';
const lockTitle = isLocked ? 'Locked' : 'Unlocked';
const lockedClass = isLocked ? ' locked' : '';
return `<span class="rpg-section-lock-icon${lockedClass}" data-tracker="${tracker}" data-path="${path}" title="${lockTitle}">${lockIcon}</span>`;
}
/**
* Converts a location name to a safe ID for use in HTML element IDs.
* Must match the logic used in inventoryActions.js.
@@ -23,8 +42,8 @@ export function getLocationId(locationName) {
}
/**
* Renders the inventory sub-tab navigation (On Person, Stored, Assets)
* @param {string} activeTab - Currently active sub-tab ('onPerson', 'stored', 'assets')
* Renders the inventory sub-tab navigation (On Person, Clothing, Stored, Assets)
* @param {string} activeTab - Currently active sub-tab ('onPerson', 'clothing', 'stored', 'assets')
* @returns {string} HTML for sub-tab navigation
*/
export function renderInventorySubTabs(activeTab = 'onPerson') {
@@ -33,6 +52,9 @@ export function renderInventorySubTabs(activeTab = 'onPerson') {
<button class="rpg-inventory-subtab ${activeTab === 'onPerson' ? 'active' : ''}" data-tab="onPerson">
On Person
</button>
<button class="rpg-inventory-subtab ${activeTab === 'clothing' ? 'active' : ''}" data-tab="clothing">
Clothing
</button>
<button class="rpg-inventory-subtab ${activeTab === 'stored' ? 'active' : ''}" data-tab="stored">
Stored
</button>
@@ -58,24 +80,30 @@ export function renderOnPersonView(onPersonItems, viewMode = 'list') {
} else {
if (viewMode === 'grid') {
// Grid view: card-style items
itemsHtml = items.map((item, index) => `
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.onPerson[${index}]`);
return `
<div class="rpg-item-card" data-field="onPerson" data-index="${index}">
${lockIconHtml}
<button class="rpg-item-remove" data-action="remove-item" data-field="onPerson" data-index="${index}" title="Remove item">
<i class="fa-solid fa-times"></i>
</button>
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="onPerson" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
</div>
`).join('');
`}).join('');
} else {
// List view: full-width rows
itemsHtml = items.map((item, index) => `
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.onPerson[${index}]`);
return `
<div class="rpg-item-row" data-field="onPerson" data-index="${index}">
${lockIconHtml}
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="onPerson" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
<button class="rpg-item-remove" data-action="remove-item" data-field="onPerson" data-index="${index}" title="Remove item">
<i class="fa-solid fa-times"></i>
</button>
</div>
`).join('');
`}).join('');
}
}
@@ -119,6 +147,88 @@ export function renderOnPersonView(onPersonItems, viewMode = 'list') {
`;
}
/**
* Renders the "Clothing" inventory view with list or grid display
* @param {string} clothingItems - Current clothing items (comma-separated string)
* @param {string} viewMode - View mode ('list' or 'grid')
* @returns {string} HTML for clothing view with items and add button
*/
export function renderClothingView(clothingItems, viewMode = 'list') {
const items = parseItems(clothingItems);
let itemsHtml = '';
if (items.length === 0) {
itemsHtml = '<div class="rpg-inventory-empty">No clothing worn</div>';
} else {
if (viewMode === 'grid') {
// Grid view: card-style items
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.clothing[${index}]`);
return `
<div class="rpg-item-card" data-field="clothing" data-index="${index}">
${lockIconHtml}
<button class="rpg-item-remove" data-action="remove-item" data-field="clothing" data-index="${index}" title="Remove item">
<i class="fa-solid fa-times"></i>
</button>
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="clothing" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
</div>
`}).join('');
} else {
// List view: full-width rows
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.clothing[${index}]`);
return `
<div class="rpg-item-row" data-field="clothing" data-index="${index}">
${lockIconHtml}
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="clothing" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
<button class="rpg-item-remove" data-action="remove-item" data-field="clothing" data-index="${index}" title="Remove item">
<i class="fa-solid fa-times"></i>
</button>
</div>
`}).join('');
}
}
const listViewClass = viewMode === 'list' ? 'rpg-item-list-view' : 'rpg-item-grid-view';
return `
<div class="rpg-inventory-section" data-section="clothing">
<div class="rpg-inventory-header">
<h4>Clothing Worn</h4>
<div class="rpg-inventory-header-actions">
<div class="rpg-view-toggle">
<button class="rpg-view-btn ${viewMode === 'list' ? 'active' : ''}" data-action="switch-view" data-field="clothing" data-view="list" title="List view">
<i class="fa-solid fa-list"></i>
</button>
<button class="rpg-view-btn ${viewMode === 'grid' ? 'active' : ''}" data-action="switch-view" data-field="clothing" data-view="grid" title="Grid view">
<i class="fa-solid fa-th"></i>
</button>
</div>
<button class="rpg-inventory-add-btn" data-action="add-item" data-field="clothing" title="Add new clothing item">
<i class="fa-solid fa-plus"></i> Add Clothing
</button>
</div>
</div>
<div class="rpg-inventory-content">
<div class="rpg-inline-form" id="rpg-add-item-form-clothing" style="display: none;">
<input type="text" class="rpg-inline-input" id="rpg-new-item-clothing" placeholder="Enter clothing item..." />
<div class="rpg-inline-buttons">
<button class="rpg-inline-btn rpg-inline-cancel" data-action="cancel-add-item" data-field="clothing">
<i class="fa-solid fa-times"></i> Cancel
</button>
<button class="rpg-inline-btn rpg-inline-save" data-action="save-add-item" data-field="clothing">
<i class="fa-solid fa-check"></i> Add
</button>
</div>
</div>
<div class="rpg-item-list ${listViewClass}">
${itemsHtml}
</div>
</div>
</div>
`;
}
/**
* Renders the "Stored" inventory view with collapsible locations and list/grid views
* @param {Object.<string, string>} stored - Stored items by location
@@ -180,24 +290,30 @@ export function renderStoredView(stored, collapsedLocations = [], viewMode = 'li
} else {
if (viewMode === 'grid') {
// Grid view: card-style items
itemsHtml = items.map((item, index) => `
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.stored.${location}[${index}]`);
return `
<div class="rpg-item-card" data-field="stored" data-location="${escapeHtml(location)}" data-index="${index}">
${lockIconHtml}
<button class="rpg-item-remove" data-action="remove-item" data-field="stored" data-location="${escapeHtml(location)}" data-index="${index}" title="Remove item">
<i class="fa-solid fa-times"></i>
</button>
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="stored" data-location="${escapeHtml(location)}" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
</div>
`).join('');
`}).join('');
} else {
// List view: full-width rows
itemsHtml = items.map((item, index) => `
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.stored.${location}[${index}]`);
return `
<div class="rpg-item-row" data-field="stored" data-location="${escapeHtml(location)}" data-index="${index}">
${lockIconHtml}
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="stored" data-location="${escapeHtml(location)}" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
<button class="rpg-item-remove" data-action="remove-item" data-field="stored" data-location="${escapeHtml(location)}" data-index="${index}" title="Remove item">
<i class="fa-solid fa-times"></i>
</button>
</div>
`).join('');
`}).join('');
}
}
@@ -276,24 +392,30 @@ export function renderAssetsView(assets, viewMode = 'list') {
} else {
if (viewMode === 'grid') {
// Grid view: card-style items
itemsHtml = items.map((item, index) => `
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.assets[${index}]`);
return `
<div class="rpg-item-card" data-field="assets" data-index="${index}">
${lockIconHtml}
<button class="rpg-item-remove" data-action="remove-item" data-field="assets" data-index="${index}" title="Remove asset">
<i class="fa-solid fa-times"></i>
</button>
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="assets" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
</div>
`).join('');
`}).join('');
} else {
// List view: full-width rows
itemsHtml = items.map((item, index) => `
itemsHtml = items.map((item, index) => {
const lockIconHtml = getLockIconHtml('userStats', `inventory.assets[${index}]`);
return `
<div class="rpg-item-row" data-field="assets" data-index="${index}">
${lockIconHtml}
<span class="rpg-item-name rpg-editable" contenteditable="true" data-field="assets" data-index="${index}" title="Click to edit">${escapeHtml(item)}</span>
<button class="rpg-item-remove" data-action="remove-item" data-field="assets" data-index="${index}" title="Remove asset">
<i class="fa-solid fa-times"></i>
</button>
</div>
`).join('');
`}).join('');
}
}
@@ -397,6 +519,7 @@ function generateInventoryHTML(inventory, options = {}) {
// Get view modes from settings (default to 'list')
const viewModes = extensionSettings.inventoryViewModes || {
onPerson: 'list',
clothing: 'list',
stored: 'list',
assets: 'list'
};
@@ -406,6 +529,9 @@ function generateInventoryHTML(inventory, options = {}) {
case 'onPerson':
html += renderOnPersonView(v2Inventory.onPerson, viewModes.onPerson);
break;
case 'clothing':
html += renderClothingView(v2Inventory.clothing, viewModes.clothing);
break;
case 'stored':
html += renderStoredView(v2Inventory.stored, collapsedLocations, viewModes.stored);
break;
@@ -476,6 +602,31 @@ export function renderInventory() {
const newName = $(this).text().trim();
updateInventoryItem(field, index, newName, location);
});
// Add event listener for section lock icon clicks (support both click and touch)
$inventoryContainer.find('.rpg-section-lock-icon').on('click touchend', function(e) {
e.preventDefault();
e.stopPropagation();
const $icon = $(this);
const trackerType = $icon.data('tracker');
const itemPath = $icon.data('path');
const currentlyLocked = isItemLocked(trackerType, itemPath);
// Toggle lock state
setItemLock(trackerType, itemPath, !currentlyLocked);
// Update icon
const newIcon = !currentlyLocked ? '🔒' : '🔓';
const newTitle = !currentlyLocked ? 'Locked' : 'Unlocked';
$icon.text(newIcon);
$icon.attr('title', newTitle);
// Toggle 'locked' class for persistent visibility
$icon.toggleClass('locked', !currentlyLocked);
// Save settings
saveSettings();
});
}
/**
+150
View File
@@ -0,0 +1,150 @@
/**
* Music Player Rendering Module
* Handles UI rendering for Spotify music player widget
*/
import { extensionSettings, committedTrackerData } from '../../core/state.js';
import { i18n } from '../../core/i18n.js';
/**
* Creates a Spotify deep link URL that opens the Spotify app
* Uses spotify:search: protocol for app, falls back to web URL
* @param {Object} songData - Object with {song, artist, searchQuery}
* @returns {Object} Object with appUrl and webUrl
*/
function createSpotifyUrls(songData) {
if (!songData || !songData.searchQuery) {
return { appUrl: '', webUrl: '' };
}
const encodedQuery = encodeURIComponent(songData.searchQuery);
return {
// Spotify app protocol - opens directly in Spotify app on desktop/mobile
appUrl: `spotify:search:${encodedQuery}`,
// Web fallback - opens Spotify web player search
webUrl: `https://open.spotify.com/search/${encodedQuery}`
};
}
/**
* Opens Spotify with the given song
* Tries app protocol first, falls back to web
* @param {Object} songData - Song data object
*/
function openInSpotify(songData) {
const urls = createSpotifyUrls(songData);
// Try to open in Spotify app first
// On mobile, this will open the Spotify app if installed
// On desktop, this will open Spotify desktop app if installed
window.location.href = urls.appUrl;
// Fallback: If app doesn't open within 2 seconds, open web version
// This handles cases where Spotify app isn't installed
setTimeout(() => {
// Check if we're still on the same page (app didn't open)
// Note: This is a best-effort fallback
if (document.hasFocus()) {
window.open(urls.webUrl, '_blank');
}
}, 1500);
}
/**
* Renders the Spotify music player as a mini player widget above chat input
* @param {HTMLElement} container - Container element to render into
*/
export function renderMusicPlayer(container) {
// console.log('[RPG Companion] Music Player: renderMusicPlayer called');
// Remove old chat-attached player if it exists
$('#rpg-chat-music-player').remove();
// console.log('[RPG Companion] Music Player: enableSpotifyMusic =', extensionSettings.enableSpotifyMusic);
if (!extensionSettings.enableSpotifyMusic) {
// console.warn('[RPG Companion] Music Player: Spotify music is disabled');
return;
}
const songData = committedTrackerData.spotifyUrl;
// console.log('[RPG Companion] Music Player: Rendering with song:', songData);
if (!songData || !songData.displayText) {
// No song - don't show anything
return;
}
// Create the mini music player widget
const musicPlayerHtml = `
<div id="rpg-chat-music-player" class="rpg-music-widget">
<div class="rpg-music-widget-content">
<div class="rpg-music-widget-icon">
<i class="fa-brands fa-spotify"></i>
</div>
<div class="rpg-music-widget-info">
<div class="rpg-music-widget-title" title="${songData.song}">${songData.song}</div>
<div class="rpg-music-widget-artist" title="${songData.artist}">${songData.artist}</div>
</div>
<button class="rpg-music-widget-play" title="Play in Spotify">
<i class="fa-solid fa-play"></i>
</button>
<button class="rpg-music-widget-close" title="Dismiss">
<i class="fa-solid fa-times"></i>
</button>
</div>
</div>
`;
// Find the chat form container and insert widget before (above) it
const $chatForm = $('#send_form');
// console.log('[RPG Companion] Music Player: Found #send_form:', $chatForm.length > 0);
if ($chatForm.length === 0) {
console.error('[RPG Companion] Music Player: Could not find #send_form - cannot render widget!');
return;
}
// Insert widget inside (at top of) the chat form
// console.log('[RPG Companion] Music Player: Prepending widget to #send_form');
$chatForm.prepend(musicPlayerHtml);
// console.log('[RPG Companion] Music Player: Widget inserted, checking if visible...');
const $widget = $('#rpg-chat-music-player');
// console.log('[RPG Companion] Music Player: Widget exists:', $widget.length > 0);
if ($widget.length > 0) {
// console.log('[RPG Companion] Music Player: Widget position:', $widget.offset());
// console.log('[RPG Companion] Music Player: Widget dimensions:', { width: $widget.width(), height: $widget.height() });
// console.log('[RPG Companion] Music Player: Widget CSS display:', $widget.css('display'));
// console.log('[RPG Companion] Music Player: Widget CSS visibility:', $widget.css('visibility'));
}
// Bind play button click
$('#rpg-chat-music-player .rpg-music-widget-play').on('click', function(e) {
e.stopPropagation();
openInSpotify(songData);
});
// Bind close button click
$('#rpg-chat-music-player .rpg-music-widget-close').on('click', function(e) {
e.stopPropagation();
$('#rpg-chat-music-player').fadeOut(200, function() {
$(this).remove();
});
});
// Clicking anywhere else on the widget also opens Spotify
$('#rpg-chat-music-player .rpg-music-widget-content').on('click', function() {
openInSpotify(songData);
});
}
/**
* Updates the music player display
* @param {HTMLElement} container - Container element
*/
export function updateMusicPlayer(container) {
renderMusicPlayer(container);
}
+48 -2
View File
@@ -5,6 +5,24 @@
import { extensionSettings, $questsContainer } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { isItemLocked, setItemLock } from '../generation/lockManager.js';
/**
* Helper to generate lock icon HTML if setting is enabled
* @param {string} tracker - Tracker name
* @param {string} path - Item path
* @returns {string} Lock icon HTML or empty string
*/
function getLockIconHtml(tracker, path) {
const showLockIcons = extensionSettings.showLockIcons ?? true;
if (!showLockIcons) return '';
const isLocked = isItemLocked(tracker, path);
const lockIcon = isLocked ? '🔒' : '🔓';
const lockTitle = isLocked ? 'Locked' : 'Unlocked';
const lockedClass = isLocked ? ' locked' : '';
return `<span class="rpg-section-lock-icon${lockedClass}" data-tracker="${tracker}" data-path="${path}" title="${lockTitle}">${lockIcon}</span>`;
}
/**
* HTML escape helper
@@ -66,6 +84,7 @@ export function renderMainQuestView(mainQuest) {
</div>
</div>
<div class="rpg-quest-item" data-field="main">
${getLockIconHtml('userStats', 'quests.main')}
<div class="rpg-quest-title">${escapeHtml(questDisplay)}</div>
<div class="rpg-quest-actions">
<button class="rpg-quest-edit" data-action="edit-quest" data-field="main" title="Edit quest">
@@ -111,8 +130,10 @@ export function renderOptionalQuestsView(optionalQuests) {
if (quests.length === 0) {
questsHtml = '<div class="rpg-quest-empty">No active optional quests</div>';
} else {
questsHtml = quests.map((quest, index) => `
questsHtml = quests.map((quest, index) => {
return `
<div class="rpg-quest-item" data-field="optional" data-index="${index}">
${getLockIconHtml('userStats', `quests.optional[${index}]`)}
<div class="rpg-quest-title rpg-editable" contenteditable="true" data-field="optional" data-index="${index}" title="Click to edit">${escapeHtml(quest)}</div>
<div class="rpg-quest-actions">
<button class="rpg-quest-remove" data-action="remove-quest" data-field="optional" data-index="${index}" title="Complete/Remove quest">
@@ -120,7 +141,7 @@ export function renderOptionalQuestsView(optionalQuests) {
</button>
</div>
</div>
`).join('');
`}).join('');
}
return `
@@ -303,4 +324,29 @@ function attachQuestEventHandlers() {
}
}
});
// Add event listener for section lock icon clicks (support both click and touch)
$questsContainer.find('.rpg-section-lock-icon').on('click touchend', function(e) {
e.preventDefault();
e.stopPropagation();
const $icon = $(this);
const trackerType = $icon.data('tracker');
const itemPath = $icon.data('path');
const currentlyLocked = isItemLocked(trackerType, itemPath);
// Toggle lock state
setItemLock(trackerType, itemPath, !currentlyLocked);
// Update icon
const newIcon = !currentlyLocked ? '🔒' : '🔓';
const newTitle = !currentlyLocked ? 'Locked' : 'Unlocked';
$icon.text(newIcon);
$icon.attr('title', newTitle);
// Toggle 'locked' class for persistent visibility
$icon.toggleClass('locked', !currentlyLocked);
// Save settings
saveSettings();
});
}
File diff suppressed because it is too large Load Diff
+224 -26
View File
@@ -19,6 +19,7 @@ import {
} from '../../core/persistence.js';
import { getSafeThumbnailUrl } from '../../utils/avatars.js';
import { buildInventorySummary } from '../generation/promptBuilder.js';
import { isItemLocked, setItemLock } from '../generation/lockManager.js';
/**
* Builds the user stats text string using custom stat names
@@ -67,6 +68,107 @@ export function buildUserStatsText() {
return text.trim();
}
/**
* Updates lastGeneratedData.userStats and committedTrackerData.userStats
* Maintains JSON format if current data is JSON, otherwise uses text format.
* @private
*/
function updateUserStatsData() {
// Check if current data is in JSON format
const currentData = lastGeneratedData.userStats || committedTrackerData.userStats;
if (currentData) {
const trimmed = currentData.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
// Maintain JSON format
try {
const jsonData = JSON.parse(currentData);
if (jsonData && typeof jsonData === 'object') {
const stats = extensionSettings.userStats;
const config = extensionSettings.trackerConfig?.userStats || {};
const enabledStats = config.customStats?.filter(stat => stat && stat.enabled && stat.name && stat.id) || [];
// Build stats array - include all stats from extensionSettings, not just enabled ones
// This preserves custom stats that AI might have added or that user has disabled
const statsArray = [];
const processedIds = new Set();
// First, add all enabled stats from config (maintains order)
enabledStats.forEach(stat => {
statsArray.push({
id: stat.id,
name: stat.name,
value: stats[stat.id] !== undefined ? stats[stat.id] : 100
});
processedIds.add(stat.id);
});
// Then, add any other numeric stats from extensionSettings that aren't in config
// (these could be custom stats the AI added or disabled stats)
const excludeFields = new Set(['mood', 'conditions', 'inventory', 'skills', 'level']);
Object.entries(stats).forEach(([key, value]) => {
if (!processedIds.has(key) && !excludeFields.has(key) && typeof value === 'number') {
statsArray.push({
id: key,
name: key.charAt(0).toUpperCase() + key.slice(1),
value: value
});
}
});
jsonData.stats = statsArray;
// Update status
jsonData.status = {
mood: stats.mood || '😐',
conditions: stats.conditions || 'None'
};
// Update inventory (convert to v3 format)
const convertToV3Items = (itemString) => {
if (!itemString) return [];
const items = itemString.split(',').map(s => s.trim()).filter(s => s);
return items.map(item => {
const qtyMatch = item.match(/^(\\d+)x\\s+(.+)$/);
if (qtyMatch) {
return { name: qtyMatch[2].trim(), quantity: parseInt(qtyMatch[1]) };
}
return { name: item, quantity: 1 };
});
};
jsonData.inventory = {
onPerson: convertToV3Items(stats.inventory?.onPerson),
clothing: convertToV3Items(stats.inventory?.clothing),
stored: stats.inventory?.stored || {},
assets: convertToV3Items(stats.inventory?.assets)
};
// Update quests
jsonData.quests = extensionSettings.quests || { main: '', optional: [] };
// Update skills if present
if (stats.skills) {
jsonData.skills = Array.isArray(stats.skills) ? stats.skills :
stats.skills.split(',').map(s => s.trim()).filter(s => s);
}
const updatedJSON = JSON.stringify(jsonData, null, 2);
lastGeneratedData.userStats = updatedJSON;
committedTrackerData.userStats = updatedJSON;
return;
}
} catch (e) {
console.warn('[RPG Companion] Failed to parse JSON, falling back to text format:', e);
}
}
}
// Fall back to text format
const statsText = buildUserStatsText();
lastGeneratedData.userStats = statsText;
committedTrackerData.userStats = statsText;
}
/**
* Renders the user stats panel with health bars, mood, inventory, and classic stats.
* Includes event listeners for editable fields.
@@ -77,7 +179,36 @@ export function renderUserStats() {
return;
}
// Don't render if no data exists (e.g., after cache clear)
// Check both lastGeneratedData and committedTrackerData
// console.log('[RPG UserStats Render] Checking data:', {
// hasLastGenerated: !!lastGeneratedData.userStats,
// hasCommitted: !!committedTrackerData.userStats,
// lastGeneratedPreview: lastGeneratedData.userStats ? lastGeneratedData.userStats.substring(0, 100) : 'null',
// committedPreview: committedTrackerData.userStats ? committedTrackerData.userStats.substring(0, 100) : 'null'
// });
if (!lastGeneratedData.userStats && !committedTrackerData.userStats) {
// Always render to the #rpg-user-stats container (mobile layout just moves it around in DOM)
$userStatsContainer.html('<div class="rpg-inventory-empty">No statuses generated yet</div>');
return;
}
// Use lastGeneratedData if available, otherwise fall back to committed data
if (!lastGeneratedData.userStats && committedTrackerData.userStats) {
lastGeneratedData.userStats = committedTrackerData.userStats;
}
const stats = extensionSettings.userStats;
// console.log('[RPG UserStats Render] Current extensionSettings.userStats:', {
// health: stats.health,
// satiety: stats.satiety,
// energy: stats.energy,
// hygiene: stats.hygiene,
// arousal: stats.arousal,
// mood: stats.mood,
// conditions: stats.conditions
// });
const config = extensionSettings.trackerConfig?.userStats || {
customStats: [
{ id: 'health', name: 'Health', enabled: true },
@@ -116,20 +247,32 @@ export function renderUserStats() {
// Create gradient from low to high color
const gradient = `linear-gradient(to right, ${extensionSettings.statBarColorLow}, ${extensionSettings.statBarColorHigh})`;
let html = '<div class="rpg-stats-content"><div class="rpg-stats-left">';
// Check if stats bars section is locked
const isStatsLocked = isItemLocked('userStats', 'stats');
const lockIcon = isStatsLocked ? '🔒' : '🔓';
const lockTitle = isStatsLocked ? 'Locked - AI cannot change stats' : 'Unlocked - AI can change stats';
const lockedClass = isStatsLocked ? ' locked' : '';
let html = '<div class="rpg-stats-content">';
html += '<div class="rpg-stats-left">';
// User info row
const showLevel = extensionSettings.trackerConfig?.userStats?.showLevel !== false;
html += `
<div class="rpg-user-info-row">
<img src="${userPortrait}" alt="${userName}" class="rpg-user-portrait" onerror="this.style.opacity='0.5';this.onerror=null;" />
<span class="rpg-user-name">${userName}</span>
<span style="opacity: 0.5;">|</span>
${showLevel ? `<span style="opacity: 0.5;">|</span>
<span class="rpg-level-label">LVL</span>
<span class="rpg-level-value rpg-editable" contenteditable="true" data-field="level" title="Click to edit level">${extensionSettings.level}</span>
<span class="rpg-level-value rpg-editable" contenteditable="true" data-field="level" title="Click to edit level">${extensionSettings.level}</span>` : ''}
</div>
`;
// Dynamic stats grid - only show enabled stats
const showLockIcons = extensionSettings.showLockIcons ?? true;
if (showLockIcons) {
html += `<span class="rpg-section-lock-icon${lockedClass}" data-tracker="userStats" data-path="stats" title="${lockTitle}">${lockIcon}</span>`;
}
html += '<div class="rpg-stats-grid">';
const enabledStats = config.customStats.filter(stat => stat && stat.enabled && stat.name && stat.id);
@@ -149,7 +292,14 @@ export function renderUserStats() {
// Status section (conditionally rendered)
if (config.statusSection.enabled) {
const isMoodLocked = isItemLocked('userStats', 'status');
const moodLockIcon = isMoodLocked ? '🔒' : '🔓';
const moodLockTitle = isMoodLocked ? 'Locked - AI cannot change mood' : 'Unlocked - AI can change mood';
const moodLockedClass = isMoodLocked ? ' locked' : '';
html += '<div class="rpg-mood">';
if (showLockIcons) {
html += `<span class="rpg-section-lock-icon${moodLockedClass}" data-tracker="userStats" data-path="status" title="${moodLockTitle}">${moodLockIcon}</span>`;
}
if (config.statusSection.showMoodEmoji) {
html += `<div class="rpg-mood-emoji rpg-editable" contenteditable="true" data-field="mood" title="Click to edit emoji">${stats.mood}</div>`;
@@ -158,7 +308,11 @@ export function renderUserStats() {
// Render custom status fields
if (config.statusSection.customFields && config.statusSection.customFields.length > 0) {
// For now, use first field as "conditions" for backward compatibility
const conditionsValue = stats.conditions || 'None';
let conditionsValue = stats.conditions || 'None';
// Strip brackets if present (from JSON array format)
if (typeof conditionsValue === 'string') {
conditionsValue = conditionsValue.replace(/^\[|\]$/g, '').trim();
}
html += `<div class="rpg-mood-conditions rpg-editable" contenteditable="true" data-field="conditions" title="Click to edit conditions">${conditionsValue}</div>`;
}
@@ -167,9 +321,24 @@ export function renderUserStats() {
// Skills section (conditionally rendered)
if (config.skillsSection.enabled) {
const skillsValue = stats.skills || 'None';
const isSkillsLocked = isItemLocked('userStats', 'skills');
const skillsLockIcon = isSkillsLocked ? '🔒' : '🔓';
const skillsLockTitle = isSkillsLocked ? 'Locked - AI cannot change skills' : 'Unlocked - AI can change skills';
const skillsLockedClass = isSkillsLocked ? ' locked' : '';
let skillsValue = 'None';
// Handle JSON array format: [{name: "Art"}, {name: "Coding"}]
if (Array.isArray(stats.skills)) {
skillsValue = stats.skills.map(s => s.name || s).join(', ') || 'None';
} else if (stats.skills) {
skillsValue = stats.skills;
}
html += `
<div class="rpg-skills-section">`;
if (showLockIcons) {
html += `
<span class="rpg-section-lock-icon${skillsLockedClass}" data-tracker="userStats" data-path="skills" title="${skillsLockTitle}">${skillsLockIcon}</span>`;
}
html += `
<div class="rpg-skills-section">
<span class="rpg-skills-label">${config.skillsSection.label}:</span>
<div class="rpg-skills-value rpg-editable" contenteditable="true" data-field="skills" title="Click to edit skills">${skillsValue}</div>
</div>
@@ -225,7 +394,13 @@ export function renderUserStats() {
html += '</div>'; // Close rpg-stats-content
// console.log('[RPG UserStats Render] Generated HTML length:', html.length);
// console.log('[RPG UserStats Render] HTML preview:', html.substring(0, 300));
// console.log('[RPG UserStats Render] Container exists:', !!$userStatsContainer, '$userStatsContainer length:', $userStatsContainer?.length);
// Always render to the #rpg-user-stats container (mobile layout just moves it around in DOM)
$userStatsContainer.html(html);
// console.log('[RPG UserStats Render] ✓ HTML rendered to #rpg-user-stats container');
// Add event listeners for editable stat values
$('.rpg-editable-stat').on('blur', function() {
@@ -242,13 +417,8 @@ export function renderUserStats() {
// Update the setting
extensionSettings.userStats[field] = value;
// Rebuild userStats text with custom stat names
const statsText = buildUserStatsText();
// Update BOTH lastGeneratedData AND committedTrackerData
// This makes manual edits immediately visible to AI
lastGeneratedData.userStats = statsText;
committedTrackerData.userStats = statsText;
// Update userStats data (maintains JSON or text format)
updateUserStatsData();
saveSettings();
saveChatData();
@@ -263,13 +433,8 @@ export function renderUserStats() {
const value = $(this).text().trim();
extensionSettings.userStats.mood = value || '😐';
// Rebuild userStats text with custom stat names
const statsText = buildUserStatsText();
// Update BOTH lastGeneratedData AND committedTrackerData
// This makes manual edits immediately visible to AI
lastGeneratedData.userStats = statsText;
committedTrackerData.userStats = statsText;
// Update userStats data (maintains JSON or text format)
updateUserStatsData();
saveSettings();
saveChatData();
@@ -280,13 +445,21 @@ export function renderUserStats() {
const value = $(this).text().trim();
extensionSettings.userStats.conditions = value || 'None';
// Rebuild userStats text with custom stat names
const statsText = buildUserStatsText();
// Update userStats data (maintains JSON or text format)
updateUserStatsData();
// Update BOTH lastGeneratedData AND committedTrackerData
// This makes manual edits immediately visible to AI
lastGeneratedData.userStats = statsText;
committedTrackerData.userStats = statsText;
saveSettings();
saveChatData();
updateMessageSwipeData();
});
// Add event listener for skills editing
$('.rpg-skills-value.rpg-editable').on('blur', function() {
const value = $(this).text().trim();
extensionSettings.userStats.skills = value || 'None';
// Update userStats data (maintains JSON or text format)
updateUserStatsData();
saveSettings();
saveChatData();
@@ -342,4 +515,29 @@ export function renderUserStats() {
$(this).blur();
}
});
// Add event listener for section lock icon clicks (support both click and touch)
$('.rpg-section-lock-icon').on('click touchend', function(e) {
e.preventDefault();
e.stopPropagation();
const $icon = $(this);
const trackerType = $icon.data('tracker');
const itemPath = $icon.data('path');
const currentlyLocked = isItemLocked(trackerType, itemPath);
// Toggle lock state
setItemLock(trackerType, itemPath, !currentlyLocked);
// Update icon
const newIcon = !currentlyLocked ? '🔒' : '🔓';
const newTitle = !currentlyLocked ? 'Locked - AI cannot change this section' : 'Unlocked - AI can change this section';
$icon.text(newIcon);
$icon.attr('title', newTitle);
// Toggle 'locked' class for persistent visibility
$icon.toggleClass('locked', !currentlyLocked);
// Save settings
saveSettings();
});
}
+369
View File
@@ -0,0 +1,369 @@
/**
* Chapter Checkpoint UI Module
* Adds UI elements for chapter checkpoint functionality
*/
import { getContext } from '../../../../../../extensions.js';
import { i18n } from '../../core/i18n.js';
import {
setChapterCheckpoint,
clearChapterCheckpoint,
isCheckpointMessage
} from '../features/chapterCheckpoint.js';
/**
* Adds the chapter checkpoint button to a message's extra menu
* @param {number} messageId - The message index
* @param {HTMLElement} menu - The message menu element
* @param {boolean} isExpanded - Whether this is for expanded message actions
*/
export function addCheckpointButtonToMessage(messageId, menu, isExpanded = false) {
if (!menu) return;
const isCheckpoint = isCheckpointMessage(messageId);
// Create the menu item
const menuItem = document.createElement('div');
// Use different classes for expanded vs dropdown menu
if (isExpanded) {
menuItem.className = 'mes_button';
menuItem.setAttribute('tabindex', '0');
} else {
menuItem.className = 'extraMesButtonsHint list-group-item flex-container flexGap5';
}
const translationKey = isCheckpoint ? 'checkpoint.clearChapterStart' : 'checkpoint.setChapterStart';
menuItem.setAttribute('data-i18n', translationKey);
menuItem.title = isCheckpoint
? 'Clear Chapter Start'
: 'Set Chapter Start — When bookmarked, this message will count as the first message in the chat history, skipping earlier ones.';
// Icon only (no text label)
const icon = document.createElement('i');
icon.className = isCheckpoint ? 'fa-solid fa-bookmark' : 'fa-regular fa-bookmark';
icon.style.color = isCheckpoint ? '#4a9eff' : '';
menuItem.appendChild(icon);
// Click handler
menuItem.addEventListener('click', (e) => {
e.stopPropagation();
const wasCheckpoint = isCheckpointMessage(messageId);
if (wasCheckpoint) {
clearChapterCheckpoint();
} else {
setChapterCheckpoint(messageId);
}
// Update this button immediately
const newIsCheckpoint = isCheckpointMessage(messageId);
icon.className = newIsCheckpoint ? 'fa-solid fa-bookmark' : 'fa-regular fa-bookmark';
icon.style.color = newIsCheckpoint ? '#4a9eff' : '';
menuItem.title = newIsCheckpoint
? 'Clear Chapter Start'
: 'Set Chapter Start: When bookmarked, this message will count as the first message in the chat history, skipping earlier ones';
const newTranslationKey = newIsCheckpoint ? 'checkpoint.clearChapterStart' : 'checkpoint.setChapterStart';
menuItem.setAttribute('data-i18n', newTranslationKey);
// Update indicators in all messages
updateAllCheckpointIndicators();
});
return menuItem;
}
/**
* Adds visual indicators to messages that are checkpoints
* @param {number} messageId - The message index
* @param {HTMLElement} messageBlock - The message DOM element
*/
export function addCheckpointIndicator(messageId, messageBlock) {
if (!messageBlock) return;
const isCheckpoint = isCheckpointMessage(messageId);
// Remove existing indicator if present
const existingIndicator = messageBlock.querySelector('.rpg-checkpoint-indicator');
if (existingIndicator) {
existingIndicator.remove();
}
if (!isCheckpoint) return;
// Add checkpoint indicator
const indicator = document.createElement('div');
indicator.className = 'rpg-checkpoint-indicator';
const indicatorText = i18n.getTranslation('checkpoint.indicator') || 'Chapter Start';
const tooltipText = i18n.getTranslation('checkpoint.tooltip') || 'Messages before this point are excluded from context';
indicator.innerHTML = `
<i class="fa-solid fa-bookmark"></i>
<span>${indicatorText}</span>
`;
indicator.title = tooltipText;
// Insert at the beginning of the message
const mesText = messageBlock.querySelector('.mes_text');
if (mesText && mesText.parentNode) {
mesText.parentNode.insertBefore(indicator, mesText);
}
}
/**
* Updates checkpoint indicators for all messages
*/
export function updateAllCheckpointIndicators() {
const context = getContext();
const chat = context.chat;
if (!chat) return;
// First, remove ALL checkpoint buttons from everywhere
document.querySelectorAll('.rpg-checkpoint-button, .rpg-checkpoint-button-expanded').forEach(btn => btn.remove());
// Update all message blocks
const messageBlocks = document.querySelectorAll('.mes');
messageBlocks.forEach((block) => {
// Get the actual message ID from the mesid attribute
const messageId = Number(block.getAttribute('mesid'));
if (isNaN(messageId)) return;
addCheckpointIndicator(messageId, block);
// Re-add buttons based on current mode
processExpandedButton(block);
const dropdownMenu = block.querySelector('.extraMesButtons');
if (dropdownMenu) {
processExtraMesButtons(dropdownMenu);
}
});
}
/**
* Removes all checkpoint UI elements
*/
export function cleanupCheckpointUI() {
// Remove all checkpoint buttons
document.querySelectorAll('.rpg-checkpoint-button, .rpg-checkpoint-button-expanded').forEach(btn => btn.remove());
// Remove all checkpoint indicators (banner)
document.querySelectorAll('.rpg-checkpoint-indicator').forEach(indicator => indicator.remove());
}
/**
* Initializes the chapter checkpoint UI
*/
export function initChapterCheckpointUI() {
// Listen for checkpoint changes
document.addEventListener('rpg-companion-checkpoint-changed', () => {
updateAllCheckpointIndicators();
});
// Listen for expandMessageActions class changes on body
const bodyObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
// The expandMessageActions class was toggled, refresh all buttons
updateAllCheckpointIndicators();
}
});
});
bodyObserver.observe(document.body, { attributes: true, attributeFilter: ['class'] });
// Listen for chat changes to update indicators
const context = getContext();
if (context && context.eventSource) {
// Update checkpoint indicators when messages are rendered
const observer = new MutationObserver((mutations) => {
let shouldUpdate = false;
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE &&
node.classList && node.classList.contains('mes')) {
shouldUpdate = true;
}
});
});
if (shouldUpdate) {
// Debounce updates to avoid excessive re-rendering
clearTimeout(window.rpgCheckpointUpdateTimeout);
window.rpgCheckpointUpdateTimeout = setTimeout(() => {
updateAllCheckpointIndicators();
}, 100);
}
});
const chatContainer = document.getElementById('chat');
if (chatContainer) {
observer.observe(chatContainer, {
childList: true,
subtree: false
});
}
}
// Update indicators on initialization
updateAllCheckpointIndicators();
}
/**
* Injects checkpoint button into message menus
* This should be called when SillyTavern renders message menus
*/
export function injectCheckpointButton() {
// Observer for dropdown menus and message blocks
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
// Check for added nodes
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
// Check if extraMesButtons container was added (dropdown menu)
if (node.classList && node.classList.contains('extraMesButtons')) {
processExtraMesButtons(node);
}
// Check if message block was added (for expanded buttons)
if (node.classList && node.classList.contains('mes')) {
processExpandedButton(node);
}
// Also check if any exist within added subtree
if (node.querySelector) {
const extraButtons = node.querySelectorAll('.extraMesButtons');
extraButtons.forEach(processExtraMesButtons);
const messageBlocks = node.querySelectorAll('.mes');
messageBlocks.forEach(processExpandedButton);
}
}
});
// Check if nodes were added TO an extraMesButtons container
if (mutation.target && mutation.target.classList &&
mutation.target.classList.contains('extraMesButtons')) {
processExtraMesButtons(mutation.target);
}
});
});
// Observe the chat container
const chatContainer = document.getElementById('chat');
if (chatContainer) {
observer.observe(chatContainer, {
childList: true,
subtree: true
});
// Process any existing dropdown menus and messages on initialization
// Use setTimeout to ensure styles are computed
setTimeout(() => {
const existingDropdownMenus = chatContainer.querySelectorAll('.extraMesButtons');
existingDropdownMenus.forEach(processExtraMesButtons);
const existingMessages = chatContainer.querySelectorAll('.mes');
existingMessages.forEach(processExpandedButton);
}, 100);
}
}
/**
* Process an extraMesButtons container to add checkpoint button (dropdown menu)
* @param {HTMLElement} menu - The extraMesButtons container
*/
function processExtraMesButtons(menu) {
if (!menu) return;
// Find the message block
const messageBlock = menu.closest('.mes');
if (!messageBlock) return;
// Get the message ID from the mesid attribute (SillyTavern's standard way)
const messageId = Number(messageBlock.getAttribute('mesid'));
if (isNaN(messageId)) return;
// Check if expanded mode is active - if so, skip dropdown
if (document.body.classList.contains('expandMessageActions')) {
return; // Expanded mode is ON, button will be added to mes_buttons instead
}
// Check if button already exists in this container
if (menu.querySelector('.rpg-checkpoint-button')) return;
// Add checkpoint button to dropdown menu
const checkpointBtn = addCheckpointButtonToMessage(messageId, menu, false);
if (checkpointBtn) {
checkpointBtn.classList.add('rpg-checkpoint-button');
menu.appendChild(checkpointBtn);
}
}
/**
* Process a message block to add expanded checkpoint button
* @param {HTMLElement} messageBlock - The message block element
*/
function processExpandedButton(messageBlock) {
if (!messageBlock) return;
const mesButtons = messageBlock.querySelector('.mes_buttons');
if (!mesButtons) return;
// Only add if expanded mode is ON (check body class)
if (!document.body.classList.contains('expandMessageActions')) {
return; // Expanded mode is OFF, button will be in dropdown instead
}
const messageId = Number(messageBlock.getAttribute('mesid'));
if (isNaN(messageId)) return;
// Check if button already exists in this container
if (mesButtons.querySelector('.rpg-checkpoint-button-expanded')) return;
// Add checkpoint button as separate mes_button
const checkpointBtn = addCheckpointButtonToMessage(messageId, mesButtons, true);
if (checkpointBtn) {
checkpointBtn.classList.add('rpg-checkpoint-button-expanded');
// Insert before the edit button if it exists, otherwise append
const editButton = mesButtons.querySelector('.mes_edit');
if (editButton) {
mesButtons.insertBefore(checkpointBtn, editButton);
} else {
mesButtons.appendChild(checkpointBtn);
}
}
}
/**
* Update the checkpoint button in an existing menu
* @param {HTMLElement} menu - The extraMesButtons or mes_buttons container
* @param {number} messageId - The message index
*/
function updateCheckpointButtonInMenu(menu, messageId) {
if (!menu) return;
// Find the checkpoint button (either dropdown or expanded)
const existingButton = menu.querySelector('.rpg-checkpoint-button, .rpg-checkpoint-button-expanded');
if (!existingButton) return;
const isCheckpoint = isCheckpointMessage(messageId);
// Update icon
const icon = existingButton.querySelector('i');
if (icon) {
icon.className = isCheckpoint ? 'fa-solid fa-bookmark' : 'fa-regular fa-bookmark';
icon.style.color = isCheckpoint ? '#4a9eff' : '';
}
// Update tooltip
existingButton.title = isCheckpoint
? 'Clear Chapter Start'
: 'Set Chapter Start — When bookmarked, this message will count as the first message in the chat history, skipping earlier ones.';
const translationKey = isCheckpoint ? 'checkpoint.clearChapterStart' : 'checkpoint.setChapterStart';
existingButton.setAttribute('data-i18n', translationKey);
}
-220
View File
@@ -1,220 +0,0 @@
/**
* Debug UI Module
* Provides mobile-friendly debug log viewer for troubleshooting parsing issues
*/
import { extensionSettings, getDebugLogs, clearDebugLogs } from '../../core/state.js';
/**
* Creates and injects the debug panel into the page
* Note: Debug toggle button is created in index.js, not here
*/
export function createDebugPanel() {
// Remove existing debug panel if any
$('#rpg-debug-panel').remove();
// Create debug panel HTML
const debugPanelHtml = `
<div id="rpg-debug-panel" class="rpg-debug-panel">
<div class="rpg-debug-header">
<h3>🔍 Debug Logs</h3>
<div class="rpg-debug-actions">
<button id="rpg-debug-copy" title="Copy logs to clipboard">
<i class="fa-solid fa-copy"></i>
</button>
<button id="rpg-debug-clear" title="Clear logs">
<i class="fa-solid fa-trash"></i>
</button>
<button id="rpg-debug-close" title="Close debug panel">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
</div>
<div id="rpg-debug-logs" class="rpg-debug-logs"></div>
</div>
`;
// Append to body
$('body').append(debugPanelHtml);
// Set up event handlers
setupDebugEventHandlers();
// Initial log render
renderDebugLogs();
}
/**
* Closes the debug panel with proper animation (mobile or desktop)
*/
function closeDebugPanel() {
const $panel = $('#rpg-debug-panel');
const isMobile = window.innerWidth <= 1000;
if (isMobile) {
// Mobile: animate slide-out to right
$panel.removeClass('rpg-mobile-open').addClass('rpg-mobile-closing');
// Wait for animation to complete before hiding
$panel.one('animationend', function() {
$panel.removeClass('rpg-mobile-closing');
$('.rpg-mobile-overlay').remove();
});
} else {
// Desktop: simple slide-down
$panel.removeClass('rpg-debug-open');
}
}
/**
* Sets up event handlers for debug panel using event delegation for mobile compatibility
*/
function setupDebugEventHandlers() {
// Use event delegation for better mobile compatibility and reliability with dynamic elements
// Remove any existing handlers first to prevent duplicates
$(document).off('click.rpgDebug');
// Toggle button
$(document).on('click.rpgDebug', '#rpg-debug-toggle', function() {
const $debugToggle = $(this);
// Skip if we just finished dragging
if ($debugToggle.data('just-dragged')) {
console.log('[RPG Debug] Click blocked - just finished dragging');
return;
}
const $panel = $('#rpg-debug-panel');
const isMobile = window.innerWidth <= 1000;
if (isMobile) {
// Mobile: use rpg-mobile-open class with slide-from-right animation
const isOpen = $panel.hasClass('rpg-mobile-open');
if (isOpen) {
// Close with animation
closeDebugPanel();
} else {
// Open with animation
$panel.addClass('rpg-mobile-open');
renderDebugLogs();
// Create overlay for mobile
const $overlay = $('<div class="rpg-mobile-overlay"></div>');
$('body').append($overlay);
// Close when clicking overlay
$overlay.on('click', function() {
closeDebugPanel();
});
}
} else {
// Desktop: use rpg-debug-open class with slide-from-bottom animation
$panel.toggleClass('rpg-debug-open');
renderDebugLogs();
}
});
// Close button
$(document).on('click.rpgDebug', '#rpg-debug-close', function(e) {
e.preventDefault();
e.stopPropagation();
closeDebugPanel();
});
// Copy button
$(document).on('click.rpgDebug', '#rpg-debug-copy', function() {
const logs = getDebugLogs();
const logsText = logs.map(log => {
let text = `[${log.timestamp}] ${log.message}`;
if (log.data) {
text += `\n${log.data}`;
}
return text;
}).join('\n\n');
navigator.clipboard.writeText(logsText).then(() => {
// Show feedback
const $btn = $(this);
const $icon = $btn.find('i');
$icon.removeClass('fa-copy').addClass('fa-check');
setTimeout(() => {
$icon.removeClass('fa-check').addClass('fa-copy');
}, 1500);
}).catch(err => {
console.error('Failed to copy logs:', err);
alert('Failed to copy logs. Please use browser console instead.');
});
});
// Clear button
$(document).on('click.rpgDebug', '#rpg-debug-clear', function() {
if (confirm('Clear all debug logs?')) {
clearDebugLogs();
renderDebugLogs();
}
});
}
/**
* Renders debug logs to the panel
*/
function renderDebugLogs() {
const logs = getDebugLogs();
const $logsContainer = $('#rpg-debug-logs');
if (logs.length === 0) {
$logsContainer.html('<div class="rpg-debug-empty">No logs yet. Logs will appear when parser runs.</div>');
return;
}
// Build logs HTML
const logsHtml = logs.map(log => {
let html = `<div class="rpg-debug-entry">`;
html += `<span class="rpg-debug-time">[${log.timestamp}]</span> `;
html += `<span class="rpg-debug-message">${escapeHtml(log.message)}</span>`;
if (log.data) {
html += `<pre class="rpg-debug-data">${escapeHtml(log.data)}</pre>`;
}
html += `</div>`;
return html;
}).join('');
$logsContainer.html(logsHtml);
// Auto-scroll to bottom
$logsContainer[0].scrollTop = $logsContainer[0].scrollHeight;
}
/**
* Escapes HTML to prevent XSS
*/
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* Shows or hides debug UI based on debug mode setting
* Note: Debug toggle button always exists in DOM (created in index.js)
*/
export function updateDebugUIVisibility() {
const $debugToggle = $('#rpg-debug-toggle');
if (extensionSettings.debugMode) {
// Show debug toggle button
$debugToggle.css('display', 'flex');
// Create debug panel if it doesn't exist
if ($('#rpg-debug-panel').length === 0) {
createDebugPanel();
}
} else {
// Hide debug toggle button
$debugToggle.css('display', 'none');
// Remove debug panel
$('#rpg-debug-panel').remove();
}
}
+56 -24
View File
@@ -3,6 +3,9 @@
* Handles desktop-specific UI functionality: tab navigation
*/
import { i18n } from '../../core/i18n.js';
import { extensionSettings } from '../../core/state.js';
/**
* Sets up desktop tab navigation for organizing content.
* Only runs on desktop viewports (>1000px).
@@ -29,23 +32,40 @@ export function setupDesktopTabs() {
return;
}
// Create tab navigation
const $tabNav = $(`
<div class="rpg-tabs-nav">
<button class="rpg-tab-btn active" data-tab="status">
<i class="fa-solid fa-chart-simple"></i>
<span>Status</span>
</button>
// Build tab navigation dynamically based on enabled settings
const tabButtons = [];
const hasInventory = $inventory.length > 0 && extensionSettings.showInventory;
const hasQuests = $quests.length > 0 && extensionSettings.showQuests;
// Status tab (always present if any status content exists)
tabButtons.push(`
<button class="rpg-tab-btn active" data-tab="status">
<i class="fa-solid fa-chart-simple"></i>
<span data-i18n-key="global.status">Status</span>
</button>
`);
// Inventory tab (only if enabled in settings)
if (hasInventory) {
tabButtons.push(`
<button class="rpg-tab-btn" data-tab="inventory">
<i class="fa-solid fa-box"></i>
<span>Inventory</span>
<span data-i18n-key="global.inventory">Inventory</span>
</button>
`);
}
// Quests tab (only if enabled in settings)
if (hasQuests) {
tabButtons.push(`
<button class="rpg-tab-btn" data-tab="quests">
<i class="fa-solid fa-scroll"></i>
<span>Quests</span>
<span data-i18n-key="global.quests">Quests</span>
</button>
</div>
`);
`);
}
const $tabNav = $(`<div class="rpg-tabs-nav">${tabButtons.join('')}</div>`);
// Create tab content containers
const $statusTab = $('<div class="rpg-tab-content active" data-tab-content="status"></div>');
@@ -55,23 +75,29 @@ export function setupDesktopTabs() {
// Move sections into their respective tabs (detach to preserve event handlers)
if ($userStats.length > 0) {
$statusTab.append($userStats.detach());
$userStats.show();
if (extensionSettings.showUserStats) $userStats.show();
}
if ($infoBox.length > 0) {
$statusTab.append($infoBox.detach());
$infoBox.show();
// Only show if enabled and has data
if (extensionSettings.showInfoBox) {
const infoBoxData = window.lastGeneratedData?.infoBox || window.committedTrackerData?.infoBox;
if (infoBoxData) $infoBox.show();
}
}
if ($thoughts.length > 0) {
$statusTab.append($thoughts.detach());
$thoughts.show();
if (extensionSettings.showCharacterThoughts) $thoughts.show();
}
if ($inventory.length > 0) {
$inventoryTab.append($inventory.detach());
$inventory.show();
// Only show if enabled (will be part of tab structure)
if (hasInventory) $inventory.show();
}
if ($quests.length > 0) {
$questsTab.append($quests.detach());
$quests.show();
// Only show if enabled (will be part of tab structure)
if (hasQuests) $quests.show();
}
// Hide dividers on desktop tabs (tabs separate content naturally)
@@ -81,11 +107,15 @@ export function setupDesktopTabs() {
const $tabsContainer = $('<div class="rpg-tabs-container"></div>');
$tabsContainer.append($tabNav);
$tabsContainer.append($statusTab);
// Always append inventory and quests tabs to preserve the elements
// But they'll only show if enabled (via tab button visibility)
$tabsContainer.append($inventoryTab);
$tabsContainer.append($questsTab);
// Replace content box with tabs container
$contentBox.html('').append($tabsContainer);
i18n.applyTranslations($tabsContainer[0]);
// Handle tab switching
$tabNav.find('.rpg-tab-btn').on('click', function() {
@@ -100,7 +130,7 @@ export function setupDesktopTabs() {
$(`.rpg-tab-content[data-tab-content="${tabName}"]`).addClass('active');
});
console.log('[RPG Desktop] Desktop tabs initialized');
}
/**
@@ -142,12 +172,14 @@ export function removeDesktopTabs() {
$contentBox.append($quests);
}
// Show sections and dividers
$userStats.show();
$infoBox.show();
$thoughts.show();
$inventory.show();
// Show/hide sections based on settings (respect visibility settings)
if (extensionSettings.showUserStats) $userStats.show();
if (extensionSettings.showInfoBox) {
const infoBoxData = window.lastGeneratedData?.infoBox || window.committedTrackerData?.infoBox;
if (infoBoxData) $infoBox.show();
}
if (extensionSettings.showCharacterThoughts) $thoughts.show();
if (extensionSettings.showInventory) $inventory.show();
if (extensionSettings.showQuests) $quests.show();
$('.rpg-divider').show();
console.log('[RPG Desktop] Desktop tabs removed');
}
File diff suppressed because it is too large Load Diff
+244 -67
View File
@@ -9,14 +9,51 @@ import {
$userStatsContainer,
$infoBoxContainer,
$thoughtsContainer,
$inventoryContainer
$inventoryContainer,
$questsContainer,
$musicPlayerContainer,
setInventoryContainer,
setQuestsContainer,
lastGeneratedData,
committedTrackerData
} from '../../core/state.js';
import { i18n } from '../../core/i18n.js';
import { setupMobileTabs, removeMobileTabs } from './mobile.js';
import { setupDesktopTabs, removeDesktopTabs } from './desktop.js';
/**
* Toggles the visibility of plot buttons based on settings.
*/
export function togglePlotButtons() {
if (extensionSettings.enablePlotButtons && extensionSettings.enabled) {
if (!extensionSettings.enabled) {
$('#rpg-plot-buttons').hide();
return;
}
// Show/hide randomized plot button based on enableRandomizedPlot setting
if (extensionSettings.enableRandomizedPlot) {
$('#rpg-plot-random').show();
} else {
$('#rpg-plot-random').hide();
}
// Show/hide natural plot button based on enableNaturalPlot setting
if (extensionSettings.enableNaturalPlot) {
$('#rpg-plot-natural').show();
} else {
$('#rpg-plot-natural').hide();
}
// Show/hide encounter button independently based on encounter settings
if (extensionSettings.encounterSettings?.enabled) {
$('#rpg-encounter-button').show();
} else {
$('#rpg-encounter-button').hide();
}
// Show the container if at least one button is visible
const shouldShowContainer = extensionSettings.enableRandomizedPlot || extensionSettings.enableNaturalPlot || extensionSettings.encounterSettings?.enabled;
if (shouldShowContainer) {
$('#rpg-plot-buttons').show();
} else {
$('#rpg-plot-buttons').hide();
@@ -51,19 +88,34 @@ export function updateCollapseToggleIcon() {
const isMobile = window.innerWidth <= 1000;
if (isMobile) {
// Mobile: slides from right, use same icon logic as desktop right panel
// Mobile: icon direction based on panel position and open state
const isOpen = $panel.hasClass('rpg-mobile-open');
console.log('[RPG Mobile] updateCollapseToggleIcon:', {
isMobile: true,
isOpen,
settingIcon: isOpen ? 'chevron-left' : 'chevron-right'
});
if (isOpen) {
// Panel open - chevron points left (to close/slide back right)
$icon.removeClass('fa-chevron-down fa-chevron-up fa-chevron-right').addClass('fa-chevron-left');
const isLeftPanel = $panel.hasClass('rpg-position-left');
// console.log('[RPG Mobile] updateCollapseToggleIcon:', {
// isMobile: true,
// isOpen,
// isLeftPanel,
// settingIcon: isOpen ? (isLeftPanel ? 'chevron-left' : 'chevron-right') : (isLeftPanel ? 'chevron-right' : 'chevron-left')
// });
if (isLeftPanel) {
if (isOpen) {
// Left panel open - chevron points left (panel will slide left to close)
$icon.removeClass('fa-chevron-down fa-chevron-up fa-chevron-right').addClass('fa-chevron-left');
} else {
// Left panel closed - chevron points left (panel is hidden on left)
$icon.removeClass('fa-chevron-down fa-chevron-up fa-chevron-right').addClass('fa-chevron-left');
}
} else {
// Panel closed - chevron points right (to open/slide in from right)
$icon.removeClass('fa-chevron-down fa-chevron-up fa-chevron-left').addClass('fa-chevron-right');
// Right panel (default)
if (isOpen) {
// Right panel open - chevron points right (panel will slide right to close)
$icon.removeClass('fa-chevron-down fa-chevron-up fa-chevron-left').addClass('fa-chevron-right');
} else {
// Right panel closed - chevron points right (panel is hidden on right)
$icon.removeClass('fa-chevron-down fa-chevron-up fa-chevron-left').addClass('fa-chevron-right');
}
}
} else {
// Desktop: icon direction based on panel position and collapsed state
@@ -92,6 +144,7 @@ export function updateCollapseToggleIcon() {
*/
export function setupCollapseToggle() {
const $collapseToggle = $('#rpg-collapse-toggle');
$collapseToggle.attr('title', i18n.getTranslation('template.mainPanel.collapseExpand'));
const $panel = $('#rpg-companion-panel');
const $icon = $collapseToggle.find('i');
@@ -104,44 +157,44 @@ export function setupCollapseToggle() {
// On mobile: button toggles panel open/closed (same as desktop behavior)
if (isMobile) {
const isOpen = $panel.hasClass('rpg-mobile-open');
console.log('[RPG Mobile] Collapse toggle clicked. Current state:', {
isOpen,
panelClasses: $panel.attr('class'),
inlineStyles: $panel.attr('style'),
panelPosition: {
top: $panel.css('top'),
bottom: $panel.css('bottom'),
transform: $panel.css('transform'),
visibility: $panel.css('visibility')
}
});
// console.log('[RPG Mobile] Collapse toggle clicked. Current state:', {
// isOpen,
// panelClasses: $panel.attr('class'),
// inlineStyles: $panel.attr('style'),
// panelPosition: {
// top: $panel.css('top'),
// bottom: $panel.css('bottom'),
// transform: $panel.css('transform'),
// visibility: $panel.css('visibility')
// }
// });
if (isOpen) {
// Close panel with animation
console.log('[RPG Mobile] Closing panel');
// console.log('[RPG Mobile] Closing panel');
closeMobilePanelWithAnimation();
} else {
// Open panel
console.log('[RPG Mobile] Opening panel');
// console.log('[RPG Mobile] Opening panel');
$panel.addClass('rpg-mobile-open');
const $overlay = $('<div class="rpg-mobile-overlay"></div>');
$('body').append($overlay);
// Debug: Check state after animation should complete
setTimeout(() => {
console.log('[RPG Mobile] 500ms after opening:', {
panelClasses: $panel.attr('class'),
hasOpenClass: $panel.hasClass('rpg-mobile-open'),
visibility: $panel.css('visibility'),
transform: $panel.css('transform'),
display: $panel.css('display'),
opacity: $panel.css('opacity')
});
// console.log('[RPG Mobile] 500ms after opening:', {
// panelClasses: $panel.attr('class'),
// hasOpenClass: $panel.hasClass('rpg-mobile-open'),
// visibility: $panel.css('visibility'),
// transform: $panel.css('transform'),
// display: $panel.css('display'),
// opacity: $panel.css('opacity')
// });
}, 500);
// Close when clicking overlay
$overlay.on('click', function() {
console.log('[RPG Mobile] Overlay clicked - closing panel');
// console.log('[RPG Mobile] Overlay clicked - closing panel');
closeMobilePanelWithAnimation();
updateCollapseToggleIcon();
});
@@ -150,20 +203,20 @@ export function setupCollapseToggle() {
// Update icon to reflect new state
updateCollapseToggleIcon();
console.log('[RPG Mobile] After toggle:', {
panelClasses: $panel.attr('class'),
inlineStyles: $panel.attr('style'),
panelPosition: {
top: $panel.css('top'),
bottom: $panel.css('bottom'),
transform: $panel.css('transform'),
visibility: $panel.css('visibility')
},
gameContainer: {
opacity: $('.rpg-game-container').css('opacity'),
visibility: $('.rpg-game-container').css('visibility')
}
});
// console.log('[RPG Mobile] After toggle:', {
// panelClasses: $panel.attr('class'),
// inlineStyles: $panel.attr('style'),
// panelPosition: {
// top: $panel.css('top'),
// bottom: $panel.css('bottom'),
// transform: $panel.css('transform'),
// visibility: $panel.css('visibility')
// },
// gameContainer: {
// opacity: $('.rpg-game-container').css('opacity'),
// visibility: $('.rpg-game-container').css('visibility')
// }
// });
return;
}
@@ -204,9 +257,13 @@ export function updatePanelVisibility() {
if (extensionSettings.enabled) {
$panelContainer.show();
togglePlotButtons(); // Update plot button visibility
$('#rpg-mobile-toggle').show(); // Show mobile FAB toggle
$('#rpg-collapse-toggle').show(); // Show collapse toggle
} else {
$panelContainer.hide();
$('#rpg-plot-buttons').hide(); // Hide plot buttons when disabled
$('#rpg-mobile-toggle').hide(); // Hide mobile FAB toggle
$('#rpg-collapse-toggle').hide(); // Hide collapse toggle
}
}
@@ -214,29 +271,131 @@ export function updatePanelVisibility() {
* Updates the visibility of individual sections.
*/
export function updateSectionVisibility() {
// Refresh container references first (in case they were detached during tab operations)
setInventoryContainer($('#rpg-inventory'));
setQuestsContainer($('#rpg-quests'));
// Show/hide sections based on settings
$userStatsContainer.toggle(extensionSettings.showUserStats);
$infoBoxContainer.toggle(extensionSettings.showInfoBox);
$thoughtsContainer.toggle(extensionSettings.showCharacterThoughts);
if ($inventoryContainer) {
$inventoryContainer.toggle(extensionSettings.showInventory);
// Use explicit .show()/.hide() instead of .toggle() to ensure proper state on reload
if (extensionSettings.showUserStats) {
$userStatsContainer.show();
} else {
$userStatsContainer.hide();
}
if (extensionSettings.showInfoBox) {
// Only show if there's data to display
const infoBoxData = lastGeneratedData.infoBox || committedTrackerData.infoBox;
if (infoBoxData) {
$infoBoxContainer.show();
} else {
$infoBoxContainer.hide();
}
} else {
$infoBoxContainer.hide();
}
if (extensionSettings.showCharacterThoughts) {
$thoughtsContainer.show();
} else {
$thoughtsContainer.hide();
}
// Use direct DOM selectors for inventory and quests to avoid stale references
if (extensionSettings.showInventory) {
$('#rpg-inventory').show();
} else {
$('#rpg-inventory').hide();
}
if (extensionSettings.showQuests) {
$('#rpg-quests').show();
} else {
$('#rpg-quests').hide();
}
if ($musicPlayerContainer) {
if (extensionSettings.enableSpotifyMusic) {
$musicPlayerContainer.show();
} else {
$musicPlayerContainer.hide();
}
}
// Show/hide dividers intelligently
// Divider after User Stats: shown if User Stats is visible AND at least one section after it is visible
const showDividerAfterStats = extensionSettings.showUserStats &&
(extensionSettings.showInfoBox || extensionSettings.showCharacterThoughts || extensionSettings.showInventory);
$('#rpg-divider-stats').toggle(showDividerAfterStats);
(extensionSettings.showInfoBox || extensionSettings.showCharacterThoughts || extensionSettings.showInventory || extensionSettings.showQuests || extensionSettings.enableSpotifyMusic);
if (showDividerAfterStats) {
$('#rpg-divider-stats').show();
} else {
$('#rpg-divider-stats').hide();
}
// Divider after Info Box: shown if Info Box is visible AND at least one section after it is visible
const showDividerAfterInfo = extensionSettings.showInfoBox &&
(extensionSettings.showCharacterThoughts || extensionSettings.showInventory);
$('#rpg-divider-info').toggle(showDividerAfterInfo);
(extensionSettings.showCharacterThoughts || extensionSettings.showInventory || extensionSettings.showQuests);
if (showDividerAfterInfo) {
$('#rpg-divider-info').show();
} else {
$('#rpg-divider-info').hide();
}
// Divider after Thoughts: shown if Thoughts is visible AND Inventory is visible
// Divider after Thoughts: shown if Thoughts is visible AND at least one section after it is visible
const showDividerAfterThoughts = extensionSettings.showCharacterThoughts &&
extensionSettings.showInventory;
$('#rpg-divider-thoughts').toggle(showDividerAfterThoughts);
(extensionSettings.showInventory || extensionSettings.showQuests || extensionSettings.enableSpotifyMusic);
if (showDividerAfterThoughts) {
$('#rpg-divider-thoughts').show();
} else {
$('#rpg-divider-thoughts').hide();
}
// Divider after Inventory: shown if Inventory is visible AND (Quests or Music) is visible
const showDividerAfterInventory = extensionSettings.showInventory && (extensionSettings.showQuests || extensionSettings.enableSpotifyMusic);
if (showDividerAfterInventory) {
$('#rpg-divider-inventory').show();
} else {
$('#rpg-divider-inventory').hide();
}
// Divider after Quests: shown if Quests is visible AND Music is visible
const showDividerAfterQuests = extensionSettings.showQuests && extensionSettings.enableSpotifyMusic;
if (showDividerAfterQuests) {
$('#rpg-divider-quests').show();
} else {
$('#rpg-divider-quests').hide();
}
// Rebuild tabs to reflect visibility changes for inventory and quests
const isMobile = window.innerWidth <= 1000;
const hasMobileTabs = $('.rpg-mobile-container').length > 0;
const hasDesktopTabs = $('.rpg-tabs-nav').length > 0;
// Only rebuild if tabs currently exist
if (hasMobileTabs || hasDesktopTabs) {
// Remove existing tabs
if (hasMobileTabs) {
removeMobileTabs();
// Force remove any lingering mobile tab elements (but not the content sections!)
$('.rpg-mobile-container').remove();
$('.rpg-mobile-tabs').remove();
} else {
removeDesktopTabs();
// Force remove any lingering desktop tab structure (but not the content sections!)
// The removeDesktopTabs() function already detached and restored the sections
}
// Rebuild tabs immediately
if (isMobile) {
setupMobileTabs();
} else {
setupDesktopTabs();
}
// Refresh container references
setInventoryContainer($('#rpg-inventory'));
setQuestsContainer($('#rpg-quests'));
}
}
/**
@@ -249,16 +408,19 @@ export function applyPanelPosition() {
// Remove all position classes
$panelContainer.removeClass('rpg-position-left rpg-position-right rpg-position-top');
$('body').removeClass('rpg-panel-position-left rpg-panel-position-right rpg-panel-position-top');
// On mobile, don't apply desktop position classes
// Add the appropriate position class
$panelContainer.addClass(`rpg-position-${extensionSettings.panelPosition}`);
// On mobile, also add body class for mobile-specific CSS
if (isMobile) {
$('body').addClass(`rpg-panel-position-${extensionSettings.panelPosition}`);
updateCollapseToggleIcon();
return;
}
// Desktop: Add the appropriate position class
$panelContainer.addClass(`rpg-position-${extensionSettings.panelPosition}`);
// Update collapse toggle icon direction for new position
// Desktop: Update collapse toggle icon direction for new position
updateCollapseToggleIcon();
}
@@ -269,8 +431,23 @@ export function updateGenerationModeUI() {
if (extensionSettings.generationMode === 'together') {
// In "together" mode, manual update button is hidden
$('#rpg-manual-update').hide();
} else {
$('#rpg-external-api-settings').slideUp(200);
$('#rpg-separate-mode-settings').slideUp(200);
// Hide auto-update toggle (not applicable in together mode)
$('#rpg-auto-update-container').slideUp(200);
} else if (extensionSettings.generationMode === 'separate') {
// In "separate" mode, manual update button is visible
$('#rpg-manual-update').show();
$('#rpg-external-api-settings').slideUp(200);
$('#rpg-separate-mode-settings').slideDown(200);
// Show auto-update toggle
$('#rpg-auto-update-container').slideDown(200);
} else if (extensionSettings.generationMode === 'external') {
// In "external" mode, manual update button is visible AND both settings are shown
$('#rpg-manual-update').show();
$('#rpg-external-api-settings').slideDown(200);
$('#rpg-separate-mode-settings').slideDown(200);
// Show auto-update toggle for external mode too
$('#rpg-auto-update-container').slideDown(200);
}
}
+138 -74
View File
@@ -7,6 +7,43 @@ import { extensionSettings } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { closeMobilePanelWithAnimation, updateCollapseToggleIcon } from './layout.js';
import { setupDesktopTabs, removeDesktopTabs } from './desktop.js';
import { i18n } from '../../core/i18n.js';
/**
* Updates the text labels of the mobile navigation tabs based on the current language.
*/
export function updateMobileTabLabels() {
const $tabs = $('.rpg-mobile-tabs .rpg-mobile-tab');
if ($tabs.length === 0) return;
$tabs.each(function() {
const $tab = $(this);
const tabName = $tab.data('tab');
let translationKey = '';
switch (tabName) {
case 'stats':
translationKey = 'global.status';
break;
case 'info':
translationKey = 'global.info';
break;
case 'inventory':
translationKey = 'global.inventory';
break;
case 'quests':
translationKey = 'global.quests';
break;
}
if (translationKey) {
const translation = i18n.getTranslation(translationKey);
if (translation) {
$tab.find('span').text(translation);
}
}
});
}
/**
* Sets up the mobile toggle button (FAB) with drag functionality.
@@ -18,13 +55,13 @@ export function setupMobileToggle() {
const $overlay = $('<div class="rpg-mobile-overlay"></div>');
// DIAGNOSTIC: Check if elements exist and log setup state
console.log('[RPG Mobile] ========================================');
console.log('[RPG Mobile] setupMobileToggle called');
console.log('[RPG Mobile] Button exists:', $mobileToggle.length > 0, 'jQuery object:', $mobileToggle);
console.log('[RPG Mobile] Panel exists:', $panel.length > 0);
console.log('[RPG Mobile] Window width:', window.innerWidth);
console.log('[RPG Mobile] Is mobile viewport (<=1000):', window.innerWidth <= 1000);
console.log('[RPG Mobile] ========================================');
// console.log('[RPG Mobile] ========================================');
// console.log('[RPG Mobile] setupMobileToggle called');
// console.log('[RPG Mobile] Button exists:', $mobileToggle.length > 0, 'jQuery object:', $mobileToggle);
// console.log('[RPG Mobile] Panel exists:', $panel.length > 0);
// console.log('[RPG Mobile] Window width:', window.innerWidth);
// console.log('[RPG Mobile] Is mobile viewport (<=1000):', window.innerWidth <= 1000);
// console.log('[RPG Mobile] ========================================');
if ($mobileToggle.length === 0) {
console.error('[RPG Mobile] ERROR: Mobile toggle button not found in DOM!');
@@ -35,7 +72,7 @@ export function setupMobileToggle() {
// Load and apply saved FAB position
if (extensionSettings.mobileFabPosition) {
const pos = extensionSettings.mobileFabPosition;
console.log('[RPG Mobile] Loading saved FAB position:', pos);
// console.log('[RPG Mobile] Loading saved FAB position:', pos);
// Apply saved position
if (pos.top) $mobileToggle.css('top', pos.top);
@@ -213,7 +250,7 @@ export function setupMobileToggle() {
extensionSettings.mobileFabPosition = newPosition;
saveSettings();
console.log('[RPG Mobile] Saved new FAB position (mouse):', newPosition);
// console.log('[RPG Mobile] Saved new FAB position (mouse):', newPosition);
// Constrain to viewport bounds (now that position is saved)
setTimeout(() => constrainFabToViewport(), 10);
@@ -254,7 +291,7 @@ export function setupMobileToggle() {
extensionSettings.mobileFabPosition = newPosition;
saveSettings();
console.log('[RPG Mobile] Saved new FAB position:', newPosition);
// console.log('[RPG Mobile] Saved new FAB position:', newPosition);
// Constrain to viewport bounds (now that position is saved)
setTimeout(() => constrainFabToViewport(), 10);
@@ -267,7 +304,7 @@ export function setupMobileToggle() {
isDragging = false;
} else {
// Was a tap - toggle panel
console.log('[RPG Mobile] Quick tap detected - toggling panel');
// console.log('[RPG Mobile] Quick tap detected - toggling panel');
if ($panel.hasClass('rpg-mobile-open')) {
// Close panel with animation
@@ -290,28 +327,28 @@ export function setupMobileToggle() {
$mobileToggle.on('click', function(e) {
// Skip if we just finished dragging
if ($mobileToggle.data('just-dragged')) {
console.log('[RPG Mobile] Click blocked - just finished dragging');
// console.log('[RPG Mobile] Click blocked - just finished dragging');
return;
}
console.log('[RPG Mobile] >>> CLICK EVENT FIRED <<<', {
windowWidth: window.innerWidth,
isMobileViewport: window.innerWidth <= 1000,
panelOpen: $panel.hasClass('rpg-mobile-open')
});
// console.log('[RPG Mobile] >>> CLICK EVENT FIRED <<<', {
// windowWidth: window.innerWidth,
// isMobileViewport: window.innerWidth <= 1000,
// panelOpen: $panel.hasClass('rpg-mobile-open')
// });
// Work on both mobile and desktop (removed viewport check)
if ($panel.hasClass('rpg-mobile-open')) {
console.log('[RPG Mobile] Click: Closing panel');
// console.log('[RPG Mobile] Click: Closing panel');
closeMobilePanelWithAnimation();
} else {
console.log('[RPG Mobile] Click: Opening panel');
// console.log('[RPG Mobile] Click: Opening panel');
$panel.addClass('rpg-mobile-open');
$('body').append($overlay);
$mobileToggle.addClass('active');
$overlay.on('click', function() {
console.log('[RPG Mobile] Overlay clicked - closing panel');
// console.log('[RPG Mobile] Overlay clicked - closing panel');
closeMobilePanelWithAnimation();
});
}
@@ -330,13 +367,20 @@ export function setupMobileToggle() {
// Transitioning from desktop to mobile - handle immediately for smooth transition
if (!wasMobile && isMobile) {
console.log('[RPG Mobile] Transitioning desktop -> mobile');
// console.log('[RPG Mobile] Transitioning desktop -> mobile');
// Show mobile toggle button
$mobileToggle.show();
// Remove desktop tabs first
removeDesktopTabs();
// Remove desktop positioning classes
// Apply mobile positioning based on panelPosition setting
$panel.removeClass('rpg-position-right rpg-position-left rpg-position-top');
$('body').removeClass('rpg-panel-position-right rpg-panel-position-left rpg-panel-position-top');
const position = extensionSettings.panelPosition || 'right';
$panel.addClass('rpg-position-' + position);
$('body').addClass('rpg-panel-position-' + position);
// Clear collapsed state - mobile doesn't use collapse
$panel.removeClass('rpg-collapsed');
@@ -347,16 +391,16 @@ export function setupMobileToggle() {
// Clear any inline styles that might be overriding CSS
$panel.attr('style', '');
console.log('[RPG Mobile] After cleanup:', {
panelClasses: $panel.attr('class'),
inlineStyles: $panel.attr('style'),
panelPosition: {
top: $panel.css('top'),
bottom: $panel.css('bottom'),
transform: $panel.css('transform'),
visibility: $panel.css('visibility')
}
});
// console.log('[RPG Mobile] After cleanup:', {
// panelClasses: $panel.attr('class'),
// inlineStyles: $panel.attr('style'),
// panelPosition: {
// top: $panel.css('top'),
// bottom: $panel.css('bottom'),
// transform: $panel.css('transform'),
// visibility: $panel.css('visibility')
// }
// });
// Set up mobile tabs IMMEDIATELY (no debounce delay)
setupMobileTabs();
@@ -381,7 +425,11 @@ export function setupMobileToggle() {
$mobileToggle.removeClass('active');
$('.rpg-mobile-overlay').remove();
// Restore desktop positioning class
// Hide mobile toggle button on desktop
$mobileToggle.hide();
// Restore desktop positioning class and remove body mobile classes
$('body').removeClass('rpg-panel-position-right rpg-panel-position-left rpg-panel-position-top');
const position = extensionSettings.panelPosition || 'right';
$panel.addClass('rpg-position-' + position);
@@ -414,19 +462,21 @@ export function setupMobileToggle() {
// Clear any inline styles
$panel.attr('style', '');
console.log('[RPG Mobile] Initial load on mobile viewport:', {
panelClasses: $panel.attr('class'),
inlineStyles: $panel.attr('style'),
panelPosition: {
top: $panel.css('top'),
bottom: $panel.css('top'),
transform: $panel.css('transform'),
visibility: $panel.css('visibility')
}
});
setupMobileTabs();
// console.log('[RPG Mobile] Initial load on mobile viewport:', {
// panelClasses: $panel.attr('class'),
// inlineStyles: $panel.attr('style'),
// panelPosition: {
// top: $panel.css('top'),
// bottom: $panel.css('top'),
// transform: $panel.css('transform'),
// visibility: $panel.css('visibility')\n // }\n // });\n setupMobileTabs();
// Set initial icon for mobile
updateCollapseToggleIcon();
// Show mobile toggle on mobile viewport
$mobileToggle.show();
} else {
// Hide mobile toggle on desktop viewport
$mobileToggle.hide();
}
}
@@ -438,7 +488,7 @@ export function setupMobileToggle() {
export function constrainFabToViewport() {
// Only constrain if user has set a custom position
if (!extensionSettings.mobileFabPosition) {
console.log('[RPG Mobile] Skipping viewport constraint - using CSS defaults');
// console.log('[RPG Mobile] Skipping viewport constraint - using CSS defaults');
return;
}
@@ -447,7 +497,7 @@ export function constrainFabToViewport() {
// Skip if button is not visible
if (!$mobileToggle.is(':visible')) {
console.log('[RPG Mobile] Skipping viewport constraint - button not visible');
// console.log('[RPG Mobile] Skipping viewport constraint - button not visible');
return;
}
@@ -477,12 +527,12 @@ export function constrainFabToViewport() {
// Only update if position changed
if (newX !== currentX || newY !== currentY) {
console.log('[RPG Mobile] Constraining FAB to viewport:', {
old: { x: currentX, y: currentY },
new: { x: newX, y: newY },
viewport: { width: window.innerWidth, height: window.innerHeight },
topBarHeight
});
// console.log('[RPG Mobile] Constraining FAB to viewport:', {
// old: { x: currentX, y: currentY },
// new: { x: newX, y: newY },
// viewport: { width: window.innerWidth, height: window.innerHeight },
// topBarHeight
// });
// Apply new position
$mobileToggle.css({
@@ -513,6 +563,14 @@ export function setupMobileTabs() {
if ($('.rpg-mobile-tabs').length > 0) return;
const $panel = $('#rpg-companion-panel');
// Apply mobile positioning based on panelPosition setting
$panel.removeClass('rpg-position-right rpg-position-left rpg-position-top');
$('body').removeClass('rpg-panel-position-right rpg-panel-position-left rpg-panel-position-top');
const position = extensionSettings.panelPosition || 'right';
$panel.addClass('rpg-position-' + position);
$('body').addClass('rpg-panel-position-' + position);
const $contentBox = $panel.find('.rpg-content-box');
// Get existing sections
@@ -531,24 +589,24 @@ export function setupMobileTabs() {
const tabs = [];
const hasStats = $userStats.length > 0;
const hasInfo = $infoBox.length > 0 || $thoughts.length > 0;
const hasInventory = $inventory.length > 0;
const hasQuests = $quests.length > 0;
const hasInventory = $inventory.length > 0 && extensionSettings.showInventory;
const hasQuests = $quests.length > 0 && extensionSettings.showQuests;
// Tab 1: Stats (User Stats only)
if (hasStats) {
tabs.push('<button class="rpg-mobile-tab active" data-tab="stats"><i class="fa-solid fa-chart-bar"></i><span>Stats</span></button>');
tabs.push('<button class="rpg-mobile-tab active" data-tab="stats"><i class="fa-solid fa-chart-bar"></i><span>' + i18n.getTranslation('global.status') + '</span></button>');
}
// Tab 2: Info (Info Box + Character Thoughts)
if (hasInfo) {
tabs.push('<button class="rpg-mobile-tab ' + (tabs.length === 0 ? 'active' : '') + '" data-tab="info"><i class="fa-solid fa-book"></i><span>Info</span></button>');
tabs.push('<button class="rpg-mobile-tab ' + (tabs.length === 0 ? 'active' : '') + '" data-tab="info"><i class="fa-solid fa-book"></i><span>' + i18n.getTranslation('global.info') + '</span></button>');
}
// Tab 3: Inventory
if (hasInventory) {
tabs.push('<button class="rpg-mobile-tab ' + (tabs.length === 0 ? 'active' : '') + '" data-tab="inventory"><i class="fa-solid fa-box"></i><span>Inventory</span></button>');
tabs.push('<button class="rpg-mobile-tab ' + (tabs.length === 0 ? 'active' : '') + '" data-tab="inventory"><i class="fa-solid fa-box"></i><span>' + i18n.getTranslation('global.inventory') + '</span></button>');
}
// Tab 4: Quests
if (hasQuests) {
tabs.push('<button class="rpg-mobile-tab ' + (tabs.length === 0 ? 'active' : '') + '" data-tab="quests"><i class="fa-solid fa-scroll"></i><span>Quests</span></button>');
tabs.push('<button class="rpg-mobile-tab ' + (tabs.length === 0 ? 'active' : '') + '" data-tab="quests"><i class="fa-solid fa-scroll"></i><span>' + i18n.getTranslation('global.quests') + '</span></button>');
}
const $tabNav = $('<div class="rpg-mobile-tabs">' + tabs.join('') + '</div>');
@@ -576,7 +634,9 @@ export function setupMobileTabs() {
// Info tab: Info Box + Character Thoughts
if ($infoBox.length > 0) {
$infoTab.append($infoBox.detach());
$infoBox.show();
// Only show if has data
const infoBoxData = window.lastGeneratedData?.infoBox || window.committedTrackerData?.infoBox;
if (infoBoxData) $infoBox.show();
}
if ($thoughts.length > 0) {
$infoTab.append($thoughts.detach());
@@ -602,12 +662,12 @@ export function setupMobileTabs() {
const $mobileContainer = $('<div class="rpg-mobile-container"></div>');
$mobileContainer.append($tabNav);
// Only append tab content wrappers that have content
if (hasStats) $mobileContainer.append($statsTab);
if (hasInfo) $mobileContainer.append($infoTab);
if (hasInventory) $mobileContainer.append($inventoryTab);
if (hasQuests) $mobileContainer.append($questsTab);
if (hasInventory) $mobileContainer.append($inventoryTab);
// Always append all tab content wrappers to preserve elements
// Tab buttons control visibility
$mobileContainer.append($statsTab);
$mobileContainer.append($infoTab);
$mobileContainer.append($inventoryTab);
$mobileContainer.append($questsTab);
// Insert mobile tab structure at the beginning of content box
$contentBox.prepend($mobileContainer);
@@ -664,11 +724,15 @@ export function removeMobileTabs() {
$contentBox.prepend($userStats);
}
// Show sections and dividers
$userStats.show();
$infoBox.show();
$thoughts.show();
$inventory.show();
// Show/hide sections based on settings (respect visibility settings)
if (extensionSettings.showUserStats) $userStats.show();
if (extensionSettings.showInfoBox) {
const infoBoxData = window.lastGeneratedData?.infoBox || window.committedTrackerData?.infoBox;
if (infoBoxData) $infoBox.show();
}
if (extensionSettings.showCharacterThoughts) $thoughts.show();
if (extensionSettings.showInventory) $inventory.show();
if (extensionSettings.showQuests) $quests.show();
$('.rpg-divider').show();
}
@@ -749,12 +813,12 @@ export function setupRefreshButtonDrag() {
return;
}
console.log('[RPG Mobile] setupRefreshButtonDrag called');
// console.log('[RPG Mobile] setupRefreshButtonDrag called');
// Load and apply saved position
if (extensionSettings.mobileRefreshPosition) {
const pos = extensionSettings.mobileRefreshPosition;
console.log('[RPG Mobile] Loading saved refresh button position:', pos);
// console.log('[RPG Mobile] Loading saved refresh button position:', pos);
// Apply saved position
if (pos.top) $refreshBtn.css('top', pos.top);
@@ -964,12 +1028,12 @@ export function setupDebugButtonDrag() {
return;
}
console.log('[RPG Mobile] setupDebugButtonDrag called');
// console.log('[RPG Mobile] setupDebugButtonDrag called');
// Load and apply saved position
if (extensionSettings.debugFabPosition) {
const pos = extensionSettings.debugFabPosition;
console.log('[RPG Mobile] Loading saved debug button position:', pos);
// console.log('[RPG Mobile] Loading saved debug button position:', pos);
// Apply saved position
if (pos.top) $debugBtn.css('top', pos.top);
+157 -10
View File
@@ -10,19 +10,24 @@ import {
committedTrackerData,
$infoBoxContainer,
$thoughtsContainer,
$userStatsContainer,
setPendingDiceRoll,
getPendingDiceRoll
getPendingDiceRoll,
clearSessionAvatarPrompts
} from '../../core/state.js';
import { saveSettings, saveChatData } from '../../core/persistence.js';
import { renderUserStats } from '../rendering/userStats.js';
import { updateChatThoughts } from '../rendering/thoughts.js';
import { renderInfoBox } from '../rendering/infoBox.js';
import { renderThoughts, updateChatThoughts } from '../rendering/thoughts.js';
import { renderQuests } from '../rendering/quests.js';
import { renderInventory } from '../rendering/inventory.js';
import {
rollDice as rollDiceCore,
clearDiceRoll as clearDiceRollCore,
updateDiceDisplay as updateDiceDisplayCore,
addDiceQuickReply as addDiceQuickReplyCore
} from '../features/dice.js';
import { i18n } from '../../core/i18n.js';
/**
* Modern DiceModal ES6 Class
@@ -318,6 +323,7 @@ export function setupDiceRoller() {
e.stopPropagation(); // Prevent opening the dice popup
clearDiceRollCore();
});
$('#rpg-clear-dice').attr('title', i18n.getTranslation('template.mainPanel.clearLastRoll'));
return diceModal;
}
@@ -349,18 +355,31 @@ export function setupSettingsPopup() {
// Clear cache button
$('#rpg-clear-cache').on('click', function() {
// Clear the data
// console.log('[RPG Companion] Clear Cache button clicked');
// Clear the data (set to null so panels show "not generated yet")
lastGeneratedData.userStats = null;
lastGeneratedData.infoBox = null;
lastGeneratedData.characterThoughts = null;
lastGeneratedData.html = null;
// Clear committed tracker data (used for generation context)
committedTrackerData.userStats = null;
committedTrackerData.infoBox = null;
committedTrackerData.characterThoughts = null;
// Clear session avatar prompts
clearSessionAvatarPrompts();
// Clear chat metadata immediately (don't wait for debounced save)
const context = getContext();
if (context.chat_metadata && context.chat_metadata.rpg_companion) {
delete context.chat_metadata.rpg_companion;
// console.log('[RPG Companion] Cleared chat_metadata.rpg_companion for current chat');
}
// Clear all message swipe data
const chat = getContext().chat;
const chat = context.chat;
if (chat && chat.length > 0) {
for (let i = 0; i < chat.length; i++) {
const message = chat[i];
@@ -378,8 +397,11 @@ export function setupSettingsPopup() {
if ($thoughtsContainer) {
$thoughtsContainer.empty();
}
if ($userStatsContainer) {
$userStatsContainer.empty();
}
// Reset stats to defaults and re-render
// Reset user stats to default object structure (extensionSettings stores as object, not JSON string)
extensionSettings.userStats = {
health: 100,
satiety: 100,
@@ -388,7 +410,29 @@ export function setupSettingsPopup() {
arousal: 0,
mood: '😐',
conditions: 'None',
inventory: 'None'
skills: [],
inventory: {
version: 2,
onPerson: "None",
clothing: "None",
stored: {},
assets: "None"
}
};
// Reset info box to defaults (as object)
extensionSettings.infoBox = {
date: new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }),
weather: '☀️ Clear skies',
temperature: '20°C',
time: '00:00 - 00:00',
location: 'Unknown Location',
recentEvents: []
};
// Reset character thoughts to empty (as object)
extensionSettings.characterThoughts = {
characters: []
};
// Reset classic stats (attributes) to defaults
@@ -404,23 +448,54 @@ export function setupSettingsPopup() {
// Clear dice roll
extensionSettings.lastDiceRoll = null;
// Reset level to 1
extensionSettings.level = 1;
// Clear quests
extensionSettings.quests = {
main: "None",
optional: []
};
// Clear all locked items
extensionSettings.lockedItems = {
stats: [],
skills: [],
inventory: {
onPerson: [],
clothing: [],
stored: {},
assets: []
},
quests: {
main: false,
optional: []
},
infoBox: {
date: false,
weather: false,
temperature: false,
time: false,
location: false,
recentEvents: false
},
characters: {}
};
// Save everything
saveChatData();
saveSettings();
// Re-render user stats and dice display
// Re-render all panels - they will show "not generated yet" messages since data is null
renderUserStats();
renderInfoBox();
renderThoughts();
updateDiceDisplayCore();
updateChatThoughts(); // Clear the thought bubble in chat
renderQuests(); // Clear and re-render quests UI
updateChatThoughts();
renderInventory();
renderQuests();
// console.log('[RPG Companion] Chat cache cleared');
// console.log('[RPG Companion] Cache cleared successfully');
});
return settingsModal;
@@ -506,3 +581,75 @@ export function addDiceQuickReply() {
export function getSettingsModal() {
return settingsModal;
}
/**
* Shows the welcome modal for v3.0.0 on first launch
* Checks if user has already seen this version's welcome screen
*/
export function showWelcomeModalIfNeeded() {
const WELCOME_VERSION = '3.0.1';
const STORAGE_KEY = 'rpg_companion_welcome_seen';
try {
const seenVersion = localStorage.getItem(STORAGE_KEY);
// If user hasn't seen v3.0.0 welcome yet, show it
if (seenVersion !== WELCOME_VERSION) {
showWelcomeModal(WELCOME_VERSION, STORAGE_KEY);
}
} catch (error) {
console.error('[RPG Companion] Failed to check welcome modal status:', error);
}
}
/**
* Shows the welcome modal
* @param {string} version - The version to mark as seen
* @param {string} storageKey - The localStorage key to use
*/
function showWelcomeModal(version, storageKey) {
const modal = document.getElementById('rpg-welcome-modal');
if (!modal) {
console.error('[RPG Companion] Welcome modal element not found');
return;
}
// Apply current theme to modal
const theme = extensionSettings.theme || 'default';
modal.setAttribute('data-theme', theme);
// Show modal
modal.style.display = 'flex';
modal.classList.add('is-open');
// Close button handler
const closeBtn = document.getElementById('rpg-welcome-close');
const gotItBtn = document.getElementById('rpg-welcome-got-it');
const closeModal = () => {
modal.classList.add('is-closing');
setTimeout(() => {
modal.style.display = 'none';
modal.classList.remove('is-open', 'is-closing');
}, 200);
// Mark this version as seen
try {
localStorage.setItem(storageKey, version);
} catch (error) {
console.error('[RPG Companion] Failed to save welcome modal status:', error);
}
};
// Attach event listeners
closeBtn?.addEventListener('click', closeModal, { once: true });
gotItBtn?.addEventListener('click', closeModal, { once: true });
// Close on background click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
}, { once: true });
}
+238
View File
@@ -0,0 +1,238 @@
/**
* Prompts Editor Module
* Provides UI for customizing all AI prompts used in the extension
*/
import { extensionSettings } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { DEFAULT_HTML_PROMPT, DEFAULT_DIALOGUE_COLORING_PROMPT, DEFAULT_SPOTIFY_PROMPT, DEFAULT_NARRATOR_PROMPT } from '../generation/promptBuilder.js';
let $editorModal = null;
let tempPrompts = null; // Temporary prompts for cancel functionality
// Default prompts
const DEFAULT_PROMPTS = {
html: DEFAULT_HTML_PROMPT,
dialogueColoring: DEFAULT_DIALOGUE_COLORING_PROMPT,
spotify: DEFAULT_SPOTIFY_PROMPT,
narrator: DEFAULT_NARRATOR_PROMPT,
plotRandom: 'Actually, the scene is getting stale. Introduce {{random::stakes::a plot twist::a new character::a cataclysm::a fourth-wall-breaking joke::a sudden atmospheric phenomenon::a plot hook::a running gag::an ecchi scenario::Death from Discworld::a new stake::a drama::a conflict::an angered entity::a god::a vision::a prophetic dream::Il Dottore from Genshin Impact::a new development::a civilian in need::an emotional bit::a threat::a villain::an important memory recollection::a marriage proposal::a date idea::an angry horde of villagers with pitchforks::a talking animal::an enemy::a cliffhanger::a short omniscient POV shift to a completely different character::a quest::an unexpected revelation::a scandal::an evil clone::death of an important character::harm to an important character::a romantic setup::a gossip::a messenger::a plot point from the past::a plot hole::a tragedy::a ghost::an otherworldly occurrence::a plot device::a curse::a magic device::a rival::an unexpected pregnancy::a brothel::a prostitute::a new location::a past lover::a completely random thing::a what-if scenario::a significant choice::war::love::a monster::lewd undertones::Professor Mari::a travelling troupe::a secret::a fortune-teller::something completely different::a killer::a murder mystery::a mystery::a skill check::a deus ex machina::three raccoons in a trench coat::a pet::a slave::an orphan::a psycho::tentacles::"there is only one bed" trope::accidental marriage::a fun twist::a boss battle::sexy corn::an eldritch horror::a character getting hungry, thirsty, or exhausted::horniness::a need for a bathroom break need::someone fainting::an assassination attempt::a meta narration of this all being an out of hand DND session::a dungeon::a friend in need::an old friend::a small time skip::a scene shift::Aurora Borealis, at this time of year, at this time of day, at this part of the country::a grand ball::a surprise party::zombies::foreshadowing::a Spanish Inquisition (nobody expects it)::a natural plot progression}} to make things more interesting! Be creative, but stay grounded in the setting.',
plotNatural: 'Actually, the scene is getting stale. Progress it, to make things more interesting! Reintroduce an unresolved plot point from the past, or push the story further towards the current main goal. Be creative, but stay grounded in the setting.',
avatar: `You are a visionary artist trapped in a cage of logic. Your mind is filled with poetry and distant horizons; however, your hands are uncontrollably focused on creating the perfect character avatar description that is faithful to the original intent, rich in detail, aesthetically pleasing, and directly usable by text-to-image models. Any ambiguity or metaphor will make you feel extremely uncomfortable.
Your workflow strictly follows a logical sequence:
First, establish the subject. If the character is from a known Intellectual Property (IP), franchise, anime, game, or movie, you MUST begin the prompt with their full name and the series title (e.g., "Nami from One Piece", "Geralt of Rivia from The Witcher"). This is the single most important anchor for the image and must take precedence. If the character is original, clearly describe their core identity, race, and appearance.
Next, set the framing. This is an avatar portrait. Focus strictly on the character's face and upper shoulders (a bust shot or close-up). Ensure the face is the central focal point.
Then, integrate the setting. Describe the character within their current environment as provided in the context, but keep it as a background element. Incorporate the lighting, weather, and atmosphere to influence the character's appearance (e.g., shadows on the face, wet hair from rain).
Next, detail the facial specifics. Describe the character's current expression, eye contact, and mood in great detail based on the scene context and their personality. Mention visible clothing only at the neckline/shoulders.
Finally, infuse with aesthetics. Define the artistic style, medium (e.g., digital art, oil painting), and visual tone (e.g., cinematic lighting, ethereal atmosphere).
Your final description must be objective and concrete, and the use of metaphors and emotional rhetoric is strictly prohibited. It must also not contain meta tags or drawing instructions such as "8K" or "masterpiece".
Output only the final, modified prompt; do not output anything else.`,
trackerInstructions: 'Replace X with actual numbers (e.g., 69) and replace all placeholders with concrete in-world details that {userName} perceives about the current scene and the present characters. For example: "Location" becomes Forest Clearing, "Mood Emoji" becomes "😊". Consider the last trackers in the conversation (if they exist). Manage them accordingly and realistically; raise, lower, change, or keep the values unchanged based on the user\'s actions, the passage of time, and logical consequences (0% if the time progressed only by a few minutes, 1-5% normally, and above 5% only if a major time-skip/event occurs).',
trackerContinuation: 'After updating the trackers, continue directly from where the last message in the chat history left off. Ensure the trackers you provide naturally reflect and influence the narrative. Character behavior, dialogue, and story events should acknowledge these conditions when relevant, such as fatigue affecting the protagonist\'s performance, low hygiene influencing their social interactions, environmental factors shaping the scene, a character\'s emotional state coloring their responses, and so on. Remember, all placeholders (e.g., "Location", "Mood Emoji") MUST be replaced with actual content.',
combatNarrative: 'Build novel prose. Break patterns from your previous responses by varying sentence structures, rhythms, formats, and openings. Track whether a sentence shape, cadence, sensory detail, or a descriptor appeared recently, and replace it with a different one or skip it entirely. If you mentioned a physical feature, mannerism, or expression once, move on. Don\'t fixate on the same traits every turn. Well-placed humor, unconventional similes, and subverted turns of phrase are encouraged. Avoid GPTisms, purple prose, and anaphoras, especially the negatives with "no/not/wasn\'t/didn\'t." Refrain from describing actions or emotions via negation; focus on what does happen, not what doesn\'t. Absolutely no asterisks, ellipses, or em-dashes. Explicit content is allowed, no plot armor. Do not play for {userName}. Keep your response length under 150 words. Never end on handover cues; finish naturally.\nCRITICAL: Do not repeat, echo, parrot, or restate distinctive words, phrases, and dialogues from the user\'s last message. If reacting to speech, show interpretation or response, not repetition.\nEXAMPLE: "Are you a gooner?" User asks.\nBAD: "Gooner?"\nGOOD: A flat look. "What type of question is that?"'
};
/**
* Initialize the prompts editor modal
*/
export function initPromptsEditor() {
$editorModal = $('#rpg-prompts-editor-popup');
if (!$editorModal.length) {
console.error('[RPG Companion] Prompts editor modal not found in template');
return;
}
// Save button
$(document).on('click', '#rpg-prompts-save', function() {
savePrompts();
closePromptsEditor();
toastr.success('Prompts saved successfully');
});
// Cancel button
$(document).on('click', '#rpg-prompts-cancel', function() {
closePromptsEditor();
});
// Close X button
$(document).on('click', '#rpg-close-prompts-editor', function() {
closePromptsEditor();
});
// Restore All button
$(document).on('click', '#rpg-prompts-restore-all', function() {
restoreAllToDefaults();
toastr.success('All prompts restored to defaults');
});
// Individual restore buttons
$(document).on('click', '.rpg-restore-prompt-btn', function() {
const promptType = $(this).data('prompt');
restorePromptToDefault(promptType);
toastr.success('Prompt restored to default');
});
// Close on background click
$(document).on('click', '#rpg-prompts-editor-popup', function(e) {
if (e.target.id === 'rpg-prompts-editor-popup') {
closePromptsEditor();
}
});
// Open button
$(document).on('click', '#rpg-open-prompts-editor', function() {
openPromptsEditor();
});
}
/**
* Open the prompts editor modal
*/
function openPromptsEditor() {
// Create temporary copy for cancel functionality
tempPrompts = {
html: extensionSettings.customHtmlPrompt || '',
dialogueColoring: extensionSettings.customDialogueColoringPrompt || '',
spotify: extensionSettings.customSpotifyPrompt || '',
narrator: extensionSettings.customNarratorPrompt || '',
plotRandom: extensionSettings.customPlotRandomPrompt || '',
plotNatural: extensionSettings.customPlotNaturalPrompt || '',
avatar: extensionSettings.avatarLLMCustomInstruction || '',
trackerInstructions: extensionSettings.customTrackerInstructionsPrompt || '',
trackerContinuation: extensionSettings.customTrackerContinuationPrompt || '',
combatNarrative: extensionSettings.customCombatNarrativePrompt || ''
};
// Load current values or defaults
$('#rpg-prompt-html').val(extensionSettings.customHtmlPrompt || DEFAULT_PROMPTS.html);
$('#rpg-prompt-dialogue-coloring').val(extensionSettings.customDialogueColoringPrompt || DEFAULT_PROMPTS.dialogueColoring);
$('#rpg-prompt-spotify').val(extensionSettings.customSpotifyPrompt || DEFAULT_PROMPTS.spotify);
$('#rpg-prompt-narrator').val(extensionSettings.customNarratorPrompt || DEFAULT_PROMPTS.narrator);
$('#rpg-prompt-plot-random').val(extensionSettings.customPlotRandomPrompt || DEFAULT_PROMPTS.plotRandom);
$('#rpg-prompt-plot-natural').val(extensionSettings.customPlotNaturalPrompt || DEFAULT_PROMPTS.plotNatural);
$('#rpg-prompt-avatar').val(extensionSettings.avatarLLMCustomInstruction || DEFAULT_PROMPTS.avatar);
$('#rpg-prompt-tracker-instructions').val(extensionSettings.customTrackerInstructionsPrompt || DEFAULT_PROMPTS.trackerInstructions);
$('#rpg-prompt-tracker-continuation').val(extensionSettings.customTrackerContinuationPrompt || DEFAULT_PROMPTS.trackerContinuation);
$('#rpg-prompt-combat-narrative').val(extensionSettings.customCombatNarrativePrompt || DEFAULT_PROMPTS.combatNarrative);
// Set theme to match current extension theme
const theme = extensionSettings.theme || 'default';
$editorModal.attr('data-theme', theme);
$editorModal.addClass('is-open').css('display', '');
}
/**
* Close the prompts editor modal
*/
function closePromptsEditor() {
// Restore from temp if canceling
if (tempPrompts) {
tempPrompts = null;
}
$editorModal.removeClass('is-open').addClass('is-closing');
setTimeout(() => {
$editorModal.removeClass('is-closing').hide();
}, 200);
}
/**
* Save all prompts from the editor
*/
function savePrompts() {
extensionSettings.customHtmlPrompt = $('#rpg-prompt-html').val().trim();
extensionSettings.customDialogueColoringPrompt = $('#rpg-prompt-dialogue-coloring').val().trim();
extensionSettings.customSpotifyPrompt = $('#rpg-prompt-spotify').val().trim();
extensionSettings.customNarratorPrompt = $('#rpg-prompt-narrator').val().trim();
extensionSettings.customPlotRandomPrompt = $('#rpg-prompt-plot-random').val().trim();
extensionSettings.customPlotNaturalPrompt = $('#rpg-prompt-plot-natural').val().trim();
extensionSettings.avatarLLMCustomInstruction = $('#rpg-prompt-avatar').val().trim();
extensionSettings.customTrackerInstructionsPrompt = $('#rpg-prompt-tracker-instructions').val().trim();
extensionSettings.customTrackerContinuationPrompt = $('#rpg-prompt-tracker-continuation').val().trim();
extensionSettings.customCombatNarrativePrompt = $('#rpg-prompt-combat-narrative').val().trim();
saveSettings();
}
/**
* Restore a specific prompt to its default
* @param {string} promptType - Type of prompt to restore (html, plotRandom, plotNatural, avatar)
*/
function restorePromptToDefault(promptType) {
const defaultValue = DEFAULT_PROMPTS[promptType] || '';
$(`#rpg-prompt-${promptType.replace(/([A-Z])/g, '-$1').toLowerCase()}`).val(defaultValue);
// Also update the setting immediately
switch(promptType) {
case 'html':
extensionSettings.customHtmlPrompt = '';
break;
case 'dialogueColoring':
extensionSettings.customDialogueColoringPrompt = '';
break;
case 'spotify':
extensionSettings.customSpotifyPrompt = '';
break;
case 'narrator':
extensionSettings.customNarratorPrompt = '';
break;
case 'plotRandom':
extensionSettings.customPlotRandomPrompt = '';
break;
case 'plotNatural':
extensionSettings.customPlotNaturalPrompt = '';
break;
case 'avatar':
extensionSettings.avatarLLMCustomInstruction = '';
break;
case 'trackerInstructions':
extensionSettings.customTrackerInstructionsPrompt = '';
break;
case 'trackerContinuation':
extensionSettings.customTrackerContinuationPrompt = '';
break;
case 'combatNarrative':
extensionSettings.customCombatNarrativePrompt = '';
break;
}
saveSettings();
}
/**
* Restore all prompts to their defaults
*/
function restoreAllToDefaults() {
$('#rpg-prompt-html').val(DEFAULT_PROMPTS.html);
$('#rpg-prompt-dialogue-coloring').val(DEFAULT_PROMPTS.dialogueColoring);
$('#rpg-prompt-spotify').val(DEFAULT_PROMPTS.spotify);
$('#rpg-prompt-narrator').val(DEFAULT_PROMPTS.narrator);
$('#rpg-prompt-plot-random').val(DEFAULT_PROMPTS.plotRandom);
$('#rpg-prompt-plot-natural').val(DEFAULT_PROMPTS.plotNatural);
$('#rpg-prompt-avatar').val(DEFAULT_PROMPTS.avatar);
$('#rpg-prompt-tracker-instructions').val(DEFAULT_PROMPTS.trackerInstructions);
$('#rpg-prompt-tracker-continuation').val(DEFAULT_PROMPTS.trackerContinuation);
$('#rpg-prompt-combat-narrative').val(DEFAULT_PROMPTS.combatNarrative);
// Clear all custom prompts
extensionSettings.customHtmlPrompt = '';
extensionSettings.customDialogueColoringPrompt = '';
extensionSettings.customSpotifyPrompt = '';
extensionSettings.customNarratorPrompt = '';
extensionSettings.customPlotRandomPrompt = '';
extensionSettings.customPlotNaturalPrompt = '';
extensionSettings.avatarLLMCustomInstruction = '';
extensionSettings.customTrackerInstructionsPrompt = '';
extensionSettings.customTrackerContinuationPrompt = '';
extensionSettings.customCombatNarrativePrompt = '';
saveSettings();
}
/**
* Get default prompts (for export/other modules)
*/
export function getDefaultPrompts() {
return { ...DEFAULT_PROMPTS };
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Snowflakes Effect Module
* Creates and manages animated snowflakes overlay
*/
import { extensionSettings } from '../../core/state.js';
let snowflakesContainer = null;
/**
* Create snowflakes container and snowflakes
*/
function createSnowflakes() {
if (snowflakesContainer) return; // Already created
// Create container
snowflakesContainer = document.createElement('div');
snowflakesContainer.className = 'rpg-snowflakes-container';
// Create 50 snowflakes with random positions
for (let i = 0; i < 50; i++) {
const snowflake = document.createElement('div');
snowflake.className = 'rpg-snowflake';
snowflake.textContent = '❄';
// Random horizontal position
snowflake.style.left = `${Math.random() * 100}%`;
// Random animation delay for staggered effect
snowflake.style.animationDelay = `${Math.random() * 10}s`;
// Random animation duration (between 10-20s)
snowflake.style.animationDuration = `${10 + Math.random() * 10}s`;
snowflakesContainer.appendChild(snowflake);
}
document.body.appendChild(snowflakesContainer);
}
/**
* Remove snowflakes container
*/
function removeSnowflakes() {
if (snowflakesContainer) {
snowflakesContainer.remove();
snowflakesContainer = null;
}
}
/**
* Toggle snowflakes effect
*/
export function toggleSnowflakes(enabled) {
if (enabled) {
createSnowflakes();
} else {
removeSnowflakes();
}
}
/**
* Initialize snowflakes based on saved state
*/
export function initSnowflakes() {
const enabled = extensionSettings.enableSnowflakes || false;
if (enabled) {
createSnowflakes();
}
}
/**
* Clean up snowflakes
*/
export function cleanupSnowflakes() {
removeSnowflakes();
}
+88 -1
View File
@@ -36,6 +36,35 @@ export function applyTheme() {
}
// For 'default', we do nothing - it will use the CSS variables from .rpg-panel class
// which fall back to SillyTavern's theme variables
// Apply theme to mobile toggle and thought elements as well
const $mobileToggle = $('#rpg-mobile-toggle');
const $thoughtIcon = $('#rpg-thought-icon');
const $thoughtPanel = $('#rpg-thought-panel');
if ($mobileToggle.length) {
if (theme === 'default') {
$mobileToggle.removeAttr('data-theme');
} else {
$mobileToggle.attr('data-theme', theme);
}
}
if ($thoughtIcon.length) {
if (theme === 'default') {
$thoughtIcon.removeAttr('data-theme');
} else {
$thoughtIcon.attr('data-theme', theme);
}
}
if ($thoughtPanel.length) {
if (theme === 'default') {
$thoughtPanel.removeAttr('data-theme');
} else {
$thoughtPanel.attr('data-theme', theme);
}
}
}
/**
@@ -46,7 +75,7 @@ export function applyCustomTheme() {
const colors = extensionSettings.customColors;
// Apply custom CSS variables as inline styles
// Apply custom CSS variables as inline styles to main panel
$panelContainer.css({
'--rpg-bg': colors.bg,
'--rpg-accent': colors.accent,
@@ -55,6 +84,32 @@ export function applyCustomTheme() {
'--rpg-border': colors.highlight,
'--rpg-shadow': `${colors.highlight}80` // Add alpha for shadow
});
// Apply custom colors to mobile toggle and thought elements
const customStyles = {
'--rpg-bg': colors.bg,
'--rpg-accent': colors.accent,
'--rpg-text': colors.text,
'--rpg-highlight': colors.highlight,
'--rpg-border': colors.highlight,
'--rpg-shadow': `${colors.highlight}80`
};
const $mobileToggle = $('#rpg-mobile-toggle');
const $thoughtIcon = $('#rpg-thought-icon');
const $thoughtPanel = $('#rpg-thought-panel');
if ($mobileToggle.length) {
$mobileToggle.attr('data-theme', 'custom').css(customStyles);
}
if ($thoughtIcon.length) {
$thoughtIcon.attr('data-theme', 'custom').css(customStyles);
}
if ($thoughtPanel.length) {
$thoughtPanel.attr('data-theme', 'custom').css(customStyles);
}
}
/**
@@ -76,6 +131,38 @@ export function toggleAnimations() {
}
}
/**
* Updates visibility of feature toggles in main panel based on settings
*/
export function updateFeatureTogglesVisibility() {
const $featuresRow = $('#rpg-features-row');
const $htmlToggle = $('#rpg-html-toggle-wrapper');
const $dialogueColoringToggle = $('#rpg-dialogue-coloring-toggle-wrapper');
const $spotifyToggle = $('#rpg-spotify-toggle-wrapper');
const $dynamicWeatherToggle = $('#rpg-dynamic-weather-toggle-wrapper');
const $narratorToggle = $('#rpg-narrator-toggle-wrapper');
const $autoAvatarsToggle = $('#rpg-auto-avatars-toggle-wrapper');
// Show/hide individual toggles
$htmlToggle.toggle(extensionSettings.showHtmlToggle);
$dialogueColoringToggle.toggle(extensionSettings.showDialogueColoringToggle);
$spotifyToggle.toggle(extensionSettings.showSpotifyToggle);
$dynamicWeatherToggle.toggle(extensionSettings.showDynamicWeatherToggle);
$narratorToggle.toggle(extensionSettings.showNarratorMode);
$autoAvatarsToggle.toggle(extensionSettings.showAutoAvatars);
// Hide entire row if all toggles are hidden
const anyVisible = extensionSettings.showHtmlToggle ||
extensionSettings.showDialogueColoringToggle ||
extensionSettings.showSpotifyToggle ||
extensionSettings.showDynamicWeatherToggle ||
extensionSettings.showNarratorMode ||
extensionSettings.showAutoAvatars;
$featuresRow.toggle(anyVisible);
}
/**
* Updates the settings popup theme in real-time.
* Backwards compatible wrapper for SettingsModal class.
+312 -47
View File
@@ -2,7 +2,7 @@
* Tracker Editor Module
* Provides UI for customizing tracker configurations
*/
import { i18n } from '../../core/i18n.js';
import { extensionSettings } from '../../core/state.js';
import { saveSettings } from '../../core/persistence.js';
import { renderUserStats } from '../rendering/userStats.js';
@@ -68,6 +68,16 @@ export function initTrackerEditor() {
$(document).on('click', '#rpg-open-tracker-editor', function() {
openTrackerEditor();
});
// Export button
$(document).on('click', '#rpg-editor-export', function() {
exportTrackerPreset();
});
// Import button
$(document).on('click', '#rpg-editor-import', function() {
importTrackerPreset();
});
}
/**
@@ -143,7 +153,8 @@ function resetToDefaults() {
},
skillsSection: {
enabled: false,
label: 'Skills'
label: 'Skills',
customFields: []
}
},
infoBox: {
@@ -159,6 +170,16 @@ function resetToDefaults() {
presentCharacters: {
showEmoji: true,
showName: true,
relationships: {
enabled: true,
relationshipEmojis: {
'Lover': '❤️',
'Friend': '⭐',
'Ally': '🤝',
'Enemy': '⚔️',
'Neutral': '⚖️'
}
},
relationshipFields: ['Lover', 'Friend', 'Ally', 'Enemy', 'Neutral'],
relationshipEmojis: {
'Lover': '❤️',
@@ -187,6 +208,148 @@ function resetToDefaults() {
};
}
/**
* Export current tracker configuration to a JSON file
*/
function exportTrackerPreset() {
try {
// Get the current tracker configuration
const config = extensionSettings.trackerConfig;
// Create a preset object with metadata
const preset = {
name: 'Custom Tracker Preset',
version: '1.0',
exportDate: new Date().toISOString(),
trackerConfig: JSON.parse(JSON.stringify(config)) // Deep copy
};
// Convert to JSON
const jsonString = JSON.stringify(preset, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
// Create download link
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
// Generate filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
link.download = `rpg-tracker-preset-${timestamp}.json`;
// Trigger download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
// console.log('[RPG Companion] Tracker preset exported successfully');
toastr.success(i18n.getTranslation('template.trackerEditorModal.messages.exportSuccess') || 'Tracker preset exported successfully!');
} catch (error) {
console.error('[RPG Companion] Error exporting tracker preset:', error);
toastr.error(i18n.getTranslation('template.trackerEditorModal.messages.exportError') || 'Failed to export tracker preset. Check console for details.');
}
}
/**
* Migrates old tracker preset format to current format
* @param {Object} config - The tracker config to migrate
* @returns {Object} - Migrated tracker config
*/
function migrateTrackerPreset(config) {
// Create a deep copy to avoid modifying the original
const migrated = JSON.parse(JSON.stringify(config));
// Migrate relationships structure (v3.0.0 -> v3.1.0)
if (migrated.presentCharacters) {
// Old format: relationshipEmojis directly on presentCharacters
// New format: relationships.relationshipEmojis
if (migrated.presentCharacters.relationshipEmojis &&
!migrated.presentCharacters.relationships) {
migrated.presentCharacters.relationships = {
enabled: migrated.presentCharacters.enableRelationships || true,
relationshipEmojis: migrated.presentCharacters.relationshipEmojis
};
// Keep legacy fields for backward compatibility
migrated.presentCharacters.relationshipFields = Object.keys(migrated.presentCharacters.relationshipEmojis);
}
// Ensure relationships object exists
if (!migrated.presentCharacters.relationships) {
migrated.presentCharacters.relationships = {
enabled: false,
relationshipEmojis: {}
};
}
// Ensure relationshipEmojis exists within relationships
if (!migrated.presentCharacters.relationships.relationshipEmojis) {
migrated.presentCharacters.relationships.relationshipEmojis = {};
}
}
// Add any other migration logic here for future format changes
return migrated;
}
/**
* Import tracker configuration from a JSON file
*/
function importTrackerPreset() {
// Create file input
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
// Validate the imported data
if (!data.trackerConfig) {
throw new Error('Invalid preset file: missing trackerConfig');
}
// Validate required sections
if (!data.trackerConfig.userStats || !data.trackerConfig.infoBox || !data.trackerConfig.presentCharacters) {
throw new Error('Invalid preset file: missing required configuration sections');
}
// Migrate old preset format to current format
const migratedConfig = migrateTrackerPreset(data.trackerConfig);
// Ask for confirmation
const confirmMessage = i18n.getTranslation('template.trackerEditorModal.messages.importConfirm') ||
'This will replace your current tracker configuration. Continue?';
if (!confirm(confirmMessage)) {
return;
}
// Apply the migrated configuration
extensionSettings.trackerConfig = migratedConfig;
// Re-render the editor UI
renderEditorUI();
// console.log('[RPG Companion] Tracker preset imported successfully');
toastr.success(i18n.getTranslation('template.trackerEditorModal.messages.importSuccess') || 'Tracker preset imported successfully!');
} catch (error) {
console.error('[RPG Companion] Error importing tracker preset:', error);
toastr.error(i18n.getTranslation('template.trackerEditorModal.messages.importError') ||
`Failed to import tracker preset: ${error.message}`);
}
};
// Trigger file selection
input.click();
}
/**
* Render the editor UI based on current config
*/
@@ -204,7 +367,7 @@ function renderUserStatsTab() {
let html = '<div class="rpg-editor-section">';
// Custom Stats section
html += '<h4><i class="fa-solid fa-heart-pulse"></i> Custom Stats</h4>';
html += `<h4><i class="fa-solid fa-heart-pulse"></i> ${i18n.getTranslation('template.trackerEditorModal.userStatsTab.customStatsTitle')}</h4>`;
html += '<div class="rpg-editor-stats-list" id="rpg-editor-stats-list">';
config.customStats.forEach((stat, index) => {
@@ -218,18 +381,33 @@ function renderUserStatsTab() {
});
html += '</div>';
html += '<button class="rpg-btn-secondary" id="rpg-add-stat"><i class="fa-solid fa-plus"></i> Add Custom Stat</button>';
html += `<button class="rpg-btn-secondary" id="rpg-add-stat"><i class="fa-solid fa-plus"></i> ${i18n.getTranslation('template.trackerEditorModal.userStatsTab.addCustomStatButton')}</button>`;
// RPG Attributes section
html += '<h4><i class="fa-solid fa-dice-d20"></i> RPG Attributes</h4>';
html += `<h4><i class="fa-solid fa-dice-d20"></i> ${i18n.getTranslation('template.trackerEditorModal.userStatsTab.rpgAttributesTitle')}</h4>`;
// Enable/disable toggle for entire RPG Attributes section
const showRPGAttributes = config.showRPGAttributes !== undefined ? config.showRPGAttributes : true;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-show-rpg-attrs" ${showRPGAttributes ? 'checked' : ''}>`;
html += '<label for="rpg-show-rpg-attrs">Enable RPG Attributes Section</label>';
html += `<label for="rpg-show-rpg-attrs">${i18n.getTranslation('template.trackerEditorModal.userStatsTab.enableRpgAttributes')}</label>`;
html += '</div>';
// Show/hide level toggle
const showLevel = config.showLevel !== undefined ? config.showLevel : true;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-show-level" ${showLevel ? 'checked' : ''}>`;
html += `<label for="rpg-show-level">Show Level</label>`;
html += '</div>';
// Always send attributes toggle
const alwaysSendAttributes = config.alwaysSendAttributes !== undefined ? config.alwaysSendAttributes : false;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-always-send-attrs" ${alwaysSendAttributes ? 'checked' : ''}>`;
html += `<label for="rpg-always-send-attrs">${i18n.getTranslation('template.trackerEditorModal.userStatsTab.alwaysIncludeAttributes')}</label>`;
html += '</div>';
html += `<small class="rpg-editor-note">${i18n.getTranslation('template.trackerEditorModal.userStatsTab.alwaysIncludeAttributesNote')}</small>`;
html += '<div class="rpg-editor-stats-list" id="rpg-editor-attrs-list">';
// Ensure rpgAttributes exists in the actual config (not just local fallback)
@@ -259,33 +437,37 @@ function renderUserStatsTab() {
});
html += '</div>';
html += '<button class="rpg-btn-secondary" id="rpg-add-attr"><i class="fa-solid fa-plus"></i> Add Attribute</button>';
html += `<button class="rpg-btn-secondary" id="rpg-add-attr"><i class="fa-solid fa-plus"></i> ${i18n.getTranslation('template.trackerEditorModal.userStatsTab.addAttributeButton')}</button>`;
// Status Section
html += '<h4><i class="fa-solid fa-face-smile"></i> Status Section</h4>';
html += `<h4><i class="fa-solid fa-face-smile"></i> ${i18n.getTranslation('template.trackerEditorModal.userStatsTab.statusSectionTitle')}</h4>`;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-status-enabled" ${config.statusSection.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-status-enabled">Enable Status Section</label>';
html += `<label for="rpg-status-enabled">${i18n.getTranslation('template.trackerEditorModal.userStatsTab.enableStatusSection')}</label>`;
html += '</div>';
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-mood-emoji" ${config.statusSection.showMoodEmoji ? 'checked' : ''}>`;
html += '<label for="rpg-mood-emoji">Show Mood Emoji</label>';
html += `<label for="rpg-mood-emoji">${i18n.getTranslation('template.trackerEditorModal.userStatsTab.showMoodEmoji')}</label>`;
html += '</div>';
html += '<label>Status Fields (comma-separated):</label>';
html += `<label>${i18n.getTranslation('template.trackerEditorModal.userStatsTab.statusFieldsLabel')}</label>`;
html += `<input type="text" id="rpg-status-fields" value="${config.statusSection.customFields.join(', ')}" class="rpg-text-input" placeholder="e.g., Conditions, Appearance">`;
// Skills Section
html += '<h4><i class="fa-solid fa-star"></i> Skills Section</h4>';
html += `<h4><i class="fa-solid fa-star"></i> ${i18n.getTranslation('template.trackerEditorModal.userStatsTab.skillsSectionTitle')}</h4>`;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-skills-enabled" ${config.skillsSection.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-skills-enabled">Enable Skills Section</label>';
html += `<label for="rpg-skills-enabled">${i18n.getTranslation('template.trackerEditorModal.userStatsTab.enableSkillsSection')}</label>`;
html += '</div>';
html += '<label>Skills Label:</label>';
html += `<label>${i18n.getTranslation('template.trackerEditorModal.userStatsTab.skillsLabelLabel')}</label>`;
html += `<input type="text" id="rpg-skills-label" value="${config.skillsSection.label}" class="rpg-text-input" placeholder="Skills">`;
html += `<label>${i18n.getTranslation('template.trackerEditorModal.userStatsTab.skillsListLabel')}</label>`;
const skillFields = config.skillsSection.customFields || [];
html += `<input type="text" id="rpg-skills-fields" value="${skillFields.join(', ')}" class="rpg-text-input" placeholder="e.g., Stealth, Persuasion, Combat">`;
html += '</div>';
$('#rpg-editor-tab-userStats').html(html);
@@ -380,6 +562,16 @@ function setupUserStatsListeners() {
extensionSettings.trackerConfig.userStats.showRPGAttributes = $(this).is(':checked');
});
// Show/hide level toggle
$('#rpg-show-level').off('change').on('change', function() {
extensionSettings.trackerConfig.userStats.showLevel = $(this).is(':checked');
});
// Always send attributes toggle
$('#rpg-always-send-attrs').off('change').on('change', function() {
extensionSettings.trackerConfig.userStats.alwaysSendAttributes = $(this).is(':checked');
});
// Status section toggles
$('#rpg-status-enabled').off('change').on('change', function() {
extensionSettings.trackerConfig.userStats.statusSection.enabled = $(this).is(':checked');
@@ -401,6 +593,13 @@ function setupUserStatsListeners() {
$('#rpg-skills-label').off('blur').on('blur', function() {
extensionSettings.trackerConfig.userStats.skillsSection.label = $(this).val();
saveSettings();
});
$('#rpg-skills-fields').off('blur').on('blur', function() {
const fields = $(this).val().split(',').map(f => f.trim()).filter(f => f);
extensionSettings.trackerConfig.userStats.skillsSection.customFields = fields;
saveSettings();
});
}
@@ -411,12 +610,12 @@ function renderInfoBoxTab() {
const config = extensionSettings.trackerConfig.infoBox;
let html = '<div class="rpg-editor-section">';
html += '<h4><i class="fa-solid fa-info-circle"></i> Widgets</h4>';
html += `<h4><i class="fa-solid fa-info-circle"></i> ${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.widgetsTitle')}</h4>`;
// Date widget
html += '<div class="rpg-editor-widget-row">';
html += `<input type="checkbox" id="rpg-widget-date" ${config.widgets.date.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-widget-date">Date</label>';
html += `<label for="rpg-widget-date">${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.dateWidget')}</label>`;
html += '<select id="rpg-date-format" class="rpg-select-mini">';
html += `<option value="Weekday, Month, Year" ${config.widgets.date.format === 'Weekday, Month, Year' ? 'selected' : ''}>Weekday, Month, Year</option>`;
html += `<option value="dd/mm/yyyy" ${config.widgets.date.format === 'dd/mm/yyyy' ? 'selected' : ''}>dd/mm/yyyy</option>`;
@@ -428,13 +627,13 @@ function renderInfoBoxTab() {
// Weather widget
html += '<div class="rpg-editor-widget-row">';
html += `<input type="checkbox" id="rpg-widget-weather" ${config.widgets.weather.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-widget-weather">Weather</label>';
html += `<label for="rpg-widget-weather">${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.weatherWidget')}</label>`;
html += '</div>';
// Temperature widget
html += '<div class="rpg-editor-widget-row">';
html += `<input type="checkbox" id="rpg-widget-temperature" ${config.widgets.temperature.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-widget-temperature">Temperature</label>';
html += `<label for="rpg-widget-temperature">${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.temperatureWidget')}</label>`;
html += '<div class="rpg-radio-group">';
html += `<label><input type="radio" name="temp-unit" value="C" ${config.widgets.temperature.unit === 'C' ? 'checked' : ''}> °C</label>`;
html += `<label><input type="radio" name="temp-unit" value="F" ${config.widgets.temperature.unit === 'F' ? 'checked' : ''}> °F</label>`;
@@ -444,19 +643,19 @@ function renderInfoBoxTab() {
// Time widget
html += '<div class="rpg-editor-widget-row">';
html += `<input type="checkbox" id="rpg-widget-time" ${config.widgets.time.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-widget-time">Time</label>';
html += `<label for="rpg-widget-time">${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.timeWidget')}</label>`;
html += '</div>';
// Location widget
html += '<div class="rpg-editor-widget-row">';
html += `<input type="checkbox" id="rpg-widget-location" ${config.widgets.location.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-widget-location">Location</label>';
html += `<label for="rpg-widget-location">${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.locationWidget')}</label>`;
html += '</div>';
// Recent Events widget
html += '<div class="rpg-editor-widget-row">';
html += `<input type="checkbox" id="rpg-widget-events" ${config.widgets.recentEvents.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-widget-events">Recent Events</label>';
html += `<label for="rpg-widget-events">${i18n.getTranslation('template.trackerEditorModal.infoBoxTab.recentEventsWidget')}</label>`;
html += '</div>';
html += '</div>';
@@ -512,12 +711,20 @@ function renderPresentCharactersTab() {
let html = '<div class="rpg-editor-section">';
// Relationship Fields Section
html += '<h4><i class="fa-solid fa-heart"></i> Relationship Status Fields</h4>';
html += '<p class="rpg-editor-hint">Define relationship types with corresponding emojis shown on character portraits</p>';
html += `<h4><i class="fa-solid fa-heart"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.relationshipStatusTitle')}</h4>`;
// Toggle for enabling/disabling relationships
const relationshipsEnabled = config.relationships?.enabled !== false; // Default to true if not set
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-relationships-enabled" ${relationshipsEnabled ? 'checked' : ''}>`;
html += `<label for="rpg-relationships-enabled">${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.enableRelationshipStatus')}</label>`;
html += '</div>';
html += `<p class="rpg-editor-hint">${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.relationshipStatusHint')}</p>`;
html += '<div class="rpg-relationship-mapping-list" id="rpg-relationship-mapping-list">';
// Show existing relationships as field → emoji pairs
const relationshipEmojis = config.relationshipEmojis || {
const relationshipEmojis = config.relationships?.relationshipEmojis || config.relationshipEmojis || {
'Lover': '❤️',
'Friend': '⭐',
'Ally': '🤝',
@@ -536,11 +743,11 @@ function renderPresentCharactersTab() {
`;
}
html += '</div>';
html += '<button class="rpg-btn-secondary" id="rpg-add-relationship"><i class="fa-solid fa-plus"></i> New Relationship</button>';
html += `<button class="rpg-btn-secondary" id="rpg-add-relationship"><i class="fa-solid fa-plus"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.newRelationshipButton')}</button>`;
// Custom Fields Section
html += '<h4><i class="fa-solid fa-list"></i> Appearance/Demeanor Fields</h4>';
html += '<p class="rpg-editor-hint">Fields shown below character name, separated by |</p>';
html += `<h4><i class="fa-solid fa-list"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.appearanceDemeanorTitle')}</h4>`;
html += `<p class="rpg-editor-hint">${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.appearanceDemeanorHint')}</p>`;
html += '<div class="rpg-editor-fields-list" id="rpg-editor-fields-list">';
@@ -560,34 +767,34 @@ function renderPresentCharactersTab() {
});
html += '</div>';
html += '<button class="rpg-btn-secondary" id="rpg-add-field"><i class="fa-solid fa-plus"></i> Add Custom Field</button>';
html += `<button class="rpg-btn-secondary" id="rpg-add-field"><i class="fa-solid fa-plus"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.addCustomFieldButton')}</button>`;
// Thoughts Section
html += '<h4><i class="fa-solid fa-comment-dots"></i> Thoughts Configuration</h4>';
html += `<h4><i class="fa-solid fa-comment-dots"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.thoughtsConfigTitle')}</h4>`;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-thoughts-enabled" ${config.thoughts?.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-thoughts-enabled">Enable Character Thoughts</label>';
html += `<label for="rpg-thoughts-enabled">${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.enableCharacterThoughts')}</label>`;
html += '</div>';
html += '<div class="rpg-thoughts-config">';
html += '<div class="rpg-editor-input-group">';
html += '<label>Thoughts Label:</label>';
html += `<label>${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.thoughtsLabelLabel')}</label>`;
html += `<input type="text" id="rpg-thoughts-name" value="${config.thoughts?.name || 'Thoughts'}" placeholder="e.g., Thoughts, Inner Voice, Feelings">`;
html += '</div>';
html += '<div class="rpg-editor-input-group">';
html += '<label>AI Instruction:</label>';
html += `<label>${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.aiInstructionLabel')}</label>`;
html += `<input type="text" id="rpg-thoughts-description" value="${config.thoughts?.description || 'Internal monologue (in first person POV, up to three sentences long)'}" placeholder="Description of what to generate">`;
html += '</div>';
html += '</div>';
// Character Stats
html += '<h4><i class="fa-solid fa-chart-bar"></i> Character Stats</h4>';
html += `<h4><i class="fa-solid fa-chart-bar"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.characterStatsTitle')}</h4>`;
html += '<div class="rpg-editor-toggle-row">';
html += `<input type="checkbox" id="rpg-char-stats-enabled" ${config.characterStats?.enabled ? 'checked' : ''}>`;
html += '<label for="rpg-char-stats-enabled">Track Character Stats</label>';
html += `<label for="rpg-char-stats-enabled">${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.trackCharacterStats')}</label>`;
html += '</div>';
html += '<p class="rpg-editor-hint">Create stats to track for each character (displayed as colored bars)</p>';
html += `<p class="rpg-editor-hint">${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.characterStatsHint')}</p>`;
html += '<div class="rpg-editor-fields-list" id="rpg-char-stats-list">';
const charStats = config.characterStats?.customStats || [];
@@ -602,7 +809,7 @@ function renderPresentCharactersTab() {
});
html += '</div>';
html += '<button class="rpg-btn-secondary" id="rpg-add-char-stat"><i class="fa-solid fa-plus"></i> Add Character Stat</button>';
html += `<button class="rpg-btn-secondary" id="rpg-add-char-stat"><i class="fa-solid fa-plus"></i> ${i18n.getTranslation('template.trackerEditorModal.presentCharactersTab.addCharacterStatButton')}</button>`;
html += '</div>';
@@ -614,16 +821,47 @@ function renderPresentCharactersTab() {
* Set up event listeners for Present Characters tab
*/
function setupPresentCharactersListeners() {
// Relationships enabled toggle
$('#rpg-relationships-enabled').off('change').on('change', function() {
if (!extensionSettings.trackerConfig.presentCharacters.relationships) {
extensionSettings.trackerConfig.presentCharacters.relationships = { enabled: true, relationshipEmojis: {} };
}
extensionSettings.trackerConfig.presentCharacters.relationships.enabled = $(this).is(':checked');
});
// Add new relationship
$('#rpg-add-relationship').off('click').on('click', function() {
// Ensure relationships object exists
if (!extensionSettings.trackerConfig.presentCharacters.relationships) {
extensionSettings.trackerConfig.presentCharacters.relationships = { enabled: true, relationshipEmojis: {} };
}
if (!extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis) {
extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis = {};
}
// Generate a unique relationship name
let baseName = 'New Relationship';
let relationshipName = baseName;
let counter = 1;
const existingRelationships = extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis;
while (existingRelationships[relationshipName]) {
counter++;
relationshipName = `${baseName} ${counter}`;
}
// Add to new structure
extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis[relationshipName] = '😊';
// Also update legacy fields for backward compatibility
if (!extensionSettings.trackerConfig.presentCharacters.relationshipEmojis) {
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis = {};
}
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis['New Relationship'] = '😊';
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis[relationshipName] = '😊';
// Sync relationshipFields
extensionSettings.trackerConfig.presentCharacters.relationshipFields =
Object.keys(extensionSettings.trackerConfig.presentCharacters.relationshipEmojis);
const emojis = extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis;
extensionSettings.trackerConfig.presentCharacters.relationshipFields = Object.keys(emojis);
renderPresentCharactersTab();
});
@@ -631,13 +869,20 @@ function setupPresentCharactersListeners() {
// Remove relationship
$('.rpg-remove-relationship').off('click').on('click', function() {
const relationship = $(this).data('relationship');
// Remove from new structure
if (extensionSettings.trackerConfig.presentCharacters.relationships?.relationshipEmojis) {
delete extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis[relationship];
}
// Remove from legacy structure
if (extensionSettings.trackerConfig.presentCharacters.relationshipEmojis) {
delete extensionSettings.trackerConfig.presentCharacters.relationshipEmojis[relationship];
}
// Sync relationshipFields
extensionSettings.trackerConfig.presentCharacters.relationshipFields =
Object.keys(extensionSettings.trackerConfig.presentCharacters.relationshipEmojis);
const emojis = extensionSettings.trackerConfig.presentCharacters.relationships?.relationshipEmojis || {};
extensionSettings.trackerConfig.presentCharacters.relationshipFields = Object.keys(emojis);
renderPresentCharactersTab();
});
@@ -648,28 +893,48 @@ function setupPresentCharactersListeners() {
const $item = $(this).closest('.rpg-relationship-item');
const emoji = $item.find('.rpg-relationship-emoji').val();
// Find the old name by matching the emoji
const oldName = Object.keys(extensionSettings.trackerConfig.presentCharacters.relationshipEmojis).find(
key => extensionSettings.trackerConfig.presentCharacters.relationshipEmojis[key] === emoji &&
key !== newName
// Ensure structures exist
if (!extensionSettings.trackerConfig.presentCharacters.relationships) {
extensionSettings.trackerConfig.presentCharacters.relationships = { enabled: true, relationshipEmojis: {} };
}
if (!extensionSettings.trackerConfig.presentCharacters.relationshipEmojis) {
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis = {};
}
// Find the old name by matching the emoji in new structure
const emojis = extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis;
const oldName = Object.keys(emojis).find(
key => emojis[key] === emoji && key !== newName
);
if (oldName && oldName !== newName) {
// Update new structure
delete emojis[oldName];
emojis[newName] = emoji;
// Update legacy structure
delete extensionSettings.trackerConfig.presentCharacters.relationshipEmojis[oldName];
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis[newName] = emoji;
// Sync relationshipFields
extensionSettings.trackerConfig.presentCharacters.relationshipFields =
Object.keys(extensionSettings.trackerConfig.presentCharacters.relationshipEmojis);
extensionSettings.trackerConfig.presentCharacters.relationshipFields = Object.keys(emojis);
}
});
// Update relationship emoji
$('.rpg-relationship-emoji').off('blur').on('blur', function() {
const name = $(this).closest('.rpg-relationship-item').find('.rpg-relationship-name').val();
// Ensure structures exist
if (!extensionSettings.trackerConfig.presentCharacters.relationships) {
extensionSettings.trackerConfig.presentCharacters.relationships = { enabled: true, relationshipEmojis: {} };
}
if (!extensionSettings.trackerConfig.presentCharacters.relationshipEmojis) {
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis = {};
}
// Update both structures
extensionSettings.trackerConfig.presentCharacters.relationships.relationshipEmojis[name] = $(this).val();
extensionSettings.trackerConfig.presentCharacters.relationshipEmojis[name] = $(this).val();
});
+300
View File
@@ -0,0 +1,300 @@
/**
* Dynamic Weather Effects Module
* Creates weather effects based on the Info Box weather field
*/
import { extensionSettings, lastGeneratedData, committedTrackerData } from '../../core/state.js';
let weatherContainer = null;
let currentWeatherType = null;
/**
* Parse weather text to determine effect type
*/
function parseWeatherType(weatherText) {
if (!weatherText) return 'none';
const text = weatherText.toLowerCase();
// Check for specific weather conditions (order matters - check combined effects first)
if (text.includes('blizzard')) {
return 'blizzard'; // Snow + Wind
}
if (text.includes('storm') || text.includes('thunder') || text.includes('lightning')) {
return 'storm'; // Rain + Lightning
}
if (text.includes('wind') || text.includes('breeze') || text.includes('gust') || text.includes('gale')) {
return 'wind';
}
if (text.includes('snow') || text.includes('flurries')) {
return 'snow';
}
if (text.includes('rain') || text.includes('drizzle') || text.includes('shower')) {
return 'rain';
}
if (text.includes('mist') || text.includes('fog') || text.includes('haze')) {
return 'mist';
}
if (text.includes('sunny') || text.includes('clear') || text.includes('bright')) {
return 'sunny';
}
if (text.includes('cloud') || text.includes('overcast') || text.includes('indoor') || text.includes('inside')) {
return 'none';
}
return 'none';
}
/**
* Extract weather from Info Box data
*/
function getCurrentWeather() {
const infoBoxData = lastGeneratedData.infoBox || committedTrackerData.infoBox || '';
// Try to parse as JSON first (new format)
try {
const parsed = typeof infoBoxData === 'string' ? JSON.parse(infoBoxData) : infoBoxData;
if (parsed && parsed.weather) {
// Return the forecast text from the weather object
return parsed.weather.forecast || parsed.weather.emoji || null;
}
} catch (e) {
// Not JSON, try old text format
}
// Fallback: Parse the old text format to find Weather field
const lines = infoBoxData.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('Weather:')) {
return trimmed.substring('Weather:'.length).trim();
}
}
return null;
}
/**
* Create snowflakes effect
*/
function createSnowflakes() {
const container = document.createElement('div');
container.className = 'rpg-weather-particles';
// Create 50 snowflakes
for (let i = 0; i < 50; i++) {
const snowflake = document.createElement('div');
snowflake.className = 'rpg-weather-particle rpg-snowflake';
snowflake.textContent = '❄';
snowflake.style.left = `${Math.random() * 100}%`;
snowflake.style.animationDelay = `${Math.random() * 10}s`;
snowflake.style.animationDuration = `${10 + Math.random() * 10}s`;
container.appendChild(snowflake);
}
return container;
}
/**
* Create rain effect
*/
function createRain() {
const container = document.createElement('div');
container.className = 'rpg-weather-particles';
// Create 100 raindrops for heavier effect
for (let i = 0; i < 100; i++) {
const raindrop = document.createElement('div');
raindrop.className = 'rpg-weather-particle rpg-raindrop';
raindrop.style.left = `${Math.random() * 100}%`;
raindrop.style.animationDelay = `${Math.random() * 2}s`;
raindrop.style.animationDuration = `${0.5 + Math.random() * 0.5}s`;
container.appendChild(raindrop);
}
return container;
}
/**
* Create mist/fog effect
*/
function createMist() {
const container = document.createElement('div');
container.className = 'rpg-weather-particles';
// Create 5 mist layers
for (let i = 0; i < 5; i++) {
const mist = document.createElement('div');
mist.className = 'rpg-weather-particle rpg-mist';
mist.style.animationDelay = `${i * 2}s`;
mist.style.animationDuration = `${15 + i * 2}s`;
mist.style.opacity = `${0.1 + Math.random() * 0.2}`;
container.appendChild(mist);
}
return container;
}
/**
* Create sunshine rays effect
*/
function createSunshine() {
const container = document.createElement('div');
container.className = 'rpg-weather-particles';
// Create 8 sun rays
for (let i = 0; i < 8; i++) {
const ray = document.createElement('div');
ray.className = 'rpg-weather-particle rpg-sunray';
ray.style.left = `${10 + i * 12}%`;
ray.style.animationDelay = `${i * 0.5}s`;
ray.style.animationDuration = `${8 + Math.random() * 4}s`;
container.appendChild(ray);
}
return container;
}
/**
* Create lightning flash effect
*/
function createLightning() {
const container = document.createElement('div');
container.className = 'rpg-weather-particles';
// Create lightning flash overlay
const flash = document.createElement('div');
flash.className = 'rpg-weather-particle rpg-lightning';
container.appendChild(flash);
return container;
}
/**
* Create wind effect
*/
function createWind() {
const container = document.createElement('div');
container.className = 'rpg-weather-particles';
// Create 30 wind streaks
for (let i = 0; i < 30; i++) {
const streak = document.createElement('div');
streak.className = 'rpg-weather-particle rpg-wind-streak';
streak.style.top = `${Math.random() * 100}%`;
streak.style.animationDelay = `${Math.random() * 5}s`;
streak.style.animationDuration = `${1.5 + Math.random() * 1}s`;
container.appendChild(streak);
}
return container;
}
/**
* Remove current weather effect
*/
function removeWeatherEffect() {
if (weatherContainer) {
weatherContainer.remove();
weatherContainer = null;
currentWeatherType = null;
}
}
/**
* Update weather effect based on current weather
*/
export function updateWeatherEffect() {
// Check if dynamic weather is enabled
if (!extensionSettings.enableDynamicWeather) {
removeWeatherEffect();
return;
}
const weather = getCurrentWeather();
const weatherType = parseWeatherType(weather);
// Don't recreate if weather hasn't changed
if (weatherType === currentWeatherType) {
return;
}
// Remove existing effect
removeWeatherEffect();
// Create new effect based on weather type
if (weatherType === 'none') {
return; // No effect
}
currentWeatherType = weatherType;
switch (weatherType) {
case 'snow':
weatherContainer = createSnowflakes();
break;
case 'rain':
weatherContainer = createRain();
break;
case 'mist':
weatherContainer = createMist();
break;
case 'sunny':
weatherContainer = createSunshine();
break;
case 'wind':
weatherContainer = createWind();
break;
case 'storm': {
// Storm = Rain + Lightning (combined effects)
const rainContainer = createRain();
const lightningContainer = createLightning();
// Merge both containers
weatherContainer = document.createElement('div');
weatherContainer.className = 'rpg-weather-particles';
weatherContainer.appendChild(rainContainer);
weatherContainer.appendChild(lightningContainer);
break;
}
case 'blizzard': {
// Blizzard = Snow + Wind (combined effects)
const snowContainer = createSnowflakes();
const windContainer = createWind();
// Merge both containers
weatherContainer = document.createElement('div');
weatherContainer.className = 'rpg-weather-particles';
weatherContainer.appendChild(snowContainer);
weatherContainer.appendChild(windContainer);
break;
}
}
if (weatherContainer) {
document.body.appendChild(weatherContainer);
}
}
/**
* Initialize weather effects
*/
export function initWeatherEffects() {
updateWeatherEffect();
}
/**
* Toggle dynamic weather effects
*/
export function toggleDynamicWeather(enabled) {
if (enabled) {
updateWeatherEffect();
} else {
removeWeatherEffect();
}
}
/**
* Clean up weather effects
*/
export function cleanupWeatherEffects() {
removeWeatherEffect();
}
+1
View File
@@ -8,6 +8,7 @@
* @typedef {Object} InventoryV2
* @property {number} version - Schema version (always 2)
* @property {string} onPerson - Items currently carried/worn by the character (plaintext list)
* @property {string} clothing - Clothing and armor currently worn (plaintext list)
* @property {Object.<string, string>} stored - Items stored at named locations (location name plaintext list)
* @property {string} assets - Character's vehicles, property, and major possessions (plaintext list)
*/
+29 -14
View File
@@ -17,6 +17,7 @@ import { sanitizeItemName, MAX_ITEMS_PER_SECTION } from './security.js';
* - Strips list markers: -, , 1., 2., etc.
* - Collapses newlines inside parentheses to spaces
* - Only splits on commas OUTSIDE parentheses (preserves commas in descriptions)
* - Preserves commas in numbers (decimal separators like 4443,445)
* - Gracefully handles unmatched parentheses
*
* @param {string} itemString - Item string from AI (various formats supported)
@@ -35,6 +36,10 @@ import { sanitizeItemName, MAX_ITEMS_PER_SECTION } from './security.js';
* parseItems("Potato (Cursed, Sexy, Your Mum & Dick, Etc), Sword")
* // → ["Potato (Cursed, Sexy, Your Mum & Dick, Etc)", "Sword"]
*
* // Decimal commas in numbers (preserved)
* parseItems("4443,445 gold coins, Sword, 1,234,567 credits")
* // → ["4443,445 gold coins", "Sword", "1,234,567 credits"]
*
* // Markdown formatting (stripped)
* parseItems("**Sword** (equipped), *Shield*") // ["Sword (equipped)", "Shield"]
*
@@ -125,7 +130,7 @@ export function parseItems(itemString) {
// STEP 5: Normalize whitespace
processed = processed.replace(/\s+/g, ' ');
// STEP 6: Smart comma splitting (only split on commas OUTSIDE parentheses)
// STEP 6: Smart comma splitting (only split on commas OUTSIDE parentheses and NOT in numbers)
// Also handles list markers, quotes, and security validation per-item
const items = [];
let currentItem = '';
@@ -146,22 +151,32 @@ export function parseItems(itemString) {
}
currentItem += char;
} else if (char === ',' && parenDepth === 0) {
// Comma outside parentheses - this is a separator
const cleaned = cleanSingleItem(currentItem);
if (cleaned) {
// Security check: validate and sanitize item name
const sanitized = sanitizeItemName(cleaned);
if (sanitized) {
items.push(sanitized);
}
// Check if this comma is between digits (decimal separator like 4443,445)
const prevChar = i > 0 ? processed[i - 1] : '';
const nextChar = i < processed.length - 1 ? processed[i + 1] : '';
const isDecimalComma = /\d/.test(prevChar) && /\d/.test(nextChar);
// DoS protection: enforce max items limit
if (items.length >= MAX_ITEMS_PER_SECTION) {
console.warn(`[RPG Companion] Reached max items limit (${MAX_ITEMS_PER_SECTION}), truncating list`);
return items;
if (isDecimalComma) {
// This is a decimal comma, not a separator - keep it
currentItem += char;
} else {
// Comma outside parentheses and not in a number - this is a separator
const cleaned = cleanSingleItem(currentItem);
if (cleaned) {
// Security check: validate and sanitize item name
const sanitized = sanitizeItemName(cleaned);
if (sanitized) {
items.push(sanitized);
}
// DoS protection: enforce max items limit
if (items.length >= MAX_ITEMS_PER_SECTION) {
console.warn(`[RPG Companion] Reached max items limit (${MAX_ITEMS_PER_SECTION}), truncating list`);
return items;
}
}
currentItem = ''; // Start new item
}
currentItem = ''; // Start new item
} else {
currentItem += char;
}
+433
View File
@@ -0,0 +1,433 @@
/**
* JSON Migration Module
* Migrates committed tracker data from v2 text format to v3 JSON format
*/
import { committedTrackerData, extensionSettings, updateCommittedTrackerData, updateExtensionSettings } from '../core/state.js';
import { saveSettings, saveChatData } from '../core/persistence.js';
/**
* Helper to separate emoji from text in a string
* @param {string} str - String potentially containing emoji followed by text
* @returns {{emoji: string, text: string}} Separated emoji and text
*/
function separateEmojiFromText(str) {
if (!str) return { emoji: '', text: '' };
str = str.trim();
// Regex to match emoji at the start
const emojiRegex = /^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F000}-\u{1F02F}\u{1F0A0}-\u{1F0FF}\u{1F100}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F910}-\u{1F96B}\u{1F980}-\u{1F9E0}\u{FE00}-\u{FE0F}\u{200D}\u{20E3}]+/u;
const emojiMatch = str.match(emojiRegex);
if (emojiMatch) {
const emoji = emojiMatch[0];
let text = str.substring(emoji.length).trim();
// Remove leading comma or space
text = text.replace(/^[,\s]+/, '');
return { emoji, text };
}
// Check if there's a comma separator anyway
const commaParts = str.split(',');
if (commaParts.length >= 2) {
return {
emoji: commaParts[0].trim(),
text: commaParts.slice(1).join(',').trim()
};
}
// No clear separation - return original as text
return { emoji: '', text: str };
}
/**
* Parses item text to JSON format
* Handles "3x Item Name" or "Item Name" formats
* @param {string} itemsText - Comma-separated items string
* @returns {Array<{name: string, quantity?: number}>} Array of item objects
*/
function parseItemsToJSON(itemsText) {
if (!itemsText || itemsText.trim() === '' || itemsText.toLowerCase() === 'none') {
return [];
}
const items = itemsText.split(',').map(s => s.trim()).filter(s => s);
return items.map(item => {
// Parse "3x Health Potion" format
const qtyMatch = item.match(/^(\d+)x\s*(.+)/i);
if (qtyMatch) {
return {
name: qtyMatch[2].trim(),
quantity: parseInt(qtyMatch[1])
};
}
return { name: item, quantity: 1 };
});
}
/**
* Migrates User Stats from v2 text format to v3 JSON format
* @param {string} textData - V2 text format user stats
* @returns {object} V3 JSON format user stats
*/
export function migrateUserStatsToJSON(textData) {
if (!textData || typeof textData !== 'string') {
return null;
}
const lines = textData.split('\n');
const result = {
version: 3,
stats: [],
status: {},
skills: [],
inventory: {
onPerson: [],
clothing: [],
stored: {},
assets: []
},
quests: {
main: null,
optional: []
}
};
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed === '---' || trimmed.startsWith('```')) continue;
// Parse "- StatName: X%" format
const statMatch = trimmed.match(/^-\s*([^:]+):\s*(\d+)%/);
if (statMatch) {
const name = statMatch[1].trim();
const id = name.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
result.stats.push({
id: id,
name: name,
value: parseInt(statMatch[2])
});
continue;
}
// Parse "Status: emoji, text" or "Status: text" format
const statusMatch = trimmed.match(/^Status:\s*(.+)/i);
if (statusMatch) {
const { emoji, text } = separateEmojiFromText(statusMatch[1]);
if (emoji) result.status.mood = emoji;
if (text) result.status.conditions = text;
continue;
}
// Parse "Skills: skill1, skill2" format
const skillsMatch = trimmed.match(/^Skills:\s*(.+)/i);
if (skillsMatch) {
const skillsText = skillsMatch[1].trim();
if (skillsText && skillsText.toLowerCase() !== 'none') {
const skills = skillsText.split(',').map(s => s.trim()).filter(s => s);
result.skills = skills.map(name => ({ name }));
}
continue;
}
// Parse inventory lines
const onPersonMatch = trimmed.match(/^On Person:\s*(.+)/i);
if (onPersonMatch) {
result.inventory.onPerson = parseItemsToJSON(onPersonMatch[1]);
continue;
}
const clothingMatch = trimmed.match(/^Clothing:\s*(.+)/i);
if (clothingMatch) {
result.inventory.clothing = parseItemsToJSON(clothingMatch[1]);
continue;
}
const storedMatch = trimmed.match(/^Stored\s*-\s*([^:]+):\s*(.+)/i);
if (storedMatch) {
const location = storedMatch[1].trim();
result.inventory.stored[location] = parseItemsToJSON(storedMatch[2]);
continue;
}
const assetsMatch = trimmed.match(/^Assets:\s*(.+)/i);
if (assetsMatch) {
const assetsText = assetsMatch[1].trim();
if (assetsText && assetsText.toLowerCase() !== 'none') {
result.inventory.assets = assetsText.split(',').map(s => s.trim()).filter(s => s).map(name => ({ name }));
}
continue;
}
// Parse quest lines
const mainQuestMatch = trimmed.match(/^Main Quests?:\s*(.+)/i);
if (mainQuestMatch) {
const questText = mainQuestMatch[1].trim();
if (questText && questText.toLowerCase() !== 'none') {
result.quests.main = { title: questText };
}
continue;
}
const optionalQuestsMatch = trimmed.match(/^Optional Quests?:\s*(.+)/i);
if (optionalQuestsMatch) {
const questsText = optionalQuestsMatch[1].trim();
if (questsText && questsText.toLowerCase() !== 'none') {
const quests = questsText.split(',').map(s => s.trim()).filter(s => s);
result.quests.optional = quests.map(title => ({ title }));
}
continue;
}
}
return result;
}
/**
* Migrates Info Box from v2 text format to v3 JSON format
* @param {string} textData - V2 text format info box
* @returns {object} V3 JSON format info box
*/
export function migrateInfoBoxToJSON(textData) {
if (!textData || typeof textData !== 'string') {
return null;
}
const lines = textData.split('\n');
const result = {
version: 3
};
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed === '---' || trimmed.startsWith('```') || trimmed.toLowerCase() === 'info box') continue;
// Parse "Date: value" format
const dateMatch = trimmed.match(/^Date:\s*(.+)/i);
if (dateMatch) {
result.date = { value: dateMatch[1].trim() };
continue;
}
// Parse "Weather: emoji, text" or "Weather: text" format
const weatherMatch = trimmed.match(/^Weather:\s*(.+)/i);
if (weatherMatch) {
const { emoji, text } = separateEmojiFromText(weatherMatch[1]);
result.weather = {
emoji: emoji || '',
forecast: text || weatherMatch[1].trim()
};
continue;
}
// Parse "Temperature: X°C" or "Temperature: X°F" format
const tempMatch = trimmed.match(/^Temperature:\s*(\d+)\s*°?([CF])?/i);
if (tempMatch) {
result.temperature = {
value: parseInt(tempMatch[1]),
unit: tempMatch[2] ? tempMatch[2].toUpperCase() : 'C'
};
continue;
}
// Parse "Time: start → end" format
const timeMatch = trimmed.match(/^Time:\s*(.+?)\s*→\s*(.+)/i);
if (timeMatch) {
result.time = {
start: timeMatch[1].trim(),
end: timeMatch[2].trim()
};
continue;
}
// Parse "Location: value" format
const locationMatch = trimmed.match(/^Location:\s*(.+)/i);
if (locationMatch) {
result.location = { value: locationMatch[1].trim() };
continue;
}
// Parse "Recent Events: event1, event2, event3" format
const eventsMatch = trimmed.match(/^Recent Events:\s*(.+)/i);
if (eventsMatch) {
const eventsText = eventsMatch[1].trim();
if (eventsText && eventsText.toLowerCase() !== 'none') {
result.recentEvents = eventsText.split(',').map(s => s.trim()).filter(s => s);
}
continue;
}
}
return result;
}
/**
* Migrates Present Characters from v2 text format to v3 JSON format
* @param {string} textData - V2 text format present characters
* @returns {object} V3 JSON format present characters
*/
export function migrateCharactersToJSON(textData) {
if (!textData || typeof textData !== 'string') {
return null;
}
const result = {
version: 3,
characters: []
};
// Split by character blocks (marked by "- Name")
const blocks = ('\n' + textData).split(/\n-\s+/);
for (const block of blocks) {
if (!block.trim()) continue;
const lines = block.trim().split('\n');
if (lines.length === 0) continue;
const character = {
name: lines[0].trim()
};
// Parse subsequent lines for this character
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (!line) continue;
// Parse "Details: emoji | field1 | field2" format
const detailsMatch = line.match(/^Details:\s*(.+)/i);
if (detailsMatch) {
const detailsText = detailsMatch[1].trim();
const parts = detailsText.split('|').map(s => s.trim());
const { emoji } = separateEmojiFromText(parts[0] || '');
if (emoji) character.emoji = emoji;
character.details = {};
for (let j = 1; j < parts.length; j++) {
const fieldName = `field${j}`;
character.details[fieldName] = parts[j];
}
continue;
}
// Parse "Relationship: status" format
const relationshipMatch = line.match(/^Relationship:\s*(.+)/i);
if (relationshipMatch) {
character.relationship = { status: relationshipMatch[1].trim() };
continue;
}
// Parse "Stats: stat1: X% | stat2: Y%" format
const statsMatch = line.match(/^Stats:\s*(.+)/i);
if (statsMatch) {
const statsText = statsMatch[1].trim();
const statParts = statsText.split('|').map(s => s.trim());
character.stats = [];
for (const statPart of statParts) {
const statValueMatch = statPart.match(/^([^:]+):\s*(\d+)%/);
if (statValueMatch) {
character.stats.push({
name: statValueMatch[1].trim(),
value: parseInt(statValueMatch[2])
});
}
}
continue;
}
// Parse "Thoughts: content" format
const thoughtsMatch = line.match(/^Thoughts:\s*(.+)/i);
if (thoughtsMatch) {
character.thoughts = { content: thoughtsMatch[1].trim() };
continue;
}
}
result.characters.push(character);
}
return result;
}
/**
* Main migration function - migrates all committed tracker data to v3 JSON format
* @returns {Promise<void>}
*/
export async function migrateToV3JSON() {
// console.log('[RPG Migration] Starting migration to v3 JSON format...');
const migrated = {
userStats: null,
infoBox: null,
characterThoughts: null
};
// Migrate User Stats
if (committedTrackerData.userStats && typeof committedTrackerData.userStats === 'string') {
// console.log('[RPG Migration] Migrating User Stats...');
migrated.userStats = migrateUserStatsToJSON(committedTrackerData.userStats);
if (migrated.userStats) {
// console.log('[RPG Migration] ✓ User Stats migrated');
}
}
// Migrate Info Box
if (committedTrackerData.infoBox && typeof committedTrackerData.infoBox === 'string') {
// console.log('[RPG Migration] Migrating Info Box...');
migrated.infoBox = migrateInfoBoxToJSON(committedTrackerData.infoBox);
if (migrated.infoBox) {
// console.log('[RPG Migration] ✓ Info Box migrated');
}
}
// Migrate Present Characters
if (committedTrackerData.characterThoughts && typeof committedTrackerData.characterThoughts === 'string') {
// console.log('[RPG Migration] Migrating Present Characters...');
migrated.characterThoughts = migrateCharactersToJSON(committedTrackerData.characterThoughts);
if (migrated.characterThoughts) {
// console.log('[RPG Migration] ✓ Present Characters migrated');
}
}
// Update committed data
updateCommittedTrackerData(migrated);
// Initialize lockedItems if not present
if (!extensionSettings.lockedItems) {
// console.log('[RPG Migration] Initializing lockedItems structure...');
updateExtensionSettings({
lockedItems: {
stats: [],
skills: [],
inventory: {
onPerson: [],
clothing: [],
stored: {},
assets: []
},
quests: {
main: false,
optional: []
},
infoBox: {
date: false,
weather: false,
temperature: false,
time: false,
location: false,
recentEvents: false
},
characters: {}
}
});
}
// Save migrated data
await saveChatData();
await saveSettings();
// console.log('[RPG Migration] ✅ Migration to v3 JSON format complete');
}
+220
View File
@@ -0,0 +1,220 @@
/**
* JSON Repair Utilities
* Handles parsing and repairing malformed JSON from AI responses
*/
/**
* Repairs malformed JSON from AI responses
* Handles common AI mistakes like trailing commas, missing commas, wrong quotes, etc.
*
* @param {string} jsonString - Potentially malformed JSON string
* @returns {object|null} Repaired JSON object or null if repair fails
*/
export function repairJSON(jsonString) {
if (!jsonString || typeof jsonString !== 'string') {
console.warn('[RPG JSON Repair] Invalid input:', typeof jsonString);
return null;
}
let cleaned = jsonString.trim();
// Remove markdown code fences
cleaned = cleaned.replace(/```json\s*/gi, '');
cleaned = cleaned.replace(/```\s*/g, '');
// Remove thinking tags (model's internal reasoning)
cleaned = cleaned.replace(/<think>[\s\S]*?<\/think>/gi, '');
cleaned = cleaned.replace(/<thinking>[\s\S]*?<\/thinking>/gi, '');
// Fix common JSON errors:
// 1. Trailing commas before closing brackets
cleaned = cleaned.replace(/,(\s*[}\]])/g, '$1');
// 2. Missing commas between properties - DISABLED because it corrupts valid JSON
// Modern AI models send properly formatted JSON, so this aggressive repair is not needed
// cleaned = cleaned.replace(/("\s*:\s*(?:"[^"]*"|[^,}\]]+))(\s+")/g, '$1,$2');
// 3. Single quotes to double quotes - DISABLED because it corrupts apostrophes in text
// Apostrophes in strings like "Zandik's Office" would become "Zandik"s Office" (invalid JSON)
// Modern AI models already use double quotes for JSON strings
// cleaned = cleaned.replace(/'/g, '"');
// 4. Unquoted keys - DISABLED because it corrupts valid JSON string values
// The AI models already send properly quoted JSON, so this is not needed
// cleaned = cleaned.replace(/(\{|,)\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g, '$1"$2":');
// 5. Remove JavaScript comments
cleaned = cleaned.replace(/\/\/.*$/gm, '');
cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, '');
// Attempt 1: Standard JSON.parse
try {
return JSON.parse(cleaned);
} catch (e) {
}
// Attempt 2: Extract JSON object between first { and last }
const objectMatch = cleaned.match(/\{[\s\S]*\}/);
if (objectMatch) {
try {
return JSON.parse(objectMatch[0]);
} catch (e) {
// Silent fail, try next method
}
}
// Attempt 3: Try to extract JSON array between first [ and last ]
const arrayMatch = cleaned.match(/\[[\s\S]*\]/);
if (arrayMatch) {
try {
return JSON.parse(arrayMatch[0]);
} catch (e) {
// Silent fail, try next method
}
}
// Attempt 4: Use Function constructor (safer than eval, still controlled)
// Only as last resort for trusted AI output
try {
const fn = new Function(`"use strict"; return (${cleaned});`);
const result = fn();
// Validate it's actually an object or array
if (result && (typeof result === 'object')) {
// console.log('[RPG JSON Repair] ✓ Repaired using Function constructor');
return result;
}
} catch (e) {
console.error('[RPG JSON Repair] ✗ All repair attempts failed:', e.message);
}
return null;
}
/**
* Validates JSON structure matches expected schema for a tracker type
*
* @param {object} data - Parsed JSON data to validate
* @param {string} type - Type of tracker ('userStats', 'infoBox', 'characters')
* @returns {boolean} True if valid, false otherwise
*/
export function validateJSONSchema(data, type) {
if (!data || typeof data !== 'object') {
return false;
}
try {
switch (type) {
case 'userStats':
return Array.isArray(data.stats) &&
data.stats.every(s =>
s &&
typeof s === 'object' &&
s.id &&
s.name &&
typeof s.value === 'number'
);
case 'infoBox':
return (data.date || data.weather || data.time || data.location || data.temperature || data.recentEvents);
case 'characters':
return Array.isArray(data.characters) &&
data.characters.every(c => c && c.name);
default:
console.warn('[RPG JSON Validation] Unknown tracker type:', type);
return false;
}
} catch (e) {
console.error('[RPG JSON Validation] Error during validation:', e);
return false;
}
}
/**
* Extracts JSON from text that may contain other content
* Looks for JSON blocks within ```json fences or standalone JSON objects
*
* @param {string} text - Text potentially containing JSON
* @returns {string|null} Extracted JSON string or null
*/
export function extractJSONFromText(text) {
if (!text || typeof text !== 'string') {
return null;
}
// Try to extract from ```json code fence
const fenceMatch = text.match(/```json\s*([\s\S]*?)```/i);
if (fenceMatch && fenceMatch[1]) {
return fenceMatch[1].trim();
}
// Try to extract from ``` code fence (without json label)
const genericFenceMatch = text.match(/```\s*([\s\S]*?)```/);
if (genericFenceMatch && genericFenceMatch[1]) {
const content = genericFenceMatch[1].trim();
// Check if it looks like JSON (starts with { or [)
if (content.startsWith('{') || content.startsWith('[')) {
return content;
}
}
// Try to find standalone JSON object
const objectMatch = text.match(/\{[\s\S]*\}/);
if (objectMatch) {
return objectMatch[0];
}
// Try to find standalone JSON array
const arrayMatch = text.match(/\[[\s\S]*\]/);
if (arrayMatch) {
return arrayMatch[0];
}
return null;
}
/**
* Safely parses JSON with automatic repair attempts
* Combines extraction, repair, and validation in one call
*
* @param {string} text - Text containing JSON (with or without code fences)
* @param {string} expectedType - Expected tracker type for validation ('userStats', 'infoBox', 'characters')
* @returns {{data: object|null, success: boolean, error: string|null}} Result object
*/
export function safeParseJSON(text, expectedType = null) {
const result = {
data: null,
success: false,
error: null
};
// Extract JSON from text
const jsonString = extractJSONFromText(text);
if (!jsonString) {
result.error = 'No JSON found in text';
return result;
}
// Attempt to repair and parse
const parsed = repairJSON(jsonString);
if (!parsed) {
result.error = 'Failed to parse JSON after repair attempts';
return result;
}
// Validate schema if type specified
if (expectedType) {
const valid = validateJSONSchema(parsed, expectedType);
if (!valid) {
result.error = `JSON does not match expected schema for type: ${expectedType}`;
result.data = parsed; // Return data anyway, might be partially useful
return result;
}
}
result.data = parsed;
result.success = true;
return result;
}
+33 -3
View File
@@ -15,6 +15,7 @@
const DEFAULT_INVENTORY_V2 = {
version: 2,
onPerson: "None",
clothing: "None",
stored: {},
assets: "None"
};
@@ -27,8 +28,36 @@ const DEFAULT_INVENTORY_V2 = {
* @returns {MigrationResult} Migration result with v2 inventory and metadata
*/
export function migrateInventory(inventory) {
// Case 1: Already v2 format (has version property and is an object)
// Case 1: v2 format missing version property (parser output)
// Parser returns v2 structure but without the version tag
if (inventory && typeof inventory === 'object' &&
'onPerson' in inventory && 'clothing' in inventory &&
'stored' in inventory && 'assets' in inventory &&
!('version' in inventory)) {
// console.log('[RPG Companion Migration] v2 inventory missing version tag, adding it');
return {
inventory: {
version: 2,
...inventory
},
migrated: true,
source: 'parser-output'
};
}
// Case 2: Already v2 format (has version property and is an object)
if (inventory && typeof inventory === 'object' && inventory.version === 2) {
// Check if clothing field exists (v2.1 upgrade)
if (!inventory.hasOwnProperty('clothing')) {
// console.log('[RPG Companion Migration] Upgrading v2 inventory to v2.1 (adding clothing field)');
inventory.clothing = "None";
return {
inventory: inventory,
migrated: true,
source: 'v2-upgrade'
};
}
// console.log('[RPG Companion Migration] Inventory already v2, no migration needed');
return {
inventory: inventory,
@@ -37,7 +66,7 @@ export function migrateInventory(inventory) {
};
}
// Case 2: null or undefined → use defaults
// Case 3: null or undefined → use defaults
if (inventory === null || inventory === undefined) {
// console.log('[RPG Companion Migration] Inventory is null/undefined, using defaults');
return {
@@ -47,7 +76,7 @@ export function migrateInventory(inventory) {
};
}
// Case 3: v1 string format → migrate to v2
// Case 4: v1 string format → migrate to v2
if (typeof inventory === 'string') {
// Check if it's an empty/default string
const trimmed = inventory.trim();
@@ -66,6 +95,7 @@ export function migrateInventory(inventory) {
inventory: {
version: 2,
onPerson: inventory,
clothing: "None",
stored: {},
assets: "None"
},
+3526 -421
View File
File diff suppressed because it is too large Load Diff
+706 -105
View File
@@ -10,7 +10,7 @@
<div class="rpg-panel-header">
<h3>
<i class="fa-solid fa-dice-d20"></i>
RPG Companion
<span id="rpg-panel-title" data-i18n-key="template.mainPanel.title">RPG Companion</span>
</h3>
</div>
@@ -18,8 +18,8 @@
<!-- Dice Roll Display -->
<div id="rpg-dice-display" class="rpg-dice-display">
<i class="fa-solid fa-dice"></i>
<span id="rpg-last-roll-text">Last Roll: None</span>
<button id="rpg-clear-dice" class="rpg-clear-dice-btn" title="Clear last roll">×</button>
<span id="rpg-last-roll-text"></span>
<button id="rpg-clear-dice" class="rpg-clear-dice-btn">×</button>
</div>
<!-- Unified Game Content Box -->
@@ -53,33 +53,92 @@
<!-- Content will be populated by JavaScript -->
</div>
<!-- Divider after Inventory -->
<div id="rpg-divider-inventory" class="rpg-divider"></div>
<!-- Quests Section -->
<div id="rpg-quests" class="rpg-section rpg-quests-section">
<!-- Content will be populated by JavaScript -->
</div>
<!-- Divider after Quests -->
<div id="rpg-divider-quests" class="rpg-divider"></div>
<!-- Music Player Section -->
<div id="rpg-music-player" class="rpg-section rpg-music-section">
<!-- Content will be populated by JavaScript -->
</div>
</div>
<!-- HTML Prompt Toggle -->
<div class="rpg-toggle-container">
<label class="rpg-toggle-label">
<input type="checkbox" id="rpg-toggle-html-prompt">
<i class="fa-solid fa-code"></i>
<span>Enable Immersive HTML</span>
</label>
</div>
<!-- Feature Toggles Row -->
<div class="rpg-features-row" id="rpg-features-row">
<!-- HTML Prompt Toggle -->
<div class="rpg-toggle-container rpg-feature-col" id="rpg-html-toggle-wrapper">
<label class="rpg-toggle-label" title="Immersive HTML">
<input type="checkbox" id="rpg-toggle-html-prompt">
<i class="fa-solid fa-code"></i>
<span class="rpg-toggle-text" data-i18n-key="template.mainPanel.immersiveHtml">Immersive HTML</span>
</label>
</div>
<!-- Dialogue Coloring Toggle -->
<div class="rpg-toggle-container rpg-feature-col" id="rpg-dialogue-coloring-toggle-wrapper">
<label class="rpg-toggle-label" title="Colored Dialogues">
<input type="checkbox" id="rpg-toggle-dialogue-coloring">
<i class="fa-solid fa-palette"></i>
<span class="rpg-toggle-text" data-i18n-key="template.mainPanel.coloredDialogues">Colored Dialogues</span>
</label>
</div>
<!-- Spotify Music Toggle -->
<div class="rpg-toggle-container rpg-feature-col" id="rpg-spotify-toggle-wrapper">
<label class="rpg-toggle-label" title="Spotify Music">
<input type="checkbox" id="rpg-toggle-spotify-music">
<i class="fa-brands fa-spotify"></i>
<span class="rpg-toggle-text" data-i18n-key="template.mainPanel.spotifyMusic">Spotify Music</span>
</label>
</div>
<!-- Dynamic Weather Toggle -->
<div class="rpg-toggle-container rpg-feature-col" id="rpg-dynamic-weather-toggle-wrapper">
<label class="rpg-toggle-label" title="Dynamic Weather Effects">
<input type="checkbox" id="rpg-toggle-dynamic-weather">
<i class="fa-solid fa-cloud-sun-rain"></i>
<span class="rpg-toggle-text" data-i18n-key="template.mainPanel.dynamicWeatherEffects">Dynamic Weather</span>
</label>
</div>
<!-- Narrator Mode Toggle -->
<div class="rpg-toggle-container rpg-feature-col" id="rpg-narrator-toggle-wrapper">
<label class="rpg-toggle-label" title="Narrator Mode">
<input type="checkbox" id="rpg-toggle-narrator">
<i class="fa-solid fa-book-open"></i>
<span class="rpg-toggle-text" data-i18n-key="template.mainPanel.narratorMode">Narrator Mode</span>
</label>
</div>
<!-- Auto-generate Avatars Toggle -->
<div class="rpg-toggle-container rpg-feature-col" id="rpg-auto-avatars-toggle-wrapper">
<label class="rpg-toggle-label" title="Auto-generate Avatars">
<input type="checkbox" id="rpg-toggle-auto-avatars-panel">
<i class="fa-solid fa-user-plus"></i>
<span class="rpg-toggle-text" data-i18n-key="template.mainPanel.autoAvatars">Auto Avatars</span>
</label>
</div> </div>
<!-- Manual Update Button -->
<button id="rpg-manual-update" class="rpg-btn-primary rpg-manual-update-btn">
<i class="fa-solid fa-sync"></i> Refresh RPG Info
<i class="fa-solid fa-sync"></i> <span data-i18n-key="template.mainPanel.refreshRpgInfo">Refresh RPG
Info</span>
</button>
<!-- Settings and Edit Trackers Buttons Row -->
<div class="rpg-settings-buttons-row">
<button id="rpg-open-tracker-editor" class="rpg-btn-settings rpg-btn-half">
<i class="fa-solid fa-sliders"></i> Edit Trackers
<i class="fa-solid fa-sliders"></i> <span data-i18n-key="template.mainPanel.editTrackersButton">Edit
Trackers</span>
</button>
<button id="rpg-open-settings" class="rpg-btn-settings rpg-btn-half">
<i class="fa-solid fa-gear"></i> Settings
<i class="fa-solid fa-gear"></i> <span
data-i18n-key="template.mainPanel.settingsButton">Settings</span>
</button>
</div>
</div>
@@ -87,188 +146,449 @@
</div>
<!-- Settings Modal -->
<div id="rpg-settings-popup" class="rpg-settings-popup" role="dialog" aria-modal="true" aria-labelledby="rpg-settings-title">
<div id="rpg-settings-popup" class="rpg-settings-popup" role="dialog" aria-modal="true"
aria-labelledby="rpg-settings-title">
<div class="rpg-settings-popup-content">
<header class="rpg-settings-popup-header">
<h3 id="rpg-settings-title">
<i class="fa-solid fa-gear" aria-hidden="true"></i>
<span>RPG Companion Settings</span>
<span data-i18n-key="template.settingsTitle">RPG Companion Settings</span>
</h3>
<button id="rpg-close-settings" class="rpg-popup-close" type="button" aria-label="Close settings">&times;</button>
<button id="rpg-close-settings" class="rpg-popup-close" type="button"
aria-label="Close settings">&times;</button>
</header>
<div class="rpg-settings-popup-body">
<div class="rpg-settings-group">
<h4><i class="fa-solid fa-palette" aria-hidden="true"></i> Theme</h4>
<h4 data-i18n-key="template.settingsModal.themeTitle"><i class="fa-solid fa-palette"
aria-hidden="true"></i> Theme</h4>
<div class="rpg-setting-row">
<label for="rpg-theme-select">Visual Theme:</label>
<label for="rpg-theme-select" data-i18n-key="template.settingsModal.themeLabel">Visual
Theme:</label>
<select id="rpg-theme-select" class="rpg-select">
<option value="default">Default</option>
<option value="sci-fi">Sci-Fi (Synthwave)</option>
<option value="fantasy">Fantasy (Rustic Parchment)</option>
<option value="cyberpunk">Cyberpunk (Neon Grid)</option>
<option value="custom">Custom</option>
<option value="default" data-i18n-key="template.settingsModal.themeOptions.default">Default
</option>
<option value="sci-fi" data-i18n-key="template.settingsModal.themeOptions.sciFi">Sci-Fi
(Synthwave)</option>
<option value="fantasy" data-i18n-key="template.settingsModal.themeOptions.fantasy">Fantasy
(Rustic Parchment)</option>
<option value="cyberpunk" data-i18n-key="template.settingsModal.themeOptions.cyberpunk">
Cyberpunk (Neon Grid)</option>
<option value="custom" data-i18n-key="template.settingsModal.themeOptions.custom">Custom
</option>
</select>
</div>
<!-- Custom Theme Colors (Hidden by default) -->
<div id="rpg-custom-colors" class="rpg-custom-colors" style="display: none;">
<div class="rpg-setting-row">
<label for="rpg-custom-bg">Background:</label>
<label for="rpg-custom-bg"
data-i18n-key="template.settingsModal.themeOptions.custom.background">Background:</label>
<input type="color" id="rpg-custom-bg" value="#1a1a2e" />
</div>
<div class="rpg-setting-row">
<label for="rpg-custom-accent">Accent:</label>
<label for="rpg-custom-accent"
data-i18n-key="template.settingsModal.themeOptions.custom.accent">Accent:</label>
<input type="color" id="rpg-custom-accent" value="#16213e" />
</div>
<div class="rpg-setting-row">
<label for="rpg-custom-text">Text:</label>
<label for="rpg-custom-text"
data-i18n-key="template.settingsModal.themeOptions.custom.text">Text:</label>
<input type="color" id="rpg-custom-text" value="#eaeaea" />
</div>
<div class="rpg-setting-row">
<label for="rpg-custom-highlight">Highlight:</label>
<label for="rpg-custom-highlight"
data-i18n-key="template.settingsModal.themeOptions.custom.highlight">Highlight:</label>
<input type="color" id="rpg-custom-highlight" value="#e94560" />
</div>
</div>
<div class="rpg-setting-row">
<label for="rpg-stat-bar-color-low">Stat Bar Color (Low):</label>
<label for="rpg-stat-bar-color-low" data-i18n-key="template.settingsModal.theme.statBarLow">Stat Bar
Color (Low):</label>
<input type="color" id="rpg-stat-bar-color-low" value="#cc3333" />
<small>Color when stats are at 0%</small>
<small data-i18n-key="template.settingsModal.theme.statBarLowNote">Color when stats are at
0%.</small>
</div>
<div class="rpg-setting-row">
<label for="rpg-stat-bar-color-high">Stat Bar Color (High):</label>
<label for="rpg-stat-bar-color-high" data-i18n-key="template.settingsModal.theme.statBarHigh">Stat
Bar Color (High):</label>
<input type="color" id="rpg-stat-bar-color-high" value="#33cc66" />
<small>Color when stats are at 100%</small>
<small data-i18n-key="template.settingsModal.theme.statBarHighNote">Color when stats are at
100%.</small>
</div>
</div>
<div class="rpg-settings-group">
<h4><i class="fa-solid fa-toggle-on" aria-hidden="true"></i> Display Options</h4>
<small class="notes" style="display: block; margin-bottom: 10px;">
<i class="fa-solid fa-info-circle" aria-hidden="true"></i> Use the Extensions tab to enable/disable the RPG Companion extension.
<h4 data-i18n-key="template.settingsModal.displayTitle"><i class="fa-solid fa-toggle-on"
aria-hidden="true"></i> Display Options</h4>
<small class="notes" style="display: block; margin-bottom: 10px;"
data-i18n-key="template.settingsModal.displayNote">
<i class="fa-solid fa-info-circle" aria-hidden="true"></i> Use the Extensions tab to enable/disable
the RPG Companion extension entirely
</small>
<div class="rpg-setting-row">
<label for="rpg-position-select">Panel Position:</label>
<label for="rpg-position-select" data-i18n-key="template.settingsModal.display.panelPosition">Panel
Position:</label>
<select id="rpg-position-select" class="rpg-select">
<option value="right">Right Sidebar</option>
<option value="left">Left Sidebar</option>
<option value="right" data-i18n-key="template.settingsModal.display.panelPositionOptions.right">
Right Sidebar</option>
<option value="left" data-i18n-key="template.settingsModal.display.panelPositionOptions.left">
Left Sidebar</option>
</select>
</div>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-auto-update" />
<span>Auto-update after messages</span>
</label>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-user-stats" />
<span>Show User Stats</span>
<span data-i18n-key="template.settingsModal.display.showUserStats">Show User Stats</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showUserStatsNote">
Enable User Stats that track your persona's statistics, mood, attributes, skills, etc.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-info-box" />
<span>Show Info Box</span>
<span data-i18n-key="template.settingsModal.display.showInfoBox">Show Info Box</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showInfoBoxNote">
Display location, time, weather, and recent events.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-thoughts" />
<span>Show Present Characters</span>
</label>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-inventory" />
<span>Show Inventory</span>
<span data-i18n-key="template.settingsModal.display.showPresentCharacters">Show Present
Characters</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showPresentCharactersNote">
Display character portraits with their current thoughts and status.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-thoughts-in-chat" />
<span>Show Thoughts in Chat</span>
<span data-i18n-key="template.settingsModal.display.showThoughtsInChat">Show Thoughts</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;">
Display character thoughts as overlay bubbles next to their messages
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showThoughtsInChatNote">
Display character thoughts as overlay bubbles next to their messages.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-always-show-bubble" />
<span>Always Show Thought Bubble</span>
<input type="checkbox" id="rpg-toggle-inventory" />
<span data-i18n-key="template.settingsModal.display.showInventory">Show Inventory</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;">
Auto-expand thought bubble without clicking the icon first
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showInventoryNote">
Track items carried, clothing worn, stored items, and assets.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-animations" />
<span>Enable Animations</span>
<input type="checkbox" id="rpg-toggle-quests" />
<span data-i18n-key="template.settingsModal.display.showQuests">Show Quests</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;">
Smooth transitions for stats, content updates, and dice rolls
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showQuestsNote">
Manage main and optional quests with objectives.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-plot-buttons" />
<span>Show Plot Progression Buttons</span>
<input type="checkbox" id="rpg-toggle-lock-icons" />
<span data-i18n-key="template.settingsModal.display.showLockIcons">Show Locking/Unlocking Trackers</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;">
Display buttons above chat input for plot progression prompts
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showLockIconsNote">
Display lock/unlock icons on tracker items to prevent AI from modifying them.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-debug-mode" />
<span>Enable Debug Mode</span>
<input type="checkbox" id="rpg-toggle-show-html-toggle" />
<span data-i18n-key="template.settingsModal.display.showImmersiveHtmlToggle">Show Immersive HTML</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;">
Shows parser logs in a mobile-friendly UI panel. Useful for troubleshooting. Look for the red bug button.
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showImmersiveHtmlToggleNote">
Display a toggle button to enable/disable HTML formatting in messages.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-show-dialogue-coloring-toggle" />
<span data-i18n-key="template.settingsModal.display.showDialogueColoringToggle">Show Colored Dialogues</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showDialogueColoringToggleNote">
Display a toggle button to enable/disable colored dialogue formatting.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-show-spotify-toggle" />
<span data-i18n-key="template.settingsModal.display.showSpotifyMusicToggle">Show Spotify Music</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showSpotifyMusicToggleNote">
Display Spotify music player with AI-suggested scene-appropriate tracks.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-show-dynamic-weather-toggle" />
<span data-i18n-key="template.settingsModal.display.showDynamicWeatherToggle">Show Dynamic Weather Effects</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showDynamicWeatherToggleNote">
Display a toggle button to enable/disable animated weather effects.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-show-narrator-mode" />
<span data-i18n-key="template.settingsModal.display.showNarratorMode">Show Narrator Mode</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showNarratorModeNote">
Display a toggle button to enable/disable narrator mode (infer characters from context).
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-show-auto-avatars" />
<span data-i18n-key="template.settingsModal.display.showAutoAvatars">Show Auto-generate Avatars</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showAutoAvatarsNote">
Display a toggle button to automatically generate avatars for characters without images.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-randomized-plot" />
<span data-i18n-key="template.settingsModal.display.showRandomizedPlot">Show Randomized Plot Progression</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showRandomizedPlotNote">
Display button for AI-generated random plot progression prompts.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-natural-plot" />
<span data-i18n-key="template.settingsModal.display.showNaturalPlot">Show Natural Plot Progression</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showNaturalPlotNote">
Display button for context-aware narrative continuation prompts.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-encounters" />
<span data-i18n-key="template.settingsModal.display.showStartEncounter">Show Start Encounter</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showStartEncounterNote">
Display button to initiate interactive combat encounters.
</small>
<label class="checkbox_label">
<input type="checkbox" id="rpg-toggle-dice-display" />
<span data-i18n-key="template.settingsModal.display.showDiceDisplay">Show Dice Roll Display</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.showDiceDisplayNote">
Display the "Last Roll" indicator in the panel
</small>
</div>
<div class="rpg-settings-group">
<h4><i class="fa-solid fa-sliders" aria-hidden="true"></i> Advanced</h4>
<h4 data-i18n-key="template.settingsModal.advancedTitle"><i class="fa-solid fa-sliders"
aria-hidden="true"></i> Advanced</h4>
<div class="rpg-setting-row">
<label for="rpg-generation-mode">Generation Mode:</label>
<label for="rpg-generation-mode"
data-i18n-key="template.settingsModal.advanced.generationMode">Generation Mode:</label>
<select id="rpg-generation-mode" class="rpg-select">
<option value="together">Together with Main Generation</option>
<option value="separate">Separate Generation</option>
<option value="together"
data-i18n-key="template.settingsModal.advanced.generationModeOptions.together">Together with
Main Generation</option>
<option value="separate"
data-i18n-key="template.settingsModal.advanced.generationModeOptions.separate">Separate
Generation</option>
<option value="external"
data-i18n-key="template.settingsModal.advanced.generationModeOptions.external">External API
</option>
</select>
<small>Together: Adds RPG tracking to main roleplay. Separate: Generates RPG data separately (manual or auto).</small>
<small data-i18n-key="template.settingsModal.advanced.generationModeNote">Together: Adds RPG
tracking to main roleplay. Separate: Generates RPG data separately (manual or auto).</small>
</div>
<div class="rpg-setting-row">
<label for="rpg-update-depth">Context Messages:</label>
<input type="number" id="rpg-update-depth" min="1" max="20" value="4" class="rpg-input" />
<small>Number of recent messages to include (Separate mode only)</small>
<!-- External API Settings (shown only when External API mode is selected) -->
<div id="rpg-external-api-settings" class="rpg-external-api-settings"
style="display: none; padding: 12px; border-left: 2px solid var(--SmartThemeBorderColor); margin-top: 8px;">
<h5 style="margin-top: 0; margin-bottom: 12px; color: var(--SmartThemeBodyColor);">
<i class="fa-solid fa-cloud" aria-hidden="true"></i>
<span data-i18n-key="template.settingsModal.advanced.externalApi.title">External API
Configuration</span>
</h5>
<div class="rpg-setting-row">
<label for="rpg-external-base-url"
data-i18n-key="template.settingsModal.advanced.externalApi.baseUrl">API Base URL:</label>
<input type="text" id="rpg-external-base-url" class="rpg-input"
placeholder="https://api.openai.com/v1" style="width: 100%;" />
<small data-i18n-key="template.settingsModal.advanced.externalApi.baseUrlNote">OpenAI-compatible
endpoint (e.g., OpenAI, OpenRouter, local LLM server)</small>
</div>
<div class="rpg-setting-row">
<label for="rpg-external-api-key"
data-i18n-key="template.settingsModal.advanced.externalApi.apiKey">API Key:</label>
<div style="display: flex; gap: 8px; width: 100%;">
<input type="password" id="rpg-external-api-key" class="rpg-input" placeholder="sk-..."
style="flex: 1;" />
<button id="rpg-toggle-api-key-visibility" class="menu_button" type="button"
title="Show/Hide API Key" style="padding: 4px 8px;">
<i class="fa-solid fa-eye"></i>
</button>
</div>
<small data-i18n-key="template.settingsModal.advanced.externalApi.apiKeyNote">Your API key for
the external service</small>
</div>
<div class="rpg-setting-row">
<label for="rpg-external-model"
data-i18n-key="template.settingsModal.advanced.externalApi.model">Model:</label>
<input type="text" id="rpg-external-model" class="rpg-input" placeholder="gpt-4o-mini"
style="width: 100%;" />
<small data-i18n-key="template.settingsModal.advanced.externalApi.modelNote">Model identifier
(e.g., gpt-4o-mini, claude-3-haiku, mistral-7b)</small>
</div>
<div class="rpg-setting-row" style="display: flex; gap: 16px;">
<div style="flex: 1;">
<label for="rpg-external-max-tokens"
data-i18n-key="template.settingsModal.advanced.externalApi.maxTokens">Max
Tokens:</label>
<input type="number" id="rpg-external-max-tokens" class="rpg-input" min="256" max="16384"
value="8192" style="width: 100%;" />
</div>
<div style="flex: 1;">
<label for="rpg-external-temperature"
data-i18n-key="template.settingsModal.advanced.externalApi.temperature">Temperature:</label>
<input type="number" id="rpg-external-temperature" class="rpg-input" min="0" max="2"
step="0.1" value="0.7" style="width: 100%;" />
</div>
</div>
<div style="margin-top: 12px;">
<button id="rpg-test-external-api" class="menu_button" type="button" style="width: 100%; display: flex; align-items: center; gap: 8px;">
<i class="fa-solid fa-plug"></i>
<span data-i18n-key="template.settingsModal.advanced.externalApi.testConnection">Test
Connection</span>
</button>
<div id="rpg-external-api-test-result"
style="margin-top: 8px; padding: 8px; border-radius: 4px; display: none;"></div>
</div>
</div>
<div id="rpg-separate-mode-settings">
<div class="rpg-setting-row">
<label for="rpg-update-depth"
data-i18n-key="template.settingsModal.advanced.contextMessages">Context Messages:</label>
<input type="number" id="rpg-update-depth" min="1" max="20" value="4" class="rpg-input" />
<small data-i18n-key="template.settingsModal.advanced.contextMessagesNote">Number of recent messages
to include (Separate/External mode)</small>
</div>
</div>
<label class="checkbox_label" id="rpg-auto-update-container" style="margin-top: 16px;">
<input type="checkbox" id="rpg-toggle-auto-update" />
<span data-i18n-key="template.settingsModal.display.toggleAutoUpdate">Auto-update after
messages</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.display.toggleAutoUpdateNote">
Automatically refresh RPG info after each message.
</small>
<label class="checkbox_label" style="margin-top: 16px;">
<input type="checkbox" id="rpg-save-tracker-history" />
<span data-i18n-key="template.settingsModal.advanced.saveTrackerHistory">Save Tracker History in
Chat</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.advanced.saveTrackerHistoryNote">
When enabled, tracker data is saved in chat history for each message. In Together mode, trackers
appear in &lt;trackers&gt; XML tags (hidden from display). In Separate mode, tracker data is stored
in message metadata. When disabled, only the most recent trackers are kept.
</small>
<div class="rpg-setting-row">
<label for="rpg-memory-messages">Memory Batch Size:</label>
<input type="number" id="rpg-memory-messages" min="4" max="50" value="16" class="rpg-input" />
<small>Number of messages to process per batch in Memory Recollection</small>
<label for="rpg-encounter-history-depth" data-i18n-key="template.settingsModal.advanced.encounterHistoryDepth">Chat History Depth For Encounters:</label>
<input type="number" id="rpg-encounter-history-depth" min="1" max="20" value="8"
class="rpg-input" />
<small data-i18n-key="template.settingsModal.advanced.encounterHistoryDepthNote">Number of recent messages to include in combat initialization.</small>
</div>
<label class="checkbox_label">
<input type="checkbox" id="rpg-use-separate-preset" />
<span>Use model connected to RPG Companion Trackers preset</span>
<input type="checkbox" id="rpg-toggle-autosave-logs" />
<span data-i18n-key="template.settingsModal.advanced.autoSaveCombatLogs">Auto-save Combat Logs</span>
</label>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;">
Separate mode only. When enabled, tracker generation will use the model from the "RPG Companion Trackers" preset instead of your main API model. The preset will be switched automatically during generation and restored afterward. Select the desired model in that preset and make sure the "Bind presets to API connections" toggle is on (next to the import/export preset buttons).
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.advanced.autoSaveCombatLogsNote">
Save detailed combat logs to file for future reference and analysis.
</small>
<!-- Clear Cache Button -->
<div class="rpg-setting-row" style="margin-top: 16px;">
<label for="rpg-skip-guided-mode"
data-i18n-key="template.settingsModal.advanced.skipInjections">Skip Injections during Guided
Generations:</label>
<select id="rpg-skip-guided-mode" class="rpg-select">
<option value="none" data-i18n-key="template.settingsModal.advanced.skipInjectionsOptions.none">
Never skip</option>
<option value="impersonation"
data-i18n-key="template.settingsModal.advanced.skipInjectionsOptions.impersonation">Only on
impersonation requests</option>
<option value="guided"
data-i18n-key="template.settingsModal.advanced.skipInjectionsOptions.guided">Always for
guided or quiet prompts</option>
</select>
</div>
<small style="display: block; margin-left: 24px; margin-top: -8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.advanced.skipInjectionsNote">
When set, the extension will not inject tracker prompts, examples, or HTML instructions according to
the selected mode when a guided generation (via `instruct` or `quiet_prompt`) is detected. Useful
when using GuidedGenerations or similar extensions.
</small>
<!-- Customize Prompts Button -->
<div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--rpg-border);">
<button id="rpg-clear-cache" class="rpg-btn-clear-cache">
<i class="fa-solid fa-trash" aria-hidden="true"></i> Clear Extension Cache
<button id="rpg-open-prompts-editor" class="rpg-btn-customize-prompts">
<i class="fa-solid fa-file-lines" aria-hidden="true"></i> <span>Customize Prompts</span>
</button>
<small style="display: block; margin-top: 8px; color: #888; font-size: 11px;">
Edit all AI prompts used for generation, plot progression, and combat encounters.
</small>
</div>
<!-- Reset FAB Positions Button -->
<div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--rpg-border);">
<button id="rpg-reset-fab-positions" class="rpg-btn-reset-fab">
<i class="fa-solid fa-arrows-rotate" aria-hidden="true"></i> Reset Button Positions
<i class="fa-solid fa-arrows-rotate" aria-hidden="true"></i> <span
data-i18n-key="template.settingsModal.advanced.resetFabPositions">Reset Button
Positions</span>
</button>
<small style="display: block; margin-top: 8px; color: #888; font-size: 11px;">
Resets all floating action buttons (toggle, refresh, debug) to default top-left positions. Useful if buttons are off-screen.
<small style="display: block; margin-top: 8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.advanced.resetFabPositionsNote">
Resets all floating action buttons (toggle, refresh) to default top-left positions.
Useful if buttons are off-screen.
</small>
</div>
<!-- Clear Cache Button -->
<div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--rpg-border);">
<button id="rpg-clear-cache" class="rpg-btn-clear-cache">
<i class="fa-solid fa-trash" aria-hidden="true"></i> <span
data-i18n-key="template.settingsModal.advanced.clearCache">Clear Extension Cache</span>
</button>
<small style="display: block; margin-top: 8px; color: #888; font-size: 11px;"
data-i18n-key="template.settingsModal.advanced.clearCacheNote">
Clears all cached data including tracker history and temporary files.
</small>
</div>
</div>
@@ -294,7 +614,8 @@
<div class="rpg-dice-selector">
<div class="rpg-dice-input-group">
<label for="rpg-dice-count">Number of Dice:</label>
<input type="number" id="rpg-dice-count" name="dice-count" min="1" max="20" value="1" class="rpg-input" />
<input type="number" id="rpg-dice-count" name="dice-count" min="1" max="20" value="1"
class="rpg-input" />
</div>
<div class="rpg-dice-input-group">
<label for="rpg-dice-sides">Dice Type:</label>
@@ -324,7 +645,8 @@
<div id="rpg-dice-result" class="rpg-dice-result" hidden aria-live="polite">
<div class="rpg-dice-result-label">Result:</div>
<output id="rpg-dice-result-value" class="rpg-dice-result-value" for="rpg-dice-count rpg-dice-sides">0</output>
<output id="rpg-dice-result-value" class="rpg-dice-result-value"
for="rpg-dice-count rpg-dice-sides">0</output>
<div id="rpg-dice-result-details" class="rpg-dice-result-details" role="status"></div>
<button id="rpg-dice-save-btn" class="rpg-btn-primary rpg-dice-save-btn" type="button">
<i class="fa-solid fa-check" aria-hidden="true"></i>
@@ -336,26 +658,31 @@
</div>
<!-- Tracker Editor Modal -->
<div id="rpg-tracker-editor-popup" class="rpg-settings-popup" role="dialog" aria-modal="true" aria-labelledby="rpg-editor-title" style="display: none;">
<div id="rpg-tracker-editor-popup" class="rpg-settings-popup" role="dialog" aria-modal="true"
aria-labelledby="rpg-editor-title" style="display: none;">
<div class="rpg-settings-popup-content">
<header class="rpg-settings-popup-header">
<h3 id="rpg-editor-title">
<i class="fa-solid fa-sliders" aria-hidden="true"></i>
<span>Edit Trackers</span>
<span data-i18n-key="template.trackerEditorModal.title">Edit Trackers</span>
</h3>
<button id="rpg-close-tracker-editor" class="rpg-popup-close" type="button" aria-label="Close tracker editor">&times;</button>
<button id="rpg-close-tracker-editor" class="rpg-popup-close" type="button"
aria-label="Close tracker editor">&times;</button>
</header>
<!-- Tabs -->
<div class="rpg-editor-tabs">
<button class="rpg-editor-tab active" data-tab="userStats">
<i class="fa-solid fa-heart-pulse"></i> User Stats
<i class="fa-solid fa-heart-pulse"></i> <span
data-i18n-key="template.trackerEditorModal.tabs.userStats">User Stats</span>
</button>
<button class="rpg-editor-tab" data-tab="infoBox">
<i class="fa-solid fa-info-circle"></i> Info Box
<i class="fa-solid fa-info-circle"></i> <span
data-i18n-key="template.trackerEditorModal.tabs.infoBox">Info Box</span>
</button>
<button class="rpg-editor-tab" data-tab="presentCharacters">
<i class="fa-solid fa-users"></i> Present Characters
<i class="fa-solid fa-users"></i> <span
data-i18n-key="template.trackerEditorModal.tabs.presentCharacters">Present Characters</span>
</button>
</div>
@@ -367,15 +694,289 @@
</div>
<footer class="rpg-settings-popup-footer">
<button id="rpg-editor-reset" class="rpg-btn-secondary" type="button">
<i class="fa-solid fa-rotate-left"></i> Reset to Defaults
<div class="rpg-editor-footer-buttons">
<div class="rpg-editor-footer-row">
<button id="rpg-editor-reset" class="rpg-btn-secondary" type="button">
<i class="fa-solid fa-rotate-left"></i> <span
data-i18n-key="template.trackerEditorModal.buttons.reset">Reset</span>
</button>
<button id="rpg-editor-export" class="rpg-btn-secondary" type="button">
<i class="fa-solid fa-file-export"></i> <span
data-i18n-key="template.trackerEditorModal.buttons.export">Export</span>
</button>
<button id="rpg-editor-import" class="rpg-btn-secondary" type="button">
<i class="fa-solid fa-file-import"></i> <span
data-i18n-key="template.trackerEditorModal.buttons.import">Import</span>
</button>
</div>
<div class="rpg-editor-footer-row">
<button id="rpg-editor-save" class="rpg-btn-primary" type="button">
<i class="fa-solid fa-save"></i> <span data-i18n-key="template.trackerEditorModal.buttons.save">Save & Apply</span>
</button>
</div>
</div>
</footer>
</div>
</div>
<!-- Prompts Editor Modal -->
<div id="rpg-prompts-editor-popup" class="rpg-settings-popup" role="dialog" aria-modal="true"
aria-labelledby="rpg-prompts-editor-title" style="display: none;">
<div class="rpg-settings-popup-content">
<header class="rpg-settings-popup-header">
<h3 id="rpg-prompts-editor-title">
<i class="fa-solid fa-file-lines" aria-hidden="true"></i>
<span>Customize Prompts</span>
</h3>
<button id="rpg-close-prompts-editor" class="rpg-popup-close" type="button"
aria-label="Close prompts editor">&times;</button>
</header>
<div class="rpg-settings-popup-body">
<small class="notes" style="display: block; margin-bottom: 16px;">
Customize the AI prompts used throughout the extension. Leave fields empty to use defaults.
</small>
<!-- HTML Prompt -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-html" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-code"></i> HTML Prompt
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Injected when "Enable Immersive HTML" is enabled. Affects all generation modes.
</small>
<textarea id="rpg-prompt-html" class="rpg-prompt-textarea" rows="4"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="html" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Dialogue Coloring Prompt -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-dialogue-coloring" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-palette"></i> Dialogue Coloring Prompt
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Injected when "Enable Dialogue Coloring" is enabled. Affects all generation modes.
</small>
<textarea id="rpg-prompt-dialogue-coloring" class="rpg-prompt-textarea" rows="4"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="dialogue-coloring" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Spotify Music Prompt -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-spotify" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-brands fa-spotify"></i> Spotify Music Prompt
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Injected when "Enable Spotify Music" is enabled. Asks AI to suggest appropriate music for the scene.
</small>
<textarea id="rpg-prompt-spotify" class="rpg-prompt-textarea" rows="4"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="spotify" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Narrator Mode Prompt -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-narrator" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-book-open"></i> Narrator Mode Prompt
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Injected when "Narrator Mode" is enabled. Instructs AI to infer characters from context.
</small>
<textarea id="rpg-prompt-narrator" class="rpg-prompt-textarea" rows="3"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="narrator" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Random Plot Progression Prompt -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-plot-random" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-dice"></i> Random Plot Progression Prompt
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Injected when the "Randomized Plot" button is clicked. Introduces random elements to the story.
</small>
<textarea id="rpg-prompt-plot-random" class="rpg-prompt-textarea" rows="6"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="plotRandom" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Natural Plot Progression Prompt -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-plot-natural" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-forward"></i> Natural Plot Progression Prompt
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Injected when the "Natural Plot" button is clicked. Progresses the story naturally.
</small>
<textarea id="rpg-prompt-plot-natural" class="rpg-prompt-textarea" rows="4"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="plotNatural" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Avatar Generation Instruction -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-avatar" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-user-circle"></i> Avatar Generation Instruction
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Instructions for LLM when generating avatar image prompts. Used by Auto-generate Missing Avatars feature.
</small>
<textarea id="rpg-prompt-avatar" class="rpg-prompt-textarea" rows="3"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="avatar" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Tracker Instructions -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-tracker-instructions" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-list-check"></i> Tracker Instructions
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Instruction portion only (format specification is hardcoded). {userName} will be replaced with the user's name.
</small>
<textarea id="rpg-prompt-tracker-instructions" class="rpg-prompt-textarea" rows="4"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="trackerInstructions" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Tracker Continuation Instruction -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-tracker-continuation" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-arrow-right"></i> Tracker Continuation Instruction
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Instructions added after tracker format specifications, telling the AI how to continue the narrative.
</small>
<textarea id="rpg-prompt-tracker-continuation" class="rpg-prompt-textarea" rows="4"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="trackerContinuation" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
<!-- Combat Narrative Style Instruction -->
<div class="rpg-prompt-editor-section">
<label for="rpg-prompt-combat-narrative" style="display: block; margin-bottom: 8px; font-weight: 600;">
<i class="fa-solid fa-fire"></i> Combat Narrative Style Instruction
</label>
<small style="display: block; margin-bottom: 8px; color: #888; font-size: 11px;">
Writing style instructions for combat encounters. Includes prose quality guidelines and anti-repetition rules. {userName} will be replaced with the user's name.
</small>
<textarea id="rpg-prompt-combat-narrative" class="rpg-prompt-textarea" rows="6"></textarea>
<button class="menu_button rpg-restore-prompt-btn" data-prompt="combatNarrative" style="margin-top: 8px;">
<i class="fa-solid fa-rotate-left"></i>&nbsp;Restore Default
</button>
</div>
</div>
<footer class="rpg-settings-popup-footer">
<button id="rpg-prompts-restore-all" class="rpg-btn-secondary" type="button">
<i class="fa-solid fa-rotate-left"></i> Restore All To Default
</button>
<div class="rpg-footer-right">
<button id="rpg-editor-cancel" class="rpg-btn-secondary" type="button">Cancel</button>
<button id="rpg-editor-save" class="rpg-btn-primary" type="button">
<i class="fa-solid fa-save"></i> Save & Apply
<button id="rpg-prompts-cancel" class="rpg-btn-secondary" type="button">Cancel</button>
<button id="rpg-prompts-save" class="rpg-btn-primary" type="button">
<i class="fa-solid fa-save"></i> Save Changes
</button>
</div>
</footer>
</div>
</div>
<!-- Welcome Modal for v3.0 -->
<div id="rpg-welcome-modal" class="rpg-settings-popup" role="dialog" aria-modal="true"
aria-labelledby="rpg-welcome-title" style="display: none;">
<div class="rpg-settings-popup-content" style="max-width: 600px;">
<header class="rpg-settings-popup-header">
<h3 id="rpg-welcome-title">
<i class="fa-solid fa-stars"></i>
Welcome to RPG Companion v.3.2.0!
</h3>
<button id="rpg-welcome-close" class="rpg-popup-close" type="button"
aria-label="Close Welcome">
<i class="fa-solid fa-times"></i>
</button>
</header>
<div class="rpg-settings-popup-body" style="max-height: 500px; overflow-y: auto; padding: 20px;">
<div style="background: rgba(255, 165, 0, 0.1); border-left: 3px solid orange; padding: 12px; margin-bottom: 20px;">
<strong style="color: orange;">⚠️ Important:</strong> Due to a change in the tracker format, we recommend that you use <strong>Clear Extension Cache</strong> in the Settings before you start using this version!
</div>
<h4 style="margin-top: 20px; margin-bottom: 10px;"><strong>What's new?</strong></h4>
<ul style="line-height: 1.6; margin-left: 20px;">
<li>Switched to the JSON format for the trackers.</li>
<li>You can now lock/unlock trackers that you don't want the model to change between generations.</li>
<li>Removed features that were half-baked or didn't work.</li>
<li>Organized Settings and Edit Trackers windows.</li>
<li>All features of the extension are now accessible from the main panel view.</li>
<li>Added Colored Dialogues option that makes the model color dialogue lines differently depending on the speaker.</li>
<li>Introduced Dynamic Weather Effects that add visual effects to your SillyTavern window depending on the current weather from the trackers.</li>
<li>All prompts used for the extension's features are now editable.</li>
<li>Made the user's level optional in the Edit Trackers.</li>
</ul>
<h4 style="margin-top: 20px; margin-bottom: 10px;"><strong>Bug Fixes:</strong></h4>
<ul style="line-height: 1.6; margin-left: 20px;">
<li>Fixed tracker logic in Together generation mode.</li>
<li>Fixed various UI bugs (too many to count).</li>
<li>Upgraded mobile view.</li>
<li>Spotify Music widget is more visible now, plus it works in the mobile view.</li>
<li>Auto-update after messages option is now available for External API generation mode.</li>
<li>Fixed the display of the thoughts window and its mobile display.</li>
<li>Mobile UI fixes (panel viewport and z-index issues).</li>
<li>Fixed the regex issue in Together mode (JSON blocks now hidden from display).</li>
<li>Fixed parsing error appearing when loading or switching chats.</li>
<li>Fixed adding new relationships in Edit Trackers (unique naming).</li>
<li>Added migration support for importing older tracker presets.</li>
<li>Lifted attributes cap from 100 to 999.</li>
<li>Fixed lock icon positioning on mobile devices.</li>
<li>Fixed smaller bugs.</li>
</ul>
<h4 style="margin-top: 20px; margin-bottom: 10px;"><strong data-i18n="settings.recommendedModels.title">Recommended Models:</strong></h4>
<p style="margin-left: 20px; line-height: 1.6;" data-i18n="settings.recommendedModels.description">
For the extension to work properly, **it is not recommended to use any models below 20B, especially if they're old.** It works best with the SOTA models such as Deepseek, Claude, GPT, or Gemini.
</p>
<h4 style="margin-top: 20px; margin-bottom: 10px;"><strong>Special thanks to all the other contributors for this project:</strong></h4>
<p style="margin-left: 20px; line-height: 1.6;">
Paperboygold, Munimunigamer, Subarashimo, Lilminzyu, Claude (???), IDeathByte, Chungchandev, Joenunezb, and Amauragis.
</p>
<div style="margin-top: 20px; text-align: center;">
<p style="margin-bottom: 10px;">Join our Discord server to share your feedback, report bugs, or request new features!</p>
<a href="https://discord.com/invite/KdAkTg94ME" target="_blank" class="menu_button" style="display: inline-block; margin: 5px;">
<i class="fa-brands fa-discord"></i> Discord Server
</a>
</div>
<div style="margin-top: 20px; text-align: center;">
<p style="margin-bottom: 10px;">And don't forget to consider supporting me if you enjoy my work. Thank you!</p>
<a href="https://ko-fi.com/marinara_spaghetti" target="_blank" class="menu_button" style="display: inline-block; margin: 5px;">
<i class="fa-solid fa-heart"></i> Support on Ko-fi
</a>
</div>
<div style="margin-top: 30px; text-align: center; font-size: 18px; font-style: italic;">
<strong>Happy gooning!</strong>
</div>
<div style="margin-top: 10px; text-align: right; color: #888; font-style: italic;">
~ Marinara
</div>
</div>
<footer class="rpg-settings-popup-footer">
<button id="rpg-welcome-got-it" class="rpg-btn-primary" type="button" style="width: 100%;">
<i class="fa-solid fa-check"></i> Got it!
</button>
</footer>
</div>
</div>