378 lines
23 KiB
JavaScript
378 lines
23 KiB
JavaScript
// v3.0.5 「备份里的设置还原不回来」端到端契约(用户实测缺陷)
|
||
//
|
||
// 根因(复核结论):备份导出把**对外脱敏展示形态**当完整设置写进备份 ——
|
||
// doBackup 走 `api('config?full=1')`,而 `wApi` 里那个分支实际返回的是 `wCfgPublic()`
|
||
// (设置弹窗用的展示形态:字段是白名单子集 + 密钥掩码)。
|
||
// 后果:① 备份里**没有** `imageTransfer.compression` 等字段 ⇒ 还原后压缩等设置回不来;
|
||
// ② `withKeys` 开关形同虚设(展示形态里根本没有 providers[].keys[].value / llm.apiKey)。
|
||
// 同形状缺陷此前已造成过一次线上事故:导入图片时 `compressConf` 拿到 undefined ⇒ 压缩被静默跳过。
|
||
//
|
||
// 本文件是**行为级**证据链(走真实 UI + 真实备份文件):
|
||
// ① 导出/改值/导入往返 ⇒ 可观察设置恢复为备份里的值(用户报的那句话的直接证明);
|
||
// ② withKeys=false ⇒ 备份内全部敏感字段为 __KEEP__,且备份字符串里**没有任何明文密钥**;
|
||
// ③ withKeys=true ⇒ 备份内确实带明文(等于导出时的本机值);
|
||
// ④ __KEEP__ 而本机无值时 ⇒ 恢复过程给出**可见提示**(不静默留空),且盘上不残留 __KEEP__ 字面量。
|
||
// 运行:npm run build && IWB_E2E_SPECS=tests/iwb-backup-config.spec.js node scripts/serve-test.js
|
||
const fs = require('fs')
|
||
const os = require('os')
|
||
const path = require('path')
|
||
const zlib = require('zlib')
|
||
const { test, expect } = require('./_pw-coverage')
|
||
|
||
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
|
||
test.use({ baseURL, viewport: { width: 1500, height: 1000 } })
|
||
|
||
const CFG_KEY = 'iwb_web_cfg'
|
||
const SECRETS = ['sk-plain-1', 'sk-llm-1', 'ghp_secret', 'imgbb_secret', 'gen_secret', 'p@ss']
|
||
|
||
const SEED = {
|
||
providers: [{ id: 'tuzi', name: '默认服务', baseUrl: 'https://a.example/v1', fallbacks: [], genPath: '/images/generations', editPath: '/images/edits', keys: [{ id: 'daily', name: '日常', source: 'literal', value: 'sk-plain-1' }] }],
|
||
imageTransfer: {
|
||
mode: 'base64', maxRefs: 5,
|
||
imageHost: {
|
||
type: 'github',
|
||
github: { owner: 'o', repo: 'r', branch: 'main', dir: 'd', token: 'ghp_secret', retentionHours: 12 },
|
||
imgbb: { key: 'imgbb_secret' },
|
||
generic: { uploadUrl: '', method: 'POST', auth: { type: 'bearer', token: 'gen_secret', headerName: '' }, fileField: 'image', urlPath: 'data.url', headers: {} },
|
||
},
|
||
// ★ 旧导出会整段丢掉这个分区(展示形态里没有它)—— 往返断言主要盯它
|
||
compression: { enabled: false, maxMB: 3, maxEdge: 1234, quality: 0.7, format: 'jpeg' },
|
||
},
|
||
outputsRetention: { enabled: false, maxFiles: 33, maxDays: 4 },
|
||
llm: { providers: [{ id: 'l0', name: '默认渠道', baseUrl: 'https://l.example/v1', fallbacks: [], keys: [{ id: 'lk0', name: 'K', value: 'sk-llm-1' }], models: [{ name: 'm1', default: true }], defaultModel: 'm1' }], defaultProviderId: 'l0', defaultInstruction: 'ins' },
|
||
canvas: { generationConcurrency: 7, snap: true },
|
||
webhook: { enabled: true, url: 'https://hook.example/x' },
|
||
security: { password: 'p@ss' },
|
||
futureField: { hello: 'world' },
|
||
}
|
||
// 「改成不同值」:每个可观察设置都换掉,才能证明是"从备份恢复"而不是"本来就没变"
|
||
const MUTATED = {
|
||
providers: [{ id: 'tuzi', name: '改了', baseUrl: 'https://b.example/v1', fallbacks: [], keys: [{ id: 'daily', name: 'x', source: 'literal', value: 'sk-changed' }] }],
|
||
imageTransfer: {
|
||
mode: 'url', maxRefs: 2,
|
||
imageHost: { type: 'imgbb', github: { owner: 'zz', repo: 'zz', branch: 'dev', dir: 'zz', token: '', retentionHours: 1 }, imgbb: { key: '' }, generic: { uploadUrl: 'https://x', method: 'PUT', auth: { type: 'none', token: '', headerName: '' }, fileField: 'f', urlPath: 'u', headers: {} } },
|
||
compression: { enabled: true, maxMB: 99, maxEdge: 4096, quality: 1, format: 'png' },
|
||
},
|
||
outputsRetention: { enabled: true, maxFiles: 1, maxDays: 1 },
|
||
llm: { providers: [{ id: 'l0', name: '改了', baseUrl: 'https://l2.example/v1', fallbacks: [], keys: [{ id: 'lk0', name: 'K', value: 'sk-llm-changed' }], models: [], defaultModel: '' }], defaultProviderId: 'l0', defaultInstruction: 'changed' },
|
||
canvas: { generationConcurrency: 2, snap: false, autoSaveImages: false },
|
||
webhook: { enabled: false, url: '' },
|
||
}
|
||
const BOARD = { id: 'w1', name: 'BACKUP', edges: [], groups: [], nodes: [{ id: 'p1', type: 'prompt', x: 120, y: 120, data: { text: 'hello' } }] }
|
||
|
||
function seed(page, cfg) {
|
||
return page.addInitScript((d) => {
|
||
window.__IWB_E2E__ = true
|
||
try {
|
||
if (sessionStorage.getItem('iwb_e2e_backup_seeded') === '1') return
|
||
sessionStorage.setItem('iwb_e2e_backup_seeded', '1')
|
||
localStorage.clear()
|
||
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
|
||
localStorage.setItem('iwb_web_workspaces', JSON.stringify({ workspaces: [d.board], activeId: 'w1', rev: 1 }))
|
||
localStorage.setItem('iwb_ws_active', 'w1')
|
||
localStorage.setItem('iwb_ws_w1', JSON.stringify(d.board))
|
||
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
|
||
} catch (e) { /* ignore */ }
|
||
}, { cfg, board: BOARD })
|
||
}
|
||
|
||
async function enterCanvas(page) {
|
||
await page.waitForTimeout(700)
|
||
const card = page.locator('.iwb-home-card:not(.iwb-home-new)').first()
|
||
if ((await card.count()) > 0 && await card.isVisible().catch(() => false)) await card.dblclick()
|
||
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible({ timeout: 20000 })
|
||
await expect(page.locator('.iwb-node').first()).toBeVisible({ timeout: 20000 })
|
||
await page.waitForTimeout(800)
|
||
}
|
||
|
||
async function openBackupModal(page) {
|
||
// 2026-10-29:备份/还原入口**只保留在设置面板**(用户要求移除另外两处菜单入口)
|
||
await page.locator('.iwb-top-nav-icon[title="服务与 Key 设置"]').click()
|
||
await page.waitForSelector('.iwb-settings-modal', { timeout: 15000 })
|
||
await page.locator('.iwb-settings-modal .iwb-tab').filter({ hasText: '备份与还原' }).click()
|
||
// 2026-10-29:入口已收进「设置面板 → 备份与还原」Tab(用户要求),
|
||
// 所以这里既断言备份区可见,也断言确实是在设置面板里(而不是旧的独立弹层)。
|
||
await expect(page.locator('.iwb-settings-modal')).toBeVisible({ timeout: 15000 })
|
||
await expect(page.locator('.iwb-backup-embedded')).toBeVisible()
|
||
}
|
||
|
||
// 导出备份并返回 ZIP 字节(本工具导出器用 STORE 条目 ⇒ Node 侧可直接解出 iwb-backup.json)
|
||
async function exportBackup(page, { withKeys }) {
|
||
const modal = page.locator('.iwb-backup-embedded')
|
||
const bkSec = modal.locator('.iwb-backup-sec').first()
|
||
const cfgItem = bkSec.locator('.iwb-backup-item').filter({ hasText: '设置(服务/图床/LLM/口令等)' })
|
||
if (!(await cfgItem.locator('input').isChecked())) await cfgItem.locator('input').check()
|
||
const keysItem = bkSec.locator('.iwb-backup-item').filter({ hasText: '包含 API Key' })
|
||
if (withKeys) await keysItem.locator('input').check()
|
||
else await keysItem.locator('input').uncheck()
|
||
const dl = page.waitForEvent('download', { timeout: 30000 })
|
||
await bkSec.getByRole('button', { name: /导出所选备份/ }).click()
|
||
const d = await dl
|
||
const p = await d.path()
|
||
return fs.readFileSync(p)
|
||
}
|
||
|
||
// ZIP(STORE)单条目读取:本地文件头 PK\x03\x04;本写入器不使用 data descriptor
|
||
function readZipEntry(buf, name) {
|
||
let i = 0
|
||
while (i + 30 <= buf.length) {
|
||
if (buf.readUInt32LE(i) !== 0x04034b50) { i++; continue }
|
||
const method = buf.readUInt16LE(i + 8)
|
||
const compSize = buf.readUInt32LE(i + 18)
|
||
const nameLen = buf.readUInt16LE(i + 26)
|
||
const extraLen = buf.readUInt16LE(i + 28)
|
||
const fname = buf.slice(i + 30, i + 30 + nameLen).toString('utf8')
|
||
const start = i + 30 + nameLen + extraLen
|
||
const data = buf.slice(start, start + compSize)
|
||
if (fname === name) return method === 0 ? data : zlib.inflateRawSync(data)
|
||
i = start + compSize
|
||
}
|
||
return null
|
||
}
|
||
|
||
// 读配置:恢复流程末尾会 location.reload(),evaluate 可能正好撞上导航("Execution context was destroyed")。
|
||
// 这里对导航竞态做有界重试,让断言稳定落在**刷新后**的文档上(而不是靠固定 sleep 猜时机)。
|
||
async function readCfg(page, tries = 20) {
|
||
let lastErr = null
|
||
for (let i = 0; i < tries; i++) {
|
||
try {
|
||
return await page.evaluate((k) => { try { return JSON.parse(localStorage.getItem(k)) } catch (e) { return null } }, CFG_KEY)
|
||
} catch (e) { lastErr = e; await page.waitForTimeout(250) }
|
||
}
|
||
throw lastErr
|
||
}
|
||
|
||
async function restoreFromZip(page, zipBuf) {
|
||
const file = path.join(os.tmpdir(), 'iwb-backup-' + Date.now() + '-' + Math.random().toString(36).slice(2) + '.zip')
|
||
fs.writeFileSync(file, zipBuf)
|
||
const modal = page.locator('.iwb-backup-embedded')
|
||
const rstSec = modal.locator('.iwb-backup-sec').nth(1)
|
||
await rstSec.locator('input[type="file"]').setInputFiles(file)
|
||
await expect(modal.locator('.iwb-backup-file')).toBeVisible({ timeout: 15000 })
|
||
// 文件解析完成后,弹层里会出现"备份内容摘要"(服务/模型/密钥数量)——把它返回给调用方断言
|
||
const loadedText = await modal.innerText()
|
||
const cfgRow = rstSec.locator('.iwb-backup-item').filter({ hasText: '设置' }).first()
|
||
if (!(await cfgRow.locator('input').isChecked())) await cfgRow.locator('input').check()
|
||
// 先挂上"刷新页面"的等待再点:恢复成功后应用必定 reload(设置生效),
|
||
// 这样断言一定发生在刷新之后的文档上,不再依赖 sleep 时长。
|
||
const nav = page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 25000 }).catch(() => null)
|
||
await rstSec.getByRole('button', { name: '恢复所选' }).click()
|
||
await nav
|
||
await page.waitForTimeout(300)
|
||
try { fs.unlinkSync(file) } catch (e) { /* ignore */ }
|
||
return loadedText
|
||
}
|
||
|
||
test('设置往返:导出备份 → 改成不同值 → 导入该备份 ⇒ 设置恢复为备份里的值(含压缩等此前被丢字段)', async ({ page }) => {
|
||
const errors = []
|
||
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
|
||
page.on('dialog', (d) => d.accept())
|
||
await seed(page, SEED)
|
||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
|
||
// ---- 导出(默认不含密钥)----
|
||
await openBackupModal(page)
|
||
const zip = await exportBackup(page, { withKeys: false })
|
||
expect(zip.length, 'ZIP 备份不应为空').toBeGreaterThan(100)
|
||
const bkJson = readZipEntry(zip, 'iwb-backup.json')
|
||
expect(bkJson, 'ZIP 内必须有 iwb-backup.json').toBeTruthy()
|
||
const bk = JSON.parse(bkJson.toString('utf8'))
|
||
const cfg = (bk.items || {}).config
|
||
expect(cfg, '备份里必须有 items.config').toBeTruthy()
|
||
// ① 完整性:旧导出(展示形态)里 compression 整段不存在
|
||
expect(cfg.imageTransfer, '备份设置必须含 imageTransfer').toBeTruthy()
|
||
expect(cfg.imageTransfer.compression, '备份设置必须含 imageTransfer.compression(旧导出丢的正是它)').toBeTruthy()
|
||
expect(cfg.imageTransfer.compression).toEqual({ enabled: false, maxMB: 3, maxEdge: 1234, quality: 0.7, format: 'jpeg' })
|
||
expect(cfg.imageTransfer.maxRefs).toBe(5)
|
||
expect(cfg.providers.length).toBe(1)
|
||
expect(cfg.llm && cfg.llm.providers.length).toBe(1)
|
||
expect(cfg.canvas && cfg.canvas.generationConcurrency).toBe(7)
|
||
expect(cfg.webhook && cfg.webhook.url).toBe('https://hook.example/x')
|
||
expect(cfg.outputsRetention && cfg.outputsRetention.maxFiles).toBe(33)
|
||
expect(cfg.futureField, '未知字段必须随备份带走(以后新增设置不会被吃掉)').toEqual({ hello: 'world' })
|
||
// ② withKeys=false ⇒ 全部敏感字段 __KEEP__ 且备份里没有任何明文
|
||
expect(cfg.providers[0].keys[0].value).toBe('__KEEP__')
|
||
expect(cfg.llm.providers[0].keys[0].value).toBe('__KEEP__')
|
||
expect(cfg.imageTransfer.imageHost.github.token).toBe('__KEEP__')
|
||
expect(cfg.imageTransfer.imageHost.imgbb.key).toBe('__KEEP__')
|
||
expect(cfg.imageTransfer.imageHost.generic.auth.token).toBe('__KEEP__')
|
||
expect(cfg.security.password).toBe('__KEEP__')
|
||
const rawBk = JSON.stringify(bk)
|
||
for (const s of SECRETS) expect(rawBk, '备份文件里不得出现明文密钥 ' + s).not.toContain(s)
|
||
console.log('[backup-config] 备份大小=' + zip.length + 'B config=' + JSON.stringify(cfg.imageTransfer.compression))
|
||
|
||
// ---- 关闭弹窗,把本机设置改成完全不同的值 ----
|
||
await page.locator('.iwb-settings-modal .iwb-modal-head button').click() // 2026-10-29:备份已并入设置面板,关的是设置弹窗
|
||
await page.evaluate(([k, v]) => localStorage.setItem(k, v), [CFG_KEY, JSON.stringify(MUTATED)])
|
||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
const before = await readCfg(page)
|
||
expect(before.imageTransfer.compression.maxEdge, '改值必须生效(前置条件)').toBe(4096)
|
||
expect(before.canvas.generationConcurrency).toBe(2)
|
||
|
||
// ---- 导入该备份 ----
|
||
await openBackupModal(page)
|
||
await restoreFromZip(page, zip) // 内部已等待"恢复后自动刷新页面"完成
|
||
|
||
const after = await readCfg(page)
|
||
// ③ 往返一致:可观察设置全部恢复为备份里的值
|
||
expect(after.imageTransfer.compression, '压缩设置必须恢复为备份里的值').toEqual({ enabled: false, maxMB: 3, maxEdge: 1234, quality: 0.7, format: 'jpeg' })
|
||
expect(after.imageTransfer.mode).toBe('base64')
|
||
expect(after.imageTransfer.maxRefs).toBe(5)
|
||
expect(after.imageTransfer.imageHost.type).toBe('github')
|
||
expect(after.imageTransfer.imageHost.github.owner).toBe('o')
|
||
expect(after.imageTransfer.imageHost.github.retentionHours).toBe(12)
|
||
expect(after.providers[0].baseUrl, '服务地址必须恢复').toBe('https://a.example/v1')
|
||
expect(after.llm.providers[0].baseUrl, 'LLM 地址必须恢复').toBe('https://l.example/v1')
|
||
expect(after.llm.defaultInstruction).toBe('ins')
|
||
expect(after.canvas.generationConcurrency).toBe(7)
|
||
expect(after.canvas.snap).toBe(true)
|
||
expect(after.canvas.autoSaveImages, '被改掉的布尔项也要恢复').toBe(true)
|
||
expect(after.webhook).toEqual({ enabled: true, url: 'https://hook.example/x' })
|
||
expect(after.outputsRetention).toEqual({ enabled: false, maxFiles: 33, maxDays: 4 })
|
||
expect(after.futureField, '未知字段往返不丢').toEqual({ hello: 'world' })
|
||
// __KEEP__ 语义:不带密钥的备份**不覆盖**本机已有 key
|
||
expect(after.providers[0].keys[0].value, 'withKeys:false ⇒ 保留本机 key').toBe('sk-changed')
|
||
expect(after.llm.providers[0].keys[0].value, 'withKeys:false ⇒ 保留本机 LLM key').toBe('sk-llm-changed')
|
||
// 盘上不得残留 __KEEP__ 字面量,也不得落展示噪音字段
|
||
const afterRaw = JSON.stringify(after)
|
||
expect(afterRaw, '盘上不得残留 __KEEP__').not.toContain('__KEEP__')
|
||
expect(afterRaw, '盘上不得落展示噪音 masked').not.toContain('"masked"')
|
||
expect(afterRaw, '盘上不得落展示噪音 filled').not.toContain('"filled"')
|
||
|
||
// ④ 恢复后设置**立即生效**:打开「设置 → 图片传输」,界面绑定值就是备份里的值。
|
||
// (旧实现里 wCfgPublic 没有 compression ⇒ 弹窗永远显示硬编码默认值;这里同时守住"界面上看得到")
|
||
await page.locator('.iwb-top-nav-icon[title="服务与 Key 设置"]').click()
|
||
await expect(page.locator('.iwb-settings-modal')).toBeVisible()
|
||
await page.locator('.iwb-settings-modal .iwb-tab').filter({ hasText: '图片传输' }).click()
|
||
await expect(page.locator('.iwb-settings-modal input[title="压缩后最长边像素"]'), '设置弹窗必须显示恢复后的真实压缩值(无需手动改一次设置才生效)').toHaveValue('1234')
|
||
await expect(page.locator('.iwb-settings-modal input[title="超过该大小(MB)才压缩"]')).toHaveValue('3')
|
||
await expect(page.locator('.iwb-settings-modal input[title="JPEG 质量 0-1"]')).toHaveValue('0.7')
|
||
expect(errors).toEqual([])
|
||
})
|
||
|
||
test('withKeys=true:备份文件里确实带明文密钥(等于导出时的本机值)', async ({ page }) => {
|
||
page.on('dialog', (d) => d.accept())
|
||
await seed(page, SEED)
|
||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
await openBackupModal(page)
|
||
const zip = await exportBackup(page, { withKeys: true })
|
||
const bk = JSON.parse(readZipEntry(zip, 'iwb-backup.json').toString('utf8'))
|
||
const cfg = bk.items.config
|
||
expect(cfg.providers[0].keys[0].value, '显式勾选"包含 API Key"必须真的带上明文').toBe('sk-plain-1')
|
||
expect(cfg.llm.providers[0].keys[0].value).toBe('sk-llm-1')
|
||
expect(cfg.imageTransfer.imageHost.github.token).toBe('ghp_secret')
|
||
expect(cfg.imageTransfer.imageHost.imgbb.key).toBe('imgbb_secret')
|
||
expect(cfg.imageTransfer.imageHost.generic.auth.token).toBe('gen_secret')
|
||
expect(cfg.security.password).toBe('p@ss')
|
||
// 恢复界面必须如实显示"含密钥"(旧判定只看 llm.apiKey,而备份里根本没有该字段)
|
||
const rstLabel = await page.locator('.iwb-backup-embedded .iwb-backup-sec').first().textContent()
|
||
expect(rstLabel, '导出区含密钥提示').toContain('备份文件含密钥')
|
||
})
|
||
|
||
test('__KEEP__ 本机无值:恢复时给出可见提示(不静默留空)', async ({ page }) => {
|
||
const dialogs = []
|
||
page.on('dialog', (d) => { dialogs.push(String(d.message() || '')); d.accept() })
|
||
await seed(page, SEED)
|
||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
await openBackupModal(page)
|
||
const zip = await exportBackup(page, { withKeys: false })
|
||
await page.locator('.iwb-settings-modal .iwb-modal-head button').click() // 2026-10-29:备份已并入设置面板,关的是设置弹窗
|
||
// 本机改成"没有这些密钥"(服务/渠道全清) ⇒ __KEEP__ 无本机值
|
||
await page.evaluate(([k, v]) => localStorage.setItem(k, v), [CFG_KEY, JSON.stringify({ providers: [], imageTransfer: { mode: 'base64' } })])
|
||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
await openBackupModal(page)
|
||
await restoreFromZip(page, zip) // 有 __KEEP__ 缺失时先弹确认再刷新,内部等待覆盖这一段
|
||
const warn = dialogs.filter((m) => m.indexOf('本机没有对应值') !== -1)
|
||
expect(warn.length, '本机无值时必须弹出可见提示(对话框),实际 dialogs=' + JSON.stringify(dialogs)).toBeGreaterThanOrEqual(1)
|
||
expect(warn[0], '提示必须点名缺失的密钥类别').toMatch(/Key|Token|口令/)
|
||
const after = await readCfg(page)
|
||
// 不静默留空:字段确实为空,但用户已被明确告知(且盘上不残留 __KEEP__)
|
||
expect(after.providers[0].keys[0].value).toBe('')
|
||
expect(JSON.stringify(after)).not.toContain('__KEEP__')
|
||
})
|
||
|
||
// 2026-10-29 新增(用户实测反馈的缺口):**withKeys=true 的还原侧**从未被测过。
|
||
// 已有三条用例只覆盖:① withKeys=false 往返(密钥保留本机)② withKeys=true 导出含明文 ③ __KEEP__ 本机无值提示。
|
||
// 但「带着明文密钥的备份,在**换设备/清空本机**后还原,密钥到底有没有回来」——没有任何断言。
|
||
// 这条用例就是补这个盲区:清空本机 config 再还原,断言 providers/models/keys 全部回来。
|
||
test('withKeys=true 往返:清空本机设置后还原 ⇒ 服务/自定义模型/密钥全部恢复', async ({ page }) => {
|
||
page.on('dialog', (d) => d.accept())
|
||
// 种子必须**带自定义模型** —— 用户报告"自定义模型还原不回来",所以这条用例专门盯它
|
||
const SEED_WITH_MODELS = Object.assign({}, SEED, {
|
||
providers: [Object.assign({}, SEED.providers[0], {
|
||
models: [{ name: 'my-custom-model-1', visible: true }, { name: 'my-custom-model-2', visible: false }],
|
||
})],
|
||
})
|
||
await seed(page, SEED_WITH_MODELS)
|
||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
await openBackupModal(page)
|
||
const zip = await exportBackup(page, { withKeys: true })
|
||
|
||
// 前置自证:备份里确实是明文密钥(否则这条用例测不到还原侧)
|
||
const cfgInZip = JSON.parse(readZipEntry(zip, 'iwb-backup.json').toString('utf8')).items.config
|
||
expect(cfgInZip.providers[0].keys[0].value, '备份内应为明文密钥').toBe('sk-plain-1')
|
||
|
||
// 模拟「换设备 / 清过数据」:整份 config 删掉
|
||
await page.evaluate((k) => localStorage.removeItem(k), CFG_KEY)
|
||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
const wiped = await readCfg(page)
|
||
expect(wiped === null || !(wiped.providers || []).length, '前置条件:本机已无服务配置').toBe(true)
|
||
|
||
await openBackupModal(page)
|
||
const loadedText = await restoreFromZip(page, zip)
|
||
// 2026-10-29 新增可见性措施:还原前就能看到"备份里有什么"(服务/模型/密钥数量)
|
||
expect(loadedText, '摘要应显示服务数量').toMatch(/1\s*个服务/)
|
||
expect(loadedText, '摘要应显示自定义模型数量').toMatch(/2\s*个模型/)
|
||
expect(loadedText, '摘要应显示明文密钥数量').toMatch(/\d+\s*个明文密钥/)
|
||
|
||
const after = await readCfg(page)
|
||
expect(after, '还原后必须有配置').toBeTruthy()
|
||
expect((after.providers || []).length, '服务商必须恢复').toBeGreaterThanOrEqual(1)
|
||
expect(after.providers[0].baseUrl, '服务地址必须恢复').toBe('https://a.example/v1')
|
||
expect(after.providers[0].keys[0].value, '★ 密钥必须恢复(这正是用户报告的失败点)').toBe('sk-plain-1')
|
||
const restoredModels = (after.providers[0].models || []).map((m) => m.name)
|
||
expect(restoredModels, '★ 自定义模型必须恢复(用户报告的第二个失败点)').toEqual(['my-custom-model-1', 'my-custom-model-2'])
|
||
expect(after.llm.providers[0].keys[0].value, 'LLM 密钥必须恢复').toBe('sk-llm-1')
|
||
})
|
||
|
||
// 2026-10-29:用户报告"还原没匹配上"的最常见原因之一 —— **备份文件本身不含设置**。
|
||
// 新增可见性措施后,这种备份在还原前必须给出明确告警(而不是让用户以为"还原坏了")。
|
||
test('备份不含设置时:还原前必须明确告警「该备份不含设置」', async ({ page }) => {
|
||
page.on('dialog', (d) => d.accept())
|
||
await seed(page, SEED)
|
||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||
await enterCanvas(page)
|
||
await openBackupModal(page)
|
||
|
||
// 只备份提示词,**取消勾选设置**(复现"备份里没有设置"的场景)
|
||
const modal = page.locator('.iwb-backup-embedded')
|
||
const bkSec = modal.locator('.iwb-backup-sec').first()
|
||
const cfgItem = bkSec.locator('.iwb-backup-item').filter({ hasText: '设置(服务/图床/LLM/口令等)' })
|
||
await cfgItem.locator('input').uncheck()
|
||
const dl = page.waitForEvent('download', { timeout: 30000 })
|
||
await bkSec.getByRole('button', { name: /导出所选备份/ }).click()
|
||
const zip = fs.readFileSync(await (await dl).path())
|
||
expect(JSON.parse(readZipEntry(zip, 'iwb-backup.json').toString('utf8')).items.config, '前置条件:该备份确实不含设置').toBeFalsy()
|
||
|
||
// 载入这份备份 → 必须看到"不含设置"的告警
|
||
const loadedText = await (async () => {
|
||
const file = path.join(os.tmpdir(), 'iwb-nocfg-' + Date.now() + '.zip')
|
||
fs.writeFileSync(file, zip)
|
||
const rstSec = modal.locator('.iwb-backup-sec').nth(1)
|
||
await rstSec.locator('input[type="file"]').setInputFiles(file)
|
||
await expect(modal.locator('.iwb-backup-file')).toBeVisible({ timeout: 15000 })
|
||
const txt = await modal.innerText()
|
||
try { fs.unlinkSync(file) } catch (e) { /* ignore */ }
|
||
return txt
|
||
})()
|
||
expect(loadedText, '必须明确告警该备份不含设置(否则用户会以为还原坏了)').toMatch(/不含设置/)
|
||
expect(loadedText, '告警要点明服务/模型/Key 无法恢复').toMatch(/服务、自定义模型、API Key 都无法恢复/)
|
||
})
|