diff --git a/changelog/unreleased/account-bundle-export-import.md b/changelog/unreleased/account-bundle-export-import.md new file mode 100644 index 00000000..5fd0d67e --- /dev/null +++ b/changelog/unreleased/account-bundle-export-import.md @@ -0,0 +1,9 @@ +### English + +- Added full account export/import on the Accounts page. Export all providers' accounts and their settings to one JSON file, copy it to another computer, and import it there to restore them. +- The export file includes stored sign-in credentials; keep it private. + +### 中文 + +- 账号页新增全量导出/导入:可把所有供应商的账号及配置导出为一个 JSON 文件,复制到另一台电脑后导入即可恢复。 +- 导出文件包含登录凭证,请妥善保管。 diff --git a/frontend/src/api/overview.ts b/frontend/src/api/overview.ts index 37a543a2..486286b7 100644 --- a/frontend/src/api/overview.ts +++ b/frontend/src/api/overview.ts @@ -489,3 +489,52 @@ export function importAccount(bundle: Record) { export function exportAccount(accountId: string) { return api>(`/api/accounts/${encodeURIComponent(accountId)}/export`) } + +export type AccountBundle = { + format: string + version: number + exported_at: string + count: number + accounts: AccountBundleEntry[] +} + +export type AccountBundleEntry = { + name: string + provider: string + region: string + auth_type?: string + enabled: boolean + max_inflight: number + priority: number + drop_system_prompt?: boolean + model_aliases?: Record + enabled_models?: string[] + models_restricted?: boolean + auto_checkin?: boolean + checkin_time?: string + workbuddy_auto_checkin?: boolean + workbuddy_checkin_time?: string + proxy_url?: string + credential?: { + format: string + credential?: unknown + user_blob?: string + machine_id?: string + } +} + +export type AccountImportResult = { + object?: string + succeeded?: number + failed?: number + data?: unknown[] + errors?: Array<{ index?: number; name?: string; message?: string }> +} + +export function exportAccountBundle() { + return api('/api/accounts/export') +} + +export function importAccountBundle(bundle: AccountBundle) { + return api('/api/accounts/import/bundle', { method: 'POST', body: JSON.stringify(bundle) }) +} diff --git a/frontend/src/components/account/AccountBundleImportModal.tsx b/frontend/src/components/account/AccountBundleImportModal.tsx new file mode 100644 index 00000000..d3fa34cf --- /dev/null +++ b/frontend/src/components/account/AccountBundleImportModal.tsx @@ -0,0 +1,81 @@ +import { Button, Modal } from '@heroui/react' +import { X } from '@phosphor-icons/react' +import type { AccountBundle } from '@/api/overview' + +type Props = { + isOpen: boolean + bundle: AccountBundle | null + fileName?: string + isPending?: boolean + t: (key: string, vars?: Record) => string + onClose: () => void + onConfirm: () => void +} + +/** Confirmation dialog for a full console account migration bundle. */ +export function AccountBundleImportModal({ + isOpen, + bundle, + fileName, + isPending, + t, + onClose, + onConfirm, +}: Props) { + const count = bundle?.accounts?.length ?? 0 + const withCredentials = bundle?.accounts?.filter((entry) => Boolean(entry.credential)).length ?? 0 + + return ( + { + if (!open && !isPending) onClose() + }} + > + + + + +
+ {t('bundleImportConfirmTitle')} +

+ {fileName ? t('bundleImportConfirmHint', { file: fileName }) : t('bundleImportConfirmHintNoFile')} +

+
+ + + +
+ +
+
{count}
+
{t('bundleImportAccountCount')}
+
+

{t('bundleImportCountDetail', { credentials: withCredentials })}

+

{t('bundleImportAdditiveHint')}

+

{t('bundleExportHint')}

+
+ + + + +
+
+
+
+ ) +} diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index 0ab9dce2..8fd09a13 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -766,6 +766,11 @@ export const messages: Record = { rewarmDone: 'Rewarm completed', accountsSigned: '{n} / {total} accounts ready', addAccount: 'Add account', + exportAll: 'Export all accounts', + importAll: 'Import all accounts', + bundleExportHint: 'Keep this file private — it contains sign-in credentials.', + toastAccountsExporting: 'Preparing account export…', + toastAccountsExported: 'Exported {n} accounts to a file.', batchImport: 'Batch import', batchImportLoading: 'Importing WorkBuddy accounts…', batchImportUnrecognized: 'Could not recognize this credential file format.', @@ -781,6 +786,15 @@ export const messages: Record = { batchImportConfirmAction: 'Import', batchImportFormatUnknown: 'Unknown format', batchImportProviderUnknown: 'Unknown provider', + bundleImportConfirmTitle: 'Import all accounts?', + bundleImportConfirmHint: 'From {file}. This restores the accounts stored in the file.', + bundleImportConfirmHintNoFile: 'This restores the accounts stored in the selected file.', + bundleImportConfirmAction: 'Import all', + bundleImportAccountCount: 'accounts in this file', + bundleImportCountDetail: '{credentials} of them include a stored sign-in credential.', + bundleImportAdditiveHint: 'Import adds new accounts with fresh IDs. Existing accounts are not changed.', + bundleImportLoading: 'Importing accounts…', + bundleImportUnrecognized: 'This is not a valid full account export file.', accountName: 'Account name', accountNameRequired: 'Enter an account name.', accountCreated: 'Account created. Session is starting.', @@ -1774,6 +1788,11 @@ export const messages: Record = { rewarmDone: 'Rewarm 完成', accountsSigned: '{n} / {total} 个账号就绪', addAccount: '添加账号', + exportAll: '导出全部账号', + importAll: '导入全部账号', + bundleExportHint: '请妥善保管此文件——其中包含登录凭证。', + toastAccountsExporting: '正在准备账号导出…', + toastAccountsExported: '已将 {n} 个账号导出到文件。', batchImport: '批量导入', batchImportLoading: '正在导入 WorkBuddy 账号…', batchImportUnrecognized: '无法识别此凭证文件格式。', @@ -1789,6 +1808,15 @@ export const messages: Record = { batchImportConfirmAction: '导入', batchImportFormatUnknown: '未知格式', batchImportProviderUnknown: '未知供应商', + bundleImportConfirmTitle: '导入全部账号?', + bundleImportConfirmHint: '来自 {file}。将恢复文件中保存的账号。', + bundleImportConfirmHintNoFile: '将恢复所选文件中保存的账号。', + bundleImportConfirmAction: '全部导入', + bundleImportAccountCount: '个账号(此文件中)', + bundleImportCountDetail: '其中 {credentials} 个包含已保存的登录凭证。', + bundleImportAdditiveHint: '导入会创建新账号并分配新 ID,不会修改已有账号。', + bundleImportLoading: '正在导入账号…', + bundleImportUnrecognized: '这不是有效的全量账号导出文件。', accountName: '账号名称', accountNameRequired: '请输入账号名称。', accountCreated: '账号已创建,会话正在启动。', diff --git a/frontend/src/lib/accountBundle.ts b/frontend/src/lib/accountBundle.ts new file mode 100644 index 00000000..4833e26e --- /dev/null +++ b/frontend/src/lib/accountBundle.ts @@ -0,0 +1,40 @@ +import type { AccountBundle } from '@/api/overview' + +export const ACCOUNT_BUNDLE_FORMAT = 'cli2api-accounts' + +export function isAccountBundle(value: unknown): value is AccountBundle { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false + const record = value as Record + return ( + typeof record.format === 'string' && + record.format.trim().toLowerCase() === ACCOUNT_BUNDLE_FORMAT && + Array.isArray(record.accounts) + ) +} + +export function parseAccountBundleText(text: string): AccountBundle { + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + throw new Error('bad_json') + } + if (!isAccountBundle(parsed)) throw new Error('bad_bundle') + return parsed as AccountBundle +} + +export function downloadAccountBundle(bundle: AccountBundle) { + const text = JSON.stringify(bundle, null, 2) + const blob = new Blob([text], { type: 'application/json' }) + const url = URL.createObjectURL(blob) + const stamp = (bundle.exported_at || new Date().toISOString()) + .replace(/[:.]/g, '-') + .slice(0, 19) + const anchor = document.createElement('a') + anchor.href = url + anchor.download = `cli2api-accounts-${stamp}.json` + document.body.appendChild(anchor) + anchor.click() + anchor.remove() + URL.revokeObjectURL(url) +} diff --git a/frontend/src/pages/AccountsPage.tsx b/frontend/src/pages/AccountsPage.tsx index 4c38acc8..13ac0ff2 100644 --- a/frontend/src/pages/AccountsPage.tsx +++ b/frontend/src/pages/AccountsPage.tsx @@ -5,6 +5,7 @@ import { Button, Label, ListBox, Select } from '@heroui/react' import { ArrowsClockwise, CalendarCheck, + DownloadSimple, MagnifyingGlass, Plus, UploadSimple, @@ -27,6 +28,8 @@ import { checkinAccount, deleteAccount, exportAccount, + exportAccountBundle, + importAccountBundle, fetchAccounts, fetchProviders, completeLoginCallback, @@ -61,6 +64,9 @@ import { summarizeWorkbuddyImportResult, type WorkbuddyImportResult, } from '@/lib/workbuddyImport' +import { downloadAccountBundle, parseAccountBundleText } from '@/lib/accountBundle' +import { AccountBundleImportModal } from '@/components/account/AccountBundleImportModal' +import type { AccountBundle } from '@/api/overview' function kiroImportEntries(bundle: Record): Record[] { if (!Array.isArray(bundle.accounts)) return [bundle] @@ -106,6 +112,11 @@ export function AccountsPage() { const hasAccounts = rows.length > 0 const [addOpen, setAddOpen] = useState(false) const [batchImporting, setBatchImporting] = useState(false) + const [bundleExporting, setBundleExporting] = useState(false) + const [bundleImporting, setBundleImporting] = useState(false) + const [bundleConfirmOpen, setBundleConfirmOpen] = useState(false) + const [bundleImportData, setBundleImportData] = useState(null) + const [bundleImportFileName, setBundleImportFileName] = useState('') const [batchConfirmOpen, setBatchConfirmOpen] = useState(false) const [batchDetection, setBatchDetection] = useState(null) const [batchBundle, setBatchBundle] = useState | null>(null) @@ -357,6 +368,96 @@ export function AccountsPage() { }) } + async function onExportAll() { + if (bundleExporting) return + setBundleExporting(true) + const toastId = 'accounts-export-all' + toast({ id: toastId, type: 'loading', title: t('toastAccountsExporting') }) + try { + const bundle = await exportAccountBundle() + downloadAccountBundle(bundle) + toast({ + id: toastId, + type: 'success', + title: t('toastAccountsExported', { n: bundle.count ?? bundle.accounts.length }), + description: t('bundleExportHint'), + }) + } catch (error) { + toast({ + id: toastId, + type: 'error', + title: t('toastFailed'), + description: error instanceof Error ? error.message : String(error), + }) + } finally { + setBundleExporting(false) + } + } + + function closeBundleConfirm() { + if (bundleImporting) return + setBundleConfirmOpen(false) + setBundleImportData(null) + setBundleImportFileName('') + } + + async function onBundleImportFile(event: ChangeEvent) { + const file = event.target.files?.[0] + event.target.value = '' + if (!file) return + try { + const raw = await file.text() + const bundle = parseAccountBundleText(raw) + setBundleImportData(bundle) + setBundleImportFileName(file.name) + setBundleConfirmOpen(true) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + toast({ + type: 'error', + title: message === 'bad_json' ? t('wizardBadJson') : t('bundleImportUnrecognized'), + }) + } + } + + async function onBundleImportConfirm() { + if (!bundleImportData || bundleImporting) return + setBundleImporting(true) + const toastId = 'bundle-import-accounts' + toast({ id: toastId, type: 'loading', title: t('bundleImportLoading') }) + try { + const result = await importAccountBundle(bundleImportData) + const succeeded = result.succeeded ?? 0 + const failed = result.failed ?? 0 + const failureSummary = (result.errors || []) + .slice(0, 3) + .map((item) => item.message || `index ${item.index}`) + .filter(Boolean) + .join('; ') + toast({ + id: toastId, + type: failed > 0 && succeeded === 0 ? 'error' : failed > 0 ? 'info' : 'success', + title: failed > 0 + ? t('accountImportPartial').replace('{ok}', String(succeeded)).replace('{fail}', String(failed)) + : t('accountImportBatch').replace('{n}', String(succeeded)), + description: failureSummary || undefined, + }) + setBundleConfirmOpen(false) + setBundleImportData(null) + setBundleImportFileName('') + if (succeeded > 0) await reloadAccounts(false) + } catch (error) { + toast({ + id: toastId, + type: 'error', + title: t('toastFailed'), + description: error instanceof Error ? error.message : String(error), + }) + } finally { + setBundleImporting(false) + } + } + async function onToggle(id: string, selected: boolean) { setEnabledById((current) => ({ ...current, [id]: selected })) await run(id, 'toggle', async () => { @@ -691,6 +792,30 @@ export function AccountsPage() { ) : null}
+ + {/* + Separate file picker for full account migration bundles. Kept + distinct from the credential "batch import" below on purpose. + */} + + void onBundleImportFile(event)} + /> @@ -706,7 +831,7 @@ export function AccountsPage() {