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.

12.5 KB
Raw Blame
import { Navigate, Routes, Route, useLocation, useNavigate } from 'react-router-dom'
import { useState, useEffect, Suspense, useMemo, useCallback, lazy } from 'react'
import Sidebar from './components/Sidebar'
import WallpaperVideo from './components/WallpaperVideo'
import PanelResizeHandle from './components/PanelResizeHandle'
import MetalMetricIcon from './components/MetalMetricIcon'
import InstallPromptBanner from './components/InstallPromptBanner'
import PortalUpdateNotice from './components/PortalUpdateNotice'
import { useSystemStatus } from './hooks/useSystemStatus'
import { useVersion } from './hooks/useVersion'
import { useFirstRun } from './hooks/useFirstRun'
import { useSessionBootstrap } from './hooks/useSessionBootstrap'
import { getInternalRoutes } from './plugins/registry'
import { X, PanelRightClose, PanelRightOpen, Loader2 } from 'lucide-react'
import { PortalIdentityProvider } from './contexts/PortalIdentityContext'

// Phone-first first-boot wizard. Mounted instead of the normal app shell
// when useFirstRun() reports firstRun=true. Lazy-loaded so the wizard
// bundle isn't paid for on every page load after onboarding.
const FirstBoot = lazy(() => import('./pages/FirstBoot'))
const ODSTalk = lazy(() => import('./pages/ODSTalk'))
const SettingsModal = lazy(() => import('./components/SettingsModal'))
const Pixel = lazy(() => import('./pages/Pixel'))
const PixelSettings = lazy(() => import('./pages/PixelSettings'))

function getStorageValue(storage, key) {
  try {
    return globalThis[storage]?.getItem(key)
  } catch {
    return null
  }
}

function setStorageValue(storage, key, value) {
  try {
    globalThis[storage]?.setItem(key, value)
  } catch {
    // Ignore storage failures in private windows or restricted environments.
  }
}

function App() {
  const location = useLocation()
  const navigate = useNavigate()
  useEffect(() => {
    if (location.pathname === '/pixel') navigate('/', {replace:true})
  }, [location.pathname, navigate])
  const panelLocation = location
  const panelOpen = !['/', '/pixel'].includes(panelLocation.pathname)
  const [panelCollapsed, setPanelCollapsed] = useState(false)
  const [panelWidth, setPanelWidth] = useState(440)
  useEffect(() => { setPanelCollapsed(false) }, [panelLocation.pathname])
  const isTalkHost = typeof window !== 'undefined' && window.location.hostname.startsWith('talk.')
  const isTalkPath = isTalkHost || location.pathname.startsWith('/talk')

  // Auto-mint a ods-session cookie on load so the install owner can
  // reach cookie-gated services (Hermes, future ones) without redeeming
  // a magic link to themselves. No-ops if a valid cookie already exists.
  // See hooks/useSessionBootstrap.js for the full rationale.
  useSessionBootstrap(!isTalkPath)

  const { status, loading, error } = useSystemStatus()
  const { version, showUpdate, dismissUpdate } = useVersion()
  // Server-side first-run flag (sourced from /api/setup/status). localStorage
  // was per-browser and gave the wrong answer on re-imaged devices or fresh
  // browsers. The hook returns firstRun=false while it's loading or if the
  // API call fails, so the normal app shell is the safe default.
  const { firstRun, refresh: refreshFirstRun } = useFirstRun()
  const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
    return getStorageValue('localStorage', 'ods-sidebar-collapsed') === 'true'
  })

  useEffect(() => {
    setStorageValue('localStorage', 'ods-sidebar-collapsed', String(sidebarCollapsed))
  }, [sidebarCollapsed])

  const dismissFirstRun = useCallback(() => {
    // SetupWizard's saveConfig has already POSTed /api/setup/complete; we
    // re-fetch the server flag so the next mount sees the new state.
    refreshFirstRun()
  }, [refreshFirstRun])

  const routes = useMemo(() => getInternalRoutes({ status, loading }), [status, loading])
  const handleToggle = useCallback(() => setSidebarCollapsed(c => !c), [])

  if (isTalkPath) {
    return (
      <div className="min-h-screen bg-theme-bg text-theme-text">
        <Suspense fallback={
          <div className="min-h-screen flex items-center justify-center">
            <div className="text-sm text-theme-text-muted">Opening ODS Talk...</div>
          </div>
        }>
          <ODSTalk />
        </Suspense>
      </div>
    )
  }

  // First-boot path: render the FirstBoot SPA fullscreen and lock out the
  // rest of the dashboard. The user can't reach Settings / Extensions / etc.
  // until they've completed onboarding — that simplifies the wizard story
  // (one path, no escape hatches) and prevents half-configured devices
  // from getting halfway-set-up.
  if (firstRun) {
    return (
      <div className="min-h-screen bg-theme-bg text-theme-text">
        <Suspense fallback={
          <div className="min-h-screen flex items-center justify-center">
            <div className="font-mono text-sm text-theme-accent tracking-widest animate-pulse">ODS</div>
          </div>
        }>
          <FirstBoot onComplete={dismissFirstRun} />
        </Suspense>
      </div>
    )
  }

  return (
    <PortalIdentityProvider>
    <div className={`pixel-app flex min-h-screen bg-theme-bg text-theme-text relative ${sidebarCollapsed ? 'sidebar-collapsed' : ''}`}>
      <WallpaperVideo />
      <Sidebar
        status={status}
        collapsed={sidebarCollapsed}
        onToggle={handleToggle}
      />

      <main className="pixel-workspace dashboard-market-shell portal-workspace flex-1 transition-all duration-200">
        <div className="portal-chat">
          {showUpdate && <PortalUpdateNotice version={version} onDismiss={dismissUpdate} onReview={() => navigate('/settings?section=updates')} />}
          {status?.bootstrap?.active && <BootstrapBanner bootstrap={status.bootstrap} />}
          <Suspense fallback={<p className="p-6 text-theme-text-muted">Opening Portal…</p>}><Pixel systemStatus={status} /></Suspense>
        </div>
        {panelOpen && <aside style={{'--portal-panel-width':`${panelWidth}px`}} className={`portal-side-panel ${panelCollapsed ? 'is-collapsed' : ''}`} aria-label="Workspace panel">
          {!panelCollapsed && <PanelResizeHandle width={panelWidth} onResize={setPanelWidth} />}
          <header><strong>{routes.find(route => route.path === panelLocation.pathname)?.label || 'Workspace'}</strong><button className="pixel-metal-control" aria-label={panelCollapsed ? 'Expand workspace panel' : 'Collapse workspace panel'} onClick={() => setPanelCollapsed(value => !value)}><MetalMetricIcon icon={panelCollapsed ? PanelRightOpen : PanelRightClose}/></button><button className="pixel-metal-control" aria-label="Close workspace panel" onClick={() => navigate('/')}><MetalMetricIcon icon={X}/></button></header>
          <div className="portal-panel-content" hidden={panelCollapsed}>
        <Suspense fallback={
          <div className="p-8 animate-pulse">
            <div className="h-8 bg-theme-card rounded w-1/3 mb-4" />
            <div className="grid grid-cols-3 gap-6">
              {[...Array(6)].map((_, i) => <div key={i} className="h-40 bg-theme-card rounded-xl" />)}
            </div>
          </div>
        }>
          <Routes location={panelLocation}>
            <Route path="/settings" element={<SettingsModal />} />
            <Route path="/pixel/settings" element={<PixelSettings />} />
            <Route path="/extensions/integrations" element={<Navigate to="/settings?section=integrations" replace />} />
            <Route path="/remote-provider" element={<Navigate to="/settings?section=remote" replace />} />
            {routes.filter(route => !['/', '/pixel', '/pixel/settings', '/settings', '/extensions/integrations', '/remote-provider'].includes(route.path)).map(route => {
              const Component = route.component
              const props = typeof route.getProps === 'function' ? route.getProps({ status, loading }) : {}
              return (
                <Route
                  key={route.id || route.path}
                  path={route.path}
                  element={<Component {...props} compact />}
                />
              )
            })}
          </Routes>
        </Suspense>
          </div>
        </aside>}
      </main>

      {/* Smart PWA install nudge — only renders when the user has shown
          enough engagement (3+ visits) AND the browser is willing to
          install. No-op on already-installed PWAs and on browsers that
          can't install (e.g. Firefox desktop). See usePwaInstallPrompt. */}
      <InstallPromptBanner />
    </div>
    </PortalIdentityProvider>
  )
}

function BootstrapBanner({ bootstrap }) {
  const phaseCopy = {
    starting: { title: 'Preparing Full Model', action: 'is being prepared', detail: 'Preparing the full model download…' },
    downloading: { title: 'Downloading Full Model', action: 'is downloading' },
    verifying: { title: 'Verifying Full Model', action: 'is being checked', detail: 'Checking the downloaded model before activation…' },
    swapping: { title: 'Activating Full Model', action: 'is starting', detail: 'Switching chat to the full model…' },
  }
  const phase = phaseCopy[bootstrap.phase] ? bootstrap.phase : 'downloading'
  const copy = phaseCopy[phase]
  const downloadComplete = phase === 'verifying' || phase === 'swapping'
  // bootstrap-upgrade.sh writes bytesTotal 0 when the server sends no
  // Content-Length, and /api/status reports that unknown percent as 0.
  const unknownTotal = phase === 'downloading'
    && !(Number.isFinite(bootstrap.bytesTotal) && bootstrap.bytesTotal > 0)
  const formatEta = (seconds) => {
    if (!seconds || seconds <= 0) return 'calculating...'
    if (seconds < 60) return `${seconds}s`
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
    const hours = Math.floor(seconds / 3600)
    const mins = Math.floor((seconds % 3600) / 60)
    return `${hours}h ${mins}m`
  }

  const formatBytes = (bytes) => {
    if (!bytes) return '0'
    return (bytes / 1e9).toFixed(1)
  }

  return (
    <div className="border-b border-theme-border p-4" style={{ background: `linear-gradient(to right, var(--theme-gradient-from), var(--theme-gradient-to))` }}>
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="w-3 h-3 bg-theme-accent rounded-full animate-pulse" />
            <div>
              <h3 className="text-sm font-semibold text-white">{copy.title}</h3>
              <p className="text-xs text-theme-text-secondary">
                {phase === 'swapping' ? 'Chat pauses during activation' : 'Chat now with lightweight model'} • <span className="text-theme-accent-light">{bootstrap.model}</span> {copy.action}
              </p>
            </div>
          </div>
          <div className="text-right">
            {unknownTotal ? (
              <Loader2 size={20} role="progressbar" aria-label="Full model download progress"
                className="ml-auto text-theme-accent motion-safe:animate-spin" />
            ) : (
              <span className="text-xl font-bold text-theme-accent">
                {downloadComplete ? 'Download 100%' : phase === 'starting' ? 'Preparing' : `${bootstrap.percent?.toFixed(1) || 0}%`}
              </span>
            )}
            {phase === 'downloading' && bootstrap.speedMbps && (
              <p className="text-xs text-theme-text-muted">{bootstrap.speedMbps.toFixed(1)} MB/s</p>
            )}
          </div>
        </div>
        {!unknownTotal && (
          <div role="progressbar" aria-label="Full model download progress"
            aria-valuenow={downloadComplete ? 100 : phase === 'starting' ? 0 : bootstrap.percent || 0}
            className="h-2 bg-theme-border rounded-full overflow-hidden">
            <div
              className="h-full bg-theme-accent rounded-full transition-all duration-500"
              style={{ width: `${downloadComplete ? 100 : phase === 'starting' ? 0 : bootstrap.percent || 0}%` }}
            />
          </div>
        )}
        {unknownTotal ? (
          <p className="text-xs text-theme-text-muted mt-2">
            {bootstrap.bytesDownloaded > 0
              ? `${formatBytes(bootstrap.bytesDownloaded)} GB downloaded · Total size unavailable`
              : 'Progress unavailable'}
          </p>
        ) : phase === 'downloading' ? (
          <p className="text-xs text-theme-text-muted mt-2">
            ETA: {formatEta(bootstrap.eta)} • {formatBytes(bootstrap.bytesDownloaded)} / {formatBytes(bootstrap.bytesTotal)} GB
          </p>
        ) : <p className="text-xs text-theme-text-muted mt-2">{copy.detail}</p>}
      </div>
    </div>
  )
}

export default App