Skip to content

🐛 fix(input): revert #11755 to fix chat input unfocus#11764

Merged
arvinxx merged 1 commit intonextfrom
fix/selection
Jan 24, 2026
Merged

🐛 fix(input): revert #11755 to fix chat input unfocus#11764
arvinxx merged 1 commit intonextfrom
fix/selection

Conversation

@arvinxx
Copy link
Copy Markdown
Member

@arvinxx arvinxx commented Jan 24, 2026

💻 Change Type

  • ✨ feat
  • 🐛 fix
  • ♻️ refactor
  • 💄 style
  • 👷 build
  • ⚡️ perf
  • ✅ test
  • 📝 docs
  • 🔨 chore

🔗 Related Issue

@Innei #11755 PR 导致输入文本后就直接失焦,我先回滚了。然后你需要针对这个场景补一个 E2E 用例确保不会有 regression

🔀 Description of Change

🧪 How to Test

  • Tested locally
  • Added/updated tests
  • No tests needed

📸 Screenshots / Videos

Before After
... ...

📝 Additional Information

Summary by Sourcery

Revert prior changes that persisted editor content across rich text toggle for cron job content and chat input, restoring simpler editor initialization behavior without shared content refs.

Enhancements:

  • Simplify cron job content editor by initializing document content directly on editor readiness instead of using an external ref for persistence.
  • Simplify chat input provider and editor state by removing the shared contentRef mechanism from the store and components.

@dosubot dosubot bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jan 24, 2026
@vercel
Copy link
Copy Markdown

vercel bot commented Jan 24, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
lobehub Canceled Canceled Jan 24, 2026 1:52am

Request Review

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Jan 24, 2026

Reviewer's Guide

Reverts the previous input markdown crash workaround by removing contentRef-based persistence and key-driven remounting of editors, and instead initializes editor content via effects while simplifying chat input provider and editor wiring.

Sequence diagram for CronJobContentEditor initialization and content change

sequenceDiagram
  actor User
  participant CronJobContentEditor
  participant useEditorHook as useEditor
  participant EditorInstance as Editor

  User->>CronJobContentEditor: Mount component with enableRichRender, initialValue, onChange
  CronJobContentEditor->>useEditorHook: useEditor()
  useEditorHook-->>CronJobContentEditor: editor (possibly undefined)

  rect rgb(235, 235, 235)
    CronJobContentEditor->>CronJobContentEditor: useEffect sync currentValueRef with initialValue
  end

  CronJobContentEditor->>CronJobContentEditor: useEffect on [editor, enableRichRender, initialValue]
  CronJobContentEditor->>EditorInstance: setTimeout(100ms) setDocument(mode, initialValue)
  note over EditorInstance: mode = markdown if enableRichRender else text

  CronJobContentEditor-->>EditorInstance: setDocument may throw error
  EditorInstance-->>CronJobContentEditor: error
  CronJobContentEditor->>CronJobContentEditor: catch error, log to console
  CronJobContentEditor->>EditorInstance: setTimeout(100ms) retry setDocument(mode, initialValue)

  User->>EditorInstance: Type content
  EditorInstance-->>CronJobContentEditor: onTextChange event

  CronJobContentEditor->>CronJobContentEditor: handleContentChange(event)
  CronJobContentEditor->>EditorInstance: getDocument(mode)
  EditorInstance-->>CronJobContentEditor: nextContent
  CronJobContentEditor->>CronJobContentEditor: compute finalContent
  CronJobContentEditor->>CronJobContentEditor: compare finalContent with currentValueRef.current
  alt content changed
    CronJobContentEditor->>CronJobContentEditor: update currentValueRef.current
    CronJobContentEditor-->>User: onChange(finalContent)
  else content unchanged
    CronJobContentEditor->>CronJobContentEditor: do nothing
  end
Loading

Class diagram for updated editor and chat input components

classDiagram
  class CronJobContentEditor {
    +boolean enableRichRender
    +string initialValue
    +onChange(value string) void
    -RefObject currentValueRef
    -editor any
    +handleContentChange(event any) void
  }

  class ChatInputProvider {
    +string agentId
    +ReactNode children
    +any leftActions
    +any rightActions
    +boolean mobile
    +any mentionItems
    +boolean allowExpand
    -editor any
    +createStore(config any) any
  }

  class InputEditor {
    +number defaultRows
    -any editor
    -any slashMenuRef
    -any send
    -updateMarkdownContent() void
    -expand() void
    -any mentionItems
    -onBlur() void
    -onChange() void
    -onCompositionEnd() void
    -onCompositionStart() void
    -onFocus() void
    -onInit(editor any) void
    -onPressEnter(payload any) void
  }

  class ChatInputStoreState {
    +boolean allowExpand
    +any editor
    +boolean isContentEmpty
    +string markdownContent
    +any mentionItems
    +any slashMenuRef
    +expand() void
    +send() void
    +updateMarkdownContent() void
  }

  ChatInputProvider --> ChatInputStoreState : creates store with
  InputEditor --> ChatInputStoreState : uses state via useChatInputStore
  InputEditor --> ChatInputProvider : rendered inside
  CronJobContentEditor --> EditorInstance : uses via useEditor

  class EditorInstance {
    +setDocument(mode string, content string) void
    +getDocument(mode string) string
  }
Loading

File-Level Changes

Change Details Files
Simplified Cron job content editor and switched to effect-based initialization instead of parent content refs and key-based remounts.
  • Removed CronJobContentEditorInner wrapper and merged logic into a single memoized CronJobContentEditor component.
  • Eliminated contentRef prop and associated restoration logic for persisting editor content across remounts.
  • Added a useEffect to initialize the editor document when the editor instance becomes available, with a delayed setDocument call and error handling.
  • Stopped passing onInit to Editor and now rely solely on handleContentChange for propagating edits upstream.
src/app/[variants]/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsx
Simplified ChatInputProvider so it no longer manages a shared contentRef for cross-remount persistence.
  • Removed ChatInputProviderInner and exported a single memoized ChatInputProvider component.
  • Dropped contentRef from the provider props and store creation parameters.
  • Removed dependency on enableInputMarkdown for forcing remounts via key and deleted the local ref used to persist content.
src/features/ChatInput/ChatInputProvider.tsx
Removed contentRef-based persistence and rehydration from the chat input editor and store state.
  • Stopped selecting contentRef from the chat input store and removed it from the selector tuple.
  • Simplified InputEditor onChange handler to only call updateMarkdownContent without updating a parent ref.
  • Simplified onInit to only store the editor instance without restoring from a contentRef.
  • Dropped contentRef from the chat input store State interface.
src/features/ChatInput/InputEditor/index.tsx
src/features/ChatInput/store/initialState.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gru-agent
Copy link
Copy Markdown
Contributor

gru-agent bot commented Jan 24, 2026

TestGru Assignment

Summary

Link CommitId Status Reason
Detail 87e22ba5ae22c2f16a5bd49485879d74d146050d 🚫 Skipped No files need to be tested {"src/app/[variants]/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsx":"File path does not match include patterns.","src/features/ChatInput/ChatInputProvider.tsx":"File path does not match include patterns.","src/features/ChatInput/InputEditor/index.tsx":"File path does not match include patterns.","src/features/ChatInput/store/initialState.ts":"File path does not match include patterns."}

History Assignment

Tip

You can @gru-agent and leave your feedback. TestGru will make adjustments based on your input

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In CronJobContentEditor, the initialization useEffect schedules a setTimeout on every change to editor, enableRichRender, or initialValue without cleanup, which can lead to multiple overlapping setDocument calls; consider storing the timeout id and clearing it in a cleanup function or restructuring to run only once when the editor becomes ready.
  • The try/catch in the CronJobContentEditor initialization effect schedules the same setTimeout logic both in the happy path and in the catch block, making the error handling redundant; you can simplify this by moving the timeout logic outside the try/catch or by logging the error without re-running the same code.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `CronJobContentEditor`, the initialization `useEffect` schedules a `setTimeout` on every change to `editor`, `enableRichRender`, or `initialValue` without cleanup, which can lead to multiple overlapping `setDocument` calls; consider storing the timeout id and clearing it in a cleanup function or restructuring to run only once when the editor becomes ready.
- The try/catch in the `CronJobContentEditor` initialization effect schedules the same `setTimeout` logic both in the happy path and in the catch block, making the error handling redundant; you can simplify this by moving the timeout logic outside the try/catch or by logging the error without re-running the same code.

## Individual Comments

### Comment 1
<location> `src/app/[variants]/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsx:35-43` </location>
<code_context>
     }, [initialValue]);

+    // Initialize editor content when editor is ready
+    useEffect(() => {
+      if (!editor) return;
+      try {
+        setTimeout(() => {
+          if (initialValue) {
+            editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);
+          }
+        }, 100);
+      } catch (error) {
+        console.error('[CronJobContentEditor] Failed to initialize editor content:', error);
+        setTimeout(() => {
</code_context>

<issue_to_address>
**suggestion (bug_risk):** The try/catch around `setTimeout` will not catch errors thrown inside the callback and duplicates the initialization logic.

Because the `try/catch` only wraps the `setTimeout` call, any error thrown by `editor.setDocument` inside the callback will escape. The catch then schedules another `setTimeout` with the same logic, causing potential duplicate execution and making control flow unclear. Instead, keep a single `setTimeout` and wrap `editor.setDocument` in a `try/catch` inside its callback, optionally adding a guard (e.g., a ref or checking current content) to avoid re-initializing an already-populated editor.

Suggested implementation:

```typescript
    const { t } = useTranslation('setting');
    const editor = useEditor();
    const currentValueRef = useRef(initialValue);
    const hasInitializedRef = useRef(false);

```

```typescript
    // Initialize editor content when editor is ready
    useEffect(() => {
      if (!editor || hasInitializedRef.current) return;

      setTimeout(() => {
        try {
          if (!initialValue || hasInitializedRef.current) return;

          editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);
          hasInitializedRef.current = true;
        } catch (error) {
          console.error(
            '[CronJobContentEditor] Failed to initialize editor content:',
            error,
          );
        }
      }, 100);

```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +35 to +43
useEffect(() => {
if (!editor) return;
try {
setTimeout(() => {
if (initialValue) {
editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);
}
}, 100);
} catch (error) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): The try/catch around setTimeout will not catch errors thrown inside the callback and duplicates the initialization logic.

Because the try/catch only wraps the setTimeout call, any error thrown by editor.setDocument inside the callback will escape. The catch then schedules another setTimeout with the same logic, causing potential duplicate execution and making control flow unclear. Instead, keep a single setTimeout and wrap editor.setDocument in a try/catch inside its callback, optionally adding a guard (e.g., a ref or checking current content) to avoid re-initializing an already-populated editor.

Suggested implementation:

    const { t } = useTranslation('setting');
    const editor = useEditor();
    const currentValueRef = useRef(initialValue);
    const hasInitializedRef = useRef(false);
    // Initialize editor content when editor is ready
    useEffect(() => {
      if (!editor || hasInitializedRef.current) return;

      setTimeout(() => {
        try {
          if (!initialValue || hasInitializedRef.current) return;

          editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);
          hasInitializedRef.current = true;
        } catch (error) {
          console.error(
            '[CronJobContentEditor] Failed to initialize editor content:',
            error,
          );
        }
      }, 100);

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

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: 87e22ba5ae

ℹ️ 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 +35 to +41
useEffect(() => {
if (!editor) return;
try {
setTimeout(() => {
if (initialValue) {
editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve draft content when reinitializing the editor

The effect re-seeds the editor from initialValue every time enableRichRender toggles, but initialValue is sourced from cronJob?.content and doesn’t reflect in-progress edits until auto‑save completes. If a user edits a cron job and then flips the input‑markdown setting before the draft is saved, this setDocument call overwrites the unsaved text with the last persisted content, effectively discarding edits. Consider restoring from the current editor/draft state instead of initialValue on render‑mode changes.

Useful? React with 👍 / 👎.

@codecov
Copy link
Copy Markdown

codecov bot commented Jan 24, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 74.43%. Comparing base (42339cd) to head (55a3fd6).
⚠️ Report is 3 commits behind head on next.

Additional details and impacted files
@@            Coverage Diff            @@
##             next   #11764     +/-   ##
=========================================
  Coverage   74.43%   74.43%             
=========================================
  Files        1191     1191             
  Lines       94492    94492             
  Branches    10474    12940   +2466     
=========================================
  Hits        70335    70335             
  Misses      24067    24067             
  Partials       90       90             
Flag Coverage Δ
app 67.58% <ø> (ø)
database 91.48% <ø> (ø)
packages/agent-runtime 90.20% <ø> (ø)
packages/context-engine 85.33% <ø> (ø)
packages/conversation-flow 92.28% <ø> (ø)
packages/file-loaders 87.04% <ø> (ø)
packages/memory-user-memory 69.30% <ø> (ø)
packages/model-bank 100.00% <ø> (ø)
packages/model-runtime 86.69% <ø> (ø)
packages/prompts 79.33% <ø> (ø)
packages/python-interpreter 92.90% <ø> (ø)
packages/ssrf-safe-fetch 0.00% <ø> (ø)
packages/utils 93.16% <ø> (ø)
packages/web-crawler 95.62% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
Store 67.99% <ø> (ø)
Services 50.69% <ø> (ø)
Server 68.51% <ø> (ø)
Libs 39.99% <ø> (ø)
Utils 93.60% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@arvinxx arvinxx changed the title Revert "🐛 fix(editor): prevent crash when toggling enableInputMarkdown setting (#11755)" 🐛 fix(input): revert #11755 to fix chat input unfocus Jan 24, 2026
@arvinxx arvinxx merged commit 90ecaf6 into next Jan 24, 2026
41 checks passed
@arvinxx arvinxx deleted the fix/selection branch January 24, 2026 02:05
@lobehubbot
Copy link
Copy Markdown
Member

❤️ Great PR @arvinxx ❤️

The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our discord and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world.

@lobehubbot
Copy link
Copy Markdown
Member

🎉 This PR is included in version 2.0.0-next.359 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released on @next size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants