Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

## 先说结论

桌面端用默认值继续启动,不等于磁盘上的偏好文件可以被默认值替换。`store.Load` 读取或解码某个文件失败后,同一个 Store 下一次 `Save` 这个文件时,先把原文件改名为 `<名称>.unreadable-<UTC 时间>`(`store.SetAsideName`),再正常写入新值。原内容一字节不丢,之后的保存照常进行。
桌面端用默认值继续启动,不等于磁盘上的偏好文件可以被默认值替换。`store.Load` 读取或解码某个文件失败后,同一个 Store 下一次 `Save` 这个文件时,先把原文件改名为 `<名称>.unreadable-<UTC 时间>`(`store.SetAsideName`),再正常写入新值。原内容一字节不丢,之后的保存照常进行。设置无法读取时,桌面端启动后提示当前使用默认设置。首次保存移走原文件后,通知显示实际备份路径。

## 问题

Expand Down Expand Up @@ -40,12 +40,14 @@

- 原内容保存在同目录的 `.unreadable-*` 文件里,用户可以对照修复后放回。
- 每次致命读取失败最多产生一个另存文件;文件不再被读取,不增加后台任务。
- 启动时提示设置文件无法读取、另存文件在哪里,仍待 #1943 后续补齐。
- 启动提示保留在通知历史。备份路径取自存储层实际完成的改名,因此替换文件写入失败时用户也能找到原内容。

## 验证

- `scripts/desktop/desktop-go.sh test ./internal/store -run 'TestSave|TestLoad|TestUnread' -count=1`

- `scripts/desktop/desktop-go.sh test -tags vivahead ./internal/workbench -run TestUnreadableSettingsWarnAtStartupAndIdentifyTheBackupOnSave -count=1`

## 适用范围

- `desktop/internal/store/store.go`
Expand Down
8 changes: 8 additions & 0 deletions desktop/internal/i18n/shared.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 24 additions & 7 deletions desktop/internal/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,21 @@ func (store *Store) Unknown(name string) []string {
// the file is first moved aside to SetAsideName(name, time), so a save never destroys content a
// load could not read, and the file that holds the new value works again from this save on.
func (store *Store) Save(name string, value any) error {
if err := store.setAside(name); err != nil {
return err
_, err := store.SaveWithBackup(name, value)
return err
}

// SaveWithBackup also returns the path of an unreadable file moved aside by this save.
// The path is returned even if writing its replacement fails.
func (store *Store) SaveWithBackup(name string, value any) (string, error) {
backup, err := store.setAside(name)
if err != nil {
return "", err
}
return backup, store.saveJSON(name, value)
}

func (store *Store) saveJSON(name string, value any) error {
store.mu.Lock()
kept := store.kept[name]
store.mu.Unlock()
Expand Down Expand Up @@ -215,20 +227,25 @@ func SetAsideName(name string, at time.Time) string {
// check, the rename and clearing the failure happen under one lock, so concurrent saves never move
// the file a first save has just written. A file already gone has nothing to keep. A rename that
// fails keeps the failure and fails the save, so the unreadable file stays where it was.
func (store *Store) setAside(name string) error {
func (store *Store) setAside(name string) (string, error) {
store.mu.Lock()
defer store.mu.Unlock()
failed := store.failedLoad[name]
if failed == nil {
return nil
return "", nil
}
path := filepath.Join(store.dir, name)
aside := filepath.Join(store.dir, SetAsideName(name, store.now()))
if err := os.Rename(path, aside); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("move unreadable %s aside before saving: %w", name, errors.Join(err, failed))
err := os.Rename(path, aside)
if errors.Is(err, fs.ErrNotExist) {
delete(store.failedLoad, name)
return "", nil
}
if err != nil {
return "", fmt.Errorf("move unreadable %s aside before saving: %w", name, errors.Join(err, failed))
}
delete(store.failedLoad, name)
return nil
return aside, nil
}

// Path is where the file name lives, for a reader that streams it instead of loading it whole,
Expand Down
8 changes: 7 additions & 1 deletion desktop/internal/workbench/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,8 @@ func New(options Options) *App {
// After the background is restored: the notice saves the settings, which would
// otherwise save no background.
a.noticeUnknownSettings()
} else {
a.noticeUnreadableSettings()
}
}
return a
Expand Down Expand Up @@ -1468,7 +1470,11 @@ func (a *App) saveSettings() {
// The background is the window's, which another tab may have changed since this one loaded.
a.settings.WorkbenchBackground = a.savedBackgroundState()
a.updates.store(&a.settings)
if err := a.store.Save(settingsFile, a.settings); err != nil {
backup, err := a.store.SaveWithBackup(settingsFile, a.settings)
if backup != "" {
a.noticeSettingsBackup(backup)
}
if err != nil {
a.operationFailed("settings_save", documentLogError(err))
a.notifyError(a.text.Errors.SaveFailed(err.Error()))
}
Expand Down
61 changes: 61 additions & 0 deletions desktop/internal/workbench/notifications_visual_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
"github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
"github.com/1lck/Lithe-IDEA/desktop/internal/store"
"github.com/vivaui/viva/app"
"github.com/vivaui/viva/headless"
Expand Down Expand Up @@ -67,3 +68,63 @@ func TestVisualNotificationsToolWindow(t *testing.T) {
})
}
}

func TestVisualSettingsRecoveryNotifications(t *testing.T) {
out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR")
if out == "" {
t.Skip("set LITHE_VISUAL_OUTPUT_DIR")
}
if err := os.MkdirAll(out, 0o755); err != nil {
t.Fatal(err)
}
system, err := app.NewDriver(app.Config{}, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(system.Close)
for _, scene := range []struct {
theme themeChoice
language string
}{{"light", "en-US"}, {"dark", "zh-CN"}} {
name := string(scene.theme) + "-" + scene.language
t.Run(name, func(t *testing.T) {
system.SetSystemAppearance(nativeAppearance(scene.theme))
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
var session *headless.Session
h := newHarnessWithDriver(t, Options{
Kernel: &testKernel{Client: core.NewClient()}, Store: store.At(dir), Languages: []string{scene.language},
}, func(config app.Config) (*app.Driver, func(), error) {
config.Width, config.Height = 1438, 900
var err error
session, err = headless.Open(config, nil, headless.Options{Scale: 1})
if err != nil {
return nil, nil, err
}
return session.Driver(), session.Close, nil
})
capture := func(stage, titleKey string) {
t.Helper()
h.settle()
if err := session.Resize(1439, 900); err != nil {
t.Fatal(err)
}
if err := session.Resize(1440, 900); err != nil {
t.Fatal(err)
}
if !h.shows(i18n.Shared(h.app.language(), titleKey)) {
t.Fatalf("the %s notification did not paint", stage)
}
if err := session.Screenshot(filepath.Join(out, "settings-recovery-"+stage+"-"+name+".png")); err != nil {
t.Fatal(err)
}
}
capture("startup", "desktop.settings.unreadable.title")
h.app.overlay.toaster.Close(h.app.notifications.list[0].toast)
h.app.setTheme(scene.theme)
capture("backup", "desktop.settings.backup.title")
})
}
}
21 changes: 21 additions & 0 deletions desktop/internal/workbench/settings_kept.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"

"github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
"github.com/vivaui/viva/ui"
)

// The stable channel and AutoBuild share one settings file, so the build that runs may meet
Expand Down Expand Up @@ -53,3 +54,23 @@ func unknownSettingsFingerprint(keys []string) string {
sum := sha256.Sum256([]byte(strings.Join(keys, "\n")))
return hex.EncodeToString(sum[:8])
}

// noticeUnreadableSettings explains the fallback while the original file is still in place.
func (a *App) noticeUnreadableSettings() {
language := a.language()
a.notifyActions(
i18n.Shared(language, "desktop.settings.unreadable.title"),
i18n.Shared(language, "desktop.settings.unreadable.detail"),
ui.ToastWarning, "", nil, "", nil,
)
}

// noticeSettingsBackup reports the actual path once the store has moved the original file.
func (a *App) noticeSettingsBackup(path string) {
language := a.language()
a.notifyActions(
i18n.Shared(language, "desktop.settings.backup.title"),
i18n.SharedFormat(language, "desktop.settings.backup.detail", map[string]string{"path": path}),
ui.ToastInfo, "", nil, "", nil,
)
}
52 changes: 52 additions & 0 deletions desktop/internal/workbench/settings_kept_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
"github.com/1lck/Lithe-IDEA/desktop/internal/store"
"github.com/vivaui/viva/app"
)

// keptNotices is the notices that told about settings this version does not read.
Expand Down Expand Up @@ -104,3 +105,54 @@ func TestAnEditorSessionANewerVersionShapedDifferentlyIsLogged(t *testing.T) {
t.Fatalf("background failures = %v, want one for the editor session read", operations)
}
}

func TestUnreadableSettingsWarnAtStartupAndIdentifyTheBackupOnSave(t *testing.T) {
// Invalid settings follow system appearance before the workbench driver
// exists. Open Viva's headless driver first to supply that setting.
system, err := app.NewDriver(app.Config{}, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(system.Close)
dir := t.TempDir()
original := []byte(`{"theme":"dark","incomplete":`)
path := filepath.Join(dir, settingsFile)
if err := os.WriteFile(path, original, 0o600); err != nil {
t.Fatal(err)
}
h := newHarnessWithOptions(t, Options{
Kernel: &testKernel{Client: core.NewClient()}, Store: store.At(dir), Languages: []string{"en"},
})
notices := h.app.notifications.list
if len(notices) != 1 || !strings.Contains(notices[0].text, "Could not read settings") || !strings.Contains(notices[0].detail, "default settings") {
t.Fatalf("startup did not explain that default settings are in use: %+v", notices)
}
backups, err := filepath.Glob(path + ".unreadable-*")
if err != nil || len(backups) != 0 {
t.Fatalf("startup changed the backup files: %v, %v", backups, err)
}
if actual, err := os.ReadFile(path); err != nil || string(actual) != string(original) {
t.Fatalf("startup changed the settings file: %q, %v", actual, err)
}

h.app.setTheme("dark")
backups, err = filepath.Glob(path + ".unreadable-*")
if err != nil || len(backups) != 1 {
t.Fatalf("after saving, backups = %v, %v", backups, err)
}
if backup, err := os.ReadFile(backups[0]); err != nil || string(backup) != string(original) {
t.Fatalf("backup = %q, %v, want original settings bytes", backup, err)
}
notices = h.app.notifications.list
if len(notices) != 2 || !strings.Contains(notices[0].detail, backups[0]) {
t.Fatalf("saving did not report the backup path: %+v", notices)
}
var restored settings
if found, err := store.At(dir).Load(settingsFile, &restored); err != nil || !found || restored.Theme != "dark" {
t.Fatalf("new settings theme = %q, found = %v, err = %v", restored.Theme, found, err)
}
h.app.saveSettings()
if got := len(h.app.notifications.list); got != 2 {
t.Fatalf("second save produced a notice, got %d notices", got)
}
}
4 changes: 4 additions & 0 deletions shared/i18n/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -11194,6 +11194,10 @@
"desktop.updates.dialog.download": "Download and Install",
"desktop.updates.dialog.restart": "Restart and Update",
"desktop.updates.dialog.downloads": "Open Downloads Page",
"desktop.settings.unreadable.title": "Could not read settings",
"desktop.settings.unreadable.detail": "Lithe is using default settings. Lithe will back up the original file the next time settings are saved.",
"desktop.settings.backup.title": "Original settings backed up",
"desktop.settings.backup.detail": "You can find the original settings file at {path}.",
"desktop.settings.unknownKept": "The settings file has {count} settings this version does not recognize ({keys}). This version ignores them but keeps them, so they still apply when you switch back to a version that knows them.",
"desktop.memory.status": "{total} · Lithe {lithe}",
"desktop.memory.tooltip": "Memory: {total} in total, {lithe} of it in the Lithe main process.",
Expand Down
4 changes: 4 additions & 0 deletions shared/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -11194,6 +11194,10 @@
"desktop.updates.dialog.download": "下载并安装",
"desktop.updates.dialog.restart": "重启并更新",
"desktop.updates.dialog.downloads": "打开下载页面",
"desktop.settings.unreadable.title": "无法读取设置",
"desktop.settings.unreadable.detail": "Lithe 正在使用默认设置。下次保存设置时,Lithe 会备份原文件。",
"desktop.settings.backup.title": "已备份原设置",
"desktop.settings.backup.detail": "原设置文件的备份位于 {path}。",
"desktop.settings.unknownKept": "设置文件中有 {count} 项此版本无法识别的设置({keys})。此版本不会使用它们,但会原样保留,换回能识别它们的版本时仍然有效。",
"desktop.memory.status": "{total} · Lithe {lithe}",
"desktop.memory.tooltip": "内存:共 {total},其中 Lithe 主进程 {lithe}。",
Expand Down
31 changes: 31 additions & 0 deletions shared/i18n/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -20631,6 +20631,37 @@
"desktop"
]
},
{
"id": "desktop.settings.unreadable.title",
"description": "Title of the startup warning for an unreadable application settings file.",
"platforms": [
"desktop"
]
},
{
"id": "desktop.settings.unreadable.detail",
"description": "Explains the startup fallback and when the unreadable file will be backed up.",
"platforms": [
"desktop"
]
},
{
"id": "desktop.settings.backup.title",
"description": "Title of the notice after moving an unreadable application settings file aside.",
"platforms": [
"desktop"
]
},
{
"id": "desktop.settings.backup.detail",
"description": "Shows the actual backup location after moving the original file aside.",
"platforms": [
"desktop"
],
"parameters": {
"path": "string"
}
},
{
"id": "desktop.settings.unknownKept",
"description": "Notice at launch when settings.json holds settings this version does not recognize, such as ones a newer build or the other update channel wrote. They are ignored but kept in the file. {count} is how many, {keys} names up to five of them.",
Expand Down
Loading