Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(chat): auto-generate-title setting; route extension persistence off localStorage
Akarshan Biswasa79f753f375c
diff --git a/extensions/llamacpp-extension/src/backend-settings.ts b/extensions/llamacpp-extension/src/backend-settings.tsnew file mode 100644index 000000000..eed70b4cd--- /dev/null+++ b/extensions/llamacpp-extension/src/backend-settings.ts@@ -0,0 +1,38 @@+import { invoke } from '@tauri-apps/api/core'+import { logger } from '@janhq/core'++/**+ * Read/write persisted settings through the Rust settings store+ * (`settings_get`/`settings_set`/`settings_remove` -> `settings.json`), the+ * same backend the web-app's Zustand stores use (see+ * web-app/src/lib/backendStorage.ts). This is the ONLY sanctioned way for the+ * extension to persist state; raw `localStorage` is reserved for one-time+ * migration reads of pre-backend data.+ */+export async function getBackendSetting(key: string): Promise<string | null> {+ try {+ return (await invoke<string | null>('settings_get', { key })) ?? null+ } catch (error) {+ logger.warn(`settings_get failed for '${key}':`, error)+ return null+ }+}++export async function setBackendSetting(+ key: string,+ value: string+): Promise<void> {+ try {+ await invoke('settings_set', { key, value })+ } catch (error) {+ logger.warn(`settings_set failed for '${key}':`, error)+ }+}++export async function removeBackendSetting(key: string): Promise<void> {+ try {+ await invoke('settings_remove', { key })+ } catch (error) {+ logger.warn(`settings_remove failed for '${key}':`, error)+ }+}diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsindex fc78d540d..e756d7ee7 100644--- a/extensions/llamacpp-extension/src/backend.ts+++ b/extensions/llamacpp-extension/src/backend.ts@@ -54,7 +54,7 @@ export async function fetchRemoteBackends(): Promise<BackendVersion[]> {try {return await invoke<BackendVersion[]>('plugin:llamacpp|fetch_remote_supported_backends',- { supportedBackends, proxy: getProxyConfig() }+ { supportedBackends, proxy: await getProxyConfig() })} catch (e) {logger.debug(@@ -139,7 +139,7 @@ export async function downloadBackend(): Promise<void> {const janDataFolderPath = await getJanDataFolderPath()const sysInfo = await getSystemInfo()- const proxyConfig = getProxyConfig()+ const proxyConfig = await getProxyConfig()const downloadItems: Array<{url: stringdiff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 5e50a17af..cee7281db 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -55,6 +55,11 @@ import {type EmbedBatchResult,} from './util'import { generatePreset, MTP_MIN_BUILD } from './preset'+import {+ getBackendSetting,+ setBackendSetting,+ removeBackendSetting,+} from './backend-settings'import { basename } from '@tauri-apps/api/path'import {loadLlamaModel,@@ -152,7 +157,8 @@ type PersistedModelState = {settings?: Record<string, PersistedProviderSetting>}-const MODEL_PROVIDER_LOCAL_STORAGE_KEY = 'model-provider'+const MODEL_PROVIDER_STORE_KEY = 'model-provider'+const INTERFACE_SETTINGS_STORE_KEY = 'setting-appearance'const LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY ='llamacpp_model_yaml_backfill_v1'@@ -256,9 +262,9 @@ const MODEL_SETTINGS_YAML_MAPPING: Record<},}-function readPersistedLlamacppModels(): PersistedModelState[] {+async function readPersistedLlamacppModels(): Promise<PersistedModelState[]> {try {- const raw = localStorage.getItem(MODEL_PROVIDER_LOCAL_STORAGE_KEY)+ const raw = await getBackendSetting(MODEL_PROVIDER_STORE_KEY)if (!raw) return []const parsed = JSON.parse(raw)const providers = parsed?.state?.providers@@ -273,6 +279,22 @@ function readPersistedLlamacppModels(): PersistedModelState[] {}}+// Interface settings persist to the Rust settings store (settings.json), not+// webview localStorage — see web-app/src/lib/backendStorage.ts. The value is+// the Zustand-persisted blob `{ state: {...} }`. Defaults to true (feature on).+async function readAutoGenerateTitleSetting(): Promise<boolean> {+ try {+ const raw = await getBackendSetting(INTERFACE_SETTINGS_STORE_KEY)+ if (!raw) return true+ const parsed = JSON.parse(raw)+ const value = parsed?.state?.autoGenerateTitle+ return typeof value === 'boolean' ? value : true+ } catch (error) {+ logger.warn('Failed to read autoGenerateTitle setting:', error)+ return true+ }+}+/*** Breadth-first search of `rootDir` for the directory directly containing* a file named `serverName`. Returns the absolute path of that directory,@@ -555,12 +577,16 @@ export default class llamacpp_extension extends AIEngine {await writeSettingsFile(settings)}+ // The ONLY sanctioned localStorage use in this extension: a one-time read ++ // clear migrating pre-backend llamacpp settings into the file store. All+ // other persistence goes through backend-settings.ts. Guarded by+ // no-localstorage.test.ts via the `localstorage-migration-allowed` markers.private async migrateLocalStorageToFile(): Promise<void> {if (await settingsFileExists()) returnif (!this.name) returnlet raw: string | null = nulltry {- raw = localStorage.getItem(this.name)+ raw = localStorage.getItem(this.name) // localstorage-migration-allowed} catch {raw = null}@@ -578,7 +604,7 @@ export default class llamacpp_extension extends AIEngine {return}try {- localStorage.removeItem(this.name)+ localStorage.removeItem(this.name) // localstorage-migration-allowed} catch (e) {logger.warn('Failed to clear migrated localStorage entry:', e)}@@ -636,7 +662,10 @@ export default class llamacpp_extension extends AIEngine {providerPath,janDataFolderPath,this.config,- { supportsMtp }+ {+ supportsMtp,+ reservedBackgroundSlots: (await readAutoGenerateTitleSetting()) ? 1 : 0,+ })const backendExe = await getBackendExePath(backend, version)@@ -734,6 +763,7 @@ export default class llamacpp_extension extends AIEngine {const supportsMtp = build >= MTP_MIN_BUILDawait generatePreset(providerPath, janDataFolderPath, this.config, {supportsMtp,+ reservedBackgroundSlots: (await readAutoGenerateTitleSetting()) ? 1 : 0,})try {@@ -845,7 +875,7 @@ export default class llamacpp_extension extends AIEngine {private async migrateAutoUnloadToModelsMax(): Promise<void> {const MIGRATION_KEY = 'llamacpp_models_max_migrated_v1'- if (localStorage.getItem(MIGRATION_KEY)) return+ if (await getBackendSetting(MIGRATION_KEY)) returntry {const old = await this.getSetting<boolean | undefined>(@@ -873,39 +903,26 @@ export default class llamacpp_extension extends AIEngine {return}- localStorage.setItem(MIGRATION_KEY, '1')+ await setBackendSetting(MIGRATION_KEY, '1')}- private getStoredBackendType(): string | null {- try {- return localStorage.getItem('llama_cpp_backend_type')- } catch (error) {- logger.warn('Failed to read backend type from localStorage:', error)- return null- }+ private async getStoredBackendType(): Promise<string | null> {+ return getBackendSetting('llama_cpp_backend_type')}- private setStoredBackendType(backendType: string): void {- try {- localStorage.setItem('llama_cpp_backend_type', backendType)- logger.info(`Stored backend type preference: ${backendType}`)- } catch (error) {- logger.warn('Failed to store backend type in localStorage:', error)- }+ private async setStoredBackendType(backendType: string): Promise<void> {+ await setBackendSetting('llama_cpp_backend_type', backendType)+ logger.info(`Stored backend type preference: ${backendType}`)}- private clearStoredBackendType(): void {- try {- localStorage.removeItem('llama_cpp_backend_type')- logger.info('Cleared stored backend type preference')- } catch (error) {- logger.warn('Failed to clear backend type from localStorage:', error)- }+ private async clearStoredBackendType(): Promise<void> {+ await removeBackendSetting('llama_cpp_backend_type')+ logger.info('Cleared stored backend type preference')}private async migrateFitOff(): Promise<void> {const MIGRATION_KEY = 'llamacpp_fit_off_v1'- if (localStorage.getItem(MIGRATION_KEY)) return+ if (await getBackendSetting(MIGRATION_KEY)) returnif (this.config.fit === true) {const settings = await this.getSettings()@@ -921,15 +938,15 @@ export default class llamacpp_extension extends AIEngine {logger.info('Migrated fit setting: disabled')}- localStorage.setItem(MIGRATION_KEY, '1')+ await setBackendSetting(MIGRATION_KEY, '1')}private async migratePersistedModelSettingsToYaml(): Promise<void> {- if (localStorage.getItem(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return+ if (await getBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return- const persistedModels = readPersistedLlamacppModels()+ const persistedModels = await readPersistedLlamacppModels()if (persistedModels.length === 0) {- localStorage.setItem(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')+ await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')return}@@ -973,7 +990,7 @@ export default class llamacpp_extension extends AIEngine {}}- localStorage.setItem(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')+ await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')}async configureBackends(): Promise<void> {@@ -1009,7 +1026,7 @@ export default class llamacpp_extension extends AIEngine {}// Get stored backend preference- const storedBackendType = this.getStoredBackendType()+ const storedBackendType = await this.getStoredBackendType()let bestAvailableBackendString = ''// "Recommended" is computed against upstream releases only — a@@ -1036,7 +1053,7 @@ export default class llamacpp_extension extends AIEngine {logger.info(`Migrating stored backend type preference from old '${storedBackendType}' to new common type: '${migrationTarget}'`)- this.setStoredBackendType(migrationTarget)+ await this.setStoredBackendType(migrationTarget)}const effectiveStoredBackendType = migrationTarget || storedBackendType@@ -1059,7 +1076,7 @@ export default class llamacpp_extension extends AIEngine {`Stored backend type '${effectiveStoredBackendType}' not available, falling back to best backend`)// Clear the invalid stored preference- this.clearStoredBackendType()+ await this.clearStoredBackendType()// bestAvailableBackendString remains as the priority one calculated earlier}}@@ -1125,18 +1142,18 @@ export default class llamacpp_extension extends AIEngine {) {initialVersion = priorVersioninitialBackend = normalizedBackend- const currentStoredBackend = this.getStoredBackendType()+ const currentStoredBackend = await this.getStoredBackendType()if (currentStoredBackend !== normalizedBackend) {- this.setStoredBackendType(normalizedBackend)+ await this.setStoredBackendType(normalizedBackend)logger.info(`Stored backend type preference from saved setting: ${normalizedBackend}`)}}} else if (bestBackend) {- const currentStoredBackend = this.getStoredBackendType()+ const currentStoredBackend = await this.getStoredBackendType()if (currentStoredBackend !== bestBackend) {- this.setStoredBackendType(bestBackend)+ await this.setStoredBackendType(bestBackend)logger.info(`Stored backend type preference from best available: ${bestBackend}`)@@ -1432,7 +1449,7 @@ export default class llamacpp_extension extends AIEngine {// Map backend type for stored preference only (not for download/config)const effectiveBackendType = await mapOldBackendToNew(backend)- const currentStoredBackend = this.getStoredBackendType()+ const currentStoredBackend = await this.getStoredBackendType()// Persist settings and stored preference before mutating in-memory config,// so that if any of these steps fail, config remains consistent.@@ -1450,7 +1467,7 @@ export default class llamacpp_extension extends AIEngine {)if (currentStoredBackend !== effectiveBackendType) {- this.setStoredBackendType(effectiveBackendType)+ await this.setStoredBackendType(effectiveBackendType)logger.info(`Updated stored backend type preference: ${effectiveBackendType}`)@@ -1717,7 +1734,8 @@ export default class llamacpp_extension extends AIEngine {this.recomposeVersionBackend()const composite = this.config.version_backend- const currentStored = this.getStoredBackendType() || undefined+ const currentStored =+ (await this.getStoredBackendType()) || undefinedconst result = await handleSettingUpdate('version_backend',composite,@@ -1725,7 +1743,7 @@ export default class llamacpp_extension extends AIEngine {)if (result.backend_type_updated && result.effective_backend_type) {- this.setStoredBackendType(result.effective_backend_type)+ await this.setStoredBackendType(result.effective_backend_type)logger.info(`Updated backend type preference to: ${result.effective_backend_type}`)@@ -2025,7 +2043,7 @@ export default class llamacpp_extension extends AIEngine {private async migrateLegacyModels() {// Attempt to migrate only once- if (localStorage.getItem('cortex_models_migrated') === 'true') return+ if ((await getBackendSetting('cortex_models_migrated')) === 'true') returnconst janDataFolderPath = await getJanDataFolderPath()const modelsDir = await joinPath([janDataFolderPath, 'models'])@@ -2125,7 +2143,7 @@ export default class llamacpp_extension extends AIEngine {}}}- localStorage.setItem('cortex_models_migrated', 'true')+ await setBackendSetting('cortex_models_migrated', 'true')}/*@@ -2386,7 +2404,7 @@ export default class llamacpp_extension extends AIEngine {downloadItems.push({url: path,save_path: localPath,- proxy: getProxyConfig(),+ proxy: await getProxyConfig(),sha256:saveName === 'model.gguf'? opts.modelSha256diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.tsindex ee8089f25..c8699718f 100644--- a/extensions/llamacpp-extension/src/preset.test.ts+++ b/extensions/llamacpp-extension/src/preset.test.ts@@ -188,6 +188,26 @@ describe('generatePreset parallel reservation', () => {const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('parallel =')})++ it('reserves no extra slot when reservedBackgroundSlots is 0 (global)', async () => {+ setupModel('llama', {})+ await generatePreset('/p', '/jan', { parallel: 1 } as any, {+ supportsMtp: false,+ reservedBackgroundSlots: 0,+ })+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('parallel = 1')+ })++ it('reserves no extra slot when reservedBackgroundSlots is 0 (per-model)', async () => {+ setupModel('llama', { parallel: 3 })+ await generatePreset('/p', '/jan', {} as any, {+ supportsMtp: false,+ reservedBackgroundSlots: 0,+ })+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('parallel = 3')+ })})describe('generatePreset ctx-size default', () => {diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.tsindex 7376fd002..4b0548f9c 100644--- a/extensions/llamacpp-extension/src/preset.ts+++ b/extensions/llamacpp-extension/src/preset.ts@@ -76,9 +76,15 @@ export async function generatePreset(providerPath: string,janDataFolderPath: string,config: LlamacppConfig,- opts: { supportsMtp?: boolean } = {}+ opts: { supportsMtp?: boolean; reservedBackgroundSlots?: number } = {}): Promise<{ path: string; embeddingCount: number }> {const supportsMtp = opts.supportsMtp === true+ // Reserved background slot count (thread auto-titling). Disabling that+ // feature drops it to 0 so no extra parallel slot is provisioned.+ const reservedBackgroundSlots =+ typeof opts.reservedBackgroundSlots === 'number'+ ? opts.reservedBackgroundSlots+ : RESERVED_BACKGROUND_SLOTSconst modelsDir = await joinPath([providerPath, 'models'])// Ensure the directory exists; an empty install is fine — we still emit a@@ -191,7 +197,7 @@ export async function generatePreset(// parallel default = -1 (auto); positive user value is intent. The reserved// slot is added on top and never exposed in the setting's own value.if (typeof config.parallel === 'number' && config.parallel > 0) {- lines.push(`parallel = ${config.parallel + RESERVED_BACKGROUND_SLOTS}`)+ lines.push(`parallel = ${config.parallel + reservedBackgroundSlots}`)}// cont-batching default = true; emit only the explicit-off case.if (config.cont_batching === false) {@@ -394,7 +400,7 @@ export async function generatePreset(lines.push(`cache-type-v = ${escapeIniValue(mc.cache_type_v)}`)}if (typeof mc.parallel === 'number' && mc.parallel > 0) {- lines.push(`parallel = ${mc.parallel + RESERVED_BACKGROUND_SLOTS}`)+ lines.push(`parallel = ${mc.parallel + reservedBackgroundSlots}`)}if (mc.cont_batching === false) {lines.push('cont-batching = false')diff --git a/extensions/llamacpp-extension/src/test/backend.test.ts b/extensions/llamacpp-extension/src/test/backend.test.tsindex 8e4bbe7de..d793d333e 100644--- a/extensions/llamacpp-extension/src/test/backend.test.ts+++ b/extensions/llamacpp-extension/src/test/backend.test.ts@@ -41,7 +41,7 @@ vi.mock('@janhq/tauri-plugin-hardware-api', () => ({getSystemInfo: vi.fn(),}))vi.mock('../util', () => ({- getProxyConfig: vi.fn().mockReturnValue({ enabled: false }),+ getProxyConfig: vi.fn().mockResolvedValue({ enabled: false }),basenameNoExt: vi.fn((name: string) => name.replace(/\.tar\.gz$/, '')),}))vi.mock('@tauri-apps/api/path', () => ({@@ -105,7 +105,7 @@ describe('Backend functions', () => {vi.mocked(mockDownloadManager.downloadFiles).mockClear()// Re-apply after clearAllMocks wipes return valuesconst { getProxyConfig } = await import('../util')- vi.mocked(getProxyConfig).mockReturnValue({ enabled: false } as any)+ vi.mocked(getProxyConfig).mockResolvedValue({ enabled: false } as any)})afterEach(() => {diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex be68c4f71..6b72719a9 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -2,6 +2,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'import { normalizeLlamacppConfig } from '@janhq/tauri-plugin-llamacpp-api'+import { getBackendSetting, setBackendSetting } from '../backend-settings'++vi.mock('../backend-settings')// Mock fetch globallyglobal.fetch = vi.fn()@@ -428,11 +431,11 @@ describe('llamacpp_extension', () => {describe('migrateFitOff', () => {beforeEach(() => {- vi.mocked(localStorage.getItem).mockReturnValue(null)+ vi.mocked(getBackendSetting).mockResolvedValue(null)})it('should skip migration if already migrated', async () => {- vi.mocked(localStorage.getItem).mockReturnValue('1')+ vi.mocked(getBackendSetting).mockResolvedValue('1')extension['config'] = { fit: true } as anyextension['getSettings'] = vi.fn()@@ -450,7 +453,7 @@ describe('llamacpp_extension', () => {expect(extension['getSettings']).not.toHaveBeenCalled()expect(extension['updateSettings']).not.toHaveBeenCalled()- expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_fit_off_v1', '1')+ expect(setBackendSetting).toHaveBeenCalledWith('llamacpp_fit_off_v1', '1')})it('should disable fit when it is true', async () => {@@ -467,7 +470,7 @@ describe('llamacpp_extension', () => {expect(updatedSettings.find((s: any) => s.key === 'fit').controllerProps.value).toBe(false)expect(updatedSettings.find((s: any) => s.key === 'ctx_size').controllerProps.value).toBe(2048)expect(extension['config'].fit).toBe(false)- expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_fit_off_v1', '1')+ expect(setBackendSetting).toHaveBeenCalledWith('llamacpp_fit_off_v1', '1')})it('should not modify other settings during fit migration', async () => {diff --git a/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.ts b/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.tsindex d76ed4757..2198d2863 100644--- a/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.ts+++ b/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.ts@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'+vi.mock('../backend-settings')+describe('migrateLegacyModels', () => {let extension: llamacpp_extensiondiff --git a/extensions/llamacpp-extension/src/test/no-localstorage.test.ts b/extensions/llamacpp-extension/src/test/no-localstorage.test.tsnew file mode 100644index 000000000..66be75899--- /dev/null+++ b/extensions/llamacpp-extension/src/test/no-localstorage.test.ts@@ -0,0 +1,43 @@+import { describe, it, expect } from 'vitest'+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join } from 'node:path'++// Enforces the "backend-only persistence" rule: the extension must not touch+// webview localStorage (it isn't the source of truth on desktop — settings+// live in settings.json via backend-settings.ts). The single sanctioned+// exception is the one-time pre-backend migration, whose lines carry the+// `localstorage-migration-allowed` marker.+const SRC_DIR = join(__dirname, '..')+const ALLOW_MARKER = 'localstorage-migration-allowed'+// Actual usage (member/index access), not the word inside a comment.+const USAGE = /localStorage\s*[.[]/++function collectSourceFiles(dir: string): string[] {+ const out: string[] = []+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry)+ if (statSync(full).isDirectory()) {+ out.push(...collectSourceFiles(full))+ continue+ }+ if (!entry.endsWith('.ts')) continue+ if (entry.endsWith('.test.ts')) continue+ out.push(full)+ }+ return out+}++describe('no localStorage outside the sanctioned migration', () => {+ it('has no unmarked localStorage usage in extension source', () => {+ const offenders: string[] = []+ for (const file of collectSourceFiles(SRC_DIR)) {+ const lines = readFileSync(file, 'utf8').split('\n')+ lines.forEach((line, i) => {+ if (USAGE.test(line) && !line.includes(ALLOW_MARKER)) {+ offenders.push(`${file}:${i + 1}: ${line.trim()}`)+ }+ })+ }+ expect(offenders, offenders.join('\n')).toEqual([])+ })+})diff --git a/extensions/llamacpp-extension/src/util.test.ts b/extensions/llamacpp-extension/src/util.test.tsindex 6f510d409..ce043f31d 100644--- a/extensions/llamacpp-extension/src/util.test.ts+++ b/extensions/llamacpp-extension/src/util.test.ts@@ -7,23 +7,26 @@ import {getProxyConfig,truncateToTokenBudget,} from './util'+import { getBackendSetting } from './backend-settings'++vi.mock('./backend-settings')beforeEach(() => {vi.clearAllMocks()- vi.mocked(localStorage.getItem).mockClear()+ vi.mocked(getBackendSetting).mockReset()})-describe('getProxyConfig', () => {- it('should return null when no proxy configuration is stored', () => {- vi.mocked(localStorage.getItem).mockReturnValue(null)+describe('getProxyConfig', async () => {+ it('should return null when no proxy configuration is stored', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue(null)- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toBeNull()- expect(localStorage.getItem).toHaveBeenCalledWith('setting-proxy-config')+ expect(getBackendSetting).toHaveBeenCalledWith('setting-proxy-config')})- it('should return null when proxy is disabled', () => {+ it('should return null when proxy is disabled', async () => {const proxyConfig = {state: {proxyEnabled: false,@@ -40,14 +43,14 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toBeNull()})- it('should return null when proxy is enabled but no URL is provided', () => {+ it('should return null when proxy is enabled but no URL is provided', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -64,14 +67,14 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toBeNull()})- it('should return basic proxy configuration with SSL settings', () => {+ it('should return basic proxy configuration with SSL settings', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -88,9 +91,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'https://proxy.example.com:8080',@@ -102,7 +105,7 @@ describe('getProxyConfig', () => {})})- it('should include authentication when both username and password are provided', () => {+ it('should include authentication when both username and password are provided', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -119,9 +122,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'http://proxy.example.com:8080',@@ -135,7 +138,7 @@ describe('getProxyConfig', () => {})})- it('should not include authentication when only username is provided', () => {+ it('should not include authentication when only username is provided', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -152,9 +155,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'http://proxy.example.com:8080',@@ -168,7 +171,7 @@ describe('getProxyConfig', () => {expect(result?.password).toBeUndefined()})- it('should not include authentication when only password is provided', () => {+ it('should not include authentication when only password is provided', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -185,9 +188,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'http://proxy.example.com:8080',@@ -201,7 +204,7 @@ describe('getProxyConfig', () => {expect(result?.password).toBeUndefined()})- it('should parse no_proxy list correctly', () => {+ it('should parse no_proxy list correctly', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -218,9 +221,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'http://proxy.example.com:8080',@@ -238,7 +241,7 @@ describe('getProxyConfig', () => {})})- it('should handle empty no_proxy entries', () => {+ it('should handle empty no_proxy entries', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -255,9 +258,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'http://proxy.example.com:8080',@@ -270,7 +273,7 @@ describe('getProxyConfig', () => {})})- it('should handle mixed SSL verification settings', () => {+ it('should handle mixed SSL verification settings', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -287,9 +290,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'https://proxy.example.com:8080',@@ -304,7 +307,7 @@ describe('getProxyConfig', () => {})})- it('should handle all SSL verification settings as false', () => {+ it('should handle all SSL verification settings as false', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -321,9 +324,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'http://proxy.example.com:8080',@@ -335,7 +338,7 @@ describe('getProxyConfig', () => {})})- it('should handle all SSL verification settings as true', () => {+ it('should handle all SSL verification settings as true', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -352,9 +355,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'https://proxy.example.com:8080',@@ -366,7 +369,7 @@ describe('getProxyConfig', () => {})})- it('should log proxy configuration details', () => {+ it('should log proxy configuration details', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -383,9 +386,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- getProxyConfig()+ await getProxyConfig()expect(logger.info).toHaveBeenCalledWith('Using proxy configuration:', {url: 'https://proxy.example.com:8080',@@ -399,7 +402,7 @@ describe('getProxyConfig', () => {})})- it('should log proxy configuration without authentication', () => {+ it('should log proxy configuration without authentication', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -416,9 +419,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- getProxyConfig()+ await getProxyConfig()expect(logger.info).toHaveBeenCalledWith('Using proxy configuration:', {url: 'http://proxy.example.com:8080',@@ -432,10 +435,10 @@ describe('getProxyConfig', () => {})})- it('should return null and log error when JSON parsing fails', () => {- vi.mocked(localStorage.getItem).mockReturnValue('invalid-json')+ it('should return null and log error when JSON parsing fails', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue('invalid-json')- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toBeNull()expect(logger.error).toHaveBeenCalledWith(@@ -444,7 +447,7 @@ describe('getProxyConfig', () => {)})- it('should handle SOCKS proxy URLs', () => {+ it('should handle SOCKS proxy URLs', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -461,9 +464,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'socks5://proxy.example.com:1080',@@ -477,7 +480,7 @@ describe('getProxyConfig', () => {})})- it('should handle comprehensive proxy configuration', () => {+ it('should handle comprehensive proxy configuration', async () => {const proxyConfig = {state: {proxyEnabled: true,@@ -494,9 +497,9 @@ describe('getProxyConfig', () => {version: 0,}- vi.mocked(localStorage.getItem).mockReturnValue(JSON.stringify(proxyConfig))+ vi.mocked(getBackendSetting).mockResolvedValue(JSON.stringify(proxyConfig))- const result = getProxyConfig()+ const result = await getProxyConfig()expect(result).toEqual({url: 'https://secure-proxy.example.com:8443',diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.tsindex 5d7d6c8c8..007352f46 100644--- a/extensions/llamacpp-extension/src/util.ts+++ b/extensions/llamacpp-extension/src/util.ts@@ -1,5 +1,5 @@-import { invoke } from '@tauri-apps/api/core'import { logger } from '@janhq/core'+import { getBackendSetting, setBackendSetting } from './backend-settings'// File path utilitiesexport function basenameNoExt(filePath: string): string {@@ -43,19 +43,7 @@ const DEFAULT_EMBEDDING_MODEL_KEY = 'default-embedding-model'// extension sees the model the user actually picked in Settings; localStorage// is only a fallback for `dev:web` (no Tauri shell).async function readDefaultEmbeddingModelRaw(): Promise<string | null> {- try {- const value = await invoke<string | null>('settings_get', {- key: DEFAULT_EMBEDDING_MODEL_KEY,- })- if (value != null) return value- } catch {- /* not running under Tauri, or command unavailable */- }- try {- return localStorage.getItem(DEFAULT_EMBEDDING_MODEL_KEY)- } catch {- return null- }+ return getBackendSetting(DEFAULT_EMBEDDING_MODEL_KEY)}export async function getDefaultEmbeddingModelId(@@ -86,28 +74,18 @@ export async function setDefaultEmbeddingModelId(parsed.state = { ...state, defaultByProvider: map }if (parsed.version === undefined) parsed.version = 0const serialized = JSON.stringify(parsed)- try {- await invoke('settings_set', {- key: DEFAULT_EMBEDDING_MODEL_KEY,- value: serialized,- })- return- } catch {- /* not running under Tauri, or command unavailable */- }- localStorage.setItem(DEFAULT_EMBEDDING_MODEL_KEY, serialized)+ await setBackendSetting(DEFAULT_EMBEDDING_MODEL_KEY, serialized)} catch {/* non-fatal */}}-export function getProxyConfig(): Record<+export async function getProxyConfig(): Promise<Record<string,string | string[] | boolean-> | null {+> | null> {try {- // Retrieve proxy configuration from localStorage- const proxyConfigString = localStorage.getItem('setting-proxy-config')+ const proxyConfigString = await getBackendSetting('setting-proxy-config')if (!proxyConfigString) {return null}diff --git a/web-app/src/hooks/useInterfaceSettings.ts b/web-app/src/hooks/useInterfaceSettings.tsindex 650ad9be0..29c2b580e 100644--- a/web-app/src/hooks/useInterfaceSettings.ts+++ b/web-app/src/hooks/useInterfaceSettings.ts@@ -112,12 +112,14 @@ interface InterfaceSettingsState {showTokenSpeed: booleancoloredUserBubble: booleanrenderHtmlArtifacts: boolean+ autoGenerateTitle: booleansetFontSize: (size: FontSize) => voidsetAccentColor: (color: AccentColorValue) => voidsetNotificationPosition: (position: NotificationPosition) => voidsetShowTokenSpeed: (show: boolean) => voidsetColoredUserBubble: (colored: boolean) => voidsetRenderHtmlArtifacts: (render: boolean) => void+ setAutoGenerateTitle: (auto: boolean) => voidresetInterface: () => void}@@ -130,6 +132,7 @@ type InterfaceSettingsPersistedSlice = Omit<| 'setShowTokenSpeed'| 'setColoredUserBubble'| 'setRenderHtmlArtifacts'+ | 'setAutoGenerateTitle'>export const fontSizeOptions = [@@ -150,6 +153,7 @@ const createDefaultInterfaceValues = (): InterfaceSettingsPersistedSlice => {showTokenSpeed: true,coloredUserBubble: true,renderHtmlArtifacts: false,+ autoGenerateTitle: true,}}@@ -188,6 +192,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(showTokenSpeed: true,coloredUserBubble: true,renderHtmlArtifacts: false,+ autoGenerateTitle: true,})},@@ -223,6 +228,10 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(setRenderHtmlArtifacts: (render) => {set({ renderHtmlArtifacts: render })},++ setAutoGenerateTitle: (auto) => {+ set({ autoGenerateTitle: auto })+ },}},{@@ -236,6 +245,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(showTokenSpeed: state.showTokenSpeed,coloredUserBubble: state.coloredUserBubble,renderHtmlArtifacts: state.renderHtmlArtifacts,+ autoGenerateTitle: state.autoGenerateTitle,}),// Apply settings when hydrating from storageonRehydrateStorage: () => (state) => {@@ -276,6 +286,10 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(if (typeof state.renderHtmlArtifacts !== 'boolean') {state.renderHtmlArtifacts = false}++ if (typeof state.autoGenerateTitle !== 'boolean') {+ state.autoGenerateTitle = true+ }}// Return the state to be used for hydrationdiff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 4bb4abc22..052454b98 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -102,6 +102,8 @@"coloredUserBubbleDesc": "Use the accent color as the background of your messages. When off, they match assistant messages with plain text on a neutral background.","renderHtmlArtifacts": "Render HTML & SVG artifacts","renderHtmlArtifactsDesc": "Add a Preview tab to HTML and SVG code blocks. HTML runs the model-generated page in a sandboxed frame that executes its own scripts but cannot access Jan, your files, or the network; SVG renders statically with scripts disabled. Off by default.",+ "autoGenerateTitle": "Auto-generate chat title",+ "autoGenerateTitleDesc": "Automatically summarize new conversations into a thread title. Turn off to keep the default title until you rename it yourself.","windowBackground": "Window Background","windowBackgroundDesc": "Set the app window's background color.","appMainView": "App Main View",diff --git a/web-app/src/routes/settings/interface.tsx b/web-app/src/routes/settings/interface.tsxindex 81d1791d8..ade5c1d70 100644--- a/web-app/src/routes/settings/interface.tsx+++ b/web-app/src/routes/settings/interface.tsx@@ -28,6 +28,8 @@ function InterfaceSettings() {setColoredUserBubble,renderHtmlArtifacts,setRenderHtmlArtifacts,+ autoGenerateTitle,+ setAutoGenerateTitle,} = useInterfaceSettings()return (@@ -101,6 +103,16 @@ function InterfaceSettings() {/>}/>+ <CardItem+ title={t('settings:interface.autoGenerateTitle')}+ description={t('settings:interface.autoGenerateTitleDesc')}+ actions={+ <Switch+ checked={autoGenerateTitle}+ onCheckedChange={setAutoGenerateTitle}+ />+ }+ /><CardItemtitle={t('settings:interface.resetToDefault')}description={t('settings:interface.resetToDefaultDesc')}diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex ab5cadacb..ac7a2e9a1 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -16,6 +16,7 @@ import { useAppState } from '@/hooks/useAppState'import { SESSION_STORAGE_PREFIX } from '@/constants/chat'import { useChat } from '@/hooks/use-chat'import { useModelProvider } from '@/hooks/useModelProvider'+import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'import { renderInstructions } from '@/lib/instructionTemplate'import {Conversation,@@ -509,7 +510,13 @@ function ThreadDetail() {(assistantCount > 0 &&assistantCount % TITLE_REFRESH_EVERY_N_ASSISTANT_MESSAGES === 0)const currentThread = useThreads.getState().threads[threadId]- if (isRefreshTick && !currentThread?.metadata?.titleSetManually) {+ const autoGenerateTitle =+ useInterfaceSettings.getState().autoGenerateTitle+ if (+ autoGenerateTitle &&+ isRefreshTick &&+ !currentThread?.metadata?.titleSetManually+ ) {const TITLE_TRANSCRIPT_MAX_TURNS = 8const recent = localMessages.slice(-TITLE_TRANSCRIPT_MAX_TURNS)const inputText =