LocalModelPanel.tsx 11 KB
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import {
  Boxes,
  Plug,
  Unplug,
  Download,
  CheckCircle2,
  Loader2,
  CircleAlert,
  RefreshCw,
  Cpu,
} from 'lucide-react';
import { api, onSSE } from '@/lib/api';
import type { OllamaStatus, OllamaModel, OllamaEvent } from '@/lib/types';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';

function fmtSize(b: number): string {
  if (b >= 1 << 30) return `${(b / (1 << 30)).toFixed(1)} GB`;
  if (b >= 1 << 20) return `${(b / (1 << 20)).toFixed(0)} MB`;
  return `${b} B`;
}

interface PullState {
  completed?: number;
  total?: number;
  status?: string;
}

export function LocalModelPanel() {
  const [status, setStatus] = useState<OllamaStatus | null>(null);
  const [models, setModels] = useState<OllamaModel[]>([]);
  const [loadErr, setLoadErr] = useState<string | null>(null);
  const [pulling, setPulling] = useState<string | null>(null);
  const [progress, setProgress] = useState<Record<string, PullState>>({});
  const [pending, setPending] = useState<string | null>(null);
  const [newModel, setNewModel] = useState('');
  const refreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const refresh = useCallback(async () => {
    try {
      const [s, m] = await Promise.all([api.ollamaStatus(), api.listOllamaModels()]);
      setStatus(s);
      setModels(m.models ?? []);
      setLoadErr(m.error ?? null);
    } catch (e) {
      setLoadErr(e instanceof Error ? e.message : '获取本地模型失败');
    }
  }, []);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  // 订阅后端经现有 SSE 总线广播的 "ollama" 事件(拉取进度 / 连接状态变化)。
  useEffect(() => {
    return onSSE('ollama', (data: unknown) => {
      const ev = data as OllamaEvent;
      if (ev.type === 'pull' && ev.model) {
        setProgress((p) => ({
          ...p,
          [ev.model]: { completed: ev.completed, total: ev.total, status: ev.status },
        }));
      } else if (ev.type === 'pull-done' && ev.model) {
        setPulling((cur) => (cur === ev.model ? null : cur));
        setProgress((p) => {
          const n = { ...p };
          delete n[ev.model];
          return n;
        });
        if (ev.ok) toast.success(`已拉取 ${ev.model}`);
        else toast.error(`拉取失败:${ev.error ?? '未知错误'}`);
        void refresh();
      } else if (ev.type === 'status') {
        setStatus((cur) =>
          cur
            ? {
                ...cur,
                running: ev.running ?? cur.running,
                connected: ev.connected ?? cur.connected,
                activeModel: ev.activeModel ?? cur.activeModel,
              }
            : cur,
        );
        void refresh();
      }
    });
  }, [refresh]);

  const connect = async (model: string) => {
    setPending(model);
    try {
      await api.connectOllama(model);
      toast.success(`已切换到本地模型 ${model}`);
    } catch (e) {
      const msg = e instanceof Error ? e.message : '连接失败';
      toast.error(msg);
    } finally {
      setPending(null);
      void refresh();
    }
  };

  const disconnect = async () => {
    setPending('disconnect');
    try {
      await api.disconnectOllama();
      toast.message('已断开本地模型,恢复默认远程模型');
    } catch (e) {
      toast.error(e instanceof Error ? e.message : '断开失败');
    } finally {
      setPending(null);
      void refresh();
    }
  };

  const pull = async () => {
    const name = newModel.trim();
    if (!name) return;
    setPulling(name);
    setProgress((p) => ({ ...p, [name]: {} }));
    try {
      await api.pullOllamaModel(name);
      setNewModel('');
      toast.message(`开始拉取 ${name}…`);
    } catch (e) {
      setPulling((cur) => (cur === name ? null : cur));
      setProgress((p) => {
        const n = { ...p };
        delete n[name];
        return n;
      });
      toast.error(e instanceof Error ? e.message : '拉取请求失败');
    }
  };

  const running = status?.running ?? false;
  const connected = status?.connected ?? false;
  const activeModel = status?.activeModel ?? null;

  return (
    <section className="rounded-2xl border border-border bg-card p-5">
      <div className="mb-4 flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <Boxes className="h-4 w-4 text-primary" />
          <h3 className="text-sm font-semibold">本地模型(Ollama)</h3>
        </div>
        <div className="flex items-center gap-2">
          <Badge variant={running ? 'success' : 'neutral'}>
            {running ? 'Ollama 运行中' : 'Ollama 未运行'}
          </Badge>
          <Badge variant={connected ? 'success' : 'neutral'}>
            {connected ? `已连接 · ${activeModel}` : '未连接'}
          </Badge>
        </div>
      </div>

      <div className="flex items-center gap-3 py-1.5">
        <Cpu className="h-4 w-4 shrink-0 text-muted-foreground" />
        <span className="w-16 shrink-0 text-xs text-muted-foreground">地址</span>
        <span className="min-w-0 flex-1 truncate font-mono text-[12px]">
          {status?.baseUrl ?? 'http://localhost:11434/v1'}
        </span>
        <button
          type="button"
          onClick={() => void refresh()}
          className="inline-flex h-7 items-center gap-1 rounded-lg border border-border px-2 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
        >
          <RefreshCw className="h-3 w-3" /> 刷新
        </button>
      </div>

      {!running ? (
        <div className="mt-2 flex items-start gap-2 rounded-lg border border-amber-500/25 bg-amber-500/5 p-2.5 text-xs text-amber-600 dark:text-amber-400">
          <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
          <span>
            Ollama 守护进程未运行。请先安装并启动 Ollama(默认监听 11434 端口),启动后即可在此管理本地模型。
          </span>
        </div>
      ) : null}

      {loadErr ? (
        <div className="mt-2 text-xs text-rose-500">{loadErr}</div>
      ) : null}

      {/* 模型列表 */}
      <div className="mt-3 space-y-2">
        {models.length === 0 && running ? (
          <div className="rounded-lg border border-border bg-muted/40 p-3 text-xs text-muted-foreground">
            本地暂无模型。在下方输入框填入模型名(如 <code className="rounded bg-muted px-1">qwen2.5</code>)拉取。
          </div>
        ) : null}
        {models.map((m) => {
          const isActive = connected && activeModel === m.name;
          return (
            <div
              key={m.name}
              className={cn(
                'flex items-center gap-3 rounded-xl border p-3',
                isActive ? 'border-emerald-500/30 bg-emerald-500/5' : 'border-border',
              )}
            >
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 truncate text-sm font-medium">
                  {m.name}
                  {isActive ? (
                    <Badge variant="success" className="px-1.5 py-0">
                      使用中
                    </Badge>
                  ) : null}
                </div>
                <div className="text-xs text-muted-foreground">{fmtSize(m.size)}</div>
              </div>
              {!isActive ? (
                <button
                  type="button"
                  disabled={pending !== null}
                  onClick={() => void connect(m.name)}
                  className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground transition-colors hover:opacity-90 disabled:opacity-50"
                >
                  <Plug className={cn('h-3.5 w-3.5', pending === m.name && 'animate-pulse')} />
                  使用
                </button>
              ) : (
                <button
                  type="button"
                  disabled={pending !== null}
                  onClick={() => void disconnect()}
                  className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
                >
                  <Unplug className="h-3.5 w-3.5" />
                  断开
                </button>
              )}
            </div>
          );
        })}
      </div>

      {/* 拉取新模型 */}
      <div className="mt-4 border-t border-border pt-4">
        <div className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground">
          <Download className="h-3.5 w-3.5" /> 拉取模型
        </div>
        <div className="flex items-center gap-2">
          <input
            value={newModel}
            onChange={(e) => setNewModel(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') void pull();
            }}
            placeholder="模型名,如 qwen2.5 / llama3.1:8b"
            className="h-9 min-w-0 flex-1 rounded-lg border border-border bg-background px-3 text-sm outline-none focus:border-primary"
          />
          <button
            type="button"
            disabled={!newModel.trim() || pulling !== null}
            onClick={() => void pull()}
            className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground transition-colors hover:opacity-90 disabled:opacity-50"
          >
            <Download className="h-3.5 w-3.5" /> 拉取
          </button>
        </div>

        {Object.entries(progress).map(([name, p]) => {
          const pct =
            p.total && p.total > 0 && p.completed != null
              ? Math.min(100, Math.round((p.completed / p.total) * 100))
              : null;
          return (
            <div key={name} className="mt-3 rounded-lg border border-border bg-muted/40 p-3">
              <div className="flex items-center justify-between text-xs">
                <span className="flex items-center gap-1.5 font-medium">
                  {pulling === name ? (
                    <Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />
                  ) : (
                    <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
                  )}
                  {name}
                </span>
                <span className="text-muted-foreground">{p.status ?? (pulling === name ? '拉取中…' : '完成')}</span>
              </div>
              {pct != null ? (
                <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-border">
                  <div
                    className="h-full rounded-full bg-primary transition-all"
                    style={{ width: `${pct}%` }}
                  />
                </div>
              ) : null}
              {pct != null ? (
                <div className="mt-1 text-right text-[11px] text-muted-foreground">{pct}%</div>
              ) : null}
            </div>
          );
        })}
      </div>
    </section>
  );
}