From c3cdac24c64e0422d9345a02db91857d93805e54 Mon Sep 17 00:00:00 2001 From: Spicy_Marinara Date: Wed, 7 Jan 2026 17:22:22 +0100 Subject: [PATCH] Release v3.0.0 - Major update with JSON format, lock/unlock trackers, reorganized UI, colored dialogues, editable prompts, and numerous bug fixes --- README.md | 73 +- RPG Companion Trackers.json | 264 ---- index.js | 271 ++-- manifest.json | 4 +- settings.html | 15 +- src/core/config.js | 7 +- src/core/persistence.js | 44 +- src/core/state.js | 109 +- src/i18n/en.json | 65 +- src/i18n/zh-tw.json | 11 +- src/systems/features/avatarGenerator.js | 22 +- src/systems/features/htmlCleaning.js | 83 ++ src/systems/features/jsonCleaning.js | 122 ++ src/systems/features/lorebookLimiter.js | 267 ---- src/systems/features/memoryRecollection.js | 843 ----------- src/systems/features/plotProgression.js | 19 +- src/systems/generation/apiClient.js | 36 +- src/systems/generation/encounterPrompts.js | 51 +- src/systems/generation/injector.js | 197 ++- src/systems/generation/jsonPromptHelpers.js | 209 +++ src/systems/generation/lockManager.js | 463 ++++++ src/systems/generation/parser.js | 360 ++++- src/systems/generation/promptBuilder.js | 714 +++++++--- src/systems/integration/sillytavern.js | 102 +- src/systems/interaction/inventoryActions.js | 51 +- src/systems/interaction/inventoryEdit.js | 52 +- src/systems/rendering/infoBox.js | 232 ++- src/systems/rendering/inventory.js | 210 ++- src/systems/rendering/musicPlayer.js | 8 +- src/systems/rendering/quests.js | 97 +- src/systems/rendering/thoughts.js | 1402 ++++++++++++------- src/systems/rendering/userStats.js | 247 +++- src/systems/ui/debug.js | 220 --- src/systems/ui/desktop.js | 11 +- src/systems/ui/layout.js | 85 +- src/systems/ui/mobile.js | 26 +- src/systems/ui/modals.js | 165 ++- src/systems/ui/promptsEditor.js | 50 +- src/systems/ui/theme.js | 73 +- src/systems/ui/trackerEditor.js | 12 + src/systems/ui/weatherEffects.js | 13 +- src/utils/jsonMigration.js | 433 ++++++ src/utils/jsonRepair.js | 220 +++ src/utils/migration.js | 23 +- style.css | 1381 +++++++++++++----- template.html | 450 +++--- 46 files changed, 6241 insertions(+), 3571 deletions(-) delete mode 100644 RPG Companion Trackers.json create mode 100644 src/systems/features/jsonCleaning.js delete mode 100644 src/systems/features/lorebookLimiter.js delete mode 100644 src/systems/features/memoryRecollection.js create mode 100644 src/systems/generation/jsonPromptHelpers.js create mode 100644 src/systems/generation/lockManager.js delete mode 100644 src/systems/ui/debug.js create mode 100644 src/utils/jsonMigration.js create mode 100644 src/utils/jsonRepair.js diff --git a/README.md b/README.md index a284ef0..b75d8e7 100644 --- a/README.md +++ b/README.md @@ -7,50 +7,30 @@ An immersive RPG extension for browsers that tracks character stats, scene infor ## 🆕 What's New -### v2.1.3 -- **Improved Thought Bubble Positioning**: Thought bubbles now align with the top of the character's avatar/name -- **Better Visibility**: Fixed issue where thought bubbles would extend above the avatar when scrolling is limited -- **Horizontal Thought Circles**: Thought circles now display horizontally for a cleaner visual flow -- **Responsive Positioning**: Thought bubbles dynamically adjust to screen width changes and stay visible at all resolutions -- **Smart Viewport Detection**: Bubbles automatically reposition to avoid being cut off at narrow window widths +### v3.0.0 -### v2.1.2 -- Added optional toggle for Relationship Status Fields in Edit Trackers -- Relationship fields and emoji badges can now be disabled/enabled like other trackers -- Maintains backward compatibility with existing configurations +**What's new?** +- Switched to the JSON format for the trackers. +- You can now lock/unlock trackers that you don't want the model to change between generations. +- Removed features that were half-baked or didn't work. +- Organized Settings and Edit Trackers windows. +- All features of the extension are now accessible from the main panel view. +- Added Colored Dialogues option that makes the model color dialogue lines differently depending on the speaker. +- Introduced Dynamic Weather Effects that add visual effects to your SillyTavern window depending on the current weather from the trackers. +- All prompts used for the extension's features are now editable. +- Made the user's level optional in the Edit Trackers. -### v2.1.1 -- Fixed a bug in together generation mode that didn't detect swipes correctly -- Fixed combat encounter prompt to consider party members better +**Bug Fixes:** +- Fixed tracker logic in Together generation mode. +- Fixed various UI bugs (too many to count). +- Upgraded mobile view. +- Spotify Music widget is more visible now, plus it works in the mobile view. +- Auto-update after messages option is now available for External API generation mode. +- Fixed the display of the thoughts window and its mobile display. +- Fixed smaller bugs. -### v2.1 - Dynamic Weather Effects -- Real-time weather visualization based on Info Box weather field -- **Snow**: Falling snowflakes with varied speeds and sizes -- **Rain**: Realistic raindrops animation -- **Mist/Fog**: Floating fog layers -- **Sunshine**: Sun rays streaming across the screen -- **Storm**: Combined rain + lightning flashes for thunderstorms -- **Wind**: Horizontal wind streaks for breezy conditions -- **Blizzard**: Combined snow + wind effects -- Weather effects positioned behind chat interface for atmospheric background -- Automatically enabled for new users, manual toggle available in panel -- Fully optimized for mobile devices - -### Clothing Inventory System -- New dedicated **Clothing** tab in inventory system -- Separate tracking for clothing and armor items -- AI now handles clothing items independently from general inventory -- Full list/grid view support with add/remove/edit functionality -- Automatic migration for existing users - -### Bug Fixes & Improvements -- Fixed tab visibility issues (disabled tabs now properly hide/show) -- Fixed theme-aware borders (removed hardcoded blue colors) -- Fixed double scrollbar in Edit Trackers window -- Fixed scroll position jumping when editing Present Characters -- Fixed dynamic weather toggle visibility behavior -- Added settings migration system for smooth feature updates -- Improved inventory schema to v2.1 with automatic migration +**Special thanks to all the other contributors for this project:** +Paperboygold, Munimunigamer, Subarashimo, Lilminzyu, Claude, IDeathByte, Chungchandev, Joenunezb, and Amauragis! ## 📥 Installation @@ -104,8 +84,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 @@ -304,13 +282,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 diff --git a/RPG Companion Trackers.json b/RPG Companion Trackers.json deleted file mode 100644 index 62d3ee1..0000000 --- a/RPG Companion Trackers.json +++ /dev/null @@ -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": {} -} \ No newline at end of file diff --git a/index.js b/index.js index 8316b38..bd71a7a 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,7 @@ 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, @@ -92,7 +93,8 @@ import { setupSettingsPopup, updateDiceDisplay, addDiceQuickReply, - getSettingsModal + getSettingsModal, + showWelcomeModalIfNeeded } from './src/systems/ui/modals.js'; import { initTrackerEditor @@ -133,9 +135,8 @@ 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'; @@ -212,12 +213,13 @@ async function addExtensionSettings() { updateChatThoughts(); // Remove thought bubbles cleanupCheckpointUI(); // Remove checkpoint buttons and indicators + // Disable dynamic weather effects + toggleDynamicWeather(false); + // Remove panel and toggle buttons $('#rpg-companion-panel').remove(); $('#rpg-mobile-toggle').remove(); $('#rpg-collapse-toggle').remove(); - $('#rpg-debug-toggle').remove(); - $('#rpg-debug-panel').remove(); $('#rpg-plot-buttons').remove(); // Remove plot buttons } else if (extensionSettings.enabled && !wasEnabled) { // Enabling extension - initialize UI @@ -227,9 +229,6 @@ async function addExtensionSettings() { injectCheckpointButton(); // Re-add checkpoint buttons updateAllCheckpointIndicators(); // Update button states } - - // Update Memory Recollection button visibility - updateMemoryRecollectionButton(); }); // Set up language selector @@ -265,8 +264,9 @@ async function initUI() { $('body').append(templateHtml); // Add mobile toggle button (FAB - Floating Action Button) + const theme = extensionSettings.theme || 'default'; const mobileToggleHtml = ` - `; @@ -309,21 +309,21 @@ 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(); + // Add or remove JSON cleaning regex based on mode + try { + if (extensionSettings.generationMode === 'together') { + await ensureJsonCleaningRegex(st_extension_settings, saveSettingsDebounced); + } else { + removeJsonCleaningRegex(st_extension_settings, saveSettingsDebounced); + } + } catch (error) { + console.error('[RPG Companion] JSON cleaning regex update failed:', error); + } }); $('#rpg-toggle-user-stats').on('change', function() { @@ -344,11 +344,6 @@ async function initUI() { updateSectionVisibility(); }); - $('#rpg-toggle-narrator-mode').on('change', function() { - extensionSettings.narratorMode = $(this).prop('checked'); - saveSettings(); - }); - $('#rpg-toggle-inventory').on('change', function() { extensionSettings.showInventory = $(this).prop('checked'); saveSettings(); @@ -361,6 +356,17 @@ async function initUI() { 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); @@ -368,23 +374,18 @@ async function initUI() { updateChatThoughts(); }); - $('#rpg-toggle-always-show-bubble').on('change', function() { - extensionSettings.alwaysShowThoughtBubble = $(this).prop('checked'); - saveSettings(); - // Force immediate save to ensure setting is persisted before any other code runs - const context = getContext(); - const extension_settings = context.extension_settings || context.extensionSettings; - extension_settings[extensionName] = extensionSettings; - // 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-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(); @@ -392,11 +393,7 @@ async function initUI() { renderMusicPlayer($musicPlayerContainer[0]); }); - $('#rpg-toggle-snowflakes').on('change', function() { - extensionSettings.enableSnowflakes = $(this).prop('checked'); - saveSettings(); - toggleSnowflakes(extensionSettings.enableSnowflakes); - }); + $('#rpg-toggle-dynamic-weather').on('change', function() { extensionSettings.enableDynamicWeather = $(this).prop('checked'); @@ -404,6 +401,11 @@ async function initUI() { 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(); @@ -420,9 +422,14 @@ async function initUI() { 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-randomized-plot').on('change', function() { + extensionSettings.enableRandomizedPlot = $(this).prop('checked'); + saveSettings(); + togglePlotButtons(); + }); + + $('#rpg-toggle-natural-plot').on('change', function() { + extensionSettings.enableNaturalPlot = $(this).prop('checked'); saveSettings(); togglePlotButtons(); }); @@ -543,12 +550,6 @@ async function initUI() { saveSettings(); }); - $('#rpg-toggle-animations').on('change', function() { - extensionSettings.enableAnimations = $(this).prop('checked'); - saveSettings(); - toggleAnimations(); - }); - // Feature toggle visibility controls $('#rpg-toggle-show-html-toggle').on('change', function() { extensionSettings.showHtmlToggle = $(this).prop('checked'); @@ -556,14 +557,14 @@ async function initUI() { updateFeatureTogglesVisibility(); }); - $('#rpg-toggle-show-spotify-toggle').on('change', function() { - extensionSettings.showSpotifyToggle = $(this).prop('checked'); + $('#rpg-toggle-show-dialogue-coloring-toggle').on('change', function() { + extensionSettings.showDialogueColoringToggle = $(this).prop('checked'); saveSettings(); updateFeatureTogglesVisibility(); }); - $('#rpg-toggle-show-snowflakes-toggle').on('change', function() { - extensionSettings.showSnowflakesToggle = $(this).prop('checked'); + $('#rpg-toggle-show-spotify-toggle').on('change', function() { + extensionSettings.showSpotifyToggle = $(this).prop('checked'); saveSettings(); updateFeatureTogglesVisibility(); }); @@ -580,14 +581,30 @@ async function initUI() { updateFeatureTogglesVisibility(); }); - $('#rpg-toggle-show-snowflakes-toggle').on('change', function() { - extensionSettings.showSnowflakesToggle = $(this).prop('checked'); + $('#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(); }); - // Auto avatar generation settings - $('#rpg-toggle-auto-avatars').on('change', function() { + $('#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(); @@ -769,34 +786,35 @@ async function initUI() { $('#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-narrator-mode').prop('checked', extensionSettings.narratorMode); $('#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-dialogue-coloring').prop('checked', extensionSettings.enableDialogueColoring); $('#rpg-toggle-spotify-music').prop('checked', extensionSettings.enableSpotifyMusic); - $('#rpg-toggle-snowflakes').prop('checked', extensionSettings.enableSnowflakes); + $('#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-snowflakes-toggle').prop('checked', extensionSettings.showSnowflakesToggle ?? true); $('#rpg-toggle-show-dynamic-weather-toggle').prop('checked', extensionSettings.showDynamicWeatherToggle ?? true); - $('#rpg-toggle-show-snowflakes-toggle').prop('checked', extensionSettings.showSnowflakesToggle ?? 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-plot-buttons').prop('checked', extensionSettings.enablePlotButtons); + $('#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); @@ -813,10 +831,8 @@ async function initUI() { $('#rpg-summary-narration').val(extensionSettings.encounterSettings?.summaryNarrative?.narration ?? 'omniscient'); $('#rpg-summary-pov').val(extensionSettings.encounterSettings?.summaryNarrative?.pov ?? 'narrator'); - $('#rpg-toggle-animations').prop('checked', extensionSettings.enableAnimations); - - // Initialize avatar options - $('#rpg-toggle-auto-avatars').prop('checked', extensionSettings.autoGenerateAvatars || false); + // 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); @@ -889,12 +905,6 @@ async function initUI() { initChapterCheckpointUI(); injectCheckpointButton(); - // Setup Memory Recollection button in World Info - setupMemoryRecollectionButton(); - - // Initialize Lorebook Limiter - initLorebookLimiter(); - // Expose weather effect functions globally for cross-module access if (!window.RPGCompanion) { window.RPGCompanion = {}; @@ -914,70 +924,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. */ @@ -992,6 +938,20 @@ 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(); @@ -1029,12 +989,25 @@ 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 for Together mode if enabled + try { + if (extensionSettings.generationMode === 'together') { + await ensureJsonCleaningRegex(st_extension_settings, saveSettingsDebounced); + } else { + // Remove the regex if switching to separate mode + removeJsonCleaningRegex(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 @@ -1086,6 +1059,14 @@ jQuery(async () => { // 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); diff --git a/manifest.json b/manifest.json index 4976567..d907c59 100644 --- a/manifest.json +++ b/manifest.json @@ -5,7 +5,7 @@ "optional": [], "js": "index.js", "css": "style.css", - "author": "Marysia", - "version": "2.1.3", + "author": "Marinara", + "version": "3.0.0", "homePage": "https://github.com/SpicyMarinara/rpg-companion-sillytavern" } diff --git a/settings.html b/settings.html index ff4f57f..491da56 100644 --- a/settings.html +++ b/settings.html @@ -22,15 +22,24 @@
- Discord +  Discord - Support +  Support
+
+
+ Contributors: +
+
+ SpicyMarinara, Paperboygold, Munimunigamer, Subarashimo, Lilminzyu, Claude, IDeathByte, Chungchandev, Joenunezb, and Amauragis +
+
+
- RPG Companion v2.1.2 + v3.0.0
diff --git a/src/core/config.js b/src/core/config.js index c5279c5..7c7750e 100644 --- a/src/core/config.js +++ b/src/core/config.js @@ -26,14 +26,13 @@ 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) @@ -86,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 }; diff --git a/src/core/persistence.js b/src/core/persistence.js index 181c80f..5297f12 100644 --- a/src/core/persistence.js +++ b/src/core/persistence.js @@ -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'; @@ -91,6 +92,14 @@ export function loadSettings() { 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(); @@ -152,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, @@ -265,14 +282,29 @@ 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 diff --git a/src/core/state.js b/src/core/state.js index 6f0c665..ecf07a7 100644 --- a/src/core/state.js +++ b/src/core/state.js @@ -10,12 +10,11 @@ * Extension settings - persisted to SillyTavern settings */ export let extensionSettings = { - settingsVersion: 2, // Version number for settings migrations + 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, @@ -23,19 +22,26 @@ export let extensionSettings = { 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 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) - enableSnowflakes: false, // Enable festive snowflakes effect + 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 - showSnowflakesToggle: true, // Show Snowflakes Effect 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) - enablePlotButtons: true, // Show plot progression buttons above chat input + 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 @@ -52,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', @@ -88,6 +99,7 @@ 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 }, @@ -170,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, @@ -187,11 +209,15 @@ export let extensionSettings = { 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: false, // Master toggle for auto-generating avatars + autoGenerateAvatars: true, // Master toggle for auto-generating avatars avatarLLMCustomInstruction: '', // Custom instruction for LLM prompt generation // External API settings for 'external' generation mode externalApiSettings: { @@ -200,6 +226,30 @@ export let extensionSettings = { 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}}) } }; @@ -326,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) { diff --git a/src/i18n/en.json b/src/i18n/en.json index 04f9c92..4e337f5 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -17,41 +17,66 @@ "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.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.theme.statBarHighNote": "Color when stats are at 100%.", "template.settingsModal.displayTitle": "Display Options", - "template.settingsModal.displayNote": "Use the Extensions tab to enable/disable the RPG Companion extension.", + "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.showThoughtsInChat": "Show Thoughts in Chat", - "template.settingsModal.display.showThoughtsInChatNote": "Display character thoughts as overlay bubbles next to their messages", + "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.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.showPlotProgressionButtons": "Show Plot Progression Buttons", - "template.settingsModal.display.showPlotProgressionButtonsNote": "Display buttons above chat input for plot progression prompts", + "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.settingsModal.display.enableDebugMode": "Enable Debug Mode", - "template.settingsModal.display.enableDebugModeNote": "Shows parser logs in a mobile-friendly UI panel. Useful for troubleshooting. Look for the red bug button.", - "template.settingsModal.display.autoGenerateAvatars": "Auto-generate Missing Avatars", - "template.settingsModal.display.autoGenerateAvatarsNote": "Automatically generate avatars for characters without custom images using the Image Generation Plugin", + "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", @@ -59,21 +84,19 @@ "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.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.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.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 (Separate mode only)", - "template.settingsModal.advanced.memoryBatchSize": "Memory Batch Size:", - "template.settingsModal.advanced.memoryBatchSizeNote": "Number of messages to process per batch in Memory Recollection", + "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": "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).", - "template.settingsModal.advanced.skipInjections": "Skip Injections during Guided Generations:", + "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", @@ -139,9 +162,11 @@ "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", diff --git a/src/i18n/zh-tw.json b/src/i18n/zh-tw.json index be8da5a..1e55e56 100644 --- a/src/i18n/zh-tw.json +++ b/src/i18n/zh-tw.json @@ -30,6 +30,8 @@ "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": "始終顯示想法泡泡", @@ -37,11 +39,11 @@ "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.showPlotProgressionButtons": "顯示劇情推進按鈕(QR)", + "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.display.enableDebugMode": "Debug Mode", - "template.settingsModal.display.enableDebugModeNote": "UI 面板中顯示日誌,對於故障排除很有用。", "template.settingsModal.advancedTitle": "進階", "template.settingsModal.advanced.generationMode": "生成模式:", "template.settingsModal.advanced.generationModeOptions.together": "同時生成", @@ -130,8 +132,9 @@ "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.refreshRpgInfo": "刷新資訊", + "template.mainPanel.snowflakesEffect": "雪花效果", "template.mainPanel.dynamicWeatherEffects": "動態天氣", "template.mainPanel.narratorMode": "旁白模式", "template.mainPanel.autoAvatars": "自動頭像", "template.mainPanel.refreshRpgInfo": "刷新資訊", "template.mainPanel.updating": "更新中...", "template.mainPanel.editTrackersButton": "追蹤器編輯", "template.mainPanel.settingsButton": "設定", diff --git a/src/systems/features/avatarGenerator.js b/src/systems/features/avatarGenerator.js index cd4f0a9..df60c8d 100644 --- a/src/systems/features/avatarGenerator.js +++ b/src/systems/features/avatarGenerator.js @@ -174,10 +174,10 @@ export async function generateAvatarsForCharacters(characterNames, onStarted = n // 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 @@ -220,16 +220,6 @@ export async function regenerateAvatar(characterName) { delete sessionAvatarPrompts[characterName]; } - // Save current preset and switch to RPG Companion Trackers if enabled - let originalPresetName = null; - if (extensionSettings.useSeparatePreset) { - originalPresetName = await getCurrentPresetName(); - if (originalPresetName) { - console.log(`[RPG Avatar] Switching from "${originalPresetName}" to RPG Companion Trackers preset`); - await switchToPreset('RPG Companion Trackers'); - } - } - try { // Generate new LLM prompt const prompt = await generateAvatarPrompt(characterName); @@ -237,12 +227,6 @@ export async function regenerateAvatar(characterName) { // Generate the avatar return await generateSingleAvatar(characterName, prompt); } finally { - // Restore original preset if we switched - if (originalPresetName && extensionSettings.useSeparatePreset) { - console.log(`[RPG Avatar] Restoring original preset: "${originalPresetName}"`); - await switchToPreset(originalPresetName); - } - // Remove from pending when done pendingGenerations.delete(characterName); } @@ -327,7 +311,7 @@ async function generateSingleAvatar(characterName, prompt = null) { if (!prompt) { prompt = sessionAvatarPrompts[characterName]; } - + if (!prompt) { console.log(`[RPG Avatar] No LLM prompt for ${characterName}, using fallback prompt`); prompt = buildFallbackPrompt(characterName); diff --git a/src/systems/features/htmlCleaning.js b/src/systems/features/htmlCleaning.js index 8023389..24f1d86 100644 --- a/src/systems/features/htmlCleaning.js +++ b/src/systems/features/htmlCleaning.js @@ -114,3 +114,86 @@ export async function ensureHtmlCleaningRegex(st_extension_settings, saveSetting // 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 + } +} diff --git a/src/systems/features/jsonCleaning.js b/src/systems/features/jsonCleaning.js new file mode 100644 index 0000000..797b2d6 --- /dev/null +++ b/src/systems/features/jsonCleaning.js @@ -0,0 +1,122 @@ +/** + * 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 alreadyExists = existingScripts.some(script => + script && script.scriptName && script.scriptName === scriptName + ); + + if (alreadyExists) { + console.log('[RPG Companion] JSON cleaning regex already exists, skipping import'); + return; + } + + console.log('[RPG Companion] Importing JSON cleaning regex for Together mode...'); + + // 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...``` code blocks containing tracker data + // The prompt now explicitly instructs models to use this format + const regexScript = { + id: uuidv4(), + scriptName: scriptName, + // Match ```json...``` code blocks (non-greedy, multiline) + // This is now the guaranteed format since prompts instruct models to use code blocks + findRegex: '/```json\\s*[\\s\\S]*?```/gi', + replaceString: '', + trimStrings: [], + placement: [0], // 0 = Output (transforms after generation, before display) + disabled: false, + markdownOnly: false, + promptOnly: false, // Apply to both prompts and outputs + 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 JSON cleaning regex'); + } + + console.log('[RPG Companion] ✅ JSON cleaning regex imported successfully'); + console.log('[RPG Companion] This regex will automatically remove tracker JSON from Together mode messages'); + } catch (error) { + console.error('[RPG Companion] Failed to import JSON cleaning regex:', error); + 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); + } +} diff --git a/src/systems/features/lorebookLimiter.js b/src/systems/features/lorebookLimiter.js deleted file mode 100644 index 9d2e6a5..0000000 --- a/src/systems/features/lorebookLimiter.js +++ /dev/null @@ -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 = ` -
- - Limit entries per generation (0 = unlimited) -
- `; - - // 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; -} diff --git a/src/systems/features/memoryRecollection.js b/src/systems/features/memoryRecollection.js deleted file mode 100644 index 95c3396..0000000 --- a/src/systems/features/memoryRecollection.js +++ /dev/null @@ -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} 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: - -${context} - - -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: - -{ - "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"] -} - - -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} 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 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 = ` -
-
-

⚠️ Generation Failed

-
-
-

Error: ${error.message}

-

Batch ${i + 1} of ${totalBatches} failed to process.

-

Would you like to retry this batch?

-
- -
- `; - - 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 = ` -
-
-

⚠️ Memory Recollection

-
-
-

Warning! This process will trigger multiple generation requests and will take time.

-

Ensure your currently selected model is the one you want to use for this task.

-

- Messages per batch: ${extensionSettings.memoryMessagesToProcess || 16} -
- (You can change this in the extension settings) -

-
- -
- `; - - 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 = ` -
-
-

🧠 Processing Memories...

-
-
-

Processing batch 0 of 0

-
-
-
-

Initializing...

-
-
- `; - - 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 = ` - ✅ Complete! Created ${entriesCreated} memory entries.
- The "Memory Recollection" lorebook has been created.
- ⚠️ Please refresh SillyTavern to see the lorebook in the World Info dropdown. - `; - 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 = ' 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); - } - } -} diff --git a/src/systems/features/plotProgression.js b/src/systems/features/plotProgression.js index 79a593c..ff61c41 100644 --- a/src/systems/features/plotProgression.js +++ b/src/systems/features/plotProgression.js @@ -5,7 +5,7 @@ import { togglePlotButtons } from '../ui/layout.js'; import { extensionSettings, setIsPlotProgression } from '../../core/state.js'; -import { DEFAULT_HTML_PROMPT } from '../generation/promptBuilder.js'; +import { DEFAULT_HTML_PROMPT, DEFAULT_DIALOGUE_COLORING_PROMPT } from '../generation/promptBuilder.js'; import { Generate } from '../../../../../../../script.js'; /** @@ -34,8 +34,8 @@ export function setupPlotButtons(handlePlotClick, handleEncounterClick) { font-size: 13px; cursor: pointer; margin: 0 2px; - " tabindex="0" role="button"> - Randomized Plot + " tabindex="0" role="button" title="Generate a random plot twist or event"> +  Randomized Plot `; @@ -114,6 +114,13 @@ export async function sendPlotProgression(type) { 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 // This will be used by onMessageReceived to clear the prompt after generation completes setIsPlotProgression(true); diff --git a/src/systems/generation/apiClient.js b/src/systems/generation/apiClient.js index 9c32f0f..d82e566 100644 --- a/src/systems/generation/apiClient.js +++ b/src/systems/generation/apiClient.js @@ -23,6 +23,7 @@ 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'; @@ -235,22 +236,6 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough const updatingText = i18n.getTranslation('template.mainPanel.updating') || 'Updating...'; $updateBtn.html(` ${updatingText}`).prop('disabled', true); - // Save current preset name before switching (if we're going to switch) - // Note: Preset switching is only used in separate mode, not external mode - if (!isExternalMode && extensionSettings.useSeparatePreset) { - originalPresetName = await getCurrentPresetName(); - console.log(`[RPG Companion] Saved original preset: "${originalPresetName}"`); - } - - // Switch to separate preset if enabled (separate mode only) - if (!isExternalMode && 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 = await generateSeparateUpdatePrompt(); // Generate response based on mode @@ -270,6 +255,18 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough if (response) { // console.log('[RPG Companion] Raw AI response:', response); const parsedData = parseResponse(response); + + // 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); @@ -383,13 +380,6 @@ export async function updateRPGData(renderUserStats, renderInfoBox, renderThough toastr.error(error.message, 'RPG Companion External API 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 - } - setIsGenerating(false); // Restore button to original state diff --git a/src/systems/generation/encounterPrompts.js b/src/systems/generation/encounterPrompts.js index 60ec25e..2bda585 100644 --- a/src/systems/generation/encounterPrompts.js +++ b/src/systems/generation/encounterPrompts.js @@ -8,7 +8,9 @@ import { chat, characters, this_chid, substituteParams } from '../../../../../.. 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 @@ -233,7 +235,9 @@ export async function buildEncounterInitPrompt() { if (extensionSettings.classicStats) { const stats = extensionSettings.classicStats; userStatsInfo += `${userName}'s Attributes: `; - userStatsInfo += `STR ${stats.str}, DEX ${stats.dex}, CON ${stats.con}, INT ${stats.int}, WIS ${stats.wis}, CHA ${stats.cha}, LVL ${extensionSettings.level}\n\n`; + 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 @@ -417,7 +421,18 @@ export async function buildCombatActionPrompt(action, combatStats) { // Add ONLY classic stats/attributes if enabled if (extensionSettings.classicStats) { const stats = extensionSettings.classicStats; - systemMessage += `\nAttributes: STR ${stats.str}, DEX ${stats.dex}, CON ${stats.con}, INT ${stats.int}, WIS ${stats.wis}, CHA ${stats.cha}, LVL ${extensionSettings.level}\n`; + 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 += `\n\n`; @@ -658,15 +673,24 @@ export async function buildCombatSummaryPrompt(combatLog, result) { summaryMessage += `\n`; if (committedTrackerData.userStats) { - summaryMessage += `${userName}'s Stats:\n${committedTrackerData.userStats}\n\n`; + const statsJSON = typeof committedTrackerData.userStats === 'object' + ? JSON.stringify(committedTrackerData.userStats, null, 2) + : committedTrackerData.userStats; + summaryMessage += statsJSON + '\n'; } if (committedTrackerData.infoBox) { - summaryMessage += `Info Box:\n${committedTrackerData.infoBox}\n\n`; + const infoBoxJSON = typeof committedTrackerData.infoBox === 'object' + ? JSON.stringify(committedTrackerData.infoBox, null, 2) + : committedTrackerData.infoBox; + summaryMessage += infoBoxJSON + '\n'; } if (committedTrackerData.characterThoughts) { - summaryMessage += `Present Characters:\n${committedTrackerData.characterThoughts}\n\n`; + const charactersJSON = typeof committedTrackerData.characterThoughts === 'object' + ? JSON.stringify(committedTrackerData.characterThoughts, null, 2) + : committedTrackerData.characterThoughts; + summaryMessage += charactersJSON + '\n'; } summaryMessage += `\n\n`; @@ -712,7 +736,22 @@ export function parseEncounterJSON(response) { cleaned = cleaned.substring(firstBrace, lastBrace + 1); } - return JSON.parse(cleaned); + // 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); diff --git a/src/systems/generation/injector.js b/src/systems/generation/injector.js index 3cbebf7..072ea7d 100644 --- a/src/systems/generation/injector.js +++ b/src/systems/generation/injector.js @@ -11,7 +11,8 @@ import { lastGeneratedData, isGenerating, lastActionWasSwipe, - setLastActionWasSwipe + setLastActionWasSwipe, + setIsGenerating } from '../../core/state.js'; import { evaluateSuppression } from './suppression.js'; import { parseUserStats } from './parser.js'; @@ -20,24 +21,38 @@ import { generateTrackerInstructions, 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. * Manages tracker data commitment and prompt injection based on generation mode. * * @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 async function onGenerationStarted(type, data) { - // console.log('[RPG Companion] onGenerationStarted called'); - // console.log('[RPG Companion] enabled:', extensionSettings.enabled); - // console.log('[RPG Companion] generationMode:', extensionSettings.generationMode); - // console.log('[RPG Companion] ⚡ EVENT: onGenerationStarted - lastActionWasSwipe =', lastActionWasSwipe, '| isGenerating =', isGenerating); - // console.log('[RPG Companion] Committed Prompt:', committedTrackerData); +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); + console.log('[RPG Companion] ⚡ EVENT: onGenerationStarted - lastActionWasSwipe =', lastActionWasSwipe, '| isGenerating =', isGenerating); + console.log('[RPG Companion] Committed Prompt:', committedTrackerData); // Skip tracker injection for image generation requests if (data?.quietImage) { @@ -46,6 +61,13 @@ export async 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; } @@ -76,8 +98,63 @@ export async function onGenerationStarted(type, data) { // 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 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 mode only: 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 @@ -85,83 +162,39 @@ export async function onGenerationStarted(type, data) { if (extensionSettings.generationMode === 'separate' && !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' - // }); - // console.log('[RPG Companion] BEFORE commit - lastGeneratedData:', { - // userStats: lastGeneratedData.userStats ? 'exists' : 'null', - // infoBox: lastGeneratedData.infoBox ? 'exists' : 'null', - // characterThoughts: lastGeneratedData.characterThoughts ? 'exists' : 'null' - // }); + 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' + }); + console.log('[RPG Companion] BEFORE commit - lastGeneratedData:', { + 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' - // }); + console.log('[RPG Companion] AFTER commit - committedTrackerData:', { + userStats: committedTrackerData.userStats ? 'exists' : 'null', + infoBox: committedTrackerData.infoBox ? 'exists' : 'null', + characterThoughts: committedTrackerData.characterThoughts ? 'exists' : 'null' + }); // Reset flag after committing (ready for next cycle) } 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' - // }); + 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' + }); // Reset flag after using it (swipe generation complete, ready for next action) } } - // For TOGETHER mode: Check if we need to commit extension data - // Only commit when user sends a new message (not on swipes) - if (extensionSettings.generationMode === 'together') { - if (!lastActionWasSwipe) { - // User sent a new message - commit data from the last assistant message they replied to - // This ensures swipes use consistent data from before the first swipe - console.log('[RPG Companion] 📝 TOGETHER MODE COMMIT: New message - committing from last assistant message'); - - // Find the last assistant message (before the user's new message) - const chat = getContext().chat; - let foundAssistantMessage = false; - - for (let i = chat.length - 1; i >= 0; i--) { - const message = chat[i]; - if (!message.is_user) { - // Found last assistant message - commit its stored tracker data - if (message.extra && message.extra.rpg_companion_swipes) { - const swipeId = message.swipe_id || 0; - const swipeData = message.extra.rpg_companion_swipes[swipeId]; - - if (swipeData) { - committedTrackerData.userStats = swipeData.userStats || null; - committedTrackerData.infoBox = swipeData.infoBox || null; - committedTrackerData.characterThoughts = swipeData.characterThoughts || null; - foundAssistantMessage = true; - console.log('[RPG Companion] ✓ Committed tracker data from message swipe', swipeId); - } - } - break; - } - } - - // Fallback: if no stored data found, use lastGeneratedData (for first message) - if (!foundAssistantMessage) { - committedTrackerData.userStats = lastGeneratedData.userStats; - committedTrackerData.infoBox = lastGeneratedData.infoBox; - committedTrackerData.characterThoughts = lastGeneratedData.characterThoughts; - console.log('[RPG Companion] ⚠ No stored message data found, using lastGeneratedData as fallback'); - } - } 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); @@ -175,7 +208,10 @@ export async 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); @@ -234,6 +270,19 @@ export async function onGenerationStarted(type, data) { setExtensionPrompt('rpg-companion-html', '', extension_prompt_types.IN_CHAT, 0, false); } + // 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 diff --git a/src/systems/generation/jsonPromptHelpers.js b/src/systems/generation/jsonPromptHelpers.js new file mode 100644 index 0000000..21fbad8 --- /dev/null +++ b/src/systems/generation/jsonPromptHelpers.js @@ -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.'; +} diff --git a/src/systems/generation/lockManager.js b/src/systems/generation/lockManager.js new file mode 100644 index 0000000..710fdf3 --- /dev/null +++ b/src/systems/generation/lockManager.js @@ -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)); +} diff --git a/src/systems/generation/parser.js b/src/systems/generation/parser.js index ce95b05..a5824e1 100644 --- a/src/systems/generation/parser.js +++ b/src/systems/generation/parser.js @@ -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 @@ -159,36 +161,246 @@ export function parseResponse(responseText) { cleanedResponse = cleanedResponse.replace(/[\s\S]*?<\/thinking>/gi, ''); debugLog('[RPG Parser] Removed thinking tags, new length:', cleanedResponse.length + ' chars'); - // Check if response uses XML tags (new format) + // 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 tags (hybrid format) const xmlMatch = cleanedResponse.match(/([\s\S]*?)<\/trackers>/i); if (xmlMatch) { debugLog('[RPG Parser] ✓ Found XML tags, using XML parser'); const trackersContent = xmlMatch[1].trim(); - // Extract sections from XML content (sections are not in code blocks) - 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'); - } + // 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); - 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'); - } + 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 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'); + 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 format) + // 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 @@ -289,7 +501,7 @@ export function parseResponse(responseText) { debugLog('[RPG Parser] ======================================================='); return result; -} +} // End parseResponse /** * Parses user stats from the text and updates the extensionSettings. @@ -303,6 +515,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 || []; diff --git a/src/systems/generation/promptBuilder.js b/src/systems/generation/promptBuilder.js index 1d69410..57513f1 100644 --- a/src/systems/generation/promptBuilder.js +++ b/src/systems/generation/promptBuilder.js @@ -7,6 +7,13 @@ import { getContext } from '../../../../../../extensions.js'; import { chat, getCurrentChatDetails, characters, this_chid } from '../../../../../../../script.js'; import { selected_group, getGroupMembers, getGroupChat, groups } from '../../../../../../group-chats.js'; import { extensionSettings, committedTrackerData, FEATURE_FLAGS } from '../../core/state.js'; +import { + buildUserStatsJSONInstruction, + buildInfoBoxJSONInstruction, + buildCharactersJSONInstruction, + addLockInstruction +} from './jsonPromptHelpers.js'; +import { applyLocks } from './lockManager.js'; // Type imports /** @typedef {import('../../types/inventory.js').InventoryV2} InventoryV2 */ @@ -16,16 +23,26 @@ import { extensionSettings, committedTrackerData, FEATURE_FLAGS } from '../../co */ export const DEFAULT_HTML_PROMPT = `If appropriate, include inline HTML, CSS, and JS segments whenever they enhance visual storytelling (e.g., for in-world screens, posters, books, letters, signs, crests, labels, etc.). Style them to match the setting's theme (e.g., fantasy, sci-fi), keep the text readable, and embed all assets directly (using inline SVGs only with no external scripts, libraries, or fonts). Use these elements freely and naturally within the narrative as characters would encounter them, including animations, 3D effects, pop-ups, dropdowns, websites, and so on. Do not wrap the HTML/CSS/JS in code fences!`; +/** + * Default Dialogue Coloring prompt text + */ +export const DEFAULT_DIALOGUE_COLORING_PROMPT = `Wrap all character/NPC "dialogues" in unique tags, exemplary: "You're pretty good." Assign a distinct color to each speaker and reuse it whenever they speak again.`; + /** * Default Spotify music prompt text (customizable by users) */ -export const DEFAULT_SPOTIFY_PROMPT = `If appropriate for the current scene's mood and atmosphere, suggest a song that fits the ambiance. Choose music that enhances the emotional tone, setting, or action of the scene.`; +export const DEFAULT_SPOTIFY_PROMPT = `If fitting for the current scene's mood and atmosphere, suggest a song that fits the ambiance. Choose music that enhances the emotional tone, setting, or action of the scene.`; /** * Spotify format instruction (constant, not editable by users) */ export const SPOTIFY_FORMAT_INSTRUCTION = `Include it in this exact format: .`; +/** + * Default Narrator Mode prompt text (customizable by users) + */ +export const DEFAULT_NARRATOR_PROMPT = `Infer the identity and details of characters present in each scene from the story context below. Do not use fixed character references; instead, identify characters naturally based on their actions, dialogue, and descriptions in the narrative.`; + /** * Gets character card information for current chat (handles both single and group chats) * @returns {string} Formatted character information @@ -49,7 +66,10 @@ async function getCharacterCardsInfo() { } characterInfo += `\n\n`; - characterInfo += `Infer the identity and details of characters present in each scene from the story context below. Do not use fixed character references - instead, identify characters naturally based on their actions, dialogue, and descriptions in the narrative.\n\n`; + + // Use custom narrator prompt if available, otherwise use default + const narratorPrompt = extensionSettings.customNarratorPrompt || DEFAULT_NARRATOR_PROMPT; + characterInfo += narratorPrompt + '\n\n'; } return characterInfo; } @@ -192,8 +212,11 @@ function buildAttributesString() { return `${attr.name} ${value}`; }); - // Add level at the end - attributeParts.push(`LVL ${extensionSettings.level}`); + // Add level at the end (if enabled) + const showLevel = extensionSettings.trackerConfig?.userStats?.showLevel !== false; // Default to true + if (showLevel) { + attributeParts.push(`LVL ${extensionSettings.level}`); + } return attributeParts.join(', '); } @@ -206,26 +229,70 @@ function buildAttributesString() { */ export function generateTrackerExample() { let example = ''; + const useXmlTags = extensionSettings.saveTrackerHistory; // Use COMMITTED data for generation context, not displayed data - // Wrap each tracker section in markdown code blocks + // Apply locks before sending to AI (for JSON format only) + // Build unified JSON structure with proper wrapper keys + const parts = []; + + console.log('[RPG Companion] generateTrackerExample - enabled modules:', { + showUserStats: extensionSettings.showUserStats, + showInfoBox: extensionSettings.showInfoBox, + showCharacterThoughts: extensionSettings.showCharacterThoughts + }); + console.log('[RPG Companion] generateTrackerExample - committed data:', { + hasUserStats: !!committedTrackerData.userStats, + hasInfoBox: !!committedTrackerData.infoBox, + hasCharacterThoughts: !!committedTrackerData.characterThoughts + }); + if (extensionSettings.showUserStats && committedTrackerData.userStats) { - example += '```\n' + committedTrackerData.userStats + '\n```\n\n'; + // Try to parse as JSON first, otherwise treat as text + try { + JSON.parse(committedTrackerData.userStats); + // It's valid JSON - apply locks + const lockedData = applyLocks(committedTrackerData.userStats, 'userStats'); + parts.push(` "userStats": ${lockedData}`); + } catch { + // It's text format - no locks applied + example += '```\n' + committedTrackerData.userStats + '\n```\n'; + } } if (extensionSettings.showInfoBox && committedTrackerData.infoBox) { - example += '```\n' + committedTrackerData.infoBox + '\n```\n\n'; + try { + JSON.parse(committedTrackerData.infoBox); + const lockedData = applyLocks(committedTrackerData.infoBox, 'infoBox'); + parts.push(` "infoBox": ${lockedData}`); + } catch { + example += '```\n' + committedTrackerData.infoBox + '\n```\n'; + } } if (extensionSettings.showCharacterThoughts && committedTrackerData.characterThoughts) { - example += '```\n' + committedTrackerData.characterThoughts + '\n```'; + try { + JSON.parse(committedTrackerData.characterThoughts); + const lockedData = applyLocks(committedTrackerData.characterThoughts, 'characters'); + parts.push(` "characters": ${lockedData}`); + } catch { + example += '```\n' + committedTrackerData.characterThoughts + '\n```'; + } } + // If we have JSON parts, wrap them in unified structure + if (parts.length > 0) { + example = '{\n' + parts.join(',\n') + '\n}'; + } + + console.log('[RPG Companion] generateTrackerExample - result length:', example.length, 'parts:', parts.length); + return example.trim(); } /** * Generates the instruction portion - format specifications and guidelines. + * NOW USES JSON FORMAT (v3) instead of text format * * @param {boolean} includeHtmlPrompt - Whether to include the HTML prompt (true for main generation, false for separate tracker generation) * @param {boolean} includeContinuation - Whether to include "After updating the trackers, continue..." instruction @@ -247,187 +314,77 @@ export function generateTrackerInstructions(includeHtmlPrompt = true, includeCon const useXmlTags = extensionSettings.saveTrackerHistory; const openTag = useXmlTags ? '\n' : ''; const closeTag = useXmlTags ? '\n' : ''; - const codeBlockMarker = useXmlTags ? '' : '```'; + const codeBlockMarker = ''; + const endCodeBlockMarker = ''; // Universal instruction header if (useXmlTags) { - // Format specification is always hardcoded - instructions += `\nAt the start of every reply, you must attach an update to the trackers in EXACTLY the same format as below, enclosed in XML tags. `; + instructions += `\nAt the start of every reply, you must attach an update to the trackers in EXACTLY the JSON format shown below, enclosed in XML tags. `; } else { - // Format specification is always hardcoded - instructions += `\nAt the start of every reply, you must attach an update to the trackers in EXACTLY the same format as below, enclosed in separate Markdown code fences. `; + instructions += '\nAt the start of every reply, you must attach an update to the trackers in EXACTLY the JSON format shown below as a single unified JSON object containing all enabled tracker fields. '; } - // Append custom instruction portion if available (same for both XML and Markdown) + // Append custom instruction portion if available const customPrompt = extensionSettings.customTrackerInstructionsPrompt; if (customPrompt) { instructions += customPrompt.replace(/{userName}/g, userName); } else { - instructions += `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. Do NOT keep the brackets or placeholder text in your response. For example: [Location] becomes Forest Clearing, [Mood Emoji] becomes 😊. `; - instructions += `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).`; + instructions += `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 "😊". `; + instructions += `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.`; } - // Add format specifications for each enabled tracker + // Add lock instruction + instructions += addLockInstruction(''); + + // Add format specifications for each enabled tracker using JSON + // Wrap all trackers in a unified JSON structure + const enabledTrackers = []; if (extensionSettings.showUserStats) { - const userStatsConfig = trackerConfig?.userStats; - const enabledStats = userStatsConfig?.customStats?.filter(s => s && s.enabled && s.name) || []; - - instructions += codeBlockMarker + '\n'; - instructions += `${userName}'s Stats\n`; - instructions += '---\n'; - - // Add custom stats dynamically - for (const stat of enabledStats) { - instructions += `- ${stat.name}: X%\n`; - } - - // Add status section if enabled - if (userStatsConfig?.statusSection?.enabled) { - const statusFields = userStatsConfig.statusSection.customFields || []; - const statusFieldsText = statusFields.map(f => `${f}`).join(', '); - - if (userStatsConfig.statusSection.showMoodEmoji) { - instructions += `Status: [Mood Emoji${statusFieldsText ? ', ' + statusFieldsText : ''}]\n`; - } else if (statusFieldsText) { - instructions += `Status: [${statusFieldsText}]\n`; - } - } - - // Add skills section if enabled - if (userStatsConfig?.skillsSection?.enabled) { - const skillFields = userStatsConfig.skillsSection.customFields || []; - const skillFieldsText = skillFields.map(f => `[${f}]`).join(', '); - instructions += `Skills: [${skillFieldsText || 'Skill1, Skill2, etc.'}]\n`; - } - - // Add inventory format based on feature flag - only if showInventory is enabled - if (extensionSettings.showInventory) { - if (FEATURE_FLAGS.useNewInventory) { - instructions += 'On Person: [Items currently carried/worn, or "None"]\n'; - instructions += 'Clothing: [Clothing/Armor currently worn, or "None"]\n'; - instructions += 'Stored - [Location Name]: [Items stored at this location]\n'; - instructions += '(Add multiple "Stored - [Location]:" lines as needed for different storage locations)\n'; - instructions += 'Assets: [Vehicles, property, major possessions, or "None"]\n'; - } else { - // Legacy v1 format - instructions += 'Inventory: [Clothing/Armor, Inventory Items (list of important items, or "None")]\\n'; - } - } - - // Add quests section - instructions += 'Main Quests: [Short title of the currently active main quest (for example, "Save the world"), or "None"]\n'; - instructions += 'Optional Quests: [Short titles of the currently active optional quests (for example, "Find Zandik\'s book"), or "None"]\n'; - - instructions += codeBlockMarker + '\n\n'; + enabledTrackers.push('userStats'); } - if (extensionSettings.showInfoBox) { - const infoBoxConfig = trackerConfig?.infoBox; - const widgets = infoBoxConfig?.widgets || {}; - - instructions += codeBlockMarker + '\n'; - instructions += 'Info Box\n'; - instructions += '---\n'; - - // Add only enabled widgets - if (widgets.date?.enabled) { - instructions += 'Date: [Weekday, Month, Year]\n'; - } - if (widgets.weather?.enabled) { - instructions += 'Weather: [Weather Emoji, Forecast]\n'; - } - if (widgets.temperature?.enabled) { - const unit = widgets.temperature.unit === 'F' ? '°F' : '°C'; - instructions += `Temperature: [Temperature in ${unit}]\n`; - } - if (widgets.time?.enabled) { - instructions += 'Time: [Time Start → Time End]\n'; - } - if (widgets.location?.enabled) { - instructions += 'Location: [Location]\n'; - } - if (widgets.recentEvents?.enabled) { - instructions += 'Recent Events: [Up to three past events leading to the ongoing scene (short descriptors with no details, for example, "last-night date with Mary")]\n'; - } - - instructions += codeBlockMarker + '\n\n'; + enabledTrackers.push('infoBox'); + } + if (extensionSettings.showCharacterThoughts) { + enabledTrackers.push('characters'); } - if (extensionSettings.showCharacterThoughts) { - const presentCharsConfig = trackerConfig?.presentCharacters; - const enabledFields = presentCharsConfig?.customFields?.filter(f => f && f.enabled && f.name) || []; + if (enabledTrackers.length > 0) { + instructions += '\n\nFORMAT:\n\nProvide EXACTLY ONE JSON code block with ALL tracker sections wrapped in a single object:\n\n```json\n{\n'; - // Check if relationships are enabled - const relationshipsEnabled = presentCharsConfig?.relationships?.enabled !== false; // Default to true - const relationshipFields = relationshipsEnabled ? (presentCharsConfig?.relationshipFields || []) : []; - - const thoughtsConfig = presentCharsConfig?.thoughts; - const characterStats = presentCharsConfig?.characterStats; - const enabledCharStats = characterStats?.enabled && characterStats?.customStats?.filter(s => s && s.enabled && s.name) || []; - - instructions += codeBlockMarker + '\n'; - instructions += 'Present Characters\n'; - instructions += '---\n'; - - // Build relationship placeholders (e.g., "Lover/Friend") - const relationshipPlaceholders = relationshipFields - .filter(r => r && r.trim()) - .map(r => `${r}`) - .join('/'); - - // Build custom field placeholders (e.g., "[Appearance] | [Current Action]") - const fieldPlaceholders = enabledFields - .map(f => `[${f.name}]`) - .join(' | '); - - // Character block format - if (extensionSettings.narratorMode) { - instructions += `- [Character Name (infer from story context; do not include ${userName}; state "Unavailable" if no other characters are present in the scene)]\n`; - } else { - instructions += `- [Name (do not include ${userName}; state "Unavailable" if no major characters are present in the scene)]\n`; + if (extensionSettings.showUserStats) { + instructions += ' "userStats": '; + const userStatsJSON = buildUserStatsJSONInstruction(); + // Add 2 spaces to all lines after the first to properly nest within root object + instructions += userStatsJSON.split('\n').map((line, i) => i === 0 ? line : ' ' + line).join('\n'); + instructions += enabledTrackers.indexOf('userStats') < enabledTrackers.length - 1 ? ',\n' : '\n'; } - // Details line with emoji and custom fields - if (fieldPlaceholders) { - instructions += `Details: [Present Character's Emoji] | ${fieldPlaceholders}\n`; - } else { - instructions += `Details: [Present Character's Emoji]\n`; + if (extensionSettings.showInfoBox) { + instructions += ' "infoBox": '; + const infoBoxJSON = buildInfoBoxJSONInstruction(); + // Add 2 spaces to all lines after the first to properly nest within root object + instructions += infoBoxJSON.split('\n').map((line, i) => i === 0 ? line : ' ' + line).join('\n'); + instructions += enabledTrackers.indexOf('infoBox') < enabledTrackers.length - 1 ? ',\n' : '\n'; } - // Relationship line (only if relationships are enabled) - if (relationshipsEnabled && relationshipPlaceholders) { - instructions += `Relationship: [(choose one: ${relationshipPlaceholders})]\n`; + if (extensionSettings.showCharacterThoughts) { + instructions += ' "characters": '; + const charactersJSON = buildCharactersJSONInstruction(); + // Add 2 spaces to all lines after the first to properly nest within root object + instructions += charactersJSON.split('\n').map((line, i) => i === 0 ? line : ' ' + line).join('\n'); } - // Stats line (if enabled) - if (enabledCharStats.length > 0) { - const statPlaceholders = enabledCharStats.map(s => `${s.name}: X%`).join(' | '); - instructions += `Stats: ${statPlaceholders}\n`; - } - - // Thoughts line (if enabled) - if (thoughtsConfig?.enabled) { - const thoughtsName = thoughtsConfig.name || 'Thoughts'; - const thoughtsDescription = thoughtsConfig.description || 'Internal monologue (in first person POV, up to three sentences long)'; - instructions += `${thoughtsName}: [${thoughtsDescription}]\n`; - } - - if (extensionSettings.narratorMode) { - instructions += `- … (Repeat the format above for every other character present in the scene, inferred from story context)\n`; - } else { - instructions += `- … (Repeat the format above for every other present major character)\n`; - } - - instructions += codeBlockMarker + '\n\n'; + instructions += '\n}\n```\n\nDo NOT output multiple separate JSON objects. Everything must be in ONE unified object with the keys shown above.'; } // Only add continuation instruction if includeContinuation is true if (includeContinuation) { const customPrompt = extensionSettings.customTrackerContinuationPrompt; if (customPrompt) { - instructions += customPrompt + '\n\n'; + instructions += '\n\n' + customPrompt + '\n\n'; } else { - instructions += `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 bracketed placeholders (e.g., [Location], [Mood Emoji]) MUST be replaced with actual content without the square brackets.\n\n`; + instructions += `\n\nAfter 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 bracketed placeholders (e.g., [Location], [Mood Emoji]) MUST be replaced with actual content without the square brackets.\n\n`; } } @@ -482,6 +439,295 @@ export function generateTrackerInstructions(includeHtmlPrompt = true, includeCon return instructions; } +/** + * Formats tracker data as human-readable text for context injection. + * Converts JSON format to a concise, natural language summary. + * @param {string} jsonData - JSON formatted tracker data + * @param {string} trackerType - Type of tracker ('userStats', 'infoBox', 'characters') + * @param {string} userName - User's name for personalization + * @returns {string} Formatted text summary + */ +function formatTrackerDataForContext(jsonData, trackerType, userName) { + if (!jsonData) return ''; + + try { + const data = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData; + let formatted = ''; + +// Helper to extract value from potentially locked fields and common object formats + const getValue = (field) => { + if (field === null || field === undefined) return ''; + + // If it's a locked object with {value, locked}, extract the value + if (field && typeof field === 'object' && !Array.isArray(field) && 'value' in field) { + return getValue(field.value); // Recursively handle in case value itself is locked + } + + // If it's a regular value, return as string + if (typeof field !== 'object') { + return String(field); + } + + // For arrays of strings, join them + if (Array.isArray(field)) { + return field.map(item => getValue(item)).filter(Boolean).join(', '); + } + + // Handle common object formats + if (field && typeof field === 'object') { + // Status object: {mood, conditions} + if ('mood' in field && 'conditions' in field) { + const mood = getValue(field.mood); + const conditions = getValue(field.conditions); + return `${mood} - ${conditions}`; + } + + // Skill/item/quest objects: {name}, {title}, {name, quantity} + if ('name' in field) { + const name = getValue(field.name); + if ('quantity' in field && field.quantity > 1) { + return `${name} (x${field.quantity})`; + } + return name; + } + + if ('title' in field) { + return getValue(field.title); + } + + // Time object: {start, end} + if ('start' in field && 'end' in field) { + return `${getValue(field.start)} - ${getValue(field.end)}`; + } + + // Weather object: {emoji, forecast} + if ('emoji' in field && 'forecast' in field) { + return `${getValue(field.emoji)} ${getValue(field.forecast)}`; + } + + // Generic object fallback: create key-value pairs + const keys = Object.keys(field); + if (keys.length > 0 && keys.length <= 3) { + const values = keys.map(k => { + const val = getValue(field[k]); + return val ? `${k}: ${val}` : null; + }).filter(Boolean); + + if (values.length > 0) { + return values.join(', '); + } + } + } + + return ''; + }; + + if (trackerType === 'userStats') { + formatted += `${userName}'s Stats:\n`; + + // Handle stats array format: [{id, name, value}, ...] + if (data.stats && Array.isArray(data.stats)) { + for (const stat of data.stats) { + if (stat && stat.value !== undefined) { + const statName = stat.name || (stat.id ? stat.id.charAt(0).toUpperCase() + stat.id.slice(1) : 'Unknown'); + formatted += `${statName}: ${stat.value}\n`; + } + } + } else { + // Fallback: handle flat format {health: 10, mana: 20, ...} + const statFieldOrder = ['health', 'mana', 'stamina', 'satiety', 'hygiene', 'energy', 'arousal']; + const specialFields = ['status', 'mood', 'skills', 'inventory', 'quests']; + + for (const statName of statFieldOrder) { + if (data[statName] !== undefined) { + const value = getValue(data[statName]); + if (value) { + const displayName = statName.charAt(0).toUpperCase() + statName.slice(1); + formatted += `${displayName}: ${value}\n`; + } + } + } + + // Custom numeric stats + for (const [key, value] of Object.entries(data)) { + if (!statFieldOrder.includes(key) && !specialFields.includes(key) && typeof value === 'number') { + const displayName = key.charAt(0).toUpperCase() + key.slice(1); + formatted += `${displayName}: ${getValue(value)}\n`; + } + } + } + + // Status/mood + if (data.status) formatted += `Status: ${getValue(data.status)}\n`; + if (data.mood) formatted += `Mood: ${getValue(data.mood)}\n`; + + // Skills - handle both array and object format + if (data.skills) { + if (Array.isArray(data.skills)) { + // Array format: ["Combat", "Magic", "Stealth"] + const skillsList = data.skills.map(s => getValue(s)).filter(s => s).join(', '); + if (skillsList) formatted += `Skills: ${skillsList}\n`; + } else if (typeof data.skills === 'object') { + // Object format: {Combat: 50, Magic: 30} + const skillsList = Object.entries(data.skills) + .map(([name, val]) => { + const skillName = getValue(name); + const skillVal = getValue(val); + return skillVal ? `${skillName}: ${skillVal}` : skillName; + }) + .filter(s => s) + .join(', '); + if (skillsList) formatted += `Skills: ${skillsList}\n`; + } + } + + // Inventory sections + if (data.inventory) { + const inv = data.inventory; + + if (inv.onPerson && Array.isArray(inv.onPerson) && inv.onPerson.length > 0) { + const items = inv.onPerson.map(i => getValue(i)).filter(i => i); + if (items.length > 0) formatted += `On Person: ${items.join(', ')}\n`; + } + + if (inv.clothing && Array.isArray(inv.clothing) && inv.clothing.length > 0) { + const items = inv.clothing.map(i => getValue(i)).filter(i => i); + if (items.length > 0) formatted += `Clothing: ${items.join(', ')}\n`; + } + + if (inv.stored && typeof inv.stored === 'object' && !Array.isArray(inv.stored)) { + for (const [location, items] of Object.entries(inv.stored)) { + if (Array.isArray(items) && items.length > 0) { + const itemsList = items.map(i => getValue(i)).filter(i => i); + if (itemsList.length > 0) { + formatted += `${getValue(location)}: ${itemsList.join(', ')}\n`; + } + } + } + } + + if (inv.assets && Array.isArray(inv.assets) && inv.assets.length > 0) { + const items = inv.assets.map(i => getValue(i)).filter(i => i); + if (items.length > 0) formatted += `Assets: ${items.join(', ')}\n`; + } + } + + // Quests + if (data.quests) { + const quests = data.quests; + + // Main quest - handle string, array, or object with {title} + if (quests.main) { + if (typeof quests.main === 'string') { + const mainQuest = getValue(quests.main); + if (mainQuest) formatted += `Main Quest: ${mainQuest}\n`; + } else if (Array.isArray(quests.main) && quests.main.length > 0) { + const questsList = quests.main.map(q => getValue(q)).filter(q => q); + if (questsList.length > 0) formatted += `Main Quests: ${questsList.join(', ')}\n`; + } else if (typeof quests.main === 'object') { + // Handle {title: "..."} format + const mainQuest = getValue(quests.main); + if (mainQuest) formatted += `Main Quest: ${mainQuest}\n`; + } + } + + // Optional quests + if (quests.optional && Array.isArray(quests.optional) && quests.optional.length > 0) { + const questsList = quests.optional.map(q => getValue(q)).filter(q => q); + if (questsList.length > 0) formatted += `Optional Quests: ${questsList.join(', ')}\n`; + } + } + } else if (trackerType === 'infoBox') { + formatted += `Info Box:\n`; + if (data.location) formatted += `Location: ${getValue(data.location)}\n`; + if (data.date) formatted += `Date: ${getValue(data.date)}\n`; + if (data.time) formatted += `Time: ${getValue(data.time)}\n`; + if (data.weather) formatted += `Weather: ${getValue(data.weather)}\n`; + if (data.temperature) formatted += `Temperature: ${getValue(data.temperature)}\n`; + + // Custom fields + const knownFields = ['location', 'date', 'time', 'weather', 'temperature']; + for (const [key, value] of Object.entries(data)) { + if (!knownFields.includes(key)) { + const val = getValue(value); + if (val) { + // Convert camelCase to Title Case with spaces (recentEvents -> Recent Events) + const displayName = key + .replace(/([A-Z])/g, ' $1') + .replace(/^./, str => str.toUpperCase()) + .trim(); + formatted += `${displayName}: ${val}\n`; + } + } + } + } else if (trackerType === 'characters') { + if (Array.isArray(data)) { + formatted += `Present Characters:\n`; + for (const char of data) { + const charName = getValue(char.name) || 'Unknown'; + formatted += `- ${charName}:\n`; + + // Details section - parse all custom fields + if (char.details && typeof char.details === 'object') { + for (const [key, value] of Object.entries(char.details)) { + const fieldValue = getValue(value); + if (fieldValue) { + // Convert camelCase/snake_case to Title Case with spaces + const fieldName = key + .replace(/_/g, ' ') + .replace(/([A-Z])/g, ' $1') + .replace(/^./, str => str.toUpperCase()) + .trim(); + formatted += ` ${fieldName}: ${fieldValue}\n`; + } + } + } + + // Relationship + if (char.relationship) { + let relValue; + if (typeof char.relationship === 'object' && !Array.isArray(char.relationship) && 'status' in char.relationship) { + relValue = getValue(char.relationship.status); + } else { + relValue = getValue(char.relationship); + } + if (relValue) formatted += ` Relationship: ${relValue}\n`; + } + + // Thoughts + if (char.thoughts) { + let thoughtValue; + if (typeof char.thoughts === 'object' && !Array.isArray(char.thoughts) && 'content' in char.thoughts) { + thoughtValue = getValue(char.thoughts.content); + } else { + thoughtValue = getValue(char.thoughts); + } + if (thoughtValue) formatted += ` Thoughts: ${thoughtValue}\n`; + } + + // Stats + if (char.stats && typeof char.stats === 'object' && !Array.isArray(char.stats)) { + const statsList = Object.entries(char.stats) + .map(([name, val]) => { + const statValue = getValue(val); + return statValue ? `${name}: ${statValue}` : null; + }) + .filter(s => s) + .join(', '); + if (statsList) formatted += ` Stats: ${statsList}\n`; + } + } + } + } + + return formatted; + } catch (e) { + console.warn('[RPG Companion] Failed to format tracker data for context:', e); + console.warn('[RPG Companion] Error details:', e.stack); + return ''; // Return empty string on error to avoid breaking context + } +} + /** * Generates a formatted contextual summary for SEPARATE mode injection. * Includes the full tracker data in original format (without code fences and separators). @@ -495,41 +741,39 @@ export function generateContextualSummary() { const trackerConfig = extensionSettings.trackerConfig; let summary = ''; - // Helper function to clean tracker data (remove code fences and separator lines) - const cleanTrackerData = (data) => { - if (!data) return ''; - return data - .split('\n') - .filter(line => { - const trimmed = line.trim(); - return trimmed && - !trimmed.startsWith('```') && - trimmed !== '---'; - }) - .join('\n'); - }; - // Add User Stats tracker data if enabled if (extensionSettings.showUserStats && committedTrackerData.userStats) { - const cleanedStats = cleanTrackerData(committedTrackerData.userStats); - if (cleanedStats) { - summary += cleanedStats + '\n\n'; + try { + const formatted = formatTrackerDataForContext(committedTrackerData.userStats, 'userStats', userName); + if (formatted) { + summary += formatted + '\n'; + } + } catch (e) { + console.warn('[RPG Companion] Failed to format userStats for context:', e); } } // Add Info Box tracker data if enabled if (extensionSettings.showInfoBox && committedTrackerData.infoBox) { - const cleanedInfoBox = cleanTrackerData(committedTrackerData.infoBox); - if (cleanedInfoBox) { - summary += cleanedInfoBox + '\n\n'; + try { + const formatted = formatTrackerDataForContext(committedTrackerData.infoBox, 'infoBox', userName); + if (formatted) { + summary += formatted + '\n'; + } + } catch (e) { + console.warn('[RPG Companion] Failed to format infoBox for context:', e); } } // Add Present Characters tracker data if enabled if (extensionSettings.showCharacterThoughts && committedTrackerData.characterThoughts) { - const cleanedThoughts = cleanTrackerData(committedTrackerData.characterThoughts); - if (cleanedThoughts) { - summary += cleanedThoughts + '\n\n'; + try { + const formatted = formatTrackerDataForContext(committedTrackerData.characterThoughts, 'characters', userName); + if (formatted) { + summary += formatted + '\n'; + } + } catch (e) { + console.warn('[RPG Companion] Failed to format characters for context:', e); } } @@ -568,47 +812,58 @@ export function generateRPGPromptText() { promptText += `Here are the previous trackers in the roleplay that you should consider when responding:\n`; promptText += `\n`; - if (extensionSettings.showUserStats) { - if (committedTrackerData.userStats) { - promptText += `Last ${userName}'s Stats:\n${committedTrackerData.userStats}\n\n`; - } else { - promptText += `Last ${userName}'s Stats:\nNone - this is the first update.\n\n`; - } + // Build unified JSON structure for previous trackers (v3.1 format) + const hasAnyPreviousData = committedTrackerData.userStats || committedTrackerData.infoBox || committedTrackerData.characterThoughts; - // Add current quests to the previous data context - if (extensionSettings.quests) { - if (extensionSettings.quests.main && extensionSettings.quests.main !== 'None') { - promptText += `Main Quests: ${extensionSettings.quests.main}\n`; + if (hasAnyPreviousData) { + const unifiedPrevious = {}; + + if (extensionSettings.showUserStats && committedTrackerData.userStats) { + try { + // Try to parse as JSON - apply locks before adding to previous + const lockedData = applyLocks(committedTrackerData.userStats, 'userStats'); + const parsed = JSON.parse(lockedData); + unifiedPrevious.userStats = parsed; + } catch { + // Old text format - show it separately for backward compat + promptText += `${committedTrackerData.userStats}\n\n`; } - if (extensionSettings.quests.optional && extensionSettings.quests.optional.length > 0) { - const optionalQuests = extensionSettings.quests.optional.filter(q => q && q !== 'None').join(', '); - promptText += `Optional Quests: ${optionalQuests || 'None'}\n`; + } + + if (extensionSettings.showInfoBox && committedTrackerData.infoBox) { + try { + // Try to parse as JSON - apply locks before adding to previous + const lockedData = applyLocks(committedTrackerData.infoBox, 'infoBox'); + const parsed = JSON.parse(lockedData); + unifiedPrevious.infoBox = parsed; + } catch { + // Old text format - show it separately for backward compat + if (!unifiedPrevious.userStats) { + promptText += `${committedTrackerData.infoBox}\n\n`; + } } - promptText += `\n`; } - // Add current skills to the previous data context - const skillsSection = extensionSettings.trackerConfig?.userStats?.skillsSection; - if (skillsSection?.enabled && skillsSection.customFields && skillsSection.customFields.length > 0) { - const skillsList = skillsSection.customFields.join(', '); - promptText += `Skills: ${skillsList}\n\n`; + if (extensionSettings.showCharacterThoughts && committedTrackerData.characterThoughts) { + try { + // Try to parse as JSON - apply locks before adding to previous + const lockedData = applyLocks(committedTrackerData.characterThoughts, 'characters'); + const parsed = JSON.parse(lockedData); + unifiedPrevious.characters = parsed; + } catch { + // Old text format - show it separately for backward compat + if (!unifiedPrevious.userStats && !unifiedPrevious.infoBox) { + promptText += `${committedTrackerData.characterThoughts}\n`; + } + } } - } - if (extensionSettings.showInfoBox) { - if (committedTrackerData.infoBox) { - promptText += `Last Info Box:\n${committedTrackerData.infoBox}\n\n`; - } else { - promptText += `Last Info Box:\nNone - this is the first update.\n\n`; - } - } - - if (extensionSettings.showCharacterThoughts) { - if (committedTrackerData.characterThoughts) { - promptText += `Last Present Characters:\n${committedTrackerData.characterThoughts}\n`; - } else { - promptText += `Last Present Characters:\nNone - this is the first update.\n`; + // If we successfully built a unified structure, display it + if (Object.keys(unifiedPrevious).length > 0) { + promptText += JSON.stringify(unifiedPrevious, null, 2) + '\n'; } + } else { + promptText += `None - this is the first update.\n`; } promptText += `\n`; @@ -638,12 +893,12 @@ export async function generateSeparateUpdatePrompt() { // Add character card information const characterInfo = await getCharacterCardsInfo(); if (characterInfo) { - systemMessage += characterInfo + '\n\n'; + systemMessage += characterInfo; } systemMessage += `Here is the description of the protagonist for reference:\n`; systemMessage += `\n{{persona}}\n\n`; - systemMessage += `\n\n`; + systemMessage += `\n`; systemMessage += `Here are the last few messages in the conversation history (between the user and the roleplayer assistant) you should reference when responding:\n`; messages.push({ @@ -665,7 +920,7 @@ export async function generateSeparateUpdatePrompt() { // Build the instruction message let instructionMessage = `\n\n`; instructionMessage += generateRPGPromptText().replace('start your response with', 'respond with'); - instructionMessage += `Provide ONLY the requested data in the exact formats specified above. Do not include any roleplay response, other text, or commentary. Remember, all bracketed placeholders (e.g., [Location], [Mood Emoji]) MUST be replaced with actual content without the square brackets.`; + instructionMessage += `\nProvide ONLY the requested data in the exact JSON format specified above. Do not include any roleplay response, other text, or commentary. Remember, all placeholders MUST be replaced with actual content. Do NOT wrap the JSON in code fences (\`\`\`json). Output the JSON object directly.`; messages.push({ role: 'user', @@ -678,23 +933,16 @@ export async function generateSeparateUpdatePrompt() { /** * Default custom instruction for avatar prompt generation */ -const DEFAULT_AVATAR_CUSTOM_INSTRUCTION = `You are a visionary artist trapped in a cage of logic. Your mind is filled with poetry and distant horizons, but 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. +const DEFAULT_AVATAR_CUSTOM_INSTRUCTION = `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 (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 high 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.`; +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.`; /** * Generates the prompt for LLM-based avatar prompt generation diff --git a/src/systems/integration/sillytavern.js b/src/systems/integration/sillytavern.js index df33570..00a063f 100644 --- a/src/systems/integration/sillytavern.js +++ b/src/systems/integration/sillytavern.js @@ -4,7 +4,7 @@ */ import { getContext } from '../../../../../../extensions.js'; -import { chat, user_avatar, setExtensionPrompt, extension_prompt_types, updateMessageBlock } from '../../../../../../../script.js'; +import { chat, user_avatar, setExtensionPrompt, extension_prompt_types, saveChatDebounced } from '../../../../../../../script.js'; // Core modules import { @@ -15,6 +15,7 @@ import { isPlotProgression, setLastActionWasSwipe, setIsPlotProgression, + setIsGenerating, updateLastGeneratedData, updateCommittedTrackerData, $musicPlayerContainer @@ -25,6 +26,8 @@ import { saveChatData, loadChatData } from '../../core/persistence.js'; 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'; @@ -80,27 +83,35 @@ export function commitTrackerData() { /** * Event handler for when the user sends a message. * Sets the flag to indicate this is NOT a swipe. - * In separate mode with auto-update disabled, commits the displayed tracker data. + * 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); + console.log('[RPG Companion] 🟢 EVENT: onMessageSent - lastActionWasSwipe =', lastActionWasSwipe); - // In separate mode with auto-update disabled, commit displayed tracker when user sends a message + // 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) { - // Commit whatever is currently displayed in lastGeneratedData if (lastGeneratedData.userStats || lastGeneratedData.infoBox || lastGeneratedData.characterThoughts) { committedTrackerData.userStats = lastGeneratedData.userStats; committedTrackerData.infoBox = lastGeneratedData.infoBox; committedTrackerData.characterThoughts = lastGeneratedData.characterThoughts; - // Save to chat metadata - saveChatData(); - - // console.log('[RPG Companion] 💾 Committed displayed tracker on user message (auto-update disabled)'); + console.log('[RPG Companion] 💾 SEPARATE MODE: Committed displayed tracker (auto-update disabled)'); } } } @@ -109,24 +120,41 @@ export function onMessageSent() { * 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); + + // 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); - // console.log('[RPG Companion] Parsed data:', parsedData); - // Update stored data + // 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); @@ -155,17 +183,6 @@ 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 - // BUT: Only commit if this is NOT a swipe (same logic as separate mode) - if (!lastActionWasSwipe && !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; @@ -296,11 +313,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; } @@ -316,21 +334,21 @@ export function onMessageSwiped(messageIndex) { 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; @@ -340,15 +358,12 @@ 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(); @@ -401,6 +416,8 @@ 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'); @@ -411,6 +428,11 @@ export function clearExtensionPrompts() { * 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(); diff --git a/src/systems/interaction/inventoryActions.js b/src/systems/interaction/inventoryActions.js index 6c50ee3..71e75c8 100644 --- a/src/systems/interaction/inventoryActions.js +++ b/src/systems/interaction/inventoryActions.js @@ -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; } diff --git a/src/systems/interaction/inventoryEdit.js b/src/systems/interaction/inventoryEdit.js index 8da3a98..c643523 100644 --- a/src/systems/interaction/inventoryEdit.js +++ b/src/systems/interaction/inventoryEdit.js @@ -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; } diff --git a/src/systems/rendering/infoBox.js b/src/systems/rendering/infoBox.js index aff7cab..ed3c8fd 100644 --- a/src/systems/rendering/infoBox.js +++ b/src/systems/rendering/infoBox.js @@ -12,6 +12,25 @@ import { } 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 `${lockIcon}`; +} /** * Helper to separate emoji from text in a string @@ -56,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 = ` -
-
-
${i18n.getTranslation('infobox.noData.title')}
-
${i18n.getTranslation('infobox.noData.instruction')}
-
-
- `; - $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: '', @@ -105,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, @@ -270,6 +323,7 @@ export function renderInfoBox() { // timeStart: data.timeStart, // location: data.location // }); + } // Get tracker configuration const config = extensionSettings.trackerConfig?.infoBox; @@ -303,8 +357,11 @@ export function renderInfoBox() { weekdayDisplay = weekdayDisplay; } + const dateLockIconHtml = getLockIconHtml('infoBox', 'date'); + row1Widgets.push(`
+ ${dateLockIconHtml}
${monthDisplay}
${weekdayDisplay}
${yearDisplay}
@@ -316,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(`
+ ${weatherLockIconHtml}
${weatherEmoji}
${weatherForecast}
@@ -357,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(`
+ ${tempLockIconHtml}
@@ -372,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; @@ -383,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(`
+ ${timeLockIconHtml}
@@ -392,7 +464,7 @@ export function renderInfoBox() {
-
${timeDisplay}
+
${timeDisplay}
`); } @@ -407,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 += `
+ ${locationLockIconHtml}
📍
@@ -421,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); + } } } } @@ -440,9 +527,12 @@ export function renderInfoBox() { validEvents.push('Click to add event'); } + const eventsLockIconHtml = getLockIconHtml('infoBox', 'recentEvents'); + html += `
+ ${eventsLockIconHtml}
@@ -517,6 +607,30 @@ 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); @@ -541,6 +655,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; diff --git a/src/systems/rendering/inventory.js b/src/systems/rendering/inventory.js index d19b461..6eba950 100644 --- a/src/systems/rendering/inventory.js +++ b/src/systems/rendering/inventory.js @@ -4,14 +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 { i18n } from '../../core/i18n.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 `${lockIcon}`; +} + /** * Converts a location name to a safe ID for use in HTML element IDs. * Must match the logic used in inventoryActions.js. @@ -31,17 +49,17 @@ export function getLocationId(locationName) { export function renderInventorySubTabs(activeTab = 'onPerson') { return `
- - - -
`; @@ -58,28 +76,34 @@ export function renderOnPersonView(onPersonItems, viewMode = 'list') { let itemsHtml = ''; if (items.length === 0) { - itemsHtml = `
${i18n.getTranslation('inventory.onPerson.empty')}
`; + itemsHtml = '
No items carried
'; } 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 `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).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 `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).join(''); + `}).join(''); } } @@ -88,30 +112,30 @@ export function renderOnPersonView(onPersonItems, viewMode = 'list') { return `
-

${i18n.getTranslation('inventory.onPerson.title')}

+

Items Currently Carried

- -
@@ -134,28 +158,34 @@ export function renderClothingView(clothingItems, viewMode = 'list') { let itemsHtml = ''; if (items.length === 0) { - itemsHtml = `
${i18n.getTranslation('inventory.clothing.empty')}
`; + itemsHtml = '
No clothing worn
'; } else { if (viewMode === 'grid') { // Grid view: card-style items - itemsHtml = items.map((item, index) => ` + itemsHtml = items.map((item, index) => { + const lockIconHtml = getLockIconHtml('userStats', `inventory.clothing[${index}]`); + return `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).join(''); + `}).join(''); } else { // List view: full-width rows - itemsHtml = items.map((item, index) => ` + itemsHtml = items.map((item, index) => { + const lockIconHtml = getLockIconHtml('userStats', `inventory.clothing[${index}]`); + return `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).join(''); + `}).join(''); } } @@ -164,30 +194,30 @@ export function renderClothingView(clothingItems, viewMode = 'list') { return `
-

${i18n.getTranslation('inventory.clothing.title')}

+

Clothing Worn

- -
-
@@ -212,30 +242,30 @@ export function renderStoredView(stored, collapsedLocations = [], viewMode = 'li let html = `
-

${i18n.getTranslation('inventory.stored.title')}

+

Storage Locations

- -
@@ -243,8 +273,8 @@ export function renderStoredView(stored, collapsedLocations = [], viewMode = 'li if (locations.length === 0) { html += ` -
- ${i18n.getTranslation('inventory.stored.empty')} +
+ No storage locations yet. Click "Add Location" to create one.
`; } else { @@ -256,28 +286,34 @@ export function renderStoredView(stored, collapsedLocations = [], viewMode = 'li let itemsHtml = ''; if (items.length === 0) { - itemsHtml = `
${i18n.getTranslation('inventory.stored.noItems')}
`; + itemsHtml = '
No items stored here
'; } 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 `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).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 `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).join(''); + `}).join(''); } } @@ -298,13 +334,13 @@ export function renderStoredView(stored, collapsedLocations = [], viewMode = 'li
@@ -313,18 +349,18 @@ export function renderStoredView(stored, collapsedLocations = [], viewMode = 'li
@@ -352,28 +388,34 @@ export function renderAssetsView(assets, viewMode = 'list') { let itemsHtml = ''; if (items.length === 0) { - itemsHtml = `
${i18n.getTranslation('inventory.assets.empty')}
`; + itemsHtml = '
No assets owned
'; } 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 `
+ ${lockIconHtml} ${escapeHtml(item)}
- `).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 `
+ ${lockIconHtml} ${escapeHtml(item)} -
- `).join(''); + `}).join(''); } } @@ -382,30 +424,30 @@ export function renderAssetsView(assets, viewMode = 'list') { return `
-

${i18n.getTranslation('inventory.assets.title')}

+

Vehicles, Property & Major Possessions

- -
@@ -414,7 +456,8 @@ export function renderAssetsView(assets, viewMode = 'list') {
- ${i18n.getTranslation('inventory.assets.description')} + Assets include vehicles (cars, motorcycles), property (homes, apartments), + and major equipment (workshop tools, special items).
@@ -451,7 +494,6 @@ function generateInventoryHTML(inventory, options = {}) { v2Inventory = { version: 2, onPerson: 'None', - clothing: 'None', stored: {}, assets: 'None' }; @@ -461,9 +503,6 @@ function generateInventoryHTML(inventory, options = {}) { if (!v2Inventory.onPerson || typeof v2Inventory.onPerson !== 'string') { v2Inventory.onPerson = 'None'; } - if (!v2Inventory.clothing || typeof v2Inventory.clothing !== 'string') { - v2Inventory.clothing = 'None'; - } if (!v2Inventory.stored || typeof v2Inventory.stored !== 'object' || Array.isArray(v2Inventory.stored)) { v2Inventory.stored = {}; } @@ -563,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(); + }); } /** diff --git a/src/systems/rendering/musicPlayer.js b/src/systems/rendering/musicPlayer.js index 49b2546..b24e791 100644 --- a/src/systems/rendering/musicPlayer.js +++ b/src/systems/rendering/musicPlayer.js @@ -56,20 +56,20 @@ function openInSpotify(songData) { * @param {HTMLElement} container - Container element to render into */ export function renderMusicPlayer(container) { - console.log('[RPG Companion] Music Player: renderMusicPlayer called'); + // 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); + // console.log('[RPG Companion] Music Player: enableSpotifyMusic =', extensionSettings.enableSpotifyMusic); if (!extensionSettings.enableSpotifyMusic) { - console.warn('[RPG Companion] Music Player: Spotify music is disabled'); + // 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); + // console.log('[RPG Companion] Music Player: Rendering with song:', songData); if (!songData || !songData.displayText) { // No song - don't show anything diff --git a/src/systems/rendering/quests.js b/src/systems/rendering/quests.js index 4b0dc26..036b0c3 100644 --- a/src/systems/rendering/quests.js +++ b/src/systems/rendering/quests.js @@ -5,7 +5,24 @@ import { extensionSettings, $questsContainer } from '../../core/state.js'; import { saveSettings } from '../../core/persistence.js'; -import { i18n } from '../../core/i18n.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 `${lockIcon}`; +} /** * HTML escape helper @@ -26,11 +43,11 @@ function escapeHtml(text) { export function renderQuestsSubTabs(activeTab = 'main') { return `
- -
`; @@ -48,9 +65,9 @@ export function renderMainQuestView(mainQuest) { return `
-

${i18n.getTranslation('quests.main.title')}

- ${!hasQuest ? `` : ''}
@@ -59,14 +76,15 @@ export function renderMainQuestView(mainQuest) {
+ ${getLockIconHtml('userStats', 'quests.main')}
${escapeHtml(questDisplay)}
` : ` -
${i18n.getTranslation('quests.main.empty')}
+
No active main quests
`}
- ${i18n.getTranslation('quests.main.hint')} + The main quests represent your primary objective in the story.
`; @@ -110,10 +128,12 @@ export function renderOptionalQuestsView(optionalQuests) { let questsHtml = ''; if (quests.length === 0) { - questsHtml = `
${i18n.getTranslation('quests.optional.empty')}
`; + questsHtml = '
No active optional quests
'; } else { - questsHtml = quests.map((quest, index) => ` + questsHtml = quests.map((quest, index) => { + return `
+ ${getLockIconHtml('userStats', `quests.optional[${index}]`)}
${escapeHtml(quest)}
- `).join(''); + `}).join(''); } return `
-

${i18n.getTranslation('quests.optional.title')}

-
@@ -149,7 +169,7 @@ export function renderOptionalQuestsView(optionalQuests) {
- ${i18n.getTranslation('quests.optional.hint')} + Optional quests are side objectives that complement your main story.
@@ -160,7 +180,7 @@ export function renderOptionalQuestsView(optionalQuests) { * Main render function for quests */ export function renderQuests() { - if (!extensionSettings.showQuests || !$questsContainer) { + if (!extensionSettings.showInventory || !$questsContainer) { return; } @@ -304,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(); + }); } diff --git a/src/systems/rendering/thoughts.js b/src/systems/rendering/thoughts.js index 901bb73..40eef84 100644 --- a/src/systems/rendering/thoughts.js +++ b/src/systems/rendering/thoughts.js @@ -14,10 +14,26 @@ import { FALLBACK_AVATAR_DATA_URI, addDebugLog } from '../../core/state.js'; -import { saveChatData } from '../../core/persistence.js'; +import { saveChatData, saveSettings } from '../../core/persistence.js'; import { getSafeThumbnailUrl } from '../../utils/avatars.js'; -import { saveSettings } from '../../core/persistence.js'; -import { isGenerating, regenerateAvatar } from '../features/avatarGenerator.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 `${lockIcon}`; +} /** * Helper to log to both console and debug logs array @@ -29,14 +45,6 @@ function debugLog(message, data = null) { } } -/** - * Escapes HTML attribute values to prevent quotes from breaking HTML - */ -function escapeHtmlAttr(str) { - if (!str) return ''; - return String(str).replace(/"/g, '"').replace(/'/g, '''); -} - /** * Interpolates color based on percentage value between low and high colors * @param {number} percentage - Value from 0-100 @@ -71,6 +79,44 @@ function getStatColor(percentage, lowColor, highColor) { return `#${toHex(r)}${toHex(g)}${toHex(b)}`; } +/** + * Strips leading and trailing square brackets from a string value. + * Used to clean placeholder notation that AI might include in responses. + * @param {string} value - The value to clean + * @returns {string} Cleaned value without surrounding brackets + */ +function stripBrackets(value) { + if (typeof value !== 'string') return value; + return value.replace(/^\[|\]$/g, '').trim(); +} + +/** + * Extracts the actual value from a field that might be locked. + * If the field is an object with {value, locked}, returns the value. + * Otherwise returns the field as-is. + * @param {any} fieldValue - The field value (might be string or {value, locked} object) + * @returns {string} The actual string value + */ +function extractFieldValue(fieldValue) { + if (fieldValue && typeof fieldValue === 'object' && 'value' in fieldValue) { + return fieldValue.value || ''; + } + return fieldValue || ''; +} + +/** + * 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, ''); +} + /** * Fuzzy name matching that handles: * - Exact matches: "Sabrina" === "Sabrina" @@ -88,12 +134,10 @@ function namesMatch(cardName, aiName) { // 1. Exact match (fast path) if (cardName.toLowerCase() === aiName.toLowerCase()) return true; - // 2. Strip parentheses and quotes from both names and match - // This allows "Dottore (Prime)" to match "Dottore" card for avatar lookup - // and "Marianna "Mari"" to match "Marianna" or "Mari" cards - const stripParensAndQuotes = (s) => s.replace(/\s*\([^)]*\)/g, '').replace(/["']/g, '').trim(); - const cardCore = stripParensAndQuotes(cardName).toLowerCase(); - const aiCore = stripParensAndQuotes(aiName).toLowerCase(); + // 2. Strip parentheses and match + const stripParens = (s) => s.replace(/\s*\([^)]*\)/g, '').trim(); + const cardCore = stripParens(cardName).toLowerCase(); + const aiCore = stripParens(aiName).toLowerCase(); if (cardCore === aiCore) return true; // 3. Check if card name appears as complete word in AI name @@ -103,200 +147,6 @@ function namesMatch(cardName, aiName) { return wordBoundary.test(aiCore); } -/** - * Gets the avatar URL for a character, checking custom NPC avatars first - * @param {string} characterName - Name of the character - * @returns {string} Avatar URL or fallback - */ -function getCharacterAvatar(characterName) { - // First, check if there's a custom NPC avatar - if (extensionSettings.npcAvatars && extensionSettings.npcAvatars[characterName]) { - const avatar = extensionSettings.npcAvatars[characterName]; - // Skip if not a valid string (e.g., if it's an object from a previous bug) - if (typeof avatar === 'string' && avatar) { - debugLog(`[RPG Thoughts] Found custom NPC avatar for: ${characterName}`); - return avatar; - } else { - // Clear invalid avatar data - console.warn(`[RPG Thoughts] Invalid avatar data for ${characterName}, clearing...`); - delete extensionSettings.npcAvatars[characterName]; - } - } - - // Use the existing avatar lookup logic - let characterPortrait = FALLBACK_AVATAR_DATA_URI; - let hasAvatar = false; - - // For group chats, search through group members first - 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') { - const thumbnailUrl = getSafeThumbnailUrl('avatar', matchingMember.avatar); - if (thumbnailUrl) { - hasAvatar = true; - return thumbnailUrl; - } - } - } - } catch (groupError) { - debugLog('[RPG Thoughts] Error checking group members:', groupError.message); - } - } - - // For regular chats or if not found in group, search all characters - if (characters && characters.length > 0) { - const matchingCharacter = characters.find(c => - c && c.name && namesMatch(c.name, characterName) - ); - - if (matchingCharacter && matchingCharacter.avatar && matchingCharacter.avatar !== 'none') { - const thumbnailUrl = getSafeThumbnailUrl('avatar', matchingCharacter.avatar); - if (thumbnailUrl) { - hasAvatar = true; - return thumbnailUrl; - } - } - } - - // If this is the current character in a 1-on-1 chat, use their portrait - if (this_chid !== undefined && characters[this_chid] && - characters[this_chid].name && namesMatch(characters[this_chid].name, characterName)) { - const thumbnailUrl = getSafeThumbnailUrl('avatar', characters[this_chid].avatar); - if (thumbnailUrl) { - hasAvatar = true; - return thumbnailUrl; - } - } - - return characterPortrait; -} - -/** - * Handles uploading a custom avatar for an NPC character - * @param {string} characterName - Name of the character to set avatar for - */ -function uploadNpcAvatar(characterName) { - // Create a file input element - const input = document.createElement('input'); - input.type = 'file'; - input.accept = 'image/*'; - - input.onchange = async (e) => { - const file = e.target.files[0]; - if (!file) return; - - // Validate file size (max 2MB to keep settings file reasonable) - if (file.size > 2 * 1024 * 1024) { - console.error('[RPG Companion] Image file too large. Maximum size is 2MB.'); - // You could add a toast notification here if available - return; - } - - // Validate file type - if (!file.type.startsWith('image/')) { - console.error('[RPG Companion] Invalid file type. Please select an image.'); - return; - } - - try { - // Read the file and convert to base64 data URI - const reader = new FileReader(); - reader.onload = (event) => { - const dataUri = event.target.result; - - // Initialize npcAvatars if it doesn't exist - if (!extensionSettings.npcAvatars) { - extensionSettings.npcAvatars = {}; - } - - // Store the avatar - extensionSettings.npcAvatars[characterName] = dataUri; - - // Save settings - saveSettings(); - - console.log(`[RPG Companion] Avatar uploaded for NPC: ${characterName}`); - - // Re-render to show the new avatar - renderThoughts(); - }; - - reader.onerror = (error) => { - console.error('[RPG Companion] Error reading image file:', error); - }; - - reader.readAsDataURL(file); - } catch (error) { - console.error('[RPG Companion] Error uploading avatar:', error); - } - }; - - // Trigger the file input - input.click(); -} - -/** - * Removes a character from the Present Characters panel and saved data - * @param {string} characterName - Name of the character to remove - */ -function removeCharacter(characterName) { - console.log(`[RPG Companion] Removing character: ${characterName}`); - - // Initialize if it doesn't exist - if (!lastGeneratedData.characterThoughts) { - return; - } - - const lines = lastGeneratedData.characterThoughts.split('\n'); - const newLines = []; - let skipUntilNextCharacter = false; - let foundCharacter = false; - - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - - // Check if this is the start of the character we want to remove - if (line.startsWith('- ')) { - const name = line.substring(2).trim(); - if (name.toLowerCase() === characterName.toLowerCase()) { - foundCharacter = true; - skipUntilNextCharacter = true; - continue; // Skip this line - } else { - // This is a different character, stop skipping - skipUntilNextCharacter = false; - } - } - - // If we're not skipping, add the line - if (!skipUntilNextCharacter) { - newLines.push(lines[i]); - } - } - - if (foundCharacter) { - // Update both lastGeneratedData and committedTrackerData - lastGeneratedData.characterThoughts = newLines.join('\n'); - committedTrackerData.characterThoughts = newLines.join('\n'); - - // Save to chat metadata - saveChatData(); - - console.log(`[RPG Companion] Character removed: ${characterName}`); - - // Re-render the panel - renderThoughts(); - } else { - console.warn(`[RPG Companion] Character not found: ${characterName}`); - } -} - /** * Renders character thoughts (Present Characters) panel. * Displays character cards with avatars, relationship badges, and traits. @@ -307,14 +157,17 @@ export function renderThoughts() { return; } + // Don't render if no data exists (e.g., after cache clear) + const thoughtsData = lastGeneratedData.characterThoughts || committedTrackerData.characterThoughts; + if (!thoughtsData) { + $thoughtsContainer.html('
No character data generated yet
'); + return; + } + debugLog('[RPG Thoughts] ==================== RENDERING PRESENT CHARACTERS ===================='); debugLog('[RPG Thoughts] showCharacterThoughts setting:', extensionSettings.showCharacterThoughts); debugLog('[RPG Thoughts] Container exists:', !!$thoughtsContainer); - // Save scroll position before re-rendering - const scrollParent = $thoughtsContainer.closest('.rpg-content-box, .rpg-tab-content, .rpg-mobile-tab-content').filter(':visible').first(); - const savedScrollTop = scrollParent.length > 0 ? scrollParent.scrollTop() : 0; - // Add updating class for animation if (extensionSettings.enableAnimations) { $thoughtsContainer.addClass('rpg-content-updating'); @@ -325,11 +178,8 @@ export function renderThoughts() { const enabledFields = config?.customFields?.filter(f => f && f.enabled && f.name) || []; const characterStatsConfig = config?.characterStats; const enabledCharStats = characterStatsConfig?.enabled && characterStatsConfig?.customStats?.filter(s => s && s.enabled && s.name) || []; - - // Check if relationships are enabled (new structure with fallback to legacy) - const relationshipsEnabled = config?.relationships?.enabled !== false; // Default to true if not set - const relationshipFields = relationshipsEnabled ? (config?.relationshipFields || []) : []; - const hasRelationshipEnabled = relationshipFields.length > 0 && relationshipsEnabled; + const relationshipFields = config?.relationshipFields || []; + const hasRelationshipEnabled = relationshipFields.length > 0; // Use committedTrackerData as fallback if lastGeneratedData is empty (e.g., after page refresh) const characterThoughtsData = lastGeneratedData.characterThoughts || committedTrackerData.characterThoughts || ''; @@ -339,11 +189,91 @@ export function renderThoughts() { debugLog('[RPG Thoughts] Enabled custom fields:', enabledFields.map(f => f.name)); debugLog('[RPG Thoughts] Enabled character stats:', enabledCharStats.map(s => s.name)); - const lines = characterThoughtsData.split('\n'); - const presentCharacters = []; + let presentCharacters = []; - debugLog('[RPG Thoughts] Split into lines count:', lines.length); - debugLog('[RPG Thoughts] Lines:', lines); + // Try parsing as JSON first (new format) + try { + const parsed = typeof characterThoughtsData === 'string' + ? JSON.parse(characterThoughtsData) + : characterThoughtsData; + + // Handle both {characters: [...]} and direct array formats + const charactersArray = Array.isArray(parsed) ? parsed : (parsed.characters || []); + + if (charactersArray.length > 0) { + // JSON format: array of character objects + presentCharacters = charactersArray.map(char => { + const character = { + name: char.name, + emoji: char.emoji || '👤' + }; + + // Extract details (appearance, demeanor, etc.) + if (char.details) { + // Map details object to custom fields by snake_case name + for (const field of enabledFields) { + const fieldKey = toSnakeCase(field.name); + if (char.details[fieldKey] !== undefined) { + character[field.name] = stripBrackets(char.details[fieldKey]); + } + } + } + + // Also check for fields at root level (for backward compatibility) + for (const field of enabledFields) { + const fieldKey = toSnakeCase(field.name); + if (char[fieldKey] !== undefined) { + character[field.name] = stripBrackets(char[fieldKey]); + } + } + + // Extract relationship + if (char.relationship) { + character.Relationship = stripBrackets(char.relationship.status || char.relationship); + } + + // Extract thoughts content for bubble display + if (char.thoughts) { + character.ThoughtsContent = stripBrackets(char.thoughts.content || char.thoughts); + } + + // Extract character stats if present + if (char.stats && enabledCharStats.length > 0) { + // Handle both object format {Health: 100, Energy: 95} and array format [{name: "Health", value: 100}] + if (Array.isArray(char.stats)) { + // Array format: [{name: "Health", value: 100}, {name: "Energy", value: 95}] + for (const statObj of char.stats) { + if (statObj.name && statObj.value !== undefined) { + const matchingStat = enabledCharStats.find(s => s.name === statObj.name); + if (matchingStat) { + character[statObj.name] = statObj.value; + } + } + } + } else { + // Object format: {Health: 100, Energy: 95} + for (const stat of enabledCharStats) { + if (char.stats[stat.name] !== undefined) { + character[stat.name] = char.stats[stat.name]; + } + } + } + } + + return character; + }); + + debugLog('[RPG Thoughts] ✓ Parsed JSON format, characters:', presentCharacters.length); + } + } catch (e) { + debugLog('[RPG Thoughts] Not JSON format, falling back to text parsing'); + } + + // If JSON parsing failed or returned empty, try text format + if (presentCharacters.length === 0) { + const lines = characterThoughtsData.split('\n'); + debugLog('[RPG Thoughts] Split into lines count:', lines.length); + debugLog('[RPG Thoughts] Lines:', lines); // Parse new multi-line format: // - [Name] @@ -354,23 +284,7 @@ export function renderThoughts() { let lineNumber = 0; let currentCharacter = null; - // Pre-process: normalize the format to handle cases where "- char" appears mid-line - // This handles: "Thoughts: ... - char 2" by splitting it into separate lines - const normalizedLines = []; - for (let line of lines) { - // Check if line contains "- [name]" pattern after some content (not at start) - // Match pattern like "some text - CharName" where there's content before the dash - const midLineCharMatch = line.match(/^(.+?)\s+-\s+([A-Z][a-zA-Z\s]+)$/); - if (midLineCharMatch && !line.trim().startsWith('- ')) { - // Split: first part stays as one line, "- Name" becomes new line - normalizedLines.push(midLineCharMatch[1].trim()); - normalizedLines.push('- ' + midLineCharMatch[2].trim()); - } else { - normalizedLines.push(line); - } - } - - for (const line of normalizedLines) { + for (const line of lines) { lineNumber++; // Skip empty lines, headers, dividers, and code fences @@ -443,10 +357,10 @@ export function renderThoughts() { debugLog(`[RPG Thoughts] Skipping thoughts/feelings line (handled in bubble rendering)`); } } + } // End of text format parsing // Get relationship emojis from config (with fallback defaults) - // Support both new and legacy structure - const relationshipEmojis = config?.relationships?.relationshipEmojis || config?.relationshipEmojis || { + const relationshipEmojis = config?.relationshipEmojis || { 'Enemy': '⚔️', 'Neutral': '⚖️', 'Friend': '⭐', @@ -462,8 +376,8 @@ export function renderThoughts() { debugLog('[RPG Thoughts] ==================== BUILDING HTML ===================='); debugLog('[RPG Thoughts] Starting HTML generation for', presentCharacters.length + ' characters'); - // If no characters parsed, show a placeholder editable card (if narrator mode is disabled) - if (presentCharacters.length === 0 && !extensionSettings.narratorMode) { + // If no characters parsed, show a placeholder editable card + if (presentCharacters.length === 0) { debugLog('[RPG Thoughts] ⚠ No characters parsed - showing placeholder card'); // Get default character portrait let defaultPortrait = FALLBACK_AVATAR_DATA_URI; @@ -479,24 +393,17 @@ export function renderThoughts() { defaultName = characters[this_chid].name || 'Character'; } - const escapedDefaultName = escapeHtmlAttr(defaultName); - - // Determine right-click action text based on auto-generate setting - const defaultAvatarRightClickAction = extensionSettings.autoGenerateAvatars - ? 'Right-click to regenerate avatar' - : 'Right-click to delete avatar'; - html += '
'; html += ` -
-
- ${escapedDefaultName} -
⚖️
+
+
+ ${defaultName} +
⚖️
- 😊 - ${defaultName} + 😊 + ${defaultName}
`; @@ -504,7 +411,7 @@ export function renderThoughts() { for (const field of enabledFields) { const fieldId = field.name.toLowerCase().replace(/\s+/g, '-'); html += ` -
+
`; } @@ -523,10 +430,66 @@ export function renderThoughts() { try { debugLog(`[RPG Thoughts] Building HTML for character ${characterIndex}/${presentCharacters.length}:`, char.name); - // Find character portrait using the new helper function - const characterPortrait = getCharacterAvatar(char.name); + // Find character portrait + // Use a base64-encoded SVG placeholder as fallback to avoid 400 errors + let characterPortrait = FALLBACK_AVATAR_DATA_URI; - debugLog(`[RPG Thoughts] Final avatar for ${char.name}:`, typeof characterPortrait === 'string' ? characterPortrait.substring(0, 50) + '...' : characterPortrait); + debugLog(`[RPG Thoughts] Looking up avatar for: ${char.name}`); + + // For group chats, search through group members first + if (selected_group) { + debugLog('[RPG Thoughts] In group chat, checking group members...'); + + try { + const groupMembers = getGroupMembers(selected_group); + debugLog('[RPG Thoughts] Group members count:', groupMembers ? groupMembers.length : 0); + + if (groupMembers && groupMembers.length > 0) { + const matchingMember = groupMembers.find(member => + member && member.name && namesMatch(member.name, char.name) + ); + + if (matchingMember && matchingMember.avatar && matchingMember.avatar !== 'none') { + const thumbnailUrl = getSafeThumbnailUrl('avatar', matchingMember.avatar); + if (thumbnailUrl) { + characterPortrait = thumbnailUrl; + debugLog('[RPG Thoughts] Found avatar in group members'); + } + } + } + } catch (groupError) { + debugLog('[RPG Thoughts] Error checking group members:', groupError.message); + } + } + + // For regular chats or if not found in group, search all characters + if (characterPortrait === FALLBACK_AVATAR_DATA_URI && characters && characters.length > 0) { + debugLog('[RPG Thoughts] Searching all characters...'); + + const matchingCharacter = characters.find(c => + c && c.name && namesMatch(c.name, char.name) + ); + + if (matchingCharacter && matchingCharacter.avatar && matchingCharacter.avatar !== 'none') { + const thumbnailUrl = getSafeThumbnailUrl('avatar', matchingCharacter.avatar); + if (thumbnailUrl) { + characterPortrait = thumbnailUrl; + debugLog('[RPG Thoughts] Found avatar in all characters'); + } + } + } + + // If this is the current character in a 1-on-1 chat, use their portrait + if (this_chid !== undefined && characters[this_chid] && + characters[this_chid].name && namesMatch(characters[this_chid].name, char.name)) { + const thumbnailUrl = getSafeThumbnailUrl('avatar', characters[this_chid].avatar); + if (thumbnailUrl) { + characterPortrait = thumbnailUrl; + debugLog('[RPG Thoughts] Found avatar from current character'); + } + } + + debugLog(`[RPG Thoughts] Final avatar for ${char.name}:`, characterPortrait.substring(0, 50) + '...'); // Get relationship badge - only if relationships are enabled in config let relationshipBadge = '⚖️'; // Default @@ -542,40 +505,41 @@ export function renderThoughts() { debugLog(`[RPG Thoughts] Building HTML card for ${char.name}...`); - // Escape character name for use in HTML attributes - const escapedName = escapeHtmlAttr(char.name); - - // Check if avatar is being generated - const isCurrentlyGenerating = isGenerating(char.name); - - // Determine right-click action text based on auto-generate setting - const avatarRightClickAction = extensionSettings.autoGenerateAvatars - ? 'Right-click to regenerate avatar' - : 'Right-click to delete avatar'; - html += ` -
-
- ${escapedName} - ${isCurrentlyGenerating ? '
' : ''} - ${hasRelationshipEnabled ? `
${relationshipBadge}
` : ''} +
+
+ ${char.name} + ${hasRelationshipEnabled ? `
${relationshipBadge}
` : ''}
- ${char.emoji} - ${char.name} - + ${char.emoji} + ${char.name}
`; // Render custom fields dynamically for (const field of enabledFields) { - const fieldValue = char[field.name] || ''; + const rawValue = char[field.name]; + const fieldValue = extractFieldValue(rawValue); const fieldId = field.name.toLowerCase().replace(/\s+/g, '-'); - html += ` -
${fieldValue}
- `; + const fieldNameLower = field.name.toLowerCase(); + // Skip lock icons for thoughts field + const showLock = !fieldNameLower.includes('thought'); + if (showLock) { + const lockIconHtml = getLockIconHtml('characters', `${char.name}.${field.name}`); + html += ` +
+ ${lockIconHtml} + ${fieldValue} +
+ `; + } else { + html += ` +
${fieldValue}
+ `; + } } html += ` @@ -584,13 +548,16 @@ export function renderThoughts() { // Render character stats if enabled (outside rpg-character-info) if (enabledCharStats.length > 0) { - html += `
`; + const lockIconHtml = getLockIconHtml('characters', `${char.name}.stats`); + html += `
+ ${lockIconHtml} +
`; for (const stat of enabledCharStats) { const statValue = char[stat.name] || 0; const statColor = getStatColor(statValue, extensionSettings.statBarColorLow, extensionSettings.statBarColorHigh); html += `
- ${stat.name}: ${statValue}% + ${stat.name}: ${statValue}%
`; } @@ -617,11 +584,6 @@ export function renderThoughts() { $thoughtsContainer.html(html); - // Restore scroll position to prevent UI jumping - if (scrollParent.length > 0 && savedScrollTop > 0) { - scrollParent.scrollTop(savedScrollTop); - } - debugLog('[RPG Thoughts] ✓ HTML rendered to container'); debugLog('[RPG Thoughts] ======================================================='); @@ -634,70 +596,29 @@ export function renderThoughts() { updateCharacterField(character, field, value); }); - // Add event handler for avatar uploads - $thoughtsContainer.find('.rpg-avatar-upload').on('click', function(e) { - // Prevent triggering if clicking on the relationship badge - if ($(e.target).hasClass('rpg-relationship-badge') || $(e.target).closest('.rpg-relationship-badge').length > 0) { - return; - } + // Add event listener for section lock icon clicks (support both click and touch) + $thoughtsContainer.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); - const characterName = $(this).data('character'); - console.log('[RPG Companion] Avatar upload clicked for:', characterName); - uploadNpcAvatar(characterName); - }); + // Toggle lock state + setItemLock(trackerType, itemPath, !currentlyLocked); - // Add event handler for regenerating avatars (right-click) - $thoughtsContainer.find('.rpg-avatar-upload').on('contextmenu', async function(e) { - // Prevent triggering if clicking on the relationship badge - if ($(e.target).hasClass('rpg-relationship-badge') || $(e.target).closest('.rpg-relationship-badge').length > 0) { - return; - } + // Update icon + const newIcon = !currentlyLocked ? '🔒' : '🔓'; + const newTitle = !currentlyLocked ? 'Locked' : 'Unlocked'; + $icon.text(newIcon); + $icon.attr('title', newTitle); - e.preventDefault(); // Prevent default context menu - const characterName = $(this).data('character'); - const $avatarEl = $(this); + // Toggle 'locked' class for persistent visibility + $icon.toggleClass('locked', !currentlyLocked); - // Check if auto-generation is enabled - if (!extensionSettings.autoGenerateAvatars) { - // If auto-generation is disabled, just remove the custom avatar - if (extensionSettings.npcAvatars && extensionSettings.npcAvatars[characterName]) { - delete extensionSettings.npcAvatars[characterName]; - saveSettings(); - console.log(`[RPG Companion] Removed custom avatar for: ${characterName}`); - renderThoughts(); - } - return; - } - - // Show generating state with spinner overlay - $avatarEl.addClass('rpg-avatar-generating'); - if (!$avatarEl.find('.rpg-generating-overlay').length) { - $avatarEl.append('
'); - } - console.log(`[RPG Companion] Regenerating avatar for: ${characterName}`); - - try { - // Regenerate the avatar - const newUrl = await regenerateAvatar(characterName); - - if (newUrl) { - console.log(`[RPG Companion] Successfully regenerated avatar for: ${characterName}`); - } else { - console.warn(`[RPG Companion] Failed to regenerate avatar for: ${characterName}`); - } - } catch (error) { - console.error(`[RPG Companion] Error regenerating avatar for ${characterName}:`, error); - } - - // Re-render to show the new avatar (or fallback) - renderThoughts(); - }); - - // Add event handler for character removal - $thoughtsContainer.find('.rpg-character-remove').on('click', function(e) { - e.stopPropagation(); // Prevent event bubbling - const characterName = $(this).data('character'); - removeCharacter(characterName); + // Save settings + saveSettings(); }); // Remove updating class after animation @@ -880,7 +801,7 @@ export function updateCharacterField(characterName, field, value) { } newCharacterLines.push(`Details: ${detailsParts.join(' | ')}`); - if (presentCharsConfig?.relationships?.enabled !== false && presentCharsConfig?.relationshipFields?.length > 0) { + if (presentCharsConfig?.relationshipFields?.length > 0) { const emojiToRelationship = { '⚔️': 'Enemy', '⚖️': 'Neutral', '⭐': 'Friend', '❤️': 'Lover' }; const relationshipValue = field === 'Relationship' ? (emojiToRelationship[value] || value) : 'Neutral'; newCharacterLines.push(`Relationship: ${relationshipValue}`); @@ -964,11 +885,39 @@ export function updateChatThoughts() { } // Parse the Present Characters data to get thoughts - const lines = lastGeneratedData.characterThoughts.split('\n'); - const thoughtsArray = []; // Array of {name, emoji, thought} + let thoughtsArray = []; // Array of {name, emoji, thought} const thoughtsConfig = extensionSettings.trackerConfig?.presentCharacters?.thoughts; const thoughtsLabel = thoughtsConfig?.name || 'Thoughts'; + // Try JSON format first + try { + const parsed = typeof lastGeneratedData.characterThoughts === 'string' + ? JSON.parse(lastGeneratedData.characterThoughts) + : lastGeneratedData.characterThoughts; + + // Handle both {characters: [...]} and direct array formats + const charactersArray = Array.isArray(parsed) ? parsed : (parsed.characters || []); + + if (charactersArray.length > 0) { + // Extract thoughts from JSON character objects + thoughtsArray = charactersArray + .filter(char => char.thoughts && char.thoughts.content) + .map(char => ({ + name: (char.name || '').toLowerCase(), + emoji: char.emoji || '👤', + thought: char.thoughts.content + })); + + debugLog('[RPG Thoughts Bubble] ✓ Parsed JSON format, thoughts:', thoughtsArray.length); + } + } catch (e) { + debugLog('[RPG Thoughts Bubble] Not JSON format, falling back to text parsing'); + } + + // If JSON parsing failed or returned empty, try text format + if (thoughtsArray.length === 0) { + const lines = lastGeneratedData.characterThoughts.split('\n'); + // console.log('[RPG Companion] Parsing thoughts from lines:', lines); // Parse new format to build character map and thoughts @@ -1022,6 +971,7 @@ export function updateChatThoughts() { } } } + } // End of text format parsing for thoughts bubbles debugLog('[RPG Thoughts] Parsed thoughts:', thoughtsArray); @@ -1056,6 +1006,325 @@ export function updateChatThoughts() { createThoughtPanel($targetMessage, thoughtsArray); } +// ===== GLOBAL DRAGGING SETUP FOR THOUGHT ICON (MOBILE ONLY) ===== +// These variables and handlers are set up once, outside createThoughtPanel +let isDragging = false; +let touchMoved = false; +let dragStartTime = 0; +let dragStartX = 0; +let dragStartY = 0; +let iconStartX = 0; +let iconStartY = 0; +const DRAG_THRESHOLD = 10; +const LONG_PRESS_DURATION = 200; +let rafId = null; +let pendingX = null; +let pendingY = null; +let thoughtIconDragHandlersInitialized = false; +let justFinishedDragging = false; // Flag to block clicks immediately after drag + +function updateIconDragPosition() { + if (pendingX !== null && pendingY !== null) { + $('#rpg-thought-icon').css({ + left: pendingX + 'px', + top: pendingY + 'px', + right: 'auto', + bottom: 'auto' + }); + pendingX = null; + pendingY = null; + } + rafId = null; +} + +function initThoughtIconDragHandlers() { + if (thoughtIconDragHandlersInitialized) return; + thoughtIconDragHandlersInitialized = true; + + console.log('[Thought Icon] Initializing drag handlers ONCE - will attach to icon when created'); +} + +// Function to attach drag handlers to a specific icon element +function attachDragHandlersToIcon($icon) { + console.log('[Thought Icon] Attaching handlers to icon element'); + + // Remove any existing handlers + $icon.off('.thoughtIconDrag'); + + // Test: add a simple click handler to verify events work + $icon.on('click.thoughtIconDrag', function(e) { + // Check global flag set immediately after drag completes + if (justFinishedDragging) { + console.log('[Thought Icon] CLICK blocked - just finished dragging'); + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); + return false; + } + console.log('[Thought Icon] CLICK detected on icon!'); + }); + + // Touch drag support - mobile only + $icon.on('touchstart.thoughtIconDrag', function(e) { + if (window.innerWidth > 1000) return; + + console.log('[Thought Icon] touchstart'); + touchMoved = false; + dragStartTime = Date.now(); + const touch = e.originalEvent.touches[0]; + dragStartX = touch.clientX; + dragStartY = touch.clientY; + + const offset = $(this).offset(); + iconStartX = offset.left; + iconStartY = offset.top; + + isDragging = false; + }); + + $icon.on('touchmove.thoughtIconDrag', function(e) { + if (window.innerWidth > 1000) return; + + if (!touchMoved) { + console.log('[Thought Icon] touchmove - first movement'); + } + touchMoved = true; + const touch = e.originalEvent.touches[0]; + const deltaX = touch.clientX - dragStartX; + const deltaY = touch.clientY - dragStartY; + const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + const timeSinceStart = Date.now() - dragStartTime; + + if (!isDragging && (timeSinceStart > LONG_PRESS_DURATION || distance > DRAG_THRESHOLD)) { + isDragging = true; + $(this).addClass('dragging'); + } + + if (isDragging) { + e.preventDefault(); + + let newX = iconStartX + deltaX; + let newY = iconStartY + deltaY; + + const iconWidth = $(this).outerWidth(); + const iconHeight = $(this).outerHeight(); + + const minX = 10; + const maxX = window.innerWidth - iconWidth - 10; + const minY = 10; + const maxY = window.innerHeight - iconHeight - 10; + + newX = Math.max(minX, Math.min(maxX, newX)); + newY = Math.max(minY, Math.min(maxY, newY)); + + pendingX = newX; + pendingY = newY; + if (!rafId) { + rafId = requestAnimationFrame(updateIconDragPosition); + } + } + }); + + $icon.on('touchend.thoughtIconDrag', function(e) { + console.log('[Thought Icon] touchend - isDragging:', isDragging, 'touchMoved:', touchMoved); + + if (isDragging) { + const offset = $(this).offset(); + const newPosition = { + left: offset.left + 'px', + top: offset.top + 'px' + }; + + extensionSettings.thoughtIconPosition = newPosition; + saveSettings(); + + setTimeout(() => { + const $currentIcon = $('#rpg-thought-icon'); + if ($currentIcon.length) { + constrainIconToViewport($currentIcon); + } + }, 10); + + setTimeout(() => { + $(this).removeClass('dragging'); + }, 50); + + isDragging = false; + + $(this).data('just-dragged', true); + setTimeout(() => { + $(this).data('just-dragged', false); + }, 300); + + e.preventDefault(); + e.stopPropagation(); + } else if (!touchMoved) { + console.log('[Thought Icon] Opening panel - was a tap'); + const $panel = $('#rpg-thought-panel'); + const iconOffset = $(this).offset(); + if (iconOffset) { + $panel.css({ + top: iconOffset.top + 'px', + left: iconOffset.left + 'px', + display: 'none' + }); + } + + $(this).addClass('rpg-hidden'); + $panel.fadeIn(200); + } else { + console.log('[Thought Icon] Did nothing - touchMoved but not isDragging'); + } + }); + + // Mouse drag support - mobile only + let mouseDown = false; + + $icon.on('mousedown.thoughtIconDrag', function(e) { + if (window.innerWidth > 1000) return; + + console.log('[Thought Icon] mousedown'); + e.preventDefault(); + + mouseDown = true; + touchMoved = false; + dragStartTime = Date.now(); + dragStartX = e.clientX; + dragStartY = e.clientY; + + const offset = $(this).offset(); + iconStartX = offset.left; + iconStartY = offset.top; + + isDragging = false; + }); + + $(document).on('mousemove.thoughtIconDrag', function(e) { + if (!mouseDown || window.innerWidth > 1000) return; + + if (!touchMoved) { + console.log('[Thought Icon] mousemove - first movement'); + } + touchMoved = true; + + const deltaX = e.clientX - dragStartX; + const deltaY = e.clientY - dragStartY; + const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + const timeSinceStart = Date.now() - dragStartTime; + + if (!isDragging && (timeSinceStart > LONG_PRESS_DURATION || distance > DRAG_THRESHOLD)) { + isDragging = true; + $('#rpg-thought-icon').addClass('dragging'); + } + + if (isDragging) { + e.preventDefault(); + + let newX = iconStartX + deltaX; + let newY = iconStartY + deltaY; + + const $currentIcon = $('#rpg-thought-icon'); + const iconWidth = $currentIcon.outerWidth(); + const iconHeight = $currentIcon.outerHeight(); + + const minX = 10; + const maxX = window.innerWidth - iconWidth - 10; + const minY = 10; + const maxY = window.innerHeight - iconHeight - 10; + + newX = Math.max(minX, Math.min(maxX, newX)); + newY = Math.max(minY, Math.min(maxY, newY)); + + pendingX = newX; + pendingY = newY; + if (!rafId) { + rafId = requestAnimationFrame(updateIconDragPosition); + } + } + }); + + $(document).on('mouseup.thoughtIconDrag', function(e) { + if (!mouseDown) return; + + console.log('[Thought Icon] mouseup - isDragging:', isDragging, 'touchMoved:', touchMoved); + + mouseDown = false; + + if (isDragging) { + // Set global flag IMMEDIATELY to block click event + justFinishedDragging = true; + setTimeout(() => { + justFinishedDragging = false; + }, 300); + + const $currentIcon = $('#rpg-thought-icon'); + + // Remove dragging class immediately to restore transitions and cursor + $currentIcon.removeClass('dragging'); + + const offset = $currentIcon.offset(); + const newPosition = { + left: offset.left + 'px', + top: offset.top + 'px' + }; + + extensionSettings.thoughtIconPosition = newPosition; + saveSettings(); + + setTimeout(() => { + if ($currentIcon.length) { + constrainIconToViewport($currentIcon); + } + }, 10); + + isDragging = false; + + // Prevent default and stop all propagation + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); + return false; + } + // If not dragging but touchMoved, do nothing (small drag below threshold) + }); +} + +function constrainIconToViewport($icon) { + if (!extensionSettings.thoughtIconPosition) return; + + const offset = $icon.offset(); + if (!offset) return; + + let currentX = offset.left; + let currentY = offset.top; + + const iconWidth = $icon.outerWidth(); + const iconHeight = $icon.outerHeight(); + + const minX = 10; + const maxX = window.innerWidth - iconWidth - 10; + const minY = 10; + const maxY = window.innerHeight - iconHeight - 10; + + let newX = Math.max(minX, Math.min(maxX, currentX)); + let newY = Math.max(minY, Math.min(maxY, currentY)); + + if (newX !== currentX || newY !== currentY) { + $icon.css({ + left: newX + 'px', + top: newY + 'px', + right: 'auto', + bottom: 'auto' + }); + + extensionSettings.thoughtIconPosition = { + left: newX + 'px', + top: newY + 'px' + }; + saveSettings(); + } +} + /** * Creates or updates the floating thought panel positioned next to the character's avatar. * Handles responsive positioning for left/right panel modes and mobile viewports. @@ -1064,6 +1333,8 @@ export function updateChatThoughts() { * @param {Array} thoughtsArray - Array of thought objects {name, emoji, thought} */ export function createThoughtPanel($message, thoughtsArray) { + // Initialize drag handlers once + initThoughtIconDragHandlers(); // Remove existing thought panel $('#rpg-thought-panel').remove(); $('#rpg-thought-icon').remove(); @@ -1082,13 +1353,12 @@ export function createThoughtPanel($message, thoughtsArray) { // Build thought bubbles HTML let thoughtsHtml = ''; thoughtsArray.forEach((thought, index) => { - const escapedThoughtName = escapeHtmlAttr(thought.name); thoughtsHtml += `
${thought.emoji}
-
+
${thought.thought}
@@ -1133,139 +1403,230 @@ export function createThoughtPanel($message, thoughtsArray) { $thoughtIcon.css(customStyles); } - // Force a consistent width for the bubble to ensure proper positioning - $thoughtPanel.css('width', '350px'); - // Append to body so it's not clipped by chat container $('body').append($thoughtPanel); - $('body').append($thoughtIcon); // Position the panel next to the avatar - const panelWidth = 350; - const panelMargin = 20; + $('body').append($thoughtIcon); - let top = avatarRect.top; // Align top of panel with top of avatar - let left; - let right; - let useRightPosition = false; - let iconTop = avatarRect.top; - let iconLeft; + // Attach drag handlers to the icon + attachDragHandlersToIcon($thoughtIcon); - // Detect mobile viewport (matches CSS breakpoint) - const isMobile = window.innerWidth <= 1000; + // Simple viewport-based positioning - always top-left corner + const margin = 20; + const topMargin = 10; // Space between ST's top bar and thought panel - if (isMobile) { - // On mobile: position icon horizontally centered on avatar - // The CSS transform will shift it upward by 60px - iconTop = avatarRect.top; // Start at avatar top (CSS will move it up) - iconLeft = avatarRect.left + (avatarRect.width / 2) - 18; // Centered horizontally (18px = half of 36px icon width) + // Function to calculate top position based on ST's top bar + const getTopPosition = () => { + const topBar = $('#top-settings-holder'); + if (topBar.length) { + return (topBar.outerHeight() || 140) + topMargin; + } + return 140 + topMargin; // Fallback + }; - // Center the thought panel horizontally on mobile - left = window.innerWidth / 2 - panelWidth / 2; - top = avatarRect.top + avatarRect.height + 60; // Position below icon with spacing + // Function to update bubble position and width + const updateBubblePosition = () => { + const topPosition = getTopPosition(); + const sheld = $('#sheld')[0]; + const isRightPanel = extensionSettings.panelPosition === 'right'; - // No side-specific classes on mobile - $thoughtPanel.removeClass('rpg-thought-panel-left rpg-thought-panel-right'); - $thoughtIcon.removeClass('rpg-thought-icon-left rpg-thought-icon-right'); + // Update top position for panel (always in desktop) + $thoughtPanel.css('top', `${topPosition}px`); - console.log('[RPG Companion] Mobile thought icon positioning:', { - isMobile, - windowWidth: window.innerWidth, - avatarLeft: avatarRect.left, - avatarWidth: avatarRect.width, - iconLeft, - iconTop - }); - } else if (panelPosition === 'left') { - // Main panel is on left, so thought bubble goes to RIGHT side - const chatContainer = $('#chat')[0]; - const chatRect = chatContainer ? chatContainer.getBoundingClientRect() : { right: window.innerWidth }; - - // Calculate how much space is available to the right of the chat - const spaceRight = window.innerWidth - chatRect.right; - - // If there's enough space, position normally; otherwise, adjust - if (spaceRight >= panelWidth + panelMargin * 2) { - left = chatRect.right + panelMargin; + // Update horizontal position based on panel position + // If panel is on right, thoughts on left (default) + // If panel is on left, thoughts on right (mirrored) + if (isRightPanel) { + $thoughtPanel.css({ + left: `${margin}px`, + right: 'auto' + }).removeClass('rpg-thought-panel-right').addClass('rpg-thought-panel-left'); } else { - // Not enough space on the right, position closer to chat or slightly overlapping - left = Math.max(chatRect.right - panelWidth - panelMargin, window.innerWidth - panelWidth - 10); + // Panel on left, so thoughts on right + $thoughtPanel.css({ + left: 'auto', + right: `${margin}px` + }).removeClass('rpg-thought-panel-left').addClass('rpg-thought-panel-right'); } - useRightPosition = false; - iconLeft = chatRect.right + 10; - $thoughtPanel.addClass('rpg-thought-panel-right'); - $thoughtIcon.addClass('rpg-thought-icon-right'); - - // Circles use default CSS positioning - } else { - // Main panel is on right, so thought bubble goes on left (near avatar) - const chatContainer = $('#chat')[0]; - const chatRect = chatContainer ? chatContainer.getBoundingClientRect() : { left: 0 }; - - // Calculate how much space is available to the left of the chat - const spaceLeft = chatRect.left; - - // If there's enough space, position normally; otherwise, adjust - if (spaceLeft >= panelWidth + panelMargin * 2) { - left = avatarRect.left - panelWidth - panelMargin; + // Only update icon position if in desktop mode or if no saved position in mobile + if (window.innerWidth > 1000) { + // Desktop: update icon to match panel position (though it's hidden) + if (isRightPanel) { + $thoughtIcon.css({ + left: `${margin}px`, + right: 'auto' + }); + } else { + $thoughtIcon.css({ + left: 'auto', + right: `${margin}px` + }); + } } else { - // Not enough space on the left, position it within visible area - left = Math.max(10, avatarRect.left - panelWidth - panelMargin); + // Mobile: only set default if no saved position exists + const iconPos = extensionSettings.thoughtIconPosition; + if (!iconPos || (!iconPos.top && !iconPos.left)) { + // Position icon in the center of the viewport + const defaultTop = window.innerHeight / 2; + const defaultLeft = window.innerWidth / 2; + $thoughtIcon.css({ + 'top': `${defaultTop}px`, + 'left': `${defaultLeft}px` + }); + } } - iconLeft = Math.max(10, avatarRect.left - 40); - $thoughtPanel.addClass('rpg-thought-panel-left'); - $thoughtIcon.addClass('rpg-thought-icon-left'); + // Update width based on available space + if (sheld) { + const sheldRect = sheld.getBoundingClientRect(); + let availableWidth; + if (isRightPanel) { + availableWidth = sheldRect.left - (margin * 2); + } else { + // Panel on left, calculate space on right + availableWidth = window.innerWidth - sheldRect.right - (margin * 2); + } + const maxWidth = Math.min(350, Math.max(200, availableWidth)); + $thoughtPanel.css('max-width', `${maxWidth}px`); + } else { + $thoughtPanel.css('max-width', '350px'); + } + }; - // Circles use default CSS positioning - } - - if (useRightPosition) { + // Set initial position and width (will be updated by updateBubblePosition) + const isRightPanel = extensionSettings.panelPosition === 'right'; + if (isRightPanel) { $thoughtPanel.css({ - top: `${top}px`, - right: `${right}px`, - left: 'auto' // Clear left positioning + left: `${margin}px`, + right: 'auto' + }).addClass('rpg-thought-panel-left'); + + $thoughtIcon.css({ + left: `${margin}px`, + right: 'auto' }); } else { $thoughtPanel.css({ - top: `${top}px`, - left: `${left}px`, - right: 'auto' // Clear right positioning + left: 'auto', + right: `${margin}px` + }).addClass('rpg-thought-panel-right'); + + $thoughtIcon.css({ + left: 'auto', + right: `${margin}px` }); } - $thoughtIcon.css({ - top: `${iconTop}px`, - left: `${iconLeft}px`, - right: 'auto' // Clear any right positioning + updateBubblePosition(); + + // Update on window resize and when ST's layout changes + $(window).on('resize.rpgThoughtBubble', updateBubblePosition); + + // Desktop: always show panel, hide icon + // Mobile: show icon, hide panel initially + const isMobileView = window.innerWidth <= 1000; + + if (isMobileView) { + $thoughtPanel.hide(); + // Remove force-hide class to let CSS media query show icon + $thoughtIcon.removeClass('rpg-force-hide'); + + // Load saved icon position in mobile, or default to center of viewport + if (extensionSettings.thoughtIconPosition && extensionSettings.thoughtIconPosition.top && extensionSettings.thoughtIconPosition.left) { + const pos = extensionSettings.thoughtIconPosition; + $thoughtIcon.css({ + top: pos.top, + left: pos.left, + transform: 'none', + right: 'auto', + bottom: 'auto' + }); + } else { + // Default position: center of viewport + $thoughtIcon.css({ + top: '50%', + left: '50%', + transform: 'translate(-50%, -50%)', + right: 'auto', + bottom: 'auto' + }); + } + } else { + // Desktop: show panel, hide icon with class + $thoughtPanel.css('display', 'block'); + $thoughtIcon.addClass('rpg-force-hide'); + } + + // Handle viewport changes between mobile and desktop + let wasMobileView = window.innerWidth <= 1000; + $(window).on('resize.thoughtIconDrag', () => { + const isMobileNow = window.innerWidth <= 1000; + + if (!wasMobileView && isMobileNow) { + // Switched to mobile - apply saved position if exists + const $currentIcon = $('#rpg-thought-icon'); + if (extensionSettings.thoughtIconPosition) { + const pos = extensionSettings.thoughtIconPosition; + if (pos.top) $currentIcon.css('top', pos.top); + if (pos.left) $currentIcon.css('left', pos.left); + } + } + + // Constrain icon if in mobile view + if (isMobileNow) { + setTimeout(() => { + const $currentIcon = $('#rpg-thought-icon'); + if ($currentIcon.length) { + constrainIconToViewport($currentIcon); + } + }, 10); + } + + wasMobileView = isMobileNow; }); - // Check if always show bubble is enabled - if (extensionSettings.alwaysShowThoughtBubble) { - // Always show panel expanded, hide both close button and icon - $thoughtPanel.show(); - $thoughtPanel.find('.rpg-thought-close').hide(); - $thoughtIcon.hide(); - } else { - // Initially hide the panel and show the icon - $thoughtPanel.hide(); - $thoughtIcon.show(); + // Close button functionality (mobile only) - support both click and touch + $thoughtPanel.find('.rpg-thought-close').on('click touchend', function(e) { + e.preventDefault(); + e.stopPropagation(); + // Only hide/show in mobile view + if (window.innerWidth <= 1000) { + $thoughtPanel.fadeOut(200, function() { + // Make sure icon is visible and clean state when panel closes (use selector, not variable) + const $icon = $('#rpg-thought-icon'); + $icon.removeClass('rpg-hidden dragging'); + $icon.data('just-dragged', false); + }); + } + }); - // Close button functionality - only when always show is disabled - $thoughtPanel.find('.rpg-thought-close').on('click', function(e) { - e.stopPropagation(); - $thoughtPanel.fadeOut(200); - $thoughtIcon.fadeIn(200); - }); + // Icon click/tap to show panel (mobile only) + const handleThoughtIconTap = function(e) { + // Skip if we just finished dragging + if ($thoughtIcon.data('just-dragged')) { + return; + } + e.preventDefault(); + e.stopPropagation(); - // Icon click to show panel - only when always show is disabled - $thoughtIcon.on('click', function(e) { - e.stopPropagation(); - $thoughtIcon.fadeOut(200); - $thoughtPanel.fadeIn(200); - }); - } + // In mobile view, position panel below ST's top bar and fit full screen + if (window.innerWidth <= 1000) { + const topBar = $('#top-settings-holder'); + const topBarHeight = topBar.length ? topBar.outerHeight() : 60; + const topPosition = topBarHeight + 10; // 10px margin below top bar - // console.log('[RPG Companion] Thought panel created at:', { top, left }); + $thoughtPanel.css({ + top: topPosition + 'px', + display: 'none' // Keep hidden while setting position + }); + } + + $thoughtIcon.addClass('rpg-hidden'); + $thoughtPanel.fadeIn(200); + }; + + // Support both click and touch events for mobile + $thoughtIcon.on('click touchend', handleThoughtIconTap); // Add event handlers for editable thoughts in the bubble $thoughtPanel.find('.rpg-editable').on('blur', function() { @@ -1276,95 +1637,66 @@ export function createThoughtPanel($message, thoughtsArray) { updateCharacterField(character, field, value); }); + // Add event listener for section lock icon clicks (support both click and touch) + $thoughtPanel.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(); + }); + // RAF throttling for smooth position updates let positionUpdateRaf = null; - // Update position on scroll with RAF throttling + // Update position on scroll with RAF throttling - DISABLED for fixed top-left positioning const updatePanelPosition = () => { + // Bubble is now fixed at top-left, no need to update position on scroll + // Just check visibility if (!$message.is(':visible')) { $thoughtPanel.hide(); $thoughtIcon.hide(); - return; - } - - // Cancel any pending RAF - if (positionUpdateRaf) { - cancelAnimationFrame(positionUpdateRaf); - } - - // Schedule update on next frame - positionUpdateRaf = requestAnimationFrame(() => { - const newAvatarRect = $avatar[0].getBoundingClientRect(); - const newTop = newAvatarRect.top; // Align with avatar top - const newIconTop = newAvatarRect.top; - let newLeft, newIconLeft; - - const isMobileNow = window.innerWidth <= 1000; - - if (isMobileNow) { - newLeft = window.innerWidth / 2 - panelWidth / 2; - newIconLeft = newAvatarRect.left + (newAvatarRect.width / 2) - 18; - } else if (panelPosition === 'left') { - // Position at chat's right edge, extending right - const chatContainer = $('#chat')[0]; - const chatRect = chatContainer ? chatContainer.getBoundingClientRect() : { right: window.innerWidth }; - const spaceRight = window.innerWidth - chatRect.right; - - if (spaceRight >= panelWidth + panelMargin * 2) { - newLeft = chatRect.right + panelMargin; - } else { - newLeft = Math.max(chatRect.right - panelWidth - panelMargin, window.innerWidth - panelWidth - 10); - } - newIconLeft = chatRect.right + 10; - } else { - // Left position relative to avatar - const chatContainer = $('#chat')[0]; - const chatRect = chatContainer ? chatContainer.getBoundingClientRect() : { left: 0 }; - const spaceLeft = chatRect.left; - - if (spaceLeft >= panelWidth + panelMargin * 2) { - newLeft = newAvatarRect.left - panelWidth - panelMargin; - } else { - newLeft = Math.max(10, newAvatarRect.left - panelWidth - panelMargin); - } - newIconLeft = Math.max(10, newAvatarRect.left - 40); - } - - $thoughtPanel.css({ - top: `${newTop}px`, - left: `${newLeft}px`, - right: 'auto' - }); - - $thoughtIcon.css({ - top: `${newIconTop}px`, - left: `${newIconLeft}px`, - right: 'auto' - }); - + } else { if ($thoughtPanel.is(':visible')) { $thoughtPanel.show(); } if ($thoughtIcon.is(':visible')) { $thoughtIcon.show(); } - - positionUpdateRaf = null; - }); + } }; - // Update position on scroll and resize + // Update visibility on scroll (but not position) $('#chat').on('scroll.thoughtPanel', updatePanelPosition); - $(window).on('resize.thoughtPanel', updatePanelPosition); - // Remove panel when clicking outside - only if always show is disabled - if (!extensionSettings.alwaysShowThoughtBubble) { - $(document).on('click.thoughtPanel', function(e) { + // Don't listen to window resize for position - we handle width separately + // Position stays fixed at top-left + + // Remove panel when clicking outside (mobile only) + $(document).on('click.thoughtPanel', function(e) { + // Only hide on click outside in mobile view + if (window.innerWidth <= 1000) { if (!$(e.target).closest('#rpg-thought-panel, #rpg-thought-icon').length) { - // Hide the panel and show the icon instead of removing - $thoughtPanel.fadeOut(200); - $thoughtIcon.fadeIn(200); + // Hide the panel and show the icon instead of removing (use selectors, not variables) + $('#rpg-thought-panel').fadeOut(200); + $('#rpg-thought-icon').removeClass('rpg-hidden').fadeIn(200); } - }); - } + } + }); } diff --git a/src/systems/rendering/userStats.js b/src/systems/rendering/userStats.js index 14a3e63..4d4fc73 100644 --- a/src/systems/rendering/userStats.js +++ b/src/systems/rendering/userStats.js @@ -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('
No statuses generated yet
'); + 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 = '
'; + // 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 = '
'; + html += '
'; // User info row + const showLevel = extensionSettings.trackerConfig?.userStats?.showLevel !== false; html += ` `; // Dynamic stats grid - only show enabled stats + const showLockIcons = extensionSettings.showLockIcons ?? true; + if (showLockIcons) { + html += `${lockIcon}`; + } html += '
'; 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 += '
'; + if (showLockIcons) { + html += `${moodLockIcon}`; + } if (config.statusSection.showMoodEmoji) { html += `
${stats.mood}
`; @@ -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 += `
${conditionsValue}
`; } @@ -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 += ` +
`; + if (showLockIcons) { + html += ` + ${skillsLockIcon}`; + } html += ` -
${config.skillsSection.label}:
${skillsValue}
@@ -225,7 +394,13 @@ export function renderUserStats() { html += '
'; // 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,8 @@ export function renderUserStats() { const value = $(this).text().trim(); extensionSettings.userStats.conditions = value || 'None'; - // 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(); @@ -298,12 +458,8 @@ export function renderUserStats() { const value = $(this).text().trim(); extensionSettings.userStats.skills = value || 'None'; - // Rebuild userStats text - const statsText = buildUserStatsText(); - - // Update BOTH lastGeneratedData AND committedTrackerData - lastGeneratedData.userStats = statsText; - committedTrackerData.userStats = statsText; + // Update userStats data (maintains JSON or text format) + updateUserStatsData(); saveSettings(); saveChatData(); @@ -359,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(); + }); } diff --git a/src/systems/ui/debug.js b/src/systems/ui/debug.js deleted file mode 100644 index c6030b0..0000000 --- a/src/systems/ui/debug.js +++ /dev/null @@ -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 = ` -
-
-

🔍 Debug Logs

-
- - - -
-
-
-
- `; - - // 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 = $('
'); - $('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('
No logs yet. Logs will appear when parser runs.
'); - return; - } - - // Build logs HTML - const logsHtml = logs.map(log => { - let html = `
`; - html += `[${log.timestamp}] `; - html += `${escapeHtml(log.message)}`; - if (log.data) { - html += `
${escapeHtml(log.data)}
`; - } - html += `
`; - 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(); - } -} diff --git a/src/systems/ui/desktop.js b/src/systems/ui/desktop.js index cca40f7..40b3c20 100644 --- a/src/systems/ui/desktop.js +++ b/src/systems/ui/desktop.js @@ -79,7 +79,11 @@ export function setupDesktopTabs() { } if ($infoBox.length > 0) { $statusTab.append($infoBox.detach()); - if (extensionSettings.showInfoBox) $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()); @@ -170,7 +174,10 @@ export function removeDesktopTabs() { // Show/hide sections based on settings (respect visibility settings) if (extensionSettings.showUserStats) $userStats.show(); - if (extensionSettings.showInfoBox) $infoBox.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(); diff --git a/src/systems/ui/layout.js b/src/systems/ui/layout.js index 2b7ad0a..79fc813 100644 --- a/src/systems/ui/layout.js +++ b/src/systems/ui/layout.js @@ -13,7 +13,9 @@ import { $questsContainer, $musicPlayerContainer, setInventoryContainer, - setQuestsContainer + setQuestsContainer, + lastGeneratedData, + committedTrackerData } from '../../core/state.js'; import { i18n } from '../../core/i18n.js'; import { setupMobileTabs, removeMobileTabs } from './mobile.js'; @@ -28,12 +30,17 @@ export function togglePlotButtons() { return; } - // Show/hide plot progression buttons based on enablePlotButtons setting - if (extensionSettings.enablePlotButtons) { + // Show/hide randomized plot button based on enableRandomizedPlot setting + if (extensionSettings.enableRandomizedPlot) { $('#rpg-plot-random').show(); - $('#rpg-plot-natural').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(); } @@ -45,7 +52,7 @@ export function togglePlotButtons() { } // Show the container if at least one button is visible - const shouldShowContainer = extensionSettings.enablePlotButtons || extensionSettings.encounterSettings?.enabled; + const shouldShowContainer = extensionSettings.enableRandomizedPlot || extensionSettings.enableNaturalPlot || extensionSettings.encounterSettings?.enabled; if (shouldShowContainer) { $('#rpg-plot-buttons').show(); } else { @@ -81,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'); + const isLeftPanel = $panel.hasClass('rpg-position-left'); + console.log('[RPG Mobile] updateCollapseToggleIcon:', { isMobile: true, isOpen, - settingIcon: isOpen ? 'chevron-left' : 'chevron-right' + isLeftPanel, + settingIcon: isOpen ? (isLeftPanel ? 'chevron-left' : 'chevron-right') : (isLeftPanel ? 'chevron-right' : 'chevron-left') }); - 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'); + + 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 @@ -237,14 +259,11 @@ export function updatePanelVisibility() { togglePlotButtons(); // Update plot button visibility $('#rpg-mobile-toggle').show(); // Show mobile FAB toggle $('#rpg-collapse-toggle').show(); // Show collapse toggle - // Debug toggle visibility is controlled by debugMode setting in debug.js } 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 - $('#rpg-debug-toggle').hide(); // Hide debug toggle button when extension disabled - $('#rpg-debug-panel').remove(); // Remove debug panel when extension disabled } } @@ -265,7 +284,13 @@ export function updateSectionVisibility() { } if (extensionSettings.showInfoBox) { - $infoBoxContainer.show(); + // Only show if there's data to display + const infoBoxData = lastGeneratedData.infoBox || committedTrackerData.infoBox; + if (infoBoxData) { + $infoBoxContainer.show(); + } else { + $infoBoxContainer.hide(); + } } else { $infoBoxContainer.hide(); } @@ -383,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(); } @@ -405,24 +433,21 @@ export function updateGenerationModeUI() { $('#rpg-manual-update').hide(); $('#rpg-external-api-settings').slideUp(200); $('#rpg-separate-mode-settings').slideUp(200); - // Disable auto-update toggle (not applicable in together mode) - $('#rpg-toggle-auto-update').prop('disabled', true); - $('#rpg-auto-update-container').css('opacity', '0.5'); + // 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); - // Enable auto-update toggle (only works in separate mode) - $('#rpg-toggle-auto-update').prop('disabled', false); - $('#rpg-auto-update-container').css('opacity', '1'); + // Show auto-update toggle + $('#rpg-auto-update-container').slideDown(200); } else if (extensionSettings.generationMode === 'external') { // In "external" mode, manual update button is visible AND external settings are shown $('#rpg-manual-update').show(); $('#rpg-external-api-settings').slideDown(200); $('#rpg-separate-mode-settings').slideUp(200); - // Disable auto-update toggle (not applicable in external mode) - $('#rpg-toggle-auto-update').prop('disabled', true); - $('#rpg-auto-update-container').css('opacity', '0.5'); + // Show auto-update toggle for external mode too + $('#rpg-auto-update-container').slideDown(200); } } diff --git a/src/systems/ui/mobile.js b/src/systems/ui/mobile.js index b80b0fc..805298d 100644 --- a/src/systems/ui/mobile.js +++ b/src/systems/ui/mobile.js @@ -375,8 +375,12 @@ export function setupMobileToggle() { // 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'); @@ -424,7 +428,8 @@ export function setupMobileToggle() { // Hide mobile toggle button on desktop $mobileToggle.hide(); - // Restore desktop positioning class + // 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); @@ -561,6 +566,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 @@ -624,7 +637,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()); @@ -714,7 +729,10 @@ export function removeMobileTabs() { // Show/hide sections based on settings (respect visibility settings) if (extensionSettings.showUserStats) $userStats.show(); - if (extensionSettings.showInfoBox) $infoBox.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(); diff --git a/src/systems/ui/modals.js b/src/systems/ui/modals.js index ced6514..d6297e0 100644 --- a/src/systems/ui/modals.js +++ b/src/systems/ui/modals.js @@ -10,13 +10,17 @@ 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, @@ -351,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]; @@ -380,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, @@ -390,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 @@ -406,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; @@ -508,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.0'; + 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 }); +} diff --git a/src/systems/ui/promptsEditor.js b/src/systems/ui/promptsEditor.js index e3a2956..6cbb407 100644 --- a/src/systems/ui/promptsEditor.js +++ b/src/systems/ui/promptsEditor.js @@ -4,7 +4,7 @@ */ import { extensionSettings } from '../../core/state.js'; import { saveSettings } from '../../core/persistence.js'; -import { DEFAULT_HTML_PROMPT, DEFAULT_SPOTIFY_PROMPT } from '../generation/promptBuilder.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 @@ -12,28 +12,22 @@ 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, but 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 (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 high 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. Do NOT keep the brackets or placeholder text in your response. 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 bracketed placeholders (e.g., [Location], [Mood Emoji]) MUST be replaced with actual content without the square brackets.', + 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?"' }; @@ -98,7 +92,9 @@ 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 || '', @@ -109,7 +105,9 @@ function openPromptsEditor() { // 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); @@ -144,7 +142,9 @@ function closePromptsEditor() { */ 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(); @@ -168,9 +168,15 @@ function restorePromptToDefault(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; @@ -199,7 +205,9 @@ function restorePromptToDefault(promptType) { */ 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); @@ -209,7 +217,9 @@ function restoreAllToDefaults() { // Clear all custom prompts extensionSettings.customHtmlPrompt = ''; + extensionSettings.customDialogueColoringPrompt = ''; extensionSettings.customSpotifyPrompt = ''; + extensionSettings.customNarratorPrompt = ''; extensionSettings.customPlotRandomPrompt = ''; extensionSettings.customPlotNaturalPrompt = ''; extensionSettings.avatarLLMCustomInstruction = ''; diff --git a/src/systems/ui/theme.js b/src/systems/ui/theme.js index b63cce0..ef7a8ee 100644 --- a/src/systems/ui/theme.js +++ b/src/systems/ui/theme.js @@ -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); + } } /** @@ -82,21 +137,29 @@ export function toggleAnimations() { 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 $snowflakesToggle = $('#rpg-snowflakes-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); - $snowflakesToggle.toggle(extensionSettings.showSnowflakesToggle); + $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.showSnowflakesToggle || - extensionSettings.showDynamicWeatherToggle; + extensionSettings.showDynamicWeatherToggle || + extensionSettings.showNarratorMode || + extensionSettings.showAutoAvatars; $featuresRow.toggle(anyVisible); } diff --git a/src/systems/ui/trackerEditor.js b/src/systems/ui/trackerEditor.js index bfa5c5a..fa20b66 100644 --- a/src/systems/ui/trackerEditor.js +++ b/src/systems/ui/trackerEditor.js @@ -348,6 +348,13 @@ function renderUserStatsTab() { html += ``; html += '
'; + // Show/hide level toggle + const showLevel = config.showLevel !== undefined ? config.showLevel : true; + html += '
'; + html += ``; + html += ``; + html += '
'; + // Always send attributes toggle const alwaysSendAttributes = config.alwaysSendAttributes !== undefined ? config.alwaysSendAttributes : false; html += '
'; @@ -510,6 +517,11 @@ 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'); diff --git a/src/systems/ui/weatherEffects.js b/src/systems/ui/weatherEffects.js index 7181396..5249b0b 100644 --- a/src/systems/ui/weatherEffects.js +++ b/src/systems/ui/weatherEffects.js @@ -51,7 +51,18 @@ function parseWeatherType(weatherText) { function getCurrentWeather() { const infoBoxData = lastGeneratedData.infoBox || committedTrackerData.infoBox || ''; - // Parse the Info Box data to find Weather field + // 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(); diff --git a/src/utils/jsonMigration.js b/src/utils/jsonMigration.js new file mode 100644 index 0000000..90cbb9c --- /dev/null +++ b/src/utils/jsonMigration.js @@ -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} + */ +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'); +} diff --git a/src/utils/jsonRepair.js b/src/utils/jsonRepair.js new file mode 100644 index 0000000..e5b5ff0 --- /dev/null +++ b/src/utils/jsonRepair.js @@ -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(/[\s\S]*?<\/think>/gi, ''); + cleaned = cleaned.replace(/[\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; +} diff --git a/src/utils/migration.js b/src/utils/migration.js index ca17e00..a79ebd7 100644 --- a/src/utils/migration.js +++ b/src/utils/migration.js @@ -28,7 +28,24 @@ 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')) { @@ -49,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 { @@ -59,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(); diff --git a/style.css b/style.css index 57a7e73..3e8f703 100644 --- a/style.css +++ b/style.css @@ -14,7 +14,8 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* CSS Variables for Theming - Default uses SillyTavern's variables */ .rpg-panel, #rpg-thought-panel, -#rpg-thought-icon { +#rpg-thought-icon, +.rpg-mobile-toggle { --rpg-bg: var(--SmartThemeBlurTintColor, rgba(26, 26, 46, 0.9)); --rpg-accent: var(--black30a, rgba(22, 33, 62, 0.9)); --rpg-text: var(--SmartThemeBodyColor, #eaeaea); @@ -192,19 +193,39 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } } -@media (max-width: 480px) { - .rpg-panel.rpg-position-right, - .rpg-panel.rpg-position-left { +@media (max-width: 768px) { + /* Left position on mobile/tablet */ + body.rpg-panel-position-left #rpg-companion-panel.rpg-panel, + #rpg-companion-panel.rpg-panel.rpg-position-left { left: 0 !important; - right: 0 !important; - width: 100%; - height: 50vh; - top: auto; - bottom: 0; + right: auto !important; + width: 85% !important; + max-width: 320px !important; + height: 100vh !important; + top: 0 !important; + bottom: 0 !important; } - .rpg-panel.rpg-position-top { - max-height: 40vh; + /* Right position on mobile/tablet */ + body.rpg-panel-position-right #rpg-companion-panel.rpg-panel, + #rpg-companion-panel.rpg-panel.rpg-position-right { + left: auto !important; + right: 0 !important; + width: 85% !important; + max-width: 320px !important; + height: 100vh !important; + top: 0 !important; + bottom: 0 !important; + } + + /* Top position on mobile */ + #rpg-companion-panel.rpg-panel.rpg-position-top { + left: 0 !important; + right: 0 !important; + width: 100% !important; + max-height: 40vh !important; + top: 0 !important; + bottom: auto !important; } } @@ -564,6 +585,14 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* ============================================ USER STATS SECTION ============================================ */ +#rpg-user-stats { + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + overflow: auto; +} + .rpg-stats-section { text-align: center; display: flex; @@ -681,6 +710,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { flex: 1; min-height: 0; overflow: hidden; + position: relative; /* For absolute positioning of lock icon */ } /* Stats Left - Portrait, Bars and mood */ @@ -800,6 +830,8 @@ body:has(.rpg-panel.rpg-position-left) #sheld { flex-direction: column; gap: clamp(3px, 0.5vh, 6px); flex: 1 1 auto; + position: relative; /* For lock icon positioning */ + overflow: visible; } .rpg-stats-grid::-webkit-scrollbar { @@ -838,26 +870,104 @@ body:has(.rpg-panel.rpg-position-left) #sheld { background: var(--rpg-text); } +/* Section-level lock icon styling - appears on hover in top-right corner */ +.rpg-section-lock-icon { + position: absolute; + top: 8px; + right: 8px; + font-size: 1rem; + cursor: pointer; + opacity: 0; + transition: opacity 0.2s ease, transform 0.1s ease; + user-select: none; + z-index: 10; + pointer-events: none; +} + +/* Show lock icon on hover or when section is locked */ +.rpg-stats-content:hover .rpg-section-lock-icon, +.rpg-dashboard-widget:hover .rpg-section-lock-icon, +.rpg-character-card:hover .rpg-section-lock-icon, +.rpg-item-card:hover .rpg-section-lock-icon, +.rpg-item-row:hover .rpg-section-lock-icon, +.rpg-quest-item:hover .rpg-section-lock-icon, +.rpg-section-lock-icon.locked { + opacity: 0.7; + pointer-events: auto; +} + +.rpg-section-lock-icon:hover { + opacity: 1; + transform: scale(1.15); +} + +/* Mobile: always show lock icons since there's no hover */ +@media (max-width: 1000px) { + .rpg-section-lock-icon { + opacity: 0.6 !important; + pointer-events: auto !important; + } + + .rpg-section-lock-icon.locked { + opacity: 0.9 !important; + } +} + +/* Make containers relative for absolute positioning of lock icon */ +.rpg-stats-content, +.rpg-dashboard-widget, +.rpg-character-content, +.rpg-item-card, +.rpg-item-row, +.rpg-quest-item { + position: relative; +} + .rpg-stat-row { display: flex; align-items: center; gap: 0.25em; flex: 1 1 0; + min-width: fit-content; + max-width: 100%; + width: 100%; min-height: clamp(12px, 1.8vh, 16px); + transition: background-color 0.2s ease; + overflow: visible; + box-sizing: border-box; +} + +/* Old per-field lock styling - remove */ +.rpg-lock-icon { + display: none; +} + +.rpg-stat-row.rpg-locked { + background-color: transparent; + border-left: none; + padding-left: 0; } .rpg-stat-label { - min-width: 4.062rem; + flex: 0 0 auto; + min-width: 3rem; + max-width: 30%; font-size: clamp(0.625rem, 0.6vw, 0.75rem); font-weight: 600; text-align: left; color: var(--rpg-text); text-transform: uppercase; letter-spacing: 0.019em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .rpg-stat-bar { flex: 1; + min-width: 3.75rem; + max-width: 100%; + width: 100%; height: clamp(9px, 1.3vh, 11px); min-height: 9px; position: relative; @@ -865,6 +975,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { overflow: hidden; box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5); border: 1px solid rgba(255, 255, 255, 0.1); + box-sizing: border-box; } .rpg-stat-fill { @@ -886,7 +997,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } /* Compact layout for high zoom / small viewports */ -@media (max-height: 750px), (max-width: 500px) { +@media (max-height: 750px), (max-width: 1500px) { .rpg-stat-row { position: relative; min-height: clamp(16px, 2.5vh, 20px); @@ -899,14 +1010,19 @@ body:has(.rpg-panel.rpg-position-left) #sheld { transform: translateY(-50%); z-index: 2; min-width: auto; - font-size: clamp(0.75rem, 0.7vw, 0.875rem); + max-width: calc(100% - 3rem); + font-size: min(0.7vw, 0.875rem); text-shadow: 0 1px 3px rgba(0, 0, 0, 0.9); + overflow: hidden; + white-space: nowrap; } .rpg-stat-bar { - width: 100%; + width: 100% !important; + max-width: 100% !important; height: 100%; min-height: clamp(16px, 2.5vh, 20px); + box-sizing: border-box; } .rpg-stat-value { @@ -918,6 +1034,22 @@ body:has(.rpg-panel.rpg-position-left) #sheld { min-width: auto; font-size: clamp(0.75rem, 0.7vw, 0.875rem); } + + .rpg-mood { + font-size: clamp(0.625rem, 1vw, 0.75rem); + flex-shrink: 1; + min-width: 0; + } + + .rpg-mood-emoji { + font-size: clamp(0.875rem, 2vw, 1.125rem); + } + + .rpg-mood-conditions { + font-size: clamp(0.625rem, 1vw, 0.75rem); + word-wrap: break-word; + overflow-wrap: break-word; + } } .rpg-mood { @@ -930,6 +1062,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { border-radius: 0.25em; border: 1px solid var(--rpg-border); flex-shrink: 0; + position: relative; /* For lock icon positioning */ } .rpg-mood-emoji { @@ -944,6 +1077,9 @@ body:has(.rpg-panel.rpg-position-left) #sheld { line-height: 1.2; color: var(--rpg-text); font-weight: 600; + word-wrap: break-word; + overflow-wrap: break-word; + hyphens: auto; } /* Skills Section */ @@ -958,6 +1094,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { border: 1px solid var(--rpg-border); flex-shrink: 0; margin-top: 0.375em; + position: relative; /* For lock icon positioning */ } .rpg-skills-label { @@ -972,6 +1109,9 @@ body:has(.rpg-panel.rpg-position-left) #sheld { line-height: 1.2; color: var(--rpg-text); font-weight: 600; + word-wrap: break-word; + overflow-wrap: break-word; + hyphens: auto; } /* Classic RPG Stats - Will match height of stats box automatically */ @@ -1114,7 +1254,8 @@ body:has(.rpg-panel.rpg-position-left) #sheld { gap: 0.25em; align-items: stretch; width: 100%; - overflow: hidden; + overflow-y: auto; + overflow-x: hidden; } /* Scrollable content wrapper inside info section */ @@ -1202,28 +1343,44 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Location widget - flexible height */ .rpg-location-widget { height: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.125em; + padding: 0.25em; + overflow: hidden; } /* Calendar Widget */ .rpg-calendar-widget { padding: 0.188em; + container-type: size; + height: 100%; + overflow: hidden; } .rpg-calendar-top { background: var(--rpg-highlight); color: var(--rpg-bg); - font-size: clamp(0.563rem, 0.55vw, 0.625rem); + font-size: clamp(0.5rem, 3.5cqh, 0.625rem); font-weight: bold; padding: 0.125em 0.375em; border-radius: 3px 3px 0 0; width: 100%; text-align: center; + word-wrap: break-word; + overflow-wrap: break-word; + white-space: normal; + max-width: 100%; + line-height: 1.2; + overflow: hidden; } .rpg-calendar-day { background: rgba(255, 255, 255, 0.1); color: var(--rpg-text); - font-size: clamp(0.625rem, 0.7vw, 0.875rem); + font-size: clamp(0.625rem, 5cqh, 0.875rem); font-weight: bold; padding: 0.25em; width: 100%; @@ -1234,17 +1391,28 @@ body:has(.rpg-panel.rpg-position-left) #sheld { display: flex; align-items: center; justify-content: center; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + word-wrap: break-word; + overflow-wrap: break-word; + white-space: normal; + max-width: 100%; + line-height: 1.2; min-width: 0; + overflow: hidden; } .rpg-calendar-year { - font-size: clamp(0.563rem, 0.55vw, 0.625rem); + font-size: clamp(0.5rem, 3.5cqh, 0.625rem); color: var(--rpg-text); opacity: 0.7; margin-top: 0.062em; + width: 100%; + text-align: center; + word-wrap: break-word; + overflow-wrap: break-word; + white-space: normal; + max-width: 100%; + line-height: 1.2; + overflow: hidden; } /* Weather Widget */ @@ -1255,6 +1423,11 @@ body:has(.rpg-panel.rpg-position-left) #sheld { justify-content: center; gap: 0.188em; padding: 0.25em; + max-width: 100%; + height: 100%; + overflow: hidden; + box-sizing: border-box; + container-type: size; } /* Weather Widget Icon */ @@ -1266,19 +1439,25 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-weather-forecast { - font-size: clamp(0.625rem, 0.6vw, 0.75rem); + font-size: clamp(0.5rem, 4cqh, 0.75rem); text-align: center; margin: 0; font-weight: 600; text-transform: uppercase; letter-spacing: 0.013em; opacity: 0.85; - line-height: 1.2; + line-height: 1.1; word-wrap: break-word; overflow-wrap: break-word; max-width: 100%; + width: 100%; white-space: normal; flex-shrink: 1; + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + hyphens: auto; } .rpg-weather-forecast.rpg-editable { @@ -1396,14 +1575,17 @@ body:has(.rpg-panel.rpg-position-left) #sheld { font-size: clamp(0.625rem, 0.6vw, 0.75rem); font-weight: bold; color: var(--rpg-text); + text-align: center; + margin-top: 0.25em; } /* Location Widget - Map */ .rpg-map-bg { width: 100%; - height: 1.875rem; + height: auto; + max-height: 60%; + padding: 0.5em 0; margin: 0; - margin-bottom: 0 !important; background: linear-gradient(45deg, rgba(255,255,255,0.05) 25%, transparent 25%), linear-gradient(-45deg, rgba(255,255,255,0.05) 25%, transparent 25%), @@ -1418,15 +1600,14 @@ body:has(.rpg-panel.rpg-position-left) #sheld { align-items: center; justify-content: center; position: relative; - overflow: hidden; - flex-shrink: 0; - margin-bottom: 0.188em; + flex: 0 0 auto; } .rpg-map-marker { - font-size: clamp(0.875rem, 1vw, 1rem); + font-size: clamp(0.875rem, 2.5vw, 1.25rem); filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8)); animation: markerPulse 2s ease-in-out infinite; + line-height: 1; } @keyframes markerPulse { @@ -1440,11 +1621,17 @@ body:has(.rpg-panel.rpg-position-left) #sheld { color: var(--rpg-text); text-align: center; line-height: 1.2; - padding: 0.125em 0.25em; + padding: 0; margin: 0; word-wrap: break-word; overflow-wrap: break-word; hyphens: auto; + flex: 1 1 auto; + min-height: 0; + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; } /* Row 3: Recent Events */ @@ -2408,6 +2595,25 @@ body:has(.rpg-panel.rpg-position-left) #sheld { background: var(--rpg-bg); cursor: pointer; transition: all 0.3s ease; + /* Ensure color picker works on all browsers */ + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; +} + +/* Remove padding for better color swatch display */ +.rpg-setting-row input[type="color"]::-webkit-color-swatch-wrapper { + padding: 0; +} + +.rpg-setting-row input[type="color"]::-webkit-color-swatch { + border: none; + border-radius: 0.25em; +} + +.rpg-setting-row input[type="color"]::-moz-color-swatch { + border: none; + border-radius: 0.25em; } .rpg-setting-row input[type="color"]:hover { @@ -2439,6 +2645,136 @@ body:has(.rpg-panel.rpg-position-left) #sheld { transition: all 0.3s ease; } +.checkbox_label input[type="checkbox"] { + accent-color: #666 !important; +} + +.checkbox_label input[type="checkbox"]:checked { + background-color: #666 !important; +} + +.rpg-panel[data-theme="sci-fi"] .checkbox_label input[type="checkbox"], +.rpg-settings-popup[data-theme="sci-fi"] .checkbox_label input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="sci-fi"] .checkbox_label input[type="checkbox"]:checked, +.rpg-settings-popup[data-theme="sci-fi"] .checkbox_label input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="fantasy"] .checkbox_label input[type="checkbox"], +.rpg-settings-popup[data-theme="fantasy"] .checkbox_label input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="fantasy"] .checkbox_label input[type="checkbox"]:checked, +.rpg-settings-popup[data-theme="fantasy"] .checkbox_label input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="cyberpunk"] .checkbox_label input[type="checkbox"], +.rpg-settings-popup[data-theme="cyberpunk"] .checkbox_label input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="cyberpunk"] .checkbox_label input[type="checkbox"]:checked, +.rpg-settings-popup[data-theme="cyberpunk"] .checkbox_label input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="custom"] .checkbox_label input[type="checkbox"], +.rpg-settings-popup[data-theme="custom"] .checkbox_label input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="custom"] .checkbox_label input[type="checkbox"]:checked, +.rpg-settings-popup[data-theme="custom"] .checkbox_label input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +/* Tracker Editor checkboxes (not wrapped in checkbox_label) */ +#rpg-tracker-editor-popup input[type="checkbox"] { + accent-color: #666 !important; +} + +#rpg-tracker-editor-popup input[type="checkbox"]:checked { + background-color: #666 !important; +} + +#rpg-tracker-editor-popup[data-theme="sci-fi"] input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="sci-fi"] input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="fantasy"] input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="fantasy"] input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="cyberpunk"] input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="cyberpunk"] input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="custom"] input[type="checkbox"] { + accent-color: var(--rpg-highlight) !important; +} + +#rpg-tracker-editor-popup[data-theme="custom"] input[type="checkbox"]:checked { + background-color: var(--rpg-highlight) !important; +} + +/* Panel checkboxes (not wrapped in checkbox_label) */ +.rpg-panel input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]) { + accent-color: #666 !important; +} + +.rpg-panel input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]):checked { + background-color: #666 !important; +} + +.rpg-panel[data-theme="sci-fi"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]) { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="sci-fi"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]):checked { + background-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="fantasy"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]) { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="fantasy"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]):checked { + background-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="cyberpunk"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]) { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="cyberpunk"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]):checked { + background-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="custom"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]) { + accent-color: var(--rpg-highlight) !important; +} + +.rpg-panel[data-theme="custom"] input[type="checkbox"]:not(.checkbox_label input[type="checkbox"]):checked { + background-color: var(--rpg-highlight) !important; +} + .checkbox_label:hover { color: var(--rpg-highlight); } @@ -2530,20 +2866,15 @@ body:has(.rpg-panel.rpg-position-left) #sheld { transform: translateY(0); } -/* ============================================ - MEMORY RECOLLECTION STYLES - ============================================ */ - -/* Memory Recollection Button */ -.rpg-memory-recollection-btn { +/* Customize Prompts Button - Neutral gray style */ +.rpg-btn-customize-prompts { width: 100%; - padding: 0.75em 1em; - margin-bottom: 10px; - background: linear-gradient(135deg, var(--rpg-border, #4a7ba7) 0%, var(--rpg-highlight, #e94560) 100%); - border: 2px solid var(--rpg-border-transparent, rgba(74, 123, 167, 0.5)); + padding: 0.625em; + background: rgba(128, 128, 128, 0.2); + border: 2px solid rgba(128, 128, 128, 0.5); border-radius: 0.5em; - color: #ffffff; - font-size: 14px; + color: #aaa; + font-size: clamp(0.938rem, 1.2vw, 1.2rem); font-weight: 600; cursor: pointer; display: flex; @@ -2553,66 +2884,18 @@ body:has(.rpg-panel.rpg-position-left) #sheld { transition: all 0.3s ease; } -.rpg-memory-recollection-btn:hover { - background: linear-gradient(135deg, var(--rpg-highlight, #e94560) 0%, var(--rpg-border, #4a7ba7) 100%); - border-color: var(--rpg-border-opaque, rgba(74, 123, 167, 0.8)); - transform: translateY(-2px); - box-shadow: 0 4px 12px var(--rpg-border-transparent, rgba(74, 123, 167, 0.3)); +.rpg-btn-customize-prompts:hover { + background: rgba(128, 128, 128, 0.3); + border-color: rgba(128, 128, 128, 0.8); + color: #ccc; + transform: translateY(-0.062rem); } -.rpg-memory-recollection-btn:active { +.rpg-btn-customize-prompts:active { transform: translateY(0); } -/* Modal Overlay */ -.rpg-memory-modal-overlay { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background: rgba(0, 0, 0, 0.7); - backdrop-filter: blur(5px); - display: flex; - align-items: center; - justify-content: center; - z-index: 10000; - animation: fadeIn 0.2s ease; -} - -@keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } -} - -/* Modal Container */ -.rpg-memory-modal { - background: var(--SmartThemeBlurTintColor, #1a1a2e); - border: 2px solid var(--rpg-border, var(--SmartThemeBorderColor, #4a7ba7)); - border-radius: 12px; - max-width: 500px; - width: 90%; - box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5); - animation: modalSlideIn 0.3s ease; -} - -@keyframes modalSlideIn { - from { - transform: translateY(-20px); - opacity: 0; - } - to { - transform: translateY(0); - opacity: 1; - } -} - -/* Modal Header */ -.rpg-memory-modal-header { - padding: 1.25em; - border-bottom: 1px solid var(--rpg-border, var(--SmartThemeBorderColor, #4a7ba7)); - background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); -} +/* Memory Recollection styles removed - feature deprecated */ .rpg-memory-modal-header h3 { margin: 0; @@ -2728,77 +3011,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { box-shadow: 0 4px 12px var(--rpg-border-transparent, rgba(74, 123, 167, 0.3)); } -/* ============================================ - LOREBOOK LIMITER STYLING - ============================================ */ - -.rpg-lorebook-limiter-container { - width: 100%; - padding: 0.75em 1em; - margin-bottom: 10px; - background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%); - border: 2px solid rgba(102, 126, 234, 0.3); - border-radius: 0.5em; - display: flex; - flex-direction: column; - gap: 0.5em; -} - -.rpg-lorebook-limiter-label { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1em; - cursor: pointer; -} - -.rpg-lorebook-limiter-title { - color: rgba(102, 126, 234, 1); - font-weight: 600; - font-size: 14px; -} - -.rpg-lorebook-limiter-input { - width: 120px; - padding: 0.5em; - background: rgba(0, 0, 0, 0.3); - border: 2px solid rgba(102, 126, 234, 0.4); - border-radius: 0.3em; - color: #ffffff; - font-size: 14px; - font-weight: 600; - text-align: center; - transition: all 0.3s ease; -} - -.rpg-lorebook-limiter-input:focus { - outline: none; - border-color: rgba(102, 126, 234, 0.8); - background: rgba(0, 0, 0, 0.5); - box-shadow: 0 0 8px rgba(102, 126, 234, 0.3); -} - -.rpg-lorebook-limiter-input::placeholder { - color: rgba(255, 255, 255, 0.4); - font-weight: 400; -} - -.rpg-lorebook-limiter-hint { - color: rgba(255, 255, 255, 0.6); - font-size: 12px; - font-style: italic; -} - -.rpg-memory-close { - background: rgba(52, 152, 219, 0.2); - color: #5dade2; - border: 2px solid rgba(52, 152, 219, 0.5); -} - -.rpg-memory-close:hover { - background: rgba(52, 152, 219, 0.3); - border-color: rgba(52, 152, 219, 0.8); -} +/* Lorebook Limiter styles removed - feature deprecated */ /* ============================================ THEME VARIATIONS @@ -2816,7 +3029,8 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Apply sci-fi theme to thought panel */ #rpg-thought-panel[data-theme="sci-fi"], -#rpg-thought-icon[data-theme="sci-fi"] { +#rpg-thought-icon[data-theme="sci-fi"], +.rpg-mobile-toggle[data-theme="sci-fi"] { --rpg-bg: #0a0e27; --rpg-accent: #1a1f3a; --rpg-text: #00fff9; @@ -2863,7 +3077,8 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Apply fantasy theme to thought panel */ #rpg-thought-panel[data-theme="fantasy"], -#rpg-thought-icon[data-theme="fantasy"] { +#rpg-thought-icon[data-theme="fantasy"], +.rpg-mobile-toggle[data-theme="fantasy"] { --rpg-bg: #2b1810; --rpg-accent: #3d2414; --rpg-text: #f4e8d0; @@ -2919,7 +3134,8 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Apply cyberpunk theme to thought panel */ #rpg-thought-panel[data-theme="cyberpunk"], -#rpg-thought-icon[data-theme="cyberpunk"] { +#rpg-thought-icon[data-theme="cyberpunk"], +.rpg-mobile-toggle[data-theme="cyberpunk"] { --rpg-bg: #000000; --rpg-accent: #0d0d0d; --rpg-text: #00ff41; @@ -4457,11 +4673,62 @@ body:has(.rpg-panel.rpg-position-left) #sheld { position: fixed; z-index: 1000; /* Lower z-index to stay below dropdown menus */ pointer-events: auto; - max-width: 15.3rem; /* 30% smaller than 21.875rem (350px → 245px) */ + max-width: 350px; /* Fixed max like panels, will be constrained by viewport */ + width: auto; transform: translateY(0); /* No vertical centering - align with avatar top */ animation: thoughtPanelFadeIn 0.4s ease-out; } +/* Collapsed thought icon */ +#rpg-thought-icon { + position: fixed; + z-index: 1000; /* Lower z-index to stay below dropdown menus */ + display: none; /* Hidden by default in desktop */ + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + border-radius: 50%; + background: var(--rpg-bg, rgba(30, 30, 50, 0.95)); + border: 2px solid var(--rpg-highlight, #e94560); + color: var(--rpg-text, #ecf0f1); + font-size: clamp(1.25rem, 1.85vw, 1.875rem); + cursor: move; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5); + backdrop-filter: blur(10px); + transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease; + user-select: none; + -webkit-user-select: none; +} + +/* Show icon only in mobile view */ +@media (max-width: 1000px) { + #rpg-thought-icon { + display: flex; + } +} + +/* Force hide class for desktop mode - overrides media query */ +#rpg-thought-icon.rpg-force-hide { + display: none !important; +} + +/* Hidden state that allows transitions */ +#rpg-thought-icon.rpg-hidden { + opacity: 0; + pointer-events: none; +} + +#rpg-thought-icon.dragging { + transition: none !important; + cursor: grabbing; +} + +#rpg-thought-icon:not(.dragging):hover { + transform: scale(1.1); + box-shadow: 0 6px 20px rgba(233, 69, 96, 0.4); +} + /* Close button */ .rpg-thought-close { position: absolute; @@ -4489,28 +4756,11 @@ body:has(.rpg-panel.rpg-position-left) #sheld { color: var(--rpg-highlight, #e94560); } -/* Collapsed thought icon */ -#rpg-thought-icon { - position: fixed; - z-index: 1000; /* Lower z-index to stay below dropdown menus */ - width: 2.25rem; - height: 2.25rem; - border-radius: 50%; - background: var(--rpg-bg, rgba(30, 30, 50, 0.95)); - border: 2px solid var(--rpg-highlight, #e94560); - display: flex; - align-items: center; - justify-content: center; - font-size: clamp(1.3rem, 1.4rem, 1.5rem); - cursor: pointer; - animation: thoughtIconPulse 2s ease-in-out infinite; - box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5); - backdrop-filter: blur(10px); -} - -#rpg-thought-icon:hover { - transform: scale(1.1); - animation: none; +/* Hide close button in desktop view (panel doesn't close) */ +@media (min-width: 1001px) { + .rpg-thought-close { + display: none !important; + } } @keyframes thoughtIconPulse { @@ -4535,6 +4785,12 @@ body:has(.rpg-panel.rpg-position-left) #sheld { z-index: 1; } +/* Flip thought circles to left side when panel is on left */ +.rpg-thought-panel-right .rpg-thought-circles { + inset: 0px auto auto -50px; + flex-direction: row; /* Normal order for left side */ +} + .rpg-thought-circle { background: var(--rpg-bg, rgba(30, 30, 50, 0.8)); border: 2px solid var(--rpg-highlight, #e94560); @@ -4569,7 +4825,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5); position: relative; backdrop-filter: blur(15px); - max-height: 30vh; + max-height: calc(100vh - 120px); /* Scale with viewport height */ overflow-y: auto; overflow-x: hidden; } @@ -4717,12 +4973,19 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } /* Responsive positioning for mobile/narrow screens */ -@media (max-width: 768px) { +@media (max-width: 1000px) { #rpg-thought-panel { position: fixed !important; max-width: 90vw !important; + width: 90vw !important; left: 50% !important; - transform: translateX(-50%) translateY(-50%) !important; + transform: translateX(-50%) !important; + max-height: calc(100vh - 80px) !important; + } + + #rpg-thought-panel .rpg-thought-bubble { + max-height: calc(100vh - 100px) !important; + overflow-y: auto !important; } .rpg-thought-circles { @@ -4754,28 +5017,39 @@ body:has(.rpg-panel.rpg-position-left) #sheld { width: 44px; height: 44px; border-radius: 50%; - background: var(--SmartThemeBlurTintColor); - border: 2px solid var(--SmartThemeBorderColor); + background: var(--rpg-bg, rgba(30, 30, 50, 0.95)); + border: 2px solid var(--rpg-highlight, #e94560); color: var(--rpg-text, #ecf0f1); font-size: clamp(1.25rem, 1.85vw, 1.875rem); - cursor: grab; + cursor: move; z-index: 10002; - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); - transition: opacity 0.3s ease, transform 0.2s ease, top 0.3s ease, left 0.3s ease, right 0.3s ease, bottom 0.3s ease; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5); + backdrop-filter: blur(10px); + transition: transform 0.2s ease, box-shadow 0.2s ease, top 0.3s ease, left 0.3s ease, right 0.3s ease, bottom 0.3s ease; user-select: none; /* Prevent text selection while dragging */ -webkit-user-select: none; will-change: top, left; /* Optimize for position changes */ } -/* Disable transitions while actively dragging */ -.rpg-mobile-toggle.dragging { - transition: none; - cursor: grabbing; +/* Center the icon inside */ +.rpg-mobile-toggle i { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; } -.rpg-mobile-toggle:hover { +/* Disable transitions while actively dragging */ +.rpg-mobile-toggle.dragging { + transition: none !important; + cursor: grabbing; + animation: none; +} + +.rpg-mobile-toggle:not(.dragging):hover { transform: scale(1.1); - box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4); + box-shadow: 0 6px 20px rgba(233, 69, 96, 0.4); } .rpg-mobile-toggle:active { @@ -4855,7 +5129,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Hidden by default - completely removed from layout */ display: none !important; - overflow-y: auto !important; + overflow: visible !important; -webkit-overflow-scrolling: touch; /* Styling */ @@ -4866,6 +5140,17 @@ body:has(.rpg-panel.rpg-position-left) #sheld { box-shadow: -5px 0 20px var(--rpg-shadow); } + /* Allow collapse button to show outside panel */ + .rpg-game-container { + overflow: visible !important; + } + + /* But keep content scrollable */ + #rpg-panel-content { + overflow-y: auto !important; + overflow-x: hidden !important; + } + /* Show panel when opened with slide-in animation */ .rpg-panel.rpg-mobile-open { display: block !important; @@ -4900,6 +5185,45 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } } + /* Slide-in animation from left */ + @keyframes rpgSlideInFromLeft { + from { + transform: translateX(-100%); + } + to { + transform: translateX(0); + } + } + + /* Slide-out animation to left */ + @keyframes rpgSlideOutToLeft { + from { + transform: translateX(0); + } + to { + transform: translateX(-100%); + } + } + + /* Left-side mobile panel positioning */ + .rpg-panel.rpg-position-left { + right: auto !important; + left: 0 !important; + border-radius: 0 20px 0 0; + border-left: none; + border-right: 1px solid var(--SmartThemeBorderColor); + box-shadow: 5px 0 20px var(--rpg-shadow); + } + + /* Left-side panel animations */ + .rpg-panel.rpg-position-left.rpg-mobile-open { + animation: rpgSlideInFromLeft 0.3s ease-in-out; + } + + .rpg-panel.rpg-position-left.rpg-mobile-closing { + animation: rpgSlideOutToLeft 0.3s ease-in-out; + } + /* ======================================== MOBILE KEYBOARD HANDLING ======================================== */ @@ -4934,15 +5258,14 @@ body:has(.rpg-panel.rpg-position-left) #sheld { pointer-events: auto !important; } - /* Collapse toggle on mobile - right side, always visible */ + /* Collapse toggle on mobile - positioned on panel edge and vertically centered */ .rpg-collapse-toggle { display: flex !important; align-items: center; justify-content: center; - position: fixed !important; - top: calc(var(--topBarBlockSize) + 120px) !important; - left: 12px !important; - right: auto !important; + position: absolute !important; + top: 50% !important; + transform: translateY(-50%) !important; width: 44px; height: 44px; min-width: 44px; @@ -4950,20 +5273,33 @@ body:has(.rpg-panel.rpg-position-left) #sheld { border-radius: 50%; background: var(--SmartThemeBlurTintColor); border: 2px solid var(--SmartThemeBorderColor); - z-index: 9999 !important; + z-index: 10000 !important; transition: all 0.2s ease; - transform: none !important; pointer-events: auto !important; cursor: pointer !important; } + /* Position on right edge when panel is on left */ + body.rpg-panel-position-left .rpg-collapse-toggle, + .rpg-panel.rpg-position-left .rpg-collapse-toggle { + left: auto !important; + right: -22px !important; + } + + /* Position on left edge when panel is on right */ + body.rpg-panel-position-right .rpg-collapse-toggle, + .rpg-panel.rpg-position-right .rpg-collapse-toggle { + left: -22px !important; + right: auto !important; + } + .rpg-collapse-toggle:hover { background: rgba(255, 255, 255, 0.1); - transform: scale(1.05) !important; + transform: translateY(-50%) scale(1.05) !important; } .rpg-collapse-toggle:active { - transform: scale(0.95) !important; + transform: translateY(-50%) scale(0.95) !important; } /* Mobile icon styling - use chevrons for drawer UX */ @@ -5050,6 +5386,25 @@ body:has(.rpg-panel.rpg-position-left) #sheld { padding: 12px; } + /* Center empty state messages in mobile tabs - only when empty */ + .rpg-mobile-tab-content #rpg-user-stats:has(> .rpg-inventory-empty) { + display: flex !important; + flex: 1; + flex-direction: column; + align-items: center; + justify-content: center; + } + + /* When empty state is shown, center it in the full panel */ + .rpg-mobile-tab-content #rpg-user-stats > .rpg-inventory-empty { + margin: auto; + } + + .rpg-mobile-tab-content .rpg-inventory-empty { + text-align: center; + width: auto !important; + } + @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } @@ -5126,7 +5481,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-calendar-day { - font-size: clamp(10px, 2.9vw, 14px) !important; + font-size: min(2.5vw, 14px) !important; } .rpg-calendar-year { @@ -5134,19 +5489,19 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-weather-forecast { - font-size: clamp(0.5625rem, 2.2vw, 0.6875rem) !important; + font-size: min(2.2vw, 0.6875rem) !important; } .rpg-temp-value { - font-size: clamp(0.625rem, 2.5vw, 0.8125rem) !important; + font-size: min(2.5vw, 0.8125rem) !important; } .rpg-time-value { - font-size: clamp(0.625rem, 2.5vw, 0.8125rem) !important; + font-size: min(2.5vw, 0.8125rem) !important; } .rpg-location-text { - font-size: clamp(0.6875rem, 2.8vw, 0.875rem) !important; + font-size: min(2.8vw, 0.875rem) !important; } .rpg-map-marker { @@ -5173,20 +5528,22 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-event-text { - font-size: clamp(8px, 2vw, 10px) !important; + font-size: clamp(11px, 2.8vw, 14px) !important; } /* ======================================== MOBILE STATS TAB LAYOUT IMPROVEMENTS ======================================== */ - /* Make the entire stats section a grid */ + /* Make the entire stats section a single column grid */ .rpg-stats-section { display: grid !important; - grid-template-columns: 40% 60%; /* Left for inventory/mood, right for attributes */ - grid-template-rows: auto auto auto auto auto; /* Portrait, bars, inventory, mood, attributes */ + grid-template-columns: 1fr !important; /* Single column */ + grid-template-rows: auto !important; /* Auto rows - everything stacked */ gap: 12px; padding: 16px 12px; + overflow-y: auto !important; /* Enable scrolling on the grid container */ + min-height: 0; } /* Use display: contents so children participate in grid */ @@ -5195,19 +5552,31 @@ body:has(.rpg-panel.rpg-position-left) #sheld { display: contents !important; } - /* Portrait row - centered at top, full width */ - .rpg-stats-header-left { - grid-column: 1 / 3; - grid-row: 1; + /* Portrait row - centered at top, row 1 */ + .rpg-stats-header-left, + .rpg-user-info-row { display: flex !important; + grid-column: 1 !important; + grid-row: 1 !important; justify-content: center; align-items: center; - gap: 4px; + gap: 8px; } + /* Make user portrait visible and sized for mobile */ .rpg-user-portrait { - width: 64px; - height: 64px; + width: clamp(32px, 8vw, 48px) !important; + height: clamp(32px, 8vw, 48px) !important; + } + + /* Make user name and level readable */ + .rpg-user-name { + font-size: clamp(13px, 3.2vw, 16px) !important; + } + + .rpg-level-label, + .rpg-level-value { + font-size: clamp(12px, 3vw, 14px) !important; } /* Hide stats title on mobile */ @@ -5215,43 +5584,18 @@ body:has(.rpg-panel.rpg-position-left) #sheld { display: none; } - /* Stat bars row - full width */ + /* Stats left container must use contents to unwrap its children */ .rpg-stats-left { - grid-column: 1 / 3; - grid-row: 2; display: contents !important; } - /* User info row on mobile */ - .rpg-user-info-row { - grid-column: 1 / 3; - grid-row: 1; - justify-content: center !important; - font-size: clamp(11px, 2.8vw, 14px) !important; - gap: clamp(6px, 1.5vw, 10px) !important; - } - - /* Make user portrait larger on mobile */ - .rpg-user-portrait { - width: clamp(24px, 6vw, 32px) !important; - height: clamp(24px, 6vw, 32px) !important; - } - - /* Make user name and level more readable on mobile */ - .rpg-user-name { - font-size: clamp(12px, 3vw, 16px) !important; - } - - .rpg-level-label, - .rpg-level-value { - font-size: clamp(11px, 2.8vw, 14px) !important; - } - + /* Stat bars - full width, row 2 */ .rpg-stats-grid { - grid-column: 1 / 3; - grid-row: 2; - min-height: 180px; /* Stretch vertically to fill more space */ - gap: clamp(8px, 2vw, 12px); /* Increase gap between stat rows */ + grid-column: 1 !important; + grid-row: 2 !important; + display: flex !important; + flex-direction: column !important; + gap: clamp(6px, 1.5vw, 8px); } /* Increase stat bar text sizes for mobile readability */ @@ -5263,28 +5607,60 @@ body:has(.rpg-panel.rpg-position-left) #sheld { font-size: clamp(12px, 3.1vw, 16px) !important; } - /* Inventory - expand to fill horizontal space in flex container */ + /* Everything else stacked below - full width, auto rows */ + .rpg-mood, + .rpg-inventory-box, + .rpg-skills-section, + .rpg-custom-field { + grid-column: 1 !important; + grid-row: auto !important; + } + + /* Attributes container - use contents to unwrap */ + .rpg-stats-right { + display: contents !important; + } + + /* Compact 2x3 or 3x2 grid for mobile */ + .rpg-classic-stats-grid { + display: grid !important; + grid-template-columns: repeat(3, 1fr) !important; + grid-template-rows: repeat(2, 1fr) !important; + gap: 6px; + margin: 0; + padding: 0; + width: 100%; + } + + /* Everything else below - full width stacked */ .rpg-inventory-box { - flex: 1 !important; /* Grow to fill all available space */ - min-width: 0 !important; /* Allow flexbox to work properly */ - max-width: none !important; /* Remove desktop width restrictions */ - width: auto !important; /* Don't force a specific width */ - min-height: 60px; /* Give it decent height */ - max-height: none; /* Remove height restriction */ + flex: 1 !important; + min-width: 0 !important; + max-width: none !important; + width: 100% !important; + grid-row: auto !important; + } + + /* Inventory box */ + .rpg-inventory-box { + flex: 1 !important; + min-width: 0 !important; + max-width: none !important; + width: auto !important; + min-height: 60px; + max-height: none; } /* Increase inventory text size for readability on mobile */ .rpg-inventory-items { font-size: clamp(11px, 2.8vw, 14px) !important; line-height: 1.4; - width: 100% !important; /* Fill the inventory box */ - white-space: normal !important; /* Allow text wrapping */ + width: 100% !important; + white-space: normal !important; } - /* Mood - row 4, aligned with attributes top */ + /* Mood */ .rpg-mood { - grid-column: 1; - grid-row: 3; display: flex; flex-direction: column; gap: 6px; @@ -5297,28 +5673,6 @@ body:has(.rpg-panel.rpg-position-left) #sheld { line-height: 1.3; } - /* Attributes - right side, rows 4-6 aligned with mood */ - .rpg-stats-right { - grid-column: 2; - grid-row: 3; - display: contents !important; - } - - .rpg-classic-stats { - grid-column: 2; - grid-row: 3; /* Align with mood */ - } - - /* Attributes as ultra-compact 2x3 grid for mobile */ - .rpg-classic-stats-grid { - display: grid !important; - grid-template-columns: repeat(2, 1fr) !important; - grid-template-rows: repeat(3, 1fr) !important; - gap: 3px; - margin: 4px 5px 4px 0; - padding-right: 5px; - } - /* Each attribute - ULTRA COMPACT with vertical stack layout */ .rpg-classic-stat { display: grid !important; @@ -5417,14 +5771,12 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Position thought icon above avatar on mobile to prevent off-screen clipping */ /* JavaScript will calculate position, but add transform to move it above and right */ #rpg-thought-icon { - /* 20% larger than desktop for better visibility on mobile */ - width: 2.7rem !important; - height: 2.7rem !important; - font-size: clamp(1.5rem, 2.2vw, 1.875rem) !important; - /* Use transform to shift icon above and to the right of avatar */ - transform: translate(50px, -45px) !important; + /* Match mobile toggle size */ + width: 44px !important; + height: 44px !important; + font-size: clamp(1.25rem, 1.85vw, 1.875rem) !important; /* Smooth animation for position changes during scroll */ - transition: top 0.2s ease-out, left 0.2s ease-out !important; + transition: transform 0.2s ease, box-shadow 0.2s ease !important; will-change: top, left; } @@ -5577,9 +5929,239 @@ body:has(.rpg-panel.rpg-position-left) #sheld { /* Readable clear cache button */ .rpg-btn-clear-cache, - .rpg-btn-reset-fab { + .rpg-btn-reset-fab, + .rpg-btn-customize-prompts { font-size: clamp(13px, 3.3vw, 17px) !important; } + + /* ======================================== + MOBILE TRACKER EDITOR FOOTER + ======================================== */ + + /* Make footer wrap and stack buttons on mobile */ + .rpg-settings-popup-footer { + flex-direction: column; + gap: 0.5em; + padding: 0.75em; + } + + .rpg-footer-left, + .rpg-footer-right { + width: 100%; + overflow-x: auto; + overflow-y: hidden; + -webkit-overflow-scrolling: touch; + scrollbar-width: thin; + flex-wrap: nowrap; + } + + /* Prevent buttons from shrinking in scroll container */ + .rpg-footer-left button, + .rpg-footer-right button { + flex-shrink: 0; + white-space: nowrap; + font-size: clamp(12px, 3.1vw, 15px) !important; + padding: 0.5em 0.75em !important; + } + + /* ======================================== + MOBILE TRACKER EDITOR HEADER + ======================================== */ + + /* Make header text smaller and wrap properly */ + .rpg-settings-popup-header h3 { + font-size: clamp(16px, 4.1vw, 20px) !important; + word-break: break-word; + } + + .rpg-settings-popup-header h3 i { + font-size: clamp(14px, 3.6vw, 18px) !important; + } + + /* ======================================== + MOBILE TRACKER EDITOR TABS + ======================================== */ + + /* Make tabs wrap and stack if needed */ + .rpg-editor-tabs { + flex-wrap: wrap; + gap: 0; + } + + .rpg-editor-tab { + flex: 1 1 auto; + min-width: 0; + padding: 0.5em 0.5em; + font-size: clamp(11px, 2.8vw, 14px) !important; + gap: 0.25em; + } + + .rpg-editor-tab i { + font-size: clamp(12px, 3.1vw, 15px) !important; + } + + /* ======================================== + MOBILE TRACKER EDITOR CONTENT + ======================================== */ + + /* Reduce popup body padding on mobile */ + .rpg-settings-popup-body { + padding: 0.75em !important; + } + + /* Make section headers smaller */ + .rpg-editor-section h4 { + font-size: clamp(13px, 3.3vw, 16px) !important; + gap: 0.25em; + } + + .rpg-editor-section h4 i { + font-size: clamp(12px, 3.1vw, 15px) !important; + } + + /* Make hint text smaller */ + .rpg-editor-hint { + font-size: clamp(11px, 2.8vw, 14px) !important; + } + + /* ======================================== + MOBILE TRACKER EDITOR STAT ITEMS + ======================================== */ + + /* Make stat items wrap on mobile */ + .rpg-editor-stat-item { + flex-wrap: wrap; + gap: 0.5em; + padding: 0.5em; + } + + /* Make stat name input full width on mobile */ + .rpg-stat-name, + .rpg-attr-name { + width: 100%; + flex: 1 1 100%; + font-size: clamp(13px, 3.3vw, 16px) !important; + } + + /* Make toggle and remove button stay on same row */ + .rpg-stat-toggle, + .rpg-attr-toggle { + flex: 0 0 auto; + } + + .rpg-stat-remove, + .rpg-attr-remove { + flex: 0 0 auto; + font-size: clamp(12px, 3.1vw, 15px) !important; + padding: 0.5em 0.75em !important; + } + + /* ======================================== + MOBILE RELATIONSHIP MAPPING + ======================================== */ + + /* Make relationship items stack vertically on mobile */ + .rpg-relationship-item { + grid-template-columns: 1fr; + gap: 0.5em; + padding: 0.75em 0.5em; + } + + /* Hide arrow on mobile since items are stacked */ + .rpg-relationship-item .rpg-arrow { + display: none; + } + + /* Make relationship inputs full width */ + .rpg-relationship-name, + .rpg-relationship-emoji { + width: 100%; + font-size: clamp(13px, 3.3vw, 16px) !important; + } + + .rpg-remove-relationship { + font-size: clamp(12px, 3.1vw, 15px) !important; + padding: 0.5em 0.75em !important; + } + + /* ======================================== + MOBILE TRACKER EDITOR INPUTS & CONTROLS + ======================================== */ + + /* Make all input fields readable on mobile */ + .rpg-editor-tab-content input[type="text"], + .rpg-editor-tab-content input[type="number"], + .rpg-editor-tab-content select, + .rpg-editor-tab-content textarea { + font-size: clamp(13px, 3.3vw, 16px) !important; + padding: 0.5em !important; + } + + /* Make add buttons full width on mobile */ + .rpg-editor-section button[id*="add"], + .rpg-editor-section button[id*="Add"] { + width: 100%; + font-size: clamp(13px, 3.3vw, 16px) !important; + padding: 0.5em !important; + } + + /* Make checkboxes with labels easier to tap */ + .rpg-editor-tab-content label { + min-height: 44px; + display: flex; + align-items: center; + font-size: clamp(13px, 3.3vw, 16px) !important; + } + + .rpg-editor-tab-content input[type="checkbox"] { + min-width: 20px; + min-height: 20px; + margin-right: 0.5em; + } + + /* ======================================== + MOBILE WIDGET ROWS (DATE/TEMPERATURE) + ======================================== */ + + /* Make widget rows wrap on mobile */ + .rpg-editor-widget-row { + flex-wrap: wrap; + gap: 0.5em; + padding: 0.75em 0.5em; + } + + /* Checkbox and main label on first row */ + .rpg-editor-widget-row > input[type="checkbox"], + .rpg-editor-widget-row > label { + flex: 0 0 auto; + } + + /* Format dropdown full width on second row */ + .rpg-editor-widget-row .rpg-select-mini { + flex: 1 1 100%; + width: 100%; + font-size: clamp(13px, 3.3vw, 16px) !important; + padding: 0.5em !important; + } + + /* Radio group full width on second row */ + .rpg-editor-widget-row .rpg-radio-group { + flex: 1 1 100%; + width: 100%; + gap: 1.5em; + justify-content: flex-start; + margin-top: 0.25em; + } + + .rpg-radio-group label { + font-size: clamp(13px, 3.3vw, 16px) !important; + gap: 0.5em; + } + + .rpg-radio-group input[type="radio"] { + min-width: 18px; + min-height: 18px; + } } /* Very narrow screens - single column layout for all stats */ @@ -5718,6 +6300,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { transition: all 0.2s ease; font-weight: 500; text-align: center; + font-size: clamp(0.75rem, 1vw, 0.9rem); } .rpg-inventory-subtab:hover { @@ -5741,6 +6324,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-inventory-header { + position: relative; display: flex; justify-content: space-between; align-items: center; @@ -5865,7 +6449,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-storage-content { - padding: 0.75rem; + padding: 0.5rem; background: var(--SmartThemeBlurTintColor); } @@ -6059,11 +6643,11 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-item-row { + position: relative; display: flex; align-items: center; - justify-content: space-between; - gap: 1rem; - padding: 0.75rem 1rem; + gap: 0.75rem; + padding: 0.75rem; background: transparent; border: 2px solid var(--rpg-highlight); border-radius: 0.25rem; @@ -6079,9 +6663,9 @@ body:has(.rpg-panel.rpg-position-left) #sheld { .rpg-item-row .rpg-item-name { flex: 1; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + line-height: 1.5; + word-wrap: break-word; + overflow-wrap: break-word; } .rpg-item-row .rpg-item-remove { @@ -6371,6 +6955,28 @@ body:has(.rpg-panel.rpg-position-left) #sheld { gap: 0.5rem; border-bottom: 2px solid var(--SmartThemeBorderColor); padding-bottom: 0.5rem; + overflow-x: auto; + overflow-y: hidden; + flex-wrap: nowrap; + scrollbar-width: thin; + scrollbar-color: var(--SmartThemeBorderColor) transparent; +} + +.rpg-quests-subtabs::-webkit-scrollbar { + height: 6px; +} + +.rpg-quests-subtabs::-webkit-scrollbar-track { + background: transparent; +} + +.rpg-quests-subtabs::-webkit-scrollbar-thumb { + background: var(--SmartThemeBorderColor); + border-radius: 3px; +} + +.rpg-quests-subtabs::-webkit-scrollbar-thumb:hover { + background: var(--rpg-accent); } .rpg-quests-subtab { @@ -6384,6 +6990,9 @@ body:has(.rpg-panel.rpg-position-left) #sheld { transition: all 0.2s ease; font-weight: 500; text-align: center; + font-size: clamp(0.75rem, 1vw, 0.9rem); + min-width: fit-content; + white-space: nowrap; } .rpg-quests-subtab:hover { @@ -6407,6 +7016,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } .rpg-quest-header { + position: relative; display: flex; justify-content: space-between; align-items: center; @@ -8372,7 +8982,7 @@ body:has(.rpg-panel.rpg-position-left) #sheld { display: flex; align-items: center; justify-content: center; - background: rgba(0, 0, 0, 0.3); + background: rgba(0, 0, 0, 0.4); border-radius: 50%; color: #1DB954; font-size: 20px; @@ -8466,37 +9076,85 @@ body:has(.rpg-panel.rpg-position-left) #sheld { } /* Mobile Responsive Styles */ -@media (max-width: 600px) { +@media (max-width: 1000px) { + .rpg-music-widget { + width: calc(100% - 20px); + max-width: none; + left: 50%; + transform: translate(-50%, calc(-100% - 8px)); + } + .rpg-music-widget-content { - padding: 8px 12px; - gap: 10px; + padding: 8px 10px; + gap: 8px; } .rpg-music-widget-icon { - width: 36px; - height: 36px; - font-size: 18px; + width: 32px; + height: 32px; + font-size: 16px; + } + + .rpg-music-widget-info { + gap: 1px; } .rpg-music-widget-title { - font-size: 13px; - } - - .rpg-music-widget-artist { - font-size: 11px; - } - - .rpg-music-widget-play { - width: 32px; - height: 32px; font-size: 12px; } - .rpg-music-widget-close { - width: 22px; - height: 22px; + .rpg-music-widget-artist { + font-size: 10px; + } + + .rpg-music-widget-play { + width: 30px; + height: 30px; font-size: 11px; } + + .rpg-music-widget-close { + width: 20px; + height: 20px; + font-size: 10px; + } +} + +@media (max-width: 600px) { + .rpg-music-widget { + width: calc(100% - 12px); + } + + .rpg-music-widget-content { + padding: 6px 8px; + gap: 6px; + } + + .rpg-music-widget-icon { + width: 28px; + height: 28px; + font-size: 14px; + } + + .rpg-music-widget-title { + font-size: 11px; + } + + .rpg-music-widget-artist { + font-size: 9px; + } + + .rpg-music-widget-play { + width: 28px; + height: 28px; + font-size: 10px; + } + + .rpg-music-widget-close { + width: 18px; + height: 18px; + font-size: 9px; + } } /* Theme Support - Apply theme colors */ @@ -8869,16 +9527,47 @@ body[data-theme="cyberpunk"] .rpg-music-widget-play { display: flex; gap: 8px; margin-bottom: 12px; + overflow-x: auto; + overflow-y: hidden; + flex-wrap: nowrap; + padding: 0 4px; /* Prevent first/last items from being cut off */ + -webkit-overflow-scrolling: touch; /* Smooth scrolling on iOS */ +} + +/* Center items when they fit, allow scrolling when they don't */ +.rpg-features-row::before, +.rpg-features-row::after { + content: ''; + margin: auto; +} + +/* Hide scrollbar for cleaner look while maintaining functionality */ +.rpg-features-row::-webkit-scrollbar { + height: 4px; +} + +.rpg-features-row::-webkit-scrollbar-track { + background: transparent; +} + +.rpg-features-row::-webkit-scrollbar-thumb { + background: rgba(128, 128, 128, 0.3); + border-radius: 2px; +} + +.rpg-features-row::-webkit-scrollbar-thumb:hover { + background: rgba(128, 128, 128, 0.5); } /* Each feature column */ .rpg-feature-col { - flex: 1; - min-width: 0; + flex: 0 0 auto; + min-width: 60px; } .rpg-feature-col .rpg-toggle-label { justify-content: center; + align-items: center; } /* Always hide text, show only checkbox + icon */ @@ -8887,8 +9576,11 @@ body[data-theme="cyberpunk"] .rpg-music-widget-play { } .rpg-feature-col .rpg-toggle-label i { - font-size: 1.125rem; + font-size: 0.95rem; flex-shrink: 0; + display: flex; + align-items: center; + justify-content: center; } /* Tablet and below: Hide text, show only checkbox + icon */ @@ -8898,15 +9590,14 @@ body[data-theme="cyberpunk"] .rpg-music-widget-play { } .rpg-feature-col .rpg-toggle-label i { - font-size: 1.cally with icons only */ -@media (max-width: 400px) { - .rpg-features-row { - flex-direction: column; - gap: 0.5rem; + font-size: 1rem; } +} +/* Very small screens: Remove column layout since we have horizontal scroll */ +@media (max-width: 400px) { .rpg-feature-col .rpg-toggle-label i { - font-size: 1.25rem; + font-size: 1rem; } } diff --git a/template.html b/template.html index 0d3b8ac..5081ea8 100644 --- a/template.html +++ b/template.html @@ -81,6 +81,15 @@
+ +
+ +
+
- -
- -
-
-
+ +
+ +
+ +
+ +
- - -
@@ -201,7 +207,7 @@ Color (Low): Color when stats are at - 0% + 0%.
@@ -209,7 +215,7 @@ Bar Color (High): Color when stats are at - 100% + 100%.
@@ -219,7 +225,7 @@ Use the Extensions tab to enable/disable - the RPG Companion extension. + the RPG Companion extension entirely
@@ -237,84 +243,145 @@ Show User Stats + + Enable User Stats that track your persona's statistics, mood, attributes, skills, etc. + + + Display location, time, weather, and recent events. + + + Display character portraits with their current thoughts and status. + + + + + Display character thoughts as overlay bubbles next to their messages. + + + Track items carried, clothing worn, stored items, and assets. + - - - Display character thoughts as overlay bubbles next to their messages + data-i18n-key="template.settingsModal.display.showQuestsNote"> + Manage main and optional quests with objectives. - Auto-expand thought bubble without clicking the icon first - - - - - Smooth transitions for stats, content updates, and dice rolls + data-i18n-key="template.settingsModal.display.showLockIconsNote"> + Display lock/unlock icons on tracker items to prevent AI from modifying them. + + Display a toggle button to enable/disable HTML formatting in messages. + + + + + Display a toggle button to enable/disable colored dialogue formatting. + - - + + Display Spotify music player with AI-suggested scene-appropriate tracks. + + + Display a toggle button to enable/disable animated weather effects. + - Display buttons above chat input for plot progression prompts + data-i18n-key="template.settingsModal.display.showNarratorModeNote"> + Display a toggle button to enable/disable narrator mode (infer characters from context). + + + + + Display a toggle button to automatically generate avatars for characters without images. + + + + + Display button for AI-generated random plot progression prompts. + + + + + Display button for context-aware narrative continuation prompts. + + + + + Display button to initiate interactive combat encounters. - Display the "Last Roll" indicator in the panel. + Display the "Last Roll" indicator in the panel - - - Automatically generate avatars for characters without custom images using the Image Generation - Plugin - - - - - Shows parser logs in a mobile-friendly UI panel. Useful for troubleshooting. Look for the red bug - button. - - - -
- -
-

Combat Encounters

- - - - Show the "Start Encounter" button above chat input for interactive combat - - -
- - - Number of recent messages to include in combat initialization -
- - - - Save detailed combat logs to file for future reference and analysis -
@@ -468,44 +486,52 @@
-
- - - Number of recent messages - to include (Separate mode only) -
- -
- - - Number of messages to - process per batch in Memory Recollection -
-
- - - 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). - +
+ + + Number of recent messages + to include (Separate mode only) +
-
@@ -726,7 +734,7 @@
- Customize the AI prompts used throughout the extension. Leave fields empty to use defaults. + Customize the AI prompts used throughout the extension. Leave fields empty to use defaults. @@ -739,7 +747,21 @@ +
+ + +
+ + + Injected when "Enable Dialogue Coloring" is enabled. Affects all generation modes. + + +
@@ -753,7 +775,21 @@ +
+ + +
+ + + Injected when "Narrator Mode" is enabled. Instructs AI to infer characters from context. + + +
@@ -767,7 +803,7 @@
@@ -781,7 +817,7 @@
@@ -795,7 +831,7 @@
@@ -809,7 +845,7 @@
@@ -823,7 +859,7 @@
@@ -837,7 +873,7 @@
@@ -855,3 +891,81 @@
+ + +