fix: Enhance file history settings with default values and validation (#12512)

This commit is contained in:
蘭
2026-04-17 16:05:57 +08:00
committed by GitHub
parent 646b99974a
commit 031a203a74
3 changed files with 102 additions and 17 deletions
+2 -2
View File
@@ -47,6 +47,6 @@ type FileHistoryRestoreReq struct {
type FileHistorySettingUpdate struct {
Enable string `json:"enable" validate:"required,oneof=Enable Disable"`
MaxPerPath int `json:"maxPerPath" validate:"required,min=1,max=1000"`
DiskQuotaMB int `json:"diskQuotaMB" validate:"required,min=1,max=1048576"`
MaxPerPath int `json:"maxPerPath" validate:"min=0,max=1000"`
DiskQuotaMB int `json:"diskQuotaMB" validate:"min=0,max=1048576"`
}
+26 -7
View File
@@ -30,9 +30,12 @@ const (
fileHistorySettingMaxPerPath = "FileHistoryMaxPerPath"
fileHistorySettingDiskQuotaMB = "FileHistoryDiskQuotaMB"
fileHistoryOpSave = "save"
fileHistoryOpRestore = "restore"
fileHistoryOpRename = "rename"
fileHistoryOpMove = "move"
fileHistoryRootDirName = "file-history"
defaultFileHistoryMaxPerPath = 20
defaultFileHistoryDiskQuotaMB = 1024
)
var historyService = NewIFileHistoryService()
@@ -62,8 +65,8 @@ func NewIFileHistoryService() IFileHistoryService {
func (s *FileHistoryService) GetSettingInfo() (*response.FileHistorySettingInfo, error) {
info := &response.FileHistorySettingInfo{
Enable: constant.StatusEnable,
MaxPerPath: 20,
DiskQuotaMB: 1024,
MaxPerPath: defaultFileHistoryMaxPerPath,
DiskQuotaMB: defaultFileHistoryDiskQuotaMB,
}
if value, err := settingRepo.GetValueByKey(fileHistorySettingEnable); err == nil && value != "" {
info.Enable = value
@@ -82,6 +85,12 @@ func (s *FileHistoryService) GetSettingInfo() (*response.FileHistorySettingInfo,
}
func (s *FileHistoryService) UpdateSetting(req request.FileHistorySettingUpdate) error {
if req.MaxPerPath <= 0 {
req.MaxPerPath = defaultFileHistoryMaxPerPath
}
if req.DiskQuotaMB <= 0 {
req.DiskQuotaMB = defaultFileHistoryDiskQuotaMB
}
if err := settingRepo.UpdateOrCreate(fileHistorySettingEnable, req.Enable); err != nil {
return err
}
@@ -161,13 +170,20 @@ func (s *FileHistoryService) RecordOperation(operation string, filePath string,
}
previousID := uint(0)
if s.isVersionOperation(operation) {
contentHash := sha256HexBytes(content)
if latestVersion, err := s.getLatestVersionByFileID(fileID); err == nil {
if latestVersion, err := s.getLatestVersionByFileID(fileID); err == nil {
switch operation {
case fileHistoryOpSave:
contentHash := sha256HexBytes(content)
if latestVersion.ContentSHA == contentHash {
return nil
}
previousID = latestVersion.ID
case fileHistoryOpRestore:
previousID = latestVersion.ID
default:
if latestChainRecord.ID != 0 {
previousID = latestChainRecord.ID
}
}
} else if latestChainRecord.ID != 0 {
previousID = latestChainRecord.ID
@@ -414,6 +430,9 @@ func (s *FileHistoryService) Restore(req request.FileHistoryRestoreReq) (respons
_ = s.rollbackRestore(currentPath, rollbackContent, rollbackMode, existedBefore)
return response.FileInfo{}, err
}
if err := historyService.RecordOperation(fileHistoryOpRestore, currentPath, rollbackContent, rollbackMode, "", ""); err != nil {
global.LOG.Warnf("record file restore history failed for %s: %v", currentPath, err)
}
info, err := files.NewFileInfo(files.FileOption{
Path: currentPath,
@@ -571,7 +590,7 @@ func (s *FileHistoryService) getLatestActiveRelatedByPath(absPath string) (model
func (s *FileHistoryService) getLatestVersionByFileID(fileID string) (model.FileHistory, error) {
var item model.FileHistory
db := global.DB.Model(&model.FileHistory{}).Where("file_id = ? AND operation = ?", fileID, fileHistoryOpSave).Order("created_at desc")
db := global.DB.Model(&model.FileHistory{}).Where("file_id = ? AND operation IN ?", fileID, []string{fileHistoryOpSave, fileHistoryOpRestore}).Order("created_at desc")
err := db.First(&item).Error
return item, err
}
@@ -609,7 +628,7 @@ func (s *FileHistoryService) resolveFileChain(paths ...string) (string, model.Fi
}
func (s *FileHistoryService) isVersionOperation(operation string) bool {
return operation == fileHistoryOpSave
return operation == fileHistoryOpSave || operation == fileHistoryOpRestore
}
func (s *FileHistoryService) totalSize() (int64, error) {
@@ -17,15 +17,21 @@
<el-card shadow="never" class="history-setting">
<el-collapse v-model="activeCollapse" :accordion="true" class="!border-0">
<el-collapse-item :title="$t('file.historySettingTitle')" name="history" class="!border-0">
<el-form label-position="top" class="flex items-end gap-6">
<el-form-item :label="$t('file.historyEnable')">
<el-form
ref="historySettingFormRef"
:model="historySetting"
:rules="historySettingRules"
label-position="top"
class="flex items-end gap-6"
>
<el-form-item :label="$t('file.historyEnable')" prop="enable">
<el-switch
v-model="historySetting.enable"
active-value="Enable"
inactive-value="Disable"
/>
</el-form-item>
<el-form-item :label="$t('file.historyMaxPerPath')">
<el-form-item :label="$t('file.historyMaxPerPath')" prop="maxPerPath">
<el-input-number
v-model="historySetting.maxPerPath"
:min="1"
@@ -33,7 +39,7 @@
class="!w-52"
/>
</el-form-item>
<el-form-item :label="$t('file.historyDiskQuota')">
<el-form-item :label="$t('file.historyDiskQuota')" prop="diskQuotaMB">
<el-input-number
v-model="historySetting.diskQuotaMB"
:min="1"
@@ -212,7 +218,7 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, ref } from 'vue';
import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, reactive, ref } from 'vue';
import { dateFormatSimpleWithSecond } from '@/utils/date';
import { computeSize } from '@/utils/size';
import { MsgError, MsgSuccess } from '@/utils/message';
@@ -221,7 +227,7 @@ import { getAgentFileHistoryInfo, updateAgentFileHistoryInfo } from '@/api/modul
import { File } from '@/api/interface/file';
import { Setting } from '@/api/interface/setting';
import { loadMonacoLanguageSupport, setupMonacoEnvironment } from '@/utils/monaco';
import { ElMessageBox } from 'element-plus';
import { ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Languages } from '@/global/mimetype';
import i18n from '@/lang';
@@ -241,6 +247,7 @@ const historyLoading = ref(false);
const deleteLoading = ref(false);
const settingSaving = ref(false);
const restoreLoading = ref(false);
const historySettingFormRef = ref<FormInstance>();
const scope = ref<'current' | 'all'>('current');
const operationFilter = ref('');
const activeCollapse = ref([]);
@@ -256,6 +263,51 @@ const historySetting = ref<Setting.FileHistoryInfo>({
maxPerPath: 20,
diskQuotaMB: 1024,
});
const historySettingRules = reactive<FormRules<Setting.FileHistoryInfo>>({
enable: [
{
required: true,
message: i18n.global.t('commons.rule.requiredInput'),
trigger: 'change',
},
],
maxPerPath: [
{
required: true,
message: i18n.global.t('commons.rule.requiredInput'),
trigger: 'change',
},
{
validator: (_, value, callback) => {
const parsedValue = Number(value);
if (!Number.isInteger(parsedValue) || parsedValue <= 0) {
callback(new Error(i18n.global.t('commons.rule.integer')));
return;
}
callback();
},
trigger: 'change',
},
],
diskQuotaMB: [
{
required: true,
message: i18n.global.t('commons.rule.requiredInput'),
trigger: 'change',
},
{
validator: (_, value, callback) => {
const parsedValue = Number(value);
if (!Number.isInteger(parsedValue) || parsedValue <= 0) {
callback(new Error(i18n.global.t('commons.rule.integer')));
return;
}
callback();
},
trigger: 'change',
},
],
});
const historyItems = ref<File.FileHistoryInfo[]>([]);
const selected = ref<File.FileHistoryInfo[]>([]);
const selectedHistory = ref<File.FileHistoryInfo | null>(null);
@@ -267,6 +319,7 @@ const windowWidth = ref(window.innerWidth);
const operationMap = {
'': i18n.global.t('app.all'),
save: i18n.global.t('commons.button.save'),
restore: i18n.global.t('commons.button.recover'),
move: i18n.global.t('file.move'),
rename: i18n.global.t('file.rename'),
} as const;
@@ -279,7 +332,7 @@ const operationOptions = Object.entries(operationMap).map(([value, label]) => ({
const getOperationLabel = (operation: string) => {
return operationMap[operation as keyof typeof operationMap] || operation;
};
const isVersionRecord = (operation: string) => operation === 'save';
const isVersionRecord = (operation: string) => operation === 'save' || operation === 'restore';
const canRestoreSelected = computed(() => isVersionRecord(selectedHistory.value?.operation || ''));
const isRestoringCurrentFile = computed(() => selectedHistory.value?.path === currentFile.value.path);
const getCurrentTargetPath = (row: File.FileHistoryInfo) => row.currentPath || row.path;
@@ -412,10 +465,23 @@ const loadHistorySetting = async () => {
historySetting.value = res.data;
};
const normalizeHistorySettingNumber = (value: number, defaultValue: number) => {
const parsedValue = Number(value);
return parsedValue > 0 ? parsedValue : defaultValue;
};
const saveHistorySetting = async () => {
settingSaving.value = true;
try {
await updateAgentFileHistoryInfo(historySetting.value);
const valid = await historySettingFormRef.value?.validate().catch(() => false);
if (!valid) {
return;
}
await updateAgentFileHistoryInfo({
...historySetting.value,
maxPerPath: normalizeHistorySettingNumber(historySetting.value.maxPerPath, 20),
diskQuotaMB: normalizeHistorySettingNumber(historySetting.value.diskQuotaMB, 1024),
});
MsgSuccess(i18n.global.t('commons.msg.updateSuccess'));
} catch (error) {
MsgError(String(error));