Skip to content

A full-featured download manager.

fix(plugins): prevent operation format switch flicker (#2376)

Dr_rOotc5e3261afedf
diff --git a/src/renderer/features/plugin-operations/operation-form.test.tsx b/src/renderer/features/plugin-operations/operation-form.test.tsx
index 51bad127..9476e2c6 100644
--- a/src/renderer/features/plugin-operations/operation-form.test.tsx
+++ b/src/renderer/features/plugin-operations/operation-form.test.tsx
@@ -98,6 +98,50 @@ const mount = () =>
<OperationForm {...request} />
</PlatformServicesProvider>
)
+function formatDrafts() {
+ const custom = structuredClone(descriptor)
+ custom.argsSchema.properties!.format = {
+ type: 'string',
+ enum: ['txt', 'md'],
+ default: 'txt',
+ }
+ custom.argsSchema.required!.push('format')
+ custom.definition.fields.push({
+ field: 'format',
+ label: 'Output format',
+ widget: 'segmented',
+ })
+ Object.assign(custom.definition.files!.output, { extensionFrom: 'format' })
+ custom.definition.ui!.layout = {
+ type: 'grid',
+ columns: 2,
+ children: [
+ { type: 'field', field: 'input' },
+ { type: 'field', field: 'ignoreCase' },
+ { type: 'field', field: 'output', span: 2, accessory: 'format' },
+ ],
+ }
+ const current: OperationDraft = {
+ ...structuredClone(draft),
+ descriptor: custom,
+ args: { ...draft.args, format: 'txt' },
+ }
+ const changed: OperationDraft = {
+ ...current,
+ args: { input, ignoreCase: false, format: 'md' },
+ files: { input: current.files.input },
+ suggestions: { output: '/files/output.md' },
+ }
+ const base = invoke.getMockImplementation()
+ invoke.mockImplementation(async (channel, ...args) => {
+ if (channel === Commands.GetPluginOperations)
+ return { descriptors: [custom], jobs: [] }
+ if (channel === Commands.PreparePluginOperation) return current
+ if (channel === Commands.UpdatePluginOperationDraft) return changed
+ return base?.(channel, ...args)
+ })
+ return { current, changed }
+}
describe('declarative operation form', () => {
beforeEach(() => {
useOperationSessions.setState({ sessions: {} })
@@ -531,47 +575,7 @@ describe('declarative operation form', () => {
).toHaveLength(1)
})
it('composes an inline format control and confirms a changed output before starting', async () => {
- const custom = structuredClone(descriptor)
- custom.argsSchema.properties!.format = {
- type: 'string',
- enum: ['txt', 'md'],
- default: 'txt',
- }
- custom.argsSchema.required!.push('format')
- custom.definition.fields.push({
- field: 'format',
- label: 'Output format',
- widget: 'segmented',
- })
- Object.assign(custom.definition.files!.output, { extensionFrom: 'format' })
- custom.definition.ui!.layout = {
- type: 'grid',
- columns: 2,
- children: [
- { type: 'field', field: 'input' },
- { type: 'field', field: 'ignoreCase' },
- { type: 'field', field: 'output', span: 2, accessory: 'format' },
- ],
- }
- const current = {
- ...structuredClone(draft),
- descriptor: custom,
- args: { ...draft.args, format: 'txt' },
- }
- const changed = {
- ...current,
- args: { input, ignoreCase: false, format: 'md' },
- files: { input: current.files.input },
- suggestions: { output: '/files/output.md' },
- }
- const base = invoke.getMockImplementation()
- invoke.mockImplementation(async (channel, ...args) => {
- if (channel === Commands.GetPluginOperations)
- return { descriptors: [custom], jobs: [] }
- if (channel === Commands.PreparePluginOperation) return current
- if (channel === Commands.UpdatePluginOperationDraft) return changed
- return base?.(channel, ...args)
- })
+ const { changed } = formatDrafts()
const view = mount()
fireEvent.click(await screen.findByRole('button', { name: 'md' }))
await screen.findByText('output.md')
@@ -595,6 +599,260 @@ describe('declarative operation form', () => {
)
).toBe(false)
})
+ it('keeps file cards and format controls stable during a delayed format update', async () => {
+ const { changed } = formatDrafts()
+ let finish!: (value: OperationDraft) => void
+ const update = new Promise<OperationDraft>((resolve) => {
+ finish = resolve
+ })
+ const base = invoke.getMockImplementation()
+ invoke.mockImplementation(async (channel, ...args) =>
+ channel === Commands.UpdatePluginOperationDraft
+ ? update
+ : base?.(channel, ...args)
+ )
+ const view = mount()
+ const format = await screen.findByRole('button', { name: 'md' })
+ const inputCard = screen.getByRole('button', { name: 'Input file' })
+ const outputCard = screen.getByRole('button', { name: 'Output file' })
+ format.focus()
+ fireEvent.click(format)
+ expect(format).toHaveAttribute('aria-pressed', 'true')
+ expect(format).toHaveFocus()
+ for (const control of [format, inputCard, outputCard])
+ expect(control).toBeEnabled()
+ const run = screen.getByRole('button', { name: 'Run operation' })
+ expect(run).toBeDisabled()
+ fireEvent.submit(run.closest('form')!)
+ expect(
+ invoke.mock.calls.some(
+ ([channel]) => channel === Commands.StartPluginOperation
+ )
+ ).toBe(false)
+ fireEvent.click(screen.getByRole('switch', { name: 'Ignore case' }))
+ await act(async () => finish(changed))
+ expect(screen.getByRole('button', { name: 'Input file' })).toBe(inputCard)
+ expect(screen.getByRole('button', { name: 'Output file' })).toBe(outputCard)
+ expect(screen.getByRole('button', { name: 'md' })).toBe(format)
+ expect(format).toHaveFocus()
+ expect(screen.getByRole('switch', { name: 'Ignore case' })).toBeChecked()
+ expect(outputCard).toHaveTextContent('output.md')
+ expect(view.container.querySelector('[data-slot="skeleton"]')).toBeNull()
+ expect(run).toBeEnabled()
+ expect(
+ useOperationSessions.getState().sessions[operationSessionKey(request)]
+ ?.values
+ ).toEqual({ ...changed.args, ignoreCase: true })
+ })
+ it.each(['resolve', 'reject'] as const)(
+ 'serializes rapid format changes and retains the last confirmed draft on %s',
+ async (result) => {
+ const { changed } = formatDrafts()
+ const requests: {
+ resolve(value: OperationDraft): void
+ reject(error: Error): void
+ }[] = []
+ const base = invoke.getMockImplementation()
+ invoke.mockImplementation(async (channel, ...args) =>
+ channel === Commands.UpdatePluginOperationDraft
+ ? new Promise<OperationDraft>((resolve, reject) => {
+ requests.push({ resolve, reject })
+ })
+ : base?.(channel, ...args)
+ )
+ mount()
+ fireEvent.click(await screen.findByRole('button', { name: 'md' }))
+ fireEvent.click(screen.getByRole('button', { name: 'txt' }))
+ expect(requests).toHaveLength(1)
+ expect(screen.getByRole('button', { name: 'txt' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ )
+ await act(async () => requests[0].resolve(changed))
+ expect(requests).toHaveLength(2)
+ expect(invoke).toHaveBeenLastCalledWith(
+ Commands.UpdatePluginOperationDraft,
+ {
+ draftId: draft.id,
+ values: expect.objectContaining({ format: 'txt' }),
+ }
+ )
+ expect(screen.getByRole('button', { name: 'txt' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ )
+ expect(
+ screen.getByRole('button', { name: 'Run operation' })
+ ).toBeDisabled()
+ const finalDraft = {
+ ...changed,
+ args: { ...changed.args, format: 'txt' },
+ suggestions: { output: '/files/output.txt' },
+ }
+ await act(async () => {
+ if (result === 'resolve') requests[1].resolve(finalDraft)
+ else requests[1].reject(new Error('pluginOperations.failed'))
+ })
+ const confirmed = result === 'resolve' ? finalDraft : changed
+ expect(
+ screen.getByRole('button', { name: String(confirmed.args.format) })
+ ).toHaveAttribute('aria-pressed', 'true')
+ expect(
+ screen.getByRole('button', { name: 'Output file' })
+ ).toHaveTextContent(`output.${confirmed.args.format}`)
+ expect(
+ useOperationSessions.getState().sessions[operationSessionKey(request)]
+ ?.values
+ ).toEqual(confirmed.args)
+ expect(
+ screen.getByRole('button', { name: 'Run operation' })
+ ).toBeEnabled()
+ if (result === 'reject')
+ expect(screen.getByRole('alert')).toBeInTheDocument()
+ }
+ )
+ it.each(['resolve', 'reject'] as const)(
+ 'waits for a format update before picking an output file on %s',
+ async (result) => {
+ const { current, changed } = formatDrafts()
+ let finish!: (value: OperationDraft) => void
+ let fail!: (error: Error) => void
+ const update = new Promise<OperationDraft>((resolve, reject) => {
+ finish = resolve
+ fail = reject
+ })
+ const base = invoke.getMockImplementation()
+ invoke.mockImplementation(async (channel, ...args) =>
+ channel === Commands.UpdatePluginOperationDraft
+ ? update
+ : base?.(channel, ...args)
+ )
+ mount()
+ fireEvent.click(await screen.findByRole('button', { name: 'md' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Ignore case' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Output file' }))
+ expect(
+ invoke.mock.calls.some(
+ ([channel]) => channel === Commands.PickPluginOperationFile
+ )
+ ).toBe(false)
+ await act(async () => {
+ if (result === 'resolve') finish(changed)
+ else fail(new Error('pluginOperations.failed'))
+ })
+ if (result === 'resolve') {
+ expect(invoke).toHaveBeenCalledWith(Commands.PickPluginOperationFile, {
+ draftId: draft.id,
+ field: 'output',
+ values: { ...changed.args, ignoreCase: true },
+ })
+ } else {
+ expect(
+ invoke.mock.calls.some(
+ ([channel]) => channel === Commands.PickPluginOperationFile
+ )
+ ).toBe(false)
+ expect(screen.getByRole('button', { name: 'txt' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ )
+ expect(
+ screen.getByRole('button', { name: 'Output file' })
+ ).toHaveTextContent('output.txt')
+ expect(
+ useOperationSessions.getState().sessions[operationSessionKey(request)]
+ ?.values
+ ).toEqual({ ...current.args, ignoreCase: true })
+ expect(screen.getByRole('alert')).toBeInTheDocument()
+ }
+ expect(screen.getByRole('switch', { name: 'Ignore case' })).toBeChecked()
+ expect(
+ screen.getByRole('button', { name: 'Run operation' })
+ ).toBeEnabled()
+ }
+ )
+ it.each(['resolve', 'reject'] as const)(
+ 'reconciles an in-flight format update before reopening the form on %s',
+ async (result) => {
+ const { current, changed } = formatDrafts()
+ let finish!: (value: OperationDraft) => void
+ let fail!: (error: Error) => void
+ const update = new Promise<OperationDraft>((resolve, reject) => {
+ finish = resolve
+ fail = reject
+ })
+ const base = invoke.getMockImplementation()
+ invoke.mockImplementation(async (channel, ...args) =>
+ channel === Commands.UpdatePluginOperationDraft
+ ? update
+ : base?.(channel, ...args)
+ )
+ const first = mount()
+ fireEvent.click(await screen.findByRole('button', { name: 'md' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Ignore case' }))
+ first.unmount()
+ const reopened = mount()
+ await waitFor(() =>
+ expect(
+ invoke.mock.calls.filter(
+ ([channel]) => channel === Commands.GetPluginOperations
+ )
+ ).toHaveLength(2)
+ )
+ expect(screen.queryByRole('button', { name: 'Run operation' })).toBeNull()
+ expect(screen.getByRole('status')).toHaveAttribute('aria-busy', 'true')
+ await act(async () => {
+ if (result === 'resolve') finish(changed)
+ else fail(new Error('pluginOperations.fileChanged'))
+ })
+ const expected = result === 'resolve' ? changed : current
+ expect(
+ await screen.findByRole('button', { name: 'Output file' })
+ ).toHaveTextContent(`output.${expected.args.format}`)
+ expect(
+ screen.getByRole('button', { name: String(expected.args.format) })
+ ).toHaveAttribute('aria-pressed', 'true')
+ expect(screen.getByRole('switch', { name: 'Ignore case' })).toBeChecked()
+ expect(
+ screen.getByRole('button', { name: 'Run operation' })
+ ).toBeEnabled()
+ if (result === 'reject')
+ expect(screen.getByRole('alert')).toHaveTextContent('changed')
+ expect(
+ invoke.mock.calls.filter(
+ ([channel]) => channel === Commands.PreparePluginOperation
+ )
+ ).toHaveLength(1)
+ expect(
+ useOperationSessions.getState().sessions[operationSessionKey(request)]
+ ?.values
+ ).toEqual({ ...expected.args, ignoreCase: true })
+ reopened.unmount()
+ }
+ )
+ it('does not open a queued file picker after the form closes', async () => {
+ const { changed } = formatDrafts()
+ let finish!: (value: OperationDraft) => void
+ const update = new Promise<OperationDraft>((resolve) => {
+ finish = resolve
+ })
+ const base = invoke.getMockImplementation()
+ invoke.mockImplementation(async (channel, ...args) =>
+ channel === Commands.UpdatePluginOperationDraft
+ ? update
+ : base?.(channel, ...args)
+ )
+ const view = mount()
+ fireEvent.click(await screen.findByRole('button', { name: 'md' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Output file' }))
+ view.unmount()
+ await act(async () => finish(changed))
+ expect(
+ invoke.mock.calls.some(
+ ([channel]) => channel === Commands.PickPluginOperationFile
+ )
+ ).toBe(false)
+ })
it('refreshes localized presentation without resetting dirty values, grants or a running job', async () => {
const localized = structuredClone(descriptor)
localized.definition.title = '文本去重'
diff --git a/src/renderer/features/plugin-operations/operation-form.tsx b/src/renderer/features/plugin-operations/operation-form.tsx
index 229c214a..70063243 100644
--- a/src/renderer/features/plugin-operations/operation-form.tsx
+++ b/src/renderer/features/plugin-operations/operation-form.tsx
@@ -28,6 +28,14 @@ import { useOperationState } from './use-operation-state'
type OperationFormProps = OperationRequest & { onClose?: () => void }
+function operationErrorKey(error: unknown): string {
+ return (
+ (error instanceof Error ? error.message : String(error)).match(
+ /pluginOperations\.[A-Za-z]+/
+ )?.[0] ?? 'pluginOperations.failed'
+ )
+}
+
export default function OperationForm(props: OperationFormProps) {
const { t } = useTranslation()
const { snapshot, failed, retry } = useOperationState()
@@ -105,6 +113,9 @@ function OperationFormContent({
const [draft, setDraft] = useState<OperationDraft | undefined>(session.draft)
const [job, setJob] = useState<OperationJob | undefined>(session?.job)
const [pending, setPending] = useState(false)
+ const [updatingDraft, setUpdatingDraft] = useState(false)
+ const [resumingDraft, setResumingDraft] = useState(!!session.draftUpdate)
+ const draftUpdate = useRef(session.draftUpdate ?? null)
const [starting, setStarting] = useState(false)
const [cancelling, setCancelling] = useState(false)
const cancelRequested = useRef(false)
@@ -134,15 +145,7 @@ function OperationFormContent({
},
[sessionKey, loadedDescriptor.descriptorRevision]
)
- const report = useCallback(
- (e: unknown) =>
- setError(
- (e instanceof Error ? e.message : String(e)).match(
- /pluginOperations\.[A-Za-z]+/
- )?.[0] ?? 'pluginOperations.failed'
- ),
- []
- )
+ const report = useCallback((e: unknown) => setError(operationErrorKey(e)), [])
const prepare = useCallback(
async (repeatJobId?: string, resume = false) => {
if (inFlight.current) return
@@ -221,9 +224,23 @@ function OperationFormContent({
...session,
descriptor: loadedDescriptor,
})
+ if (session.draftUpdate) {
+ // A closed form can still be updating the host. Reopen only after its
+ // confirmed file references and latest values have reached the session.
+ void session.draftUpdate.then((failure) => {
+ if (!mounted.current) return
+ const latest = useOperationSessions.getState().sessions[sessionKey]
+ setDraft(latest?.draft)
+ form.reset(latest?.values ?? latest?.draft?.args ?? {})
+ draftUpdate.current = null
+ setResumingDraft(false)
+ if (failure) report(failure)
+ })
+ return
+ }
if ((!draft || draft.expiresAt < Date.now()) && !job)
void prepare(undefined, true)
- }, [draft, job, loadedDescriptor, prepare, session, sessionKey])
+ }, [draft, form, job, loadedDescriptor, prepare, report, session, sessionKey])
// Localization updates presentation without changing the revision or grants.
useEffect(() => {
save({ descriptor: loadedDescriptor })
@@ -274,35 +291,71 @@ function OperationFormContent({
}
const change = (field: string, value: string | number | boolean) => {
if (!draft || inFlight.current) return
- const previous = form.getValues()
+ if (form.getValues(field) === value) return
form.setValue(field, value, { shouldDirty: true })
save({ key: undefined })
- if (
- !Object.values(draft.descriptor.definition.files ?? {}).some(
- (f) => f.kind === 'output-file' && f.extensionFrom === field
- )
+ const files = draft.descriptor.definition.files ?? {}
+ const extensionFields = Object.values(files).flatMap((binding) =>
+ binding.kind === 'output-file' && binding.extensionFrom
+ ? [binding.extensionFrom]
+ : []
)
- return
- inFlight.current = true
- setPending(true)
- void invokeOperation<OperationDraft>(Commands.UpdatePluginOperationDraft, {
- draftId: draft.id,
- values: form.getValues(),
- })
- .then(acceptDraft)
- .catch((e) => {
+ if (!extensionFields.includes(field) || draftUpdate.current) return
+
+ // Synchronize formats without flashing the whole form's disabled styles.
+ // Each response must settle before another update touches the host draft.
+ setUpdatingDraft(true)
+ setError('')
+ draftUpdate.current = (async () => {
+ let confirmed = draft
+ try {
+ let submitted: typeof values
+ do {
+ submitted = { ...form.getValues() }
+ confirmed = await invokeOperation<OperationDraft>(
+ Commands.UpdatePluginOperationDraft,
+ { draftId: draft.id, values: submitted }
+ )
+ } while (
+ extensionFields.some((key) => form.getValues(key) !== submitted[key])
+ )
+ return undefined
+ } catch (e) {
+ if (mounted.current) report(e)
+ return operationErrorKey(e)
+ } finally {
+ // Keep unrelated edits made during the request. File references and
+ // their formats always come from the last confirmed host draft.
+ const nextValues = { ...form.getValues() }
+ for (const key of [...Object.keys(files), ...extensionFields]) {
+ delete nextValues[key]
+ if (confirmed.args[key] !== undefined)
+ nextValues[key] = confirmed.args[key]
+ }
if (mounted.current) {
- form.reset(previous)
- report(e)
+ setDraft(confirmed)
+ form.reset(nextValues, {
+ keepErrors: true,
+ keepDirty: true,
+ keepTouched: true,
+ })
+ setUpdatingDraft(false)
}
- })
- .finally(() => {
- inFlight.current = false
- if (mounted.current) setPending(false)
- })
+ save({
+ draft: confirmed,
+ draftUpdate: undefined,
+ values: nextValues,
+ key: undefined,
+ })
+ draftUpdate.current = null
+ }
+ })()
+ save({ draftUpdate: draftUpdate.current })
}
const pick = async (field: string, dropCandidate?: string) => {
if (!draft) return null
+ if (draftUpdate.current && (await draftUpdate.current)) return null
+ if (!mounted.current) return null
const params = { draftId: draft.id, field, values: form.getValues() }
let next: OperationDraft | null
if (__MOTRIX_TARGET__ === 'electron')
@@ -327,7 +380,7 @@ function OperationFormContent({
return next
}
const start = form.handleSubmit(async (values) => {
- if (!draft || inFlight.current || job) return
+ if (!draft || inFlight.current || draftUpdate.current || job) return
inFlight.current = true
cancelRequested.current = false
setStarting(true)
@@ -421,7 +474,8 @@ function OperationFormContent({
draft.descriptor.descriptorRevision)
? loadedDescriptor
: draft?.descriptor
- if (!draft && !job && !starting && pending) return <OperationSkeleton />
+ if (resumingDraft || (!draft && !job && !starting && pending))
+ return <OperationSkeleton />
if (!descriptor || (!draft && !job && !starting))
return (
<div role="status" className="space-y-3">
@@ -570,6 +624,7 @@ function OperationFormContent({
type="submit"
disabled={
blocked ||
+ updatingDraft ||
descriptor.argsSchema.required?.some(
(field) =>
!values[field] &&
diff --git a/src/renderer/features/plugin-operations/operation-store.ts b/src/renderer/features/plugin-operations/operation-store.ts
index b7f8a6af..83fc96ad 100644
--- a/src/renderer/features/plugin-operations/operation-store.ts
+++ b/src/renderer/features/plugin-operations/operation-store.ts
@@ -21,6 +21,7 @@ export const useOperationDialog = create<{
export interface OperationSession {
descriptor?: OperationDescriptor
draft?: OperationDraft
+ draftUpdate?: Promise<string | undefined>
values?: Record<string, string | number | boolean>
job?: OperationJob
key?: string