Skip to content

fix(ui): guard MarkdownEditor against null values in setMarkdown#25

Open
namastex888 wants to merge 6 commits into
masterfrom
dev
Open

fix(ui): guard MarkdownEditor against null values in setMarkdown#25
namastex888 wants to merge 6 commits into
masterfrom
dev

Conversation

@namastex888

@namastex888 namastex888 commented Mar 18, 2026

Copy link
Copy Markdown
Collaborator

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

    • Preserve empty form inputs in agent edits.
    • Prevent undefined values in the Markdown editor to improve stability.
  • New Features

    • CLI parses YAML frontmatter more robustly and handles parse errors.
    • CLI creation flows exit early and notify when an agent is pending approval.
  • Chores

    • Role permission lookup centralized to shared definitions.

automagik-genie and others added 3 commits March 18, 2026 14:07
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

@greptile-apps greptile-apps 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.

namastex888 has reached the 50-review limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, 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

  • UI Crash Fix: Resolved a TypeError: Cannot read properties of null (reading 'trim') that occurred when the MarkdownEditor received null values, specifically on the agent configuration page.
  • Nullish Coalescing Operator Adoption: Replaced logical OR (||) with the nullish coalescing operator (??) in AgentConfigForm's onChange handlers and MarkdownEditor's setMarkdown calls and markdown prop to explicitly handle null or undefined values.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai

coderabbitai Bot commented Mar 18, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d0288bf9-95ed-4b23-9b33-0d7235f3e151

📥 Commits

Reviewing files that changed from the base of the PR and between 28c8f36 and b436e39.

📒 Files selected for processing (1)
  • ui/src/components/MarkdownEditor.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • ui/src/components/MarkdownEditor.tsx

📝 Walkthrough

Walkthrough

UI 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 pending_approval, and member role logic now imports shared role presets.

Changes

Cohort / File(s) Summary
UI — Form handlers
ui/src/components/AgentConfigForm.tsx
Switched `
UI — Markdown editor
ui/src/components/MarkdownEditor.tsx
Guarded editor inputs with value ?? "" and used latestValueRef.current ?? "" to avoid passing undefined into markdown processing and replacements.
CLI — Dependencies
cli/package.json
Added runtime deps @paperclipai/adapter-openclaw-gateway, js-yaml and dev dep @types/js-yaml; minor reordering of existing deps.
CLI — Agent command
cli/src/commands/client/agent.ts
Replaced manual frontmatter parsing with js-yaml (yaml.load) and robust error handling; preserved capability fallback heuristics; added early-exit behavior after create/import when agent status === "pending_approval" with JSON or message output.
CLI — Member command
cli/src/commands/client/member.ts
Removed local role presets; now imports ROLE_PRESETS, MEMBERSHIP_ROLES, and MembershipRole from @paperclipai/shared and maps grants to { permissionKey } shape.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰
I nibble YAML, keep each empty string bright,
?? holds the gaps through the soft editor light.
CLI reads the doc, then waits by the gate—
If approval's pending, I patiently wait. 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title focuses on guarding MarkdownEditor against null values in setMarkdown, which aligns with changes in MarkdownEditor.tsx. However, the changeset includes substantial modifications to AgentConfigForm.tsx, agent.ts, member.ts, and package.json dependencies that are not mentioned or implied by the title. Update the title to reflect all major changes, such as: 'fix: guard null values in MarkdownEditor and improve YAML parsing in agent configuration' or provide a more comprehensive description.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dev
📝 Coding Plan
  • Generate coding plan for human review comments

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 and usage tips.

@gemini-code-assist gemini-code-assist 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.

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.

Comment thread ui/src/components/MarkdownEditor.tsx Outdated
if (updated !== current) {
latestValueRef.current = updated;
ref.current?.setMarkdown(updated);
ref.current?.setMarkdown(updated ?? "");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

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.

Comment thread ui/src/components/MarkdownEditor.tsx Outdated
if (next !== current) {
latestValueRef.current = next;
ref.current?.setMarkdown(next);
ref.current?.setMarkdown(next ?? "");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

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)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

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.

Suggested change
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Similar to the other change, since v is a string, v ?? undefined is equivalent to v. This can be simplified for clarity.

Suggested change
mark("adapterConfig", "bootstrapPromptTemplate", v ?? undefined)
mark("adapterConfig", "bootstrapPromptTemplate", v)

…-missing

fix(cli): address PR review feedback — yaml parser, pending_approval guard, shared imports

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between e24a90a and 28c8f36.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • cli/package.json
  • cli/src/commands/client/agent.ts
  • cli/src/commands/client/member.ts

Comment on lines +757 to +768
// 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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

Suggested change
// 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>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment on lines +228 to +229
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
if (value != null) result[key] = String(value);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants