fix(ui): harden chunk editor feedback after code review

Surface index-sync warnings instead of false save success, sync generated-question metadata after inline edits, and reload chunks on 409 revision conflicts.

Co-authored-by: Cursor <cursoragent@cursor.com>
main
wizardchen 2026-07-28 20:22:01 +08:00 committed by lyingbug
parent 497e8312e3
commit c3b08d6c26
5 changed files with 72 additions and 16 deletions

View File

@ -1090,6 +1090,60 @@ const chunkDraft = ref('');
const savingChunkId = ref('');
const chunkStatusLoading = ref('');
const getChunkMetadata = (item: any): Record<string, any> => (
typeof item.metadata === 'string'
? JSON.parse(item.metadata || '{}')
: { ...(item.metadata || {}) }
);
const setChunkMetadata = (item: any, metadata: Record<string, any>) => {
item.metadata = metadata;
};
const upsertChunkGeneratedQuestion = (item: any, questionData: GeneratedQuestion) => {
const metadata = getChunkMetadata(item);
const questions: GeneratedQuestion[] = [...(metadata.generated_questions || [])];
const index = questions.findIndex((q) => q.id === questionData.id);
if (index >= 0) {
questions[index] = questionData;
} else {
questions.push(questionData);
}
metadata.generated_questions = questions;
setChunkMetadata(item, metadata);
};
const notifyChunkMutationOutcome = (item: any, result: any, successMessage?: string) => {
Object.assign(item, result.data);
applySummaryState(result.summary_status, result.description);
if (item.index_status === 'failed') {
MessagePlugin.warning(t('knowledgeBase.chunkSavedIndexFailed'));
return;
}
if (successMessage) {
MessagePlugin.success(successMessage);
}
};
const reloadChunksFromStart = () => {
page = 1;
loadingChunks = true;
pendingRequestedPage = 1;
pendingChunksBeforeLoad = 0;
editingChunkId.value = '';
chunkDraft.value = '';
emit('getDoc', 1);
};
const handleChunkEditError = (error: any, fallbackMessage: string) => {
if (error?.status === 409) {
MessagePlugin.warning(error?.message || t('knowledgeBase.chunkEditConflict'));
reloadChunksFromStart();
return;
}
MessagePlugin.error(error?.message || fallbackMessage);
};
const startChunkEdit = (item: any) => {
if (editingChunkId.value === item.id) {
editingChunkId.value = '';
@ -1111,13 +1165,11 @@ const saveChunkEdit = async (item: any) => {
content: chunkDraft.value,
expected_revision: item.content_revision || 0,
});
Object.assign(item, result.data);
editingChunkId.value = '';
applySummaryState(result.summary_status, result.description);
notifyChunkMutationOutcome(item, result, t('common.saveSuccess'));
void refreshChunkHistoryAfterMutation(item);
MessagePlugin.success(t('common.saveSuccess'));
} catch (error: any) {
MessagePlugin.error(error?.message || t('common.saveFailed'));
handleChunkEditError(error, t('common.saveFailed'));
} finally {
savingChunkId.value = '';
}
@ -1130,11 +1182,10 @@ const toggleChunkEnabled = async (item: any, isEnabled: boolean) => {
is_enabled: isEnabled,
expected_revision: item.content_revision || 0,
});
Object.assign(item, result.data);
applySummaryState(result.summary_status, result.description);
notifyChunkMutationOutcome(item, result);
void refreshChunkHistoryAfterMutation(item);
} catch (error: any) {
MessagePlugin.error(error?.message || t('common.error'));
handleChunkEditError(error, t('common.error'));
} finally {
chunkStatusLoading.value = '';
}
@ -1254,12 +1305,10 @@ const revertChunk = async (item: any, revision: number) => {
revertingRevision.value = `${item.id}:${revision}`;
try {
const result: any = await revertDocumentChunk(props.details.id, item.id, revision, item.content_revision || 0);
Object.assign(item, result.data);
applySummaryState(result.summary_status, result.description);
notifyChunkMutationOutcome(item, result, t('knowledgeBase.chunkReverted'));
await refreshChunkHistoryAfterMutation(item);
MessagePlugin.success(t('knowledgeBase.chunkReverted'));
} catch (error: any) {
MessagePlugin.error(error?.message || t('common.error'));
handleChunkEditError(error, t('common.error'));
} finally {
revertingRevision.value = '';
}
@ -1317,9 +1366,7 @@ const addQuestion = async (item: any) => {
const result: any = await upsertGeneratedQuestion(item.id, question);
questionDrafts.value[item.id] = '';
questionComposerChunk.value = '';
const metadata = typeof item.metadata === 'string' ? JSON.parse(item.metadata || '{}') : (item.metadata || {});
metadata.generated_questions = [...(metadata.generated_questions || []), result.data];
item.metadata = metadata;
upsertChunkGeneratedQuestion(item, result.data);
MessagePlugin.success(t('common.saveSuccess'));
} catch (error: any) {
MessagePlugin.error(error?.message || t('common.error'));
@ -1348,8 +1395,9 @@ const saveQuestionEdit = async (item: any, question: GeneratedQuestion) => {
savingQuestionKey.value = `${item.id}:${question.id}`;
try {
const result: any = await upsertGeneratedQuestion(item.id, value, question.id);
question.question = value;
question.content_revision = result?.data?.content_revision ?? (item.content_revision || 0);
if (result?.data) {
upsertChunkGeneratedQuestion(item, result.data);
}
cancelQuestionEdit();
MessagePlugin.success(t('common.saveSuccess'));
} catch (error: any) {

View File

@ -549,6 +549,8 @@ export default {
summaryRefreshed: 'Summary refreshed',
summaryRefreshQueued: 'Summary refresh queued; it will update automatically when ready',
indexFailed: 'Index sync failed',
chunkSavedIndexFailed: 'Content saved, but index sync failed. Use Retry index.',
chunkEditConflict: 'This chunk was modified by someone else. The list was refreshed; please try again.',
retryIndex: 'Retry index',
indexRetrySuccess: 'Index synchronized',
history: 'History',

View File

@ -559,6 +559,8 @@ export default {
summaryRefreshed: "요약이 업데이트되었습니다",
summaryRefreshQueued: "요약 새로고침이 대기열에 추가되었으며 완료되면 자동으로 업데이트됩니다",
indexFailed: "인덱스 동기화 실패",
chunkSavedIndexFailed: "내용은 저장되었지만 인덱스 동기화에 실패했습니다. 인덱스 재시도를 사용하세요.",
chunkEditConflict: "다른 사용자가 이 청크를 수정했습니다. 목록을 새로고침했으니 다시 시도하세요.",
retryIndex: "인덱스 재시도",
indexRetrySuccess: "인덱스가 동기화되었습니다",
history: "기록",

View File

@ -484,6 +484,8 @@ export default {
summaryRefreshed: 'Сводка обновлена',
summaryRefreshQueued: 'Обновление сводки поставлено в очередь и обновится автоматически после завершения',
indexFailed: 'Ошибка синхронизации индекса',
chunkSavedIndexFailed: 'Содержимое сохранено, но синхронизация индекса не удалась. Нажмите «Повторить индексацию».',
chunkEditConflict: 'Этот чанк был изменён другим пользователем. Список обновлён — повторите попытку.',
retryIndex: 'Повторить индексацию',
indexRetrySuccess: 'Индекс синхронизирован',
history: 'История',

View File

@ -548,6 +548,8 @@ export default {
summaryRefreshed: "摘要已更新",
summaryRefreshQueued: "摘要刷新已提交,完成后会自动更新",
indexFailed: "索引同步失败",
chunkSavedIndexFailed: "内容已保存,但索引同步失败,请点击重试索引",
chunkEditConflict: "分块已被他人修改,列表已刷新,请重试",
retryIndex: "重试索引",
indexRetrySuccess: "索引已同步",
history: "历史",