fix(junction): isolate lifecycle previews and drafts

This commit is contained in:
que01 committed 2026-09-08 15:28:06 +08:00
1 parent 89f4ce79b0
commit a5f64a2349
4 files changed
+75 -1

No files matched your search

@@ -101,6 +101,20 @@ describe('cancellation', () => {
expect(signals).toHaveLength(1);
});
it('drops a response after its owning scope was invalidated', async () => {
const { send, pending, signals } = deferredTransport();
const requester = new PreviewRequester({ session, send, onSettled });
requester.flush({ constraints: [] });
requester.invalidate();
expect(signals[0].aborted).toBe(true);
// Transports are allowed to resolve despite abort; this is the lifecycle
// boundary that protects a newly selected junction.
pending[0].resolve(preview(1));
await vi.advanceTimersByTimeAsync(0);
expect(onSettled).not.toHaveBeenCalled();
expect(session.lastValidPreview()).toBeNull();
});
it('never reports an abort as an error', async () => {
const send = vi.fn<PreviewTransport>(async () => {
throw Object.assign(new Error('cancelled'), { name: 'AbortError' });
@@ -38,6 +38,8 @@ function isAbort(error: unknown): boolean {
export class PreviewRequester {
private timer: ReturnType<typeof setTimeout> | null = null;
private inFlight: AbortController | null = null;
/** Changes whenever the owning map/junction scope changes. */
private generation = 0;
private readonly debounceMs: number;
constructor(private readonly options: PreviewRequesterOptions) {
@@ -75,6 +77,18 @@ export class PreviewRequester {
this.inFlight = null;
}
/**
* Aborts the active scope and makes responses from it ineligible for apply.
*
* Abort is cooperative: a transport may resolve after the signal fires. The
* generation check in `dispatch()` is therefore the authority that prevents
* an A-scope response from replacing the UI after A -> B navigation.
*/
invalidate(): void {
this.generation += 1;
this.cancel();
}
private async dispatch(draft: PreviewDraft): Promise<void> {
// Abort the older request before starting a newer one: its answer is already
// obsolete, and leaving it running wastes a solve the user cannot see.
@@ -82,8 +96,10 @@ export class PreviewRequester {
const controller = new AbortController();
this.inFlight = controller;
const previewSeq = this.options.session.nextPreviewSeq();
const generation = this.generation;
try {
const response = await this.options.send({ previewSeq, ...draft }, controller.signal);
if (generation !== this.generation) return;
const outcome = this.options.session.acceptPreview(response);
// A stale response is dropped silently; that is the arbitration working.
if (outcome.applied) this.options.onSettled(outcome, response);