The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat: remove local AI onboarding and download snackbar
Steven Enamakel1609b34248dd
diff --git a/app/src/components/AppUpdatePrompt.tsx b/app/src/components/AppUpdatePrompt.tsxindex 5af0697bfd..a0a31ca57f 100644--- a/app/src/components/AppUpdatePrompt.tsx+++ b/app/src/components/AppUpdatePrompt.tsx@@ -18,7 +18,7 @@ import { createPortal } from 'react-dom';import { useAppUpdate } from '../hooks/useAppUpdate';import { useT } from '../lib/i18n/I18nContext';-import { formatBytes } from '../utils/localAiHelpers';+import { formatBytes } from '../utils/format';import Button from './ui/Button';interface AppUpdatePromptProps {diff --git a/app/src/components/LocalAIDownloadSnackbar.tsx b/app/src/components/LocalAIDownloadSnackbar.tsxdeleted file mode 100644index 5d4e7fd117..0000000000--- a/app/src/components/LocalAIDownloadSnackbar.tsx+++ /dev/null@@ -1,284 +0,0 @@-import debugFactory from 'debug';-import { useCallback, useEffect, useRef, useState } from 'react';-import { createPortal } from 'react-dom';--import { useT } from '../lib/i18n/I18nContext';-import { useCoreState } from '../providers/CoreStateProvider';-import {- formatBytes,- formatEta,- progressFromDownloads,- progressFromStatus,- statusLabel,-} from '../utils/localAiHelpers';-import {- type LocalAiDownloadsProgress,- type LocalAiStatus,- openhumanLocalAiDownloadsProgress,- openhumanLocalAiStatus,-} from '../utils/tauriCommands';-import Button from './ui/Button';--const log = debugFactory('local-ai-download');--const ACTIVE_POLL_INTERVAL = 2000;--const IN_FLIGHT_STATES = new Set(['loading', 'downloading', 'installing']);--/** Whether a `LocalAiStatus.state` string denotes an active download/bootstrap. */-const isInFlightState = (state: string | undefined): boolean =>- state != null && IN_FLIGHT_STATES.has(state);--/**- * Pure predicate deciding whether a download/bootstrap is currently in flight,- * mirroring the `isDownloading` derivation used for rendering. Drives the fast- * poll's continuation: keep polling `inference_downloads_progress` +- * `inference_status` only while a download is genuinely in flight.- */-const isDownloadInFlight = (- status: LocalAiStatus | null,- downloads: LocalAiDownloadsProgress | null-): boolean => {- const downloadState = downloads?.state;- const currentState = isInFlightState(downloadState)- ? downloadState- : (status?.state ?? downloadState ?? 'idle');- return (- isInFlightState(currentState) ||- (downloads?.progress != null && downloads.progress > 0 && downloads.progress < 1)- );-};--/**- * Persistent snackbar that shows local AI download progress.- * Anchored bottom-right.- * Dismiss hides the UI but does NOT cancel the download.- */-const LocalAIDownloadSnackbar = () => {- const { t } = useT();- const [status, setStatus] = useState<LocalAiStatus | null>(null);- const [downloads, setDownloads] = useState<LocalAiDownloadsProgress | null>(null);- const [dismissed, setDismissed] = useState(false);- const [collapsed, setCollapsed] = useState(false);- const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);- // Track previous isDownloading in state so we can reset the dismiss flag on a- // not-downloading → downloading transition during render (render-phase update,- // the officially recommended React pattern for adjusting state on derived-value changes).- const [prevIsDownloading, setPrevIsDownloading] = useState(false);-- // Detect an active download from the folded local-AI state in the app-state- // snapshot (polled by CoreStateProvider) instead of a dedicated idle poll of- // the inference RPCs. When idle this component issues ZERO inference calls;- // the snapshot's `runtime.localAi.state` is what flips us into the fast poll.- const { snapshot: coreSnapshot } = useCoreState();- const coreDownloadActive = isInFlightState(coreSnapshot.runtime.localAi?.state ?? undefined);-- // While a download is in flight, poll the inference RPCs fast for smooth,- // granular progress/speed/ETA (the 2–5s app-state cadence is too coarse and- // carries no downloads-progress detail). The poll starts when core state- // reports activity and keeps going as long as the download itself is in- // flight, then stops — so there is no steady-state inference polling.- useEffect(() => {- if (!coreDownloadActive) return;-- let cancelled = false;- log('fast poll: starting (core reports download active)');-- const poll = async () => {- let settled = false;- try {- const [statusRes, downloadsRes] = await Promise.all([- openhumanLocalAiStatus(),- openhumanLocalAiDownloadsProgress(),- ]);- if (statusRes.result) setStatus(statusRes.result);- if (downloadsRes.result) setDownloads(downloadsRes.result);- // The download reached a terminal state — stop the fast poll early- // rather than waiting for core state to catch up (it lags up to ~5s).- // A successful response that carries no `result` (a soft failure, not a- // thrown error) must be treated as transient, not as "download- // complete" — otherwise one empty blip would permanently freeze the- // fast poll for the rest of the download (same failure mode the catch- // below guards against for thrown errors).- if (statusRes.result || downloadsRes.result) {- settled = !isDownloadInFlight(statusRes.result ?? null, downloadsRes.result ?? null);- }- } catch (err) {- // Transient RPC failure (core may be busy). Do NOT treat this as- // settled: keep polling while core state still reports the download- // active, otherwise one blip would permanently stop progress updates- // for the rest of the download (the effect won't re-run until- // `coreDownloadActive` flips).- log('fast poll: transient error, will retry: %O', err);- }- if (!cancelled && !settled) {- timerRef.current = setTimeout(poll, ACTIVE_POLL_INTERVAL);- } else if (settled) {- log('fast poll: download settled, stopping');- }- };-- void poll();- return () => {- cancelled = true;- if (timerRef.current) clearTimeout(timerRef.current);- log('fast poll: stopped (unmount or core reports inactive)');- };- }, [coreDownloadActive]);-- const downloadState = downloads?.state;- const currentState =- downloadState === 'loading' || downloadState === 'downloading' || downloadState === 'installing'- ? downloadState- : (status?.state ?? downloadState ?? 'idle');- // Gate on `coreDownloadActive` so a download that the core no longer reports- // active can't leave the snackbar stuck: when the folded state flips inactive,- // polling stops and any still-"downloading" local status/downloads must not- // keep the overlay visible.- const isDownloading =- coreDownloadActive &&- (currentState === 'loading' ||- currentState === 'downloading' ||- currentState === 'installing' ||- (downloads?.progress != null && downloads.progress > 0 && downloads.progress < 1));-- // Render-phase update: when a new download cycle starts (not-downloading → downloading),- // reset the dismiss/collapsed flags so the snackbar reappears automatically.- if (!!isDownloading !== prevIsDownloading) {- setPrevIsDownloading(!!isDownloading);- if (isDownloading && !prevIsDownloading) {- setDismissed(false);- setCollapsed(false);- }- }-- const handleDismiss = useCallback(() => setDismissed(true), []);- const handleToggleCollapse = useCallback(() => setCollapsed(prev => !prev), []);-- if (!isDownloading || dismissed) return null;-- // Use currentState as the source of truth for the fallback sentinel so the- // label (derived from currentState) and the progress bar stay in sync.- // We still forward download_progress from status so a real numeric value- // isn't lost when the downloads object has no progress field.- // When status is absent, progressFromStatus(null) returns 0, which is the- // correct baseline while data hasn't arrived yet.- const statusForProgress: LocalAiStatus | null = status- ? { ...status, state: currentState }- : null;- const progress = progressFromDownloads(downloads) ?? progressFromStatus(statusForProgress);- const percent = progress != null ? Math.round(progress * 100) : null;- const speed = downloads?.speed_bps ?? status?.download_speed_bps;- const eta = downloads?.eta_seconds ?? status?.eta_seconds;- const downloaded = downloads?.downloaded_bytes ?? status?.downloaded_bytes;- const total = downloads?.total_bytes ?? status?.total_bytes;- const label = statusLabel(currentState);- const isInstallingPhase = currentState === 'installing';- const phaseDetail = downloads?.warning ?? status?.warning;-- // Collapsed: small pill- if (collapsed) {- return createPortal(- <div className="fixed bottom-14 right-2 z-9998 animate-fade-up">- <button- onClick={handleToggleCollapse}- className="flex items-center gap-2 bg-stone-900 border border-stone-700/50 rounded-full px-3 py-2 shadow-large hover:border-stone-600 transition-colors"- aria-label={t('app.localAiDownload.expandAria')}>- <svg- className="w-4 h-4 text-primary-400 animate-pulse"- viewBox="0 0 20 20"- fill="currentColor">- <path d="M10.75 2.75a.75.75 0 00-1.5 0v8.614L6.295 8.235a.75.75 0 10-1.09 1.03l4.25 4.5a.75.75 0 001.09 0l4.25-4.5a.75.75 0 00-1.09-1.03l-2.955 3.129V2.75z" />- <path d="M3.5 12.75a.75.75 0 00-1.5 0v2.5A2.75 2.75 0 004.75 18h10.5A2.75 2.75 0 0018 15.25v-2.5a.75.75 0 00-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5z" />- </svg>- <span className="text-xs font-medium text-content-faint">- {percent != null ? `${percent}%` : label}- </span>- </button>- </div>,- document.body- );- }-- // Expanded: full snackbar- return createPortal(- <div className="fixed bottom-14 right-2 z-9998 w-[320px] animate-fade-up">- <div className="bg-stone-900 border border-stone-700/50 rounded-2xl shadow-large overflow-hidden">- {/* Header */}- <div className="flex items-center justify-between px-4 pt-3 pb-1">- <div className="flex items-center gap-2">- <svg- className="w-4 h-4 text-primary-400 animate-pulse"- viewBox="0 0 20 20"- fill="currentColor">- <path d="M10.75 2.75a.75.75 0 00-1.5 0v8.614L6.295 8.235a.75.75 0 10-1.09 1.03l4.25 4.5a.75.75 0 001.09 0l4.25-4.5a.75.75 0 00-1.09-1.03l-2.955 3.129V2.75z" />- <path d="M3.5 12.75a.75.75 0 00-1.5 0v2.5A2.75 2.75 0 004.75 18h10.5A2.75 2.75 0 0018 15.25v-2.5a.75.75 0 00-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5z" />- </svg>- <span className="text-sm font-medium text-white">{label}</span>- </div>- <div className="flex items-center gap-1">- <Button- iconOnly- variant="tertiary"- size="xs"- onClick={handleToggleCollapse}- aria-label={t('app.localAiDownload.collapseAria')}>- <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="currentColor">- <path d="M3.75 7.25a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5z" />- </svg>- </Button>- <Button- iconOnly- variant="tertiary"- size="xs"- onClick={handleDismiss}- aria-label={t('app.localAiDownload.dismissAria')}>- <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="currentColor">- <path d="M4.28 3.22a.75.75 0 00-1.06 1.06L6.94 8l-3.72 3.72a.75.75 0 101.06 1.06L8 9.06l3.72 3.72a.75.75 0 101.06-1.06L9.06 8l3.72-3.72a.75.75 0 00-1.06-1.06L8 6.94 4.28 3.22z" />- </svg>- </Button>- </div>- </div>-- {/* Phase detail */}- {phaseDetail && (- <div className="px-4 pb-1">- <span className="text-[11px] text-content-faint truncate block">{phaseDetail}</span>- </div>- )}-- {/* Progress bar */}- <div className="px-4 py-2">- <div className="h-1.5 w-full rounded-full bg-stone-800 overflow-hidden">- <div- className={`h-full rounded-full bg-linear-to-r from-primary-500 to-primary-400 transition-all duration-500 ${- isInstallingPhase ? 'animate-pulse' : ''- }`}- style={{ width: isInstallingPhase ? '100%' : `${percent ?? 0}%` }}- />- </div>- </div>-- {/* Details */}- <div className="flex items-center justify-between px-4 pb-3 text-xs text-content-faint">- <span>- {isInstallingPhase- ? t('app.localAiDownload.installing')- : downloaded != null && total != null- ? `${formatBytes(downloaded)} / ${formatBytes(total)}`- : percent != null- ? `${percent}%`- : t('app.localAiDownload.preparing')}- </span>- <span>- {speed != null && speed > 0 ? `${formatBytes(speed)}/s` : ''}- {eta != null && eta > 0 ? ` · ${formatEta(eta)}` : ''}- </span>- </div>- </div>- </div>,- document.body- );-};--export default LocalAIDownloadSnackbar;diff --git a/app/src/components/__tests__/LocalAIDownloadSnackbar.test.tsx b/app/src/components/__tests__/LocalAIDownloadSnackbar.test.tsxdeleted file mode 100644index 1904cf565a..0000000000--- a/app/src/components/__tests__/LocalAIDownloadSnackbar.test.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';--import { getCoreStateSnapshot, setCoreStateSnapshot } from '../../lib/coreState/store';-import { renderWithProviders } from '../../test/test-utils';-import LocalAIDownloadSnackbar from '../LocalAIDownloadSnackbar';--// Default: isTauri returns false, so snackbar should not render-vi.mock('../../utils/tauriCommands', () => ({- isTauri: vi.fn(() => false),- openhumanLocalAiStatus: vi.fn().mockResolvedValue({ result: null }),- openhumanLocalAiDownloadsProgress: vi.fn().mockResolvedValue({ result: null }),-}));--/**- * Seed the folded `runtime.localAi.state` in core state. The snackbar reads this- * (instead of an idle inference poll) to decide whether to run its fast poll, so- * tests that expect it to poll must mark a download active here first.- */-function seedLocalAiState(state: string | null): void {- const current = getCoreStateSnapshot();- setCoreStateSnapshot({- ...current,- snapshot: {- ...current.snapshot,- runtime: {- ...current.snapshot.runtime,- localAi: state === null ? null : ({ state } as never),- },- },- });-}--afterEach(() => {- seedLocalAiState(null);-});--describe('LocalAIDownloadSnackbar', () => {- it('does not render when not in Tauri environment', () => {- renderWithProviders(<LocalAIDownloadSnackbar />);-- expect(screen.queryByText('Downloading')).not.toBeInTheDocument();- expect(screen.queryByLabelText('Dismiss download notification')).not.toBeInTheDocument();- });-- it('does not poll or render when core state reports no active download', async () => {- const tauriCommands = await import('../../utils/tauriCommands');- vi.mocked(tauriCommands.isTauri).mockReturnValue(true);- vi.mocked(tauriCommands.openhumanLocalAiStatus).mockClear();- vi.mocked(tauriCommands.openhumanLocalAiDownloadsProgress).mockClear();- seedLocalAiState('ready');-- renderWithProviders(<LocalAIDownloadSnackbar />);-- await vi.waitFor(() => {- expect(screen.queryByText('Downloading')).not.toBeInTheDocument();- });- // Idle → zero inference polls (the fold's whole point).- expect(tauriCommands.openhumanLocalAiStatus).not.toHaveBeenCalled();- expect(tauriCommands.openhumanLocalAiDownloadsProgress).not.toHaveBeenCalled();-- vi.mocked(tauriCommands.isTauri).mockReturnValue(false);- });-- it('polls and renders when core state reports an active download', async () => {- const tauriCommands = await import('../../utils/tauriCommands');- vi.mocked(tauriCommands.isTauri).mockReturnValue(true);- vi.mocked(tauriCommands.openhumanLocalAiStatus).mockResolvedValue({- result: {- state: 'loading',- download_progress: 0.42,- downloaded_bytes: 512 * 1024 * 1024,- total_bytes: 1024 * 1024 * 1024,- warning: 'Connecting to local Ollama runtime',- } as never,- logs: [],- });- vi.mocked(tauriCommands.openhumanLocalAiDownloadsProgress).mockResolvedValue({- result: { state: 'idle', progress: null } as never,- logs: [],- });- seedLocalAiState('loading');-- renderWithProviders(<LocalAIDownloadSnackbar />);-- await vi.waitFor(() => {- expect(screen.getByText('Loading model...')).toBeInTheDocument();- expect(screen.getByText('512 MB / 1.0 GB')).toBeInTheDocument();- });-- vi.mocked(tauriCommands.isTauri).mockReturnValue(false);- });-});diff --git a/app/src/pages/onboarding/steps/LocalAIStep.tsx b/app/src/pages/onboarding/steps/LocalAIStep.tsxdeleted file mode 100644index 4f94fc9012..0000000000--- a/app/src/pages/onboarding/steps/LocalAIStep.tsx+++ /dev/null@@ -1,179 +0,0 @@-import { useCallback, useEffect, useRef, useState } from 'react';--import Button from '../../../components/ui/Button';-import { useT } from '../../../lib/i18n/I18nContext';-import { bootstrapLocalAiWithRecommendedPreset } from '../../../utils/localAiBootstrap';-import { openhumanLocalAiPresets } from '../../../utils/tauriCommands';-import OnboardingNextButton from '../components/OnboardingNextButton';--/* ---------- component ---------- */--interface LocalAIStepProps {- onNext: (result: { consentGiven: boolean; downloadStarted: boolean }) => void;- onBack?: () => void;- onDownloadError?: (message: string) => void;-}--const LocalAIStep = ({ onNext, onBack: _onBack, onDownloadError }: LocalAIStepProps) => {- const { t } = useT();- const downloadStartedRef = useRef(false);- const [recommendDisabled, setRecommendDisabled] = useState<boolean | null>(null);-- useEffect(() => {- let cancelled = false;- // Read-only probe: never apply/persist a preset from the mount effect.- // Preset application lives in handleConsent via bootstrapLocalAiWithRecommendedPreset.- openhumanLocalAiPresets()- .then(presets => {- if (!cancelled) {- setRecommendDisabled(presets.recommend_disabled ?? false);- }- })- .catch(() => {- if (!cancelled) setRecommendDisabled(false);- });- return () => {- cancelled = true;- };- }, []);-- const handleConsent = useCallback(() => {- if (downloadStartedRef.current) return;- downloadStartedRef.current = true;- console.debug('[LocalAIStep] starting background Local AI bootstrap after consent');-- // Fire-and-forget: start bootstrap in the background — the global snackbar tracks progress.- void bootstrapLocalAiWithRecommendedPreset(false, '[LocalAIStep]').catch((err: unknown) => {- console.warn('[LocalAIStep] Local AI bootstrap failed:', err);- onDownloadError?.(t('onboarding.localAI.setupIssue'));- });-- // Advance to next step immediately- onNext({ consentGiven: true, downloadStarted: true });- }, [onNext, onDownloadError, t]);-- const handleSkip = useCallback(() => {- console.debug('[LocalAIStep] skipping local AI — using cloud fallback');- onNext({ consentGiven: false, downloadStarted: false });- }, [onNext]);-- // Still probing device — show nothing yet.- if (recommendDisabled === null) {- return null;- }-- // Low-RAM device: show cloud fallback option as the primary path.- if (recommendDisabled) {- return (- <div className="rounded-2xl border border-line bg-surface p-8 shadow-soft animate-fade-up">- <div className="flex flex-col items-center mb-5">- <div className="flex h-16 w-16 items-center justify-center rounded-full bg-primary-50 dark:bg-primary-500/15 mb-3">- <svg- className="h-8 w-8 text-primary-500"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- strokeWidth={1.5}>- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M2.25 15a4.5 4.5 0 004.5 4.5H18a3.75 3.75 0 001.332-7.257 3 3 0 00-3.758-3.848 5.25 5.25 0 00-10.233 2.33A4.502 4.502 0 002.25 15z"- />- </svg>- </div>- <h1 className="text-xl font-bold mb-2 text-content">{t('onboarding.localAI')}</h1>- <p className="text-content-secondary text-sm text-center">- {t('onboarding.localAIDesc')}- </p>- </div>-- <div className="space-y-2 mb-5">- <div className="rounded-xl border border-primary-200 dark:border-primary-500/30 bg-primary-50 dark:bg-primary-500/15 px-3 py-2">- <p className="text-xs text-content-secondary">- <span className="font-semibold">{t('onboarding.localAI')}</span>- <span className="text-content-secondary"> — {t('onboarding.localAIDesc')}</span>- </p>- </div>- <div className="rounded-xl border border-line bg-surface-muted px-3 py-2">- <p className="text-xs text-content-secondary">- <span className="font-semibold">{t('common.download')}</span>- <span className="text-content-secondary"> — {t('misc.downloading')}</span>- </p>- </div>- <div className="rounded-xl border border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-3 py-2">- <p className="text-xs text-content-secondary">- <span className="font-semibold">{t('welcome.connect')}</span>- <span className="text-content-secondary"> — {t('onboarding.localAIDesc')}</span>- </p>- </div>- </div>-- <OnboardingNextButton- label={t('onboarding.localAI.continueWithCloud')}- onClick={handleSkip}- />-- <Button variant="tertiary" size="xs" onClick={handleConsent} className="mt-3 w-full">- {t('onboarding.localAI.useLocalAnyway')}- </Button>- </div>- );- }-- // Sufficient RAM: local AI is opt-in. Present cloud as the primary path and- // local AI as an explicit choice for users who want full privacy.- return (- <div className="rounded-2xl border border-line bg-surface p-8 shadow-soft animate-fade-up">- <div className="flex flex-col items-center mb-5">- <div className="flex h-16 w-16 items-center justify-center rounded-full bg-primary-50 dark:bg-primary-500/15 mb-3">- <svg- className="h-8 w-8 text-primary-500"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- strokeWidth={1.5}>- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M2.25 15a4.5 4.5 0 004.5 4.5H18a3.75 3.75 0 001.332-7.257 3 3 0 00-3.758-3.848 5.25 5.25 0 00-10.233 2.33A4.502 4.502 0 002.25 15z"- />- </svg>- </div>- <h1 className="text-xl font-bold mb-2 text-content">{t('onboarding.localAI')}</h1>- <p className="text-content-secondary text-sm text-center">{t('onboarding.localAIDesc')}</p>- </div>-- <div className="space-y-2 mb-5">- <div className="rounded-xl border border-primary-200 dark:border-primary-500/30 bg-primary-50 dark:bg-primary-500/15 px-3 py-2">- <p className="text-xs text-content-secondary">- <span className="font-semibold">{t('onboarding.localAI')}</span>- <span className="text-content-secondary"> — {t('onboarding.localAIDesc')}</span>- </p>- </div>- <div className="rounded-xl border border-line bg-surface-muted px-3 py-2">- <p className="text-xs text-content-secondary">- <span className="font-semibold">{t('onboarding.localAI')}</span>- <span className="text-content-secondary"> — {t('onboarding.localAIDesc')}</span>- </p>- </div>- <div className="rounded-xl border border-line bg-surface-muted px-3 py-2">- <p className="text-xs text-content-secondary">- <span className="font-semibold">{t('common.refresh')}</span>- <span className="text-content-secondary"> — {t('onboarding.localAIDesc')}</span>- </p>- </div>- </div>-- <OnboardingNextButton- label={t('onboarding.localAI.continueWithCloud')}- onClick={handleSkip}- />-- <Button variant="tertiary" size="xs" onClick={handleConsent} className="mt-3 w-full">- {t('onboarding.localAI.useLocalInstead')}- </Button>- </div>- );-};--export default LocalAIStep;diff --git a/app/src/pages/onboarding/steps/__tests__/LocalAIStep.test.tsx b/app/src/pages/onboarding/steps/__tests__/LocalAIStep.test.tsxdeleted file mode 100644index 1641c4184e..0000000000--- a/app/src/pages/onboarding/steps/__tests__/LocalAIStep.test.tsx+++ /dev/null@@ -1,167 +0,0 @@-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { renderWithProviders } from '../../../../test/test-utils';-import LocalAIStep from '../LocalAIStep';--vi.mock('../../../../utils/localAiBootstrap', () => ({- bootstrapLocalAiWithRecommendedPreset: vi.fn().mockResolvedValue({} as never),-}));--vi.mock('../../../../utils/tauriCommands', () => ({- openhumanLocalAiPresets: vi- .fn()- .mockResolvedValue({- recommend_disabled: false,- presets: [],- recommended_tier: 'ram_2_4gb',- current_tier: 'ram_2_4gb',- selected_tier: null,- device: {- total_ram_bytes: 16 * 1024 * 1024 * 1024,- cpu_count: 8,- cpu_brand: 'test',- os_name: 'test',- os_version: '1.0',- has_gpu: false,- gpu_description: null,- },- } as never),-}));--describe('LocalAIStep', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('happy path (sufficient RAM): defaults to cloud, no local AI bootstrap', async () => {- const { bootstrapLocalAiWithRecommendedPreset } =- await import('../../../../utils/localAiBootstrap');-- const onNext = vi.fn();- renderWithProviders(<LocalAIStep onNext={onNext} />);-- const cloudButton = await screen.findByRole('button', { name: /continue with cloud/i });- fireEvent.click(cloudButton);-- expect(onNext).toHaveBeenCalledOnce();- expect(onNext).toHaveBeenCalledWith({ consentGiven: false, downloadStarted: false });- expect(bootstrapLocalAiWithRecommendedPreset).not.toHaveBeenCalled();- });-- it('opt-in (sufficient RAM): starts local AI bootstrap when user chooses local AI', async () => {- const { bootstrapLocalAiWithRecommendedPreset } =- await import('../../../../utils/localAiBootstrap');-- const onNext = vi.fn();- renderWithProviders(<LocalAIStep onNext={onNext} />);-- const optInButton = await screen.findByRole('button', { name: /use local ai instead/i });- fireEvent.click(optInButton);-- expect(onNext).toHaveBeenCalledOnce();- expect(onNext).toHaveBeenCalledWith({ consentGiven: true, downloadStarted: true });- expect(bootstrapLocalAiWithRecommendedPreset).toHaveBeenCalledOnce();- expect(bootstrapLocalAiWithRecommendedPreset).toHaveBeenCalledWith(false, '[LocalAIStep]');- });-- it('error path: calls onDownloadError once when opt-in bootstrap fails', async () => {- const { bootstrapLocalAiWithRecommendedPreset } =- await import('../../../../utils/localAiBootstrap');- vi.mocked(bootstrapLocalAiWithRecommendedPreset).mockRejectedValueOnce(- new Error('network error')- );-- const onNext = vi.fn();- const onDownloadError = vi.fn();- renderWithProviders(<LocalAIStep onNext={onNext} onDownloadError={onDownloadError} />);-- const optInButton = await screen.findByRole('button', { name: /use local ai instead/i });- fireEvent.click(optInButton);-- // onNext still fires immediately- expect(onNext).toHaveBeenCalledOnce();-- // onDownloadError fires asynchronously after the rejected promise settles- await waitFor(() => {- expect(onDownloadError).toHaveBeenCalledOnce();- });- expect(onDownloadError).toHaveBeenCalledWith('Local AI setup encountered an issue');- });-- it('double-click guard (opt-in): bootstrap runs only once', async () => {- const { bootstrapLocalAiWithRecommendedPreset } =- await import('../../../../utils/localAiBootstrap');- vi.mocked(bootstrapLocalAiWithRecommendedPreset).mockResolvedValue({} as never);-- const onNext = vi.fn();- renderWithProviders(<LocalAIStep onNext={onNext} />);-- const optInButton = await screen.findByRole('button', { name: /use local ai instead/i });- fireEvent.click(optInButton);- fireEvent.click(optInButton);-- expect(onNext).toHaveBeenCalledOnce();- expect(bootstrapLocalAiWithRecommendedPreset).toHaveBeenCalledOnce();- });-- it('shows cloud fallback UI when device is below RAM floor', async () => {- const { openhumanLocalAiPresets } = await import('../../../../utils/tauriCommands');- vi.mocked(openhumanLocalAiPresets).mockResolvedValue({- recommend_disabled: true,- presets: [],- recommended_tier: 'ram_2_4gb',- current_tier: 'ram_2_4gb',- selected_tier: null,- device: {- total_ram_bytes: 4 * 1024 * 1024 * 1024,- cpu_count: 4,- cpu_brand: 'test',- os_name: 'test',- os_version: '1.0',- has_gpu: false,- gpu_description: null,- },- } as never);-- const onNext = vi.fn();- renderWithProviders(<LocalAIStep onNext={onNext} />);-- const cloudButton = await screen.findByRole('button', { name: /continue with cloud/i });- expect(cloudButton).toBeTruthy();-- fireEvent.click(cloudButton);- expect(onNext).toHaveBeenCalledWith({ consentGiven: false, downloadStarted: false });- });-- it('allows force-enabling local AI on low-RAM device', async () => {- const { openhumanLocalAiPresets } = await import('../../../../utils/tauriCommands');- const { bootstrapLocalAiWithRecommendedPreset } =- await import('../../../../utils/localAiBootstrap');- vi.mocked(openhumanLocalAiPresets).mockResolvedValue({- recommend_disabled: true,- presets: [],- recommended_tier: 'ram_2_4gb',- current_tier: 'ram_2_4gb',- selected_tier: null,- device: {- total_ram_bytes: 4 * 1024 * 1024 * 1024,- cpu_count: 4,- cpu_brand: 'test',- os_name: 'test',- os_version: '1.0',- has_gpu: false,- gpu_description: null,- },- } as never);-- const onNext = vi.fn();- renderWithProviders(<LocalAIStep onNext={onNext} />);-- const forceButton = await screen.findByRole('button', { name: /use local ai anyway/i });- fireEvent.click(forceButton);-- expect(onNext).toHaveBeenCalledWith({ consentGiven: true, downloadStarted: true });- expect(bootstrapLocalAiWithRecommendedPreset).toHaveBeenCalledOnce();- });-});diff --git a/app/src/utils/__tests__/localAiBootstrap.test.ts b/app/src/utils/__tests__/localAiBootstrap.test.tsdeleted file mode 100644index a89e774b4a..0000000000--- a/app/src/utils/__tests__/localAiBootstrap.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import {- bootstrapLocalAiWithRecommendedPreset,- ensureRecommendedLocalAiPresetIfNeeded,-} from '../localAiBootstrap';--vi.mock('../tauriCommands', () => ({- openhumanLocalAiApplyPreset: vi.fn(),- openhumanLocalAiPresets: vi.fn(),-}));--describe('localAiBootstrap', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('applies the recommended preset when no tier is selected', async () => {- const tauriCommands = await import('../tauriCommands');- vi.mocked(tauriCommands.openhumanLocalAiPresets).mockResolvedValue({- presets: [],- recommended_tier: 'ram_2_4gb',- current_tier: 'ram_2_4gb',- selected_tier: null,- device: {- total_ram_bytes: 32 * 1024 * 1024 * 1024,- cpu_count: 8,- cpu_brand: 'Test CPU',- os_name: 'macOS',- os_version: '15',- has_gpu: true,- gpu_description: 'Test GPU',- },- });- vi.mocked(tauriCommands.openhumanLocalAiApplyPreset).mockResolvedValue({- applied_tier: 'ram_2_4gb',- chat_model_id: 'gemma3:1b-it-qat',- vision_model_id: '',- embedding_model_id: 'all-minilm:latest',- quantization: 'qat',- });- const result = await bootstrapLocalAiWithRecommendedPreset(false, '[test]');-- expect(tauriCommands.openhumanLocalAiPresets).toHaveBeenCalledOnce();- expect(tauriCommands.openhumanLocalAiApplyPreset).toHaveBeenCalledWith('ram_2_4gb');- expect(result.preset.hadSelectedTier).toBe(false);- expect(result.preset.appliedTier).toBe('ram_2_4gb');- });-- it('skips preset application when a tier is already selected', async () => {- const tauriCommands = await import('../tauriCommands');- vi.mocked(tauriCommands.openhumanLocalAiPresets).mockResolvedValue({- presets: [],- recommended_tier: 'ram_2_4gb',- current_tier: 'ram_2_4gb',- selected_tier: 'ram_2_4gb',- device: {- total_ram_bytes: 32 * 1024 * 1024 * 1024,- cpu_count: 8,- cpu_brand: 'Test CPU',- os_name: 'macOS',- os_version: '15',- has_gpu: true,- gpu_description: 'Test GPU',- },- });-- const result = await ensureRecommendedLocalAiPresetIfNeeded('[test]');-- expect(tauriCommands.openhumanLocalAiApplyPreset).not.toHaveBeenCalled();- expect(result.hadSelectedTier).toBe(true);- expect(result.selectedTier).toBe('ram_2_4gb');- });-});diff --git a/app/src/utils/__tests__/localChatGating.test.ts b/app/src/utils/__tests__/localChatGating.test.tsdeleted file mode 100644index 76b22679ba..0000000000--- a/app/src/utils/__tests__/localChatGating.test.ts+++ /dev/null@@ -1,85 +0,0 @@-/**- * Tests for local-chat gating logic.- *- * These are pure unit tests — no Tauri / socket I/O involved.- * They verify:- * 1. segmentMessage correctly splits responses into bubbles.- * 2. getSegmentDelay stays within [500, 1400] ms.- * 3. The local-only gate pattern (isLocalModelActive) works- * as intended by checking its value logic directly.- */-import { describe, expect, it } from 'vitest';--import { getSegmentDelay, segmentMessage } from '../messageSegmentation';--const MIN_DELAY = 500;-const MAX_DELAY = 1400;--describe('local chat gating — segmentation', () => {- it('short reply is a single bubble', () => {- const reply = 'Sure thing!';- expect(segmentMessage(reply)).toEqual([reply]);- });-- it('long reply with paragraph breaks splits into multiple bubbles', () => {- const reply = [- 'First paragraph with enough content to pass the minimum length check.',- 'Second paragraph also has enough content to be its own bubble in the UI.',- ].join('\n\n');- const segments = segmentMessage(reply);- expect(segments.length).toBeGreaterThanOrEqual(2);- expect(segments.length).toBeLessThanOrEqual(5);- });-- it('each segment meets minimum length threshold', () => {- const reply = [- 'This is the first segment that is long enough to stand on its own.',- 'This is the second segment that is also long enough to be shown.',- 'And a third one here.',- ].join('\n\n');- const segments = segmentMessage(reply);- for (const seg of segments) {- expect(seg.length).toBeGreaterThan(0);- }- });-- it('never returns more than 5 segments', () => {- const reply = Array.from(- { length: 10 },- (_, i) => `Paragraph number ${i + 1} has enough words to be a proper segment here.`- ).join('\n\n');- const segments = segmentMessage(reply);- expect(segments.length).toBeLessThanOrEqual(5);- });-});--describe('local chat gating — delivery delays', () => {- it('delay is at least MIN_DELAY for any segment', () => {- expect(getSegmentDelay('')).toBeGreaterThanOrEqual(MIN_DELAY);- expect(getSegmentDelay('x')).toBeGreaterThanOrEqual(MIN_DELAY);- });-- it('delay is capped at MAX_DELAY', () => {- expect(getSegmentDelay('a'.repeat(10_000))).toBeLessThanOrEqual(MAX_DELAY);- });-- it('delay increases with segment length', () => {- const d1 = getSegmentDelay('short');- const d2 = getSegmentDelay('a'.repeat(300));- expect(d2).toBeGreaterThanOrEqual(d1);- });-});--describe('local chat gating — message role mapping', () => {- it('maps sender user → role user', () => {- const sender = 'user';- const role = sender === 'user' ? 'user' : 'assistant';- expect(role).toBe('user');- });-- it('maps sender agent → role assistant', () => {- const sender: string = 'agent';- const role = sender === 'user' ? 'user' : 'assistant';- expect(role).toBe('assistant');- });-});diff --git a/app/src/utils/__tests__/messageSegmentation.test.ts b/app/src/utils/__tests__/messageSegmentation.test.tsdeleted file mode 100644index 5f9ae92d75..0000000000--- a/app/src/utils/__tests__/messageSegmentation.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { describe, expect, it } from 'vitest';--import { getSegmentDelay, segmentMessage } from '../messageSegmentation';--describe('segmentMessage', () => {- it('returns the original text as a single segment when text is short', () => {- const short = 'Hello there!';- expect(segmentMessage(short)).toEqual([short]);- });-- it('returns single segment for text under 80 chars', () => {- const text = 'This is a sentence that is almost long enough but not quite yet for splitting.';- expect(segmentMessage(text)).toHaveLength(1);- });-- it('splits on paragraph breaks', () => {- const text =- 'First paragraph with enough content to be meaningful and readable.\n\n' +- 'Second paragraph that also has meaningful content and is not too short.';- const segments = segmentMessage(text);- expect(segments.length).toBeGreaterThanOrEqual(2);- expect(segments[0]).toContain('First paragraph');- expect(segments[1]).toContain('Second paragraph');- });-- it('merges short paragraphs with the previous one', () => {- const text =- 'First paragraph with enough content to stand alone as a meaningful segment.\n\n' +- 'Short.\n\n' +- 'Third paragraph with enough content to be a standalone bubble in delivery.';- const segments = segmentMessage(text);- // "Short." should be merged with first or third- expect(segments.every(s => s.length >= 40)).toBe(true);- });-- it('merges a short first paragraph into the second paragraph', () => {- const text =- 'Ok.\n\n' +- 'This second paragraph is intentionally long enough to stand alone after merging.';- const segments = segmentMessage(text);-- expect(segments.length).toBe(1);- expect(segments[0].startsWith('Ok.\n\n')).toBe(true);- expect(segments[0].length).toBeGreaterThanOrEqual(40);- });-- it('forward-merges a short first paragraph yet keeps the remaining bubbles', () => {- // Three paragraphs where only the first is below MIN_SEGMENT_CHARS. This- // exercises the forward-merge branch in mergeTooShort while still returning- // multiple segments from the paragraph-split strategy (no leading stub).- const text =- 'Ok.\n\n' +- 'This second paragraph is intentionally long enough to stand alone as a bubble.\n\n' +- 'And a third paragraph that is also long enough to remain its own standalone bubble.';- const segments = segmentMessage(text);-- expect(segments).toHaveLength(2);- expect(segments[0].startsWith('Ok.\n\n')).toBe(true);- expect(segments.every(s => s.length >= 40)).toBe(true);- });-- it('splits on sentence boundaries when no paragraph breaks exist', () => {- const text =- 'This is the first sentence with some content. This is the second sentence with more content. ' +- 'This is the third sentence that adds even more words. And this is a final wrap-up sentence here.';- const segments = segmentMessage(text);- expect(segments.length).toBeGreaterThanOrEqual(2);- });-- it('never returns more than 5 segments', () => {- const manyParagraphs = Array.from(- { length: 10 },- (_, i) =>- `Paragraph ${i + 1} has enough words and content to be a real standalone bubble message.`- ).join('\n\n');- const segments = segmentMessage(manyParagraphs);- expect(segments.length).toBeLessThanOrEqual(5);- });-- it('handles text with only a single paragraph gracefully', () => {- const single =- 'This is a single paragraph that happens to be long enough to potentially split but has no newlines or clear sentence breaks ending in uppercase.';- const segments = segmentMessage(single);- expect(segments.length).toBeGreaterThanOrEqual(1);- expect(segments.every(s => s.length > 0)).toBe(true);- });-- it('does not return empty segments', () => {- const text =- 'Valid first paragraph content.\n\n\n\n\n\nValid second paragraph content that is long enough.';- const segments = segmentMessage(text);- expect(segments.every(s => s.trim().length > 0)).toBe(true);- });-});--describe('getSegmentDelay', () => {- it('returns a value between 500 and 1400 ms', () => {- const delays = [- getSegmentDelay(''),- getSegmentDelay('short'),- getSegmentDelay('x'.repeat(100)),- getSegmentDelay('x'.repeat(1000)),- ];- for (const d of delays) {- expect(d).toBeGreaterThanOrEqual(500);- expect(d).toBeLessThanOrEqual(1400);- }- });-- it('returns a larger delay for longer segments', () => {- const short = getSegmentDelay('Hi there!');- const long = getSegmentDelay(- 'This is a much longer segment that contains many more words and characters.'- );- expect(long).toBeGreaterThan(short);- });-});--describe('edge cases', () => {- it('handles text with only whitespace', () => {- expect(segmentMessage(' ')).toEqual(['']);- });-- it('handles exactly 80 characters — treated as short, returns single segment', () => {- const text = 'a'.repeat(80);- expect(segmentMessage(text)).toHaveLength(1);- });-- it('handles exactly 81 characters with a paragraph break — may split', () => {- const text = 'a'.repeat(40) + '\n\n' + 'b'.repeat(40);- const result = segmentMessage(text);- // Both paragraphs are >= MIN_SEGMENT_CHARS so should split- expect(result.length).toBeGreaterThanOrEqual(1);- });-- it('delay scales with length', () => {- const short = getSegmentDelay('hi');- const long = getSegmentDelay('a'.repeat(500));- expect(long).toBeGreaterThan(short);- expect(long).toBeLessThanOrEqual(1400);- expect(short).toBeGreaterThanOrEqual(500);- });-});diff --git a/app/src/utils/format.test.ts b/app/src/utils/format.test.tsnew file mode 100644index 0000000000..013c3d2158--- /dev/null+++ b/app/src/utils/format.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { formatBytes } from './format';++describe('formatBytes', () => {+ it('returns 0 B for missing, negative, or non-finite input', () => {+ expect(formatBytes(undefined)).toBe('0 B');+ expect(formatBytes(null)).toBe('0 B');+ expect(formatBytes(-1)).toBe('0 B');+ expect(formatBytes(Number.NaN)).toBe('0 B');+ expect(formatBytes(Number.POSITIVE_INFINITY)).toBe('0 B');+ });++ it('keeps sub-kilobyte values in bytes', () => {+ expect(formatBytes(512)).toBe('512 B');+ });++ it('uses one decimal below 10 and none above', () => {+ expect(formatBytes(1536)).toBe('1.5 KB');+ expect(formatBytes(20 * 1024 * 1024)).toBe('20 MB');+ expect(formatBytes(3 * 1024 ** 4)).toBe('3.0 TB');+ });+});diff --git a/app/src/utils/format.ts b/app/src/utils/format.tsnew file mode 100644index 0000000000..8ad6291424--- /dev/null+++ b/app/src/utils/format.ts@@ -0,0 +1,17 @@+/**+ * Shared display formatters.+ */++/** Format a byte count as a short human-readable size (`0 B`, `512 B`, `1.5 MB`, `12 GB`). */+export const formatBytes = (bytes?: number | null): string => {+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '0 B';+ if (bytes < 1024) return `${Math.round(bytes)} B`;+ const units = ['KB', 'MB', 'GB', 'TB'];+ let value = bytes / 1024;+ let unit = units[0];+ for (let i = 1; i < units.length && value >= 1024; i += 1) {+ value /= 1024;+ unit = units[i];+ }+ return `${value.toFixed(value >= 10 ? 0 : 1)} ${unit}`;+};diff --git a/app/src/utils/localAiBootstrap.ts b/app/src/utils/localAiBootstrap.tsdeleted file mode 100644index 9e106cff81..0000000000--- a/app/src/utils/localAiBootstrap.ts+++ /dev/null@@ -1,104 +0,0 @@-import {- openhumanLocalAiApplyPreset,- openhumanLocalAiPresets,- type PresetsResponse,-} from './tauriCommands';--const MAX_RETRIES = 5;-const RETRY_BASE_DELAY_MS = 250;--const wait = (ms: number) =>- new Promise<void>(resolve => {- setTimeout(resolve, ms);- });--const normalizeSelectedTier = (tier: string | null | undefined): string | null => {- if (typeof tier !== 'string') return null;- const normalized = tier.trim().toLowerCase();- return normalized.length > 0 ? normalized : null;-};--const retryLocalAiCommand = async <T>(- label: string,- run: () => Promise<T>,- logPrefix: string-): Promise<T> => {- let lastError: unknown;- for (let attempt = 1; attempt <= MAX_RETRIES; attempt += 1) {- try {- return await run();- } catch (error) {- lastError = error;- if (attempt === MAX_RETRIES) {- break;- }- console.debug(- `${logPrefix} ${label} failed on attempt ${attempt}/${MAX_RETRIES}; retrying after core warm-up`,- error- );- await wait(RETRY_BASE_DELAY_MS * attempt);- }- }- throw lastError instanceof Error ? lastError : new Error(`Failed to ${label}`);-};--interface LocalAiPresetResolution {- presets: PresetsResponse;- recommendedTier: string;- selectedTier: string | null;- hadSelectedTier: boolean;- appliedTier: string | null;-}--export const ensureRecommendedLocalAiPresetIfNeeded = async (- logPrefix = '[local-ai-bootstrap]'-): Promise<LocalAiPresetResolution> => {- const presets = await retryLocalAiCommand(- 'load local AI presets',- () => openhumanLocalAiPresets(),- logPrefix- );- const selectedTier = normalizeSelectedTier(presets.selected_tier);- const recommendedTier = presets.recommended_tier;-- if (selectedTier) {- console.debug(- `${logPrefix} keeping existing local AI preset`,- JSON.stringify({ selectedTier, currentTier: presets.current_tier, recommendedTier })- );- return { presets, recommendedTier, selectedTier, hadSelectedTier: true, appliedTier: null };- }-- // No selected tier yet: persist the recommended tier so the Rust-side- // `config_with_recommended_tier_if_unselected()` honors the user's- // opt-in instead of defaulting a low-RAM device back to disabled.- // The mount-time probe in LocalAIStep uses `openhumanLocalAiPresets()`- // directly, so this apply only runs when the user has explicitly- // chosen to proceed with local AI (consent flow).- console.debug(- `${logPrefix} applying recommended local AI preset`,- JSON.stringify({ recommendedTier, recommendDisabled: presets.recommend_disabled ?? false })- );- await retryLocalAiCommand(- 'apply recommended local AI preset',- () => openhumanLocalAiApplyPreset(recommendedTier),- logPrefix- );-- return {- presets: { ...presets, current_tier: recommendedTier, selected_tier: recommendedTier },- recommendedTier,- selectedTier: null,- hadSelectedTier: false,- appliedTier: recommendedTier,- };-};--export const bootstrapLocalAiWithRecommendedPreset = async (- force = false,- logPrefix = '[local-ai-bootstrap]'-) => {- void force;- const preset = await ensureRecommendedLocalAiPresetIfNeeded(logPrefix);- return { preset };-};diff --git a/app/src/utils/localAiHelpers.ts b/app/src/utils/localAiHelpers.tsdeleted file mode 100644index af2410751a..0000000000--- a/app/src/utils/localAiHelpers.ts+++ /dev/null@@ -1,76 +0,0 @@-/**- * Shared helpers for local AI download progress display.- * Used by Home.tsx, LocalAIStep.tsx, AIPanel.tsx, and LocalAIDownloadSnackbar.tsx.- */-import type { LocalAiDownloadsProgress, LocalAiStatus } from './tauriCommands';--export const formatBytes = (bytes?: number | null): string => {- if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '0 B';- if (bytes < 1024) return `${Math.round(bytes)} B`;- const units = ['KB', 'MB', 'GB', 'TB'];- let value = bytes / 1024;- let unit = units[0];- for (let i = 1; i < units.length && value >= 1024; i += 1) {- value /= 1024;- unit = units[i];- }- return `${value.toFixed(value >= 10 ? 0 : 1)} ${unit}`;-};--export const formatEta = (etaSeconds?: number | null): string => {- if (typeof etaSeconds !== 'number' || !Number.isFinite(etaSeconds) || etaSeconds <= 0) return '';- const mins = Math.floor(etaSeconds / 60);- const secs = etaSeconds % 60;- if (mins <= 0) return `${secs}s`;- return `${mins}m ${secs.toString().padStart(2, '0')}s`;-};--export const progressFromStatus = (status: LocalAiStatus | null): number => {- if (!status) return 0;- if (typeof status.download_progress === 'number') {- return Math.max(0, Math.min(1, status.download_progress));- }- switch (status.state) {- case 'ready':- return 1;- case 'loading':- return 0.92;- case 'downloading':- return 0.25;- case 'installing':- return 0.1;- case 'idle':- return 0;- default:- return 0;- }-};--export const progressFromDownloads = (- downloads: LocalAiDownloadsProgress | null-): number | null => {- if (!downloads) return null;- if (typeof downloads.progress !== 'number') return null;- return Math.max(0, Math.min(1, downloads.progress));-};--export const statusLabel = (state: string): string => {- switch (state) {- case 'ready':- return 'Ready';- case 'downloading':- return 'Downloading';- case 'installing':- return 'Installing Runtime';- case 'loading':- return 'Loading model...';- case 'degraded':- return 'Needs Attention';- case 'disabled':- return 'Disabled';- case 'idle':- return 'Idle';- default:- return state;- }-};diff --git a/app/src/utils/messageSegmentation.ts b/app/src/utils/messageSegmentation.tsdeleted file mode 100644index 4a91af14ff..0000000000--- a/app/src/utils/messageSegmentation.ts+++ /dev/null@@ -1,140 +0,0 @@-/**- * messageSegmentation — splits AI responses into natural chat bubbles.- *- * Gate: only called when local model is active. Cloud/API paths bypass this entirely.- */--const MIN_SEGMENT_CHARS = 40;-const MAX_SEGMENTS = 5;--/**- * Split `text` into an array of segments suitable for multi-bubble delivery.- *- * Priority order:- * 1. Paragraph breaks (\n\n) — highest-fidelity natural split.- * 2. Sentence-ending punctuation (. ! ?) followed by space + uppercase.- * 3. Fall back to the whole text as a single segment.- *- * Always returns at least one element. Returns the original text as `[text]`- * when it's too short or cannot be meaningfully split.- */-export function segmentMessage(text: string): string[] {- const trimmed = text.trim();-- // Don't bother segmenting short messages- if (trimmed.length < 80) return [trimmed];-- // --- Strategy 1: paragraph splits ---- const paragraphs = trimmed- .split(/\n\n+/)- .map(p => p.trim())- .filter(p => p.length > 0);-- if (paragraphs.length >= 2) {- const merged = mergeTooShort(paragraphs, '\n\n');- if (merged.length >= 2) return merged.slice(0, MAX_SEGMENTS);- }-- // --- Strategy 2: sentence splits ---- const sentences = splitSentences(trimmed);- if (sentences.length >= 2) {- const grouped = groupSentences(sentences);- if (grouped.length >= 2) return grouped.slice(0, MAX_SEGMENTS);- }-- // --- Fallback: single bubble ---- return [trimmed];-}--/**- * Estimate a natural inter-bubble delay in milliseconds.- * Scales loosely with the length of the segment just delivered.- * Bounded: min 500ms, max 1 400ms.- */-export function getSegmentDelay(segment: string): number {- const base = 500;- const perChar = 1.5;- return Math.min(base + segment.length * perChar, 1400);-}--// ─── helpers ─────────────────────────────────────────────────────────────────--/**- * Merge adjacent items that are shorter than MIN_SEGMENT_CHARS.- *- * Previously only short segments following a prior segment were merged (into- * the preceding one). A short *first* segment was left as-is because the- * `result.length > 0` guard prevented it from being absorbed. This caused the- * first chat bubble to show fewer than MIN_SEGMENT_CHARS characters while all- * subsequent short segments were correctly consolidated.- *- * Fix: after the normal backward-merge pass, check whether the first segment- * is still too short and, if so, forward-merge it into the second segment.- */-function mergeTooShort(parts: string[], joiner: string): string[] {- const result: string[] = [];- for (const part of parts) {- if (result.length > 0 && part.length < MIN_SEGMENT_CHARS) {- result[result.length - 1] += joiner + part;- } else {- result.push(part);- }- }-- // If the first segment is still shorter than the minimum, forward-merge it- // into the second segment (if one exists) so no leading stub bubble is shown.- if (result.length >= 2 && result[0].length < MIN_SEGMENT_CHARS) {- result[1] = result[0] + joiner + result[1];- result.shift();- }-- return result;-}--/**- * Split on sentence-ending punctuation (. ! ?) followed by a space and- * an uppercase letter. Uses a manual loop to avoid lookbehind assertions- * that may not be available in all WebKit versions.- */-function splitSentences(text: string): string[] {- const parts: string[] = [];- let current = '';-- for (let i = 0; i < text.length; i++) {- current += text[i];- const ch = text[i];- const next1 = text[i + 1];- const next2 = text[i + 2];-- if (- (ch === '.' || ch === '!' || ch === '?') &&- next1 === ' ' &&- next2 !== undefined &&- next2 >= 'A' &&- next2 <= 'Z'- ) {- parts.push(current.trim());- current = '';- i++; // skip the space- }- }-- if (current.trim().length > 0) parts.push(current.trim());- return parts.filter(p => p.length > 0);-}--/**- * Group individual sentences into at most MAX_SEGMENTS bubbles.- * Tries to aim for 2–3 bubbles for readability.- */-function groupSentences(sentences: string[]): string[] {- const targetCount = Math.min(3, Math.ceil(sentences.length / 2));- const groupSize = Math.ceil(sentences.length / targetCount);- const groups: string[] = [];-- for (let i = 0; i < sentences.length; i += groupSize) {- groups.push(sentences.slice(i, i + groupSize).join(' '));- }-- return groups.filter(g => g.length >= MIN_SEGMENT_CHARS);-}diff --git a/app/test/playwright/specs/local-model-runtime.spec.ts b/app/test/playwright/specs/local-model-runtime.spec.tsdeleted file mode 100644index a8b02290f7..0000000000--- a/app/test/playwright/specs/local-model-runtime.spec.ts+++ /dev/null@@ -1,19 +0,0 @@-import { expect, test } from '@playwright/test';--import { bootAuthenticatedPage, waitForAppReady } from '../helpers/core-rpc';--test.describe('Local model runtime flow', () => {- test('shows direct-runtime guidance instead of app-managed bootstrap controls', async ({- page,- }) => {- await bootAuthenticatedPage(page, 'pw-local-model-runtime');- // Navigate after the authenticated shell has mounted. Supplying this legacy- // settings path during bootstrap races its default chat-route restoration.- await page.goto('/#/settings/local-model-debug');- await waitForAppReady(page);-- await expect- .poll(async () => page.evaluate(() => window.location.hash))- .toContain('/connections');- });-});