LocalModelPanel.tsx
11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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>
);
}