mirror of
https://github.com/iflytek/skillhub.git
synced 2026-11-15 09:11:18 +00:00
fix(authoring): protect draft files and unsaved edits
Signed-off-by: zjncs <18910855655@163.com>
This commit is contained in:
parent
2754d86991
commit
b8d8d497c9
3 changed files with 33 additions and 7 deletions
|
|
@ -7,7 +7,7 @@ import { DraftFileEditor } from './draft-file-editor'
|
|||
import i18n from '@/i18n/config'
|
||||
|
||||
vi.mock('@tanstack/react-router', () => ({ useBlocker: () => ({ status: 'idle' }) }))
|
||||
vi.mock('@/api/client', () => ({ authoringApi: { getDraft: vi.fn(), readFile: vi.fn(), saveFile: vi.fn(), deleteFile: vi.fn() } }))
|
||||
vi.mock('@/api/client', () => ({ authoringApi: { getDraft: vi.fn(), listFiles: vi.fn(), readFile: vi.fn(), saveFile: vi.fn(), deleteFile: vi.fn() } }))
|
||||
vi.mock('@/shared/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
|
||||
const clients: QueryClient[] = []
|
||||
function mount() {
|
||||
|
|
@ -60,6 +60,17 @@ describe('draft files', () => {
|
|||
expect(authoringApi.saveFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses to overwrite a file absent from the cached list', async () => {
|
||||
vi.mocked(authoringApi.listFiles).mockResolvedValue([{ path: 'new.md' }])
|
||||
mount()
|
||||
await screen.findByLabelText('File content')
|
||||
fireEvent.change(screen.getByLabelText('Path'), { target: { value: 'new.md' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create file' }))
|
||||
await waitFor(() => expect(authoringApi.listFiles).toHaveBeenCalledWith(42))
|
||||
await waitFor(() => expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Create file' }).disabled).toBe(false))
|
||||
expect(authoringApi.saveFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses server encoding rather than an extension to protect binary bytes', async () => {
|
||||
vi.mocked(authoringApi.readFile).mockResolvedValue({ content: '/wAB', encoding: 'base64', sha256: 'binary' })
|
||||
mount()
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ export function DraftFileEditor({ draftId, files, revision, onSaved, onDirtyChan
|
|||
enabled: path != null, meta: { skipGlobalErrorHandler: true }, retry: false,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
const loadedFile = read.data
|
||||
const blocker = useBlocker({ shouldBlockFn: () => dirty || busy, enableBeforeUnload: dirty || busy, withResolver: true })
|
||||
useEffect(() => { onDirtyChange(dirty || busy) }, [dirty, busy, onDirtyChange])
|
||||
|
||||
|
|
@ -78,7 +79,20 @@ export function DraftFileEditor({ draftId, files, revision, onSaved, onDirtyChan
|
|||
toast.error(t('authoring.files.exists'))
|
||||
return
|
||||
}
|
||||
if (await mutateFile(() => authoringApi.saveFile(draftId, { path: next, content: '', expectedRevision: revision }), 'authoring.files.created', next)) setNewPath('')
|
||||
const created = await mutateFile(async () => {
|
||||
// Read the revision before listing files. Any concurrent creation after
|
||||
// that revision either appears in the list or makes the write conflict.
|
||||
const snapshot = await authoringApi.getDraft(draftId)
|
||||
if (snapshot.revision == null) throw new Error(t('authoring.ui.loadFailed'))
|
||||
const latestFiles = await authoringApi.listFiles(draftId)
|
||||
if (latestFiles.some(file => file.path === next)) {
|
||||
throw new Error(t('authoring.files.exists'))
|
||||
}
|
||||
return authoringApi.saveFile(draftId, {
|
||||
path: next, content: '', expectedRevision: snapshot.revision,
|
||||
})
|
||||
}, 'authoring.files.created', next)
|
||||
if (created) setNewPath('')
|
||||
}
|
||||
const upload = async () => {
|
||||
if (!uploadFile || !newPath.trim() || busy || dirty) return
|
||||
|
|
@ -112,7 +126,7 @@ export function DraftFileEditor({ draftId, files, revision, onSaved, onDirtyChan
|
|||
{!path && <p>{t('authoring.files.empty')}</p>}
|
||||
{path && read.isPending && <p role="status">{t('authoring.ui.loading')}</p>}
|
||||
{path && read.isError && <QueryError error={read.error} retry={() => void read.refetch()} />}
|
||||
{path && read.isSuccess && (read.data.encoding === 'text' ? <TextFileEditor key={`${draftId}:${path}:${read.data.sha256}:${editorGeneration}`} content={read.data.content ?? ''} disabled={busy} onDirtyChange={setDirty} onSave={content => mutateFile(() => authoringApi.saveFile(draftId, { path, content, expectedRevision: read.data.revision }), 'authoring.files.saved')} /> : <div className="space-y-2 rounded-md border p-4" data-testid="binary-file-panel">
|
||||
{path && loadedFile && (loadedFile.encoding === 'text' ? <TextFileEditor key={`${draftId}:${path}:${loadedFile.sha256}:${editorGeneration}`} content={loadedFile.content ?? ''} disabled={busy} onDirtyChange={setDirty} onSave={content => mutateFile(() => authoringApi.saveFile(draftId, { path, content, expectedRevision: loadedFile.revision }), 'authoring.files.saved')} /> : <div className="space-y-2 rounded-md border p-4" data-testid="binary-file-panel">
|
||||
<p className="break-all font-mono text-sm">{path}</p>
|
||||
<p className="text-sm">{t('authoring.files.size')}: {formatBytes(selected?.size ?? 0)}</p>
|
||||
<p className="break-all font-mono text-xs">sha256: {selected?.sha256}</p>
|
||||
|
|
|
|||
|
|
@ -31,11 +31,11 @@ function DraftWorkbench({ id }: { id: number }) {
|
|||
})
|
||||
const files = useQuery({
|
||||
queryKey: ['authoring', 'draft', id, 'files'], queryFn: () => authoringApi.listFiles(id),
|
||||
enabled: validId && draft.isSuccess, meta: { skipGlobalErrorHandler: true }, retry: false,
|
||||
enabled: validId && draft.data != null, meta: { skipGlobalErrorHandler: true }, retry: false,
|
||||
})
|
||||
const runs = useQuery({
|
||||
queryKey: ['authoring', 'draft', id, 'runs'], queryFn: () => authoringApi.listRuns(id),
|
||||
enabled: validId && draft.isSuccess, meta: { skipGlobalErrorHandler: true }, retry: false,
|
||||
enabled: validId && draft.data != null, meta: { skipGlobalErrorHandler: true }, retry: false,
|
||||
refetchInterval: query => query.state.data?.some(run => run.active) ? 1500 : false,
|
||||
})
|
||||
const activeRun = runs.data?.some(run => run.active) ?? false
|
||||
|
|
@ -60,7 +60,7 @@ function DraftWorkbench({ id }: { id: number }) {
|
|||
|
||||
if (!validId) return <p role="alert">{t('authoring.detail.loadFailed')}</p>
|
||||
if (draft.isPending) return <p role="status">{t('authoring.ui.loading')}</p>
|
||||
if (draft.isError) return <QueryError error={draft.error} retry={() => void draft.refetch()} />
|
||||
if (!draft.data) return <QueryError error={draft.error} retry={() => void draft.refetch()} />
|
||||
const current = draft.data
|
||||
if (current.revision == null) return <p role="alert">{t('authoring.detail.loadFailed')}</p>
|
||||
return (
|
||||
|
|
@ -79,10 +79,11 @@ function DraftWorkbench({ id }: { id: number }) {
|
|||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t('authoring.detail.structureOnly')}</p>
|
||||
{dirty && <p role="status" className="text-sm text-muted-foreground">{t('authoring.detail.saveFirst')}</p>}
|
||||
{draft.isError && <QueryError error={draft.error} retry={() => void draft.refetch()} />}
|
||||
<Card><CardContent className="pt-6">
|
||||
{files.isPending && <p role="status">{t('authoring.ui.loading')}</p>}
|
||||
{files.isError && <QueryError error={files.error} retry={() => void files.refetch()} />}
|
||||
{files.isSuccess && <DraftFileEditor draftId={id} files={files.data} revision={current.revision} onSaved={refreshDraft} onDirtyChange={setDirty} />}
|
||||
{files.data && <DraftFileEditor draftId={id} files={files.data} revision={current.revision} onSaved={refreshDraft} onDirtyChange={setDirty} />}
|
||||
</CardContent></Card>
|
||||
<section className="space-y-3" aria-label={t('authoring.detail.tabRuns')}>
|
||||
<h2 className="text-lg font-semibold">{t('authoring.detail.tabRuns')}</h2>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue