fix(ui): guard MarkdownEditor against null values in setMarkdown#25
fix(ui): guard MarkdownEditor against null values in setMarkdown#25namastex888 wants to merge 6 commits into
Conversation
Prevents TypeError crash when agent config page renders markdown fields with null values. Adds ?? "" defensive guards in MarkdownEditor and changes || to ?? in AgentConfigForm onChange handlers for markdown-backed fields. Closes paperclipai#1227
…guard, shared imports - Replace custom YAML frontmatter parser with js-yaml library - Add pending_approval guard in local-cli --create flow: skip key creation and exit cleanly when agent requires board approval - Remove redundant startsWith check in tryParseJson - Import ROLE_PRESETS from @paperclipai/shared instead of duplicating - Add clarifying comment on SOUL.md capabilities heuristic Co-Authored-By: Paperclip <noreply@paperclip.ing>
fix(ui): guard MarkdownEditor against null values in setMarkdown
There was a problem hiding this comment.
namastex888 has reached the 50-review limit for trial accounts. To continue receiving code reviews, upgrade your plan.
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a critical fix to prevent a UI crash in the MarkdownEditor component. By adopting the nullish coalescing operator, the editor now gracefully handles potentially null or undefined input values, enhancing the stability and reliability of the agent configuration page. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. Footnotes
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughUI preserves empty-string values in form and editor flows; CLI adds YAML frontmatter parsing, new dependencies, improved agent import/create handling that early-exits on Changes
Sequence Diagram(s)sequenceDiagram
participant CLI
participant FS
participant YAML as "js-yaml"
participant API as "Agent Service"
CLI->>FS: read agent markdown/frontmatter
CLI->>YAML: yaml.load(frontmatter)
YAML-->>CLI: parsed metadata (or null on error)
CLI->>API: create/import agent with metadata
API-->>CLI: returns agent (status)
alt status == "pending_approval"
CLI->>CLI: output { pendingApproval: true } (JSON) or show message and exit
else
CLI->>CLI: continue normal processing (list/show details)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
There was a problem hiding this comment.
Code Review
This pull request aims to fix a crash in MarkdownEditor by guarding against null values. The changes in MarkdownEditor.tsx to handle potentially null value props are correct. However, I've identified two critical issues where a null value from latestValueRef.current can still cause a crash before your safeguards are reached. My review includes comments with details on how to fix these potential TypeError exceptions. Additionally, I've provided a couple of suggestions in AgentConfigForm.tsx to simplify the code where ?? is used on variables that are already guaranteed to be strings.
| if (updated !== current) { | ||
| latestValueRef.current = updated; | ||
| ref.current?.setMarkdown(updated); | ||
| ref.current?.setMarkdown(updated ?? ""); |
There was a problem hiding this comment.
This change correctly adds a safeguard, but a TypeError can still occur on line 263 before this line is reached. If latestValueRef.current is null, current.replace(...) will crash. The null check should happen before the .replace() call.
I recommend changing the code around line 263 to:
const current = latestValueRef.current ?? "";
const updated = current.replace(
new RegExp(`(!\\[[^\]]*\\]\\(${escapedSrc}\\))(?!\\n\\n)`, "g"),
"$1\n\n",
);With this change, updated will always be a string, and the ?? "" on the current line can be removed.
| if (next !== current) { | ||
| latestValueRef.current = next; | ||
| ref.current?.setMarkdown(next); | ||
| ref.current?.setMarkdown(next ?? ""); |
There was a problem hiding this comment.
Similar to another part of this file, this safeguard is in the right direction but a crash can occur on line 395 before this line is executed. The applyMention function expects a string, but current (from latestValueRef.current) can be null, which will cause a TypeError inside applyMention.
To fix this, you should ensure a string is passed to applyMention:
const next = applyMention(current ?? "", state.query, option);This ensures next is always a string, so the ?? "" on the current line can be removed.
| <MarkdownEditor | ||
| value={eff("identity", "capabilities", props.agent.capabilities ?? "")} | ||
| onChange={(v) => mark("identity", "capabilities", v || null)} | ||
| onChange={(v) => mark("identity", "capabilities", v ?? null)} |
There was a problem hiding this comment.
Since v is a string from MarkdownEditor's onChange callback, it will not be null or undefined. Therefore, v ?? null is equivalent to just v. You can simplify this for clarity.
| onChange={(v) => mark("identity", "capabilities", v ?? null)} | |
| onChange={(v) => mark("identity", "capabilities", v)} |
| )} | ||
| onChange={(v) => | ||
| mark("adapterConfig", "bootstrapPromptTemplate", v || undefined) | ||
| mark("adapterConfig", "bootstrapPromptTemplate", v ?? undefined) |
…-missing fix(cli): address PR review feedback — yaml parser, pending_approval guard, shared imports
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cli/src/commands/client/agent.ts`:
- Around line 757-768: The pending-approval guard currently only returns when
the agent was just created; move or duplicate the check so that any path that
loads an agentRow with agentRow.status === "pending_approval" exits before
attempting key creation. Concretely, locate the logic that loads agentRow (the
variable agentRow) and ensure the same if (agentRow.status ===
"pending_approval") { ... return; } block runs immediately after
loading/fetching the agentRow (before any key creation calls), preserving the
existing ctx.json and console output behavior so key creation is never attempted
for agents already pending approval.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 55a37a60-caf8-4be7-afd4-ddf725373f6f
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (3)
cli/package.jsoncli/src/commands/client/agent.tscli/src/commands/client/member.ts
| // If the agent is pending board approval, key creation will be | ||
| // rejected (409). Exit early and let the user retry after approval. | ||
| if (agentRow.status === "pending_approval") { | ||
| if (ctx.json) { | ||
| printOutput({ agent: { id: agentRow.id, name: agentRow.name, status: agentRow.status }, pendingApproval: true }, { json: true }); | ||
| } else { | ||
| console.log( | ||
| pc.yellow("Agent created but pending board approval. Run `agent local-cli` again after approval."), | ||
| ); | ||
| } | ||
| return; | ||
| } |
There was a problem hiding this comment.
Pending-approval guard is scoped too narrowly.
At Line 759, the early return only runs when the agent was just created in this command. If an existing agent is already pending_approval, execution still reaches key creation and fails (the exact path this guard is trying to avoid).
💡 Proposed fix
- // If the agent is pending board approval, key creation will be
- // rejected (409). Exit early and let the user retry after approval.
- if (agentRow.status === "pending_approval") {
- if (ctx.json) {
- printOutput({ agent: { id: agentRow.id, name: agentRow.name, status: agentRow.status }, pendingApproval: true }, { json: true });
- } else {
- console.log(
- pc.yellow("Agent created but pending board approval. Run `agent local-cli` again after approval."),
- );
- }
- return;
- }
}
+ // If the agent is pending board approval, key creation will be
+ // rejected (409). Exit early for both newly created and existing agents.
+ if (agentRow.status === "pending_approval") {
+ if (ctx.json) {
+ printOutput(
+ { agent: { id: agentRow.id, name: agentRow.name, status: agentRow.status }, pendingApproval: true },
+ { json: true },
+ );
+ } else {
+ console.log(
+ pc.yellow("Agent is pending board approval. Run `agent local-cli` again after approval."),
+ );
+ }
+ return;
+ }
+
// --- Normal local-cli flow: generate key + install skills ---📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // If the agent is pending board approval, key creation will be | |
| // rejected (409). Exit early and let the user retry after approval. | |
| if (agentRow.status === "pending_approval") { | |
| if (ctx.json) { | |
| printOutput({ agent: { id: agentRow.id, name: agentRow.name, status: agentRow.status }, pendingApproval: true }, { json: true }); | |
| } else { | |
| console.log( | |
| pc.yellow("Agent created but pending board approval. Run `agent local-cli` again after approval."), | |
| ); | |
| } | |
| return; | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@cli/src/commands/client/agent.ts` around lines 757 - 768, The
pending-approval guard currently only returns when the agent was just created;
move or duplicate the check so that any path that loads an agentRow with
agentRow.status === "pending_approval" exits before attempting key creation.
Concretely, locate the logic that loads agentRow (the variable agentRow) and
ensure the same if (agentRow.status === "pending_approval") { ... return; }
block runs immediately after loading/fetching the agentRow (before any key
creation calls), preserving the existing ctx.json and console output behavior so
key creation is never attempted for agents already pending approval.
…lace() and applyMention latestValueRef.current could be null when accessed inside setTimeout (image upload callback) and replaceMentionFromMarkdown, causing a crash on .replace() and .lastIndexOf() respectively. Add `?? ""` null coalescing at the two assignment sites and remove the now-redundant `?? ""` on downstream setMarkdown calls where the value is already guaranteed to be a string. Co-Authored-By: Paperclip <noreply@paperclip.ing>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 28c8f3630f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) { | ||
| if (value != null) result[key] = String(value); |
There was a problem hiding this comment.
Preserve object-valued frontmatter when parsing
yaml.load already converts adapterConfig/runtimeConfig frontmatter like adapterConfig: {"cwd":"/repo"} into objects, but this code stringifies every parsed value, turning those objects into "[object Object]". The downstream tryParseJson(...) then returns null, so agent import silently drops adapter/runtime config and can create unusable agents (missing command/cwd/env). This is a regression from the previous parser, which preserved inline JSON strings for these fields.
Useful? React with 👍 / 👎.
…rd-v2 fix(ui): guard MarkdownEditor against null latestValueRef
Summary
Merges the MarkdownEditor null crash fix from dev to master.
Fixes
TypeError: Cannot read properties of null (reading 'trim')on the agent configuration page. See #24 for details.Also submitted upstream: paperclipai#1230
Summary by CodeRabbit
Bug Fixes
New Features
Chores