All files / src/features/sorting useOptimisticRound.ts

94.11% Statements 48/51
82.6% Branches 19/23
100% Functions 11/11
100% Lines 41/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 1213x                 3x                                                   3x 31x                                   97x 97x 97x   97x 97x 97x 97x     28x 28x 28x 28x 28x 28x             28x 28x 2x 1x 1x   1x   26x   27x 27x 27x   28x         6x 6x 6x 6x 6x 5x 2x 2x   3x 3x     97x 97x               2x      
"use client";
 
import { useMemo, useRef, useState } from "react";
import { enqueue, newClientKey, removeQueued, type PendingEntry, type QueueKey } from "./decisionQueue";
import { directSubmit } from "./directSubmit";
import { awaitAck, isInFlight, triggerFlush, useDecisionFlusher, type AckOutcome } from "./decisionFlusher";
import { triageDecisions, type TriageResult } from "./roundCopy";
 
// TONE register — a gentle stumble, never "error"/"failed".
export const STUMBLE_LINE = "That didn't go through — give it another try in a moment.";
 
type TriageDecision = { itemId: string; result: TriageResult };
 
interface RevisitState {
  itemId: string;
  label: string;
}
 
export interface OptimisticRound {
  key: QueueKey;
  stumble: boolean;
  /** Persist-before-advance: resolves true once the answer is safe, false to stay put. */
  submitDecision: (itemId: string, decision: TriageDecision) => Promise<boolean>;
  revisit: RevisitState | null;
  canGoBack: boolean;
  /** The last answer's label for "Undo: …"; null when there is none. */
  lastLabel: string | null;
  /**
   * Undo the last answer: a still-queued one is removed (`fresh` — show the piece
   * as new); one already sent is re-presented (`revisit`). null when nothing moved.
   */
  goBack: () => { itemId: string; label: string; fresh: boolean } | null;
  clearRevisit: () => void;
}
 
const labelFor = (decision: TriageDecision) =>
  triageDecisions(decision.itemId).find((t) => t.decision.result === decision.result)?.label ?? decision.result;
 
/**
 * The feelings phase's answer engine: flusher wiring, persist-before-advance with
 * the storage fallback, and Undo. A still-queued answer is removed outright; one
 * already sent is re-presented with its choice selected, and the next tap
 * supersedes it (the log is append-only, latest wins).
 */
export function useOptimisticRound({
  curatorId,
  sessionId,
  collectionId,
}: {
  curatorId: string;
  sessionId: string;
  /** ULID collection.id — the queue key (never the slug). */
  collectionId: string;
}): OptimisticRound {
  const key = useMemo<QueueKey>(() => ({ curatorId, sessionId, collectionId }), [curatorId, sessionId, collectionId]);
  useDecisionFlusher(key);
  const [answers, setAnswers] = useState<Array<{ clientKey: string; itemId: string; label: string }>>([]);
  // Ack outcomes as they land, so Undo can tell a standing answer from a rejected one.
  const outcomesRef = useRef(new Map<string, AckOutcome>());
  const [revisit, setRevisit] = useState<RevisitState | null>(null);
  const [stumble, setStumble] = useState(false);
  const busyRef = useRef(false);
 
  async function submitDecision(itemId: string, decision: TriageDecision): Promise<boolean> {
    Iif (busyRef.current) return false;
    busyRef.current = true;
    try {
      setStumble(false);
      const clientKey = newClientKey();
      const entry: PendingEntry = {
        kind: "decision",
        clientKey,
        type: "triage",
        decision,
        enqueuedAt: new Date().toISOString(),
      };
      const persisted = await enqueue(key, entry, () => triggerFlush(key)); // quota → shrink the queue, retry once (F18)
      if (persisted === "needs_fallback") {
        if (!(await directSubmit({ sessionId, collectionId }, entry))) {
          setStumble(true);
          return false;
        }
        outcomesRef.current.set(clientKey, { status: "created" });
      } else {
        void awaitAck(key, clientKey).then((o) => outcomesRef.current.set(clientKey, o));
      }
      setAnswers((prev) => [...prev, { clientKey, itemId, label: labelFor(decision) }]);
      setRevisit(null);
      return true;
    } finally {
      busyRef.current = false;
    }
  }
 
  function goBack(): { itemId: string; label: string; fresh: boolean } | null {
    Iif (revisit !== null) return null;
    const last = answers[answers.length - 1];
    Iif (last === undefined) return null;
    const outcome = outcomesRef.current.get(last.clientKey);
    if (outcome?.status === "rejected") return null;
    if (outcome === undefined && !isInFlight(key, last.clientKey) && removeQueued(key, last.clientKey)) {
      setAnswers((prev) => prev.slice(0, -1));
      return { itemId: last.itemId, label: last.label, fresh: true };
    }
    setRevisit({ itemId: last.itemId, label: last.label });
    return { itemId: last.itemId, label: last.label, fresh: false };
  }
 
  const last = answers[answers.length - 1];
  return {
    key,
    stumble,
    submitDecision,
    revisit,
    canGoBack: revisit === null && last !== undefined,
    lastLabel: last?.label ?? null,
    goBack,
    clearRevisit: () => setRevisit(null),
  };
}