Skip to content

fix: trim card names, scope agent context, and render Markdown - #4307

Merged
SpicyMarinara merged 4 commits into
stagingfrom
agent/4303-4306-issue-sweep
Jul 30, 2026
Merged

fix: trim card names, scope agent context, and render Markdown#4307
SpicyMarinara merged 4 commits into
stagingfrom
agent/4303-4306-issue-sweep

Conversation

@SpicyMarinara

@SpicyMarinara SpicyMarinara commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

Linked issues

Closes #4303
Closes #4304
Closes #4305
Closes #4306

Why this change

The latest issue sweep found four user-visible gaps: pasted Character names retain accidental edge whitespace, edited chat text needs durable Memory Recall protection, custom agents receive context they do not need, and card/lorebook fields have no rendered Markdown view. Each correction stays within the existing subsystem without introducing a parallel framework.

What changes

  • Trim Character names on editor blur, schema validation, persistence, restore, reset, and duplication boundaries.
  • Protect edited-message Memory Recall behavior with an end-to-end regression proving stale native chunks are removed and rebuilt only from the saved edit.
  • Add per-custom-agent selectors for chat history, Character, Persona, activated lorebook, summary, Author's Notes, tracker, and recalled-memory context. Shared calls use the union requested by their participating agents.
  • Stop unrelated background and tracker context from leaking into custom-agent requests.
  • Add source/preview Markdown toggles to Character, Persona, and lorebook fields, and render formatted card text in library detail views through the existing safe renderer.

Validation

  • Run pnpm check
  • Run relevant regression checks
  • Manually verify affected browser paths
  • Read and follow CONTRIBUTING.md

Automated evidence run locally:

  • pnpm check passed.
  • Prompt regression passed, including individual custom-agent filtering and batched context unions.
  • Regeneration-context regression passed, including edited-message invalidation and rebuild.
  • Focused desktop browser proof for Markdown source/preview passed.
  • The full UI smoke matrix completed with 152 passes and 87 expected skips; 13 unrelated existing accent/theme and background-library cases failed. None overlap files or behavior changed here.

Manual verification needed

  • Manually verify pasted Character names lose leading and trailing whitespace after leaving the field and after save/import.
  • Manually verify edited messages are the only native message version injected by Memory Recall.
  • Manually verify each custom-agent context toggle independently and in a combined agent call.
  • Manually verify Markdown source/preview controls for Character, Persona, and lorebook fields on desktop and mobile.

Summary by CodeRabbit

  • New Features
    • Custom agents can configure which context sources they use (including per-source enablement in the editor).
    • Markdown preview and formatted rendering are now available across more character/persona/lorebook and library views (textarea preview UI).
    • Agent generation can include selected author notes and activated lorebook entry content.
  • Bug Fixes
    • Character names are trimmed of leading/trailing whitespace when saved, imported, and persisted across versions.
    • Memory Recall now injects only the currently edited message revision.
  • Tests
    • Added E2E and expanded regression coverage for Markdown preview integrity, context-source selection semantics, name normalization, and edited-message regeneration.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds configurable context sources for custom agents, Markdown previews and rendered card text, character-name trimming across validation and storage, and regression coverage for edited-message memory recall.

Changes

Custom-agent context controls

Layer / File(s) Summary
Context-source contract and editor controls
packages/shared/src/types/agent.ts, packages/client/src/components/agents/AgentEditor.tsx, packages/client/src/localization/locales/en.json
Custom-agent context-source types, defaults, normalization, persistence, capability gating, and toggle controls are added.
Context propagation and prompt filtering
packages/server/src/services/agents/agent-executor.ts, packages/server/src/services/generation/agent-resolution.ts, packages/server/src/routes/generate...
Resolved agents are marked as custom or built-in; generation context carries author notes and activated lorebook entries, while prompt sections are filtered by selected sources.
Context regression coverage
scripts/regressions/prompt.regression.ts
Regression cases cover default selections, per-source inclusion, vector context, and batched context unions.

Markdown previews and rendering

Layer / File(s) Summary
Markdown preview editor
packages/client/src/components/ui/MacroTextarea.tsx, packages/client/src/localization/locales/en.json
MacroTextarea switches between source editing and rendered Markdown preview.
Character, persona, and lorebook fields
packages/client/src/components/characters/CharacterEditor.tsx, packages/client/src/components/personas/PersonaEditor.tsx, packages/client/src/components/lorebooks/*
Markdown preview is enabled for supported text fields.
Library rendering and E2E validation
packages/client/src/components/characters/CharacterLibraryView.tsx, e2e/core-flows.e2e.ts
Library text renders Markdown, and an E2E test verifies preview rendering without changing source text.

Character-name normalization

Layer / File(s) Summary
Validation and persistence normalization
packages/shared/src/schemas/character.schema.ts, packages/server/src/services/storage/characters.storage.ts, packages/client/src/components/characters/CharacterEditor.tsx
Character names are trimmed during validation, editing, creation, versioning, restoration, reset, and duplication.
Regression coverage
scripts/regressions/open-issues.regression.ts
Assertions verify trimming during validation and storage flows.

Edited-message memory recall

Layer / File(s) Summary
Regeneration regression coverage
scripts/regressions/regeneration-context.regression.ts
Edited messages invalidate stale memory chunks, and rebuilt chunks contain edited text without superseded content.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AgentEditor
  participant AgentResolution
  participant AgentExecutor
  participant GenerationContext
  AgentEditor->>AgentResolution: persist selected contextSources
  AgentResolution->>AgentExecutor: provide isCustomAgent metadata
  GenerationContext->>AgentExecutor: provide authorNotes and activatedLorebookEntries
  AgentExecutor->>AgentExecutor: compute selected source union
  AgentExecutor->>AgentExecutor: include matching prompt context blocks
Loading

Possibly related PRs

Suggested labels: feature, refactor

Suggested reviewers: kolacheee, thetopham, promansis

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR addresses #4303-#4306 with matching code and tests for name trimming, Memory Recall edits, custom-agent context, and Markdown rendering.
Out of Scope Changes check ✅ Passed No clear out-of-scope code changes are present; supporting changelog, locale, and regression updates align with the stated objectives.
Title check ✅ Passed The title clearly summarizes the main changes: trimmed card names, scoped custom-agent context, and Markdown rendering.
Description check ✅ Passed The description covers linked issues, rationale, changes, and validation; docs/release and UI evidence sections are the only light gaps.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/4303-4306-issue-sweep

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@SpicyMarinara

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@SpicyMarinara
SpicyMarinara marked this pull request as ready for review July 30, 2026 13:45
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/client/src/components/agents/AgentEditor.tsx`:
- Around line 314-362: Keep CUSTOM_AGENT_CONTEXT_SOURCE_META synchronized with
CUSTOM_AGENT_CONTEXT_SOURCE_IDS by adding a dev-time completeness check that
verifies every shared source ID has exactly one metadata entry. Use the existing
source-ID symbols and preserve the current metadata structure, while making
missing or duplicate entries fail during development rather than silently
omitting an editor toggle.

In `@packages/client/src/components/characters/CharacterEditor.tsx`:
- Around line 1017-1020: Apply the same blur-time name normalization used by the
existing editable name input to the Metadata-tab name input near the metadata
field. Add an onBlur handler that trims formData.name and calls
updateField("name", trimmedName) only when the value changes, ensuring both
inputs keep the shared name state normalized.

In `@packages/server/src/services/agents/agent-executor.ts`:
- Around line 2631-2653: Escape the user-authored text appended in the
chatSummary and authorNotes branches of buildAgentExtras using the existing
escapeXml helper, matching the activatedLorebookEntries block. Keep the
surrounding tags and conditional gating unchanged while ensuring both context
values are escaped before insertion.

In `@packages/server/src/services/storage/characters.storage.ts`:
- Line 97: Update createVersionSnapshot to normalize the parsed existing
character data before serializing and persisting the snapshot. Reuse
normalizeCharacterData on the result of parseCharacterData(existing.data), while
preserving the existing snapshot storage flow.

In `@packages/shared/src/types/agent.ts`:
- Around line 553-573: Update the context-source defaults used by
normalizeCustomAgentContextSources so missing contextSources preserve the full
legacy-enabled behavior, including characters, persona, lorebook entries, chat
summary, author notes, tracker data, and recalled memories. Apply the same
legacy default constant to both server and local duplicate definitions, while
retaining explicit stored boolean values during normalization.

In `@scripts/regressions/open-issues.regression.ts`:
- Around line 520-528: Add focused regression cases in the storage normalization
tests for restoreVersion, resetVersions, and duplicateCharacter, using padded
character names and asserting each path persists or returns the trimmed name.
Keep the existing create coverage unchanged and exercise the storage methods
directly to verify normalization when route validation is bypassed.

In `@scripts/regressions/regeneration-context.regression.ts`:
- Around line 197-212: Strengthen the invalidation test around
chatStorage.updateMessageContent by seeding a second memoryChunks row for
editedChat whose message range does not include createdMessages[2]. Assert
afterEdit retains that unaffected chunk while removing the overlapping
stale-edited-memory row, proving invalidation is targeted rather than deleting
every chunk for the chat.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7fbcafd0-e43b-4f7e-89fd-eadde1a1203b

📥 Commits

Reviewing files that changed from the base of the PR and between 99fb624 and 5b45bea.

📒 Files selected for processing (20)
  • CHANGELOG.md
  • e2e/core-flows.e2e.ts
  • packages/client/src/components/agents/AgentEditor.tsx
  • packages/client/src/components/characters/CharacterEditor.tsx
  • packages/client/src/components/characters/CharacterLibraryView.tsx
  • packages/client/src/components/lorebooks/LorebookEntryRow.tsx
  • packages/client/src/components/lorebooks/LorebookFormFields.tsx
  • packages/client/src/components/personas/PersonaEditor.tsx
  • packages/client/src/components/ui/MacroTextarea.tsx
  • packages/client/src/localization/locales/en.json
  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/routes/generate/retry-agents-route.ts
  • packages/server/src/services/agents/agent-executor.ts
  • packages/server/src/services/generation/agent-resolution.ts
  • packages/server/src/services/storage/characters.storage.ts
  • packages/shared/src/schemas/character.schema.ts
  • packages/shared/src/types/agent.ts
  • scripts/regressions/open-issues.regression.ts
  • scripts/regressions/prompt.regression.ts
  • scripts/regressions/regeneration-context.regression.ts

Comment thread packages/client/src/components/agents/AgentEditor.tsx
Comment thread packages/client/src/components/characters/CharacterEditor.tsx
Comment thread packages/server/src/services/agents/agent-executor.ts
Comment thread packages/server/src/services/storage/characters.storage.ts
Comment thread packages/shared/src/types/agent.ts
Comment thread scripts/regressions/open-issues.regression.ts
Comment thread scripts/regressions/regeneration-context.regression.ts
@SpicyMarinara SpicyMarinara changed the title fix: address July 30 issue sweep fix: trim card names, scope agent context, and render Markdown Jul 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/server/src/services/agents/agent-executor.ts (2)

1268-1302: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include recalled-memory vector context in batched agent prompts.

buildBatchSystemPrompt assembles lore/extras from the batch’s selected sources, but the batch call only renders that merged prompt and does not append buildCustomAgentVectorContextBlock. Since that helper is only used in the standard single-agent path, agents with recalledMemories enabled won’t get their <vector_context> block in combined batch calls. Add equivalent vector-context assembly for batch configs or merge the block into the batch system prompt.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/server/src/services/agents/agent-executor.ts` around lines 1268 -
1302, Update buildBatchSystemPrompt to include recalled-memory vector context
for batch configs by assembling the equivalent
buildCustomAgentVectorContextBlock output and merging it into the generated
system prompt. Ensure agents with recalledMemories enabled receive a
<vector_context> block in combined calls while preserving existing lore and
extras assembly.

83-100: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Make isCustomAgent required at the prompt boundary.

isCustomAgent is optional, and getAgentContextSources treats undefined as a built-in agent, returning ALL_AGENT_CONTEXT_SOURCES. A custom-agent config that omits this field will ignore saved settings.contextSources and send unrelated prompt context to the model. Make the discriminator required, with explicit false for built-ins, or assert custom-agent configs before prompt assembly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/server/src/services/agents/agent-executor.ts` around lines 83 - 100,
Make isCustomAgent required in the prompt-boundary configuration and update all
built-in agent call sites to pass false explicitly, ensuring custom-agent
configurations cannot omit the discriminator and bypass settings.contextSources.
Update getAgentContextSources and related AgentExecConfig types as needed while
preserving normalized custom sources and ALL_AGENT_CONTEXT_SOURCES for explicit
built-ins.
packages/server/src/services/storage/characters.storage.ts (1)

509-518: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Normalize the pre-restore snapshot as well.

restoredData is normalized, but currentData remains raw and is serialized at Line [518]. Restoring over a legacy padded name therefore leaves that padded value in version history, and the comparison can create an unnecessary snapshot.

Normalize currentData before both the comparison and insertion:

Proposed fix
-        const currentData = parseCharacterData(existing.data);
+        const currentData = normalizeCharacterData(parseCharacterData(existing.data));

This keeps the restore path aligned with the PR’s name-normalization objective.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/server/src/services/storage/characters.storage.ts` around lines 509
- 518, Normalize currentData before the alreadyMatches comparison and before
serializing it in the character card version insert within the restore flow. Use
the normalized current value alongside restoredData so legacy padded names do
not trigger unnecessary snapshots or remain in version history.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/regressions/open-issues.regression.ts`:
- Around line 559-577: Update the restoreVersion regression fixture so the
current character row’s name is padded before restoration, ensuring the
transactional pre-restore snapshot exercises legacy normalization. After calling
restoreVersion, query the inserted characterCardVersions record with source
"restore" and assert its stored JSON name is trimmed, while retaining the
existing restored-card assertion as appropriate.

In `@scripts/regressions/regeneration-context.regression.ts`:
- Around line 248-251: Replace the dynamic RegExp assertions in the regression
test with direct substring assertions using includes for both editedLine and
originalLine checks. Keep the existing positive and negative assertion behavior
around rebuiltEditedChunk.content unchanged.

---

Outside diff comments:
In `@packages/server/src/services/agents/agent-executor.ts`:
- Around line 1268-1302: Update buildBatchSystemPrompt to include
recalled-memory vector context for batch configs by assembling the equivalent
buildCustomAgentVectorContextBlock output and merging it into the generated
system prompt. Ensure agents with recalledMemories enabled receive a
<vector_context> block in combined calls while preserving existing lore and
extras assembly.
- Around line 83-100: Make isCustomAgent required in the prompt-boundary
configuration and update all built-in agent call sites to pass false explicitly,
ensuring custom-agent configurations cannot omit the discriminator and bypass
settings.contextSources. Update getAgentContextSources and related
AgentExecConfig types as needed while preserving normalized custom sources and
ALL_AGENT_CONTEXT_SOURCES for explicit built-ins.

In `@packages/server/src/services/storage/characters.storage.ts`:
- Around line 509-518: Normalize currentData before the alreadyMatches
comparison and before serializing it in the character card version insert within
the restore flow. Use the normalized current value alongside restoredData so
legacy padded names do not trigger unnecessary snapshots or remain in version
history.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 860549b8-5904-4d54-b084-dccbb1187638

📥 Commits

Reviewing files that changed from the base of the PR and between 5b45bea and 7dc15cf.

📒 Files selected for processing (6)
  • packages/client/src/components/agents/AgentEditor.tsx
  • packages/client/src/components/characters/CharacterEditor.tsx
  • packages/server/src/services/agents/agent-executor.ts
  • packages/server/src/services/storage/characters.storage.ts
  • scripts/regressions/open-issues.regression.ts
  • scripts/regressions/regeneration-context.regression.ts

Comment thread scripts/regressions/open-issues.regression.ts
Comment thread scripts/regressions/regeneration-context.regression.ts Outdated
@SpicyMarinara

Copy link
Copy Markdown
Collaborator Author

CodeRabbit incremental outside-diff follow-up:

  • Applied the required isCustomAgent discriminator and propagated it through Knowledge Retrieval/Router configs in 95fccca7d.
  • Applied normalization of the transactional pre-restore snapshot in 95fccca7d.
  • Did not add vector context to ordinary batched prompts: shouldRunAgentIndividually already isolates every agent with access_vectors, so such an agent cannot reach buildBatchSystemPrompt. Adding the block there would broaden or duplicate context without a reachable consumer.

Validation after these changes: pnpm check, prompt regression, and edited-message/memory regression pass.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/server/src/services/agents/agent-executor.ts (1)

1091-1097: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant getBatchContextSources(configs) computation.

executeAgentBatch computes batchContextSources from configs at line 1097, then buildBatchSystemPrompt (called with the same configs) recomputes the identical union at line 1268. Since getBatchContextSources is pure and configs doesn't change between the two calls, consider threading the already-computed value into buildBatchSystemPrompt instead of recomputing it.

♻️ Proposed refactor
 function buildBatchSystemPrompt(
   configs: AgentExecConfig[],
   context: AgentContext,
   renderedTemplates?: RenderedAgentTemplateMap,
+  contextSources: CustomAgentContextSources = getBatchContextSources(configs),
 ): string {
   const parts: string[] = [];
-  const contextSources = getBatchContextSources(configs);

And pass batchContextSources from executeAgentBatch's call site:

-    const systemPrompt = buildBatchSystemPrompt(configs, context, renderedTemplates);
+    const batchContextSources = getBatchContextSources(configs);
+    const systemPrompt = buildBatchSystemPrompt(configs, context, renderedTemplates, batchContextSources);

Also applies to: 1262-1268

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/server/src/services/agents/agent-executor.ts` around lines 1091 -
1097, Remove the redundant getBatchContextSources computation by extending
buildBatchSystemPrompt to accept the precomputed batchContextSources value. Pass
that value from executeAgentBatch at its call site, and use the parameter inside
buildBatchSystemPrompt instead of recomputing the union from configs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/server/src/services/agents/agent-executor.ts`:
- Around line 1091-1097: Remove the redundant getBatchContextSources computation
by extending buildBatchSystemPrompt to accept the precomputed
batchContextSources value. Pass that value from executeAgentBatch at its call
site, and use the parameter inside buildBatchSystemPrompt instead of recomputing
the union from configs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 0fad529a-2af9-49c9-9d63-c1e64f200c16

📥 Commits

Reviewing files that changed from the base of the PR and between 7dc15cf and 95fccca.

📒 Files selected for processing (6)
  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/services/agents/agent-executor.ts
  • packages/server/src/services/storage/characters.storage.ts
  • scripts/regressions/open-issues.regression.ts
  • scripts/regressions/prompt.regression.ts
  • scripts/regressions/regeneration-context.regression.ts

@SpicyMarinara

Copy link
Copy Markdown
Collaborator Author

Final CodeRabbit follow-up: I am not applying the low-value getBatchContextSources parameter-threading refactor. The helper unions eight booleans once per batch, and keeping context-source derivation inside buildBatchSystemPrompt preserves the function’s self-contained contract without measurable cost. This is intentionally left simple per the scope of the issue sweep.

@SpicyMarinara
SpicyMarinara merged commit f541064 into staging Jul 30, 2026
27 of 33 checks passed
@SpicyMarinara
SpicyMarinara deleted the agent/4303-4306-issue-sweep branch July 30, 2026 14:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant