From c04d128724748702fb6efdc833ef713e744ce582 Mon Sep 17 00:00:00 2001 From: JINGHAN YU Date: Tue, 24 Nov 2026 10:32:47 +0900 Subject: [PATCH] =?UTF-8?q?fix(web):=20=E9=85=8D=E7=BD=AE=E5=90=91?= =?UTF-8?q?=E5=AF=BC=E6=8C=89=E5=91=BD=E4=BB=A4=E6=89=BE=E6=AD=A3=E5=9C=A8?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E7=9A=84=20key=20db=20=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=EF=BC=8C=E5=AF=86=E9=92=A5=E5=AD=98=E5=A5=BD=E5=90=8E=E7=94=B1?= =?UTF-8?q?=20useProfiles=20=E9=87=8D=E8=AF=BB=E6=A1=A3=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 数据库密钥一步不再把任务 id 存在自己的状态里,而是从共享的任务列表里找未结束的 key db --save:换步骤或关掉向导再回来,仍显示进度和「取消」,不会再排上第二个任务。 key db --save / key image --save 任务成功后由 useProfiles 重读档案,向导关着也会刷新。 fixed https://github.com/334456777/WeFlow/issues/1138 Co-Authored-By: Claude Opus 5.5 --- web/src/App.tsx | 2 +- web/src/api/jobs.ts | 10 +++- web/src/api/setup.ts | 8 +++ web/src/mock/server.test.ts | 18 ++++++ web/src/settings/SetupWizard.test.tsx | 79 +++++++++++++++++++++++++-- web/src/settings/SetupWizard.tsx | 39 ++++++++----- web/src/settings/useProfiles.ts | 26 +++++++-- 7 files changed, 155 insertions(+), 27 deletions(-) diff --git a/web/src/App.tsx b/web/src/App.tsx index 929580d98..449fe797b 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -88,7 +88,7 @@ export function App() { const scope = useScope(backend); const jobs = useJobs(usable, scope); // the account setup (#216): it opens by itself when a tab finds the account not set up, and from the settings - const profiles = useProfiles(usable, scope); + const profiles = useProfiles(usable, scope, jobs.jobs); const profile = profiles.profiles ? currentProfile(profiles.profiles) : undefined; const [setupOpen, setSetupOpen] = useState(false); useEffect(() => { diff --git a/web/src/api/jobs.ts b/web/src/api/jobs.ts index 6df2b04f5..149976745 100644 --- a/web/src/api/jobs.ts +++ b/web/src/api/jobs.ts @@ -51,13 +51,19 @@ export const jobFileUrl = (id: string) => mediaAddress('jobs/' + encodeURICompon /** The address of the job's server-sent events; the token goes in the address, as `EventSource` sends no header. */ export const jobEventsUrl = (id: string) => apiUrl('jobs/' + encodeURIComponent(id) + '/events', { access_token: token() }); +/** The words of a job's command line that are not flags, `weflow` left out: `export`, `messages`, then the values. */ +const wordsOf = (command: readonly string[]) => command.slice(1).filter(word => !word.startsWith('-')); + +/** The command a job runs, by its first two words: `export messages`, `key db`. */ +export const commandName = (command: readonly string[]) => wordsOf(command).slice(0, 2).join(' '); + /** * What a job does, in words: 「导出聊天记录」 for `export messages`, … With `names` (conversations by id), the * conversation it names: 「导出聊天记录 · 林沐」. */ export function describeCommand(command: string[], names?: ReadonlyMap): string { - const words = command.slice(1).filter(word => !word.startsWith('-')); - const name = words.slice(0, 2).join(' '); + const words = wordsOf(command); + const name = commandName(command); const known = COMMANDS[name] ?? COMMANDS[words[0]]; const what = known ? t(known) : name; const about = names && command.find(word => names.has(word)); diff --git a/web/src/api/setup.ts b/web/src/api/setup.ts index 8afa2d19c..ec46aa5f0 100644 --- a/web/src/api/setup.ts +++ b/web/src/api/setup.ts @@ -2,6 +2,7 @@ // directory and its accounts, saving settings, and testing that the database opens. The keys are fetched by // `key db --save` / `key image --save`, which store them on the server: they never reach the page. import { call, get } from './client'; +import { commandName, type Job } from './jobs'; import { t } from '../i18n'; import type * as Contract from './contract.gen'; @@ -38,6 +39,13 @@ export const testDatabase = (signal?: AbortSignal) => get call('POST', 'key/image', { save: true }); +/** The key a job saves in the current profile: `db` for `key db --save`, `image` for `key image --save`, else null. */ +export function savedKey(job: Pick): 'db' | 'image' | null { + if (!job.command.includes('--save')) return null; + const name = commandName(job.command); + return name === 'key db' ? 'db' : name === 'key image' ? 'image' : null; +} + /** A database key as `config set decrypt_key` takes it: 64 hexadecimal digits. */ export const isDatabaseKey = (value: string) => /^[0-9a-fA-F]{64}$/.test(value.trim()); diff --git a/web/src/mock/server.test.ts b/web/src/mock/server.test.ts index cb35b8a9f..26fb49a4d 100644 --- a/web/src/mock/server.test.ts +++ b/web/src/mock/server.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from '#test'; import type { Job, ProfileSummary } from '../api/contract.gen'; import type { Params, SampleAnswer } from '../api/client'; +import { savedKey } from '../api/setup'; import { server } from './server'; // The sample server keeps what changes for as long as the page (here, the test run) is open, and other test files use @@ -111,6 +112,23 @@ describe('the sample server (#896)', () => { expect(ask('GET', 'jobs').filter(j => [first.id, second.id, key.id].includes(j.id)).map(j => j.status)).toEqual(['succeeded', 'cancelled']); }); + it('saves the database key once its job has succeeded, as a job the page knows by its command (#1138)', () => { + vi.useFakeTimers({ toFake: ['Date'], now: Date.now() + 7_200_000 }); + const t0 = Date.now(); + ask('PUT', 'config/set', { key: 'current_profile', value: 'keyed-by-job' }); + const keyed = () => ask('GET', 'api/config/profiles').find(p => p.current)!.decryptKey; + expect(keyed()).toBe(false); + const job = start('key/db', { save: true }); + expect(savedKey(job)).toBe('db'); + at(t0 + 1000); + expect(ask('GET', 'jobs/' + job.id).status).toBe('running'); + expect(keyed()).toBe(false); + at(t0 + 10_000); + expect(ask('GET', 'jobs/' + job.id)).toMatchObject({ status: 'succeeded', result: { success: true, data: { saved: ['decrypt_key'] } } }); + expect(keyed()).toBe(true); + ask('PUT', 'config/set', { key: 'current_profile', value: 'default' }); + }); + it('refuses the page\'s versions, which need a server', () => { expect(server.answer('GET', 'web/list', {}, false)).toEqual({ refused: true }); }); diff --git a/web/src/settings/SetupWizard.test.tsx b/web/src/settings/SetupWizard.test.tsx index 220c03ae1..dbc290038 100644 --- a/web/src/settings/SetupWizard.test.tsx +++ b/web/src/settings/SetupWizard.test.tsx @@ -1,9 +1,10 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from '#test'; -import type { Profile } from '../api/setup'; +import { currentProfile, type Profile } from '../api/setup'; import { useJobs } from '../jobs/useJobs'; import { SetupDialog } from './SetupDialog'; import { SetupWizard } from './SetupWizard'; +import { useProfiles } from './useProfiles'; afterEach(() => { cleanup(); @@ -99,8 +100,7 @@ describe('SetupWizard', () => { 'GET /jobs': () => ok(jobs), 'GET /jobs/k1': () => ok({ ...job('succeeded'), result: { success: true, data: { method: 'wx_key', saved: ['decrypt_key'] } } }), }); - const onChanged = vi.fn(); - render(); + render(); await act(async () => {}); fireEvent.click(screen.getByRole('button', { name: '获取数据库密钥' })); await act(async () => {}); @@ -125,12 +125,12 @@ describe('SetupWizard', () => { expect(streams()).toBe(2); expect(doing()).toContain('请在微信的登录窗口点击「进入微信」'); - // the job's end, as its stream tells it + // the job's end, as its stream tells it; the profile is read again by useProfiles, not by the step jobs = [job('succeeded')]; const done = { ...job('succeeded'), result: { success: true, data: { method: 'wx_key', saved: ['decrypt_key'] } } }; await act(async () => { emit('result', done); }); expect(screen.getByRole('status').textContent).toContain('已获取数据库密钥'); - expect(onChanged).toHaveBeenCalled(); + expect(screen.getByRole('button', { name: '获取数据库密钥' })).toBeTruthy(); }); it('takes a typed key only when it is 64 hexadecimal digits', async () => { @@ -187,6 +187,75 @@ describe('SetupDialog', () => { return {}} onClose={() => {}} onDone={() => {}} />; } + /** The dialog as the workspace holds it: the jobs and the profiles outlive it. */ + function Workspace({ open }: { open: boolean }) { + const jobs = useJobs(true, 0); + const profiles = useProfiles(true, 0, jobs.jobs); + const profile = profiles.profiles ? currentProfile(profiles.profiles) : undefined; + return {}} onDone={() => {}} />; + } + + /** A server whose `key db --save` job, `id`, runs until `finish` ends it; the key is in the profile from then on. */ + function keyServer(id: string) { + const job = (status: string) => ({ id, status, command: ['weflow', '--json', '--progress', 'key', 'db', '--save'], createdAt: 1, startedAt: null, finishedAt: null, exitCode: null, httpStatus: null, progress: null }); + let jobs: unknown[] = []; + let keyed = false; + const calls = serve({ + 'GET /api/config/profiles': () => ok([{ ...PROFILE, dbPath: 'D:/x', wxid: 'wxid_a', decryptKey: keyed }]), + 'POST /key/db': () => { jobs = [job('running')]; return json({ success: true, data: job('running') }, 202); }, + 'GET /jobs': () => ok(jobs), + ['GET /jobs/' + id]: () => ok({ ...job(keyed ? 'succeeded' : 'running'), result: keyed ? { success: true, data: { saved: ['decrypt_key'] } } : null }), + }); + const finish = async () => { + keyed = true; + jobs = [job('succeeded')]; + const done = { ...job('succeeded'), result: { success: true, data: { saved: ['decrypt_key'] } } }; + await act(async () => { for (const source of opened.filter(s => s.url.startsWith('/jobs/' + id + '/events') && !s.closed)) source.emit('result', done); }); + }; + return { calls, finish, started: () => calls.filter(c => c.method === 'POST' && c.url.startsWith('/key/db')).length }; + } + + it('shows the database key job running after another step, and starts no second one (#1138)', async () => { + const { started } = keyServer('k2'); + render(); + await act(async () => {}); + expect(currentStep()).toContain('数据库密钥'); + fireEvent.click(screen.getByRole('button', { name: '获取数据库密钥' })); + await act(async () => {}); + expect(document.querySelector('.setup-running')).not.toBeNull(); + + fireEvent.click(screen.getByRole('button', { name: '3图片密钥' })); + fireEvent.click(screen.getByRole('button', { name: '2数据库密钥' })); + await act(async () => {}); + expect(currentStep()).toContain('数据库密钥'); + expect(document.querySelector('.setup-running')?.textContent).toContain('正在准备'); + expect(screen.getByRole('button', { name: '取消' })).toBeTruthy(); + expect(screen.queryByRole('button', { name: '获取数据库密钥' })).toBeNull(); + expect(started()).toBe(1); + }); + + it('reads the profile again when the job saved the key with the setup closed (#1138)', async () => { + const { calls, finish } = keyServer('k3'); + const profileReads = () => calls.filter(c => c.url.startsWith('/api/config/profiles')).length; + const { rerender } = render(); + await act(async () => {}); + fireEvent.click(screen.getByRole('button', { name: '获取数据库密钥' })); + await act(async () => {}); + + rerender(); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(document.querySelector('.setup-content')).toBeNull(); + const before = profileReads(); + await finish(); + expect(profileReads()).toBe(before + 1); + + rerender(); + await act(async () => {}); + fireEvent.click(screen.getByRole('button', { name: '已完成数据库密钥' })); + expect(document.querySelector('.setup-state')?.textContent).toBe('当前档案已有数据库密钥。'); + expect((screen.getByRole('button', { name: '下一步' }) as HTMLButtonElement).disabled).toBe(false); + }); + it('starts a profile added under a set-up one at the data directory (#898)', () => { serve({}); const setUp: Profile = { ...PROFILE, wxid: 'wxid_a', dbPath: 'D:/xwechat_files', decryptKey: true }; diff --git a/web/src/settings/SetupWizard.tsx b/web/src/settings/SetupWizard.tsx index ecbb0f142..6db7d88dc 100644 --- a/web/src/settings/SetupWizard.tsx +++ b/web/src/settings/SetupWizard.tsx @@ -9,7 +9,7 @@ import { ApiError, sampling } from '../api/client'; import { isFinished, jobEventsUrl } from '../api/jobs'; import { onPresence, present } from '../api/presence'; import { - detectDirs, findAccounts, isDatabaseKey, saveImageKeys, setConfig, testDatabase, + detectDirs, findAccounts, isDatabaseKey, saveImageKeys, savedKey, setConfig, testDatabase, type Account, type Profile, } from '../api/setup'; import { SteadyLabel } from '../Chip'; @@ -144,29 +144,40 @@ function phaseText(phase: KeyPhase | null): string { } } -/** Step 2: `key db --save` as a job, or a key typed in and saved with `config set decrypt_key`. */ +/** + * Step 2: `key db --save` as a job, or a key typed in and saved with `config set decrypt_key`. The job is looked for + * in the shared list, as the step is left and the setup closed while it runs (#1138); `useProfiles` reads the + * profile again once it has saved the key. + */ function KeyStep({ profile, jobs, onSaved, onNext }: { profile: Profile | undefined; jobs: JobsState; onSaved(): void; onNext(): void }) { - const [jobId, setJobId] = useState(null); const [typed, setTyped] = useState(''); const [note, setNote] = useState<{ text: string; error?: boolean } | null>(null); - const job = findJob(jobs, jobId); - const phase = useKeyPhase(job && !isFinished(job.status) ? job.id : null); - const running = Boolean(job && !isFinished(job.status)); + const [starting, setStarting] = useState(false); + // the one that runs first, should another tab have queued one more + const job = jobs.jobs.filter(j => savedKey(j) === 'db' && !isFinished(j.status)).at(-1); + const running = Boolean(job); + const phase = useKeyPhase(job?.id ?? null); + // the job seen running, to say how it ended + const [watched, setWatched] = useState(null); + useEffect(() => { if (job) setWatched(job.id); }, [job?.id]); + const ended = findJob(jobs, watched); useEffect(() => { - if (!job || !isFinished(job.status)) return; - if (job.status === 'succeeded') { setNote({ text: t('已获取数据库密钥,保存在服务端的当前档案里。') }); onSaved(); } - else if (job.status === 'failed') setNote({ text: (job.result?.error?.message || t('获取密钥失败。')) + ' ' + t('可以重试,或者手动填写密钥。'), error: true }); + if (!ended || !isFinished(ended.status)) return; + if (ended.status === 'succeeded') setNote({ text: t('已获取数据库密钥,保存在服务端的当前档案里。') }); + else if (ended.status === 'failed') setNote({ text: (ended.result?.error?.message || t('获取密钥失败。')) + ' ' + t('可以重试,或者手动填写密钥。'), error: true }); else setNote({ text: t('已取消。') }); - setJobId(null); - }, [job?.status]); + setWatched(id => (id === ended.id ? null : id)); + }, [ended?.status]); const start = async () => { setNote(null); - try { setJobId((await runJob(t('获取数据库密钥'), 'POST', 'key/db', { save: true }, false)).id); } + setStarting(true); + try { setWatched((await runJob(t('获取数据库密钥'), 'POST', 'key/db', { save: true }, false)).id); } catch (problem) { setNote({ text: reason(problem, t('没有开始,请重试。')), error: true }); } + finally { setStarting(false); } }; - const cancel = () => { if (jobId) removeJob(jobId).catch(() => setNote({ text: t('取消失败,请重试。'), error: true })); }; + const cancel = () => { if (job) removeJob(job.id).catch(() => setNote({ text: t('取消失败,请重试。'), error: true })); }; const saveTyped = async (event: FormEvent) => { event.preventDefault(); try { @@ -188,7 +199,7 @@ function KeyStep({ profile, jobs, onSaved, onNext }: { profile: Profile | undefi :
- +
} {note && {note.text}}
diff --git a/web/src/settings/useProfiles.ts b/web/src/settings/useProfiles.ts index b0d4ba43c..45142113a 100644 --- a/web/src/settings/useProfiles.ts +++ b/web/src/settings/useProfiles.ts @@ -1,7 +1,8 @@ // The profiles of `config profiles` (#216) while the server is there: read again for another server or account -// (`scope`), and when the setup saved a setting. -import { useCallback, useEffect, useState } from 'react'; -import { getProfiles, type Profile } from '../api/setup'; +// (`scope`), when the setup saved a setting, and when a job that saves a key has succeeded. +import { useCallback, useEffect, useRef, useState } from 'react'; +import { isFinished, type Job } from '../api/jobs'; +import { getProfiles, savedKey, type Profile } from '../api/setup'; /** The profiles as read, and what reads them again. */ export interface ProfilesState { @@ -12,12 +13,27 @@ export interface ProfilesState { reload(): void; } -/** `config profiles` while `enabled`, read again for another `scope` and on `reload`. */ -export function useProfiles(enabled: boolean, scope: number): ProfilesState { +/** + * `config profiles` while `enabled`, read again for another `scope`, on `reload`, and once one of `jobs` that saves a + * key (`key db --save`, `key image --save`) has succeeded. + */ +export function useProfiles(enabled: boolean, scope: number, jobs: readonly Job[]): ProfilesState { const [profiles, setProfiles] = useState(null); const [failed, setFailed] = useState(false); const [round, setRound] = useState(0); const reload = useCallback(() => setRound(n => n + 1), []); + // here rather than in the setup, which is closed or on another step while the job runs (#1138); a job first seen + // ended changed nothing since the profiles were read + const saving = useRef(new Set()); + useEffect(() => { + let saved = false; + for (const job of jobs) { + if (!savedKey(job)) continue; + if (!isFinished(job.status)) saving.current.add(job.id); + else if (saving.current.delete(job.id) && job.status === 'succeeded') saved = true; + } + if (saved) reload(); + }, [jobs, reload]); useEffect(() => { if (!enabled) { setProfiles(null); setFailed(false); return; } const controller = new AbortController();