Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

5.5 KB
Raw Blame
import {useEffect,useRef,useState} from 'react'
import HelpLink from './HelpLink'

const phases=new Set(['idle','completed','prepared','held','applying','applied','committing','rolling-back','unavailable'])
/** A validated /api/models/recovery receipt, or null. Portal's inline Recover reads it too. */
export function recoveryReceipt(value) {
  if (!value || typeof value.pending!=='boolean' || !phases.has(value.phase)
      || value.pending !== !['idle','completed'].includes(value.phase)) return null
  if(value.transactionId!=null && (typeof value.transactionId!=='string'
      || value.transactionId.length!==64 || !/^[a-f0-9]+$/.test(value.transactionId)))return null
  if(!['idle','unavailable'].includes(value.phase) && value.transactionId==null)return null
  return value
}

/** Recovery verifies the existing transaction; it never starts a new model load. */
export default function PortalModelRecovery({onPendingChange,onBusyChange,onRecovered,refreshKey=0,active=true,operationActive=false}) {
  const [state,setState]=useState(null),[busy,setBusy]=useState(false),[error,setError]=useState('')
  // Offered only when the agent says the switch changed nothing (fleet row 27).
  const [releasable,setReleasable]=useState(false)
  const mounted=useRef(false),request=useRef(null),locked=useRef(false)
  const pendingTransaction=useRef(null)
  const callbacks=useRef({onPendingChange,onBusyChange,onRecovered})
  callbacks.current={onPendingChange,onBusyChange,onRecovered}
  useEffect(()=>{
    mounted.current=true
    return ()=>{mounted.current=false;request.current?.abort();callbacks.current.onBusyChange?.(false)}
  },[])
  useEffect(()=>{
    if(!active || locked.current)return
    const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),6000)
    void fetch('/api/models/recovery',{signal:controller.signal}).then(async response=>{
      // The API also projects validated pending receipts on 409/503. Other
      // failures are not recovery state and must never invent an outcome.
      if(!response.ok && ![409,503].includes(response.status))return
      const value=recoveryReceipt(await response.json())
      if(!controller.signal.aborted && value){
        setState(value);callbacks.current.onPendingChange?.(value.pending)
        if(value.pending)pendingTransaction.current=value.transactionId
        // Models or another tab can complete this same held transaction. A
        // successful, matching receipt retires its earlier local errors;
        // idle, unrelated receipts, and availability alone do not prove it.
        else if(response.ok && value.phase==='completed' && value.transactionId===pendingTransaction.current && !operationActive){
          pendingTransaction.current=null;setError('');setReleasable(false);callbacks.current.onRecovered?.()
        }else if(value.transactionId!==pendingTransaction.current)pendingTransaction.current=null
      }
    }).catch(()=>{}).finally(()=>clearTimeout(timer))
    return ()=>{controller.abort();clearTimeout(timer)}
  },[refreshKey,active,operationActive])
  async function recover(release=false) {
    if(locked.current || operationActive || !state?.pending)return
    locked.current=true;setBusy(true);setError('');callbacks.current.onBusyChange?.(true)
    const controller=new AbortController();request.current=controller
    const timer=setTimeout(()=>controller.abort(),405000)
    try {
      const response=await fetch('/api/models/recovery',{method:'POST',headers:{'Content-Type':'application/json'},
        body:release?'{"releaseUnverified":true}':'{}',signal:controller.signal})
      const value=recoveryReceipt(await response.json())
      if(!mounted.current || controller.signal.aborted)return
      if(value){pendingTransaction.current=value.pending?value.transactionId:null;setState(value);callbacks.current.onPendingChange?.(value.pending)}
      if(response.ok && value && !value.pending){setReleasable(false);callbacks.current.onRecovered?.();return}
      const proofMissing=value?.reason==='model-recovery-proof-required'
      setReleasable(proofMissing && value.releasable===true)
      setError(proofMissing
        ? value.releasable===true
          ? 'ODS could not confirm the model Portal used before this switch, so it cannot finish the switch the usual way.'
          : 'The interrupted switch still needs repair. The saved state has been preserved.'
        : 'Recovery could not be confirmed. Reopen the model menu to read the current state.')
    } catch {
      if(mounted.current)setError('Recovery could not be confirmed. Reopen the model menu to read the current state.')
    } finally {
      clearTimeout(timer);request.current=null;locked.current=false
      if(mounted.current){setBusy(false);callbacks.current.onBusyChange?.(false)}
    }
  }
  if(!state?.pending)return null
  return <div className="portal-model-notice">
    <p>{operationActive ? 'A model operation is in progress. Wait for it to finish before requesting recovery.' : 'A model switch still needs verification before continuing.'}</p>
    <button type="button" disabled={busy || operationActive} onClick={()=>recover()}>{busy?'Recovering…':'Recover model switch'}</button>
    {error && <p role="alert">{error}</p>}
    {releasable && <>
      <p>The switch did not change anything, so ODS can release it and put Portal back on the model settings it had before. If that model was not working, choose another model or rerun the installer afterwards.</p>
      <button type="button" disabled={busy || operationActive} onClick={()=>recover(true)}>{busy?'Releasing…':'Release without checking'}</button>
    </>}
    {error && <HelpLink/>}
  </div>
}