Skip to content

feat: add visual editing mode for chat configurations - #1684

Closed
HynoR wants to merge 1 commit into
QuantumNous:alphafrom
HynoR:feat/chatjson
Closed

HynoR wants to merge 1 commit into
QuantumNous:alphafrom
HynoR:feat/chatjson

Conversation

@HynoR

@HynoR HynoR commented Aug 28, 2025 •

Copy link
Copy Markdown
Contributor

聊天设置可以可视化编辑
image

Summary by CodeRabbit

  • New Features
    • Introduced dual editing modes for chat configurations: JSON editor and a new visual table view.
    • Visual mode includes searchable list of configurations (name and URL) with add, edit, and delete actions.
    • Added modal-based creation and editing with field validation.
    • Added mode toggle controls and UI enhancements (icons, divider).
    • Included an in-app banner with guidance on URL replacement keys/addresses.
    • Improved synchronization between visual and JSON representations.

@coderabbitai

coderabbitai Bot commented Aug 28, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Introduces a dual-mode chat configuration editor (JSON and visual), adds table-based management with search/add/edit/delete via a modal, implements JSON↔configs transformations and synchronization via state and effects, updates onSubmit with added logging, and expands imports/UI elements. No exported/public signatures changed.

Changes

Cohort / File(s) Summary
Dual-mode editor & UI components
web/src/pages/Setting/Chat/SettingsChats.jsx
Adds RadioGroup to switch JSON/visual modes; introduces Table-based list with search, add, edit, delete; Modal form for create/edit; Divider and Banner; imports UI elements and icons.
Data transformation & sync logic
.../SettingsChats.jsx
Implements jsonToConfigs, configsToJson, syncJsonToConfigs, syncConfigsToJson to keep JSON textarea and visual list consistent.
State management & effects
.../SettingsChats.jsx
Adds states: editMode, chatConfigs, modalVisible, editingConfig, isEdit, searchText, modalFormRef; useEffect hooks to initialize/sync on props.options changes and mode switches.
Submission pathway
.../SettingsChats.jsx
Maintains existing server update via form API with added debug logs; compareObjects flow unchanged functionally.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant SC as SettingsChats
  participant VE as Visual Editor (Table/Modal)
  participant JE as JSON Editor (Textarea)
  participant SY as Sync Utils (json↔configs)
  participant API as Server/API

  Note over SC: Init with props.options
  SC->>SY: jsonToConfigs(JSON from options)
  SY-->>SC: [{id,name,url},...]
  SC->>JE: Set textarea value
  SC->>VE: Set table data

  alt Switch to Visual Mode
    U->>SC: Select "Visual" mode
    SC->>VE: Show table/search/actions
  else Switch to JSON Mode
    U->>SC: Select "JSON" mode
    SC->>JE: Show textarea
  end

  rect rgba(200,255,200,0.2)
  Note over VE: Create/Edit flow
  U->>VE: Click Add/Edit
  VE->>U: Open Modal (form: name, url)
  U->>VE: Submit form
  VE->>SC: Update chatConfigs
  SC->>SY: configsToJson(chatConfigs)
  SY-->>SC: JSON string
  SC->>JE: Sync textarea with JSON
  end

  rect rgba(200,200,255,0.2)
  Note over JE: Direct JSON edit
  U->>JE: Edit JSON
  JE->>SC: onChange(JSON)
  SC->>SY: jsonToConfigs(JSON)
  SY-->>SC: Parsed configs
  SC->>VE: Sync table rows
  end

  U->>SC: Save (Submit)
  SC->>API: Submit form values (includes Chats JSON)
  API-->>SC: Response
  SC-->>U: Success/Failure feedback
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A bunny taps the toggle, hop to JSON, hop to UI,
Tables bloom like clover, modals wink an eye.
Names and URLs align, in tidy carrot rows,
Syncing burrow tunnels where the data flows.
Save, submit—thump-thump!—the meadow softly knows. 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (1)
web/src/pages/Setting/Chat/SettingsChats.jsx (1)

156-175: Guard JSON.parse on props.options['Chats'] to avoid hard crash

Parsing untrusted server data without try/catch can break the page if malformed.

Apply:

-          const obj = JSON.parse(props.options[key]);
-          currentInputs[key] = JSON.stringify(obj, null, 2);
+          try {
+            const obj = JSON.parse(props.options[key] ?? '[]');
+            currentInputs[key] = JSON.stringify(obj, null, 2);
+          } catch (e) {
+            showWarning(t('Chats 配置不是合法 JSON,已重置为空数组'));
+            currentInputs[key] = '[]';
+          }
🧹 Nitpick comments (9)
web/src/pages/Setting/Chat/SettingsChats.jsx (9)

189-199: Remove setTimeout hack in handleAddConfig; initialize via effect

Rely on a visibility effect to set form values deterministically.

Apply:

   const handleAddConfig = () => {
     setEditingConfig({ name: '', url: '' });
     setIsEdit(false);
     setModalVisible(true);
-    setTimeout(() => {
-      if (modalFormRef.current) {
-        modalFormRef.current.setValues({ name: '', url: '' });
-      }
-    }, 100);
   };

Add outside this range (near other hooks):

useEffect(() => {
  if (modalVisible && modalFormRef.current) {
    modalFormRef.current.setValues(editingConfig ?? { name: '', url: '' });
  }
}, [modalVisible, editingConfig]);

200-209: Remove setTimeout hack in handleEditConfig; reuse the same effect

Avoid timing assumptions; let the effect populate the modal form.

Apply:

   const handleEditConfig = (config) => {
     setEditingConfig({ ...config });
     setIsEdit(true);
     setModalVisible(true);
-    setTimeout(() => {
-      if (modalFormRef.current) {
-        modalFormRef.current.setValues(config);
-      }
-    }, 100);
   };

318-335: Drop setTimeout during mode switch; effect already syncs JSON form

Reduces flakiness and duplicate state writes.

Apply:

-              onChange={(e) => {
-                const newMode = e.target.value;
-                setEditMode(newMode);
-                
-                // 确保模式切换时数据正确同步
-                setTimeout(() => {
-                  if (newMode === 'json' && refForm.current) {
-                    refForm.current.setValues(inputs);
-                  }
-                }, 100);
-              }}
+              onChange={(e) => {
+                const newMode = e.target.value;
+                setEditMode(newMode);
+              }}

407-409: Disable the save button while saving

Avoids duplicate submissions; aligns with the spinner state.

Apply:

-          <Button type='primary' onClick={onSubmit}>{t('保存聊天设置')}</Button>
+          <Button type='primary' loading={loading} onClick={onSubmit}>
+            {t('保存聊天设置')}
+          </Button>

412-418: Prevent accidental modal close and stale form state

Make edits safer.

Apply:

       <Modal
         title={isEdit ? t('编辑聊天配置') : t('添加聊天配置')}
         visible={modalVisible}
         onOk={handleModalOk}
         onCancel={handleModalCancel}
-        width={600}
+        width={600}
+        maskClosable={false}
+        destroyOnClose
       >

260-301: Optional: make URL cell clickable with safe attributes

Small UX improvement; React escapes content so safe to render anchor.

Example diff:

       {
         title: t('URL链接'),
         dataIndex: 'url',
         key: 'url',
-        render: (text) => (
+        render: (text) => (
           <div style={{ maxWidth: 300, wordBreak: 'break-all' }}>
-          {text}
+            {text ? (
+              <a href={text} target="_blank" rel="noopener noreferrer">
+                {text}
+              </a>
+            ) : (
+              '-'
+            )}
           </div>
         ),
       },

376-404: JSON editor rules OK; consider normalizing on blur to keep both modes consistent

Not urgent. On blur, pretty-print valid JSON back into the field to reduce diffs across saves.

If desired, I can provide a small handler to parse+stringify on blur and show a non-intrusive warning on failure.


58-65: Consider defaulting to visual mode for discoverability (optional)

Given this PR introduces visual editing, starting in visual mode could improve UX. Non-blocking.


66-103: Add unit tests for JSON↔configs transforms

Guard against regressions and edge-cases (multi-key objects, blanks, duplicates).

I can add Jest tests covering: valid round-trip, invalid JSON, multi-key flattening, trimming, dedupe.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fbe7f35 and 9c830d1.

📒 Files selected for processing (1)
  • web/src/pages/Setting/Chat/SettingsChats.jsx (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
web/src/pages/Setting/Chat/SettingsChats.jsx (1)
web/src/helpers/utils.jsx (1)
  • showSuccess (148-150)
🔇 Additional comments (1)
web/src/pages/Setting/Chat/SettingsChats.jsx (1)

156-175: Drop global schema check—Chats is only parsed in SettingsChats.jsx (via jsonToConfigs) and initialized in ChatsSetting.jsx, with no other consumers.

Comment on lines +66 to +81
const jsonToConfigs = (jsonString) => {
try {
const configs = JSON.parse(jsonString);
return Array.isArray(configs)
? configs.map((config, index) => ({
id: index,
name: Object.keys(config)[0] || '',
url: Object.values(config)[0] || ''
}))
: [];
} catch (error) {
console.error('JSON parse error:', error);
return [];
}
};

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.

🛠️ Refactor suggestion

jsonToConfigs: validate shape; avoid silent data loss; surface parse issues

Currently only the first key of each object is used; invalid entries are silently dropped, and parse errors just return [].

Apply:

-  const jsonToConfigs = (jsonString) => {
-    try {
-      const configs = JSON.parse(jsonString);
-      return Array.isArray(configs) 
-        ? configs.map((config, index) => ({
-            id: index,
-            name: Object.keys(config)[0] || '',
-            url: Object.values(config)[0] || ''
-          }))
-        : [];
-    } catch (error) {
-      console.error('JSON parse error:', error);
-      return [];
-    }
-  };
+  const jsonToConfigs = (jsonString) => {
+    try {
+      const arr = JSON.parse(jsonString);
+      if (!Array.isArray(arr)) return [];
+      const pairs = arr.flatMap((entry) => {
+        if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
+          return Object.entries(entry).map(([name, url]) => ({
+            name: String(name).trim(),
+            url: String(url ?? '').trim(),
+          }));
+        }
+        return [];
+      });
+      return pairs.map((cfg, index) => ({ id: index, ...cfg }));
+    } catch (error) {
+      console.error('JSON parse error:', error);
+      showWarning(t('无法解析 JSON:可视化列表将暂不更新'));
+      return chatConfigs;
+    }
+  };

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +82 to +87
const configsToJson = (configs) => {
const jsonArray = configs.map(config => ({
[config.name]: config.url
}));
return JSON.stringify(jsonArray, null, 2);
};

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.

🛠️ Refactor suggestion

configsToJson: filter blanks and dedupe by name

Prevents emitting empty keys and reduces churn.

Apply:

-  const configsToJson = (configs) => {
-    const jsonArray = configs.map(config => ({
-      [config.name]: config.url
-    }));
-    return JSON.stringify(jsonArray, null, 2);
-  };
+  const configsToJson = (configs) => {
+    const seen = new Set();
+    const jsonArray = configs
+      .map(({ name = '', url = '' }) => ({ name: name.trim(), url: url.trim() }))
+      .filter(({ name, url }) => name && url && !seen.has(name) && (seen.add(name), true))
+      .map(({ name, url }) => ({ [name]: url }));
+    return JSON.stringify(jsonArray, null, 2);
+  };
📝 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
const configsToJson = (configs) => {
const jsonArray = configs.map(config => ({
[config.name]: config.url
}));
return JSON.stringify(jsonArray, null, 2);
};
const configsToJson = (configs) => {
const seen = new Set();
const jsonArray = configs
.map(({ name = '', url = '' }) => ({ name: name.trim(), url: url.trim() }))
.filter(({ name, url }) => name && url && !seen.has(name) && (seen.add(name), true))
.map(({ name, url }) => ({ [name]: url }));
return JSON.stringify(jsonArray, null, 2);
};
🤖 Prompt for AI Agents
In web/src/pages/Setting/Chat/SettingsChats.jsx around lines 82-87, the
configsToJson currently maps all configs to JSON including entries with empty
name/url and duplicate names; update it to first filter out configs where name
or url is falsy (empty strings), then deduplicate by name (e.g., use a Map keyed
by name and keep the last occurrence or desired precedence), build the array
from the Map values, and finally JSON.stringify that array with indentation;
this prevents emitting empty keys and reduces churn.

Comment on lines +211 to +216
const handleDeleteConfig = (id) => {
const newConfigs = chatConfigs.filter(config => config.id !== id);
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
showSuccess(t('删除成功'));
};

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.

🛠️ Refactor suggestion

Add delete confirmation and clarify persistence semantics

Deletion isn’t persisted until “保存聊天设置”; current success toast can mislead.

Apply:

-  const handleDeleteConfig = (id) => {
-    const newConfigs = chatConfigs.filter(config => config.id !== id);
-    setChatConfigs(newConfigs);
-    syncConfigsToJson(newConfigs);
-    showSuccess(t('删除成功'));
-  };
+  const handleDeleteConfig = (id) => {
+    Modal.confirm({
+      title: t('确认删除'),
+      content: t('删除后需点击“保存聊天设置”才会生效,是否继续?'),
+      onOk: () => {
+        const newConfigs = chatConfigs.filter((config) => config.id !== id);
+        setChatConfigs(newConfigs);
+        syncConfigsToJson(newConfigs);
+        showSuccess(t('已删除,保存后生效'));
+      },
+    });
+  };
📝 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
const handleDeleteConfig = (id) => {
const newConfigs = chatConfigs.filter(config => config.id !== id);
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
showSuccess(t('删除成功'));
};
const handleDeleteConfig = (id) => {
Modal.confirm({
title: t('确认删除'),
content: t('删除后需点击“保存聊天设置”才会生效,是否继续?'),
onOk: () => {
const newConfigs = chatConfigs.filter((config) => config.id !== id);
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
showSuccess(t('已删除,保存后生效'));
},
});
};

@seefs001

Copy link
Copy Markdown
Collaborator

帮忙改一下冲突(

@HynoR

HynoR commented Sep 27, 2025

Copy link
Copy Markdown
Contributor Author

帮忙改一下冲突(

下周抽空弄,有空麻烦先把这个小改动review 一下 #1862

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