From 77a6a1b6453b9d083456c6e7196cac4d6d9ce47a Mon Sep 17 00:00:00 2001 From: ONEDAY <62494140+fatelove42@users.noreply.github.com> Date: Sun, 18 Jan 2026 18:24:05 +0800 Subject: [PATCH] fix: initialize tracksCacheBytes on startup to enforce cache limit (#1951) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, tracksCacheBytes was initialized to 0 and only updated when entering the settings page. This caused the cache limit to not work until the user manually opened settings. Now the cache size is calculated from the database on app startup, ensuring cache cleanup triggers correctly. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/utils/db.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/utils/db.js b/src/utils/db.js index 6dfabebf11..6920815b22 100644 --- a/src/utils/db.js +++ b/src/utils/db.js @@ -30,6 +30,46 @@ db.version(1).stores({ let tracksCacheBytes = 0; +// 等待 settings 可用 +async function waitForSettingsReady(timeoutMs = 5000) { + const interval = 100; + const maxTries = Math.ceil(timeoutMs / interval); + let tries = 0; + while ( + (store.state == null || + store.state.settings == null || + store.state.settings.cacheLimit === undefined) && + tries < maxTries + ) { + await new Promise(resolve => setTimeout(resolve, interval)); + tries++; + } + return store.state && store.state.settings; +} + +// 初始化现有缓存总大小,确保应用启动时能正确判断并清理超限缓存 +async function initTracksCacheBytes() { + if (!process.env.IS_ELECTRON) return; + try { + await waitForSettingsReady(); + const all = await db.trackSources.toArray(); + tracksCacheBytes = all.reduce( + (sum, t) => sum + (t?.source?.byteLength || 0), + 0 + ); + console.debug( + '[debug][db.js] initTracksCacheBytes, total bytes:', + tracksCacheBytes + ); + deleteExcessCache(); + } catch (err) { + console.debug('[debug][db.js] initTracksCacheBytes failed', err); + } +} + +// 模块加载时触发初始化 +initTracksCacheBytes(); + async function deleteExcessCache() { if ( store.state.settings.cacheLimit === false ||