mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-26 05:27:06 +00:00
feat(web): export and import browser settings (#2442)
* feat(web): export and import browser settings from Settings → About Browser-local settings (theme, display, chat, voice, machine labels, ...) can now be exported to a JSON file and imported in another browser. Only an explicit allowlist (SETTINGS_STORAGE_KEYS) moves; credentials, hub URL, drafts, UI state and trust grants never do. Import replaces the allowlisted keys and reloads so every hook re-reads its value. A test scans web/src and shared/src storage code and fails on any hapi* key that is not classified as a setting or not, so new keys get decided by whoever adds them. Closes #2441 via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> * fix(web): reject malformed settings files and carry legacy fallback keys Addresses Swear Review on #2442: reject array settings and unknown versions before touching storage, and move legacy keys that settings still fall back to (tool-card display, active-only list filter, ElevenLabs voice) along with them. The session-list status filter is a Display setting, so it and unread-only are now settings too. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> --------- Co-authored-by: HAPI <noreply@hapi.run>
This commit is contained in:
@@ -143,6 +143,12 @@ Optional, not a requirement for every feature or a reason to expand a bug fix.
|
||||
- Opt in per feature; skip the wrapper if an upstream component already supplies onboarding.
|
||||
- Working example: `ScratchlistToggleButton` in `src/components/AssistantChat/ComposerButtons.tsx`. Use the source rather than maintaining a copied example here.
|
||||
|
||||
### Browser settings export/import
|
||||
|
||||
Settings → About exports and imports browser-local settings as JSON. Only keys in `SETTINGS_STORAGE_KEYS` (`src/lib/settingsTransfer.ts`) move; import replaces them and reloads.
|
||||
|
||||
A new `hapi*` localStorage key must be classified: in `SETTINGS_STORAGE_KEYS` if the user chose it to configure the app and it makes sense in another browser on the same hub, otherwise in `NOT_SETTINGS_KEYS` (`src/lib/settingsTransfer.test.ts`). Data, drafts, last-used values, per-session or per-path UI state, dismissals, device-bound state, credentials, and trust grants are not settings. The test fails on unclassified keys.
|
||||
|
||||
## Authentication
|
||||
|
||||
See `src/hooks/useAuth.ts` and `src/hooks/useAuthSource.ts`.
|
||||
|
||||
@@ -5,7 +5,11 @@ export function downloadBase64File(fileName: string, base64Content: string, mime
|
||||
bytes[index] = byteChars.charCodeAt(index)
|
||||
}
|
||||
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: mimeType ?? 'application/octet-stream' }))
|
||||
downloadBlob(fileName, new Blob([bytes], { type: mimeType ?? 'application/octet-stream' }))
|
||||
}
|
||||
|
||||
export function downloadBlob(fileName: string, blob: Blob): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = fileName
|
||||
|
||||
@@ -1278,6 +1278,11 @@ export default {
|
||||
'settings.about.website': 'Website',
|
||||
'settings.about.appVersion': 'App Version',
|
||||
'settings.about.protocolVersion': 'Protocol Version',
|
||||
'settings.about.backup.title': 'Settings',
|
||||
'settings.about.backup.description': 'Stored in this browser only.',
|
||||
'settings.about.backup.exportButton': 'Export',
|
||||
'settings.about.backup.importButton': 'Import',
|
||||
'settings.about.backup.importError': 'This file is not a HAPI settings export.',
|
||||
|
||||
// Browse / Workspace
|
||||
'browse.title': 'Browse',
|
||||
|
||||
@@ -1183,6 +1183,11 @@ export default {
|
||||
'settings.about.website': 'Сайт',
|
||||
'settings.about.appVersion': 'Версия приложения',
|
||||
'settings.about.protocolVersion': 'Версия протокола',
|
||||
'settings.about.backup.title': 'Настройки',
|
||||
'settings.about.backup.description': 'Хранятся только в этом браузере.',
|
||||
'settings.about.backup.exportButton': 'Экспорт',
|
||||
'settings.about.backup.importButton': 'Импорт',
|
||||
'settings.about.backup.importError': 'Этот файл не является экспортом настроек HAPI.',
|
||||
|
||||
// Обзор / Рабочее пространство
|
||||
'browse.title': 'Обзор',
|
||||
|
||||
@@ -1276,6 +1276,11 @@ export default {
|
||||
'settings.about.website': '官方网站',
|
||||
'settings.about.appVersion': '应用版本',
|
||||
'settings.about.protocolVersion': '协议版本',
|
||||
'settings.about.backup.title': '设置',
|
||||
'settings.about.backup.description': '仅保存在当前浏览器。',
|
||||
'settings.about.backup.exportButton': '导出',
|
||||
'settings.about.backup.importButton': '导入',
|
||||
'settings.about.backup.importError': '此文件不是 HAPI 设置导出文件。',
|
||||
|
||||
// Browse / Workspace
|
||||
'browse.title': '浏览',
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { exportSettings, importSettings, SETTINGS_STORAGE_KEYS } from './settingsTransfer'
|
||||
|
||||
/**
|
||||
* `hapi*` literals in storage code that are NOT settings: data, drafts, history,
|
||||
* per-session/per-path UI state, last-used values, dismissals, device-bound
|
||||
* state, credentials, trust grants, and event names.
|
||||
*/
|
||||
const NOT_SETTINGS_KEYS = new Set([
|
||||
// Credentials, hub, device-bound state
|
||||
'hapi_access_token::',
|
||||
'hapi_hub_url',
|
||||
'hapi.push.disabled',
|
||||
'hapi.push.vapidKey',
|
||||
'hapi-sidebar-width',
|
||||
// Trust grant: an imported file must not be able to allow link schemes
|
||||
'hapi-allowed-schemes',
|
||||
// Data, drafts, history, last-used values
|
||||
'hapi.codexImportedSessions',
|
||||
'hapi.sessionReadState.v1:',
|
||||
'hapi.scratchlist.v1.',
|
||||
'hapi-recent-skills',
|
||||
'hapi:recentPaths',
|
||||
'hapi:lastMachineId',
|
||||
'hapi:newSession:agent',
|
||||
'hapi:newSession:yolo',
|
||||
'hapi:newSession:launchSettings:v1',
|
||||
'hapi-share-transfers',
|
||||
'hapi:composer-drafts',
|
||||
'hapi:ask-user-question-drafts',
|
||||
'hapi:new-session-form-draft',
|
||||
'hapi:queued-edit-recovery',
|
||||
'hapi:message-window:v2:',
|
||||
// Transient UI state and filters
|
||||
'hapi-dir-scroll-',
|
||||
'hapi-dir-expanded-',
|
||||
'hapi-file-candidate',
|
||||
'hapi-files-tab',
|
||||
'hapi-mention-inactive-collapsed',
|
||||
'hapi-session-list-machine-filter',
|
||||
'hapi.scratchlist-collapsed.v1.',
|
||||
// Onboarding and dismissals
|
||||
'hapi.fue.v1.',
|
||||
'hapi.fue.v1.scratchlist-toggle',
|
||||
'hapi-voice-context-notice',
|
||||
'hapi.scratchlist.v2.banner-dismissed.',
|
||||
'hapi.scratchlist.v2.migrated.',
|
||||
// Not storage keys: event names and the export file format tag
|
||||
'hapi-web-settings',
|
||||
'hapi-color-theme-change',
|
||||
'hapi-composer-toolbar-layout-change',
|
||||
'hapi-session-preview-limit-changed',
|
||||
'hapi-tool-card-display-mode-change',
|
||||
'hapi-transcription-providers-refresh',
|
||||
'hapi-voice-backends-refresh',
|
||||
'hapi-voice-input-change',
|
||||
'hapi.push.subscriptionChanged',
|
||||
'hapi.sessionReadState.changed',
|
||||
'hapi:codex-imported-sessions-updated',
|
||||
])
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
||||
const path = join(dir, entry.name)
|
||||
if (entry.isDirectory()) return entry.name === 'test' ? [] : sourceFiles(path)
|
||||
return /\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name) ? [path] : []
|
||||
})
|
||||
}
|
||||
|
||||
describe('SETTINGS_STORAGE_KEYS', () => {
|
||||
it('classifies every hapi storage key as setting or not', () => {
|
||||
const roots = [resolve(__dirname, '..'), resolve(__dirname, '../../../shared/src')]
|
||||
const found = new Set<string>()
|
||||
for (const file of roots.flatMap(sourceFiles)) {
|
||||
const source = readFileSync(file, 'utf8')
|
||||
if (!/localStorage|STORAGE_KEY/.test(source)) continue
|
||||
for (const match of source.matchAll(/['"`](hapi[-._:][\w.:-]*)/g)) found.add(match[1])
|
||||
}
|
||||
const settings = new Set(SETTINGS_STORAGE_KEYS)
|
||||
const unclassified = [...found].filter((key) => !settings.has(key) && !NOT_SETTINGS_KEYS.has(key))
|
||||
expect(unclassified, 'Add new keys to SETTINGS_STORAGE_KEYS (settingsTransfer.ts) or NOT_SETTINGS_KEYS (this file)').toEqual([])
|
||||
expect(SETTINGS_STORAGE_KEYS.filter((key) => NOT_SETTINGS_KEYS.has(key))).toEqual([])
|
||||
expect(SETTINGS_STORAGE_KEYS.filter((key) => !found.has(key)), 'Stale settings keys').toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings export/import', () => {
|
||||
beforeEach(() => localStorage.clear())
|
||||
|
||||
it('round-trips settings and ignores everything else', () => {
|
||||
localStorage.setItem('hapi-appearance', 'dark')
|
||||
localStorage.setItem('hapi-machine-labels', '{"m1":"Laptop"}')
|
||||
localStorage.setItem('hapi_access_token::https://hub', 'secret')
|
||||
const file = exportSettings()
|
||||
expect(file.settings).toEqual({ 'hapi-appearance': 'dark', 'hapi-machine-labels': '{"m1":"Laptop"}' })
|
||||
|
||||
localStorage.clear()
|
||||
localStorage.setItem('hapi-font-scale', '1.2')
|
||||
localStorage.setItem('hapi-tool-grouping-mode', 'classified') // legacy fallback must not survive import
|
||||
expect(importSettings(JSON.stringify({
|
||||
...file,
|
||||
settings: { ...file.settings, 'hapi_hub_url': 'https://evil', 'hapi-lang': 42 },
|
||||
}))).toBe(2)
|
||||
expect(localStorage.getItem('hapi-appearance')).toBe('dark')
|
||||
expect(localStorage.getItem('hapi-machine-labels')).toBe('{"m1":"Laptop"}')
|
||||
expect(localStorage.getItem('hapi-font-scale')).toBeNull()
|
||||
expect(localStorage.getItem('hapi-tool-grouping-mode')).toBeNull()
|
||||
expect(localStorage.getItem('hapi_hub_url')).toBeNull()
|
||||
expect(localStorage.getItem('hapi-lang')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects files that are not settings exports without touching storage', () => {
|
||||
localStorage.setItem('hapi-appearance', 'dark')
|
||||
expect(() => importSettings('{"settings":{}}')).toThrow()
|
||||
expect(() => importSettings('{"format":"hapi-web-settings","version":1,"settings":[]}')).toThrow()
|
||||
expect(() => importSettings('{"format":"hapi-web-settings","version":2,"settings":{}}')).toThrow()
|
||||
expect(() => importSettings('not json')).toThrow()
|
||||
expect(localStorage.getItem('hapi-appearance')).toBe('dark')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import { VOICE_PERSONALITY_STORAGE_KEY } from '@hapi/protocol/voice-personality'
|
||||
import { LEGACY_ELEVENLABS_VOICE_STORAGE_KEY, VOICE_BACKEND_PREFERENCE_STORAGE_KEY, VOICE_PICKER_STORAGE_KEYS } from '@hapi/protocol/voicePickerCatalog'
|
||||
|
||||
/**
|
||||
* localStorage keys that hold user settings, i.e. values the user chose to
|
||||
* configure the app that make sense on another browser on the same hub,
|
||||
* plus legacy keys a setting still falls back to. Only these keys are
|
||||
* exported or imported.
|
||||
*
|
||||
* Adding a `hapi*` storage key? Put it here if it is a setting, otherwise in
|
||||
* NOT_SETTINGS_KEYS in settingsTransfer.test.ts. That test fails on unclassified keys.
|
||||
*/
|
||||
export const SETTINGS_STORAGE_KEYS: readonly string[] = [
|
||||
// Display
|
||||
'hapi-appearance',
|
||||
'hapi-color-theme',
|
||||
'hapi-theme-colors',
|
||||
'hapi-font-scale',
|
||||
'hapi-terminal-font-size',
|
||||
'hapi-lang',
|
||||
'hapi-code-wrap',
|
||||
'hapi-tool-card-display-mode',
|
||||
'hapi-tool-grouping-mode', // legacy fallbacks, still read when the key above is unset
|
||||
'hapi-terminal-tool-display-mode',
|
||||
'hapi-tool-group-bg',
|
||||
'hapi-user-message-bg',
|
||||
'hapi-concise-chat-mode',
|
||||
'hapi-reasoning-collapsed',
|
||||
'hapi-codex-exploration-collapsed',
|
||||
'hapi-session-header-metadata',
|
||||
'hapi.filePreview.markdownMode.v1',
|
||||
// Chat and composer
|
||||
'hapi-composer-enter-behavior',
|
||||
'hapi-composer-toolbar-layout',
|
||||
'hapi.composer.richMentions',
|
||||
'hapi-open-external-links-in-new-tab',
|
||||
'hapi-auto-bridge-transient-model-errors',
|
||||
'hapi.sessionExportFormat',
|
||||
// Sessions, machines, files
|
||||
'hapi-app-badge-enabled',
|
||||
'hapi-keep-unread-sessions-visible',
|
||||
'hapi-pin-in-progress-sessions',
|
||||
'hapi-session-list-status-mode',
|
||||
'hapi-session-list-status',
|
||||
'hapi-session-list-sort',
|
||||
'hapi-session-list-active-first',
|
||||
'hapi-session-list-unread-only',
|
||||
'hapi-show-active-sessions-only', // legacy fallback for hapi-session-list-status
|
||||
'hapi-session-preview-limit',
|
||||
'hapi-machine-labels',
|
||||
'hapi-directory-sort',
|
||||
'hapi:workspaceBrowserShowHidden',
|
||||
// Voice
|
||||
'hapi-voice-mode',
|
||||
'hapi-voice-lang',
|
||||
'hapi-voice-proactive',
|
||||
'hapi-transcription-provider',
|
||||
'hapi-transcription-mode',
|
||||
VOICE_BACKEND_PREFERENCE_STORAGE_KEY,
|
||||
...Object.values(VOICE_PICKER_STORAGE_KEYS),
|
||||
LEGACY_ELEVENLABS_VOICE_STORAGE_KEY,
|
||||
VOICE_PERSONALITY_STORAGE_KEY,
|
||||
]
|
||||
|
||||
const FORMAT = 'hapi-web-settings'
|
||||
|
||||
export type SettingsFile = {
|
||||
format: typeof FORMAT
|
||||
version: 1
|
||||
exportedAt: string
|
||||
settings: Record<string, string>
|
||||
}
|
||||
|
||||
export function exportSettings(storage: Storage = localStorage): SettingsFile {
|
||||
const settings: Record<string, string> = {}
|
||||
for (const key of SETTINGS_STORAGE_KEYS) {
|
||||
const value = storage.getItem(key)
|
||||
if (value !== null) settings[key] = value
|
||||
}
|
||||
return { format: FORMAT, version: 1, exportedAt: new Date().toISOString(), settings }
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every settings key with the file's value; keys absent from the file
|
||||
* are removed (back to default). Unknown keys and non-string values are ignored.
|
||||
* Throws if the text is not a settings file; storage is untouched in that case.
|
||||
*/
|
||||
export function importSettings(text: string, storage: Storage = localStorage): number {
|
||||
const parsed: unknown = JSON.parse(text)
|
||||
const file = parsed as Partial<SettingsFile> | null
|
||||
if (
|
||||
typeof file !== 'object' || file === null
|
||||
|| file.format !== FORMAT || file.version !== 1
|
||||
|| typeof file.settings !== 'object' || file.settings === null || Array.isArray(file.settings)
|
||||
) {
|
||||
throw new Error('Not a HAPI settings file')
|
||||
}
|
||||
const settings = file.settings
|
||||
let applied = 0
|
||||
for (const key of SETTINGS_STORAGE_KEYS) {
|
||||
const value = Object.hasOwn(settings, key) ? settings[key] : undefined
|
||||
if (typeof value === 'string') {
|
||||
storage.setItem(key, value)
|
||||
applied += 1
|
||||
} else {
|
||||
storage.removeItem(key)
|
||||
}
|
||||
}
|
||||
return applied
|
||||
}
|
||||
@@ -1,9 +1,36 @@
|
||||
import { useState, type ChangeEvent } from 'react'
|
||||
import { PROTOCOL_VERSION } from '@hapi/protocol'
|
||||
import { useTranslation } from '@/lib/use-translation'
|
||||
import { downloadBlob } from '@/lib/file-download'
|
||||
import { exportSettings, importSettings } from '@/lib/settingsTransfer'
|
||||
import { SettingsPageContent, SettingsRow, SettingsSection } from '@/components/settings/SettingsPrimitives'
|
||||
|
||||
const buttonClassName = 'cursor-pointer rounded-lg bg-[var(--app-button)] px-3 py-2 text-sm font-medium text-[var(--app-button-text)]'
|
||||
|
||||
export default function SettingsAboutPage() {
|
||||
const { t } = useTranslation()
|
||||
const [importError, setImportError] = useState(false)
|
||||
|
||||
const handleExport = () => {
|
||||
const file = exportSettings()
|
||||
const blob = new Blob([JSON.stringify(file, null, 2)], { type: 'application/json' })
|
||||
downloadBlob(`hapi-settings-${file.exportedAt.slice(0, 10)}.json`, blob)
|
||||
}
|
||||
|
||||
const handleImport = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const selected = event.target.files?.[0]
|
||||
event.target.value = ''
|
||||
if (!selected) return
|
||||
try {
|
||||
importSettings(await selected.text())
|
||||
} catch {
|
||||
setImportError(true)
|
||||
return
|
||||
}
|
||||
// Hooks cache their values on mount; reload so every setting is re-read.
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsPageContent description={t('settings.about.description')}>
|
||||
<SettingsSection>
|
||||
@@ -13,6 +40,21 @@ export default function SettingsAboutPage() {
|
||||
<SettingsRow label={t('settings.about.appVersion')} trailing={<span className="text-[var(--app-hint)]">{__APP_VERSION__}</span>} />
|
||||
<SettingsRow label={t('settings.about.protocolVersion')} trailing={<span className="text-[var(--app-hint)]">{PROTOCOL_VERSION}</span>} />
|
||||
</SettingsSection>
|
||||
<SettingsSection>
|
||||
<SettingsRow label={t('settings.about.backup.title')} description={t('settings.about.backup.description')} trailing={
|
||||
<div className="flex gap-2">
|
||||
<button type="button" onClick={handleExport} className={buttonClassName}>
|
||||
{t('settings.about.backup.exportButton')}
|
||||
</button>
|
||||
<label className={`${buttonClassName} focus-within:ring-2 focus-within:ring-[var(--app-link)]`}>
|
||||
{t('settings.about.backup.importButton')}
|
||||
<input type="file" accept="application/json,.json" className="sr-only" onChange={(event) => void handleImport(event)} />
|
||||
</label>
|
||||
</div>
|
||||
}>
|
||||
{importError ? <div role="alert" className="mt-0.5 text-xs text-red-600 dark:text-red-400">{t('settings.about.backup.importError')}</div> : null}
|
||||
</SettingsRow>
|
||||
</SettingsSection>
|
||||
</SettingsPageContent>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -483,6 +483,16 @@ describe('responsive settings pages', () => {
|
||||
expect(screen.getByRole('link', { name: 'hapi.run' })).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
})
|
||||
|
||||
it('reports an invalid settings import file and keeps current settings', async () => {
|
||||
localStorage.setItem('hapi-appearance', 'dark')
|
||||
const { container } = renderPage(<SettingsAboutPage />)
|
||||
expect(screen.getByRole('button', { name: 'Export' })).toBeInTheDocument()
|
||||
const input = container.querySelector('input[type="file"]') as HTMLInputElement
|
||||
fireEvent.change(input, { target: { files: [new File(['{}'], 'other.json', { type: 'application/json' })] } })
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('not a HAPI settings export')
|
||||
expect(localStorage.getItem('hapi-appearance')).toBe('dark')
|
||||
})
|
||||
|
||||
it('links common voice settings to full-page voices and advanced pages', () => {
|
||||
renderPage(<SettingsVoicePage />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Voice/ }))
|
||||
|
||||
Reference in New Issue
Block a user