Ver Fonte

fix(settings): race condition in orchestration toggle — optimistic update (#121)

The useEffect initial fetch for orchestration state could complete
after the user toggled, overwriting the new value with the stale DB
state. Fix: optimistic update (set state immediately on toggle),
revert on PUT failure, and skip stale initial fetch if already touched.
gnacho há 3 meses atrás
pai
commit
64167409fd
1 ficheiros alterados com 8 adições e 3 exclusões
  1. 8 3
      app/src/pages/Settings.tsx

+ 8 - 3
app/src/pages/Settings.tsx

@@ -2455,12 +2455,13 @@ export default function Settings() {
   // ——— Orquestación (issue #121): toggle opt-in en la AdminBar ———
   // ——— Orquestación (issue #121): toggle opt-in en la AdminBar ———
   const [orchOn, setOrchOn] = useState(false)
   const [orchOn, setOrchOn] = useState(false)
   const [orchBusy, setOrchBusy] = useState(false)
   const [orchBusy, setOrchBusy] = useState(false)
+  const orchTouched = useRef(false)
   useEffect(() => {
   useEffect(() => {
     let alive = true
     let alive = true
     void fetch('/api/settings/orchestration')
     void fetch('/api/settings/orchestration')
       .then((r) => (r.ok ? r.json() : null))
       .then((r) => (r.ok ? r.json() : null))
       .then((d) => {
       .then((d) => {
-        if (alive && d) setOrchOn(!!d.enabled)
+        if (alive && d && !orchTouched.current) setOrchOn(!!d.enabled)
       })
       })
       .catch(() => undefined)
       .catch(() => undefined)
     return () => {
     return () => {
@@ -2468,6 +2469,8 @@ export default function Settings() {
     }
     }
   }, [])
   }, [])
   const toggleOrchestration = useCallback(async (enabled: boolean) => {
   const toggleOrchestration = useCallback(async (enabled: boolean) => {
+    orchTouched.current = true
+    setOrchOn(enabled)
     setOrchBusy(true)
     setOrchBusy(true)
     try {
     try {
       const res = await fetch('/api/settings/orchestration', {
       const res = await fetch('/api/settings/orchestration', {
@@ -2475,8 +2478,10 @@ export default function Settings() {
         headers: { 'Content-Type': 'application/json' },
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({ enabled }),
         body: JSON.stringify({ enabled }),
       })
       })
-      if (!res.ok) return
-      setOrchOn(enabled)
+      if (!res.ok) {
+        setOrchOn(!enabled)
+        return
+      }
       refreshOverview() // el overview propaga el flag → el nav se actualiza
       refreshOverview() // el overview propaga el flag → el nav se actualiza
     } finally {
     } finally {
       setOrchBusy(false)
       setOrchBusy(false)