Repository navigation
Conversation
WalkthroughIntroduces 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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 crashParsing 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 effectRely 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 effectAvoid 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 formReduces 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 savingAvoids 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 stateMake 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 attributesSmall 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 consistentNot 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 transformsGuard 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.
📒 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—Chatsis only parsed in SettingsChats.jsx (via jsonToConfigs) and initialized in ChatsSetting.jsx, with no other consumers.
| 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 []; | ||
| } | ||
| }; | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| const configsToJson = (configs) => { | ||
| const jsonArray = configs.map(config => ({ | ||
| [config.name]: config.url | ||
| })); | ||
| return JSON.stringify(jsonArray, null, 2); | ||
| }; |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| const handleDeleteConfig = (id) => { | ||
| const newConfigs = chatConfigs.filter(config => config.id !== id); | ||
| setChatConfigs(newConfigs); | ||
| syncConfigsToJson(newConfigs); | ||
| showSuccess(t('删除成功')); | ||
| }; |
There was a problem hiding this comment.
🛠️ 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.
| 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('已删除,保存后生效')); | |
| }, | |
| }); | |
| }; |
|
帮忙改一下冲突( |
下周抽空弄,有空麻烦先把这个小改动review 一下 #1862 |
聊天设置可以可视化编辑

Summary by CodeRabbit