fix(app): editor store keeps an unanswered copy across mode changes, refuses unsaved submit

This commit is contained in:
bchanot committed 2026-11-04 12:17:41 +01:00
1 parent 7f1d44065b
commit b14509f221
7 files changed
+102 -4

No files matched your search

+1
View File
@@ -210,6 +210,7 @@ export async function discardChanges(
const state = api.get()
const block = blockKind(state)
if (block || !state.preview) return { ok: false, reason: 'blocked', kind: block ?? 'not_ready' }
if (state.saving || state.submitting) return { ok: false, reason: 'blocked', kind: 'busy' }
if (!option.confirmed) return { ok: false, reason: 'blocked', kind: 'confirmation_required' }
if (state.staleBase) return reloadServerDraft(api, option)
const replaced = state.preview.replaceDocument(state.savedText)
+7 -2
View File
@@ -55,7 +55,8 @@ function conflictFrom(admin: OfficialSheetAdmin, state: EditorState): ConflictSt
/** Reads the conflict; a failed read or an unparsable answer is the `unknown` variant. */
export async function readConflict(api: StoreApi, session: number): Promise<void> {
const state = api.get()
api.set({ conflict: { status: 'reading' } })
const reading: ConflictState = { status: 'reading' }
api.set({ conflict: reading })
let next: ConflictState
try {
const admin = await getOfficialSheetAdmin(requireClient(), state.sheetId ?? '')
@@ -63,7 +64,10 @@ export async function readConflict(api: StoreApi, session: number): Promise<void
} catch {
next = { status: 'unknown' }
}
if (api.get().session === session) api.set({ conflict: next })
// A dismissed dialog or a later save replaced the reading state: drop the late answer.
if (api.get().session === session && api.get().conflict === reading) {
api.set({ conflict: next })
}
}
interface Attempt {
@@ -150,6 +154,7 @@ export async function submit(api: StoreApi, note?: string): Promise<SubmitOutcom
const block = saveBlock(state)
if (block) return blocked(block)
if (state.staleBase) return blocked('stale_base')
if (state.unsaved) return blocked('unsaved')
api.set({ submitting: true })
try {
const args = {
+2 -1
View File
@@ -9,6 +9,7 @@ import {
copyInputsChanged,
ignoreCopy,
restoreCopy,
setCanEdit,
syncCopy,
} from './recoveryFlow'
@@ -23,7 +24,7 @@ export const useEditorStore = create<EditorState>()((set, get) => {
...initialData(),
open: (versionId, userId, options) => open(api, versionId, userId, options),
close: () => close(api),
setCanEdit: (canEdit) => set({ canEdit }),
setCanEdit: (canEdit) => setCanEdit(api, canEdit),
commit: (command, options) => commit(api, command, options?.accept),
undoStep: () => stepHistory(api, 'undo'),
redoStep: () => stepHistory(api, 'redo'),
+1
View File
@@ -19,6 +19,7 @@ export type BlockKind =
| 'confirmation_required'
| 'stale_base'
| 'revision_unknown'
| 'unsaved'
| 'session_changed'
export interface Blocked {
+27 -1
View File
@@ -68,6 +68,32 @@ export function detectRecovery(input: DetectInput): RecoveryPatch {
return { ...NO_RECOVERY, recovery: 'pending', offer }
}
/**
* A mode change. Becoming editable re-runs the recovery detection (a copy found while the
* mode could not use it is offered or refused now, never overwritten); unsaved work of
* this session is kept as is.
*/
export function setCanEdit(api: StoreApi, canEdit: boolean): void {
const state = api.get()
if (canEdit === state.canEdit) return
const ready = state.status === 'ready' && state.userId !== null
if (!canEdit || !ready || state.unsaved) {
const unusable = ready && !canEdit && copyExists(state.userId ?? '', state.versionId ?? '')
api.set({ canEdit, unusableCopy: unusable })
return
}
api.set({
canEdit,
...detectRecovery({
userId: state.userId ?? '',
versionId: state.versionId ?? '',
canEdit,
savedText: state.savedText,
savedRevision: state.savedRevision,
}),
})
}
function sheetNameOf(state: EditorState): string {
const name = state.previewState?.document.name
return name?.fr.trim() || name?.en.trim() || state.versionId || ''
@@ -94,7 +120,7 @@ function buildCopy(state: EditorState): RecoveryCopy {
*/
export function syncCopy(api: StoreApi): void {
const state = api.get()
const live = state.status === 'ready' && state.canEdit
const live = state.status === 'ready' && state.canEdit && !state.unusableCopy
if (!live || state.recovery !== 'none' || !state.unsaved) return
const result = writeCopy(buildCopy(state))
api.set({
@@ -263,3 +263,35 @@ describe('cap, quota and other accounts', () => {
expect(storedCopy()).toBeNull()
})
})
describe('becoming editable with a stored copy', () => {
it('offers a different copy and keeps its bytes, commit refused', async () => {
seed(movedText(10), 3)
const raw = sessionStorage.getItem(copyKeyOf())
await openReady({ canEdit: false })
store.getState().setCanEdit(true)
expect(store.getState()).toMatchObject({ recovery: 'pending', unusableCopy: false })
expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' })
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
})
it('refuses an unreadable copy and never overwrites it', async () => {
sessionStorage.setItem(copyKeyOf(), 'not json{')
await openReady({ canEdit: false })
store.getState().setCanEdit(true)
expect(store.getState()).toMatchObject({ recovery: 'refused', refusedKind: 'unreadable' })
expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' })
expect(sessionStorage.getItem(copyKeyOf())).toBe('not json{')
})
it('does not write over a copy flagged unusable', async () => {
seed(movedText(10), 3)
const raw = sessionStorage.getItem(copyKeyOf())
await openReady()
store.getState().ignoreCopy({ confirmed: true })
seed(movedText(10), 3)
store.setState({ unusableCopy: true })
commitMove(40)
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
})
})
+32
View File
@@ -332,3 +332,35 @@ describe('discard and submit', () => {
expect(store.getState().conflict).toEqual({ status: 'unknown' })
})
})
describe('guards', () => {
it('refuses a submit while the document differs from the saved text', async () => {
await openReady()
commitMove(40)
expect(await store.getState().submit()).toMatchObject({ ok: false, kind: 'unsaved' })
expect(sb.submitSheetReview).not.toHaveBeenCalled()
})
it('refuses a discard while a save is in flight', async () => {
await openReady()
commitMove(40)
sb.saveSheetDraft.mockReturnValue(deferred<unknown>().promise as never)
void store.getState().save()
expect(await store.getState().discardChanges({ confirmed: true })).toMatchObject({ kind: 'busy' })
expect(store.getState().unsaved).toBe(true)
})
it('drops a conflict read that lands after dismissal', async () => {
await openReady()
commitMove(40)
const late = deferred<unknown>()
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft_conflict'))
sb.getOfficialSheetAdmin.mockReturnValue(late.promise as never)
const saving = store.getState().save()
await vi.waitFor(() => expect(store.getState().conflict).toEqual({ status: 'reading' }))
store.getState().dismissConflict()
late.resolve({ draft_version: { version_id: VERSION, version_number: 1, revision: 5 }, draft_last_save: null })
await saving
expect(store.getState().conflict).toBeNull()
})
})